text
stringlengths
10
2.72M
package com.example.administrator.demo_wallpaper_android.async_system; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.widget.Toast; import com.example.administrator.demo_wallpaper_android.interfacesystem.General_Interface; /** * Created by Administrator on 11/13/2017. */ public abstract class BaseActyvity extends AppCompatActivity implements General_Interface { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(getLayoutID()); initView(); } protected abstract int getLayoutID(); protected abstract void initView(); @Override public void erorr() { Toast.makeText(this,"Lỗi, xin kiểm tra lại đường truyền",Toast.LENGTH_SHORT).show(); } protected void connect(String api){ General_AsyncTask general_asyncTask = new General_AsyncTask(this,BaseActyvity.this); general_asyncTask.execute(api); } }
//найти индексы первого максимального числа в массиве дано n строк, m целых чисел в строке и сами числа(не больше 100). package Array; import java.util.Scanner; public class array_12 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int m = scanner.nextInt(); int num; int a = 0; int b = 0; int i = 0; int j = 0; int[][] arr = new int[n][m]; int res = -2147483648; for(j = 0; j < n; j++) { for (i = 0; i < m; i++) { num = scanner.nextInt(); arr[j][i] = num; if (num > res) { res = num; a = j; b = i; } } } System.out.println(a + " " + b); } }
package com.chaiyining.start; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.chaiyining.service.MathService; public class ConsumerStart { public static void main(String[] args) { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:ApplicantionContext.xml"); MathService bean = context.getBean(MathService.class); int puls = bean.puls(10, 3); System.out.println("相加后的结果是"+puls); int subtract = bean.subtract(1, 3); System.out.println("相减后的结果是:"+subtract); int multiply = bean.multiply(20, 5); System.out.println("相乘后的结果是"+multiply); int divide = bean.divide(50, 5); System.out.println("相除后的结果是"+divide); } }
package com.cs.messaging.sftp; import com.google.common.base.Objects; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.Serializable; import java.util.Date; /** * @author Joakim Gottzén */ public class PlayerActivity implements Serializable { private static final long serialVersionUID = 1L; @SuppressWarnings("UnusedDeclaration") public static final int CUSTOMER_PRODUCT_ID = 0; public static final int CASINO_PRODUCT_ID = 1; public static final int NORMAL_ADJUSTMENT = 1; @SuppressWarnings("UnusedDeclaration") public static final int CONTRIBUTION_ADJUSTMENT = 6; @Nonnull private final Long customerId; @Nonnull private final Date activityDate; @Nonnull private final Integer productId; @Nonnull private final Double grossRevenue; @Nonnull private final Double bonuses; @Nonnull private final Double adjustments; @Nonnull private final Double deposits; @Nonnull private final Integer blings; @Nonnull private final Double turnover; @Nonnull private final Double withdrawals; @Nonnull private final Integer transactions; @Nonnull private final Integer adjustmentTypeId; public PlayerActivity(@Nonnull final Long customerId, @Nonnull final Date activityDate, @Nonnull final Integer productId, @Nonnull final Double grossRevenue, @Nonnull final Double bonuses, @Nonnull final Double adjustments, @Nonnull final Double deposits, @Nonnull final Integer blings, @Nonnull final Double turnover, @Nonnull final Double withdrawals, @Nonnull final Integer transactions, @Nullable final Integer adjustmentTypeId) { this.customerId = customerId; this.activityDate = activityDate; this.productId = productId; this.grossRevenue = grossRevenue; this.bonuses = bonuses; this.adjustments = adjustments; this.deposits = deposits; this.blings = blings; this.turnover = turnover; this.withdrawals = withdrawals; this.transactions = transactions; if (adjustmentTypeId != null) { this.adjustmentTypeId = adjustmentTypeId; } else { this.adjustmentTypeId = NORMAL_ADJUSTMENT; } } @Nonnull public Long getCustomerId() { return customerId; } @Nonnull public Date getActivityDate() { return activityDate; } @Nonnull public Integer getProductId() { return productId; } @Nonnull public Double getGrossRevenue() { return grossRevenue; } @Nonnull public Double getBonuses() { return bonuses; } @Nonnull public Double getAdjustments() { return adjustments; } @Nonnull public Double getDeposits() { return deposits; } @Nonnull public Integer getBlings() { return blings; } @Nonnull public Double getTurnover() { return turnover; } @Nonnull public Double getWithdrawals() { return withdrawals; } @Nonnull public Integer getTransactions() { return transactions; } @Nonnull public Integer getAdjustmentTypeId() { return adjustmentTypeId; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final PlayerActivity that = (PlayerActivity) o; return Objects.equal(customerId, that.customerId) && Objects.equal(activityDate, that.activityDate) && Objects.equal(productId, that.productId) && Objects.equal(grossRevenue, that.grossRevenue) && Objects.equal(adjustments, that.adjustments) && Objects.equal(deposits, that.deposits) && Objects.equal(blings, that.blings) && Objects.equal(turnover, that.turnover) && Objects.equal(withdrawals, that.withdrawals) && Objects.equal(transactions, that.transactions) && Objects.equal(adjustmentTypeId, that.adjustmentTypeId); } @Override public int hashCode() { return Objects.hashCode(customerId, activityDate, productId, grossRevenue, adjustments, deposits, blings, turnover, withdrawals, transactions, adjustmentTypeId); } @Override public String toString() { return Objects.toStringHelper(this) .add("customerId", customerId) .add("activityDate", activityDate) .add("productId", productId) .add("grossRevenue", grossRevenue) .add("bonuses", bonuses) .add("adjustments", adjustments) .add("deposits", deposits) .add("blings", blings) .add("turnover", turnover) .add("withdrawals", withdrawals) .add("transactions", transactions) .add("adjustmentTypeId", adjustmentTypeId) .toString(); } }
package com.example.kuno.sdcardex; import android.os.Bundle; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import android.widget.Toast; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class MainActivity extends AppCompatActivity { String filename = "test" + System.currentTimeMillis() + ".txt"; File sdcard_path = Environment.getExternalStorageDirectory(); TextView tvOutput; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvOutput = (TextView) findViewById(R.id.tvOutput); writeFileToSDCard(); readFileFromSDCard(); } private void writeFileToSDCard() { tvOutput.setText("[파일 쓰기]\n"); if(sdcard_path.exists() && sdcard_path.canWrite()){ File uadDir = new File(sdcard_path.getAbsolutePath() + "/filetest"); //파일생성 uadDir.mkdir(); FileOutputStream fos = null; try{ fos = new FileOutputStream(uadDir.getAbsolutePath() + "/" + filename); String msg = "SD카드의 파일 내용"; fos.write(msg.getBytes()); tvOutput.append("파일이 생성되었습니다.\n"); }catch(Exception e){ Toast.makeText(this, "예외: " + e.toString(), Toast.LENGTH_SHORT).show(); }finally { if(fos!=null) try {fos.close();} catch (IOException e) {e.printStackTrace();} } } } private void readFileFromSDCard() { tvOutput.append("------------------------------\n"); tvOutput.append("[파일읽기]\n"); File rFile = new File(sdcard_path.getAbsolutePath() + "/filetest/" + filename); if(rFile.canRead()){ FileInputStream fis = null; try{ fis = new FileInputStream(rFile); byte[] reader = new byte[fis.available()]; //fis의 바이트 크기만큼 fis.read(reader); tvOutput.append(new String(reader)); }catch (Exception e){ Toast.makeText(this, "예외 발생: " + e.toString(), Toast.LENGTH_SHORT).show(); }finally{ if(fis!=null) try {fis.close();} catch (IOException e) {e.printStackTrace();} } } } }
package net.gupt.ebuy.service; import java.util.List; import net.gupt.ebuy.dao.MessageDao; import net.gupt.ebuy.dao.MessageDaoImpl; import net.gupt.ebuy.pojo.Idea; /** * 意见反馈模块业务接口实现类 * @author glf * */ public class MessageServiceImpl implements MessageService{ private MessageDao messageDao = new MessageDaoImpl(); public boolean submitMessage(Idea idea) { messageDao.saveMess(idea); return true; } public List<Idea> queryMessage() { List<Idea> ideas = messageDao.findAll(); return ideas; } }
package huadi.com.Route; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.R.integer; import android.content.Context; import android.os.AsyncTask; import android.util.Log; import android.widget.Toast; public class RealTimeBike extends AsyncTask<String, String, String> // <傳入參數, 處理中更新介面參數, 處理後傳出參數> { // private final String bikeurl = // "http://its.taipei.gov.tw/aspx/Youbike.aspx?Mode=1"; //台北市交通局5分鐘更新(舊) String info = ""; Transform trans = new Transform(); String mitems; // 按下的圖標 Context mcontext; public RealTimeBike(String items, Context context) { mitems = items; mcontext = context; } @Override protected String doInBackground(String... params) { if (params.length < 0) return null; HttpURLConnection con = null; try { URL url = new URL("http://www.youbike.com.tw/info3b.php?sno=" + params[0]); // String.format("%04d",)); Log.e("Exception", params[0]); con = (HttpURLConnection) url.openConnection(); con.setReadTimeout(10000); con.setConnectTimeout(15000); con.setRequestMethod("GET"); con.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.2; en-GB; rv:1.9.2.9) Gecko/20100824 Firefox/3.6.9"); con.setDoInput(true); con.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); String n, result = ""; StringBuilder htmlContent = new StringBuilder(); while ((n = reader.readLine()) != null) htmlContent.append(n); result = htmlContent.toString(); String pattern; pattern = "sbi\\s*\\=\\s*'([0-9]+)?'.*sus\\s*\\=\\s*'([0-9]+)?';"; Pattern p = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); Matcher m = p.matcher(result); while (m.find()) { int total = Integer.parseInt(m.group(1)) + Integer.parseInt(m.group(2)); info = m.group(1) + " / " + total; } } catch (Exception e) { Log.e("Exception", e.toString()); info = "測試或維修中..."; } finally { if (con != null) con.disconnect(); } return info; } @Override protected void onPostExecute(String result) { super.onPostExecute(result); Toast.makeText(mcontext, "這裡是 " + mitems + "\r\n可借車輛 " + result, Toast.LENGTH_SHORT).show(); } @Override protected void onProgressUpdate(String... params) { super.onProgressUpdate(params); } }
package ru.parse.dump.vind; import ru.parse.dump.objects.DumpClass; import java.util.HashMap; import java.util.Map; public class DumpClassCacheRegion { private static final int CAPACITY = 100000; private Map<Long, DumpClass> cached = new HashMap<>(CAPACITY); public void put(DumpClass aClass) { cached.put(aClass.getAddress(), aClass); } public DumpClass find(long address) { return cached.get(address); } public int size() { return cached.size(); } }
package com.yc.cinema.service.impl; import static org.junit.Assert.*; import java.util.List; import org.apache.logging.log4j.LogManager; import org.junit.Test; import com.yc.cinema.entity.FilmType; import com.yc.cinema.service.TypeService; public class TypeServiceImplTest { TypeService service = new TypeServiceImpl(); @Test public void testGetTypes() { List<FilmType> filmtypes = service.getTypes(); LogManager.getLogger().debug("取到的值:" + filmtypes); assertNotNull("获取失败",filmtypes); } }
package com.sinodynamic.hkgta.scheduler.job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.scheduling.quartz.QuartzJobBean; import org.springframework.web.context.WebApplicationContext; import com.sinodynamic.hkgta.service.mms.SynchronizeSpaData; public class SpaAppointmentsSynchronizeTask extends QuartzJobBean implements ApplicationContextAware { private final Logger logger = LoggerFactory.getLogger(SpaAppointmentsSynchronizeTask.class); WebApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = (WebApplicationContext)applicationContext; } @Override protected void executeInternal(JobExecutionContext context) throws JobExecutionException { try { SynchronizeSpaData synchronizeSpaData = applicationContext.getBean(SynchronizeSpaData.class); synchronizeSpaData.synchronizeAppointments(); } catch (Exception e) { e.printStackTrace(); logger.error(e.getMessage(), e); } } }
package exercicios.desafios.uri; import java.util.Scanner; public class TiposTriangulo { public static void main(String[] args) { // Area de declaração de variaveis double A, B, C; double aux, a2, bc; Scanner sc = new Scanner(System.in); System.out.println("digite o valor de a"); A = sc.nextDouble(); System.out.println("digite o valor de b"); B = sc.nextDouble(); System.out.println("digite o valor de c"); C = sc.nextDouble(); // verifica se "a" é maior que os elementos if (B > A) { aux = B; A = B; B = aux; } if (C > A) { aux = A; A = C; C = aux; } a2 = Math.pow(A, 2); bc = Math.pow(B, 2) + Math.pow(C, 2); if (A > B + C) { System.out.println("NAO FORMA TRIANGULO"); } else { // Pode formar algum triangulo if (a2 > bc) { System.out.println("TRIANGULO OBTUSANGULO"); } else if (a2 < bc) { System.out.println("TRIANGULO ACUTANGULO"); } else { System.out.println("TRIANGULO RETANGULO"); } // Verifica arestas if (A == B && B == C) { System.out.println("TRIANGULO EQUILATERO"); } else if (A == B || A == C || B == C) { System.out.println("TRIANGULO ISOSCELES"); } } sc.close(); } }
package se.kth.kthfsdashboard.log; import java.util.ArrayList; import java.util.List; import javax.ejb.EJB; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; /** * * @author x */ @ManagedBean(name = "logController") @RequestScoped public class LogController { @EJB private LogEJB logEJB; private Log log = new Log(); private List<Log> logList = new ArrayList<Log>(); public String doCreateLog() { setLog(getLogEJB().addLog(getLog())); setLogList(getLogEJB().findLogs()); return "showAlllogs.xhtml"; } public String doShowlogs() { setLogList(getLogEJB().findLogs()); // FacesContext ctx = FacesContext.getCurrentInstance(); // ctx.addMessage(null, new FacesMessage("book created", "BOOK created!!!!!!!!!!!!!")); // return null; return "showAlllogs.xhtml"; } public LogEJB getLogEJB() { return logEJB; } public void setLogEJB(LogEJB logEJB) { this.logEJB = logEJB; } public Log getLog() { return log; } public void setLog(Log log) { this.log = log; } public List<Log> getLogList() { return logList; } public void setLogList(List<Log> logList) { this.logList = logList; } }
package com.xander.minitasker; import android.os.AsyncTask; import android.os.Handler; import android.os.Looper; import android.os.Message; /** * 执行耗时任务后,回调到 UI 线程 * Created by xander on 2018/4/11. */ public abstract class UiTasker<R> { /** * 回调消息 */ private static final int MESSAGE_POST_RESULT = 100; /** * 和 UI 线程绑定的 Handler */ private static InternalHandler sHandler; /** * 获取和 UI 线程绑定的 Handler * @return 和 UI 线程绑定的 Handler */ private static Handler getMainHandler() { synchronized (AsyncTask.class) { if (sHandler == null) { sHandler = new InternalHandler(Looper.getMainLooper()); } return sHandler; } } /** * 接收到回调消息后处理回调消息 */ private static class InternalHandler extends Handler { public InternalHandler(Looper looper) { super(looper); } @SuppressWarnings({ "unchecked", "RawUseOfParameterizedType" }) @Override public void handleMessage(Message msg) { switch (msg.what) { case MESSAGE_POST_RESULT: // There is only one result UiTasker uiTasker = (UiTasker) msg.obj; uiTasker.callback(uiTasker.getResult()); break; default: break; } } } /** * 耗时任务执行结果 */ private R result; /** * 耗时任务 * @return */ public abstract R run(); /** * 回调方法 * @param result */ public abstract void callback(R result); /** * 设置回调结果 * @param iResult */ public void setResult(R iResult) { result = iResult; } /** * 获取回调结果 * @return */ public R getResult() { return result; } /** * 发送回调消息 */ public void postResult() { Message message = Message.obtain(); message.what = MESSAGE_POST_RESULT; message.obj = this; UiTasker.getMainHandler().sendMessage(message); } }
package com.seu.common.annotation; import java.lang.annotation.*; /** * @author ethan * @date 2018/12/27 */ @Target({ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface TokenToUser { /** * 当前用户在request中的名字 * @return */ String value() default "user"; }
package user.com.commons; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import user.com.foodexuserui.Breakfast; import user.com.foodexuserui.Dinner; import user.com.foodexuserui.Lunch; public class TabPagerAdapter extends FragmentStatePagerAdapter { public TabPagerAdapter(FragmentManager fm) { super(fm); // TODO Auto-generated constructor stub } @Override public Fragment getItem(int i) { Fragment fragment = new Fragment(); switch (i) { case 0: fragment = new Breakfast(); break; case 1: fragment = new Lunch(); break; case 2: fragment = new Dinner(); break; default: return null; } return fragment; } @Override public int getCount() { // TODO Auto-generated method stub return 3; //No of Tabs } }
package com.mao.springweb.fileTest; import org.apache.commons.io.FileUtils; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.net.URLEncoder; @Controller public class FileUpload { @GetMapping("/fileIndex") public String fileIndex(){ return "file"; } @PostMapping("/upload") public String uploadFile(HttpServletRequest req, @RequestParam("description") String description, @RequestParam("file") MultipartFile file) throws Exception{ System.out.println("description: "+description); if(file.isEmpty()){ return "error"; } // String filePath= req.getServletContext().getRealPath("/upload/"); System.out.println("filePath: "+filePath); //上传文件名 String fileName=file.getOriginalFilename(); //创建目录 File newFilePath=new File(filePath,fileName); if(!newFilePath.getParentFile().exists()){ newFilePath.getParentFile().mkdirs(); } //将上传文件保存 file.transferTo(new File(filePath+File.pathSeparator+fileName)); return "success"; } @RequestMapping("/downloadIndex") public String downloadIndex(){ return "download"; } @GetMapping("/download") public ResponseEntity<byte[]> download(HttpServletRequest req, @RequestParam("fileName") String fileName , @RequestHeader("User-Agent") String userAgent, Model model)throws Exception{ System.out.println("download"); //下载文件路径 String path=req.getServletContext().getRealPath("/upload/"); File file=new File(path+File.separator+fileName); //http状态为200 ResponseEntity.BodyBuilder builder= ResponseEntity.ok(); builder.contentLength(file.length()); //二进制流数据 builder.contentType(MediaType.APPLICATION_OCTET_STREAM); //解码 fileName= URLEncoder.encode(fileName,"UTF-8"); //设置响应文件,下载或保存 if(userAgent.indexOf("MSIE")>0){ //IE builder.header("Content-Dispostion","attachment;filename="+fileName); }else{ builder.header("Content-Disposition","attachment; filename*=UTF-8''"+fileName); } return builder.body(FileUtils.readFileToByteArray(file)); } }
package com.zc.base.sys.modules.user.controller; import com.google.gson.Gson; import com.zc.base.common.bo.Node; import com.zc.base.common.controller.SdBaseController; import com.zc.base.common.exception.SdExceptionFactory; import com.zc.base.orm.mybatis.paging.JqueryStylePaging; import com.zc.base.orm.mybatis.paging.JqueryStylePagingResults; import com.zc.base.sys.common.constant.AmiLogConstant; import com.zc.base.sys.common.constant.SysConstant; import com.zc.base.sys.common.util.DefineStringUtil; import com.zc.base.sys.modules.user.dto.RolePri; import com.zc.base.sys.modules.user.entity.Privilege; import com.zc.base.sys.modules.user.entity.Role; import com.zc.base.sys.modules.user.entity.User; import com.zc.base.sys.modules.user.service.PriService; import com.zc.base.sys.modules.user.service.RoleService; import com.zc.base.sys.modules.user.service.UserService; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.support.RequestContextUtils; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.List; /** * 角色管理 * * @author Jack.M * @version 1.0 */ @Controller @RequestMapping({"/sys/role"}) public class RoleController extends SdBaseController { @Resource private SdExceptionFactory sdExceptionFactory; @Autowired private PriService priService; private RoleService roleService; private UserService userService; @RequestMapping(value = {"/addRole"}, produces = {"application/json"}) @ResponseBody @RequiresPermissions({"PIVAS_BTN_125"}) public String addRole(Role role) throws Exception { Role roleNumber = this.roleService.getRoleID(role); try { if (roleNumber != null) { if (role.getName().equals(roleNumber.getName())) { throw this.sdExceptionFactory.createSdException("00003", null, null); } } else { this.roleService.addRole(role); addOperLog("SM_2", AmiLogConstant.BRANCH_SYSTEM.SM, getMessage("log.role.tip.addrole", new String[]{role.getName()}), true); } return buildSuccessJsonMsg(this.messageHolder.getMessage("common.op.success")); } catch (Exception e) { addOperLog("SM_2", AmiLogConstant.BRANCH_SYSTEM.SM, getMessage("log.role.tip.addrole", new String[]{role.getName()}), false); throw e; } } @RequestMapping(value = {"/addRoleRefPrivilege"}, produces = {"application/json"}) @ResponseBody @RequiresPermissions({"PIVAS_BTN_128"}) public String addRoleRefPrivilege(@RequestBody RolePri rp) throws Exception { Role role = new Role(); role.setRoleId(Long.valueOf(rp.getRoleId())); Role u = this.roleService.getRoleID(role); try { if ((u == null) || (!this.priService.checkExists(rp.getPris()))) { throw this.sdExceptionFactory.createSdException("00001", null, null); } this.priService.addRolePrivilegeBatch(Long.valueOf(rp.getRoleId()), rp.getPris(), rp.getIgnorePris()); addOperLog("SM_2", AmiLogConstant.BRANCH_SYSTEM.SM, getMessage("log.user.tip.roleImpowerLose", new String[]{u.getRoleId().toString(), u.getName()}), true); return buildSuccessJsonMsg(this.messageHolder.getMessage("common.op.success")); } catch (Exception e) { addOperLog("SM_2", AmiLogConstant.BRANCH_SYSTEM.SM, getMessage("log.user.tip.roleImpowerLose", new String[]{rp.getRoleId().toString()}), false); throw e; } } @RequestMapping(value = {"/delRole"}, produces = {"application/json"}) @ResponseBody @RequiresPermissions({"PIVAS_BTN_127"}) public String delRole(String roleId) throws Exception { try { this.roleService.delRole(roleId); addOperLog("SM_2", AmiLogConstant.BRANCH_SYSTEM.SM, getMessage("log.role.tip.deleteRole", new String[]{roleId}), true); return buildSuccessJsonMsg(this.messageHolder.getMessage("common.op.success")); } catch (Exception e) { addOperLog("SM_2", AmiLogConstant.BRANCH_SYSTEM.SM, getMessage("log.role.tip.deleteRole", new String[]{roleId}), false); throw e; } } @RequestMapping(value = {"/rolelist"}, produces = {"application/json"}) @ResponseBody public String getRole(Role role, JqueryStylePaging jquryStylePaging) throws Exception { String[] namelist = role.getNameList(); if (namelist != null) { for (int i = 0; i < namelist.length; i++) { namelist[i] = DefineStringUtil.escapeAllLike(namelist[i]); } } String[] desclist = role.getDescList(); if (desclist != null) { for (int i = 0; i < desclist.length; i++) { desclist[i] = DefineStringUtil.escapeAllLike(desclist[i]); } } JqueryStylePagingResults<Role> rolePagingResults = this.roleService.getRole(role, jquryStylePaging); return new Gson().toJson(rolePagingResults); } public RoleService getRoleService() { return this.roleService; } public UserService getUserService() { return this.userService; } @RequestMapping({"/initRole"}) @RequiresPermissions({"PIVAS_MENU_118"}) public String initRole() { return "sys/user/roleList"; } @RequestMapping(value = {"/initUpdateRole"}, produces = {"application/json"}) @ResponseBody @RequiresPermissions({"PIVAS_BTN_126"}) public String initUpdateUser(Role role) { Role roleInfo = this.roleService.getRoleID(role); if (roleInfo == null) { throw this.sdExceptionFactory.createSdException("00001", null, null); } return new Gson().toJson(roleInfo); } @Autowired public void setRoleService(RoleService roleService) { this.roleService = roleService; } @Autowired public void setUserService(UserService userService) { this.userService = userService; } @RequestMapping(value = {"/treeRole"}, produces = {"application/json"}) @ResponseBody @RequiresPermissions({"PIVAS_BTN_128"}) public String treeRole(HttpServletRequest request, Long roleId) { List<Node> nodes = new ArrayList(); List<Privilege> hasPri = null; User us = getCurrentUser(); String userAccount = us.getAccount(); boolean isAdmin = false; if (SysConstant.SYSADMIN.equals(userAccount)) { isAdmin = true; } String language = RequestContextUtils.getLocale(request).getLanguage(); hasPri = this.priService.getPrivilegeListByRoleId(roleId, us.getUserId(), language); if ((hasPri != null) && (hasPri.size() > 0)) { Node node = null; for (Privilege p : hasPri) { node = new Node(); node.setId(p.getPrivilegeId()); node.setpId(p.getParentId()); node.setChecked(Boolean.valueOf(p.isCheck())); if (isAdmin) { node.setChkDisabled(Boolean.valueOf(false)); } else { node.setChkDisabled(Boolean.valueOf(!p.isUse())); } node.setName(p.getName()); nodes.add(node); } } return new Gson().toJson(nodes); } @RequestMapping(value = {"/updateRole"}, produces = {"application/json"}) @ResponseBody @RequiresPermissions({"PIVAS_BTN_126"}) public String updateRole(Role role) throws Exception { String roleName = role.getName(); role.setName(null); Role r = this.roleService.getRoleID(role); try { if (r == null) { throw this.sdExceptionFactory.createSdException("00001", null, null); } role.setName(roleName); this.roleService.updateRole(role); addOperLog("SM_2", AmiLogConstant.BRANCH_SYSTEM.SM, getMessage("log.role.tip.updateRole", new String[]{role.getRoleId().toString(), r.getName(), role.getName()}), true); return buildSuccessJsonMsg(this.messageHolder.getMessage("common.op.success")); } catch (Exception e) { addOperLog("SM_2", AmiLogConstant.BRANCH_SYSTEM.SM, getMessage("log.role.tip.updateRoleLose", new String[]{role.getRoleId().toString(), role.getName()}), false); throw e; } } }
package com.jpeng.demo.delete; import com.jpeng.demo.notes.Learn; /** * Created by 王将 on 2018/6/12. */ public class LearnDelete { private int position; private Learn learn; public void setPosition(int position) { this.position = position; } public void setLearn(Learn learn) { this.learn = learn; } public int getPosition() { return position; } public Learn getLearn() { return learn; } }
package uz.otash.shop.components; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; import uz.otash.shop.entity.*; import uz.otash.shop.entity.enums.RoleName; import uz.otash.shop.repository.*; import uz.pdp.springbootjpa.entity.*; import uz.pdp.springbootjpa.repository.*; @Component public class DataLoader implements CommandLineRunner { @Value("${spring.sql.init.mode}") private String mode; @Autowired RoleRepository roleRepository; @Autowired UserRepository userRepository; @Autowired WarehouseRepository warehouseRepository; @Autowired ShopRepository shopRepository; @Autowired CategoryRepository categoryRepository; @Autowired BrandRepository brandRepository; @Autowired DefectRepository defectRepository; @Autowired ProductRepository productRepository; @Autowired ProductWithAmountRepository productWithAmountRepository; @Autowired RejectRepository rejectRepository; @Autowired SaleRepository saleRepository; @Autowired TransferRepository transferRepository; @Override public void run(String... args) throws Exception { if (mode.equals("always")){ Role roleDirector = roleRepository.save(new Role(RoleName.ROLE_DIRECTOR)); Role roleManager = roleRepository.save(new Role(RoleName.ROLE_MANAGER)); Role roleSeller = roleRepository.save(new Role(RoleName.ROLE_SELLER)); User director = userRepository.save(new User( "director", "123", "director", "director", roleDirector )); User manager = userRepository.save(new User( "manager", "456", "manager", "manager", roleManager )); User seller = userRepository.save(new User( "seller", "789", "seller", "seller", roleSeller )); Warehouse mainSklad = warehouseRepository.save(new Warehouse( "mainWarehouse", "Uy", manager )); Shop shop1 = shopRepository.save(new Shop("shop1", "NEXT", seller)); Warehouse shop1Warehouse = warehouseRepository.save(new Warehouse( shop1.getName()+" Warehouse", shop1.getAddress(), shop1 )); Category chexolCategory = categoryRepository.save(new Category("Chexol")); Category naushnikCategory = categoryRepository.save(new Category("Naushnik")); Brand samsung = brandRepository.save(new Brand("Samsung")); Brand lg = brandRepository.save(new Brand("LG")); Product naushnik = productRepository.save(new Product( "naushnik", "Daxshat naushnik", 100.0, 150.0, 100, naushnikCategory, samsung )); Product chexol = productRepository.save(new Product( "chexol", "Daxshat chexol", 50.0, 80.0, 100, chexolCategory, lg )); Transfer mainSkladgaKirim = transferRepository.save(new Transfer( mainSklad, true )); Transfer shop1gaKirim = transferRepository.save(new Transfer( mainSklad, shop1Warehouse, true )); productWithAmountRepository.save(new ProductWithAmount( naushnik, 100, mainSkladgaKirim )); productWithAmountRepository.save(new ProductWithAmount( chexol, 100, mainSkladgaKirim )); productWithAmountRepository.save(new ProductWithAmount( naushnik, 50, shop1gaKirim )); productWithAmountRepository.save(new ProductWithAmount( chexol, 50, shop1gaKirim )); Sale firstSale = saleRepository.save(new Sale( shop1, shop1.getSeller() )); productWithAmountRepository.save(new ProductWithAmount( naushnik, 10, firstSale )); productWithAmountRepository.save(new ProductWithAmount( chexol, 10, firstSale )); Reject reject = rejectRepository.save(new Reject( shop1 )); productWithAmountRepository.save(new ProductWithAmount( naushnik, 1, reject )); productWithAmountRepository.save(new ProductWithAmount( chexol, 1, reject )); Defect defect = defectRepository.save(new Defect( shop1Warehouse, true, manager )); productWithAmountRepository.save(new ProductWithAmount( naushnik, 3, defect )); productWithAmountRepository.save(new ProductWithAmount( chexol, 3, defect )); } } }
package se.rtz.mltool.commnads; import java.io.IOException; import java.io.PrintStream; import org.dom4j.Document; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; import se.rtz.mltool.args.XmlInputExtractor; import se.rtz.tool.arg.Param; import se.rtz.tool.arg.freetextoutput.FreeTextPrintStreamExtractor; import se.rtz.tool.commands.Command; import se.rtz.tool.commands.CommandDoc; @CommandDoc(author = "Daniel Schwartz, schw@rtz.se", description = "Indents an xml to make it more readable.", name = "indent") public class Indent implements Command { private Document document; private PrintStream outputStream; @Override public void execute() { OutputFormat format = OutputFormat.createPrettyPrint(); try { XMLWriter writer = new XMLWriter(outputStream, format); writer.write(document); } catch (IOException e) { throw new RuntimeException("could not write output", e); } } @Override public void close() throws IOException { outputStream.close(); document = null; } @Param(description = "Formatted output.", exampleValues = "./anOutputFile.xml", token = "-out", moreInfo = "If omitted or if ':out:' is passed as value, then std out will be used.", extractor = FreeTextPrintStreamExtractor.class) public void setPrintStream(PrintStream outputStream) { this.outputStream = outputStream; } @Param(description = "Xml input. If not given (or if equal to ':in:') std in will be used.", exampleValues = "./aFile.xml", token = "-xmlIn", extractor = XmlInputExtractor.class) public void setDocument(Document document) { this.document = document; } }
import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ AddressBookTest.class, BuddyInfoTest.class, }) public class AllTests { }
public class CD { String artista; double preco; String nome; int qtd; public CD(String n, double p, String a, int q) { nome = n; preco = p; artista = a; qtd = q; } public double compraCD(double qtd) { double valCompra = (this.preco * qtd); return valCompra; } }
package net.rationalminds.es; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Annotation for environment switching. Use this annotation over methods which you want to behave differently * in case of development or testing environment. Annotation value requires fully qualified method name. * if alternate method requires no argument then value must be a.b.c.MyClass.myMethod() * if alternate method requires argument values of annotated method then value must be a.b.c.MyClass.myMethod(args) * if alternate method requires reference of 'this' values of annotated method then value must be a.b.c.MyClass.myMethod(this) * @author Vaibhav Pratap Singh * */ @Retention(RUNTIME) @Target(METHOD) public @interface EnvironmentalControl { String devMethod() default ""; String testMethod() default ""; }
package com.qualcomm.QCARSamples.FrameMarkers.util; import java.io.IOException; import java.net.URL; import java.net.URLConnection; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import android.util.Log; public class PositionSendUtil { public static String TARGET_URL = "http://qcarposserv.heroku.com/positions/add?userid=%s&x=%.3f&y=%.3f"; static class UploadInfo { private String username; private float x; private float y; public UploadInfo(String username, float x, float y) { super(); this.username = username; this.x = x; this.y = y; } } private BlockingQueue<UploadInfo> mQueue; private Thread mThread; public PositionSendUtil() { mQueue = new LinkedBlockingQueue<PositionSendUtil.UploadInfo>(); mThread = new Thread(mRunnable); mThread.start(); } public void dispose() { if (mThread != null) { mThread.interrupt(); try { mThread.join(); } catch (InterruptedException e) { // ignore } } if (mQueue != null) { mQueue = null; } } Runnable mRunnable = new Runnable() { @Override public void run() { try { while (true) { UploadInfo info = mQueue.take(); if (mQueue.size() > 0) { mQueue.clear(); } String urlStr = String.format(TARGET_URL, info.username, info.x, info.y); try { URL url = new URL(urlStr); URLConnection conn = url.openConnection(); conn.getContent(); } catch (IOException e) { Log.e("FrameMaker", e.getMessage() + " " + urlStr); } } } catch (InterruptedException e) { // ignore } } }; public void sendPosition(String username, float x, float y) { UploadInfo info = new UploadInfo(username, x, y); mQueue.add(info); } }
package tryprojects; public class Student { private String firstName, lastName, rollId; public Student(String firstName, String lastName, String rollId) { this.firstName = firstName; this.lastName = lastName; this.rollId = rollId; } @Override public String toString() { return "Student{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", rollId='" + rollId + '\'' + '}'; } }
/** * This class is generated by jOOQ */ package schema.tables; import java.sql.Timestamp; import java.util.Arrays; import java.util.List; import javax.annotation.Generated; import org.jooq.Field; import org.jooq.ForeignKey; import org.jooq.Identity; import org.jooq.Schema; import org.jooq.Table; import org.jooq.TableField; import org.jooq.UniqueKey; import org.jooq.impl.TableImpl; import schema.BitnamiEdx; import schema.Keys; import schema.tables.records.ProctoringProctoredexamstudentattemptRecord; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.8.4" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class ProctoringProctoredexamstudentattempt extends TableImpl<ProctoringProctoredexamstudentattemptRecord> { private static final long serialVersionUID = -636078683; /** * The reference instance of <code>bitnami_edx.proctoring_proctoredexamstudentattempt</code> */ public static final ProctoringProctoredexamstudentattempt PROCTORING_PROCTOREDEXAMSTUDENTATTEMPT = new ProctoringProctoredexamstudentattempt(); /** * The class holding records for this type */ @Override public Class<ProctoringProctoredexamstudentattemptRecord> getRecordType() { return ProctoringProctoredexamstudentattemptRecord.class; } /** * The column <code>bitnami_edx.proctoring_proctoredexamstudentattempt.id</code>. */ public final TableField<ProctoringProctoredexamstudentattemptRecord, Integer> ID = createField("id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); /** * The column <code>bitnami_edx.proctoring_proctoredexamstudentattempt.created</code>. */ public final TableField<ProctoringProctoredexamstudentattemptRecord, Timestamp> CREATED = createField("created", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false), this, ""); /** * The column <code>bitnami_edx.proctoring_proctoredexamstudentattempt.modified</code>. */ public final TableField<ProctoringProctoredexamstudentattemptRecord, Timestamp> MODIFIED = createField("modified", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false), this, ""); /** * The column <code>bitnami_edx.proctoring_proctoredexamstudentattempt.started_at</code>. */ public final TableField<ProctoringProctoredexamstudentattemptRecord, Timestamp> STARTED_AT = createField("started_at", org.jooq.impl.SQLDataType.TIMESTAMP, this, ""); /** * The column <code>bitnami_edx.proctoring_proctoredexamstudentattempt.completed_at</code>. */ public final TableField<ProctoringProctoredexamstudentattemptRecord, Timestamp> COMPLETED_AT = createField("completed_at", org.jooq.impl.SQLDataType.TIMESTAMP, this, ""); /** * The column <code>bitnami_edx.proctoring_proctoredexamstudentattempt.last_poll_timestamp</code>. */ public final TableField<ProctoringProctoredexamstudentattemptRecord, Timestamp> LAST_POLL_TIMESTAMP = createField("last_poll_timestamp", org.jooq.impl.SQLDataType.TIMESTAMP, this, ""); /** * The column <code>bitnami_edx.proctoring_proctoredexamstudentattempt.last_poll_ipaddr</code>. */ public final TableField<ProctoringProctoredexamstudentattemptRecord, String> LAST_POLL_IPADDR = createField("last_poll_ipaddr", org.jooq.impl.SQLDataType.VARCHAR.length(32), this, ""); /** * The column <code>bitnami_edx.proctoring_proctoredexamstudentattempt.attempt_code</code>. */ public final TableField<ProctoringProctoredexamstudentattemptRecord, String> ATTEMPT_CODE = createField("attempt_code", org.jooq.impl.SQLDataType.VARCHAR.length(255), this, ""); /** * The column <code>bitnami_edx.proctoring_proctoredexamstudentattempt.external_id</code>. */ public final TableField<ProctoringProctoredexamstudentattemptRecord, String> EXTERNAL_ID = createField("external_id", org.jooq.impl.SQLDataType.VARCHAR.length(255), this, ""); /** * The column <code>bitnami_edx.proctoring_proctoredexamstudentattempt.allowed_time_limit_mins</code>. */ public final TableField<ProctoringProctoredexamstudentattemptRecord, Integer> ALLOWED_TIME_LIMIT_MINS = createField("allowed_time_limit_mins", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); /** * The column <code>bitnami_edx.proctoring_proctoredexamstudentattempt.status</code>. */ public final TableField<ProctoringProctoredexamstudentattemptRecord, String> STATUS = createField("status", org.jooq.impl.SQLDataType.VARCHAR.length(64).nullable(false), this, ""); /** * The column <code>bitnami_edx.proctoring_proctoredexamstudentattempt.taking_as_proctored</code>. */ public final TableField<ProctoringProctoredexamstudentattemptRecord, Byte> TAKING_AS_PROCTORED = createField("taking_as_proctored", org.jooq.impl.SQLDataType.TINYINT.nullable(false), this, ""); /** * The column <code>bitnami_edx.proctoring_proctoredexamstudentattempt.is_sample_attempt</code>. */ public final TableField<ProctoringProctoredexamstudentattemptRecord, Byte> IS_SAMPLE_ATTEMPT = createField("is_sample_attempt", org.jooq.impl.SQLDataType.TINYINT.nullable(false), this, ""); /** * The column <code>bitnami_edx.proctoring_proctoredexamstudentattempt.student_name</code>. */ public final TableField<ProctoringProctoredexamstudentattemptRecord, String> STUDENT_NAME = createField("student_name", org.jooq.impl.SQLDataType.VARCHAR.length(255).nullable(false), this, ""); /** * The column <code>bitnami_edx.proctoring_proctoredexamstudentattempt.review_policy_id</code>. */ public final TableField<ProctoringProctoredexamstudentattemptRecord, Integer> REVIEW_POLICY_ID = createField("review_policy_id", org.jooq.impl.SQLDataType.INTEGER, this, ""); /** * The column <code>bitnami_edx.proctoring_proctoredexamstudentattempt.proctored_exam_id</code>. */ public final TableField<ProctoringProctoredexamstudentattemptRecord, Integer> PROCTORED_EXAM_ID = createField("proctored_exam_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); /** * The column <code>bitnami_edx.proctoring_proctoredexamstudentattempt.user_id</code>. */ public final TableField<ProctoringProctoredexamstudentattemptRecord, Integer> USER_ID = createField("user_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); /** * The column <code>bitnami_edx.proctoring_proctoredexamstudentattempt.is_status_acknowledged</code>. */ public final TableField<ProctoringProctoredexamstudentattemptRecord, Byte> IS_STATUS_ACKNOWLEDGED = createField("is_status_acknowledged", org.jooq.impl.SQLDataType.TINYINT.nullable(false), this, ""); /** * Create a <code>bitnami_edx.proctoring_proctoredexamstudentattempt</code> table reference */ public ProctoringProctoredexamstudentattempt() { this("proctoring_proctoredexamstudentattempt", null); } /** * Create an aliased <code>bitnami_edx.proctoring_proctoredexamstudentattempt</code> table reference */ public ProctoringProctoredexamstudentattempt(String alias) { this(alias, PROCTORING_PROCTOREDEXAMSTUDENTATTEMPT); } private ProctoringProctoredexamstudentattempt(String alias, Table<ProctoringProctoredexamstudentattemptRecord> aliased) { this(alias, aliased, null); } private ProctoringProctoredexamstudentattempt(String alias, Table<ProctoringProctoredexamstudentattemptRecord> aliased, Field<?>[] parameters) { super(alias, null, aliased, parameters, ""); } /** * {@inheritDoc} */ @Override public Schema getSchema() { return BitnamiEdx.BITNAMI_EDX; } /** * {@inheritDoc} */ @Override public Identity<ProctoringProctoredexamstudentattemptRecord, Integer> getIdentity() { return Keys.IDENTITY_PROCTORING_PROCTOREDEXAMSTUDENTATTEMPT; } /** * {@inheritDoc} */ @Override public UniqueKey<ProctoringProctoredexamstudentattemptRecord> getPrimaryKey() { return Keys.KEY_PROCTORING_PROCTOREDEXAMSTUDENTATTEMPT_PRIMARY; } /** * {@inheritDoc} */ @Override public List<UniqueKey<ProctoringProctoredexamstudentattemptRecord>> getKeys() { return Arrays.<UniqueKey<ProctoringProctoredexamstudentattemptRecord>>asList(Keys.KEY_PROCTORING_PROCTOREDEXAMSTUDENTATTEMPT_PRIMARY, Keys.KEY_PROCTORING_PROCTOREDEXAMSTUDENTATTEMPT_PROCTORING_PROCTOREDEXAMSTUDENTATT_USER_ID_15D13FA8DAC316A0_UNIQ); } /** * {@inheritDoc} */ @Override public List<ForeignKey<ProctoringProctoredexamstudentattemptRecord, ?>> getReferences() { return Arrays.<ForeignKey<ProctoringProctoredexamstudentattemptRecord, ?>>asList(Keys.D5E0A120C32F715BFE04A0A57F399EC0, Keys.PROCTORING_PROCTOREDEXA_USER_ID_633FD8F4F65A0CAC_FK_AUTH_USER_ID); } /** * {@inheritDoc} */ @Override public ProctoringProctoredexamstudentattempt as(String alias) { return new ProctoringProctoredexamstudentattempt(alias, this); } /** * Rename this table */ public ProctoringProctoredexamstudentattempt rename(String name) { return new ProctoringProctoredexamstudentattempt(name, null); } }
package models; import java.sql.Date; public class ItemTransaction { private int transactionId; private int itemId; private String itemName; private String itemDescription; private int price; private Date boughtDate; private Date useDate; private boolean isAvailable; private boolean isUsed; public ItemTransaction(int transactionId, int itemId, String itemName, String itemDescription, Date boughtDate, Date useDate, boolean isAvailable) { this.transactionId = transactionId; this.itemId = itemId; this.itemName = itemName; this.itemDescription = itemDescription; this.boughtDate = boughtDate; this.useDate = useDate; this.isAvailable = isAvailable; } public ItemTransaction(int transactionId, int itemId, String itemName, int price, String itemDescription, boolean isAvailable, boolean isUsed) { this.transactionId = transactionId; this.itemId = itemId; this.itemName = itemName; this.price = price; this.itemDescription = itemDescription; this.isAvailable = isAvailable; this.isUsed = isUsed; } public int getTransactionId() { return transactionId; } public void setTransactionId(int transactionId) { this.transactionId = transactionId; } public int getItemId() { return itemId; } public void setItemId(int itemId) { this.itemId = itemId; } public String getItemName() { return itemName; } public void setItemName(String itemName) { this.itemName = itemName; } public String getItemDescription() { return itemDescription; } public void setItemDescription(String itemDescription) { this.itemDescription = itemDescription; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public Date getBoughtDate() { return boughtDate; } public void setBoughtDate(Date boughtDate) { this.boughtDate = boughtDate; } public Date getUseDate() { return useDate; } public void setUseDate(Date useDate) { this.useDate = useDate; } public boolean isAvailable() { return isAvailable; } public void setAvailable(boolean available) { isAvailable = available; } public boolean isUsed() { return isUsed; } public void setUsed(boolean used) { isUsed = used; } }
package com.capstone.videoeffect; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.Toast; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.FirebaseAuth; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; public class ResetPasswordActivity extends AppCompatActivity { EditText txtEmail; Button btnsubmit; ImageView ivback; FirebaseAuth firebaseAuth; ProgressBar progressBar; @Override public boolean onSupportNavigateUp() { onBackPressed(); return true; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_reset_password); txtEmail = findViewById(R.id.txtEmail); btnsubmit = findViewById(R.id.btnsubmit); ivback = findViewById(R.id.ivback); progressBar = findViewById(R.id.progressBar); firebaseAuth = FirebaseAuth.getInstance(); ivback.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); btnsubmit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Progress progressBar.setVisibility(View.VISIBLE); String mail = txtEmail.getText().toString(); firebaseAuth.sendPasswordResetEmail(mail).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Toast.makeText(ResetPasswordActivity.this, "Reset Link Sent To Your Email Successful.", Toast.LENGTH_SHORT).show(); progressBar.setVisibility(View.GONE); Intent intent = new Intent(getApplicationContext(), LoginActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); finish(); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast.makeText(ResetPasswordActivity.this, "Error! Reset Link is Not Sent" + e.getMessage(), Toast.LENGTH_SHORT).show(); progressBar.setVisibility(View.GONE); } }); } }); } }
package cn.mldn.eusplatform.dao; import java.sql.SQLException; import java.util.Set; import cn.mldn.eusplatform.vo.Action; import cn.mldn.util.dao.IBaseDAO; public interface IActionDAO extends IBaseDAO<Long, Action> { /** * 根据部门编号查询所有对应的权限 * @param did 部门编号 * @return 权限编号集合 * @throws SQLException JDBC */ public Set<String> findAllByDept(Long did) throws SQLException ; }
package co.aca.model; import org.hibernate.annotations.CreationTimestamp; import javax.persistence.*; import java.util.Date; @Entity @Table(name = "register") public class Register { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") private int registrationId; @Column(name = "course_id") private int courseId; @Column(name = "user_id") private int userId; @CreationTimestamp @Column(name = "signing_date") private Date signingDate; public int getRegistrationId() { return registrationId; } public void setRegistrationId(int registrationId) { this.registrationId = registrationId; } public int getCourseId() { return courseId; } public void setCourseId(int courseId) { this.courseId = courseId; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public Date getSigningDate() { return signingDate; } public void setSigningDate(Date signingDate) { this.signingDate = signingDate; } }
package plugins.fmp.fmpTools; public enum EnumStatusComputation { START_COMPUTATION, STOP_COMPUTATION }
package remote; import java.rmi.Remote; import java.rmi.RemoteException; public interface IAdminMode extends Remote, IUser { /** * prints out the steps of the pricing curve * @throws RemoteException */ public String getPricingCurve() throws RemoteException; /** * inserts a new or updates an existing price step * @param taskCount * @param percent * @throws RemoteException thrown if taskCount or percentage invalid * @throws ManagementException */ public void setPriceStep(int taskCount, double percent) throws RemoteException, ManagementException; }
/* * 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.beans.factory.support; import java.lang.reflect.Method; import java.util.function.Supplier; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.function.ThrowingBiFunction; import org.springframework.util.function.ThrowingSupplier; /** * Specialized {@link Supplier} that can be set on a * {@link AbstractBeanDefinition#setInstanceSupplier(Supplier) BeanDefinition} * when details about the {@link RegisteredBean registered bean} are needed to * supply the instance. * * @author Phillip Webb * @author Stephane Nicoll * @since 6.0 * @param <T> the type of instance supplied by this supplier * @see RegisteredBean * @see org.springframework.beans.factory.aot.BeanInstanceSupplier */ @FunctionalInterface public interface InstanceSupplier<T> extends ThrowingSupplier<T> { @Override default T getWithException() { throw new IllegalStateException("No RegisteredBean parameter provided"); } /** * Get the supplied instance. * @param registeredBean the registered bean requesting the instance * @return the supplied instance * @throws Exception on error */ T get(RegisteredBean registeredBean) throws Exception; /** * Return the factory method that this supplier uses to create the * instance, or {@code null} if it is not known or this supplier uses * another means. * @return the factory method used to create the instance, or {@code null} */ @Nullable default Method getFactoryMethod() { return null; } /** * Return a composed instance supplier that first obtains the instance from * this supplier and then applies the {@code after} function to obtain the * result. * @param <V> the type of output of the {@code after} function, and of the * composed function * @param after the function to apply after the instance is obtained * @return a composed instance supplier */ default <V> InstanceSupplier<V> andThen( ThrowingBiFunction<RegisteredBean, ? super T, ? extends V> after) { Assert.notNull(after, "'after' function must not be null"); return new InstanceSupplier<>() { @Override public V get(RegisteredBean registeredBean) throws Exception { return after.applyWithException(registeredBean, InstanceSupplier.this.get(registeredBean)); } @Override public Method getFactoryMethod() { return InstanceSupplier.this.getFactoryMethod(); } }; } /** * Factory method to create an {@link InstanceSupplier} from a * {@link ThrowingSupplier}. * @param <T> the type of instance supplied by this supplier * @param supplier the source supplier * @return a new {@link InstanceSupplier} */ static <T> InstanceSupplier<T> using(ThrowingSupplier<T> supplier) { Assert.notNull(supplier, "Supplier must not be null"); if (supplier instanceof InstanceSupplier<T> instanceSupplier) { return instanceSupplier; } return registeredBean -> supplier.getWithException(); } /** * Factory method to create an {@link InstanceSupplier} from a * {@link ThrowingSupplier}. * @param <T> the type of instance supplied by this supplier * @param factoryMethod the factory method being used * @param supplier the source supplier * @return a new {@link InstanceSupplier} */ static <T> InstanceSupplier<T> using(@Nullable Method factoryMethod, ThrowingSupplier<T> supplier) { Assert.notNull(supplier, "Supplier must not be null"); if (supplier instanceof InstanceSupplier<T> instanceSupplier && instanceSupplier.getFactoryMethod() == factoryMethod) { return instanceSupplier; } return new InstanceSupplier<>() { @Override public T get(RegisteredBean registeredBean) throws Exception { return supplier.getWithException(); } @Override public Method getFactoryMethod() { return factoryMethod; } }; } /** * Lambda friendly method that can be used to create an * {@link InstanceSupplier} and add post processors in a single call. For * example: {@code InstanceSupplier.of(registeredBean -> ...).andThen(...)}. * @param <T> the type of instance supplied by this supplier * @param instanceSupplier the source instance supplier * @return a new {@link InstanceSupplier} */ static <T> InstanceSupplier<T> of(InstanceSupplier<T> instanceSupplier) { Assert.notNull(instanceSupplier, "InstanceSupplier must not be null"); return instanceSupplier; } }
/* * Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE.txt file for licensing information. */ package pl.edu.icm.unity.unicore.samlidp.preferences; import java.util.Collection; import java.util.Set; import eu.emi.security.authn.x509.impl.X500NameUtils; import pl.edu.icm.unity.saml.idp.preferences.SPSettingsEditor; import pl.edu.icm.unity.saml.idp.preferences.SamlPreferences.SPSettings; import pl.edu.icm.unity.server.utils.UnityMessageSource; import pl.edu.icm.unity.types.basic.AttributeType; import pl.edu.icm.unity.types.basic.Identity; import pl.edu.icm.unity.unicore.samlidp.preferences.SamlPreferencesWithETD.SPETDSettings; import pl.edu.icm.unity.unicore.samlidp.web.ETDSettingsEditor; import pl.edu.icm.unity.webui.common.attributes.AttributeHandlerRegistry; /** * Allows to edit settings for a single UNICORE SAML service provider. * Implementation wise it merges {@link SPSettingsEditor} with {@link ETDSettingsEditor} * * @author K. Benedyczak */ public class SPSettingsWithETDEditor extends SPSettingsEditor { private ETDSettingsEditor editor; public SPSettingsWithETDEditor(UnityMessageSource msg, AttributeHandlerRegistry attributeHandlerRegistries, Identity[] identities, Collection<AttributeType> atTypes, String sp, SPSettings initial, SPETDSettings initialETD) { super(msg, attributeHandlerRegistries, identities, atTypes, sp, initial); editor = new ETDSettingsEditor(msg, this); editor.setValues(initialETD); } public SPSettingsWithETDEditor(UnityMessageSource msg, AttributeHandlerRegistry attributeHandlerRegistries, Identity[] identities, Collection<AttributeType> atTypes, Set<String> allSps) { super(msg, attributeHandlerRegistries, identities, atTypes, allSps); editor = new ETDSettingsEditor(msg, this); } public SPETDSettings getSPETDSettings() { return editor.getSPETDSettings(); } /** * In UNICORE case the service provider should be given as DN. * Return comparable form if possible */ @Override public String getSP() { if (sp == null) return spLabel.getValue(); String spStr = (String) sp.getValue(); try { return X500NameUtils.getComparableForm(spStr); } catch (Exception e) { return spStr; } } }
package ru.hse.servers; import ru.hse.servers.protocol.message.Message; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.util.*; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; public class Client { private final int id; private final TestConfig config; private final CountDownLatch latch; private final CountDownLatch startLatch; private final Random random = new Random(); private final ExecutorService writeThread = Executors.newSingleThreadExecutor(); private final List<Task> tasks = new CopyOnWriteArrayList<>(); private List<Long> results = new ArrayList<>(); Client(int id, TestConfig config, CountDownLatch latch, CountDownLatch startLatch) { this.id = id; this.config = config; this.latch = latch; this.startLatch = startLatch; for (int i = 0; i < config.numberOfQueriesFromEachClient; i++) { tasks.add(new Task(i)); } } private Message generateMessage(int taskId) { List<Integer> list = new ArrayList<>(config.arraysSize); for (int i = 0; i < config.arraysSize; i++) { list.add(random.nextInt(2 * Constants.ARRAY_VALUES_ABS_MAX) - Constants.ARRAY_VALUES_ABS_MAX); } return Message.newBuilder().addAllArray(list).setTaskId(taskId).setClientId(id).build(); } public void run() throws Exception { try (SocketChannel channel = SocketChannel.open(new InetSocketAddress(Constants.HOST_IP, Constants.PORT))) { channel.configureBlocking(true); startLatch.await(); channel.write(ByteBuffer.allocate(4).putInt(config.numberOfQueriesFromEachClient).flip()); writeThread.submit(() -> { for (int i = 0; i < config.numberOfQueriesFromEachClient; i++) { Task task = tasks.get(i); task.startTask(); try { Utils.writeMessageToChannel(channel, task.message); } catch (IOException e) { throw new RuntimeException(e); } if (i + 1 != config.numberOfQueriesFromEachClient) { try { Thread.sleep(config.pauseBetweenQueries); } catch (InterruptedException e) { throw new RuntimeException(e); } } } }); for (int i = 0; i < config.numberOfQueriesFromEachClient; i++) { Message result = Utils.readMessageFromChannel(channel); //System.out.println("Client " + id + " read finished"); Task task = tasks.get(result.getTaskId()); task.endTask(); checkResult(result.getArrayList()); } } finally { writeThread.shutdownNow(); latch.countDown(); System.out.println("Client " + id + " finished"); } } private void checkResult(List<Integer> result) { if (result.size() != config.arraysSize) { throw new RuntimeException("Got invalid array size " + result.size() + ", expected " + config.arraysSize); } for (int i = 0; i < result.size() - 1; i++) { if (result.get(i) > result.get(i + 1)) throw new RuntimeException("Got unsorted array");; } } public void stop() { writeThread.shutdownNow(); } public List<Long> getResults() { return results; } private class Task { public final int taskId; public final Message message; public long start; public long end; public Task(int taskId) { this.taskId = taskId; message = generateMessage(taskId); } public void startTask() { start = System.currentTimeMillis(); } public void endTask() { end = System.currentTimeMillis(); results.add(end - start); System.out.println("Client " + id + " query finished in " + (end - start)); } } }
package ak.minigunquest.util; /** * Created by Aleksander on 20/03/2015. */ public class References { public static String gameName = "I'M LOST FOR WORDS"; }
package org.giddap.dreamfactory.leetcode.onlinejudge.implementations; import org.giddap.dreamfactory.leetcode.onlinejudge.LongestPalindromicSubstring; public class LongestPalindromicSubstringImpl implements LongestPalindromicSubstring { @Override public String longestPalindrome(String s) { String lps = ""; for (int i = 0; i < s.length(); i++) { String one = constructPalindrome(s, i, i); String two = constructPalindrome(s, i, i + 1); if (one.length() >= two.length()) { if (one.length() > lps.length()) { lps = one; } } else { if (two.length() > lps.length()) { lps = two; } } } return lps; } private String constructPalindrome(String s, int l, int r) { while (l >= 0 && r < s.length()) { if (s.charAt(l) != s.charAt(r)) { break; } l--; r++; } return s.substring(l + 1, r); } }
package com.jfronny.raut.modules; import com.jfronny.raut.api.BaseModule; import com.jfronny.raut.api.DepRegistry; import com.jfronny.raut.api.GenericPlant; import com.jfronny.raut.items.Crystal; import io.github.cottonmc.cotton.datapack.recipe.RecipeUtil; import net.fabricmc.fabric.api.blockrenderlayer.v1.BlockRenderLayerMap; import net.fabricmc.fabric.api.loot.v1.FabricLootPoolBuilder; import net.fabricmc.fabric.api.loot.v1.FabricLootSupplierBuilder; import net.fabricmc.fabric.api.loot.v1.event.LootTableLoadingCallback; import net.minecraft.client.render.RenderLayer; import net.minecraft.item.BlockItem; import net.minecraft.item.Item; import net.minecraft.loot.ConstantLootTableRange; import net.minecraft.loot.LootManager; import net.minecraft.loot.condition.RandomChanceLootCondition; import net.minecraft.loot.entry.ItemEntry; import net.minecraft.resource.ResourceManager; import net.minecraft.util.Identifier; import static com.jfronny.raut.RaUt.cfg; public class CrystalPlantModule extends BaseModule { public static final GenericPlant CRYSTAL_PLANT = new GenericPlant(); public static final BlockItem CRYSTAL_PLANT_SEED = CRYSTAL_PLANT.seed; public static final Item CRYSTAL = new Crystal(); @Override public void Init() { DepRegistry.registerBlock("crystal_plant", cfg.crystalPlant.enabled, CRYSTAL_PLANT, CRYSTAL_PLANT_SEED); DepRegistry.registerItem("crystal", cfg.crystalPlant.enabled, CRYSTAL); if (!cfg.crystalPlant.enabled || !cfg.crystalPlant.craftGApples) { RecipeUtil.removeRecipe("raut:crystal_apple"); } if (!cfg.crystalPlant.enabled || !cfg.crystalPlant.craftGApples2) { RecipeUtil.removeRecipe("raut:crystal_enchanted_apple"); } } @Override public void onLootTableLoading(ResourceManager resourceManager, LootManager lootManager, Identifier id, FabricLootSupplierBuilder supplier, LootTableLoadingCallback.LootTableSetter setter) { if ((id.equals(new Identifier("chests/abandoned_mineshaft")) || id.equals(new Identifier("chests/desert_pyramid")) || id.equals(new Identifier("chests/jungle_temple")))) { if (cfg.crystalPlant.enabled) { FabricLootPoolBuilder poolBuilder = FabricLootPoolBuilder .builder() .withRolls(ConstantLootTableRange.create(1)) .withCondition(RandomChanceLootCondition.builder(0.1f)) .withEntry(ItemEntry.builder(CRYSTAL)) .withEntry(ItemEntry.builder(CRYSTAL_PLANT_SEED)); supplier.withPool(poolBuilder); } } } @Override public void InitClient() { BlockRenderLayerMap.INSTANCE.putBlock(CRYSTAL_PLANT, RenderLayer.getCutout()); } }
package com.beike.dao.film.impl; import java.math.BigDecimal; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Calendar; import java.util.Date; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.simple.ParameterizedRowMapper; import org.springframework.stereotype.Repository; import com.beike.dao.GenericDaoImpl; import com.beike.dao.film.FilmDao; import com.beike.entity.film.Cinema; import com.beike.entity.film.FilmRelease; import com.beike.page.Pager; import com.beike.util.StringUtils; /** * @Title: 影院Dao实现 * @Package com.beike.dao.film.impl * @Description: * @author wenjie.mai * @date 2012-11-28 上午15:39:59 * @version V1.0 */ @Repository("filmDao") public class FilmDaoImpl extends GenericDaoImpl<Cinema, Long> implements FilmDao { private static Log log = LogFactory.getLog(FilmDaoImpl.class); @SuppressWarnings("rawtypes") @Override public List getFilmType() { StringBuilder typesql = new StringBuilder(); typesql.append("SELECT DISTINCT(film_sort),film_py FROM beiker_film_sort WHERE is_available = 1 "); List typelist = this.getJdbcTemplate().queryForList(typesql.toString()); return typelist; } @SuppressWarnings("rawtypes") @Override public List getFilmId(String film_py) { StringBuilder idsql = new StringBuilder(); idsql.append("SELECT DISTINCT(film_id) FROM beiker_film_sort WHERE is_available = 1 "); if (org.apache.commons.lang.StringUtils.isNotBlank(film_py)) { idsql.append(" AND film_py = '").append(film_py).append("' "); } List idlist = this.getJdbcTemplate().queryForList(idsql.toString()); return idlist; } @SuppressWarnings("rawtypes") @Override public int getFilmInfoCount(List<Long> filmids) { StringBuilder filmcountsql = new StringBuilder(); filmcountsql.append("SELECT film_id FROM beiker_film_release where is_available = 1 "); if (filmids != null && filmids.size() > 0) { filmcountsql.append(" AND film_id IN (").append(StringUtils.arrayToString(filmids.toArray(), ",")).append(") "); } List filmcountlist = this.getJdbcTemplate().queryForList(filmcountsql.toString()); if (filmcountlist == null || filmcountlist.size() == 0) return 0; return filmcountlist.size(); } @SuppressWarnings("rawtypes") @Override public List getFilmInfo(List<Long> filmids, int start, int end) { StringBuilder filmsql = new StringBuilder(); filmsql.append("SELECT film_id,film_name,duration,director,starring,small_photo,large_photo,sort,show_date,"); filmsql.append("area,type,description,lowest_price,grade,msg,url,trailer_des,is_available,upd_time "); filmsql.append("FROM beiker_film_release where is_available = 1 "); if (filmids != null && filmids.size() > 0) { filmsql.append(" AND film_id IN (").append(StringUtils.arrayToString(filmids.toArray(), ",")).append(") "); } filmsql.append(" ORDER BY grade DESC "); filmsql.append(" LIMIT ").append(start).append(",").append(end); List filmlist = this.getJdbcTemplate().queryForList(filmsql.toString()); return filmlist; } @SuppressWarnings("rawtypes") @Override public List getPopularFilmRank(int num) { StringBuilder popularsql = new StringBuilder(); popularsql.append("SELECT film_id,film_name,duration,director,starring,small_photo,large_photo,sort,"); popularsql.append("area,type,description,lowest_price,grade,msg,url,trailer_des,is_available,upd_time,show_date "); popularsql.append("FROM beiker_film_release where is_available = 1 "); popularsql.append("ORDER BY show_date DESC "); popularsql.append("LIMIT ").append(num); List filmlist = this.getJdbcTemplate().queryForList(popularsql.toString()); return filmlist; } @Override public int queryFilmReleaseCountByCinema(Long cityId, Long cinemaId) { String sql = "select count(*) from((select distinct fr.id from beiker_film_release fr right join beiker_film_show fs on fr.film_id = fs.film_id where fs.city_id = ? and fr.id is not null and fr.is_available = 1 and fs.cinema_id = ?) tmp )"; int result = getSimpleJdbcTemplate().queryForInt(sql,cityId, cinemaId); return result; } @Override public List<FilmRelease> queryFilmReleaseByCinema(Pager pager, Long cityId, Long cinemaId) { String sql = "select distinct fr.film_id,fr.film_name,fr.sort,fr.area,fr.director,fr.starring,fr.small_photo,fr.large_photo,fr.lowest_price,fr.grade from beiker_film_release fr right join beiker_film_show fs on fr.film_id = fs.film_id where fs.city_id =:cityId and fr.id is not null and fr.is_available = 1 and fs.cinema_id = :cinemaId order by fr.grade desc limit :startRow,:pageSize"; MapSqlParameterSource parameterSource = new MapSqlParameterSource(); parameterSource.addValue("cityId", cityId); parameterSource.addValue("cinemaId", cinemaId); parameterSource.addValue("startRow", pager.getStartRow()); parameterSource.addValue("pageSize", pager.getPageSize()); List<FilmRelease> result = getSimpleJdbcTemplate().query(sql, new ParameterizedRowMapper<FilmRelease>() { @Override public FilmRelease mapRow(ResultSet rs, int rowNum) throws SQLException { FilmRelease film = new FilmRelease(); film.setFilmId(rs.getLong("fr.film_id")); film.setFilmName(rs.getString("fr.film_name")); film.setSort(rs.getString("fr.sort")); film.setArea(rs.getString("fr.area")); film.setDirector(rs.getString("fr.director")); film.setStarring(rs.getString("fr.starring")); film.setSmallPhoto(rs.getString("fr.small_photo")); film.setLargePhoto(rs.getString("fr.large_photo")); film.setLowestPrice(rs.getBigDecimal("fr.lowest_price")); film.setGrade(rs.getBigDecimal("fr.grade")); return film; }}, parameterSource); return result; } @Override public int queryFilmReleaseCountCityId(Long cityId) { String sql = "select count(*) from((select distinct fr.id from beiker_film_release fr right join beiker_film_show fs on fr.film_id = fs.film_id where fr.id is not null and fr.is_available = 1 and fs.city_id = "+cityId+") tmp )"; int result = getSimpleJdbcTemplate().queryForInt(sql); return result; } @Override public List<FilmRelease> queryFilmReleaseCityId(Pager pager, Long cityId) { String sql = "select distinct fr.film_id,fr.film_name,fr.sort,fr.area,fr.director,fr.starring,fr.small_photo,fr.large_photo,fr.lowest_price,fr.grade from beiker_film_release fr right join beiker_film_show fs on fr.film_id = fs.film_id where fr.id is not null and fr.is_available = 1 and fs.city_id = "+cityId+" order by fr.grade desc limit :startRow,:pageSize"; MapSqlParameterSource parameterSource = new MapSqlParameterSource(); parameterSource.addValue("startRow", pager.getStartRow()); parameterSource.addValue("pageSize", pager.getPageSize()); List<FilmRelease> result = getSimpleJdbcTemplate().query(sql, new ParameterizedRowMapper<FilmRelease>() { @Override public FilmRelease mapRow(ResultSet rs, int rowNum) throws SQLException { FilmRelease film = new FilmRelease(); film.setFilmId(rs.getLong("fr.film_id")); film.setFilmName(rs.getString("fr.film_name")); film.setSort(rs.getString("fr.sort")); film.setArea(rs.getString("fr.area")); film.setDirector(rs.getString("fr.director")); film.setStarring(rs.getString("fr.starring")); film.setSmallPhoto(rs.getString("fr.small_photo")); film.setLargePhoto(rs.getString("fr.large_photo")); film.setLowestPrice(rs.getBigDecimal("fr.lowest_price")); film.setGrade(rs.getBigDecimal("fr.grade")); return film; }}, parameterSource); return result; } @SuppressWarnings("rawtypes") @Override public List getTuanGouFilmRank(Long tagextid, Long cityId, int num) { StringBuilder tgsql = new StringBuilder(); tgsql.append(" SELECT DISTINCT(bg.goodsid) FROM beiker_goods bg"); tgsql.append(" LEFT JOIN beiker_catlog_good bcd ON bg.goodsid = bcd.goodid"); tgsql.append(" LEFT JOIN beiker_goods_profile bgp ON bcd.goodid = bgp.goodsid"); tgsql.append(" WHERE bg.isavaliable = '1' AND bg.startTime<=NOW()"); tgsql.append(" AND bg.endTime>=NOW() AND bgp.sales_count < bg.maxcount"); tgsql.append(" AND bcd.area_id = ").append(cityId); tgsql.append(" AND bcd.tagextid = ").append(tagextid); tgsql.append(" ORDER BY bgp.sales_count DESC LIMIT ").append(num); List tglist = this.getJdbcTemplate().queryForList(tgsql.toString()); return tglist; } @SuppressWarnings("rawtypes") @Override public List getFilmLanguage(List<Long> filmids) { StringBuilder langsql = new StringBuilder(); langsql.append("SELECT DISTINCT(LANGUAGE),film_id FROM beiker_film_show WHERE is_available = 1 "); if (filmids != null && filmids.size() > 0) { langsql.append(" AND film_id IN (").append(StringUtils.arrayToString(filmids.toArray(), ",")).append(") "); langsql.append(" ORDER BY find_in_set(film_id,'").append(StringUtils.arrayToString(filmids.toArray(), ",")).append("') "); } List langlist = this.getJdbcTemplate().queryForList(langsql.toString()); return langlist; } @SuppressWarnings("rawtypes") @Override public List getCinemaIdByFilmId(Long filmId, String startTime, String endTime) { StringBuilder filmsql = new StringBuilder(); filmsql.append("SELECT DISTINCT(cinema_id) FROM beiker_film_show WHERE is_available = 1 "); filmsql.append("AND film_id = ").append(filmId).append(" AND show_time>= '").append(startTime).append("' "); filmsql.append("AND show_time<= '").append(endTime).append("' "); filmsql.append("ORDER BY show_time ASC"); List filmlist = this.getJdbcTemplate().queryForList(filmsql.toString()); return filmlist; } @SuppressWarnings("rawtypes") @Override public List getRegionIdByCity(Long cityId) { StringBuilder regionsql = new StringBuilder(); regionsql.append(" SELECT id,region_name,region_enname FROM beiker_region_property WHERE parentid = 0 "); regionsql.append(" AND areaid = ").append(cityId); regionsql.append(" ORDER BY id ASC "); List regionlist = this.getJdbcTemplate().queryForList(regionsql.toString()); return regionlist; } @SuppressWarnings("rawtypes") @Override public List getRegionByFilmCount(List<Long> cinemalist,Long cityId) { StringBuilder filmsql = new StringBuilder(); filmsql.append("SELECT DISTINCT(bci.dist_id),brp.region_name FROM beiker_cinema_info bci "); filmsql.append("LEFT JOIN beiker_wpw_cinema_map bwcp ON bci.cinema_id = bwcp.cinema_id "); filmsql.append("LEFT JOIN beiker_cinema bc ON bwcp.cinema_wpw_id = bc.cinema_id "); filmsql.append("LEFT JOIN beiker_region_property brp ON bci.dist_id = brp.id "); filmsql.append("WHERE bc.is_available = 1 AND cinema_status =0 AND brp.parentid = 0 "); filmsql.append("AND bc.city_id = ").append(cityId).append(" AND bci.city_id = ").append(cityId); if(cinemalist != null && cinemalist.size()>0){ filmsql.append(" AND bc.cinema_id IN (").append(StringUtils.arrayToString(cinemalist.toArray(),",")).append(") "); } List filmlist = this.getJdbcTemplate().queryForList(filmsql.toString()); return filmlist; } @SuppressWarnings("rawtypes") @Override public List getCinemaId(List<Long> cinemalist) { StringBuilder qpsql = new StringBuilder(); qpsql.append("SELECT bci.cinema_id,bg.goodsid,bg.currentPrice FROM beiker_cinema_info bci "); qpsql.append("LEFT JOIN beiker_goods_cinema bgc ON bci.cinema_id = bgc.cinema_id "); qpsql.append("LEFT JOIN beiker_goods bg ON bgc.goods_id = bg.goodsid "); qpsql.append("WHERE bg.isavaliable = '1' AND bg.startTime<=NOW() AND bg.endTime>=NOW() "); if (cinemalist != null && cinemalist.size() > 0) { qpsql.append(" AND bci.cinema_id IN (").append(StringUtils.arrayToString(cinemalist.toArray(), ",")).append(") "); } qpsql.append(" ORDER BY bg.currentPrice DESC "); List goodlist = this.getJdbcTemplate().queryForList(qpsql.toString()); return goodlist; } @SuppressWarnings("rawtypes") @Override public List getGoodsIdByCityId(Long cityId, List<Long> idlist) { StringBuilder goodsql = new StringBuilder(); goodsql.append("SELECT bci.cinema_id,SUM(bgp.sales_count) AS totalcount,bci.name,bg.goodsid,bci.address,bci.coord,bci.photo FROM beiker_cinema_info bci "); goodsql.append("LEFT JOIN beiker_goods_cinema bgc ON bci.cinema_id = bgc.cinema_id "); goodsql.append("LEFT JOIN beiker_goods bg ON bgc.goods_id = bg.goodsid "); goodsql.append("LEFT JOIN beiker_goods_profile bgp ON bg.goodsid = bgp.goodsid "); goodsql.append("WHERE bg.isavaliable = '1' AND bg.startTime<=NOW() AND bg.endTime>=NOW() "); goodsql.append("AND bgp.sales_count < bg.maxcount AND bci.city_id = ").append(cityId); if (idlist != null && idlist.size() > 0) { goodsql.append(" AND bci.cinema_id IN (").append(StringUtils.arrayToString(idlist.toArray(), ",")).append(") "); } goodsql.append(" GROUP BY bci.cinema_id "); goodsql.append(" ORDER BY totalcount DESC "); List goodlist = this.getJdbcTemplate().queryForList(goodsql.toString()); return goodlist; } @SuppressWarnings("rawtypes") @Override public List getCinemaInfoById(List<Long> cinemalist) { StringBuilder csql = new StringBuilder(); csql.append("SELECT cinema_id,NAME,address FROM beiker_cinema_info where 1=1 "); if (cinemalist != null && cinemalist.size() > 0) { csql.append(" AND cinema_id IN (").append(StringUtils.arrayToString(cinemalist.toArray(), ",")).append(") "); } List li = this.getJdbcTemplate().queryForList(cinemalist.toString()); return li; } @SuppressWarnings("rawtypes") @Override public List getFilmLanguageById(Long filmId) { StringBuilder langsql = new StringBuilder(); langsql.append(" SELECT DISTINCT(LANGUAGE),film_id FROM beiker_film_show WHERE is_available = 1 "); langsql.append(" AND film_id = ").append(filmId); List langlist = this.getJdbcTemplate().queryForList(langsql.toString()); return langlist; } @SuppressWarnings("rawtypes") @Override public List getFilmInfoById(Long filmId) { StringBuilder filmsql = new StringBuilder(); filmsql.append("SELECT film_id,film_name,duration,director,starring,small_photo,large_photo,sort,show_date,"); filmsql.append("area,type,description,lowest_price,grade,msg,url,trailer_des,is_available,upd_time "); filmsql.append("FROM beiker_film_release where is_available = 1 "); filmsql.append("AND film_id = ").append(filmId); filmsql.append(" LIMIT 1"); List filmlist = this.getJdbcTemplate().queryForList(filmsql.toString()); return filmlist; } @SuppressWarnings("rawtypes") @Override public List getCinemaInfo(List<Long> cidlist, int start, int end,Long cityId,Long filmId) { StringBuilder csql = new StringBuilder(); csql.append("SELECT bci.cinema_id pid,bci.photo,bci.name,bci.address,"); csql.append("bci.coord,bci.tel,bc.type,bc.cinema_id wid,MIN(bfs.v_price) vprice FROM beiker_cinema_info bci "); csql.append("LEFT JOIN beiker_wpw_cinema_map bwcp ON bci.cinema_id = bwcp.cinema_id "); csql.append("LEFT JOIN beiker_cinema bc ON bwcp.cinema_wpw_id = bc.cinema_id "); csql.append("LEFT JOIN beiker_film_show bfs ON bc.cinema_id = bfs.cinema_id "); csql.append("AND bci.city_id = ").append(cityId).append(" AND bc.city_id = ").append(cityId); csql.append(" WHERE bc.is_available = 1 AND bci.cinema_status = 0 AND bfs.show_time >= NOW() "); csql.append(" AND bfs.film_id = ").append(filmId); if (cidlist != null && cidlist.size() > 0) { csql.append(" AND bci.cinema_id IN (").append(StringUtils.arrayToString(cidlist.toArray(), ",")).append(") "); } csql.append(" GROUP BY bci.cinema_id "); csql.append(" LIMIT ").append(start).append(",").append(end); List filmlist = this.getJdbcTemplate().queryForList(csql.toString()); return filmlist; } @SuppressWarnings("rawtypes") @Override public List getCinemaInfoIdByCity(Long cityId, String flag, List<Long> notidlist) { StringBuilder cisql = new StringBuilder(); cisql.append(" SELECT DISTINCT(bci.cinema_id) FROM beiker_cinema_info bci"); cisql.append(" JOIN beiker_wpw_cinema_map bwcm ON bci.cinema_id = bwcm.cinema_id"); cisql.append(" JOIN beiker_cinema bc ON bwcm.cinema_wpw_id = bc.cinema_id"); cisql.append(" WHERE bci.cinema_status = 0 AND bc.is_available = 1"); cisql.append(" AND bc.city_id = ").append(cityId).append(" AND bci.city_id = ").append(cityId); if (flag.equals("0")) { cisql.append(" AND bc.type IN (1,3) "); } if (notidlist != null && notidlist.size() > 0) { cisql.append(" AND bci.cinema_id NOT IN(").append(StringUtils.arrayToString(notidlist.toArray(), ",")).append(") "); } List cilist = this.getJdbcTemplate().queryForList(cisql.toString()); return cilist; } @SuppressWarnings("rawtypes") @Override public List getPopularFilmByGrade(int num) { StringBuilder popularsql = new StringBuilder(); popularsql.append("SELECT film_id,film_name,duration,director,starring,small_photo,large_photo,sort,"); popularsql.append("area,type,description,lowest_price,grade,msg,url,trailer_des,is_available,upd_time,show_date "); popularsql.append("FROM beiker_film_release where is_available = 1 "); popularsql.append("ORDER BY grade DESC "); popularsql.append("LIMIT ").append(num); List filmlist = this.getJdbcTemplate().queryForList(popularsql.toString()); return filmlist; } @SuppressWarnings("rawtypes") @Override public List getCinemaInfoIdByCinemaId(List<Long> cidlist,Long cityId) { StringBuilder str = new StringBuilder(); str.append("SELECT bci.cinema_id qid,bc.cinema_id wid FROM beiker_cinema_info bci "); str.append("JOIN beiker_wpw_cinema_map bwcm ON bci.cinema_id = bwcm.cinema_id "); str.append("JOIN beiker_cinema bc ON bwcm.cinema_wpw_id = bc.cinema_id "); str.append("WHERE bci.cinema_status = 0 AND bc.is_available = 1 "); str.append("AND bci.city_id = ").append(cityId).append(" AND bc.city_id = ").append(cityId); if(cidlist != null && cidlist.size() > 0){ str.append(" AND bc.cinema_id IN (").append(StringUtils.arrayToString(cidlist.toArray(),",")).append(") "); } List li = this.getJdbcTemplate().queryForList(str.toString()); return li; } @SuppressWarnings("rawtypes") @Override public List getCinemaPriceById(List<Long> cidlist,Long filmId) { StringBuilder pricesql = new StringBuilder(); pricesql.append("SELECT DISTINCT(cinema_id),v_price FROM beiker_film_show WHERE is_available = 1 "); pricesql.append(" AND film_id = ").append(filmId); if(cidlist != null && cidlist.size() > 0){ pricesql.append(" AND cinema_id IN (").append(StringUtils.arrayToString(cidlist.toArray(),",")).append(") "); } pricesql.append(" ORDER BY v_price DESC "); List pricelist = this.getJdbcTemplate().queryForList(pricesql.toString()); return pricelist; } @SuppressWarnings("rawtypes") @Override public List getCinemaList(List<Long> cidlist, int start, int end,Long cityId,Long regionId,Long filmId) { StringBuilder csql = new StringBuilder(); csql.append("SELECT bci.cinema_id pid,bci.photo,bci.name,bci.address,"); csql.append("bci.coord,bci.tel,bc.type,bc.cinema_id wid,bci.dist_id,MIN(bfs.v_price) vprice FROM beiker_cinema_info bci "); csql.append("LEFT JOIN beiker_wpw_cinema_map bwcp ON bci.cinema_id = bwcp.cinema_id "); csql.append("LEFT JOIN beiker_cinema bc ON bwcp.cinema_wpw_id = bc.cinema_id "); csql.append("LEFT JOIN beiker_film_show bfs ON bc.cinema_id = bfs.cinema_id "); csql.append("WHERE bc.is_available = 1 AND bci.cinema_status = 0 AND bfs.show_time >= NOW() "); csql.append(" AND bfs.film_id = ").append(filmId); if(cityId != null && cityId > 0){ csql.append(" AND bc.city_id = ").append(cityId).append(" AND bci.city_id = ").append(cityId); } if(regionId != null && regionId > 0){ csql.append(" AND bc.dist_id = ").append(regionId); } if(cidlist != null && cidlist.size()>0){ csql.append(" AND bc.cinema_id IN (").append(StringUtils.arrayToString(cidlist.toArray(),",")).append(") "); } csql.append(" GROUP BY bci.cinema_id "); csql.append(" LIMIT ").append(start).append(",").append(end); List filmlist = this.getJdbcTemplate().queryForList(csql.toString()); return filmlist; } @SuppressWarnings("rawtypes") @Override public List getFilmShowlist(Long filmId, Long cinemaId, String startTime,String endTime) { StringBuilder str = new StringBuilder(); str.append("SELECT show_time,show_index,LANGUAGE,dimensional,hall_name,v_price FROM beiker_film_show WHERE is_available =1 "); str.append(" AND cinema_id = ").append(cinemaId); str.append(" AND film_id = ").append(filmId).append(" AND show_time >= NOW() "); str.append(" AND show_time >= '").append(startTime).append("' AND show_time <= '").append(endTime).append("' "); str.append(" ORDER BY show_time ASC "); List showlist = this.getJdbcTemplate().queryForList(str.toString()); return showlist; } @SuppressWarnings("rawtypes") @Override public List getCinemaIdByCid(Long cinemaId) { StringBuilder idsql = new StringBuilder(); idsql.append("SELECT bci.cinema_id qid,bc.cinema_id wid FROM beiker_cinema_info bci "); idsql.append("LEFT JOIN beiker_wpw_cinema_map bwcp ON bci.cinema_id = bwcp.cinema_id "); idsql.append("LEFT JOIN beiker_cinema bc ON bwcp.cinema_wpw_id = bc.cinema_id "); idsql.append("WHERE bci.cinema_id = ").append(cinemaId); idsql.append(" LIMIT 1 "); List li = this.getJdbcTemplate().queryForList(idsql.toString()); return li; } @SuppressWarnings("rawtypes") @Override public List getCinemaFormList(List<Long> cidlist,Long cityId) { StringBuilder str = new StringBuilder(); str.append("SELECT bci.cinema_id pid,bci.photo,bci.name,bci.address,"); str.append("bci.coord,bci.tel,bc.type,bc.cinema_id wid FROM beiker_cinema_info bci "); str.append("LEFT JOIN beiker_wpw_cinema_map bwcp ON bci.cinema_id = bwcp.cinema_id "); str.append("LEFT JOIN beiker_cinema bc ON bwcp.cinema_wpw_id = bc.cinema_id "); str.append("WHERE bci.cinema_status = 0 AND bc.is_available = 1 "); str.append("bci.city_id = ").append(cityId).append(" AND bc.city_id = ").append(cityId); if(cidlist != null && cidlist.size() >0){ str.append(" AND bci.cinema_id IN (").append(StringUtils.arrayToString(cidlist.toArray(),",")).append(") "); } List li = this.getJdbcTemplate().queryForList(str.toString()); return li; } @SuppressWarnings("rawtypes") @Override public int getCinemaListCount(List<Long> cidlist,Long cityId,Long regionId,Long filmId) { StringBuilder csql = new StringBuilder(); csql.append("SELECT bci.cinema_id pid,bci.photo,bci.name,bci.address,"); csql.append("bci.coord,bci.tel,bc.type,bc.cinema_id wid FROM beiker_cinema_info bci "); csql.append("LEFT JOIN beiker_wpw_cinema_map bwcp ON bci.cinema_id = bwcp.cinema_id "); csql.append("LEFT JOIN beiker_cinema bc ON bwcp.cinema_wpw_id = bc.cinema_id "); csql.append("LEFT JOIN beiker_film_show bfs ON bc.cinema_id = bfs.cinema_id "); csql.append("WHERE bc.is_available = 1 AND bci.cinema_status = 0 AND bfs.show_time >= NOW() "); csql.append("AND bfs.film_id = ").append(filmId); if(cityId != null && cityId > 0){ csql.append(" AND bc.city_id = ").append(cityId).append(" AND bci.city_id = ").append(cityId); } if(regionId != null && regionId > 0){ csql.append(" AND bc.dist_id = ").append(regionId); } if(cidlist != null && cidlist.size()>0){ csql.append(" AND bc.cinema_id IN (").append(StringUtils.arrayToString(cidlist.toArray(),",")).append(") "); } csql.append(" GROUP BY bci.cinema_id "); List filmlist = this.getJdbcTemplate().queryForList(csql.toString()); if(filmlist == null || filmlist.size() == 0 ) return 0; return filmlist.size(); } @SuppressWarnings("rawtypes") @Override public List getCinemaInfoList(Long cityId, List<Long> idlist,int num) { StringBuilder cisql = new StringBuilder(); cisql.append(" SELECT distinct(bci.cinema_id),bci.name,bci.address,bci.coord,bci.photo FROM beiker_cinema_info bci"); cisql.append(" JOIN beiker_wpw_cinema_map bwcm ON bci.cinema_id = bwcm.cinema_id"); cisql.append(" JOIN beiker_cinema bc ON bwcm.cinema_wpw_id = bc.cinema_id"); cisql.append(" WHERE bci.cinema_status = 0 AND bc.is_available = 1"); cisql.append(" AND bc.city_id = ").append(cityId).append(" AND bci.city_id = ").append(cityId); if (idlist != null && idlist.size() > 0) { cisql.append(" AND bci.cinema_id IN(").append(StringUtils.arrayToString(idlist.toArray(), ",")).append(") "); } cisql.append(" LIMIT ").append(num); List cilist = this.getJdbcTemplate().queryForList(cisql.toString()); return cilist; } @Override public BigDecimal getLowestPriceByFilm(Long cityId, Long cinemaId, Long filmId) { // 只查询最近三天的放映计划 Date now = new Date(); Calendar threeDaysAfter = Calendar.getInstance(); threeDaysAfter.set(Calendar.DATE, threeDaysAfter.get(Calendar.DATE) + 3); String sql = "select min(v_price) from beiker_film_show where show_time >= :showTimeStart and is_available = 1 and status = 1 and city_id = :cityId and cinema_id = :cinemaId and film_id = :filmId"; MapSqlParameterSource parameterSource = new MapSqlParameterSource(); parameterSource.addValue("showTimeStart", now); parameterSource.addValue("cityId", cityId); parameterSource.addValue("cinemaId", cinemaId); parameterSource.addValue("filmId", filmId); BigDecimal result = getSimpleJdbcTemplate().queryForObject(sql, BigDecimal.class, parameterSource); return result; } }
package wifi; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; /** * This class acts as a thin layer between the GUI client code and the Java-based * 802.11~ layer. (There's a similar layer that mediates between the Java GUI code * and a C++ implementation of the 802.11~ project.) See {@link GUIClientInterface} * for full descriptions of these routines. * * @author richards */ public class JavaGUIAdapter implements GUIClientInterface { private static Dot11Interface theDot11Layer; private static CircularByteBuffer cbb; private static BufferedReader reader; /** * An array of addresses to use for the "send" buttons in the GUI. * @return An array of MAC addresses assigned to buttons by the GUI. */ public short[] getDefaultAddrs() { short[] temp = {101, 201, 301, 401, 501, 601, 701, 801, 901}; return temp; } /** * Create an instance of the 802.11~ layer. It wraps a PrintWriter around a * BufferedReader that's wrapped around a CircularByteBuffer (whew!) so that * we can read the text that the 802.11~ layer writes to the stream and * display it in the GUI's window. * * @param MACaddr The MAC address passed to the 802.11~ constructor. * @return Returns 0 on success, -1 if an error occurs. */ public int initializeLinkLayer(short MACaddr) { try { cbb = new CircularByteBuffer(CircularByteBuffer.INFINITE_SIZE); reader = new BufferedReader(new InputStreamReader(cbb.getInputStream())); theDot11Layer = new LinkLayer(MACaddr, new PrintWriter(cbb.getOutputStream(), true)); } catch (Exception e) { // TODO Auto-generated catch block return -1; } return 0; } /** * This method calls the 802.11~ layer's recv() method, which should block until * data arrives. It then builds an array of bytes consisting of the the sender's * MAC address followed by the data from the recv() call. (This may seem odd, but * the approach is easy to support on both the C++ and Java side.) * @return An array of bytes containing MAC addresses and data */ public byte[] watchForIncomingData() { // Create a Transmission object, and pass it to the recv() call byte[] buf = new byte[2048]; Transmission t = new Transmission((short)0, (short)0, buf); int result = theDot11Layer.recv(t); // See if there was any data in the transmission int dataLen = 0; if (result > 0) dataLen = result; // Build a byte array, fill it with the source address and data, // and return the whole shebang. byte[] data = new byte[dataLen + 2]; data[0] = (byte) ((t.getSourceAddr() >>> 8) & 0xFF); data[1] = (byte) (t.getSourceAddr() & 0xFF); System.arraycopy(t.getBuf(), 0, data, 2, dataLen); return data; } /** * Wrapper around the 802.11~ layer's send routine. * @param dest The destination MAC address * @param payload The data to send * @return Returns the value returned by the linklayer's <code>send()</code> method. */ public int sendOutgoingData(short dest, byte[] payload) { return theDot11Layer.send(dest, payload, payload.length); } /** * This routine pulls text from the stream to which the 802.11~ layer is writing * and returns any new text as an array of bytes. * @return An array of bytes representing characters sent to output stream since last call. */ public byte[] pollForStreamOutput() { String msg = ""; try { while (reader.ready()) msg += reader.readLine() + "\n"; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return msg.getBytes(); } /** * The GUI calls this when the user asks to pass command info to the 802.11~ layer. * @param command Specifies the command to send * @param value The value passed with the command * @return Returns the value returned by the linklayer's <code>command()</code> method. */ public int sendCommand(int command, int value) { return theDot11Layer.command(command, value); } }
package a_Zadanie_3; import java.util.InputMismatchException; import java.util.Scanner; public class Main3 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); guess(scan); scan.close(); } static void guess(Scanner scan) { int min = 0, max = 1000; int tries = 0; while (true) { int guess = ((max - min) / 2) + min; System.out.println("Zgaduję: " + guess); int usersAnswer = didHeGuess(scan); if (usersAnswer == 1) { System.out.println("Za mało!"); min = guess; tries++; } else if (usersAnswer == 2) { System.out.println("Za dużo!"); max = guess; tries++; } else if (usersAnswer == 3) { System.out.println("Wygrałem!"); tries++; break; } } System.out.println("Zadłem w " + tries + " próbach :)"); } static int didHeGuess(Scanner scan) { System.out.println("Wpisz do konsoli: "); System.out.println("1 aby powiedzieć \"Za mało!\", 2 aby powiedzieć \"Za dużo!\" oraz 3 dla \"Zgadłeś!\""); int n0 = 0; while (true) { try { int n = scan.nextInt(); if (n <= 3 && n > 0) { n0 = n; break; } else { System.out.println("Wprowadź poprawną wartość."); } } catch (InputMismatchException e) { System.out.println("Wprowadzona wartość musi być liczbą."); scan.nextLine(); } } return n0; } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.tfar.beans; /** * * @author hatem */ import com.tfar.entity.Cousin; import com.tfar.entity.Cytogenetique; import com.tfar.entity.Androgene; import com.tfar.services.FicheService; import com.tfar.services.PatientService; import com.tfar.services.HopitalService; import com.tfar.services.ServiceService; import com.tfar.services.MedecinService; import com.tfar.entity.Fiche; import com.tfar.entity.Frere; import com.tfar.entity.CousinPK; import com.tfar.entity.FrerePK; import com.tfar.entity.Patient; import com.tfar.entity.Hopitale; import com.tfar.entity.Service; import com.tfar.entity.Medecin; import com.tfar.entity.Membre; import com.tfar.entity.MembrePK; import com.tfar.services.CousinService; import com.tfar.services.CytogenetiqueService; import com.tfar.services.AndrogeneService; import com.tfar.services.FrereService; import com.tfar.services.MembreService; import com.tfar.entity.CytogenetiquePK; import com.tfar.entity.AndrogenePK; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; import java.util.Map; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.SessionScoped; import javax.faces.context.FacesContext; import javax.faces.event.ValueChangeEvent; import org.primefaces.context.RequestContext; /** * * @author Asus */ @ManagedBean (name="ModifierFicheBean") @SessionScoped public class ModifierFicheMBean implements Serializable { //inject spring bean via DI @ManagedProperty("#{HopitalService}") private HopitalService hopitalService; public String getMedecin() { return medecin; } public void setMedecin(String medecin) { this.medecin = medecin; } public String getNomMedecin() { System.out.println("Nom Medecin : " + medecinService.getMedecinParCIN(Integer.valueOf(newfiche.getMedecin())).getNomMedecin()); return medecinService.getMedecinParCIN(Integer.valueOf(newfiche.getMedecin())).getNomMedecin(); } @ManagedProperty("#{ServiceService}") private ServiceService serviceService; @ManagedProperty("#{MedecinService}") private MedecinService medecinService; @ManagedProperty("#{FicheService}") private FicheService ficheService; @ManagedProperty("#{PatientService}") private PatientService patientService; @ManagedProperty("#{CytogenetiqueService}") private CytogenetiqueService cytogenetiqueService; @ManagedProperty("#{AndrogeneService}") private AndrogeneService androgeneService; @ManagedProperty("#{FrereService}") private FrereService frereService; @ManagedProperty("#{CousinService}") private CousinService cousinService; public String hopital; public String service; public String medecin; public CousinService getCousinService() { return cousinService; } public void setCousinService(CousinService cousinService) { this.cousinService = cousinService; } public FrereService getFrereService() { return frereService; } public void setFrereService(FrereService frereService) { this.frereService = frereService; } public MembreService getMembreService() { return membreService; } public void setMembreService(MembreService membreService) { this.membreService = membreService; } @ManagedProperty("#{MembreService}") private MembreService membreService; public String data = "1"; public int nbFreres = 0; public int nbFreresUpdate=0; public int nbCousins = 0 ; public int nbCousinsUpdate = 0 ; public int nbMembres = 0 ; public int nbMembresUpdate = 0 ; public int nbCytogenetiques = 0; public int nbAndrogenes = 0; public CytogenetiqueService getCytogenetiqueService() { return cytogenetiqueService; } public void setCytogenetiqueService(CytogenetiqueService cytogenetiqueService) { this.cytogenetiqueService = cytogenetiqueService; } private Fiche newfiche = new Fiche(); private Fiche fiche = new Fiche(); public String getData() { return data; } public void setData(String data) { this.data = data; } public Fiche getFiche() { return fiche; } public void setFiche(Fiche fiche) { this.fiche = fiche; } private Patient newpatient = new Patient(); public List<String> values = new ArrayList(); public List<Frere> freres = new ArrayList(); public List<Cytogenetique> cytogenetiques = new ArrayList(); public List<Androgene> androgenes = new ArrayList(); public List<Cousin> cousins = new ArrayList(); public List<Membre> membres = new ArrayList(); public int getNbMembres() { return nbMembres; } public void setNbMembres(int nbMembres) { this.nbMembres = nbMembres; } public List<Membre> getMembres() { return membres; } public void setMembres(List<Membre> membres) { this.membres = membres; } public int getNbFreres() { return nbFreres; } public void setNbFreres(int nbFreres) { this.nbFreres = nbFreres; } public int getNbCousins() { return nbCousins; } public void setNbCousins(int nbCousins) { this.nbCousins = nbCousins; } public List<Cousin> getCousins() { return cousins; } public void setCousins(List<Cousin> cousins) { this.cousins = cousins; } public List<Cytogenetique> getCytogenetiques() { return cytogenetiques; } public void setCytogenetiques(List<Cytogenetique> cytogenetiques) { this.cytogenetiques = cytogenetiques; } public List<Androgene> getAndrogenes() { return androgenes; } public void setAndrogenes(List<Androgene> androgenes) { this.androgenes = androgenes; } public List<Frere> getFreres() { return freres; } public void setFreres(List<Frere> freres) { this.freres = freres; } public List<String> getValues() { return values; } public void setValues(List<String> values) { this.values = values; } public PatientService getPatientService() { return patientService; } public void setPatientService(PatientService patientService) { this.patientService = patientService; } public Patient getNewpatient() { return newpatient; } public void setNewpatient(Patient newpatient) { this.newpatient = newpatient; } private List <Hopitale> ListHopitals; public void setListHopitals(List<Hopitale> ListHopitals) { this.ListHopitals = ListHopitals; } public void setListServices(List<Service> ListServices) { this.ListServices = ListServices; } public void setListMedecins(List<Medecin> ListMedecins) { this.ListMedecins = ListMedecins; } private List <Service> ListServices; private List <Medecin> ListMedecins; public List <Hopitale> getListHopitals() { return ListHopitals = hopitalService.getAllHopital(); } public List <Service> getListServices () { return ListServices=serviceService.getAllService(); } public List <Medecin> getListMedecins () { return ListMedecins=medecinService.getAllMedecin(); } public String update() { System.out.println("File " +newfiche.getNDossier()+ " starting update."); //hopitalService.add(newhopital); //serviceService.add(newservice, newhopital); //medecinService.add(newmedecin, newservice); // newfiche.setMedecin(String.valueOf(medecinService.getMedecinParNom(newfiche.getMedecin()).getCin())); newfiche.setMedecin(medecinService.getMedecinParNom(medecin).getCin().toString()); ficheService.update(newfiche); patientService.update(newpatient); System.out.println("Freres : "+freres.toString()); System.out.println("File " +newfiche.getNDossier()+ " successfully saved."); FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Enregistrement de la fiche", "Enregistrée avec succès."); RequestContext.getCurrentInstance().showMessageInDialog(message); //newhopital = new Hopital(); //newservice = new Service(); //newmedecin = new Medecin(); return "Welcome?faces-redirect=true"; } public void treatnbfrere() { int nbTraitement = 0; System.out.println("......treatnbfrere ..."); //freres = frereService.getListFrereParnDossier(newfiche.getNDossier()); this.nbFreresUpdate = (this.newfiche.getNbVivant() + newfiche.getNbMort()) - this.nbFreres; System.out.println("......nbFreresUpdate = " + nbFreresUpdate); if (this.nbFreres < this.newfiche.getNbVivant() + newfiche.getNbMort()) if (freres ==null) { freres = new ArrayList<Frere>(); System.out.println("......Traitement : freres = new ArrayList(); ..."); nbTraitement = this.newfiche.getNbVivant() + newfiche.getNbMort(); } else nbTraitement = (this.newfiche.getNbVivant()+this.newfiche.getNbMort()) - this.nbFreres; for (int i = 0; i < nbTraitement; i++) { System.out.println("Adding frere"+i); Frere f = new Frere(); //f.setPrenomfrere("Test "+i); freres.add(f); } System.out.println("updatenbvivant : Nombre vivant : " + String.valueOf(this.newfiche.getNbVivant())); } public void treatnbCousin() { System.out.println("Modifier Fiche - Treat Cousins"); cousins = cousinService.getListCousinParnDossier(newfiche.getNDossier()); System.out.println("Modifier Fiche - Treat Cousins for update"); int nbTraitement = 0; System.out.println("......treatnbCousin ..."); this.nbCousinsUpdate = this.newfiche.getCousin() - this.nbCousins; System.out.println("......nbCousinsUpdate = " + nbCousinsUpdate); if (this.nbCousinsUpdate > 0) if (cousins ==null) cousins = new ArrayList<Cousin>(); System.out.println("......Traitement : cousins = new ArrayList(); ..."); nbTraitement = this.newfiche.getCousin(); for (int i = 0; i < this.nbCousinsUpdate; i++) { System.out.println("Adding frere"+i); Cousin c = new Cousin(); cousins.add(c); } System.out.println("Update cousins : " + String.valueOf(this.nbCousinsUpdate)); } public void treatnbMembre() { System.out.println("Modifier Fiche - Treat Membres"); membres = membreService.getListMembreParnDossier(newfiche.getNDossier()); System.out.println("Modifier Fiche - Treat membres for update"); int nbTraitement = 0; System.out.println("......treatnbMembre ..."); this.nbMembresUpdate = this.newfiche.getMembre() - this.nbMembres; System.out.println("......nbMembresUpdate = " + nbMembresUpdate); if (this.nbMembresUpdate > 0) if (membres ==null) membres = new ArrayList<Membre>(); System.out.println("......Traitement : membre = new ArrayList(); ..."); nbTraitement = this.newfiche.getMembre(); for (int i = 0; i < this.nbMembresUpdate; i++) { System.out.println("Adding Membre"+i); Membre c = new Membre(); membres.add(c); } System.out.println("Update Membres : " + String.valueOf(this.nbMembresUpdate)); } public int validfreres() { if (!freres.isEmpty()) { ListIterator<Frere> lf = freres.listIterator(); int i=0; System.out.println("Nombre FRERES : "+ freres.size()); System.out.println("FRERES : "+freres.toString()); while(lf.hasNext()){ Frere f = lf.next(); System.out.println("nbFreres "+this.nbFreres); if (i< this.nbFreres ) { FrerePK fpk = new FrerePK(this.newfiche.getnDossier(),f.getPlacefratrie()); f.setFrerePK(fpk); frereService.update(f); System.out.println("Update frere "+f.getPrenomfrere()); } else { System.out.println("Num Dossier :"+this.newfiche.getnDossier()); System.out.println("Place Fraterie :"+f.getPlacefratrie()); System.out.println("Before Adding frere "+f.getPrenomfrere()); FrerePK fpk = new FrerePK(this.newfiche.getnDossier(),f.getPlacefratrie()); f.setFrerePK(fpk); frereService.add(f); System.out.println("Add frere "+f.getPrenomfrere()); } i++; } this.nbFreres = this.newfiche.getNbVivant() + newfiche.getNbMort(); System.out.println("MAJ nb frere "+this.nbFreres); } RequestContext.getCurrentInstance().closeDialog(null); return 0; } public void validcousins(){ if (!cousins.isEmpty()) { ListIterator<Cousin> lc = cousins.listIterator(); int i=0; System.out.println("Nombre Cousins : "+ cousins.size()); System.out.println("COUSINS : "+cousins.toString()); while(lc.hasNext()){ Cousin c = lc.next(); System.out.println("nbCousins "+this.nbCousins); if (i< this.nbCousins ) { CousinPK cpk = new CousinPK(this.newfiche.getnDossier(),c.getCousinPK().getIdCousin()); c.setCousinPK(cpk); cousinService.update(c); System.out.println("Update cousin "+c.getPrenomCousin()); } else { System.out.println("Num Dossier :"+this.newfiche.getnDossier()); System.out.println("Place Cousin :"+c.getPlaceCousin()); System.out.println("Before Adding cousin "+c.getPrenomCousin()); CousinPK cpk = new CousinPK(this.newfiche.getnDossier(),i); c.setCousinPK(cpk); cousinService.add(c); System.out.println("Add cousin "+c.getPrenomCousin()); } i++; } } RequestContext.getCurrentInstance().closeDialog(null); } public void validMembres() { if (!membres.isEmpty()) { ListIterator<Membre> lc = membres.listIterator(); int i=0; System.out.println("Nombre Membre : "+ membres.size()); System.out.println("membres : "+membres.toString()); while(lc.hasNext()){ Membre c = lc.next(); System.out.println("nbMembres "+this.nbMembres); if (i< this.nbMembres ) { MembrePK cpk = new MembrePK(this.newfiche.getnDossier(),c.getMembrePK().getIdMembre()); c.setMembrePK(cpk); membreService.update(c); System.out.println("Update membre "+c.getPrenomM()); } else { System.out.println("Num Dossier :"+this.newfiche.getnDossier()); // System.out.println("Place Membre :"+c.getMembrePK().getIdMembre()); MembrePK cpk = new MembrePK(this.newfiche.getnDossier(),i); c.setMembrePK(cpk); membreService.add(c); System.out.println("Add Membre "+c.getPrenomM()); } i++; } } RequestContext.getCurrentInstance().closeDialog(null); } public int validCytogenetique() { if (!cytogenetiques.isEmpty()) { ListIterator<Cytogenetique> lc = cytogenetiques.listIterator(); int i=0; System.out.println("Nombre cytogenetiques : "+ cytogenetiques.size()); System.out.println("cytogenetiques : "+cytogenetiques.toString()); while(lc.hasNext()){ Cytogenetique c = lc.next(); System.out.println("nbCytogenetiques "+this.nbCytogenetiques); if (i< this.nbCytogenetiques ) { CytogenetiquePK cpk = new CytogenetiquePK(this.newfiche.getnDossier(),i+1); c.setCytogenetiquePK(cpk); cytogenetiqueService.update(c); System.out.println("Update Cytogenetique "+c.getCytogenetiquePK().getNEtudeCyto()); } else { System.out.println("Nouvelles données cytogénétiques"); CytogenetiquePK cpk = new CytogenetiquePK(this.newfiche.getnDossier(),i+1); c.setCytogenetiquePK(cpk); cytogenetiqueService.add(c); System.out.println("Add cytogenetique "+c.getCytogenetiquePK().toString()); } i++; } this.nbCytogenetiques = cytogenetiques.size() ; System.out.println("MAJ nb cytogenetique "+this.nbCytogenetiques); } RequestContext.getCurrentInstance().closeDialog(null); return 0; } public void treatAndrogene() { int i; for (i=0; i<this.nbAndrogenes; i++) { Androgene a = androgenes.get(i); System.out.println("Date : " + a.toString()); } for (int j=i; j<30; j++) { Androgene a = new Androgene(); androgenes.add(a); } System.out.println("Treat Androgene => Open dialog"); } public int validAndrogene() { if (!androgenes.isEmpty()) { ListIterator<Androgene> la = androgenes.listIterator(); int i=0; System.out.println("Nombre androgenes : "+ androgenes.size()); System.out.println("androgenes : "+androgenes.toString()); while(la.hasNext()){ Androgene a = la.next(); System.out.println("nbAndrogenes "+this.nbAndrogenes); if (i< this.nbAndrogenes ) { //AndrogenePK apk = new AndrogenePK(this.newfiche.getnDossier(),i+3); AndrogenePK apk; if (i==0) apk = new AndrogenePK(this.newfiche.getnDossier(),3); else apk = new AndrogenePK(this.newfiche.getnDossier(),6*i); a.setAndrogenePK(apk); androgeneService.update(a); System.out.println("Update Androgene "+a.getAndrogenePK().getMois()); } else { System.out.println("Nouvelles données cytogénétiques"); AndrogenePK apk; if (i==0) apk = new AndrogenePK(this.newfiche.getnDossier(),3); else apk = new AndrogenePK(this.newfiche.getnDossier(),6*i); a.setAndrogenePK(apk); androgeneService.add(a); System.out.println("Add Androgene "+a.getAndrogenePK().getMois()); } i++; } this.nbAndrogenes = androgenes.size() ; System.out.println("MAJ nb androgenes "+this.nbAndrogenes); } RequestContext.getCurrentInstance().closeDialog(null); return 0; } public void treatCytogenetique() { int i; for (i=0; i<this.nbCytogenetiques; i++) { Cytogenetique c = cytogenetiques.get(i); System.out.println("Date : " + c.toString()); } for (int j=i; j<4; j++) { Cytogenetique c = new Cytogenetique(); cytogenetiques.add(c); } System.out.println("Treat cytogenetique => Open dialog"); } public void formFrere() { System.out.println("Form FRERE : Nombre vivant : " + String.valueOf(this.newfiche.getNbVivant())); } public void submitFormFrere() { } public HopitalService getHopitalService() { return hopitalService; } public void setHopitalService(HopitalService hopitalService) { this.hopitalService = hopitalService; } public ServiceService getServiceService() { return serviceService; } public void setServiceService(ServiceService serviceService) { this.serviceService = serviceService; } public MedecinService getMedecinService() { return medecinService; } public void setMedecinService(MedecinService medecinService) { this.medecinService = medecinService; } public FicheService getFicheService() { return ficheService; } public void setFicheService(FicheService ficheService) { this.ficheService = ficheService; } public Fiche getNewfiche() { return newfiche; } public void setNewfiche(Fiche newfiche) { this.newfiche = newfiche; } private String valueChange; public String getValueChange() { return valueChange; } public void setValueChange(String valueChange) { this.valueChange = valueChange; } public void handleChange(ValueChangeEvent event){ System.out.println("New value: " + event.getNewValue()); } public String ModifierFiche(){ FacesContext fc = FacesContext.getCurrentInstance(); Map<String,String> params = fc.getExternalContext().getRequestParameterMap(); data = params.get("codefiche"); System.out.println("Fiche " + data +" successfully loaded" ); newfiche=ficheService.getFicheParnDossier(data); newpatient=patientService.getPatientParnDossier(data); System.out.println("getListFrereParnDossier(" + frereService.toString()); freres = frereService.getListFrereParnDossier(data); this.nbFreres = freres.size(); cousins = cousinService.getListCousinParnDossier(data); this.nbCousins= cousins.size(); membres = membreService.getListMembreParnDossier(data); this.nbMembres = membres.size(); hopital = hopitalService.getHopitalParNum(newfiche.getHopital()).getNomHopitale(); service = serviceService.getServiceParNum(newfiche.getService()).getNomService(); this.cytogenetiques = cytogenetiqueService.getListCytogenetiqueParnDossier(data); this.nbCytogenetiques = this.cytogenetiques.size(); this.androgenes = androgeneService.getListAndrogeneParnDossier(data); this.nbAndrogenes = this.androgenes.size(); System.out.println("***** MEDECIN = " + newfiche.getMedecin()); medecin = medecinService.getMedecinParCIN(Integer.valueOf(newfiche.getMedecin())).getNomMedecin(); System.out.println("Hopital =======" + hopital); //return "ModifierFiche?faces-redirect=true"; return "modifyTest?faces-redirect=true"; } public String getHopital() { return hopital; } public void setHopital(String hopital) { this.hopital = hopital; } public String getService() { return service; } public void setService(String service) { this.service = service; } public void converter(){ FacesContext fc = FacesContext.getCurrentInstance(); Map<String,String> params = fc.getExternalContext().getRequestParameterMap(); //data = params.get("codefiche"); //System.out.println("Fiche " + data +" successfully loaded" ); } public boolean checkboxConverter(String value){ String str = new String("oui"); System.out.println("check box converter : " + value + "compare " + value.compareTo(str) ); return value.compareTo(str)==1; } public AndrogeneService getAndrogeneService() { return androgeneService; } public void setAndrogeneService(AndrogeneService androgeneService) { this.androgeneService = androgeneService; } }
package common.bean; import java.util.List; public class ImportResult { /** * Ma tra ve */ // Khong co loi public static final int NO_ERROR = 0; public static final int DATA_CONTENT_ERROR = 3; // Du lieu co loi public static final int FIRST_DATA_ROW_ERROR = 1; // So dong cua file nho hon dong bat dau public static final int NO_DATA_ERROR = 2; // Khong co du lieu public static final int FORMAT_ERROR = 4; // Khong dung dinh dang Excel public static final int EXCEED_MAX_NUMBER_OF_RECORD_ERROR = 8; // Loi so dong vuot qua public static final int FILE_NOT_FOUND_ERROR = 9; // File not found // Exception public static final int EXCEPTION_ERROR = 10; private int returnCode; private String message; private List<ImportError> errorList; private List<Object[]> dataList; public ImportResult(int returnCode, String message) { this.returnCode = returnCode; this.message = message; } public ImportResult(int returnCode, List<ImportError> errorList) { this.returnCode = returnCode; this.errorList = errorList; } public ImportResult(List<Object[]> dataList) { this.returnCode = NO_ERROR; this.dataList = dataList; } // GETTERS public int getReturnCode() { return returnCode; } public String getMessage() { return message; } public List<Object[]> getDataList() { return dataList; } public List<ImportError> getErrorList() { return errorList; } }
package com.deity.design.observer; /** * 2017年2月6日23:29:47 * 观察者接口,也可以做成抽象的,如果有众多的观察者则可以implement或者extend该接口或抽象类 * Created by Deity on 2017/1/10. */ public interface IObserver { /** * 当主题发生新的变动时,可调用该方法通知观察者更新信息 * @param somethingNews 从主题接收到的更新信息 */ void update(String somethingNews); }
import java.util.ArrayList; public abstract class Game { Chessboard chessboard; int times; ArrayList<Grid> place; ArrayList<Grid> reverse; Printer printer; private long start; private long end; public abstract void start(); public int getTotalTime(){ return (int)(end - start)/1000; } public void startTime(){ start = System.currentTimeMillis(); } public void endTime(){ end = System.currentTimeMillis(); } }
package com.selfspring.gimi.cc.after; /** * Created by ckyang on 2019/12/12. */ public class PersonRF { private String name; private PhoneNumber phoneNumber; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getOfficeAreaCode() { return phoneNumber.getOfficeAreaCode(); } public void setOfficeAreaCode(String officeAreaCode) { this.phoneNumber.setOfficeAreaCode(officeAreaCode); } public String getOfficeNumber() { return this.phoneNumber.getOfficeNumber(); } public void setOfficeNumber(String officeNumber) { this.phoneNumber.setOfficeNumber(officeNumber); } }
package com.coolweather.android.gson; public class Weather { }
package Composition; public class BasicAccount { CableTV ac; public BasicAccount(CableTV account, String nome) { this.ac = account; this.setNome(nome); } public void setNome(String nome) { ac.setNome(nome); } public String getNome() { return ac.getNome(); } public void calculatePackage(double numberChannels) { ac.setInvoiceGenerated(numberChannels); } public double invoiceGenerated() { return ac.invoiceGenerated(); } }
package com.example.herokuproject.services; import com.example.herokuproject.entities.Persona; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import java.util.List; public interface PersonaService extends BaseService<Persona, Long>{ //Metodo que se va a encargar de la busqueda List<Persona> search (String filtro) throws Exception; Page<Persona> search (String filtro, Pageable pageable) throws Exception; }
package com.example.demo; public class Customer { private String customer; public Customer(){ this.customer = "customer-define"; } public String getLead() { return customer; } }
package com.spacePhoto.controller; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.sql.Date; import java.util.LinkedList; import java.util.Queue; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; import com.spacePhoto.model.SpacePhotoServiceB; import com.spacePhoto.model.SpacePhotoVO; @WebServlet("/SpacePhotoServlet") @MultipartConfig(fileSizeThreshold = 1024 * 1024, maxFileSize = 5 * 1024 * 1024, maxRequestSize = 5 * 5 * 1024 * 1024) public class SpacePhotoServletB extends HttpServlet { // private static final long serialVersionUID = 1L; public SpacePhotoServletB() { super(); } protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doPost(req, res); } protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); String action = req.getParameter("action"); if ("backend_AddSpacePhoto".equals(action)) { Queue<String> errorMsgs = new LinkedList<String>(); req.setAttribute("errorMsgs", errorMsgs); try { String spaceId = req.getParameter("spaceId").trim(); if(spaceId == null || spaceId.isEmpty()) errorMsgs.add("場地編號: 請勿空白"); Part part = req.getPart("spacePhoto"); InputStream in = null; byte[] spacePhoto = null; String filename = getFileNameFromPart(part); if (filename == null || filename.isEmpty()) { // if (part == null) { File file = new File(getServletContext().getRealPath("/") + "/backend/img/BlobTest3.jpg"); FileInputStream fis = new FileInputStream(file); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[8192]; int i; while ((i = fis.read(buffer)) != -1) { baos.write(buffer, 0, i); } spacePhoto = baos.toByteArray(); baos.close(); fis.close(); } else { in = part.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[8192]; int i; while ((i = in.read(buffer)) != -1) { baos.write(buffer, 0, i); } spacePhoto = baos.toByteArray(); baos.close(); in.close(); } SpacePhotoVO addSpacePhoto = new SpacePhotoVO(); addSpacePhoto.setSpaceId(spaceId); addSpacePhoto.setSpacePhoto(spacePhoto); if (!errorMsgs.isEmpty()) { req.setAttribute("addSpacePhoto", addSpacePhoto); RequestDispatcher failureView = req.getRequestDispatcher("/backend/spacePhoto/addSpacePhoto.jsp"); failureView.forward(req, res); return; } SpacePhotoServiceB spacePhotoServ = new SpacePhotoServiceB(); addSpacePhoto = spacePhotoServ.addSpacePhoto(addSpacePhoto); String url = "/backend/spacePhoto/selectAllSpacePhoto.jsp"; RequestDispatcher sucessVeiw = req.getRequestDispatcher(url); sucessVeiw.forward(req, res); } catch (Exception e) { e.printStackTrace(); errorMsgs.add(e.getMessage()); RequestDispatcher exceptionView = req.getRequestDispatcher("/backend/error.jsp"); exceptionView.forward(req, res); } } if ("backend_SelectOneSpacePhoto".equals(action)) { Queue<String> errorMsgs = new LinkedList<String>(); req.setAttribute("errorMsgs", errorMsgs); try { String spacePhotoId = req.getParameter("spacePhotoId").trim(); if(spacePhotoId == null || spacePhotoId.isEmpty()) errorMsgs.add("場地評價編號: 請勿空白"); if (!errorMsgs.isEmpty()) { RequestDispatcher failureView = req.getRequestDispatcher("/backend/spacePhoto/spacePhoto.jsp"); failureView.forward(req, res); return; } SpacePhotoServiceB spacePhotoServ = new SpacePhotoServiceB(); SpacePhotoVO selectOneSpacePhoto = new SpacePhotoVO(); selectOneSpacePhoto = spacePhotoServ.selectOneSpacePhoto(spacePhotoId); if (selectOneSpacePhoto == null) { errorMsgs.add("查無資料"); } if (!errorMsgs.isEmpty()) { RequestDispatcher failureView = req.getRequestDispatcher("/backend/spacePhoto/spacePhoto.jsp"); failureView.forward(req, res); return; } req.setAttribute("selectOneSpacePhoto", selectOneSpacePhoto); String url = "/backend/spacePhoto/selectOneSpacePhoto.jsp"; RequestDispatcher sucessVeiw = req.getRequestDispatcher(url); sucessVeiw.forward(req, res); } catch (Exception e) { e.printStackTrace(); errorMsgs.add(e.getMessage()); RequestDispatcher exceptionView = req.getRequestDispatcher("/backend/error.jsp"); exceptionView.forward(req, res); } } if ("backend_DeleteSpacePhoto".equals(action)) { Queue<String> errorMsgs = new LinkedList<String>(); req.setAttribute("errorMsgs", errorMsgs); try { String spacePhotoId = req.getParameter("spacePhotoId").trim(); SpacePhotoServiceB spacePhotoServ = new SpacePhotoServiceB(); SpacePhotoVO deleteSpace = new SpacePhotoVO(); spacePhotoServ.deleteSpacePhoto(spacePhotoId); String url = "/backend/spacePhoto/selectAllSpacePhoto.jsp"; RequestDispatcher sucessVeiw = req.getRequestDispatcher(url); sucessVeiw.forward(req, res); } catch (Exception e) { e.printStackTrace(); errorMsgs.add(e.getMessage()); RequestDispatcher exceptionView = req.getRequestDispatcher("/backend/error.jsp"); exceptionView.forward(req, res); } } if ("backend_SelectOneUpdate".equals(action)) { Queue<String> errorMsgs = new LinkedList<String>(); req.setAttribute("errorMsgs", errorMsgs); try { String spacePhotoId = req.getParameter("spacePhotoId").trim(); SpacePhotoServiceB spacePhotoServ = new SpacePhotoServiceB(); SpacePhotoVO selectOneUpdate = new SpacePhotoVO(); selectOneUpdate = spacePhotoServ.selectOneSpacePhoto(spacePhotoId); req.setAttribute("selectOneUpdate", selectOneUpdate); String url = "/backend/spacePhoto/updateSpacePhoto.jsp"; RequestDispatcher sucessVeiw = req.getRequestDispatcher(url); sucessVeiw.forward(req, res); } catch (Exception e) { e.printStackTrace(); errorMsgs.add(e.getMessage()); RequestDispatcher exceptionView = req.getRequestDispatcher("/backend/error.jsp"); exceptionView.forward(req, res); } } if ("backend_UpdateSpacePhoto".equals(action)) { Queue<String> errorMsgs = new LinkedList<String>(); req.setAttribute("errorMsgs", errorMsgs); try { String spacePhotoId = req.getParameter("spacePhotoId").trim(); String spaceId = req.getParameter("spaceId").trim(); if (spaceId == null || spaceId.isEmpty()) errorMsgs.add("場地編號: 請勿空白"); Part part = req.getPart("spacePhoto"); InputStream in = null; byte[] spacePhoto = null; String filename = getFileNameFromPart(part); if (filename == null || filename.isEmpty()) { // if (part == null) { // errorMsgs.add("場地圖片: 請勿空白"); SpacePhotoServiceB spacePhotoServ = new SpacePhotoServiceB(); SpacePhotoVO spaceOriginPhoto = spacePhotoServ.selectOneSpacePhoto(spacePhotoId); spacePhoto = spaceOriginPhoto.getSpacePhoto(); } else { in = part.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[8192]; int i; while ((i = in.read(buffer)) != -1) { baos.write(buffer, 0, i); } spacePhoto = baos.toByteArray(); baos.close(); in.close(); } SpacePhotoVO updateSpacePhoto = new SpacePhotoVO(); updateSpacePhoto.setSpacePhotoId(spacePhotoId); updateSpacePhoto.setSpaceId(spaceId); updateSpacePhoto.setSpacePhoto(spacePhoto); if (!errorMsgs.isEmpty()) { req.setAttribute("selectOneUpdate", updateSpacePhoto); RequestDispatcher failureView = req.getRequestDispatcher("/backend/spacePhoto/updateSpacePhoto.jsp"); failureView.forward(req, res); return; } SpacePhotoServiceB spacePhotoServ = new SpacePhotoServiceB(); updateSpacePhoto = spacePhotoServ.updateSpacePhoto(updateSpacePhoto); // req.setAttribute("updateSpacePhoto", updateSpacePhoto); String url = "/backend/spacePhoto/selectAllSpacePhoto.jsp"; RequestDispatcher sucessVeiw = req.getRequestDispatcher(url); sucessVeiw.forward(req, res); } catch (Exception e) { e.printStackTrace(); errorMsgs.add(e.getMessage()); RequestDispatcher exceptionView = req.getRequestDispatcher("/backend/error.jsp"); exceptionView.forward(req, res); } } //====================================================================================================================================== if ("addSpacePhoto".equals(action)) { Queue<String> errorMsgs = new LinkedList<String>(); req.setAttribute("errorMsgs", errorMsgs); try { String spaceId = req.getParameter("spaceId").trim(); if(spaceId == null || spaceId.isEmpty()) errorMsgs.add("場地編號: 請勿空白"); Part part = req.getPart("spacePhoto"); InputStream in = null; byte[] spacePhoto = null; String filename = getFileNameFromPart(part); if (filename == null || filename.isEmpty()) { // if (part == null) { // errorMsgs.add("員工圖片: 請勿空白"); File file = new File(getServletContext().getRealPath("/") + "/backend/img/BlobTest3.jpg"); FileInputStream fis = new FileInputStream(file); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[8192]; int i; while ((i = fis.read(buffer)) != -1) { baos.write(buffer, 0, i); } spacePhoto = baos.toByteArray(); baos.close(); fis.close(); } else { in = part.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[8192]; int i; while ((i = in.read(buffer)) != -1) { baos.write(buffer, 0, i); } spacePhoto = baos.toByteArray(); baos.close(); in.close(); } SpacePhotoVO addSpacePhoto = new SpacePhotoVO(); addSpacePhoto.setSpaceId(spaceId); addSpacePhoto.setSpacePhoto(spacePhoto); if (!errorMsgs.isEmpty()) { req.setAttribute("addSpacePhoto", addSpacePhoto); RequestDispatcher failureView = req.getRequestDispatcher("/frontend/spacePhoto/addSpacePhoto.jsp"); failureView.forward(req, res); return; } SpacePhotoServiceB spacePhotoServ = new SpacePhotoServiceB(); addSpacePhoto = spacePhotoServ.addSpacePhoto(addSpacePhoto); String url = "/frontend/spacePhoto/selectAllSpacePhoto.jsp"; RequestDispatcher sucessVeiw = req.getRequestDispatcher(url); sucessVeiw.forward(req, res); } catch (Exception e) { e.printStackTrace(); errorMsgs.add(e.getMessage()); RequestDispatcher exceptionView = req.getRequestDispatcher("/frontend/error.jsp"); exceptionView.forward(req, res); } } if ("selectOneSpacePhoto".equals(action)) { Queue<String> errorMsgs = new LinkedList<String>(); req.setAttribute("errorMsgs", errorMsgs); try { String spacePhotoId = req.getParameter("spacePhotoId").trim(); if(spacePhotoId == null || spacePhotoId.isEmpty()) errorMsgs.add("場地評價編號: 請勿空白"); if (!errorMsgs.isEmpty()) { RequestDispatcher failureView = req.getRequestDispatcher("/frontend/spacePhoto/spacePhoto.jsp"); failureView.forward(req, res); return; } SpacePhotoServiceB spacePhotoServ = new SpacePhotoServiceB(); SpacePhotoVO selectOneSpacePhoto = new SpacePhotoVO(); selectOneSpacePhoto = spacePhotoServ.selectOneSpacePhoto(spacePhotoId); if (selectOneSpacePhoto == null) { errorMsgs.add("查無資料"); } if (!errorMsgs.isEmpty()) { RequestDispatcher failureView = req.getRequestDispatcher("/frontend/spacePhoto/spacePhoto.jsp"); failureView.forward(req, res); return; } req.setAttribute("selectOneSpacePhoto", selectOneSpacePhoto); String url = "/frontend/spacePhoto/selectOneSpacePhoto.jsp"; RequestDispatcher sucessVeiw = req.getRequestDispatcher(url); sucessVeiw.forward(req, res); } catch (Exception e) { e.printStackTrace(); errorMsgs.add(e.getMessage()); RequestDispatcher exceptionView = req.getRequestDispatcher("/frontend/error.jsp"); exceptionView.forward(req, res); } } if ("deleteSpacePhoto".equals(action)) { Queue<String> errorMsgs = new LinkedList<String>(); req.setAttribute("errorMsgs", errorMsgs); try { String spacePhotoId = req.getParameter("spacePhotoId").trim(); SpacePhotoServiceB spacePhotoServ = new SpacePhotoServiceB(); SpacePhotoVO deleteSpace = new SpacePhotoVO(); spacePhotoServ.deleteSpacePhoto(spacePhotoId); String url = "/frontend/spacePhoto/selectAllSpacePhoto.jsp"; RequestDispatcher sucessVeiw = req.getRequestDispatcher(url); sucessVeiw.forward(req, res); } catch (Exception e) { e.printStackTrace(); errorMsgs.add(e.getMessage()); RequestDispatcher exceptionView = req.getRequestDispatcher("/frontend/error.jsp"); exceptionView.forward(req, res); } } if ("selectOneUpdate".equals(action)) { Queue<String> errorMsgs = new LinkedList<String>(); req.setAttribute("errorMsgs", errorMsgs); try { String spacePhotoId = req.getParameter("spacePhotoId").trim(); SpacePhotoServiceB spacePhotoServ = new SpacePhotoServiceB(); SpacePhotoVO selectOneUpdate = new SpacePhotoVO(); selectOneUpdate = spacePhotoServ.selectOneSpacePhoto(spacePhotoId); req.setAttribute("selectOneUpdate", selectOneUpdate); String url = "/frontend/spacePhoto/updateSpacePhoto.jsp"; RequestDispatcher sucessVeiw = req.getRequestDispatcher(url); sucessVeiw.forward(req, res); } catch (Exception e) { e.printStackTrace(); errorMsgs.add(e.getMessage()); RequestDispatcher exceptionView = req.getRequestDispatcher("/frontend/error.jsp"); exceptionView.forward(req, res); } } if ("updateSpacePhoto".equals(action)) { Queue<String> errorMsgs = new LinkedList<String>(); req.setAttribute("errorMsgs", errorMsgs); try { String spacePhotoId = req.getParameter("spacePhotoId").trim(); String spaceId = req.getParameter("spaceId").trim(); if (spaceId == null || spaceId.isEmpty()) errorMsgs.add("場地編號: 請勿空白"); Part part = req.getPart("spacePhoto"); InputStream in = null; byte[] spacePhoto = null; String filename = getFileNameFromPart(part); if (filename == null || filename.isEmpty()) { // if (part == null) { // errorMsgs.add("場地圖片: 請勿空白"); SpacePhotoServiceB spacePhotoServ = new SpacePhotoServiceB(); SpacePhotoVO spaceOriginPhoto = spacePhotoServ.selectOneSpacePhoto(spacePhotoId); spacePhoto = spaceOriginPhoto.getSpacePhoto(); } else { in = part.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[8192]; int i; while ((i = in.read(buffer)) != -1) { baos.write(buffer, 0, i); } spacePhoto = baos.toByteArray(); baos.close(); in.close(); } SpacePhotoVO updateSpacePhoto = new SpacePhotoVO(); updateSpacePhoto.setSpacePhotoId(spacePhotoId); updateSpacePhoto.setSpaceId(spaceId); updateSpacePhoto.setSpacePhoto(spacePhoto); if (!errorMsgs.isEmpty()) { req.setAttribute("selectOneUpdate", updateSpacePhoto); RequestDispatcher failureView = req.getRequestDispatcher("/frontend/spacePhoto/updateSpacePhoto.jsp"); failureView.forward(req, res); return; } SpacePhotoServiceB spacePhotoServ = new SpacePhotoServiceB(); updateSpacePhoto = spacePhotoServ.updateSpacePhoto(updateSpacePhoto); // req.setAttribute("updateSpacePhoto", updateSpacePhoto); String url = "/frontend/spacePhoto/selectAllSpacePhoto.jsp"; RequestDispatcher sucessVeiw = req.getRequestDispatcher(url); sucessVeiw.forward(req, res); } catch (Exception e) { e.printStackTrace(); errorMsgs.add(e.getMessage()); RequestDispatcher exceptionView = req.getRequestDispatcher("/frontend/error.jsp"); exceptionView.forward(req, res); } } } public String getFileNameFromPart(Part part) { String header = part.getHeader("content-disposition"); // System.out.println(header); String filename = header.substring(header.lastIndexOf("=") + 2, header.length() - 1); if (filename.length() == 0) { return null; } return filename; } }
public class Student_Runner_Boxcar { public static void main(String[] args) { // Testing various required behaviors of the Boxcar constructor System.out.println("Testing Boxcar constructors:"); Boxcar car1 = new Boxcar(); System.out.println("Printing Boxcar():\n" + car1 + "\n"); Boxcar car2 = new Boxcar("widgets", 7, false); System.out.println("Printing Boxcar(\"widgets\", 7, false):\n" + car2 + "\n"); Boxcar car3 = new Boxcar("WaDGeTs", 7, true); System.out.println("Testing lowercase cargo and setting cargo to 0 if in repair.\n"); System.out.println("Printing Boxcar(\"WaDGeTs\", 7, true):\n" + car3 + "\n"); Boxcar car4 = new Boxcar("OtherStuff", 7, false); System.out.println("Testing cargo other than accepted values.\n"); System.out.println("Printing Boxcar(\"OtherStuff\", 7, true):\n" + car4 + "\n"); // car2 is not burnt out. Lets call callForRepair on car2 and make sure it // gets marked for repair and set to 0 units. System.out.println("Testing callForRepair:"); car2.callForRepair(); System.out.println("Printing Boxcar called for repair:\n" + car2 + "\n"); // Let's test the loadCargo() method. We'll make a new Boxcar with 7 gadgets, // then load cargo until it reaches maximum capacity. Boxcar car5 = new Boxcar("gadgets", 7, false); car5.loadCargo(); // car5 should print out with 8 gadgets System.out.println("Printing Boxcar with 8 gadgets:\n" + car5 + "\n"); // now let's load cargo three more times. This should put the car over maximum // capacity and should keep the cargo size at 10. car5.loadCargo(); car5.loadCargo(); car5.loadCargo(); System.out.println("Printing Boxcar with 10 gadgets, tried to overload:\n" + car5 + "\n"); // lastly, let's test to make sure we can't load cargo onto a Boxcar that is in // repair, using car2. car2.loadCargo(); System.out.println("Printing Boxcar in repair, can't load (0 cargo):\n" + car2 + "\n"); System.out.println("Testing isFull:"); // Let's test a full car and a non-full car to make sure they return true and // false, respectively. Boxcar car6 = new Boxcar("gizmos", 10, false); Boxcar car7 = new Boxcar("widgets", 7, false); System.out.println("Printing isFull on full car:\n" + car6.isFull() + "\n"); System.out.println("Printing isFull on non-full car:\n" + car7.isFull() + "\n"); System.out.println("Testing getCargo:"); // Let's make sure car7 returns "widgets" as its cargo. System.out.println("Printing getCargo on a \"widgets\" car:\n" + car7.getCargo() + "\n"); System.out.println("Testing setCargo:"); // Making sure it can set cargo to "gadgets" car7.setCargo("gadgets"); System.out.println("Setting cargo to gadgets:\n" + car7 + "\n"); // Testing it will convert cargo to lowercase car7.setCargo("WADGetS"); System.out.println("Testing lowercase conversion (WADGetS -> wadgets):\n" + car7 + "\n"); // Testing it will set cargo to "gizsmos" if a nonvalid cargo is entered car7.setCargo("onions"); System.out.println("Testing invalid cargo type sets to gizmos (onions -> gizmos):\n" + car7 + "\n"); } }
public class character { private int pointX; private int pointY; public MoveLeft(){ pointX--; } public MoveRight(){ pointX++; } public MoveUp(){ pointY--; } public MoveDown(){ pointY++; } public int[] GetLocation(){ return { pointX, pointY }; } }
package com.springboot.racemanage.service.serviceImpl; import com.springboot.racemanage.service.RaceinfoService; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; import com.springboot.racemanage.po.Raceinfo; import com.springboot.racemanage.dao.RaceinfoDao; import org.springframework.transaction.annotation.Transactional; @Service @Transactional public class RaceinfoServiceImpl implements RaceinfoService{ @Resource private RaceinfoDao raceinfoDao; public int insert(Raceinfo pojo){ return raceinfoDao.insert(pojo); } public int insertSelective(Raceinfo pojo){ return raceinfoDao.insertSelective(pojo); } public int insertList(List<Raceinfo> pojos){ return raceinfoDao.insertList(pojos); } public int update(Raceinfo pojo){ return raceinfoDao.update(pojo); } @Override public List<Raceinfo> findByStatusAndTerm(Integer status, Integer term) { return raceinfoDao.findByStatusAndTerm(status,term); } @Override public Raceinfo findFirstByUuid(String uuid) { return raceinfoDao.findFirstByUuid(uuid); } @Override public Raceinfo findById(Integer id) { return raceinfoDao.findById(id); } @Override public List<Raceinfo> findByPageNo(Integer pageNo) { //根据页数一次查10条数据 return raceinfoDao.findByPageNo((pageNo-1)*10); } }
package project; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import javafx.collections.FXCollections; import javafx.collections.ObservableList; public class ProjectDAO { //일련번호로 메세지 가져오기 static Massage selectMassage(int selectedMId) { Connection conn = ConnectionDB.getDB(); String sql = "select * from MASSAGE where MID =" + selectedMId; ObservableList<Massage> list = FXCollections.observableArrayList(); Massage msg = null; try { PreparedStatement pstmt =conn.prepareStatement(sql); ResultSet rs = pstmt.executeQuery(); while(rs.next()) { msg = new Massage(rs.getString("FROMID"), rs.getString("TOID"), rs.getString("TITLE"), rs.getString("MASSAGE"), rs.getInt("MID")); list.add(msg); }; } catch (SQLException e) { e.printStackTrace(); } return msg; } //받은 메세지 가져오기 static ObservableList<Massage> selectMassage(String userId) { Connection conn = ConnectionDB.getDB(); String sql = "select * from MASSAGE where TOID ='" + userId + "'"; ObservableList<Massage> list = FXCollections.observableArrayList(); try { PreparedStatement pstmt =conn.prepareStatement(sql); ResultSet rs = pstmt.executeQuery(); while(rs.next()) { Massage msg = new Massage(rs.getString("FROMID"), rs.getString("TOID"), rs.getString("TITLE"), rs.getString("MASSAGE"), rs.getInt("MID"), rs.getString("CHK")); list.add(msg); }; } catch (SQLException e) { e.printStackTrace(); } return list; } //읽지 않은 메세지 가져오기 static ObservableList<Massage> selectNotReadMassage(String userId) { Connection conn = ConnectionDB.getDB(); String sql = "select * from MASSAGE where TOID ='" + userId + "' and CHK = 'new'"; ObservableList<Massage> list = FXCollections.observableArrayList(); try { PreparedStatement pstmt =conn.prepareStatement(sql); ResultSet rs = pstmt.executeQuery(); while(rs.next()) { Massage msg = new Massage(rs.getString("FROMID"), rs.getString("TOID"), rs.getString("TITLE"), rs.getString("MASSAGE"), rs.getInt("MID")); list.add(msg); }; } catch (SQLException e) { e.printStackTrace(); } return list; } //구매창에서 더블클릭해서 PId값에 따른 ID가져오기 static Item selectIdOfPId(int selectedPId) { Connection conn = ConnectionDB.getDB(); String sql = "select * from SELLITEM where PID =" + selectedPId; ObservableList<Item> list = FXCollections.observableArrayList(); Item item = null; try { PreparedStatement pstmt =conn.prepareStatement(sql); ResultSet rs = pstmt.executeQuery(); while(rs.next()) { item = new Item(rs.getString("ID"), rs.getString("NAME"), rs.getString("CONDITION"), rs.getInt("PRICE"), rs.getInt("PID")); } } catch (SQLException e) { e.printStackTrace(); } return item; } static ObservableList<Member> selectMember() { Connection conn = ConnectionDB.getDB(); String sql = "select * from MEMBER"; ObservableList<Member> list = FXCollections.observableArrayList(); try { PreparedStatement pstmt =conn.prepareStatement(sql); ResultSet rs = pstmt.executeQuery(); while(rs.next()) { Member mem = new Member(rs.getString("ID"), rs.getInt("PASSWORD")); list.add(mem); }; } catch (SQLException e) { e.printStackTrace(); } return list; } static ObservableList<Item> listOfBuy(String userId) { Connection conn = ConnectionDB.getDB(); String sql = "select * from SELLITEM where ID != '" + userId + "'"; ObservableList<Item> list = FXCollections.observableArrayList(); try { PreparedStatement pstmt =conn.prepareStatement(sql); ResultSet rs = pstmt.executeQuery(); while(rs.next()) { Item item = new Item(rs.getString("ID"), rs.getString("NAME"), rs.getString("CONDITION"), rs.getInt("PRICE"), rs.getInt("PID")); list.add(item); }; } catch (SQLException e) { e.printStackTrace(); } return list; } public static ObservableList<Item> listSelling(String userId) { Connection conn = ConnectionDB.getDB(); String sql = "select * from SELLITEM where ID = '" + userId + "'"; ObservableList<Item> list = FXCollections.observableArrayList(); try { PreparedStatement pstmt =conn.prepareStatement(sql); ResultSet rs = pstmt.executeQuery(); while(rs.next()) { Item item = new Item(rs.getString("ID"), rs.getString("NAME"), rs.getString("CONDITION"), rs.getInt("PRICE"), rs.getInt("PID")); list.add(item); }; } catch (SQLException e) { e.printStackTrace(); } return list; } public static ObservableList<Item> listBuy(String userId) { Connection conn = ConnectionDB.getDB(); String sql = "select * from BUYITEM where BUYID = '" + userId + "'"; ObservableList<Item> list = FXCollections.observableArrayList(); try { PreparedStatement pstmt =conn.prepareStatement(sql); ResultSet rs = pstmt.executeQuery(); while(rs.next()) { Item item = new Item(rs.getString("ID"), rs.getString("NAME"), rs.getString("CONDITION"), rs.getInt("PRICE"), rs.getInt("PID")); list.add(item); }; } catch (SQLException e) { e.printStackTrace(); } return list; } public static ObservableList<Item> listSell(String userId) { Connection conn = ConnectionDB.getDB(); String sql = "select * from BUYITEM where ID = '" + userId + "'"; ObservableList<Item> list = FXCollections.observableArrayList(); try { PreparedStatement pstmt =conn.prepareStatement(sql); ResultSet rs = pstmt.executeQuery(); while(rs.next()) { Item item = new Item(rs.getString("ID"), rs.getString("NAME"), rs.getString("CONDITION"), rs.getInt("PRICE"), rs.getInt("PID")); list.add(item); }; } catch (SQLException e) { e.printStackTrace(); } return list; } static void btnSendMassageAction(String userId, String sellingId, String MassageTitle , String Massage) { Connection conn = ConnectionDB.getDB(); String sql = "insert into MASSAGE values(?, ?, ?, ?, MassageSequence.nextval, 'new')"; try { PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setNString(1, userId); pstmt.setNString(2, sellingId); pstmt.setNString(3, MassageTitle); pstmt.setNString(4, Massage); pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } static void btnSignIn(String txtID, String txtPassword) { Connection conn = ConnectionDB.getDB(); String sql = "insert into MEMBER values(?,?)"; try { PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setNString(1, txtID); pstmt.setNString(2, txtPassword); pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } static void btnSellAddAction(String userId, String name, String status, String price) { Connection conn = ConnectionDB.getDB(); String sql = "insert into SELLITEM values(?,?,?,?, sequence1.nextval)"; try { PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, userId); pstmt.setString(2, name); pstmt.setString(3, status); pstmt.setString(4, price); pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } static void btnModifyAction(String name, String status, String price, int selectedPID) { Connection conn = ConnectionDB.getDB(); String sql = "UPDATE SELLITEM SET NAME = ?, CONDITION = ?, PRICE = ? WHERE PID = "+ selectedPID; try { PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, name); pstmt.setString(2, status); pstmt.setString(3, price); pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } static void UpdateChk(int selectedMId) { Connection conn = ConnectionDB.getDB(); String sql = "UPDATE MASSAGE SET CHK = ' ' WHERE MID = "+ selectedMId; try { PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } static void btnDeleteMassageAction(int selectedMId) { Connection conn = ConnectionDB.getDB(); String sql = "delete MASSAGE where MID = "+ selectedMId; try { PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } static void buy(int buyPid, String userId) { Connection conn = ConnectionDB.getDB(); String sql = "select * from SELLITEM where PID = " + buyPid; Item item = null; try { PreparedStatement pstmt =conn.prepareStatement(sql); ResultSet rs = pstmt.executeQuery(); while(rs.next()) { item = new Item(rs.getString("ID"), rs.getString("NAME"), rs.getString("CONDITION"), rs.getInt("PRICE"), rs.getInt("PID")); }; } catch (SQLException e) { e.printStackTrace(); } String sql2 = "delete SELLITEM where PID = "+ buyPid; try { PreparedStatement pstmt = conn.prepareStatement(sql2); pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } String sql3 = "insert into BUYITEM values(?,?,?,?,?,?)"; try { PreparedStatement pstmt = conn.prepareStatement(sql3); pstmt.setString(1, item.getId()); pstmt.setString(2, item.getName()); pstmt.setString(3, item.getCondition()); pstmt.setString(4, String.valueOf(item.getPrice())); pstmt.setString(5, String.valueOf(buyPid)); pstmt.setString(6, String.valueOf(userId)); pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } static ObservableList<Item> btnSearchAction(String buySearch) { Connection conn = ConnectionDB.getDB(); String sql = "select * from SELLITEM where NAME like '%" + buySearch + "%'"; ObservableList<Item> list = FXCollections.observableArrayList(); try { PreparedStatement pstmt =conn.prepareStatement(sql); ResultSet rs = pstmt.executeQuery(); while(rs.next()) { Item item = new Item(rs.getString("ID"), rs.getString("NAME"), rs.getString("CONDITION"), rs.getInt("PRICE"), rs.getInt("PID")); list.add(item); }; } catch (SQLException e) { e.printStackTrace(); } return list; } }
package ru.job4j.addresslist; import org.junit.Test; import ru.job4j.addresslist.Address; import ru.job4j.addresslist.Profile; import ru.job4j.addresslist.Profiles; import java.util.List; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; public class ProfileTest { @Test public void whenFiveAddresses() { Profiles profiles = new Profiles(); Address address = new Address("Москва", "Ленина", 25, 84); Address address1 = new Address("Минск", "Космонавтов", 31, 25); Address address2 = new Address("Киев", "Победителей", 114, 5); Address address3 = new Address("Минск", "Космонавтов", 31, 25); List<Profile> profilesList = List.of(new Profile(address), new Profile(address1), new Profile(address2), new Profile((address3))); List<Address> result = profiles.collect(profilesList); List<Address> expected = List.of(address2, address1, address); assertThat(result, is(expected)); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package josteo.infrastructure.repositories.Pazienti; import josteo.model.paziente.*; import josteo.infrastructure.EntityFactoryFramework.*; import josteo.infrastructure.DomainBase.*; import java.sql.ResultSet; /** * * @author cristiano */ public class TrattamentoFactory implements IEntityFactory<Trattamento>{ public Trattamento BuildEntity(Object recordset){ ResultSet rs = (ResultSet) recordset; int key = 0; Trattamento entity = null; Note note; try { key = rs.getInt("ID"); note = new Note(rs.getString("descrizione"), rs.getDate("data")); entity = new Trattamento(key, note); } catch(Exception exc) { System.out.println(exc.getMessage()); } return entity; } }
package test.oops.converter; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class CurrencyConverter { public static void main(String[] args) { List<Money> currency= new ArrayList<Money>(); Scanner sc= new Scanner(System.in); System.out.println("Enter the amount to be converted"); int amt= sc.nextInt(); //sc.nextLine(); System.out.println("Print the type of money as input"); int choice= sc.nextInt(); //sc.nextLine(); Money rupeemoney= new Rupees(); Money dollarmoney= new Dollar(); Money euromoney = new Euro(); Money poundmoney= new Pound(); currency.add(poundmoney); currency.add(euromoney); currency.add(dollarmoney); currency.add(rupeemoney); switch (choice) { case 1: System.out.println("Rupees"); rupeemoney.convert(amt); break; case 2: System.out.println("Dollars"); dollarmoney.convert(amt); break; case 3: System.out.println("Euro"); euromoney.convert(amt); break; case 4: System.out.println("Pound"); poundmoney.convert(amt); default: System.out.println("Currency not present in list"); break; } } }
package com.min.edu.model; import java.util.List; import java.util.Map; import com.min.edu.dto.MemberDTO; public interface MemberIDao { //회원가입 public boolean signUpMember(MemberDTO dto); //아이디 중복체크 0이면 true로 처리 public int idDuplicateCheck(String id); //아이디, 패스워드 맵에 담아서 로그인 public MemberDTO loginMember(Map<String,String> map); }
package com.edasaki.rpg.spells.assassin; import org.bukkit.entity.Player; import com.edasaki.core.utils.RParticles; import com.edasaki.rpg.PlayerDataRPG; import com.edasaki.rpg.spells.Spell; import com.edasaki.rpg.spells.SpellEffect; import de.slikey.effectlib.util.ParticleEffect; public class DoubleStab extends SpellEffect { public static final String BUFF_ID = "double stab"; @Override public boolean cast(final Player p, PlayerDataRPG pd, int level) { RParticles.showWithOffset(ParticleEffect.SPELL, p.getLocation().add(0, p.getEyeHeight() * 0.5, 0), 1.0, 15); double value = 0; switch (level) { case 1: value = 0.6; break; case 2: value = 0.7; break; case 3: value = 0.8; break; case 4: value = 0.9; break; case 5: value = 1.0; break; case 6: value = 1.1; break; case 7: value = 1.2; break; case 8: value = 1.3; break; case 9: value = 1.4; break; case 10: value = 1.5; break; case 11: value = 1.6; break; case 12: value = 1.7; break; case 13: value = 1.8; break; case 14: value = 1.9; break; case 15: value = 2.0; break; case 16: value = 2.1; break; case 17: value = 2.2; break; case 18: value = 2.3; break; case 19: value = 2.4; break; case 20: value = 2.5; break; case 21: value = 2.6; break; case 22: value = 2.7; break; case 23: value = 2.8; break; case 24: value = 2.9; break; case 25: value = 3.0; break; } pd.removeBuff(ShadowStab.BUFF_ID); pd.giveBuff(DoubleStab.BUFF_ID, value, Spell.LONG_DURATION); Spell.notify(p, "You prepare to double stab on your next attack."); return true; } }
// Kadane's algo // https://en.wikipedia.org/wiki/Maximum_subarray_problem public class Solution { public int maxSubArray(int[] nums) { int lmax=nums[0], gmax=nums[0]; for(int i=1; i<nums.length; i++) { // The main question that Kadane's algo cleverly addressed is how to // maintain subarray window, thus it's sum? // It uses a key insight in resetting start index of the window // // if lmax+x < x then reset the start and end index to current index // Otherwise add x to lmax and increment end index lmax = Math.max(lmax+nums[i], nums[i]); gmax = Math.max(lmax, gmax); } return gmax; } }
package com.aof.component.prm.project; import java.util.Date; import java.util.HashSet; import java.util.Set; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import com.aof.component.prm.bid.BidMaster; public class ProjPlanBomMaster { private long id; private ProjectMaster project; private BidMaster bid; private Long bom_id; private int version; private Date startDate; private Date endDate; private String status; private String ReveConfirm; private String CostConfirm; private String enable; private StandardBOMMaster template; public StandardBOMMaster getTemplate() { return template; } public void setTemplate(StandardBOMMaster template) { this.template = template; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public long getId() { return id; } public void setId(long id) { this.id = id; } public ProjectMaster getProject() { return project; } public void setProject(ProjectMaster project) { this.project = project; } public String getReveConfirm() { return ReveConfirm; } public void setReveConfirm(String reveConfirm) { ReveConfirm = reveConfirm; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } public String getEnable() { return enable; } public void setEnable(String enable) { this.enable = enable; } public String getCostConfirm() { return CostConfirm; } public void setCostConfirm(String costConfirm) { CostConfirm = costConfirm; } public BidMaster getBid() { return bid; } public void setBid(BidMaster bid) { this.bid = bid; } public Long getBom_id() { return bom_id; } public void setBom_id(Long bom_id) { this.bom_id = bom_id; } public boolean equals(Object other) { if ( !(other instanceof ProjPlanBomMaster) ) return false; ProjPlanBomMaster castOther = (ProjPlanBomMaster) other; return new EqualsBuilder() .append(this.getId(), castOther.getId()) .isEquals(); } public int hashCode() { return new HashCodeBuilder() .append(getId()) .toHashCode(); } }
package startgame; import javax.swing.JFrame; /** * The Class Main. */ public class Maingui { /** * The main method. * * @param args the arguments */ public static void main(String[] args) { Controller controller = new Controller(); controller.getView().setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); controller.getView().setSize(1370, 770); controller.getView().setTitle("Game"); controller.getView().setVisible(true); controller.getView().playpanel.setFocusable(true); controller.getView().playpanel.requestFocusInWindow(); } }
package io.zentity.common; import io.zentity.common.FunctionalUtil.Recursable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionStage; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; public class CompletableFutureUtil { /** * Returns a new {@link CompletionStage} that, when the passed stage completes exceptionally, * is composed using the results of the supplied function applied to this stage's exception. * * @param stage The current future stage. * @param fn The handler function. * @param <T> The future result type. * @return The wrapped future stage. * @see <a href="https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/util/concurrent/CompletionStage.html#exceptionallyCompose(java.util.function.Function)"></a> * @see <a href="https://github.com/spotify/completable-futures/blob/25bbd6e0c1c6cef974112aeb859938a6e927f4c5/src/main/java/com/spotify/futures/CompletableFutures.java"></a> */ public static <T> CompletionStage<T> composeExceptionally(CompletionStage<T> stage, Function<Throwable, ? extends CompletableFuture<T>> fn) { return stage .thenApply(CompletableFuture::completedFuture) .exceptionally(fn) .thenCompose(Function.identity()); } /** * Returns a new {@link CompletableFuture} that, when the passed future completes exceptionally, is * composed using the results of the supplied function applied to this stage's exception. * * @param fut The current future. * @param fn The handler function. * @param <T> The future result type. * @return The wrapped future. * @see <a href="https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/util/concurrent/CompletionStage.html#exceptionallyCompose(java.util.function.Function)"></a> * @see <a href="https://github.com/spotify/completable-futures/blob/25bbd6e0c1c6cef974112aeb859938a6e927f4c5/src/main/java/com/spotify/futures/CompletableFutures.java"></a> */ public static <T> CompletableFuture<T> composeExceptionally(CompletableFuture<T> fut, Function<Throwable, ? extends CompletableFuture<T>> fn) { return composeExceptionally((CompletionStage<T>) fut, fn).toCompletableFuture(); } /** * Unwrap a {@link CompletionException} to get the first cause that is not a {@link CompletionException}, or the * last-most {@link CompletionException} if there is no more specific cause. * * @param ex The exception. * @return The most specific {@link Throwable} that was found. */ public static Throwable getCause(Throwable ex) { Objects.requireNonNull(ex, "exception cannot be null"); if ((ex instanceof CompletionException || ex instanceof ExecutionException) && ex.getCause() != null) { return getCause(ex.getCause()); } return ex; } /** * Like {@link CompletableFuture#completedFuture} but completed exceptionally. * * @param throwable the cause. * @param <T> the future type. * @return the future, completed exceptionally. */ public static <T> CompletableFuture<T> exceptionallyCompletedFuture(Throwable throwable) { CompletableFuture<T> fut = new CompletableFuture<>(); fut.completeExceptionally(throwable); return fut; } /** * Create a looping recursive function. * * @param exitCondition The exit condition predicate. * @param futureSupplier A function to get a new {@link CompletableFuture} for recursive chaining, called once each loop. * @param <T> The type of the result of each loop. * @return A recursive function that will chain {@link CompletableFuture CompletableFutures} until the exit condition is met. */ public static <T> Recursable<T, CompletableFuture<T>> recursiveLoopFunction(final Predicate<T> exitCondition, final Supplier<CompletableFuture<T>> futureSupplier) { return (val, f) -> { if (exitCondition.test(val)) { return CompletableFuture.completedFuture(val); } return futureSupplier.get().thenCompose(f); }; } /** * Join all the results of a stream of futures into a list. * * @param futures The stream of {@link CompletableFuture CompletableFutures}. * @param <T> The item result type. * @return The list of results. */ public static <T> List<T> joinAllOf(Stream<CompletableFuture<T>> futures) { return futures.map(CompletableFuture::join).collect(Collectors.toList()); } /** * Join all the results of a collection of futures into a list. * * @param futures The collection of {@link CompletableFuture CompletableFutures}. * @param <T> The item result type. * @return The list of results. */ public static <T> List<T> joinAllOf(Collection<CompletableFuture<T>> futures) { return joinAllOf(futures.stream()); } /** * Like {@link CompletableFuture#allOf} but returns all the resulting values in a {@link List}. * * @param futures Collection of futures. * @param <T> The type of result item. * @return A future that completes with the combined result list. */ public static <T> CompletableFuture<List<T>> allOf(Collection<CompletableFuture<T>> futures) { CompletableFuture<Void> allFut = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])); return allFut.thenApply(nil -> joinAllOf(futures)); } /** * Like {@link CompletableFuture#allOf} but accepts a {@link Collection}. * * @param futures Collection of futures. * @return A future that completes when all futures in the collection are finished. */ public static CompletableFuture<Void> allOfIgnored(Collection<CompletableFuture<?>> futures) { return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])); } /** * Run a list of async operations one after the other. * * @param suppliers A list of suppliers that kick off async work. * @param <T> The result type of a single async task. * @return A future with the results of all of them. */ public static <T> CompletableFuture<List<T>> runSeries(Collection<Supplier<CompletableFuture<T>>> suppliers) { return suppliers .stream() .reduce( CompletableFuture.completedFuture(new ArrayList<>()), // accumulator (allFut, nextSupplier) -> allFut .thenCompose( (allItems) -> nextSupplier.get().thenApply((item) -> { allItems.add(item); return allItems; }) ), // combiner (fut1, fut2) -> fut1.thenCombine(fut2, (l1, l2) -> { l1.addAll(l2); return l1; }) ); } @SuppressWarnings("unchecked") static <T> CompletableFuture<List<T>> runParallelInChains(List<Supplier<CompletableFuture<T>>> suppliers, int parallelism) { final int size = suppliers.size(); // Hold on to all supplied futures so that results can be ordered at the end CompletableFuture<T>[] futures = new CompletableFuture[size]; final AtomicInteger currentIdx = new AtomicInteger(0); final CompletableFuture<Void> FINISHED = CompletableFuture.completedFuture(null); final Supplier<CompletableFuture<?>> nextFutureSupplier = () -> { int nextIdx = currentIdx.getAndIncrement(); if (nextIdx >= size) { // signal that there are no more futures to supply return FINISHED; } CompletableFuture<T> nextFuture = suppliers.get(nextIdx).get(); futures[nextIdx] = nextFuture; return nextFuture; }; // recursively get the next future to run immediately after the last future finishes final Recursable<CompletableFuture<?>, CompletableFuture<?>> futureRunner = (fut, f) -> { if (fut == FINISHED) { return FINISHED; } return fut.thenCompose((ignored) -> f.apply(nextFutureSupplier.get())); }; // "parallelism" number of "channels" for running as many at the same time as possible List<CompletableFuture<?>> channels = IntStream.range(0, parallelism) .mapToObj(i -> futureRunner.apply(CompletableFuture.completedFuture(null))) .collect(Collectors.toList()); return allOfIgnored(channels).thenApply((ignored) -> joinAllOf(Arrays.stream(futures))); } static <T> CompletableFuture<List<T>> runParallelInPartitions(List<Supplier<CompletableFuture<T>>> suppliers, int parallelism) { Collection<List<Supplier<CompletableFuture<T>>>> partitions = CollectionUtil.partition(suppliers, parallelism); return partitions .stream() .reduce( CompletableFuture.completedFuture(new ArrayList<>()), // accumulator (allFut, nextBatch) -> allFut .thenCompose( (allItems) -> runSeries(nextBatch).thenApply((item) -> { allItems.addAll(item); return allItems; }) ), // combiner (fut1, fut2) -> fut1.thenCombine(fut2, (l1, l2) -> { l1.addAll(l2); return l1; }) ); } /** * Run a list of async operations one after the other. * * <p> * NOTE: The current implementation recursively chains futures using {@link CompletableFuture#thenCompose}. * Running long lists of futures will cause a StackOverflow exception, as the future chains * will grow too long. To mitigate this for now, lists longer than 1,000 will be partitioned evenly * and each partition will be run in parallel which is less efficient, * especially when tasks widely vary in execution time. A nice optimization would be * a non-recursive implementation, likely involving another class to manage execution and "chaining". * * @param suppliers A list of suppliers that kick off async work. * @param parallelism The max async tasks to run at one time. * @param <T> The result type of a single async task. * @return A future with the results of all of them. */ public static <T> CompletableFuture<List<T>> runParallel(List<Supplier<CompletableFuture<T>>> suppliers, int parallelism) { if (parallelism < 1) { throw new IllegalArgumentException("Cannot have parallelism less than 1"); } if (parallelism == 1) { return runSeries(suppliers); } if (suppliers.size() < 1000) { return runParallelInChains(suppliers, parallelism); } // otherwise, just partition and run each partition in series return runParallelInPartitions(suppliers, parallelism); } }
package com.lrms.dao.impl; import org.springframework.stereotype.Repository; import com.lrms.dao.PatientBillPaymentDao; import com.lrms.model.PatientBillPayment; import com.lrms.util.HibernateDaoUtil; /** * * @author dward * */ @Repository public class PatientBillPaymentDaoImpl extends HibernateDaoUtil implements PatientBillPaymentDao{ @Override public boolean save(PatientBillPayment entity) { beginHibernateTransaction(); try { session.save(entity); tx.commit(); txnIsSuccess = true; } catch (Exception e) { tx.rollback(); e.printStackTrace(); } finally { closeHibernateSession(session); } return txnIsSuccess; } }
package org.openmrs.module.atomfeed; import java.util.Date; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openmrs.Patient; import org.openmrs.PatientIdentifier; import org.openmrs.PersonAddress; import org.openmrs.PersonAttribute; import org.openmrs.PersonName; import org.openmrs.Role; import org.openmrs.User; import org.openmrs.api.context.Context; public class Utils { static Log log = LogFactory.getLog("org.openmrs.module.atomfeed"); //static org.apache.log4j.Logger l = org.apache.log4j.Logger.getLogger("org.openmrs.module.atomfeed" ); // static org.slf4j.Logger lflog = LoggerFactory.getLogger("org.openmrs.module.atomfeed"); public static void logInfo(String message){ //l.info("L:"+message); log.info("LOG:"+message); //lflog.info("LFLOG:"+message); } public static void logDebug(String message){ //l.info("L:"+message); log.debug("LOG:"+message); //lflog.info("LFLOG:"+message); } public static void logWarn(String message){ //l.info("L:"+message); log.warn("LOG:"+message); //lflog.info("LFLOG:"+message); } public static boolean shouldCreateAtomfeed(User dataEntryUser) { String ignoreRoles = Context.getAdministrationService().getGlobalProperty("atomfeed.data-update.data-entry.roles-to-ignore"); logDebug("Ignorable Roles list:"+ignoreRoles); if(StringUtils.isBlank(ignoreRoles)){//no role to ignore. go ahead and create feed return true; } String[] rl = ignoreRoles.trim().split(","); for (String r : rl) { for (Role drl : dataEntryUser.getRoles()) { // has a role marked as ignorable.. donot create atomfeed.. donot use user.hasRole .. it doesnt work if(drl.getName().equalsIgnoreCase(r.trim())){ logInfo("Ignorable Role found:"+drl.getName()); return false; } } } return true;// create atomfeed. no role found to be ignored } public static String formatDataEntrySource(User user) { String deSource = ""; for (Role r : user.getRoles()) { deSource += r.getName()+","; } return deSource; } }
package br.com.apisEjpa.repository; import org.springframework.data.jpa.repository.JpaRepository; import br.com.apisEjpa.models.Vendedor; public interface VendedorRepository extends JpaRepository<Vendedor, Long> { Vendedor findByCodigo(long id); }
package com.lakin.garageopener10.app; import android.app.Activity; //import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.webkit.WebSettings; import android.webkit.WebView; public class MainActivity extends Activity { //private String mWebViewTempUrl; private WebView mWebView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mWebView = (WebView) findViewById(R.id.activity_main_webview); // Enable Javascript WebSettings webSettings = mWebView.getSettings(); webSettings.setJavaScriptEnabled(true); mWebView.loadUrl("http://lakin.home.kg/opener.php"); // Stop local links and redirects from opening in browser instead of WebView mWebView.setWebViewClient(new MyAppWebViewClient()); } @Override protected void onPause() { super.onPause(); // mWebViewTempUrl = mWebView.getUrl(); mWebView.loadUrl("http://lakin.home.kg/blank.html"); } @Override protected void onResume() { super.onResume(); // if (!mWebViewTempUrl.equals("") && mWebViewTempUrl != null) { mWebView.loadUrl("http://lakin.home.kg/opener.php"); // } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
package com.project.springboot.dao; import org.springframework.data.jpa.repository.JpaRepository; import com.project.springboot.entity.EmbededInvoiceBill; import com.project.springboot.entity.InvoiceBill; public interface InvoiceBillRepository extends JpaRepository<InvoiceBill, EmbededInvoiceBill>{ }
package revolt.backend.entity; import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; import lombok.experimental.FieldDefaults; import javax.persistence.*; @Getter @Setter @Entity @Table(name = "liquid") @FieldDefaults(level = AccessLevel.PRIVATE) public class Liquid { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) Long id; @Column(name = "liquid_name") String name; @Column(name = "liquid_nic") String nic; @Column(name = "liquid_price") Integer price; @Column(name = "liquid_description", length = 1000) String description; @Column(name = "liquid_picture") String picture; @Column(name = "liquid_value") String value; @ManyToOne @JoinColumn(name = "countryId") Country country; @ManyToOne @JoinColumn(name = "brandId") Brand brand; }
package com.bitwise.ticketbooking; import java.util.HashMap; import java.util.Map; public class AuthenticatedUser { HashMap<String,String> userList = new HashMap(); AuthenticatedUser(){ userList.put("pooja", "1234"); userList.put("nupur", "abcd"); } public HashMap getUserList(){ return userList; } public boolean validate(String name,String password){ if(userList.containsKey(name) && userList.get(name).equals(password)){ return true; } else return false; } }
package fr.bank; import org.junit.runner.RunWith; import cucumber.api.junit.Cucumber; @RunWith(Cucumber.class) public class RunCucumberTests { }
package Sorters; public class RadixSort extends Sorter{ public RadixSort (int[] array){ super(array); } private int findMax(){ int max = array[0]; for(int num: array){ max = (num > max) ? num : max; } return max; } @Override protected void sort(int start, int finish) { int max = findMax(); int base = 10; for(int i = 1; i <= max; i *= 10){ int[] temp = new int[array.length]; int pos = 0; for(int count = 0; count < base; count++){ for(int j = 0; j < array.length; j++){ if((array[j] / i) % 10 == count){ temp[pos++] = array[j]; } } } array = temp; } } }
// Decompiled by DJ v3.5.5.77 Copyright 2003 Atanas Neshkov Date: 2005-12-05 오후 4:43:01 // Home Page : http:// members.fortunecity.com/neshkov/dj.html - Check often for new version! // Decompiler options: packimports(3) // Source File Name: CPEduStudentBean.java package com.ziaan.cp; import java.sql.PreparedStatement; import java.sql.Statement; import java.util.ArrayList; import com.ziaan.library.ConfigSet; import com.ziaan.library.DBConnectionManager; import com.ziaan.library.DataBox; import com.ziaan.library.ErrorManager; import com.ziaan.library.FormatDate; import com.ziaan.library.ListSet; import com.ziaan.library.RequestBox; import com.ziaan.library.SQLString; import com.ziaan.library.StringManager; import com.ziaan.system.CodeConfigBean; public class CPEduStudentBean { public CPEduStudentBean() { try { config = new ConfigSet(); row = Integer.parseInt(config.getProperty("page.bulletin.row") ); } catch(Exception exception) { exception.printStackTrace(); } } public int getStucnt(RequestBox requestbox) throws Exception { DBConnectionManager dbconnectionmanager = null; Object obj = null; ListSet listset = null; Object obj1 = null; String s = ""; Object obj2 = null; String v_searchtext = requestbox.getString("p_searchtext"); String s2 = requestbox.getString("p_cp"); String s3 = requestbox.getString("s_grcode"); String s4 = requestbox.getString("s_gyear"); String s5 = requestbox.getString("s_grseq"); //String s6 = requestbox.getString("s_grcomp"); String s6 = requestbox.getStringDefault("s_grcomp", "ALL"); String s7 = ""; if ( !s6.equals("ALL")) s7 = s6; //s7 = s6.substring(0, 4); boolean flag = false; int j = 0; try { dbconnectionmanager = new DBConnectionManager(); ArrayList arraylist = new ArrayList(); if ( s4.equals("")) { s4 = FormatDate.getDate("yyyy"); requestbox.put("s_gyear", s4); } s = "select \n"; s = s + " subj, \n"; s = s + " subjnm, \n"; s = s + " year, \n"; s = s + " subjseq, \n"; s = s + " subjseqgr,\n"; s = s + " propstart, \n"; s = s + " propend,\n"; s = s + " edustart, \n"; s = s + " eduend, \n"; s = s + " cpnm, \n"; s = s + " cpsubjseq,\n"; s = s + " usercnt \n"; s = s + " from "; s = s + " ( "; s = s + " select \n"; s = s + " b.subj, \n"; s = s + " b.subjnm, \n"; s = s + " b.year, \n"; s = s + " b.subjseq, \n"; s = s + " b.subjseqgr,\n"; s = s + " b.propstart, \n"; s = s + " b.propend,\n"; s = s + " b.edustart, \n"; s = s + " b.eduend, \n"; s = s + " c.cpnm, \n"; s = s + " b.cpsubjseq,\n"; s = s + " ( \n"; s = s + " select \n"; s = s + " count(x.userid) \n"; s = s + " from \n"; s = s + " tz_student x, tz_member y \n"; s = s + " where \n"; s = s + " x.subj = b.subj \n"; s = s + " and x.subjseq = b.subjseq \n"; s = s + " and x.year = b.year \n"; s = s + " and x.userid = y.userid \n"; if ( !s6.equals("ALL")) s = s + " and y.comp = '" + s7 + "' \n"; //s = s + " and substr(y.comp, 1, 4) = '" + s7 + "' \n"; s = s + " ) as usercnt \n"; s = s + " from \n"; s = s + " vz_scsubjseq b, \n"; s = s + " tz_cpinfo c\n"; s = s + " where \n"; s = s + " 1=1 \n"; s = s + " and b.owner = c.cpseq \n"; if ( !s3.equals("")) { s = s + " and b.grcode = " + SQLString.Format(s3); if ( !v_searchtext.equals("")) s = s + " and lower(b.subjnm) like " + SQLString.Format("%" + v_searchtext.toLowerCase() + "%"); s = s + " and b.gyear = " + SQLString.Format(s4); if ( !s5.equals("ALL")) s = s + " and b.grseq = " + SQLString.Format(s5); if ( !s2.equals("ALL")) s = s + " and b.owner = " + SQLString.Format(s2); } s = s + " ) \n"; s = s + " where \n"; s = s + " usercnt != 0\n"; for ( listset = dbconnectionmanager.executeQuery(s); listset.next();) { int i = listset.getInt("usercnt"); j += i; } } catch(Exception exception1) { throw new Exception("sql = " + s + "\r\n" + exception1.getMessage() ); } finally { if ( listset != null ) try { listset.close(); } catch(Exception _ex) { } if ( dbconnectionmanager != null ) try { dbconnectionmanager.freeConnection(); } catch(Exception _ex) { } } return j; } public ArrayList selectApprovalList(RequestBox requestbox) throws Exception { DBConnectionManager dbconnectionmanager = null; java.sql.PreparedStatement preparedstatement = null; ListSet listset = null; ArrayList arraylist = null; String s = ""; Object obj = null; String v_searchtext = requestbox.getString("p_searchtext"); String s2 = requestbox.getString("p_cp"); String s3 = requestbox.getString("s_grcode"); String s4 = requestbox.getString("s_gyear"); String s5 = requestbox.getString("s_grseq"); int i = requestbox.getInt("p_pageno"); //String s6 = requestbox.getString("s_grcomp"); String s6 = requestbox.getStringDefault("s_grcomp", "ALL"); String s7 = ""; String v_orderColumn = requestbox.getString ("p_orderColumn" ); // 정렬할 컬럼명 String v_orderType = requestbox.getString ("p_orderType" ); // 정렬할 순서 if ( !s6.equals("ALL")) s7 = s6; //s7 = s6.substring(0, 4); try { dbconnectionmanager = new DBConnectionManager(); arraylist = new ArrayList(); if ( s4.equals("")) { s4 = FormatDate.getDate("yyyy"); requestbox.put("s_gyear", s4); } s = "select \n"; s = s + " subj, \n"; s = s + " subjnm, \n"; s = s + " year, \n"; s = s + " subjseq, \n"; s = s + " subjseqgr,\n"; s = s + " propstart, \n"; s = s + " propend,\n"; s = s + " edustart, \n"; s = s + " eduend, \n"; s = s + " cpnm, \n"; s = s + " cpsubjseq,\n"; s = s + " usercnt \n"; s = s + " from "; s = s + " ( "; s = s + " select \n"; s = s + " b.subj, \n"; s = s + " b.subjnm, \n"; s = s + " b.year, \n"; s = s + " b.subjseq, \n"; s = s + " b.subjseqgr,\n"; s = s + " b.propstart, \n"; s = s + " b.propend,\n"; s = s + " b.edustart, \n"; s = s + " b.eduend, \n"; s = s + " c.cpnm, \n"; s = s + " b.cpsubjseq,\n"; s = s + " ( \n"; s = s + " select \n"; s = s + " count(x.userid) \n"; s = s + " from \n"; s = s + " tz_student x, tz_member y \n"; s = s + " where \n"; s = s + " x.subj = b.subj \n"; s = s + " and x.subjseq = b.subjseq \n"; s = s + " and x.year = b.year \n"; s = s + " and x.userid = y.userid \n"; if ( !s6.equals("ALL")) s = s + " and y.comp = '" + s7 + "' \n"; //s = s + " and substr(y.comp, 1, 4) = '" + s7 + "' \n"; s = s + " ) as usercnt \n"; s = s + " from \n"; s = s + " vz_scsubjseq b, \n"; s = s + " tz_cpinfo c\n"; s = s + " where \n"; s = s + " 1=1 \n"; s = s + " and b.owner = c.cpseq \n"; if ( !s3.equals("")) { s = s + " and b.grcode = " + SQLString.Format(s3); if ( !v_searchtext.equals("")) s = s + " and lower(b.subjnm) like " + SQLString.Format("%" + v_searchtext.toLowerCase() + "%"); s = s + " and b.gyear = " + SQLString.Format(s4); if ( !s5.equals("ALL")) s = s + " and b.grseq = " + SQLString.Format(s5); if ( !s2.equals("ALL")) s = s + " and b.owner = " + SQLString.Format(s2); } s = s + " ) \n"; s = s + " where \n"; s = s + " usercnt != 0\n"; if ( v_orderColumn.equals("grseq" ) ) v_orderColumn = " C.grseq "; if ( !v_orderColumn.equals("") ) { s = s + " order by " + v_orderColumn + v_orderType + " \n"; } preparedstatement = dbconnectionmanager.prepareStatement(s, 1004, 1008); listset = new ListSet(preparedstatement); listset.setPageSize(row); listset.setCurrentPage(i); int j = listset.getTotalPage(); int k = listset.getTotalCount(); com.ziaan.library.DataBox databox; for ( ; listset.next(); arraylist.add(databox)) { databox = listset.getDataBox(); databox.put("d_dispnum", new Integer((k - listset.getRowNum() ) + 1)); databox.put("d_totalpage", new Integer(j)); databox.put("d_rowcount", new Integer(row)); } } catch(Exception exception1) { ErrorManager.getErrorStackTrace(exception1, requestbox, s); throw new Exception("sql = " + s + "\r\n" + exception1.getMessage() ); } finally { if ( listset != null ) try { listset.close(); } catch(Exception _ex) { } if ( preparedstatement != null ) try { preparedstatement.close(); } catch(Exception _ex) { } if ( dbconnectionmanager != null ) try { dbconnectionmanager.freeConnection(); } catch(Exception _ex) { } } return arraylist; } public ArrayList selectApprovalUserList(RequestBox requestbox) throws Exception { DBConnectionManager dbconnectionmanager = null; Statement statement = null; ListSet listset = null; ArrayList arraylist = null; String s = ""; Object obj = null; String s1 = requestbox.getString("p_gyear"); String s2 = requestbox.getString("p_year"); String s3 = requestbox.getString("p_subj"); String s4 = requestbox.getString("p_subjseq"); //String s5 = requestbox.getString("s_grcomp"); String s5 = requestbox.getStringDefault("s_grcomp", "ALL"); String s6 = ""; if ( !s5.equals("ALL")) s6 = s5; //s6 = s5.substring(0, 4); try { dbconnectionmanager = new DBConnectionManager(); arraylist = new ArrayList(); s = "select \n"; s = s + " a.userid, \n"; s = s + " a.name, \n"; s = s + " a.email, \n"; s = s + " a.handphone,\n"; //s = s + " a.comptel, \n"; s = s + " c.subjnm, \n"; s = s + " c.eduurl, \n"; s = s + " c.cpsubj, \n"; //s = s + " get_compnm(a.comp, 2, 2) compnm,\n"; //s = s + " get_cpsubjeduurl(a.userid, b.subj, b.year, b.subjseq, 'ZZ') cpeduurl"; s = s + " get_compnm(a.comp) compnm \n"; //s = s + " get_cpsubjeduurl(a.userid, b.subj, b.year, b.subjseq, 'ZZ') cpeduurl"; s = s + " from tz_member a, tz_student b, tz_subj c \n"; s = s + " where a.userid = b.userid "; s = s + " and b.year = " + SQLString.Format(s2); s = s + " and b.subj = " + SQLString.Format(s3); s = s + " and b.subjseq = " + SQLString.Format(s4); s = s + " and b.subj = c.subj "; if ( !s5.equals("ALL")) s = s + " and a.comp = '" + s6 + "' \n"; //s = s + " and substr(a.comp, 1, 4) = '" + s6 + "' \n"; s = s + "order by a.name"; System.out.println("cpstudent_sql == == >> >> " + s); com.ziaan.library.DataBox databox; for ( listset = dbconnectionmanager.executeQuery(s); listset.next(); arraylist.add(databox)) { databox = listset.getDataBox(); databox.put("d_dispnum", new Integer(listset.getRowNum() )); } String s7 = String.valueOf(listset.getRowNum() - 1); requestbox.put("d_totalrow", s7); } catch(Exception exception1) { ErrorManager.getErrorStackTrace(exception1, requestbox, s); throw new Exception("sql = " + s + "\r\n" + exception1.getMessage() ); } finally { if ( listset != null ) try { listset.close(); } catch(Exception _ex) { } if ( statement != null ) try { statement.close(); } catch(Exception _ex) { } if ( dbconnectionmanager != null ) try { dbconnectionmanager.freeConnection(); } catch(Exception _ex) { } } return arraylist; } public String selectCPseq(String s) throws Exception { DBConnectionManager dbconnectionmanager = null; ListSet listset = null; String s1 = ""; Object obj = null; String s2 = ""; try { dbconnectionmanager = new DBConnectionManager(); s1 = "select cpseq, cpnm "; s1 = s1 + " from tz_cpinfo "; s1 = s1 + " where userid = " + SQLString.Format(s); for ( listset = dbconnectionmanager.executeQuery(s1); listset.next();) s2 = listset.getString("cpseq"); } catch(Exception exception1) { throw new Exception("sql = " + s1 + "\r\n" + exception1.getMessage() ); } finally { if ( listset != null ) try { listset.close(); } catch(Exception _ex) { } if ( dbconnectionmanager != null ) try { dbconnectionmanager.freeConnection(); } catch(Exception _ex) { } } return s2; } public ArrayList selectCancelList(RequestBox requestbox) throws Exception { DBConnectionManager dbconnectionmanager = null; java.sql.PreparedStatement preparedstatement = null; ListSet listset = null; ArrayList arraylist = null; String s = ""; Object obj = null; String s1 = requestbox.getString("p_searchtext"); String s2 = requestbox.getString("p_cp"); String s3 = requestbox.getString("s_grcode"); String s4 = requestbox.getString("s_gyear"); String s5 = requestbox.getString("s_grseq"); int i = requestbox.getInt("p_pageno"); //String s6 = requestbox.getString("s_grcomp"); String s6 = requestbox.getStringDefault("s_grcomp", "ALL"); String s7 = ""; if ( !s6.equals("ALL")) s7 = s6; //s7 = s6.substring(0, 4); try { dbconnectionmanager = new DBConnectionManager(); arraylist = new ArrayList(); if ( s4.equals("")) { s4 = FormatDate.getDate("yyyy"); requestbox.put("s_gyear", s4); } s = s + " select \n"; s = s + " subj, \n"; s = s + " subjnm, \n"; s = s + " year, \n"; s = s + " subjseq, \n"; s = s + " subjseqgr,\n"; s = s + " propstart, \n"; s = s + " propend,\n"; s = s + " edustart, \n"; s = s + " eduend, \n"; s = s + " cpnm, \n"; s = s + " cpsubjseq,\n"; s = s + " usercnt \n"; s = s + " from \n"; s = s + " ( \n"; s = s + " select \n"; s = s + " b.subj, \n"; s = s + " b.subjnm, \n"; s = s + " b.year, \n"; s = s + " b.subjseq, \n"; s = s + " b.subjseqgr,\n"; s = s + " b.propstart, \n"; s = s + " b.propend,\n"; s = s + " b.edustart, \n"; s = s + " b.eduend, \n"; s = s + " c.cpnm, \n"; s = s + " b.cpsubjseq,\n"; s = s + " ( \n"; s = s + " select \n"; s = s + " count(x.userid) \n"; s = s + " from \n"; s = s + " tz_cancel x, tz_member y \n"; s = s + " where \n"; s = s + " x.subj = b.subj \n"; s = s + " and x.subjseq = b.subjseq \n"; s = s + " and x.year = b.year \n"; s = s + " and x.userid = y.userid \n"; if ( !s6.equals("ALL")) s = s + " and y.comp = '" + s7 + "' \n"; //s = s + " and substr(y.comp, 1, 4) = '" + s7 + "' \n"; s = s + " ) as usercnt \n"; s = s + " from \n"; s = s + " vz_scsubjseq b, \n"; s = s + " tz_cpinfo c\n"; s = s + " where \n"; s = s + " 1=1 \n"; s = s + " and b.owner = c.cpseq \n"; if ( !s3.equals("")) { s = s + " and b.grcode = " + SQLString.Format(s3); if ( !s1.equals("")) s = s + " and b.subjnm like " + SQLString.Format("%" + s1 + "%"); s = s + " and b.gyear = " + SQLString.Format(s4); if ( !s5.equals("ALL")) s = s + " and b.grseq = " + SQLString.Format(s5); if ( !s2.equals("ALL")) s = s + " and b.owner = " + SQLString.Format(s2); } s = s + " ) \n"; s = s + " where \n"; s = s + " usercnt != 0\n"; preparedstatement = dbconnectionmanager.prepareStatement(s, 1004, 1008); listset = new ListSet(preparedstatement); listset.setPageSize(row); listset.setCurrentPage(i); int j = listset.getTotalPage(); int k = listset.getTotalCount(); com.ziaan.library.DataBox databox; for ( ; listset.next(); arraylist.add(databox)) { databox = listset.getDataBox(); databox.put("d_dispnum", new Integer((k - listset.getRowNum() ) + 1)); databox.put("d_totalpage", new Integer(j)); databox.put("d_rowcount", new Integer(row)); } } catch(Exception exception1) { ErrorManager.getErrorStackTrace(exception1, requestbox, s); throw new Exception("sql = " + s + "\r\n" + exception1.getMessage() ); } finally { if ( listset != null ) try { listset.close(); } catch(Exception _ex) { } if ( preparedstatement != null ) try { preparedstatement.close(); } catch(Exception _ex) { } if ( dbconnectionmanager != null ) try { dbconnectionmanager.freeConnection(); } catch(Exception _ex) { } } return arraylist; } /** 과목별 취소인원 엑셀 다운로드 * selectCancelListExcel * @param requestbox * @return * @throws Exception */ public ArrayList selectCancelListExcel(RequestBox requestbox) throws Exception { DBConnectionManager dbconnectionmanager = null; Statement statement = null; ListSet listset = null; ArrayList arraylist = null; String s = ""; Object obj = null; String s1 = requestbox.getString("p_gyear"); String s2 = requestbox.getString("p_year"); String s3 = requestbox.getString("p_subj"); String s4 = requestbox.getString("p_subjseq"); //String s5 = requestbox.getString("s_grcomp"); String s5 = requestbox.getStringDefault("s_grcomp", "ALL"); String s6 = ""; if ( !s5.equals("ALL")) s6 = s5; //s6 = s5.substring(0, 4); try { dbconnectionmanager = new DBConnectionManager(); arraylist = new ArrayList(); //s = "select a.userid, a.name, a.email, a.handphone, a.comptel, c.subjnm, c.eduurl, c.cpsubj, b.canceldate, b.reason "; //2008.11.11 comptel 컬럼이 없음 s = "select a.userid, a.name, a.email, a.handphone, '' comptel, c.subjnm, c.eduurl, c.cpsubj, b.canceldate, b.reason "; s = s + " from tz_member a, tz_cancel b, tz_subj c "; s = s + " where a.userid = b.userid "; s = s + " and b.year = " + SQLString.Format(s2); s = s + " and b.subj = " + SQLString.Format(s3); s = s + " and b.subjseq = " + SQLString.Format(s4); s = s + " and b.subj = c.subj "; if ( !s5.equals("ALL")) s = s + " and a.comp = '" + s6 + "' \n"; //s = s + " and substr(a.comp, 1, 4) = '" + s6 + "' \n"; s = s + " order by a.name "; com.ziaan.library.DataBox databox; for ( listset = dbconnectionmanager.executeQuery(s); listset.next(); arraylist.add(databox)) { databox = listset.getDataBox(); databox.put("d_dispnum", new Integer(listset.getRowNum() )); } String s7 = String.valueOf(listset.getRowNum() - 1); requestbox.put("d_totalrow", s7); } catch(Exception exception1) { ErrorManager.getErrorStackTrace(exception1, requestbox, s); throw new Exception("sql = " + s + "\r\n" + exception1.getMessage() ); } finally { if ( listset != null ) try { listset.close(); } catch(Exception _ex) { } if ( statement != null ) try { statement.close(); } catch(Exception _ex) { } if ( dbconnectionmanager != null ) try { dbconnectionmanager.freeConnection(); } catch(Exception _ex) { } } return arraylist; } public ArrayList selectCancelUserList(RequestBox requestbox) throws Exception { DBConnectionManager dbconnectionmanager = null; Statement statement = null; ListSet listset = null; ArrayList arraylist = null; String s = ""; Object obj = null; String s1 = requestbox.getString("p_gyear"); String s2 = requestbox.getString("p_year"); String s3 = requestbox.getString("p_subj"); String s4 = requestbox.getString("p_subjseq"); //String s5 = requestbox.getString("s_grcomp"); String s5 = requestbox.getStringDefault("s_grcomp", "ALL"); String s6 = ""; if ( !s5.equals("ALL")) s6 = s5; //s6 = s5.substring(0, 4); try { dbconnectionmanager = new DBConnectionManager(); arraylist = new ArrayList(); //s = "select a.userid, a.name, a.email, a.handphone, a.comptel, c.subjnm, c.eduurl, c.cpsubj, b.canceldate, b.reason "; //2008.11.11 comptel 컬럼이 없음 s = "select a.userid, a.name, a.email, a.handphone, '' comptel, c.subjnm, c.eduurl, c.cpsubj, b.canceldate, b.reason "; s = s + " from tz_member a, tz_cancel b, tz_subj c "; s = s + " where a.userid = b.userid "; s = s + " and b.year = " + SQLString.Format(s2); s = s + " and b.subj = " + SQLString.Format(s3); s = s + " and b.subjseq = " + SQLString.Format(s4); s = s + " and b.subj = c.subj "; if ( !s5.equals("ALL")) s = s + " and a.comp = '" + s6 + "' \n"; //s = s + " and substr(a.comp, 1, 4) = '" + s6 + "' \n"; s = s + " order by a.name "; com.ziaan.library.DataBox databox; for ( listset = dbconnectionmanager.executeQuery(s); listset.next(); arraylist.add(databox)) { databox = listset.getDataBox(); databox.put("d_dispnum", new Integer(listset.getRowNum() )); } String s7 = String.valueOf(listset.getRowNum() - 1); requestbox.put("d_totalrow", s7); } catch(Exception exception1) { ErrorManager.getErrorStackTrace(exception1, requestbox, s); throw new Exception("sql = " + s + "\r\n" + exception1.getMessage() ); } finally { if ( listset != null ) try { listset.close(); } catch(Exception _ex) { } if ( statement != null ) try { statement.close(); } catch(Exception _ex) { } if ( dbconnectionmanager != null ) try { dbconnectionmanager.freeConnection(); } catch(Exception _ex) { } } return arraylist; } public ArrayList selectExcel(RequestBox requestbox) throws Exception { DBConnectionManager dbconnectionmanager = null; Statement statement = null; ListSet listset = null; ArrayList arraylist = null; String s = ""; Object obj = null; String s1 = requestbox.getString("p_downgubun"); String s2 = requestbox.getString("p_gyear"); String s3 = requestbox.getString("p_year"); String s4 = requestbox.getString("p_subj"); String s5 = requestbox.getString("p_subjseq"); //String s6 = requestbox.getString("s_grcomp"); String s6 = requestbox.getStringDefault("s_grcomp", "ALL"); String s7 = ""; if ( !s6.equals("ALL")) s7 = s6; //s7 = s6.substring(0, 4); try { dbconnectionmanager = new DBConnectionManager(); arraylist = new ArrayList(); if ( s1.equals("1")) { s = "select \n"; s = s + " a.userid, \n"; s = s + " a.name, \n"; s = s + " a.email, \n"; s = s + " a.handphone,\n"; //s = s + " a.comptel, \n"; s = s + " c.subjnm, \n"; s = s + " c.eduurl, \n"; s = s + " c.cpsubj, \n"; s = s + " fn_crypt('2', a.birth_date, 'knise') birth_date, \n"; //s = s + " get_compnm(a.comp, 2, 2) compnm\n"; s = s + " get_compnm(a.comp) compnm\n"; s = s + " from tz_member a, tz_student b, tz_subj c \n"; s = s + " where a.userid = b.userid "; s = s + " and b.year = " + SQLString.Format(s3); s = s + " and b.subj = " + SQLString.Format(s4); s = s + " and b.subjseq = " + SQLString.Format(s5); s = s + " and b.subj = c.subj "; if ( !s6.equals("ALL")) s = s + " and a.comp = '" + s7 + "' \n"; //s = s + " and substr(a.comp, 1, 4) = '" + s7 + "' \n"; s = s + "order by a.name"; } else if ( s1.equals("2")) { //s = "select a.userid, a.name, a.email, a.handphone, a.comptel, c.subjnm, c.eduurl, c.cpsubj, b.canceldate, b.reason, a.birth_date "; s = "select a.userid, a.name, a.email, a.handphone, c.subjnm, c.eduurl, c.cpsubj, b.canceldate, b.reason, fn_crypt('2', a.birth_date, 'knise') birth_date "; s = s + " from tz_member a, tz_cancel b, tz_subj c "; s = s + " where a.userid = b.userid "; s = s + " and b.year = " + SQLString.Format(s3); s = s + " and b.subj = " + SQLString.Format(s4); s = s + " and b.subjseq = " + SQLString.Format(s5); s = s + " and b.subj = c.subj "; if ( !s6.equals("ALL")) s = s + " and a.comp = '" + s7 + "' \n"; //s = s + " and substr(a.comp, 1, 4) = '" + s7 + "' \n"; s = s + " order by a.name "; } else if ( s1.equals("3")) { s = "select a.userid, a.name, fn_crypt('2', a.birth_date, 'knise') birth_date, '' jikwinm, a.email, a.comptel, a.handphone, b.appdate as adate, c.subjnm, c.eduurl, c.cpsubj "; s = s + " from tz_member a, tz_propose b, tz_subj c "; s = s + " where a.userid = b.userid "; s = s + " and b.year = " + SQLString.Format(s3); s = s + " and b.subj = " + SQLString.Format(s4); s = s + " and b.subjseq = " + SQLString.Format(s5); s = s + " and b.subj = c.subj "; } System.out.println(s); com.ziaan.library.DataBox databox; for ( listset = dbconnectionmanager.executeQuery(s); listset.next(); arraylist.add(databox)) { databox = listset.getDataBox(); databox.put("d_dispnum", new Integer(listset.getRowNum() )); } String s8 = String.valueOf(listset.getRowNum() - 1); requestbox.put("total_row_count", s8); } catch(Exception exception1) { ErrorManager.getErrorStackTrace(exception1, requestbox, s); throw new Exception("sql = " + s + "\r\n" + exception1.getMessage() ); } finally { if ( listset != null ) try { listset.close(); } catch(Exception _ex) { } if ( statement != null ) try { statement.close(); } catch(Exception _ex) { } if ( dbconnectionmanager != null ) try { dbconnectionmanager.freeConnection(); } catch(Exception _ex) { } } return arraylist; } public ArrayList selectProposeList(RequestBox requestbox) throws Exception { DBConnectionManager dbconnectionmanager = null; java.sql.PreparedStatement preparedstatement = null; ListSet listset = null; ArrayList arraylist = null; String s = ""; Object obj = null; String s1 = requestbox.getString("p_searchtext"); String s2 = requestbox.getString("p_cp"); String s3 = requestbox.getString("s_grcode"); String s4 = requestbox.getString("s_gyear"); int i = requestbox.getInt("p_pageno"); try { dbconnectionmanager = new DBConnectionManager(); arraylist = new ArrayList(); if ( s4.equals("")) { s4 = FormatDate.getDate("yyyy"); requestbox.put("s_gyear", s4); } s = "select a.subj, a.subjnm, b.year, b.subjseq, b.propstart, b.propend, b.edustart, b.eduend, c.cpnm, b.cpsubjseq, count(d.userid) as usercnt "; s = s + " from tz_subj a, tz_subjseq b, tz_cpinfo c, tz_propose d "; s = s + " where a.subj = b.subj and "; s = s + " b.subj = d.subj( +) and "; s = s + " b.year = d.year( +) and "; s = s + " b.subjseq = d.subjseq( +) and "; if ( !s3.equals("")) { s = s + " b.grcode = " + SQLString.Format(s3); s = s + " and "; if ( !s1.equals("")) { s = s + " a.subjnm like " + SQLString.Format("%" + s1 + "%"); if ( !s4.equals("")) s = s + " and "; } if ( !s4.equals("") && !s4.equals("ALL")) { s = s + " b.gyear = " + SQLString.Format(s4); s = s + " and "; } else if ( s4.equals("")) { s = s + " b.gyear = " + SQLString.Format(FormatDate.getDate("yyyy") ); s = s + " and "; } if ( !s2.equals("") && !s2.equals("ALL")) { s = s + " a.owner = " + SQLString.Format(s2); s = s + " and a.owner = c.cpseq "; } else if ( !s2.equals("") || s2.equals("ALL")) s = s + " a.owner = c.cpseq "; else s = s + " a.owner = c.cpseq "; } else { s = s + " b.grcode = 'zzzzzz'"; } s = s + " group by a.subj, a.subjnm, b.year, b.subjseq, b.propstart, b.propend, b.edustart, b.eduend, b.cpsubjseq, c.cpnm "; preparedstatement = dbconnectionmanager.prepareStatement(s, 1004, 1008); listset = new ListSet(preparedstatement); listset.setPageSize(row); listset.setCurrentPage(i); int j = listset.getTotalPage(); int k = listset.getTotalCount(); com.ziaan.library.DataBox databox; for ( ; listset.next(); arraylist.add(databox)) { databox = listset.getDataBox(); databox.put("d_dispnum", new Integer((k - listset.getRowNum() ) + 1)); databox.put("d_totalpage", new Integer(j)); databox.put("d_rowcount", new Integer(row)); } } catch(Exception exception1) { ErrorManager.getErrorStackTrace(exception1, requestbox, s); throw new Exception("sql = " + s + "\r\n" + exception1.getMessage() ); } finally { if ( listset != null ) try { listset.close(); } catch(Exception _ex) { } if ( preparedstatement != null ) try { preparedstatement.close(); } catch(Exception _ex) { } if ( dbconnectionmanager != null ) try { dbconnectionmanager.freeConnection(); } catch(Exception _ex) { } } return arraylist; } public ArrayList selectProposeUserList(RequestBox requestbox) throws Exception { DBConnectionManager dbconnectionmanager = null; Statement statement = null; ListSet listset = null; ArrayList arraylist = null; String s = ""; Object obj = null; String s1 = requestbox.getString("p_gyear"); String s2 = requestbox.getString("p_year"); String s3 = requestbox.getString("p_subj"); String s4 = requestbox.getString("p_subjseq"); try { dbconnectionmanager = new DBConnectionManager(); arraylist = new ArrayList(); s = "select a.userid, a.name, a.email, a.handphone, c.subjnm, c.eduurl, c.cpsubj "; s = s + " from tz_member a, tz_propose b, tz_subj c "; s = s + " where a.userid = b.userid "; s = s + " and b.year = " + SQLString.Format(s2); s = s + " and b.subj = " + SQLString.Format(s3); s = s + " and b.subjseq = " + SQLString.Format(s4); s = s + " and b.subj = c.subj "; com.ziaan.library.DataBox databox; for ( listset = dbconnectionmanager.executeQuery(s); listset.next(); arraylist.add(databox)) { databox = listset.getDataBox(); databox.put("d_dispnum", new Integer(listset.getRowNum() )); } String s5 = String.valueOf(listset.getRowNum() - 1); requestbox.put("d_totalrow", s5); } catch(Exception exception1) { ErrorManager.getErrorStackTrace(exception1, requestbox, s); throw new Exception("sql = " + s + "\r\n" + exception1.getMessage() ); } finally { if ( listset != null ) try { listset.close(); } catch(Exception _ex) { } if ( statement != null ) try { statement.close(); } catch(Exception _ex) { } if ( dbconnectionmanager != null ) try { dbconnectionmanager.freeConnection(); } catch(Exception _ex) { } } return arraylist; } /** 수강확정/취소/신청 명단 엑셀 다운로드 @param box receive from the form object and session @return ArrayList 수강확정/취소/신청자 리스트 */ public ArrayList selectStudentExcel(RequestBox box) throws Exception { DBConnectionManager connMgr = null; PreparedStatement pstmt = null; ListSet ls = null; ArrayList list = null; String sql = ""; DataBox dbox = null; String downgubun; // 엑셀다운구분(1:확정자,2:취소자,3:신청자) downgubun = box.getString("p_downgubun"); String v_syear = box.getString("p_syear"); // 수강시작년도 String v_smon = CodeConfigBean.addZero(StringManager.toInt(box.getString("p_smon")), 2); // 수강시작월 String v_sday = CodeConfigBean.addZero(StringManager.toInt(box.getString("p_sday")), 2); // 수강시작일 String v_start = v_syear + v_smon + v_sday; String v_eyear = box.getString("p_eyear"); // 수강종료년도 String v_emon = CodeConfigBean.addZero(StringManager.toInt(box.getString("p_emon")), 2); // 수강종료월 String v_eday = CodeConfigBean.addZero(StringManager.toInt(box.getString("p_eday")), 2); // 수강종료일 String v_end = v_eyear + v_emon + v_eday; String v_grcode = box.getString("s_grcode"); String v_cp = box.getString("p_cp"); if ( box.getSession("gadmin").equals("S1") ) { // 외주업체 담당자라면 해당 회사정보코드를 알아낸다. v_cp = this.selectCPseq(box.getSession("userid") ); // v_cp = CodeConfigBean.addZero(StringManager.toInt(v_seq), 5); } try { System.out.println("v_start : " + v_start ); System.out.println("v_end : " + v_end ); connMgr = new DBConnectionManager(); list = new ArrayList(); if ( downgubun.equals("1") ) { // 확정자 명단 다운로드 //sql = " select a.userid, a.name, '' jikwinm, a.birth_date, a.email, a.comptel, a.handphone, \n"; sql = " select a.userid, a.name, '' jikwinm, fn_crypt('2', a.birth_date, 'knise') birth_date, a.email, a.handphone, get_compnm(a.comp) compnm, a.position_nm, a.lvl_nm, \n"; sql += " (select appdate from tz_propose x where x.subj = b.subj and x.subjseq = b.subjseq and x.year = b.year and x.userid = b.userid) as adate, \n"; sql += " c.subjnm, c.subjseq, c.subjseqgr, c.cpsubjseq, c.edustart, c.eduend, d.cpnm, e.grcodenm, \n"; sql += " '' work_plcnm \n"; sql += " from tz_member a, tz_student b, tz_subjseq c, tz_cpinfo d, tz_grcode e, tz_subj f \n"; sql += " where a.userid = b.userid \n"; sql += " and b.subj = c.subj \n"; sql += " and b.subjseq = c.subjseq \n"; sql += " and b.year = c.year \n"; sql += " and c.subj = f.subj \n"; sql += " and f.owner = d.cpseq \n"; sql += " and c.grcode = e.grcode \n"; sql += " and ( \n"; sql += " c.edustart BETWEEN " + SQLString.Format(v_start + "00") + " AND " + SQLString.Format(v_end + "23") + " \n"; sql += " and \n"; sql += " c.eduend BETWEEN " + SQLString.Format(v_start + "00") + " AND " + SQLString.Format(v_end + "23") + " \n"; sql += " ) \n"; /* 09.10.30 수정 sql += " and ( \n"; sql += " c.edustart BETWEEN " + SQLString.Format(v_start + "000000") + " AND " + SQLString.Format(v_end + "235959") + " \n"; sql += " or \n"; sql += " c.eduend BETWEEN " + SQLString.Format(v_start + "000000") + " AND " + SQLString.Format(v_end + "235959") + " \n"; sql += " ) \n"; */ /* sql += " and ( \n"; sql += " (substr(c.edustart,1,8) <= " + SQLString.Format(v_start) + " \n"; sql += " and substr(c.eduend,1,8) >= " + SQLString.Format(v_start) + " \n"; sql += " ) or ( \n"; sql += " substr(c.edustart,1,8) <= " + SQLString.Format(v_end) + " \n"; sql += " and substr(c.eduend,1,8) >= " + SQLString.Format(v_end) + " \n"; sql += " ) ) \n"; */ // sql += " and b.isproposeapproval = ANY('Y','L') "; // sql += " and b.chkfinal = 'Y' "; // sql += " and (nvl(b.cancelkind,'zz') = 'zz' or length(ltrim(b.cancelkind)) = 0) "; } else if ( downgubun.equals("2") ) { // 취소자 명단 다운로드 //sql = " select a.userid, a.name, '' orga_ename, '' jikwinm, a.birth_date, a.email, a.comptel, a.handphone, \n"; sql = " select a.userid, a.name, '' orga_ename, '' jikwinm, fn_crypt('2', a.birth_date, 'knise') birth_date, a.email, a.handphone, get_compnm(a.comp) compnm, a.position_nm, a.lvl_nm, \n"; sql += " b.canceldate as adate, c.subjnm, c.subjseq, c.subjseqgr, c.cpsubjseq, c.edustart, c.eduend, d.cpnm, e.grcodenm, \n"; sql += " '' work_plcnm \n"; sql += " from tz_member a, tz_cancel b, tz_subjseq c, tz_cpinfo d, tz_grcode e, tz_subj f \n"; sql += " where a.userid = b.userid \n"; sql += " and b.subj = c.subj \n"; sql += " and b.subjseq = c.subjseq \n"; sql += " and b.year = c.year \n"; sql += " and c.subj = f.subj \n"; sql += " and f.owner = d.cpseq \n"; sql += " and c.grcode = e.grcode \n"; sql += " and ( \n"; sql += " c.edustart BETWEEN " + SQLString.Format(v_start + "00") + " AND " + SQLString.Format(v_end + "23") + " \n"; sql += " and \n"; sql += " c.eduend BETWEEN " + SQLString.Format(v_start + "00") + " AND " + SQLString.Format(v_end + "23") + " \n"; sql += " ) \n"; /* 09.10.30 수정 sql += " and ( \n"; sql += " c.edustart BETWEEN " + SQLString.Format(v_start + "000000") + " AND " + SQLString.Format(v_end + "235959") + " \n"; sql += " or \n"; sql += " c.eduend BETWEEN " + SQLString.Format(v_start + "000000") + " AND " + SQLString.Format(v_end + "235959") + " \n"; sql += " ) \n"; */ /* sql += " and ( \n"; sql += " (substr(c.edustart,1,8) <= " + SQLString.Format(v_start) + " \n"; sql += " and substr(c.eduend,1,8) >= " + SQLString.Format(v_start) + " \n"; sql += " ) or ( \n"; sql += " substr(c.edustart,1,8) <= " + SQLString.Format(v_end) + " \n"; sql += " and substr(c.eduend,1,8) >= " + SQLString.Format(v_end) + " \n"; sql += " ) )"; */ } else if ( downgubun.equals("3") ) { // 신청자 명단 다운로드 //sql = " select a.userid, a.name, '' orga_ename, '' jikwinm, a.birth_date, a.email, a.comptel, a.handphone, \n"; sql = " select a.userid, a.name, '' orga_ename, '' jikwinm, fn_crypt('2', a.birth_date, 'knise') birth_date, a.email, a.handphone, get_compnm(a.comp) compnm, \n"; sql += " b.appdate as adate, c.subjnm, c.subjseq, c.subjseqgr, c.cpsubjseq, c.edustart, c.eduend, d.cpnm, e.grcodenm, \n"; sql += " '' work_plcnm \n"; sql += " from tz_member a, tz_propose b, tz_subjseq c, tz_cpinfo d, tz_grcode e, tz_subj f \n"; sql += " where a.userid = b.userid \n"; sql += " and b.subj = c.subj \n"; sql += " and b.subjseq = c.subjseq \n"; sql += " and b.year = c.year \n"; sql += " and c.subj = f.subj \n"; sql += " and f.owner = d.cpseq \n"; sql += " and c.grcode = e.grcode \n"; sql += " and ( \n"; sql += " c.edustart BETWEEN " + SQLString.Format(v_start + "00") + " AND " + SQLString.Format(v_end + "23") + " \n"; sql += " and \n"; sql += " c.eduend BETWEEN " + SQLString.Format(v_start + "00") + " AND " + SQLString.Format(v_end + "23") + " \n"; sql += " ) \n"; /* 09.10.30 수정 sql += " and ( \n"; sql += " c.edustart BETWEEN " + SQLString.Format(v_start + "000000") + " AND " + SQLString.Format(v_end + "235959") + " \n"; sql += " or \n"; sql += " c.eduend BETWEEN " + SQLString.Format(v_start + "000000") + " AND " + SQLString.Format(v_end + "235959") + " \n"; sql += " ) \n"; */ /* sql += " and ( \n"; sql += " (substr(c.edustart,1,8) <= " + SQLString.Format(v_start) + " \n"; sql += " and substr(c.eduend,1,8) >= " + SQLString.Format(v_start) + " \n"; sql += " ) or ( \n"; sql += " substr(c.edustart,1,8) <= " + SQLString.Format(v_end) + " \n"; sql += " and substr(c.eduend,1,8) >= " + SQLString.Format(v_end) + " \n"; sql += " ) )"; */ } if ( !v_grcode.equals("ALL") ) { sql += " and e.grcode = " + SQLString.Format(v_grcode); } if ( !v_cp.equals("ALL") ) { sql += " and d.cpseq = " + SQLString.Format(v_cp); } sql += " order by e.grcode "; // System.out.println("cpsql == == =< > < > < > < > < > < > < > < > excel< > < > < > < > < > < > < > < > < > " +sql); ls = connMgr.executeQuery(sql); while ( ls.next() ) { dbox = ls.getDataBox(); dbox.put("d_dispnum", new Integer( ls.getRowNum() )); list.add(dbox); } String total_row_count = "" + ( ls.getRowNum() - 1); // 전체 row 수를 반환한다 box.put("total_row_count",total_row_count); } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( pstmt != null ) { try { pstmt.close(); } catch ( Exception e1 ) { } } // 꼭 닫아준다 if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return list; } private ConfigSet config; private int row; }
/* * 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 gt.com.atel.bossassigner.implementation; import javax.enterprise.context.RequestScoped; import javax.enterprise.inject.Alternative; import javax.inject.Named; /** * * @author atel */ @Named("bossMockAssignerImpl") @RequestScoped @Alternative public class BossMockAssignerImpl implements BossAssignerService { @Override public String assignBoss() { return "This is a mock test"; } }
package com.cdero.gamerbot.audio; //import statements import com.cdero.gamerbot.audio.lavaplayer.GuildMusicManager; import com.cdero.gamerbot.audio.lavaplayer.MusicManagers; import net.dv8tion.jda.api.entities.TextChannel; import net.dv8tion.jda.api.entities.VoiceChannel; import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent; /** * * @author Christopher DeRoche * @version 1.0 * @since 1.0 * */ public class NowPlayingCommand { /** * Responds with a message showing the currently playing track from Gamer Bot. * * @param event Gets and sends the current audio queue to the channel where the message was sent from. */ protected NowPlayingCommand(GuildMessageReceivedEvent event) { TextChannel channel = event.getChannel(); VoiceChannel voiceChannel = event.getMember().getVoiceState().getChannel(); GuildMusicManager musicManager = MusicManagers.musicManagers.get(event.getGuild().getIdLong()); if (voiceChannel == null) { channel.sendMessage(":x: **You are not connected to a voice channel!**").queue(); return; } else if (musicManager == null || musicManager.player.getPlayingTrack() == null) { channel.sendMessage(":x: **There is nothing playing!**").queue(); return; } else { channel.sendMessage(":white_check_mark: **Currently playing :arrow_right: " + musicManager.player.getPlayingTrack().getInfo().title + "**").queue(); return; } } }
package com.service; import java.util.HashMap; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.dao.HouseDAO; import com.dto.HouseInfoDTO; import com.dto.HouseOptionDTO; import com.dto.HousePriceDTO; import com.dto.HouseRcnlistDTO; import com.dto.HouseWishlistDTO; @Service public class HouseService { @Autowired HouseDAO dao; public HashMap<String, Object> searchList(String search, int curPage) {// 검색에 의한 결과 리스트 페이징 처리 return dao.searchList(search, curPage); }// searchList public List<HashMap<String, Object>> retrieveAllItems() {// 전체매물 리스트 return dao.retrieveAllItems(); }// retrieveAllItems public List<HashMap<String, Object>> retrieveNewItems() {// 신매물 리스트 return dao.retrieveNewItems(); }// retrieveNewItems public List<HashMap<String, Object>> retrieveHotItems() {// 핫매물 리스트 return dao.retrieveHotItems(); }// retrieveHotItems public HashMap<String, Object> listByFilter(HashMap<String, List<String>> queryMap, int curPage) {// 필터에 의한 리스트 return dao.listByFilter(queryMap, curPage); }// retrieveHotItems public List<HashMap<String, Object>> houseByAgent(String agntid) {// 거래중인 매물 return dao.houseByAgent(agntid); }// houseByAgent public List<HashMap<String, Object>> houseSoldByAgent(String agntid) {// 거래완료 매물 return dao.houseSoldByAgent(agntid); }// houseSoldByAgent public List<HashMap<String, Object>> houseLikeByAgent(String agntid) {// 에이전트가 등록한 매물 좋아요받은 순 return dao.houseLikeByAgent(agntid); }// houseLikeByAgent public List<HashMap<String, Object>> houseByRegisterDate(String agntid) {// 에이전트가 등록한 매물 좋아요받은 순 return dao.houseByRegisterDate(agntid); }// houseByRegisterDate public List<HashMap<String, Object>> houseSoldByAgentCount(String agntid) {// 에이전트가 등록한 매물 좋아요받은 순 return dao.houseSoldByAgentCount(agntid); }// houseSoldByAgentCount public String getLastCode(String htype) {// 마지막으로 등록된 코드 가져오기 return dao.getLastCode(htype); }// end getLastCode @Transactional public int houseRegister(HashMap<String, Object> registerMap) {// 매물등록 int n = dao.houseRegister_info((HouseInfoDTO) registerMap.get("info")); n = dao.houseRegister_price((HousePriceDTO) registerMap.get("price")); n = dao.houseRegister_option((HouseOptionDTO) registerMap.get("option")); return n; }// end houseRegister @Transactional public int houseUpdate(HashMap<String, Object> registerMap) {// 매물 수정 int n = dao.houseUpdate_info((HouseInfoDTO) registerMap.get("info")); n = dao.houseUpdate_price((HousePriceDTO) registerMap.get("price")); n = dao.houseUpdate_option((HouseOptionDTO) registerMap.get("option")); return n; }// end houseUpdate public int houseDel(List<String> list) {// 매물삭제 return dao.houseDel(list); }// end houseDel @Transactional public int updateCntWish(HouseWishlistDTO dto) {// 매물 cnthwish 업데이트 int n = dao.addWish(dto); // n = dao.updateCntWish(session, dto.getHcode()); return n; }// end updateCntWish //매물 중개중/중개완료 여부 저장 public int houseChange( List<List<String>> list) { return dao.houseChange(list); } /////////////////////////////////////////////////////////// // Basic : House 자세히보기 public HouseInfoDTO houseRetrieve(String hcode) { return dao.houseRetrieve(hcode); } // Basic : house 가격 public HousePriceDTO housePrice(String hcode) { return dao.housePrice(hcode); } // Basic : house 옵션 public HouseOptionDTO houseOption(String hcode) { return dao.houseOption(hcode); } /////////////////////////////////////////////////////////// // 최근 본 House 테이블 보기 public List<HouseRcnlistDTO> selectRcnlist(String userid) { return dao.selectRcnlist(userid); } // 최근 본 House DB 데이터 저장 public int rcnListAllDone(List<HouseRcnlistDTO> rList) { return dao.rcnListAllDone(rList); } // 최근 본 House DB 데이터 삭제 public int deleteRcnlist(List<Long> userRcnList) { return dao.deleteRcnlist(userRcnList); } // 최근 본 / 찜한 House 리스트 보기 public List<HashMap<String, Object>> rcnHouseInfo(List<String> hCodeList) { return dao.rcnHouseInfo(hCodeList); } // 찜한 House 리스트 보기 public List<HouseWishlistDTO> selectWishlist(String userid) { return dao.selectWishlist(userid); } }
package elainpeli; /* * 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. */ /** * * @author Minna */ public class Pelaaja { private String nimi; private int pisteet; public Pelaaja(String nimi) { this.nimi = nimi; this.pisteet = 0; } public void lisaaPisteita() { this.pisteet++; } public int pisteet() { return this.pisteet; } public String nimi() { return this.nimi; } }
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import java.io.*; import java.net.*; import java.util.List; import java.util.Map; public class Client { private static final String boundary="-------------client"; private static final String nextLine = "\r\n"; //服务器路径 private String serverUrl; //代理 private Proxy proxy=null; /** * 设置服务器url * @param serverUrl */ public Client(String serverUrl) { this.serverUrl = serverUrl; } /** * 设置服务器url和代理 * @param serverUrl * @param proxy */ public Client(String serverUrl, Proxy proxy) { this.serverUrl = serverUrl; this.proxy = proxy; } /** * 获取HttpURLConnection * @param subUrl 请求子url * @return * @throws IOException */ private HttpURLConnection getConn(String subUrl) throws IOException { if(proxy!=null){ return (HttpURLConnection) new URL(serverUrl+subUrl).openConnection(proxy); } return (HttpURLConnection) new URL(serverUrl+subUrl).openConnection(); } /** * 上传文件 * @param file 本地文件 * @return 文件上传后uuid * @throws IOException */ public String uploadFile(File file) throws Exception { HttpURLConnection conn= getConn("/upload"); //设置连接信息 conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestProperty("Accept-Charset", "utf-8"); conn.setRequestProperty("Connection", "keep-alive"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); conn.setRequestProperty("Accept", "application/json"); conn.connect(); //设置上传数据 OutputStream out = new DataOutputStream(conn.getOutputStream()); String header = "--" + boundary + nextLine; header += "Content-Disposition: form-data;name=\"uploadFile\";" + "filename=\"" + file.getName() + "\"" + nextLine + nextLine; out.write(header.getBytes()); DataInputStream fileIn = new DataInputStream(new FileInputStream(file)); int length = 0; byte[] bufferOut = new byte[2048]; while ((length = fileIn.read(bufferOut)) != -1) { out.write(bufferOut, 0, length); } fileIn.close(); String footer = nextLine + "--" + boundary + "--" + nextLine; out.write(footer.getBytes()); out.flush(); out.close(); //读取下载信息 BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; StringBuilder stringBuilder = new StringBuilder(); while ((line = br.readLine()) != null) { stringBuilder.append(line); } conn.disconnect(); //解析json JSONObject jsonObject= JSON.parseObject(stringBuilder.toString()); if(jsonObject.get("status").equals("success")){ return (String) jsonObject.get("uid"); }else{ throw new Exception("something is wrong:"+jsonObject.get("info")); } } /** * 获取文件信息 * @param name 文件uuid * @return * @throws Exception */ public FileInfo getFileInfo(String name) throws Exception { //设置请求信息 HttpURLConnection conn= getConn("/info/"+name); conn.setRequestMethod("GET"); conn.connect(); //获取下载后信息 InputStream inputStream = conn.getInputStream(); StringBuilder stringBuilder = new StringBuilder(); String line; BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); while ((line = br.readLine()) != null) { stringBuilder.append(line); } conn.disconnect(); //解析json数据 FileInfo res=null; JSONObject jsonObject= JSON.parseObject(stringBuilder.toString()); if(jsonObject.get("status").equals("success")){ res=jsonObject.getObject("data",FileInfo.class); }else{ throw new Exception("something is wrong:"+jsonObject.get("info")); } return res; } /** * 下载文件 * @param name 文件uuid * @param targetFile 目标存储文件 * @throws IOException */ public void downloadFile(String name,File targetFile) throws IOException { //设置文件信息 HttpURLConnection conn=getConn("/download/"+name); conn.setRequestMethod("GET"); conn.connect(); //获取文件名,此方法中不需要 // Map<String, List<String>> headers = conn.getHeaderFields(); // String fileName = headers.get("Content-Disposition").get(0); // System.out.println(fileName); //写文件 if(!targetFile.getParentFile().exists()) { targetFile.getParentFile().mkdirs(); }; FileOutputStream fos = new FileOutputStream(targetFile); InputStream is = conn.getInputStream(); int len; byte[] b = new byte[2048]; while((len = is.read(b)) != -1) { fos.write(b,0,len); } fos.close(); is.close(); conn.disconnect(); } }
package io.nuls.consensus.v1.thread; import io.nuls.core.thread.ThreadUtils; import io.nuls.core.thread.commom.NulsThreadFactory; import io.nuls.consensus.model.bo.Chain; import io.nuls.consensus.v1.entity.BasicObject; import io.nuls.consensus.v1.entity.BasicRunnable; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ThreadPoolExecutor; /** * @author Eva */ public class ThreadController extends BasicObject { /** * 专用线程池 */ private ThreadPoolExecutor threadPool; private List<BasicRunnable> list = new ArrayList<>(); public ThreadController(Chain chain) { super(chain); init(); } public void execute(BasicRunnable runnable) { list.add(runnable); threadPool.execute(runnable); } public void shutdown() { if (threadPool != null) { for (BasicRunnable runnable : list) { runnable.stop(); } threadPool.shutdown(); list.clear(); this.init(); } } private void init() { this.threadPool = ThreadUtils.createThreadPool(3, 100, new NulsThreadFactory("pocbft" + chain.getChainId())); } }
package sy.project2019.itshow.sasohan2019.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; import java.util.ArrayList; import java.util.Calendar; import sy.project2019.itshow.sasohan2019.DB.DBHelper; import sy.project2019.itshow.sasohan2019.Model.FamilyModel; import sy.project2019.itshow.sasohan2019.R; public class WriteActivity extends AppCompatActivity { Button addbtn; String title, contents; EditText ed_title, ed_contents; Intent intent; DBHelper db; CheckBox isP; Spinner spinner; ArrayList<String> arrayList; ArrayAdapter<String> arrayAdapter; ArrayList<FamilyModel> familyArr; String receiver; int isPrivate=0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.saranghae_wirte); arrayList = new ArrayList<>(); addbtn = findViewById(R.id.btn_add); ed_title = findViewById(R.id.edit_title); ed_contents = findViewById(R.id.edit_content); isP = findViewById(R.id.isPrivate); db = new DBHelper(getApplication(), DBHelper.tableName, null, 1); familyArr = db.getAllFamily(); if(familyArr.size() != 0){ for(int i=0; i< familyArr.size(); i++){ arrayList.add(familyArr.get(i).getName()); arrayAdapter.notifyDataSetChanged(); } } arrayAdapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, arrayList); spinner = (Spinner)findViewById(R.id.Receiver); spinner.setAdapter(arrayAdapter); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { // if(view.isPressed()){ Toast.makeText(getApplicationContext(),arrayList.get(i)+"가 선택되었습니다.", Toast.LENGTH_SHORT).show(); receiver = arrayList.get(i); // }else{ // Toast.makeText(getApplicationContext(),"선택안되었습니다.", // Toast.LENGTH_SHORT).show(); // } // Toast.makeText(getApplicationContext(),arrayList.get(i)+"가 선택되었습니다.", // Toast.LENGTH_SHORT).show(); } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); addbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //db에 글 추가 if(isP.isChecked()){ isPrivate = 1; } db.DiaryInsert(ed_title.getText().toString(), ed_contents.getText().toString(), receiver, 0, isPrivate); //db삽입성공시 Toast toast = Toast.makeText(getApplicationContext(),"일기가 등록되었습니다.",Toast.LENGTH_SHORT); toast.show(); finish(); } }); } @Override public void onStart() { super.onStart(); arrayAdapter.notifyDataSetChanged(); } }
package kr.or.ddit.basic; import java.net.URL; import java.util.ResourceBundle; import javafx.fxml.Initializable; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.CheckBox; import javafx.scene.control.RadioButton; import javafx.scene.control.TextField; import javafx.scene.control.ToggleGroup; import javafx.scene.control.TextArea; import javafx.scene.control.Button; public class ControllControll implements Initializable{ @FXML private RadioButton male; @FXML private RadioButton female; @FXML private CheckBox mountain; @FXML private CheckBox travel; @FXML private CheckBox reader; @FXML private CheckBox baduk; @FXML private CheckBox janggi; @FXML private CheckBox game; @FXML private CheckBox tennis; @FXML private CheckBox badmin; @FXML private TextField userName; @FXML private TextArea txtResult; @FXML private Button sum; @Override public void initialize(URL location, ResourceBundle resources) { ToggleGroup group = new ToggleGroup(); male.setToggleGroup(group); female.setToggleGroup(group); male.setSelected(true); } @FXML public void btnClick(ActionEvent event) { String name = userName.getText(); String result = ""; String gender = ""; if(male.isSelected()) { gender += "남자"; }else { gender += "여자"; } if(mountain.isSelected()) { result += "등산, "; } if(travel.isSelected()) { result += "여행, "; } if(reader.isSelected()) { result += "독서, "; } if(baduk.isSelected()) { result += "바둑, "; } if(janggi.isSelected()) { result += "장기, "; } if(game.isSelected()) { result += "게임, "; } if(tennis.isSelected()) { result += "테니스, "; } if(badmin.isSelected()) { result += "배드민턴, "; } txtResult.appendText(name +"님은" + gender+ "이고 취미는" + result +"입니다."); }; }
package com.thinkgem.jeesite.modules.sys.security; import java.util.Map; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import org.apache.shiro.subject.Subject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Maps; import com.thinkgem.jeesite.common.utils.StringUtils; import com.thinkgem.jeesite.modules.sys.entity.User; import com.thinkgem.jeesite.modules.sys.utils.UserUtils; /** * 登出,继承{@link org.apache.shiro.web.filter.authc.LogoutFilter},实现自定义登出后跳转页面 * * @author 廖水平 */ public class LogoutFilter extends org.apache.shiro.web.filter.authc.LogoutFilter { protected Logger logger = LoggerFactory.getLogger(getClass()); private Map<String, String> userTypeRedirectUrlMap = Maps.newHashMap(); /** * 用户退出登录时跳转的URL<br/> * * @param userTypeRedirectUrlMap * Map<用户类型, 退出时跳转的URL> */ public void setUserTypeRedirectUrlMap(Map<String, String> userTypeRedirectUrlMap) { this.userTypeRedirectUrlMap = userTypeRedirectUrlMap; } /** * 重写,从配置中读取:退出登录后跳转的url */ @Override protected String getRedirectUrl(ServletRequest request, ServletResponse response, Subject subject) { String redirectUrl = null; User user = UserUtils.getUser(); if (user != null) { String userType = user.getUserType(); if (!StringUtils.isBlank(userType)) { if (userTypeRedirectUrlMap != null && !userTypeRedirectUrlMap.isEmpty()) { redirectUrl = userTypeRedirectUrlMap.get(userType); if (!StringUtils.isBlank(redirectUrl)) { logger.debug("userType={},redirectUrl={}", userType, redirectUrl); return redirectUrl; } } } } redirectUrl = super.getRedirectUrl(); if (StringUtils.isBlank(redirectUrl)) { redirectUrl = LogoutFilter.DEFAULT_REDIRECT_URL; } return redirectUrl; } }
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Dictionary; import java.util.Enumeration; import java.util.Hashtable; import javax.xml.crypto.dsig.keyinfo.KeyValue; public class ArkBotSettings { public static File settings; public static File shortcuts; private static Dictionary<String, String> setdic; private static Dictionary<String, Integer> shortdic; public ArkBotSettings() { settings = new File("ArkBotFiles/Settings/ArkBotSettings.txt"); shortcuts = new File("ArkBotFiles/Settings/ArkBotShortcuts.txt"); InitializeDics(); } public static void ResetSettings() { setdic.put("Username", "default"); setdic.put("SetupPrompt", "true"); setdic.put("ResX", "1440"); setdic.put("ResY", "900"); setdic.put("FullScreen", "false"); setdic.put("NormFullScreen", "false"); setdic.put("Development", "0"); setdic.put("AndrewIsAwesome", "true"); WriteSettings(true); } public static void ResetShortcuts() { shortdic.put("AGatherStartStop", 74); // Keypad Minus shortdic.put("AGatherDrop", 55); // Keypad Multiply shortdic.put("AHealIncOne", 74); // Keypad Minus shortdic.put("AHealIncTen", 55); // Keypad Multiply shortdic.put("AHealAbort", 3637); // Keypad Divide shortdic.put("BreederStartStop", 74); // Keypad Minus shortdic.put("MSplit", 78); // Keypad Plus shortdic.put("APilot", 74); // Keypad Minus shortdic.put("AFish", 74); // Keypad Minus WriteShortcuts(true); } private static void InitializeDics() { // Settings setdic = new Hashtable<String, String>(); if (settings.exists() && settings.length() > 0) { fileToDic(1); } else { ResetSettings(); } // Shortcuts shortdic = new Hashtable<String, Integer>(); if (shortcuts.exists() && shortcuts.length() > 0) { fileToDic(2); } else { ResetShortcuts(); } } private static void WriteSettings(boolean overwrite) { // Determine if file is empty or not if (settings.length() == 0 || overwrite) { try { PrintWriter writer = new PrintWriter("ArkBotFiles/Settings/ArkBotSettings.txt"); Enumeration<String> key = setdic.keys(); Enumeration<String> element = setdic.elements(); while(key.hasMoreElements()) { String name = key.nextElement().toString(); writer.println(name + " = " + setdic.get(name)); element.nextElement(); } writer.close(); } catch (FileNotFoundException e) { ArkBot.ERROR = "Setup Error"; StringWriter error = new StringWriter(); e.printStackTrace(new PrintWriter(error)); ArkBotGUI.GUIText("ERROR: Could not write to ArkBotSettings.txt"); ArkBotGUI.GUIText(error.toString()); e.printStackTrace(); } } else { fileToDic(1); } } private static void WriteShortcuts(boolean overwrite) { // Determine if file is empty or not if (shortcuts.length() == 0 || overwrite) { try { PrintWriter writer = new PrintWriter("ArkBotFiles/Settings/ArkBotShortcuts.txt"); Enumeration<String> key = shortdic.keys(); Enumeration<Integer> element = shortdic.elements(); while(key.hasMoreElements()) { String name = key.nextElement().toString(); writer.println(name + " = " + shortdic.get(name)); element.nextElement(); } writer.close(); } catch (FileNotFoundException e) { ArkBot.ERROR = "Setup Error"; StringWriter error = new StringWriter(); e.printStackTrace(new PrintWriter(error)); ArkBotGUI.GUIText("ERROR: Could not write to ArkBotShortcuts.txt"); ArkBotGUI.GUIText(error.toString()); e.printStackTrace(); } } else { fileToDic(1); } } // Returns Setting value public static String GetSetting(String name) { return setdic.get(name); } // Returns Setting value public static Integer GetShortcut(String name) { return shortdic.get(name); } public static void UpdateSetting(String name, String value) { setdic.remove(name); setdic.put(name, value); ArkBotGUI.GUIText("Updated ArkBotSettings.txt " + name + " = " + value); WriteSettings(true); } public static void UpdateShortcut(String name, Integer value) { shortdic.remove(name); shortdic.put(name, value); ArkBotGUI.GUIText("Updated ArkBotShortcuts.txt " + name + " = " + value); WriteShortcuts(true); } private static void fileToDic(int dic) { BufferedReader br; // Settings if (dic == 1) { try { br = new BufferedReader(new FileReader("ArkBotFiles/Settings/ArkBotSettings.txt")); String line = br.readLine(); while (line != null) { String name = ""; String value = ""; char text[] = line.toCharArray(); // read name int i = 0; while (text[i] != ' ') { name = name + text[i]; i++; } // move to value while (text[i] == ' ' || text[i] == '=') { i++; } // read value while(i!= text.length) { value = value + text[i]; i++; } setdic.put(name, value); line = br.readLine(); } br.close(); } catch (IOException e) { ArkBot.ERROR = "Setup Error"; StringWriter error = new StringWriter(); e.printStackTrace(new PrintWriter(error)); ArkBotGUI.GUIText("ERROR: Could not read from ArkBotSettings.txt"); ArkBotGUI.GUIText(error.toString()); e.printStackTrace(); } // Shortcuts } else if (dic == 2) { try { br = new BufferedReader(new FileReader("ArkBotFiles/Settings/ArkBotShortcuts.txt")); String line = br.readLine(); while (line != null) { String name = ""; String value = ""; char text[] = line.toCharArray(); // read name int i = 0; while (text[i] != ' ') { name = name + text[i]; i++; } // move to value while (text[i] == ' ' || text[i] == '=') { i++; } // read value while(i!= text.length) { value = value + text[i]; i++; } shortdic.put(name, Integer.parseInt(value)); line = br.readLine(); } br.close(); } catch (IOException e) { ArkBot.ERROR = "Setup Error"; StringWriter error = new StringWriter(); e.printStackTrace(new PrintWriter(error)); ArkBotGUI.GUIText("ERROR: Could not read from ArkBotShortcuts.txt"); ArkBotGUI.GUIText(error.toString()); e.printStackTrace(); } } } public static void printDic(int dic) { // Settings if (dic == 1) { Enumeration<String> key = setdic.keys(); Enumeration<String> element = setdic.elements(); while(key.hasMoreElements()) { String name = key.nextElement().toString(); System.out.println(name + " = " + setdic.get(name)); element.nextElement(); } // Shortcuts } else if (dic == 2) { Enumeration<String> key = shortdic.keys(); Enumeration<Integer> element = shortdic.elements(); while(key.hasMoreElements()) { String name = key.nextElement().toString(); System.out.println(name + " = " + setdic.get(name)); element.nextElement(); } } } }
package com.marisolGarcia2611.primerproyecto; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.content.Intent; import android.os.CountDownTimer; import android.view.View; import android.widget.TextView; import java.awt.font.TextAttribute; public class activity_splash extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); final TextView label; label = findViewById(R.id.lbl2); new CountDownTimer(5000, 1000) { @Override public void onTick(long millisUntilFinished) { label.setText( millisUntilFinished / 1000+"%" ); } @Override public void onFinish() { startActivity(new Intent(activity_splash.this,activity_centro.class)); finish(); label.setText("Welcome to app"); } }.start(); } }
package com.auro.scholr.home.data.model; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class GetStudentUpdateProfile { @SerializedName("status") @Expose private String status; @SerializedName("error") @Expose private Boolean error; @SerializedName("message") @Expose private String message; @SerializedName("username") @Expose private String username; @SerializedName("email_id") @Expose private String emailId; @SerializedName("mobile_no") @Expose private String mobileNo; @SerializedName("grade") @Expose private String grade; @SerializedName("gender") @Expose private String gender; @SerializedName("school_type") @Expose private String schoolType; @SerializedName("board_type") @Expose private String boardType; @SerializedName("language") @Expose private String language; @SerializedName("scholarship_amount") @Expose private Integer scholarshipAmount; @SerializedName("user_profile_image") @Expose private String userProfileImage; @SerializedName("mobile_model") @Expose private String mobileModel; @SerializedName("mobile_manufacturer") @Expose private String mobileManufacturer; @SerializedName("mobile_version") @Expose private String mobileVersion; @SerializedName("latitude") @Expose private String latitude; @SerializedName("longitude") @Expose private String longitude; @SerializedName("is_private_tution") @Expose private String isPrivateTution; @SerializedName("private_tution_type") @Expose private String privateTutionType; @SerializedName("state_id") @Expose private String state_id; @SerializedName("district_id") @Expose private String district_id; @SerializedName("is_log") @Expose private boolean isLog; public String getState_id() { return state_id; } public void setState_id(String state_id) { this.state_id = state_id; } public String getDistrict_id() { return district_id; } public void setDistrict_id(String district_id) { this.district_id = district_id; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Boolean getError() { return error; } public void setError(Boolean error) { this.error = error; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getEmailId() { return emailId; } public void setEmailId(String emailId) { this.emailId = emailId; } public String getMobileNo() { return mobileNo; } public void setMobileNo(String mobileNo) { this.mobileNo = mobileNo; } public String getGrade() { return grade; } public void setGrade(String grade) { this.grade = grade; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getSchoolType() { return schoolType; } public void setSchoolType(String schoolType) { this.schoolType = schoolType; } public String getBoardType() { return boardType; } public void setBoardType(String boardType) { this.boardType = boardType; } public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } public Integer getScholarshipAmount() { return scholarshipAmount; } public void setScholarshipAmount(Integer scholarshipAmount) { this.scholarshipAmount = scholarshipAmount; } public String getUserProfileImage() { return userProfileImage; } public void setUserProfileImage(String userProfileImage) { this.userProfileImage = userProfileImage; } public String getMobileModel() { return mobileModel; } public void setMobileModel(String mobileModel) { this.mobileModel = mobileModel; } public String getMobileManufacturer() { return mobileManufacturer; } public void setMobileManufacturer(String mobileManufacturer) { this.mobileManufacturer = mobileManufacturer; } public String getMobileVersion() { return mobileVersion; } public void setMobileVersion(String mobileVersion) { this.mobileVersion = mobileVersion; } public String getLatitude() { return latitude; } public void setLatitude(String latitude) { this.latitude = latitude; } public String getLongitude() { return longitude; } public void setLongitude(String longitude) { this.longitude = longitude; } public String getIsPrivateTution() { return isPrivateTution; } public void setIsPrivateTution(String isPrivateTution) { this.isPrivateTution = isPrivateTution; } public String getPrivateTutionType() { return privateTutionType; } public void setPrivateTutionType(String privateTutionType) { this.privateTutionType = privateTutionType; } public boolean isLog() { return isLog; } public void setLog(boolean log) { isLog = log; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.davivienda.sara.reintegros.general; /** * DiarioElectronicoHelperInterface - 27/08/2008 * Descripción : * Versión : 1.0 * * @author jjvargas * Davivienda 2008 */ public interface ReintegrosHelperInterface { public String obtenerDatos(); }
package com.goldsand.collaboration.server.connect; import android.util.Log; import com.goldsand.collaboration.connection.Authorizer; import com.goldsand.collaboration.connection.Connection; import org.apache.http.conn.util.InetAddressUtils; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; public class ConnectionImpl extends Connection { public ConnectionImpl(ConnectionType type) { super(type); } public ConnectionImpl(ConnectionType type, Authorizer authorizer) { super(type, authorizer); } @Override public int getServerBroadcastPort() { return 10081; } @Override public int getClientBroadcastPort() { return 10082; } @Override public int getConnectionPort() { return 10083; } @Override public String getLocalHostIp() { Log.i("ApplicationManager", "getLocalHostIp()"); String ipaddress = ""; try { Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); while (en.hasMoreElements()) { NetworkInterface nif = en.nextElement(); Enumeration<InetAddress> inet = nif.getInetAddresses(); while (inet.hasMoreElements()) { InetAddress ip = inet.nextElement(); if (!ip.isLoopbackAddress() && InetAddressUtils.isIPv4Address(ip.getHostAddress())) { return ip.getHostAddress(); } } } } catch (SocketException e) { e.printStackTrace(); } return ipaddress; } }
package ru.job4j.web; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.HashMap; import java.util.Set; import javax.json.Json; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; import javax.json.JsonWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletException; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; import ru.job4j.models.Item; import ru.job4j.services.ItemDAO; import ru.job4j.utils.Filter; import ru.job4j.utils.Validation; /** * Класс Delete реализует контроллер Удаление элементов TODO-листа. * * @author Gureyev Ilya (mailto:ill-jah@yandex.ru) * @version 2019-01-12 * @since 2018-04-03 */ public class Delete extends AbstractServlet { /** * Карта фильтров. */ private final HashMap<String, Filter> filters = new HashMap<>(); /** * ItemDAO. */ private final ItemDAO idao = new ItemDAO(); /** * Логгер. */ private final Logger logger = LogManager.getLogger(this.getClass().getSimpleName()); /** * Инициализатор. * @throws javax.servlet.ServletException исключение сервлета. */ @Override public void init() throws ServletException { try { super.init(); this.filters.put("id", new Filter("id", new String[]{"isExists", "isFilled", "isDecimal"})); } catch (Exception ex) { this.logger.error("ERROR", ex); } } /** * Обрабатывает GET-запросы. http://bot.net:8080/ch1_todolist-1.0/delete/ * @param req запрос. * @param resp ответ. * @throws javax.servlet.ServletException исключение сервлета. * @throws java.io.IOException исключение ввода-вывода. */ @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { } /** * Обрабатывает POST-запросы. http://bot.net:8080/ch1_todolist-1.0/delete/ * @param req запрос. * @param resp ответ. * @throws javax.servlet.ServletException исключение сервлета. * @throws java.io.IOException исключение ввода-вывода. */ @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { JsonObjectBuilder jsonb = Json.createObjectBuilder(); JsonObjectBuilder jsonErrors = Json.createObjectBuilder(); String status = ""; try { String idStr = req.getParameter("id"); Validation va = new Validation(); va.validate("id", idStr, this.filters.get("id").getFilters()); if (va.hasErrors()) { status = "error"; HashMap<String, String> errors = va.getErrors(); Set<String> keys = errors.keySet(); for (String key : keys) { jsonErrors.add(key, errors.get(key)); } } else { int id = Integer.parseInt(idStr); Item item = new Item(id, "", "", 0L, false); this.idao.delete(item); status = "ok"; } } catch (Exception ex) { this.logger.error("ERROR", ex); status = "error"; jsonErrors.add("exception", "delete"); } finally { jsonb.add("status", status); jsonb.add("errors", jsonErrors); JsonObject json = jsonb.build(); StringWriter strWriter = new StringWriter(); try (JsonWriter jsonWriter = Json.createWriter(strWriter)) { jsonWriter.writeObject(json); } String jsonData = strWriter.toString(); resp.setContentType("application/json"); PrintWriter writer = new PrintWriter(resp.getOutputStream()); writer.append(jsonData); writer.flush(); } } /** * Вызывается при уничтожении сервлета. */ @Override public void destroy() { try { this.idao.close(); } catch (Exception ex) { this.logger.error("ERROR", ex); } } }
package ch.erp.management.mvp.contract; import ch.erp.management.mvp.base.BaseModel; import ch.erp.management.mvp.base.BasePresenter; import ch.erp.management.mvp.base.BaseView; /** * Fragment库存-Contract */ public interface MStockContract { /** * 库存 -IView */ interface MStockIView extends BaseView { } /** * 库存-Presenter */ abstract class MIStockActivityP extends BasePresenter<MStockIView> { /** * 延時一秒-顯示佈局 */ public abstract void delayedDisplay(); } /** * 库存-Model */ abstract class MIStockModel extends BaseModel { } }
package com.apon.taalmaatjes.backend.api.returns; import java.sql.Date; public class VolunteerInstanceReturn { private String volunteerExtId; private String externalIdentifier; private Date dateStart; private Date dateEnd; public String getVolunteerExtId() { return volunteerExtId; } public void setVolunteerExtId(String volunteerExtId) { this.volunteerExtId = volunteerExtId; } public String getExternalIdentifier() { return externalIdentifier; } public void setExternalIdentifier(String externalIdentifier) { this.externalIdentifier = externalIdentifier; } public Date getDateStart() { return dateStart; } public void setDateStart(Date dateStart) { this.dateStart = dateStart; } public Date getDateEnd() { return dateEnd; } public void setDateEnd(Date dateEnd) { this.dateEnd = dateEnd; } }
package com.fsClothes.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.fsClothes.mapper.CategoryMapper; import com.fsClothes.pojo.Category; import com.fsClothes.pojo.CategoryRootBean; import com.fsClothes.service.CategoryService; /** * @author MrDCG * @version 创建时间:2019年9月28日 下午2:35:55 * */ @Service public class CategoryServiceImpl implements CategoryService { @Autowired private CategoryMapper categoryMapper; @Override public void insertRoot(String categoryName, String categoryDescription) { categoryMapper.insertRoot(new CategoryRootBean(categoryName,categoryDescription)); } @Override public void insertChild(String name,String descr,int pid) { int grade = categoryMapper.findByPid(pid); categoryMapper.insertChild(new Category(name,descr,pid,grade+1)); categoryMapper.updateParent(pid); } @Override public List<Category> findAll() { return categoryMapper.findAll(); } @Override public List<Category> findToTree(int categoryParentId) { return categoryMapper.findToTree(categoryParentId); } @Override public void delete(int id, int pid) { // TODO Auto-generated method stub } @Override public Category findById(int id) { return categoryMapper.findById(id); } @Override public void updateParIsLeaf(int pid) { categoryMapper.updateParIsLeaf(pid); } @Override public void deleteDate(int id) { categoryMapper.deleteData(id); } @Override public List<Category> findByLeaf() { return categoryMapper.findByLeaf(); } @Override public List<Category> findRootCategory() { return categoryMapper.findRootCategory(); } @Override public List<Category> findParentCategory(int id) { return categoryMapper.findParentCategory(id); } }
package com.tntdjs.midi.controllers.data.config; import java.io.File; import java.util.List; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import com.tntdjs.midi.controllers.data.config.objects.ButtonSet; import com.tntdjs.midi.controllers.data.config.objects.MidiButton; import com.tntdjs.midi.controllers.data.config.objects.MidiDevices; import com.tntdjs.midi.controllers.data.config.objects.MidiDevices.Device.ButtonGroups; /** * * @author tsenausk * */ public class UnMarshallMidiDevice { private static final Logger LOGGER = LogManager.getLogger(UnMarshallMidiDevice.class.getName()); public static void main(String[] args) { try { File file = new File("config/midi/controllers/akai/lpd8/LPD8Config.xml"); JAXBContext jaxbContext = JAXBContext.newInstance(MidiDevices.class); /** * the only difference with the marshaling operation is here */ Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); MidiDevices midiDevices = (MidiDevices) jaxbUnmarshaller.unmarshal(file); LOGGER.info("Manufacturer=" + midiDevices.getDevice().getManufacturer()); LOGGER.info("Device=" + midiDevices.getDevice().getName()); ButtonGroups buttonGroups = midiDevices.getDevice().getButtonGroups(); List<ButtonSet> buttonList = buttonGroups.getButtonSet(); for (int i = 0; i < buttonList.size(); i++) { ButtonSet buttonSet = buttonList.get(i); LOGGER.info(""); LOGGER.info("ButtonSet=" + buttonSet.getName()); LOGGER.info("ButtonSet Bank=" + buttonSet.getBank()); LOGGER.info(""); List<MidiButton> mButtonList = buttonSet.getMidiButtons(); for (int n = 0; n < mButtonList.size(); n++) { MidiButton mButton = mButtonList.get(n); LOGGER.info("Button " + mButton.getId()); LOGGER.info("\t" + mButton.getId()); LOGGER.info("\t" + mButton.getAction()); LOGGER.info("\t" + mButton.getSource()); LOGGER.info("\t" + mButton.getType()); LOGGER.info("\t" + mButton.getValue()); LOGGER.info("\t" + mButton.getMidiNote()); } } LOGGER.info(midiDevices); } catch (JAXBException e) { e.printStackTrace(); } } }
package dao; import table.TeacherCourse; import java.sql.SQLException; public interface TeacherCourseDao { public void addTeacherCourse(TeacherCourse teacherCourse) throws SQLException; public void deleteCourseGroup(Integer teacherCourseId) throws SQLException; }
package state3; public class Person { private State state; public Person(State state) { super(); this.state = state; } public void live(){ if( state != null){ state.live(); state = state.next(); }else{ System.out.println("我已经死了,没有下一个状态了"); } } }
package com.example.routes; import android.Manifest; import android.content.DialogInterface; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.Typeface; import android.location.Location; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v4.app.FragmentActivity; import android.support.v4.content.ContextCompat; import android.support.v7.app.AlertDialog; import android.text.SpannableString; import android.text.SpannableStringBuilder; import android.text.style.ForegroundColorSpan; import android.util.TypedValue; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.android.volley.RequestQueue; import com.android.volley.toolbox.Volley; import com.google.android.gms.appindexing.Action; import com.google.android.gms.appindexing.AppIndex; import com.google.android.gms.appindexing.Thing; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.PendingResult; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.LocationSettingsRequest; import com.google.android.gms.location.LocationSettingsResult; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.Polyline; import com.google.android.gms.maps.model.PolylineOptions; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import static android.graphics.Color.parseColor; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener { private static final String ROUTE_KEY = "use_this_to_save_user_preferences"; private GoogleMap mMap; private List<Stop> mStopList; private List<Route> mRouteList; private HashMap<Integer, Marker> mMarkerMap; // maps stop id to google maps marker private HashMap<String, Polyline> mPolylineMap; // maps route name to google maps polyline private RequestQueue mRequestQueue; private boolean[] mSelectedRoutes; private Bitmap imageBitmap; private GoogleApiClient mGoogleApiClient; private Location mLocation; private LocationRequest mLocationRequest; private SharedPreferences mPref; private HashSet<String> mPrefRoutes; //private Button closestStop; @Override public void onConnected(@Nullable Bundle bundle) { if (ActivityCompat.checkSelfPermission(this, Manifest.permission .ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat .checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 2); // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); createLocationRequest(); LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder() .addLocationRequest(mLocationRequest); PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build()); startLocationUpdates(); } protected void startLocationUpdates() { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } LocationServices.FusedLocationApi.requestLocationUpdates( mGoogleApiClient, mLocationRequest, (LocationListener) this); } protected void createLocationRequest() { mLocationRequest = new LocationRequest(); mLocationRequest.setInterval(10000); mLocationRequest.setFastestInterval(5000); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); } @Override public void onConnectionSuspended(int i) { } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { } @Override public void onLocationChanged(Location location) { mLocation = location; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); /*closestStop = (Button) findViewById(R.id.closestStop); closestStop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { displayClosestStop(findClosestStop()); } }); */ imageBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.piny); imageBitmap = resizeMapIcons(imageBitmap, 30, 30); // set up queue for http requests (for route/stop info) mRequestQueue = Volley.newRequestQueue(this); mPref = PreferenceManager.getDefaultSharedPreferences(this); mPrefRoutes = (HashSet<String>) mPref.getStringSet(ROUTE_KEY, null); mRouteList = new ArrayList<>(); getRoutes(); mStopList = new ArrayList<>(); getStops(); Button selectRouteButton = (Button) findViewById(R.id.select_route_button); selectRouteButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { routeSelectionDialog(); } }); // ATTENTION: This "addApi(AppIndex.API)"was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .addApi(AppIndex.API).build(); mGoogleApiClient.connect(); } public String getJSONString(String filename) { InputStream is = getResources().openRawResource( getResources().getIdentifier(filename, "raw", getPackageName())); Writer writer = new StringWriter(); char[] buffer = new char[1024]; try { Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); int n; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } String jsonString = writer.toString(); return jsonString; } public void getRoutes() { String jsonString = getJSONString("routes_info"); try { JSONArray jsonArray = new JSONArray(jsonString); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); Route route = new Route(); route.name = jsonObject.getString("name"); route.formalName = jsonObject.getString("formal_name"); route.color = parseColor(jsonObject.getString("color")); JSONArray coordinates = jsonObject.getJSONArray("coordinates"); route.path = new ArrayList<>(); for (int j = 0; j < coordinates.length(); j++) { JSONArray coordinate = coordinates.getJSONArray(j); // lat and lon are stored in (lon, lat) for some reason ugh route.path.add(new LatLng(coordinate.getDouble(1), coordinate.getDouble(0))); } // initialize stops list, we will fill it in get stops route.stops = new ArrayList<>(); mRouteList.add(route); } mSelectedRoutes = new boolean[mRouteList.size()]; for (int i = 0; i < mRouteList.size(); i++) { mSelectedRoutes[i] = mPrefRoutes == null || mPrefRoutes.contains(mRouteList.get(i).name); } if (mPrefRoutes == null) { mPrefRoutes = new HashSet<>(); } drawMaps(); } catch (JSONException e) { e.printStackTrace(); } } public void getStops() { String jsonString = getJSONString("stops_times"); try { JSONArray jsonArray = new JSONArray(jsonString); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); Stop stop = new Stop(); stop.id = jsonObject.getInt("id"); stop.name = jsonObject.getString("name"); stop.lat = jsonObject.getDouble("lat"); stop.lon = jsonObject.getDouble("lon"); if (jsonObject.has("times")) { JSONObject times = jsonObject.getJSONObject("times"); stop.stopTimeStrings = new HashMap<>(); for (Iterator<String> iter = times.keys(); iter.hasNext(); ) { String routeName = iter.next(); stop.stopTimeStrings.put(routeName, times.getString(routeName)); for (int j = 0; j < mRouteList.size(); j++) { Route route = mRouteList.get(j); if (route.name.equals(routeName)) { route.stops.add(stop.id); if (stop.color==null) stop.color = route.color; else stop.color = ContextCompat.getColor(this, R.color.gray); } } } } mStopList.add(stop); } drawMaps(); } catch (JSONException e) { e.printStackTrace(); } } public void drawMaps() { // draw map will be called from both onMapReady, getRoutes, and getStops // but only run when all have completed if (mMap == null) { return; } if (mRouteList.size() == 0) { return; } if (mStopList.size() == 0) { return; } // make invisible markers for each stop mMarkerMap = new HashMap<>(); for (int i = 0; i < mStopList.size(); i++) { Stop stop = mStopList.get(i); drawStopMarker(stop); } // draw invisible lines for each route mPolylineMap = new HashMap<>(); for (int i = 0; i < mRouteList.size(); i++) { Route route = mRouteList.get(i); drawRouteLine(route); } // show selected routes by making their lines and markers visible updateMaps(); } public Bitmap resizeMapIcons(Bitmap imageBitmap, int width, int height){ Bitmap resizedBitmap = Bitmap.createScaledBitmap(imageBitmap, width, height, false); return resizedBitmap; } public Bitmap changeBitmapColor(Bitmap sourceBitmap, int newColor){ Paint paint = new Paint(); ColorFilter filter = new PorterDuffColorFilter(newColor, PorterDuff.Mode.SRC_IN); paint.setColorFilter(filter); Canvas canvas = new Canvas(sourceBitmap); canvas.drawBitmap(sourceBitmap, 0, 0, paint); return sourceBitmap; } private void drawStopMarker(Stop stop) { Bitmap stopMarker = imageBitmap; if (stop.color != null){ int markerColor = stop.color; stopMarker = changeBitmapColor(imageBitmap, markerColor); } MarkerOptions markerOptions = new MarkerOptions() .position(stop.getLatLng()) .title(stop.name) .visible(false) .icon(BitmapDescriptorFactory.fromBitmap(stopMarker)); Marker marker = mMap.addMarker(markerOptions); marker.setTag(stop.stopTimeStrings); mMarkerMap.put(stop.id, marker); } private void drawRouteLine(Route route) { PolylineOptions polylineOptions = new PolylineOptions() .addAll(route.path) .color(route.color) .visible(false); Polyline polyline = mMap.addPolyline(polylineOptions); mPolylineMap.put(route.name, polyline); } private void updateMaps() { // loop twice because some stops are in multiple routes // don't want to hide a stop that should be shown in another route for (int i = 0; i < mRouteList.size(); i++) { Route route = mRouteList.get(i); if (!mSelectedRoutes[i]) { setRouteVisibility(route,false); } } for (int i = 0; i < mRouteList.size(); i++) { Route route = mRouteList.get(i); if (mSelectedRoutes[i]) { setRouteVisibility(route,true); } } } private void setRouteVisibility(Route route, Boolean visibility) { Polyline polyline = mPolylineMap.get(route.name); polyline.setVisible(visibility); for (int j = 0; j < route.stops.size(); j++) { int stop_id = route.stops.get(j); Marker marker = mMarkerMap.get(stop_id); marker.setVisible(visibility); } } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; LatLng northwestern = new LatLng(42.056437, -87.675900); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(northwestern, 12)); // set custom marker info window view so stop times are visible mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() { @Override public View getInfoWindow(Marker marker) { return null; } @Override public View getInfoContents(Marker marker) { View view = getLayoutInflater().inflate(R.layout.marker_text, null); TextView stopName = (TextView) view.findViewById(R.id.stop_name); stopName.setText(marker.getTitle()); stopName.setTypeface(null, Typeface.BOLD); stopName.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20); TextView stopTime = (TextView) view.findViewById(R.id.stop_time); HashMap<String, String> stopTimeStrings = (HashMap<String, String>) marker.getTag(); SpannableStringBuilder builder = new SpannableStringBuilder(); // allows multicolor boolean moreThanOneRoute = false; for(int i = 0; i < mRouteList.size(); i++) { if (mSelectedRoutes[i]) { String stopTimeString = stopTimeStrings.get(mRouteList.get(i).name); if (stopTimeString != null) { if (moreThanOneRoute) { // if we're adding more than one route's times, need line break builder.append(System.getProperty("line.separator")); } SpannableString nameSpannable= new SpannableString(mRouteList.get(i).formalName); nameSpannable.setSpan(new ForegroundColorSpan( mRouteList.get(i).color), 0, mRouteList.get(i).formalName.length(), 0); builder.append(nameSpannable); builder.append(System.getProperty("line.separator")); builder.append(" "); //tab builder.append(stopTimeString); moreThanOneRoute = true; } } } stopTime.setText(builder, TextView.BufferType.SPANNABLE); return view; } }); drawMaps(); } private void routeSelectionDialog() { String[] routeNames = new String[mRouteList.size()]; for (int i = 0; i < mRouteList.size(); i++) { routeNames[i] = mRouteList.get(i).formalName; } AlertDialog.Builder builder = new AlertDialog.Builder(this) .setMultiChoiceItems(routeNames, mSelectedRoutes, new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i, boolean b) { mSelectedRoutes[i] = b; // update user preferences (which routes to show) if (b) { mPrefRoutes.add(mRouteList.get(i).name); } else { mPrefRoutes.remove(mRouteList.get(i).name); } SharedPreferences.Editor editor = mPref.edit(); editor.remove(ROUTE_KEY); editor.commit(); editor.putStringSet(ROUTE_KEY,mPrefRoutes); editor.apply(); mPrefRoutes = (HashSet<String>) mPref.getStringSet(ROUTE_KEY,null); updateMaps(); } }) .setTitle("Select Routes to Display") .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }); AlertDialog dialog = builder.create(); dialog.show(); } /* private Stop findClosestStop(){ if (mLocation == null) { return null; } if (mStopList.size() == 0) { return null; } double min = Double.MAX_VALUE; Location stop = new Location(""); int index = 0; for (int i = 0; i < mStopList.size() ; i++) { stop.setLatitude(mStopList.get(i).lat); stop.setLongitude(mStopList.get(i).lon); if (mLocation.distanceTo(stop) < min){ index = i; } } return mStopList.get(index); } private void displayClosestStop(Stop closest_stop){ if (closest_stop == null) { return; } mMap.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(closest_stop.lat, closest_stop.lon))); } */ /** * ATTENTION: This was auto-generated to implement the App Indexing API. * See https://g.co/AppIndexing/AndroidStudio for more information. */ public Action getIndexApiAction() { Thing object = new Thing.Builder() .setName("Maps Page") // TODO: Define a title for the content shown. // TODO: Make sure this auto-generated URL is correct. .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]")) .build(); return new Action.Builder(Action.TYPE_VIEW) .setObject(object) .setActionStatus(Action.STATUS_TYPE_COMPLETED) .build(); } @Override public void onStart() { super.onStart(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. mGoogleApiClient.connect(); AppIndex.AppIndexApi.start(mGoogleApiClient, getIndexApiAction()); } @Override public void onStop() { super.onStop(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. AppIndex.AppIndexApi.end(mGoogleApiClient, getIndexApiAction()); mGoogleApiClient.disconnect(); } }
package cn.senlin.jiaoyi.service; import cn.senlin.jiaoyi.entity.InformationCode; import cn.senlin.jiaoyi.entity.UserInformation; import java.util.List; public interface InformationService { UserInformation loadInformation(String userAccount); List<InformationCode> loadByType(String codeType); String updateInformation(UserInformation usin, String userName); }
package run.service; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Service; import dao.UserDAO; import entities.UserObj; import run.entity.UserDTO; import run.convert.ConvertEntitesToDTOs; @Service public class UserService { private UserDAO dao=new UserDAO(); public List<UserDTO> getAll(){ List<UserDTO> list=new ArrayList<UserDTO>(); for(UserObj u:dao.selectAll()) { UserDTO user=ConvertEntitesToDTOs.convertUserObjToDTO(u); list.add(user); } return list; } public List<UserDTO> getAllUsers(){ List<UserDTO> list=new ArrayList<UserDTO>(); for(UserObj u:dao.selectAllUsers()) { UserDTO user=ConvertEntitesToDTOs.convertUserObjToDTO(u); list.add(user); } return list; } public List<UserDTO> getAllOwners(){ List<UserDTO> list=new ArrayList<UserDTO>(); for(UserObj u:dao.selectAllOwners()) { UserDTO user=ConvertEntitesToDTOs.convertUserObjToDTO(u); list.add(user); } return list; } public void closeConnection() { dao.closeConnection(); } public UserDTO getByID(String id) { UserDTO user=ConvertEntitesToDTOs.convertUserObjToDTO(dao.selectByID(Integer.parseInt(id))); System.out.println(user.toString()); return user; } public UserDTO getUser(String id) { UserDTO user=ConvertEntitesToDTOs.convertUserObjToDTO(dao.selectUserByID(Integer.parseInt(id))); return user; } public UserDTO getOwner(String id) { UserDTO user=ConvertEntitesToDTOs.convertUserObjToDTO(dao.selectOwnerByID(Integer.parseInt(id))); return user; } public void createUser(UserDTO user) { dao.insertUser(user.getName(), user.getUserName(), user.getPassword(), user.getAccount()); } public void createOwner(UserDTO user) { dao.insertOwner(user.getName(), user.getUserName(), user.getPassword(), user.getAccount()); } public void updateUser(UserDTO user,String id) { try { dao.update(Integer.parseInt(id),user.getName(), user.getUserName(), user.getPassword(), user.getAccount()); } catch(IllegalArgumentException e){ } } public void deleteUser(String id) { try { dao.delete(Integer.parseInt(id)); } catch(IllegalArgumentException e){ } } public void depositUser(String id,float sum) { float s=dao.selectByID(Integer.parseInt(id)).getAccount(); s+=sum; dao.update(Integer.parseInt(id), "", "", "", s); } public void withdrawUser(String id,float sum) { float s=dao.selectByID(Integer.parseInt(id)).getAccount(); s-=sum; dao.update(Integer.parseInt(id), "", "", "", s); } }
package com.blog.servlet.user; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.blog.Iservice.IAlbumsService; import com.blog.Iservice.IDianZanService; import com.blog.Iservice.IPhotoService; import com.blog.bean.Albums; import com.blog.bean.DianZan; import com.blog.bean.Page; import com.blog.bean.Photos; import com.blog.service.impl.AlbumsService; import com.blog.service.impl.DianZanService; import com.blog.service.impl.PhotoService; public class ShowAlbumDetailsServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String al_ids = request.getParameter("al_id"); int al_id=Integer.parseInt(al_ids); HttpSession session = request.getSession(); if(session.getAttribute("u_id")!=null){ int u_id = (Integer) session.getAttribute("u_id"); IDianZanService iDianZanService=new DianZanService(); DianZan dianzanxinxi = iDianZanService.dianzan(u_id, al_id); request.setAttribute("dianzanxinxi", dianzanxinxi); } IAlbumsService albumsService=new AlbumsService(); int dianzancount = albumsService.getTotalCountBydianzan(al_id); Albums albums = albumsService.Albums(al_id); IPhotoService iPhotoService =new PhotoService(); Page page = new Page(); String cPage = request.getParameter("currentPage") ;// if(cPage == null) { cPage = "1" ; } int currentPage = Integer.parseInt( cPage ); page.setCurrentPage(currentPage); int totalCount = iPhotoService.getTotalCountByp_albums(al_id);//×ÜÊý¾ÝÊý page.setTotalCount(totalCount); int pageSize=16; int totalPage =totalCount%pageSize==0?totalCount/pageSize:totalCount/pageSize+1; page.setTotalPage(totalPage); List<Photos> list = iPhotoService.photosByp_albums(al_id, currentPage, pageSize); page.setPhotos(list); request.setAttribute("al_id", al_id); request.setAttribute("albums", albums); request.setAttribute("dianzan", dianzancount); request.setAttribute("page", page); request.getRequestDispatcher("/user/u_photo.jsp").forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
package com.pykj.annotation.demo.annotation.injection.value; import com.pykj.annotation.project.entity.Bird; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @description: @Value * @author: zhangpengxiang * @time: 2020/4/15 23:19 */ @Configuration public class MyConfig { @Bean public Bird bird() { return new Bird(); } }