text stringlengths 10 2.72M |
|---|
package addview.utils;
import android.os.Environment;
import java.io.File;
/**
* @author 673391138@qq.com
* @since 17/5/9
* 主要功能:
*/
public class HkcFileHelper {
public static void getRootDir(){
File root = Environment.getExternalStorageDirectory();
if(root == null || !root.exists()){
HkcLog.d("root is null !");
return;
}
File[] files = root.listFiles();
}
}
|
package com.nfet.icare.controller;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.nfet.icare.pojo.DeviceCount;
import com.nfet.icare.pojo.FaultCount;
import com.nfet.icare.pojo.Fix;
import com.nfet.icare.pojo.Mgr_Fix;
import com.nfet.icare.pojo.Mgr_Warranty;
import com.nfet.icare.pojo.User;
import com.nfet.icare.service.FixServiceImpl;
import com.nfet.icare.service.UserServiceImpl;
import com.nfet.icare.util.GlobalMethods;
/**
* 报修统计
* 1、报修统计
* 2、客户报修订单
*/
//报修统计
@Controller
@RequestMapping("/mgr")
public class Mgr_FixController {
Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private FixServiceImpl fixServiceImpl;
@Autowired
private UserServiceImpl userServiceImpl;
//报修统计
@RequestMapping("/fixStatistics")
@ResponseBody
public Map<String, Object> fixStatistics() {
Map<String, Object> fixMap = new HashMap<>();
FaultCount faultCount = new FaultCount();
List<Fix> fixList = new ArrayList<>();
List<FaultCount> faultCounts = new ArrayList<>();
List<FaultCount> newFaultCounts = new ArrayList<>();
List<DeviceCount> deviceCounts = new ArrayList<>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
int [] countArr = new int[7];
int [] sumArr = new int[7];
String[] nameStr=new String[5];
String[] typeStr=new String[10];
//折线统计
fixList = fixServiceImpl.fixList();
String[] weekStr = GlobalMethods.weekDays();
int sum = fixServiceImpl.sevenCounts(weekStr[0]);
for (int i = 0; i < 7; i++) {
for (Fix fix : fixList) {
//总报修
Date date = new Date(fix.getOrderTime().getTime());
if (sdf.format(date).equals(weekStr[i])) {
sum ++;
}
//新增报修
if (fix.getOrderTime().toString().indexOf(weekStr[i]) != -1) {
countArr[i] ++;
}
}
sumArr[i] = sum;
}
//扇形统计(故障类型)
faultCounts = fixServiceImpl.faultCounts();
if (faultCounts.size()<=4) {
fixMap.put("faultCounts", faultCounts);
//故障名称
for (int i = 0; i < faultCounts.size(); i++) {
nameStr[i] = faultCounts.get(i).getName();
}
}
else {
for (int i = 0; i < 4; i++) {
newFaultCounts.add(faultCounts.get(i));
}
faultCount.setName("其他");
faultCount.setValue(fixList.size()-faultCounts.get(0).getValue()-faultCounts.get(1).getValue()-faultCounts.get(2).getValue()-faultCounts.get(3).getValue());
newFaultCounts.add(faultCount);
//故障名称
for (int i = 0; i < newFaultCounts.size(); i++) {
nameStr[i] = newFaultCounts.get(i).getName();
}
fixMap.put("faultCounts", newFaultCounts);
}
//扇形统计(设备型号)
deviceCounts = fixServiceImpl.deviceCounts();
//型号名称
for (int i = 0; i < deviceCounts.size(); i++) {
typeStr[i] = deviceCounts.get(i).getName();
}
// //将一周的时间格式从年月日改为月日
// for (int i = 0; i < weekStr.length; i++) {
// String string = weekStr[i].substring(5);
// weekStr[i] = string;
// }
fixMap.put("weekStr", weekStr);
fixMap.put("nameStr", nameStr);
fixMap.put("typeStr", typeStr);
fixMap.put("countArr", countArr);
fixMap.put("sumArr", sumArr);
fixMap.put("deviceCounts", deviceCounts);
return fixMap;
}
//客户报修订单
@RequestMapping("/allFixOrder")
@ResponseBody
public List<Mgr_Fix> allFixOrder() throws ParseException{
List<Mgr_Fix> allFixOrder = new ArrayList<>();
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
int num = 1;
allFixOrder = fixServiceImpl.allFixOrder();
for (Mgr_Fix mgr_Fix : allFixOrder) {
//加序号
mgr_Fix.setNum(num);
num ++;
//维修方式
if (mgr_Fix.getFixPattern() == 0) {
mgr_Fix.setFixPatternStr("上门");
}
else {
mgr_Fix.setFixPatternStr("送修");
}
//维修进度
if (mgr_Fix.getFixSchedule() == 1) {
mgr_Fix.setFixScheduleStr("报修成功");
}
else if (mgr_Fix.getFixSchedule() == 2) {
mgr_Fix.setFixScheduleStr("客服确认");
}
else if (mgr_Fix.getFixSchedule() == 3) {
mgr_Fix.setFixScheduleStr("维修中");
}
else if (mgr_Fix.getFixSchedule() == 4) {
mgr_Fix.setFixScheduleStr("维修完成");
}
//获取客户姓名
mgr_Fix.setUserName(userServiceImpl.checkUserPhone(mgr_Fix.getUserPhone()).getName());
//修改下单时间显示格式
mgr_Fix.setOrderTimeStr(sdf2.format(sdf1.parse(mgr_Fix.getOrderTime().toString().substring(0,19))));
//修改维修地址显示内容
if (mgr_Fix.getArea() != null) {
mgr_Fix.setAddress(mgr_Fix.getProvince().getProvinceName()+" "
+mgr_Fix.getCity().getCityName()+" "
+mgr_Fix.getArea().getAreaName()+" "
+mgr_Fix.getAddress());
}
else {
mgr_Fix.setAddress(mgr_Fix.getProvince().getProvinceName()+" "
+mgr_Fix.getCity().getCityName()+" "
+mgr_Fix.getAddress());
}
}
return allFixOrder;
}
}
|
package com.scan;
import org.springframework.stereotype.Service;
/**
* @Author:wangrui
* @Date:2020/5/7 13:50
*/
@Service
public class LoginService {
}
|
package shared.message;
import java.lang.reflect.InvocationTargetException;
public class Perform extends Message {
private static final long serialVersionUID = 7723312253042480119L;
private String method;
public Perform(String method,Object... fields) {
super(fields);
this.method = method;
}
public void perform(shared.Readable object){
try {
//System.out.println(method+">>"+object+">>"+super.getAll()+">>"+object.getMethod(method));
object.getMethod(method).invoke(object, super.getAll());
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
}
}
|
package com.codingchili.instance.model.spells;
import com.codingchili.instance.model.events.Event;
import com.codingchili.instance.model.events.EventType;
/**
* @author Robin Duda
*
* Emitted when the spell state is changed, for example a charge is added or
* a spell is learned.
*/
public class SpellStateEvent implements Event {
private SpellState state;
private Spell spell;
public SpellStateEvent(SpellState state, Spell spell) {
this.state = state;
this.spell = spell;
}
public int getCharges() {
return state.charges(spell);
}
public long getCooldown() {
return state.cooldown(spell);
}
public String getSpell() {
return spell.getId();
}
@Override
public EventType getRoute() {
return EventType.spellstate;
}
}
|
package org.dreamer.expression.calc;
import org.junit.Test;
import static org.junit.Assert.*;
public class ExpressionsTest {
public ExpressionsTest() {}
@Test
public void constExpressionsTest() {
assertEquals(Math.E, ValueExpression.constant("E").eval(), 0.0);
assertEquals(Math.PI, ValueExpression.constant("PI").eval(), 0.0);
}
@Test
public void binaryExpressionsTest() {
final ValueExpression v1 = new ValueExpression(10.0);
final ValueExpression v2 = new ValueExpression(5.0);
assertEquals(v1.eval() + v2.eval(), BinaryExpression.add(v1, v2).eval(), 0.0);
assertEquals(v1.eval() - v2.eval(), BinaryExpression.sub(v1, v2).eval(), 0.0);
assertEquals(v1.eval() * v2.eval(), BinaryExpression.mul(v1, v2).eval(), 0.0);
assertEquals(v1.eval() / v2.eval(), BinaryExpression.div(v1, v2).eval(), 0.0);
}
} |
package Topic15_Pętle;
public class Patient {
public String name;
public String surName;
int nrPesel;
public Patient(String name, String surName, int nrPesel) {
this.name = name;
this.surName = surName;
this.nrPesel = nrPesel;
}
public Patient() {}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurName() {
return surName;
}
public void setSurName(String surName) {
this.surName = surName;
}
public int getNrPesel() {
return nrPesel;
}
public void setNrPesel(int nrPesel) {
this.nrPesel = nrPesel;
}
public void printInfoAboutPatiens(){
System.out.println("Imię pacjęta: " + getName());
System.out.println("Nazwisko pacjęta: " + getSurName());
System.out.println("Numer PESEL pacjęta: " + getNrPesel());
}
}
|
/**
* @Description:
* @Author: lay
* @Date: Created in 16:55 2018/12/5
* @Modified By:IntelliJ IDEA
*/
public class Customer {
private String name;
private BillingPlan plan;
private PaymentHistory history;
public BillingPlan getPlan(){
return plan;
}
public String getName(){
return name;
}
public PaymentHistory getHistory(){
return history;
}
public boolean isNull(){
return false;
}
static Customer newNull(){
return new NullCustomer();
}
}
|
package org.spider.exception;
/**
* @author liuxin
* @version Id: SpiderException.java, v 0.1 2018/7/26 下午10:04
*/
public class SpiderException extends RuntimeException {
public SpiderException(String errorMsg){
super(errorMsg);
}
}
|
package com.legend.rmi.quickstart.common;
/**
* Created by allen on 6/28/16.
*/
public interface Constants {
String ZK_CONNECT_STRING = "localhost:2181";
int ZK_SESSION_TIMEOUT = 5000; // In milliseconds
/**
* $ bin/zkCli.sh -server localhost:2181
* > create /rmi null
* > create /rmi/registry null
* > ls /
*/
String ZK_REGISTRY_PATH = "/rmi/registry";
String ZK_PROVIDER_PATH = ZK_REGISTRY_PATH + "/provider";
}
|
package abiguime.tz.com.tzyoutube.main.fragment_user;
import android.content.Context;
import android.support.v4.app.FragmentManager;
import abiguime.tz.com.tzyoutube._data.User;
import abiguime.tz.com.tzyoutube._data.source.UserDataSource;
import abiguime.tz.com.tzyoutube._data.source.remote.UserRemoteDataSource;
/**
* Created by abiguime on 2016/11/30.
*/
public class UserPagePresenter implements UserPageContract.Presenter{
private final UserPageContract.View view;
UserRemoteDataSource model;
public UserPagePresenter(UserPageContract.View view, UserRemoteDataSource model) {
this.view = view;
this.model = model;
}
@Override
public void login(String name, String password) {
/* 检查数据*/
view.onLoginProgress(); // 显示进度条 。。。
/* --数据在服务器上- */
model.login(name, password, new UserDataSource.LoginCallBack() {
@Override
public void onLoginSuccess(User user) {
view.showUser(user);
}
@Override
public void onLoginError(String message) {
view.onLoginError(message); // 显示进度条 。。。
}
});
}
@Override
public void start() {
}
}
|
package com.choco.order.interceptor;
import com.alibaba.dubbo.config.annotation.Reference;
import com.choco.common.entity.Admin;
import com.choco.common.utils.CookieUtil;
import com.choco.common.utils.JsonUtil;
import com.choco.sso.service.SSOService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;
/**
* Created by choco on 2021/1/6 11:51
*/
@Component
public class OrderLoginInterceptor implements HandlerInterceptor {
@Reference(interfaceClass = SSOService.class)
private SSOService ssoService;
@Autowired
private RedisTemplate<String, String> redisTemplate;
@Value("${user.ticket}")
private String userTicket;
@Value("${shop.portal.url}")
private String shopPortalUrl;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String ticket = CookieUtil.getCookieValue(request, "userTicket");
if (!StringUtils.isEmpty(ticket)) {
//这一步就是验证
Admin admin = ssoService.validate(ticket);
request.getSession().setAttribute("user", admin);
//重新设置redis的失效时间
ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
valueOperations.set(userTicket + ":" + ticket, JsonUtil.object2JsonStr(admin), 30L, TimeUnit.MINUTES);
return true;
}
//如何ticket不存在,则重定向
response.sendRedirect(shopPortalUrl + "/login?redirectUrl=" + request.getRequestURI());
return false;
}
}
|
package CrossSections;
import java.util.Queue;
/**
* Created by Frank Fang on 9/8/18.
*/
//This is the interface that is the abstract of the class which can addCar, passCar
public interface IRoad {
void add(Car car);
Car passCar();
boolean isEmpty();
int getCarNum();
Queue<Car> getCars();
}
|
package com.github.fierioziy.particlenativeapi.core.particle.type;
import com.github.fierioziy.particlenativeapi.api.particle.type.ParticleTypeBlockMotion;
import com.github.fierioziy.particlenativeapi.api.particle.type.ParticleTypeMotion;
import com.github.fierioziy.particlenativeapi.api.utils.ParticleException;
import org.bukkit.Material;
public class ParticleTypeBlockMotionImpl implements ParticleTypeBlockMotion {
@Override
public ParticleTypeMotion of(Material block) {
return of(block, (byte) 0);
}
@Override
public ParticleTypeMotion of(Material block, int meta) {
return of(block, (byte) meta);
}
@Override
public ParticleTypeMotion of(Material block, byte meta) {
throw new ParticleException(
"Requested particle type is not supported by this server version!"
);
}
@Override
public boolean isPresent() {
return false;
}
}
|
package com.example.finalproject;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
final static String TAG = "MainActivity";
static final int LOGIN_REQUEST_CODE = 1;
final List<Songs> songsLibrary = new ArrayList<>();
FrontViewCustomAdapter arrayAdapter;
//ArrayAdapter<Songs> arrayAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ListView songsListView = new ListView(this); //findViewById(R.id.mainListView);
setContentView(songsListView);
songsLibrary.add(new Songs("Kanye West", "", "https://lastfm.freetls.fastly.net/i/u/300x300/375a9688a2cb3d4e073bacf71735a63f.png", "", "Sphaghet codes with me"));
songsLibrary.add(new Songs("Evolve", "Imagine Dragons", "https://lastfm.freetls.fastly.net/i/u/300x300/8c77e9f509c4dd3bca8d3ac6b5344ce5.png", "", "inspirational music from Imagine Dragons."));
songsLibrary.add(new Songs("Destiny","NF","https://lastfm.freetls.fastly.net/i/u/300x300/65613775652434e5111cd24bb02503e4.png","","Heart Throbbing beats with deep lyrics"));
arrayAdapter = new FrontViewCustomAdapter(this, R.id.frontArtistView , songsLibrary);
songsListView.setAdapter(arrayAdapter);
songsListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
songsListView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
@Override
public void onItemCheckedStateChanged(ActionMode actionMode, int i, long l, boolean b) {
int numChecked = songsListView.getCheckedItemCount();
actionMode.setTitle(numChecked + " selected");
}
@Override
public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
return false;
}
@Override
public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
return false;
}
@Override
public void onDestroyActionMode(ActionMode actionMode) {
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == LOGIN_REQUEST_CODE && resultCode == Activity.RESULT_OK)
{
String song = data.getStringExtra("song");
String artist = data.getStringExtra("artist");
String album = data.getStringExtra("album");
String photoURL = data.getStringExtra("photoURL");
String comment = data.getStringExtra("comment");
songsLibrary.add(new Songs(artist,song,photoURL,album,comment));
arrayAdapter.notifyDataSetChanged();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.addPostButton:
Intent intent = new Intent(MainActivity.this, PostActivity.class);
startActivityForResult(intent, LOGIN_REQUEST_CODE);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
|
package br.assembleia.dao.impl;
import br.assembleia.dao.ReceitaDAO;
import br.assembleia.entidades.Receita;
import java.math.BigDecimal;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;
@Repository
public class ReceitaDAOImpl implements ReceitaDAO {
@PersistenceContext
private EntityManager entityManager;
@Override
public Receita getById(Long id) {
return entityManager.find(Receita.class, id);
}
@SuppressWarnings("unchecked")
@Override
public List<Receita> listarTodos() {
return entityManager.createQuery("FROM " + Receita.class.getName())
.getResultList();
}
@Override
public void salvar(Receita receita) {
entityManager.merge(receita);
entityManager.flush();
}
@Override
public void editar(Receita receita) {
entityManager.merge(receita);
entityManager.flush();
}
@Override
public void deletar(Receita receita) {
receita = getById(receita.getId());
entityManager.remove(receita);
entityManager.flush();
}
@Override
public void deletarId(final Long id) {
Receita receita = getById(id);
entityManager.remove(receita);
entityManager.flush();
}
@Override
public BigDecimal valorReceitaPeriodo(Integer mes, Integer ano) {
StringBuilder sql = new StringBuilder();
sql.append("Select SUM(r.valor) from Receita r ");
sql.append("Where extract(MONTH FROM r.data) = ? and extract(YEAR FROM r.data) = ? ");
Query q = entityManager.createQuery(sql.toString());
q.setParameter(1, mes);
q.setParameter(2, ano);
BigDecimal result = (BigDecimal) q.getSingleResult();
return result;
}
@Override
public List<Receita> listarReceitasMesAno(Integer mes, Integer ano) {
StringBuilder sql = new StringBuilder();
sql.append("Select r from Receita r ");
sql.append(" Where extract(MONTH FROM r.data) = ? and extract(YEAR FROM r.data) = ? ");
Query q = entityManager.createQuery(sql.toString());
q.setParameter(1, mes);
q.setParameter(2, ano);
List<Receita> result = q.getResultList();
return result;
}
@Override
public BigDecimal listarReceitasRecebidas() {
StringBuilder sql = new StringBuilder();
sql.append("Select sum(r.valor) from Receita r ");
sql.append("where r.recebido = true ");
Query q = entityManager.createQuery(sql.toString());
BigDecimal result = (BigDecimal) q.getSingleResult();
return result;
}
@Override
public List<Receita> listarUltimasReceitasVisao(Integer mes, Integer ano) {
StringBuilder sql = new StringBuilder();
sql.append("Select r from Receita r ");
sql.append(" Where extract(MONTH FROM r.data) = ? "
+ "and extract(YEAR FROM r.data) = ? AND r.recebido = true ");
Query q = entityManager.createQuery(sql.toString());
q.setParameter(1, mes);
q.setParameter(2, ano);
List<Receita> result = q.getResultList();
return result;
}
@Override
public List<Receita> buscarReceitaMembroData(Long mes) {
StringBuilder sql = new StringBuilder();
sql.append("Select r FROM Receita r ");
sql.append(" inner join r.membro m ");
sql.append(" Where extract(MONTH FROM r.data) = ? AND r.recebido = true "
+ "order by m.nome ");
Query q = entityManager.createQuery(sql.toString());
q.setParameter(1, mes.intValue());
List<Receita> result = q.getResultList();
return result;
}
@Override
public BigDecimal buscarReceitaGrafico(Long mes, Integer ano) {
StringBuilder sql = new StringBuilder();
sql.append("Select sum(r.valor) from Receita r ");
sql.append("Where extract(MONTH FROM r.data) = ? and extract(YEAR FROM r.data) = ? ");
Query q = entityManager.createQuery(sql.toString());
q.setParameter(1, mes.intValue());
q.setParameter(2, ano);
BigDecimal result = (BigDecimal) q.getSingleResult();
return result;
}
@Override
public BigDecimal listarReceitasCategoriaMesAno(Integer mes, Integer ano, Long id) {
StringBuilder sql = new StringBuilder();
sql.append("Select sum(r.valor) from Receita r ");
sql.append("Where r.categoria.id = ? and extract(MONTH FROM r.data) = ? and extract(YEAR FROM r.data) = ? ");
Query q = entityManager.createQuery(sql.toString());
q.setParameter(1, id);
q.setParameter(2, mes);
q.setParameter(3, ano);
BigDecimal result = (BigDecimal) q.getSingleResult();
return result;
}
}
|
package com.github.ofofs.jca.constants;
import com.github.ofofs.jca.annotation.API;
/**
* 常量
*
* @author kangyonggan
* @since 6/23/18
*/
public interface JcaConstants {
/**
* 返回值类型void
*/
String RETURN_VOID = "void";
/**
* 构造器名称
*/
@API(status = API.Status.EXPERIMENTAL)
String CONSTRUCTOR_NAME = "<init>";
/**
* null
*/
String NULL = "null";
}
|
package pl.qaaacademy.todo.item;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pl.qaaacademy.todo.enums.ItemStatus;
import pl.qaaacademy.todo.exceptions.TodoItemAlreadyCompletedException;
import pl.qaaacademy.todo.interfaces.StatusChangable;
import static pl.qaaacademy.todo.core.TodoItemValidator.validateDescription;
import static pl.qaaacademy.todo.core.TodoItemValidator.validateTitle;
public class TodoItem implements StatusChangable {
private String title;
private String description;
private ItemStatus status;
protected static final Logger logger = LoggerFactory.getLogger(TodoItem.class);
private TodoItem() {
}
private TodoItem(String title, String description) {
this.title = title;
this.description = description;
this.status = ItemStatus.PENDING;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
validateTitle(title);
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
validateDescription(description);
this.description = description;
}
public ItemStatus getStatus() {
return status;
}
// public void setStatus(ItemStatus status) {
// this.status = status;
// }
public static TodoItem of(String title, String description) {
validateTitle(title);
validateDescription(description);
return new TodoItem(title,description);
}
// private static void validateTitle(String title) {
// if (title == null || title.isBlank()) {
// logger.error("Item title is null or blank");
// throw new TodoItemValidationException("Item title is null or blank");
// }
// }
// private static void validateDescription(String description) {
// if (description != null) {
// int stringLength = description.length();
// if (stringLength > 250) {
// logger.error("Too long description");
// throw new TodoItemDescriptionTooLongException("Description is longer then 250 characters");
// }
// }else if (description == null) {
// logger.error("Description i null");
// throw new TodoItemNullDescriptionException("Description is null");
// }
// }
@Override
public void toggleStatus() {
if (this.status == ItemStatus.PENDING) {
this.status = ItemStatus.IN_PROGRESS;
} else if (this.status == ItemStatus.COMPLETED) {
logger.error("Completed status is not changeable");
throw new TodoItemAlreadyCompletedException("Item has been completed");
} else {
this.status = ItemStatus.PENDING;
}
}
@Override
public void complete() {
if (this.status == ItemStatus.IN_PROGRESS) {
this.status = ItemStatus.COMPLETED;
}
}
}
|
public class Vector {
int[] v;
public Vector() {
}
public Vector(int size) {
this.v = new int[size];
}
public int[] fillRandom() {
for (int i = 0; i < v.length; i++) {
int rand = (int) (Math.random() * 100) + 1;
v[i] = rand;
}
return v;
}
public int[] fillSpecific(int[] values) {
this.v = values;
return v;
}
}
|
package slimeknights.tconstruct.smeltery.tileentity;
import java.util.Locale;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.play.server.SPacketUpdateTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.IStringSerializable;
import net.minecraft.util.ITickable;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraft.world.WorldServer;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.capability.CapabilityFluidHandler;
import net.minecraftforge.fluids.capability.IFluidHandler;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import slimeknights.tconstruct.common.TinkerNetwork;
import slimeknights.tconstruct.library.Util;
import slimeknights.tconstruct.library.fluid.ChannelSideTank;
import slimeknights.tconstruct.library.fluid.ChannelTank;
import slimeknights.tconstruct.smeltery.network.ChannelConnectionPacket;
import slimeknights.tconstruct.smeltery.network.ChannelFlowPacket;
import slimeknights.tconstruct.smeltery.network.FluidUpdatePacket.IFluidPacketReceiver;
public class TileChannel extends TileEntity implements ITickable, IFluidPacketReceiver {
/** Stores if the channel can be connected on the side */
private ChannelConnection[] connections;
/** Connection on the bottom as its boolean */
private boolean connectedDown;
/** Stores if the channel is currently flowing, byte will determine for how long */
private byte[] isFlowing;
/** Stores if the channel is currently flowing down */
private boolean isFlowingDown;
/** Stores if the block was powered last update */
private boolean wasPowered;
private int numOutputs;
private ChannelTank tank;
private ChannelSideTank[] sideTanks;
public TileChannel() {
this.connections = new ChannelConnection[4];
this.connectedDown = false;
this.isFlowing = new byte[4];
this.tank = new ChannelTank(36, this);
this.sideTanks = new ChannelSideTank[4];
this.numOutputs = 0;
}
/* Flow */
/**
* Ticking logic
*/
@Override
public void update() {
if(getWorld().isRemote) {
return;
}
FluidStack fluid = tank.getFluid();
if(fluid != null && fluid.amount > 0) {
// if we have down, use only that
boolean hasFlown = false;
if(isConnectedDown()) {
hasFlown = trySide(EnumFacing.DOWN, TileFaucet.LIQUID_TRANSFER);
// otherwise, ensure we have a connection before pouring
}
if(!hasFlown && numOutputs > 0) {
// we want to split the fluid if needed rather than favoring a side
int flowRate = Math.max(1, Math.min(tank.usableFluid() / numOutputs, TileFaucet.LIQUID_TRANSFER));
// then just try each side
for(EnumFacing side : EnumFacing.HORIZONTALS) {
trySide(side, flowRate);
}
}
}
// clear flowing if we should no longer flow on a side
for(int i = 0; i < 4; i++) {
if(isFlowing[i] > 0) {
isFlowing[i]--;
if(isFlowing[i] == 0) {
TinkerNetwork.sendToClients((WorldServer) world, pos, new ChannelFlowPacket(pos, EnumFacing.getHorizontal(i), false));
}
}
}
tank.freeFluid();
}
protected boolean trySide(@Nonnull EnumFacing side, int flowRate) {
if(tank.getFluid() == null || this.getConnection(side) != ChannelConnection.OUT) {
return false;
}
// what are we flowing into
TileEntity te = world.getTileEntity(pos.offset(side));
// for channels, we have slightly quicker logic
if(te instanceof TileChannel) {
TileChannel channel = (TileChannel)te;
// only flow if the other channel is receiving
EnumFacing opposite = side.getOpposite();
if(channel.getConnection(opposite) == ChannelConnection.IN) {
return fill(side, channel.getTank(opposite), flowRate);
}
}
else {
IFluidHandler toFill = getFluidHandler(te, side.getOpposite());
if(toFill != null) {
return fill(side, toFill, flowRate);
}
}
return false;
}
protected boolean fill(EnumFacing side, @Nonnull IFluidHandler handler, int amount) {
FluidStack fluid = tank.getUsableFluid();
// make sure we do not allow more than the fluid allows
fluid.amount = Math.min(fluid.amount, amount);
int filled = fluid.amount == 0 ? 0 : handler.fill(fluid, false);
if(filled > 0) {
setFlow(side, true);
filled = handler.fill(fluid, true);
tank.drainInternal(filled, true);
return true;
}
setFlow(side, false);
return false;
}
protected TileChannel getChannel(BlockPos pos) {
TileEntity te = getWorld().getTileEntity(pos);
if(te != null && te instanceof TileChannel) {
return (TileChannel) te;
}
return null;
}
protected IFluidHandler getFluidHandler(TileEntity te, EnumFacing direction) {
if(te != null && te.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, direction)) {
return te.getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, direction);
}
return null;
}
/* Fluid interactions */
@Override
public boolean hasCapability(@Nonnull Capability<?> capability, @Nullable EnumFacing side) {
if(capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY) {
// only allow inserting if the side is set to in
// basically, block out and none, along with sides that cannot be in
return side == null || getConnection(side) == ChannelConnection.IN;
}
return super.hasCapability(capability, side);
}
@Nonnull
@Override
public <T> T getCapability(@Nonnull Capability<T> capability, @Nullable EnumFacing side) {
if(capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY) {
// ensure we allow on that side
if(side == null || getConnection(side) == ChannelConnection.IN) {
return CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY.cast(getTank(side));
}
}
return super.getCapability(capability, side);
}
/**
* Called on block placement to fill data from blocks on all sides
* @param side Side clicked
* @param sneak If true, player was sneaking
*/
public void onPlaceBlock(EnumFacing hit, boolean sneak) {
EnumFacing side = hit.getOpposite();
// if placed below a TE, update to connect to it
TileEntity te = world.getTileEntity(pos.offset(side));
if(te == null) {
return;
}
if(side == EnumFacing.UP) {
if(te instanceof TileChannel) {
((TileChannel)te).connectedDown = true;
}
}
// for the rest, try to connect to it
// if its a channel, connect to each other
else if(te instanceof TileChannel) {
// if its a channel, update ours and their connections to each other
// if we hit the bottom of a channel, make it flow into us
if(side == EnumFacing.DOWN) {
this.connectedDown = true;
} else {
// default to out on click, but do in if sneaking
ChannelConnection connection = sneak ? ChannelConnection.IN : ChannelConnection.OUT;
this.setConnection(side, connection.getOpposite());
((TileChannel)te).setConnection(hit, connection);
}
// if its another fluid container, just connect to it
} else if(te.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, side.getOpposite())) {
// we already know we can connect, so just set out
this.setConnection(side, ChannelConnection.OUT);
}
this.wasPowered = world.isBlockPowered(pos);
}
/**
* Handles an update from another block to update the shape
* @param fromPos BlockPos that changed
*/
public void handleBlockUpdate(BlockPos fromPos, boolean didPlace, boolean isPowered) {
if(world.isRemote) {
return;
}
EnumFacing side = Util.facingFromNeighbor(this.pos, fromPos);
// we don't care about up as we don't connect on up
if(side != null && side != EnumFacing.UP) {
boolean isValid = false;
boolean shouldOutput = false;
TileEntity te = world.getTileEntity(fromPos);
if(te instanceof TileChannel) {
isValid = true;
} else if(te != null && te.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, side.getOpposite())) {
isValid = true;
// if we placed it and are not a channel, set the output state
shouldOutput = didPlace;
}
// if there is a connection and its no longer valid, clear it
ChannelConnection connection = this.getConnection(side);
if(connection != ChannelConnection.NONE && !isValid) {
this.setConnection(side, ChannelConnection.NONE);
TinkerNetwork.sendToClients((WorldServer) world, pos, new ChannelConnectionPacket(pos, side, false));
// if there is no connection and one can be formed, we might automatically add one on condition
// the new block must have been placed (not just updated) and must not be a channel
} else if(shouldOutput && connection == ChannelConnection.NONE && isValid) {
this.setConnection(side, ChannelConnection.OUT);
TinkerNetwork.sendToClients((WorldServer) world, pos, new ChannelConnectionPacket(pos, side, true));
}
}
// redstone power
if(isPowered != wasPowered && side != EnumFacing.DOWN) {
TileEntity te = world.getTileEntity(pos.down());
boolean isValid2 = te != null && (te instanceof TileChannel || te.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, side.getOpposite()));
this.connectedDown = isValid2 && isPowered;
TinkerNetwork.sendToClients((WorldServer) world, pos, new ChannelConnectionPacket(pos, EnumFacing.DOWN, this.connectedDown));
wasPowered = isPowered;
}
}
/**
* Interacts with the tile entity, setting the side to show or hide
* @param side Side clicked
* @return true if the channel changed
*/
public boolean interact(EntityPlayer player, EnumFacing side) {
// if placed below a channel, connect it to us
TileEntity te = world.getTileEntity(pos.offset(side));
// if the TE is a channel, note that for later
boolean isChannel = false;
if(te instanceof TileChannel) {
isChannel = true;
// otherwise ensure we can actually connect on that side
} else if(te == null || !te.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, side.getOpposite())) {
// if it is already none, no reason to set it back to none
if(this.getConnection(side) == ChannelConnection.NONE) {
// but for sides lets try again with the bottom connection
if(side != EnumFacing.DOWN) {
return this.interact(player, EnumFacing.DOWN);
}
} else {
this.setConnection(side, ChannelConnection.NONE);
this.updateBlock(pos);
}
return false;
}
// if down, just reverse the connection
String message;
if(side == EnumFacing.DOWN) {
this.connectedDown = !this.connectedDown;
this.updateBlock(pos);
message = this.connectedDown ? "channel.connected_down.allow" : "channel.connected_down.disallow";
} else {
// otherwise, we rotate though connections
ChannelConnection newConnect = this.getConnection(side).getNext(player.isSneaking());
this.setConnection(side, newConnect);
// if we have a neighbor, update them as well
BlockPos offset = this.pos.offset(side);
if(isChannel) {
((TileChannel)te).setConnection(side.getOpposite(), newConnect.getOpposite());
}
// block updates
this.updateBlock(pos);
this.updateBlock(offset);
switch(newConnect) {
case OUT:
message = "channel.connected.out";
break;
case IN:
message = "channel.connected.in";
break;
default:
message = "channel.connected.none";
}
}
player.sendStatusMessage(new TextComponentTranslation(Util.prefix(message)), true);
return true;
}
/* Helper methods */
public ChannelTank getTank() {
return this.tank;
}
protected IFluidHandler getTank(@Nonnull EnumFacing side) {
if(side == null || side == EnumFacing.UP) {
return tank;
}
int index = side.getHorizontalIndex();
if(index >= 0) {
if(sideTanks[index] == null) {
sideTanks[index] = new ChannelSideTank(this, tank, side);
}
return sideTanks[index];
}
return null;
}
/**
* Gets the connection for a side
* @param side Side to query
* @return Connection on the specified side
*/
@Nonnull
public ChannelConnection getConnection(@Nonnull EnumFacing side) {
// just always return in for up, thats fine
if(side == EnumFacing.UP) {
return ChannelConnection.IN;
}
// down should ask the boolean, might be out
if(side == EnumFacing.DOWN) {
return this.connectedDown ? ChannelConnection.OUT : ChannelConnection.NONE;
}
// the other four use an array index
int index = side.getHorizontalIndex();
if(index < 0) {
return null;
}
// not nullable
ChannelConnection connection = connections[index];
return connection == null ? ChannelConnection.NONE : connection;
}
public boolean isConnectedDown() {
return connectedDown;
}
public void setConnection(@Nonnull EnumFacing side, @Nonnull ChannelConnection connection) {
if(side == EnumFacing.DOWN) {
this.connectedDown = connection == ChannelConnection.OUT;
return;
}
int index = side.getHorizontalIndex();
if(index >= 0) {
ChannelConnection oldConnection = this.connections[index];
// if we changed from or to none, adjust connections
if(oldConnection != ChannelConnection.OUT && connection == ChannelConnection.OUT) {
numOutputs++;
} else if (oldConnection == ChannelConnection.OUT && connection != ChannelConnection.OUT) {
numOutputs--;
}
this.connections[index] = connection;
}
}
public void setFlow(@Nonnull EnumFacing side, boolean isFlowing) {
if(side == EnumFacing.UP) {
return;
}
boolean wasFlowing = setFlowRaw(side, isFlowing);
if(wasFlowing != isFlowing) {
TinkerNetwork.sendToClients((WorldServer) world, pos, new ChannelFlowPacket(pos, side, isFlowing));
}
}
private boolean setFlowRaw(@Nonnull EnumFacing side, boolean isFlowing) {
boolean wasFlowing;
if(side == EnumFacing.DOWN) {
wasFlowing = this.isFlowingDown;
this.isFlowingDown = isFlowing;
} else {
int index = side.getHorizontalIndex();
wasFlowing = this.isFlowing[index] > 0;
this.isFlowing[index] = (byte) (isFlowing ? 2 : 0);
}
return wasFlowing;
}
public boolean isFlowing(@Nonnull EnumFacing side) {
if(side == EnumFacing.DOWN) {
return this.isFlowingDown;
}
int index = side.getHorizontalIndex();
if(index >= 0) {
return this.isFlowing[index] > 0;
}
return false;
}
public boolean isFlowingDown() {
return isFlowingDown;
}
private void updateBlock(BlockPos pos) {
IBlockState state = world.getBlockState(pos);
world.notifyBlockUpdate(pos, state, state, 2);
}
/* Rendering */
@Override
public boolean hasFastRenderer() {
return true;
}
@Override
@SideOnly(Side.CLIENT)
public AxisAlignedBB getRenderBoundingBox() {
return new AxisAlignedBB(pos.getX(), pos.getY() - 1, pos.getZ(), pos.getX() + 1, pos.getY() + 1, pos.getZ() + 1);
}
/* NBT */
private static final String TAG_CONNECTIONS = "connections";
private static final String TAG_CONNECTED_DOWN = "connected_down";
private static final String TAG_IS_FLOWING = "is_flowing";
private static final String TAG_IS_FLOWING_DOWN = "is_flowing_down";
private static final String TAG_WAS_POWERED = "was_powered";
private static final String TAG_TANK = "tank";
// load and save
@Nonnull
@Override
public NBTTagCompound writeToNBT(NBTTagCompound nbt) {
nbt = super.writeToNBT(nbt);
byte[] bytes = new byte[4];
ChannelConnection connection;
for(int i = 0; i < 4; i++) {
connection = connections[i];
bytes[i] = connection == null ? 0 : connection.getIndex();
}
nbt.setByteArray(TAG_CONNECTIONS, bytes);
nbt.setBoolean(TAG_CONNECTED_DOWN, connectedDown);
nbt.setByteArray(TAG_IS_FLOWING, isFlowing);
nbt.setBoolean(TAG_IS_FLOWING_DOWN, isFlowingDown);
nbt.setBoolean(TAG_WAS_POWERED, wasPowered);
nbt.setTag(TAG_TANK, tank.writeToNBT(new NBTTagCompound()));
return nbt;
}
@Override
public void readFromNBT(NBTTagCompound nbt) {
super.readFromNBT(nbt);
// connections
if(nbt.hasKey(TAG_CONNECTIONS)) {
this.connections = new ChannelConnection[4];
this.numOutputs = 0;
byte[] bytes = nbt.getByteArray(TAG_CONNECTIONS);
for(int i = 0; i < 4 && i < bytes.length; i++) {
this.connections[i] = ChannelConnection.fromIndex(bytes[i]);
// just calc this instead of storing it
if(this.connections[i] != ChannelConnection.NONE) {
this.numOutputs++;
}
}
}
this.connectedDown = nbt.getBoolean(TAG_CONNECTED_DOWN);
// isFlowing
if(nbt.hasKey(TAG_IS_FLOWING)) {
this.isFlowing = nbt.getByteArray(TAG_IS_FLOWING);
}
this.isFlowingDown = nbt.getBoolean(TAG_IS_FLOWING_DOWN);
this.wasPowered = nbt.getBoolean(TAG_WAS_POWERED);
// tank
NBTTagCompound tankTag = nbt.getCompoundTag(TAG_TANK);
if(tankTag != null) {
tank.readFromNBT(tankTag);
}
}
// networking
@Override
public void updateFluidTo(FluidStack fluid) {
tank.setFluid(fluid);
}
@SideOnly(Side.CLIENT)
public void updateConnection(EnumFacing side, boolean connect) {
this.setConnection(side, connect ? ChannelConnection.OUT : ChannelConnection.NONE);
this.updateBlock(pos);
}
@SideOnly(Side.CLIENT)
public void updateFlow(EnumFacing side, boolean flow) {
this.setFlowRaw(side, flow);
}
@Override
public SPacketUpdateTileEntity getUpdatePacket() {
NBTTagCompound tag = new NBTTagCompound();
writeToNBT(tag);
return new SPacketUpdateTileEntity(this.getPos(), this.getBlockMetadata(), tag);
}
@Override
public void onDataPacket(NetworkManager net, SPacketUpdateTileEntity pkt) {
super.onDataPacket(net, pkt);
readFromNBT(pkt.getNbtCompound());
}
@Nonnull
@Override
public NBTTagCompound getUpdateTag() {
// new tag instead of super since default implementation calls the super of writeToNBT
return writeToNBT(new NBTTagCompound());
}
@Override
public void handleUpdateTag(@Nonnull NBTTagCompound tag) {
readFromNBT(tag);
}
public static enum ChannelConnection implements IStringSerializable {
NONE,
IN,
OUT;
byte index;
ChannelConnection() {
index = (byte)ordinal();
}
public byte getIndex() {
return index;
}
public ChannelConnection getOpposite() {
switch(this) {
case IN: return OUT;
case OUT: return IN;
}
return NONE;
}
public ChannelConnection getNext(boolean reverse) {
if(reverse) {
switch(this) {
case NONE: return IN;
case IN: return OUT;
case OUT: return NONE;
}
} else {
switch(this) {
case NONE: return OUT;
case OUT: return IN;
case IN: return NONE;
}
}
// not possible
throw new UnsupportedOperationException();
}
public static ChannelConnection fromIndex(int index) {
if(index < 0 || index >= values().length) {
return NONE;
}
return values()[index];
}
@Override
public String getName() {
return this.toString().toLowerCase(Locale.US);
}
public boolean canFlow() {
return this != NONE;
}
public static boolean canFlow(ChannelConnection connection) {
return connection != null && connection != NONE;
}
}
}
|
package com.example.actividaddeaprendizaje.characters.searchCharacters.model;
import com.example.actividaddeaprendizaje.beans.ResponseAPI;
import com.example.actividaddeaprendizaje.characters.searchCharacters.contract.SearchCharactersContract;
import com.example.actividaddeaprendizaje.service.CharactersApiAdapter;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class SearchCharactersModel implements SearchCharactersContract.Model, Callback<ResponseAPI> {
OnCharacterListener onCharacterListener;
@Override
public void getCharacterWS(OnCharacterListener onCharacterLister, String nombre) {
this.onCharacterListener = onCharacterLister;
Call<ResponseAPI> responseAPICall = CharactersApiAdapter.getApiService().getCharactersByName(nombre);
responseAPICall.enqueue(this);
}
@Override
public void onResponse(Call<ResponseAPI> call, Response<ResponseAPI> response) {
if (response.isSuccessful() && !response.body().getData().getResults().isEmpty()){
onCharacterListener.resolve(response.body().getData().getResults());
}else {
onCharacterListener.resolveVoid("Character Not Found");
}
}
@Override
public void onFailure(Call<ResponseAPI> call, Throwable t) {
onCharacterListener.reject("Fallo al traer los datos");
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jdbc.object;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.Types;
import javax.sql.DataSource;
import org.junit.jupiter.api.Test;
import org.springframework.jdbc.core.SqlParameter;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/**
* @author Juergen Hoeller
* @since 22.02.2005
*/
public class BatchSqlUpdateTests {
@Test
public void testBatchUpdateWithExplicitFlush() throws Exception {
doTestBatchUpdate(false);
}
@Test
public void testBatchUpdateWithFlushThroughBatchSize() throws Exception {
doTestBatchUpdate(true);
}
private void doTestBatchUpdate(boolean flushThroughBatchSize) throws Exception {
final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?";
final int[] ids = new int[] { 100, 200 };
final int[] rowsAffected = new int[] { 1, 2 };
Connection connection = mock();
DataSource dataSource = mock();
given(dataSource.getConnection()).willReturn(connection);
PreparedStatement preparedStatement = mock();
given(preparedStatement.getConnection()).willReturn(connection);
given(preparedStatement.executeBatch()).willReturn(rowsAffected);
DatabaseMetaData mockDatabaseMetaData = mock();
given(mockDatabaseMetaData.supportsBatchUpdates()).willReturn(true);
given(connection.prepareStatement(sql)).willReturn(preparedStatement);
given(connection.getMetaData()).willReturn(mockDatabaseMetaData);
BatchSqlUpdate update = new BatchSqlUpdate(dataSource, sql);
update.declareParameter(new SqlParameter(Types.INTEGER));
if (flushThroughBatchSize) {
update.setBatchSize(2);
}
update.update(ids[0]);
update.update(ids[1]);
if (flushThroughBatchSize) {
assertThat(update.getQueueCount()).isEqualTo(0);
assertThat(update.getRowsAffected()).hasSize(2);
}
else {
assertThat(update.getQueueCount()).isEqualTo(2);
assertThat(update.getRowsAffected()).isEmpty();
}
int[] actualRowsAffected = update.flush();
assertThat(update.getQueueCount()).isEqualTo(0);
if (flushThroughBatchSize) {
assertThat(actualRowsAffected).as("flush did not execute updates").isEmpty();
}
else {
assertThat(actualRowsAffected).as("executed 2 updates").hasSize(2);
assertThat(actualRowsAffected[0]).isEqualTo(rowsAffected[0]);
assertThat(actualRowsAffected[1]).isEqualTo(rowsAffected[1]);
}
actualRowsAffected = update.getRowsAffected();
assertThat(actualRowsAffected).as("executed 2 updates").hasSize(2);
assertThat(actualRowsAffected[0]).isEqualTo(rowsAffected[0]);
assertThat(actualRowsAffected[1]).isEqualTo(rowsAffected[1]);
update.reset();
assertThat(update.getRowsAffected()).isEmpty();
verify(preparedStatement).setObject(1, ids[0], Types.INTEGER);
verify(preparedStatement).setObject(1, ids[1], Types.INTEGER);
verify(preparedStatement, times(2)).addBatch();
verify(preparedStatement).close();
}
}
|
package edu.uestc.sdn;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import struct.*;
//处理业务的handler
public class ControllerHandler extends SimpleChannelInboundHandler<ACProtocol>{
private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//cause.printStackTrace();
ctx.close();
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, ACProtocol msg) throws Exception {
//接收到数据,并处理
int len = msg.getLen();
byte[] contentIn = msg.getContent();
Packet_in packet_in = new Packet_in();
try {
JavaStruct.unpack(packet_in, contentIn);
}catch(StructException e) {
e.printStackTrace();
}
System.out.println("ingress :"+packet_in.ingress_port);
System.out.println("reason :"+packet_in.reason);
//回复消息
Packet_in packet_out = new Packet_in();
packet_out.ingress_port = 11;
packet_out.reason = 21;
byte[] contentOut = JavaStruct.pack(packet_out);
ACProtocol msgOut = new ACProtocol();
msgOut.setLen(contentOut.length);
msgOut.setContent(contentOut);
ctx.writeAndFlush(msgOut);
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
System.out.println("[switch]" + ctx.channel().remoteAddress() + " connected.");
channelGroup.add(ctx.channel());
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
System.out.println("[switch]" + ctx.channel().remoteAddress() + " disconnected.");
}
}
|
package nl.kolkos.photoGallery.repositories;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import nl.kolkos.photoGallery.entities.PhotoGallery;
import nl.kolkos.photoGallery.entities.PhotoGalleryACL;
import nl.kolkos.photoGallery.entities.User;
@Repository
public interface PhotoGalleryACLRepository extends JpaRepository<PhotoGalleryACL, Long>{
List<PhotoGalleryACL> findByPhotoGallery(PhotoGallery photoGallery);
List<PhotoGalleryACL> findByUser(User user);
PhotoGalleryACL findByPhotoGalleryAndUser(PhotoGallery photoGallery, User user);
PhotoGalleryACL findByIdAndUser(long id, User user);
PhotoGalleryACL findFirstByUserAndUserIsCreatorOrderByPhotoGallery(User user, boolean userIsCreator);
}
|
package com.rocktech.hospitalrms;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
public class AboutActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
}
public void exitApp(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("EXIT");
builder.setMessage("Are you sure you want to exit?");
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
finishAffinity();
System.exit(0);
}
});
builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// TODO: 9/11/2020 Cancel submission
}
});
builder.show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.home_menu, menu);
return super.onCreateOptionsMenu(menu);
}
//
@Override
public void onBackPressed() {
Intent intent = new Intent(this, HomepageActivity.class);
startActivity(intent);
// super.onBackPressed();
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.home:
Intent intent = new Intent(this, HomepageActivity.class);
startActivity(intent);
break;
case R.id.about:
Toast.makeText(this, "You are here already",Toast.LENGTH_SHORT).show();
break;
case R.id.signIn:
intent = new Intent(this, MainActivity.class);
startActivity(intent);
break;
case R.id.exit:
exitApp();
break;
default: return super.onOptionsItemSelected(item);
}
return true;
}
}
|
package egovframework.svt.find;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import egovframework.adm.cfg.mem.service.MemberSearchService;
import egovframework.adm.sms.SMSSenderDAO;
import egovframework.com.cmm.EgovMessageSource;
@Service
public class IdPwdFindService {
protected static final Log log = LogFactory.getLog(IdPwdFindService.class);
@Resource(name = "egovMessageSource")
EgovMessageSource egovMessageSource;
@Autowired
IdPwdFindDAO idPwdFindDAO;
@Resource(name = "SMSSenderDAO")
SMSSenderDAO SMSSenderDAO;
@Resource(name = "memberSearchService")
MemberSearchService memberSearchService;
public String findId(Map<String, String> paramMap, Model model) {
Map<String, String> view = idPwdFindDAO.getIdPwdFind(paramMap);
if(null != paramMap.get("epkiDn") && "" != String.valueOf(paramMap.get("epkiDn")) && null != view) {
model.addAttribute("view", view);
} else {
model.addAttribute("resultMsg", egovMessageSource.getMessage("fail.common.idpwd.search"));
return "forward:/usr/mem/userIdPwdSearch01.do";
}
return "usr/mem/userIdPwdSearch02";
}
public String findPwd(Map<String, String> paramMap, Model model) throws Exception {
Map<String, String> view = idPwdFindDAO.getIdPwdFind(paramMap);
if(null != paramMap.get("epkiDn") && "" != String.valueOf(paramMap.get("epkiDn")) && null != view) {
model.addAttribute("view", view);
Map<String, Object> commandMap = new HashMap<String, Object>();
commandMap.put("p_userid_1", paramMap.get("userid"));
// p_userid_1 setting
boolean ok = memberSearchService.updatePwdReset(commandMap);
String p_handphone = String.valueOf(view.get("handphone"));
String pwd = view.get("pwd") + "";
String content = "회원님의 비밀번호는 [" + pwd + "]입니다. 로그인하신 후 꼭 비밀번호 변경부탁드립니다.";
//문자발송
if(ok == true && p_handphone != null && !p_handphone.equals("")) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("p_handphone", p_handphone);
map.put("content", content);
boolean isOk = SMSSenderDAO.dacomSmsSender(map);
if(isOk) {
model.addAttribute("view", view);
} else {
model.addAttribute("resultMsg", egovMessageSource.getMessage("fail.common.idpwd.search"));
return "forward:/usr/mem/userIdPwdSearch01.do";
}
} else {
model.addAttribute("resultMsg", egovMessageSource.getMessage("fail.common.idpwd.search"));
return "forward:/usr/mem/userIdPwdSearch01.do";
}
} else {
model.addAttribute("resultMsg", egovMessageSource.getMessage("fail.common.idpwd.search"));
return "forward:/usr/mem/userIdPwdSearch01.do";
}
return "usr/mem/userIdPwdSearch02";
}
public Map<String, Object> userPwdInit(Map<String, Object> commandMap) {
Map<String, Object> resultMap = new HashMap<String, Object>();
try {
//p_userid_1
boolean ok = memberSearchService.updatePwdReset(commandMap);
String p_handphone = String.valueOf(commandMap.get("p_handphone"));
String pwd = String.valueOf(commandMap.get("p_birthDate"));
String content = "회원님의 비밀번호는 [" + pwd + "]입니다. 로그인하신 후 꼭 비밀번호 변경부탁드립니다.";
if(ok) {
if(StringUtils.isNotBlank(p_handphone)) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("p_handphone", p_handphone);
map.put("content", content);
boolean isOk = SMSSenderDAO.dacomSmsSender(map);
if(isOk) {
resultMap.put("resultMsg", "비밀번호 초기화가 완료되었습니다.");
resultMap.put("resultCode", "0000");
} else {
resultMap.put("resultMsg", "문자전송에 실패했습니다.");
resultMap.put("resultCode", "1003");
}
} else {
resultMap.put("resultMsg", "핸드폰번호가 없습니다.");
resultMap.put("resultCode", "1002");
}
} else {
resultMap.put("resultMsg", "비밀번호 초기화에 실패했습니다.");
resultMap.put("resultCode", "1001");
}
} catch (Exception e) {
resultMap.put("resultMsg", "비밀번호 초기화에 실패했습니다.");
resultMap.put("resultCode", "1001");
}
return resultMap;
}
public String findIdHtml5(Map<String, String> paramMap, ModelMap model) {
Map<String, String> view = idPwdFindDAO.getIdPwdFind(paramMap);
if(null != paramMap.get("epkiDn") && "" != String.valueOf(paramMap.get("epkiDn")) && null != view) {
model.addAttribute("view", view);
} else {
model.addAttribute("resultMsg", egovMessageSource.getMessage("fail.common.idpwd.search"));
return "forward:/usr/mem/userIdPwdSearch01.do";
}
return "usr/mem/userIdPwdSearch02";
}
public String findPwdHtml5(Map<String, String> paramMap, ModelMap model) throws Exception {
Map<String, String> view = idPwdFindDAO.getIdPwdFind(paramMap);
if(null != paramMap.get("epkiDn") && "" != String.valueOf(paramMap.get("epkiDn")) && null != view) {
model.addAttribute("view", view);
Map<String, Object> commandMap = new HashMap<String, Object>();
commandMap.put("p_userid_1", paramMap.get("userid"));
// p_userid_1 setting
boolean ok = memberSearchService.updatePwdReset(commandMap);
String p_handphone = String.valueOf(view.get("handphone"));
String pwd = view.get("pwd") + "";
String content = "회원님의 비밀번호는 [" + pwd + "]입니다. 로그인하신 후 꼭 비밀번호 변경부탁드립니다.";
//문자발송
if(ok == true && p_handphone != null && !p_handphone.equals("")) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("p_handphone", p_handphone);
map.put("content", content);
boolean isOk = SMSSenderDAO.dacomSmsSender(map);
if(isOk) {
model.addAttribute("view", view);
} else {
model.addAttribute("resultMsg", egovMessageSource.getMessage("fail.common.idpwd.search"));
return "forward:/usr/mem/userIdPwdSearch01.do";
}
} else {
model.addAttribute("resultMsg", egovMessageSource.getMessage("fail.common.idpwd.search"));
return "forward:/usr/mem/userIdPwdSearch01.do";
}
} else {
model.addAttribute("resultMsg", egovMessageSource.getMessage("fail.common.idpwd.search"));
return "forward:/usr/mem/userIdPwdSearch01.do";
}
return "usr/mem/userIdPwdSearch02";
}
}
|
package com.zju.courier.service;
import com.zju.courier.entity.Staff;
import com.zju.courier.pojo.StaffPosition;
import java.util.List;
public interface StaffService {
List<Staff> list();
Staff query(int id);
void update(Staff staff);
void insert(Staff staff);
void delete(int id);
List<StaffPosition> load();
}
|
package cn.itcast.core.service.product;
import java.util.List;
import cn.itcast.core.pojo.product.Sku;
public interface SkuService {
//查询库存列表
public List<Sku> selectSkuListByProduct(Long productId);
//修改库存
public void updateSkuById(Sku sku);
}
|
package com.geek._07;
import com.algorithm.tree.TreeNode;
/**
* 输入:root = [1,2,3,null,null,4,5]
* 输出:[1,2,3,null,null,4,5]
*/
public class Serialize {
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
return null;
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
return null;
}
}
|
/******************************************************************************
* __ *
* <-----/@@\-----> *
* <-< < \\// > >-> *
* <-<-\ __ /->-> *
* Data / \ Crow *
* ^ ^ *
* info@datacrow.net *
* *
* This file is part of Data Crow. *
* Data Crow is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public *
* License as published by the Free Software Foundation; either *
* version 3 of the License, or any later version. *
* *
* Data Crow 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 for more details. *
* *
* You should have received a copy of the GNU General Public *
* License along with this program. If not, see http://www.gnu.org/licenses *
* *
******************************************************************************/
package net.datacrow.console.components;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.KeyStroke;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.text.JTextComponent;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.CannotUndoException;
import javax.swing.undo.UndoManager;
import net.datacrow.core.resources.DcResources;
public class DcUndoListenerer {
private final UndoManager undo = new UndoManager();
private final UndoAction undoAction;
private final RedoAction redoAction;
public DcUndoListenerer(JTextComponent component) {
this.undoAction = new UndoAction();
this.redoAction = new RedoAction();
component.getDocument().addUndoableEditListener(new UndoEditListener());
component.getActionMap().put("Undo", undoAction);
component.getInputMap().put(KeyStroke.getKeyStroke("control Z"), DcResources.isInitialized() ? DcResources.getText("lblUndo") : "Undo");
component.getActionMap().put("Redo", redoAction);
component.getInputMap().put(KeyStroke.getKeyStroke("control Y"), DcResources.isInitialized() ? DcResources.getText("lblRedo") : "Redo");
}
public UndoAction getUndoAction() {
return undoAction;
}
public RedoAction getRedoAction() {
return redoAction;
}
protected class UndoEditListener implements UndoableEditListener {
@Override
public void undoableEditHappened(UndoableEditEvent e) {
undo.addEdit(e.getEdit());
updateUndoState();
updateRedoState();
}
}
public void redo() {
try {
undo.redo();
} catch (CannotRedoException ignore) {}
updateRedoState();
updateUndoState();
}
protected void updateRedoState() {
if (undo.canRedo()) {
redoAction.setEnabled(true);
redoAction.putValue(Action.NAME, undo.getRedoPresentationName());
} else {
redoAction.setEnabled(false);
redoAction.putValue(Action.NAME, DcResources.isInitialized() ? DcResources.getText("lblRedo") : "Redo");
}
}
public void undo() {
try {
undo.undo();
} catch (CannotUndoException ignore) {}
updateUndoState();
updateRedoState();
}
protected void updateUndoState() {
if (undo.canUndo()) {
undoAction.setEnabled(true);
undoAction.putValue(Action.NAME, undo.getUndoPresentationName());
} else {
undoAction.setEnabled(false);
undoAction.putValue(Action.NAME, DcResources.isInitialized() ? DcResources.getText("lblUndo") : "Undo");
}
}
public class UndoAction extends AbstractAction {
public UndoAction() {
super(DcResources.isInitialized() ? DcResources.getText("lblUndo") : "Undo");
setEnabled(false);
}
@Override
public void actionPerformed(ActionEvent e) {
undo();
}
}
public class RedoAction extends AbstractAction {
public RedoAction() {
super(DcResources.isInitialized() ? DcResources.getText("lblRedo") : "Redo");
setEnabled(false);
}
@Override
public void actionPerformed(ActionEvent e) {
redo();
}
}
}
|
package ru.mcfr.oxygen.framework.operations.table;
import ro.sync.ecss.extensions.api.*;
import ro.sync.ecss.extensions.api.access.AuthorTableAccess;
import ro.sync.ecss.extensions.api.node.AuthorDocumentFragment;
import ro.sync.ecss.extensions.api.node.AuthorNode;
import javax.swing.text.BadLocationException;
/**
* Created by IntelliJ IDEA.
* User: ws
* Date: 29.03.11
* Time: 16:42
* To change this template use File | Settings | File Templates.
*/
public class InsertCellOperation implements AuthorOperation{
public void doOperation(AuthorAccess authorAccess, ArgumentsMap argumentsMap) throws IllegalArgumentException, AuthorOperationException {
AuthorDocumentController controller = authorAccess.getDocumentController();
AuthorSchemaManager manager = authorAccess.getDocumentController().getAuthorSchemaManager();
AuthorTableAccess tableContainer = authorAccess.getTableAccess();
int currentPosition = authorAccess.getEditorAccess().getCaretOffset();
try {
AuthorNode seldNode = controller.getNodeAtOffset(currentPosition);
while (!seldNode.getName().equals("ячейка"))
seldNode = seldNode.getParent();
int insertPosition = seldNode.getEndOffset() + 1;
AuthorDocumentFragment cellFragment = controller.createNewDocumentFragmentInContext("<ячейка/>", insertPosition);
controller.insertFragment(insertPosition, cellFragment);
} catch (BadLocationException e) {
e.printStackTrace();
}
}
public ArgumentDescriptor[] getArguments() {
return new ArgumentDescriptor[0]; //To change body of implemented methods use File | Settings | File Templates.
}
public String getDescription() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
}
|
package main;
import java.io.FileInputStream;
import org.apache.jena.larq.IndexBuilderString;
import org.apache.jena.larq.IndexLARQ;
import org.apache.jena.larq.LARQ;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.query.ResultSetFormatter;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Property;
public class tplo17main {
public static String ontoFilename = "documents/lo17.owl";
public static String ontoFilenameN3 = "documents/lo17.n3";
public static String kbUTF8Filename = "documents/kblo17-utf8.owl";
public static String LO17_PREFIX = "lo17";
public static Logger logger = Logger.getLogger("com.hp");
/**
* @param args
*/
public static void main(String[] args) {
BasicConfigurator.configure();
logger.setLevel(Level.INFO);
q2();
}
// Réponse à la question 2
public static void q2() {
Model model = null;
model = ModelFactory.createDefaultModel();
try {
// Crée un model = parser ontologie/bdc
// pour parser ontologie
//model.read(new FileInputStream(ontoFilename), "RDF/XML");
// pour parser bdc
// model.read(new FileInputStream(kbUTF8Filename), "RDF/XML");
// query2_a(model, "queries/query_bdc_kblo17_date.sparql");
// larq
model.read(new FileInputStream(kbUTF8Filename), "RDF/XML");
IndexLARQ index = getWholeStringIndex(model);
Query q = readFileQuery("queries/query_bdc_kblo17_index.sparql");
queryIndex(q, index, model);
// IndexLARQ index2 = getPropertyIndex(model, "hasAuteur");
// Query q2 = readFileQuery("queries/query_bdc_kblo17_index.sparql");
// queryIndex(q2, index, model);
// à continuer
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Exemple de requête à partir d'un fichier
* @param model
*/
public static void query2_a(Model model, String file) {
Query q = readFileQuery(file);
// Remplacer les ???? dans le fichier requête
System.out.println("===== Concepts =====");
runQuery(q, model);
}
/**
* Retourne une query à partir d'un nom de fichier
* @param filename
* @return
*/
public static Query readFileQuery(String filename) {
return QueryFactory.read(filename);
}
/**
* Retourne une query à partir de la chaîne de la query
* @param queryString
* @return
*/
public static Query readStringQuery(String queryString) {
return QueryFactory.create(queryString);
}
/**
* Exécute une query sur un model. L'affichage se fait dans la console
* @param q
* @param model
*/
public static void runQuery(Query q, Model model) {
QueryExecution queryExecution = QueryExecutionFactory.create(q, model);
ResultSet r = queryExecution.execSelect();
ResultSetFormatter.out(System.out, r);
queryExecution.close();
}
/**
* Exécute une query nécessitant un index LARQ.
* La sortie se fait dans la console
* @param q
* @param index
* @param model
*/
public static void queryIndex(Query q, IndexLARQ index, Model model) {
QueryExecution queryExecution = QueryExecutionFactory.create(q, model);
LARQ.setDefaultIndex(queryExecution.getContext(), index);
ResultSet r = queryExecution.execSelect();
ResultSetFormatter.out(System.out, r);
queryExecution.close();
}
/**
* Retourne l'index des noeuds littéraux de toute la base
* @param model
* @return
*/
public static IndexLARQ getWholeStringIndex(Model model) {
IndexBuilderString larqBuilder = new IndexBuilderString();
larqBuilder.indexStatements(model.listStatements());
larqBuilder.closeWriter();
model.unregister(larqBuilder);
return larqBuilder.getIndex();
}
/**
* Crée un index à partir du nom local d'une propriété
* usage : IndexLARQ titreIndex = getPropertyIndex(model, "hasTitreArticle");
* @param model
* @param propertyLocalName
* @return
*/
public static IndexLARQ getPropertyIndex(Model model,String propertyLocalName) {
Property p = getProperty(model, propertyLocalName);
IndexBuilderString larqBuilder = new IndexBuilderString(p);
larqBuilder.indexStatements(model.listStatements());
larqBuilder.closeWriter();
model.unregister(larqBuilder);
return larqBuilder.getIndex();
}
/**
* Méthode privée utile pour la méthode précédente.
* @param model
* @param localName
* @return
*/
private static Property getProperty(Model model, String localName) {
String nslo17 = model.getNsPrefixURI(LO17_PREFIX);
Property p = model.getProperty(nslo17 + localName);
return p;
}
}
|
import oop.ex3.searchengine.Hotel;
import org.junit.*;
import static org.junit.Assert.*;
public class BoopingSiteTest {
/** name file of hotels_tst1 which has only one city */
private static final String DATASET_ONE_CITY = "hotels_tst1.txt";
/** name file of hotels_tst2 which is empty */
private static final String DATASET_EMPTY = "hotels_tst2.txt";
/** name file of hotels_dataset which is the full dataset */
private static final String DATASET_FULL = "hotels_dataset.txt";
/** city name not in database */
private static final String CITY_NOT_IN_DATABASE = "makore";
/** city name in database */
private static final String CITY_IN_DATABASE = "manali";
/** representing the maximum star rating possible */
private static final int MAXIMUM_STAR_RATING = 5;
/** representing a valid double latitude degree [-90,90] */
private static final double VALID_LATITUDE = 85.2;
/** representing double value over 90 degree */
private static final double OVER_90_LATITUDE = 91.1;
/** representing double value below (-90) degree */
private static final double BELOW_MINUS_90_LATITUDE = (-91.3);
/** representing a valid double longitude degree [-180,180] */
private static final double VALID_LONGITUDE = 150.4;
/** representing double value over 180 degree */
private static final double OVER_180_LONGITUDE = 180.8;
/** representing double value below (-180) degree */
private static final double BELOW_MINUS_180_LONGITUDE = (-183.6);
/** representing the numbers of hotels in DATASET_ONE_CITY (all of them) */
private static final int NUMBER_OF_HOTELS_IN_DATASET_ONE_CITY = 70;
/** representing the numbers of hotels in DATASET_EMPTY (no hotels because it's empty) */
private static final int NUMBER_OF_HOTELS_IN_DATASET_EMPTY = 0;
/** representing the smallest string possible according to the alphabet order */
private static final String SMALLEST_STRING_POSSIBLE = "a";
/** representing the equal value is returned from comparator method */
private static final int COMPARE_EQUAL = 0;
BoopingSite boopingSite_empty = new BoopingSite(DATASET_EMPTY);
BoopingSite boopingSite_one_city = new BoopingSite(DATASET_ONE_CITY);
BoopingSite boopingSite_full = new BoopingSite(DATASET_FULL);
/**
* reset the boopingSite after each test
*/
@Before
public void reset() {
boopingSite_empty = new BoopingSite(DATASET_EMPTY);
boopingSite_one_city = new BoopingSite(DATASET_ONE_CITY);
boopingSite_full = new BoopingSite(DATASET_FULL);
}
/**
* test constructor function
*/
@Test
public void constructorTest() {
assertNotNull(boopingSite_empty);
assertNotNull(boopingSite_one_city);
assertNotNull(boopingSite_full);
}
/**
* test getHotelsInCityByRating function
*/
@Test
public void getHotelsInCityByRatingTest() {
hotelsInCityByRatingTest(boopingSite_empty);
hotelsInCityByRatingTest(boopingSite_one_city);
hotelsInCityByRatingTest(boopingSite_full);
}
/**
* test getHotelsInCityByRating function with given BoopingSite object
*/
private void hotelsInCityByRatingTest(BoopingSite boopingSite) {
// --------------------- invalid inputs ---------------------
Hotel[] empty_hotel_array = new Hotel[0];
// no hotels in the given city (==city not in database)
assertArrayEquals(empty_hotel_array, boopingSite.getHotelsInCityByRating(CITY_NOT_IN_DATABASE));
// given city name is null
assertArrayEquals(empty_hotel_array, boopingSite.getHotelsInCityByRating(null));
// --------------------- valid inputs ---------------------
Hotel[] sorted_rating_hotels = boopingSite.getHotelsInCityByRating(CITY_IN_DATABASE);
int last_star_rating = MAXIMUM_STAR_RATING;
String last_hotel_name = SMALLEST_STRING_POSSIBLE;
// moving across all returned hotels and check if their rating and name is in descending order
for (Hotel hotel : sorted_rating_hotels) {
// current rate is bigger than last
assertFalse(hotel.getStarRating() > last_star_rating);
// if they have the same rating => check current name is before the last name in alphabet order
if (hotel.getStarRating() == last_star_rating) {
assertFalse(last_hotel_name.compareTo(hotel.getPropertyName()) < COMPARE_EQUAL);
}
last_star_rating = hotel.getStarRating();
last_hotel_name = hotel.getPropertyName();
}
}
/**
* calculating the distance from (x1,y1) to (x2,y2) according to the Euclidean distance
* @param x1 : double of latitude
* @param y1 : double of longitude
* @return double of the distance
*/
private double calculateDistance(double x1, double y1) {
return Math.sqrt(((BoopingSiteTest.VALID_LONGITUDE - y1) * (BoopingSiteTest.VALID_LONGITUDE - y1)) +
((BoopingSiteTest.VALID_LATITUDE - x1) * (BoopingSiteTest.VALID_LATITUDE - x1)));
}
/**
* test getHotelsByProximity function
*/
@Test
public void getHotelsByProximityTest() {
hotelsByProximityTest(boopingSite_empty);
hotelsByProximityTest(boopingSite_one_city);
hotelsByProximityTest(boopingSite_full);
}
/**
* test getHotelsByProximity function with given BoopingSite object
*/
private void hotelsByProximityTest(BoopingSite boopingSite) {
// --------------------- invalid inputs ---------------------
Hotel[] empty_hotel_array = new Hotel[0];
// invalid: latitude > 90
assertArrayEquals(empty_hotel_array,
boopingSite.getHotelsByProximity(OVER_90_LATITUDE, VALID_LONGITUDE));
// invalid: latitude < (-90)
assertArrayEquals(empty_hotel_array,
boopingSite.getHotelsByProximity(BELOW_MINUS_90_LATITUDE, VALID_LONGITUDE));
// invalid: longitude > 180
assertArrayEquals(empty_hotel_array,
boopingSite.getHotelsByProximity(VALID_LATITUDE, OVER_180_LONGITUDE));
// invalid: longitude < (-180)
assertArrayEquals(empty_hotel_array,
boopingSite.getHotelsByProximity(VALID_LATITUDE, BELOW_MINUS_180_LONGITUDE));
// --------------------- valid inputs ---------------------
Hotel[] sorted_proximity_hotels = boopingSite.getHotelsByProximity(VALID_LATITUDE, VALID_LONGITUDE);
// checking the number of hotels in sorted_proximity_hotels
if (boopingSite == boopingSite_empty) {
assertEquals(NUMBER_OF_HOTELS_IN_DATASET_EMPTY, sorted_proximity_hotels.length);
} else if (boopingSite == boopingSite_one_city) {
assertEquals(NUMBER_OF_HOTELS_IN_DATASET_ONE_CITY, sorted_proximity_hotels.length);
}
double last_distance = 0.0; // initialize to not important value
int last_POIs_number = 0;
boolean first_hotel = true;
// moving across all hotels and check if their proximity and POIs are in the right order
for (Hotel hotel : sorted_proximity_hotels) {
if (first_hotel) {
last_distance = calculateDistance(hotel.getLatitude(), hotel.getLongitude());
last_POIs_number = hotel.getNumPOI();
first_hotel = false;
continue;
}
double curr_distance = calculateDistance(hotel.getLatitude(), hotel.getLongitude());
// current distance is smaller than lat distance
assertFalse(curr_distance < last_distance);
// if they have the same distance => check if curr number of POI is bigger than last POI number
if (curr_distance == last_distance) {
assertFalse(last_POIs_number < hotel.getNumPOI());
}
last_distance = curr_distance;
last_POIs_number = hotel.getNumPOI();
}
}
/**
* test getHotelsByProximity function
*/
@Test
public void getHotelsInCityByProximityTest() {
hotelsInCityByProximityTest(boopingSite_empty);
hotelsInCityByProximityTest(boopingSite_one_city);
hotelsInCityByProximityTest(boopingSite_full);
}
/**
* test getHotelsInCityByProximity function with given BoopingSite object
*/
private void hotelsInCityByProximityTest(BoopingSite boopingSite) {
// --------------------- invalid inputs ---------------------
Hotel[] empty_hotel_array = new Hotel[0];
// invalid: city not in database
assertArrayEquals(empty_hotel_array, boopingSite
.getHotelsInCityByProximity(CITY_NOT_IN_DATABASE, VALID_LATITUDE, VALID_LONGITUDE));
// invalid: city's name is null
assertArrayEquals(empty_hotel_array, boopingSite
.getHotelsInCityByProximity(null, VALID_LATITUDE, VALID_LONGITUDE));
// invalid: latitude > 90
assertArrayEquals(empty_hotel_array, boopingSite
.getHotelsInCityByProximity(CITY_IN_DATABASE, OVER_90_LATITUDE, VALID_LONGITUDE));
// invalid: latitude < (-90)
assertArrayEquals(empty_hotel_array, boopingSite
.getHotelsInCityByProximity(CITY_IN_DATABASE, BELOW_MINUS_90_LATITUDE, VALID_LONGITUDE));
// invalid: longitude > 180
assertArrayEquals(empty_hotel_array, boopingSite
.getHotelsInCityByProximity(CITY_IN_DATABASE, VALID_LATITUDE, OVER_180_LONGITUDE));
// invalid: longitude < (-180)
assertArrayEquals(empty_hotel_array, boopingSite
.getHotelsInCityByProximity(CITY_IN_DATABASE, VALID_LATITUDE, BELOW_MINUS_180_LONGITUDE));
// --------------------- valid inputs ---------------------
Hotel[] sorted_proximity_hotels_by_city = boopingSite
.getHotelsInCityByProximity(CITY_IN_DATABASE, VALID_LATITUDE, VALID_LONGITUDE);
// checking the number of hotels in sorted_proximity_hotels
if (boopingSite == boopingSite_empty) {
assertEquals(NUMBER_OF_HOTELS_IN_DATASET_EMPTY, sorted_proximity_hotels_by_city.length);
} else if (boopingSite == boopingSite_one_city) {
assertEquals(NUMBER_OF_HOTELS_IN_DATASET_ONE_CITY, sorted_proximity_hotels_by_city.length);
}
double last_distance = 0.0; // initialize to not important value
int last_POIs_number = 0;
boolean first_hotel = true;
// moving across all returned hotels and check if their proximity and POIs are in the right order
for (Hotel hotel : sorted_proximity_hotels_by_city) {
// hotel is not from the given city
assertEquals(CITY_IN_DATABASE, hotel.getCity());
if (first_hotel) {
last_distance = calculateDistance(hotel.getLatitude(), hotel.getLongitude());
last_POIs_number = hotel.getNumPOI();
first_hotel = false;
continue;
}
double curr_distance = calculateDistance(hotel.getLatitude(), hotel.getLongitude());
// current distance is smaller than lat distance
assertFalse(curr_distance < last_distance);
// if they have the same distance => check if curr number of POI is bigger than last POI number
if (curr_distance == last_distance) {
assertFalse(last_POIs_number < hotel.getNumPOI());
}
last_distance = curr_distance;
last_POIs_number = hotel.getNumPOI();
}
}
}
|
/**
*
*/
package com.UBQPageObjectLib;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import com.UBQGenericLib.WebDriverCommonLib;
/**
* @author Basanagouda
*
*/
public class VehicleMaster extends WebDriverCommonLib {
WebDriver driver;
// ----------------------Constructor----------------------//
public VehicleMaster(WebDriver driver) {
this.driver = driver;
}
// ----------------------UI Elements----------------------//
// ---For vehicle no---//
@FindBy(how = How.XPATH, using = "//input[@id='vehicle_no']")
private WebElement Vehicleno;
// ---For Vehicle desc---//
@FindBy(how = How.XPATH, using = "//input[@id='vehicle_desc']")
private WebElement Vehicledesc;
// ---For vehicleTypeId---//
@FindBy(how = How.XPATH, using = "//select[@id='vehicleTypeId']")
private WebElement vehicleTypeId;
// ---For VehicleCapacityCBB---//
@FindBy(how = How.XPATH, using = "//input[@id='vehicleCapacityCBB']")
private WebElement VehicleCapacityCBB;
// ---For VehicleCapacityValue---//
@FindBy(how = How.XPATH, using = "//input[@id='vehicleCapacityValue']")
private WebElement VehicleCapacityValue;
// ---For vehicleCapacityTonnes---//
@FindBy(how = How.XPATH, using = "//input[@id='vehicleCapacityTonnes']")
private WebElement VehicleCapacityTonnes;
// ---For SelectIsActive---//
@FindBy(how = How.XPATH, using = "//input[@id='vehicle_is_active']")
private WebElement SelectIsActive;
// ---For ClcikSaveBtn---//
@FindBy(how = How.XPATH, using = "//input[@id='saveBtn']")
private WebElement ClcikSaveBtn;
// ---For ClcikCancelBtn---//
@FindBy(how = How.XPATH, using = "//input[@id='cancel']")
private WebElement ClcikCancelBtn;
// ---For SearchText---//
@FindBy(how = How.XPATH, using = "//input[@id='searchTxt']")
private WebElement SearchText;
// ---For SearchBtn---//
@FindBy(how = How.XPATH, using = "//input[@id='searchbtn']")
private WebElement SearchBtn;
// ----------------------Functions----------------------//
public void enterVehicleno(String vehicleno) {
entervalue(vehicleno, Vehicleno);
}
public String getVehicleno() {
return getvalue(Vehicleno);
}
public void enterVehicledesc(String vehicledesc) {
entervalue(vehicledesc, Vehicledesc);
}
public String getVehicledesc() {
return getvalue(Vehicledesc);
}
// ---For Select SBU function---//
public void SelectVehicleTypeId(String vehicletype) {
selectvalue(vehicletype, vehicleTypeId);
}
public String getVehicleTypeId() {
return getselectDrpdwnValue(vehicleTypeId);
}
public void enterVehicleCapacityCBB(String vehicleCapacityCBB) {
entervalue(vehicleCapacityCBB, VehicleCapacityCBB);
}
public String getVehicleCapacityCBB() {
return getvalue(VehicleCapacityCBB);
}
public void enterVehicleCapacityValue(String vehicleCapacityValue) {
entervalue(vehicleCapacityValue, VehicleCapacityValue);
}
public String getVehicleCapacityValue() {
return getvalue(VehicleCapacityValue);
}
public void enterVehicleCapacityTonnes(String vehicleCapacityTonnes) {
entervalue(vehicleCapacityTonnes, VehicleCapacityTonnes);
}
public String getVehicleCapacityTonnes() {
return getvalue(VehicleCapacityTonnes);
}
// ---For SelectIsActive---//
public void SelectIsActive() {
checkboxselect(SelectIsActive);
}
// ---For ClcikSaveBtn---//
public void ClickOnOk() {
buttonClick(ClcikSaveBtn);
}
// ---For ClcikCancelBtn---//
public void ClickOnCancel() {
buttonClick(ClcikCancelBtn);
}
// ---For SearchText---//
public void enterSearchText(String searchtext) {
entervalue(searchtext, SearchText);
}
// ---For ClickOnSearchBtn---//
public void ClickOnSearchBtn() {
buttonClick(SearchBtn);
}
}
|
package net.codejava.spring.controller;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
@Controller
public class HomeController {
@RequestMapping(value = "/")
public ModelAndView goHome(HttpServletResponse response) throws IOException {
return new ModelAndView("home");
}
@RequestMapping(value = "/viewXSLT")
public ModelAndView viewXSLT(HttpServletRequest request,
HttpServletResponse response) throws IOException {
// builds absolute path of the XML file
String xmlFile = "resources/citizens.xml";
String contextPath = request.getServletContext().getRealPath("");
String xmlFilePath = contextPath + File.separator + xmlFile;
Source source = new StreamSource(new File(xmlFilePath));
// adds the XML source file to the model so the XsltView can detect
ModelAndView model = new ModelAndView("XSLTView");
model.addObject("xmlSource", source);
return model;
}
@RequestMapping(value = "/viewXSLTtry")
public ModelAndView viewXSLTtry(HttpServletRequest request,
HttpServletResponse response) throws IOException {
// builds absolute path of the XML file
String xmlFile = "resources/myCDcollection_1.xml";
String contextPath = request.getServletContext().getRealPath("");
String xmlFilePath = contextPath + File.separator + xmlFile;
Source source = new StreamSource(new File(xmlFilePath));
// adds the XML source file to the model so the XsltView can detect
ModelAndView model = new ModelAndView("XSLTViewTry");
model.addObject("xmlSource", source);
return model;
}
@RequestMapping(value = "/viewXSLTAccessLog")
public ModelAndView viewXSLTAccessLog(HttpServletRequest request,
HttpServletResponse response) throws IOException {
// builds absolute path of the XML file
String xmlFile = "resources/accessLog.xml";
String contextPath = request.getServletContext().getRealPath("");
String xmlFilePath = contextPath + File.separator + xmlFile;
Source source = new StreamSource(new File(xmlFilePath));
// adds the XML source file to the model so the XsltView can detect
ModelAndView model = new ModelAndView("XSLTViewAccessLog");
model.addObject("xmlSource", source);
return model;
}
@RequestMapping(value = "/viewIterator")
public void viewIterator(HttpServletRequest request,
HttpServletResponse response) throws IOException, ParserConfigurationException, TransformerException {
//创建解析DOM解析器
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.newDocument();
//根元素
Element documentElement = doc.createElement("document");
doc.appendChild(documentElement);
//响应数据
CloseableHttpResponse response1 = HttpClients.createDefault().execute(new HttpGet("https://redan-api.herokuapp.com/story/"));
//返回获取实体
HttpEntity entity = response1.getEntity();
if (entity != null) {
String str = EntityUtils.toString(entity, "UTF-8");
//把这个字符串转成json数组
JSONArray jsonArray = new JSONObject(str).getJSONArray("result");
//拿到第一个对象
JSONObject jsonObject = jsonArray.getJSONObject(0);
//通过第一个对象拿到所有的值
Iterator<String> keys = jsonObject.keys();
//
while (keys.hasNext()) {
//第一层所有key
String next = keys.next();
//拿到对象所对应的key所对应的value
String getKey = jsonObject.get(next).toString();
System.out.println("第一次的所有key-- " + next + "第一次的所有values" + getKey);
// doc.createElement(getKey);
//是文本的情况下
Element element1 = doc.createElement(next);
if (!(getKey.endsWith("}") || getKey.endsWith("]"))) {
//创建第一层的子节点
System.out.println(next + " " + getKey);
element1.setTextContent(getKey);
}
documentElement.appendChild(element1);
if (getKey.endsWith("}")) {
//第二层json对象
JSONObject jsonObject2 = jsonObject.getJSONObject(next);
//json对象的key
Iterator<String> key1 = jsonObject2.keys();
while (key1.hasNext()) {
//拿到所有key
String next1 = key1.next();
String value2 = jsonObject2.getString(next1);
Element element2 = doc.createElement(next1);
element2.setTextContent(value2);
element1.appendChild(element2);
}
} //如果第json是数组
if (getKey.endsWith("]")) {
JSONArray jsonArray1 = jsonObject.getJSONArray(next);
for (int i = 0; i < jsonArray1.length(); i++) {
JSONObject jsonObject2 = jsonArray1.getJSONObject(i);
Iterator<String> key3 = jsonObject2.keys();
while (key3.hasNext()) {
//拿到所有key
String next2 = key3.next();
String value3 = jsonObject2.get(next2).toString();
Element element3 = doc.createElement(next2);
if (!value3.endsWith("}")) {
element3.setTextContent(value3);
}
element1.appendChild(element3);
//判断第三层是否还是json对
if (value3.endsWith("}")) {
JSONObject jsonObject3 = jsonObject2.getJSONObject(next2);
Iterator<String> key4 = jsonObject3.keys();
while (key4.hasNext()) {
String next5 = key4.next();
//通过key拿到对应的valus
String value = jsonObject3.getString(next5);
System.out.println(next5 + " 第三层的的值 " + value);
Element element4 = doc.createElement(next5);
element4.setTextContent(value);
element3.appendChild(element4);
}
}
}
}
}
}
}
//更新到本项目
TransformerFactory.newInstance().newTransformer().transform(new DOMSource(doc), new StreamResult(response.getOutputStream()));
}
@RequestMapping(value = "/viewFor")
@ResponseBody
public void viewFor(HttpServletRequest request,
HttpServletResponse response) throws IOException, ParserConfigurationException, TransformerException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.newDocument();
Element documentElement = doc.createElement("document");
doc.appendChild(documentElement);
CloseableHttpResponse response1 = HttpClients.createDefault().execute(new HttpGet("https://redan-api.herokuapp.com/story/"));
HttpEntity entity = response1.getEntity();
if (entity != null) {
String str = EntityUtils.toString(entity, "UTF-8");
//获取的最外层的json数组
JSONArray jsonArray = new JSONObject(str).getJSONArray("result");
JSONObject jsonObject = jsonArray.getJSONObject(0);
Iterator<String> keys = jsonObject.keys();
for (int i = 0; i < jsonObject.length(); i++) {
//拿到这第一层的所有的节点
String key1 = keys.next();
String string1 = jsonObject.getString(key1);
//创建节点
Element key1eElement = doc.createElement(key1);
if (!string1.endsWith("}") && !string1.endsWith("]")) {
key1eElement.setTextContent(string1);
}
documentElement.appendChild(key1eElement);
//是json 对象时候
if (string1.startsWith("{")) {
JSONObject jsono2 = jsonObject.getJSONObject(key1);
Iterator<String> keys2 = jsono2.keys();
for (int j = 0; j < jsono2.length(); j++) {
String next2 = keys2.next();
String vaString = jsono2.getString(next2);
Element key3eElement = doc.createElement(next2);
key3eElement.setTextContent(vaString);
key1eElement.appendChild(key3eElement);
}
}
//是数组的情况
if (string1.startsWith("[")) {
JSONArray json3 = jsonObject.getJSONArray(key1);//鎵?鏈夊??
for (int j = 0; j < json3.length(); j++) {
JSONObject json4 = json3.getJSONObject(j);
for (Iterator<String> keys3 = json4.keys(); keys3.hasNext();) {
String next4 = keys3.next();
String stringValue = json4.get(next4).toString();
Element key5Element = doc.createElement(next4);
key1eElement.appendChild(key5Element);
if (stringValue.startsWith("{")) {
JSONObject json5 = json4.getJSONObject(next4);
Iterator<String> keys4 = json5.keys();
for (int r = 0; r < json5.length(); r++) {
String next5 = keys4.next();
String stringValue2 = json5.getString(next5);
Element key6Element = doc.createElement(next5);
key6Element.setTextContent(stringValue2);
key5Element.appendChild(key6Element);
}
} else if (!stringValue.startsWith("{")) {
System.out.println("key5" + next4 + "stringValue" + stringValue);
key5Element.setTextContent(stringValue);
}
}
}
}
}
//更新到本项目
TransformerFactory.newInstance().newTransformer().transform(new DOMSource(doc), new StreamResult(response.getOutputStream()));
}
}
@RequestMapping(value = "/getView")
@ResponseBody
public void getView(HttpServletRequest request,
HttpServletResponse response) throws IOException, ParserConfigurationException, TransformerException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.newDocument();
//创建的根元素
Element documentElement = doc.createElement("document");
doc.appendChild(documentElement);
//创建客户端
CloseableHttpResponse response1 = HttpClients.createDefault().execute(new HttpGet("https://redan-api.herokuapp.com/story/"));
//返回字符串实体
HttpEntity entity1 = response1.getEntity();
if (entity1 != null) {
//给返回的实体设置编码
String retSrc = EntityUtils.toString(entity1, "UTF-8");
//获得最外层的元素的是个数组
JSONArray storyList = new JSONObject(retSrc).getJSONArray("result");
// 那么遍历里面的元素取出所有的元素
for (int i = 0; i < storyList.length(); i++) {
//拿到json 每个数组元素判断json数组判断元素是否对象还是数组
JSONObject jsonObject = storyList.getJSONObject(i);
Iterator<String> next1 = jsonObject.keys();
while (next1.hasNext()) {
String next2 = next1.next();
//文本的情况下
Element documentNext2 = doc.createElement(next2);
String teString = jsonObject.get(next2).toString();
if (!(next2.equals("author") || next2.equals("comments"))) {
documentNext2.setTextContent(teString);
}
documentElement.appendChild(documentNext2);
//在comments数组中
if (next2.equals("comments")) {
JSONArray jsonArray = jsonObject.getJSONArray(next2);
//创建标签节点
for (int j = 0; j < jsonArray.length(); j++) {
JSONObject jsonObject3 = jsonArray.getJSONObject(j);
Iterator<String> next3 = jsonObject3.keys();
while (next3.hasNext()) {
String next4 = next3.next();
Element elementNext4 = doc.createElement(next4);
if (!next4.equals("who")) {
String vaString = jsonObject3.getString(next4);
elementNext4.setTextContent(vaString);
}
if (next4.equals("who")) {
JSONObject jsonObject4 = jsonObject3.getJSONObject(next4);
Iterator<String> next5 = jsonObject4.keys();
while (next5.hasNext()) {
String next6 = next5.next();
String vaString = jsonObject4.getString(next6);
Element documentNext6 = doc.createElement(next6);
documentNext6.setTextContent(vaString);
elementNext4.appendChild(documentNext6);
}
}
documentNext2.appendChild(elementNext4);
}
}
}
if (next2.equals("author")) {
JSONObject jsonObject5 = jsonObject.getJSONObject(next2);
Iterator<String> next7 = jsonObject5.keys();
while (next7.hasNext()) {
String next8 = next7.next();
String vaString2 = jsonObject5.getString(next8);
//创建节点标签
Element documentNext8 = doc.createElement(next8);
documentNext8.setTextContent(vaString2);
documentNext2.appendChild(documentNext8);
}
}
}
}
}
//更新到本项目
TransformerFactory.newInstance().newTransformer().transform(new DOMSource(doc), new StreamResult(response.getOutputStream()));
}
@RequestMapping(value = "/viewXSL")
public ModelAndView getXsl(HttpServletRequest request,
HttpServletResponse response) throws IOException, ParserConfigurationException, TransformerException {
// builds absolute path of the XML file
String xmlFile = "resources/B.xml";
String contextPath = request.getServletContext().getRealPath("");
String xmlFilePath = contextPath + File.separator + xmlFile;
Source source = new StreamSource(new File(xmlFilePath));
// adds the XML source file to the model so the XsltView can detect
ModelAndView model = new ModelAndView("B");
model.addObject("xmlSource", source);
return model;
}
}
|
package com.git.cloud.resmgt.common.dao.impl;
import com.git.cloud.common.dao.CommonDAOImpl;
import com.git.cloud.common.exception.RollbackableBizException;
import com.git.cloud.resmgt.common.dao.IRmHostTypeDAO;
import com.git.cloud.resmgt.common.model.po.RmHostTypePo;
public class RmHostTypeDAO extends CommonDAOImpl implements IRmHostTypeDAO{
@Override
public RmHostTypePo getRmHostTypeById(String hostTypeId) throws RollbackableBizException {
return super.findObjectByID("getRmHostTypeById", hostTypeId);
}
}
|
package com.quaspecsystems.payspec.service.business.impl;
import com.quaspecsystems.payspec.lib.exception.QuaspecServiceException;
import com.quaspecsystems.payspec.lib.model.IUser;
import com.quaspecsystems.payspec.lib.service.UserService;
import com.quaspecsystems.payspec.persistence.domain.Employee;
import com.quaspecsystems.payspec.persistence.domain.Organization;
import com.quaspecsystems.payspec.persistence.domain.User;
import com.quaspecsystems.payspec.persistence.repository.DataAccessService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
@Service("userService")
public class UserServiceImpl implements UserService{
public final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
@Autowired
private DataAccessService dataAccessService;
@Autowired
private PasswordEncoder passwordEncoder;
@Override
@Transactional
public IUser getByUserId(Long userId) throws QuaspecServiceException {
Optional<User> user = dataAccessService.getUserRepository().findById(userId);
if(user.isPresent()){
return user.get();
}
return null;
}
@Override
@Transactional
public List<? extends IUser> getAll() throws QuaspecServiceException {
return dataAccessService.getUserRepository().findAll();
}
@Override
@Transactional
public IUser getByUsername(String username) throws QuaspecServiceException {
return dataAccessService.getUserRepository().findByUserName(username);
}
@Override
public IUser createUser(IUser iUser) throws QuaspecServiceException {
IUser user = null;
User customer = null;
Employee employee = null;
Organization organization = dataAccessService.getOrganizationRepository().findByName(iUser.getOrganization().getName());
if(iUser.getUserType().equalsIgnoreCase("1")) {
customer = new User(iUser.getUserName(),iUser.getEmail(),passwordEncoder.encode(iUser.getPassword()),iUser.getGsmPhoneNumber(), iUser.getNationalId(), organization);
return dataAccessService.getUserRepository().save(customer);
} else if (iUser.getUserType().equalsIgnoreCase("2")) {
employee = new Employee(iUser.getUserName(),iUser.getEmail(),passwordEncoder.encode(iUser.getPassword()),iUser.getGsmPhoneNumber(), iUser.getNationalId(), organization);
return dataAccessService.getUserRepository().save(employee);
}
return null;
}
@Override
public IUser updateUser(IUser iUser) throws QuaspecServiceException {
return createUser(iUser);
}
@Override
public void deleteUser(String userId) throws QuaspecServiceException {
dataAccessService.getUserRepository().deleteById(dataAccessService.getUserRepository().findByUserName(userId).getId());
}
@Override
public boolean isUserExist(String userId) {
return dataAccessService.getUserRepository().existsById(dataAccessService.getUserRepository().findByUserName(userId).getId());
}
}
|
package animalBonus;
public class AnimalTester {
public static void main(String[] args) {
Animal zebra = new Animal(4, "African Savannah");
displayAnimalDetails(zebra);
Dog sledDog = new Dog(4, "Frozen tundra");
sledDog.setBreed("Siberian Husky");
displayAnimalDetails(sledDog);
Fish salmon = new Fish(0, "Freshwater");
salmon.setTasty(true);
displayAnimalDetails(salmon);
Animal trout = new Fish(0, "Freshwater");
displayAnimalDetails(trout);//set tasty to null
Cat jaguar = new Cat(4, "Rainforest");
jaguar.setCoatPattern("Spots");
displayAnimalDetails(jaguar);
Animal tiger = new Cat(4, "Jungle");
displayAnimalDetails(tiger);//sets coat pattern as null
}
public static void displayAnimalDetails(Animal a) {
System.out.println(a.getAnimalInfo());
}
}
|
package kusob;
import java.util.Calendar;
public class DateTest {
public static void main(String[] args) {
Calendar c = Calendar.getInstance();
String ntime = String.valueOf(c.get(Calendar.YEAR));
int a = Integer.parseInt(ntime);
int b = 2016; //2000년도가 1기라고 가정하자
int gisu = a-b+1;
System.out.println(gisu);
}
}
|
/**
* Copyright 2015 Thomas Cashman
*/
package org.protogen.compiler.core.condition;
/**
*
* @author Thomas Cashman
*/
public class OrCondition implements Condition {
private final Condition [] conditions;
public OrCondition(Condition [] conditions) {
this.conditions = conditions;
}
public Condition[] getConditions() {
return conditions;
}
}
|
package id.bts.PiWebRestIoT.services;
public interface GpioService {
void switchOnLedRuang1();
void switchOnLedRuang2();
void switchOffLedRuang1();
void switchOffLedRuang2();
}
|
package inheritance;
/**
* Created by E797240 on 02/11/2016.
*/
public class Customer2Runner {
public static void main(String... args) {
Customer2 customer2 = new Customer2("Rajesh", "London");
customer2.add("Book: Scala in depth");
System.out.println(customer2.total());
DiscoutedCustomer2 discoutedCustomer2 = new DiscoutedCustomer2("Raj","London");
discoutedCustomer2.add("Book: Scala Puzzlers");
System.out.println(discoutedCustomer2.total());
}
}
|
package android.support.v4.widget;
import android.widget.ListView;
public class ListViewAutoScrollHelper extends AutoScrollHelper {
private final ListView mTarget;
public boolean canTargetScrollHorizontally(int i) {
return false;
}
public ListViewAutoScrollHelper(ListView listView) {
super(listView);
this.mTarget = listView;
}
public void scrollTargetBy(int i, int i2) {
ListViewCompat.scrollListBy(this.mTarget, i2);
}
public boolean canTargetScrollVertically(int i) {
ListView listView = this.mTarget;
int count = listView.getCount();
boolean z = false;
if (count == 0) {
return z;
}
int childCount = listView.getChildCount();
int firstVisiblePosition = listView.getFirstVisiblePosition();
int i2 = firstVisiblePosition + childCount;
boolean z2 = true;
if (i > 0) {
if (i2 >= count && listView.getChildAt(childCount - z2).getBottom() <= listView.getHeight()) {
return z;
}
} else if (i < 0) {
return (firstVisiblePosition > 0 || listView.getChildAt(z).getTop() < 0) ? z2 : z;
} else {
return z;
}
}
}
|
package com.daz.student.server;
import java.util.List;
import java.util.Map;
import com.daz.student.pojo.studentPojo;
import com.github.pagehelper.PageInfo;
public interface IStudentServer {
public List<studentPojo> searchStudentList(Map<String, Object> searchConditionMap) throws Exception;
public PageInfo<studentPojo> searchStudentByTeacherId(Map<String, Object> searchConditionMap,int pageNum,int pageSize)throws Exception;
public List<studentPojo> searchStudentIsNotSelect(Map<String, Object> searchConditionMap)throws Exception;
}
|
package by.belotserkovsky.dao;
import by.belotserkovsky.pojos.History;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.Projections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Created by K.Belotserkovsky
*/
@Repository
public class HistoryDao extends Dao<History> implements IHistoryDao {
private static Logger log = Logger.getLogger(HistoryDao.class);
@Autowired
public HistoryDao(SessionFactory sessionFactory){
super(sessionFactory);
}
public List<History> getByUser(int offset, int numberOfRecords, String userName){
String hql = "FROM History hitory WHERE user.userName=:userName";
List<History> all = getSession().createQuery(hql).setParameter("userName", userName).setFirstResult(offset).setMaxResults(numberOfRecords).list();
log.info("Got all.");
return all;
}
public int getFoundRows(String userName){
String hql = "SELECT count(history) FROM History history WHERE user.userName=:userName";
Long result = (Long)getSession().createQuery(hql).setParameter("userName", userName).uniqueResult();
int foundRows = result.intValue();
log.info("Got a number of rows.");
return foundRows;
}
}
|
package com.akulcompany.interfaces;
import com.akulcompany.enums.Group_numbers;
import com.akulcompany.enums.Кafedra_name;
import java.util.ArrayList;
public interface GroupInterface {
Group_numbers getNumber();
Кafedra_name getName_cafedra();
ArrayList<String> getEmployeeList ();
}
|
package com.limefriends.molde.menu_mypage.faq;
public class FaqApi {
public static final String POST_FAQ_API = "/v1/faq";
}
|
package bioui;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.Scanner;
/**
*
* @author timothy
*/
public class DBConnect {
private Connection conn;
private Statement stat;
private ResultSet res;
/**
* Constructor
* @throws java.sql.SQLException
*/
public DBConnect() throws SQLException{
Statement statement = conn.createStatement();
}
/**
* Attempt to log into the database
*/
public void openConnection(){
try{
Class.forName("com.mysql.jbdc.Driver");
String databaseLocation = "jdbc:mysql://localhost:3306/BioDB";
conn=DriverManager.getConnection(databaseLocation);
System.out.println("Connection established");
}
catch(ClassNotFoundException | SQLException e){
System.out.println("Error: You are an idiot because:\n"+e.getMessage());
}
}
/**
* Make a unique transaction number for each form filled.
* Read the number from DO_NOT_TOUCH.txt & return it.
* Replace the number in the file with the next integer.
* @return The transaction ID number
* @throws java.io.FileNotFoundException someone removed the ID file
*/
public int id() throws FileNotFoundException{
//Open the file
String fileName = "DO_NOT_TOUCH.txt";
File file = new File(fileName);
int ID;
//Read the number
try (Scanner inputFile = new Scanner(file)) {
//Read the number
String line = inputFile.nextLine();
//Parse number into ID integer
ID = Integer.parseInt(line);
//Close the file
}
//Replace number in DO_NOT_TOUCH.txt with the next integer
try ( //Open the file
PrintWriter outputFile = new PrintWriter(fileName)) {
//Replace number in DO_NOT_TOUCH.txt with the next integer
outputFile.print(ID+1);
//Close the file
}
//Output the ID number
return ID;
}
/**
* Close the connection to the database
*/
public void closeConnection(){
try {
conn.close();
}
catch (SQLException ex) {
System.out.println("Error: "+ex.getMessage());
}
}
}
|
package org.gavrilov.repository;
import org.gavrilov.domain.User;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
@CacheConfig(cacheNames = "users")
public interface UserRepository extends JpaRepository<User, Long>, JpaSpecificationExecutor<User> {
@Cacheable
@Override
Optional<User> findOne(Specification<User> specification);
}
|
package com.tyj.venus.service.impl;
import com.tyj.venus.dao.UserInfoRepository;
import com.tyj.venus.dao.UserRepository;
import com.tyj.venus.entity.User;
import com.tyj.venus.entity.UserInfo;
import com.tyj.venus.service.UserInfoService;
import com.tyj.venus.service.UserService;
import com.tyj.venus.tools.Tools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
@Service(value = "userInfoService")
public class UserInfoServiceImpl extends BaseServiceImpl <UserInfo, Integer> implements UserInfoService {
@Autowired
private UserInfoRepository userInfoRepository;
@Override
public UserInfo login(String username, String password) {
UserInfo user = userInfoRepository.login(username, Tools.Md5(password));
if (user != null) {
user.setLoginAt(new Date());
user.setLoginCount(user.getLoginCount()+1);
userInfoRepository.save(user);
return user;
}
return null;
}
}
|
package com.cdgpacific.sellercatpal;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.InputStream;
import java.util.ArrayList;
public class ViewImageFullActivity extends AppCompatActivity {
private ProgressDialog pDialog;
public ArrayList<ImageGalleryItem> ImageGallery;
public String URL = ""; //http://www.cheappartsguy.com/api/get/images/tablet/";
public ImageView imageView;
public Button btnBack;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_image_full);
getSupportActionBar().hide();
btnBack = (Button) findViewById(R.id.btnBack);
imageView = (ImageView) findViewById(R.id.image);
URL = getIntent().getStringExtra("url");
URL = URL.replace("THMB", "ORGL");
String title = getIntent().getStringExtra("title");
Bitmap bitmap = getIntent().getParcelableExtra("image");
btnBack.setText("CLICK HERE TO RETURN TO VIEW UNITS IN A BOX");
btnBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
imageView.setImageBitmap(bitmap);
new DownloadImageTask().execute();
}
private class DownloadImageTask extends AsyncTask<Void, Void, Bitmap> {
@Override
protected void onPreExecute() {
loaderShow("Please wait... Downloading Images...");
super.onPreExecute();
}
protected Bitmap doInBackground(Void... urls) {
Bitmap bitmap = null;
try {
Log.d("DONE", URL);
bitmap = do_downloading(URL);
Log.d("DONE", bitmap + "");
Thread.sleep(200);
}
catch (Exception ex) { }
return bitmap;
}
public Bitmap do_downloading(String url) {
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(url).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
Log.d("DONE", "YES");
loaderHide();
imageView.setImageBitmap(result);
}
}
private void loaderShow(String Message) {
pDialog = new ProgressDialog(ViewImageFullActivity.this);
pDialog.setMessage(Message);
pDialog.setCancelable(false);
pDialog.show();
}
private void loaderHide(){
if (pDialog.isShowing())
pDialog.dismiss();
}
}
|
package projecteuler;
public class CombinatoricSelections {
public static void main(String args[]) {
int count = 0;
for (long n = 1; n <= 100; n++) {
for (long r = 1; r <= n; r++) {
long num = fact(n);
long den1 = fact(r);
long den2 = fact(n - r);
long denmul = den1 * den2;
if (denmul == 0) {
System.out.println(n + " " + r);
}
long combination = num / denmul;
if (combination > 1000000) {
System.out.println(combination);
count++;
}
}
}
System.out.println(count);
}
public static long fact(long num) {
if (num == 0) {
return 1;
}
int factorial = 1;
for (int i = 1; i <= num; i++) {
factorial = factorial * i;
}
return factorial;
}
}
|
package com.quickdoodle.trainer.datahandler;
import com.quickdoodle.model.activationfunction.Matrix;
public class Doodle {
/**Instace variable untuk menyimpan nilai pixel dari doodle pada array satu dimensi*/
private double[] pixelValues;
/**Instace variable untuk menyimpan target vector dari doodle*/
private double[] target;
/**Instace variable untuk menyimpan nilai label dari doodle. Nilai ini digunakan untuk menetapkan nilai pada target vector dari doodle*/
private int label;
/**Instace variable untuk menyimpan nama label dari doodle.*/
private String labelName;
/**
* Mengembalikan object Doodle yang akan digunakan untuk proses training.
*
* @param pixelValues
* nilai pixel doodle yang disimpan pada array satu dimensi (one hot vector)
* @param label
* nilai label dari doodle
* @param classSize
* ukuran class dari model
* @return Doodle dengan vector target
*/
Doodle(int label, String labelName, int classSize, String pixelValues) {
this.pixelValues = Matrix.stringToDoubleArray(pixelValues);
this.target = new double[classSize];
this.target[label] = 1.0;
this.label = label;
this.labelName = labelName;
}
/**
* Method ini digunakan untuk mengambil nilai pixel doodle yang disimpan pada array satu dimensi (one hot vector)
*
* @return nilai pixel doodle yang disimpan pada array satu dimensi (one hot vector)
*/
public double[] getPixelValues() {
return pixelValues;
}
/**
* Method ini digunakan untuk mengambil target vector dari doodle
*
* @return nilai target vector dari doodle
*/
public double[] getTarget() {
return target;
}
/**
* Method ini digunakan untuk mengambil nilai label dari doodle
*
* @return nilai label dari doodle
*/
public int getLabel() {
return label;
}
/**
* Method ini digunakan untuk mengambil nama label dari doodle
*
* @return nama label dari doodle
*/
public String getLabelName() {
return labelName;
}
}
|
package com.asu.sineok.app;
import com.asu.sineok.gui.Window;
public class Controller {
private Window window;
Controller(Window window) {
this.window = window;
}
void init() {
window.getPlotButton().addActionListener(e -> {
Plotter.plot(window.getMultiplier().getText(), window.getFreq().getText(), window.getSeconds().getText());
});
}
}
|
package test;
import static org.junit.Assert.*;
import java.util.Date;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import com.mybatis.dao.CommentsDao;
import com.mybatis.dao.NewsDao;
import com.mybatis.dao.TopicDao;
import com.mybatis.util.MybatisUtil;
import com.news.pojo.Topic;
public class MybatisTest {
@Test
public void testName() throws Exception {
SqlSession sqlSession =null;
try {
sqlSession = MybatisUtil.getsqlSession();
// CommentsDao dao = sqlSession.getMapper(CommentsDao.class);
// int res = dao.saveComments(48, "wodetian", "123456", "123456",new Date());
// int res = dao.deleteTopicByTid(32);
// NewsDao dao = sqlSession.getMapper(NewsDao.class);
// int res = dao.addTname("bbb");
// TopicDao dao = sqlSession.getMapper(TopicDao.class);
// List<Topic> data = dao.getAllTopic();
// System.out.println(data.size());
sqlSession.commit();
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
MybatisUtil.closeSqlSession(sqlSession);
}
}
}
|
package ru.job4j.tracker;
import java.util.ArrayList;
/**
* Класс MenuTracker реализует сущность меню трэкера.
*
* @author Goureyev Ilya (mailto:ill-jah@yandex.ru)
* @version 3
* @since 2017-04-23
*/
class MenuTracker {
/**
* Символ новой строки.
*/
public static final String LS = System.getProperty("line.separator");
/**
* Объект ввода.
*/
private Input input;
/**
* Объект трэкера заявок.
*/
private Tracker tracker;
/**
* Массив действий пользователя.
*/
private ArrayList<IUserAction> actions = new ArrayList<>();
/**
* Конструктор.
* @param input объект класса, реализующего интерфэйс Input.
* @param tracker объект трэкера.
*/
MenuTracker(Input input, Tracker tracker) {
this.input = input;
this.tracker = tracker;
}
/**
* Инициализирует меню трэкера.
*/
public void fillActions() {
this.actions.add(new AddItem(MenuActions.ADD));
//this.actions.add(this.new AddItem(MenuActions.ADD));
this.actions.add(new MenuTracker.ShowItems(MenuActions.SHOW));
this.actions.add(new EditItem(MenuActions.EDIT));
this.actions.add(new DeleteItem(MenuActions.DELETE));
this.actions.add(new FindItemById(MenuActions.FINDBYID));
this.actions.add(new FindItemsByName(MenuActions.FINDBYNAME));
}
/**
* Добавляет в массив пользовательских действие нвое действие.
* @param action добавляемое действие.
*/
public void addAction(UserAction action) {
this.actions.add(action);
}
/**
* Выполняет действие, выбранное пользователем.
* @param key идентификатор действия.
*/
public void select(int key) {
this.actions.get(key).execute(this.input, this.tracker);
}
/**
* Выводит меню трэкера.
*/
public void show() {
System.out.println("Please, enter the action number:");
for (IUserAction action : this.actions) {
if (action != null) {
System.out.println(action.info());
}
}
}
/**
* Класс AddItem реализует сущность добавления заявки в трэкер.
*
* @author Goureev Ilya (mailto:ill-jah@yandex.ru)
* @version 1
* @since 2017-04-23
*/
private class AddItem extends UserAction {
/**
* Конструктор.
* @param action константа действия.
*/
AddItem(MenuActions action) {
super(action);
}
/**
* Выполняет действие, выбранное пользователем.
* @param input объект ввода.
* @param tracker объект трэкера.
*/
public void execute(Input input, Tracker tracker) {
System.out.println("");
System.out.println("New task.");
String name = input.ask("Enter user name: ");
String desc = input.ask("Enter task description: ");
String id = tracker.generateId();
tracker.add(new Item(id, name, desc));
StringBuilder sb = new StringBuilder();
sb.append(LS);
sb.append("Task added. Id: ");
sb.append(id);
sb.append(LS);
System.out.println(sb.toString());
}
}
/**
* Класс ShowItems реализует сущность печати заявок трэкера.
*
* @author Goureev Ilya (mailto:ill-jah@yandex.ru)
* @version 1
* @since 2017-04-23
*/
private static class ShowItems extends UserAction {
/**
* Конструктор.
* @param action константа действия.
*/
ShowItems(MenuActions action) {
super(action);
}
/**
* Выполняет действие, выбранное пользователем.
* @param input объект ввода.
* @param tracker объект трэкера.
*/
public void execute(Input input, Tracker tracker) {
StringBuilder sb = new StringBuilder();
sb.append(LS);
sb.append("Tasks in tracker:");
sb.append(LS);
for (Item item : tracker.getAll()) {
sb.append(item.toString());
sb.append(LS);
}
System.out.println(sb.toString());
}
}
/**
* Класс DeleteItem реализует сущность удаления заявки из трэкера.
*
* @author Goureev Ilya (mailto:ill-jah@yandex.ru)
* @version 1
* @since 2017-04-23
*/
private class DeleteItem extends UserAction {
/**
* Конструктор.
* @param action константа действия.
*/
DeleteItem(MenuActions action) {
super(action);
}
/**
* Выполняет действие, выбранное пользователем.
* @param input объект ввода.
* @param tracker объект трэкера.
*/
public void execute(Input input, Tracker tracker) {
System.out.println("");
System.out.println("Delete task.");
String id = input.ask("Enter task id: ");
if (tracker.delete(id)) {
System.out.println("Task deleted.");
} else {
System.out.println("Nothing deleted.");
}
System.out.println("");
}
}
/**
* Класс FindItemById реализует сущность поиска заявки по идентификатору.
*
* @author Goureev Ilya (mailto:ill-jah@yandex.ru)
* @version 1
* @since 2017-04-23
*/
private class FindItemById extends UserAction {
/**
* Конструктор.
* @param action константа действия.
*/
FindItemById(MenuActions action) {
super(action);
}
/**
* Выполняет действие, выбранное пользователем.
* @param input объект ввода.
* @param tracker объект трэкера.
*/
public void execute(Input input, Tracker tracker) {
System.out.println("");
System.out.println("Find task.");
String id = input.ask("Enter task id: ");
Item item = tracker.findById(id);
if (item.isEmpty()) {
System.out.println("Nothing found.");
System.out.println("");
} else {
System.out.println("");
System.out.println("Found:");
System.out.println(item.toString());
System.out.println("");
}
}
}
/**
* Класс FindItemsByName реализует сущность поиска заявок по имени.
*
* @author Goureev Ilya (mailto:ill-jah@yandex.ru)
* @version 1
* @since 2017-04-23
*/
private class FindItemsByName extends UserAction {
/**
* Конструктор.
* @param action константа действия.
*/
FindItemsByName(MenuActions action) {
super(action);
}
/**
* Выполняет действие, выбранное пользователем.
* @param input объект ввода.
* @param tracker объект трэкера.
*/
public void execute(Input input, Tracker tracker) {
System.out.println("");
System.out.println("Find task.");
String name = input.ask("Enter user name: ");
Item[] items = tracker.findByName(name);
if (items.length == 0) {
System.out.println("Nothing found.");
System.out.println("");
} else {
StringBuilder sb = new StringBuilder();
sb.append(LS);
sb.append("Found:");
sb.append(LS);
for (Item item : items) {
sb.append(item.toString());
sb.append(LS);
}
System.out.println(sb.toString());
}
}
}
}
/**
* Класс EditItem реализует сущность редактирования заявки в трэкере.
*
* @author Goureev Ilya (mailto:ill-jah@yandex.ru)
* @version 1
* @since 2017-04-23
*/
class EditItem extends UserAction {
/**
* Конструктор.
* @param action константа действия.
*/
EditItem(MenuActions action) {
super(action);
}
/**
* Выполняет действие, выбранное пользователем.
* @param input объект ввода.
* @param tracker объект трэкера.
*/
public void execute(Input input, Tracker tracker) {
System.out.println("");
System.out.println("Edit task.");
String id = input.ask("Enter task id: ");
Item item = tracker.findById(id);
if (item.isEmpty()) {
System.out.println("There is no task with this id.");
System.out.println("");
return;
}
String name = input.ask("Enter new user name or just press Enter to go on: ");
if (!name.isEmpty()) {
item.setName(name);
}
String desc = input.ask("Enter new description or just press Enter to go on: ");
if (!desc.isEmpty()) {
item.setDesc(desc);
}
tracker.update(item);
System.out.println("Task updated.");
System.out.println("");
}
}
|
package com.array;
/* 队列
* 底层结构:动态数组实现
* 因为底层结构不同,栈实现的细节也不同,未来方便后续的栈的实现,把栈的主要功能
* 抽象成一个接口
* 应用: 1.进程任务调度
* 2.优先队列
* 3.消息队列
* 特点: 1.线性结构
* 2.操作的是数组的一部分(可以看作是子集)
* 3.元素是先进先出(first in first out)FIFO
* 4.从数组的一端(队尾)添加元素,另一端(队首)取出元素,
* —————————————————
* 队首 。。。| 2 | 3 | 1 | 4 | 。。。队尾
* —————————————————
* ^-getFront(指向队首)
*/
import com.queue.Queue_Interface;
public class ArrayQueue<E> implements Queue_Interface<E> {
private MyArray<E> array;//自定义的动态数组
//自定义容量的有参构造
public ArrayQueue(int capacity) {
array=new MyArray<>(capacity);
}
//初始容量为10的无参构造
public ArrayQueue() {
array=new MyArray<>();
}
//队列中元素的个数--O(1)
@Override
public int size() {
return array.size();
}
//判断队列是否为空--O(1)
@Override
public boolean isEmpty() {
return array.isEmpty();
}
//入队列--O(1)-均摊复杂度(包含扩容的O(n))
@Override
public void enqueue(E item) {
array.addLast(item);
}
//出队列--O(n)(不包含缩容复杂度)----时间复杂度有点高,因为要移动n-1个数据
@Override
public E dequeue() {
return array.removeFirst();
}
//获取队首的元素--O(1)
@Override
public E getFront() {
return array.getFirst();
}
//获取队列当前的容量--O(1)
public int getCapacity() {
return array.getCapacity();
}
@Override
public String toString() {
StringBuilder s = new StringBuilder();
s.append(String.format("Queue: size=%d , capacity=%d\n",array.size(),array.getCapacity()));
s.append("front[");
for(int i =0;i<size();i++) {
s.append(array.get(i));
if(i != size()-1) {
s.append(", ");
}
}
s.append("]tail");
return s.toString();
}
}
|
package com.Memento.whitebox;
import javax.swing.*;
/**
* Created by Valentine on 2018/5/11.
*/
public class Memento {
private int state;
public Memento(){
super();
}
public Memento(int state){
this.state = state;
System.out.println("备忘录状态"+state);
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.vootoo.client.netty;
import io.netty.util.internal.PlatformDependent;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicLong;
/**
* @author chenlb on 2015-06-13 13:54.
*/
public class ResponsePromiseContainer {
/** Global_Container */
public static final ResponsePromiseContainer GLOBAL_CONTAINER = new ResponsePromiseContainer();
protected AtomicLong ridSeed = new AtomicLong(0);
protected ConcurrentMap<Long, ResponsePromise> responsePromiseMaps = PlatformDependent.newConcurrentHashMap();
public ResponsePromise createResponsePromise() {
long rid = ridSeed.incrementAndGet();
ResponsePromise responsePromise = new ResponsePromise(rid);
do {
ResponsePromise oldPromise = responsePromiseMaps.putIfAbsent(rid, responsePromise);
if (oldPromise != null) {
rid = ridSeed.incrementAndGet();
} else {
responsePromise.setRid(rid);
break;
}
} while (true);
return responsePromise;
}
public ResponsePromise removeResponsePromise(long rid) {
return responsePromiseMaps.remove(rid);
}
}
|
/**
*
*/
package nnets;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.NumberTickUnit;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
/**
* @author I.C. Ricardo Alfredo Macias Olvera
*
*/
public class Clustering extends JFrame{
/**
* Clustering with SNN (Spike Neural Network)
* Multiple synapses architecture
* 5 clusters with gaussian distribution with means 0
* Each cluster has 3 points (data)
* output classes : 5
* codification : fixed receptive fields
* Number of receptive fields : 1
* Type of synapses : multiple
*/
private static final long serialVersionUID = 1L;
private static final String title = "Clustering SNN";
// private static int out_neu=5;
XYSeriesCollection xySeriesCollection = new XYSeriesCollection();
XYSeries NormalDataAdded = new XYSeries("NormalData");
XYSeries DelaysAdded = new XYSeries("Delays");
XYSeries Class_A_Added = new XYSeries("Class_A");
XYSeries Class_B_Added = new XYSeries("Class_B");
XYSeries Class_C_Added = new XYSeries("Class_C");
XYSeries Class_D_Added = new XYSeries("Class_D");
XYSeries Class_E_Added = new XYSeries("Class_E");
// Create a new ArrayList
static ArrayList<Integer> newListClas = new ArrayList<Integer>();
static ArrayList<Integer> arClas= new ArrayList<Integer>();
static double [][] aus = null;
private static double [][] ein = null;
static double [] vclasA = null;
static double [] vclasB = null;
static double [] vclasC = null;
static double [] vclasD = null;
static double [] vclasE = null;
public Clustering(String s) {
final ChartPanel chart_Normal_Panel = createNormalizedPanel();
this.add(chart_Normal_Panel, BorderLayout.CENTER);
JPanel control = new JPanel();
control.add(new JButton(new AbstractAction("Clear") {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
xySeriesCollection.removeAllSeries();
}
}));
control.add(new JButton(new AbstractAction("Add Clusters") {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
double movX =0.00;
for (double sp : vclasA) {
double x = 0.0;
double y = 0.0;
System.out.println(" ");
movX = movX + 0.035;
x = movX;
y = sp;
System.out.println("A -> "+ y);
Class_A_Added.add(x, y);
}
for (double sp : vclasB) {
double x = 0.0;
double y = 0.0;
System.out.println(" ");
movX = movX + 0.035;
x = movX;
y = sp;
System.out.println("B ->"+ y);
Class_B_Added.add(x, y);
}
for (double sp : vclasC) {
double x = 0.0;
double y = 0.0;
System.out.println(" ");
movX = movX + 0.035;
x = movX;
y = sp;
System.out.println("C ->"+ y);
Class_C_Added.add(x, y);
}
for (double sp : vclasD) {
double x = 0.0;
double y = 0.0;
System.out.println(" ");
movX = movX + 0.035;
x = movX;
y = sp;
System.out.println("D ->"+ y);
Class_D_Added.add(x, y);
}
for (double sp : vclasE) {
double x = 0.0;
double y = 0.0;
System.out.println(" ");
movX = movX + 0.035;
x = movX;
y = sp;
System.out.println("E ->"+ y);
Class_E_Added.add(x, y);
}
xySeriesCollection.addSeries(Class_E_Added);
xySeriesCollection.addSeries(Class_D_Added);
xySeriesCollection.addSeries(Class_C_Added);
xySeriesCollection.addSeries(Class_B_Added);
xySeriesCollection.addSeries(Class_A_Added);
}
}));
control.add(new JButton(new AbstractAction("Add Normal") {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
double movX =0.00;
for (double[] sp : ein) {
double x = 0.0;
double y = 0.0;
System.out.println(" ");
for (int i = 0; i < sp.length; i++) {
movX = movX + 0.035;
x = movX;
y = sp[i];
System.out.println("sp "+ y);
NormalDataAdded.add(x, y);
}
}
xySeriesCollection.addSeries(NormalDataAdded);
}
}));
control.add(new JButton(new AbstractAction("Add Delays") {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
double movX =0.00;
for (double[] sp : aus) {
double x = 0.0;
double y = 0.0;
System.out.println(" ");
for (int i = 0; i < sp.length; i++) {
movX = movX + 0.035;
x = movX;
y = sp[i];
System.out.println("d "+ y);
DelaysAdded.add(x, y);
}
}
xySeriesCollection.addSeries(DelaysAdded);
}
}));
this.add(control, BorderLayout.SOUTH);
}
private ChartPanel createNormalizedPanel() {
test();
JFreeChart jfreechart = ChartFactory.createScatterPlot(
title, "X", "Y", createNormalizedData(),
PlotOrientation.VERTICAL, true, true, false);
XYPlot xyPlot = (XYPlot) jfreechart.getPlot();
xyPlot.setDomainCrosshairVisible(true);
xyPlot.setRangeCrosshairVisible(true);
XYItemRenderer renderer = xyPlot.getRenderer();
renderer.setSeriesPaint(0, Color.blue);
NumberAxis domain = (NumberAxis) xyPlot.getDomainAxis();
domain.setRange(0.00, 1.00);
domain.setTickUnit(new NumberTickUnit(0.1));
domain.setVerticalTickLabels(true);
NumberAxis rangep = (NumberAxis) xyPlot.getRangeAxis();
rangep.setRange(0.0, 1.0);
rangep.setTickUnit(new NumberTickUnit(0.1));
return new ChartPanel(jfreechart);
}
private XYDataset createNormalizedData() {
double movX =0.0;
XYSeries NormalData = new XYSeries("NormalData");
movX =0;
for (double[] ds : ein) {
double x = 0.0;
double y = 0.0;
for (int i =0; i< ds.length; i++) {
movX = movX + 0.035;
x = movX;
y = ds[i];
NormalData.add(x,y);
}
}
xySeriesCollection.addSeries(NormalData);
return xySeriesCollection;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
Clustering demo = new Clustering(title);
demo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
demo.pack();
demo.setLocationRelativeTo(null);
demo.setVisible(true);
}
});
}
public static void print( double arr[]) {
for (double d : arr) {
System.out.print(" "+ d);
}
}
public static double max(double [] vec) {
double ele = vec[0];
double max =0;
for (int x =1 ; x < vec.length; x++) {
double vectmp = vec[x];
if (ele > vectmp) {
max = ele;
}else
max = vectmp;
ele = max;
}
return max;
}
public static double min (double [] vec) {
double ele = vec[0];
double min =0;
for (int x =1 ; x < vec.length; x++) {
double vectmp = vec[x];
if (ele < vectmp) {
min = ele;
}else
min = vectmp;
ele = min;
}
return min;
}
public static double [][] kodieren_rf(double [][] ein, int rf[],
int maxd, double [] sigma, double f_cut, double rho, int typ, int plt) {
/***
*
* Encode analog values by means of multiple fixed receptive fields
*/
int t_neur = 0;
for (int i =0; i < rf.length; i++) {
t_neur = t_neur + rf[i];
}
int t_cj = ein.length;
System.out.println( "\n t_cj - > t_cj -> t_cj -> "+ t_cj);
aus = new double [t_cj][ t_neur];
double [] ct = new double[rf.length];
if (rf.length <3)
System.out.println("receptive fields must be greater than 3");
System.out.println(" ");
double range =0;
int i = 0;
for (double [] d : ein) {
range =0;
range =max(d) -min(d);
System.out.println(" max "+ max(d)+" min "+ min(d)+" range "+ range);
for (int j = 0; j < d.length; j++) {
ein[i][j]= (ein[i][j] - min(d))/range;
}
i++;
}
if (typ ==1) {
for (int j =0 ; j < rf.length; j++ ) {
ct[j] = (j-0.5) * (1/rf[j]);
}
}else if (typ == 0) {
for (int j =0 ; j < rf.length; j++ ) {
ct[j] = (j-1.5) * (1/rf[j]-2);
}
}else
System.out.println("typ must be 0 / 1");
System.out.println("\nPRINT EIN NORMALIZED \n");
for (double [] d : ein) {
System.out.println(" ");
print(d);
}
double aux = 0;
for (int j =0; j< t_cj; j++) {
for (int k=0; k < rf.length; k++) {
aux = maxd-maxd* Math.exp(-1*(Math.pow((ein[j][k]-ct[k]), 2)
/ Math.pow(2*sigma[k], 2)));
aus[j][k] = (aux*(1/rho))*rho;
if (aus[j][k] > maxd*f_cut)
aus[j][k] = -1;
}
}
return aus;
}
public static void test() {
int out_neu=5;
double rho = 0.6;
int conj = 5;
int tau = 4;
int [] rf = {1, 1, 1};
double [] sigma = {1/(1.5*rf[0]-2),1/(1.5*rf[1]-2), 1/(1.5*rf[0]-2)};
double f_cut =0.9;
int maxd = 2;
int [] d = {0,1,2};
int w_max = 1, w_min=0;
int max_epoch = 2;
int t_max =5;
double eta = 0.25;
double beta = 0.1;
double nu = 5.0;
double kapa = 1 - (Math.pow(nu, 2)) / (2* Math.log(beta/(beta+1)) );
int in_neu = 0;
for (int i =0 ; i < rf.length; i++) {
in_neu = in_neu + rf[i];
}
System.out.println("in_neu -> "+ in_neu);
int ssin = d.length;
//double teta = 1.5* (in_neu/out_neu) * (w_max-w_min)*ssin/2;
double teta = 0.5;
// Initialize weights
double [][][] w= new double[in_neu][out_neu][ssin];
double [][] ein = {{2.3,6, 8.5,4.5},
{9.3,3.3, 4.2,7.3},
{15,3.5,7.2,8.2},
{22.1,6.6, 5.7, 4.4},
{1.3,8.4,1.6,1}};
Clustering.ein = ein;
double ssinv=0;
Random r = new Random();
for (int i =0; i <in_neu; i++)
for( int j=0; j < out_neu; j++) {
ssinv = 0;
for (int s =0; s < ssin; s++) {
ssinv= (0 + (1 - 0) * r.nextDouble());
w[i][j][s] = (w_min+ssinv) * (w_max-w_min);
}
}
System.out.println("PRINT W \n");
for (double[][] es : w) {
System.out.println(" ");
for (double[] es2 : es) {
print(es2);
}
}
// delays
aus = kodieren_rf(ein, rf, maxd, sigma, f_cut, rho, 0, 0);
System.out.println("\n aus after kodieren_rf -------> "+ aus.length);
int ctrl_1=0;
System.out.println("\n delays \n");
for (double [] d1 : aus) {
System.out.println(" ");
print(d1);
}
double [][][] delta_t = new double [1][1][ssin];
System.out.println(" <<<<<<<< delta_t - ssin >>>>>>>>>> "+ ssin);
double [][] f_times = new double[2][1];
System.out.println(" \n\n Training begins\n");
int neu = 0;
double inst =0;
double dneu =0;
while(ctrl_1 <= max_epoch) {
System.out.println(" ");
for (double[] tr : aus) {
System.out.println(" ");
for (int z = 0 ; z < tr.length; z ++) {
System.out.print (" "+ tr[z] );
ArrayList<ArrayList<Object>> firings = wer_schiesst(tr, t_max, w, d, tau, rho, teta, 0);
for(int i=0; i< firings.get(0).size(); i++) {
neu = (int) firings.get(0).get(i);
dneu = neu;
f_times[0][i] = dneu;
}
for (int j =0 ; j < firings.get(1).size(); j++) {
f_times[1][j] = (double) firings.get(1).get(j);
inst = (double) firings.get(1).get(j);
}
if ( neu!=0 && firings.get(0).size() == 1 ) { //size of neu
for (int i=0; i< in_neu; i++) {
if (tr[z] == -1) {
for ( i=0; i < w[z][neu].length; i++) {
w[z][neu][i] = w[z][neu][i] -eta;
}
}else {
System.out.println("< -delta_t -> ");
for ( i=0; i < ssin; i++) {
delta_t[0][0][i] = tr[z] +d[z] -inst;
w[z][neu][i] = w[z][neu][i] + eta * ((1 +beta) * Math.exp(-1*( (Math.pow((delta_t[0][0][i]) +3.3, 2))/(2*kapa-2)))-beta);
}
}
System.out.println("\nGetting indx < w_min \n");
for ( i=0; i < w[z][neu].length; i++) {
if (w[z][neu][i] < w_min) {
System.out.println(" w_min i -> -> -> "+ i);
w[z][neu][i] = w_min;
}else if (w[z][neu][i] > w_max) {
System.out.println(" w_max i -> -> -> "+ i);
w[z][neu][i] = w_max;
}
}
}
}
}
}
ctrl_1++;
teta = teta + (0.3*teta) /max_epoch;
}
int i=0, j=0, ausr =0, ausc=0;
for ( i=0; i < aus.length; i++) {
ausc = 0;
for (j =0; j < aus[i].length; j++) {
ausc = ausc +1 ;
}
ausr = ausr + 1;
}
System.out.println("aus groups -> "+ ausr);
System.out.println("aus data -> "+ ausc);
System.out.println(" conj -> "+ conj);
System.out.println(" in_neu -> "+ in_neu);
//Testing the net
int [] clas = new int[conj];
int c =0;
for (c=0; c < conj; c++) {
for (double[] tr : aus) {
ArrayList<ArrayList<Object>> firings = wer_schiesst(tr, t_max, w, d, tau, rho, teta, 0);
for(j=0; j< firings.get(0).size(); j++) {
neu = (int) firings.get(0).get(j);
System.out.println("neu ---testing---> " + neu);
}
}
clas[c] = neu;
}
System.out.println("\n PRINT CLASES -> \n ");
for(int x =0; x< clas.length; x++)
System.out.println(clas[x]);
System.out.println(" ");
System.out.println("total clases arr - > " + arClas.size());
for (Integer element : arClas) {
if (!newListClas.contains(element)) {
newListClas.add(element);
}
}
System.out.println("NO DUPLICATES CLASES");
for (Integer integer : newListClas) {
System.out.println(" clas -----> "+ integer);
}
vclasA = new double[ein[0].length];
vclasB = new double[ein[0].length];
vclasC = new double[ein[0].length];
vclasD = new double[ein[0].length];
vclasE = new double[ein[0].length];
for ( i=0; i< out_neu; i++) {
for ( j=0; j< newListClas.size(); j++) {
if (i == newListClas.get(j)) {
System.out.println("ein[ "+ i +" ] -> "+ ein[i]);
for (int z =0; z < ein[i].length; z++) {
System.out.println("val -> " + ein[i][z]);
if (i == newListClas.get(j) && i == 0) {
vclasA[z] = ein[i][z];
}
if (i == newListClas.get(j) && i == 1) {
vclasB[z] = ein[i][z];
}
if (i == newListClas.get(j) && i == 2) {
vclasC[z] = ein[i][z];
}
if (i == newListClas.get(j) && i == 3) {
vclasD[z] = ein[i][z];
}
if (i == newListClas.get(j) && i == 4) {
vclasE[z] = ein[i][z];
}
}
}
}
}
System.out.println(" size of vectors -> \n");
System.out.println("\n vclasA.length -> "+ vclasA.length);
print(vclasA);
System.out.println("\n vclasB.length -> "+ vclasB.length);
print(vclasB);
System.out.println("\n vclasC.length -> "+ vclasC.length);
print(vclasC);
System.out.println("\n vclasD.length -> "+ vclasD.length);
print(vclasD);
System.out.println("\n vclasE.length -> "+ vclasE.length);
print(vclasE);
}
public static ArrayList<ArrayList<Object>> wer_schiesst(double[] in,int t_max, double [][][] w, int [] d, int tau, double rho, double teta, int plt ) {
/**
* Function that returns the neuron was fired and the firing time
*
*/
System.out.println(" ");
System.out.println("in -> "+ in+ " t_max -> " + t_max +" w -> "+ w + " d -> "+ d + " tau -> "+ tau+ " "
+ " rho -> "+ rho + " teta -> "+ teta + " plt -> "+ plt );
int ein = 0, ausx =0, ssin=0;
for (double [][] input : w) {
ausx=0;
for (double[] output : input) {
ssin=0;
for (double ssyn : output) {
ssin++;
}
ausx++;
}
ein++;
}
System.out.println("Wiegths dimensions");
System.out.println("\ninput - > "+ ein + " output -> "+ ausx + " ssyn -> "+ ssin);
// input - > 3 output -> 5 ssyn -> 3
double [] indx = new double[in.length];
for (int i=0; i < in.length; i++) {
if(in[i] !=-1) {
indx[i] = in[i];
}
}
int tam = indx.length;
System.out.println("indx ->> "+ tam);
System.out.println("\n <- indx -> \n");
print(indx);
int neu =0;
double inst =0;
ArrayList<ArrayList<Object>> firings = new ArrayList<ArrayList<Object>>();
double [] vals = new double[2];
if (indx.length == 0) {
neu =0; inst = -1;
vals[0] = neu;
vals[1] = inst;
return firings;
}
System.out.println("\n d size "+ d.length + " ssin "+ ssin);
double [] out ;
double dt=0, dtt=0, sai=0,t =0;
ArrayList<Object> neuIndx = null;
ArrayList<Object> neuInst = null;
System.out.println("j -> "+ aus[0].length);
System.out.println(" i -> "+ tam);
System.out.println(" k -> "+ ssin);
//ArrayList<Integer> indxTemp = new ArrayList<Integer>();
while (neu == 0 && t <= t_max) {
System.out.println("<- wer_schiesst -> ");
out = new double[ausx];
for (int j=0; j< ausx; j++) {
System.out.println(" ");
for (int i=0; i < tam; i++) {
dt = t - indx[i];
for (int k =0; k < ssin; k++) {
dtt= (dt - d[k])/tau;
sai = w[i][j][k]*dtt*Math.exp(1-dtt);
if (sai < 0)
sai =0;
out[j] = out[j] +sai;
}
}
}
if (max(out)>= teta ) {
neuInst = new ArrayList<Object>();
neuIndx = new ArrayList<Object>();
for (int x =0; x < out.length ; x++) {
if (out[x] == max(out)) {
neu = x;
neuIndx.add(neu);
arClas.add(neu);
inst = t;
System.out.println("neu - > "+ neu + " inst -> "+ inst);
neuInst.add(inst);
}else
neu = 0;
}
firings.add(neuIndx);
firings.add(neuInst);
}else
neu =0;
t=t+rho;
}
return firings;
}
}
|
/**
* Basic abstractions for working with message handler methods.
*/
@NonNullApi
@NonNullFields
package org.springframework.messaging.handler;
import org.springframework.lang.NonNullApi;
import org.springframework.lang.NonNullFields;
|
//Jesus Rodriguez
//2/17/2020
//ITC 115 Winter 2020
/*
* Write a method called boyGirl that accepts a Scanner
* that is reading its input from a file containing a series
* of names followed by integers. The names alternate between boy's
* names and girl's names. Your method should compute the absolute difference
* between the sum of the boy's integers and the sum the girl's integers.
* The input could end with either a boy or girl; you may not assume that it
* contains an even number of names. For example, if the input file contains the following:
* Erick 3 Rita 7 Tanner 14 Jillin 13 Curtis 4 Stefanie 12 Ben 6
* then the method should produce the following console output , since the boy's sum is 27
* and the girl's sum is 32.
* 4 boys, 3 girls
* Difference between boy's and girl's sums: 5
*/
import java.io.*;
import java.util.*;
public class who {
public static void main(String[] args)
throws FileNotFoundException{ //Avoid the exception FileNotFoundException
Scanner input = new Scanner (new File("boysgirls.txt")); // Open the file boysgirls.txt
boyGirl(input); //Calls the method boyGirl
}
public static void boyGirl(Scanner input) {
int boys = 0;
int boySum = 0; //Declaring variables
int girls = 0;
int girlSum = 0;
while(input.hasNext()) { //Condition while to get the values of boys and then do a sum
input.next();
boys++;
boySum += input.nextInt();
if(!input.hasNext())
break;
input.next(); //Condition while to get the values of girls and then do a sum
girls++;
girlSum += input.nextInt();
}
System.out.println(boys + " boys, " + girls + " girls");
System.out.println("Difference between boys' and girls' sums: " + //Prints out the values.
Math.abs(boySum - girlSum));
}
}
|
// jDownloader - Downloadmanager
// Copyright (C) 2012 JD-Team support@jdownloader.org
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package jd.plugins.decrypter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
import java.util.regex.Pattern;
import jd.PluginWrapper;
import jd.controlling.ProgressController;
import jd.nutils.encoding.Encoding;
import jd.parser.Regex;
import jd.parser.html.HTMLParser;
import jd.plugins.CryptedLink;
import jd.plugins.DecrypterPlugin;
import jd.plugins.DownloadLink;
import jd.plugins.FilePackage;
import jd.plugins.components.PluginJSonUtils;
import org.appwork.utils.formatter.SizeFormatter;
import org.jdownloader.plugins.components.antiDDoSForDecrypt;
@DecrypterPlugin(revision = "$Revision$", interfaceVersion = 3, names = { "box.com" }, urls = { "https?://(?:www|[a-z0-9\\-_]*)(?:\\.?app)?\\.box\\.(?:net|com)/(?:shared|s)/(?!static)[a-z0-9]+(/\\d+/\\d+)?" })
public class BoxCom extends antiDDoSForDecrypt {
private static final Pattern FEED_FILEINFO_PATTERN = Pattern.compile("<item>(.*?)<\\/item>", Pattern.DOTALL);
private static final Pattern FEED_FILETITLE_PATTERN = Pattern.compile("<title>(.*?)<\\/title>", Pattern.DOTALL);
private static final Pattern FEED_DL_LINK_PATTERN = Pattern.compile("<media:content url=\\\"(.*?)\\\"\\s*/>", Pattern.DOTALL);
private static final Pattern SINGLE_DOWNLOAD_LINK_PATTERN = Pattern.compile("(https?://(www|[a-z0-9\\-_]+)\\.box\\.com/index\\.php\\?rm=box_download_shared_file\\&file_id=.+?\\&shared_name=\\w+)");
private static final String ERROR = "(<h2>The webpage you have requested was not found\\.</h2>|<h1>404 File Not Found</h1>|Oops — this shared file or folder link has been removed\\.|RSS channel not found)";
private static final String TYPE_APP = "https?://(?:\\w+\\.)?app\\.box\\.com/(s|shared)/[a-z0-9]+(/1/\\d+)?";
public BoxCom(PluginWrapper wrapper) {
super(wrapper);
}
@Override
public ArrayList<DownloadLink> decryptIt(final CryptedLink parameter, final ProgressController progress) throws Exception {
final ArrayList<DownloadLink> decryptedLinks = new ArrayList<DownloadLink>();
String cryptedlink = parameter.toString().replace("box.net/", "box.com/").replace("box.com/s/", "box.com/shared/");
logger.finer("Decrypting: " + cryptedlink);
br.setCookie("http://box.com", "country_code", "US");
br.setFollowRedirects(true);
br.getPage(cryptedlink);
if (br.getURL().equals("https://www.box.com/freeshare")) {
decryptedLinks.add(createOfflinelink(cryptedlink));
return decryptedLinks;
}
if (br.getHttpConnection().getResponseCode() == 404 || br.containsHTML("<title>Box \\| 404 Page Not Found</title>") || br.containsHTML("error_message_not_found")) {
decryptedLinks.add(createOfflinelink(cryptedlink));
return decryptedLinks;
}
String fpName = null;
if (br.getURL().matches(TYPE_APP)) {
final String cp = PluginJSonUtils.getJsonValue(br, "current_page");
final String pc = PluginJSonUtils.getJsonValue(br, "page_count");
final int currentPage = cp != null ? Integer.parseInt(cp) : 1;
final int pageCount = pc != null ? Integer.parseInt(pc) : 1;
String parent = null;
fpName = PluginJSonUtils.getJsonValue(this.br, "name");
final String main_folderid = new Regex(cryptedlink, "box\\.com/(s|shared)/([a-z0-9]+)").getMatch(1);
String json_Text = br.getRegex("\"db\":(\\{.*?\\})\\}\\}").getMatch(0);
if (json_Text == null) {
/*
* Check if folder is empty - folders that contain only subfolders but no files are also "empty" so better check this in
* here!
*/
if (br.containsHTML("class=\"empty_folder\"")) {
decryptedLinks.add(createOfflinelink(cryptedlink));
return decryptedLinks;
}
/* Maybe single file */
String filename = br.getRegex("data-hover=\"tooltip\" aria-label=\"([^<>\"]*?)\"").getMatch(0);
if (filename == null) {
filename = br.getRegex("var name = '([^<>\"]*?)';").getMatch(0);
}
final String filesize = br.getRegex("class=\"file_size\">\\(([^<>\"]*?)\\)</span>").getMatch(0);
String fid = br.getRegex("itemTypedID: \"f_(\\d+)\"").getMatch(0);
if (filename != null) {
boolean web_doc = false;
if (fid == null) {
fid = Long.toString(System.currentTimeMillis());
web_doc = true;
}
final DownloadLink fina = createDownloadlink("https://app.box.com/index.php?rm=box_download_shared_file" + "&file_id=f_" + fid + "&shared_name=" + main_folderid);
fina.setName(Encoding.htmlDecode(filename.trim()));
if (filesize != null) {
fina.setDownloadSize(SizeFormatter.getSize(filesize));
}
fina.setAvailable(true);
if (web_doc) {
fina.setProperty("force_http_download", true);
}
fina.setProperty("mainlink", parameter);
decryptedLinks.add(fina);
return decryptedLinks;
}
// new failover
final DownloadLink dl = createDownloadlink("https://www.boxdecrypted.com/shared/" + new Regex(cryptedlink, "([a-z0-9]+)$").getMatch(0));
decryptedLinks.add(dl);
return decryptedLinks;
// /* Okay seems like our code failed */
// logger.warning("Decrypt failed for link: " + cryptedlink);
// return null;
}
for (int i = currentPage; i - 1 != pageCount; i++) {
final ArrayList<String> filelinkinfo = splitAtRepeat(json_Text);
if (filelinkinfo.isEmpty()) {
// this can happen when empty folder we need to seek info from javascript based html instead of pure json.
json_Text = br.getRegex("(\"shared_folder_info\".*?),\"db\"").getMatch(0);
// fix packagename
final String parentName = PluginJSonUtils.getJsonValue(json_Text, "name");
if (fpName == null || parentName != null && !fpName.equals(parentName)) {
fpName = parentName;
}
decryptedLinks.add(createOfflinelink(cryptedlink));
break;
}
for (final String singleflinkinfo : filelinkinfo) {
// each json object has parent and parent name info. We can use this to set correct packagename!
if (parent == null) {
parent = PluginJSonUtils.getJsonValue(singleflinkinfo, "parent");
}
final String parentName = PluginJSonUtils.getJsonValue(singleflinkinfo, "parent_name");
if (fpName == null || parentName != null && !fpName.equals(parentName)) {
fpName = parentName;
}
final String type = PluginJSonUtils.getJsonValue(singleflinkinfo, "type");
/* Check for invalid entry */
if (type == null) {
continue;
}
final String id = new Regex(singleflinkinfo, "\"typed_id\":\"(f|d)_(\\d+)\"").getMatch(1);
if (type.equals("folder")) {
final DownloadLink fina = createDownloadlink("https://app.box.com/s/" + main_folderid + "/1/" + id);
decryptedLinks.add(fina);
} else {
final String filename = PluginJSonUtils.getJsonValue(singleflinkinfo, "name");
final String filesize = PluginJSonUtils.getJsonValue(singleflinkinfo, "raw_size");
final String sha1 = PluginJSonUtils.getJsonValue(singleflinkinfo, "sha1");
if (id != null && filename != null && filesize != null) {
final String finallink = "https://app.box.com/index.php?rm=box_download_shared_file" + "&file_id=f_" + id + "&shared_name=" + main_folderid;
final DownloadLink fina = createDownloadlink(finallink);
fina.setName(filename);
fina.setDownloadSize(Long.parseLong(filesize));
if (sha1 != null) {
fina.setSha1Hash(sha1);
}
fina.setAvailable(true);
fina.setContentUrl(finallink);
decryptedLinks.add(fina);
}
}
}
if (i != pageCount) {
br.getPage(br.getURL() + "/" + (i + 1) + "/" + parent);
json_Text = br.getRegex("\"db\":(\\{.*?\\})\\}\\}").getMatch(0);
if (json_Text == null) {
break;
}
}
}
if (decryptedLinks.size() == 0) {
if (br.containsHTML("class=\"empty_folder\"")) {
decryptedLinks.add(createOfflinelink(cryptedlink));
return decryptedLinks;
}
logger.warning("Decrypt failed for link: " + cryptedlink);
return null;
}
if (fpName != null) {
final FilePackage fp = FilePackage.getInstance();
fp.setName(Encoding.htmlDecode(fpName.trim()));
fp.addLinks(decryptedLinks);
}
return decryptedLinks;
}
if (br.containsHTML("id=\"name\" title=\"boxdocs\"")) {
fpName = new Regex(cryptedlink, "([a-z0-9]+)$").getMatch(0);
final String textArea = br.getRegex("<tr id=\"wrp_base\" style=\"height: 100%;\">(.*?)<tr id=\"wrp_footer\">").getMatch(0);
if (textArea == null) {
logger.warning("Decrypt failed for link: " + cryptedlink);
return null;
}
final String[] pictureLinks = HTMLParser.getHttpLinks(textArea, "");
if (pictureLinks != null && pictureLinks.length != 0) {
for (final String pictureLink : pictureLinks) {
if (!pictureLink.contains("box.com/")) {
final DownloadLink dl = createDownloadlink("directhttp://" + pictureLink);
decryptedLinks.add(dl);
}
}
}
} else {
// Folder or single link
if (br.containsHTML("id=\"shared_folder_files_tab_content\"")) {
br.getRequest().setHtmlCode(br.toString().replace("\\", ""));
final String pathValue = br.getRegex("\\{\"p_(\\d+)\"").getMatch(0);
fpName = br.getRegex("\"name\":\"([^<>\"]*?)\"").getMatch(0);
// Hmm maybe a single link
if (pathValue == null || fpName == null) {
decryptedLinks.add(createSingleDownloadlink(cryptedlink));
return decryptedLinks;
}
final String basicLink = br.getURL().replace("/shared/", "/s/");
final String pageCount = br.getRegex("\"page_count\":(\\d+)").getMatch(0);
final String linkID = new Regex(cryptedlink, "box\\.com/shared/([a-z0-9]+)").getMatch(0);
int pages = 1;
if (pageCount != null) {
pages = Integer.parseInt(pageCount);
}
for (int i = 1; i <= pages; i++) {
logger.info("Decrypting page " + i + " of " + pages);
br.getPage(basicLink + "/" + i + "/" + pathValue);
br.getRequest().setHtmlCode(br.toString().replace("\\", ""));
final String[] links = br.getRegex("\"nnttttdata-href=\"(/s/[a-z0-9]+/\\d+/\\d+/\\d+/\\d+)\"").getColumn(0);
final String[] filenames = br.getRegex("data-downloadurl=\"[a-z0-9/]+:([^<>\"]*?):https://www\\.box").getColumn(0);
final String[] filesizes = br.getRegex("class=\"item_size\">([^<>\"]*?)</li>").getColumn(0);
final String[] folderLinks = br.getRegex("\"unidb\":\"folder_(\\d+)\"").getColumn(0);
// Hmm maybe a single link
if ((links == null || links.length == 0 || filenames == null || filenames.length == 0 || filesizes == null || filesizes.length == 0) && (folderLinks == null || folderLinks.length == 0)) {
decryptedLinks.add(createSingleDownloadlink(cryptedlink));
return decryptedLinks;
}
if (folderLinks != null && folderLinks.length != 0) {
for (final String folderLink : folderLinks) {
final DownloadLink dl = createDownloadlink("https://www.box.com/shared/" + linkID + "/1/" + folderLink);
decryptedLinks.add(dl);
}
}
if (links != null && links.length != 0 && filenames != null && filenames.length != 0 && filesizes != null && filesizes.length != 0) {
final int numberOfEntries = links.length;
if (filenames.length != numberOfEntries || filesizes.length != numberOfEntries) {
logger.warning("Decrypt failed for link: " + cryptedlink);
return null;
}
for (int count = 0; count < numberOfEntries; count++) {
final String url = links[count];
final String filename = filenames[count];
final String filesize = filesizes[count];
final DownloadLink dl = createDownloadlink("https://www.boxdecrypted.com" + url);
dl.setProperty("plainfilename", filename);
dl.setProperty("plainfilesize", filesize);
dl.setName(Encoding.htmlDecode(filename.trim()));
dl.setDownloadSize(SizeFormatter.getSize(filesize));
dl.setAvailable(true);
decryptedLinks.add(dl);
}
}
}
} else {
final DownloadLink dl = createDownloadlink("https://www.boxdecrypted.com/shared/" + new Regex(cryptedlink, "([a-z0-9]+)$").getMatch(0));
decryptedLinks.add(dl);
return decryptedLinks;
}
}
if (fpName != null) {
final FilePackage fp = FilePackage.getInstance();
fp.setName(Encoding.htmlDecode(fpName.trim()));
fp.addLinks(decryptedLinks);
}
if (decryptedLinks.size() == 0) {
logger.info("Haven't found any links to decrypt, now trying decryptSingleDLPage");
decryptedLinks.add(createDownloadlink(cryptedlink.replaceAll("box\\.com/shared", "boxdecrypted.com/shared")));
}
return decryptedLinks;
}
private DownloadLink createSingleDownloadlink(final String cryptedLink) {
final String fileID = br.getRegex("\"typed_id\":\"f_(\\d+)\"").getMatch(0);
final String fid = new Regex(cryptedLink, "([a-z0-9]+)$").getMatch(0);
String fsize = br.getRegex("\"size\":\"([^<>\"]*?)\"").getMatch(0);
if (fsize == null) {
fsize = "0b";
}
String singleFilename = br.getRegex("id=\"filename_\\d+\" name=\"([^<>\"]*?)\"").getMatch(0);
if (singleFilename == null) {
singleFilename = fid;
}
final DownloadLink dl = createDownloadlink("http://www.boxdecrypted.com/s/" + fid + "/1/1/1/" + new Random().nextInt(1000));
dl.setProperty("plainfilename", singleFilename);
dl.setProperty("plainfilesize", fsize);
if (fileID != null) {
dl.setProperty("fileid", fileID);
}
dl.setProperty("sharedname", fid);
return dl;
}
/**
* cant always make regex that works for getColumn or getRow. this following method works around this!
*
* @author raztoki
* @param input
* @return
*/
private ArrayList<String> splitAtRepeat(final String input) {
String i = input;
ArrayList<String> filelinkinfo = new ArrayList<String>();
while (true) {
String result = new Regex(i, "(\"(?:file|folder)_\\d+.*?\\}),(?:\"(?:file|folder)_\\d+|)").getMatch(0);
if (result == null) {
break;
}
result = PluginJSonUtils.validateResultForArrays(input, result);
filelinkinfo.add(result);
i = i.replace(result, "");
}
return filelinkinfo;
}
/**
* Extracts the download link from a single file download page.
*
* @param cryptedUrl
* the url of the download page
* @return a list that contains the extracted download link, null if the download link couldn't be extracted.
* @throws IOException
*/
/**
* Extracts download links from a box.net rss feed.
*
* @param feedUrl
* the url of the rss feed
* @return a list of decrypted links, null if the links could not be extracted.
* @throws IOException
*/
private ArrayList<DownloadLink> decryptFeed(String feedUrl, final String cryptedlink) throws IOException {
ArrayList<DownloadLink> decryptedLinks = new ArrayList<DownloadLink>();
if (br.getRedirectLocation() != null) {
br.getPage(br.getRedirectLocation());
}
if (br.containsHTML("<title>Box \\| 404 Page Not Found</title>")) {
final DownloadLink dl = createDownloadlink(cryptedlink.replaceAll("box\\.com/shared", "boxdecrypted.com/shared"));
dl.setAvailable(false);
dl.setProperty("offline", true);
decryptedLinks.add(dl);
return decryptedLinks;
}
String title = br.getRegex(FEED_FILETITLE_PATTERN).getMatch(0);
String[] folder = br.getRegex(FEED_FILEINFO_PATTERN).getColumn(0);
if (folder == null) {
return null;
}
for (String fileInfo : folder) {
String dlUrl = new Regex(fileInfo, FEED_DL_LINK_PATTERN).getMatch(0);
if (dlUrl == null) {
logger.info("Couldn't find download link. Skipping file.");
continue;
}
// These ones are direct links so let's handle them as directlinks^^
dlUrl = "directhttp://" + dlUrl.replace("amp;", "");
logger.finer("Found link in rss feed: " + dlUrl);
DownloadLink dl = createDownloadlink(dlUrl);
decryptedLinks.add(dl);
if (title != null) {
FilePackage filePackage = FilePackage.getInstance();
filePackage.setName(title);
filePackage.add(dl);
}
}
logger.info("Found " + decryptedLinks.size() + " links in feed: " + feedUrl);
return decryptedLinks;
}
/* NO OVERRIDE!! */
public boolean hasCaptcha(CryptedLink link, jd.plugins.Account acc) {
return false;
}
} |
package com.phicomm.account.provider;
public class Person {
public String name;
public String userKey;
public String userBirth;
public String userAddress;
public String userEmail;
public String userImage;
public String createTime;
public String nickName;
public String phone;
public String userId;
public String userSex;
public String trueName;
public String age;
public String password;
public String jssessionid;
public String syncTime;
public int contactSwitcherSelected;
}
|
package controller.admin;
import dao.AdminDao;
import entity.Admin;
import helper.SessionManager;
import interceptor.AdminInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import validator.form.AdminFormValidator;
import javax.enterprise.inject.Intercepted;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;
import java.util.Optional;
/**
* Created by wsit on 6/13/17.
*/
@Controller
@RequestMapping("/admin/admins/")
public class AdminController {
@Autowired
private AdminDao adminDao;
@RequestMapping(method = RequestMethod.GET , value = "create")
public ModelAndView create(){
return new ModelAndView("admin/admins/create").addObject("fields",new AdminFormValidator());
}
@RequestMapping(method = RequestMethod.POST,value = "create")
public ModelAndView store(HttpServletRequest request, @ModelAttribute("fields")@Valid AdminFormValidator fields, BindingResult result, RedirectAttributes redirectAttributes){
Admin superAdmin = (Admin) SessionManager.getAdminFromSession(request);
if(result.hasErrors()){
return new ModelAndView("admin/admins/create").addObject("fields",fields);
}
if(adminDao.isExists(fields.getEmail())){
result.rejectValue("email","error.email","Email is already taken");
return new ModelAndView("admin/login").addObject("fields",fields);
}
Admin admin = new Admin();
admin.setName(fields.getName());
admin.setEmail(fields.getEmail());
admin.setPassword(DigestUtils.md5DigestAsHex(fields.getPassword().getBytes()));
admin.setType(Integer.parseInt(fields.getType()));
admin.setCreatedAt(new Date());
admin.setUpdatedAt(new Date());
admin.setCreatedBy(superAdmin.getId());
admin.setUpadatedBy(superAdmin.getId());
admin = adminDao.insert(admin);
return new ModelAndView("redirect:/admin/admins/list");
}
@RequestMapping(method = RequestMethod.GET,value = "list")
public ModelAndView list(){
return new ModelAndView("admin/admins/list").addObject("admins",adminDao.all());
}
@RequestMapping(method = RequestMethod.GET, value = "status/{id}")
public ModelAndView changeStatus(HttpServletRequest request, @PathVariable("id") int id){
Admin admin = adminDao.getById(id);
if(admin.getStatus()!= 0){
admin.setStatus(0);
}else{
admin.setStatus(1);
}
adminDao.update(admin);
return new ModelAndView("redirect:/admin/admins/list");
}
}
|
/**
* All rights Reserved, Designed By www.tydic.com
* @Title: ItemCatController.java
* @Package com.taotao.controller
* @Description: TODO(用一句话描述该文件做什么)
* @author: axin
* @date: 2018年12月3日 下午11:15:57
* @version V1.0
* @Copyright: 2018 www.hao456.top Inc. All rights reserved.
*/
package com.taotao.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.taotao.common.pojo.TreeNode;
import com.taotao.service.ItemCatService;
/**
* @ClassName: ItemCatController
* @Description:商品分类Controller
* @author: Axin
* @date: 2018年12月3日 下午11:15:57
* @Copyright: 2018 www.hao456.top Inc. All rights reserved.
*/
@Controller
@RequestMapping("/item/cat")
public class ItemCatController {
@Autowired
private ItemCatService itemCatService;
@RequestMapping("/list")
@ResponseBody
public List<TreeNode> getCatList(@RequestParam(value="id",defaultValue="0")long parentId){
List<TreeNode> list = this.itemCatService.getCatList(parentId);
return list;
}
}
|
/*
*6.5.5
*
*/
public class KeyBoard extends Turtle{
public static void main(String[] args){
Turtle.startTurtle(new KeyBoard());
}
public void start(){
int i;
int j;
int k;
int l;
int m;
int margin=3;
k=1;
while(k<=3){
j=1;
while(j<=10){
i=1;
while(i<=4){
fd(10);
rt(90);
i++;
}
up();
rt(90);
fd(10+margin);
lt(90);
down();
j++;
}
lt(90);
up();
fd((10+margin)*10);
lt(90);
fd(10+margin);
rt(180);
down();
k++;
}
up();
fd(10);
lt(90);
fd(margin);
down();
l=1;
while(l<=2){
rt(90);
fd((10+margin)*3+margin);
rt(90);
fd((10+margin)*10+margin);
l++;
}
up();
rt(90);
fd(10+(margin*3));
rt(90);
fd((margin*5)+(10*3));
down();
m=1;
while(m<=2){
fd(5);
up();
fd((margin*5)+(10*2));
down();
m++;
}
}
}
|
package com.hhdb.csadmin.plugin.tree.ui.rightMenu;
import java.awt.event.ActionEvent;
import java.sql.Connection;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import com.hh.frame.common.log.LM;
import com.hh.frame.dbobj.hhdb.HHdbDatabase;
import com.hh.frame.swingui.event.CmdEvent;
import com.hh.frame.swingui.event.ErrorEvent;
import com.hh.frame.swingui.event.HHEvent;
import com.hhdb.csadmin.common.util.StartUtil;
import com.hhdb.csadmin.plugin.tree.HTree;
import com.hhdb.csadmin.plugin.tree.service.ScriptService;
import com.hhdb.csadmin.plugin.tree.ui.BaseTreeNode;
import com.hhdb.csadmin.plugin.tree.ui.script.ExescriptPanel;
/**
* 数据库实例右键菜单
*
* @author huyuanzhui
*
*/
public class DBMenu extends BasePopupMenu {
private static final long serialVersionUID = 1L;
private BaseTreeNode treeNode;
private HTree htree = null;
public DBMenu(HTree htree){
this.htree = htree;
add(createMenuItem("执行脚本", "runScript", this));
addSeparator();
add(createMenuItem("新建数据库", "adddb", this));
add(createMenuItem("删除数据库", "delete", this));
}
public DBMenu getInstance(BaseTreeNode node) {
treeNode = node;
return this;
}
@Override
public void actionPerformed(ActionEvent e) {
String actionCmd = e.getActionCommand();
if(actionCmd.equals("runScript")){
try {
if(!ScriptService.checkTableEst()){
ScriptService.initTable();
}
String flagName = treeNode.getMetaTreeNodeBean().getName();
String toId = "com.hhdb.csadmin.plugin.tabpane";
CmdEvent tabPanelEvent = new CmdEvent(htree.PLUGIN_ID, toId, "AddPanelEvent");
tabPanelEvent.addProp("TAB_TITLE", "数据库脚本执行("+flagName+")");
tabPanelEvent.addProp("COMPONENT_ID", "script_"+ScriptService.dbtype+flagName);
tabPanelEvent.addProp("ICO", "start.png");
tabPanelEvent.setObj(new ExescriptPanel(htree,treeNode,ScriptService.dbtype));
htree.sendEvent(tabPanelEvent);
} catch (SQLException e1) {
LM.error(LM.Model.CS.name(), e1);
JOptionPane.showMessageDialog(null, e1.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
return;
}
}
else if (actionCmd.equals("adddb")) {
CmdEvent addevent = new CmdEvent(htree.PLUGIN_ID, "com.hhdb.csadmin.plugin.database", "add");
htree.sendEvent(addevent);
}
else if (actionCmd.equals("delete")) {
CmdEvent getconnEvent = new CmdEvent(htree.PLUGIN_ID,"com.hhdb.csadmin.plugin.conn", "GetConn");
HHEvent refevent = htree.sendEvent(getconnEvent);
if(!(refevent instanceof ErrorEvent)){
Connection conn = (Connection)refevent.getObj();
HHdbDatabase hdb = new HHdbDatabase(conn,treeNode.getMetaTreeNodeBean().getName(), true,StartUtil.prefix);
try {
hdb.drop();
JOptionPane.showMessageDialog(null,"删除成功!", "消息",
JOptionPane.INFORMATION_MESSAGE);
htree.treeService.refreshDBCollection(treeNode.getParentBaseTreeNode());
} catch (Exception e1) {
LM.error(LM.Model.CS.name(), e1);
JOptionPane.showMessageDialog(null,e1.getMessage(), "错误",
JOptionPane.ERROR_MESSAGE);
}
}else{
JOptionPane.showMessageDialog(null,((ErrorEvent)refevent).getErrorMessage(), "错误",
JOptionPane.ERROR_MESSAGE);
}
}
}
}
|
package com.wse.controller;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class CreateAndWriteFileIn {
public CreateAndWriteFileIn( String filePath ) {
try {
File file = new File(filePath);
if (file.exists()){
System.out.println("File already exists.");
}else{
file.createNewFile();
System.out.println("File is created!");
}
} catch (IOException e) {
e.printStackTrace();
}
}
public CreateAndWriteFileIn( String filePath, String content ) {
try {
File file = new File(filePath);
if (file.exists()){
System.out.println("File already exists.");
}else{
file.createNewFile();
System.out.println("File is created!");
}
FileWriter writer = new FileWriter(file);
writer.write(content);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
package com.company;
import java.util.Scanner;
public class Capturar {
public static String capturarString(String msg){
System.out.print(msg);
Scanner sc = new Scanner(System.in);
return sc.nextLine();
}
public static int capturarEntero(String msg){
System.out.print(msg);
Scanner sc = new Scanner(System.in);
return sc.nextInt();
}
public static float capturarFloat(String msg){
System.out.print(msg);
Scanner sc = new Scanner(System.in);
return sc.nextFloat();
}
}
|
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
private boolean carryOn;
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = getDigitSum(l1, l2);
ListNode curr = head;
l1 = l1.next;
l2 = l2.next;
while(l1 != null && l2 != null){
ListNode digitSum = getDigitSum(l1, l2);
curr.next = digitSum;
curr = curr.next;
l1 = l1.next;
l2 = l2.next;
}
while(l1 != null){
ListNode digitSum = getDigitSum(l1, new ListNode(0));
curr.next = digitSum;
curr = curr.next;
l1 = l1.next;
}
while(l2 != null){
ListNode digitSum = getDigitSum(l2, new ListNode(0));
curr.next = digitSum;
curr = curr.next;
l2 = l2.next;
}
if(carryOn){
curr.next = new ListNode(1);
}
return head;
}
private ListNode getDigitSum(ListNode l1, ListNode l2){
if(carryOn){ // carry 1 digit
int sum = l1.val + l2.val + 1;
if(sum >= 10){ // still carry 1
return new ListNode(sum % 10);
}else{ // no carryon anymore
carryOn = false;
return new ListNode(sum);
}
}else{ // no carryon
int sum = l1.val + l2.val;
if(sum >= 10){ // now carries 1
carryOn = true;
return new ListNode(sum % 10);
}else{ // still no carryon
return new ListNode(sum);
}
}
}
} |
package com.atguigu.lgl;
/*
��д�����1ѭ����150������ÿ�д�ӡһ��ֵ��������ÿ��3�ı������ϴ�ӡ����foo��,��ÿ��5�ı������ϴ�ӡ��biz��,��ÿ��7�ı������ϴ�ӡ�����baz����
*/
public class test5
{
public static void main(String[] args){
for (int i=1;i<=150 ;i++ )
{
int sum1=i%3;
int sum2=i%5;
int sum3=i%7;
System.out.print(i +" ");
if(sum1 == 0)
{
System.out.print("foo " );
}
if (sum2 == 0)
{
System.out.print("biz " );
}
if (sum3 == 0)
{
System.out.print("baz " );
}
System.out.println();
}
}
} |
package com.Hackerrank.ds.stack;
import java.util.Scanner;
import java.util.Stack;
public class SimpleTextEditor {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner sc=new Scanner(System.in);
int q=sc.nextInt();
String output="";
Stack<StackNode> stack=new Stack<StackNode>();
StackNode stackNode=null;
for(int i=0;i<q;i++){
int k=sc.nextInt();
//insert
if(k==1){
String s=sc.next();
output=output+s;
stackNode=new StackNode(s,true);
stack.push(stackNode);
}else if(k==2){//delete
int d=sc.nextInt();
int size=output.length();
String deletedText=output.substring(size-d,size);
output=output.substring(0,size-d);
stackNode=new StackNode(deletedText,false);
stack.push(stackNode);
}else if(k==3){//print
int p=sc.nextInt();
// System.out.println("Printing entire string"+output);
System.out.println(output.charAt(p-1));
}else {//undo
if(!stack.isEmpty()){
stackNode=stack.pop();
if(stackNode.insertFlag){
output=output.substring(0,output.length()-stackNode.str.length());
}else{
output=output+stackNode.str;
}
}
}
}
}
private static class StackNode{
String str;
boolean insertFlag;
StackNode(String str,boolean insertFlag){
this.str=str;
this.insertFlag=insertFlag;
}
}
} |
package net.winksoft;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.NfcB;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.winksoft.idcardcer.bean.IdCardBean;
import com.winksoft.idcardcer.callback.IReadIdCardCallBack;
import com.winksoft.idcardcer.callback.ResultCode;
import com.winksoft.idcardcer.main.IDCardAuthTask;
import com.winksoft.reader.NFCReader;
import java.io.IOException;
import butterknife.BindView;
import butterknife.ButterKnife;
public class MainActivity extends AppCompatActivity implements IReadIdCardCallBack {
@BindView(R.id.tv_name)
TextView tvName;
@BindView(R.id.iv_photo)
ImageView ivPhoto;
@BindView(R.id.tv_sex)
TextView tvSex;
@BindView(R.id.tv_ehtnic)
TextView tvEhtnic;
@BindView(R.id.tv_address)
TextView tvAddress;
@BindView(R.id.tv_number)
TextView tvNumber;
@BindView(R.id.tv_signed)
TextView tvSigned;
@BindView(R.id.tv_validate)
TextView tvValidate;
@BindView(R.id.tv_birthday)
TextView tvBirthday;
@BindView(R.id.t_ping)
TextView tPing;
@BindView(R.id.t_cer)
TextView tCer;
@BindView(R.id.t_comm)
TextView tComm;
@BindView(R.id.t_time)
TextView tTime;
@BindView(R.id.t_read_fail)
TextView tReadFail;
@BindView(R.id.t_cer_fail)
TextView tCerFail;
@BindView(R.id.t_comm_fail)
TextView tCommFail;
@BindView(R.id.t_sucess)
TextView tSucess;
@BindView(R.id.t_ip_port)
TextView tIpPort;
@BindView(R.id._conn_state)
TextView tConnState;
@BindView(R.id.t_read_state)
TextView tReadState;
@BindView(R.id.step_tv1)
TextView stepTv1;
@BindView(R.id.step_tv2)
TextView stepTv2;
@BindView(R.id.step_tv3)
TextView stepTv3;
@BindView(R.id.step_tv4)
TextView stepTv4;
@BindView(R.id.step_tv5)
TextView stepTv5;
@BindView(R.id.step_tv6)
TextView stepTv6;
@BindView(R.id.step_tv7)
TextView stepTv7;
@BindView(R.id.step_tv8)
TextView stepTv8;
@BindView(R.id.step_tv9)
TextView stepTv9;
@BindView(R.id.step_tv10)
TextView stepTv10;
private NfcB mNfcbTag;
private static int read_fail_count = 0;
private static int cer_fail_count = 0;
private static int comm_fail_count = 0;
private static int success_count = 0;
private Dialog mIp_port_dialog;
private IDCardAuthTask mIdCardAuthTask;
private ProgressDialog mLoadingDialog;
private AlertDialog mSet_nfc_dialog;
// private String ip = "49.71.66.14";
private String ip = "114.230.202.137";
private int port = 18988;
private int i;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
tIpPort.setText(ip + " " + port);
clearUI();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.main_setting_menu:
ipPortSettingDialog();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onResume() {
super.onResume();
final NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (nfcAdapter == null) {
Toast.makeText(this, "抱歉!此设备不支持NFC功能", Toast.LENGTH_SHORT).show();
return;
}
if (!nfcAdapter.isEnabled()) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("请打开NFC");
builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
openNFCSetting();
if (mSet_nfc_dialog != null && mSet_nfc_dialog.isShowing()) {
mSet_nfc_dialog.dismiss();
}
}
});
mSet_nfc_dialog = builder.create();
mSet_nfc_dialog.show();
return;
}
if (nfcAdapter.isEnabled())
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
int READER_FLAGS = NfcAdapter.FLAG_READER_NFC_A | NfcAdapter.FLAG_READER_NFC_B | NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK;
nfcAdapter.enableReaderMode(this, new NfcAdapter.ReaderCallback() {
@Override
public void onTagDiscovered(Tag tag) {
mNfcbTag = NfcB.get(tag);
try {
mNfcbTag.connect();
if (mNfcbTag.isConnected()) {
// ----------------------------------------------------------------------
NFCReader nfcReader = new NFCReader();
nfcReader.setTag(mNfcbTag);
if (mIdCardAuthTask != null) {
mIdCardAuthTask = null;
}
mIdCardAuthTask = new IDCardAuthTask(nfcReader, MainActivity.this, ip, port);
mIdCardAuthTask.execute();
// ----------------------------------------------------------------------
}
} catch (IOException e) {
e.printStackTrace();
}
}
}, READER_FLAGS, null);
}
}
private void claerCount() {
read_fail_count = 0;
cer_fail_count = 0;
comm_fail_count = 0;
success_count = 0;
tReadFail.setText("");
tCommFail.setText("");
tCerFail.setText("");
tSucess.setText("");
}
private void clearUI() {
tvName.setText("");
ivPhoto.setImageBitmap(null);
tvSex.setText("");
tvEhtnic.setText("");
tvBirthday.setText("");
tvAddress.setText("");
tvSigned.setText("");
tvValidate.setText("");
tvNumber.setText("");
}
private void showLoading() {
missLoading();
mLoadingDialog = new ProgressDialog(this);
mLoadingDialog.setMessage("正在连接中,请稍后……");
mLoadingDialog.show();
}
private void missLoading() {
if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
mLoadingDialog.dismiss();
}
}
@Override
public void onStartRead() {
clearUI();
i = 0;
stepTv1.setText("");
stepTv2.setText("");
stepTv3.setText("");
stepTv4.setText("");
stepTv5.setText("");
stepTv6.setText("");
stepTv7.setText("");
stepTv8.setText("");
stepTv9.setText("");
stepTv10.setText("");
showLoading();
}
@Override
public void onSuccess(IdCardBean idCardBean) {
missLoading();
if (idCardBean != null) {
// 成功
tReadState.setTextColor(getResources().getColor(R.color.md_green_A400));
tReadState.setText("读取成功");
tSucess.setText(++success_count + "次");
tvName.setText(idCardBean.getName());
ivPhoto.setImageBitmap(idCardBean.getPhoto());
tvSex.setText(idCardBean.getSex());
tvEhtnic.setText(idCardBean.getNation());
tvBirthday.setText(formatDate(idCardBean.getBirth()));
tvAddress.setText(idCardBean.getAddress());
tvSigned.setText(idCardBean.getPolice());
tvValidate.setText(formatDate1(idCardBean.getFromValidDate()) + " - " + formatDate1(idCardBean.getToValidDate()));
tvNumber.setText(idCardBean.getCode());
tPing.setText(idCardBean.getT_ping() + "ms");
tCer.setText(idCardBean.getT_cer() + "ms");
tComm.setText(idCardBean.getT_commun() + "ms");
tTime.setText(System.currentTimeMillis() - idCardBean.getTime() + "ms");
}
}
private void clearTime() {
tPing.setText("");
tCer.setText("");
tComm.setText("");
tTime.setText("");
}
@Override
public void onFail(int errCode, String errMsg) {
missLoading();
clearTime();
tReadState.setTextColor(getResources().getColor(R.color.md_red_500));
if (errCode == ResultCode.FAILED_TO_READ ||
errCode == ResultCode.TAG_LOSS ||
errCode == ResultCode.E_USERIDNOTFOUND ||
errCode == ResultCode.E_USERMACERROR ||
errCode == ResultCode.E_USERDATEERR ||
errCode == ResultCode.E_USERDAYLIMIT ||
errCode == ResultCode.E_USERCONCURRENCY ||
errCode == ResultCode.E_USERTERMDAYLIMIT ||
errCode == ResultCode.E_USERDAYLIMIT_IDSAM ||
errCode == ResultCode.E_OTHER) {
// 读取错误
tReadState.setText(errMsg);
tReadFail.setText(++read_fail_count + "次");
} else if (errCode == ResultCode.CER_FAILED) {
// 认证错误
tReadState.setText(errMsg);
tCerFail.setText(++cer_fail_count + "次");
} else if (errCode == ResultCode.COMM_FAILED) {
// 通信错误
tCommFail.setText(++comm_fail_count + "次");
tReadState.setText(errMsg);
} else if (errCode == ResultCode.CONNECTION_FAILED) {
tConnState.setTextColor(getResources().getColor(R.color.md_red_500));
tConnState.setText(errMsg);
}
}
@Override
public void onConnectSuccess() {
tConnState.setText("连接服务器成功");
tConnState.setTextColor(getResources().getColor(R.color.md_green_A400));
}
@Override
public void onConnectClose() {
missLoading();
tConnState.setText("连接断开");
tConnState.setTextColor(getResources().getColor(R.color.md_red_500));
}
@Override
public void onStep(String s, String s1, String s2, String s3, String s4, String s5, String s6, String s7, String s8, String s9) {
stepTv1.setText(s);
stepTv2.setText(s1);
stepTv3.setText(s2);
stepTv4.setText(s3);
stepTv5.setText(s4);
stepTv6.setText(s5);
stepTv7.setText(s6);
stepTv8.setText(s7);
stepTv9.setText(s8);
stepTv10.setText(s9);
}
public String formatDate(String s) {
return new StringBuffer()
.append(s.substring(0, 4))
.append(" 年 ")
.append(s.substring(4, 6))
.append(" 月 ")
.append(s.substring(6, 8))
.append(" 日 ")
.toString();
}
public String formatDate1(String s) {
return new StringBuffer()
.append(s.substring(0, 4))
.append(".")
.append(s.substring(4, 6))
.append(".")
.append(s.substring(6, 8))
.toString();
}
/**
* 输入IP PORT的dialog
*/
public void ipPortSettingDialog() {
mIp_port_dialog = new Dialog(this, R.style.dialog_new);
mIp_port_dialog.setContentView(R.layout.input_ip_port_dialog);
TextView ptitle = (TextView) mIp_port_dialog.findViewById(R.id.pTitle);
final EditText ipEt = (EditText) mIp_port_dialog.findViewById(R.id.ip_et);
final EditText portEt = (EditText) mIp_port_dialog.findViewById(R.id.port_et);
ipEt.setText(ip);
portEt.setText(port + "");
Button qd = (Button) mIp_port_dialog.findViewById(R.id.confirm_btn);
Button qx = (Button) mIp_port_dialog.findViewById(R.id.cancel_btn);
ptitle.setText("参数设置");
qx.setText("取消");
qd.setText("确定");
qd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String ip_input = ipEt.getText().toString().toString();
String port_input = portEt.getText().toString().toString();
if (TextUtils.isEmpty(ip_input)) {
Toast.makeText(MainActivity.this, "ip不能设置为空", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(port_input)) {
Toast.makeText(MainActivity.this, "端口号不能设置为空", Toast.LENGTH_SHORT).show();
return;
}
ip = ip_input;
port = Integer.parseInt(port_input);
tIpPort.setText(ip + " " + port);
closeIsodep();
tReadState.setText("");
tConnState.setText("");
clearUI();
clearTime();
claerCount();
if (mIdCardAuthTask != null) {
mIdCardAuthTask.close();
}
missSettingDialog();
}
});
qx.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
missSettingDialog();
}
});
mIp_port_dialog.setCancelable(false);
mIp_port_dialog.show();
}
private void missSettingDialog() {
if (mIp_port_dialog != null && mIp_port_dialog.isShowing()) {
mIp_port_dialog.dismiss();
}
}
public void closeIsodep() {
if (mNfcbTag != null && mNfcbTag.isConnected()) {
try {
mNfcbTag.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 打开NFC设置
*/
public void openNFCSetting() {
Intent intent = new Intent(Settings.ACTION_NFC_SETTINGS);
startActivity(intent);
}
}
|
package com.xld.common.other;
import javax.servlet.http.HttpServletRequest;
/**
* IP地址操作工具类
* @author xld
* @date 2018-09-29
*/
public class IpAddressUtil {
/**
* 获取访问用户的客户端IP(适用于公网与局域网)
*/
public static String getIpAddress(HttpServletRequest request){
if (request == null) {
return null;
}
String ip = request.getHeader("x-forwarded-for");
if (StrUtil.isNotEmpty(ip) && !"unknown".equalsIgnoreCase(ip)) {
// 多次反向代理后会有多个ip值,第一个ip才是真实ip
if(ip.indexOf(",") != -1){
ip = ip.split(",")[0];
}
}
if (StrUtil.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (StrUtil.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (StrUtil.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (StrUtil.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (StrUtil.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Real-IP");
}
if (StrUtil.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return StrUtil.trimToEmpty(ip);
}
}
|
package co.edu.meli.application.entrypoint;
import co.edu.meli.domain.dto.AllSatelliteRequestDTO;
import co.edu.meli.domain.dto.PositionDTO;
import co.edu.meli.domain.dto.ResponseDTO;
import co.edu.meli.domain.model.Result;
import co.edu.meli.domain.model.SpaceshipReference;
import co.edu.meli.domain.usecase.ExtractInformationUseCase;
import lombok.extern.slf4j.Slf4j;
import javax.inject.Inject;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.net.HttpURLConnection;
@Slf4j
@Path("/topsecret")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class TopSecretResource {
@Inject
ExtractInformationUseCase extractInformationUseCase;
@POST
public ResponseDTO extract(AllSatelliteRequestDTO requestDTO) {
try {
final SpaceshipReference spaceshipReference = SpaceshipReference.builder()
.toKenobi(requestDTO.findDistance("kenobi"))
.toSato(requestDTO.findDistance("sato"))
.toSkywalker(requestDTO.findDistance("skywalker"))
.build();
var result = extractInformationUseCase.process(spaceshipReference, requestDTO.messagesList());
return buildResponse(result);
} catch (Exception ex) {
throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);
}
}
private ResponseDTO buildResponse(Result result) {
final PositionDTO positionDTO = new PositionDTO(result.getPosition().getEast(), result.getPosition().getNorth());
return new ResponseDTO(positionDTO, result.getMessage());
}
} |
package com.inu.tmi.map;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.nhn.android.maps.NMapActivity;
import com.nhn.android.maps.NMapContext;
import com.nhn.android.maps.NMapController;
import com.nhn.android.maps.NMapLocationManager;
import com.nhn.android.maps.NMapView;
import com.nhn.android.maps.maplib.NGeoPoint;
import com.nhn.android.maps.nmapmodel.NMapError;
import com.nhn.android.maps.nmapmodel.NMapPlacemark;
import com.nhn.android.maps.overlay.NMapPOIdata;
import com.nhn.android.maps.overlay.NMapPOIitem;
import com.nhn.android.mapviewer.overlay.NMapOverlayManager;
import com.nhn.android.mapviewer.overlay.NMapPOIdataOverlay;
/**
* NMapFragment 클래스는 NMapActivity를 상속하지 않고 NMapView만 사용하고자 하는 경우에 NMapContext를 이용한 예제임.
* NMapView 사용시 필요한 초기화 및 리스너 등록은 NMapActivity 사용시와 동일함.
*/
public class NMapFragment extends Fragment {
private static final boolean DEBUG = false;
private static final String LOG_TAG = "TMI";
private String CLIENT_ID = "0wrUmrxzqvLfV5oXKiPZ";
private NMapContext mMapContext;
private NMapController mMapController;
private NMapViewerResourceProvider mMapViewerResourceProvider;
private NMapOverlayManager mOverlayManager;
private NMapPOIdataOverlay poiDataOverlay;
private NMapPOIdataOverlay mFloatingPOIdataOverlay;
private NMapPOIitem mFloatingPOIitem;
private double latitude;
private double longitude;
private String address;
private NGeoPoint point;
private NGeoPoint selectPoint;
/**
* Fragment에 포함된 NMapView 객체를 반환함
*/
private NMapView findMapView(View v) {
if (!(v instanceof ViewGroup)) {
return null;
}
ViewGroup vg = (ViewGroup) v;
if (vg instanceof NMapView) {
return (NMapView) vg;
}
for (int i = 0; i < vg.getChildCount(); i++) {
View child = vg.getChildAt(i);
if (!(child instanceof ViewGroup)) {
continue;
}
NMapView mapView = findMapView(child);
if (mapView != null) {
return mapView;
}
}
return null;
}
/* Fragment 라이프사이클에 따라서 NMapContext의 해당 API를 호출함 */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mMapContext = new NMapContext(super.getActivity());
mMapContext.setMapDataProviderListener(onDataProviderListener);
mMapContext.onCreate();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
throw new IllegalArgumentException("onCreateView should be implemented in the subclass of NMapFragment.");
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Fragment에 포함된 NMapView 객체 찾기
final NMapView mapView = findMapView(super.getView());
if (mapView == null) {
throw new IllegalArgumentException("NMapFragment dose not have an instance of NMapView.");
}
mapView.setClientId(CLIENT_ID);// 클라이언트 아이디 설정
mapView.setClickable(true);
mapView.setEnabled(true);
mapView.setFocusable(true);
mapView.setFocusableInTouchMode(true);
mapView.requestFocus();
NMapLocationManager mMapLocationManager = new NMapLocationManager(getContext());
mMapLocationManager.setOnLocationChangeListener(onMyLocationChangeListener);
mMapLocationManager.enableMyLocation(true);
NMapLocationManager initPosition = new NMapLocationManager(getContext());
initPosition.setOnLocationChangeListener(new NMapLocationManager.OnLocationChangeListener() {
@Override
public boolean onLocationChanged(NMapLocationManager nMapLocationManager, NGeoPoint nGeoPoint) {
if (mMapController != null) {
mMapController.animateTo(nGeoPoint);
mMapController.setMapCenter(nGeoPoint);
}
point = nGeoPoint;
MarkMyLocation();
return false;
}
@Override
public void onLocationUpdateTimeout(NMapLocationManager nMapLocationManager) {
}
@Override
public void onLocationUnavailableArea(NMapLocationManager nMapLocationManager, NGeoPoint nGeoPoint) {
}
});
initPosition.enableMyLocation(true);
// NMapActivity를 상속하지 않는 경우에는 NMapView 객체 생성후 반드시 setupMapView()를 호출해야함.
mMapContext.setupMapView(mapView);
mMapViewerResourceProvider = new NMapViewerResourceProvider(getContext());
mOverlayManager = new NMapOverlayManager(getContext(), mapView, mMapViewerResourceProvider);
mMapController = mapView.getMapController();
}
public NGeoPoint getPoint() {
return point;
}
public NGeoPoint getSelectPoint() {
return selectPoint;
}
public String getAddress() {
return address;
}
private final NMapLocationManager.OnLocationChangeListener onMyLocationChangeListener = new NMapLocationManager.OnLocationChangeListener() {
@Override
public boolean onLocationChanged(NMapLocationManager nMapLocationManager, NGeoPoint nGeoPoint) {
latitude = nGeoPoint.getLatitude();
longitude = nGeoPoint.getLongitude();
point = nGeoPoint;
return true;
}
@Override
public void onLocationUpdateTimeout(NMapLocationManager nMapLocationManager) {
}
@Override
public void onLocationUnavailableArea(NMapLocationManager nMapLocationManager, NGeoPoint nGeoPoint) {
}
};
private final NMapActivity.OnDataProviderListener onDataProviderListener = new NMapActivity.OnDataProviderListener() {
@Override
public void onReverseGeocoderResponse(NMapPlacemark placeMark, NMapError errInfo) {
if (placeMark != null) {
address = placeMark.toString();
}
if (DEBUG) {
Log.i(LOG_TAG, "onReverseGeocoderResponse: placeMark="
+ ((placeMark != null) ? placeMark.toString() : null));
}
if (errInfo != null) {
Log.e(LOG_TAG, "Failed to findPlacemarkAtLocation: error=" + errInfo.toString());
return;
}
}
};
private final NMapPOIdataOverlay.OnFloatingItemChangeListener onPOIdataFloatingItemChangeListener = new NMapPOIdataOverlay.OnFloatingItemChangeListener() {
@Override
public void onPointChanged(NMapPOIdataOverlay poiDataOverlay, NMapPOIitem item) {
NGeoPoint point = item.getPoint();
if (DEBUG) {
Log.i(LOG_TAG, "onPointChanged: point=" + point.toString());
}
mMapContext.findPlacemarkAtLocation(point.longitude, point.latitude);
item.setTitle(address);
}
};
private final NMapPOIdataOverlay.OnStateChangeListener onPOIdataStateChangeListener = new NMapPOIdataOverlay.OnStateChangeListener() {
@Override
public void onCalloutClick(NMapPOIdataOverlay poiDataOverlay, NMapPOIitem item) {
if (DEBUG) {
Log.i(LOG_TAG, "onCalloutClick: title=" + item.getTitle());
}
// [[TEMP]] handle a click event of the callout
}
@Override
public void onFocusChanged(NMapPOIdataOverlay poiDataOverlay, NMapPOIitem item) {
if (DEBUG) {
if (item != null) {
Log.i(LOG_TAG, "onFocusChanged: " + item.toString());
} else {
Log.i(LOG_TAG, "onFocusChanged: ");
}
}
}
};
public void MarkMyLocation() {
mMapContext.findPlacemarkAtLocation(longitude, latitude);
int markerId = NMapPOIflagType.PIN;
if (poiDataOverlay != null && !poiDataOverlay.isHidden()) {
poiDataOverlay.setHidden(true);
poiDataOverlay.removeAllPOIdata();
}
// set POI data
NMapPOIdata poiData = new NMapPOIdata(1, mMapViewerResourceProvider);
poiData.beginPOIdata(1);
poiData.addPOIitem(longitude, latitude, address, markerId, 0);
poiData.endPOIdata();
NMapPOIitem item = poiData.getPOIitem(0);
if(item != null){
//item.setPoint(mMapController.getMapCenter());
item.setPoint(point);
// set floating mode
item.setFloatingMode(NMapPOIitem.FLOATING_TOUCH | NMapPOIitem.FLOATING_DRAG);
// show right button on callout
mFloatingPOIitem = item;
point = mFloatingPOIitem.getPoint();
}
// create POI data overlay
poiDataOverlay = mOverlayManager.createPOIdataOverlay(poiData, null);
if (poiDataOverlay != null) {
poiDataOverlay.setOnFloatingItemChangeListener(onPOIdataFloatingItemChangeListener);
// set event listener to the overlay
poiDataOverlay.setOnStateChangeListener(onPOIdataStateChangeListener);
poiDataOverlay.selectPOIitem(0, false);
mFloatingPOIdataOverlay = poiDataOverlay;
}
// show all POI data
poiDataOverlay.showAllPOIdata(0);
}
public String MarkLocation()
{
return address.toString();
}
@Override
public void onStart() {
super.onStart();
mMapContext.onStart();
}
@Override
public void onResume() {
super.onResume();
mMapContext.onResume();
}
@Override
public void onPause() {
super.onPause();
mMapContext.onPause();
}
@Override
public void onStop() {
mMapContext.onStop();
super.onStop();
}
@Override
public void onDestroyView() {
super.onDestroyView();
}
@Override
public void onDestroy() {
mMapContext.onDestroy();
super.onDestroy();
}
} |
package ru.ptahi.blurjava;
/** Localizable strings for {@link ru.ptahi.blurjava}. */
@javax.annotation.Generated(value="org.netbeans.modules.openide.util.NbBundleProcessor")
class Bundle {
/**
* @return <i>Source</i>
* @see BlurJavaModuleDataObject
*/
static String LBL_BlurJavaModule_EDITOR() {
return org.openide.util.NbBundle.getMessage(Bundle.class, "LBL_BlurJavaModule_EDITOR");
}
/**
* @return <i>Files of BlurJavaModule</i>
* @see BlurJavaModuleDataObject
*/
static String LBL_BlurJavaModule_LOADER() {
return org.openide.util.NbBundle.getMessage(Bundle.class, "LBL_BlurJavaModule_LOADER");
}
/**
* @return <i>Visual</i>
* @see BlurJavaModuleVisualElement
*/
static String LBL_BlurJavaModule_VISUAL() {
return org.openide.util.NbBundle.getMessage(Bundle.class, "LBL_BlurJavaModule_VISUAL");
}
private void Bundle() {}
}
|
package com.codigo.smartstore.database.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
// jednostka podziału administracyjnego
@Entity
@Table(name = "AdministrativeDivisionType")
public class AdministrativeDivisionType {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "Id")
private Long id;
@Column(name = "Code", length = 10, nullable = false, unique = true)
private String Code;
@Column(name = "Name", length = 50, nullable = false, unique = false)
private String name;
} |
package com.example.nahid.houserent.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
/**
* Created by nahid on 13-Aug-17.
*/
public class PostModel {
@SerializedName("post_status")
@Expose
private String postStatus;
public String getPostStatus() {
return postStatus;
}
public void setPostStatus(String postStatus) {
this.postStatus = postStatus;
}
}
|
package com.orlanth23.popularmovie.retrofitservice;
import com.orlanth23.popularmovie.model.ResultListMovie;
import com.orlanth23.popularmovie.model.ResultListReview;
import com.orlanth23.popularmovie.model.ResultListTrailers;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;
public interface MovieDbAPI {
@GET("movie/popular")
Call<ResultListMovie> getPopularMovies(@Query("api_key") String api_key, @Query("page") int page);
@GET("movie/top_rated")
Call<ResultListMovie> getTopRated(@Query("api_key") String api_key, @Query("page") int page);
@GET("movie/{movie_id}/videos")
Call<ResultListTrailers> getTrailers(@Path("movie_id") int movie_id, @Query("api_key") String api_key);
@GET("movie/{movie_id}/reviews")
Call<ResultListReview> getReviews(@Path("movie_id") int movie_id, @Query("api_key") String api_key, @Query("page") int page);
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.http.codec.multipart;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Supplier;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import org.springframework.core.ResolvableType;
import org.springframework.core.ResolvableTypeProvider;
import org.springframework.core.codec.CharSequenceEncoder;
import org.springframework.core.codec.CodecException;
import org.springframework.core.codec.Hints;
import org.springframework.core.io.Resource;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.log.LogFormatUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ReactiveHttpOutputMessage;
import org.springframework.http.codec.EncoderHttpMessageWriter;
import org.springframework.http.codec.FormHttpMessageWriter;
import org.springframework.http.codec.HttpMessageWriter;
import org.springframework.http.codec.ResourceHttpMessageWriter;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.MultiValueMap;
/**
* {@link HttpMessageWriter} for writing a {@code MultiValueMap<String, ?>}
* as multipart form data, i.e. {@code "multipart/form-data"}, to the body
* of a request.
*
* <p>The serialization of individual parts is delegated to other writers.
* By default only {@link String} and {@link Resource} parts are supported but
* you can configure others through a constructor argument.
*
* <p>This writer can be configured with a {@link FormHttpMessageWriter} to
* delegate to. It is the preferred way of supporting both form data and
* multipart data (as opposed to registering each writer separately) so that
* when the {@link MediaType} is not specified and generics are not present on
* the target element type, we can inspect the values in the actual map and
* decide whether to write plain form data (String values only) or otherwise.
*
* @author Sebastien Deleuze
* @author Rossen Stoyanchev
* @since 5.0
* @see FormHttpMessageWriter
*/
public class MultipartHttpMessageWriter extends MultipartWriterSupport
implements HttpMessageWriter<MultiValueMap<String, ?>> {
/** Suppress logging from individual part writers (full map logged at this level). */
private static final Map<String, Object> DEFAULT_HINTS = Hints.from(Hints.SUPPRESS_LOGGING_HINT, true);
private final Supplier<List<HttpMessageWriter<?>>> partWritersSupplier;
@Nullable
private final HttpMessageWriter<MultiValueMap<String, String>> formWriter;
/**
* Constructor with a default list of part writers (String and Resource).
*/
public MultipartHttpMessageWriter() {
this(Arrays.asList(
new EncoderHttpMessageWriter<>(CharSequenceEncoder.textPlainOnly()),
new ResourceHttpMessageWriter()
));
}
/**
* Constructor with explicit list of writers for serializing parts.
*/
public MultipartHttpMessageWriter(List<HttpMessageWriter<?>> partWriters) {
this(partWriters, new FormHttpMessageWriter());
}
/**
* Constructor with explicit list of writers for serializing parts and a
* writer for plain form data to fall back when no media type is specified
* and the actual map consists of String values only.
* @param partWriters the writers for serializing parts
* @param formWriter the fallback writer for form data, {@code null} by default
*/
public MultipartHttpMessageWriter(List<HttpMessageWriter<?>> partWriters,
@Nullable HttpMessageWriter<MultiValueMap<String, String>> formWriter) {
this(() -> partWriters, formWriter);
}
/**
* Constructor with a supplier for an explicit list of writers for
* serializing parts and a writer for plain form data to fall back when
* no media type is specified and the actual map consists of String
* values only.
* @param partWritersSupplier the supplier for writers for serializing parts
* @param formWriter the fallback writer for form data, {@code null} by default
* @since 6.0.3
*/
public MultipartHttpMessageWriter(Supplier<List<HttpMessageWriter<?>>> partWritersSupplier,
@Nullable HttpMessageWriter<MultiValueMap<String, String>> formWriter) {
super(initMediaTypes(formWriter));
this.partWritersSupplier = partWritersSupplier;
this.formWriter = formWriter;
}
private static List<MediaType> initMediaTypes(@Nullable HttpMessageWriter<?> formWriter) {
List<MediaType> result = new ArrayList<>(MultipartHttpMessageReader.MIME_TYPES);
if (formWriter != null) {
result.addAll(formWriter.getWritableMediaTypes());
}
return Collections.unmodifiableList(result);
}
/**
* Return the configured part writers.
* @since 5.0.7
*/
public List<HttpMessageWriter<?>> getPartWriters() {
return Collections.unmodifiableList(this.partWritersSupplier.get());
}
/**
* Return the configured form writer.
* @since 5.1.13
*/
@Nullable
public HttpMessageWriter<MultiValueMap<String, String>> getFormWriter() {
return this.formWriter;
}
@Override
public boolean canWrite(ResolvableType elementType, @Nullable MediaType mediaType) {
if (MultiValueMap.class.isAssignableFrom(elementType.toClass())) {
if (mediaType == null) {
return true;
}
for (MediaType supportedMediaType : getWritableMediaTypes()) {
if (supportedMediaType.isCompatibleWith(mediaType)) {
return true;
}
}
}
return false;
}
@Override
public Mono<Void> write(Publisher<? extends MultiValueMap<String, ?>> inputStream,
ResolvableType elementType, @Nullable MediaType mediaType, ReactiveHttpOutputMessage outputMessage,
Map<String, Object> hints) {
return Mono.from(inputStream)
.flatMap(map -> {
if (this.formWriter == null || isMultipart(map, mediaType)) {
return writeMultipart(map, outputMessage, mediaType, hints);
}
else {
@SuppressWarnings("unchecked")
Mono<MultiValueMap<String, String>> input = Mono.just((MultiValueMap<String, String>) map);
return this.formWriter.write(input, elementType, mediaType, outputMessage, hints);
}
});
}
private boolean isMultipart(MultiValueMap<String, ?> map, @Nullable MediaType contentType) {
if (contentType != null) {
return contentType.getType().equalsIgnoreCase("multipart");
}
for (List<?> values : map.values()) {
for (Object value : values) {
if (value != null && !(value instanceof String)) {
return true;
}
}
}
return false;
}
private Mono<Void> writeMultipart(MultiValueMap<String, ?> map,
ReactiveHttpOutputMessage outputMessage, @Nullable MediaType mediaType, Map<String, Object> hints) {
byte[] boundary = generateMultipartBoundary();
mediaType = getMultipartMediaType(mediaType, boundary);
outputMessage.getHeaders().setContentType(mediaType);
LogFormatUtils.traceDebug(logger, traceOn -> Hints.getLogPrefix(hints) + "Encoding " +
(isEnableLoggingRequestDetails() ?
LogFormatUtils.formatValue(map, !traceOn) :
"parts " + map.keySet() + " (content masked)"));
DataBufferFactory bufferFactory = outputMessage.bufferFactory();
Flux<DataBuffer> body = Flux.fromIterable(map.entrySet())
.concatMap(entry -> encodePartValues(boundary, entry.getKey(), entry.getValue(), bufferFactory))
.concatWith(generateLastLine(boundary, bufferFactory))
.doOnDiscard(DataBuffer.class, DataBufferUtils::release);
if (logger.isDebugEnabled()) {
body = body.doOnNext(buffer -> Hints.touchDataBuffer(buffer, hints, logger));
}
return outputMessage.writeWith(body);
}
private Flux<DataBuffer> encodePartValues(
byte[] boundary, String name, List<?> values, DataBufferFactory bufferFactory) {
return Flux.fromIterable(values)
.concatMap(value -> encodePart(boundary, name, value, bufferFactory));
}
@SuppressWarnings({"rawtypes", "unchecked"})
private <T> Flux<DataBuffer> encodePart(byte[] boundary, String name, T value, DataBufferFactory factory) {
MultipartHttpOutputMessage message = new MultipartHttpOutputMessage(factory);
HttpHeaders headers = message.getHeaders();
T body;
ResolvableType resolvableType = null;
if (value instanceof HttpEntity httpEntity) {
headers.putAll(httpEntity.getHeaders());
body = (T) httpEntity.getBody();
Assert.state(body != null, "MultipartHttpMessageWriter only supports HttpEntity with body");
if (httpEntity instanceof ResolvableTypeProvider resolvableTypeProvider) {
resolvableType = resolvableTypeProvider.getResolvableType();
}
}
else {
body = value;
}
if (resolvableType == null) {
resolvableType = ResolvableType.forClass(body.getClass());
}
if (!headers.containsKey(HttpHeaders.CONTENT_DISPOSITION)) {
if (body instanceof Resource resource) {
headers.setContentDispositionFormData(name, resource.getFilename());
}
else if (resolvableType.resolve() == Resource.class) {
body = (T) Mono.from((Publisher<?>) body).doOnNext(o -> headers
.setContentDispositionFormData(name, ((Resource) o).getFilename()));
}
else {
headers.setContentDispositionFormData(name, null);
}
}
MediaType contentType = headers.getContentType();
ResolvableType finalBodyType = resolvableType;
Optional<HttpMessageWriter<?>> writer = this.partWritersSupplier.get().stream()
.filter(partWriter -> partWriter.canWrite(finalBodyType, contentType))
.findFirst();
if (!writer.isPresent()) {
return Flux.error(new CodecException("No suitable writer found for part: " + name));
}
Publisher<T> bodyPublisher = (body instanceof Publisher publisher ? publisher : Mono.just(body));
// The writer will call MultipartHttpOutputMessage#write which doesn't actually write
// but only stores the body Flux and returns Mono.empty().
Mono<Void> partContentReady = ((HttpMessageWriter<T>) writer.get())
.write(bodyPublisher, resolvableType, contentType, message, DEFAULT_HINTS);
// After partContentReady, we can access the part content from MultipartHttpOutputMessage
// and use it for writing to the actual request body
Flux<DataBuffer> partContent = partContentReady.thenMany(Flux.defer(message::getBody));
return Flux.concat(
generateBoundaryLine(boundary, factory),
partContent,
generateNewLine(factory));
}
private class MultipartHttpOutputMessage implements ReactiveHttpOutputMessage {
private final DataBufferFactory bufferFactory;
private final HttpHeaders headers = new HttpHeaders();
private final AtomicBoolean committed = new AtomicBoolean();
@Nullable
private Flux<DataBuffer> body;
public MultipartHttpOutputMessage(DataBufferFactory bufferFactory) {
this.bufferFactory = bufferFactory;
}
@Override
public HttpHeaders getHeaders() {
return (this.body != null ? HttpHeaders.readOnlyHttpHeaders(this.headers) : this.headers);
}
@Override
public DataBufferFactory bufferFactory() {
return this.bufferFactory;
}
@Override
public void beforeCommit(Supplier<? extends Mono<Void>> action) {
this.committed.set(true);
}
@Override
public boolean isCommitted() {
return this.committed.get();
}
@Override
public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
if (this.body != null) {
return Mono.error(new IllegalStateException("Multiple calls to writeWith() not supported"));
}
this.body = generatePartHeaders(this.headers, this.bufferFactory).concatWith(body);
// We don't actually want to write (just save the body Flux)
return Mono.empty();
}
@Override
public Mono<Void> writeAndFlushWith(Publisher<? extends Publisher<? extends DataBuffer>> body) {
return Mono.error(new UnsupportedOperationException());
}
public Flux<DataBuffer> getBody() {
return (this.body != null ? this.body :
Flux.error(new IllegalStateException("Body has not been written yet")));
}
@Override
public Mono<Void> setComplete() {
return Mono.error(new UnsupportedOperationException());
}
}
}
|
package com.gsccs.sme.web.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONObject;
import com.gsccs.sme.api.domain.base.Attach;
import com.gsccs.sme.api.domain.base.JsonMsg;
import com.gsccs.sme.api.service.ConfigServiceI;
import com.gsccs.sme.oss.client.ObjectMetadata;
import com.gsccs.sme.oss.client.OssClient;
/**
* 附件管理控制类
*
* @author x.d zhang
*
*/
@Controller
public class UploadController {
@Autowired
private ConfigServiceI configAPI;
private static String IP = "172.16.28.9";
private static int PORT = 7001;
private static String DOMAIN = "http://dns1.smeym.org/";
private static String SITE = "smeym";
private static String PATH = "images";
// 最大文件大小 5M
private static long maxSize = 10000000;
// 定义允许上传的文件扩展名
HashMap<String, String> extMap = new HashMap<String, String>();
/**
* 初始化参数
*/
private void initConf() {
IP = configAPI.getConfigVal("OSS_IP");
PORT = Integer.valueOf(configAPI.getConfigVal("OSS_PORT"));
DOMAIN = configAPI.getConfigVal("OSS_DOMAIN");
SITE = configAPI.getConfigVal("OSS_SITE");
PATH = configAPI.getConfigVal("OSS_PATH");
extMap.put("image", "gif,jpg,jpeg,png,bmp");
extMap.put("flash", "swf,flv");
extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");
}
@RequestMapping(value = "/keditorupload", method = RequestMethod.POST)
@ResponseBody
public void keditorupload(HttpServletRequest request,
HttpServletResponse response) {
try {
//初始化参数
initConf();
// response.setContentType("text/html; charset=UTF-8");
response.setContentType("application/json; charset=UTF-8");
if (!ServletFileUpload.isMultipartContent(request)) {
response.getWriter().println(getError(false, "请选择文件。"));
response.getWriter().flush();
return;
}
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
List items = upload.parseRequest(request);
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
String fileName = item.getName();
if (!item.isFormField()) {
// 检查文件大小
if (item.getSize() > maxSize) {
response.getWriter().println(
getError(false, "上传文件大小超过限制。"));
response.getWriter().flush();
return;
}
// 检查扩展名
String fileExt = fileName.substring(
fileName.lastIndexOf(".") + 1).toLowerCase();
String filetype = null;
Iterator<String> its = extMap.keySet().iterator();
while (its.hasNext()) {
String key = its.next();
if (Arrays.<String> asList(extMap.get(key).split(","))
.contains(fileExt)) {
filetype = key;
break;
}
}
if (StringUtils.isEmpty(filetype)) {
response.getWriter().println(
getError(false, "上传文件扩展名是不允许的扩展名。"));
}
OssClient client = new OssClient(IP, PORT);
byte[] content = item.get();
ObjectMetadata metadata = new ObjectMetadata();
metadata.setDomain(DOMAIN);
metadata.setSchema(SITE);
metadata.setPath(PATH);
metadata.setType(fileExt);
metadata.setContent(content);
JSONObject obj = client.putObject(metadata);
JSONObject result = new JSONObject();
result.put("error", 0);
result.put("url", obj.get("url").toString());
response.getWriter().println(result);
response.getWriter().flush();
return;
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
private JSONObject getError(boolean success, String message) {
// System.out.println("success:" + success);
// System.out.println("message:" + message);
JSONObject obj = new JSONObject();
if (success) {
obj.put("error", 0);
} else {
obj.put("error", 1);
}
obj.put("message", message);
return obj;
}
@RequestMapping("/uploadfile")
@ResponseBody
public JsonMsg uploadify(HttpServletRequest request,
HttpServletResponse response) {
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
JsonMsg msg = new JsonMsg();
try {
//初始化参数
initConf();
DiskFileItemFactory diskFileItemFactory_ = new DiskFileItemFactory();
ServletFileUpload fUpload = new ServletFileUpload(diskFileItemFactory_);
if (!ServletFileUpload.isMultipartContent(request)) {
msg.setSuccess(false);
msg.setMsg("请选择文件。");
return msg;
}
Attach attach = new Attach();
attach.setId(df.format(new Date()));
List<FileItem> list_ = (List<FileItem>) fUpload
.parseRequest(request);
for (FileItem item : list_) {
String fileName = item.getName();
if (fileName != null) {
attach.setFilename(fileName);
// 检查文件大小
if (item.getSize() > maxSize) {
msg.setSuccess(false);
msg.setMsg("上传文件大小超过限制。");
return msg;
}
// 检查扩展名
String fileExt = fileName.substring(
fileName.lastIndexOf(".") + 1).toLowerCase();
String filetype = null;
Iterator<String> its = extMap.keySet().iterator();
while (its.hasNext()) {
String key = its.next();
if (Arrays.<String> asList(extMap.get(key).split(","))
.contains(fileExt)) {
filetype = key;
break;
}
}
if (StringUtils.isEmpty(filetype)) {
msg.setSuccess(false);
msg.setMsg("上传文件扩展名是不允许的扩展名。");
return msg;
}
OssClient client = new OssClient(IP, PORT);
byte[] content = item.get();
ObjectMetadata metadata = new ObjectMetadata();
metadata.setDomain(DOMAIN);
metadata.setSchema(SITE);
metadata.setPath(PATH);
metadata.setType(fileExt);
metadata.setContent(content);
JSONObject obj = client.putObject(metadata);
attach.setFilepath(obj.get("url").toString());
}
}
msg.setSuccess(true);
msg.setMsg("上传成功!");
msg.setData(attach);
} catch (FileUploadException e) {
e.printStackTrace();
msg.setSuccess(false);
msg.setMsg("上传失败!" + e.getLocalizedMessage());
} catch (IOException e) {
e.printStackTrace();
msg.setSuccess(false);
msg.setMsg("上传失败!" + e.getLocalizedMessage());
} catch (Exception e) {
e.printStackTrace();
msg.setSuccess(false);
msg.setMsg("上传失败!" + e.getLocalizedMessage());
}
return msg;
}
private JSONObject getError(String message) {
JSONObject obj = new JSONObject();
obj.put("error", 1);
obj.put("message", message);
return obj;
}
public static void main(String args[]) throws Exception {
testExp();
}
public void fileupload() throws Exception {
OssClient client = new OssClient(IP, PORT);
File file = new File("E:\\DSC_4623.JPG");
InputStream input = new FileInputStream(file);
byte[] content = new byte[input.available()];
input.read(content);
// byte[] content = item.get();
ObjectMetadata.ExtensionType exten = ObjectMetadata.ExtensionType.jpg;
ObjectMetadata metadata = new ObjectMetadata();
metadata.setDomain(DOMAIN);
metadata.setSchema(PATH);
metadata.setPath("images");
metadata.setType("jpg");
metadata.setContent(content);
JSONObject obj = client.putObject(metadata);
String filePath = obj.get("url").toString();
System.out.println("filepath:" + filePath);
}
public static void testExp() {
// 定义允许上传的文件扩展名
HashMap<String, String> extMap = new HashMap<String, String>();
extMap.put("image", "gif,jpg,jpeg,png,bmp");
extMap.put("flash", "swf,flv");
extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");
String fileExt = "gif";
}
}
|
package Week2;
import java.util.Arrays;
public class week04 {
public static void main(String[] args) {
int[] point = { 93, 32, 52, 9, 81, 2, 68 };
int total = 0;
int min = point[0];
int x = 0 , y = 0;
for (int i = 0; i < point.length - 1; i++) {
for (int j = i + 1; j < point.length; j++) {
total = point[i] - point[j];
if (total < 0) {
total *= -1;
}
if (min > total) {
min = total;
x = i;
y = j;
}
}
}
System.out.println("resutlt : [ " + x + " , " + y + " ]");
}
}
|
package norapol.saowarak.narubeth.rmutr.broadcastertest;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import java.io.File;
import norapol.saowarak.narubeth.rmutr.broadcastertest.utility.Utility;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final int REQUEST_CODE_RECORD_AUDIO = 101;
private static final int REQUEST_CODE_WRITE_STORAGE = 102;
//Explicit
private ImageView talkNameImageView, newTestMaleImageView, newTestFemaleImageView;
// private int[] myVideo = {R.raw.talkname1, R.raw.talkname2, R.raw.talkname3,
// R.raw.talkname4, R.raw.talkname5, R.raw.talkname6, R.raw.talkname7,
// R.raw.talkname8, R.raw.talkname9, R.raw.talkname10, R.raw.talkname11,
// R.raw.talkname12, R.raw.talkname13, R.raw.talkname14, R.raw.talkname15,};
// private int[] myVideo1 = {R.raw.testfemale1,R.raw.testfemale2};
//
// private int[] myVideo2 = {R.raw.testmale1,R.raw.testmale2};
private myDBClass myDB;
private ImageView historyImageView;
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
reQuestPermissionOnSafe();
//Bind Widget
bindWidget();
//Image Controller
imageController();
//Create private directory
createDirectory();
//create DB
myDB = new myDBClass(this);
myDB.getWritableDatabase(); // First method
myDB.clearTable();
insertListNameDynasty(); // insert list for show in takename
insertListNewTestMale(); // insert list for show in news male
insertListNewTestFemale(); // insert list for show in news female
} // Main Method
private void reQuestPermissionOnSafe() {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
int hasRecordAudioPermission = checkSelfPermission(Manifest.permission.RECORD_AUDIO);
if (hasRecordAudioPermission != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[] {Manifest.permission.RECORD_AUDIO},
REQUEST_CODE_RECORD_AUDIO);
return;
}
int hasWriteStoragePermission = checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (hasWriteStoragePermission != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_CODE_WRITE_STORAGE);
return;
}
}
}
private void createDirectory() {
File mydir = getApplicationContext().getDir(Utility.DIRECTORY_NAME, Context.MODE_PRIVATE); //Creating an internal dir;
if (!mydir.exists()) {
Log.e("ERROR", "Folder does not exists");
mydir.mkdir();
} else {
Log.e("ERROR", "Folder have exists in "+mydir.getPath());
}
}
private void insertListNameDynasty() {
myDB.insertNameDynasty("พระบาทสมเด็จพระเจ้าอยู่หัว", "talkname1.mp4");
myDB.insertNameDynasty("สมเด็จพระนางเจ้าฯพระบรมราชินีนาถ", "talkname2.mp4");
myDB.insertNameDynasty("สมเด็จพระบรมโอรสาธิราชฯสยามมกุฎราชกุมาร", "talkname3.mp4");
myDB.insertNameDynasty("สมเด็จพระเทพรัตนราชสุดาฯสยามบรมราชกุมารี", "talkname4.mp4");
myDB.insertNameDynasty("สมเด็จพระเจ้าลูกเธอ เจ้าฟ้าจุฬาภรณ์วลัยลักษณ์อัครราชกุมารี", "talkname5.mp4");
myDB.insertNameDynasty("สมเด็จพระเจ้าภคินีเธอ เจ้าฟ้าเพชรรัตนราชสุดา สิริโสภาพัณณวดี", "talkname6.mp4");
myDB.insertNameDynasty("สมเด็จพระเจ้าพี่นางเธอ เจ้าฟ้ากัลยาณิวัฒนา กรมหลวงนราธิวาสราชนครินทร์", "talkname7.mp4");
myDB.insertNameDynasty("สมเด็จพระศรีนคริทราบรมราชชนี", "talkname8.mp4");
myDB.insertNameDynasty("พระเจ้าวรวงศ์เธอ พระองค์เจ้าโสมสวลี พระวรราชาทินัดดามาตุ", "talkname9.mp4");
myDB.insertNameDynasty("พระเจ้าหลานเธอ พระองค์เจ้าสิริภาจุฑาภรณ์", "talkname10.mp4");
myDB.insertNameDynasty("พระเจ้าหลานเธอ พระองค์เจ้าอทิตยาทร กิติคุณ", "talkname11.mp4");
myDB.insertNameDynasty("พระเจ้าหลานเธอ พระองค์เจ้าพัชรกิติยาภา", "talkname12.mp4");
myDB.insertNameDynasty("พระเจ้าหลานเธอ พระองค์เจ้าสิริวัณณวรีนารีรัตน์", "talkname13.mp4");
myDB.insertNameDynasty("พระเจ้าหลานเธอ พระองค์เจ้าทีปังกรรัศมีโชติ", "talkname14.mp4");
myDB.insertNameDynasty("ทูลกระหม่อมหญิงอุบลรัตนราชกัญญา สิริวัฒนาพรรณวดี", "talkname15.mp4");
}
private void insertListNewTestMale() {
myDB.insertNewTestMale("แบบทดสอบสำหรับผู้ชายชุดที่ 1", "testmale1.mp4");
myDB.insertNewTestMale("แบบทดสอบสำหรับผู้ชายชุดที่ 2", "testmale2.mp4");
myDB.insertNewTestMale("แบบทดสอบสำหรับผู้ชายชุดที่ 3", "testmale3.mp4");
myDB.insertNewTestMale("แบบทดสอบสำหรับผู้ชายชุดที่ 4", "testmale4.mp4");
myDB.insertNewTestMale("แบบทดสอบสำหรับผู้ชายชุดที่ 5", "testmale5.mp4");
}
private void insertListNewTestFemale() {
myDB.insertNewTestFemale("แบบทดสอบสำหรับผู้หญิงชุดที่ 1", "testfemale1.mp4");
myDB.insertNewTestFemale("แบบทดสอบสำหรับผู้หญิงชุดที่ 2", "testfemale2.mp4");
myDB.insertNewTestFemale("แบบทดสอบสำหรับผู้หญิงชุดที่ 3", "testfemale3.mp4");
myDB.insertNewTestFemale("แบบทดสอบสำหรับผู้หญิงชุดที่ 4", "testfemale4.mp4");
myDB.insertNewTestFemale("แบบทดสอบสำหรับผู้หญิงชุดที่ 5", "testfemale5.mp4");
}
private void imageController() {
talkNameImageView.setOnClickListener(this);
newTestMaleImageView.setOnClickListener(this);
newTestFemaleImageView.setOnClickListener(this);
historyImageView.setOnClickListener(this);
}
private void bindWidget() {
talkNameImageView = (ImageView) findViewById(R.id.imageView2);
newTestMaleImageView = (ImageView) findViewById(R.id.imageView3);
newTestFemaleImageView = (ImageView) findViewById(R.id.imageView4);
historyImageView = (ImageView) findViewById(R.id.img_history);
}
@Override
public void onClick(View view) {
String sourceVideo = "";
Class<?> toClass = null;
int intIcon = R.drawable.nameread;
switch (view.getId()) {
case R.id.imageView2:
intIcon = R.drawable.nameread;
sourceVideo = "talkname"; //ส่งเงื่อนไขในการอ่านไฟล์จาก SQLite
toClass = DetailListView.class;
break;
case R.id.imageView3:
intIcon = R.drawable.testboy;
sourceVideo = "newtest_male"; //ส่งเงื่อนไขในการอ่านไฟล์จาก SQLite
toClass = DetailListView.class;
break;
case R.id.imageView4:
intIcon = R.drawable.gtest;
sourceVideo = "newtest_female"; //ส่งเงื่อนไขในการอ่านไฟล์จาก SQLite
toClass = DetailListView.class;
break;
case R.id.img_history:
//Intent to History
toClass = HistoryListView.class;
break;
default:
intIcon = R.drawable.nameread;
sourceVideo = "talkname"; //ส่งเงื่อนไขในการอ่านไฟล์จาก SQLite
break;
} // switch
//Intent to ListView
Intent objIntent = new Intent(MainActivity.this, toClass);
objIntent.putExtra("Icon", intIcon);
objIntent.putExtra("sourceVideo", sourceVideo);
startActivity(objIntent);
} // onClick
} // Main Class |
package org.hpin.fg.system.util;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
public class HttpUtil {
public static String http(String url, LinkedHashMap<String, String> params,String sig) {
StringBuffer sb = new StringBuffer();// 构建请求参数
if (params != null) {
for (Entry<String, String> e : params.entrySet()) {
sb.append(e.getKey());
sb.append("=");
try {
sb.append(URLEncoder.encode(e.getValue(),"UTF-8"));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
sb.append("&");
}
try {
sb.append("sig").append("=").append(URLEncoder.encode(sig,"UTF-8"));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
sb.substring(0, sb.length() - 1);
}
System.out.println("send_url:" + url);
System.out.println("send_data:" + sb.toString());
// 尝试发送请求
URL _url = null;
HttpURLConnection con = null;
try {
_url = new URL(url);
con = (HttpURLConnection) _url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setDoInput(true);
con.setUseCaches(false);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
osw.write(sb.toString());
osw.flush();
osw.close();
} catch (Exception e) {
e.printStackTrace();
}
// 读取返回内容
StringBuffer buffer = new StringBuffer();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
String temp;
while ((temp = br.readLine()) != null) {
buffer.append(temp);
buffer.append("\n");
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if (con != null)
con.disconnect();
}
return buffer.toString();
}
public static void main(String[]args){
//System.out.println(HttpUtil.http("http://www.baidu.com", null));
}
}
|
package com.karya.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="issueditem001mb")
public class IssuedItem001MB {
private static final long serialVersionUID = -723583058586873479L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "issueId")
private int issueId;
@Column(name="porderCode")
private String porderCode;
@Column(name="issueDate")
private String issueDate;
@Column(name="itemCode")
private String itemCode;
@Column(name="description")
private String description;
@Column(name="quantity")
private String quantity;
@Column(name="uom")
private String uom;
@Column(name="amount")
private String amount;
@Column(name="serialNo")
private String serialNo;
@Column(name="sourceWH")
private String sourceWH;
@Column(name="targetWH")
private String targetWH;
@Column(name="stockEntry")
private String stockEntry;
@Column(name="company")
private String company;
public int getIssueId() {
return issueId;
}
public void setIssueId(int issueId) {
this.issueId = issueId;
}
public String getPorderCode() {
return porderCode;
}
public void setPorderCode(String porderCode) {
this.porderCode = porderCode;
}
public String getIssueDate() {
return issueDate;
}
public void setIssueDate(String issueDate) {
this.issueDate = issueDate;
}
public String getItemCode() {
return itemCode;
}
public void setItemCode(String itemCode) {
this.itemCode = itemCode;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public String getUom() {
return uom;
}
public void setUom(String uom) {
this.uom = uom;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getSerialNo() {
return serialNo;
}
public void setSerialNo(String serialNo) {
this.serialNo = serialNo;
}
public String getSourceWH() {
return sourceWH;
}
public void setSourceWH(String sourceWH) {
this.sourceWH = sourceWH;
}
public String getTargetWH() {
return targetWH;
}
public void setTargetWH(String targetWH) {
this.targetWH = targetWH;
}
public String getStockEntry() {
return stockEntry;
}
public void setStockEntry(String stockEntry) {
this.stockEntry = stockEntry;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
|
package com.auro.scholr.home.data.model.passportmodels;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class PassportMonthModel{
boolean isExpanded;
@SerializedName("month_name")
@Expose
private String monthName;
@SerializedName("data_list")
@Expose
private List<PassportSubjectModel> passportSubjectModelList = null;
@SerializedName("month")
@Expose
private String month;
@SerializedName("mobile_no")
@Expose
private String mobileNo;
@SerializedName("subjects")
@Expose
private List<String> subjects = null;
public List<PassportSubjectModel> getPassportSubjectModelList() {
return passportSubjectModelList;
}
public void setPassportSubjectModelList(List<PassportSubjectModel> passportSubjectModelList) {
this.passportSubjectModelList = passportSubjectModelList;
}
public String getMonth() {
return month;
}
public void setMonth(String month) {
this.month = month;
}
public String getMobileNo() {
return mobileNo;
}
public void setMobileNo(String mobileNo) {
this.mobileNo = mobileNo;
}
public List<String> getSubjects() {
return subjects;
}
public void setSubjects(List<String> subjects) {
this.subjects = subjects;
}
public boolean isExpanded() {
return isExpanded;
}
public void setExpanded(boolean expanded) {
isExpanded = expanded;
}
public String getMonthName() {
return monthName;
}
public void setMonthName(String monthName) {
this.monthName = monthName;
}
}
|
package edu.udc.psw.desenhos.DB.DAO;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import edu.udc.psw.desenhos.DB.DBConnection;
import edu.udc.psw.desenhos.DB.data.Desenhos;
import edu.udc.psw.desenhos.DB.data.TipoForma;
public class TipoFormaDao {
private Statement statement;
private ResultSet resultSet;
private int numberOfRows;
private String query = "SELECT tipoforma.nome, tipoforma.qtd_pontos, tipoforma_qtd_escalares, tipoforma.id_tipo FROM TipoForma";
private String update = "UPDATE (nome, qtd_pontos, qtd_escalares) from TipoForma with ";
private String insert = "INSERT into TipoForma nome, qtd_pontos, qtd_escalares values ";
public TipoFormaDao() {
try {
// cria Statement para consultar banco de dados
statement = DBConnection.getConnection().createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
// configura consulta e a executa
setQuery();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
public void moveToRow(int row) {
try {
resultSet.absolute(row);
} catch (SQLException ex) {
ex.printStackTrace();
}
}
public int getTipoForma() {
int tipoforma;
tipoforma = new TipoForma(
((TipoForma) resultSet).getNome(),
(TipoForma) resultSet).getQtd_escalares();
return tipoforma;
}
public int getNumberOfRows() {
return numberOfRows;
}
public void save(TipoForma tipoforma) throws SQLException, IllegalStateException {
String newData = update + "('" + tipoforma.getId_tipo() + "', '" + tipoforma.getQtd_escalares() + "', '"
+ tipoforma.getQtd_pontos() + "')" + " WHERE id_tipo = " + "', '" + tipoforma.getId_tipo() + "');";
statement.executeUpdate(newData);
}
public void insert(TipoForma tipoforma) throws SQLException, IllegalStateException {
String newData = update + "('" + tipoforma.getId_tipo() + "', '" + tipoforma.getQtd_escalares() + "', '"
+ tipoforma.getQtd_pontos() + "');";
int affectedRows = statement.executeUpdate(newData, Statement.RETURN_GENERATED_KEYS);
if (affectedRows == 0) {
throw new SQLException("Creating Desenhos failed, no rows affected.");
}
try (ResultSet generatedKeys = statement.getGeneratedKeys()) {
if (generatedKeys.next()) {
tipoforma.setId_tipo(generatedKeys.getLong(1));
}
else {
throw new SQLException("Creating user failed, no ID obtained.");
}
}
setQuery();
}
// configura nova string de consulta de banco de dados
public void setQuery() throws SQLException, IllegalStateException {
// especifica consulta e a executa
resultSet = statement.executeQuery(query);
// determina o número de linhas em ResultSet
resultSet.last(); // move para a última linha
numberOfRows = resultSet.getRow(); // obtém número de linha
resultSet.first();
}
// fecha Statement e Connection
public void disconnectFromDatabase() {
try {
statement.close();
DBConnection.getConnection().close();
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
}
} |
package com.esum.framework.jdbc;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Map;
import org.junit.Test;
import com.esum.framework.common.util.SysUtil;
import com.esum.framework.core.config.Configurator;
import com.esum.framework.jdbc.datasource.DataSourceManager;
import com.esum.framework.jdbc.datasource.JdbcDataSource;
import junit.framework.TestCase;
public class SqlTemplateTest extends TestCase {
public void setUp() throws Exception {
System.setProperty("xtrus.home", "d:/test/xtrus-4.4.1");
Configurator.init(Configurator.DEFAULT_DB_PROPERTIES_ID, SysUtil.replacePropertyToValue("${xtrus.home}/conf/db.properties"));
}
public void testSqlTemplate() throws Exception {
JdbcDataSource jds = DataSourceManager.getInstance().createDefaultDataSource();
assertNotNull(jds);
SqlTemplate sqlTemplate = new SqlTemplate(jds.getDataSource());
assertNotNull(sqlTemplate);
Map<String, Object> resultMap = sqlTemplate.select("SELECT * FROM NODE_INFO", new MapResultSetExtractor());
assertNotNull(resultMap);
System.out.println(resultMap.toString());
}
public void testPreparedStatement() throws Exception {
JdbcDataSource jds = DataSourceManager.getInstance().createDefaultDataSource();
assertNotNull(jds);
SqlTemplate sqlTemplate = new SqlTemplate(jds.getDataSource());
assertNotNull(sqlTemplate);
Map<String, Object> nodeMap = sqlTemplate.execute("SELECT * FROM NODE_INFO WHERE NODE_ID = ?",
new PreparedStatementCallback<Map<String, Object>>() {
@Override
public Map<String, Object> doInPreparedStatement(PreparedStatement ps)
throws SQLException {
ps.setString(1, "MAIN");
ResultSet rs = null;
try {
rs = ps.executeQuery();
return new MapResultSetExtractor().extractData(rs);
} finally {
if(rs!=null)
rs.close();
}
}
});
System.out.println(nodeMap.toString());
}
public void testSelect() throws Exception {
JdbcDataSource jds = DataSourceManager.getInstance().createDefaultDataSource();
assertNotNull(jds);
SqlTemplate sqlTemplate = new SqlTemplate(jds.getDataSource());
assertNotNull(sqlTemplate);
Map<String, Object> resultMap = sqlTemplate.selectOne("SELECT 1 AS CNT FROM DUAL", new MapRowMapper());
assertNotNull(resultMap);
assertEquals("1", resultMap.get("CNT").toString());
resultMap = sqlTemplate.select("SELECT 1 AS CNT FROM DUAL", new MapResultSetExtractor());
assertEquals("1", resultMap.get("CNT").toString());
SqlParameterValues params = new SqlParameterValues();
params.add(new SqlParameterValue(Types.VARCHAR, "MAIN"));
resultMap = sqlTemplate.selectOne("SELECT * FROM NODE_INFO WHERE NODE_ID = ?", params);
assertEquals("MAIN", resultMap.get("NODE_ID").toString());
}
@Test
public void testCallable() throws Exception {
JdbcDataSource jds = DataSourceManager.getInstance().createDefaultDataSource();
assertNotNull(jds);
SqlTemplate sqlTemplate = new SqlTemplate(jds.getDataSource());
assertNotNull(sqlTemplate);
Connection connection = jds.getConnection();
String result = sqlTemplate.execute(connection,
"{call TEST_PROCEDURE2(?, ?)}", new CallableStatementCallback<String>() {
@Override
public String doInCallableStatement(CallableStatement cs) throws SQLException {
cs.setString(1, "TEST");
cs.registerOutParameter(2, Types.VARCHAR); //out param
int completed = cs.executeUpdate();
if(completed>0)
return cs.getString(2);
return null;
}
});
System.out.println("result : "+result);
connection.close();
}
}
|
package cn.itcast.core.service;
import cn.itcast.core.pojo.entity.BuyerCart;
import java.util.List;
public interface BuyerCartService {
/**
* 将购买的商品加入到用户当前所拥有的购物车列表中
* @param cartList 用户现在拥有的购物车列表
* @param itemId 用户购买的商品库存id
* @param num 购买数量
* @return
*/
public List<BuyerCart> addItemToCartList(List<BuyerCart> cartList, Long itemId, Integer num);
/**
* 将购物车列表根据用户名存入redis
* @param cartList 存入的购物车列表
* @param userName 用户名
*/
public void setCartListToRedis(List<BuyerCart> cartList, String userName);
/**
* 根据用户名到redis中获取购物车列表
* @param userName 用户名
* @return
*/
public List<BuyerCart> getCartListFromRedis(String userName);
/**
* 将cookie中的购物车列表合并到redis的购物车列表中并返回合并后的购物车列表
* @param cookieCartList cookie的购物车列表
* @param redisCartList redis的购物车列表
* @return 合并后的购物车列表
*/
public List<BuyerCart> mergeCookieCartToRedisCart(List<BuyerCart> cookieCartList, List<BuyerCart> redisCartList);
public void setRedisCart(String userName);
}
|
import entity.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.Date;
import java.sql.SQLException;
public class Main {
public static void main(String[] args) throws Exception {
Entity.initializeSQL();
executeDrop();
executeCreate();
executeInsert();
}
private static void testSQL() throws SQLException {
Entity.initializeSQL();
executeDrop();
executeCreate();
// executeDelete();
executeInsert();
new User("admin1", "p", true).insert();
new User("admin2", "p", true).insert();
new User("admin4", "p", true).insert();
new User("admin5", "p", true).insert();
new User("user1", "p", false).insert();
new Student("user1", "e", "Freshman", "Computer Science").insert();
new User("user2", "p2", false).insert();
new Student("user2", "e2", "Freshman", "Computer Science").insert();
System.out.println("all users:");
User.selectAllUsers().forEach(u -> System.out.println(u.username + " " + u.isAdmin));
System.out.println();
new Project("pn", "an", "ae", 2, "d", "Community", null, null, null).insert();
new Project("pn1", "an", "ae", 2, "d", "Community", null, null, null).insert();
new Project("pn2", "an", "ae", 2, "d", "Community", null, null, null).insert();
new Project("pn3", "an", "ae", 2, "d", "Community", null, null, null).insert();
new Project("pn4", "an", "ae", 2, "d", "Community", null, null, null).insert();
new Project("pn5", "an", "ae", 2, "d", "Community", null, null, null).insert();
new Project("pn6", "an", "ae", 2, "d", "Community", null, null, null).insert();
new Project("pn7", "an", "ae", 2, "d", "Community", null, null, null).insert();
new Project("pn8", "an", "ae", 2, "d", "Community", null, null, null).insert();
new Project("pn9", "an", "ae", 2, "d", "Community", null, null, null).insert();
new Project("pn0", "an", "ae", 2, "d", "Community", null, null, null).insert();
new Project("pn00", "an", "ae", 2, "d", "Community", null, null, null).insert();
new Project("pn01", "an", "ae", 2, "d", "Community", null, null, null).insert();
System.out.println("all projects:");
Project.selectAllProjects().forEach(p -> System.out.println(p.projectName));
System.out.println();
new StudentProjectApplication("user1", "pn", "Pending", new Date(10909009)).insert();
new StudentProjectApplication("user1", "pn1", "Pending", new Date(10909009)).insert();
new StudentProjectApplication("user1", "pn2", "Pending", new Date(10909009)).insert();
new StudentProjectApplication("user1", "pn3", "Pending", new Date(10909009)).insert();
new StudentProjectApplication("user1", "pn4", "Pending", new Date(10909009)).insert();
new StudentProjectApplication("user1", "pn5", "Pending", new Date(10909009)).insert();
new StudentProjectApplication("user1", "pn6", "Pending", new Date(10909009)).insert();
new StudentProjectApplication("user1", "pn7", "Pending", new Date(10909009)).insert();
new StudentProjectApplication("user1", "pn8", "Pending", new Date(10909009)).insert();
new StudentProjectApplication("user1", "pn9", "Pending", new Date(10909009)).insert();
new StudentProjectApplication("user1", "pn0", "Pending", new Date(10909009)).insert();
new StudentProjectApplication("user1", "pn00", "Pending", new Date(10909009)).insert();
new StudentProjectApplication("user1", "pn01", "Pending", new Date(10909009)).insert();
new StudentProjectApplication("user2", "pn01", "Pending", new Date(10909009)).insert();
new StudentProjectApplication("user2", "pn01", "Pending", new Date(10909009)).insert();
new StudentProjectApplication("user2", "pn02", "Pending", new Date(10909009)).insert();
StudentProjectApplication spa = new StudentProjectApplication("user2", "pn", "Pending", new Date(10909009));
spa.insert();
StudentProjectApplication.selectAllStudentProjectApplications().forEach(
s -> {
System.out.println(s.student);
System.out.println(s.project);
System.out.println(s.applyStatus);
}
);
System.out.println("-->");
spa.updateStatus("Accepted");
StudentProjectApplication.selectAllStudentProjectApplications().forEach(
s -> {
System.out.println(s.student);
System.out.println(s.project);
System.out.println(s.applyStatus);
}
);
System.out.println();
System.out.println("AdminViewApplication:");
AdminViewApplication.selectAllAdminViewApplications().forEach(a -> System.out.printf("%s - %s - %s - %s\n", a.projectName, a.studentMajor, a.studentYear, a.applyStatus));
System.out.println();
System.out.println("Popular Projects:");
PopularProject.selectPopularProjects().forEach(p -> System.out.println(p.project + " " + p.numApplicants));
Entity.endSQL();
}
private static void executeDrop() throws SQLException {
Entity.execute(readFile("drop.sql"));
}
private static void executeCreate() throws SQLException {
Entity.execute(readFile("create.sql"));
}
private static void executeDelete() throws SQLException {
Entity.execute(readFile("delete.sql"));
}
private static void executeInsert() throws SQLException {
Entity.execute(readFile("insert.sql"));
}
private static String readFile(String filename) {
try {
return new String(Files.readAllBytes(Paths.get(filename)));
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
return null;
}
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates and open the template
* in the editor.
*/
package com.codigo.smartstore.xbase.codepage;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CoderResult;
/**
* Klasa realizuje mechanizm kodowania i dekodowania znaków zgodnie ze
* specyfikacją algorytmu ROT47
*
* @author andrzej.radziszewski
* @version 1.0.0.0
* @category charset
*/
public class Rot47Charset
extends
Charset {
/**
* Nazwa podstawowego algorytmu kodowania znaków
*/
private static final String BASE_CHARSET_NAME = "UTF-8";
/**
* Podstawowy konstruktor obiektu klasy<code>Rot47Charset</code>
*
* @param canonical
* @param aliases
*/
public Rot47Charset(final String canonical, final String[] aliases) {
super(canonical, aliases);
this.baseCharset = Charset.forName(Rot47Charset.BASE_CHARSET_NAME);
}
@Override
public boolean contains(final Charset cs) {
return cs.equals(this);
}
@Override
public CharsetDecoder newDecoder() {
return new Rot47CharsetDecoder(
this, this.baseCharset.newDecoder());
}
@Override
public CharsetEncoder newEncoder() {
return new Rot47CharsetEncoder(
this, this.baseCharset.newEncoder());
}
private final Charset baseCharset;
private void rot47(final CharBuffer cb) {
for (int pos = cb.position(); pos < cb.limit(); pos++) {
char c = cb.get(pos);
if (((byte) c >= 33) && ((byte) c <= 126)) {
c = (char) (33 + ((c + 14) % 94));
cb.put(pos, c);
}
}
}
private class Rot47CharsetDecoder
extends
CharsetDecoder {
private final CharsetDecoder baseDecoder;
public Rot47CharsetDecoder(final Charset cs, final CharsetDecoder baseDecoder) {
super(cs, baseDecoder.averageCharsPerByte(), baseDecoder.maxCharsPerByte());
this.baseDecoder = baseDecoder;
}
@Override
protected CoderResult decodeLoop(final ByteBuffer in, final CharBuffer out) {
this.baseDecoder.reset();
final CoderResult result = this.baseDecoder.decode(in, out, true);
Rot47Charset.this.rot47(out);
return result;
}
}
private class Rot47CharsetEncoder
extends
CharsetEncoder {
private final CharsetEncoder baseEncoder;
public Rot47CharsetEncoder(final Charset cs, final CharsetEncoder baseEncoder) {
super(cs, baseEncoder.averageBytesPerChar(), baseEncoder.maxBytesPerChar());
this.baseEncoder = baseEncoder;
}
@Override
protected CoderResult encodeLoop(final CharBuffer in, final ByteBuffer out) {
final CharBuffer buffer = CharBuffer.allocate(in.remaining());
while (in.hasRemaining())
buffer.put(in.get());
buffer.rewind();
Rot47Charset.this.rot47(buffer);
this.baseEncoder.reset();
final CoderResult result = this.baseEncoder.encode(buffer, out, true);
in.position(in.position() - buffer.remaining());
return result;
}
}
}
|
package Tutorial.P3_ActorTool.S4_FSM_State.HelloWorld;
import akka.actor.*;
import static Tutorial.P3_ActorTool.S4_FSM_State.HelloWorld.Message.*;
/**
* Created by lamdevops on 6/17/17.
*/
public class AppHelloWorldFSM {
public static void main(String[] args) throws InterruptedException {
ActorSystem system = ActorSystem.create("hello-world-fsm");
ActorRef helloWorld = system.actorOf(Props.create(HelloWorldFSM.class), "hello-world");
ActorRef probe = system.actorOf(Props.create(Probe.class));
helloWorld.tell(new Hello(probe), ActorRef.noSender());
helloWorld.tell(new Connect(probe), ActorRef.noSender());
helloWorld.tell(new Disconnect(probe), ActorRef.noSender());
Thread.sleep(100);
system.terminate();
}
}
|
package main.model;
import org.springframework.lang.NonNull;
import javax.persistence.*;
import java.util.Date;
@Entity
@Table(name = "consultations")
public class Consultation {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
@Column
@NonNull
@Temporal(TemporalType.TIMESTAMP)
private Date date;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "patient_id", nullable = false)
private Patient patient;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", nullable = false)
private User user;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Patient getPatient() {
return patient;
}
public void setPatient(Patient patient) {
this.patient = patient;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
|
/*
* Copyright 2002-2019 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.context.annotation;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.parsing.BeanDefinitionParsingException;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition;
/**
* Unit tests covering cases where a user defines an invalid Configuration
* class, e.g.: forgets to annotate with {@link Configuration} or declares
* a Configuration class as final.
*
* @author Chris Beams
*/
public class InvalidConfigurationClassDefinitionTests {
@Test
public void configurationClassesMayNotBeFinal() {
@Configuration
final class Config { }
BeanDefinition configBeanDef = rootBeanDefinition(Config.class).getBeanDefinition();
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
beanFactory.registerBeanDefinition("config", configBeanDef);
ConfigurationClassPostProcessor pp = new ConfigurationClassPostProcessor();
assertThatExceptionOfType(BeanDefinitionParsingException.class).isThrownBy(() ->
pp.postProcessBeanFactory(beanFactory))
.withMessageContaining("Remove the final modifier");
}
}
|
package net.mcviral.dev.plugins.pvpcontrol.main;
import net.mcviral.dev.plugins.pvpcontrol.gangs.Gang;
import net.mcviral.dev.plugins.pvpcontrol.points.PointsPlayer;
import net.mcviral.dev.plugins.pvpcontrol.pvp.Result;
import net.md_5.bungee.api.ChatColor;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.entity.PotionSplashEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
public class Listeners implements Listener{
private PVPControl plugin = null;
public Listeners(PVPControl plugin){
this.plugin = plugin;
}
//if (plugin.debug){
//plugin.log.info("");
//}
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerJoin(PlayerJoinEvent event){
plugin.getPVPController().getMembers().add(new Member(event.getPlayer().getUniqueId()));
if (plugin.getPointsController().isOnFile(event.getPlayer().getUniqueId())){
plugin.getPointsController().loadPlayer(event.getPlayer().getUniqueId());
}else{
plugin.getPointsController().createPlayer(event.getPlayer().getUniqueId());
}
}
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerQuit(PlayerQuitEvent event){
for (Member m : plugin.getPVPController().getMembers()){
if (m.getUUID().equals(event.getPlayer().getUniqueId())){
plugin.getPVPController().getMembers().remove(m);
}
}
}
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerDeath(PlayerDeathEvent event){
if (!plugin.isBlacklistedWorld(event.getEntity().getWorld().getName())){
if (event.getEntity().getKiller() instanceof Player){
Player p = (Player) event.getEntity().getKiller();
PointsPlayer pp = plugin.getPointsController().getPlayer(p.getUniqueId());
pp.setPoints(pp.getPoints() + 1);
p.sendMessage(ChatColor.GRAY + "You killed " + event.getEntity().getName());
}
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onEntityDamageByEntityEvent(EntityDamageByEntityEvent event){
if (!plugin.isBlacklistedWorld(event.getEntity().getWorld().getName())){
Result r = null;
if (plugin.debug){
plugin.log.info("EntityDamageByEntityEvent called.");
}
boolean allow = true;
Player vic = null;
Player atk = null;
if (event.getEntity() instanceof Player){
vic = (Player) event.getEntity();
cancelTaskDueToHit(vic);
if (event.getDamager() instanceof Player){
atk = (Player) event.getDamager();
cancelTaskDueToHit(atk);
if (atk != vic){
r = allowPVP(vic, atk);
allow = r.isAllowed();
if (plugin.debug){
plugin.log.info("Allow PVP: " + allow);
}
}
}else if (event.getDamager() instanceof Projectile){
Projectile p = (Projectile) event.getDamager();
if (p.getShooter() instanceof Player){
atk = (Player) p.getShooter();
cancelTaskDueToHit(atk);
r = allowPVP(vic, atk);
allow = r.isAllowed();
if (plugin.debug){
plugin.log.info("Allow projectile PVP: " + allow);
}
}
}
}
if (!allow){
event.setCancelled(true);
if (r != null){
if (r.getCause() != null){
if (r.getCause() == "ATK"){
atk.sendMessage(ChatColor.RED + "You have PVP off, turn it on to engage other players in combat.");
}else if (r.getCause() == "VIC"){
atk.sendMessage(ChatColor.RED + "This player has PVP off, you aren't allowed to damage them.");
}else if (r.getCause() == "GANG"){
atk.sendMessage(ChatColor.RED + "This player is in your gang and friendly fire is disabled.");
}else{
//Wut, why's it not normal?
}
}else{
//No cause, wut?
}
}else{
//Wut
}
//atk.sendMessage(ChatColor.RED + "This player has PVP off, you aren't allowed to damage them.");
}
}
}
//CHECK BOTH FOR GANG AND MEMBER PVP OFF
//@SuppressWarnings("unused")
@EventHandler(priority = EventPriority.HIGH)
public void onPotionSplash(PotionSplashEvent event){
if (!plugin.isBlacklistedWorld(event.getEntity().getWorld().getName())){
Result r = null;
boolean allow = true;
Player atk = null;
if (event.getEntity().getShooter() instanceof Player){
atk = (Player) event.getEntity().getShooter();
cancelTaskDueToHit(atk);
Player vic = null;
for (LivingEntity e : event.getAffectedEntities()){
if (e instanceof Player){
vic = (Player) e;
cancelTaskDueToHit(vic);
r = allowPVP(vic, atk);
allow = r.isAllowed();
}
}
}
if (!allow){
event.setCancelled(true);
atk.sendMessage(ChatColor.RED + "One or more of the players you hit has PVP off or is in your gang, you aren't allowed to damage them.");
}
}
}
public void cancelTaskDueToHit(Player p){
Member m = plugin.getPVPController().getMember(p.getUniqueId());
if (m == null){
m = new Member(p.getUniqueId());
return;
}
if (m.hasATaskRunning()){
p.sendMessage(ChatColor.YELLOW + "Your PVP change has been canceled as you were hit.");
m.cancelTask();
}
}
public Result allowPVP(Player vic, Player atk){
boolean allow = true;
String cause = null;
//Check global pvp then gang pvp
if (plugin.debug){
plugin.log.info("Atk: " + atk.getName() + " Vic: " + vic.getName());
}
if (plugin.getPVPController().isAMember(atk.getUniqueId())){
if (plugin.debug){
plugin.log.info("Attacker is registered as a member.");
}
Member matk = plugin.getPVPController().getMember(atk.getUniqueId());
if (matk.getGlobalPVP()){
if (plugin.debug){
plugin.log.info("Attacker's pvp is off");
}
if (plugin.getPVPController().isAMember(vic.getUniqueId())){
Member mvic = plugin.getPVPController().getMember(vic.getUniqueId());
if (mvic.getGlobalPVP()){
if (plugin.debug){
plugin.log.info("Both players pvp is on");
}
allow = true;//erm, no
}else{
//PVP off
if (cause == null){
cause = "VIC";
}
allow = false;
}
}else{
allow = true;//erm, no
}
}else{
//PVP off
if (cause == null){
cause = "ATK";
}
allow = false;
}
}else{
if (plugin.debug){
plugin.log.info("Woah, why is " + atk.getName() + " not registered as a member?");
}
}
//Check gang
Gang gatk = plugin.getGangController().getGang(atk.getUniqueId());
Gang gvic = plugin.getGangController().getGang(vic.getUniqueId());
if ((gatk != null) && (gvic != null)){
//They are both in gangs
if (gatk == gvic){
if (gatk.allowsFriendlyfire()){
//Allowed
}else{
//PVP off
if (cause == null){
cause = "GANG";
}
allow = false;
}
}else{
//allowed
}
}else{
//who cares
}
return new Result(allow, cause);
}
}
|
package com.gaoshin.cloud.web.job.entity;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;
import com.gaoshin.cloud.web.job.bean.JobConfKey;
public class Parameter {
public static Map<String, String> replace(Map<String, String> params) {
Map<String, String> basic = new HashMap<String, String>();
setTimestamp(params);
while(true) {
int size1 = params.size();
int size2 = basic.size();
String[] keys = params.keySet().toArray(new String[0]);
for(String key : keys) {
String value = params.get(key);
if(value.indexOf("${")==-1) {
basic.put(key, value);
params.remove(key);
continue;
}
}
keys = params.keySet().toArray(new String[0]);
for(String key : keys) {
String value = params.get(key);
for(String search : basic.keySet()) {
String replaceValue = basic.get(search);
value = value.replaceAll("\\$\\{" + search + "\\}", replaceValue);
if(value.indexOf("${")==-1) {
break;
}
}
if(value.indexOf("${")==-1) {
basic.put(key, value);
params.remove(key);
}
else {
params.put(key, value);
}
}
if(size1 == params.size() && size2 == basic.size()) {
break;
}
}
return basic;
}
private static void setTimestamp(Map<String, String> params) {
String timestamp = params.get(JobConfKey.Timestamp.name());
if(timestamp == null) {
return;
}
long ts = Long.parseLong(timestamp);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSS");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = new Date(ts);
String datestr = sdf.format(date);
String[] times = datestr.split("-");
params.put("year", times[0]);
params.put("month", times[1]);
params.put("day", times[2]);
params.put("hour", times[3]);
params.put("minute", times[4]);
params.put("second", times[5]);
}
}
|
package com.fixit.core.data;
public class WorkingHours {
private double open;
private double close;
public WorkingHours(double open, double close) {
this.open = open;
this.close = close;
}
public double getOpen() {
return open;
}
public void setOpen(double open) {
this.open = open;
}
public double getClose() {
return close;
}
public void setClose(double close) {
this.close = close;
}
@Override
public String toString() {
return "OpeningHours [open=" + open + ", close=" + close + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(close);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(open);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
WorkingHours other = (WorkingHours) obj;
if (Double.doubleToLongBits(close) != Double.doubleToLongBits(other.close))
return false;
if (Double.doubleToLongBits(open) != Double.doubleToLongBits(other.open))
return false;
return true;
}
}
|
package com.bedroom.utils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.bedroom.service.BedroomService;
@Component
public class BedroomUtils {
@Autowired
private BedroomService bedroomService;
/**
* 得到bedroomid到bedroomName的转换
* @param bedroomNameMap
* @return
*/
public Map<String,String> mapBedroomIdToBedroomName() {
List<Map<String,Object>> bedroomNameMap = bedroomService.getBedroomName();
Map<String,String> nameMap = new HashMap<>();
for(int i=0;i<bedroomNameMap.size();i++) {
if(bedroomNameMap.get(i) == null) {
continue;
}
Map<String,Object> tempMap = bedroomNameMap.get(i);
String newKey="",newValue="";
for(Map.Entry<String,Object> entry : tempMap.entrySet()) {
if("bedroom_id".equals(entry.getKey())) {
newKey = String.valueOf(entry.getValue());
}else if("bedroom_name".equals(entry.getKey())) {
newValue= String.valueOf(entry.getValue());
}
}
nameMap.put(newKey, newValue);
}
return nameMap;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.