text
stringlengths 10
2.72M
|
|---|
package yuste.zombis.mde;
public interface EstadoJuego {
void actualizar();
void dibujar();
void procesarClick(int boton, float x, float y);
void procesarMensajeRed(String mensaje);
}
|
package com.yunhe.basicdata.service;
import com.yunhe.basicdata.entity.WarehouseManagement;
import com.baomidou.mybatisplus.extension.service.IService;
import java.util.List;
import java.util.Map;
/**
* <p>
* 仓库管理 服务类
* </p>
*
* @author 李恒逵, 唐凯宽
* @since 2019-01-02
*/
public interface IWarehouseManagementService extends IService<WarehouseManagement> {
/**
* <>
* 分页查询仓库
* </>
*
* @param pageSize 每页显示数量
* @param pageNum 当前页
* @return 仓库列表
*/
Map selectWareList(String data, int pageSize, int pageNum);
/**
* <>
* 删除仓库
* </>
*
* @param id 仓库ID
*/
void deleteByid(int id);
/**
* 修改仓库
*
* @param warehouseManagement 仓库的实体类
*/
Integer update(WarehouseManagement warehouseManagement);
/**
* 根据id查找仓库
*
* @param id 仓库ID
* @return 根据id返回的仓库信息
*/
WarehouseManagement selectByid(int id);
/**
* <>
* 模糊查询
* </>
*
* @param data 模糊查询属性
* @return 根据查询得到的仓库信息
*/
Map vagueselect1(String data);
/**
* 增加仓库
*
* @param warehouseManagement 要增加仓库的实体类
*/
Integer addWarehouse(WarehouseManagement warehouseManagement);
/**
* 查询仓库
*
* @return
*/
List<WarehouseManagement> selectware();
/**
* 查询所有
* @author 史江浩
* @since 2019-01-24 09:45
* @return 所有仓库信息
*/
List<WarehouseManagement> selectquanWarList();
}
|
package com.codingblocks.permissions;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.net.NetworkInterface;
public class MainActivity extends AppCompatActivity {
Button btn , btnDial;
TextView tv;
EditText etNum;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = findViewById(R.id.tv);
btn = findViewById(R.id.btn);
btnDial = findViewById(R.id.btnDial);
etNum = findViewById(R.id.etNum);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
assert cm != null;
NetworkInfo netInfo = cm.getActiveNetworkInfo();
boolean isConnected = netInfo != null && netInfo.isConnected() ;
tv.setText(isConnected ? "CONNECTED" : "DISCONNECTED");
}
});
btnDial.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int perm = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CALL_PHONE);
if(perm == PackageManager.PERMISSION_GRANTED)
{
call();
}
else
{
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{
Manifest.permission.CALL_PHONE
},
101
);
}
}
});
}
void call()
{
String telno = etNum.getText().toString();
Uri uri = Uri.parse("tel:" + telno);
Intent i = new Intent(Intent.ACTION_CALL, uri);
}
}
|
package webstoreselenium.qa.pages;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import webstoreselenium.qa.base.TestBase;
import webstoreselenium.qa.utils.TestUtil;
public class ProductsZTM extends TestBase {
public ProductsZTM(){
PageFactory.initElements(driver, this);
}
@FindBy(xpath=" //img[contains(@src,'ztm/ZTM-Series')]") WebElement ztmSeries;
//
public WebStoreZTM clickZTMseries(){
TestUtil.click(ztmSeries);
return new WebStoreZTM();
}
}
|
package com.anexa.livechat.service.impl.odoo;
public class SessionConnectionRefusedException extends RuntimeException {
private static final long serialVersionUID = 1L;
}
|
public class BinaryToDecimal {
public static int findDecimal(long num){
int ans = 0,count = 0;
while(num!=0){
ans += ((num%10)*Math.pow(2, count));
num = num/10;
count++;
}
return ans;
}
public static void main(String[] args) {
System.out.println(findDecimal(100001l));
}
}
|
package com.isystk.sample.web.admin.api.v1.upload;
import com.isystk.sample.common.dto.Dto;
import lombok.Getter;
import lombok.Setter;
@Setter
@Getter
public class UploadRestDto implements Dto {
Integer imageId;
Integer imagePath;
}
|
package de.adesso.gitstalker;
import de.adesso.gitstalker.core.REST.OrganizationController;
import de.adesso.gitstalker.core.Tasks.OrganizationUpdateTask;
import de.adesso.gitstalker.core.Tasks.RequestProcessorTask;
import de.adesso.gitstalker.core.Tasks.ResponseProcessorTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.scheduling.annotation.EnableScheduling;
import de.adesso.gitstalker.core.repositories.RequestRepository;
@SpringBootApplication
@EnableMongoRepositories("de/adesso/gitstalker/core/repositories")
@EnableScheduling
@ComponentScan(basePackageClasses = OrganizationController.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
/**
* Initialization of the Update Task for the saved organisation
*
* @return OrganizationUpdateTask
*/
@Bean
public OrganizationUpdateTask organisationUpdateTask() {
return new OrganizationUpdateTask();
}
/**
* Initialization of the Request Task for crawling the data according to the saved queries.
*
* @return RequestProcessorTask
*/
@Bean
public RequestProcessorTask requestProcessorTask() {
return new RequestProcessorTask();
}
/**
* Initialization of the Response Task for processing the request response data of the queries.
*
* @return ResponseProcessorTask
*/
@Bean
public ResponseProcessorTask responseProcessorTask() {
return new ResponseProcessorTask();
}
}
|
package by.dt.boaopromtorg.service.impl;
import by.dt.boaopromtorg.entity.Price;
import by.dt.boaopromtorg.entity.Product;
import by.dt.boaopromtorg.entity.dto.PriceDTO;
import by.dt.boaopromtorg.entity.dto.ProductSearchDTO;
import by.dt.boaopromtorg.repository.ProductRepository;
import by.dt.boaopromtorg.service.ProductService;
import by.dt.boaopromtorg.web.controller.exception.AlreadyExistException;
import by.dt.boaopromtorg.web.controller.exception.NotFoundException;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ProductServiceImpl implements ProductService{
@Autowired
private ProductRepository productRepository;
public void addProduct(Product product) {
Product existingProduct = productRepository.findProductByBarcode(product.getBarcode());
if(existingProduct != null){
throw new AlreadyExistException("Product is already exist");
}
ObjectId objectId = new ObjectId();
product.setId(objectId.toString());
productRepository.insert(product);
}
@Override public List<Product> searchProduct(ProductSearchDTO productSearchDTO) {
List<Product> products = productRepository.findProducts(productSearchDTO);
if(products == null || products.isEmpty()){
throw new NotFoundException("Product not found");
}
return products;
}
@Override public Product searchProductByBarсode(String barcode) {
Product product = productRepository.findProductByBarcode(barcode);
if(product == null){
throw new NotFoundException("Product not found");
}
return product;
}
@Override public void updatePrice(PriceDTO priceDTO) {
Product product = productRepository.findProductByBarcode(priceDTO.getBarcode());
boolean hasPriceWithCurrentPriceUnit = false;
for (Price price : product.getPrices()){
price.getShopIds().removeAll(priceDTO.getShopIds());
if(price.getPriceUnit().equals(priceDTO.getPriceUnit())){
hasPriceWithCurrentPriceUnit = true;
price.getShopIds().addAll(priceDTO.getShopIds());
}
if(price.getShopIds().isEmpty()){
product.getPrices().remove(price);
}
}
if(!hasPriceWithCurrentPriceUnit){
Price price = new Price(priceDTO);
product.getPrices().add(price);
}
productRepository.save(product);
}
}
|
package javadatastructures;
import java.util.ArrayList;
/**
*
* @author Raul Farkas
*/
public class HashTableConcatenation<E> {
ArrayList<HashTableNode>[] list;
public HashTableConcatenation() {
list = new ArrayList[100];
}
public HashTableConcatenation(int i) {
list = new ArrayList[i];
}
public int hash(String value) {
int hashValue = 0;
for (int i = 0; i < value.length(); i++) {
hashValue += (int) (value.charAt(i) * Math.pow(2, i));
//hashValue += (int) value.charAt(i);
}
return hashValue % list.length;
}
public void add(String key, E value) {
int hkey = hash(key);
if (list[hkey] == null) {
list[hkey] = new ArrayList();
}
list[hkey].add(new HashTableNode(key, value));
}
public HashTableNode get(String key) throws Exception {
int hkey = hash(key);
HashTableNode ret = null;
if (list[hkey] != null) {
for (HashTableNode l : list[hkey]) {
if(l.getKey() == key){
ret = l;
break;
}
}
}
if(ret == null){
throw new Exception("Key not found!");
}
return ret;
}
}
|
package com.jiuzhe.app.hotel.dto;
/**
* @Descript;展示给清洁工看的信息
*/
public class CleanDto {
//门店id
private String storeId;
//门店名称
private String storeName;
//房间id
private String skuId;
//房间名称
private String skuName;
//房号
private String roomNo;
//地址
private String address;
//房间类型
private String roomType;
//城市名
private String city;
//房间状态
private Integer roomStatus;
public String getStoreName() {
return storeName;
}
public void setStoreName(String storeName) {
this.storeName = storeName;
}
public String getStoreId() {
return storeId;
}
public void setStoreId(String storeId) {
this.storeId = storeId;
}
public String getSkuId() {
return skuId;
}
public void setSkuId(String skuId) {
this.skuId = skuId;
}
public String getSkuName() {
return skuName;
}
public void setSkuName(String skuName) {
this.skuName = skuName;
}
public String getRoomNo() {
return roomNo;
}
public void setRoomNo(String roomNo) {
this.roomNo = roomNo;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getRoomType() {
return roomType;
}
public void setRoomType(String roomType) {
this.roomType = roomType;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public Integer getRoomStatus() {
return roomStatus;
}
public void setRoomStatus(Integer roomStatus) {
this.roomStatus = roomStatus;
}
}
|
package com.fleet.reactor.controller;
import com.fleet.reactor.entity.User;
import com.fleet.reactor.service.UserService;
import org.springframework.web.bind.annotation.*;
import reactor.core.Reactor;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.event.Event;
import javax.annotation.Resource;
import java.util.List;
@RestController
@RequestMapping("/user")
public class UserController {
@Resource
private UserService userService;
@Resource
private Reactor reactor;
@RequestMapping("/hi")
public String hi() {
User user = new User();
user.setId(1L);
user.setName("fleet");
reactor.notify("hiHandler", Event.wrap(user));
return "hello";
}
@RequestMapping("insert")
public Mono<User> insert(@RequestBody User user) {
printlnThread("调用insert");
return userService.insert(user);
}
@RequestMapping("/delete/{id}")
public Mono<User> delete(@PathVariable("id") Long id) {
printlnThread("调用delete");
return userService.delete(id);
}
@RequestMapping("update")
public Mono<User> update(@RequestBody User user) {
printlnThread("调用update");
return userService.update(user);
}
@RequestMapping("/get/{id}")
public Mono<User> get(@PathVariable("id") Long id) {
printlnThread("调用get");
return userService.get(id);
}
@RequestMapping("list")
public Flux<User> list() {
printlnThread("调用list");
return userService.list();
}
@RequestMapping("/listByIds")
public Flux<User> listByIds(@RequestParam("ids") List<Long> ids) {
printlnThread("调用listByIds");
return userService.list(ids);
}
/**
* 打印当前线程
*/
private void printlnThread(Object object) {
String threadName = Thread.currentThread().getName();
System.out.println("UserController[" + threadName + "]: " + object);
}
}
|
package com.example.demo.service.impl;
import com.example.demo.exception.ResourceNotFoundException;
import com.example.demo.model.Question;
import com.example.demo.repository.QuestionRepository;
import com.example.demo.service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
@Service
public class QuestionServiceImpl implements QuestionService {
@Autowired
private QuestionRepository questionRepository;
@Override
public Question createQuestion(Question question) {
return questionRepository.save(question);
}
@Override
public Question getQuestionById(Long id) {
return questionRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Question", "Id", id));
}
@Override
public ResponseEntity<?> deleteQuestion(Long questionId) {
Question question = questionRepository.findById(questionId)
.orElseThrow(() -> new ResourceNotFoundException("Question", "Id", questionId));
questionRepository.delete(question);
return ResponseEntity.ok().build();
}
@Override
public Page<Question> getAllQuestions(Pageable pageable) {
return questionRepository.findAll(pageable);
}
}
|
package com.miaosha.demo.validator;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import java.util.HashMap;
import java.util.Map;
/**
* @Classname ValidationResult
* @Description TODO
* @Date 2019/10/22 14:21
* @Author gt
*/
@Data
public class ValidationResult {
// 校验结果是否有错
private boolean hasErrors = false;
// 存放错误信息的Map
private Map<String, String> errorMsgMap = new HashMap<>();
// 实现通用的通过格式化信字符串信息获取结果的msg方法
public String getErrMsg() {
return StringUtils.join(errorMsgMap.values().toArray()
, ",");
}
}
|
package com.tencent.mm.ui.contact;
import android.content.Context;
import android.content.res.ColorStateList;
import android.database.Cursor;
import android.support.v4.app.Fragment;
import android.util.SparseArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewStub;
import android.widget.TextView;
import com.tencent.mm.R;
import com.tencent.mm.ac.m;
import com.tencent.mm.bt.a.e;
import com.tencent.mm.model.au;
import com.tencent.mm.model.c;
import com.tencent.mm.model.q;
import com.tencent.mm.model.s;
import com.tencent.mm.platformtools.ai;
import com.tencent.mm.pluginsdk.ui.d.j;
import com.tencent.mm.sdk.e.m.b;
import com.tencent.mm.sdk.platformtools.ad;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.ab;
import com.tencent.mm.storage.bl;
import com.tencent.mm.ui.AddressView;
import com.tencent.mm.ui.base.MMSlideDelView;
import com.tencent.mm.ui.base.MMSlideDelView$c;
import com.tencent.mm.ui.base.MMSlideDelView.d;
import com.tencent.mm.ui.base.MMSlideDelView.g;
import com.tencent.mm.ui.f;
import com.tencent.mm.ui.y;
import com.tencent.smtt.sdk.TbsReaderView$ReaderCallback;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
public class a extends f<String, com.tencent.mm.storage.f> implements b {
public static final ColorStateList kBs = com.tencent.mm.bp.a.ac(ad.getContext(), R.e.mm_list_textcolor_one);
public static final ColorStateList kBt = com.tencent.mm.bp.a.ac(ad.getContext(), R.e.hint_text_color);
private String eIQ = "";
private com.tencent.mm.ui.applet.b eKg = null;
protected List<String> gRN = null;
protected g hkN;
protected MMSlideDelView$c hkO;
protected d hkQ = MMSlideDelView.getItemStatusCallBack();
private boolean hoW = false;
OnClickListener iZP = new 1(this);
protected MMSlideDelView.f lCE;
StringBuilder sb = new StringBuilder(32);
private String[] tDY = null;
private int type;
public HashMap<String, com.tencent.mm.storage.f> ugE = new HashMap();
protected String ugF = null;
protected String ugG = null;
private List<Object> ugH;
private List<String> ugI;
private int ugJ = 0;
protected int[] ugK;
String[] ugL;
protected com.tencent.mm.ui.contact.AddressUI.a ugM;
private Set<Integer> ugN = new HashSet();
private int ugO = 0;
private boolean ugP = true;
a ugQ;
private boolean ugR = false;
boolean ugS = false;
private String ugT;
LinkedList<View> ugU = new LinkedList();
boolean ugV;
HashMap<View, ViewStub> ugW = new HashMap();
private SparseArray<String> ugX = new SparseArray();
private SparseArray<Integer> ugY = new SparseArray();
private HashSet<String> ugZ = new HashSet();
public final /* synthetic */ com.tencent.mm.bt.a.a coc() {
return new com.tencent.mm.storage.f();
}
/* renamed from: dq */
public final void q(String str, int i) {
if (i == 5) {
this.ugZ.add(str);
}
super.q(str, i);
}
public final void pause() {
this.ugZ.clear();
super.pause();
}
public void notifyDataSetChanged() {
this.ugT = q.GF();
if (this.ugK == null) {
cxW();
}
if (getCount() == 0) {
super.notifyDataSetChanged();
return;
}
this.ugO = coV();
x.i("MicroMsg.AddressAdapter", "newcursor favourCount %d", new Object[]{Integer.valueOf(this.ugO)});
super.notifyDataSetChanged();
}
public a(Context context, String str, String str2, int i) {
super(context);
this.context = context;
this.ugF = str;
this.ugG = str2;
this.type = i;
this.ugR = true;
this.ugH = new LinkedList();
this.ugI = new LinkedList();
this.ugT = q.GF();
this.TAG = "MiscroMsg.AddressDrawWithCacheAdapter";
}
public final void l(Fragment fragment) {
if (fragment instanceof com.tencent.mm.ui.contact.AddressUI.a) {
this.ugM = (com.tencent.mm.ui.contact.AddressUI.a) fragment;
}
}
public final void detach() {
if (this.eKg != null) {
this.eKg.detach();
this.eKg = null;
}
}
public final void setPerformItemClickListener(g gVar) {
this.hkN = gVar;
}
public final void a(MMSlideDelView.f fVar) {
this.lCE = fVar;
}
public final void setGetViewPositionCallback(MMSlideDelView$c mMSlideDelView$c) {
this.hkO = mMSlideDelView$c;
}
public final void dQ(List<String> list) {
if (this.type != 2) {
list.add(q.GF());
}
au.HU();
bl Hg = c.FZ().Hg("@t.qq.com");
if (Hg != null) {
list.add(Hg.name);
}
if (this.type == 3 || this.type == 5 || this.type == 4 || this.type == 1 || this.type == 0) {
for (String add : s.Hp()) {
list.add(add);
}
}
list.add("blogapp");
this.gRN = list;
}
public final int getPositionForSection(int i) {
if (this.ugK != null && i >= 0 && i < this.ugK.length) {
i = this.ugK[i];
}
return this.ugO + i;
}
private boolean cxU() {
return this.ugF.equals("@micromsg.qq.com") || this.ugF.equals("@all.contact.without.chatroom");
}
protected Cursor cxV() {
long currentTimeMillis = System.currentTimeMillis();
List linkedList = new LinkedList();
linkedList.add("weixin");
au.HU();
Cursor a = c.FR().a(this.ugF, this.ugG, this.gRN, linkedList, cxU(), this.ugR);
x.d("MicroMsg.AddressAdapter", "kevin setCursor : " + (System.currentTimeMillis() - currentTimeMillis));
return a;
}
protected final void cxW() {
int count = getCount();
if (count != 0) {
int i;
int i2;
this.ugO = coV();
if (this.tDY != null) {
this.ugK = s.a(this.ugF, this.ugG, this.gRN, this.tDY);
this.ugL = s.a(this.ugF, this.ugG, this.tDY, this.gRN);
} else if (cnU()) {
long currentTimeMillis = System.currentTimeMillis();
HashSet hashSet = new HashSet();
this.ugK = new int[30];
this.ugL = new String[30];
i = this.ugO;
int i3 = 0;
while (i < count) {
com.tencent.mm.storage.f fVar = (com.tencent.mm.storage.f) Dy(i);
if (fVar != null) {
String b = b(fVar, i);
if (hashSet.add(b)) {
this.ugK[i3] = i - this.ugO;
this.ugL[i3] = b;
i2 = i3 + 1;
}
i2 = i3;
} else {
x.d("MicroMsg.AddressAdapter", "newCursor getItem is null");
i2 = i3;
}
i++;
i3 = i2;
}
x.d("MicroMsg.AddressAdapter", "newCursor resetShowHead by Memory : " + (System.currentTimeMillis() - currentTimeMillis) + "favourCount : " + this.ugO);
} else {
long currentTimeMillis2 = System.currentTimeMillis();
this.ugK = s.b(this.ugF, this.ugG, this.gRN, this.eIQ);
this.ugL = s.a(this.ugF, this.ugG, this.eIQ, this.gRN);
x.d("MicroMsg.AddressAdapter", "kevin resetShowHead part1 : " + (System.currentTimeMillis() - currentTimeMillis2));
}
this.ugN.clear();
for (int i4 : this.ugK) {
this.ugN.add(Integer.valueOf(i4 - 1));
}
}
}
public final void cxX() {
this.hkQ.aYm();
}
public View getView(int i, View view, ViewGroup viewGroup) {
b bVar;
int i2 = -1;
if (!this.ugV) {
for (int i3 = 0; i3 < 8; i3++) {
this.ugU.add(y.gq(this.context).inflate(R.i.address_new_item_myview, null));
}
this.ugV = true;
}
com.tencent.mm.storage.f fVar = (com.tencent.mm.storage.f) Dy(i);
if (view == null) {
View view2;
if (this.ugU.size() > 0) {
View view3 = (View) this.ugU.getFirst();
this.ugU.removeFirst();
view2 = view3;
} else {
view2 = View.inflate(this.context, R.i.address_new_item_myview, null);
}
bVar = new b();
bVar.kuR = (TextView) view2.findViewById(R.h.contactitem_catalog);
bVar.kuS = (TextView) view2.findViewById(R.h.contactitem_signature);
bVar.kBx = (AddressView) view2.findViewById(R.h.myview);
bVar.uhb = (TextView) view2.findViewById(R.h.contactitem_account_delete);
bVar.uhc = view2.findViewById(R.h.contactitem_selector);
bVar.uhd = (TextView) view2.findViewById(R.h.openim_contact_desc);
LayoutParams layoutParams = bVar.uhc.getLayoutParams();
layoutParams.height = (int) (((float) com.tencent.mm.bp.a.ae(this.context, R.f.ContactListHeight)) * com.tencent.mm.bp.a.fh(this.context));
bVar.uhc.setLayoutParams(layoutParams);
if (this.ugM != null) {
this.ugM.hLH.a(bVar.kBx);
}
view2.setTag(bVar);
view = view2;
} else {
bVar = (b) view.getTag();
}
if (fVar != null) {
CharSequence b;
au.HU();
ab Yg = c.FR().Yg(fVar.field_username);
x.d("MicroMsg.AddressAdapter", "user:%s, remark:%s", new Object[]{Yg.field_username, Yg.field_conRemark});
com.tencent.mm.storage.f fVar2 = (com.tencent.mm.storage.f) Dy(i - 1);
com.tencent.mm.storage.f fVar3 = (com.tencent.mm.storage.f) Dy(i + 1);
int a = fVar2 == null ? -1 : a(fVar2, i - 1);
int a2 = a(fVar, i);
if (fVar3 != null) {
i2 = a(fVar3, i + 1);
}
if (this.ugP) {
if (i == 0) {
b = b(fVar, i);
if (!ai.oW(b)) {
bVar.kuR.setVisibility(0);
bVar.kuR.setText(b);
if (!this.ugP || a2 == i2) {
bVar.uhc.setBackgroundResource(R.g.list_item_normal);
}
com.tencent.mm.pluginsdk.ui.a.b.a(bVar.kBx, fVar.field_username);
if (fVar.field_verifyFlag != 0) {
bVar.kBx.setMaskBitmap(null);
} else if (com.tencent.mm.model.am.a.dBt != null) {
String gY = com.tencent.mm.model.am.a.dBt.gY(fVar.field_verifyFlag);
if (gY != null) {
bVar.kBx.setMaskBitmap(m.kU(gY));
} else {
bVar.kBx.setMaskBitmap(null);
}
} else {
bVar.kBx.setMaskBitmap(null);
}
bVar.kBx.updateTextColors();
b = fVar.sNQ;
if (b == null) {
try {
if (ab.XR(fVar.field_username)) {
b = ((com.tencent.mm.openim.a.b) com.tencent.mm.kernel.g.l(com.tencent.mm.openim.a.b.class)).d(ad.getContext(), fVar.BL(), com.tencent.mm.bp.a.ad(this.context, R.f.NormalTextSize));
} else {
Context context = this.context;
b = fVar.BL();
String str = fVar.field_username;
if (b == null || b.length() <= 0) {
Object obj = str;
}
str = "";
if (str.length() > 0 && !str.equals(b)) {
this.sb.append(b);
this.sb.append("(");
this.sb.append(str);
this.sb.append(")");
b = this.sb.toString();
this.sb.delete(0, this.sb.length());
}
b = j.a(context, b, com.tencent.mm.bp.a.ad(this.context, R.f.NormalTextSize));
}
} catch (Exception e) {
b = null;
}
if (b == null) {
b = "";
}
bVar.kBx.setName(b);
} else {
bVar.kBx.setName(b);
}
bVar.kBx.setDescription(ai.oV(fVar.field_remarkDesc));
a(fVar, bVar);
}
} else if (i > 0 && a2 != a) {
b = b(fVar, i);
if (!ai.oW(b)) {
bVar.kuR.setVisibility(0);
bVar.kuR.setText(b);
bVar.uhc.setBackgroundResource(R.g.list_item_normal);
com.tencent.mm.pluginsdk.ui.a.b.a(bVar.kBx, fVar.field_username);
if (fVar.field_verifyFlag != 0) {
bVar.kBx.setMaskBitmap(null);
} else if (com.tencent.mm.model.am.a.dBt != null) {
String gY2 = com.tencent.mm.model.am.a.dBt.gY(fVar.field_verifyFlag);
if (gY2 != null) {
bVar.kBx.setMaskBitmap(m.kU(gY2));
} else {
bVar.kBx.setMaskBitmap(null);
}
} else {
bVar.kBx.setMaskBitmap(null);
}
bVar.kBx.updateTextColors();
b = fVar.sNQ;
if (b == null) {
bVar.kBx.setName(b);
} else {
try {
if (ab.XR(fVar.field_username)) {
b = ((com.tencent.mm.openim.a.b) com.tencent.mm.kernel.g.l(com.tencent.mm.openim.a.b.class)).d(ad.getContext(), fVar.BL(), com.tencent.mm.bp.a.ad(this.context, R.f.NormalTextSize));
} else {
Context context2 = this.context;
b = fVar.BL();
String str2 = fVar.field_username;
if (b == null || b.length() <= 0) {
Object obj2 = str2;
}
str2 = "";
if (str2.length() > 0 && !str2.equals(b)) {
this.sb.append(b);
this.sb.append("(");
this.sb.append(str2);
this.sb.append(")");
b = this.sb.toString();
this.sb.delete(0, this.sb.length());
}
b = j.a(context2, b, com.tencent.mm.bp.a.ad(this.context, R.f.NormalTextSize));
}
} catch (Exception e2) {
b = null;
}
if (b == null) {
b = "";
}
bVar.kBx.setName(b);
}
bVar.kBx.setDescription(ai.oV(fVar.field_remarkDesc));
a(fVar, bVar);
}
}
}
bVar.kuR.setVisibility(8);
bVar.uhc.setBackgroundResource(R.g.list_item_normal);
com.tencent.mm.pluginsdk.ui.a.b.a(bVar.kBx, fVar.field_username);
if (fVar.field_verifyFlag != 0) {
bVar.kBx.setMaskBitmap(null);
} else if (com.tencent.mm.model.am.a.dBt != null) {
String gY22 = com.tencent.mm.model.am.a.dBt.gY(fVar.field_verifyFlag);
if (gY22 != null) {
bVar.kBx.setMaskBitmap(m.kU(gY22));
} else {
bVar.kBx.setMaskBitmap(null);
}
} else {
bVar.kBx.setMaskBitmap(null);
}
bVar.kBx.updateTextColors();
b = fVar.sNQ;
if (b == null) {
try {
if (ab.XR(fVar.field_username)) {
b = ((com.tencent.mm.openim.a.b) com.tencent.mm.kernel.g.l(com.tencent.mm.openim.a.b.class)).d(ad.getContext(), fVar.BL(), com.tencent.mm.bp.a.ad(this.context, R.f.NormalTextSize));
} else {
Context context22 = this.context;
b = fVar.BL();
String str22 = fVar.field_username;
if (b == null || b.length() <= 0) {
Object obj22 = str22;
}
str22 = "";
if (str22.length() > 0 && !str22.equals(b)) {
this.sb.append(b);
this.sb.append("(");
this.sb.append(str22);
this.sb.append(")");
b = this.sb.toString();
this.sb.delete(0, this.sb.length());
}
b = j.a(context22, b, com.tencent.mm.bp.a.ad(this.context, R.f.NormalTextSize));
}
} catch (Exception e22) {
b = null;
}
if (b == null) {
b = "";
}
bVar.kBx.setName(b);
} else {
bVar.kBx.setName(b);
}
bVar.kBx.setDescription(ai.oV(fVar.field_remarkDesc));
a(fVar, bVar);
}
bVar.kBx.updatePositionFlag();
bVar.kBx.setContentDescription(bVar.kBx.getNickName() == null ? "" : bVar.kBx.getNickName().toString());
return view;
}
protected void a(com.tencent.mm.storage.f fVar, b bVar) {
try {
bVar.uhd.setText(null);
bVar.uhd.setVisibility(8);
if (ab.XR(fVar.field_username)) {
CharSequence aE = ((com.tencent.mm.openim.a.b) com.tencent.mm.kernel.g.l(com.tencent.mm.openim.a.b.class)).aE(fVar.field_openImAppid, fVar.field_descWordingId);
if (aE != null && aE.length() > 0) {
bVar.uhd.setVisibility(0);
bVar.uhd.setText(aE);
}
}
} catch (Throwable th) {
}
}
protected int a(com.tencent.mm.storage.f fVar, int i) {
if (i < this.ugO) {
return 32;
}
if (fVar != null) {
return fVar.field_showHead;
}
x.e("MicroMsg.AddressAdapter", "contact is null, position:%d", new Object[]{Integer.valueOf(i)});
return -1;
}
protected String b(com.tencent.mm.storage.f fVar, int i) {
if (i < this.ugO) {
return getString(R.l.address_favour_contact_catalog_name);
}
if (fVar.field_showHead == 31) {
return "";
}
if (fVar.field_showHead == 123) {
return "#";
}
if (fVar.field_showHead == 33) {
return getString(R.l.address_application_account_catalog_name);
}
if (fVar.field_showHead == 43) {
return getString(R.l.room_head_name);
}
if (fVar.field_showHead == 32) {
return getString(R.l.address_favour_contact_catalog_name);
}
String str = (String) this.ugX.get(fVar.field_showHead);
if (str != null) {
return str;
}
str = String.valueOf((char) fVar.field_showHead);
this.ugX.put(fVar.field_showHead, str);
return str;
}
public int getCount() {
return super.getCount();
}
private String getString(int i) {
String str = (String) this.ugX.get(i);
if (str != null) {
return str;
}
str = this.context.getString(i);
this.ugX.put(i, str);
return str;
}
public final com.tencent.mm.bt.a.d<String> coW() {
return (com.tencent.mm.bt.a.d) cxV();
}
public final ArrayList<com.tencent.mm.storage.f> ae(ArrayList<String> arrayList) {
long currentTimeMillis = System.currentTimeMillis();
List arrayList2 = new ArrayList();
int i = 0;
while (true) {
int i2 = i;
if (i2 >= arrayList.size()) {
break;
}
arrayList2.add((String) arrayList.get(i2));
i = i2 + 1;
}
ArrayList<com.tencent.mm.storage.f> arrayList3 = new ArrayList(arrayList2.size());
au.HU();
Cursor dg = c.FR().dg(arrayList2);
while (dg.moveToNext()) {
com.tencent.mm.storage.f fVar = new com.tencent.mm.storage.f();
fVar.d(dg);
arrayList3.add(fVar);
}
dg.close();
x.d("MicroMsg.AddressAdapter", "rebulidAllChangeData :" + (System.currentTimeMillis() - currentTimeMillis));
return arrayList3;
}
public final SparseArray<String>[] a(HashSet<f.b<String, com.tencent.mm.storage.f>> hashSet, SparseArray<String>[] sparseArrayArr) {
SparseArray<String>[] sparseArrayArr2 = new SparseArray[sparseArrayArr.length];
List linkedList = new LinkedList();
linkedList.add("weixin");
long currentTimeMillis = System.currentTimeMillis();
au.HU();
Cursor b = c.FR().b(this.ugF, this.ugG, this.gRN, linkedList, cxU(), this.ugR);
int i;
if (b instanceof e) {
com.tencent.mm.bt.a.d[] dVarArr = ((e) b).ter;
int length = dVarArr.length;
for (int i2 = 0; i2 < length; i2++) {
dVarArr[i2].Dz(TbsReaderView$ReaderCallback.GET_BAR_ANIMATING);
sparseArrayArr2[i2] = new SparseArray();
i = 0;
while (dVarArr[i2].moveToNext()) {
sparseArrayArr2[i2].put(i, dVarArr[i2].getString(0));
i++;
}
}
this.ugO = dVarArr[0].getCount();
} else {
sparseArrayArr2[0] = new SparseArray();
i = 0;
while (b.moveToNext()) {
sparseArrayArr2[0].put(i, b.getString(0));
i++;
}
}
b.close();
x.d("MicroMsg.AddressAdapter", "refreshPosistion last :" + (System.currentTimeMillis() - currentTimeMillis));
return sparseArrayArr2;
}
public final void cxY() {
super.q(null, 1);
}
public void a(int i, com.tencent.mm.sdk.e.m mVar, Object obj) {
if (obj == null || !(obj instanceof String)) {
x.d("MicroMsg.AddressAdapter", "onNotifyChange obj not String event:%d stg:%s obj:%s", new Object[]{Integer.valueOf(i), mVar, obj});
return;
}
au.HU();
if (mVar != c.FR()) {
return;
}
if (s.hd((String) obj) || this.ugZ.contains((String) obj)) {
x.d("MicroMsg.AddressAdapter", "newcursor is stranger ,return");
return;
}
super.q((String) obj, 2);
if (this.ugS && this.ugM != null) {
this.ugM.uhx = true;
x.d("MicroMsg.AddressAdapter", "ADDRESS onNotifyChange");
}
}
}
|
package tachyon.client;
import java.io.InputStream;
import java.io.IOException;
/**
* <code>InStream</code> is the base input stream class for TachyonFile streaming input methods. It
* can only be gotten by calling the methods in <code>tachyon.client.TachyonFile</code>, but can not
* be initialized by the client code.
*/
public abstract class InStream extends InputStream {
protected final TachyonFile mFile;
protected final TachyonFS mTachyonFS;
protected final ReadType mReadType;
/**
* @param file the input file of the InStream
* @param readType the InStream's read type
*/
InStream(TachyonFile file, ReadType readType) {
mFile = file;
mTachyonFS = mFile.mTachyonFS;
mReadType = readType;
}
@Override
public abstract void close() throws IOException;
@Override
public abstract int read() throws IOException;
@Override
public abstract int read(byte[] b) throws IOException;
@Override
public abstract int read(byte[] b, int off, int len) throws IOException;
/**
* Sets the stream pointer offset, measured from the beginning of this stream, at which the next
* read or write occurs. The offset may be set beyond the end of the stream.
*
* @param pos the offset position, measured in bytes from the beginning of the InStream, at which
* to set the stream pointer.
* @throws IOException if pos is less than 0 or if an I/O error occurs.
*/
public abstract void seek(long pos) throws IOException;
@Override
public abstract long skip(long n) throws IOException;
}
|
package lesson25.Ex5;
import java.util.Date;
public class Manager extends Employee{
private Date startTerm; //băt đầu nhiệm kỳ
private Date endTerm; //kết thúc nhiệm kỳ
public Manager(String idEmp, String position, float basicWages, float experience,
int dayInTheMonth, float bonus, float receiveWages, Date startTerm, Date endTerm) {
super(idEmp, position, basicWages, experience, dayInTheMonth, bonus, receiveWages);
this.startTerm = startTerm;
this.endTerm = endTerm;
}
public Manager(String idCard, String fullName, String address, Date dayOfBirth,
String email, String phoneNumber, String idEmp, String position,
float basicWages, float experience, int dayInTheMonth, float bonus,
float receiveWages, Date startTerm, Date endTerm) {
super(idCard, fullName, address, dayOfBirth, email, phoneNumber, idEmp, position,
basicWages, experience, dayInTheMonth, bonus, receiveWages);
this.startTerm = startTerm;
this.endTerm = endTerm;
}
/**
* phương thức support cho CreateMng
* @param employee
* @param start
* @param end
*/
public Manager(Employee employee, Date start, Date end) {
super(employee.getIdCard(), employee.getFullName(), employee.getAddress(), employee.getDayOfBirth(),
employee.getEmail(), employee.getPhoneNumber(), employee.getIdEmp(), employee.getPosition(),
employee.getBasicWages(), employee.getExperience(), employee.getDayInTheMonth(), employee.getBonus(),
employee.getReceiveWages());
startTerm = start;
endTerm = end;
}
public final Date getStartTerm() {
return startTerm;
}
public final void setStartTerm(Date startTerm) {
this.startTerm = startTerm;
}
public final Date getEndTerm() {
return endTerm;
}
public final void setEndTerm(Date endTerm) {
this.endTerm = endTerm;
}
//các hành động
@Override
public void work(String job) {
System.out.println("Giám đốc " + getFullName() + " đang làm " + job);
}
@Override
public void eat(String food) {
System.out.println("Giám đốc " + getFullName() + " đang ăn " + food);
}
@Override
public void sleep() {
System.out.println("Giám đốc " + getFullName() + " đang ngủ");
}
@Override
public void talk() {
System.out.println("Giám đốc " + getFullName() + " đang nói chuyện điện thoại");
}
@Override
public void relax() {
System.out.println("Giám đốc " + getFullName() + " đang đi đánh gold");
}
@Override
public void calcularReceiveWage() { //tính tổng lương thực nhận
super.calcularReceiveWage(); //vì cách tính tương thực nhận của giám đốc và nv là như nhau nên chỉ cần override lại là xong
}
// @Override
// public void receiveWage() { //nhận lương
// System.out.println("Giám đốc " + getFullName() + " được nhận " + getReceiveWages() + ".VNĐ lương tháng này");
// }
@Override
public void calcularBonus() { //tính thưởng
if (getDayInTheMonth() >= 22) {
setBonus(getReceiveWages() * 0.25f);
} else {
setBonus(0);
}
}
@Override
public void receiveBonus() { //nhận lương
System.out.println("Giám đốc " + getFullName() + " đã nhận " + getReceiveWages() + ".VNĐ thưởng tháng này");
}
@Override
public void travel(String where) {
System.out.println("Giám đốc " + getFullName() + " đang đi chơi với đối tác ở " + where);
}
public void meeting() {
System.out.println("Giám đốc đang họp HĐQT");
}
public void signDocument() {
System.out.println("Giám đốc đang ký văn bản");
}
public void meetPartner() {
System.out.println("Giám đốc đang đi gặp gỡ đối tác");
}
}
|
/*
* Copyright (c) 2011-2016 Pivotal Software Inc, All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package reactor.aeron.publisher;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import reactor.core.support.Logger;
import reactor.Timers;
import reactor.aeron.Context;
import reactor.aeron.support.AeronInfra;
import reactor.aeron.support.AeronUtils;
import reactor.aeron.support.ServiceMessagePublicationFailedException;
import reactor.aeron.support.ServiceMessageType;
import reactor.core.error.SpecificationExceptions;
import reactor.core.support.ReactiveState;
import reactor.core.support.SingleUseExecutor;
import reactor.core.support.UUIDUtils;
import reactor.fn.Consumer;
import reactor.core.timer.Timer;
import reactor.io.buffer.Buffer;
import uk.co.real_logic.aeron.Publication;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* @author Anatoly Kadyshev
* @since 2.1
*/
public class AeronPublisher implements Publisher<Buffer>, ReactiveState.Downstream {
private static final Logger logger = Logger.getLogger(AeronPublisher.class);
final AeronInfra aeronInfra;
private final Context context;
private final ExecutorService executor;
private final Consumer<Void> shutdownTask;
private final Consumer<Void> onTerminateTask;
private final Publication serviceRequestPub;
private final AtomicBoolean alive = new AtomicBoolean(true);
private volatile boolean terminated = false;
private final HeartbeatSender heartbeatSender;
private final ServiceMessageSender serviceMessageSender;
private volatile AtomicBoolean subscribed = new AtomicBoolean(false);
private volatile SignalPoller signalPoller;
private final String sessionId;
public static AeronPublisher create(Context context) {
context.validate();
return new AeronPublisher(context);
}
public AeronPublisher(Context context,
Consumer<Void> shutdownTask,
Consumer<Void> onTerminateTask) {
if (shutdownTask == null) {
shutdownTask = new Consumer<Void>() {
@Override
public void accept(Void value) {
shutdown();
}
};
}
this.context = context;
this.onTerminateTask = onTerminateTask;
this.aeronInfra = context.createAeronInfra();
this.executor = SingleUseExecutor.create(context.name() + "-signal-poller");
this.serviceRequestPub = createServiceRequestPub(context, this.aeronInfra);
this.sessionId = getSessionId(context);
this.serviceMessageSender = new ServiceMessageSender(this, serviceRequestPub, sessionId);
this.heartbeatSender = new HeartbeatSender(context,
new ServiceMessageSender(this, serviceRequestPub, sessionId), new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) {
shutdown();
}
});
this.shutdownTask = shutdownTask;
}
protected String getSessionId(Context context) {
return AeronUtils.isMulticastCommunication(context) ?
UUIDUtils.create().toString():
context.receiverChannel() + "/" + context.streamId() + "/" + context.errorStreamId();
}
public AeronPublisher(Context context) {
this(context,
null,
new Consumer<Void>() {
@Override
public void accept(Void value) {
}
});
}
private Publication createServiceRequestPub(Context context, AeronInfra aeronInfra) {
return aeronInfra.addPublication(context.senderChannel(), context.serviceRequestStreamId());
}
@Override
public void subscribe(Subscriber<? super Buffer> subscriber) {
if (subscriber == null) {
throw SpecificationExceptions.spec_2_13_exception();
}
if (!subscribed.compareAndSet(false, true)) {
throw new IllegalStateException("Only single subscriber is supported");
}
signalPoller = createSignalsPoller(subscriber);
try {
executor.execute(signalPoller);
heartbeatSender.start();
} catch (Throwable t) {
signalPoller = null;
subscribed.set(false);
subscriber.onError(new RuntimeException("Failed to schedule poller for signals", t));
}
}
private SignalPoller createSignalsPoller(final Subscriber<? super Buffer> subscriber) {
return new SignalPoller(context, serviceMessageSender, subscriber, aeronInfra, new Consumer<Boolean>() {
@Override
public void accept(Boolean isTerminalSignalReceived) {
heartbeatSender.shutdown();
terminateSession();
signalPoller = null;
subscribed.set(false);
if (context.autoCancel() || isTerminalSignalReceived) {
shutdownTask.accept(null);
}
}
});
}
private void terminateSession() {
try {
serviceMessageSender.sendCancel();
} catch (Exception e) {
context.errorConsumer().accept(
new ServiceMessagePublicationFailedException(ServiceMessageType.Cancel, e));
}
}
public void shutdown() {
if (alive.compareAndSet(true, false)) {
// Doing a shutdown via timer to avoid shutting down Aeron in its thread
final Timer globalTimer = Timers.global();
globalTimer.submit(new Consumer<Long>() {
@Override
public void accept(Long value) {
if (signalPoller != null) {
signalPoller.shutdown();
}
executor.shutdown();
globalTimer.submit(new Consumer<Long>() {
@Override
public void accept(Long aLong) {
if (!executor.isTerminated()) {
globalTimer.submit(this);
return;
}
aeronInfra.close(serviceRequestPub);
aeronInfra.shutdown();
logger.info("publisher shutdown, sessionId: {}", sessionId);
terminated = true;
onTerminateTask.accept(null);
}
});
}
});
}
}
@Override
public Object downstream() {
return signalPoller;
}
public boolean alive() {
return alive.get();
}
public boolean isTerminated() {
return terminated;
}
}
|
package com.rex.demo.study.demo.entity;
import lombok.Data;
/**
* stock 实体类
*
* @Author li zhiqang
* @create 2020/11/24
*/
@Data
public class StockEntity {
private String accountingMl;
private String manufacturerName;
private String customerEnableCode;
private Integer ownerId;
private String warehouseCategoryCode;
private Long organizationId;
private Integer inventoryNumber;
private String sterilizationBatchNo;
private Integer effectiveDays;
private String packageUnitName;
private String warehouseAreaDesc;
private String commodityCode;
private String registerNumber;
private Integer warehouseCategoryId;
private String batchNo;
private String brandName;
private String commoditySpec;
private String commodityNumber;
private String organizationName;
private String supplierEnableCode;
private Integer logicAreaId;
private String commodityType;
private String productionPlace;
private String professionalGroup;
private String customerName;
private Integer quotiety;
private Integer warehouseId;
private Integer goodsLocationId;
private String storageCondition;
private String inventoryOrganizationCode;
private String productionLicense;
private Long producedDate;
private Integer supplierId;
private String warehouseAreaCode;
private String accountingName;
private String ownerCode;
private Integer allocatedQuantity;
private Integer packageUnitId;
private String customerCode;
private Integer customerId;
private String supplierCode;
private String warehouseName;
private String warehouseCode;
private String inventoryOrganizationName;
private String goodsLocation;
private String ownerName;
private String isSimplelevy;
private String logicAreaName;
private String supplierName;
private Integer quantity;
private String inventoryOrganizationId;
private String deviceClassifyType;
private String warehouseCategoryName;
private Integer commodityId;
private String commodityRemark;
private String deviceClassify;
private Integer warehouseAreaId;
private String logicAreaCode;
private String coldChainMark;
private String accountingOne;
private String classifyIdLevel1;
private String classifyIdLevel2;
private String registerName;
private Long effectiveDate;
private String commodityName;
}
|
package com.james.pojo;
import lombok.Data;
@Data
public class Category {
private int cid;
private String cname;
}
|
package com.jlgproject.view;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.jlgproject.R;
/**
* @author 王锋 on 2017/9/6.
*/
public class MyLinearLayout extends LinearLayout {
private ImageView image;
private TextView text;
private Context context;
public MyLinearLayout(Context context) {
this(context,null);
}
public MyLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
this.context=context;
LayoutInflater.from(context).inflate(R.layout.sxy_shiping, this);
init();
}
private void init() {
image= (ImageView) findViewById(R.id.tv_src);
text= (TextView) findViewById(R.id.tv_leibie);
}
public void setImage(String src) {
// image.setImageResource(src);
Glide.with(context).load(src).into(image);
}
public void setText(String str) {
text.setText(str);
}
}
|
package com.stem.entity;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class UserApproveExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public UserApproveExample() {
oredCriteria = new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andIdIsNull() {
addCriterion("ID is null");
return (Criteria) this;
}
public Criteria andIdIsNotNull() {
addCriterion("ID is not null");
return (Criteria) this;
}
public Criteria andIdEqualTo(Integer value) {
addCriterion("ID =", value, "id");
return (Criteria) this;
}
public Criteria andIdNotEqualTo(Integer value) {
addCriterion("ID <>", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThan(Integer value) {
addCriterion("ID >", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThanOrEqualTo(Integer value) {
addCriterion("ID >=", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThan(Integer value) {
addCriterion("ID <", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThanOrEqualTo(Integer value) {
addCriterion("ID <=", value, "id");
return (Criteria) this;
}
public Criteria andIdIn(List<Integer> values) {
addCriterion("ID in", values, "id");
return (Criteria) this;
}
public Criteria andIdNotIn(List<Integer> values) {
addCriterion("ID not in", values, "id");
return (Criteria) this;
}
public Criteria andIdBetween(Integer value1, Integer value2) {
addCriterion("ID between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andIdNotBetween(Integer value1, Integer value2) {
addCriterion("ID not between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andUserNameIsNull() {
addCriterion("USER_NAME is null");
return (Criteria) this;
}
public Criteria andUserNameIsNotNull() {
addCriterion("USER_NAME is not null");
return (Criteria) this;
}
public Criteria andUserNameEqualTo(String value) {
addCriterion("USER_NAME =", value, "userName");
return (Criteria) this;
}
public Criteria andUserNameNotEqualTo(String value) {
addCriterion("USER_NAME <>", value, "userName");
return (Criteria) this;
}
public Criteria andUserNameGreaterThan(String value) {
addCriterion("USER_NAME >", value, "userName");
return (Criteria) this;
}
public Criteria andUserNameGreaterThanOrEqualTo(String value) {
addCriterion("USER_NAME >=", value, "userName");
return (Criteria) this;
}
public Criteria andUserNameLessThan(String value) {
addCriterion("USER_NAME <", value, "userName");
return (Criteria) this;
}
public Criteria andUserNameLessThanOrEqualTo(String value) {
addCriterion("USER_NAME <=", value, "userName");
return (Criteria) this;
}
public Criteria andUserNameLike(String value) {
addCriterion("USER_NAME like", value, "userName");
return (Criteria) this;
}
public Criteria andUserNameNotLike(String value) {
addCriterion("USER_NAME not like", value, "userName");
return (Criteria) this;
}
public Criteria andUserNameIn(List<String> values) {
addCriterion("USER_NAME in", values, "userName");
return (Criteria) this;
}
public Criteria andUserNameNotIn(List<String> values) {
addCriterion("USER_NAME not in", values, "userName");
return (Criteria) this;
}
public Criteria andUserNameBetween(String value1, String value2) {
addCriterion("USER_NAME between", value1, value2, "userName");
return (Criteria) this;
}
public Criteria andUserNameNotBetween(String value1, String value2) {
addCriterion("USER_NAME not between", value1, value2, "userName");
return (Criteria) this;
}
public Criteria andNameIsNull() {
addCriterion("NAME is null");
return (Criteria) this;
}
public Criteria andNameIsNotNull() {
addCriterion("NAME is not null");
return (Criteria) this;
}
public Criteria andNameEqualTo(String value) {
addCriterion("NAME =", value, "name");
return (Criteria) this;
}
public Criteria andNameNotEqualTo(String value) {
addCriterion("NAME <>", value, "name");
return (Criteria) this;
}
public Criteria andNameGreaterThan(String value) {
addCriterion("NAME >", value, "name");
return (Criteria) this;
}
public Criteria andNameGreaterThanOrEqualTo(String value) {
addCriterion("NAME >=", value, "name");
return (Criteria) this;
}
public Criteria andNameLessThan(String value) {
addCriterion("NAME <", value, "name");
return (Criteria) this;
}
public Criteria andNameLessThanOrEqualTo(String value) {
addCriterion("NAME <=", value, "name");
return (Criteria) this;
}
public Criteria andNameLike(String value) {
addCriterion("NAME like", value, "name");
return (Criteria) this;
}
public Criteria andNameNotLike(String value) {
addCriterion("NAME not like", value, "name");
return (Criteria) this;
}
public Criteria andNameIn(List<String> values) {
addCriterion("NAME in", values, "name");
return (Criteria) this;
}
public Criteria andNameNotIn(List<String> values) {
addCriterion("NAME not in", values, "name");
return (Criteria) this;
}
public Criteria andNameBetween(String value1, String value2) {
addCriterion("NAME between", value1, value2, "name");
return (Criteria) this;
}
public Criteria andNameNotBetween(String value1, String value2) {
addCriterion("NAME not between", value1, value2, "name");
return (Criteria) this;
}
public Criteria andEmailIsNull() {
addCriterion("EMAIL is null");
return (Criteria) this;
}
public Criteria andEmailIsNotNull() {
addCriterion("EMAIL is not null");
return (Criteria) this;
}
public Criteria andEmailEqualTo(String value) {
addCriterion("EMAIL =", value, "email");
return (Criteria) this;
}
public Criteria andEmailNotEqualTo(String value) {
addCriterion("EMAIL <>", value, "email");
return (Criteria) this;
}
public Criteria andEmailGreaterThan(String value) {
addCriterion("EMAIL >", value, "email");
return (Criteria) this;
}
public Criteria andEmailGreaterThanOrEqualTo(String value) {
addCriterion("EMAIL >=", value, "email");
return (Criteria) this;
}
public Criteria andEmailLessThan(String value) {
addCriterion("EMAIL <", value, "email");
return (Criteria) this;
}
public Criteria andEmailLessThanOrEqualTo(String value) {
addCriterion("EMAIL <=", value, "email");
return (Criteria) this;
}
public Criteria andEmailLike(String value) {
addCriterion("EMAIL like", value, "email");
return (Criteria) this;
}
public Criteria andEmailNotLike(String value) {
addCriterion("EMAIL not like", value, "email");
return (Criteria) this;
}
public Criteria andEmailIn(List<String> values) {
addCriterion("EMAIL in", values, "email");
return (Criteria) this;
}
public Criteria andEmailNotIn(List<String> values) {
addCriterion("EMAIL not in", values, "email");
return (Criteria) this;
}
public Criteria andEmailBetween(String value1, String value2) {
addCriterion("EMAIL between", value1, value2, "email");
return (Criteria) this;
}
public Criteria andEmailNotBetween(String value1, String value2) {
addCriterion("EMAIL not between", value1, value2, "email");
return (Criteria) this;
}
public Criteria andSexIsNull() {
addCriterion("SEX is null");
return (Criteria) this;
}
public Criteria andSexIsNotNull() {
addCriterion("SEX is not null");
return (Criteria) this;
}
public Criteria andSexEqualTo(String value) {
addCriterion("SEX =", value, "sex");
return (Criteria) this;
}
public Criteria andSexNotEqualTo(String value) {
addCriterion("SEX <>", value, "sex");
return (Criteria) this;
}
public Criteria andSexGreaterThan(String value) {
addCriterion("SEX >", value, "sex");
return (Criteria) this;
}
public Criteria andSexGreaterThanOrEqualTo(String value) {
addCriterion("SEX >=", value, "sex");
return (Criteria) this;
}
public Criteria andSexLessThan(String value) {
addCriterion("SEX <", value, "sex");
return (Criteria) this;
}
public Criteria andSexLessThanOrEqualTo(String value) {
addCriterion("SEX <=", value, "sex");
return (Criteria) this;
}
public Criteria andSexLike(String value) {
addCriterion("SEX like", value, "sex");
return (Criteria) this;
}
public Criteria andSexNotLike(String value) {
addCriterion("SEX not like", value, "sex");
return (Criteria) this;
}
public Criteria andSexIn(List<String> values) {
addCriterion("SEX in", values, "sex");
return (Criteria) this;
}
public Criteria andSexNotIn(List<String> values) {
addCriterion("SEX not in", values, "sex");
return (Criteria) this;
}
public Criteria andSexBetween(String value1, String value2) {
addCriterion("SEX between", value1, value2, "sex");
return (Criteria) this;
}
public Criteria andSexNotBetween(String value1, String value2) {
addCriterion("SEX not between", value1, value2, "sex");
return (Criteria) this;
}
public Criteria andIdCardIsNull() {
addCriterion("ID_CARD is null");
return (Criteria) this;
}
public Criteria andIdCardIsNotNull() {
addCriterion("ID_CARD is not null");
return (Criteria) this;
}
public Criteria andIdCardEqualTo(String value) {
addCriterion("ID_CARD =", value, "idCard");
return (Criteria) this;
}
public Criteria andIdCardNotEqualTo(String value) {
addCriterion("ID_CARD <>", value, "idCard");
return (Criteria) this;
}
public Criteria andIdCardGreaterThan(String value) {
addCriterion("ID_CARD >", value, "idCard");
return (Criteria) this;
}
public Criteria andIdCardGreaterThanOrEqualTo(String value) {
addCriterion("ID_CARD >=", value, "idCard");
return (Criteria) this;
}
public Criteria andIdCardLessThan(String value) {
addCriterion("ID_CARD <", value, "idCard");
return (Criteria) this;
}
public Criteria andIdCardLessThanOrEqualTo(String value) {
addCriterion("ID_CARD <=", value, "idCard");
return (Criteria) this;
}
public Criteria andIdCardLike(String value) {
addCriterion("ID_CARD like", value, "idCard");
return (Criteria) this;
}
public Criteria andIdCardNotLike(String value) {
addCriterion("ID_CARD not like", value, "idCard");
return (Criteria) this;
}
public Criteria andIdCardIn(List<String> values) {
addCriterion("ID_CARD in", values, "idCard");
return (Criteria) this;
}
public Criteria andIdCardNotIn(List<String> values) {
addCriterion("ID_CARD not in", values, "idCard");
return (Criteria) this;
}
public Criteria andIdCardBetween(String value1, String value2) {
addCriterion("ID_CARD between", value1, value2, "idCard");
return (Criteria) this;
}
public Criteria andIdCardNotBetween(String value1, String value2) {
addCriterion("ID_CARD not between", value1, value2, "idCard");
return (Criteria) this;
}
public Criteria andPartnerNameIsNull() {
addCriterion("PARTNER_NAME is null");
return (Criteria) this;
}
public Criteria andPartnerNameIsNotNull() {
addCriterion("PARTNER_NAME is not null");
return (Criteria) this;
}
public Criteria andPartnerNameEqualTo(String value) {
addCriterion("PARTNER_NAME =", value, "partnerName");
return (Criteria) this;
}
public Criteria andPartnerNameNotEqualTo(String value) {
addCriterion("PARTNER_NAME <>", value, "partnerName");
return (Criteria) this;
}
public Criteria andPartnerNameGreaterThan(String value) {
addCriterion("PARTNER_NAME >", value, "partnerName");
return (Criteria) this;
}
public Criteria andPartnerNameGreaterThanOrEqualTo(String value) {
addCriterion("PARTNER_NAME >=", value, "partnerName");
return (Criteria) this;
}
public Criteria andPartnerNameLessThan(String value) {
addCriterion("PARTNER_NAME <", value, "partnerName");
return (Criteria) this;
}
public Criteria andPartnerNameLessThanOrEqualTo(String value) {
addCriterion("PARTNER_NAME <=", value, "partnerName");
return (Criteria) this;
}
public Criteria andPartnerNameLike(String value) {
addCriterion("PARTNER_NAME like", value, "partnerName");
return (Criteria) this;
}
public Criteria andPartnerNameNotLike(String value) {
addCriterion("PARTNER_NAME not like", value, "partnerName");
return (Criteria) this;
}
public Criteria andPartnerNameIn(List<String> values) {
addCriterion("PARTNER_NAME in", values, "partnerName");
return (Criteria) this;
}
public Criteria andPartnerNameNotIn(List<String> values) {
addCriterion("PARTNER_NAME not in", values, "partnerName");
return (Criteria) this;
}
public Criteria andPartnerNameBetween(String value1, String value2) {
addCriterion("PARTNER_NAME between", value1, value2, "partnerName");
return (Criteria) this;
}
public Criteria andPartnerNameNotBetween(String value1, String value2) {
addCriterion("PARTNER_NAME not between", value1, value2, "partnerName");
return (Criteria) this;
}
public Criteria andPartnerTelIsNull() {
addCriterion("PARTNER_TEL is null");
return (Criteria) this;
}
public Criteria andPartnerTelIsNotNull() {
addCriterion("PARTNER_TEL is not null");
return (Criteria) this;
}
public Criteria andPartnerTelEqualTo(String value) {
addCriterion("PARTNER_TEL =", value, "partnerTel");
return (Criteria) this;
}
public Criteria andPartnerTelNotEqualTo(String value) {
addCriterion("PARTNER_TEL <>", value, "partnerTel");
return (Criteria) this;
}
public Criteria andPartnerTelGreaterThan(String value) {
addCriterion("PARTNER_TEL >", value, "partnerTel");
return (Criteria) this;
}
public Criteria andPartnerTelGreaterThanOrEqualTo(String value) {
addCriterion("PARTNER_TEL >=", value, "partnerTel");
return (Criteria) this;
}
public Criteria andPartnerTelLessThan(String value) {
addCriterion("PARTNER_TEL <", value, "partnerTel");
return (Criteria) this;
}
public Criteria andPartnerTelLessThanOrEqualTo(String value) {
addCriterion("PARTNER_TEL <=", value, "partnerTel");
return (Criteria) this;
}
public Criteria andPartnerTelLike(String value) {
addCriterion("PARTNER_TEL like", value, "partnerTel");
return (Criteria) this;
}
public Criteria andPartnerTelNotLike(String value) {
addCriterion("PARTNER_TEL not like", value, "partnerTel");
return (Criteria) this;
}
public Criteria andPartnerTelIn(List<String> values) {
addCriterion("PARTNER_TEL in", values, "partnerTel");
return (Criteria) this;
}
public Criteria andPartnerTelNotIn(List<String> values) {
addCriterion("PARTNER_TEL not in", values, "partnerTel");
return (Criteria) this;
}
public Criteria andPartnerTelBetween(String value1, String value2) {
addCriterion("PARTNER_TEL between", value1, value2, "partnerTel");
return (Criteria) this;
}
public Criteria andPartnerTelNotBetween(String value1, String value2) {
addCriterion("PARTNER_TEL not between", value1, value2, "partnerTel");
return (Criteria) this;
}
public Criteria andPartnerAddressIsNull() {
addCriterion("PARTNER_ADDRESS is null");
return (Criteria) this;
}
public Criteria andPartnerAddressIsNotNull() {
addCriterion("PARTNER_ADDRESS is not null");
return (Criteria) this;
}
public Criteria andPartnerAddressEqualTo(String value) {
addCriterion("PARTNER_ADDRESS =", value, "partnerAddress");
return (Criteria) this;
}
public Criteria andPartnerAddressNotEqualTo(String value) {
addCriterion("PARTNER_ADDRESS <>", value, "partnerAddress");
return (Criteria) this;
}
public Criteria andPartnerAddressGreaterThan(String value) {
addCriterion("PARTNER_ADDRESS >", value, "partnerAddress");
return (Criteria) this;
}
public Criteria andPartnerAddressGreaterThanOrEqualTo(String value) {
addCriterion("PARTNER_ADDRESS >=", value, "partnerAddress");
return (Criteria) this;
}
public Criteria andPartnerAddressLessThan(String value) {
addCriterion("PARTNER_ADDRESS <", value, "partnerAddress");
return (Criteria) this;
}
public Criteria andPartnerAddressLessThanOrEqualTo(String value) {
addCriterion("PARTNER_ADDRESS <=", value, "partnerAddress");
return (Criteria) this;
}
public Criteria andPartnerAddressLike(String value) {
addCriterion("PARTNER_ADDRESS like", value, "partnerAddress");
return (Criteria) this;
}
public Criteria andPartnerAddressNotLike(String value) {
addCriterion("PARTNER_ADDRESS not like", value, "partnerAddress");
return (Criteria) this;
}
public Criteria andPartnerAddressIn(List<String> values) {
addCriterion("PARTNER_ADDRESS in", values, "partnerAddress");
return (Criteria) this;
}
public Criteria andPartnerAddressNotIn(List<String> values) {
addCriterion("PARTNER_ADDRESS not in", values, "partnerAddress");
return (Criteria) this;
}
public Criteria andPartnerAddressBetween(String value1, String value2) {
addCriterion("PARTNER_ADDRESS between", value1, value2, "partnerAddress");
return (Criteria) this;
}
public Criteria andPartnerAddressNotBetween(String value1, String value2) {
addCriterion("PARTNER_ADDRESS not between", value1, value2, "partnerAddress");
return (Criteria) this;
}
public Criteria andCreateTimeIsNull() {
addCriterion("CREATE_TIME is null");
return (Criteria) this;
}
public Criteria andCreateTimeIsNotNull() {
addCriterion("CREATE_TIME is not null");
return (Criteria) this;
}
public Criteria andCreateTimeEqualTo(Date value) {
addCriterion("CREATE_TIME =", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotEqualTo(Date value) {
addCriterion("CREATE_TIME <>", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeGreaterThan(Date value) {
addCriterion("CREATE_TIME >", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeGreaterThanOrEqualTo(Date value) {
addCriterion("CREATE_TIME >=", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeLessThan(Date value) {
addCriterion("CREATE_TIME <", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeLessThanOrEqualTo(Date value) {
addCriterion("CREATE_TIME <=", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeIn(List<Date> values) {
addCriterion("CREATE_TIME in", values, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotIn(List<Date> values) {
addCriterion("CREATE_TIME not in", values, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeBetween(Date value1, Date value2) {
addCriterion("CREATE_TIME between", value1, value2, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotBetween(Date value1, Date value2) {
addCriterion("CREATE_TIME not between", value1, value2, "createTime");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
}
|
package it.cinema.multisala;
/**
* Classe <code>Recensione</code> contiene tutte le informazioni
* relative alle recensioni dei film realizzate dei clienti.
*
* @version 1.00 08 Gen 2018
* @author Matteo Borghese
*
*/
public class Recensione {
/** Id della recensione */
private int idRecensione;
/** Voto del film */
private int voto;
/** Commento del film */
private String commento;
/** Nome utente del recensore */
private String username;
/** Parole non lecite */
private final String[] BLACK_LIST = {"parolaccia", "insulto"};
/**
* Costruttore di recensione.
*
* @param idRecensione id della recensione
* @param voto voto del film
* @param commento commento del film
* @param username ome utente del recensore
*/
public Recensione(int idRecensione, int voto, String commento, String username) {
super();
this.setIdRecensione(idRecensione);;
this.setVoto(voto);;
this.setCommento(commento);;
this.setUsername(username);;
}
/**
* Get id della recensione.
*
* @return id della recensione
*/
public int getIdRecensione() {
return idRecensione;
}
/**
* Set id della recensione.
*
* @param idRecensione id della recensione
*/
public void setIdRecensione(int idRecensione) {
this.idRecensione = idRecensione;
}
/**
* Get voto del film.
*
* @return voto del film
*/
public int getVoto() {
return voto;
}
/**
* Set voto del film.
*
* @param voto voto del film
*/
public void setVoto(int voto) {
this.voto = voto;
}
/**
* Get commento del film.
*
* @return commento del film
*/
public String getCommento() {
return commento;
}
/**
* Set commento del film.
*
* @param commento commento del film
*/
public void setCommento(String commento) {
this.commento = commento;
}
/**
* Get nome utente del recensore.
*
* @return nome utente del recensore
*/
public String getUsername() {
return username;
}
/**
* Set nome utente del recensore.
*
* @param username nome utente del recensore
*/
public void setUsername(String username) {
this.username = username;
}
/**
* Valida la recensione.
*
* @param voto voto del film
* @param commento commento al film
* @return true se la recensione è conforme, false altrimenti
*/
public boolean verificaRecensione(int voto,String commento) {
if(voto == 0) {
System.err.println("inserire un voto");
return false; //qualora l'utente non inserisca il voto esso è 0 val default
}
if(commento == null || commento.equals("")) {
System.err.println("inserire un commento");
return false; //nessun commento inserito
}else{
for (String badWord : BLACK_LIST) {
//rimuovo dal commento tutte le parole indesiderate
commento = commento.replaceAll("(?i)\\b[^\\w -]*" + badWord
+ "[^\\w -]*\\b", "****");
}
this.setCommento(commento);
return true;
}
}
}
|
package me.luliru.gateway.core.process;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import me.luliru.gateway.core.RequestContext;
import reactor.core.publisher.Mono;
/**
* DispatchInboundHandler
* Created by luliru on 2019/7/30.
*/
@Slf4j
public class ProcessorChain extends SimpleChannelInboundHandler<FullHttpRequest> {
private ProcessorInitializer initializer;
private ProcessorHolder head;
private ProcessorHolder tail;
private ProcessorHolder point;
private Mono<?> mono;
public ProcessorChain(ProcessorInitializer initializer){
this.initializer = initializer;
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
RequestContext rctx = RequestContext.createContext(ctx);
rctx.setKeepAlive(HttpUtil.isKeepAlive(msg));
rctx.chain(this);
log.debug("channelRead0:{}",rctx.id());
initializer.init(rctx,msg);
point = head;
mono = Mono.just(msg);
loop(rctx);
}
private void loop(RequestContext rctx){
if(point != null){
Processor processor = point.getProcessor();
try{
mono = processor.process(rctx,mono);
if(mono != null){
// 由于mono的机制,只有在subscribe时,事件才会被处理
// 所以必须在返回每个mono之后,通过调用subscribe,强制触发processor处理,从而实现processor动态增减
mono.subscribe(t -> {
log.debug("{} => {}",processor.getClass(),t);
mono = Mono.justOrEmpty(t);
point = point.getNext();
loop(rctx);
},e ->{
log.debug("{} => exception",processor.getClass(),e);
mono = Mono.error(e);
point = point.getNext();
loop(rctx);
});
}
}catch (Exception e){
log.warn("出现未知异常",e);
}
}
}
public void addLast(Processor processor){
addLast(processor.toString(),processor);
}
public void addLast(String name,Processor processor){
ProcessorHolder holder = new ProcessorHolder();
holder.setName(processor.toString());
holder.setProcessor(processor);
if(head == null){
head = holder;
tail = holder;
}else{
tail.setNext(holder);
holder.setPrev(tail);
tail = holder;
}
}
public void channelInactive(ChannelHandlerContext ctx) {
RequestContext.destroyContext(ctx);
ctx.fireChannelInactive();
}
}
|
import java.io.IOException;
import java.util.Scanner;
/*
* Another class to trade with. feel free to move the main.
*/
public class Trader {
public static void main(String [] args) throws IOException
{
System.out.println("Enter the Ticker:");
Scanner sc = new Scanner(System.in);
Stock stock = new Stock(sc.nextLine());
System.out.println(MarketUtils.getPrice(stock.ticker));
System.out.println(stock.price);
}
}
|
package com.jmeter.plugin.util;
import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.URL;
import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ReferenceConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import com.alibaba.dubbo.config.utils.ReferenceConfigCache;
import com.alibaba.dubbo.registry.RegistryService;
import com.alibaba.dubbo.rpc.service.GenericService;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
/**
* @Author: liuzhanhui
* @Decription:
* @Date: Created in 2019-01-02:10:56
* Modify date: 2019-01-02:10:56
*/
public class ZkServiceUtil {
public static Map<String, String[]> getInterfaceMethods(String address){
Map<String, String[]> serviceMap = new HashMap<>();
try {
ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setName("dubboSample");
RegistryConfig registry = new RegistryConfig();
registry.setAddress(address);
registry.setProtocol("zookeeper");
registry.setClient("curator");
registry.setGroup(null);
ReferenceConfig referenceConfig = new ReferenceConfig();
referenceConfig.setApplication(applicationConfig);
referenceConfig.setRegistry(registry);
referenceConfig.setInterface("com.alibaba.dubbo.registry.RegistryService");
ReferenceConfigCache cache = ReferenceConfigCache.getCache();
RegistryService registryService = (RegistryService) cache.get(referenceConfig);
RegistryServerSync registryServerSync = RegistryServerSync.get(address + "_");
registryService.subscribe(RegistryServerSync.SUBSCRIBE, registryServerSync);
ConcurrentMap<String, ConcurrentMap<String, Map<String, URL>>> map = registryServerSync.getRegistryCache();
ConcurrentMap<String, Map<String, URL>> providers = map.get(Constants.PROVIDERS_CATEGORY);
if (providers == null || providers.isEmpty()) {
throw new RuntimeException("zookeeper连接失败");
} else {
for (String url : providers.keySet()) {
Map<String, URL> provider = providers.get(url);
for (String str : provider.keySet()) {
String methodName = provider.get(str).getParameter(Constants.METHODS_KEY);
String[] methods = methodName.split(",");
serviceMap.put(url, methods);
}
}
}
} catch (Exception e) {
System.out.println("zk连接失败");
return null;
}
return serviceMap;
}
public static GenericService getGenericService(String address, String interfaceName) {
GenericService genericService = null;
try {
RegistryConfig registry = new RegistryConfig();
registry.setAddress(address);
registry.setClient("curator");
registry.setProtocol("zookeeper");
registry.setCheck(true);
registry.setGroup(null);
registry.setTimeout(10000);
ReferenceConfig<GenericService> reference = new ReferenceConfig<GenericService>();
reference.setApplication(new ApplicationConfig("dubboSample"));
reference.setInterface(interfaceName);
reference.setProtocol("dubbo");
reference.setTimeout(5000);
reference.setVersion("3.0.0");
reference.setGroup(null);
reference.setRegistry(registry);
reference.setGeneric(true);
genericService = reference.get();
}catch (Exception e){
System.out.println("zk连接异常,请检查zk地址!");
return null;
}
return genericService;
}
public static void main(String[] args) {
GenericService genericService = getGenericService("172.18.4.48:2181", "com.noriental.adminsvr.service.teaching.ChapterService");
Map<String,Object> map = new HashMap();
map.put("entity","200,201,202");
Object result = genericService.$invoke("findByIds", new String[]{"com.noriental.adminsvr.request.RequestEntity"}, new Object[]{map});
System.out.println(result);
}
}
|
package reference_test;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.HashMap;
import java.util.WeakHashMap;
/**
* Description:
*
* @author Baltan
* @date 2018/5/3 22:29
*/
public class Test3 {
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
/**
* a和m有对"a"的强引用,wm有对"a"的弱引用
* b和m有对"b"的强引用,wm有对"b"的弱引用
*/
String a = new String("a");
String b = new String("b");
WeakHashMap wm = new WeakHashMap();
wm.put(a, "aaa");
wm.put(b, "bbb");
HashMap m = new HashMap();
m.put(a, "aaa");
m.put(b, "bbb");
System.out.println(mapper.writeValueAsString(m));
System.out.println(mapper.writeValueAsString(wm));
System.out.println("============================");
/**
* 以下四行代码执行后,wm有对"a"的弱引用,b和m有对"b"的强引用,此时"a"会被垃圾回收
*/
m.remove(a);
wm.remove(b);
a = null;
b = null;
System.gc();
System.out.println(mapper.writeValueAsString(m));
System.out.println(mapper.writeValueAsString(wm));
}
}
|
package exer;
import java.util.HashMap;
public class MethodTest1 {
static HashMap<Integer,Long> map = new HashMap<>();
public static void main(String[] args) {
long start = System.nanoTime();
long i = Method(6);
long end = System.nanoTime();
System.out.println(i);
System.out.println(end - start);
}
//利用递归实现斐波那契数列
public static long Method(int num){
if(num == 1 || num == 2){
return 1;
}
return Method(num - 1) + Method(num - 2);
}
//备忘录算法
public static long Method1(int num){
if(num == 1 || num == 2){
return 1;
}
Long value;
if((value = map.get(num)) == null){
value = Method1(num - 1) + Method1(num - 2);
map.put(num, value);
}
return value;
}
//用普通循环实现斐波那契数列
public static long Method2(int num){
long l = 1, j = 1, k = 1;
for (int i = 3; i <= num; i++) {
k = l + j;
l = j;
j = k;
}
return num == 0 ? 0 : k;
}
}
|
package com.action;
import com.dao.kqjlDao;
import com.entity.Attence;
import java.io.PrintStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class kqjlAction
{
private String reason;
private String time;
private String emname;
private String method;
private String userintro;
private String username;
private String password;
private String monitor;
private kqjlDao dao = new kqjlDao();
public String kqjlInsert()
{
System.out.println(this.reason + "::" + this.time + "::" + "::" + this.emname + "::" + this.method + "::" + this.userintro+"::"+this.monitor);
Attence attence = new Attence();
attence.setAttencetype(this.reason.concat("(".concat("考勤".concat(")"))));
attence.setStartTime(changeTime(this.time));
attence.setEndTime(changeTime(this.time));
attence.setName(this.emname);
attence.setReason(this.userintro);
attence.setStatus("同意");
attence.setMonitor(monitor);
boolean result = this.dao.kqjlInsert(attence);
if (result) {
return "success";
}
return "error";
}
public Date changeTime(String time)
{
Date date = new Date();
String h = String.valueOf(date.getHours());
String m = String.valueOf(date.getMinutes());
String s = String.valueOf(date.getSeconds());
String ctime = time.concat(" ".concat(h.concat(":".concat(m.concat(":".concat(s))))));
System.out.println("修改后的time--->>>>::" + ctime);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date2 = null;
try
{
date2 = sdf.parse(ctime);
}
catch (ParseException e)
{
e.printStackTrace();
}
return date2;
}
public String getReason()
{
return this.reason;
}
public void setReason(String reason)
{
this.reason = reason;
}
public String getTime()
{
return this.time;
}
public void setTime(String time)
{
this.time = time;
}
public String getEmname()
{
return this.emname;
}
public void setEmname(String emname)
{
this.emname = emname;
}
public String getMethod()
{
return this.method;
}
public void setMethod(String method)
{
this.method = method;
}
public String getUserintro()
{
return this.userintro;
}
public void setUserintro(String userintro)
{
this.userintro = userintro;
}
public String getUsername()
{
return this.username;
}
public void setUsername(String username)
{
this.username = username;
}
public String getPassword()
{
return this.password;
}
public void setPassword(String password)
{
this.password = password;
}
public String getMonitor() {
return monitor;
}
public void setMonitor(String monitor) {
this.monitor = monitor;
}
}
|
/*
* 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 twitteranalysis;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Fraser
*/
public class EncodeChromosomeTest {
public EncodeChromosomeTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of setOgUserName method, of class EncodeChromosome.
*/
@Test
public void testSetOgUserName() {
System.out.println("setOgUserName");
String ogUserName = "Fraser";
EncodeChromosome instance = new EncodeChromosome();
instance.setOgUserName(ogUserName);
}
/**
* Test of setOgStatus method, of class EncodeChromosome.
*/
@Test
public void testSetOgStatus() {
System.out.println("setOgStatus");
String status = "Hello";
EncodeChromosome instance = new EncodeChromosome();
instance.setOgStatus(status);
}
/**
* Test of setComment method, of class EncodeChromosome.
*/
@Test
public void testSetComment() {
System.out.println("setComment");
String comment = "Hi";
EncodeChromosome instance = new EncodeChromosome();
instance.setComment(comment);
}
/**
* Test of setFollowersCount method, of class EncodeChromosome.
*/
@Test
public void testSetFollowersCount() {
System.out.println("setFollowersCount");
int followersCount = 500;
EncodeChromosome instance = new EncodeChromosome();
instance.setFollowersCount(followersCount);
}
/**
* Test of setFavouriteCount method, of class EncodeChromosome.
*/
@Test
public void testSetFavouriteCount() {
System.out.println("setFavouriteCount");
int favouriteCount = 2;
EncodeChromosome instance = new EncodeChromosome();
instance.setFavouriteCount(favouriteCount);
}
/**
* Test of setFriendCount method, of class EncodeChromosome.
*/
@Test
public void testSetFriendCount() {
System.out.println("setFriendCount");
int friendCount = 400;
EncodeChromosome instance = new EncodeChromosome();
instance.setFriendCount(friendCount);
}
/**
* Test of setLocation method, of class EncodeChromosome.
*/
@Test
public void testSetLocation() {
System.out.println("setLocation");
Country location = new Country("AT","Austria","EU");
EncodeChromosome instance = new EncodeChromosome();
instance.setLocation(location);
}
/**
* Test of setIsVerified method, of class EncodeChromosome.
*/
@Test
public void testSetIsVerified() {
System.out.println("setIsVerified");
boolean verified = true;
EncodeChromosome instance = new EncodeChromosome();
instance.setIsVerified(verified);
}
/**
* Test of setHasSwear method, of class EncodeChromosome.
*/
@Test
public void testSetHasSwear() {
System.out.println("setHasSwear");
boolean swear = true;
EncodeChromosome instance = new EncodeChromosome();
instance.setHasSwear(swear);
}
/**
* Test of setHasPositiveWord method, of class EncodeChromosome.
*/
@Test
public void testSetHasPositiveWord() {
System.out.println("setHasPositiveWord");
boolean posWord = true;
EncodeChromosome instance = new EncodeChromosome();
instance.setHasPositiveWord(posWord);
}
/**
* Test of setHasNegativeWord method, of class EncodeChromosome.
*/
@Test
public void testSetHasNegativeWord() {
System.out.println("setHasNegativeWord");
boolean negWord = true;
EncodeChromosome instance = new EncodeChromosome();
instance.setHasNegativeWord(negWord);
}
/**
* Test of setHasPositiveEmoji method, of class EncodeChromosome.
*/
@Test
public void testSetHasPositiveEmoji() {
System.out.println("setHasPositiveEmoji");
boolean posEmoji = true;
EncodeChromosome instance = new EncodeChromosome();
instance.setHasPositiveEmoji(posEmoji);
}
/**
* Test of setHasnegativeEmoji method, of class EncodeChromosome.
*/
@Test
public void testSetHasnegativeEmoji() {
System.out.println("setHasnegativeEmoji");
boolean negEmoji = true;
EncodeChromosome instance = new EncodeChromosome();
instance.setHasnegativeEmoji(negEmoji);
}
/**
* Test of getOgUserName method, of class EncodeChromosome.
*/
@Test
public void testGetOgUserName() {
System.out.println("getOgUserName");
EncodeChromosome instance = new EncodeChromosome();
instance.setOgUserName("Fraser");
String expResult = "Fraser";
String result = instance.getOgUserName();
assertEquals(expResult, result);
}
/**
* Test of getOgStatus method, of class EncodeChromosome.
*/
@Test
public void testGetOgStatus() {
System.out.println("getOgStatus");
EncodeChromosome instance = new EncodeChromosome();
instance.setOgStatus("Hello");
String expResult = "Hello";
String result = instance.getOgStatus();
assertEquals(expResult, result);
}
/**
* Test of getComment method, of class EncodeChromosome.
*/
@Test
public void testGetComment() {
System.out.println("getComment");
EncodeChromosome instance = new EncodeChromosome();
instance.setComment("hi");
String expResult = "hi";
String result = instance.getComment();
assertEquals(expResult, result);
}
/**
* Test of getFollowersCount method, of class EncodeChromosome.
*/
@Test
public void testGetFollowersCount() {
System.out.println("getFollowersCount");
EncodeChromosome instance = new EncodeChromosome();
instance.setFollowersCount(150);
int expResult = 2;
int result = instance.getFollowersCount();
assertEquals(expResult, result);
}
/**
* Test of getFavouriteCount method, of class EncodeChromosome.
*/
@Test
public void testGetFavouriteCount() {
System.out.println("getFavouriteCount");
EncodeChromosome instance = new EncodeChromosome();
instance.setFavouriteCount(5);
int expResult = 1;
int result = instance.getFavouriteCount();
assertEquals(expResult, result);
}
/**
* Test of getFriendCount method, of class EncodeChromosome.
*/
@Test
public void testGetFriendCount() {
System.out.println("getFriendCount");
EncodeChromosome instance = new EncodeChromosome();
instance.setFriendCount(1000);
int expResult = 3;
int result = instance.getFriendCount();
assertEquals(expResult, result);
}
/**
* Test of getLocation method, of class EncodeChromosome.
*/
@Test
public void testGetLocation() {
System.out.println("getLocation");
EncodeChromosome instance = new EncodeChromosome();
instance.setLocation(new Country("AT","Austria","EU"));
int expResult = 3;
int result = instance.getLocation();
assertEquals(expResult, result);
}
/**
* Test of getIsVerified method, of class EncodeChromosome.
*/
@Test
public void testGetIsVerified() {
System.out.println("getIsVerified");
EncodeChromosome instance = new EncodeChromosome();
instance.setIsVerified(true);
int expResult = 1;
int result = instance.getIsVerified();
assertEquals(expResult, result);
}
/**
* Test of getHasSwear method, of class EncodeChromosome.
*/
@Test
public void testGetHasSwear() {
System.out.println("getHasSwear");
EncodeChromosome instance = new EncodeChromosome();
instance.setHasSwear(true);
int expResult = 1;
int result = instance.getHasSwear();
assertEquals(expResult, result);
}
/**
* Test of getHasPositiveWord method, of class EncodeChromosome.
*/
@Test
public void testGetHasPositiveWord() {
System.out.println("getHasPositiveWord");
EncodeChromosome instance = new EncodeChromosome();
instance.setHasPositiveWord(true);
int expResult = 1;
int result = instance.getHasPositiveWord();
assertEquals(expResult, result);
}
/**
* Test of getHasNegativeWord method, of class EncodeChromosome.
*/
@Test
public void testGetHasNegativeWord() {
System.out.println("getHasNegativeWord");
EncodeChromosome instance = new EncodeChromosome();
instance.setHasNegativeWord(true);
int expResult = 1;
int result = instance.getHasNegativeWord();
assertEquals(expResult, result);
}
/**
* Test of getHasPositiveEmoji method, of class EncodeChromosome.
*/
@Test
public void testGetHasPositiveEmoji() {
System.out.println("getHasPositiveEmoji");
EncodeChromosome instance = new EncodeChromosome();
instance.setHasPositiveEmoji(true);
int expResult = 1;
int result = instance.getHasPositiveEmoji();
assertEquals(expResult, result);
}
/**
* Test of getHasNegativeEmoji method, of class EncodeChromosome.
*/
@Test
public void testGetHasNegativeEmoji() {
System.out.println("getHasNegativeEmoji");
EncodeChromosome instance = new EncodeChromosome();
instance.setHasnegativeEmoji(true);
int expResult = 1;
int result = instance.getHasNegativeEmoji();
assertEquals(expResult, result);
}
}
|
import java.awt.*;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;
public class transactionPanel extends JPanel implements Constants{
String investorName;
int investorCounter=0, companyCounter = 0;
JLabel titles[] = new JLabel[6];
public static boolean[] isSelling = new boolean[3];
public static JLabel transactionNumber[] = new JLabel[3];
JLabel companyName[] = new JLabel[3];
public static JLabel totalPrice[] = new JLabel[3];
JRadioButton buyType[] = new JRadioButton[3];
JRadioButton sellType[] = new JRadioButton[3];
ButtonGroup group[] = new ButtonGroup[3];
public static JTextField quantity[] = new JTextField[3];
public static JTextField unitPrice[] = new JTextField[3];
JPanel panel = new JPanel();
JPanel[] panels = new JPanel[investorCounter];
JPanel mainPanel= new JPanel(new GridLayout(1,6,5,5));
JPanel titlesPanel = new JPanel(new GridLayout(1,6,5,5));
JPanel TTpanel = new JPanel(new GridLayout(3,1,5,5));
JPanel compPanel = new JPanel(new GridLayout(3,1,5,5));
JPanel totalPanel = new JPanel(new GridLayout(3,1,5,5));
JPanel qtyPanel = new JPanel(new GridLayout(3,1,5,5));
JPanel pricePanel = new JPanel(new GridLayout(3,1,5,5));
JPanel numbersPanel = new JPanel(new GridLayout(3,1,5,5));
JPanel buttonPanel = new JPanel(new GridLayout(3,1,5,5));
NextButtonListener textListener = new NextButtonListener();
ButtonListener bl = new ButtonListener();
int[] actInv = new int[3];
int[] actComp = new int[9];
final boolean testInvestor[] = {false, true, true, false, true};
final boolean testCompanies1[] = {false, true, true, false, true};
;
public transactionPanel(int InvestorNumber) //String nameInvestor, boolean[5] listCompanies
{
panel.setLayout(new BorderLayout());
for(int i = 0; i <=5; i++)
{
switch(i){
case 0: titles[i] = new JLabel("Transaction #"); break;
case 1: titles[i] = new JLabel("Company Name"); break;
case 2: titles[i] = new JLabel("Type"); break;
case 3: titles[i] = new JLabel("Quantity"); break;
case 4: titles[i] = new JLabel("Unit Price"); break;
case 5: titles[i] = new JLabel("Total"); break;
}
titlesPanel.add(titles[i]);
}
/** for(int k = 0; k < testInvestor.length; k++){
if(testInvestor[k] == true)
{
investorLabels[investorCounter] = new JLabel(InvestorNames[k]);
System.out.println(InvestorNames[k]);
actInv[investorCounter] = k;
investorCounter++;
}
}
*/
for(int a = 0; a < 5; ++a)
{
if(selectionPanel.companiesBoolean[InvestorNumber][a]==true)
{
actComp[companyCounter]=a;
companyName[companyCounter] = new JLabel(CompanyNames[a]);
compPanel.add(companyName[companyCounter]);
++companyCounter;
}
}
for(int a = 1; a<=companyCounter;++a)
{
numbersPanel.add(new JLabel(Integer.toString(a)));
}
JPanel[] botones = new JPanel[3];
for(int a = 0; a < companyCounter; ++a)
{
buyType[a] = new JRadioButton("B", true);
sellType[a] = new JRadioButton("S", false);
ButtonGroup type = new ButtonGroup();
// group[a].add(buyType[a]);
// group[a].add(sellType[a]);
botones[a] = new JPanel(new GridLayout(1,2));
type.add(buyType[a]);
type.add(sellType[a]);
if(a == 0)
{
sellType[a].addActionListener(new RadioButtonListener1());
buyType[a].addActionListener(new RadioButtonListener1());
}
if(a == 1)
{
sellType[a].addActionListener(new RadioButtonListener2());
buyType[a].addActionListener(new RadioButtonListener2());
}
if(a == 2)
{
sellType[a].addActionListener(new RadioButtonListener3());
buyType[a].addActionListener(new RadioButtonListener3());
}
botones[a].add(buyType[a]);
botones[a].add(sellType[a]);
buttonPanel.add(botones[a]);
quantity[a] = new JTextField(10);
qtyPanel.add(quantity[a]);
unitPrice[a] = new JTextField(10);
pricePanel.add(unitPrice[a]);
totalPrice[a] = new JLabel("--");
totalPanel.add(totalPrice[a]);
quantity[a].addKeyListener(textListener);
unitPrice[a].addKeyListener(textListener);
}
panel.add(titlesPanel, BorderLayout.NORTH);
mainPanel.add(numbersPanel);
mainPanel.add(compPanel);
mainPanel.add(buttonPanel);
mainPanel.add(qtyPanel);
mainPanel.add(pricePanel);
mainPanel.add(totalPanel);
panel.add(mainPanel, BorderLayout.CENTER);
add(panel);
}
}
class NextButtonListener implements KeyListener
{
@Override
public void keyTyped(KeyEvent ke) {
}
@Override
public void keyPressed(KeyEvent ke) {
}
@Override
public void keyReleased(KeyEvent ke) {
for(int i=0; i<=2; i++)
{
Transactions transaction = new Transactions();
try
{
transaction.setQty(Integer.parseInt(transactionPanel.quantity[i].getText()));
transactionPanel.totalPrice[i].setText(Float.toString(transaction.getQty() * transaction.getPrice()));
System.out.println(Float.parseFloat(transactionPanel.unitPrice[i].getText()));
transaction.setPrice(Float.parseFloat(transactionPanel.unitPrice[i].getText()));
transactionPanel.totalPrice[i].setText(Float.toString(transaction.getQty() * transaction.getPrice()));
}
catch(NumberFormatException e)
{
transactionPanel.totalPrice[i].setText("--");
}
}
}
}
class RadioButtonListener1 implements ActionListener{
public void actionPerformed(ActionEvent e) {
JRadioButton btn = (JRadioButton) e.getSource();
if(btn.getText() == "B")
{
transactionPanel.isSelling[0] = false;
}
else
transactionPanel.isSelling[0] = true;
}
}
class RadioButtonListener2 implements ActionListener{
public void actionPerformed(ActionEvent e) {
JRadioButton btn = (JRadioButton) e.getSource();
if(btn.getText() == "B")
{
transactionPanel.isSelling[1] = false;
}
else
transactionPanel.isSelling[1] = true;
}
}
class RadioButtonListener3 implements ActionListener{
public void actionPerformed(ActionEvent e) {
JRadioButton btn = (JRadioButton) e.getSource();
if(btn.getText() == "B")
{
transactionPanel.isSelling[2] = false;
}
else
transactionPanel.isSelling[2] = true;
}
}
|
/*
* 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 DTO;
/**
*
* @author ThinkPro
*/
public class dto_LichSuKH {
int MaLop;
String TenLop;
String TenCT;
String NgBD;
String NgKT;
int diemNghe;
int diemNoi;
int diemDoc;
int diemViet;
float diemTB;
String TrangThai;
public dto_LichSuKH(int MaLop, String TenLop, String TenCT, String NgBD, String NgKT, int diemNghe, int diemNoi, int diemDoc, int diemViet, float diemTB, String TrangThai) {
this.MaLop = MaLop;
this.TenLop = TenLop;
this.TenCT = TenCT;
this.NgBD = NgBD;
this.NgKT = NgKT;
this.diemNghe = diemNghe;
this.diemNoi = diemNoi;
this.diemDoc = diemDoc;
this.diemViet = diemViet;
this.diemTB = diemTB;
this.TrangThai = TrangThai;
}
public dto_LichSuKH() {
}
public int getMaLop() {
return MaLop;
}
public void setMaLop(int MaLop) {
this.MaLop = MaLop;
}
public String getTenLop() {
return TenLop;
}
public void setTenLop(String TenLop) {
this.TenLop = TenLop;
}
public String getTenCT() {
return TenCT;
}
public void setTenCT(String TenCT) {
this.TenCT = TenCT;
}
public String getNgBD() {
return NgBD;
}
public void setNgBD(String NgBD) {
this.NgBD = NgBD;
}
public String getNgKT() {
return NgKT;
}
public void setNgKT(String NgKT) {
this.NgKT = NgKT;
}
public int getDiemNghe() {
return diemNghe;
}
public void setDiemNghe(int diemNghe) {
this.diemNghe = diemNghe;
}
public int getDiemNoi() {
return diemNoi;
}
public void setDiemNoi(int diemNoi) {
this.diemNoi = diemNoi;
}
public int getDiemDoc() {
return diemDoc;
}
public void setDiemDoc(int diemDoc) {
this.diemDoc = diemDoc;
}
public int getDiemViet() {
return diemViet;
}
public void setDiemViet(int diemViet) {
this.diemViet = diemViet;
}
public float getDiemTB() {
return diemTB;
}
public void setDiemTB(float diemTB) {
this.diemTB = diemTB;
}
public String getTrangThai() {
return TrangThai;
}
public void setTrangThai(String TrangThai) {
this.TrangThai = TrangThai;
}
}
|
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
int N, a[], prev, next, curr, peaks = 0;
for (int i = 0; i < T; i++) {
peaks = 0;
N = sc.nextInt();
a = new int[N];
for (int j = 0; j < N; j++) {
a[j] = sc.nextInt();
}
for (int j = 1; j < N - 1; j++) {
prev = a[j - 1];
curr = a[j];
next = a[j + 1];
if (prev < curr && curr > next) {
peaks += 1;
}
}
System.out.println("Case #" + (i + 1) + ": " + peaks);
}
}
}
|
package org.corbin.common.base.constant;
/**
* 预设值
*/
public interface EntityPreset {
/**
* 性别
*/
enum Sex {
man("男", Preset.MAN),
woman("女", Preset.WOMEN),
secret("保密", Preset.UN_SEX);
String sex;
Integer sexEncoding;
Sex(String sex, Integer sexEncoding) {
this.sex = sex;
this.sexEncoding = sexEncoding;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getSexEncoding() {
return sexEncoding;
}
public void setSexEncoding(Integer sexEncoding) {
this.sexEncoding = sexEncoding;
}
}
/**
* 歌曲类型
*/
enum SongType {
other("其他", Preset.OTHER),
classic("古典", Preset.CLASSICAL),
rock("摇滚", Preset.ROCK_AND_ROLL),
pop("流行", Preset.POP),
chinese("华语", Preset.CHINESE),
folk("民谣", Preset.FOLK),
euorpe("欧美", Preset.EUROPE);
String songType;
Integer songTypeEncoding;
SongType(String songType, Integer songTypeEncoding) {
this.songTypeEncoding = songTypeEncoding;
this.songType = songType;
}
public String getSongType() {
return songType;
}
public void setSongType(String songType) {
this.songType = songType;
}
public Integer getSongTypeEncoding() {
return songTypeEncoding;
}
public void setSongTypeEncoding(Integer songTypeEncoding) {
this.songTypeEncoding = songTypeEncoding;
}
}
/**
* 歌手类型
*/
enum SingerType {
other("其他", Preset.OTHER),
classic("古典", Preset.CLASSICAL),
rock("摇滚", Preset.ROCK_AND_ROLL),
pop("流行", Preset.POP),
chinese("华语", Preset.CHINESE),
folk("民谣", Preset.FOLK),
euorpe("欧美", Preset.EUROPE);
String singerType;
Integer singerTypeEncoding;
SingerType(String singerType, Integer singerTypeEncoding) {
this.singerType = singerType;
this.singerTypeEncoding = singerTypeEncoding;
}
public String getSingerType() {
return singerType;
}
public void setSingerType(String singerType) {
this.singerType = singerType;
}
public Integer getSingerTypeEncoding() {
return singerTypeEncoding;
}
public void setSingerTypeEncoding(Integer singerTypeEncoding) {
this.singerTypeEncoding = singerTypeEncoding;
}
}
/**
* 收藏类型
*/
enum CollectType {
other("其他", Preset.OTHER),
song("歌曲", Preset.SONG),
singer("歌手", Preset.SINGER),
song_order("歌单", Preset.SONG_ORDER),
mv("MV",Preset.MV);
String collectType;
Integer collectTypeEncoding;
CollectType(String collectType, Integer collectTypeEncoding) {
this.collectType = collectType;
this.collectTypeEncoding = collectTypeEncoding;
}
public String getCollectType() {
return collectType;
}
public void setCollectType(String collectType) {
this.collectType = collectType;
}
public Integer getCollectTypeEncoding() {
return collectTypeEncoding;
}
public void setCollectTypeEncoding(Integer collectTypeEncoding) {
this.collectTypeEncoding = collectTypeEncoding;
}
}
interface Preset {
Integer MAN = 1;
Integer WOMEN = 2;
Integer UN_SEX = 0;
/**
* 歌曲、歌手类型 0.其他 1 .古典、2.摇滚、3流行、4华语、5民谣、6欧美
*/
Integer OTHER = 0;
Integer CLASSICAL = 1;
Integer ROCK_AND_ROLL = 2;
Integer POP = 3;
Integer CHINESE = 4;
Integer FOLK = 5;
Integer EUROPE = 6;
/**
* 收藏内容类型 0 其他 1歌曲 2 歌手 3 歌单 4 mv
*/
Integer SONG = 1;
Integer SINGER = 2;
Integer SONG_ORDER = 3;
Integer MV = 4;
}
}
|
package br.usp.memoriavirtual.utils;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import br.usp.memoriavirtual.modelo.fachadas.ModeloException;
public class MVModeloEmailParser {
public MVModeloEmailParser() {
}
public String getMensagem(Map<String, String> tags,
MVModeloEmailTemplates template) throws ModeloException {
try {
ServletContext ctx = (ServletContext) FacesContext.getCurrentInstance()
.getExternalContext().getContext();
String deploymentDirectoryPath = ctx.getRealPath("/");
String path = deploymentDirectoryPath+"WEB-INF/classes/br/usp/memoriavirtual/utils/emailtemplates/"+template.toString();
String email = lerArquivo(path,
Charset.defaultCharset());
Iterator<Entry<String, String>> it = tags.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> par = (Map.Entry<String, String>) it
.next();
email = email.replace(par.getKey(), par.getValue());
}
return email;
} catch (Exception e) {
throw new ModeloException(e);
}
}
static String lerArquivo(String caminho, Charset encoding)
throws IOException {
byte[] encoded = Files.readAllBytes(Paths.get(new File(caminho)
.getAbsolutePath()));
return new String(encoded, encoding);
}
}
|
package jmda.app.xstaffr.common.domain.extended;
enum SearchRequestState
{
/** {@link SearchRequest} received from {@link Requester} by external staffing */
OPEN,
/** {@link SearchRequest} solved successfully */
CLOSED_SOLVED,
/** {@link SearchRequest} closed without success */
CLOSED_UNSOLVED;
}
|
package org.libreoffice;
import android.content.Context;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import org.json.JSONException;
import org.json.JSONObject;
public class SearchController/* implements View.OnClickListener*/ {
// private LibreOfficeMainActivity mActivity;
private Context mContext;
private enum SearchDriection {
UP, DOWN
};
// public SearchController(LibreOfficeMainActivity activity) {
// mActivity = activity;
//
// ((ImageButton) activity.findViewById(R.id.button_search_up)).setOnClickListener(this);
// ((ImageButton) activity.findViewById(R.id.button_search_down)).setOnClickListener(this);
// }
public SearchController(Context context){
mContext = context;
}
private void search(String searchString, SearchDriection direction, float x, float y) {
try {
JSONObject rootJson = new JSONObject();
addProperty(rootJson, "SearchItem.SearchString", "string", searchString);
addProperty(rootJson, "SearchItem.Backward", "boolean", direction == SearchDriection.DOWN ? "true" : "false");
addProperty(rootJson, "SearchItem.SearchStartPointX", "long", String.valueOf((long) UnitConverter.pixelToTwip(x, LOKitShell.getDpi())));
addProperty(rootJson, "SearchItem.SearchStartPointY", "long", String.valueOf((long) UnitConverter.pixelToTwip(y, LOKitShell.getDpi())));
addProperty(rootJson, "SearchItem.Command", "long", String.valueOf(0)); // search all == 1
LOKitShell.sendEvent(new LOEvent(LOEvent.UNO_COMMAND, ".uno:ExecuteSearch", rootJson.toString()));
} catch (JSONException e) {
e.printStackTrace();
}
}
private void addProperty(JSONObject json, String parentValue, String type, String value) throws JSONException {
JSONObject child = new JSONObject();
child.put("type", type);
child.put("value", value);
json.put(parentValue, child);
}
// @Override
// public void onClick(View view) {
// ImageButton button = (ImageButton) view;
//
// SearchDriection direction = SearchDriection.DOWN;
// switch(button.getId()) {
// case R.id.button_search_down:
// direction = SearchDriection.DOWN;
// break;
// case R.id.button_search_up:
// direction = SearchDriection.UP;
// break;
// default:
// break;
// }
//
// String searchText = ((EditText) mActivity.findViewById(R.id.search_string)).getText().toString();
//
// float x = mActivity.getCurrentCursorPosition().centerX();
// float y = mActivity.getCurrentCursorPosition().centerY();
// search(searchText, direction, x, y);
// }
}
|
package com.mc.mimo.moviechallenge.api;
import com.mc.mimo.moviechallenge.pojo.moviedetails.Movie;
import com.mc.mimo.moviechallenge.pojo.movielist.MovieList;
import com.mc.mimo.moviechallenge.pojo.search.Search;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;
public interface APIInterface {
@GET("movie/now_playing?")
Call<MovieList> doGetNowPlaingList(@Query("page") String page, @Query("language") String lang);
@GET("movie/popular?")
Call<MovieList> doGetPopularList(@Query("page") String page, @Query("language") String lang);
@GET("movie/top_rated?")
Call<MovieList> doGetTopRatedList(@Query("page") String page, @Query("language") String lang);
@GET("movie/{movie_id}?")
Call<Movie> doGetMovieDetails(@Path("movie_id") int movie_id, @Query("language") String lang);
@GET("search/movie?")
Call<Search> doSearch(@Query("query") String query);
}
|
package com.atn.app.webservices;
public interface AtnVenueShareWebserviceListener
{
public void onSuccess(String message);
public void onFailed(int errorCode, String errorMessage);
}
|
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.kryonet.Listener;
import com.esotericsoftware.kryonet.Server;
import java.io.IOException;
public class LoggerServer extends Listener {
private static Logger logger = LoggerFactory.getLogger(LoggerServer.class);
private static Server server;
private static int tcpPort = 80, udpPort = 80;
public static void main(String[] args) {
logger.debug("starting server");
server = new Server();
server.getKryo().register(Integer.class);
try {
server.bind(tcpPort, udpPort);
} catch (IOException e) {
e.printStackTrace();
}
server.start();
server.addListener(new LoggerServer());
}
public void connected(Connection c) {
logger.debug("new connection from {}", c.getRemoteAddressTCP().getHostName());
}
public void received(Connection c, Object p) {
logger.debug("get some data:");
if ((p instanceof Integer) & (p != null)) {
Integer receivedInteger = (Integer) p;
logger.debug(String.valueOf(receivedInteger));
}
}
/**public void disconnected(Connection c) {
logger.debug("disconnected: {}", c.getRemoteAddressTCP().getHostName());
}**/
}
|
package com.example.ted.geetestdemo;
import android.os.Handler;
import android.os.Message;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class CheckRunnable implements Runnable {
private String phone;
private String challenge;
private Handler handler;
public CheckRunnable(Handler handler, String phone, String challenge) {
this.handler = handler;
this.phone = phone;
this.challenge = challenge;
}
@Override
public void run() {
Map<String, Object> map = new HashMap<>(8);
map.put("phone", phone);
map.put("challenge", challenge);
String verifyParams = GHttpUtils.postHttpOfMap("http://www.geetest.com/demo/gt/verify", map);
try {
JSONObject jsonObject = new JSONObject(verifyParams);
if ("success".equals(jsonObject.getString("status"))) {
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
} else {
Message message = new Message();
message.what = 2;
handler.sendMessage(message);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
|
package org.meizhuo.rpc.zksupport.LoadBalance;
import io.netty.channel.ChannelHandlerContext;
import org.apache.zookeeper.ZooKeeper;
import org.meizhuo.rpc.Exception.ProvidersNoFoundException;
import org.meizhuo.rpc.zksupport.service.ZnodeType;
import java.util.List;
/**
* Created by wephone on 18-1-8.
* 负载均衡策略抽象接口
* 其他模块不耦合负载均衡代码
*/
public interface LoadBalance {
//平衡连接消费者端的所有服务 仅在启动时使用
void balanceAll(ZooKeeper zooKeeper);
/**
* 负载均衡的连接平衡操作
* @param serviceName
*/
void balance(ZooKeeper zooKeeper, String serviceName, List<String> znodes, ZnodeType type);
/**
* 负载均衡选择服务中已选中的IP之一
* @param serviceName
* @return
*/
String chooseIP(String serviceName) throws ProvidersNoFoundException;
}
|
/*
Author: <<author name redacted >>
Title: ProgrammingAssignment 2
Purpose: The purpose of this assignment is to create a counter in which counts all operations, declarations and branches
in order for Sortable() to sort the given Table.
*/
public class TableSorter {
public static int operationCount = 0; //variable to count number of operations needed to sort.
/*/
Input: Table
Output: boolean
Functionality: Returns true if who table is sorted, else, it returns false.
*/
public boolean isSorted(Table t){
return isColSorted(t) && isRowSorted(t);
}
/*
Input: Table
Output: boolean
Functionality: Checks if all the columns are sorted.
*/
private boolean isColSorted(Table t) {
int range = t.getSize();
for(int c=0; c<range; c++){
for(int r=0; r<range-1; r++){
int currentValue = t.getTableValue(r,c);
int nextValue = t.getTableValue(r+1, c);
if(currentValue > nextValue){
return false;
}
}
}
return true;
}
/*
Input: Table
Output: Boolean
Functionality: Checks if all the rows are sorted.
*/
public boolean isRowSorted(Table t){
int range = t.getSize();
for(int r=0; r<range; r++){
for(int c=0; c<range-1; c++){
int currentValue = t.getTableValue(r,c);
int nextValue = t.getTableValue(r, c+1);
if(currentValue > nextValue){
return false;
}
}
}
return true;
}
/*
Input: Table
Output: None
Functionality: Takes care of sorting the table row-wise and column-wise
*/
public static void sortable(Table t){
operationCount++; //function called +1
sortRow(t);
operationCount++; //function call to 'sortRow'
//after having each row sorted, sort each column.
sortCol(t);
operationCount++; //function call to 'sortCol'
}
/*
Input: Table
Output: None
Functionality: Sorts all the columns in the Table
*/
public static void sortCol(Table t){
int range = t.getSize();
operationCount+= 2; //variable declaration and function call
operationCount+=2; //declaration for variable 'c' in for loop and compare
for(int c=0; c<range; c++){ //loop needed to traverse column
operationCount+=2; //declaration for variable 'r' for upcoming for loop and compare, loop
for(int r=0; r<range; r++){ //loop needed to traverse row
operationCount+=2; //declaration for variable 'i' and compare in loop
for(int i=0; i<range-r-1; i++){ //loop needed to check elements which were swapped previously.
int currentVal = t.getTableValue(i, c);
int nextVal = t.getTableValue(i+1,c);
operationCount+=4; //declaration of variables 'currentVal' and 'nextVal' and 2 function calls, one for each variable
operationCount++; //comparison for currentVal and nextVal
if (currentVal > nextVal){
//perform swap
t.setTableValue(i, c,nextVal);
t.setTableValue(i+1, c, currentVal);
operationCount+=2; //setting values for table calling functions
}
operationCount++; //branch when condition above is false
operationCount+=3; //for loop increment, a branch and a compare in the loop
} operationCount++; //for branch when loop compare fails
operationCount+=3; //for loop increment, a branch and a compare in the loop
} operationCount++; //for branch when loop compare fails
operationCount+=3; //for loop increment, a branch and a compare in the loop
} operationCount++; //for branch when loop compare fails
}
/*
Input: Table
Output: None
Functionality: Sorts all the rows in the Table.
*/
public static void sortRow(Table t){
int range = t.getSize();
operationCount+= 2; //variable declaration and function call
operationCount+=2; //declaration for variable 'r' in for loop and compare
for(int r=0; r<range; r++){ //loop needed to traverse row
operationCount+=2; //declaration for variable 'c' for upcoming for loop and compare
for(int c=0; c<range; c++){ //loop needed to traverse column
operationCount+=2; //declaration for variable 'i' for upcoming for loop and compare
for(int i=0; i<range-c-1; i++){ //loop needed to check elements that were swapped previously.
int currentVal = t.getTableValue(r, i);
int nextVal = t.getTableValue(r,i+1);
operationCount+=4; //declaration of variables 'currentVal' and 'nextVal' and two function calls
operationCount++; //comparison for currentVal and nextVal
if (currentVal > nextVal){
//perform swap
t.setTableValue(r, i,nextVal);
t.setTableValue(r, i+1, currentVal);
operationCount+=2; //setting values for table
}
operationCount++; //branch when condition above is false
operationCount+=3; //for loop increment, a branch and a compare in the loop
} operationCount++; //for branch when loop compare fails
operationCount+=3; //for loop increment, a branch and a compare in the loop
}operationCount++; //for branch when loop compare fails
operationCount+=3; //for loop increment, a branch and a compare in the loop
} operationCount++; //for branch when loop compare fails
}
//main method with 1 FILE TEST CASE and 6 INITIALIZED TEST CASES
public static void main(String[] args) throws Exception {
int [] values0 = new int[]{4,-1,2,0};
int [] values1 = new int[]{5,1,8,3,2,1,5,7,3,6,2,1,-1,-1,5,9};
int [] values2 = new int[]{-5,-1,-8,-3,-2,-1,-5,-7,-3,-6,-2,-1,-1,-1,-5,-9,-3,-5,-6,-10,-2,-1,0,-76,-4};
int [] values3 = new int[]{5,1,8,3,2,1,5,7,3,6,2,1,-1,-1,5,9,3,5,6,10,-2,-1,0,-76,4,-10,0,2,99,100000,2147483647,-2147483648,-10000,-555, 1234,55};
int [] values4 = new int[]{0,0,0,-1,-1,-1,-2,0,-1};
int [] values5 = new int[]{0,1,2,3,4,5,6,7,8};
int [] TESTCASES [] = {values0, values1, values2, values3, values4, values5};
//test case for file
Table t1 = Table.GetTable("input");
String stringTable = t1.toString();
System.out.println("---------------File Test Case----------------");
System.out.println(stringTable);
System.out.println("THIS TABLE IS SORTED: " + new TableSorter().isSorted(t1));
sortable(t1);
String stringT = t1.toString();
System.out.println(stringT);
System.out.println("THIS TABLE IS SORTED: " + new TableSorter().isSorted(t1));
System.out.println("NUMBER OF OPERATIONS TO SORT TABLE: " + operationCount);
//Loop used to test cases for initialized array of values.
for(int i=0; i<TESTCASES.length; i++){
Table t = new Table(TESTCASES[i].length, TESTCASES[i]);
System.out.println("---------------TEST CASE #" + i + " ------------------");
String stringT1 = t.toString();
System.out.print(stringT1);
System.out.println("THE TABLE ABOVE IS SORTED: " + new TableSorter().isSorted(t));
sortable(t);
System.out.println("----------------SORTED TEST CASE #" + i + " -------------------");
String stringTable1 = t.toString();
System.out.print(stringTable1);
System.out.println("THE TABLE ABOVE IS SORTED: " + new TableSorter().isSorted(t));
System.out.println("NUMBER OF OPERATIONS TO SORT TABLE: " + operationCount);
}
}
}
|
package com.example.firstapp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;
public class ashwajeet extends YouTubeBaseActivity {
YouTubePlayerView youTubePlayerView;
Button b4;
YouTubePlayer.OnInitializedListener onInitializedListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ashwajeet);
Intent inte=getIntent();
final String text=inte.getStringExtra(Main2Activity.Extra_Text);
b4=(Button)findViewById(R.id.button4);
youTubePlayerView=(YouTubePlayerView)findViewById(R.id.ytp);
onInitializedListener=new YouTubePlayer.OnInitializedListener() {
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
youTubePlayer.loadVideo(text);
youTubePlayer.play();
}
@Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
};
b4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
youTubePlayerView.initialize(PlayerConfig.API_KEY,onInitializedListener);
b4.setVisibility(view.GONE);
}
});
}
}
|
/*
* 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 entities;
import entities.query.FlexQuerySpecification;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author Florian
*/
@Entity
@XmlRootElement
@NamedQueries({
@NamedQuery(name="Project.ActivateMany", query="UPDATE Project p SET p.active = :active WHERE p.id IN(:projectIds)")
})
public class Project extends entities.Entity {
private static final long serialVersionUID = 1L;
public static final FlexQuerySpecification<Project> PROJECTLIST_FOR_USER;
public static final FlexQuerySpecification<Project> PROJECTLIST_FOR_ADMIN;
public static final FlexQuerySpecification<Project> LIST_FOR_RIGHTS;
static {
// attention à conserver un espace lors des retours à la ligne dans l'écriture des requêtes...
PROJECTLIST_FOR_USER = new FlexQuerySpecification<>("SELECT p FROM Project p INNER JOIN p.projectRights pr "
+ "WHERE p.active = true AND pr.user.id = :userId AND pr.project.id = p.id "
+ "AND MOD(pr.rights/:right, 2) >= 1 :where: ORDER BY p.name ASC", "p", Project.class);
PROJECTLIST_FOR_USER.addWhereSpec("name", "projectName", "LIKE", "AND", String.class);
PROJECTLIST_FOR_ADMIN = new FlexQuerySpecification<>("SELECT p FROM Project p :where: :orderby:", "p", Project.class);
PROJECTLIST_FOR_ADMIN.addWhereSpec("name", "projectName", "LIKE", "AND", String.class);
PROJECTLIST_FOR_ADMIN.addWhereSpec("active", "projectActive", "=", "AND", boolean.class);
PROJECTLIST_FOR_ADMIN.addOrderBySpec("name");
PROJECTLIST_FOR_ADMIN.addOrderBySpec("active");
PROJECTLIST_FOR_ADMIN.addDefaultOrderByClause("name", "ASC");
LIST_FOR_RIGHTS = new FlexQuerySpecification<>("SELECT p FROM Project p :where: :orderby:", "p", Project.class);
LIST_FOR_RIGHTS.addWhereSpec("name", "projectName", "LIKE", "AND", String.class);
LIST_FOR_RIGHTS.addOrderBySpec("name");
LIST_FOR_RIGHTS.addOrderBySpec("active");
}
@NotNull
private String name;
private boolean active = true;
@OneToMany(mappedBy="project", fetch=FetchType.LAZY)
private List<File> files = new ArrayList<>();
@OneToMany(mappedBy="project", fetch=FetchType.LAZY)
private List<ProjectRight> projectRights = new ArrayList<>();
@OneToMany(mappedBy="project", fetch=FetchType.LAZY)
private List<WorkflowCheck> workflowChecks = new ArrayList<>();
@OneToMany(mappedBy = "project", fetch=FetchType.LAZY)
private List<Log> logs = new ArrayList<>();
public Project() {}
public Project(Long id) {
super(id);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
@XmlTransient
public List<File> getFiles() {
return files;
}
public void setFiles(List<File> files) {
this.files = files;
}
@XmlTransient
public List<ProjectRight> getProjectRights() {
return projectRights;
}
public void setProjectRights(List<ProjectRight> projectRights) {
this.projectRights = projectRights;
}
@XmlTransient
public List<WorkflowCheck> getWorkflowChecks() {
return workflowChecks;
}
public void setWorkflowChecks(List<WorkflowCheck> workflowChecks) {
this.workflowChecks = workflowChecks;
}
@XmlTransient
public List<Log> getLogs() {
return logs;
}
public void setLogs(List<Log> logs) {
this.logs = logs;
}
@Override
public String toString() {
return "entities.Project[ id=" + getId() + " ]";
}
}
|
package com.mahadihasan.mc.patient;
import java.util.Date;
/**
*
* @author MAHADI HASAN NAHID
*/
public class Patient {
//---------------Fields--------
private String id;
private String name;
private String bloodGroup;
private String sex;
private String height;
private String email;
private String mobileNo;
private String weight;
private String age;
private String dateOfBirth;
//---------------------
public Patient(String id, String name, String age, String sex,
String bloodGrp,String height, String weight, String dateOfBirth,
String mob, String email) {
setID(id);
setName(name);
setAge(age);
setSex(sex);
setBloodGroup(bloodGrp);
setHeight(height);
setWeight(weight);
setdateOfBirth(dateOfBirth);
setMobileNo(mob);
setEmail(email);
}
private void setID(String id) {
this.id = id;
}
public String getID() {
return id;
}
private String calcuateAge(Date dateOfBirth) {
return null;
}
private void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
private void setAge(String age) {
this.age = age;
}
public String getAge() {
return age;
}
private void setSex(String sex) {
this.sex = sex;
}
public String getSex() {
return sex;
}
private void setHeight(String height) {
this.height = height;
}
public String getHeight() {
return height;
}
private void setWeight(String weight) {
this.weight = weight;
}
public String getWeight() {
return weight;
}
private void setdateOfBirth(String dOfBirth) {
dateOfBirth = dOfBirth;
}
public String getDateOfBirth() {
return dateOfBirth;
}
private void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
private void setBloodGroup(String bloodGrp) {
bloodGroup = bloodGrp;
}
public String getBloodGroup() {
return bloodGroup;
}
private void setMobileNo(String mob) {
mobileNo = mob;
}
public String getMobileNo() {
return mobileNo;
}
}
|
package lildoop.mapReduce.service;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import org.json.JSONObject;
import lildoop.mapReduce.enums.Function;
import lildoop.mapReduce.models.Query;
import lildoop.mapReduce.models.QueryResult;
public class Dispatcher {
private Query currentQuery;
// private BufferedReader fileStream;
private String[] fileData;
private int numSetsSent;
private int numSetsReceived;
private int currentIndex;
private String[] columns;
private QueryResult totalResult;
// private FileClient fileClient;
public Dispatcher(Query query) {
this.currentQuery = query;
// this.fileStream = null;
this.numSetsSent = 0;
this.numSetsReceived = 0;
// this.fileClient = fileClient;
this.currentIndex = 0;
this.columns = null;
this.totalResult = null;
readFile();
}
private void readFile() {
String file = null;
// try {
// file = fileClient.retrieveFile(currentQuery.getFileName());
// } catch (MalformedURLException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// }
String dataDirectory = "C:/Lildoop/map_reduce_data/";
file = convertFileToString(dataDirectory + currentQuery.getFileName() + ".txt");
this.fileData = file.split("\n");
columns = fileData[currentIndex++].split(",");
}
public String convertFileToString(String filePath) {
StringBuilder file = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new FileReader(new File(filePath)))) {
String line = null;
while((line = reader.readLine()) != null) {
file.append(line);
file.append("\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return file.substring(0, file.length() - 2);
}
public JSONObject[] getNextWorkSet() {
int amount = 20;
int count = 0;
int endIndex = currentIndex + amount;
if (endIndex >= fileData.length) {
endIndex = fileData.length;
}
JSONObject[] workData = new JSONObject[endIndex - currentIndex];
for (int i = currentIndex; i < endIndex; i++) {
String[] data = fileData[i].split(",");
JSONObject row = new JSONObject();
for (int j = 0; j < columns.length; j++) {
String column = columns[j];
String val = data[j];
row.put(column, val);
}
workData[count++] = row;
}
currentIndex = endIndex;
numSetsSent++;
return workData;
}
public boolean isProccessing() {
return (currentIndex < fileData.length) || (numSetsReceived < numSetsSent);
}
public String getResults() {
return totalResult.getJSON();
}
public String getWorkJson(JSONObject[] rows) {
return currentQuery.getWorkJson(rows);
}
public void addResults(JSONObject resultJson) {
if (totalResult == null) {
totalResult = new QueryResult(resultJson);
} else {
QueryResult result = new QueryResult(resultJson);
aggregateResults(result);
}
numSetsReceived++;
}
private void aggregateResults(QueryResult result) {
int resultVal = result.getValue();
int totVal = totalResult.getValue();
Function func = result.getFunction();
switch (func) {
case COUNT:
totVal += resultVal;
break;
case SUM:
totVal += resultVal;
break;
case AVG:
totVal += resultVal;
totVal /= 2;
break;
default:
throw new IllegalStateException("Specified function is not valid.");
}
totalResult.updateValue(totVal);
}
}
|
package VSMSerialization;
import java.io.Serializable;
import no.uib.cipr.matrix.DenseVector;
public class VSMWordEmbeddingSem implements Serializable {
/**
*
*/
private static final long serialVersionUID = 2172651922100576452L;
private DenseVector wordEmbeddingSem;
public DenseVector getWordEmbeddingSem() {
return wordEmbeddingSem;
}
public void setWordEmbeddingSem(DenseVector wordEmbeddingSem) {
this.wordEmbeddingSem = wordEmbeddingSem;
}
}
|
package com.pzc.app.photoweb.mapper;
import com.pzc.app.photoweb.model.Photo;
import java.util.List;
/**
* @author pengzc
* @deprecated 相册接口
*
*/
public interface PhotoMapper {
/**
* 查询所有相册
* @return
*/
List<Photo> selectAll();
void addPhoto(Photo photo);
}
|
package pe.gob.sunarp.controller;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import pe.gob.sunarp.adm.service.EMPLEADOService;
@WebServlet({ "/EMPLEADOController", "/getUsuarios", "/editEmpleado","/editEmpleado_post","/getEmpleadosByTagsAJAX",
"/createEmpleado"})
public class EMPLEADOController extends HttpServlet {
private static final long serialVersionUID = 1L;
/*
* protected void doGet(HttpServletRequest request, HttpServletResponse
* response) throws ServletException, IOException {
* request.setAttribute("message", "hello"); RequestDispatcher
* view=request.getRequestDispatcher("EMPLEADO/ListEmpleados.jsp");
* view.forward(request,response); }
*/
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String path = request.getServletPath();
switch (path) {
case "/getUsuarios":
getEmpleadosByTags(request, response);
break;
case "/getEmpleadosByTagsAJAX":
getEmpleadosByTagsAJAX(request, response);
break;
case "/editEmpleado":
editEmpleado(request, response);
break;
case "/editEmpleado_post":
editEmpleado_post(request, response);
break;
case "/createEmpleado":
createEmpleado(request, response);
break;
}
}
private void createEmpleado(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Datos
String CO_AREA = request.getParameter("CO_AREA");
String CO_CARGO = request.getParameter("CO_CARGO");
String EST_EMPL = request.getParameter("EST_EMPL");
String APE_PAT = request.getParameter("APE_PAT");
String APE_MAT = request.getParameter("APE_MAT");
String NOMBRE = request.getParameter("NOMBRE");
// Proceso
EMPLEADOService service = new EMPLEADOService();
service.createEmpleado(CO_AREA, CO_CARGO, EST_EMPL, APE_PAT, APE_MAT, NOMBRE);
//Map<String, ?> EMPLEADO = service.getEmpleadoByID(CO_EMPL);
// Forward
//request.setAttribute("EMPLEADO", EMPLEADO);
//RequestDispatcher rd = request.getRequestDispatcher("Views/EMPLEADO/EditEmpleado.jsp");
//rd.forward(request, response);
RequestDispatcher rd;
if (service.getCode() == 1) {
rd = request.getRequestDispatcher("Views/EMPLEADO/ListEmpleados.jsp");
// rd1.forward(request, response);
} else {
request.setAttribute("mensaje", service.getMensaje());
rd = request.getRequestDispatcher("Views/EMPLEADO/CreateEmpleado.jsp");
}
rd.forward(request, response);
}
private void editEmpleado(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Datos
String CO_EMPL = request.getParameter("CO_EMPL");
// Proceso
EMPLEADOService service = new EMPLEADOService();
/* Buscamos */
Map<String, ?> EMPLEADO = service.getEmpleadoByID(CO_EMPL);
// Forward
request.setAttribute("EMPLEADO", EMPLEADO);
RequestDispatcher rd = request.getRequestDispatcher("Views/EMPLEADO/EditEmpleado.jsp");
rd.forward(request, response);
}
private void editEmpleado_post(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Datos
String CO_EMPL = request.getParameter("CO_EMPL");
String APE_PAT = request.getParameter("APE_PAT");
String APE_MAT = request.getParameter("APE_MAT");
String NOMBRE = request.getParameter("NOMBRE");
String CO_AREA = request.getParameter("CO_AREA");
String CO_CARGO = request.getParameter("CO_CARGO");
String EST_EMPL = request.getParameter("EST_EMPL");
// Proceso
EMPLEADOService service = new EMPLEADOService();
service.editEmpleadoData(CO_EMPL, APE_PAT, APE_MAT, NOMBRE,CO_AREA,CO_CARGO,EST_EMPL);
//Map<String, ?> EMPLEADO = service.getEmpleadoByID(CO_EMPL);
// Forward
//request.setAttribute("EMPLEADO", EMPLEADO);
//RequestDispatcher rd = request.getRequestDispatcher("Views/EMPLEADO/EditEmpleado.jsp");
//rd.forward(request, response);
RequestDispatcher rd;
if (service.getCode() == 1) {
rd = request.getRequestDispatcher("Views/EMPLEADO/ListEmpleados.jsp");
// rd1.forward(request, response);
} else {
request.setAttribute("mensaje", service.getMensaje());
rd = request.getRequestDispatcher("Views/EMPLEADO/EditEmpleado.jsp");
}
rd.forward(request, response);
}
private void getEmpleadosByTags(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Datos
// String cuenta = request.getParameter("cuenta");
String paterno = request.getParameter("txtPaterno");
String materno = request.getParameter("txtMaterno");
String nombre = request.getParameter("txtNombre");
// Proceso
EMPLEADOService service = new EMPLEADOService();
List<Map<String, ?>> lista = service.getEmpleadosByTags(paterno, materno, nombre);
System.err.println("CODE: " + service.getCode());
System.err.println("MENSAJE: " + service.getMensaje());
System.err.println("Cantidad de lista: " + lista.size());
// Forward
request.setAttribute("lista", lista);
RequestDispatcher rd = request.getRequestDispatcher("Views/EMPLEADO/ListEmpleados.jsp");
rd.forward(request, response);
}
private void getEmpleadosByTagsAJAX(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Datos
String paterno = request.getParameter("paterno");
String materno = request.getParameter("materno");
String nombre = request.getParameter("nombre");
// Proceso
EMPLEADOService service = new EMPLEADOService();
List<Map<String, ?>> lista = service.getEmpleadosByTags(paterno, materno, nombre);
System.err.println("CODE: " + service.getCode());
System.err.println("MENSAJE: " + service.getMensaje());
System.err.println("Cantidad de lista: " + lista.size());
// Forward
/*request.setAttribute("lista", lista);
RequestDispatcher rd = request.getRequestDispatcher("Views/EMPLEADO/ListEmpleados.jsp");
rd.forward(request, response);*/
// Crear cadena JSON
Gson gson = new Gson();
String cadenaJson = gson.toJson(lista);
// Respuesta
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(cadenaJson);
response.getWriter().flush();
System.err.println("cadenaJson de " + paterno + ": " + cadenaJson);
}
}
|
package Learn;
import java.sql.*;
public class JDBCExa {
public static void main(String[] args){
try {
Class c = Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/product",
"root", "1234");
con.setAutoCommit(false);
PreparedStatement ps = con.prepareStatement("update master set product_name = ?, price = 8230 Where product_no = 6;");
ps.addBatch("insert into master values(51,'Hello',20);");
ps.addBatch("insert into master values(52,'Hello',20);");
ps.executeBatch();
ps.setString(1,"Monitor");
//ps.setInt(2,590);
ps.executeUpdate();
Statement sm = con.createStatement();
ResultSet rss = sm.executeQuery("select * from master;");
while (rss.next()){
System.out.println(rss.getInt(1) + "\t" +rss.getString(2) + "\t" +
rss.getFloat(3) + "\t" );
}
con.close();
} catch ( ClassNotFoundException | SQLException s){
System.out.println(s);
}
}
}
|
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aot.test.generate.compile;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.tools.FileObject;
import javax.tools.ForwardingJavaFileManager;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.JavaFileObject.Kind;
import javax.tools.SimpleJavaFileObject;
import org.springframework.aot.test.generate.file.ClassFile;
import org.springframework.aot.test.generate.file.ClassFiles;
import org.springframework.util.ClassUtils;
/**
* {@link JavaFileManager} to create in-memory {@link DynamicClassFileObject
* ClassFileObjects} when compiling.
*
* @author Phillip Webb
* @author Andy Wilkinson
* @since 6.0
*/
class DynamicJavaFileManager extends ForwardingJavaFileManager<JavaFileManager> {
private final ClassFiles existingClasses;
private final ClassLoader classLoader;
private final Map<String, DynamicClassFileObject> compiledClasses = Collections.synchronizedMap(
new LinkedHashMap<>());
DynamicJavaFileManager(JavaFileManager fileManager, ClassLoader classLoader,
ClassFiles existingClasses) {
super(fileManager);
this.classLoader = classLoader;
this.existingClasses = existingClasses;
}
@Override
public ClassLoader getClassLoader(Location location) {
return this.classLoader;
}
@Override
public JavaFileObject getJavaFileForOutput(Location location, String className,
JavaFileObject.Kind kind, FileObject sibling) throws IOException {
if (kind == JavaFileObject.Kind.CLASS) {
return this.compiledClasses.computeIfAbsent(className,
DynamicClassFileObject::new);
}
return super.getJavaFileForOutput(location, className, kind, sibling);
}
@Override
public Iterable<JavaFileObject> list(Location location, String packageName,
Set<Kind> kinds, boolean recurse) throws IOException {
List<JavaFileObject> result = new ArrayList<>();
if (kinds.contains(Kind.CLASS)) {
for (ClassFile existingClass : this.existingClasses) {
String existingPackageName = ClassUtils.getPackageName(existingClass.getName());
if (existingPackageName.equals(packageName) || (recurse && existingPackageName.startsWith(packageName + "."))) {
result.add(new ClassFileJavaFileObject(existingClass));
}
}
}
Iterable<JavaFileObject> listed = super.list(location, packageName, kinds, recurse);
listed.forEach(result::add);
return result;
}
@Override
public String inferBinaryName(Location location, JavaFileObject file) {
if (file instanceof ClassFileJavaFileObject classFile) {
return classFile.getClassName();
}
return super.inferBinaryName(location, file);
}
ClassFiles getClassFiles() {
return this.existingClasses.and(this.compiledClasses.entrySet().stream().map(entry ->
ClassFile.of(entry.getKey(), entry.getValue().getBytes())).toList());
}
private static final class ClassFileJavaFileObject extends SimpleJavaFileObject {
private final ClassFile classFile;
private ClassFileJavaFileObject(ClassFile classFile) {
super(URI.create("class:///" + classFile.getName().replace('.', '/') + ".class"), Kind.CLASS);
this.classFile = classFile;
}
public String getClassName() {
return this.classFile.getName();
}
@Override
public InputStream openInputStream() {
return new ByteArrayInputStream(this.classFile.getContent());
}
}
}
|
package gdut.ff.domain;
import java.io.Serializable;
import java.util.Date;
/**
* 标签
* @author liuffei
* @date 2018-07-10
*
*/
public class Tag implements Serializable{
private static final long serialVersionUID = 1L;
//主键
private int id;
//标签的业务标识
private String tagId;
//标签名称
private String tagName;
//创建时间
private Date gmtCreate;
//修改时间
private Date gmtModified;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTagId() {
return tagId;
}
public void setTagId(String tagId) {
this.tagId = tagId;
}
public String getTagName() {
return tagName;
}
public void setTagName(String tagName) {
this.tagName = tagName;
}
public Date getGmtCreate() {
return gmtCreate;
}
public void setGmtCreate(Date gmtCreate) {
this.gmtCreate = gmtCreate;
}
public Date getGmtModified() {
return gmtModified;
}
public void setGmtModified(Date gmtModified) {
this.gmtModified = gmtModified;
}
@Override
public String toString() {
return "Tag [id=" + id + ", tagId=" + tagId + ", tagName=" + tagName + ", gmtCreate=" + gmtCreate
+ ", gmtModified=" + gmtModified + "]";
}
}
|
package Estudiante.View;
import java.util.Scanner;
import Etudiante.entity.Estudiante;
import General.InputTypesUniversidad;
public class RegistroEstudiante {
public static Estudiante ingresarEstudiante(Scanner scanner)
{
int codigoEstudiante=InputTypesUniversidad.readInt("Ingrese su codigo de estudiante:", scanner);
int codigoCuenta=InputTypesUniversidad.readInt("Ingrese el numero de cuenta:", scanner);
String Nombre=InputTypesUniversidad.readString("Nombre:", scanner);
String Apellido=InputTypesUniversidad.readString("Apellido: ", scanner);
int CI=InputTypesUniversidad.readInt("Carnet de Identidad:", scanner);
int fechaNacimiento=InputTypesUniversidad.readInt("Fecha de nacimiento:", scanner);
int telefono=InputTypesUniversidad.readInt("Telefono:", scanner);
String Direccion=InputTypesUniversidad.readString("Direccion:", scanner);
boolean PAA=InputTypesUniversidad.readBoolean("Dio la Prueba de Aptitud Academica? true(si)/false(no)", scanner);
int IdClase=InputTypesUniversidad.readInt("Codigo de la clase:", scanner);
return new Estudiante(codigoEstudiante,codigoCuenta, Nombre,Apellido, fechaNacimiento, telefono, Direccion, PAA, CI, IdClase);
}
}
|
package gitPackage;
public class GitDay2 {
public static void main(String[] args) {
System.out.println(" Future is soon and perfect");
System.out.println(" Hello git users");
System.out.println("Check if your local is ahead of origine master");
System.out.println(" Commit 7");
}
}
|
package com.goldgov.gtiles.core.module;
import java.io.Serializable;
import java.util.LinkedHashMap;
import org.springframework.util.Assert;
import com.goldgov.gtiles.core.module.infofield.DependencyModule;
/**
* 模块对象
* @author LiuHG
* @version 1.0
*/
public class Module implements Serializable{
private static final long serialVersionUID = 5685954877676754055L;
private ModuleDescription description;
private Module[] subModules;
private ModuleState moduleState = ModuleState.UNKNOW;
private LinkedHashMap<DependencyModule,DependencyState> dependencyState = new LinkedHashMap<DependencyModule,DependencyState>();
private transient ModuleContext moduleContext;
public Module(ModuleDescription description){
//TODO i18n
Assert.notNull(description,"模块描述不能为null");
this.description = description;
}
public String getId() {
return description.id();
}
public ModuleDescription getDescription() {
return description;
}
public LinkedHashMap<DependencyModule, DependencyState> getDependencyState() {
return dependencyState;
}
public void setDependencyState(DependencyModule dependency,DependencyState state){
if(dependency.getId().equals(this.getId())){
//TODO 不需要依赖自己
return;
}
dependencyState.put(dependency, state);
}
public Module[] getSubModules() {
if(!isLocalModule()){
throw new RuntimeException("不能获取远程模块的子模块信息");
}
return subModules;
}
public void setSubModules(Module[] subModules) {
this.subModules = subModules;
}
public ModuleState getModuleState() {
return moduleState;
}
public void setModuleState(ModuleState moduleState) {
if(this.moduleState == moduleState){
return;
}
this.moduleState = moduleState;
if(moduleContext != null){
moduleContext.updateModuleStateBySub(this);
}
}
public boolean isLocalModule(){
return (description instanceof LocalModule);
}
void setModuleContext(ModuleContext moduleContext){
this.moduleContext = moduleContext;
}
@Override
public String toString() {
return "Module:" + description.name() + " Version:" + description.version() + " State:" + moduleState;
}
}
|
package modelo;
public class Neognato extends Neornithe{
private Galloanserae galloanserae;
private Neoave neoave;
protected int numeroHuesosEnPatas;
protected double longitudTercerDedo;
public Neognato(String col, double alt, double pes, double longC, double densO, char ranM, int numHEP, double longTD){
super(col, alt, pes, longC, densO, ranM);
numeroHuesosEnPatas = numHEP;
longitudTercerDedo = longTD;
}
public Galloanserae darGalloanserae(){
return galloanserae;
}
public Neoave darNeoave(){
return neoave;
}
public int darNumeroHuesosEnPatas(){
return numeroHuesosEnPatas;
}
public double darLongitudTercerDedo(){
return longitudTercerDedo;
}
public void modificarNumeroHuesosEnPatas(int numHEP){
numeroHuesosEnPatas = numHEP;
}
public void modificarLongitudTercerDedo(double longTD){
longitudTercerDedo = longTD;
}
/**@Override
*/
public double calcularPromedioPesoAve(){
double peso = 0;
peso = neoave.darPeso() + neoave.calcularPromedioPesoAve();
if(galloanserae != null){
peso += galloanserae.darPeso();
}
return peso;
}
/**@Override
*/
public double calcularSumaAltura(){
double suma = 0;
suma = neoave.darAltura() + neoave.calcularSumaAltura();
if(galloanserae != null){
suma += galloanserae.darAltura();
}
return suma;
}
/**@Override
*/
public int calcularTotalBajo(){
int bajo = 0;
if( neoave.darRangoMetabolico() == 'B'){
bajo++;
}
bajo += neoave.calcularTotalBajo();
if(galloanserae != null && galloanserae.darRangoMetabolico() == 'B'){
bajo++;
}
return bajo;
}
/**@Override
*/
public int calcularTotalMedio(){
int medio = 0;
if( neoave.darRangoMetabolico() == 'M'){
medio++;
}
medio += neoave.calcularTotalMedio();
if(galloanserae != null && galloanserae.darRangoMetabolico() == 'M'){
medio++;
}
return medio;
}
/**@Override
*/
public int calcularTotalAlto(){
int alto = 0;
if( neoave.darRangoMetabolico() == 'A'){
alto++;
}
alto += neoave.calcularTotalAlto();
if(galloanserae != null && galloanserae.darRangoMetabolico() == 'A'){
alto++;
}
return alto;
}
}
|
package com.employeemanagement.controller;
import com.employeemanagement.entity.EmployeeEntity;
import com.employeemanagement.service.EmployeeService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.NoSuchElementException;
@Controller
@AllArgsConstructor
@RequestMapping("/employee")
public class EmployeeController {
private final EmployeeService service;
@GetMapping("all")
public String findAll(final Model model) {
model.addAttribute("employees", service.findAll());
return "employees";
}
@GetMapping("{id}")
public String findByEmail(final @PathVariable int id, final Model model) {
model.addAttribute("employee", service.findById(id).get());
return "employee";
}
@GetMapping("add")
public String add(final Model model) {
model.addAttribute("employeeEntity", new EmployeeEntity());
return "add-employee";
}
@PostMapping("add")
public String save(final @Valid @ModelAttribute EmployeeEntity employeeEntity, final BindingResult result) {
if (result.hasErrors())
return "add-employee";
service.save(employeeEntity);
return "redirect:/employee/all?employee-added=true";
}
@GetMapping("update/{id}")
public String update(final @PathVariable int id, final Model model) {
model.addAttribute("employeeEntity", service.findById(id).get());
return "update-employee";
}
@PostMapping("update/{id}")
public String update(final @PathVariable int id, final @Valid EmployeeEntity employeeEntity, final BindingResult result) {
if (result.hasErrors())
return "update-employee";
final EmployeeEntity employee = service.findById(id)
.orElseThrow(() -> new NoSuchElementException("No value present"));
employee.setName(employeeEntity.getName());
employee.setAge(employeeEntity.getAge());
employee.setEmail(employeeEntity.getEmail());
employee.setGender(employeeEntity.getGender());
employee.setPhone(employeeEntity.getPhone());
employee.setDesignation(employeeEntity.getDesignation());
service.save(employee);
return "redirect:/employee/all?employee-updated=true";
}
@GetMapping("delete/{id}")
public String deleteById(final @PathVariable int id) {
service.deleteById(id);
return "redirect:/employee/all?employee-deleted=true";
}
}
|
package ninja.farhood.exercises;
public class Ex1pattern {
public static void main(String[] args) {
System.out.println(" J A V V A");
System.out.println(" J A A V V A A");
System.out.println("J J AAAAA V V AAAAA");
System.out.println(" J J A A V A A");
}
}
|
package com.bookstore.repository;
import com.bookstore.domain.UserShipping;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserShippingRepository extends JpaRepository<UserShipping, Long> {
}
|
package com.zhouyi.business.core.model;
import java.io.Serializable;
import java.util.Date;
public class TestNameInfo implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String familyName;
private String birthday;
private Integer sex;
private String homePlace;
private Double latitude;
private Double longitude;
private Long userId; //创建者
private Date createTime; //创建日期
private Integer isDouble;
private String combine;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFamilyName() {
return familyName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public String getHomePlace() {
return homePlace;
}
public void setHomePlace(String homePlace) {
this.homePlace = homePlace;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Double getLatitude() {
return latitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
public Integer getIsDouble() {
return isDouble;
}
public void setIsDouble(Integer isDouble) {
this.isDouble = isDouble;
}
public String getCombine() {
return combine;
}
public void setCombine(String combine) {
this.combine = combine;
}
}
|
package com.tencent.mm.compatible.util;
public interface b$a {
void ex(int i);
}
|
package com.tencent.mm.protocal;
import com.tencent.mm.protocal.c.g;
public class c$ip extends g {
public c$ip() {
super("showMenuItems", "showMenuItems", 86, false);
}
}
|
import javafx.application.Application;
import javafx.stage.Stage;
/**
* Created by Александр on 18.09.2017.
*/
public class StratAdmin extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
System.out.println("SVVVDFB");
}
public static void main(String[] args) {
launch(args);
}
}
|
package controller.controller;
import controller.datamapper.EigenaarDataMapper;
import controller.dtos.EigenaarDTO;
import domain.Eigenaar;
import exceptions.eigenexcepties.OnjuistWachtwoordExceptie;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path("/")
public class EigenaarController {
private EigenaarDataMapper eigenaarDM;
@Inject
public void setEigenaarDM(EigenaarDataMapper eigenaarDM) {
this.eigenaarDM = eigenaarDM;
}
@Path("login")
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response Login(EigenaarDTO eigenaarDTO){
Eigenaar eigenaar = eigenaarDM.mapToDomain(eigenaarDTO);
try {
eigenaar.setIngelogd();
} catch (OnjuistWachtwoordExceptie e) {
Response.status(401).build();
}
return Response.ok(eigenaarDM.mapToDTO(eigenaar)).build();
}
}
|
package hr.mealpler.client.adapters;
import hr.mealpler.client.activities.R;
import hr.mealpler.client.activities.R.id;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
public class HeightSpinnerAdapter extends ArrayAdapter<String> implements
SpinnerAdapter {
private LayoutInflater inflate;
private int resourceId;
private String[] options;
private Context context;
public HeightSpinnerAdapter(Context context, int textViewResourceId,
String[] objects) {
super(context, textViewResourceId, objects);
this.context = context;
this.inflate = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.resourceId = textViewResourceId;
this.options = objects;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflate.inflate(resourceId, null);
Holder holder = new Holder();
holder.textView = (TextView) convertView
.findViewById(R.id.textView1);
convertView.setTag(holder);
}
Holder holder = (Holder) convertView.getTag();
holder.textView.setText(options[position]);
return convertView;
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflate.inflate(resourceId, null);
Holder holder = new Holder();
holder.textView = (TextView) convertView
.findViewById(R.id.textView1);
convertView.setTag(holder);
}
Holder holder = (Holder) convertView.getTag();
holder.textView.setText(options[position]);
holder.textView.setBackgroundColor(Color.parseColor("#D8D8D8"));
return convertView;
}
private class Holder {
TextView textView;
}
}
|
package misc;
import java.awt.Panel;
import java.awt.datatransfer.DataFlavor;
import javax.swing.JPanel;
import main.Card;
public class PanelDataFlavor extends DataFlavor {
public static final PanelDataFlavor SHARED_INSTANCE = new PanelDataFlavor();
public PanelDataFlavor() {
super(JPanel.class, null);
}
}
|
package com.smxknife.springboot.v2.jpa.domain.one_to_many_single;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import java.util.ArrayList;
import java.util.List;
/**
* @author smxknife
* 2019-02-21
*/
@Entity
public class Department1 {
@Id
long id;
@OneToMany
List<Employee1> employees = new ArrayList<>();
}
|
package unico;
abstract class Terrestre implements IMotorizzati,INonMotorizzati{
public void Spostamento() {
// TODO Auto-generated method stub
System.out.println("il mezzo di trasporto terrestre si muove");
}
}
|
/**
* Copyright (C) 2015 Zalando SE (http://tech.zalando.com)
*
* 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.zalando.zmon.actuator;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
@Component
public class ZmonRestFilterBeanPostProcessor implements BeanPostProcessor {
private static final Log logger = LogFactory.getLog(ZmonRestFilterBeanPostProcessor.class);
private final ZmonRestResponseFilter zmonRestResponseFilter;
private final List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
@Autowired
public ZmonRestFilterBeanPostProcessor(final ZmonRestResponseFilter zmonRestResponseFilter) {
this.zmonRestResponseFilter = zmonRestResponseFilter;
interceptors.add(zmonRestResponseFilter);
}
@Override
public Object postProcessBeforeInitialization(final Object possiblyRestTemplateBean, final String beanName)
throws BeansException {
if (possiblyRestTemplateBean instanceof RestTemplate) {
RestTemplate restTemplateBean = (RestTemplate) possiblyRestTemplateBean;
restTemplateBean.setInterceptors(interceptors);
logger.info("Added " + ZmonRestFilterBeanPostProcessor.class.getCanonicalName() + " instance to "
+ beanName);
}
return possiblyRestTemplateBean;
}
@Override
public Object postProcessAfterInitialization(final Object o, final String s) throws BeansException {
return o;
}
}
|
package rog.bookstore.menu;
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.faces.bean.ManagedBean;
@ManagedBean(name="menuBean")
@SessionScoped
public class MenuBean implements Serializable{
}
|
package by.it.example.openweathermap;
import by.it.example.beans.Weather;
import org.junit.Test;
import static org.junit.Assert.*;
public class WeatherServiceGoodTest {
@Test
public void getWeather() {
WeatherClient client = Mocks.createMock(Data.CITY, Data.TEMPERATURE);
WeatherService service = new WeatherService(client);
Weather weather = service.getWeather("Minsk");
double temperature = weather.getTemperature();
assertEquals(Data.TEMPERATURE, temperature, 1e-10);
}
}
|
package com.mindtree.service;
import java.util.ArrayList;
import com.mindtree.entity.Product;
public interface SellerServiceInterface {
public String insertProduct(Product product);
public ArrayList<Product> retrieveProductDetails();
public String deleteProduct(int productId);
public String updateProductDetails(int productId ,Product product);
}
|
package com.tencent.mm.ui.base;
public interface MMRadioGroupView$b {
}
|
package GUI;
import Estruturas.PalavraFactory;
import Estruturas.Hashing.TabelaHash;
import Estruturas.Trie.ASCII_Trie;
import FuncoesHash.FuncaoHashingFactory;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.SwingWorker.StateValue;
/**
* 626966
*
* @author Lucas
*/
public class Principal extends javax.swing.JFrame {
private TabelaHash tbHash;
private ASCII_Trie trie;
private PreProcessamentoTrie preWorkerTrie;
private PreProcessamento preWorkerHash;
private BuscarPalavra buscarWorker;
private BuscarPalavraTrie buscarWorkerTrie;
public Principal() {
printSystemStatus();
initComponents();
initComboTuplas();
initComboHashing();
// Centraliza a janela
this.setLocationRelativeTo(null);
}
private void printSystemStatus() {
for (Object o : java.lang.System.getProperties().values()) {
System.out.println(o);
}
System.out.println(">> " + System.getProperty("sun.arch.data.model"));
}
private void initComboTuplas() {
this.tipoPalavra.setModel(new javax.swing.DefaultComboBoxModel(PalavraFactory.TipoPalavra.values()));
this.tipoPalavra.setSelectedIndex(0);
}
private void initComboHashing() {
this.funcaoHashing.setModel(new javax.swing.DefaultComboBoxModel(FuncaoHashingFactory.Funcao.values()));
this.funcaoHashing.setSelectedIndex(0);
}
/**
* 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() {
panelArquivo = new javax.swing.JPanel();
labelArquivo = new javax.swing.JLabel();
textoCaminho = new javax.swing.JTextField();
botaoAbrir = new javax.swing.JButton();
labelLingua = new javax.swing.JLabel();
comboLingua = new javax.swing.JComboBox();
panelAbas = new javax.swing.JTabbedPane();
panelHash = new javax.swing.JPanel();
panelConfigHash = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
tamanhoTabela = new javax.swing.JTextField();
limiteDocumentosHash = new javax.swing.JTextField();
tipoPalavra = new javax.swing.JComboBox();
funcaoHashing = new javax.swing.JComboBox();
botaoIniciarHash = new javax.swing.JButton();
panelBuscarHash = new javax.swing.JPanel();
jLabel7 = new javax.swing.JLabel();
textoBuscarHash = new javax.swing.JTextField();
botaoBuscarPalavraHash = new javax.swing.JButton();
barraProgressoHash = new javax.swing.JProgressBar();
panelLogHash = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
logHash = new javax.swing.JTextArea();
panelTrie = new javax.swing.JPanel();
panelConfigTrie = new javax.swing.JPanel();
jLabel8 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
limiteDocumentosTrie = new javax.swing.JTextField();
botaoIniciarTrie = new javax.swing.JButton();
panelLogTrie = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
logTrie = new javax.swing.JTextArea();
panelBuscarTrie = new javax.swing.JPanel();
jLabel9 = new javax.swing.JLabel();
textoBuscarTrie = new javax.swing.JTextField();
botaoBuscarPalavraTrie = new javax.swing.JButton();
barraProgressoTrie = new javax.swing.JProgressBar();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Índice invertido de busca");
labelArquivo.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
labelArquivo.setText("Arquivo:");
textoCaminho.setText("C:\\Users\\Lucas\\Desktop\\short-abstracts_en.ttl");
botaoAbrir.setText("Abrir");
botaoAbrir.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botaoAbrirActionPerformed(evt);
}
});
labelLingua.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
labelLingua.setText("Língua do arquivo selecionado:");
comboLingua.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Inglês", "Português" }));
javax.swing.GroupLayout panelArquivoLayout = new javax.swing.GroupLayout(panelArquivo);
panelArquivo.setLayout(panelArquivoLayout);
panelArquivoLayout.setHorizontalGroup(
panelArquivoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelArquivoLayout.createSequentialGroup()
.addContainerGap()
.addGroup(panelArquivoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelArquivoLayout.createSequentialGroup()
.addComponent(labelArquivo)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(textoCaminho)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(botaoAbrir, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(panelArquivoLayout.createSequentialGroup()
.addComponent(labelLingua)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(comboLingua, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
panelArquivoLayout.setVerticalGroup(
panelArquivoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelArquivoLayout.createSequentialGroup()
.addContainerGap()
.addGroup(panelArquivoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelArquivo)
.addComponent(textoCaminho, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(botaoAbrir))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(panelArquivoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelLingua)
.addComponent(comboLingua, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel2.setText("Configurações");
jLabel3.setText("Tamanho da tabela");
jLabel4.setText("N° de documentos a serem lidos");
jLabel5.setText("Estrutura das tuplas");
jLabel6.setText("Função de hashing");
tamanhoTabela.setText("500009");
limiteDocumentosHash.setText("1000000");
botaoIniciarHash.setText("Iniciar Leitura Hash");
botaoIniciarHash.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botaoIniciarHashActionPerformed(evt);
}
});
javax.swing.GroupLayout panelConfigHashLayout = new javax.swing.GroupLayout(panelConfigHash);
panelConfigHash.setLayout(panelConfigHashLayout);
panelConfigHashLayout.setHorizontalGroup(
panelConfigHashLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelConfigHashLayout.createSequentialGroup()
.addContainerGap()
.addGroup(panelConfigHashLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelConfigHashLayout.createSequentialGroup()
.addGroup(panelConfigHashLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel5)
.addComponent(jLabel6)
.addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(panelConfigHashLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(tipoPalavra, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(funcaoHashing, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(limiteDocumentosHash, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 137, Short.MAX_VALUE)))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelConfigHashLayout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(botaoIniciarHash))
.addGroup(panelConfigHashLayout.createSequentialGroup()
.addComponent(jLabel2)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(panelConfigHashLayout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 88, Short.MAX_VALUE)
.addComponent(tamanhoTabela, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
panelConfigHashLayout.setVerticalGroup(
panelConfigHashLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelConfigHashLayout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(panelConfigHashLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(tamanhoTabela, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(panelConfigHashLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(limiteDocumentosHash, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(panelConfigHashLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(tipoPalavra, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(panelConfigHashLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(funcaoHashing, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 276, Short.MAX_VALUE)
.addComponent(botaoIniciarHash))
);
jLabel7.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel7.setText("Buscar palavra:");
botaoBuscarPalavraHash.setText("Buscar");
botaoBuscarPalavraHash.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botaoBuscarPalavraHashActionPerformed(evt);
}
});
javax.swing.GroupLayout panelBuscarHashLayout = new javax.swing.GroupLayout(panelBuscarHash);
panelBuscarHash.setLayout(panelBuscarHashLayout);
panelBuscarHashLayout.setHorizontalGroup(
panelBuscarHashLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelBuscarHashLayout.createSequentialGroup()
.addContainerGap()
.addGroup(panelBuscarHashLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(barraProgressoHash, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(panelBuscarHashLayout.createSequentialGroup()
.addComponent(jLabel7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(textoBuscarHash)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(botaoBuscarPalavraHash)))
.addContainerGap())
);
panelBuscarHashLayout.setVerticalGroup(
panelBuscarHashLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelBuscarHashLayout.createSequentialGroup()
.addContainerGap()
.addGroup(panelBuscarHashLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(textoBuscarHash, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(botaoBuscarPalavraHash))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(barraProgressoHash, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
logHash.setEditable(false);
logHash.setColumns(20);
logHash.setRows(5);
jScrollPane1.setViewportView(logHash);
javax.swing.GroupLayout panelLogHashLayout = new javax.swing.GroupLayout(panelLogHash);
panelLogHash.setLayout(panelLogHashLayout);
panelLogHashLayout.setHorizontalGroup(
panelLogHashLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelLogHashLayout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 548, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
panelLogHashLayout.setVerticalGroup(
panelLogHashLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
);
javax.swing.GroupLayout panelHashLayout = new javax.swing.GroupLayout(panelHash);
panelHash.setLayout(panelHashLayout);
panelHashLayout.setHorizontalGroup(
panelHashLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelHashLayout.createSequentialGroup()
.addGroup(panelHashLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelHashLayout.createSequentialGroup()
.addComponent(panelConfigHash, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(panelLogHash, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(panelHashLayout.createSequentialGroup()
.addContainerGap()
.addComponent(panelBuscarHash, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addContainerGap())
);
panelHashLayout.setVerticalGroup(
panelHashLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelHashLayout.createSequentialGroup()
.addGroup(panelHashLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(panelConfigHash, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(panelLogHash, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(panelBuscarHash, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
panelAbas.addTab("Tabela Hash", panelHash);
jLabel8.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel8.setText("Configurações");
jLabel10.setText("N° de documentos a serem lidos");
limiteDocumentosTrie.setText("1000000");
botaoIniciarTrie.setText("Iniciar Leitura Trie");
botaoIniciarTrie.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botaoIniciarTrieActionPerformed(evt);
}
});
javax.swing.GroupLayout panelConfigTrieLayout = new javax.swing.GroupLayout(panelConfigTrie);
panelConfigTrie.setLayout(panelConfigTrieLayout);
panelConfigTrieLayout.setHorizontalGroup(
panelConfigTrieLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelConfigTrieLayout.createSequentialGroup()
.addContainerGap()
.addGroup(panelConfigTrieLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelConfigTrieLayout.createSequentialGroup()
.addComponent(jLabel10, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(limiteDocumentosTrie, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(panelConfigTrieLayout.createSequentialGroup()
.addComponent(jLabel8)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelConfigTrieLayout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(botaoIniciarTrie)))
.addContainerGap())
);
panelConfigTrieLayout.setVerticalGroup(
panelConfigTrieLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelConfigTrieLayout.createSequentialGroup()
.addComponent(jLabel8)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(panelConfigTrieLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel10)
.addComponent(limiteDocumentosTrie, 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)
.addComponent(botaoIniciarTrie))
);
logTrie.setEditable(false);
logTrie.setColumns(20);
logTrie.setRows(5);
jScrollPane2.setViewportView(logTrie);
javax.swing.GroupLayout panelLogTrieLayout = new javax.swing.GroupLayout(panelLogTrie);
panelLogTrie.setLayout(panelLogTrieLayout);
panelLogTrieLayout.setHorizontalGroup(
panelLogTrieLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelLogTrieLayout.createSequentialGroup()
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 548, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
panelLogTrieLayout.setVerticalGroup(
panelLogTrieLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 425, Short.MAX_VALUE)
);
jLabel9.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel9.setText("Buscar palavra:");
botaoBuscarPalavraTrie.setText("Buscar");
botaoBuscarPalavraTrie.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botaoBuscarPalavraTrieActionPerformed(evt);
}
});
javax.swing.GroupLayout panelBuscarTrieLayout = new javax.swing.GroupLayout(panelBuscarTrie);
panelBuscarTrie.setLayout(panelBuscarTrieLayout);
panelBuscarTrieLayout.setHorizontalGroup(
panelBuscarTrieLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelBuscarTrieLayout.createSequentialGroup()
.addContainerGap()
.addGroup(panelBuscarTrieLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(barraProgressoTrie, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(panelBuscarTrieLayout.createSequentialGroup()
.addComponent(jLabel9)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(textoBuscarTrie)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(botaoBuscarPalavraTrie)))
.addContainerGap())
);
panelBuscarTrieLayout.setVerticalGroup(
panelBuscarTrieLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelBuscarTrieLayout.createSequentialGroup()
.addContainerGap()
.addGroup(panelBuscarTrieLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel9)
.addComponent(textoBuscarTrie, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(botaoBuscarPalavraTrie))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(barraProgressoTrie, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout panelTrieLayout = new javax.swing.GroupLayout(panelTrie);
panelTrie.setLayout(panelTrieLayout);
panelTrieLayout.setHorizontalGroup(
panelTrieLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelTrieLayout.createSequentialGroup()
.addGroup(panelTrieLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelTrieLayout.createSequentialGroup()
.addComponent(panelConfigTrie, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(panelLogTrie, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(panelTrieLayout.createSequentialGroup()
.addContainerGap()
.addComponent(panelBuscarTrie, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addContainerGap())
);
panelTrieLayout.setVerticalGroup(
panelTrieLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelTrieLayout.createSequentialGroup()
.addGroup(panelTrieLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(panelConfigTrie, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(panelLogTrie, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(panelBuscarTrie, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
panelAbas.addTab("Trie", panelTrie);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(panelArquivo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(panelAbas)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(panelArquivo, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(panelAbas, javax.swing.GroupLayout.DEFAULT_SIZE, 558, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* Botao "Abrir". Abre uma janela para escolher o arquivo.
*/
private void botaoAbrirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoAbrirActionPerformed
final File dir = new File(textoCaminho.getText()).getAbsoluteFile();
final JFileChooser fileChooser = new JFileChooser(dir.getParentFile());
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
final int option = fileChooser.showOpenDialog(Principal.this);
if (option == JFileChooser.APPROVE_OPTION) {
final File selected = fileChooser.getSelectedFile();
textoCaminho.setText(selected.getAbsolutePath());
}
}//GEN-LAST:event_botaoAbrirActionPerformed
/**
* Inicia a busca por uma palavra na tabela hash.
*/
private void botaoBuscarPalavraHashActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoBuscarPalavraHashActionPerformed
// if (true) {
// ContaBuscas a = new ContaBuscas(tbHash);
// Thread b = new Thread(a);
// b.start();
// return;
// }
if (tbHash == null || textoBuscarHash.getText() == null || textoBuscarHash.getText().isEmpty()) {
return;
}
// Desabilita os botões
botaoIniciarHash.setEnabled(false);
botaoBuscarPalavraHash.setEnabled(false);
logHash.append("\nIniciando busca usando os termos: " + textoBuscarHash.getText() + "\n");
// Cria worker thread
buscarWorker = new BuscarPalavra(logHash, textoBuscarHash.getText().split(" "), tbHash);
// Cria um Listener para receber os eventos enviados pelo worker thread
buscarWorker.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(final PropertyChangeEvent event) {
switch (event.getPropertyName()) {
case "progress":
// Atualiza a barra de progresso
barraProgressoHash.setIndeterminate(false);
barraProgressoHash.setValue((Integer) event.getNewValue());
break;
case "state":
switch ((StateValue) event.getNewValue()) {
case DONE:
// Finaliza
barraProgressoHash.setIndeterminate(false);
barraProgressoHash.setValue(0);
botaoIniciarHash.setEnabled(true);
botaoBuscarPalavraHash.setEnabled(true);
buscarWorker = null;
break;
case STARTED:
case PENDING:
// Em processo de inicialização
barraProgressoHash.setIndeterminate(true);
break;
}
break;
}
}
});
// Inicia o worker thread
buscarWorker.execute();
}//GEN-LAST:event_botaoBuscarPalavraHashActionPerformed
/**
* Cria a tabela hash
*/
private void botaoIniciarHashActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoIniciarHashActionPerformed
//Desabilita a janela
this.setEnabled(false);
// Limpa a tabela hash e a trie
tbHash = null;
trie = null;
// Indica o Garbage Collector
System.gc();
// Pega os campos de configuracao
String caminho = textoCaminho.getText();
int tamanho = Integer.parseInt(tamanhoTabela.getText());
int limite = Integer.parseInt(limiteDocumentosHash.getText());
FuncaoHashingFactory.Funcao funcao = (FuncaoHashingFactory.Funcao) funcaoHashing.getSelectedItem();
PalavraFactory.TipoPalavra palavra = (PalavraFactory.TipoPalavra) tipoPalavra.getSelectedItem();
String lingua = (String) this.comboLingua.getSelectedItem();
// Cria worker thread
// preWorker = new PreProcessamentoTrie(caminho, limite, log, this);
preWorkerHash = new PreProcessamento(caminho, tamanho, limite, palavra, funcao, logHash, this, lingua);
// Cria um Listener para receber os eventos enviados pelo worker thread
preWorkerHash.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(final PropertyChangeEvent event) {
switch (event.getPropertyName()) {
case "progress":
// Atualiza a barra de progresso
barraProgressoHash.setIndeterminate(false);
barraProgressoHash.setValue((Integer) event.getNewValue());
break;
case "state":
switch ((StateValue) event.getNewValue()) {
case DONE:
// Finaliza
barraProgressoHash.setIndeterminate(false);
barraProgressoHash.setValue(0);
preWorkerHash = null;
break;
case STARTED:
case PENDING:
// Em processo de inicialização
barraProgressoHash.setIndeterminate(true);
break;
}
break;
}
}
});
// Inicia o worker thread
preWorkerHash.execute();
}//GEN-LAST:event_botaoIniciarHashActionPerformed
/**
* Cria a trie
*/
private void botaoIniciarTrieActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoIniciarTrieActionPerformed
//Desabilita a janela
this.setEnabled(false);
// Limpa a tabela hash e a trie
tbHash = null;
trie = null;
// Indica o Garbage Collector
System.gc();
// Pega os campos de configuracao
String caminho = textoCaminho.getText();
int limite = Integer.parseInt(limiteDocumentosTrie.getText());
String lingua = (String) this.comboLingua.getSelectedItem();
// Cria worker thread
preWorkerTrie = new PreProcessamentoTrie(caminho, limite, logTrie, this, lingua);
// Cria um Listener para receber os eventos enviados pelo worker thread
preWorkerTrie.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(final PropertyChangeEvent event) {
switch (event.getPropertyName()) {
case "progress":
// Atualiza a barra de progresso
barraProgressoTrie.setIndeterminate(false);
barraProgressoTrie.setValue((Integer) event.getNewValue());
break;
case "state":
switch ((StateValue) event.getNewValue()) {
case DONE:
// Finaliza
barraProgressoTrie.setIndeterminate(false);
barraProgressoTrie.setValue(0);
preWorkerTrie = null;
break;
case STARTED:
case PENDING:
// Em processo de inicialização
barraProgressoTrie.setIndeterminate(true);
break;
}
break;
}
}
});
// Inicia o worker thread
preWorkerTrie.execute();
}//GEN-LAST:event_botaoIniciarTrieActionPerformed
/**
* Busca palavras na trie
*/
private void botaoBuscarPalavraTrieActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoBuscarPalavraTrieActionPerformed
// if (true) {
// ContaBuscasTrie a = new ContaBuscasTrie(trie);
// Thread b = new Thread(a);
// b.start();
// return;
// }
if (trie == null || textoBuscarTrie.getText() == null || textoBuscarTrie.getText().isEmpty()) {
return;
}
logTrie.append("\nIniciando busca usando os termos: " + textoBuscarTrie.getText() + "\n");
// Cria worker thread
buscarWorkerTrie = new BuscarPalavraTrie(logTrie, textoBuscarTrie.getText().split(" "), trie);
// Cria um Listener para receber os eventos enviados pelo worker thread
buscarWorkerTrie.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(final PropertyChangeEvent event) {
switch (event.getPropertyName()) {
case "progress":
// Atualiza a barra de progresso
barraProgressoTrie.setIndeterminate(false);
barraProgressoTrie.setValue((Integer) event.getNewValue());
break;
case "state":
switch ((StateValue) event.getNewValue()) {
case DONE:
// Finaliza
barraProgressoTrie.setIndeterminate(false);
barraProgressoTrie.setValue(0);
buscarWorker = null;
break;
case STARTED:
case PENDING:
// Em processo de inicialização
barraProgressoTrie.setIndeterminate(true);
break;
}
break;
}
}
});
// Inicia o worker thread
buscarWorkerTrie.execute();
}//GEN-LAST:event_botaoBuscarPalavraTrieActionPerformed
/**
* Recebe a tabela Hash criada pela worker thread
*/
public void setTabelaHash(TabelaHash tb) {
this.tbHash = tb;
}
/**
* Recebe a Trie criada pela worker thread
*/
public void setTrie(ASCII_Trie trie) {
this.trie = trie;
}
/**
* @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(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Principal.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() {
new Principal().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JProgressBar barraProgressoHash;
private javax.swing.JProgressBar barraProgressoTrie;
private javax.swing.JButton botaoAbrir;
private javax.swing.JButton botaoBuscarPalavraHash;
private javax.swing.JButton botaoBuscarPalavraTrie;
private javax.swing.JButton botaoIniciarHash;
private javax.swing.JButton botaoIniciarTrie;
private javax.swing.JComboBox comboLingua;
private javax.swing.JComboBox funcaoHashing;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JLabel labelArquivo;
private javax.swing.JLabel labelLingua;
private javax.swing.JTextField limiteDocumentosHash;
private javax.swing.JTextField limiteDocumentosTrie;
private javax.swing.JTextArea logHash;
private javax.swing.JTextArea logTrie;
private javax.swing.JTabbedPane panelAbas;
private javax.swing.JPanel panelArquivo;
private javax.swing.JPanel panelBuscarHash;
private javax.swing.JPanel panelBuscarTrie;
private javax.swing.JPanel panelConfigHash;
private javax.swing.JPanel panelConfigTrie;
private javax.swing.JPanel panelHash;
private javax.swing.JPanel panelLogHash;
private javax.swing.JPanel panelLogTrie;
private javax.swing.JPanel panelTrie;
private javax.swing.JTextField tamanhoTabela;
private javax.swing.JTextField textoBuscarHash;
private javax.swing.JTextField textoBuscarTrie;
private javax.swing.JTextField textoCaminho;
private javax.swing.JComboBox tipoPalavra;
// End of variables declaration//GEN-END:variables
}
|
package sample;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.input.DragEvent;
import javafx.scene.input.TransferMode;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import java.io.File;
import java.net.URL;
import java.util.Objects;
import java.util.ResourceBundle;
public class Controller implements Initializable {
@FXML public TextField txtProjectName;
@FXML public TextField txtProjectPath;
@FXML public TextField txtDragAndDropFile;
@FXML public Button btnConvert;
@FXML private Label lblErrorMessage;
private Model model;
private final String user_home = System.getProperty("user.home");
@Override
public void initialize(URL location, ResourceBundle resources) {
model = Model.INSTANCE();
btnConvert.setDisable(true);
//Set default Path
txtProjectPath.setPromptText(user_home);
model.setFilePath_java(user_home);
}
public void onDragDropped(DragEvent event) {
File file = event.getDragboard().getFiles().get(0);
checkFile(file);
}
@FXML
public void onBtnSelectFile(ActionEvent actionEvent) {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Open Resource File");
fileChooser.getExtensionFilters().add(
new FileChooser.ExtensionFilter("Text Files", "*.graphml"));
File file = fileChooser.showOpenDialog(((Node)actionEvent.getTarget()).getScene().getWindow());
checkFile(file);
}
private void checkFile(File file){
if(file != null){
model.setFilePath_graphml(file.getAbsolutePath());
txtDragAndDropFile.setText(file.getName());
btnConvert.setDisable(false);
}
}
@FXML
public void onBtnSelectPath(ActionEvent actionEvent) {
DirectoryChooser directoryChooser = new DirectoryChooser();
File selectedDirectory = directoryChooser.showDialog(((Node)actionEvent.getTarget()).getScene().getWindow());
if(selectedDirectory == null){
//No Directory selected
}else{
if(checkForProjectName()){
setErrorMessage("Please select a name for the project folder first");
}else{
setErrorMessage("");
model.setFilePath_java(selectedDirectory.getAbsolutePath()+"\\"+txtProjectName.getText());
txtProjectPath.setText(selectedDirectory.getAbsolutePath()+"\\"+txtProjectName.getText());
}
}
}
@FXML
public void onBtnConvert(ActionEvent actionEvent) {
if(checkForProjectName()){
setErrorMessage("Please select a name for the project folder");
}else{
model.execute();
}
}
private boolean checkForProjectName() {
return txtProjectName.getText().equals("") || Objects.isNull(txtProjectName.getText());
}
public void setErrorMessage(String errorMessage){
lblErrorMessage.setText(errorMessage);
}
public void onDragOverOver(DragEvent event) {
if (event.getDragboard().hasFiles()) {
event.acceptTransferModes(TransferMode.ANY);
}
}
}
|
package kr.ko.nexmain.server.MissingU.config.dao;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import kr.ko.nexmain.server.MissingU.common.model.CommReqVO;
import kr.ko.nexmain.server.MissingU.config.model.GetNoticeReqVO;
import kr.ko.nexmain.server.MissingU.config.model.GetUserGuideReqVO;
import kr.ko.nexmain.server.MissingU.config.model.SaveManToManReqVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
import org.springframework.stereotype.Repository;
import com.ibatis.sqlmap.client.SqlMapClient;
@Repository
public class ConfigDaoImpl extends SqlMapClientDaoSupport implements ConfigDao {
public ConfigDaoImpl(){
super();
}
@Autowired
public ConfigDaoImpl(SqlMapClient sqlMapClient) {
super();
setSqlMapClient(sqlMapClient);
}
/** 공지사항 리스트 조회 */
public List<Map<String,Object>> selectNoticeList(CommReqVO inputVO) {
return (List<Map<String,Object>>) getSqlMapClientTemplate().queryForList("Config.selectNoticeList", inputVO);
}
/** 공지사항 조회 */
public Map<String,Object> selectNotice(GetNoticeReqVO inputVO) {
return (Map<String,Object>) getSqlMapClientTemplate().queryForObject("Config.selectNotice", inputVO);
}
/** 미확인 공지사항 수 조회 */
public Integer selectUnreadNotiCnt(Integer lastReadNoticeId) {
return (Integer) getSqlMapClientTemplate().queryForObject("Config.selectUnreadNotiCnt", lastReadNoticeId);
}
/** 공지사항 조회수 증가 */
public int updateNoticeReadCnt(GetNoticeReqVO inputVO) {
return getSqlMapClientTemplate().update("Config.updateNoticeReadCnt", inputVO);
}
/** 사용자가이드 리스트 조회 */
public List<Map<String,Object>> selectUserGuideList(CommReqVO inputVO) {
return (List<Map<String,Object>>) getSqlMapClientTemplate().queryForList("Config.selectUserGuideList", inputVO);
}
/** 사용자가이드 조회 */
public Map<String,Object> selectUserGuide(GetUserGuideReqVO inputVO) {
return (Map<String,Object>) getSqlMapClientTemplate().queryForObject("Config.selectUserGuide", inputVO);
}
/** 긴급 공지 조회 */
@Override
public Map<String, Object> selectEMRNofitice(CommReqVO inputVO, boolean useShowYn) {
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("gLang", inputVO.getgLang());
params.put("useShowYN", useShowYn ? "1" : "0");
return (Map<String,Object>) getSqlMapClientTemplate().queryForObject("Config.selectEMRNofitice", params);
}
/** 1:1 문의 저장 */
public Integer insertManToManQuestion(SaveManToManReqVO inputVO) {
return (Integer) getSqlMapClientTemplate().insert("Config.insertIntoManToManQuestion", inputVO);
}
/** 긴급 공지 조회 */
@Override
public Map<String, Object> selectEMRNofiticeRandomChat(CommReqVO inputVO, boolean useShowYn) {
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("gLang", inputVO.getgLang());
params.put("useShowYN", useShowYn ? "1" : "0");
return (Map<String,Object>) getSqlMapClientTemplate().queryForObject("Config.selectEMRNofiticeRandomChat", params);
}
}
|
package programmers.lv1;
import java.util.Arrays;
public class Budget_Test {
//예산 문제
//Arrays.sort로 정렬시키고 합쳤다.
public int solution(int[] d, int budget) {
Arrays.sort(d);
int sum = 0;
int answer = 0;
for(int i = 0; i<d.length;i++){
sum += d[i];
if(sum<=budget){
answer++;
}
}
return answer;
}
}
|
package com.vilio.bps.commonMapper.dao;
import java.util.List;
import java.util.Map;
import com.vilio.bps.commonMapper.pojo.BpsCompanyCity;
/**
* @实体名称 估价公司与城市关联表
* @数据库表 BPS_COMPANY_CITY
* @开发日期 2017-06-12
* @技术服务 www.fwjava.com
*/
public interface IBpsCompanyCityMapper {
/**
* 1.新增一条数据
* 注: 根据Bean实体执行新增操作.
* @param bpsCompanyCity - 估价公司与城市关联表
* @throws Exception - 异常捕捉
*/
public void getInsert(BpsCompanyCity bpsCompanyCity) throws Exception;
public void getInsertPrmMap(Map<String, Object> map) throws Exception;
/**
* 2.删除一条数据
* 注: 根据Bean实体的主键ID执行删除操作.
* @param id - 数据主键
* @return int - 执行结果
* @throws Exception - 异常捕捉
*/
public int getDelete(String id) throws Exception;
/**
* 3.变更一条数据
* 注: 根据Bean实体的主键ID执行变更操作.
* @param bpsCompanyCity - 估价公司与城市关联表
* @return int - 执行结果
* @throws Exception - 异常捕捉
*/
public int getUpdate(BpsCompanyCity bpsCompanyCity) throws Exception;
public int getUpdatePrmMap(Map<String, Object> map) throws Exception;
/**
* 4.获取一个Bean实体
* 注: 根据Bean实体的主键ID获取一个Bean实体.
* @param id - 数据主键
* @return BpsCompanyCity - 执行结果
* @throws Exception - 异常捕捉
*/
public BpsCompanyCity getBean(String id) throws Exception;
public Map<String ,Object> getBeanRtnMap(String id) throws Exception;
/**
* 5.条件查询
* 注: 支持多条件查询、模糊查询、日期比较查询等操作.
* @param bpsCompanyCity - 估价公司与城市关联表
* @return List<BpsCompanyCity> - 执行结果
* @throws Exception - 异常捕捉
*/
public List<BpsCompanyCity> getList(BpsCompanyCity bpsCompanyCity) throws Exception;
public List<BpsCompanyCity> getListPrmMapRtnBean(Map<String, Object> map) throws Exception;
public List<Map<String ,Object>> getListPrmMapRtnMap(Map<String, Object> map) throws Exception;
/**
* 6.验证多条件数据是否存在
* 注: 根据多条件验证该数据是否存在 ,并返回数据量.
* @param bpsCompanyCity - 估价公司与城市关联表
* @return int - 存在数量
* @throws Exception - 异常捕捉
*/
public int getCheckBy(BpsCompanyCity bpsCompanyCity) throws Exception;
public int getCheckByPrmMap(Map<String, Object> map) throws Exception;
//根据城市id获取关联估价公司
public List<BpsCompanyCity> queryCompanyCityByCityCode(String cityCode);
}
|
package com.maven.jdbc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan("com.maven.jdbc.dao")
public class BootApplicationMain {
public static void main(String[] args) {
SpringApplication.run(BootApplicationMain.class, args);
}
}
|
package com.commercetools.pspadapter.payone;
import com.commercetools.payments.TransactionStateResolver;
import com.commercetools.payments.TransactionStateResolverImpl;
import com.commercetools.pspadapter.payone.domain.ctp.PaymentWithCartLike;
import com.commercetools.pspadapter.payone.domain.ctp.paymentmethods.PaymentMethod;
import com.commercetools.pspadapter.payone.transaction.PaymentMethodDispatcher;
import io.sphere.sdk.payments.Payment;
import io.sphere.sdk.payments.Transaction;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnitRunner;
import util.PaymentTestHelper;
import javax.annotation.Nonnull;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import static com.commercetools.pspadapter.payone.util.PayoneConstants.PAYONE;
import static java.util.stream.Collectors.toList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@RunWith(MockitoJUnitRunner.class)
public class PaymentDispatcherTest {
private final PaymentTestHelper payments = new PaymentTestHelper();
@Spy
private TransactionStateResolver transactionStateResolver = new TransactionStateResolverImpl();
private class CountingPaymentMethodDispatcher extends PaymentMethodDispatcher {
public int count = 0;
public CountingPaymentMethodDispatcher() {
super((payment, transaction) -> payment,
Collections.emptyMap(),
transactionStateResolver);
}
@Override
public PaymentWithCartLike dispatchPayment(@Nonnull PaymentWithCartLike payment) {
count += 1;
return super.dispatchPayment(payment);
}
}
@Test
public void testRefusingWrongPaymentInterface() throws Exception {
PaymentDispatcher dispatcher = new PaymentDispatcher(null, "TEST-IGNORED");
final Throwable noInterface = catchThrowable(() -> dispatcher.dispatchPayment(new PaymentWithCartLike(payments.dummyPaymentNoInterface(), null)));
assertThat(noInterface).isInstanceOf(IllegalArgumentException.class);
final Throwable wrongInterface = catchThrowable(() -> dispatcher.dispatchPayment(new PaymentWithCartLike(payments.dummyPaymentWrongInterface(), null)));
assertThat(wrongInterface).isInstanceOf(IllegalArgumentException.class);
}
@Test
public void testRefusingUnknownPaymentMethod() throws Exception {
PaymentDispatcher dispatcher = new PaymentDispatcher(new HashMap<>(), "TEST-IGNORED");
final Throwable noInterface = catchThrowable(() -> dispatcher.dispatchPayment(new PaymentWithCartLike(payments.dummyPaymentUnknownMethod(), null)));
assertThat(noInterface).isInstanceOf(IllegalArgumentException.class);
}
@Test
public void testDispatchCorrectlyWithInitialTransactions() throws Exception {
verifyDispatchCallsProperMethods(payments.dummyPaymentTwoTransactionsInitial(),
payments.dummyPaymentTwoTransactionsSuccessInitial());
}
@Test
public void testDispatchCorrectlyWithPendingTransactions() throws Exception {
// Initial/PendingFix: this should not be true after migrating to Initial state:
// Pending transactions should NOT be dispatched any more
verifyDispatchCallsProperMethods(payments.dummyPaymentTwoTransactionsPending(),
payments.dummyPaymentTwoTransactionsSuccessPending());
}
private void verifyDispatchCallsProperMethods(Payment paymentPendingOrInitial, Payment paymentSuccess) throws Exception {
final PaymentWithCartLike paymentPendingOrInitialWithCartLike = new PaymentWithCartLike(paymentPendingOrInitial, null);
final PaymentWithCartLike paymentSuccessWithCartLike = new PaymentWithCartLike(paymentSuccess, null);
final Transaction firstInitTransaction = paymentPendingOrInitial.getTransactions().get(0);
final CountingPaymentMethodDispatcher creditCardDispatcher = new CountingPaymentMethodDispatcher();
final CountingPaymentMethodDispatcher postFinanceDispatcher = new CountingPaymentMethodDispatcher();
final HashMap<PaymentMethod, PaymentMethodDispatcher> methodDispatcherMap = new HashMap<>();
methodDispatcherMap.put(PaymentMethod.CREDIT_CARD, creditCardDispatcher);
methodDispatcherMap.put(PaymentMethod.BANK_TRANSFER_POSTFINANCE_EFINANCE, postFinanceDispatcher);
PaymentDispatcher dispatcher = new PaymentDispatcher(methodDispatcherMap, PAYONE);
dispatcher.dispatchPayment(paymentPendingOrInitialWithCartLike);
ArgumentCaptor<Transaction> transactionCaptor = ArgumentCaptor.forClass(Transaction.class);
// isNotCompletedTransaction expected to be called twice: 1 - filter transaction, 2 - re-verify update transaction
verify(transactionStateResolver, times(2)).isNotCompletedTransaction(transactionCaptor.capture());
// credit card is dispatched ones, cos it has only one CC payment
assertThat(creditCardDispatcher.count).isEqualTo(1);
// sepa is not called, because there were no sepa payments
assertThat(postFinanceDispatcher.count).isEqualTo(0);
// PaymentMethodDispatcher#dispatchPayment() filters in first in-completed (Initial/Pending) transaction,
// and then verifies updated transaction, which is the same in our case.
// second transaction is skipped, because the first one is updated successfully.
List<Transaction> verifiedTransactions = transactionCaptor.getAllValues();
assertThat(verifiedTransactions.stream().map(Transaction::getId).collect(toList()))
.containsExactly(firstInitTransaction.getId(), firstInitTransaction.getId());
dispatcher.dispatchPayment(paymentSuccessWithCartLike);
// 2 is number of times isNotCompletedTransaction() is called on previous step,
// +3 times is called now: 1 for first success transaction (filtered out), 1 for second pending/initial, 1 for updated transaction
verify(transactionStateResolver, times(2 + 3)).isNotCompletedTransaction(transactionCaptor.capture());
// second (accumulated) with test above CC dispatch call
assertThat(creditCardDispatcher.count).isEqualTo(1 + 1);
// sepa still never called
assertThat(postFinanceDispatcher.count).isEqualTo(0);
}
}
|
package com.example.localdatatimedemo.configuration;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
/**
* Description TODO
*
* @author Roye.L
* @date 2019/4/9 0:04
* @since 1.0
*/
public class ChungeAdapter implements TypeAdapterFactory {
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
return null;
}
}
|
package com.rc.portal.dao.impl;
import java.sql.SQLException;
import java.util.List;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.rc.app.framework.webapp.model.page.PageManager;
import com.rc.app.framework.webapp.model.page.PageWraper;
import com.rc.portal.dao.TShortBuyDAO;
import com.rc.portal.vo.TShortBuy;
import com.rc.portal.vo.TShortBuyExample;
public class TShortBuyDAOImpl implements TShortBuyDAO {
private SqlMapClient sqlMapClient;
public void setSqlMapClient(SqlMapClient sqlMapClient) {
this.sqlMapClient = sqlMapClient;
}
public SqlMapClient getSqlMapClient() {
return sqlMapClient;
}
public TShortBuyDAOImpl() {
super();
}
public TShortBuyDAOImpl(SqlMapClient sqlMapClient) {
super();
this.sqlMapClient = sqlMapClient;
}
public int countByExample(TShortBuyExample example) throws SQLException {
Integer count = (Integer) sqlMapClient.queryForObject("t_short_buy.ibatorgenerated_countByExample", example);
return count.intValue();
}
public int deleteByExample(TShortBuyExample example) throws SQLException {
int rows = sqlMapClient.delete("t_short_buy.ibatorgenerated_deleteByExample", example);
return rows;
}
public int deleteByPrimaryKey(Long id) throws SQLException {
TShortBuy key = new TShortBuy();
key.setId(id);
int rows = sqlMapClient.delete("t_short_buy.ibatorgenerated_deleteByPrimaryKey", key);
return rows;
}
public Long insert(TShortBuy record) throws SQLException {
return (Long) sqlMapClient.insert("t_short_buy.ibatorgenerated_insert", record);
}
public Long insertSelective(TShortBuy record) throws SQLException {
return (Long) sqlMapClient.insert("t_short_buy.ibatorgenerated_insertSelective", record);
}
public List selectByExample(TShortBuyExample example) throws SQLException {
List list = sqlMapClient.queryForList("t_short_buy.ibatorgenerated_selectByExample", example);
return list;
}
public TShortBuy selectByPrimaryKey(Long id) throws SQLException {
TShortBuy key = new TShortBuy();
key.setId(id);
TShortBuy record = (TShortBuy) sqlMapClient.queryForObject("t_short_buy.ibatorgenerated_selectByPrimaryKey", key);
return record;
}
public int updateByExampleSelective(TShortBuy record, TShortBuyExample example) throws SQLException {
UpdateByExampleParms parms = new UpdateByExampleParms(record, example);
int rows = sqlMapClient.update("t_short_buy.ibatorgenerated_updateByExampleSelective", parms);
return rows;
}
public int updateByExample(TShortBuy record, TShortBuyExample example) throws SQLException {
UpdateByExampleParms parms = new UpdateByExampleParms(record, example);
int rows = sqlMapClient.update("t_short_buy.ibatorgenerated_updateByExample", parms);
return rows;
}
public int updateByPrimaryKeySelective(TShortBuy record) throws SQLException {
int rows = sqlMapClient.update("t_short_buy.ibatorgenerated_updateByPrimaryKeySelective", record);
return rows;
}
public int updateByPrimaryKey(TShortBuy record) throws SQLException {
int rows = sqlMapClient.update("t_short_buy.ibatorgenerated_updateByPrimaryKey", record);
return rows;
}
private static class UpdateByExampleParms extends TShortBuyExample {
private Object record;
public UpdateByExampleParms(Object record, TShortBuyExample example) {
super(example);
this.record = record;
}
public Object getRecord() {
return record;
}
}
public PageWraper selectByRepositoryByPage(TShortBuyExample example) throws SQLException {
PageWraper pw=null;
int count=this.countByExample(example);
List list = sqlMapClient.queryForList("t_short_buy.selectByExampleByPage", example);
System.out.println("��Դ��ҳ��ѯlist.size="+list.size());
pw=PageManager.getPageWraper(example.getPageInfo(), list, count);
return pw;
}
}
|
package br.uff.ic.provmonitor.model;
import java.util.Date;
/**
* Represents the execution info of elements
* */
public class ExecutionStatus {
private String elementId;
private String elementType;
private String status;
private Date startTime;
private Date endTime;
private String elementPath;
private String performers;
private String commitId;
public String getElementId() {
return elementId;
}
public void setElementId(String elementId) {
this.elementId = elementId;
}
public String getElementType() {
return elementType;
}
public void setElementType(String elementType) {
this.elementType = elementType;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public String getElementPath() {
return elementPath;
}
public void setElementPath(String elementPath) {
this.elementPath = elementPath;
}
public String getPerformers() {
return performers;
}
public void setPerformers(String performers) {
this.performers = performers;
}
public String getCommitId() {
return commitId;
}
public void setCommitId(String commitId) {
this.commitId = commitId;
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.cmsfacades.uniqueidentifier.functions;
import static org.junit.Assert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import static org.hamcrest.Matchers.*;
import de.hybris.bootstrap.annotations.UnitTest;
import de.hybris.platform.cmsfacades.data.ItemData;
import de.hybris.platform.core.model.user.UserGroupModel;
import de.hybris.platform.servicelayer.dto.converter.Converter;
import de.hybris.platform.servicelayer.user.daos.UserGroupDao;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.security.access.method.P;
@UnitTest
@RunWith(MockitoJUnitRunner.class)
public class DefaultUserGroupModelUniqueIdentifierConverterTest
{
@InjectMocks
private DefaultUserGroupModelUniqueIdentifierConverter converter;
@Mock
private UserGroupDao userGroupDao;
@Mock
private ObjectFactory<ItemData> itemDataDataFactory;
private String fakeItemId = "item-id";
@Mock
private UserGroupModel userGroupModel;
@Before
public void setup()
{
when(itemDataDataFactory.getObject()).thenReturn(new ItemData());
when(userGroupModel.getUid()).thenReturn(fakeItemId);
when(userGroupDao.findUserGroupByUid(fakeItemId)).thenReturn(userGroupModel);
}
@Test
public void itemTypeReturnsCorrectType()
{
assertThat(String.format("DefaultUserGroupModelUniqueIdentifierConverterTest itemType " +
"should return %s typecode", UserGroupModel._TYPECODE),
converter.getItemType(), is(UserGroupModel._TYPECODE));
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowExceptionWhenItemModelIsNull()
{
//prepare
UserGroupModel itemModel = null;
//execute
converter.convert(itemModel);
}
@Test
public void shouldPassConversionModelToData()
{
final ItemData convert = converter.convert(userGroupModel);
assertThat(convert.getItemId(), is(fakeItemId));
}
@Test
public void shouldPassConversionDataToModel()
{
final ItemData itemData = new ItemData();
itemData.setItemId(fakeItemId);
final UserGroupModel convert = converter.convert(itemData);
assertThat(convert.getUid(), is(fakeItemId));
}
}
|
module feb {
}
|
/*
* Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.test.lib.jfr;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import jdk.test.lib.process.OutputAnalyzer;
import jdk.test.lib.process.ProcessTools;
/**
* Helper class for running applications with enabled JFR recording
*/
public class AppExecutorHelper {
/**
* Executes an application with enabled JFR and writes collected events
* to the given output file.
* Which events to track and other parameters are taken from the setting .jfc file.
*
* @param setting JFR settings file(optional)
* @param jfrFilename JFR resulting recording filename(optional)
* @param additionalVMFlags additional VM flags passed to the java(optional)
* @param className name of the class to execute
* @param classArguments arguments passed to the class(optional)
* @return output analyzer for executed application
*/
public static OutputAnalyzer executeAndRecord(String settings, String jfrFilename, String[] additionalVmFlags,
String className, String... classArguments) throws Exception {
List<String> arguments = new ArrayList<>();
String baseStartFlightRecording = "-XX:StartFlightRecording";
String additionalStartFlightRecording = "";
if (additionalVmFlags != null) {
Collections.addAll(arguments, additionalVmFlags);
}
if (settings != null & jfrFilename != null) {
additionalStartFlightRecording = String.format("=settings=%s,filename=%s", settings, jfrFilename);
} else if (settings != null) {
additionalStartFlightRecording = String.format("=settings=%s", settings);
} else if (jfrFilename != null) {
additionalStartFlightRecording = String.format("=filename=%s", jfrFilename);
}
arguments.add(baseStartFlightRecording + additionalStartFlightRecording);
arguments.add(className);
if (classArguments.length > 0) {
Collections.addAll(arguments, classArguments);
}
ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(true, arguments.toArray(new String[0]));
return ProcessTools.executeProcess(pb);
}
}
|
package com.sunshine.eloqnt.sunshine.activities;
import android.os.Bundle;
import android.view.Menu;
import com.sunshine.eloqnt.sunshine.fragments.ForecastFragment;
import com.sunshine.eloqnt.sunshine.R;
/**
* Created by Daniel on 1/10/2016.
*/
public class ForecastActivity extends MainActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new ForecastFragment())
.commit();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
}
|
package ru.Makivay.sandbox.searcher;
import javax.annotation.Nullable;
/**
* Created by makivay on 14.02.17.
*/
public class LcsPath {
private final String text;
private final int startPosition;
private final int charLenght;
private final double prob;
private final double pathProb;
private final int pathlenght;
private final LcsPath parent;
public LcsPath(String text, int startPosition, double prob) {
this.text = text;
this.startPosition = startPosition;
this.charLenght = text.length();
this.prob = prob;
this.parent = null;
this.pathProb = prob;
this.pathlenght = 1;
}
public LcsPath(String text, int startPosition, double prob, LcsPath parent) {
this.text = text;
this.startPosition = startPosition;
this.charLenght = text.length();
this.prob = prob;
this.parent = parent;
this.pathProb = parent.getPathProb() * prob;
this.pathlenght = parent.getPathlenght() + 1;
}
public String getText() {
return text;
}
public int getStartPosition() {
return startPosition;
}
public int getCharLenght() {
return charLenght;
}
public double getProb() {
return prob;
}
@Nullable
public LcsPath getParent() {
return parent;
}
public double getPathProb() {
return pathProb;
}
public int getPathlenght() {
return pathlenght;
}
}
|
package com.example.OCP.advancedClassDesing.nestedClasses.variablesInNestedClass;
/**
* Created by guille on 10/14/18.
*/
public class A {
private int x = 30;
private class B {
private int x = 20;
private class C {
private int x = 10;
public void getAllTheX(){
System.out.println(x); // 10
System.out.println(this.x); //10
System.out.println(B.this.x); //20
System.out.println(A.this.x); //30
System.out.println(C.this.x); //10
}
}
}
public static void main (String...args){
A a = new A();
A.B b = new A().new B();
B.C c = b.new C();
c.getAllTheX();
}
}
|
package simulateur;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import fr.dgac.ivy.Ivy;
import fr.dgac.ivy.IvyException;
public class SimulateurSRA5 extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
private String[] grammaire = {"deplacer","creer","rectangle", "ici", "ce rectangle", "ce cercle","ca","supprimer","cercle"};
public SimulateurSRA5() {
Ivy busVocal = new Ivy("Reconnaissance Vocale", "RecoVocale Ready", null);
try {
busVocal.start("127.255.255.255:2010");
} catch (IvyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JPanel main = new JPanel();
for(String mot : grammaire) {
JButton b = new JButton(mot);
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
busVocal.sendMsg("Text="+mot+" Confidence=0,99");
} catch (IvyException e1) {
e1.printStackTrace();
}
}
});
main.add(b);
}
this.setContentPane(main);
this.setVisible(true);
this.setSize(600, 350);
this.setLocation(650, 400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
|
//dto é um pacote/pasta chamado data transfer object que contem arquivos com get set e constructor
package dto;
//eu posso colocar extends Object ou não, pq Objeto é extendido de todas as classes
public class Item extends Object{
private int codigo;
private String titulo;
private String ano; // string de 4 digitos
private String sinopse;
// construtor vazio
public Item() {
this(1, "sem titulo", "1980");
}
// construtor cheio
public Item(int codigo, String titulo, String ano) {
super(); // invocar construtor da superClasse (classe q extend ) = extendes objet
setCodigo(codigo);
setTitulo(titulo);
setAno(ano);
}
public String getAno() {
return ano;
}
public void setAno(String ano2) {
if (ano2 != null && ano2.length() == 4) {
for (int i = 0; i < 4; i++) {
//verifiva char por char se é um numero
// ! só serve pra bool java
if (!Character.isDigit(ano2.charAt(i))) {
// tratamento de exessao
throw new IllegalArgumentException("Ano inválido");
}
}
this.ano = ano2;
} else {
// tratamento de exessao
throw new IllegalArgumentException("Ano inválido");
}
}
public int getCodigo() {
return codigo;
}
// SET IS VOID
public void setCodigo(int codigo) {
this.codigo = codigo;
}
public String getTitulo() {
return titulo;
}
// SET IS VOID
public void setTitulo(String titulo) {
this.titulo = titulo;
}
}
|
package com.elepy.annotations;
import com.elepy.auth.Permissions;
import com.elepy.handlers.CreateHandler;
import com.elepy.handlers.DefaultCreate;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation used to change the way Elepy handles creates.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface Create {
/**
* The class that handles the functionality of creates on this Resource.
*
* @return the route createHandler
* @see DefaultCreate
* @see com.elepy.handlers.CreateHandler
*/
Class<? extends CreateHandler> handler() default DefaultCreate.class;
/**
* A list of required permissions to execute this A
*/
String[] requiredPermissions() default Permissions.AUTHENTICATED;
}
|
package com.example.myreadproject8.ui.adapter.bookcase;
import android.app.Activity;
import android.text.TextUtils;
import com.example.myreadproject8.Application.App;
import com.example.myreadproject8.Application.SysManager;
import com.example.myreadproject8.entity.SearchBookBean;
import com.example.myreadproject8.greendao.entity.Book;
import com.example.myreadproject8.ui.adapter.base.BaseListAdapter;
import com.example.myreadproject8.ui.adapter.holder.IViewHolder;
import com.example.myreadproject8.ui.adapter.holder.search.SearchBookHolder;
import com.example.myreadproject8.util.mulvalmap.ConcurrentMultiValueMap;
import com.example.myreadproject8.util.search.SearchEngine;
import com.example.myreadproject8.util.string.StringUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @author fengyue
* @date 2020/10/2 10:08
*/
public class SearchBookAdapter extends BaseListAdapter<SearchBookBean> {
private Activity activity;
private ConcurrentMultiValueMap<SearchBookBean, Book> mBooks;
private SearchEngine searchEngine;
private String keyWord;
public SearchBookAdapter(Activity activity, ConcurrentMultiValueMap<SearchBookBean, Book> mBooks, SearchEngine searchEngine, String keyWord) {
this.activity = activity;
this.mBooks = mBooks;
this.searchEngine = searchEngine;
this.keyWord = keyWord;
}
//创建一个搜索书目
@Override
protected IViewHolder<SearchBookBean> createViewHolder(int viewType) {
return new SearchBookHolder(activity, mBooks, searchEngine, keyWord);
}
//将所有数目加入recycleView
public void addAll(List<SearchBookBean> newDataS, String keyWord) {
List<SearchBookBean> copyDataS = new ArrayList<>(getItems());
List<SearchBookBean> filterDataS = new ArrayList<>();
//选择过滤器
switch (SysManager.getSetting().getSearchFilter()) {
case 0:
filterDataS.addAll(newDataS);
break;
case 1:
default://包含即可
for (SearchBookBean ssb : newDataS) {
if (StringUtils.isContainEachOther(ssb.getName(), keyWord) ||
StringUtils.isContainEachOther(ssb.getAuthor(), keyWord)) {
filterDataS.add(ssb);
}
}
break;
case 2://完全相等
for (SearchBookBean ssb : newDataS) {
if (StringUtils.isEqual(ssb.getName(), keyWord) ||
StringUtils.isEqual(ssb.getAuthor(), keyWord)) {
filterDataS.add(ssb);
}
}
break;
}
if (filterDataS.size() > 0) {
List<SearchBookBean> searchBookBeansAdd = new ArrayList<>();
if (copyDataS.size() == 0) {
copyDataS.addAll(filterDataS);
} else {
//存在
for (SearchBookBean temp : filterDataS) {
boolean hasSame = false;
for (int i = 0, size = copyDataS.size(); i < size; i++) {
SearchBookBean searchBook = copyDataS.get(i);
if (TextUtils.equals(temp.getName(), searchBook.getName())
&& TextUtils.equals(temp.getAuthor(), searchBook.getAuthor())) {
hasSame = true;
break;
}
}
if (!hasSame) {
searchBookBeansAdd.add(temp);
}
}
//添加
for (SearchBookBean temp : searchBookBeansAdd) {
if (TextUtils.equals(keyWord, temp.getName())) {
for (int i = 0; i < copyDataS.size(); i++) {
SearchBookBean searchBook = copyDataS.get(i);
if (!TextUtils.equals(keyWord, searchBook.getName())) {
copyDataS.add(i, temp);
break;
}
}
} else if (TextUtils.equals(keyWord, temp.getAuthor())) {
for (int i = 0; i < copyDataS.size(); i++) {
SearchBookBean searchBook = copyDataS.get(i);
if (!TextUtils.equals(keyWord, searchBook.getName()) && !TextUtils.equals(keyWord, searchBook.getAuthor())) {
copyDataS.add(i, temp);
break;
}
}
} else {
copyDataS.add(temp);
}
}
}
synchronized (this) {
App.runOnUiThread(() -> {
mList = copyDataS;
notifyDataSetChanged();
});
}
}
}
private void sort(List<SearchBookBean> bookBeans) {
//排序,基于最符合关键字的搜书结果应该是最短的
//TODO ;这里只做了简单的比较排序,还需要继续完善
Collections.sort(bookBeans, (o1, o2) -> {
if (o1.getName().equals(keyWord))
return -1;
if (o2.getName().equals(keyWord))
return 1;
if (o1.getAuthor() != null && o1.getAuthor().equals(keyWord))
return -1;
if (o2.getAuthor() != null && o2.getAuthor().equals(keyWord))
return 1;
return Integer.compare(o1.getName().length(), o2.getName().length());
});
}
private int getAddIndex(List<SearchBookBean> beans, SearchBookBean bean) {
int maxWeight = 0;
int index = -1;
if (TextUtils.equals(keyWord, bean.getName())) {
maxWeight = 5;
}else if (TextUtils.equals(keyWord, bean.getAuthor())) {
maxWeight = 3;
}
for (int i = 0; i < beans.size(); i++) {
SearchBookBean searchBook = beans.get(i);
int weight = 0;
if (TextUtils.equals(bean.getName(), searchBook.getName())) {
weight = 4;
} else if (TextUtils.equals(bean.getAuthor(), searchBook.getAuthor())) {
weight = 2;
} else if (bean.getName().length() <= searchBook.getName().length()) {
weight = 1;
}
if (weight > maxWeight) {
index = i;
maxWeight = weight;
}
}
if (maxWeight == 5 || maxWeight == 3) index = 0;
return index;
}
}
|
package com.NewIO;
import java.io.IOException;
import java.nio.file.*;
public class File工具类 {
public static void main(String[] args) {
//
}
//文件的写入与读取
public void Read_and_WriteFile(){
Path path = Paths.get("D:","test","test","zhang.txt");
String str = "NIO is so good , and the tools is also good";
try {
Files.write(path,str.getBytes(), StandardOpenOption.APPEND);
System.out.println("写入成功");
} catch (IOException e) {
e.printStackTrace();
}
try {
byte[] bytes = Files.readAllBytes(path);
System.out.println(new String(bytes));
} catch (IOException e) {
e.printStackTrace();
}
}
//文件的复制
private static void copyFile(){
Path path = Paths.get("D:","test","test","zhang.txt");
Path path1 = Paths.get("D:","test","newio");
try {
Files.copy(path,path1, StandardCopyOption.REPLACE_EXISTING);
System.out.println("文件复制成功");
} catch (IOException e) {
e.printStackTrace();
}
}
//文件的移动
}
|
package demo.openaphid.list;
import java.util.ArrayList;
import java.util.List;
/*
Copyright 2012 Aphid Mobile
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.
*/
public class Section {
private String title;
private List<Row> rows = new ArrayList<Row>();
public Section(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public List<Row> getRows() {
return rows;
}
}
|
package udacity.project.lynsychin.popularmovies.model;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class TrailerDB {
Integer id;
@SerializedName("results")
List<Trailer> trailers;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public List<Trailer> getTrailers() {
return trailers;
}
public void setTrailers(List<Trailer> trailers) {
this.trailers = trailers;
}
}
|
package com.takshine.wxcrm.controller;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.takshine.core.service.CRMService;
import com.takshine.marketing.domain.ActivityPrint;
import com.takshine.wxcrm.base.common.ErrCode;
import com.takshine.wxcrm.base.util.CatchPicture;
import com.takshine.wxcrm.base.util.Get32Primarykey;
import com.takshine.wxcrm.base.util.PropertiesUtil;
import com.takshine.wxcrm.base.util.StringUtils;
import com.takshine.wxcrm.base.util.UserUtil;
import com.takshine.wxcrm.base.util.ZJWKUtil;
import com.takshine.wxcrm.domain.DiscuGroup;
import com.takshine.wxcrm.domain.DiscuGroupTopic;
import com.takshine.wxcrm.domain.DiscuGroupUser;
import com.takshine.wxcrm.domain.MessagesExt;
import com.takshine.wxcrm.domain.Resource;
import com.takshine.wxcrm.domain.ResourceRela;
import com.takshine.wxcrm.domain.Tag;
import com.takshine.wxcrm.domain.WxuserInfo;
import com.takshine.wxcrm.message.error.CrmError;
/**
* 资料 页面控制器
*
* @author zhihe
*
*/
@Controller
@RequestMapping("/resource")
public class ResourceController
{
// 日志
protected static Logger logger = Logger.getLogger(ResourceController.class
.getName());
@Autowired
@Qualifier("cRMService")
private CRMService cRMService;
/**
* 查询 资料列表
*
* @param request
* @param response
* @return
* @throws Exception
*/
@RequestMapping("/list")
public String list(HttpServletRequest request, HttpServletResponse response)
throws Exception
{
logger.info("ResourceController-->in list");
request.setAttribute("filepath","http://"+PropertiesUtil.getAppContext("file.service") + PropertiesUtil.getAppContext("file.service.userpath").replace("/usr", "").replace("/zjftp","")+"/");
//查询对象
Resource res = new Resource();
res.setPagecounts(new Integer(999));
res.setCurrpages(new Integer(0));
//设置查询条件
//调用入口
String source = request.getParameter("source");
if (StringUtils.isNotNullOrEmptyStr(source))
{
String condition = request.getParameter("cond");
String dgid = request.getParameter("dgid");
request.setAttribute("source", source);
request.setAttribute("dgid", dgid);
if (StringUtils.isNotNullOrEmptyStr(condition))
{
if (!StringUtils.regZh(condition))
{
condition = new String(condition.getBytes("ISO-8859-1"), "UTF-8");
}
res.setResourceInfo3(condition);
}
}
else
{
request.setAttribute("source", "");
}
try
{
//获取用户信息
if (StringUtils.isNotNullOrEmptyStr(UserUtil.getCurrUser(request).getParty_row_id()))
{
res.setCreator(UserUtil.getCurrUser(request).getParty_row_id());
}
else
{
logger.error(ErrCode.ERR_MSG_1);
throw new Exception(ErrCode.ERR_MSG_UNBIND);
}
//获取传递过来的查询条件
String queryCond = request.getParameter("resourceInfo3");
if (StringUtils.isNotNullOrEmptyStr(queryCond))
{
res.setResourceInfo3(queryCond);
}
//标签上关联的文章id
String modelId = request.getParameter("modelId");
if (StringUtils.isNotNullOrEmptyStr(modelId))
{
res.setResourceId(modelId);
}
List<Resource>resList = cRMService.getDbService().getResourceService().findResourceListByFilter(res);
if (null != resList && !resList.isEmpty())
{
request.setAttribute("resList", resList);
//获取文章相关的标签
List<Tag> allResTag = new ArrayList<Tag>();
List<Tag> resItemList = null;
Tag tag = null;
for (Resource r : resList)
{
tag = new Tag();
tag.setModelId(r.getResourceId());
tag.setModelType("resource_tag");//标签类型
resItemList = cRMService.getDbService().getTagModelService().findTagListByModelId(tag);
r.setTagList(resItemList);
allResTag.addAll(resItemList);
if(StringUtils.isNotNullOrEmptyStr(r.getResourceUrl())){
String[] urls = r.getResourceUrl().split(",");
for(String url : urls){
r.getImgUrlList().add(url);
}
}
}
request.setAttribute("allResTag", allResTag);
//获取所有标签名,去重
ArrayList<String> tgNList = new ArrayList<String>();
for (Tag tg : allResTag)
{
if (!tgNList.contains(tg.getTagName()))
{
tgNList.add(tg.getTagName());
}
}
request.setAttribute("tgNList", tgNList);
}
else
{
request.setAttribute("resList", new ArrayList<Resource>());
request.setAttribute("resListSize", 0);
request.setAttribute("resTagList", new ArrayList<Resource>());
request.setAttribute("allResTag", new ArrayList<Tag>());
request.setAttribute("tgNList", new ArrayList<String>());
}
//获取系统推荐文章列表
res.setCreator(null);
List<Resource> sysList = this.getSysTopResources(res);
if (null != sysList && !sysList.isEmpty())
{
request.setAttribute("sysList", sysList);
}
else
{
request.setAttribute("sysList", new ArrayList<Resource>());
}
}
catch(Exception ex)
{
throw ex;
}
logger.info("ResourceController-->out list");
return "resource/list";
}
/**
* 根据查询条件查询对应的
* @param res
* @param request
* @param response
* @return
* @throws Exception
*/
@RequestMapping("/getTags")
@ResponseBody
public String getTags(HttpServletRequest request, HttpServletResponse response) throws Exception
{
return null;
}
/**
* 异步查询资料列表
*
* @param request
* @param response
* @return
* @throws Exception
*/
@RequestMapping("/rlist")
@ResponseBody
public String rlist(HttpServletRequest request, HttpServletResponse response)
throws Exception
{
return null;
}
/**
* 新增资料
*
* @param request
* @param response
* @return
* @throws Exception
*/
@RequestMapping("/add")
public String add(Resource obj, HttpServletRequest request,
HttpServletResponse response) throws Exception
{
ZJWKUtil.getRequestURL(request);//获取请求的url
//客户端类型
boolean isMobile = ZJWKUtil.isMobileAccess(request);
if(isMobile){
return "resource/add";
}else{
return "resource/pcadd";
}
}
/**
* 保存
*
* @param obj
* @param request
* @param response
* @return
* @throws Exception
*/
@RequestMapping(value = "/save", method = RequestMethod.POST)
@ResponseBody
public String save(Resource obj, HttpServletRequest request,
HttpServletResponse response) throws Exception
{
//返回值对象
CrmError retMess = new CrmError();
logger.info("ResourceController-->resource content == "+obj.getResourceContent());
logger.info("ResourceController-->resource resourceInfo1 == "+obj.getResourceInfo1());
if(!StringUtils.isNotNullOrEmptyStr(obj.getResourceTitle())){
if(StringUtils.isNotNullOrEmptyStr(obj.getResourceContent())){
if(obj.getResourceContent().length()>50){
obj.setResourceTitle(obj.getResourceContent().substring(0,50));
}else{
obj.setResourceTitle(obj.getResourceContent());
}
}
}
obj.setResourceId(Get32Primarykey.getRandom32PK());
obj.setCreator(UserUtil.getCurrUser(request).getParty_row_id());
int flg = cRMService.getDbService().getResourceService().addResource(obj);
if(flg ==1){
retMess.setErrorCode(ErrCode.ERR_CODE_0);
retMess.setRowId(obj.getResourceId());
}else{
retMess.setErrorCode(ErrCode.ERR_CODE__1);
retMess.setErrorMsg(ErrCode.ERR_MSG_FAIL);
}
return JSONObject.fromObject(retMess).toString();
}
/**
* 异步保存
* @param obj
* @param request
* @param response
* @return
* @throws Exception
*/
@RequestMapping(value = "/asynsave", method = RequestMethod.POST)
@ResponseBody
public String syncSave(Resource obj, HttpServletRequest request,
HttpServletResponse response) throws Exception
{
logger.info("ResourceController-->in asynsave");
//返回值对象
CrmError retMess = new CrmError();
//前台传递的url--粘贴链接
String url = request.getParameter("url");
String type = "other";
try
{
//获取当前用户
if(StringUtils.isNotNullOrEmptyStr(UserUtil.getCurrUser(request).getParty_row_id()))
{
obj.setCreator(UserUtil.getCurrUser(request).getParty_row_id());
if (StringUtils.isNotNullOrEmptyStr(url))
{
obj.setResourceUrl(url);
//判断url是否是微信体系
if (url.indexOf("weixin.qq") >0 || url.indexOf("WEIXIN.QQ")>0)
{
type = "wx";
}
if ("other".equals(type))
{
processOtherUrl(url,obj);
}
else if ("wx".equals(type))
{
//微信系统的文章
processWxUrl(url,obj);
}
//处理完成后保存后台
int ret = cRMService.getDbService().getResourceService().addResource(obj);
if (ret == 1)
{
retMess.setErrorCode(ErrCode.ERR_CODE_0);
retMess.setErrorMsg(ErrCode.ERR_MSG_SUCC);
}
else
{
retMess.setErrorCode(ErrCode.ERR_CODE__1);
retMess.setErrorMsg(ErrCode.ERR_MSG_FAIL);
}
}
else
{
retMess.setErrorCode(ErrCode.ERR_CODE__1);
retMess.setErrorMsg(ErrCode.ERR_MSG_FAIL);
}
}
else
{
//当前无登陆用户
retMess.setErrorCode(ErrCode.ERR_CODE_1001001);
retMess.setErrorMsg(ErrCode.ERR_MSG_UNBIND);
}
logger.info("ResourceController-->out asynsave");
}
catch(Exception ex)
{
logger.error(ex);
retMess.setErrorCode(ErrCode.ERR_CODE__1);
retMess.setErrorMsg(ErrCode.ERR_MSG_FAIL);
}
return JSONObject.fromObject(retMess).toString();
}
/**
* 预处理wx url,获取文档的标题和简要描述
* @param url
* @param res
*/
private void processWxUrl(String url, Resource res) throws Exception
{
StringBuffer temp = new StringBuffer();
try
{
HttpURLConnection uc = (HttpURLConnection)new URL(url). openConnection();
uc.setConnectTimeout(10000);
uc.setDoOutput(true);
uc.setRequestMethod("GET");
uc.setUseCaches(false);
InputStream in = new BufferedInputStream(uc.getInputStream());
Reader rd = new InputStreamReader(in, "UTF-8");
int c = 0;
while ((c = rd.read()) != -1)
{
temp.append((char) c);
}
try
{
//获取最后一个js脚本,获取链接相关信息
String info =temp.substring(temp.lastIndexOf("<script"),temp.length());
//拿到标题的起始位置
int title_post = info.indexOf("var msg_title");
//拿到描述的起始位置
int desc_post = info.indexOf("var msg_desc");
//拿到url的起始位置
int url_post = info.indexOf("var msg_cdn_url");
//截取后根据=分割获取值
String title_temp = info.substring(title_post,desc_post).split("=")[1];
String title = title_temp.substring(title_temp.indexOf("\"")+1,title_temp.lastIndexOf("\""));
res.setResourceTitle(title);
//截取后根据=分割获取值
String desc = info.substring(desc_post,url_post).split("=")[1];
res.setResourceContent(desc);
}
catch(Exception ex)
{
//如果无法获取标题和描述则直接使用登陆用户的信息
WxuserInfo query = new WxuserInfo();
query.setParty_row_id(res.getCreator());
WxuserInfo wxuser = cRMService.getWxService().getWxUserinfoService().getWxuserInfo(query);
if (null != wxuser)
{
res.setResourceTitle(wxuser.getNickname());
res.setResourceContent(url);
}
}
in.close();
}
catch (Exception e)
{
logger.error(e);
throw e;
}
}
/**
* 预处理other url,获取文档的标题和简要描述
* @param url
* @param res
*/
private void processOtherUrl(String url, Resource res) throws Exception
{
StringBuffer temp = new StringBuffer();
//登陆用户的信息
WxuserInfo query = new WxuserInfo();
query.setParty_row_id(res.getCreator());
WxuserInfo wxuser = cRMService.getWxService().getWxUserinfoService().getWxuserInfo(query);
try
{
HttpURLConnection uc = (HttpURLConnection)new URL(url). openConnection();
uc.setConnectTimeout(10000);
uc.setDoOutput(true);
uc.setRequestMethod("GET");
uc.setUseCaches(false);
InputStream in = new BufferedInputStream(uc.getInputStream());
Reader rd = new InputStreamReader(in, "UTF-8");
int c = 0;
while ((c = rd.read()) != -1)
{
temp.append((char) c);
}
try
{
//获取标题
if (temp.indexOf("<title") > 0)
{
String title_temp =temp.substring(temp.indexOf("<title"),temp.indexOf("</title>"));
String title =title_temp.substring(title_temp.indexOf(">")+1,title_temp.length());
if (StringUtils.isNotNullOrEmptyStr(title))
{
if (!StringUtils.regZh(title))
{
title = new String(title.getBytes("ISO-8859-1"), "UTF-8");
}
res.setResourceTitle(title);
}
else
{
res.setResourceTitle(wxuser.getNickname());
}
}
else
{
if (null != wxuser)
{
res.setResourceTitle(wxuser.getNickname());
}
}
//获取正文或描述等其他信息
String desc_text = "";
String desc_p = "";
if (temp.indexOf("<textarea") > 0)
{
String desc_text_temp = temp.substring(temp.indexOf("<textarea"),temp.indexOf("</textarea>"));
desc_text = desc_text_temp.substring(desc_text_temp.indexOf(">")+1,desc_text_temp.length());
}
if (temp.indexOf("<p") > 0)
{
String desc_p_temp = temp.substring(temp.indexOf("<p"),temp.indexOf("</p>"));
desc_p = desc_p_temp.substring(desc_p_temp.indexOf(">")+1,desc_p_temp.length());
}
if (StringUtils.isNotNullOrEmptyStr(desc_text))
{
if (StringUtils.isNotNullOrEmptyStr(desc_p))
{
if (desc_text.length() > desc_p.length())
{
res.setResourceContent(desc_text);
}
else
{
res.setResourceContent(desc_p);
}
}
else
{
res.setResourceContent(desc_text);
}
}
else
{
res.setResourceContent(url);
}
}
catch(Exception ex)
{
res.setResourceContent(url);
}
in.close();
}
catch (Exception e)
{
logger.error(e);
throw e;
}
}
/**
* 修改资料
*
* @param request
* @param response
* @return
*/
@RequestMapping("/upd")
public String update(Resource obj, HttpServletRequest request,
HttpServletResponse response) throws Exception {
return "redirect:/resource/list";
}
/**
* 删除资料
*
* @param request
* @param response
* @return
*/
@RequestMapping("/del")
@ResponseBody
public String delete(Resource obj, HttpServletRequest request,
HttpServletResponse response) throws Exception
{
logger.info("ResourceController-->in delete");
//返回值对象
CrmError retMess = new CrmError();
String type = request.getParameter("type");
//获取登陆用户信息
String userId = UserUtil.getCurrUser(request).getParty_row_id();
if (!StringUtils.isNotNullOrEmptyStr(userId))
{
retMess.setErrorCode(ErrCode.ERR_CODE_1001001);
retMess.setErrorMsg(ErrCode.ERR_MSG_UNBIND);
}
else
{
Resource res = new Resource();
//根据传入的操作类型处理单一删除或者批量删除
if ("single".equals(type))
{
String singleId = request.getParameter("id");//详情界面才会传递单一的id
res.setResourceId(singleId);
res.setResourceStatus("0");
res.setCreator(userId);
cRMService.getDbService().getResourceService().updateResourceById(res);
//资源删除 同步到讨论组
if(org.apache.commons.lang.StringUtils.isNotBlank(singleId)){
cRMService.getDbService().getDiscuGroupService().delDiscuGroupTopicByTopicId(singleId);
}
}
else if ("mulit".equals(type))
{
//获取需要删除的资料id
String delList = request.getParameter("delIds");
String ids[] = delList.substring(0,delList.length()-1).split(",");
for (String id : ids)
{
res.setResourceId(id);
res.setResourceStatus("0");
res.setCreator(userId);
cRMService.getDbService().getResourceService().updateResourceById(res);
//资源删除 同步到讨论组
if(org.apache.commons.lang.StringUtils.isNotBlank(id)){
cRMService.getDbService().getDiscuGroupService().delDiscuGroupTopicByTopicId(id);
}
}
}
retMess.setErrorCode(ErrCode.ERR_CODE_0);
retMess.setErrorMsg(ErrCode.ERR_MSG_SUCC);
}
logger.info("ResourceController-->out delete");
return JSONObject.fromObject(retMess).toString();
}
/**
* 资料详情
*
* @param request
* @param response
* @return
*/
@RequestMapping("/detail")
public String detail(HttpServletRequest request, HttpServletResponse response)
throws Exception
{
ZJWKUtil.getRequestURL(request);
logger.info("ResourceController-->in detail");
String url = request.getParameter("resurl");
String id = request.getParameter("id");
String resType = request.getParameter("restype");
String isSys = request.getParameter("isSys");
logger.info("ResourceController-->in detail id is:" + id);
//根据id查询文章详情
//拿详情
Resource query = new Resource();
query.setResourceId(id);
query.setPagecounts(new Integer(999));
query.setCurrpages(new Integer(0));
List<Resource> retList = cRMService.getDbService().getResourceService().findResourceListByFilter(query);
if (null != retList && !retList.isEmpty())
{
Resource res = retList.get(0);
request.setAttribute("res", retList.get(0));
//根据资源类型返回对应的值
if ("link".equals(res.getResourceType()))
{
if (StringUtils.isNotNullOrEmptyStr(url))
{
request.setAttribute("resourceUrl", url);
}
else
{
request.setAttribute("resourceUrl", res.getResourceUrl());
}
}
else if ("img".equals(res.getResourceType()))
{
//拿所有图片
MessagesExt mext = new MessagesExt();
mext.setRelaid(id);
mext.setPagecounts(new Integer(999));
mext.setCurrpages(new Integer(0));
List<MessagesExt>imgList = cRMService.getDbService().getResourceService().getAllMessagesExtByRelaId(mext);
if (null != imgList && !imgList.isEmpty())
{
request.setAttribute("imgList", imgList);
}
else
{
request.setAttribute("imgList", new ArrayList<MessagesExt>());
}
}
else if ("timg".equals(res.getResourceType())) //图文列表(PC端新建文章)
{
}
else
{
throw new Exception("数据不正确");
}
//页面按钮控制
boolean ispraise = false;
if (UserUtil.hasCurrUser(request))
{
String userId = UserUtil.getCurrUser(request).getParty_row_id();
//优先判断是不是自己进入
if (userId.equals(res.getCreator()))
{
//如果是自己,判断是否是系统的
if (StringUtils.isNotNullOrEmptyStr(isSys))
{
request.setAttribute("discuBtn", true);
request.setAttribute("openBtn", false);
}
else
{
request.setAttribute("discuBtn", true);
request.setAttribute("openBtn", true);
}
}
else
{
if (StringUtils.isNotNullOrEmptyStr(isSys))
{
//不是自己,但是系统的
request.setAttribute("backBtn", true);
request.setAttribute("saveBtn", true);
request.setAttribute("nextBtn", true);
}
else
{
//不是自己,也不是系统的
request.setAttribute("saveBtn", true);
request.setAttribute("backBtn", false);
request.setAttribute("nextBtn", false);
}
}
//是否允许点赞
if (StringUtils.isNotNullOrEmptyStr(UserUtil.getCurrUserId(request)))
{
ispraise = true;
request.setAttribute("userId", UserUtil.getCurrUserId(request));
}
// 点赞统计
ActivityPrint ap2 = new ActivityPrint();
ap2.setActivityid(id);
ap2.setType("PRAISE");
int praiseCount = cRMService.getDbService().getActivityPrintService().countObjByFilter(ap2);//点赞数
if (praiseCount > 0)
{
request.setAttribute("praiseCount", praiseCount);
}
else
{
request.setAttribute("praiseCount", 0);
}
//List<ActivityPrint> praiseList = cRMService.getDbService().getActivityPrintService().searchActivityPrintList(ap2);// 点赞列表
//是否已点赞
ap2.setSourceid(UserUtil.getCurrUserId(request));
if (cRMService.getDbService().getActivityPrintService().countObjByFilter(ap2) > 0)
{
ispraise = false;
}
request.setAttribute("ispraise", ispraise);
}
else
{
request.setAttribute("discuBtn", false);
request.setAttribute("openBtn", false);
request.setAttribute("backBtn", false);
request.setAttribute("saveBtn", false);
request.setAttribute("nextBtn", true);
}
request.setAttribute("resId", id);
if (StringUtils.isNotNullOrEmptyStr(resType))
{
request.setAttribute("resType", resType);
}
else
{
request.setAttribute("resType", res.getResourceType());
}
request.setAttribute("isSys", isSys);
request.setAttribute("filepath","http://"+PropertiesUtil.getAppContext("file.service") + PropertiesUtil.getAppContext("file.service.userpath").replace("/usr", "").replace("/zjftp","")+"/");
//打开详情则增加一次浏览量
this.processRes(res,"explorer");
//判断是否显示查看原文按钮
if(StringUtils.isNotNullOrEmptyStr(res.getResourceUrl()) && res.getResourceUrl().indexOf("mp.weixin.qq.com") > 0)
{
request.setAttribute("originBtn", true);
}
else
{
request.setAttribute("originBtn", false);
}
//short url
request.setAttribute("shorturl", PropertiesUtil.getAppContext("zjwk.short.url") + ZJWKUtil.shortUrl(PropertiesUtil.getAppContext("app.content")+"/resource/detail?id="+query.getResourceId()));
//获取系统推荐文章
Resource r = new Resource();
r.setCurrpages(new Integer(0));
r.setPagecounts(new Integer(3));
r.setNotinresid(id);
List<Resource> resList = cRMService.getDbService().getResourceService().findResourceBySys(r);
if (null != resList && resList.size()>0)
{
request.setAttribute("sysList", resList);
}
else
{
request.setAttribute("sysList", new ArrayList<Resource>());
}
logger.info("ResourceController-->out detail");
return "resource/detail";
}
else
{
throw new Exception("未找到对应的数据");
}
}
/**
* 下一篇
*
* @param request
* @param response
* @return
*/
@RequestMapping("/nextFromSys")
public String nextFromSys(HttpServletRequest request, HttpServletResponse response)
throws Exception
{
logger.info("ResourceController-->in nextFromSys");
Resource retRes = null;//需要返回的文章
int allSysCount = 0;
int allReadCount = 0;
int myselfCount = 0;
String id = request.getParameter("resid");
String isSys = request.getParameter("isSys");
String creator = request.getParameter("creator");
//页面按钮控制
String userId = UserUtil.getCurrUser(request).getParty_row_id();
//获取session中已有的文章id
String readIds = (String)(request.getSession().getAttribute("READ_RESOURCE_IDS") == null ? "":request.getSession().getAttribute("READ_RESOURCE_IDS"));
if (StringUtils.isNotNullOrEmptyStr(readIds))
{
readIds += "," + id;
}
else
{
readIds = id;
}
request.getSession().setAttribute("READ_RESOURCE_IDS", readIds);//再次保存
String idList[] = readIds.split(",");
allReadCount =idList.length;
//查询当前文章作者的系统推荐的文章
Resource res = new Resource();
res.setPagecounts(new Integer(999));
res.setCurrpages(new Integer(0));
res.setCreator(creator);
List<Resource> sysListByCreator = this.getSysTopResources(res);
//查询当前文章作者的系统推荐的文章
Resource res_sys = new Resource();
res_sys.setPagecounts(new Integer(999));
res_sys.setCurrpages(new Integer(0));
List<Resource> sysList = this.getSysTopResources(res_sys);
allSysCount = sysList.size();
//查询当前用户的系统推荐文章
Resource res_my = new Resource();
res_my.setPagecounts(new Integer(999));
res_my.setCurrpages(new Integer(0));
res_my.setCreator(userId);
List<Resource> myList = this.getSysTopResources(res_my);
myselfCount = myList.size();
if (sysListByCreator != null && !sysListByCreator.isEmpty())
{
for (Resource temp : sysListByCreator)
{
boolean flag = false;
for (String tempId : idList)
{
if (temp.getResourceId().equals(tempId))
{
flag = true;
break;
}
}
if (flag)
{
continue;
}
retRes = new Resource();
retRes = temp;
break;
}
}
//如果在该作者下面没有新的下一篇,则在所有的系统推荐里面找
if (null == retRes)
{
if (sysList != null && !sysList.isEmpty())
{
for (Resource temp : sysList)
{
boolean flag = false;
for (String tempId : idList)
{
if (temp.getResourceId().equals(tempId))
{
flag = true;
break;
}
}
//已阅读的跳过
if (flag)
{
continue;
}
//如果是自己推荐出来的文章,默认跳过
if (temp.getCreator().equals(userId))
{
continue;
}
//没阅读过,也不是自己推荐的系统文章,返回
retRes = new Resource();
retRes = temp;
break;
}
}
}
if((allReadCount +1 >= (allSysCount - myselfCount)))
{
request.setAttribute("lastFlag", true);
request.getSession().removeAttribute("READ_RESOURCE_IDS");
}
request.setAttribute("res", retRes);
//根据资源类型返回对应的值
if ("link".equals(retRes.getResourceType()))
{
request.setAttribute("resourceUrl", retRes.getResourceUrl());
}
else if ("img".equals(retRes.getResourceType()))
{
//拿所有图片
MessagesExt mext = new MessagesExt();
mext.setRelaid(retRes.getResourceId());
mext.setPagecounts(new Integer(999));
mext.setCurrpages(new Integer(0));
List<MessagesExt>imgList = cRMService.getDbService().getResourceService().getAllMessagesExtByRelaId(mext);
if (null != imgList && !imgList.isEmpty())
{
request.setAttribute("imgList", imgList);
}
}
else
{
throw new Exception(ErrCode.ERR_CODE_100007001);//没有找到数据
}
//优先判断是不是自己进入
if (userId.equals(retRes.getCreator()))
{
//如果是自己,判断是否是系统的
if (StringUtils.isNotNullOrEmptyStr(isSys))
{
request.setAttribute("discuBtn", true);
request.setAttribute("openBtn", false);
}
else
{
request.setAttribute("discuBtn", true);
request.setAttribute("openBtn", true);
}
}
else
{
if (StringUtils.isNotNullOrEmptyStr(isSys))
{
//不是自己,但是系统的
request.setAttribute("backBtn", true);
request.setAttribute("saveBtn", true);
request.setAttribute("nextBtn", true);
}
else
{
//不是自己,也不是系统的
request.setAttribute("saveBtn", true);
request.setAttribute("backBtn", false);
request.setAttribute("nextBtn", false);
}
}
//判断是否显示查看原文按钮
if(null != retRes.getResourceUrl() && retRes.getResourceUrl().indexOf("mp.qq.com") > 0)
{
request.setAttribute("originBtn", true);
}
else
{
request.setAttribute("originBtn", false);
}
request.setAttribute("resId", retRes.getResourceId());
request.setAttribute("resType", retRes.getResourceType());
request.setAttribute("isSys", isSys);
request.setAttribute("filepath","http://"+PropertiesUtil.getAppContext("file.service") + PropertiesUtil.getAppContext("file.service.userpath").replace("/usr", "").replace("/zjftp","")+"/");
//打开详情则增加一次浏览量
this.processRes(retRes,"explorer");
//short url
request.setAttribute("shorturl", PropertiesUtil.getAppContext("zjwk.short.url") + ZJWKUtil.shortUrl(PropertiesUtil.getAppContext("app.content")+"/entr/access?parentId="+retRes.getResourceId()+"&parentType=resource"));
logger.info("ResourceController-->out nextFromSys");
return "resource/detail";
}
/**
* 显示讨论组
* @param request
* @param response
* @return
*/
@RequestMapping("/showDiscu")
public String showDiscu(HttpServletRequest request,
HttpServletResponse response) throws Exception
{
logger.info("ResourceController-->in showDiscu");
//缓存文章id
String resId = request.getParameter("resid");
request.setAttribute("resId", resId);
//缓存文章类型
String resType = request.getParameter("restype");
request.setAttribute("resType", resType);
//缓存文章url resType为link时才有值
String resUrl = request.getParameter("resurl");
request.setAttribute("resUrl", resUrl);
//获取登陆用户
String partyId = null;
if (StringUtils.isNotNullOrEmptyStr(UserUtil.getCurrUser(request).getParty_row_id()))
{
partyId = UserUtil.getCurrUser(request).getParty_row_id();
}
else
{
logger.error(ErrCode.ERR_MSG_UNBIND);
throw new Exception(ErrCode.ERR_CODE_1001001);
}
//获取登陆用户发起和参与的讨论组信息
DiscuGroup dg = new DiscuGroup();
//传递了查询条件
String condition = request.getParameter("condition");
if (StringUtils.isNotNullOrEmptyStr(condition))
{
dg.setName(condition);
}
dg.setCreator(partyId);
List<DiscuGroup>dgList = cRMService.getDbService().getDiscuGroupService().findJoinDiscuGroupList(dg);
if (null != dgList && !dgList.isEmpty())
{
request.setAttribute("dgList", dgList);
}
//响应界面
logger.info("ResourceController-->out showDiscu");
return "resource/resDiscu";
}
/**
* 推荐到讨论组
* @param request
* @param response
* @return
*/
@RequestMapping("/pushDiscu")
@ResponseBody
public String pushDiscu(HttpServletRequest request,
HttpServletResponse response) throws Exception
{
logger.info("ResourceController-->in pushDiscu");
CrmError ret = new CrmError();
//选择的讨论组id
String selectIds = request.getParameter("selectIds");
String messageType = request.getParameter("type");
String resId = request.getParameter("resId");
ArrayList<String> succIds = new ArrayList<String>();
ArrayList<String> failIds = new ArrayList<String>();
//获取登陆用户
String partyId = null;
if (StringUtils.isNotNullOrEmptyStr(UserUtil.getCurrUser(request).getParty_row_id()))
{
partyId = UserUtil.getCurrUser(request).getParty_row_id();
//循环
DiscuGroupTopic dgt = null;
String ids[] = selectIds.substring(0,selectIds.length()-1).split(",");
for(String id : ids)
{
dgt = new DiscuGroupTopic();
dgt.setCreator(partyId);
dgt.setDis_id(id);
dgt.setTopic_id(resId);
dgt.setTopic_type("article");
dgt.setTopic_status("audited");
ret = cRMService.getDbService().getDiscuGroupService().addDiscuGroupTopic(dgt);
if (null != ret && ErrCode.ERR_CODE_0.equals(ret.getErrorCode()))
{
succIds.add(id);
continue;
}
else
{
failIds.add(id);
break;
}
}
//完成关系建立,开始针对成功的讨论组发送消息
if (!succIds.isEmpty())
{
//发送消息
logger.info("选择的消息类型:" + messageType);
for (int i=0;i<succIds.size();i++)
{
HashMap<String, Object> inparams = new HashMap<String, Object>();
DiscuGroupUser dgu = new DiscuGroupUser();
dgu.setDis_id(succIds.get(i));
List<?> dguList = cRMService.getDbService().getDiscuGroupUserService().findObjListByFilter(dgu);
String content = UserUtil.getCurrUser(request).getName() + "在讨论组[dis_name]分享了新的话题,点击进入该讨论组查看";
String url = "/discuGroup/detail?rowId=" + succIds.get(i);
inparams.put("users", dguList);
inparams.put("content", content);
inparams.put("url", url);
this.sendMessage(inparams);
}
}
ret.setErrorCode(ErrCode.ERR_CODE_0);
ret.setErrorMsg(ErrCode.ERR_MSG_SUCC);
if (!failIds.isEmpty())
{
ret.setRowCount(""+failIds.size());
}
}
else
{
ret.setErrorCode(ErrCode.ERR_CODE_1001001);
ret.setErrorMsg(ErrCode.ERR_MSG_UNBIND);
}
logger.info("ResourceController-->out pushDiscu");
//返回
return JSONObject.fromObject(ret).toString();
}
/**
* 公开推荐
* @param request
* @param response
* @return
*/
@RequestMapping("/pushToSys")
@ResponseBody
public String pushToSys(HttpServletRequest request,HttpServletResponse response) throws Exception
{
logger.info("ResourceController-->in pushToSys");
String retStr = "0";
String resId = request.getParameter("id");
Resource res = new Resource();
try
{
res.setResourceId(resId);
res.setCreator(UserUtil.getCurrUser(request).getParty_row_id());
//推荐前先校验是否已被推荐
List<Resource> resList = cRMService.getDbService().getResourceService().findResourceListByFilter(res);
Resource temp = new Resource();
if (null != resList && resList.size()>0)
{
temp = resList.get(0);
//如果该文章已推荐
if ("public".equals(temp.getResourceInfo2()))
{
retStr = "2";//文章已推荐
}
else
{
res.setResourceInfo2("public");//公开推荐标识
cRMService.getDbService().getResourceService().updateResourceById(res);
}
}
else
{
retStr = "1";//未找到对应的记录
}
//待处理,增加操作轨迹
}
catch(Exception ex)
{
logger.error(ex);
retStr = "1";//异常
}
//返回
logger.info("ResourceController-->out pushToSys");
return retStr;
}
/**
* 获取系统推荐文章
* @return
*/
private List<Resource> getSysTopResources(Resource res)
{
return cRMService.getDbService().getResourceService().findResourceBySys(res);
}
/**
* 收藏系统文章
* @param request
* @param response
* @return
*/
@RequestMapping("/saveFromSys")
@ResponseBody
public String saveFromSys(HttpServletRequest request,HttpServletResponse response) throws Exception
{
String resId = request.getParameter("resId");
//查询文章详情
Resource query = new Resource();
query.setResourceId(resId);
query.setPagecounts(new Integer(999));
query.setCurrpages(new Integer(0));
List<Resource> retList = cRMService.getDbService().getResourceService().findResourceListByFilter(query);
if (null != retList && !retList.isEmpty())
{
Resource tempRes = retList.get(0);
Resource newRes = new Resource();
newRes.setResourceId(Get32Primarykey.getRandom32PK());
//创建者为当前登陆用户
newRes.setCreator(UserUtil.getCurrUser(request).getParty_row_id());
//从系统文章中获取标题、内容、url、类型
newRes.setResourceTitle(tempRes.getResourceTitle());
newRes.setResourceContent(tempRes.getResourceContent());
newRes.setResourceUrl(tempRes.getResourceUrl());
newRes.setResourceType(tempRes.getResourceType());
//根据title判断重复
Resource searRes = new Resource();
searRes.setResourceTitle(tempRes.getResourceTitle());
searRes.setCreator(UserUtil.getCurrUser(request).getParty_row_id());
searRes.setResourceUrl(tempRes.getResourceUrl());
List<Resource> objSearRes = (List<Resource>)cRMService.getDbService().getResourceService().findObjListByFilter(searRes);
int retInt = 0;
if(objSearRes.size() == 0){
retInt = cRMService.getDbService().getResourceService().addResource(newRes);
}else{
retInt = 2;
}
//为1则保存成功
if (retInt == 1)
{
//拿到文章所有的图片关系,如果有则新增一套关系
MessagesExt mext = new MessagesExt();
mext.setRelaid(resId);
mext.setPagecounts(new Integer(999));
mext.setCurrpages(new Integer(0));
List<MessagesExt>imgList = cRMService.getDbService().getResourceService().getAllMessagesExtByRelaId(mext);
if (null != imgList && !imgList.isEmpty())
{
MessagesExt newMext = new MessagesExt();
for (MessagesExt temp : imgList)
{
newMext.setRelaid(newRes.getResourceId());
newMext.setFilename(temp.getFilename());
newMext.setFiletype(temp.getFiletype());
newMext.setSource_filename(temp.getSource_filename());
newMext.setRelatype(temp.getRelatype());
cRMService.getDbService().getMessagesExtService().addObj(newMext);
}
}
//收藏成功则在原文章关系表中增加收藏量
this.processRes(tempRes, "save");
}
else if (retInt == 2)
{
return "2";
}
else
{
return "1";
}
}
return "0";//成功
}
/**
* 查询系统文章列表
*
* @param request
* @param response
* @return
* @throws Exception
*/
@RequestMapping("/syslist")
public String syslist(HttpServletRequest request, HttpServletResponse response)
throws Exception
{
logger.info("ResourceController-->in syslist");
//查询对象
Resource res = new Resource();
//查询条件
String condition = request.getParameter("resourceInfo3");
//分页
String currpage = request.getParameter("currpage");
if (StringUtils.isNotNullOrEmptyStr(currpage))
{
res.setCurrpages(Integer.valueOf(currpage) * new Integer(10) + 1);
res.setPagecounts(res.getCurrpages() - 1 + new Integer(10));
}
else
{
res.setCurrpages(new Integer(0));
res.setPagecounts(new Integer(10));
currpage = "0";
}
if (StringUtils.isNotNullOrEmptyStr(condition))
{
if (!StringUtils.regZh(condition))
{
condition = new String(condition.getBytes("ISO-8859-1"), "UTF-8");
}
res.setResourceInfo3(condition);
}
try
{
List<Resource>resList = cRMService.getDbService().getResourceService().findResourceBySys(res);
if (null != resList && !resList.isEmpty())
{
request.setAttribute("sysList", resList);
}
else
{
request.setAttribute("sysList", new ArrayList<Resource>());
}
request.setAttribute("currpage", currpage);
request.setAttribute("filepath","http://"+PropertiesUtil.getAppContext("file.service") + PropertiesUtil.getAppContext("file.service.userpath").replace("/usr", "").replace("/zjftp","")+"/");
}
catch(Exception ex)
{
throw ex;
}
logger.info("ResourceController-->out syslist");
return "resource/syslist";
}
/**
*
* @param request
* @param response
* @return
* @throws Exception
*/
@RequestMapping("/syncsyslist")
@ResponseBody
public String syncsyslist(HttpServletRequest request, HttpServletResponse response)
throws Exception
{
logger.info("ResourceController-->in syslist");
//查询对象
Resource res = new Resource();
//分页
String currpages = request.getParameter("currpages");
String pagecounts = request.getParameter("pagecounts");
if (StringUtils.isNotNullOrEmptyStr(currpages))
{
res.setCurrpages(Integer.valueOf(currpages));
}
else
{
res.setCurrpages(new Integer(0));
}
if (StringUtils.isNotNullOrEmptyStr(pagecounts))
{
res.setPagecounts(Integer.valueOf(pagecounts));
}
else
{
res.setPagecounts(new Integer(10));
}
try
{
List<Resource>resList = cRMService.getDbService().getResourceService().findResourceBySys(res);
if (null != resList && !resList.isEmpty())
{
return JSONArray.fromObject(resList).toString();
}
}
catch(Exception ex)
{
throw ex;
}
logger.info("ResourceController-->out syncsyslist");
return "";
}
/**
* 浏览文章后,增加浏览次数
* @param res
*/
public void processRes(Resource res, String type)
{
logger.info("ResourceController-->in explorRes");
ResourceRela rela = new ResourceRela();
rela.setRelaResourceId(res.getResourceId());
rela.setRelaUserId(res.getCreator());
if ("explorer".equals(type))
{
rela.setRelaExploreNum("1");
}
else if ("save".equals(type))
{
rela.setRelaInfo1("1");
}
else if ("share".equals(type))
{
rela.setRelaInfo2("1");
}
cRMService.getDbService().getResourceService().updateResourceRelaById(rela);
logger.info("ResourceController-->out explorRes");
}
/**
* 发送微信通知
* @param inparams
*/
public void sendMessage(HashMap<String, Object> inparams)
{
if (!inparams.isEmpty())
{
String redirectUrl = (String)inparams.get("url");
String content = (String)inparams.get("content");
List<DiscuGroupUser> users = (List<DiscuGroupUser>)inparams.get("users");
String type = (String)inparams.get("messageType");
if (!com.takshine.wxcrm.base.util.StringUtils.isNotNullOrEmptyStr(type))
{
type = "auto";
}
if ("auto".equals(type))
{
for(DiscuGroupUser user : users)
{
content = content.replace("dis_name", "测试");
cRMService.getWxService().getWxRespMsgService().respCommCustMsgByOpenId("oEImns7oxhKcCwKq-vPJ_6DvORUQ",null,null,content,redirectUrl);
/*Map<String, String> map = RedisCacheUtil.getStringMapAll(Constants.LOGINTIME_KEY+ "_" +user.getUser_id());
if(null!=map&&map.keySet().size()>0)
{
String relaOpenId = (String)map.get("openId");
String loginTime = (String)map.get("loginTime");
String differtime = 172800000+"";//48小时
if(!com.takshine.wxcrm.base.util.StringUtils.isNotNullOrEmptyStr(loginTime)&&DateTime.comDate(loginTime, differtime, DateTime.DateTimeFormat1))
{
content = content.replace("dis_name", "测试");
cRMService.getWxService().getWxRespMsgService().respCommCustMsgByOpenId(relaOpenId,null,null,content,redirectUrl);
}
}*/
}
}
else if ("mail".equals(type))
{
}
else if ("weixin".equals(type))
{
}
else if ("message".equals(type))
{
/*for(DiscuGroupUser user : users)
{
Map<String, String> map = RedisCacheUtil.getStringMapAll(Constants.LOGINTIME_KEY+ "_" +user.getUser_id());
if(null!=map&&map.keySet().size()>0){
String relaOpenId = (String)map.get("openId");
String loginTime = (String)map.get("loginTime");
String differtime = 172800000+"";//48小时
//若48小时未登录,则发送短信(20150204 短信模板没有定下来 暂时处理)
if(com.takshine.wxcrm.base.util.StringUtils.isNotNullOrEmptyStr(loginTime)&&DateTime.comDate(loginTime, differtime, DateTime.DateTimeFormat1)){
String url = PropertiesUtil.getMsgContext("service.url1");
String sn = PropertiesUtil.getMsgContext("service.sn");
String pwd = PropertiesUtil.getMsgContext("service.pwd");
pwd = MD5Util.getMD5(sn+pwd);
String msg = PropertiesUtil.getMsgContext("message.model3");
String signature = PropertiesUtil.getMsgContext("msg.signature");
String msgmodule = URLEncoder.encode(msg+signature, "utf-8");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new NameValuePair("sn", sn));
params.add(new NameValuePair("pwd",pwd));
params.add(new NameValuePair("mobile", str.split(",")[1]));
params.add(new NameValuePair("content",msgmodule));
params.add(new NameValuePair("ext", ""));
params.add(new NameValuePair("stime", ""));
params.add(new NameValuePair("rrid", ""));
params.add(new NameValuePair("msgfmt", ""));
HttpClient3Post.request(url, params.toArray(new NameValuePair[params.size()]));
}else{//微信推送消息
cRMService.getWxService().getWxRespMsgService().respCommCustMsgByOpenId(relaOpenId,null,null,content,url);
}
}
}*/
}
}
}
/*public static void main(String[] args)
{
StringBuffer temp = new StringBuffer();
try
{
//String url = "http://mp.weixin.qq.com/s?__biz=MzA5NzEzNjIwMQ==&mid=200319795&idx=3&sn=4ecd5fab9f572c12c0d3054f574b6a24&scene=2#rd";
String url = "http://mp.weixin.qq.com/mp/appmsg/show?__biz=MjM5NDkzNTg2MQ==&appmsgid=200081705&itemidx=3&sign=35149432f15bcd3313050b7900673022&scene=2";
HttpURLConnection uc = (HttpURLConnection)new URL(url).
openConnection();
uc.setConnectTimeout(10000);
uc.setDoOutput(true);
uc.setRequestMethod("GET");
uc.setUseCaches(false);
InputStream in = new BufferedInputStream(uc.getInputStream());
Reader rd = new InputStreamReader(in, "UTF-8");
int c = 0;
while ((c = rd.read()) != -1) {
temp.append((char) c);
}
String info =temp.substring(temp.lastIndexOf("<script"),temp.length());
//System.out.println(info);
int title_post = info.indexOf("var msg_title");
System.out.println("var msg_title:" + title_post);
int desc_post = info.indexOf("var msg_desc");
System.out.println("var msg_desc:" + desc_post);
int url_post = info.indexOf("var msg_cdn_url");
System.out.println("var msg_cdn_url:" + url_post);
String title = info.substring(title_post,desc_post).split("=")[1];
System.out.println(title);
String desc = info.substring(desc_post,url_post).split("=")[1];
System.out.println(desc);
in.close();
} catch (Exception e)
{
e.printStackTrace();
}
}*/
@RequestMapping("/resInit")
@ResponseBody
public String resInit(HttpServletRequest request,HttpServletResponse response) throws Exception
{
CatchPicture.initResourceImg(cRMService);
return "resource/init";
}
}
|
package com.libedi.demo.repository.order;
import org.springframework.data.jpa.repository.JpaRepository;
import com.libedi.demo.domain.order.Order;
/**
* OrderRepository
*
* @author Sang-jun, Park
* @since 2019. 09. 10
*/
public interface OrderRepository extends JpaRepository<Order, Long> {
}
|
package no.hiof.larseknu.varargs;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Random;
public class Main {
public static void main(String[] args) {
// Kaller summer-metode med 2 argumenter
System.out.println(summer(5, 6));
// Kaller summer-metode med 3 argumenter
System.out.println(summer(5, 6, 6));
// Kaller summer-metode med ukjent antall int-verdier (når vi kommer over 3)
System.out.println(summer(5, 6, 6, 6));
// Kaller doMath-matode som først tar en string, så et ukjent antall int-verdier
System.out.println(doMath("-", 5, 6, 6, 6));
// Sjekker om et tilfeldig tall vi generer er over eller under ti ved hjelp av en "hurtig-if)
String tall = (10 < new Random().nextInt() ? "over ti" : "under ti");
// Kaller string-format med forskjellige typer argumenter
// Argumentene etter den første stringen blir lagt inn der vi har satt specifiers (%s, %d) etc.
System.out.println(String.format("Dette er en %s med mange argumenter %tY + %d, %s",
"string", LocalDate.of(2016, 2, 2), 2, tall));
// En litt enklere versjon
// Argumentene etter den første stringen blir lagt inn der vi har satt specifiers (%s, %d) etc.
System.out.println(String.format("Dette er en %s som tar varargs %d, %d", "string", 42, 9001));
}
// Summer-metode som tar to int verdier
public static int summer(int a, int b) {
return summer(a, b, 0);
}
// Summer-metode som tar tre int verdier
public static int summer(int a, int b, int c) {
return a + b + c;
}
// Summer-metode som tar et ukjent antall int-verdier
public static int summer(int... tall) {
int sum = 0;
for (int etTall : tall) {
sum += etTall;
}
return sum;
}
// doMath metode som først tar matteOperasjon som vil si + - etc., for så et ukjent antall int-verdier
public static int doMath(String matteOperasjon, int... tall) {
// Sjekker hva vi skal gjøre, summere eller substrahere
switch (matteOperasjon) {
case "+":
// bruker summer-metoden vi allerede har
return summer(tall);
case "-":
int sum = 0;
for (int etTall : tall)
sum -= etTall;
return sum;
}
return 0;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.