text stringlengths 10 2.72M |
|---|
package com.pzhu.topicsys.common.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import org.apache.commons.lang3.time.DateFormatUtils;
/**
*
* @ClassName: DateUtils
* @date 2013-6-24 上午8:57:16
* @Description: 日期工具类, 继承org.apache.commons.lang.time.DateUtils类
*
*/
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
private static String[] parsePatterns = { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm" };
/**
* @param date
* 日期
* @param years
* 年数
* @param months
* 月数
* @param days
* 天数
* @return
* @about version :1.00
* @auther : lifajun
* @Description :返回指定年数,月数,天数之后的日期
*/
public static Date afterDate(Date date, int years, int months, int days) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.YEAR, years);
cal.add(Calendar.MONTH, months);
cal.add(Calendar.DAY_OF_MONTH, days);
return cal.getTime();
}
/**
* @param date
* 日期
* @param years
* 年数
* @param months
* 月数
* @param days
* 天数
* @param hours
* 小时数
* @param minutes
* 分钟数
* @param seconds
* 秒数
* @return
* @about version :1.00
* @auther : lifajun
* @Description :返回指定年数,月数,天数,小时数,分钟数,秒数之后的日期
*/
public static Date afterDate(Date date, int years, int months, int days, int hours, int minutes, int seconds) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.YEAR, years);
cal.add(Calendar.MONTH, months);
cal.add(Calendar.DAY_OF_MONTH, days);
cal.add(Calendar.HOUR_OF_DAY, hours);
cal.add(Calendar.MINUTE, minutes);
cal.add(Calendar.SECOND, seconds);
return cal.getTime();
}
/**
* @param date
* 日期
* @param days
* 天数
* @return
* @about version :1.00
* @auther : lifajun
* @Description :返回指定天数之后的日期
*/
public static Date afterDays(Date date, int days) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH, days);
return cal.getTime();
}
/**
*
* @author Lipx
*
* Description:<br>
* 返回指定周数之后的日期
*
* @param date
* @param weeks
* @return
*/
public static Date afterWeeks(Date date, int weeks) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.WEEK_OF_YEAR, weeks);
return cal.getTime();
}
/**
* @param date
* 日期
* @param months
* 月数
* @return
* @about version :1.00
* @auther : lifajun
* @Description :返回指定月数之后的日期
*/
public static Date afterMonths(Date date, int months) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MONTH, months);
return cal.getTime();
}
/**
* @param date
* 日期
* @param years
* 年数
* @return
* @about version :1.00
* @auther : lifajun
* @Description :返回指定年数之后的日期
*/
public static Date afterYears(Date date, int years) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.YEAR, years);
return cal.getTime();
}
/**
* @param date
* 日期
* @param years
* 年数
* @param months
* 月数
* @param days
* 天数
* @return
* @about version :1.00
* @auther : lifajun
* @Description :返回指定年数,月数,天数之前的日期
*/
public static Date beforeDate(Date date, int years, int months, int days) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.YEAR, -years);
cal.add(Calendar.MONTH, -months);
cal.add(Calendar.DAY_OF_MONTH, -days);
return cal.getTime();
}
/**
* @param date
* 日期
* @param years
* 年数
* @param months
* 月数
* @param days
* 天数
* @param hours
* 小时数
* @param minutes
* 分钟数
* @param seconds
* 秒数
* @return
* @about version :1.00
* @auther : lifajun
* @Description :返回指定年数,月数,天数,小时数,分钟数,秒数之前的日期
*/
public static Date beforeDate(Date date, int years, int months, int days, int hours, int minutes, int seconds) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.YEAR, -years);
cal.add(Calendar.MONTH, -months);
cal.add(Calendar.DAY_OF_MONTH, -days);
cal.add(Calendar.HOUR_OF_DAY, -hours);
cal.add(Calendar.MINUTE, -minutes);
cal.add(Calendar.SECOND, -seconds);
return cal.getTime();
}
/**
* @param date
* 日期
* @param days
* 天数
* @return
* @about version :1.00
* @auther : lifajun
* @Description :返回指定天数之前的日期
*/
public static Date beforeDays(Date date, int days) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH, -days);
return cal.getTime();
}
/**
* @param date
* 日期
* @param months
* 月数
* @return
* @about version :1.00
* @auther : lifajun
* @Description :返回指定月数之前的日期
*/
public static Date beforeMonths(Date date, int months) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MONTH, -months);
return cal.getTime();
}
/**
*
* @author Lipx
*
* Description:<br>
* 返回指定周数之前的日期
*
* @param date
* @param weeks
* @return
*/
public static Date beforeWeeks(Date date, int weeks) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.WEEK_OF_YEAR, -weeks);
return cal.getTime();
}
/**
* @param date
* 日期
* @param years
* 年数
* @return
* @about version :1.00
* @auther : lifajun
* @Description :返回指定年数之前的日期
*/
public static Date beforeYears(Date date, int years) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.YEAR, -years);
return cal.getTime();
}
/**
* 得到日期字符串 默认格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E"
*/
public static String formatDate(Date date, String pattern) {
String formatDate = null;
if (pattern != null) {
formatDate = DateFormatUtils.format(date, pattern);
} else {
formatDate = DateFormatUtils.format(date, "yyyy-MM-dd");
}
return formatDate;
}
/**
* 把字符串转换成指定格式的日期
*
* @param dateStr
* @param pattern
* @return
* @throws ParseException
*/
public static Date parseDate(String dateStr, String pattern) throws ParseException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
Date date = simpleDateFormat.parse(dateStr);
return date;
}
/**
* 取当前时间字符串
*
* 时间字符串格式为:年(4位)-月份(2位)-日期(2位) 小时(2位):分钟(2位):秒(2位)
*
* @return 时间字符串
*/
public static String getCurrentDateString() {
return getCurrentDateString("yyyy-MM-dd HH:mm:ss");
}
/**
* 按格式取当前时间字符串
*
* @param formatString
* 格式字符串
* @return
*/
public static String getCurrentDateString(String formatString) {
Date currentDate = new Date();
return formatDate(currentDate, formatString);
}
/**
* 得到当前日期和时间字符串 格式(yyyy-MM-dd HH:mm:ss)
*/
public static String getDateTime() {
return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
}
/**
* 得到当天字符串 格式(dd)
*/
public static String getDay() {
return formatDate(new Date(), "dd");
}
/**
* 取得指定日期的23点59分59秒
*
* @param dateStr
* 日期 年月
* @return : 格式化为当天的最后一秒
* @author : chenlong
* @version : 1.00
* @throws ParseException
* @create time : 2013-3-18
* @description : 取得指定日期的最后一秒
*/
public static Date getDayLastSecond(String dateStr) throws ParseException {
// 当日期字符串不为空或者""时,转换为Date类型
if (dateStr != null || !"".equals(dateStr)) {
Date date = parseDate("yyyy-MM-dd", dateStr);
// 实例化Calendar类型
Calendar cal = Calendar.getInstance();
// 设置年月
cal.setTime(date);
// 设置时间为23时
cal.set(Calendar.HOUR_OF_DAY, 23);
// 设置时间为59分
cal.set(Calendar.MINUTE, 59);
// 设置时间为59秒
cal.set(Calendar.SECOND, 59);
// 设置时间为999毫秒
cal.set(Calendar.MILLISECOND, 999);
return cal.getTime();
} else {
return null;
}
}
/**
* 获取传入日期一天的结束时间 yyyy-MM-dd 23:59:59
*
* @param date
* @return
*/
public static Date getDayLastSecond(Date date) {
// 实例化Calendar类型
Calendar cal = Calendar.getInstance();
// 设置年月
cal.setTime(date);
// 设置时间为23时
cal.set(Calendar.HOUR_OF_DAY, 23);
// 设置时间为59分
cal.set(Calendar.MINUTE, 59);
// 设置时间为59秒
cal.set(Calendar.SECOND, 59);
// 设置时间为999毫秒
cal.set(Calendar.MILLISECOND, 999);
return cal.getTime();
}
/**
* 取得指定年月的第一天
*
* @param yearMonthStr
* 年月
* @return : firstDay 第一天
* @author : youyd
* @version : 1.00
* @throws ParseException
* @create time : 2013-2-25 下午12:43:16
* @description : 取得指定年月的第一天
*/
public static Date getFirstDay(String yearMonthStr) throws ParseException {
// 当日期字符串不为空或者""时,转换为Date类型
if (yearMonthStr != null || !"".equals(yearMonthStr)) {
Date yearMonth = parseDate(yearMonthStr, "yyyy-MM");
// 实例化Calendar类型
Calendar cal = Calendar.getInstance();
// 设置年月
cal.setTime(yearMonth);
// 设置日期为该月第一天
cal.set(Calendar.DATE, 1);
// 返回指定年月的第一天
return cal.getTime();
} else {
return null;
}
}
/**
*
* @author Lipx
*
* Description:<br>
* 取得指定年月的第一天
*
* @param yearMonthStr
* @return
* @throws ParseException
*/
public static Date getFirstDay(Date yearMonthStr) throws ParseException {
// 当日期字符串不为空或者""时,转换为Date类型
if (yearMonthStr != null) {
Date yearMonth = parseDate(formatDate(yearMonthStr, "yyyy-MM"), "yyyy-MM");
// 实例化Calendar类型
Calendar cal = Calendar.getInstance();
// 设置年月
cal.setTime(yearMonth);
// 设置日期为该月第一天
cal.set(Calendar.DATE, 1);
// 返回指定年月的第一天
return cal.getTime();
} else {
return null;
}
}
/**
* 取得指定年月的最后一天
*
* @param yearMonthStr
* 年月
* @return : lastDay 最后一天
* @author : youyd
* @version : 1.00
* @throws ParseException
* @create time : 2013-2-25 下午12:43:16
* @description : 取得指定年月的最后一天
*/
public static Date getLastDay(String yearMonthStr) throws ParseException {
// 当日期字符串不为空或者""时,转换为Date类型
if (yearMonthStr != null || !"".equals(yearMonthStr)) {
Date yearMonth = parseDate(yearMonthStr, "yyyy-MM");
// 实例化Calendar类型
Calendar cal = Calendar.getInstance();
// 设置年月
cal.setTime(yearMonth);
// 设置月份为下一月份
cal.set(Calendar.MONTH, cal.get(Calendar.MONTH));
// 设置日期为下一月份第一天
cal.set(Calendar.DATE, 1);
// 设置时间为23时
cal.set(Calendar.HOUR_OF_DAY, 23);
// 设置时间为59分
cal.set(Calendar.MINUTE, 59);
// 设置时间为59秒
cal.set(Calendar.SECOND, 59);
// 设置时间为999毫秒
cal.set(Calendar.MILLISECOND, 999);
// 回滚一天 即上月份的最后一天
cal.roll(Calendar.DATE, -1);
// 返回指定年月的最后一天
return cal.getTime();
} else {
return null;
}
}
/**
*
* @author Lipx
*
* Description:<br>
* 取得指定年月的最后一天
*
* @param yearMonthStr
* @return
* @throws ParseException
*/
public static Date getLastDay(Date yearMonthStr) throws ParseException {
// 当日期字符串不为空或者""时,转换为Date类型
if (yearMonthStr != null || !"".equals(yearMonthStr)) {
Date yearMonth = parseDate(formatDate(yearMonthStr, "yyyy-MM"), "yyyy-MM");
// 实例化Calendar类型
Calendar cal = Calendar.getInstance();
// 设置年月
cal.setTime(yearMonth);
// 设置月份为下一月份
cal.set(Calendar.MONTH, cal.get(Calendar.MONTH));
// 设置日期为下一月份第一天
cal.set(Calendar.DATE, 1);
// 设置时间为23时
cal.set(Calendar.HOUR_OF_DAY, 23);
// 设置时间为59分
cal.set(Calendar.MINUTE, 59);
// 设置时间为59秒
cal.set(Calendar.SECOND, 59);
// 设置时间为999毫秒
cal.set(Calendar.MILLISECOND, 999);
// 回滚一天 即上月份的最后一天
cal.roll(Calendar.DATE, -1);
// 返回指定年月的最后一天
return cal.getTime();
} else {
return null;
}
}
/**
* 得到当前月份字符串 格式(MM)
*/
public static String getMonth() {
return formatDate(new Date(), "MM");
}
/**
* @param date1
* @param date2
* @return 返回两个日期间的月数
*/
public static Integer getMonths(Date date1, Date date2) {
int iMonth = 0;
int flag = 0;
try {
Calendar objCalendarDate1 = Calendar.getInstance();
objCalendarDate1.setTime(date1);
Calendar objCalendarDate2 = Calendar.getInstance();
objCalendarDate2.setTime(date2);
if (objCalendarDate2.equals(objCalendarDate1))
return 0;
if (objCalendarDate1.after(objCalendarDate2)) {
Calendar temp = objCalendarDate1;
objCalendarDate1 = objCalendarDate2;
objCalendarDate2 = temp;
}
if (objCalendarDate2.get(Calendar.DAY_OF_MONTH) < objCalendarDate1.get(Calendar.DAY_OF_MONTH))
flag = 1;
if (objCalendarDate2.get(Calendar.YEAR) > objCalendarDate1.get(Calendar.YEAR))
iMonth = ((objCalendarDate2.get(Calendar.YEAR) - objCalendarDate1.get(Calendar.YEAR)) * 12 + objCalendarDate2.get(Calendar.MONTH) - flag)
- objCalendarDate1.get(Calendar.MONTH);
else
iMonth = objCalendarDate2.get(Calendar.MONTH) - objCalendarDate1.get(Calendar.MONTH) - flag;
} catch (Exception e) {
e.printStackTrace();
}
return iMonth;
}
public static Integer getYears(Date date1, Date date2) {
Calendar calBegin = Calendar.getInstance();
calBegin.setTime(date1);
Calendar calEnd = Calendar.getInstance();
calEnd.setTime(date2);
return calEnd.get(Calendar.YEAR) - calBegin.get(Calendar.YEAR);
}
/**
* 获取传入日期的开始时间 yyyy-MM-dd 00:00:00
*
* @param date
* @return
*/
public static Date getDayStartSecond(Date date) {
// 实例化Calendar类型
Calendar cal = Calendar.getInstance();
// 设置年月
cal.setTime(date);
// 设置时间为0时
cal.set(Calendar.HOUR_OF_DAY, 0);
// 设置时间为0分
cal.set(Calendar.MINUTE, 0);
// 设置时间为0秒
cal.set(Calendar.SECOND, 0);
// 设置时间为0毫秒
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
/**
* 得到当前时间字符串 格式(HH:mm:ss)
*/
public static String getTime() {
return formatDate(new Date(), "HH:mm:ss");
}
/**
* 得到当前星期字符串 格式(E)星期几
*/
public static String getWeek() {
return formatDate(new Date(), "E");
}
/**
* 得到当前年份字符串 格式(yyyy)
*/
public static String getYear() {
return formatDate(new Date(), "yyyy");
}
/**
* @param date1
* 日期1
* @param date2
* 日期2
* @return
* @about version :1.00
* @auther : lifajun
* @Description :返回两个日期相差天数的绝对值
*/
public static Integer intervalDay(Date date1, Date date2) {
return Math.abs((int) ((date1.getTime() - date2.getTime()) / (1000 * 60 * 60 * 24)));
}
/**
*
* @author Lipx
*
* Description:<br>
* 返回两个日期相差周数的绝对值
*
* @param date1
* @param date2
* @return
*/
public static Integer intervalWeek(Date date1, Date date2) {
return (int) Math.ceil(Math.abs((int) ((date1.getTime() - date2.getTime()) / (1000 * 60 * 60 * 24))) / 7);
}
/**
* @description 计算量日期中的月数差
* @param date1
* @param date2
* @return
*/
public static Integer intervalMonth(Date date1, Date date2) {
Calendar calendar1 = Calendar.getInstance();
Calendar calendar2 = Calendar.getInstance();
calendar1.setTime(date1);
calendar2.setTime(date2);
int year1 = calendar1.get(Calendar.YEAR);
int year2 = calendar2.get(Calendar.YEAR);
int month1 = calendar1.get(Calendar.MONTH);
int month2 = calendar2.get(Calendar.MONTH);
int month12 = Math.abs(year1 - year2) * 12;
if (year1 - year2 > 0) {
month1 += month12;
} else if (year2 - year1 > 0) {
month2 += month12;
}
return Math.abs(month2 - month1);
}
/**
* 日期型字符串转化为日期 格式 { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm" }
*/
public static Date parseDate(Object str) {
if (str == null) {
return null;
}
try {
return parseDate(str.toString(), parsePatterns);
} catch (ParseException e) {
return null;
}
}
/**
* 获取过去的天数
*
* @param date
* @return
*/
public static long pastDays(Date date) {
long t = new Date().getTime() - date.getTime();
return t / (24 * 60 * 60 * 1000);
}
/**
* 获取过去的小时
*
* @param date
* @return
*/
public static long pastHour(Date date) {
long t = new Date().getTime() - date.getTime();
return t / (60 * 60 * 1000);
}
/**
* 获取过去的分钟
*
* @param date
* @return
*/
public static long pastMinutes(Date date) {
long t = new Date().getTime() - date.getTime();
return t / (60 * 1000);
}
/**
* 转换为时间(天,时:分:秒.毫秒)
*
* @param timeMillis
* @return
*/
public static String formatDateTime(long timeMillis) {
long day = timeMillis / (24 * 60 * 60 * 1000);
long hour = (timeMillis / (60 * 60 * 1000) - day * 24);
long min = ((timeMillis / (60 * 1000)) - day * 24 * 60 - hour * 60);
long s = (timeMillis / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
long sss = (timeMillis - day * 24 * 60 * 60 * 1000 - hour * 60 * 60 * 1000 - min * 60 * 1000 - s * 1000);
return (day > 0 ? day + "," : "") + hour + ":" + min + ":" + s + "." + sss;
}
/**
* 获取两个日期之间的天数
*
* @param before
* @param after
* @return
*/
public static double getDistanceOfTwoDate(Date before, Date after) {
long beforeTime = before.getTime();
long afterTime = after.getTime();
return (afterTime - beforeTime) / (1000 * 60 * 60 * 24);
}
/**
*
* @author Lipx
*
* Description:<br>
* 获取当前时间所在年的周数
*
* @param date
* @return
*/
public static int getWeekOfYear(Date date) {
Calendar c = new GregorianCalendar();
c.setFirstDayOfWeek(Calendar.MONDAY);
c.setMinimalDaysInFirstWeek(7);
c.setTime(date);
return c.get(Calendar.WEEK_OF_YEAR);
}
/**
*
* @author Lipx
*
* Description:<br>
* 获取当前时间所在年的最大周数
*
* @param year
* @return
*/
public static int getMaxWeekNumOfYear(int year) {
Calendar c = new GregorianCalendar();
c.set(year, Calendar.DECEMBER, 31, 23, 59, 59);
return getWeekOfYear(c.getTime());
}
/**
*
* @author Lipx
*
* Description:<br>
* 获取某年的第几周的开始日期
*
* @param year
* @param week
* @return
*/
public static Date getFirstDayOfWeek(int year, int week) {
Calendar c = new GregorianCalendar();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, Calendar.JANUARY);
c.set(Calendar.DATE, 1);
Calendar cal = (GregorianCalendar) c.clone();
cal.add(Calendar.DATE, week * 7);
return getFirstDayOfWeek(cal.getTime());
}
/**
*
* @author Lipx
*
* Description:<br>
* 获取某年的第几周的结束日期
*
* @param year
* @param week
* @return
*/
public static Date getLastDayOfWeek(int year, int week) {
Calendar c = new GregorianCalendar();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, Calendar.JANUARY);
c.set(Calendar.DATE, 1);
Calendar cal = (GregorianCalendar) c.clone();
cal.add(Calendar.DATE, week * 7);
return getLastDayOfWeek(cal.getTime());
}
/**
*
* @author Lipx
*
* Description:<br>
* 获取当前时间所在周的开始日期
*
* @param date
* @return
*/
public static Date getFirstDayOfWeek(Date date) {
Calendar c = new GregorianCalendar();
c.setFirstDayOfWeek(Calendar.MONDAY);
c.setTime(date);
c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek()); // Monday
return c.getTime();
}
/**
*
* @author Lipx
*
* Description:<br>
* 获取当前时间所在周的结束日期
*
* @param date
* @return
*/
public static Date getLastDayOfWeek(Date date) {
Calendar c = new GregorianCalendar();
c.setFirstDayOfWeek(Calendar.MONDAY);
c.setTime(date);
c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek() + 6); // Sunday
return c.getTime();
}
}
|
package cn.catcatmeow.web.controller;
import cn.catcatmeow.pojo.Account;
import cn.catcatmeow.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/account")
public class AccountController {
@Autowired
private AccountService accountService;
@GetMapping("/{id}")
public Account queryAccountById(@PathVariable(value = "id",required = true) int id){
return accountService.findById(id);
}
}
|
/*
* Program: Building.java
* Project: MissileDefense
* Author: J. Ethan Wallace and Michael Gibson
* Date Written: 10/05/2014 - 10/08/2014
* Abstract: These are the buildings that the player must protect. It is created in (and implements with) the MDGame class.
*/
import java.awt.Color;
public class Building extends GameObject {
protected int maxHealth = 1;
protected int health = 1;
public Building() {}
public Building(MDGame game, int x) {
this.game = game;
this.x = x;
maxHealth = health = 3;
width = 35;
height = health*15;
color = new Color(150,200,255);
}
public void update() {
height = health*15;
y = game.getHeight() - game.groundHeight;
}
public void hit() {
health--;
if (health < 1)
onDeath();
}
protected void onDeath() {
super.onDeath();
Sound.play("snd/BuildingCollapse.wav");
}
}
|
package com.fc.activity.kdg;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.hardware.camera2.params.RggbChannelVector;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.animation.LinearInterpolator;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.TextView.OnEditorActionListener;
import com.fc.R;
import com.fc.activity.FrameActivity;
import com.fc.activity.esp.AddParts;
import com.fc.activity.esp.ServiceReportsComplete;
import com.fc.activity.main.MainActivity;
import com.fc.cache.DataCache;
import com.fc.cache.ServiceReportCache;
import com.fc.common.Constant;
import com.fc.utils.Config;
import com.fc.utils.ImageUtil;
import com.fc.zxing.CaptureActivity;
/**
* 巡检-服务报告
*
* @author zdkj
*
*/
public class FwbgXj extends FrameActivity {
private Button confirm, cancel;
private String flag, zbh, message, type;
private TextView tv_curr;
private String[] from;
private int[] to;
private ArrayList<Map<String, String>> data_zp;
private LinearLayout ll_show;
private Map<String, ArrayList<String>> filemap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 默认焦点不进入输入框,避免显示输入法
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
appendMainBody(R.layout.activity_xj_fwbg);
initVariable();
initView();
initListeners();
showProgressDialog();
Config.getExecutorService().execute(new Runnable() {
@Override
public void run() {
getWebService("query");
}
});
// if("(暂停)".equals(ztzt)){
// confirm.setOnClickListener(null);
// dialogShowMessage("该工单处于暂停状态,不能提交!", null, null);
// }
}
@Override
protected void initVariable() {
confirm = (Button) findViewById(R.id.include_botto).findViewById(
R.id.confirm);
cancel = (Button) findViewById(R.id.include_botto).findViewById(
R.id.cancel);
confirm.setText("保存");
cancel.setText("确认完成");
}
@Override
protected void initView() {
title.setText(DataCache.getinition().getTitle());
ll_show = (LinearLayout) findViewById(R.id.ll_show);
from = new String[] { "id", "name" };
to = new int[] { R.id.bm, R.id.name };
filemap = new HashMap<String, ArrayList<String>>();
final Map<String, Object> itemmap = ServiceReportCache.getObjectdata()
.get(ServiceReportCache.getIndex());
zbh = itemmap.get("zbh").toString();
((TextView) findViewById(R.id.tv_1)).setText(zbh);
((TextView) findViewById(R.id.tv_2)).setText(itemmap.get("sbbm").toString());
((TextView) findViewById(R.id.tv_3)).setText(itemmap.get("sblx").toString());
((TextView) findViewById(R.id.tv_4)).setText(itemmap.get("fgsl").toString());
((TextView) findViewById(R.id.tv_5)).setText(itemmap.get("jsrq").toString());
((TextView) findViewById(R.id.tv_6)).setText(itemmap.get("ds").toString());
((TextView) findViewById(R.id.tv_7)).setText(itemmap.get("ssqx").toString());
((TextView) findViewById(R.id.tv_8)).setText(itemmap.get("xqmc").toString());
((TextView) findViewById(R.id.tv_9)).setText(itemmap.get("xxdz").toString());
((TextView) findViewById(R.id.tv_10)).setText(itemmap.get("bz").toString());
((TextView) findViewById(R.id.tv_jddz)).setText(itemmap.get("jddz").toString());
}
@Override
protected void initListeners() {
//
OnClickListener backonClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bt_topback:
onBackPressed();
break;
case R.id.cancel:
type = "2";
for (int i = 0; i < ll_show.getChildCount(); i++) {
LinearLayout ll = (LinearLayout) ll_show.getChildAt(i);
Map<String, String> map = data_zp.get(i);
if (ll.getChildAt(1) instanceof LinearLayout) {
ll = (LinearLayout) ll.getChildAt(1);
if (ll.getChildAt(0) instanceof RadioGroup) {
RadioGroup rg = (RadioGroup) ll.getChildAt(0);
if (rg.getCheckedRadioButtonId() == -1) {
dialogShowMessage_P("各项信息不能为空,请选择", null);
return;
}
}
if (ll.getChildAt(0) instanceof Spinner) {
Spinner spinner_val = (Spinner) ll.getChildAt(0);
if (spinner_val.getSelectedItemPosition()==0) {
dialogShowMessage_P("各项信息不能为空,请选择", null);
return;
}
}
}
}
showProgressDialog();
Config.getExecutorService().execute(new Runnable() {
@Override
public void run() {
getWebService("submit");
}
});
break;
case R.id.confirm:
type = "1";
// for (int i = 0; i < ll_show.getChildCount(); i++) {
// LinearLayout ll = (LinearLayout) ll_show.getChildAt(i);
// Map<String, String> map = data_zp.get(i);
// String kzzf3 = map.get("kzzf3");
//
// if (ll.getChildAt(1) instanceof EditText) {
// if ("1".equals(kzzf3)) { // 1表示必填
// EditText et = (EditText) ll.getChildAt(1);
// String tag = et.getTag().toString();
// if (!isNotNull(et)) {
// dialogShowMessage_P(tag + "不能为空,请录入", null);
// return;
// }
// }
// } else if (ll.getChildAt(1) instanceof LinearLayout) {
// ll = (LinearLayout) ll.getChildAt(1);
// if (ll.getChildAt(0) instanceof RadioGroup) {
// RadioGroup rg = (RadioGroup) ll.getChildAt(0);
// if (rg.getCheckedRadioButtonId() == -1) {
// dialogShowMessage_P("各项信息不能为空,请选择", null);
// return;
// }
// }
// }
//
// }
showProgressDialog();
Config.getExecutorService().execute(new Runnable() {
@Override
public void run() {
getWebService("submit");
}
});
break;
default:
break;
}
}
};
topBack.setOnClickListener(backonClickListener);
cancel.setOnClickListener(backonClickListener);
confirm.setOnClickListener(backonClickListener);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
ArrayList<String> list = data.getStringArrayListExtra("imglist");
loadImg(list);
}
}
@Override
protected void getWebService(String s) {
if (s.equals("query")) {// 提交
try {
JSONObject jsonObject = callWebserviceImp.getWebServerInfo(
"_PAD_KDG_XJ_FWBG_MXCX", zbh + "*" + zbh + "*" + zbh,
"uf_json_getdata", this);
flag = jsonObject.getString("flag");
data_zp = new ArrayList<Map<String, String>>();
if (Integer.parseInt(flag) > 0) {
JSONArray jsonArray = jsonObject.getJSONArray("tableA");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject temp = jsonArray.getJSONObject(i);
Map<String, String> item = new HashMap<String, String>();
item.put("tzlmc", temp.getString("tzlmc"));
item.put("kzzf1", temp.getString("kzzf1"));
item.put("kzsz1", temp.getString("kzsz1"));
item.put("kzzf3", temp.getString("kzzf3"));
item.put("str", temp.getString("str"));
item.put("tzz", temp.getString("tzz"));
item.put("mxh", temp.getString("mxh"));
item.put("path", temp.getString("path"));
data_zp.add(item);
}
Message msg = new Message();
msg.what = Constant.NUM_6;
handler.sendMessage(msg);
} else {
// flag = jsonObject.getString("msg");
Message msg = new Message();
msg.what = Constant.NUM_6;// 失败
handler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
Message msg = new Message();
msg.what = Constant.NETWORK_ERROR;
handler.sendMessage(msg);
}
}
if (s.equals("submit")) {// 提交
try {
String cs = "";
for (int i = 0; i < ll_show.getChildCount(); i++) {
LinearLayout ll = (LinearLayout) ll_show.getChildAt(i);
if (ll.getChildAt(1) instanceof LinearLayout) {
ll = (LinearLayout) ll.getChildAt(1);
if (ll.getChildAt(0) instanceof RadioGroup) {
RadioGroup rg = (RadioGroup) ll.getChildAt(0);
RadioButton rb = (RadioButton) rg.findViewById(rg
.getCheckedRadioButtonId());
if (rb == null) {
cs += "#@##@#0";
} else {
String che = rb.getId() == R.id.rb_1 ? "1"
: "2";
cs += rb.getText().toString() + "#@#" + che
+ "#@#" + rb.getTag().toString();
}
cs += "#^#";
} else if (ll.getChildAt(0) instanceof EditText) {
EditText et = (EditText) ll.getChildAt(0);
CheckBox cb = (CheckBox) ll.getChildAt(1);
String che = cb.isChecked() ? "1" : "2";
cs += et.getText().toString() + "#@#" + che + "#@#"
+ et.getTag().toString();
cs += "#^#";
} else if (ll.getChildAt(0) instanceof Spinner) {
Spinner spinner_val = (Spinner) ll.getChildAt(0);
String data = spinner_val.getSelectedItem().toString();
data = data.substring(1, data.length()-1);
String[] datas = data.split(",");
String name = datas[0].replace("name=", "").trim();
String id = datas[1].replace("id=", "").trim();
cs += name + "#@#" + name + "#@#"+ id;
cs += "#^#";
}
}
}
if (!"".equals(cs)) {
cs = cs.substring(0, cs.length() - 3);
}
// 再提交服务报告
String typeStr = "fwbg";
if ("2".equals(type)) {
typeStr = "fwbg_qr";
}
String str = zbh + "*PAM*" + DataCache.getinition().getUserId();
str += "*PAM*";
str += cs;
JSONObject json = this.callWebserviceImp.getWebServerInfo(
"c#_PAD_KDG_XJ_ALL", str, typeStr, typeStr,
"uf_json_setdata2", this);
flag = json.getString("flag");
if (Integer.parseInt(flag) > 0) {
upload();
// Message msg = new Message();
// msg.what = Constant.SUCCESS;
// handler.sendMessage(msg);
} else {
flag = json.getString("msg");
Message msg = new Message();
msg.what = Constant.FAIL;
handler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
Message msg = new Message();
msg.what = Constant.NETWORK_ERROR;
handler.sendMessage(msg);
}
}
}
private void upload() {
try {
boolean flag = true;
List<Map<String, String>> filelist = new ArrayList<Map<String, String>>();
for (String mxh : filemap.keySet()) {
List<String> filepathlist = filemap.get(mxh);
for (int j = 0; j < filepathlist.size(); j++) {
Map<String, String> map = new HashMap<String, String>();
map.put("mxh", mxh);
map.put("num", j + "");
String path = filepathlist.get(j);
map.put("filepath", path);
if(path.indexOf(Constant.ImgPath)==-1){
filelist.add(map);
}
}
}
int filenum = filelist.size();
for (int i = 0; i < filenum; i++) {
Map<String, String> map = filelist.get(i);
if (flag) {
String mxh = map.get("mxh");
String filepath = map.get("filepath");
String num = map.get("num");
filepath = filepath.substring(7, filepath.length());
// 压缩图片到100K
filepath = ImageUtil
.compressAndGenImage(
convertBitmap(new File(filepath),
getScreenWidth()), 200, "jpg");
File file = new File(filepath);
// toastShowMessage("开始上传第" + (i + 1) + "/" + filenum +
// "张图片");
flag = uploadPic(num, mxh, readJpeg(file),
"uf_json_setdata", zbh, "c#_PAD_KDG_XJ_GDCZP");
file.delete();
} else {
flag = false;
break;
}
}
if (flag) {
Message msg = new Message();
msg.what = 12;
handler.sendMessage(msg);
} else {
Message msg = new Message();
msg.what = 13;
handler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
Message msg = new Message();
msg.what = 13;
handler.sendMessage(msg);
}
}
@SuppressLint("ResourceAsColor")
protected void LoadSbxx(ArrayList<Map<String, String>> data, LinearLayout ll) {
String errormsg = "";
try {
for (int i = 0; i < data.size(); i++) {
Map<String, String> map = data.get(i);
String title = map.get("tzlmc");
errormsg = title;
String type = map.get("kzzf1");
String tzz = map.get("tzz") == null ? "" : map.get("tzz")
.toString();
String content = map.get("str");
View view = null;
if ("2".equals(type)) {// 输入
view = LayoutInflater.from(getApplicationContext())
.inflate(R.layout.include_xj_text, null);
TextView tv_name = (TextView) view
.findViewById(R.id.tv_name);
EditText et_val = (EditText) view.findViewById(R.id.et_val);
et_val.setText(tzz);
et_val.setTag(map.get("mxh"));
et_val.setHint(title);
et_val.setHintTextColor(R.color.gray);
tv_name.setText(title);
} else if ("1".equals(type)) {// 选择
String[] contents = content.split(",");
if (contents.length == 2) {
view = LayoutInflater.from(getApplicationContext())
.inflate(R.layout.include_xj_aqfx, null);
TextView tv_name = (TextView) view
.findViewById(R.id.tv_name);
RadioButton rb_1 = (RadioButton) view
.findViewById(R.id.rb_1);
RadioButton rb_2 = (RadioButton) view
.findViewById(R.id.rb_2);
rb_1.setText(contents[0]);
rb_2.setText(contents[1]);
rb_1.setTag(map.get("mxh"));
rb_2.setTag(map.get("mxh"));
if (tzz.equals(contents[0])) {
rb_1.setChecked(true);
} else if (tzz.equals(contents[1])) {
rb_2.setChecked(true);
}
tv_name.setText(title);
} else if (contents.length == 3) {
view = LayoutInflater.from(getApplicationContext())
.inflate(R.layout.include_xj_type_2, null);
TextView tv_name = (TextView) view
.findViewById(R.id.tv_name);
RadioButton rb_1 = (RadioButton) view
.findViewById(R.id.rb_1);
RadioButton rb_2 = (RadioButton) view
.findViewById(R.id.rb_2);
RadioButton rb_3 = (RadioButton) view
.findViewById(R.id.rb_3);
rb_1.setText(contents[0]);
rb_2.setText(contents[1]);
rb_3.setText(contents[2]);
rb_1.setTag(map.get("mxh"));
rb_2.setTag(map.get("mxh"));
rb_3.setTag(map.get("mxh"));
if (tzz.equals(contents[0])) {
rb_1.setChecked(true);
} else if (tzz.equals(contents[1])) {
rb_2.setChecked(true);
} else if (tzz.equals(contents[2])) {
rb_3.setChecked(true);
}
tv_name.setText(title);
}else{
view = LayoutInflater.from(getApplicationContext())
.inflate(R.layout.include_xj_type_6, null);
TextView tv_name = (TextView) view.findViewById(R.id.tv_name);
Spinner spinner_val = (Spinner) view.findViewById(R.id.spinner_val);
ArrayList<Map<String, String>> data_val = new ArrayList<Map<String, String>>();
Map<String, String> item = new HashMap<String, String>();
item.put("id", "");
item.put("name", "");
data_val.add(item);
for(int m=0;m<contents.length;m++){
item = new HashMap<String, String>();
item.put("id", map.get("mxh"));
item.put("name", contents[m]);
data_val.add(item);
}
SimpleAdapter adapter = new SimpleAdapter(FwbgXj.this,
data_val, R.layout.spinner_item, from, to);
spinner_val.setAdapter(adapter);
for (int m = 0; m < data_val.size(); m++) {
Map<String, String> map_val = data_val.get(m);
if (tzz.equals(map_val.get("name"))) {
spinner_val.setSelection(m);
}
}
tv_name.setText(title);
}
} else if ("3".equals(type)) {// 图片
view = LayoutInflater.from(getApplicationContext())
.inflate(R.layout.include_xj_pz, null);
TextView tv_name = (TextView) view
.findViewById(R.id.tv_name);
tv_name.setText(title);
TextView tv_1 = (TextView) view.findViewById(R.id.tv_1);
final String mxh = map.get("mxh");
tv_1.setTag(mxh);
String path = map.get("path");
try {
if(!"".equals(path)){
String[] paths = path.split(",");
ArrayList<String> arraylist = new ArrayList<String>();
for(int n=0;n<paths.length;n++){
arraylist.add(Constant.ImgPath+tzz+"/"+paths[n]);
}
filemap.put(mxh, arraylist);
tv_1.setText("继续选择");
tv_1.setBackgroundResource(R.drawable.btn_normal_yellow);
}
} catch (Exception e) {
}
tv_1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
tv_curr = (TextView) v;
ArrayList<String> list = filemap.get(mxh);
camera(1, list);
}
});
} else if ("4".equals(type)) { // 日期
view = LayoutInflater.from(getApplicationContext())
.inflate(R.layout.include_xj_text, null);
TextView tv_name = (TextView) view
.findViewById(R.id.tv_name);
final EditText et_val = (EditText) view
.findViewById(R.id.et_val);
et_val.setFocusable(false);
et_val.setText(tzz);
et_val.setTag(map.get("mxh"));
et_val.setHintTextColor(R.color.gray);
et_val.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dateDialog(et_val);
}
});
tv_name.setText(title);
} else if ("5".equals(type)) { // 数值
view = LayoutInflater.from(getApplicationContext())
.inflate(R.layout.include_xj_text, null);
TextView tv_name = (TextView) view
.findViewById(R.id.tv_name);
EditText et_val = (EditText) view.findViewById(R.id.et_val);
et_val.setInputType(InputType.TYPE_CLASS_NUMBER);
et_val.setText(tzz);
et_val.setTag(map.get("mxh"));
et_val.setHintTextColor(R.color.gray);
tv_name.setText(title);
}
ll.addView(view);
}
} catch (Exception e) {
dialogShowMessage_P("数据错误:" + errormsg + ",选项数据类型不匹配,请联系管理员修改",
null);
e.printStackTrace();
}
}
private void loadImg(final ArrayList<String> list) {
try {
String mxh = tv_curr.getTag().toString();
if(list.size()>0){
tv_curr.setText("继续选择");
tv_curr.setBackgroundResource(R.drawable.btn_normal_yellow);
}else{
tv_curr.setText("选择图片");
tv_curr.setBackgroundResource(R.drawable.btn_normal);
}
filemap.put(mxh, list);
} catch (Exception e) {
e.printStackTrace();
}
}
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case Constant.FAIL:
if (progressDialog != null) {
progressDialog.dismiss();
}
dialogShowMessage_P("失败,请检查后重试...错误标识:" + flag, null);
break;
case Constant.SUCCESS:
if (progressDialog != null) {
progressDialog.dismiss();
}
message = "提交成功";
dialogShowMessage_P(message,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface face,
int paramAnonymous2Int) {
onBackPressed();
}
});
break;
case Constant.NETWORK_ERROR:
if (progressDialog != null) {
progressDialog.dismiss();
}
dialogShowMessage_P(Constant.NETWORK_ERROR_STR, null);
break;
case Constant.NUM_6:
if (progressDialog != null) {
progressDialog.dismiss();
}
LoadSbxx(data_zp, ll_show);
break;
case Constant.NUM_7:
if (progressDialog != null) {
progressDialog.dismiss();
}
break;
case Constant.NUM_8:
if (progressDialog != null) {
progressDialog.dismiss();
}
break;
case Constant.NUM_9:
if (progressDialog != null) {
progressDialog.dismiss();
}
dialogShowMessage_P(message,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface face,
int paramAnonymous2Int) {
}
});
break;
case 11:
if (progressDialog != null) {
progressDialog.dismiss();
}
dialogShowMessage_P("仓位权限错误,请联系管理员", null);
break;
case 12:
if (progressDialog != null) {
progressDialog.dismiss();
}
dialogShowMessage_P("服务报告提交成功",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface face,
int paramAnonymous2Int) {
Intent intent = getIntent();
setResult(-1, intent);
finish();
}
});
break;
case 13:
if (progressDialog != null) {
progressDialog.dismiss();
}
dialogShowMessage_P("服务报告提交成功,图片上传失败,请到服务报告修改模块中修改!",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface face,
int paramAnonymous2Int) {
Intent intent = getIntent();
setResult(-1, intent);
finish();
}
});
break;
case 14:
if (progressDialog != null) {
progressDialog.dismiss();
}
dialogShowMessage_P("请拍照!", null);
break;
case 15:
break;
}
}
};
//
// @Override
// public void onBackPressed() {
// Intent intent = new Intent(this, MainActivity.class);
// intent.putExtra("currType", 1);
// startActivity(intent);
// finish();
// }
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pe.gob.sunarp.incidenciasapp.prueba;
import java.util.List;
import pe.gob.sunarp.incidenciasapp.dto.IncidenciaDto;
import pe.gob.sunarp.incidenciasapp.service.contrato.IncidenciaService;
import pe.gob.sunarp.incidenciasapp.service.implementacion.IncidenciaServiceImplementacion;
/**
*
* @author REYSAN
*/
public class Prueba02 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
IncidenciaService service = new IncidenciaServiceImplementacion();
String[] tipo2 = service.getListaNombre();
service.registrarIncidencia(new IncidenciaDto(100, tipo2[0], "Se puede Resolver en la semana", "Modificacion de sistemaa"));
service.registrarIncidencia(new IncidenciaDto(200, tipo2[0], "Se puede Resolver en el transcurso del dia", "impresora"));
service.registrarIncidencia(new IncidenciaDto(300, tipo2[0], "Se debe resolver inmediatamente", " cable"));
service.registrarIncidencia(new IncidenciaDto(100, tipo2[1], "Se puede Resolver en la semana", "Modificacion de sistemaa"));
service.registrarIncidencia(new IncidenciaDto(200, tipo2[1], "Se puede Resolver en el transcurso del dia", "impresora"));
service.registrarIncidencia(new IncidenciaDto(300, tipo2[1], "Se debe resolver inmediatamente", " cable"));
List<IncidenciaDto> lista = service.getIncidente(tipo2[1]);
for(IncidenciaDto dto : lista){
System.out.println("Datos: "+dto.getCodigo() +"\t" + dto.getNombre() +"\t"+ dto.getDetalle()+"\t"+ dto.getIncidente());
}
}
}
|
package studentService;
import java.util.HashMap;
import Student.entity.Student;
public class StudentOeration {
HashMap<String, Student> studentRank;
HashMap<Student, Integer> studentMarks;
public StudentOeration() {
super();
this.studentRank = new HashMap<>();
this.studentMarks = new HashMap<>();
}
public StudentOeration(HashMap<String, Student> studentRank, HashMap<Student, Integer> studentMarks) {
super();
this.studentRank = studentRank;
this.studentMarks = studentMarks;
}
public void printStudentMarks(HashMap<Student, Integer> set) {
this.studentMarks = set;
for (Student s : studentMarks.keySet()) {
System.out.print(s.getRollNumber() + ":");
System.out.print(s.getName() + " ");
System.out.print(studentMarks.get(s));
System.out.println();
}
}
public void printStudentRanks(HashMap<String, Student> set) {
this.studentRank = set;
for (String s : studentRank.keySet()) {
System.out.print(studentRank.get(s).getRollNumber()+":");
System.out.print(studentRank.get(s).getName()+" ");
System.out.print(s);
System.out.println();
}
}
}
|
package com.vendingMachine.DeloitteTask.Dao;
import java.util.HashMap;
import java.util.Map;
/**
* Warehouse acts as a dao class for maintaining the count of products and coins
*
* @author Nanda Babu A
*
* @param <Product/Coin>
*/
public class Warehouse<T> {
private Map<T, Integer> warehouse = new HashMap<T, Integer>();
/**
* getQuantity is used to return the quantity of products/coins from warehouse
*
* @param product
* @return quantityValue
*/
public int getQuantity(T product) {
Integer value = warehouse.get(product);
return value == null ? 0 : value;
}
/**
* add is used to add the quantity of inputed coins in warehouse
*
* @param product
*/
public void add(T product) {
int count = warehouse.get(product);
warehouse.put(product, count + 1);
}
/**
* deduct is used to reduce the values from the warehouse with the current
* products/coins
*
* @param product
*/
public void deduct(T product) {
if (hasProduct(product)) {
int count = warehouse.get(product);
warehouse.put(product, count - 1);
}
}
/**
* hasProduct checks whether the products/coins are present in the warehouse or
* not
*
* @param product
* @return booleanValue
*/
public boolean hasProduct(T product) {
return getQuantity(product) > 0;
}
/**
* clear method is used to empty the products/coins warehouse
*/
public void clear() {
warehouse.clear();
}
/**
* put method is used to set the initial values of products/coins to the
* warehouse in vendor machine
*
* @param product
* @param quantity
*/
public void put(T product, int quantity) {
warehouse.put(product, quantity);
}
} |
package org.erwthmatologio.ptyxiakh;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.app.AlertDialog;
public class MainActivity extends Activity
{
String[][] questions = new String[20][6];
static int j=0;
static int i=0;
static int correct=0;
static int questionnum=0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
questions[0][0]="Alternate Question 1";
questions[0][1]="Correct 1";
questions[0][2]="Correct 2";
questions[0][3]="Correct 3";
questions[0][4]="Correct 4";
questions[0][5]="4";
questions[1][0]="Alternate Question 2";
questions[1][1]="Correct 1";
questions[1][2]="Correct 2";
questions[1][3]="Correct 3";
questions[1][4]="Correct 4";
questions[1][5]="2";
questions[2][0]="Alternate Question 3";
questions[2][1]="Correct 1";
questions[2][2]="Correct 2";
questions[2][3]="Correct 3";
questions[2][4]="Correct 4";
questions[2][5]="1";
questions[3][0]="Alternate Question 4";
questions[3][1]="Correct 1";
questions[3][2]="Correct 2";
questions[3][3]="Correct 3";
questions[3][4]="Correct 4";
questions[3][5]="3";
questions[4][0]="Alternate Question 5";
questions[4][1]="Correct 1";
questions[4][2]="Correct 2";
questions[4][3]="Correct 3";
questions[4][4]="Correct 4";
questions[4][5]="1";
retrieveQuestion();
}
public void retrieveQuestion()
{
TextView question = (TextView)findViewById(R.id.textView1);
RadioGroup radioGroup = (RadioGroup)findViewById(R.id.radioGroup1);
for (i = 0; i < radioGroup.getChildCount(); i++)
((RadioButton) radioGroup.getChildAt(i)).setText(questions[j][i+1]);
question.setText(questions[j][0]);
j++;
}
public void onRadioButtonClicked(View view)
{
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setMessage("This is an alert with no consequence");
dlgAlert.setTitle("App Title");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(false);
dlgAlert.create();
RadioButton button = (RadioButton) view;
RadioGroup radioGroup = (RadioGroup)findViewById(R.id.radioGroup1);
int k=Integer.parseInt(questions[j-1][i+1]);
boolean checked = ((RadioButton) radioGroup.getChildAt(k-1)).isChecked();
if ((checked)&&(questionnum<5))
{
button.setChecked(false);
correct++;
questionnum++;
}
else
{
button.setChecked(false);
questionnum++;
}
if (questionnum<5)
retrieveQuestion();
else
{
dlgAlert.setMessage(String.valueOf(correct)+"/"+String.valueOf(questionnum)+" are correct!");
dlgAlert.show();
}
}
protected void onPause() {
super.onPause();
j=0;
correct=0;
questionnum=0;
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
|
package com.yinghai.a24divine_user.module.order.book;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.view.ViewStub;
import com.example.fansonlib.callback.LoadMoreListener;
import com.example.fansonlib.utils.ShowToast;
import com.example.fansonlib.widget.recyclerview.AutoLoadRecyclerView;
import com.yinghai.a24divine_user.R;
import com.yinghai.a24divine_user.base.BaseMvpSwipeFragment;
import com.yinghai.a24divine_user.bean.OrderBean;
import com.yinghai.a24divine_user.bean.ProductOrderListBean;
import com.yinghai.a24divine_user.callback.OnAdapterListener;
import com.yinghai.a24divine_user.constant.ConstAdapter;
import com.yinghai.a24divine_user.module.divine.book.pay.PayWaysWindow;
import com.yinghai.a24divine_user.module.order.all.mvp.ContractOrder;
import com.yinghai.a24divine_user.module.order.all.mvp.OrderPresenter;
import com.yinghai.a24divine_user.module.order.detail.OrderDetailsActivity;
import com.yinghai.a24divine_user.utils.LogUtils;
/**
* @author Created by:fanson
* Created on:2017/10/24 16:13
* Describe:未完成的订单Fragment
*/
public class BookFragment extends BaseMvpSwipeFragment<OrderPresenter> implements ContractOrder.IOrderView, LoadMoreListener, OnAdapterListener, PayWaysWindow.PayCallback {
private static final String TAG = BookFragment.class.getSimpleName();
/**
* 标识数据是否已全部加载完毕
*/
private boolean mIsLoadComplete = false;
private static final int PAGE_SIZE = 10;
private BookOrderAdapter mAdapter;
private BookProductAdapter mProductAdapter;
private AutoLoadRecyclerView mRecyclerView;
private PayWaysWindow payWaysWindow;
private ViewStub mViewStub;
private boolean mIsPull = false; //标识是否上拉刷新
private boolean mIsLoadData = false; // 标记是否已加载数据
/**
* 标识有没切换类型
*/
private boolean mIsChangeType = false;
public static final int TYPE_DIVINE = 1;
/**
* 获取数据的类型
*/
private int mDataType = TYPE_DIVINE;
@Override
protected int getLayoutId() {
return R.layout.fragment_book_order;
}
@Override
protected OrderPresenter createPresenter() {
return new OrderPresenter(this, hostActivity);
}
@Override
protected View initView(View view, Bundle bundle) {
super.initView(view, bundle);
initRecyclerView();
return rootView;
}
private void initRecyclerView() {
mRecyclerView = findMyViewId(R.id.rv_book_order);
mRecyclerView.setLayoutManager(new LinearLayoutManager(hostActivity));
mRecyclerView.setOnPauseListenerParams(true, true);
mRecyclerView.setLoadMoreListener(this);
mAdapter = new BookOrderAdapter(hostActivity, this);
mRecyclerView.setAdapter(mAdapter);
}
@Override
protected void initToolbarTitle() {
}
@Override
protected void initData() {
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
LogUtils.d(TAG, isVisibleToUser);
if (isVisibleToUser && !mIsLoadData) {
showLoading();
getOrderData();
mIsChangeType = false;
mIsLoadData = true;
}
}
/**
* 更改获取数据的类型
*
* @param type
*/
public void resetDataType(int type) {
if (type == TYPE_DIVINE) {
if (mAdapter == null) {
mAdapter = new BookOrderAdapter(hostActivity, this);
}
mAdapter.clearList();
mRecyclerView.setAdapter(mAdapter);
} else {
if (mProductAdapter == null) {
mProductAdapter = new BookProductAdapter(hostActivity, this);
}
mProductAdapter.clearList();
mRecyclerView.setAdapter(mProductAdapter);
}
mDataType = type;
mIsChangeType = true;
mIsLoadData = false;
mIsLoadComplete = false;
mPresenter.resetPageNum();
if (getUserVisibleHint()) {
showLoading();
getOrderData();
mIsChangeType = false;
mIsLoadData = true;
}
}
private void getOrderData() {
mPresenter.onOrderOrder("1;2;3;4;997", mDataType);
}
@Override
public void loadMore() {
if (!mIsLoadComplete){
getOrderData();
}
}
@Override
protected void pullRefresh() {
mIsPull = true;
mIsLoadComplete = false;
mPresenter.resetPageNum();
getOrderData();
}
@Override
public void showOrderSuccess(OrderBean bean) {
if (mIsPull) {
mAdapter.clearList();
mIsPull = false;
}
mRecyclerView.loadFinish(null);
if (bean.getData().getTfOrderList() != null && bean.getData().getTfOrderList().size() > 0) {
hideNoDataLayout();
mAdapter.appendList(bean.getData().getTfOrderList());
if (bean.getData().getTfOrderList().size() < PAGE_SIZE) {
mIsLoadComplete = true;
}
}
if (mAdapter.getItemCount() == 0) {
showNoDataLayout();
mIsLoadComplete = true;
}
stopRefresh();
hideLoading();
}
@Override
public void showOrderFailure(String errorMsg) {
ShowToast.singleShort(errorMsg);
stopRefresh();
hideLoading();
}
@Override
public void showProductListSuccess(ProductOrderListBean bean) {
if (mIsPull) {
mProductAdapter.clearList();
mIsPull = false;
}
mRecyclerView.loadFinish(null);
if (bean.getData().getTfOrderList() != null && bean.getData().getTfOrderList().size() > 0) {
hideNoDataLayout();
mProductAdapter.appendList(bean.getData().getTfOrderList());
if (bean.getData().getTfOrderList().size() < PAGE_SIZE) {
mIsLoadComplete = true;
}
}
if (mProductAdapter.getItemCount() == 0) {
showNoDataLayout();
mIsLoadComplete = true;
}
stopRefresh();
hideLoading();
}
@Override
public void showProductListFailure(String errorMsg) {
ShowToast.singleShort(errorMsg);
stopRefresh();
hideLoading();
}
/**
* 显示无数据界面
*/
@Override
public void showNoDataLayout() {
if (mViewStub==null){
mViewStub = (ViewStub) hostActivity.findViewById(R.id.vs_book_no_data);
}
if (mViewStub != null) {
mViewStub.setVisibility(View.VISIBLE);
}
}
/**
* 隐藏无数据界面
*/
@Override
public void hideNoDataLayout() {
if (mViewStub != null) {
mViewStub.setVisibility(View.GONE);
}
}
@Override
public void clickItem(Object... object) {
switch ((Integer) object[0]) {
case ConstAdapter.DIVINE_ORDER_DETAIL:
OrderDetailsActivity.startOrderDetailsActivity(hostActivity, 2, (OrderBean.DataBean.TfOrderListBean) object[1]);
break;
case ConstAdapter.OPEN_PRODUCT_ORDER_DETAIL:
OrderDetailsActivity.startOrderDetailsActivity(hostActivity, 1, (ProductOrderListBean.DataBean.TfOrderListBean) object[1]);
break;
case ConstAdapter.OPEN_PAY_WINDOW:
payWaysWindow = new PayWaysWindow(hostActivity, (String) object[1], (Integer) object[2], (Integer) object[3], this);
payWaysWindow.showPopupWindow();
break;
default:
break;
}
}
@Override
public void showPayLoading() {
}
@Override
public void paySuccess() {
payWaysWindow.dismiss();
ShowToast.singleShort(getString(R.string.pay_success_to_order_see));
}
@Override
public void payFailure(int errCode) {
ShowToast.singleShort(getString(R.string.alipay_failure) + errCode);
}
@Override
public void completeOrderSuccess() {
ShowToast.singleShort(getString(R.string.order_has_complete));
hideLoading();
}
@Override
public void completeOrderFailure(String errMsg) {
ShowToast.singleShort(errMsg);
hideLoading();
}
@Override
public void onDestroy() {
super.onDestroy();
mAdapter.releaseResource();
}
}
|
package com.coder4.lmsia.thrift.client;
/**
* @author coder4
*/
public class K8ServiceKey {
private String k8ServiceHost;
private int k8ServicePort;
public K8ServiceKey(String k8ServiceHost, int k8ServicePort) {
this.k8ServiceHost = k8ServiceHost;
this.k8ServicePort = k8ServicePort;
}
public String getK8ServiceHost() {
return k8ServiceHost;
}
public void setK8ServiceHost(String k8ServiceHost) {
this.k8ServiceHost = k8ServiceHost;
}
public int getK8ServicePort() {
return k8ServicePort;
}
public void setK8ServicePort(int k8ServicePort) {
this.k8ServicePort = k8ServicePort;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("K8ServiceKey{");
sb.append("k8ServiceHost='").append(k8ServiceHost).append('\'');
sb.append(", k8ServicePort=").append(k8ServicePort);
sb.append('}');
return sb.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
K8ServiceKey that = (K8ServiceKey) o;
if (k8ServicePort != that.k8ServicePort) return false;
return k8ServiceHost != null ? k8ServiceHost.equals(that.k8ServiceHost) : that.k8ServiceHost == null;
}
@Override
public int hashCode() {
int result = k8ServiceHost != null ? k8ServiceHost.hashCode() : 0;
result = 31 * result + k8ServicePort;
return result;
}
} |
package SystemCode;
/**
* DatabaseHandler
*
* @author Mark Glenn
* L00113302 Cloud
*/
import javax.swing.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
@SuppressWarnings("serial")
public class DatabaseHandler extends javax.swing.JFrame {
// credentials for database including AWS RDS database endpoint and JDBC
// driver
/**
* Access details for database
*/
final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
final String DB_URL = "jdbc:mysql://devops.clql55s9fxrz.eu-west-1.rds.amazonaws.com";
final String USER_NAME = "DevOps";
final String PASSWORD = "groupthree";
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
/**
* Connect to database
*
*/
public void connectToDatabase() {
try {
// STEP 1 - Load the JDBC driver
java.lang.Class.forName(JDBC_DRIVER);
System.out.println("STEP 1 COMPLETE - Driver Registered...");
// STEP 2 - Open a connection
conn = DriverManager.getConnection(DB_URL, USER_NAME, PASSWORD);
System.out.println("STEP 2 COMPLETE - Connection obtained...");
//JOptionPane.showMessageDialog(null,"Connected to Database");
// STEP 3 - Create Statement object
stmt = conn.createStatement();
System.out.println("STEP 3 COMPLETE - Query executed.");
} catch (ClassNotFoundException e) {
//JOptionPane.showMessageDialog(null,"Could not load driver.\n" + e.getMessage());
} catch (SQLException e) {
//System.out.print("Connection Error");
}
}
/**
* @param query
* create database query
*/
public void doQuery(String query) {
try {
java.lang.Class.forName(JDBC_DRIVER);
System.out.println("STEP 1 COMPLETE - Driver Registered...");
// STEP 1 - Open a connection
conn = DriverManager.getConnection(DB_URL, USER_NAME, PASSWORD);
System.out.println("STEP 2 COMPLETE - Connection obtained...");
// STEP 2 - Create Statement object
stmt = conn.createStatement();
System.out.println("STEP 3 COMPLETE - Statement object created...");
System.out.println("STEP 4(a) COMPLETE - Query executed and database found...");
System.out.println("STEP 4(b) COMPLETE - Query executed.");
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
}// end of class
|
package com.sample.app;
import static org.junit.Assert.*;
import java.util.HashMap;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.sample.app.NativeRooster;
import com.sample.app.Rooster;
public class NativeRoosterTest {
private NativeRooster nativeRooster;
private Rooster rooster;
private HashMap<String, String> converter;
@Before
public void init() {
converter = new HashMap<String, String>();
converter.put("MyLang", "Ko-Ko-Ro-Koooo");
converter.put("Danish", "ky-ky-li-ky");
converter.put("Dutch", "ku-ke-le-ku");
converter.put("Finnish", "ku-kko-kie-kuu");
nativeRooster = new NativeRooster(rooster);
}
@Test
public void test_nativeRooster_no_secondLanguage(){
nativeRooster.converter=converter;
assertEquals("Cock-a-doodle-doo",nativeRooster.singInLanguage(""));
}
@Test(expected = RuntimeException.class)
public void test_nativeRooster_secondLanguage_nullcheck(){
nativeRooster.converter=null;
assertEquals("Ko-Ko-Ro-Koooo",nativeRooster.singInLanguage(""));
}
@Test
public void test_nativeRooster_secondLanguage_myLang(){
nativeRooster.converter=converter;
assertEquals("Ko-Ko-Ro-Koooo",nativeRooster.singInLanguage("MyLang"));
}
@Test
public void test_nativeRooster_secondLanguage_danishLang(){
nativeRooster.converter=converter;
assertEquals("ky-ky-li-ky",nativeRooster.singInLanguage("Danish"));
}
@Test
public void test_nativeRooster_secondLanguage_dutchLang(){
nativeRooster.converter=converter;
assertEquals("ku-ke-le-ku",nativeRooster.singInLanguage("Dutch"));
}
@Test
public void test_nativeRooster_secondLanguage_finnishLang(){
nativeRooster.converter=converter;
assertEquals("ku-kko-kie-kuu",nativeRooster.singInLanguage("Finnish"));
}
@After
public void finalize() {
System.out.println("Completed");
}
}
|
package com.findmyfriend;
/**
* Created by Harish on 18-09-2016.
*/
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
import java.util.Calendar;
public class Scheduler extends AppCompatActivity implements View.OnClickListener {
String mobl="",msg="";
EditText contnet;
Button btn;
DatePicker dp;
TimePicker tp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scheduler);
Bundle bundle=getIntent().getExtras();
mobl=bundle.getString("Mobile");
contnet=(EditText)findViewById(R.id.content);
btn=(Button)findViewById(R.id.send);
btn.setOnClickListener(this);
dp=(DatePicker)findViewById(R.id.datePicker);
tp=(TimePicker)findViewById(R.id.timePicker);
}
@Override
public void onClick(View v) {
Calendar cal = Calendar.getInstance();
cal.set(5, dp.getDayOfMonth());
cal.set(2, dp.getMonth());
cal.set(1, dp.getYear());
cal.set(11, tp.getCurrentHour().intValue());
cal.set(12, tp.getCurrentMinute().intValue());
cal.set(13, 0);
Intent intent = new Intent(this, MyReceiver.class);
Bundle bundle = new Bundle();
bundle.putString("sms",mobl);
bundle.putString("mob", msg);
intent.putExtra("bundle", bundle);
// ((AlarmManager) this.getSystemService(NotificationCompatApi21.CATEGORY_ALARM)).set(0, cal.getTimeInMillis(), PendingIntent.getBroadcast(this, 1234, intent, 134217728));
//this.dismiss();
}
}
|
package lando.systems.ld36.entities;
import aurelienribon.tweenengine.primitives.MutableFloat;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.utils.Array;
import lando.systems.ld36.ai.StateMachine;
import lando.systems.ld36.ai.Transition;
import lando.systems.ld36.ai.conditions.AwayFromObjectCondition;
import lando.systems.ld36.ai.conditions.NearObjectCondition;
import lando.systems.ld36.ai.conditions.NearScreenCondition;
import lando.systems.ld36.ai.states.ChaseAvoidState;
import lando.systems.ld36.ai.states.ChaseState;
import lando.systems.ld36.ai.states.WaitState;
import lando.systems.ld36.ai.states.WanderState;
import lando.systems.ld36.levels.Level;
import lando.systems.ld36.utils.Assets;
public class FlashDriveEasy extends Enemy {
public FlashDriveEasy(Level level, float x, float y) {
super(level);
walkAnimation = Assets.flashWalk;
attackAnimation = Assets.flashPunch;
tex = walkAnimation.getKeyFrame(timer);
width = tex.getRegionWidth();
height = new MutableFloat(tex.getRegionHeight());
jumpVelocity = 50f;
hitBounds = new Rectangle(position.x, position.y, 32f, tex.getRegionHeight());
health = 2;
maxHealth = 2;
position.x = x;
position.y = y;
// TODO: Maybe remove this?
isMoving = true;
}
public void update(float dt) {
super.update(dt);
jump();
timer += dt;
}
public void initializeStates(){
WaitState wait = new WaitState(this);
WanderState wander = new WanderState(this);
ChaseAvoidState chase = new ChaseAvoidState(this);
// Conditions
NearScreenCondition nearCond = new NearScreenCondition(level.screen.camera, this);
NearObjectCondition nearPlayer = new NearObjectCondition(this, level.player, 70);
AwayFromObjectCondition farPlayer = new AwayFromObjectCondition(this, level.player, 70);
// Transitions
Array<Transition> transitions = new Array<Transition>();
transitions.add(new Transition(wait, nearCond, wander));
transitions.add(new Transition(wander, nearPlayer, chase));
transitions.add(new Transition(chase, farPlayer, wander));
// Create State Machine
stateMachine = new StateMachine(wait, transitions);
addDieState();
}
}
|
package model;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import controller.Controller;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
public class PosaljiBtnEvent implements EventHandler<javafx.event.ActionEvent> {
private TextField primalacTextFld;
private TextField naslovTextFld;
private TextArea textPorukeTextArea;
private Scene scene2;
private Scene scena3;
private Label labelaScene2;
private Stage primaryStage;
public PosaljiBtnEvent(TextField primalacTextFld, TextField naslovTextFld, TextArea textPorukeTextArea) {
this.primalacTextFld = primalacTextFld;
this.naslovTextFld = naslovTextFld;
this.textPorukeTextArea = textPorukeTextArea;
}
@Override
public void handle(ActionEvent arg0) {
try {
// iscitavanje file-a i izvlacenje korisnika kome se salje poruka
ArrayList<Korisnik> korisniciIzFajla = Controller.getInstance().getKorisniciUFileu();
Korisnik primalac = new Korisnik(primalacTextFld.getText());
for (Korisnik korisnik : korisniciIzFajla) {
if (korisnik.equals(primalac)) {
// pravljenje novog objekta tipa Poruka koji se kasnije dodaje u kolekciju
// Korisnika koji salje i koji prima poruke
Poruka poruka = new Poruka(primalac.toString(), Controller.getInstance().getKorisnik().toString(),
Calendar.getInstance().getTime(), naslovTextFld.getText(), textPorukeTextArea.getText());
for (int i = 0; i < korisniciIzFajla.size(); i++) {
if (korisniciIzFajla.get(i).equals(Controller.getInstance().getKorisnik())) {
korisniciIzFajla.get(i).getPoslatePoruke().add(poruka);
}
}
if (korisnik.equals(Controller.getInstance().getScenaTreca().getKorisnik())) {
Controller.getInstance().getScenaTreca().getKorisnik().getPrimljenePoruke().add(poruka);
} else {
korisnik.getPrimljenePoruke().add(poruka);
}
Controller.getInstance().getScenaDruga().setKorisnik(Controller.getInstance().getKorisnik());
Controller.getInstance().getScenaDruga().getUkupnoPorukaLbl()
.setText("Ukupno poruka: "
+ Controller.getInstance().getScenaDruga().getKorisnik().getPrimljenePoruke().size()
+ " dolazne i "
+ Controller.getInstance().getScenaDruga().getKorisnik().getPoslatePoruke().size()
+ " odlazne");
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("korisnici.dat"));
out.writeObject(korisniciIzFajla);
out.flush();
out.close();
scene2 = Controller.getInstance().getSceneTwo();
primaryStage = Controller.getInstance().getPrimaryStage();
primaryStage.setScene(scene2);
primaryStage.show();
primalacTextFld.clear();
naslovTextFld.clear();
textPorukeTextArea.clear();
return;
}
}
Alert alert = new Alert(AlertType.INFORMATION);
alert.setContentText("Korisnik kome zelite poslati poruku ne postoji!");
alert.show();
} catch (Exception e) {
// TODO: handle exception
}
}
}
|
package com.ibeiliao.pay.admin.controller.report;
import com.ibeiliao.pay.ServiceException;
import com.ibeiliao.pay.admin.dto.PageResult;
import com.ibeiliao.pay.admin.dto.RestResult;
import com.ibeiliao.pay.admin.utils.RequestUtils;
import com.ibeiliao.pay.admin.utils.resource.Menu;
import com.ibeiliao.pay.admin.utils.resource.MenuResource;
import com.ibeiliao.pay.api.ApiCode;
import com.ibeiliao.pay.api.GetListResponse;
import com.ibeiliao.pay.api.dto.response.SchoolVO;
import com.ibeiliao.pay.api.provider.StatePayProvider;
import com.ibeiliao.platform.commons.utils.ParameterUtil;
import com.ibeiliao.statement.api.dto.response.PayCodeSchoolDailySummary;
import com.ibeiliao.statement.api.dto.response.PayCodeSchoolDailySummaryResp;
import com.ibeiliao.statement.api.provider.PayCodeStatementProvider;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.FastDateFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
/**
* 功能: 幼儿园支付方式 统计
* <p>
* 详细:
*
* @author jingyesi 16/11/9
*/
@Controller
@RequestMapping("admin/report")
@Menu(name = "查询幼儿园支付方式每日汇总", parent = "报表管理", sequence = 1300000)
public class PayCodeSchoolDailySummaryController {
private static final Logger logger = LoggerFactory.getLogger(PayCodeDailySummaryController.class);
@Autowired
private PayCodeStatementProvider payCodeStatementProvider;
@Autowired
private StatePayProvider statePayProvider;
@RequestMapping("queryPayCodeSchoolSummary.xhtml")
@MenuResource("查询幼儿园支付方式每日汇总页面")
public String index(HttpServletRequest request) {
ModelMap model = new ModelMap();
// 获取所有幼儿园
GetListResponse<SchoolVO> response = statePayProvider.getAllSallers();
request.setAttribute("schools", response.getData());
return "/report/paycode_school_daily_summary";
}
@RequestMapping("queryPayCodeSchoolSummary")
@MenuResource("查询幼儿园支付方式每日汇总")
@ResponseBody
public PageResult queryPayCodeSchoolSummary(
String time, short payCode, long schoolId, int page, int pageSize) {
logger.info("查询幼儿园支付方式每日汇总 | payCode:{}, schoolId:{} time: {}, page:{}, pageSize:{}",
payCode, schoolId, time, page, pageSize);
ParameterUtil.assertTrue(StringUtils.isNotEmpty(time), "时间范围不能为空");
Date[] dateArr = RequestUtils.toDateArray(time);
PayCodeSchoolDailySummaryResp response = payCodeStatementProvider.querySchoolDailySummaryByDate(
payCode, schoolId, dateArr[0], dateArr[1], page, pageSize);
if (response.getCode() != ApiCode.SUCCESS) {
throw new ServiceException(ApiCode.FAILURE, response.getMessage());
}
return new PageResult<List<PayCodeSchoolDailySummary>>(page, pageSize, 0, response.getList());
}
@RequestMapping("queryPayCodeSchoolSummarySum")
@MenuResource("查询幼儿园支付方式每日汇总合计")
@ResponseBody
public RestResult queryPayCodeSchoolSummarySum(
String time, short payCode, long schoolId) {
logger.info("查询幼儿园支付方式每日汇总 | payCode:{}, schoolId:{} time: {}",
payCode, schoolId, time);
ParameterUtil.assertTrue(StringUtils.isNotEmpty(time), "时间范围不能为空");
Date[] dateArr = RequestUtils.toDateArray(time);
PayCodeSchoolDailySummaryResp response = payCodeStatementProvider.querySchoolDailySummarySumByDate(
payCode, schoolId, dateArr[0], dateArr[1]);
if (response.getCode() != ApiCode.SUCCESS) {
throw new ServiceException(ApiCode.FAILURE, response.getMessage());
}
return new RestResult(ApiCode.SUCCESS, null, response.getList().get(0));
}
// /**
// * 把输入的时间范围转换成 Date 数组
// *
// * @param dateRange
// * @return
// */
// private Date[] toDateArray(String dateRange) {
// String[] array = dateRange.split(" - ");
// FastDateFormat fdf = FastDateFormat.getInstance("yyyy-MM-dd");
// try {
// Date startTime = fdf.parse(array[0]);
// Date endTime = fdf.parse(array[1]);
// return new Date[]{startTime, endTime};
// } catch (ParseException e) {
// throw new IllegalArgumentException("错误的时间范围: " + dateRange);
// }
// }
}
|
package tolteco.sigma.report;
import java.awt.Desktop;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import tolteco.sigma.model.dao.DatabaseException;
import tolteco.sigma.model.dao.jdbc.JDBCFinancaDAO;
import tolteco.sigma.model.entidades.Financa;
/**
* Codigo de escrita de relatorios em PDF do SIGMA
* @author Maycon
*/
public class EscritaRelatorio {
private final StringBuilder QUERY = new StringBuilder();
private String namefile = "Relatorio(";
private String A = new SimpleDateFormat("dd/MM/YYYY").format(new Date());
private String B = new SimpleDateFormat("dd-MM-YYYY").format(new Date());
/**
* 14/05 - Maycon
* Escreve o Latex
* @param tipo : tipo de relatorio solicitado
* @return : true se tudo ocorreu bem
* @throws DatabaseException em erro.
*/
private boolean writeReport(int tipo) throws DatabaseException {
String t;
if (tipo == 0){
t = "Mensal";
} else if (tipo == 1){
t = "Anual";
} else {
t = "Nao definido";
}
JDBCFinancaDAO jfd = new JDBCFinancaDAO();
namefile = namefile + B;
namefile = namefile + ").tex";
final File file = new File(namefile);
try {
file.createNewFile();
} catch (IOException ex) {
return false;
} //Finalização de criacao de arquivo
PrintWriter writer;
try {
writer = new PrintWriter(new BufferedWriter(new FileWriter(file, true)));
} catch (IOException ex) {
Logger.getLogger(EscritaRelatorio.class.getName()).log(Level.SEVERE, null, ex);
return false;
}//Finalizacao de inicializacao de escritor
/**
* 04/09 - Maycon
* Executa metodo que busca os dados e os tras em um ArrayList para serem adicionados a escrita depois
*/
List<Financa> data = jfd.toReport(tipo);
if (data == null){
return false;
}
QUERY.append("\\documentclass[11pt]{article}\n")
.append("\\usepackage[brazilian]{babel}\n")
.append("\\usepackage[utf8]{inputenc}\n")
.append("\\usepackage[T1]{fontenc}\n")
.append("\\usepackage{makeidx}\n")
.append("\\usepackage{multirow}\n")
.append("\\usepackage{subfigure}\n")
.append("\\usepackage{multicol}\n")
.append("\\usepackage{color}\n")
.append("\\usepackage[dvipsnames,svgnames,table]{xcolor}\n")
.append("\\usepackage{graphicx}\n")
.append("\\usepackage{epstopdf}\n")
.append("\\usepackage{ulem}\n")
.append("\\usepackage{float}\n")
.append("\\usepackage{enumerate}\n")
.append("\\usepackage{hyperref}\n")
.append("\\usepackage{amsmath}\n")
.append("\\usepackage{amssymb,amsmath}\n")
.append("\\usepackage{watermark}\n")
.append("\\usepackage{eso-pic,calc}\n")
.append("\\usepackage{fancyhdr}\n")
.append("\\usepackage{verbatim}\n")
.append("\\usepackage{tabularx}\n")
.append("\\usepackage[none]{hyphenat}\n")
.append("\\renewcommand{\\theenumi}{\\Alph{enumi}}\n")
.append("\\makeatletter\n")
.append("\\sloppy\n")
.append("\\usepackage{geometry}\n")
.append("\\geometry{a4paper,left=2cm,right=2cm,bottom=2cm,top=2cm,headsep=1.5cm}\n")
.append("\n")
.append("\\makeatletter\n")
.append(" \\newenvironment{indentation}[3]%\n")
.append(" {\\par\\setlength{\\parindent}{#3}\n")
.append(" \\setlength{\\leftmargin}{#1} \\setlength{\\rightmargin}{#2}%\n")
.append(" \\advance\\linewidth -\\leftmargin \\advance\\linewidth -\\rightmargin%\n")
.append(" \\advance\\@totalleftmargin\\leftmargin \\@setpar{{\\@@par}}%\n")
.append(" \\parshape 1\\@totalleftmargin \\linewidth\\ignorespaces}{\\par}%\n")
.append("\\makeatother \n")
.append("\n")
.append("% new LaTeX commands\n")
.append("\n")
.append("\n")
.append("\\begin{document}\n")
.append("\n")
.append("\\begin{center}\n")
.append("\\textbf{\\large R\\ E\\ L\\ A\\ T\\ Ó\\ R\\ I\\ O\\ \\ \\ S\\ I\\ G\\ M\\ A}\n")
.append("\\end{center}\n")
.append("\\begin{flushleft}\n")
.append("\\line(1,0){485}\\\\\n")
.append("Data de Emissão: ").append(A).append("\\\\\n")
.append("Tipo de Relatório: ").append(t).append("\\\\\n")
.append("\\line(1,0){485}\\\\\n")
.append("\\end{flushleft}\n")
.append("\n")
.append("\\begin{center}\n")
.append("\\textbf{Receitas}\n")
.append("\\end{center}\n")
.append("\n")
.append("\\begin{table}[h]\n")
.append(" \\begin{tabularx}{\\textwidth}{l l l l}\n")
.append(" Data\\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ & Situação\\ \\ \\ \\ \\ \\ \\ \\ \\ \\ & Observacoes\\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ & Valor \\\\\n")
.append(" \\hline\n")
.append(" 04/01/2016 & Quitado & Conserto X & 485 \\\\\n")//Aqui vai comecar o agrupamento
.append(" 06/01/2016 & Quitado & exemplo de texto & 125 \\\\\n")
.append(" 07/01/2016 & Não Quitado & freio de charrete & 387 \\\\\n")
.append(" 17/01/2016 & Quitado & Bolinho de aipim & 387 \\\\\n")
.append(" 23/01/2016 & Não Quitado & Batata & 56 \\\\\n")
.append(" & &\\textbf{Valor Total} & 1259\n")
.append(" \\end{tabularx}\n")
.append("\\end{table}\n")
.append("\n")
.append("\\begin{center}\n")
.append("\\textbf{Despesas}\n")
.append("\\end{center}\n")
.append("\n")
.append("\\end{document}");
writer.println(QUERY.toString());
writer.close(); //Close já dá writer.flush(); mas em alguns casos pode ser recomendado fazer separado.
//Finalização de criação de comandos
QUERY.setLength(0);
/**
* 14/05 - Maycon
* Chama o compilador de Latex (Nada bonito, mas funciona que é uma belezura)
*/
final File bat = new File("LatexCompiler.bat");
try {
Desktop dt = Desktop.getDesktop();
dt.open(bat);
} catch (Exception e) {
return false;
} //Finalização de execução de arquivo
return true;
}
}
|
package pack1;
public class Example13 extends Example11{
int c=30;
int d=40;
public static void m3(){
Example13 ex3=new Example13();
Example11 ex1=new Example11();
System.out.println(ex3.c+ex3.d+ex1.a+ex1.b);
}
}
|
package com.jim.multipos.ui.mainpospage.dialogs;
import android.app.Dialog;
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.View;
import android.view.Window;
import android.widget.TextView;
import com.jim.mpviews.MpButton;
import com.jim.mpviews.MpEditText;
import com.jim.mpviews.MpSwitcher;
import com.jim.multipos.R;
import com.jim.multipos.data.DatabaseManager;
import com.jim.multipos.data.db.model.Discount;
import com.jim.multipos.utils.TextWatcherOnTextChange;
import com.jim.multipos.utils.UIUtils;
import java.text.DecimalFormat;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by Portable-Acer on 09.11.2017.
*/
public class AddDiscountDialog extends Dialog {
@BindView(R.id.btnCancel)
MpButton btnCancel;
@BindView(R.id.btnNext)
MpButton btnOk;
@BindView(R.id.swDiscountType)
MpSwitcher swDiscountType;
@BindView(R.id.tvPrice)
TextView tvPrice;
@BindView(R.id.tvType)
TextView tvType;
@BindView(R.id.etDiscountAmount)
MpEditText etDiscountAmount;
@BindView(R.id.etResultPrice)
MpEditText etResultPrice;
@BindView(R.id.etDiscountName)
MpEditText etDiscountName;
@BindView(R.id.tvDiscountAmountType)
TextView tvDiscountAmountType;
private int discountAmountType;
private int discountType;
private DiscountDialog.CallbackDiscountDialog callbackDiscountDialog;
private double resultPrice = 0;
private double discountValue = 0;
public AddDiscountDialog(@NonNull Context context, DatabaseManager databaseManager, double price, int discountType, DiscountDialog.CallbackDiscountDialog callbackDiscountDialog, DecimalFormat formatter) {
super(context);
this.discountType = discountType;
this.callbackDiscountDialog = callbackDiscountDialog;
View dialogView = getLayoutInflater().inflate(R.layout.discount_manual_dialog, null);
ButterKnife.bind(this, dialogView);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(dialogView);
View v = getWindow().getDecorView();
v.setBackgroundResource(android.R.color.transparent);
tvPrice.setText(formatter.format(price));
String abbr = databaseManager.getMainCurrency().getAbbr();
if (swDiscountType.isLeft()) {
discountAmountType = Discount.VALUE;
tvType.setText(abbr);
} else {
discountAmountType = Discount.PERCENT;
tvType.setText("%");
}
swDiscountType.setSwitcherStateChangedListener((isRight, isLeft) -> {
if (isLeft) {
discountAmountType = Discount.VALUE;
tvType.setText(abbr);
tvDiscountAmountType.setText(context.getString(R.string.discount_amount));
if (!etResultPrice.getText().toString().isEmpty() && !etDiscountAmount.getText().toString().isEmpty()) {
discountValue = price - resultPrice;
etResultPrice.requestFocus();
etDiscountAmount.setText(formatter.format(discountValue));
}
} else {
discountAmountType = Discount.PERCENT;
tvType.setText("%");
tvDiscountAmountType.setText(context.getString(R.string.discount_percent));
if (!etResultPrice.getText().toString().isEmpty() && !etDiscountAmount.getText().toString().isEmpty()) {
discountValue = 100 - (100 * resultPrice / price);
etResultPrice.requestFocus();
etDiscountAmount.setText(formatter.format(discountValue));
if (discountValue > 100)
etDiscountAmount.setError(context.getString(R.string.discount_percent_cannot_be_bigger_hundred));
}
}
});
etDiscountAmount.addTextChangedListener(new TextWatcherOnTextChange() {
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (getCurrentFocus() == etDiscountAmount)
if (charSequence.length() != 0) {
try {
discountValue = formatter.parse(etDiscountAmount.getText().toString()).doubleValue();
double result = 0;
if (discountAmountType == Discount.VALUE) {
if (discountValue > price) {
etDiscountAmount.setError(context.getString(R.string.discount_value_cant_be_bigger_than_price));
} else {
result = price - discountValue;
resultPrice = result;
etResultPrice.setText(formatter.format(result));
}
} else {
if (discountValue > 100) {
etDiscountAmount.setError(context.getString(R.string.discount_percent_cannot_be_bigger_hundred));
} else {
result = price - (price * discountValue / 100);
resultPrice = result;
etResultPrice.setText(formatter.format(result));
}
}
} catch (Exception e) {
etDiscountAmount.setError(context.getString(R.string.invalid));
}
} else {
etResultPrice.setText(formatter.format(0));
}
}
});
etResultPrice.addTextChangedListener(new TextWatcherOnTextChange() {
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (getCurrentFocus() == etResultPrice)
if (charSequence.length() != 0) {
try {
resultPrice = formatter.parse(etResultPrice.getText().toString()).doubleValue();
if (resultPrice <= price) {
double result = 0;
if (discountAmountType == Discount.VALUE)
result = price - resultPrice;
else {
result = 100 - (100 * resultPrice / price);
}
etDiscountAmount.setText(formatter.format(result));
} else
etResultPrice.setError(context.getString(R.string.result_price_cant_be_bigger));
} catch (Exception e) {
etResultPrice.setError(context.getString(R.string.invalid));
}
} else etDiscountAmount.setText(formatter.format(0));
}
});
btnOk.setOnClickListener(view -> {
if (etDiscountAmount.getText().toString().isEmpty()) {
etDiscountAmount.setError(context.getString(R.string.enter_amount));
} else if (etResultPrice.getText().toString().isEmpty()) {
etResultPrice.setError(context.getString(R.string.enter_amount));
} else if (etDiscountName.getText().toString().isEmpty()) {
etDiscountName.setError(context.getString(R.string.disc_reacon_cant_empty));
} else if (resultPrice > price) {
etResultPrice.setError(context.getString(R.string.result_price_cant_be_bigger));
} else if (discountValue > price){
etDiscountAmount.setError("Discount value cannot be bigger than price");
} else {
new android.os.Handler().postDelayed(() -> {
Discount discount = new Discount();
discount.setIsManual(true);
discount.setAmount(discountValue);
discount.setCreatedDate(System.currentTimeMillis());
discount.setName(etDiscountName.getText().toString());
discount.setAmountType(discountAmountType);
discount.setUsedType(discountType);
this.callbackDiscountDialog.choiseManualDiscount(discount);
dismiss();
}, 300);
UIUtils.closeKeyboard(etDiscountName, getContext());
}
});
btnCancel.setOnClickListener(view ->
dismiss());
}
}
|
package tk.mybatis.simple.provider;
import org.apache.ibatis.jdbc.SQL;
import tk.mybatis.simple.model.SysPrivilege;
/**
* 权限Mapper对应的Provider实现
*/
public class PrivilegeProvider {
public String selectById(final Long id){
return new SQL(){
{
SELECT("id, privilege_name, privilege_url");
FROM("sys_privilege");
WHERE("id = #{id}");
}
}.toString();
}
public String selectByPrivilege(final SysPrivilege privilege){
return new SQL(){
{
SELECT("id, privilege_name, privilege_url");
FROM("sys_privilege");
//参数不为空的时候才能使用这些条件进行查询,参数 null 时查询所有
if(privilege != null){
if(privilege.getId() != null){
WHERE("id = #{id}");
}
if(privilege.getPrivilegeName() != null && privilege.getPrivilegeName().length() > 0){
//注意 MySql 中的 concat 函数
WHERE("privilege_name like concat('%',#{privilegeName},'%')");
}
if(privilege.getPrivilegeUrl() != null && privilege.getPrivilegeUrl().length() > 0){
//这里为了举例,直接拼接的字符串
WHERE("privilege_url like '%" +privilege.getPrivilegeUrl()+ "%'");
}
}
}
}.toString();
}
public String selectAll(){
return "select * from sys_privilege";
}
public String insert(final SysPrivilege sysPrivilege){
return new SQL(){
{
INSERT_INTO("sys_privilege");
VALUES("privilege_name", "#{privilegeName}");
VALUES("privilege_url", "#{privilegeUrl}");
}
}.toString();
}
public String updateById(final SysPrivilege sysPrivilege){
return new SQL(){
{
UPDATE("sys_privilege");
SET("privilege_name = #{privilegeName}");
SET("privilege_url = #{privilegeUrl}");
WHERE("id = #{id}");
}
}.toString();
}
public String deleteById(final Long id){
return new SQL(){
{
DELETE_FROM("sys_privilege");
WHERE("id = #{id}");
}
}.toString();
}
}
|
package com.e6soft.form.dao;
import com.e6soft.core.mybatis.EntityDao;
import com.e6soft.form.model.BusinessFormType;
public interface BusinessFormTypeDao extends EntityDao<BusinessFormType,String> {
}
|
package br.com.nozinho.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "contato_endereco")
public class ContatoEndereco extends Entidade{
/**
*
*/
private static final long serialVersionUID = -8053381221856809691L;
@Id
@Column(name = "idcontato_endereco")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "idcontato")
private Contato contato;
@ManyToOne
@JoinColumn(name = "idcidade")
private Cidade cidade;
@Column
private String endereco;
@Column
private String numero;
@Column
private String complemento;
@Column
private String bairro;
@Column(length = 8)
private String cep;
@Column(name = "tipo_contato_endereco")
@Enumerated(EnumType.ORDINAL)
private TipoEnderecoEnum tipoEndereco;
public Contato getContato() {
return contato;
}
public void setContato(Contato contato) {
this.contato = contato;
}
public Cidade getCidade() {
return cidade;
}
public void setCidade(Cidade cidade) {
this.cidade = cidade;
}
public String getEndereco() {
return endereco;
}
public void setEndereco(String endereco) {
this.endereco = endereco;
}
public String getNumero() {
return numero;
}
public void setNumero(String numero) {
this.numero = numero;
}
public String getComplemento() {
return complemento;
}
public void setComplemento(String complemento) {
this.complemento = complemento;
}
public String getBairro() {
return bairro;
}
public void setBairro(String bairro) {
this.bairro = bairro;
}
public String getCep() {
return cep;
}
public void setCep(String cep) {
this.cep = cep;
}
@Override
public Serializable getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public TipoEnderecoEnum getTipoEndereco() {
return tipoEndereco;
}
public void setTipoEndereco(TipoEnderecoEnum tipoEndereco) {
this.tipoEndereco = tipoEndereco;
}
}
|
package com.github.emailtohl.integration.web.service.cms;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import com.github.emailtohl.integration.web.service.cms.entities.Article;
/**
* 文章实体的数据访问接口
* @author HeLei
*/
interface ArticleRepository extends JpaRepository<Article, Long>, ArticleRepositoryCustomization {
Page<Article> findByTypeName(String typeName, Pageable pageable);
}
|
package com.tencent.mm.plugin.wallet_payu.create.ui;
import android.os.Bundle;
import com.tencent.mm.plugin.remittance.ui.RemittanceF2fDynamicCodeUI;
import com.tencent.mm.ui.base.a;
@a(3)
public class WalletPayUVerifyCodeUI extends RemittanceF2fDynamicCodeUI {
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
}
}
|
/*
* UniTime 3.5 (University Timetabling Application)
* Copyright (C) 2014, UniTime LLC, and individual contributors
* as indicated by the @authors tag.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.unitime.timetable.server.hql;
import java.io.IOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.unitime.localization.impl.Localization;
import org.unitime.timetable.export.Exporter.Printer;
import org.unitime.timetable.export.hql.SavedHqlExportToCSV;
import org.unitime.timetable.gwt.command.client.GwtRpcException;
import org.unitime.timetable.gwt.command.server.GwtRpcImplementation;
import org.unitime.timetable.gwt.command.server.GwtRpcImplements;
import org.unitime.timetable.gwt.resources.GwtMessages;
import org.unitime.timetable.gwt.shared.PageAccessException;
import org.unitime.timetable.gwt.shared.SavedHQLInterface.HQLExecuteRpcRequest;
import org.unitime.timetable.gwt.shared.SavedHQLInterface.Table;
import org.unitime.timetable.security.SessionContext;
/**
* @author Tomas Muller
*/
@GwtRpcImplements(HQLExecuteRpcRequest.class)
public class HQLExecuteBackend implements GwtRpcImplementation<HQLExecuteRpcRequest, Table> {
protected static GwtMessages MESSAGES = Localization.create(GwtMessages.class);
@Autowired
private SessionContext sessionContext;
@Override
@PreAuthorize("checkPermission('HQLReports')")
public Table execute(HQLExecuteRpcRequest request, SessionContext context) {
try {
final Table ret = new Table();
Printer out = new Printer() {
@Override
public void printLine(String... fields) throws IOException {
ret.add(fields);
}
@Override
public void printHeader(String... fields) throws IOException {
ret.add(fields);
}
@Override
public void hideColumn(int col) {}
@Override
public String getContentType() { return null; }
@Override
public void flush() throws IOException {}
@Override
public void close() throws IOException {}
};
SavedHqlExportToCSV.execute(sessionContext.getUser(), out,
request.getQuery(),
request.getOptions(),
request.getFromRow(),
request.getMaxRows());
return ret;
} catch (PageAccessException e) {
throw e;
} catch (Exception e) {
throw new GwtRpcException(MESSAGES.failedExecution(e.getMessage() + (e.getCause() == null ? "" : " (" + e.getCause().getMessage() + ")")));
}
}
}
|
/*
* 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 model.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.Properties;
import java.util.Queue;
import java.util.ResourceBundle;
/**
*
* @author Sasha
*/
public class ConnectionPool {
/** queue of connections */
private Queue<Connection> connections;
/** max number of connections in the queue */
private int maxConnections;
/** maximum number of connetions by default */
private static final int MAX_CONNECTIONS_DEFAULT = 1;
/**
* Constructor
*/
public ConnectionPool() {
connections = new LinkedList<>();
maxConnections = MAX_CONNECTIONS_DEFAULT;
}
/**
* Get max nubmer of connections
* @return int max number of connections
*/
public synchronized int getMaxConnections() {
return maxConnections;
}
/**
* Set maxium number of connections in the queue
* @param maxConnections
*/
public synchronized void setMaxConnection(int maxConnections) {
this.maxConnections = maxConnections;
}
/**
* Get free connection if exists or create new connection
* @return
* @throws SQLException
* @throws ServerOverloadedException
*/
public synchronized WrapperConnectionProxy getConnection() throws SQLException, ServerOverloadedException {
Connection freeConnection;
if (connections.size() > 0) {
freeConnection = connections.poll();
} else if (connections.size() < maxConnections) {
Properties prop = new Properties();
ResourceBundle bundle = ResourceBundle.getBundle("model/dao/restaurantprop");
String url = bundle.getString("db.url");
String login = bundle.getString("db.login");
String pass = bundle.getString("db.password");
prop.put("user", login);
prop.put("password", pass);
prop.put("autoReconnect", "true");
prop.put("characterEncoding", "UTF-8");
prop.put("useUnicode", "true");
freeConnection = DriverManager.getConnection(url, prop);
} else {
throw new ServerOverloadedException();
}
return new WrapperConnectionProxy(freeConnection, this);
}
/**
* Return connection to the queue (pool)
* @param connection connection is returned
*/
public synchronized void putConnection(Connection connection) {
if (connection != null) {
if (connections.size() < maxConnections) {
connections.add(connection);
} else {
try {
connection.close();
}catch (SQLException e) {
System.out.println("connection was not be closed!!! " + e.getMessage());
}
}
}
}
}
|
package com.smxknife.servlet.springboot.demo01.filterchain;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
/**
* @author smxknife
* 2019-01-02
*/
public class MyFilterChain implements FilterChain {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException, ServletException {
System.out.println(this.getClass().getSimpleName() + " doFilter...");
}
}
|
package week_1.core.general.copy;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/*
* student 1 Student1 [id=111, name=John, course=Course1 [subject1=Physics, subject2=Chemistry, subject3=Biology]]
student 2 Student1 [id=111, name=John, course=Course1 [subject1=Physics, subject2=Chemistry, subject3=Biology]]
// changed ID and Subject
student 1 Student1 [id=111, name=John, course=Course1 [subject1=Physics, subject2=Chemistry, subject3=Biology]]
student 2 Student1 [id=222, name=John, course=Course1 [subject1=Physics, subject2=Chemistry, subject3=Maths]]
*
*/
public class deep_copy_sample_2 {
public static void main(String[] args) throws Exception {
Course2 science = new Course2("Physics", "Chemistry", "Biology");
Student2 student1 = new Student2(111, "John", science);
Student2 student2 = null;
student2 = (Student2) ObjectClonerUtil.deepCopy(student1);
System.out.println("student 1 " + student1);
System.out.println("student 2 " + student2);
student2.id = 222;
student2.course.subject3 = "Maths";
System.out.println("student 1 " + student1);
System.out.println("student 2 " + student2);
}
}
class Course2 implements Serializable {
private static final long serialVersionUID = -1156997019783635521L;
String subject1;
String subject2;
String subject3;
public Course2(String sub1, String sub2, String sub3) {
this.subject1 = sub1;
this.subject2 = sub2;
this.subject3 = sub3;
}
@Override
public String toString() {
return "Course1 [subject1=" + subject1 + ", subject2=" + subject2 + ", subject3=" + subject3 + "]";
}
}
class Student2 implements Serializable {
private static final long serialVersionUID = -8491434461894336733L;
int id;
String name;
Course2 course;
public Student2(int id, String name, Course2 course) {
this.id = id;
this.name = name;
this.course = course;
}
@Override
public String toString() {
return "Student1 [id=" + id + ", name=" + name + ", course=" + course + "]";
}
}
class ObjectClonerUtil {
static public Object deepCopy(Object oldObj) throws Exception {
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream(); // A
oos = new ObjectOutputStream(bos); // B
oos.writeObject(oldObj); // C
oos.flush(); // D
ByteArrayInputStream bin = new ByteArrayInputStream(bos.toByteArray()); // E
ois = new ObjectInputStream(bin); // F
return ois.readObject(); // G
} catch (Exception e) {
System.out.println("Exception in ObjectCloner = " + e);
throw (e);
} finally {
oos.close();
ois.close();
}
}
}
|
package com.accp.pub.pojo;
public class Functionandrole {
private Integer roleid;
private String rolename;
private Integer functionid;
private String functionname;
private String bz;
private String bz1;
private String bz2;
private String bz3;
public Integer getRoleid() {
return roleid;
}
public void setRoleid(Integer roleid) {
this.roleid = roleid;
}
public String getRolename() {
return rolename;
}
public void setRolename(String rolename) {
this.rolename = rolename == null ? null : rolename.trim();
}
public Integer getFunctionid() {
return functionid;
}
public void setFunctionid(Integer functionid) {
this.functionid = functionid;
}
public String getFunctionname() {
return functionname;
}
public void setFunctionname(String functionname) {
this.functionname = functionname == null ? null : functionname.trim();
}
public String getBz() {
return bz;
}
public void setBz(String bz) {
this.bz = bz == null ? null : bz.trim();
}
public String getBz1() {
return bz1;
}
public void setBz1(String bz1) {
this.bz1 = bz1 == null ? null : bz1.trim();
}
public String getBz2() {
return bz2;
}
public void setBz2(String bz2) {
this.bz2 = bz2 == null ? null : bz2.trim();
}
public String getBz3() {
return bz3;
}
public void setBz3(String bz3) {
this.bz3 = bz3 == null ? null : bz3.trim();
}
} |
package com.bfchengnuo.security.app;
import com.bfchengnuo.security.core.social.SocialConfig;
import com.bfchengnuo.security.core.social.support.CustomizeSpringSocialConfigurer;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
/**
* 后处理器,适配 App 无 Session 下自动完成绑定
* 实现 {@link BeanPostProcessor} 接口到作用是,在 Spring 初始化所有 bean 之前和之后会调用我们自定义到方法逻辑
*
* @see com.bfchengnuo.security.app.social.AppSingUpUtils
* @see SocialConfig#springSocialSecurityConfig()
*
* @author 冰封承諾Andy
* @date 2019-11-16
*/
@Component
public class SpringSocialConfigurerPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (StringUtils.equals(beanName, "springSocialSecurityConfig")) {
CustomizeSpringSocialConfigurer configurer = (CustomizeSpringSocialConfigurer) bean;
// 改变跳转到 URL
configurer.signupUrl("/social/signUp");
return configurer;
}
return bean;
}
}
|
package ArraySample;
public class ArrayLengthExample {
public static void main(String[] args) {
int[] scores = {83, 90, 87};
int sum =0;
for(int i=0; i<scores.length; i++) {
sum += scores[i];
}
System.out.println("총합: "+sum);
double avg = (double)sum / scores.length;
System.out.println("평균: "+avg);
//합계구하는 부분을 메소드로 대체하여 구현해보세요.
System.out.println("\n=== Method Implementation ===");
Sum(scores);
}
private static void Sum(int[] scores) {
int i;
int sum=0;
for(i=0; i<scores.length; i++) {
sum+=scores[i];
}
System.out.println("합계는: "+sum);
}
//1차원 배열에 1~10까지의 데이터를 저장하고,그 중에서 짝수의 데이터의 합을 구하세요.
}
|
package com.withertech.overtokapi;
import com.withertech.overtokapi.resource.OvertokServices;
import org.apache.catalina.Context;
import org.apache.catalina.startup.Tomcat;
import org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher;
import org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap;
public class Launcher {
private static final String RESTEASY_SERVLET_NAME = "resteasy-servlet";
public static void main(String[] args) throws Exception {
new Launcher().start();
}
void start() throws Exception {
String port = System.getenv("PORT");
if (port == null || port.isEmpty()) {
port = "9090";
}
String contextPath = "/api";
String appBase = ".";
Tomcat tomcat = new Tomcat();
tomcat.setPort(Integer.valueOf(port));
tomcat.getHost().setAppBase(appBase);
Context context = tomcat.addContext(contextPath, appBase);
context.addApplicationListener(ResteasyBootstrap.class.getName());
Tomcat.addServlet(context, RESTEASY_SERVLET_NAME, new HttpServletDispatcher());
context.addParameter("javax.ws.rs.Application", OvertokServices.class.getName());
context.addServletMapping("/*", RESTEASY_SERVLET_NAME);
tomcat.start();
tomcat.getServer().await();
}
} |
package com.tencent.mm.plugin.fts.ui.d;
import android.content.Context;
import com.tencent.mm.kernel.g;
import com.tencent.mm.plugin.fts.a.a.i;
import com.tencent.mm.plugin.fts.a.a.j;
import com.tencent.mm.plugin.fts.a.a.l;
import com.tencent.mm.plugin.fts.a.d.e;
import com.tencent.mm.plugin.fts.a.d.e.b;
import com.tencent.mm.plugin.fts.a.n;
import com.tencent.mm.plugin.fts.ui.a;
import com.tencent.mm.plugin.fts.ui.a.h;
import com.tencent.mm.plugin.fts.ui.a.q;
import com.tencent.mm.sdk.platformtools.ag;
import java.util.HashSet;
public final class c extends a {
public c(Context context, b bVar, int i) {
super(context, bVar, i);
}
protected final com.tencent.mm.plugin.fts.a.a.a a(ag agVar, HashSet<String> hashSet) {
i iVar = new i();
iVar.jsn = 96;
iVar.jss = 3;
iVar.bWm = this.bWm;
iVar.jst = hashSet;
iVar.jsu = com.tencent.mm.plugin.fts.a.c.a.jsT;
iVar.jsv = this;
iVar.handler = agVar;
return ((n) g.n(n.class)).search(2, iVar);
}
protected final void a(j jVar, HashSet<String> hashSet) {
if (bk(jVar.jsx)) {
e.a aVar = new e.a();
aVar.jte = jVar.jsx;
aVar.iPZ = -3;
aVar.jrx = jVar.jrx;
if (aVar.jte.size() > 3) {
if (((l) aVar.jte.get(3)).jrv.equals("create_chatroom")) {
boolean z;
if (aVar.jte.size() > 4) {
z = true;
} else {
z = false;
}
aVar.jtd = z;
aVar.jte = aVar.jte.subList(0, 4);
} else {
aVar.jtd = true;
aVar.jte = aVar.jte.subList(0, 3);
}
}
this.jvp.add(aVar);
}
}
protected final com.tencent.mm.plugin.fts.a.d.a.a a(int i, e.a aVar) {
com.tencent.mm.plugin.fts.a.d.a.a hVar;
int i2 = (i - aVar.jta) - 1;
if (i2 < aVar.jte.size() && i2 >= 0) {
l lVar = (l) aVar.jte.get(i2);
if (lVar.jrv.equals("create_chatroom")) {
hVar = new h(i);
hVar.jrx = aVar.jrx;
} else if (lVar.type == 131075) {
com.tencent.mm.plugin.fts.a.d.a.a a = a(131075, i, lVar, aVar);
a.cF(lVar.type, lVar.jru);
hVar = a;
}
if (hVar != null) {
hVar.jtm = i2 + 1;
}
return hVar;
}
hVar = null;
if (hVar != null) {
hVar.jtm = i2 + 1;
}
return hVar;
}
public final int getType() {
return 48;
}
public final com.tencent.mm.plugin.fts.a.d.a.a a(int i, int i2, l lVar, e.a aVar) {
com.tencent.mm.plugin.fts.a.d.a.a qVar = new q(i2);
qVar.fyJ = lVar;
qVar.jrx = aVar.jrx;
qVar.cF(lVar.type, lVar.jru);
return qVar;
}
}
|
package com.ibiscus.myster.model.survey.item;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.OneToMany;
@Entity(name = "SingleChoice")
@DiscriminatorValue("SINGLE_CHOICE")
public class SingleChoice extends AbstractSurveyItem {
@OneToMany(mappedBy = "surveyItemId", fetch = FetchType.EAGER, orphanRemoval = true)
private List<Choice> choices;
SingleChoice() {
super();
}
public SingleChoice(long id, long categoryId, int position, String title, String description, List<Choice> choices) {
super(id, categoryId, position, title, description);
this.choices = new ArrayList<Choice>(choices);
}
public List<Choice> getChoices() {
return choices;
}
public Choice getChoiceByValue(Integer value) {
return choices.stream().filter(c -> c.getValue().equals(value)).findFirst().get();
}
}
|
package jc.sugar.JiaHui.jmeter.configtestelement;
import jc.sugar.JiaHui.jmeter.*;
import org.apache.jmeter.protocol.http.control.Cookie;
import org.apache.jmeter.protocol.http.control.CookieManager;
import org.apache.jmeter.testelement.property.JMeterProperty;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.apache.jorphan.util.Converter.*;
@JMeterElementMapperFor(value = JMeterElementType.CookieManager, testGuiClass = JMeterElement.CookieManager)
public class CookieManagerMapper extends AbstractJMeterElementMapper<CookieManager> {
public static final String WEB_CLEAR_EACH_ITERATION = "clearEachIteration";
public static final String WEB_CONTROLLED_BY_THREAD = "controlledByThreadGroup";
public static final String WEB_POLICY = "policy";
public static final String WEB_COOKIES = "cookies";
public static final String WEB_COOKIE_NAME = "name";
public static final String WEB_COOKIE_VALUE = "value";
public static final String WEB_COOKIE_DOMAIN = "domain";
public static final String WEB_COOKIE_PATH = "path";
public static final String WEB_COOKIE_SECURE = "secure";
public static final String WEB_COOKIE_EXPIRES = "expires";
public static final String WEB_COOKIE_PATH_SPECIFIED = "pathSpecified";
public static final String WEB_COOKIE_DOMAIN_SPECIFIED = "domainSpecified";
private CookieManagerMapper(CookieManager element, Map<String, Object> attributes) {
super(element, attributes);
}
public CookieManagerMapper(Map<String, Object> attributes){
this(new CookieManager(), attributes);
}
public CookieManagerMapper(CookieManager element){
this(element, new HashMap<>());
}
@Override
public CookieManager fromAttributes() {
element.setClearEachIteration(getBoolean(attributes.get(WEB_CLEAR_EACH_ITERATION)));
element.setControlledByThread(getBoolean(attributes.get(WEB_CONTROLLED_BY_THREAD)));
element.setCookiePolicy(getString(attributes.get(WEB_POLICY)));
List<Map<String, Object>> cookieAttributesList = (List<Map<String, Object>>) attributes.get(WEB_COOKIES);
for(Map<String, Object> cookieAttributes: cookieAttributesList){
Cookie cookie = new Cookie(
getString(cookieAttributes.get(WEB_COOKIE_NAME)),
getString(cookieAttributes.get(WEB_COOKIE_VALUE)),
getString(cookieAttributes.get(WEB_COOKIE_DOMAIN)),
getString(cookieAttributes.get(WEB_COOKIE_PATH)),
getBoolean(cookieAttributes.get(WEB_COOKIE_SECURE)),
getLong(cookieAttributes.get(WEB_COOKIE_EXPIRES)),
getBoolean(cookieAttributes.get(WEB_COOKIE_PATH_SPECIFIED)),
getBoolean(cookieAttributes.get(WEB_COOKIE_DOMAIN_SPECIFIED))
);
element.add(cookie);
}
return element;
}
@Override
public Map<String, Object> toAttributes() {
attributes.put(WEB_CATEGORY, JMeterElementCategory.ConfigElement);
attributes.put(WEB_TYPE, JMeterElementType.CookieManager);
attributes.put(WEB_CLEAR_EACH_ITERATION, element.getClearEachIteration());
attributes.put(WEB_CONTROLLED_BY_THREAD, element.getControlledByThread());
attributes.put(WEB_POLICY, element.getPolicy());
List<Map<String, Object>> cookies = new ArrayList<>();
for (JMeterProperty jMeterProperty : element.getCookies()) {
Map<String, Object> cookieAttributes = new HashMap<>();
Cookie cookie = (Cookie) jMeterProperty.getObjectValue();
cookieAttributes.put(WEB_ID, System.identityHashCode(cookie));
cookieAttributes.put(WEB_COOKIE_NAME, cookie.getName());
cookieAttributes.put(WEB_COOKIE_VALUE, cookie.getValue());
cookieAttributes.put(WEB_COOKIE_DOMAIN, cookie.getDomain());
cookieAttributes.put(WEB_COOKIE_PATH, cookie.getPath());
cookieAttributes.put(WEB_COOKIE_EXPIRES, cookie.getExpires());
cookieAttributes.put(WEB_COOKIE_PATH_SPECIFIED, cookie.isPathSpecified());
cookieAttributes.put(WEB_COOKIE_DOMAIN_SPECIFIED, cookie.isDomainSpecified());
cookies.add(cookieAttributes);
}
attributes.put(WEB_COOKIES, cookies);
return attributes;
}
}
|
package com.mes.old.meta;
// Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final
/**
* KWip generated by hbm2java
*/
public class KWip implements java.io.Serializable {
private KWipId id;
public KWip() {
}
public KWip(KWipId id) {
this.id = id;
}
public KWipId getId() {
return this.id;
}
public void setId(KWipId id) {
this.id = id;
}
}
|
public class DrowShip1 extends DrowShip{
public DrowShip1(int[][] battleground) {
super(battleground, 1);
}
}
|
package com.alexkirillov.alitabot;
import com.alexkirillov.alitabot.services.scheduling.WeekManager;
import org.telegram.telegrambots.ApiContextInitializer;
import org.telegram.telegrambots.meta.TelegramBotsApi;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
public class Main {
public static void main(String[] x){
ApiContextInitializer.init();
TelegramBotsApi telegramBotsApi = new TelegramBotsApi();
try{
AlitaBot bot = new AlitaBot();
telegramBotsApi.registerBot(bot);
//initialize daily update function
bot.week_manager.weekUpdate();
} catch (TelegramApiException e) {
e.printStackTrace();
}
System.out.println("Bot Started");
}
}
|
package com.goldgov.dygl.module.pmuserinfo.web;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import com.goldgov.dygl.module.partymember.service.PartyMemberQuery;
import com.goldgov.dygl.module.pmuserinfo.service.IPmUserAwardInfoService;
import com.goldgov.dygl.module.pmuserinfo.service.IPmUserPunishInfoService;
import com.goldgov.dygl.module.pmuserinfo.service.PmUserAwardInfo;
import com.goldgov.dygl.module.pmuserinfo.service.PmUserPunishInfo;
import com.goldgov.gtiles.core.web.GoTo;
import com.goldgov.gtiles.core.web.annotation.ModelQuery;
import com.goldgov.gtiles.core.web.validator.Valid;
@RequestMapping("/module/pmuserpunishinfo")
@Controller("pmUserPunishInfo")
public class PmUserPunishInfoController {
public static final String PAGE_BASE_PATH = "pmuserinfo/web/pages/";
@Autowired
@Qualifier("pmUserPunishInfoService")
private IPmUserPunishInfoService pmUserPunishInfoService;
@Autowired
@Qualifier("pmUserAwardInfoService")
private IPmUserAwardInfoService pmUserAwardInfoService;
@InitBinder
private void initBinder(WebDataBinder binder){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
@SuppressWarnings("unchecked")
@RequestMapping("/preAdd")
public String preAdd(@ModelQuery("query") PartyMemberQuery partyMemberQuery,String id,Model model,HttpServletRequest request) throws Exception{
if(partyMemberQuery.getPartyMemberID()!=null && !"".equals(partyMemberQuery.getPartyMemberID())){
String userID = pmUserAwardInfoService.getLoginIdByAaid(partyMemberQuery.getPartyMemberID());
partyMemberQuery.setUserID(userID);
}
PmUserPunishInfo info;
if(id!=null && !"".equals(id)){
info = pmUserPunishInfoService.findInfoById(id);
}else{
info = new PmUserPunishInfo();
//info.setAwardApplyTime(new Date());
info.setLoginId(partyMemberQuery.getUserID());
}
model.addAttribute("info", info);
List<PmUserPunishInfo> resultList = pmUserPunishInfoService.findInfoList(partyMemberQuery);
partyMemberQuery.setResultList(resultList);
return new GoTo(this).sendPage("PmUserPunishInfoList.ftl");
}
@RequestMapping("/addInfo")
public String addInfo(@Valid(throwException=true) @ModelAttribute("info") PmUserPunishInfo info,@ModelQuery("query") PartyMemberQuery partyMemberQuery,Model model,HttpServletRequest request) throws Exception{
pmUserPunishInfoService.addInfo(info);
return new GoTo(this).sendForward("preAdd?userID="+info.getLoginId());
}
@RequestMapping("/findInfo")
public String findInfo(@ModelQuery("query") PartyMemberQuery partyMemberQuery,Model model,String id,HttpServletRequest request) throws Exception{
PmUserPunishInfo info = pmUserPunishInfoService.findInfoById(id);
model.addAttribute("info", info);
return new GoTo(this).sendPage("PmUserPunishInfoView.ftl");
}
@RequestMapping("/updateInfo")
public String updateInfo(@Valid(throwException=true) @ModelAttribute("ciBean") PmUserPunishInfo info,Model model,HttpServletRequest request) throws Exception{
pmUserPunishInfoService.updateInfo(info);
return new GoTo(this).sendForward("preAdd?userID="+info.getLoginId());
}
@RequestMapping("/deleteInfo")
public String deleteBusinessTable(String ids,HttpServletRequest request) throws Exception{
if(ids!=null&&!ids.equals("")){
pmUserPunishInfoService.deleteInfo(ids.split(","));
}
return new GoTo(this).sendForward("preAdd");
}
}
|
package chapter10.Exercise10_01;
public class TestTime {
public static void main(String[] args) {
Time t1 = new Time();
Time t2 = new Time(555550000);
printTime(t1);
System.out.println("--------");
printTime(t2);
}
public static void printTime(Time t) {
System.out.print(t.getHour() + ":");
System.out.print(t.getMinute() + ":");
System.out.print(t.getSecond() + "\n");
}
}
|
package ex36;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import static org.junit.jupiter.api.Assertions.*;
class AppTest {
@Test
void average() {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(100);
list.add(200);
list.add(1000);
list.add(300);
assertEquals(400.0, App.average(list) );
}
@Test
void minimum() {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(100);
list.add(200);
list.add(1000);
list.add(300);
assertEquals(100, App.minimum(list) );
}
@Test
void maximum() {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(100);
list.add(200);
list.add(1000);
list.add(300);
assertEquals(1000, App.maximum(list) );
}
@Test
void stdDev() {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(100);
list.add(200);
list.add(1000);
list.add(300);
assertEquals(353.55, Math.round(App.stdDev(list) * 100) / 100.0);
}
} |
package com.yinghai.a24divine_user.module.divine.divinelist.model;
import com.example.fansonlib.base.BaseModel;
import com.example.fansonlib.http.HttpResponseCallback;
import com.example.fansonlib.http.HttpUtils;
import com.example.fansonlib.utils.SharePreferenceHelper;
import com.yinghai.a24divine_user.bean.BusinessTypeListBean;
import com.yinghai.a24divine_user.constant.ConHttp;
import com.yinghai.a24divine_user.constant.ConResultCode;
import com.yinghai.a24divine_user.constant.ConstantPreference;
import com.yinghai.a24divine_user.utils.ValidateAPITokenUtil;
import java.util.HashMap;
import java.util.Map;
/**
* @author Created by:fanson
* Created Time: 2017/12/28 14:13
* Describe:获取类型的M层
*/
public class GetBusinessTypeModel extends BaseModel implements ContractBusinessType.IModel{
private ITypeCallback mCallback;
@Override
public void onGetBusinessType(ITypeCallback callback) {
mCallback = callback;
String time = String.valueOf(System.currentTimeMillis());
Map<String, Object> maps = new HashMap<>(5);
maps.put("userId", SharePreferenceHelper.getInt(ConstantPreference.I_USER_ID, -1));
maps.put("apiSendTime", time);
maps.put("apiToken", ValidateAPITokenUtil.ctreatTokenStringByTimeString(time));
HttpUtils.getHttpUtils().post(ConHttp.GET_BUSINESS_TYPE, maps, new HttpResponseCallback<BusinessTypeListBean>() {
@Override
public void onSuccess(BusinessTypeListBean bean) {
if (mCallback == null) {
return;
}
switch (bean.getCode()) {
case ConResultCode.SUCCESS:
mCallback.onGetBusinessTypeSuccess(bean.getData());
break;
default:
break;
}
}
@Override
public void onFailure(String errorMsg) {
if (mCallback != null) {
mCallback.onGetBusinessTypeFailure(errorMsg);
}
}
});
}
@Override
public void onDestroy() {
super.onDestroy();
mCallback = null;
}
}
|
/*!
* Copyright 2002 - 2017 Webdetails, a Pentaho company. All rights reserved.
*
* This software was developed by Webdetails and is provided under the terms
* of the Mozilla Public License, Version 2.0, or any later version. You may not use
* this file except in compliance with the license. If you need a copy of the license,
* please go to http://mozilla.org/MPL/2.0/. The Initial Developer is Webdetails.
*
* Software distributed under the Mozilla Public License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
* the license for the specific language governing your rights and limitations.
*/
package pt.webdetails.cdf.dd.model.inst.writer.cdfrunjs.properties;
import org.apache.commons.lang.StringUtils;
import pt.webdetails.cdf.dd.model.core.writer.ThingWriteException;
import pt.webdetails.cdf.dd.model.inst.PropertyBinding;
import pt.webdetails.cdf.dd.model.inst.writer.cdfrunjs.dashboard.CdfRunJsDashboardWriteContext;
public class CdfRunJsGenericPropertyBindingWriter extends CdfRunJsPropertyBindingWriter {
public void write( StringBuilder out, CdfRunJsDashboardWriteContext context, PropertyBinding propBind )
throws ThingWriteException {
String indent = context.getIndent();
String jsValue = writeValue( propBind );
if ( StringUtils.isNotEmpty( jsValue ) ) {
addJsProperty( out, propBind.getAlias(), jsValue, indent, context.isFirstInList() );
context.setIsFirstInList( false );
}
}
private String writeValue( PropertyBinding propBind ) {
String canonicalValue = propBind.getValue();
if ( StringUtils.isNotEmpty( canonicalValue ) ) {
switch ( propBind.getProperty().getValueType() ) {
case STRING: return this.writeString( canonicalValue );
case BOOLEAN: return this.writeBoolean( canonicalValue );
case NUMBER: return this.writeNumber( canonicalValue );
case ARRAY: return this.writeArray( canonicalValue );
case FUNCTION: return this.writeFunction( canonicalValue );
case LITERAL: return this.writeLiteral( canonicalValue );
case QUERY: return this.writeQuery( canonicalValue );
//case VOID:
}
}
return ""; // empty canonical or VOID
}
private String writeQuery( String canonicalValue ) {
throw new UnsupportedOperationException( "Feature implemented in DatasourceProperty Writer -- something went wrong!" );
}
}
|
package it.unica.pr2.pizza;
import java.util.*;
public class AbstractUser extends Admin{
public AbstractUser(){
}
}
|
package org.fuserleer.ledger.atoms;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.ThreadLocalRandom;
import org.bouncycastle.util.Arrays;
import org.fuserleer.BasicObject;
import org.fuserleer.crypto.Hash;
import org.fuserleer.crypto.Hash.Mode;
import org.fuserleer.common.Primitive;
import org.fuserleer.exceptions.ValidationException;
import org.fuserleer.ledger.StateInstruction;
import org.fuserleer.ledger.StateMachine;
import org.fuserleer.serialization.DsonOutput;
import org.fuserleer.serialization.Serialization;
import org.fuserleer.serialization.SerializerId2;
import org.fuserleer.serialization.DsonOutput.Output;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;
@SerializerId2("ledger.particle")
public abstract class Particle extends BasicObject implements Primitive, StateInstruction
{
public enum Spin
{
UP, DOWN, NEUTRAL, ANY;
@JsonValue
@Override
public String toString()
{
return this.name();
}
public static Hash spin(Hash hash, Spin spin)
{
byte[] hashBytes = Arrays.clone(hash.toByteArray());
if (spin.equals(Spin.DOWN) == true)
hashBytes[0] &= ~1;
else if (spin.equals(Spin.UP) == true)
hashBytes[0] |= 1;
return new Hash(hashBytes);
}
}
@JsonProperty("nonce")
@DsonOutput(value = {Output.ALL})
private long nonce;
@JsonProperty("spin")
@DsonOutput(value = {Output.API, Output.WIRE, Output.PERSIST})
private Spin spin;
protected Particle()
{
super();
}
protected Particle(Spin spin)
{
if (Objects.requireNonNull(spin).equals(Spin.NEUTRAL) == true)
throw new IllegalArgumentException("Spin NEUTRAL particles are implicit");
if (spin.equals(Spin.DOWN) == true && isConsumable() == false)
throw new IllegalArgumentException("Particle of type "+this.getClass()+" is not consumable");
this.spin = spin;
this.nonce = ThreadLocalRandom.current().nextLong();
}
@Override
protected Object clone() throws CloneNotSupportedException
{
return (Particle) super.clone();
}
@SuppressWarnings("unchecked")
public final <T extends Particle> T get(Spin spin)
{
if (Objects.requireNonNull(spin).equals(Spin.NEUTRAL) == true)
throw new IllegalArgumentException("Spin NEUTRAL particles are implicit");
try
{
T cloned = (T) this.clone();
((Particle)cloned).spin = spin;
return cloned;
}
catch (CloneNotSupportedException cnsex)
{
// Should never happen, throw a runtime instead.
throw new RuntimeException(cnsex);
}
}
public final Spin getSpin()
{
return this.spin;
}
public final Hash getHash(Spin spin)
{
return computeHash(spin);
}
protected final synchronized Hash computeHash()
{
return computeHash(this.spin);
}
private Hash computeHash(Spin spin)
{
if (Objects.requireNonNull(spin).equals(Spin.NEUTRAL) == true)
throw new IllegalArgumentException("Spin NEUTRAL particles are implicit");
try
{
byte[] hashBytes = Serialization.getInstance().toDson(this, Output.HASH);
return Spin.spin(new Hash(hashBytes, Mode.DOUBLE), spin);
}
catch (Exception e)
{
throw new RuntimeException("Error generating hash: " + e, e);
}
}
@JsonProperty("consumable")
@DsonOutput(Output.API)
public abstract boolean isConsumable();
@JsonProperty("ephemeral")
@DsonOutput(Output.API)
public boolean isEphemeral()
{
return true;
}
public void prepare(StateMachine stateMachine) throws ValidationException, IOException
{
if (this.spin == null)
throw new ValidationException("Spin is null");
}
public abstract void execute(StateMachine stateMachine) throws ValidationException, IOException;
public String toString()
{
return super.toString()+" "+this.spin;
}
}
|
package com.project.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "evaluation")
public class Evaluation {
@Id
String id;
String nameOfEvaluator;
Score[] listOfScore;
public Evaluation() {
}
public Evaluation(String nameOfEvaluator,Score[] listOfScore) {
this.nameOfEvaluator=nameOfEvaluator;
this.listOfScore = listOfScore;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getNameOfEvaluator() {
return nameOfEvaluator;
}
public void setNameOfEvaluator(String nameOfEvaluator) {
this.nameOfEvaluator = nameOfEvaluator;
}
public Score[] getListOfScore() {
return listOfScore;
}
public void setListOfScore(Score[] listOfScore) {
this.listOfScore = listOfScore;
}
}
|
import org.apache.commons.lang3.StringEscapeUtils;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.http.HttpServlet;
@SuppressWarnings("serial")
public class SearchServlet extends HttpServlet {
// protected static Logger log = LogManager.getLogger();
public SearchServlet() {
}
protected static final DatabaseHandler dbhandler = DatabaseHandler.getInstance();
/**
*
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int matchingRecords = 0;
String searchString = request.getParameter("search");
searchString = searchString == null ? "" : searchString;
searchString = StringEscapeUtils.escapeHtml4(searchString);
sendTop(response);
if (!searchString.isEmpty()) {
String mode = request.getParameter("mode");
if (mode.equals("Search on Zipcode")) {
matchingRecords = sendSearchByStartup(response, dbhandler.searchByZipcode(searchString));
} else if (mode.equals("Search on Startup Name")) {
matchingRecords = sendSearchByStartup(response, dbhandler.searchByStartupName(searchString));
} else if (mode.equals("Search on an Individual")) {
String[] names = searchString.split(" ");
if (names.length == 2) {
matchingRecords = sendSearchByIndividual(response, dbhandler.searchByIndividual(names[0], names[1]));
}
} else if (mode.equals("Search on Investor Name")) {
matchingRecords = sendSearchByInvestor(response, dbhandler.searchByInvestor(searchString));
}
} else {
sendSearchByStartup(response, null);
}
sendMidsection(response);
sendSearchForm(request, response, matchingRecords);
sendBottom(response);
}
/**
*
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
// log.info("SearchServlet ID " + this.hashCode() + " handling POST request.");
String searchString = request.getParameter("search");
searchString = searchString == null ? "" : searchString;
searchString = StringEscapeUtils.escapeHtml4(searchString);
response.setStatus(HttpServletResponse.SC_OK);
response.sendRedirect(request.getServletPath());
}
/**
* Retrieves information from a status error message
*
* @param errorName - The name of the error received
* @return - A string containing the information from the error
*/
protected String getStatusMessage(String errorName) {
Status status = null;
try {
status = Status.valueOf(errorName);
} catch (Exception ex) {
// log.debug(errorName, ex);
status = Status.ERROR;
}
return status.toString();
}
/**
* Checks the status code and returns a status error if a problem is
* encountered.
*
* @param code - The code of the status message
* @return - A string containing the status associated with the given code
*/
protected String getStatusMessage(int code) {
Status status = null;
try {
status = Status.values()[code];
} catch (Exception ex) {
// log.debug(ex.getMessage(), ex);
status = Status.ERROR;
}
return status.toString();
}
/**
* Sends to the browser the top of our dynamically-generated web
* page.
*
* @param response - The HTTP response we are writing to
*/
protected void sendTop(HttpServletResponse response) {
try {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(" <!DOCTYPE html> ");
out.println(" <html lang=\"en\"> ");
out.println(" <head> ");
out.println(" <meta charset=\"utf-8\"> ");
out.println(" <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> ");
out.println(" <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> ");
out.println(
" <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> ");
out.println(" <title>San Francisco Startup Atlas</title> ");
out.println(" ");
out.println(" <!-- Bootstrap --> ");
out.println(" <link href=\"WWWRoot/bootstrap/css/bootstrap.min.css\" rel=\"stylesheet\"> ");
out.println(" ");
out.println(
" <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> ");
out.println(" <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> ");
out.println(" <!--[if lt IE 9]> ");
out.println(
" <script src=\"https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js\"></script> ");
out.println(" <script src=\"https://oss.maxcdn.com/respond/1.4.2/respond.min.js\"></script> ");
out.println(" <![endif]--> ");
out.println(" <!--Begin Google Maps Code--> ");
out.println(" <style> ");
out.println(" body, html { ");
out.println(" height: 100%; ");
out.println(" width: 100%; ");
out.println(" } ");
out.println(" ");
out.println(" #map-canvas { ");
out.println(" position:absolute; ");
out.println(" width: 100%; ");
out.println(" height: 100%; ");
out.println(" margin-top: 65px; ");
out.println(" padding: 0; ");
out.println(" } ");
out.println(" .overlap { ");
out.println(" position: relative ");
out.println(" } ");
out.println(" </style> ");
out.println(
" <script src=\"http://maps.googleapis.com/maps/api/js?key=AIzaSyB5qzrkKo4aZgEFddk4eJE1RFUa8DNvrPs\"></script> ");
out.println(" <script type=\"text/javascript\"> ");
out.println(" var map ");
out.println(" ");
out.println(" function initialize() { ");
out.println(" ");
out.println(" var mapCanvas = document.getElementById('map-canvas'); ");
out.println(" var googleMapOptions = ");
out.println(" { ");
out.println(" mapTypeControl: true, ");
out.println(" mapTypeControlOptions: { ");
out.println(" style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR, ");
out.println(" position: google.maps.ControlPosition.LEFT_CENTER ");
out.println(" }, ");
out.println(" center: new google.maps.LatLng(37.778083, -122.400195), ");
out.println(" zoom: 14, ");
out.println(" mapTypeId: google.maps.MapTypeId.ROADMAP ");
out.println(" }; ");
out.println(" map = new google.maps.Map(mapCanvas, googleMapOptions); ");
out.println(" ");
} catch (IOException ex) {
// log.warn("Unable to prepare HTTP response.");
return;
}
}
/**
* Sends to the browser the section of javascript where map markers are generated - this method
* is used specifically when searching by individual
*
* @param response
* @param person
* @return
*/
protected int sendSearchByIndividual(HttpServletResponse response, Person person) {
int matchingRecords = 0;
try {
PrintWriter out = response.getWriter();
// BEGIN - map initialization section where markers are added
if (person != null) {
out.println(" var infowindow = new google.maps.InfoWindow; ");
out.println(" var marker; ");
for (Person.Role role : person.getRoles()) {
for (Address address : role.getOrganization().getAddresses()) {
matchingRecords++;
out.println(" marker = new google.maps.Marker({ ");
out.printf(" position: new google.maps.LatLng(%f, %f), ", address.getLatitude(),
address.getLongitude());
out.println(" animation: google.maps.Animation.DROP, ");
out.println(" map: map ");
out.println(" }); ");
out.println(" ");
out.println(" google.maps.event.addListener(marker, 'click', (function(marker) { ");
out.println(" return function() {");
out.printf("infowindow.setContent('<h5>%s<br>" +
"<small>%s</small>" +
"<p><small>Industry Vertical: <b>%s</b><br>" +
"Date Founded: <b>%s</b></br>" +
"Funding Rounds: <b>%s</b></br>" +
"Total Funding: <b>%s</b></small></p>" +
"<h6>%s %s<br>" +
"<small>%s</small></h6>'); ",
role.getOrganization().getName(),
address.getStreetAddress(),
role.getOrganization().getVertical(),
role.getOrganization().getSince(),
role.getOrganization().getFundingRounds(),
role.getOrganization().getTotalFunding(),
person.getFirstName(), person.getLastName(),
role.getRole());
out.println(" infowindow.open(map, marker); ");
out.println(" } ");
out.println(" })(marker)); ");
}
}
}
// END - map initialization section where markers are added
} catch (IOException ex) {
// log.warn("Unable to prepare HTTP response.");
return 0;
}
return matchingRecords;
}
/**
* Sends to the browser the section of javascript where map markers are generated - this method
* is used specifically when searching by investor name
*
* @param response
* @param investor
* @return
*/
protected int sendSearchByInvestor(HttpServletResponse response, Investor investor) {
int matchingRecords = 0;
try {
PrintWriter out = response.getWriter();
// BEGIN - map initialization section where markers are added
if (investor != null) {
out.println(" var infowindow = new google.maps.InfoWindow; ");
out.println(" var marker; ");
for (Startup startup : investor.getInvestments()) {
for (Address address : startup.getAddresses()) {
matchingRecords++;
out.println(" marker = new google.maps.Marker({ ");
out.printf(" position: new google.maps.LatLng(%f, %f), ", address.getLatitude(),
address.getLongitude());
out.println(" animation: google.maps.Animation.DROP, ");
out.println(" map: map ");
out.println(" }); ");
out.println(" ");
out.println(" google.maps.event.addListener(marker, 'click', (function(marker) { ");
out.println(" return function() {");
out.printf("infowindow.setContent('<h5>%s<br>" +
"<small>%s</small>" +
"<p><small>Industry Vertical: <b>%s</b><br>" +
"Date Founded: <b>%s</b></br>" +
"Funding Rounds: <b>%s</b></br>" +
"Total Funding: <b>%s</b></small></p>" +
"<h6>%s</h6>'); ",
startup.getName(),
address.getStreetAddress(),
startup.getVertical(),
startup.getSince(),
startup.getFundingRounds(),
startup.getTotalFunding(),
investor.getName());
out.println(" infowindow.open(map, marker); ");
out.println(" } ");
out.println(" })(marker)); ");
}
}
}
// END - map initialization section where markers are added
} catch (IOException ex) {
// log.warn("Unable to prepare HTTP response.");
return 0;
}
return matchingRecords;
}
/**
* Sends to the browser the section of javascript where map markers are generated - this method
* is used specifically when searching by startup name or location
*
* @param response
* @param startups
* @return
*/
protected int sendSearchByStartup(HttpServletResponse response, ArrayList<Startup> startups) {
int matchingRecords = 0;
try {
PrintWriter out = response.getWriter();
// BEGIN - map initialization section where markers are added
if (startups != null) {
out.println(" var infowindow = new google.maps.InfoWindow; ");
out.println(" var marker; ");
for (Startup startup : startups) {
for (Address address : startup.getAddresses()) {
matchingRecords++;
if (matchingRecords < 300) {
out.println(" marker = new google.maps.Marker({ ");
out.printf(" position: new google.maps.LatLng(%f, %f), ",
address.getLatitude(), address.getLongitude());
out.println(" animation: google.maps.Animation.DROP, ");
out.println(" map: map ");
out.println(" }); ");
out.println(" ");
out.println(" google.maps.event.addListener(marker, 'click', (function(marker) { ");
out.println(" return function() {");
out.printf("infowindow.setContent('<h5>%s<br>" +
"<small>%s</small>" +
"<p><small>Industry Vertical: <b>%s</b><br>" +
"Date Founded: <b>%s</b></br>" +
"Funding Rounds: <b>%s</b></br>" +
"Total Funding: <b>%s</b></small></p>'); ",
startup.getName(),
address.getStreetAddress(),
startup.getVertical(),
startup.getSince(),
startup.getFundingRounds(),
startup.getTotalFunding());
out.println(" infowindow.open(map, marker); ");
out.println(" } ");
out.println(" })(marker)); ");
}
}
}
}
// END - map initialization section where markers are added
} catch (IOException ex) {
// log.warn("Unable to prepare HTTP response.");
return 0;
}
return matchingRecords;
}
/**
* Sends the midesction of the dynamically-generated web page to the
* browser.
*
* @param response - The HTTP response we are writing to
*/
protected void sendMidsection(HttpServletResponse response) {
try {
PrintWriter out = response.getWriter();
out.println(" ");
out.println(" } ");
out.println(" ");
out.println(" function addMarker(markerTitle, markerLatitude, markerLongitude) { ");
out.println(" ");
out.println(" var infowindow = new google.maps.InfoWindow; ");
out.println(" var marker; ");
out.println(" ");
out.println(" marker = new google.maps.Marker({ ");
out.println(" position: new google.maps.LatLng(markerLatitude, markerLongitude), ");
out.println(" animation: google.maps.Animation.DROP, ");
out.println(" map: map ");
out.println(" }); ");
out.println(" ");
out.println(" google.maps.event.addListener(marker, 'click', function() { ");
out.println(" infowindow.setContent(markerTitle); ");
out.println(" infowindow.open(map, marker); ");
out.println(" }); ");
out.println(" } ");
out.println(" ");
out.println(" google.maps.event.addDomListener(window, 'load', initialize); ");
out.println(" ");
out.println(" </script> ");
out.println(" </head> ");
out.println(" <body> ");
out.println(" ");
out.println(" <div id=\"map-canvas\"></div> ");
out.println(" ");
out.println(" <div class=\"row\"> ");
out.println(" <div class=\"col-xs-1\"></div> ");
out.println(
" <div class=\"col-xs-10\"><h1><small>The</small> San Francisco <small>Startup Atlas</small></h1></div> ");
out.println(" <div class=\"col-xs-1\"><iframe src=\"https://ghbtns.com/github-btn.html?user=dwestgate&repo=San-Francisco-Startup-Atlas&type=star&count=true\" frameborder=\"0\" scrolling=\"0\" width=\"170px\" height=\"20px\"></iframe></div> ");
out.println(" </div> ");
out.println(" ");
} catch (IOException ex) {
// log.warn("Unable to prepare HTTP response.");
return;
}
}
/**
* Constructs the search form and button and sends it as an HTTP response to
* the browser.
* @param request
* @param response
* @param matchingRecords
* @throws IOException
*/
private static void sendSearchForm(HttpServletRequest request, HttpServletResponse response, int matchingRecords) throws IOException {
PrintWriter out = response.getWriter();
String mode = "";
if (request.getParameter("mode") != null) {
mode = request.getParameter("mode");
}
out.println(" <form method=\"get\" role=\"form\" action=\"/search\"> ");
out.println(" ");
out.println(" ");
out.println(" <div class=\"row\"> ");
out.println(" <div class=\"col-xs-12\"></div> ");
out.println(" </div> ");
out.println(" ");
out.println(" <div class=\"row\"> ");
out.println(" <div class=\"col-xs-12\"></div> ");
out.println(" </div> ");
out.println(" ");
out.println(" <div class=\"row\"> ");
out.println(" <div class=\"col-sm-8\"></div> ");
out.println(" <div class=\"col-xs-12 col-sm-3\"> ");
out.println(" <select class=\"form-control\" name=\"mode\"> ");
out.printf(" <option %s>Search on Startup Name</option>",
((mode.equals("Search on Startup Name")) ? "selected=\"selected\"" : ""));
out.printf(" <option %s>Search on Investor Name</option>",
((mode.equals("Search on Investor Name")) ? "selected=\"selected\"" : ""));
// out.println(" <option>Search on Street Address</option> ");
out.printf(" <option %s>Search on Zipcode</option>",
((mode.equals("Search on Zipcode")) ? "selected=\"selected\"" : ""));
out.printf(" <option %s>Search on an Individual</option>",
((mode.equals("Search on an Individual")) ? "selected=\"selected\"" : ""));
out.println(" </select> ");
out.println(" </div> ");
out.println(" <div class=\"col-sm-1\"></div> ");
out.println(" </div> ");
out.println(" ");
out.println(" <div class=\"row\"> ");
out.println(" <div class=\"col-xs-12\"></div> ");
out.println(" </div> ");
out.println(" ");
out.println(" <div class=\"row\"> ");
out.println(" <div class=\"col-sm-8\"></div> ");
out.println(" <div class=\"col-xs-12 col-sm-3\"> ");
out.println(
" <input type=\"text\" name=\"search\" class=\"form-control\" id=\"search_box\" placeholder=\"Enter search term here\" autofocus> ");
out.println(" </div> ");
out.println(" <div class=\"col-sm-1\"></div> ");
out.println(" </div> ");
out.println(" ");
out.println(" <div class=\"row\"> ");
out.println(" <div class=\"col-xs-12\"></div> ");
out.println(" </div> ");
out.println(" ");
out.println(" <div class=\"row\"> ");
out.println(" <div class=\"col-sm-8\"></div> ");
out.println(" <div class=\"col-xs-12 col-sm-1\"> ");
out.printf(" <button type=\"submit\" class=\"btn btn-primary\">Search</button> ");
out.println(" </div> ");
out.println(" <div class=\"col-sm-3\"></div> ");
out.println(" </div> ");
out.println(" </form> ");
out.println(" ");
out.println(" <div class=\"row\"> ");
out.println(" <div class=\"col-xs-12\"> </div> ");
out.println(" </div> ");
out.println(" ");
if (!mode.isEmpty()) {
out.println(" <div class=\"row\"> ");
out.println(" <div class=\"col-sm-8\"></div> ");
out.println(" <div class=\"col-xs-12 col-sm-3\"> ");
out.printf(" <div class=\"panel panel-%s\"> ",
(matchingRecords == 0 ? "danger" : "primary"));
out.println(" <div class=\"panel-heading\"> ");
out.printf(" <h5 class=\"panel-title\">Matching Startups: %d</h5> ", matchingRecords);
out.println(" </div> ");
out.println(" <div class=\"panel-body\"> ");
out.printf(" <p>Search type: <b>%s</b><br>Search string: <b>%s</b></p>",
mode, request.getParameter("search"));
out.println(" </div> ");
out.println(" </div> ");
out.println(" </div> ");
out.println(" <div class=\"col-sm-1\"></div> ");
out.println(" </div> ");
out.println(" ");
}
}
/**
* Outputs the bootom portion of the dynamically-constructed web pages.
*
* @param response - The HTTP response we are writing to
*/
protected void sendBottom(HttpServletResponse response) {
try {
PrintWriter out = response.getWriter();
out.println(" ");
out.println(" ");
out.println(" ");
out.println(" <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> ");
out.println(
" <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js\"></script> ");
out.println(" <!-- Include all compiled plugins (below), or include individual files as needed --> ");
out.println(" <script src=\"js/bootstrap.min.js\"></script> ");
out.println(" </body> ");
out.println(" </html> ");
out.flush();
response.setStatus(HttpServletResponse.SC_OK);
response.flushBuffer();
} catch (IOException ex) {
// log.warn("Unable to finish HTTP response.");
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
}
}
|
package com.ss.android.ugc.aweme.miniapp.g;
import com.ss.android.ugc.aweme.miniapp.MiniAppService;
import com.tt.miniapp.settings.data.ABTestDAO;
import com.tt.miniapphost.AppBrandLogger;
import com.tt.option.l.a;
public class k extends a {
public AppBrandLogger.ILogger createLogger() {
return new AppBrandLogger.ILogger(this) {
public final void flush() {
if (MiniAppService.inst().getBaseLibDepend() != null)
MiniAppService.inst().getBaseLibDepend().a("f", "", "", null);
}
public final void logD(String param1String1, String param1String2) {
if (MiniAppService.inst().getBaseLibDepend() != null)
MiniAppService.inst().getBaseLibDepend().a("d", param1String1, param1String2, null);
}
public final void logE(String param1String1, String param1String2) {
if (MiniAppService.inst().getBaseLibDepend() != null)
MiniAppService.inst().getBaseLibDepend().a("e", param1String1, param1String2, null);
}
public final void logE(String param1String1, String param1String2, Throwable param1Throwable) {
if (MiniAppService.inst().getBaseLibDepend() != null)
MiniAppService.inst().getBaseLibDepend().a("et", param1String1, param1String2, param1Throwable);
}
public final void logI(String param1String1, String param1String2) {
if (MiniAppService.inst().getBaseLibDepend() != null)
MiniAppService.inst().getBaseLibDepend().a("i", param1String1, param1String2, null);
}
public final void logW(String param1String1, String param1String2) {
if (MiniAppService.inst().getBaseLibDepend() != null)
MiniAppService.inst().getBaseLibDepend().a("w", param1String1, param1String2, null);
}
};
}
public ABTestDAO.IUploadVids uploadVid() {
return super.uploadVid();
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\ss\androi\\ugc\aweme\miniapp\g\k.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/ |
import java.util.Comparator;
class Action {
public double time;
public double[] velocities;
public Action(double[] velocities, double time) {
this.time = time;
this.velocities = velocities;
}
}
class ActionComp implements Comparator<Action>{
@Override
public int compare(Action o1, Action o2) {
return (int)(o1.time-o2.time);
}
}
|
package com.kodilla.spring;
import com.kodilla.spring.forum.ForumUser;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringRunnerTestSuite {
@Test
public void testUserLoadedIntoContainer() {
//Given
ApplicationContext context =
new AnnotationConfigApplicationContext("com.kodilla.spring");
ForumUser user = context.getBean(ForumUser.class);
String expected = "John Smith";
//When
String actual = user.getUsername();
//Then
Assert.assertEquals(expected, actual);
}
}
|
package traffic_simulator;
public class Road {
final int ROAD_LENGTH = 36;
String roadName;
int roadEnd1X;//traffic_simulator.Road end X-Y coordinates measured from middle of road to keep vehicles on either side
int roadEnd1Y;
int roadEnd2X;
int roadEnd2Y;
String direction;
public Road(String newName, int coordinateX, int coordinateY, String newDirection){
roadName = newName;
roadEnd1X = coordinateX;
roadEnd1Y = coordinateY;
direction = newDirection;
if(direction.equals("north-south")){
roadEnd2X = roadEnd1X;
roadEnd2Y = roadEnd1Y + ROAD_LENGTH;
} else {
roadEnd2X = roadEnd1X + ROAD_LENGTH;
roadEnd2Y = roadEnd1Y;
}
}
public int getRoadEnd1X() {
return roadEnd1X;
}
public int getRoadEnd1Y() {
return roadEnd1Y;
}
public int getRoadEnd2X() {
return roadEnd2X;
}
public int getRoadEnd2Y() {
return roadEnd2Y;
}
}
|
package com.sedwt.icloud.controller;
import com.sedwt.icloud.common.Result;
import com.sedwt.icloud.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* @author : zhang yijun
* @date : 2021/3/15 14:17
* @description : TODO
*/
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
/**
* 用户注册
* @param username 用户名
* @param password 密码
* @return
*/
@GetMapping("/signup")
public Result signUp(@RequestParam String username, @RequestParam String password){
//TODO 参数校验
return userService.signUp(username, password);
}
/**
* 用户登陆
* @param username 用户名
* @param password 密码
* @return
*/
@GetMapping("/login")
public Result login(@RequestParam String username, @RequestParam String password){
// TODO 参数校验
return userService.login(username, password);
}
}
|
package org.tinyspring.aop.config;
import org.tinyspring.beans.BeanUtils;
import org.tinyspring.beans.factory.BeanFactory;
import org.tinyspring.beans.factory.BeanFactoryAware;
import org.tinyspring.beans.factory.FactoryBean;
import org.tinyspring.utils.StringUtils;
import java.lang.reflect.Method;
/**
* @author tangyingqi
* @date 2018/7/31
*/
public class MethodLocatingFactory implements FactoryBean<Method>,BeanFactoryAware {
private String targetBeanName;
private String methodName;
private Method method;
public void setTargetBeanName(String targetBeanName) {
this.targetBeanName = targetBeanName;
}
public void setMethodName(String methodName) {
this.methodName = methodName;
}
@Override
public void setBeanFactory(BeanFactory beanFactory){
if (!StringUtils.hasText(targetBeanName)){
throw new IllegalStateException("Property 'targetBeanName' is required");
}
if (!StringUtils.hasText(methodName)){
throw new IllegalStateException("Property 'methodName' is required");
}
Class<?> beanClass = beanFactory.getType(targetBeanName);
if (beanClass == null){
throw new IllegalStateException("Can't determine type of bean with name'"+this.targetBeanName+"'");
}
this.method = BeanUtils.resolveSignature(this.methodName,beanClass);
if (this.method == null) {
throw new IllegalArgumentException("Unable to locate method [" + this.methodName +
"] on bean [" + this.targetBeanName + "]");
}
}
@Override
public Method getObject(){
return this.method;
}
@Override
public Class<?> getObjectType() {
return Method.class;
}
}
|
package main.model;
import java.util.List;
import object.visualparadigm.Shape;
public class EPCElement {
private Shape shape;
private boolean isStartNode;
private boolean reqDummyTrans;
private String operatorType; //Split, Join
private List<String> fromShapeId;
private List<String> toShapeId;
private CPNObject cpnObject;
private List<String> incomeCPNId;
private List<String> outcomeCPNId;
private String initMark = "";
public Shape getShape() {
return shape;
}
public void setShape(Shape shape) {
this.shape = shape;
}
public boolean isStartNode() {
return isStartNode;
}
public void setStartNode(boolean isStartNode) {
this.isStartNode = isStartNode;
}
public String getOperatorType() {
return operatorType;
}
public void setOperatorType(String operatorType) {
this.operatorType = operatorType;
}
public CPNObject getCpnObject() {
return cpnObject;
}
public void setCpnObject(CPNObject cpnObject) {
this.cpnObject = cpnObject;
}
public boolean isReqDummyTrans() {
return reqDummyTrans;
}
public void setReqDummyTrans(boolean reqDummyTrans) {
this.reqDummyTrans = reqDummyTrans;
}
public List<String> getFromShapeId() {
return fromShapeId;
}
public void setFromShapeId(List<String> fromShapeId) {
this.fromShapeId = fromShapeId;
}
public List<String> getToShapeId() {
return toShapeId;
}
public void setToShapeId(List<String> toShapeId) {
this.toShapeId = toShapeId;
}
public List<String> getIncomeCPNId() {
return incomeCPNId;
}
public void setIncomeCPNId(List<String> incomeCPNId) {
this.incomeCPNId = incomeCPNId;
}
public List<String> getOutcomeCPNId() {
return outcomeCPNId;
}
public void setOutcomeCPNId(List<String> outcomeCPNId) {
this.outcomeCPNId = outcomeCPNId;
}
public String getInitMark() {
return initMark;
}
public void setInitMark(String initMark) {
this.initMark = initMark;
}
}
|
package Exams.February24_2019;
import java.util.Scanner;
public class TronRacers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = Integer.parseInt(scanner.nextLine());
int rowF = 0;
int colF = 0;
int rowS = 0;
int colS = 0;
String[][] field = new String[n][n];
for (int i = 0; i < n; i++) {
String[] line = scanner.nextLine().split("");
for (int i1 = 0; i1 < n; i1++) {
if (line[i1].equalsIgnoreCase("f")) {
rowF = i;
colF = i1;
}
if (line[i1].equalsIgnoreCase("s")) {
rowS = i;
colS = i1;
}
field[i][i1] = line[i1];
}
}
if (field != null) {
while (true) {
String[] tokens = scanner.nextLine().split("\\s+");
String cmd1 = tokens[0];
String cmd2 = tokens[1];
if (field[rowF][colF].equalsIgnoreCase("f")) {
if (cmd1.equalsIgnoreCase("up")) {
rowF = getRowUp(n, rowF);
} else if (cmd1.equalsIgnoreCase("down")) {
rowF = getRowDown(n, rowF);
} else if (cmd1.equalsIgnoreCase("left")) {
colF = getColLeft(n, colF);
} else if (cmd1.equalsIgnoreCase("right")){
colF = getColRight(n, colF);
}
if (field[rowF][colF].equalsIgnoreCase("s")) {
field[rowF][colF] = "x";
printField(field);
return;
}
field[rowF][colF] = "f";
}
if (field[rowS][colS].equalsIgnoreCase("s")) {
if (cmd2.equalsIgnoreCase("up")) {
rowS = getRowUp(n, rowS);
} else if (cmd2.equalsIgnoreCase("down")) {
rowS = getRowDown(n, rowS);
} else if (cmd2.equalsIgnoreCase("left")) {
colS = getColLeft(n, colS);
} else if (cmd2.equalsIgnoreCase("right")){
colS = getColRight(n, colS);
}
if (field[rowS][colS].equalsIgnoreCase("f")) {
field[rowS][colS] = "x";
printField(field);
return;
}
field[rowS][colS] = "s";
}
}
}
}
private static int getColRight(int n, int colF) {
if (colF + 1 < n) {
colF++;
} else {
colF = 0;
}
return colF;
}
private static int getColLeft(int n, int colF) {
if (colF - 1 >= 0) {
colF--;
} else {
colF = n - 1;
}
return colF;
}
private static int getRowDown(int n, int rowS) {
rowS = getColRight(n, rowS);
return rowS;
}
private static int getRowUp(int n, int rowF) {
if (rowF - 1 >= 0) {
rowF--;
} else {
rowF = n - 1;
}
return rowF;
}
private static void printField(String[][] field) {
for (String[] strings : field) {
for (int i1 = 0; i1 < field[0].length; i1++) {
System.out.print((strings[i1]));
}
System.out.println();
}
}
}
|
package com.project.common_basic.hybrid;
/**
* 标题栏右侧按钮点击监听
*
* Created by joye on 2017/3/8.
*/
public interface RightBtnClickListener {
boolean onClickRightBtn();
}
|
package test;
import static org.junit.Assert.assertEquals;
import junit.framework.Assert;
import model.ChemicalElement;
import model.Classification;
import org.junit.Before;
import org.junit.Test;
public class ChemicalElementTest {
ChemicalElement elemen1;
ChemicalElement elemen2;
ChemicalElement elemen3;
ChemicalElement elemen4;
@Before
public void setUp() throws Exception {
elemen1 = new ChemicalElement("Hidrogênio", "H", 1, 1, 1, Classification.NAO_METAIS);
elemen2 = new ChemicalElement("Ferro", "Fe", 4, 8, 26, Classification.METAIS_DE_TRANSICAO);
elemen3 = new ChemicalElement("Bromo", "Br", 4, 17, 35, Classification.HALOGENIOS);
elemen4 = new ChemicalElement("Elemento", "E", 1, 1, 21, Classification.LIQUIDO);
}
@Test
public void testConstructorChemicalElement() {
try {
new ChemicalElement(" ", "H", 1, 1, 1, Classification.NAO_METAIS);
Assert.fail("Esperava excessão.");
} catch(Exception e) {
assertEquals("Nome Inválido!", e.getMessage());
}
try {
new ChemicalElement(null, "H", 1, 1, 1, Classification.NAO_METAIS);
Assert.fail("Esperava excessão.");
} catch(Exception e) {
assertEquals("Nome Inválido!", e.getMessage());
}
try {
new ChemicalElement("Hidrogênio", " ", 1, 1, 1, Classification.NAO_METAIS);
Assert.fail("Esperava excessão.");
} catch(Exception e) {
assertEquals("Símbolo Inválido!", e.getMessage());
}
try {
new ChemicalElement("Hidrogênio", null, 1, 1, 1, Classification.NAO_METAIS);
Assert.fail("Esperava excessão.");
} catch(Exception e) {
assertEquals("Símbolo Inválido!", e.getMessage());
}
try {
new ChemicalElement("Hidrogênio", "H", -300, 1, 1, Classification.NAO_METAIS);
Assert.fail("Esperava excessão.");
} catch(Exception e) {
assertEquals("Linha Inválida!", e.getMessage());
}
try {
new ChemicalElement("Hidrogênio", "H", 300, 1, 1, Classification.NAO_METAIS);
Assert.fail("Esperava excessão.");
} catch(Exception e) {
assertEquals("Linha Inválida!", e.getMessage());
}
try {
new ChemicalElement("Hidrogênio", "H", 0, 1, 1, Classification.NAO_METAIS);
Assert.fail("Esperava excessão.");
} catch(Exception e) {
assertEquals("Linha Inválida!", e.getMessage());
}
try {
new ChemicalElement("Hidrogênio", "H", 1, -500, 1, Classification.NAO_METAIS);
Assert.fail("Esperava excessão.");
} catch(Exception e) {
assertEquals("Coluna Inválida!", e.getMessage());
}
try {
new ChemicalElement("Hidrogênio", "H", 1, 500, 1, Classification.NAO_METAIS);
Assert.fail("Esperava excessão.");
} catch(Exception e) {
assertEquals("Coluna Inválida!", e.getMessage());
}
try {
new ChemicalElement("Hidrogênio", "H", 1, 0, 1, Classification.NAO_METAIS);
Assert.fail("Esperava excessão.");
} catch(Exception e) {
assertEquals("Coluna Inválida!", e.getMessage());
}
try {
new ChemicalElement("Hidrogênio", "H", 1, 1, -1000, Classification.NAO_METAIS);
Assert.fail("Esperava excessão.");
} catch(Exception e) {
assertEquals("Número Atômico Inválido!", e.getMessage());
}
try {
new ChemicalElement("Hidrogênio", "H", 1, 1, 1000, Classification.NAO_METAIS);
Assert.fail("Esperava excessão.");
} catch(Exception e) {
assertEquals("Número Atômico Inválido!", e.getMessage());
}
try {
new ChemicalElement("Hidrogênio", "H", 1, 1, 0, Classification.NAO_METAIS);
Assert.fail("Esperava excessão.");
} catch(Exception e) {
assertEquals("Número Atômico Inválido!", e.getMessage());
}
try {
new ChemicalElement("Hidrogênio", "H", 1, 1, 1, null);
Assert.fail("Esperava excessão.");
} catch(Exception e) {
assertEquals("Classificação não pode ser nula!", e.getMessage());
}
}
@Test
public void testChemicalElement() {
assertEquals("Hidrogênio", elemen1.getName());
assertEquals("H", elemen1.getSymbol());
assertEquals(1, elemen1.getLines());
assertEquals(1, elemen1.getColumn());
assertEquals(1, elemen1.getAtomicNumber());
assertEquals(Classification.NAO_METAIS, elemen1.getClassification());
assertEquals("Ferro", elemen2.getName());
assertEquals("Fe", elemen2.getSymbol());
assertEquals(4, elemen2.getLines());
assertEquals(8, elemen2.getColumn());
assertEquals(26, elemen2.getAtomicNumber());
assertEquals(Classification.METAIS_DE_TRANSICAO, elemen2.getClassification());
assertEquals("Bromo", elemen3.getName());
assertEquals("Br", elemen3.getSymbol());
assertEquals(4, elemen3.getLines());
assertEquals(17, elemen3.getColumn());
assertEquals(35, elemen3.getAtomicNumber());
assertEquals(Classification.HALOGENIOS, elemen3.getClassification());
assertEquals("Elemento", elemen4.getName());
assertEquals("E", elemen4.getSymbol());
assertEquals(1, elemen4.getLines());
assertEquals(1, elemen4.getColumn());
assertEquals(21, elemen4.getAtomicNumber());
assertEquals(Classification.LIQUIDO, elemen4.getClassification());
}
@Test
public void testSetsChemicalElement() throws Exception {
assertEquals("Hidrogênio", elemen1.getName());
elemen1.setName("Caramelo");
assertEquals("Caramelo", elemen1.getName());
assertEquals("H", elemen1.getSymbol());
elemen1.setSymbol("Ca");
assertEquals("Ca", elemen1.getSymbol());
assertEquals(1, elemen1.getLines());
elemen1.setLine(5);
assertEquals(5, elemen1.getLines());
assertEquals(1, elemen1.getColumn());
elemen1.setColumn(10);
assertEquals(10, elemen1.getColumn());
assertEquals(1, elemen1.getAtomicNumber());
elemen1.setAtomicNumber(20);
assertEquals(20, elemen1.getAtomicNumber());
assertEquals(Classification.NAO_METAIS, elemen1.getClassification());
elemen1.setClassification(Classification.ACTINIDEOS);
assertEquals(Classification.ACTINIDEOS, elemen1.getClassification());
assertEquals("Caramelo", elemen1.getName());
assertEquals("Ca", elemen1.getSymbol());
assertEquals(5, elemen1.getLines());
assertEquals(10, elemen1.getColumn());
assertEquals(20, elemen1.getAtomicNumber());
assertEquals(Classification.ACTINIDEOS, elemen1.getClassification());
}
@Test
public void testToString() {
assertEquals("Nome: Hidrogênio | Símbolo: H | Número Atômico: 1 | Linha: 1 | Couna: 1", elemen1.toString());
assertEquals("Nome: Ferro | Símbolo: Fe | Número Atômico: 26 | Linha: 4 | Couna: 8", elemen2.toString());
assertEquals("Nome: Bromo | Símbolo: Br | Número Atômico: 35 | Linha: 4 | Couna: 17", elemen3.toString());
assertEquals("Nome: Elemento | Símbolo: E | Número Atômico: 21 | Linha: 1 | Couna: 1", elemen4.toString());
}
} |
package interpreter;
class Node
{
Node left;
Node right;
String value;
String type;
int length;
public Node(String value, String type, int length) {
this.value = value;
this.type = type;
this.length = length;
}
}
|
package com.portmods.SC.handler;
import net.minecraft.client.Minecraft;
import org.lwjgl.opengl.ARBFramebufferObject;
import static org.lwjgl.opengl.EXTFramebufferObject.*;
import static org.lwjgl.opengl.GL11.*;
/**
* Created by David on 8/14/2014.
*/
public class RenderHandler {
public RenderHandler()
{
fbo = glGenFramebuffersEXT(); // create a new framebuffer
texture = glGenTextures(); // and a new texture used as a color buffer
depth = glGenRenderbuffersEXT(); // a new depthbuffer
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo); // switch to the new framebuffer
glBindTexture(GL_TEXTURE_2D, texture); // Bind the colorbuffer texture
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); // make it linear filterd
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, Minecraft.getMinecraft().displayWidth, Minecraft.getMinecraft().displayHeight, 0, GL_RGBA, GL_INT, (java.nio.ByteBuffer) null); // Create the texture data
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, texture, 0); // attach it to the framebuffer
glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, depth); // bind the depth renderbuffer
glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, ARBFramebufferObject.GL_DEPTH24_STENCIL8, Minecraft.getMinecraft().displayWidth, Minecraft.getMinecraft().displayHeight); // get the data space for it
glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, ARBFramebufferObject.GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER_EXT, depth); // bind it to the framebuffer
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
}
public void updateResolution(int width, int height)
{
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo); // switch to the new framebuffer
glBindTexture(GL_TEXTURE_2D, texture); // Bind the colorbuffer texture
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_INT, (java.nio.ByteBuffer) null); // Create the texture data
glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, depth); // bind the depth renderbuffer
glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, ARBFramebufferObject.GL_DEPTH24_STENCIL8, width, height); // get the data space for it
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
}
public int texture;
public int fbo;
public int depth;
}
|
package xframe.example.pattern.factory.simplefactory;
public class Byd extends Car {
Byd(){
System.out.println("call Byd constructor.");
}
}
|
package com.alfa.work2;
public interface MyConverter {
String convertStr(String str);
public static boolean isnull(String str){
return str == null ? true : str.trim().equals("") ;
}
}
|
package com.mes.old.meta;
// Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final
/**
* Jobshop产品外协率 generated by hbm2java
*/
public class Jobshop产品外协率 implements java.io.Serializable {
private Jobshop产品外协率Id id;
public Jobshop产品外协率() {
}
public Jobshop产品外协率(Jobshop产品外协率Id id) {
this.id = id;
}
public Jobshop产品外协率Id getId() {
return this.id;
}
public void setId(Jobshop产品外协率Id id) {
this.id = id;
}
}
|
package cardreceiptmanager.model;
/**
* Created by User on 1/27/2016.
*/
public class CardModel {
}
|
package com.example.project_redbus;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
public class search extends AppCompatActivity {
private ImageView backbtn;
private TextView sourceglb,destinationbang,presentday;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
backbtn=findViewById(R.id.backhome);
sourceglb=findViewById(R.id.gulbarga);
destinationbang=findViewById(R.id.banhalore);
presentday=findViewById(R.id.seatchdate);
Intent intent=getIntent();
String s=intent.getStringExtra("source");
String d=intent.getStringExtra("destination");
String pd=intent.getStringExtra("persentdate");
sourceglb.setText(s);
destinationbang.setText(d);
presentday.setText(pd);
ArrayList<Example> exampleList = new ArrayList<>();
exampleList.add(new Example("SRS", "Rs-700", "7AM to 7PM ","3-STAR"));
exampleList.add(new Example("VRL", "Rs-1200", "11AM to 5PM","4-STAR"));
exampleList.add(new Example("Pavit", "Rs-950", "1PM to 11:50PM ","3-STAR"));
exampleList.add(new Example("Sugema", "Rs-800", "3PM to 2AM","5-SRAT"));
exampleList.add(new Example("Krishna", "Rs-1500", "1PM to 5AM","5-STAR"));
exampleList.add(new Example("Ram", "Rs-1800", "2PM to 5AM","1-STAR"));
exampleList.add(new Example("Sangam", "Rs-1000", "3PM to 8AM","4-STAR"));
mRecyclerView = findViewById(R.id.recycleview);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new ExampleAdapter(exampleList);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
backbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(search.this,MainActivity.class);
startActivity(intent);
}
});
}
} |
/*
* 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 laptinhmang;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author dangn
*/
public class ControllDownload {
private String link;
private ArrayList<Download> listDownloads;
private long durationThread;
private long current;
private long before;
private long size;
private String fileName;
private int quantityThread;
private int speed;
private boolean DownloadStatus;
public static boolean DownladStart = true;
public static boolean DownloadPause = false;
public ControllDownload(String link) {
this.link = link;
listDownloads = new ArrayList<>();
DownloadStatus = DownloadPause;
}
public ControllDownload() {
listDownloads = new ArrayList<>();
this.before = 0;
this.current = 0;
}
public String getLink() {
return link;
}
public void setLink(String link) {
try {
this.before = 0;
this.current = 0;
this.link = link;
setSize();
setFileName();
setQuantityThread();
setDurationThread();
setThreadDownload();
} catch (IOException ex) {
Logger.getLogger(ControllDownload.class.getName()).log(Level.SEVERE, null, ex);
}
}
public long getDurationThread() {
return durationThread;
}
public void setDurationThread() {
this.durationThread = durationThread = size / quantityThread;
}
public void setThreadDownload(){
listDownloads.clear();
try {
long start = 0, end = 0;
for (int i = 0; i < quantityThread; i++) {
start = i * durationThread;
end = (i + 1) * durationThread;
if (i == quantityThread - 1) {
end = size;
}
Download download = new Download(start, end, new URL(link), fileName);
listDownloads.add(download);
}
} catch (IOException ex) {
Logger.getLogger(ControllDownload.class.getName()).log(Level.SEVERE, null, ex);
}
}
public long getCurrent() {
current = 0;
for (int i = 0; i < listDownloads.size(); i++) {
current = current + listDownloads.get(i).getCurrent();
}
return current;
}
public String infoDownload(){
String info = "";
for (int i = 0; i < listDownloads.size(); i++) {
info = info + String.format("Thread%d : %d / %d kb \n",(i+1),(listDownloads.get(i).getCurrent())/1024,durationThread/1024);
}
return info;
}
public void start() {
if(!listDownloads.isEmpty()){
DownloadStatus = DownladStart;
for (Download download : listDownloads) {
download.start();
}
}
}
public void pause() {
if(!listDownloads.isEmpty()){
DownloadStatus = DownloadPause;
for (Download download : listDownloads) {
download.pause();
}
}
}
public String getFileName() {
return fileName;
}
public void setFileName() throws IOException {
String raw = "";
fileName = "";
try {
URL url = new URL(link);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
raw = connection.getHeaderField("Content-Disposition");
System.out.println(raw);
int i = 0;
boolean kt = false;
if (raw != null) {
fileName = raw.split("filename=")[1].trim();
if (fileName.indexOf(';') != -1) {
fileName = fileName.split(";")[0].trim();
}
if (fileName.indexOf('"') != -1) {
fileName = fileName.replace('"', ' ').trim();
}
} else {
fileName = link.substring(link.lastIndexOf('/') + 1);
System.out.println(fileName);
if(fileName.indexOf(".")==-1){
fileName = "abc.xyz";
}
if(fileName.indexOf("mp4")!=-1){
fileName = fileName.substring(0,fileName.indexOf("mp4")+3);
}
}
connection.disconnect();
System.out.println(fileName);
} catch (MalformedURLException ex) {
Logger.getLogger(Download.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void setSize() throws IOException {
URL url = new URL(link);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
if (connection.getResponseCode() != 200) {
System.out.println("Error return code != 200");
}
size = connection.getContentLength();
connection.disconnect();
}
public void setQuantityThread(int quantityThread) {
this.quantityThread = quantityThread;
}
public void setQuantityThread() {
quantityThread = (int) (size/(10280*1028));
quantityThread = (quantityThread>16)?16:quantityThread;
quantityThread = (quantityThread<1)?1:quantityThread;
}
public long getSize() {
return size;
}
public int getQuantityThread() {
return quantityThread;
}
public int getSpeed(int sleep){
speed=0;
getCurrent();
speed = (int)((current - before)*(1000/sleep));
before = current;
return speed/1028;
}
public String getTIme(){
String time="";
if(speed==0) return "0";
int seconds = (int)(size - current) / speed;
int h = seconds/3600;
int m = (seconds%3600)/60;
int s = (seconds%3600)%60;
if(h==0){
if(s < 10) time = time+m+" : " + "0"+s;
else time = time + m +" : " + s;
}
else{
if(m<0){
if(s < 10) time = time + h +" : 0" + m +" : " + "0"+s;
else time = time +h +" : 0" + m +" : " + s;
}
else{
if(s < 10) time = time + h +" : " + m +" : " + "0"+s;
else time = time +h +" : " + m +" : " + s;
}
}
return time;
}
public boolean getDownloadStatus() {
return DownloadStatus;
}
}
|
package com.example.startapp006;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
public class MyItemRecyclerViewAdapter extends RecyclerView.Adapter<MyItemRecyclerViewAdapter.ViewHolder> {
private final List<Items> mValues;
public MyItemRecyclerViewAdapter(List<Items> items) {
mValues = items;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_item, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
Items item = mValues.get(position);
holder.msurnameView.setText(item.surname);
holder.mnameView.setText(item.name);
holder.meMailView.setText(item.eMail);
holder.mphoneNumberView.setText(item.phoneNumber);
}
@Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView msurnameView;
public final TextView mnameView;
public final TextView meMailView;
public final TextView mphoneNumberView;
public ViewHolder(View view) {
super(view);
mView = view;
msurnameView = (TextView) view.findViewById(R.id.lSurname);
mnameView = (TextView) view.findViewById(R.id.lName);
meMailView = (TextView) view.findViewById(R.id.leMail);
mphoneNumberView = (TextView) view.findViewById(R.id.lPhoneNumber);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
}
// @Override
// public String toString() {
// return super.toString() + " '" + mnameView.getText() + "'";
// }
}
} |
package com.e6soft.bpm.service;
import java.util.List;
import org.jdom.Element;
import com.e6soft.api.bpm.dto.BpmFormData;
import com.e6soft.bpm.model.FlownodeAction;
import com.e6soft.core.service.BaseService;
/**
* 节点应用Action操作
* @author 陈福忠
*
*/
public interface FlownodeActionService extends BaseService<FlownodeAction, String> {
/**
* 删除 根据nodeId
* @author 王瑜
*/
public void deleteByNodeid(String nodeId);
/**
* 根据nodeId获取ActionList
* @author 陈福忠
* @param nodeId
* @return
*/
public List<FlownodeAction> queryByNodeId(String nodeId);
/**
* 导出流程节点所有应用
* @author 陈福忠
* @param nodeId
* @return
*/
public List<Element> exportFlowNodeActionElement(String nodeId);
/**
* 导入节点所有应用
* @author 陈福忠
* @param nodeId
* @param flowNodeActionList
*/
public void importFlowNodeAction(String nodeId, List<Element> flowNodeActionList) ;
public void updateFlowNodeActionList(String nodeId,List<FlownodeAction> flownodeActionList);
public void doNodeAction(String nodeId,Integer position,BpmFormData bpmFormData);
/**
* 修改节点应用的状态
* @author KeBing 2013-6-13
*/
public void updateFlowNodeActionStatusList(String nodeId, List<FlownodeAction> flownodeActionList);
}
|
import java.util.Scanner;
public class Consecutive_number{
public static boolean isConsecutiveFour(int[] arr) {
boolean result = true;
if(arr.length<1)
return false;
int min=getmin(arr);
int max=getmax(arr);
int n=arr.length;
int count=0;
if(max+min-1==n) {
boolean[] reached=new boolean[n];
for(int i=0;i<n;i++) {
if(reached[arr[i]-min]!=false)
return false;
reached[arr[i]-min]=true;
count++;
}
return true;
}
return false;
}
static int getmin(int[] arr) {
int min=arr[0];
for(int i=0;i<arr.length;i++) {
if(min>arr[i]) {
min=arr[i];
}
}
return min;
}
static int getmax(int[] arr) {
int max=arr[0];
for(int i=0;i<arr.length;i++) {
if(max<arr[i]) {
max=arr[i];
}
}
return max;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int num=sc.nextInt();
int arr[]=new int[num];
for(int i=0;i<num;i++) {
arr[i]=sc.nextInt();
}
if((isConsecutiveFour(arr)==true))
System.out.println("consecutive");
else
System.out.println("not consecutive");
}
}
|
/**
* @author Mie Plougstrup, Anders Abildgaard, Bo Stokholm
* @Version 16-12-2014
*/
package dbLayer;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import modelLayer.Trailer;
/**
* @author Bo Nielsen
* */
public class DbTrailer {
private Connection con;
private DbBusinessPartner dbbp;
public DbTrailer(){
dbbp = new DbBusinessPartner();
con = DbConnection.getInstance().getDBcon();
}
/**
* Find a trailer by its trailer id.
* @param int id
* @return Trailer object
*/
public Trailer retrieveById(int id){
String wClause = " trailerId = "+ id;
return singleWhere(wClause);
}
/**
* Find trailer by trailer name.
* @param String attValue
* @return Trailer
*/
public Trailer retrieveByTrailerName(String attValue){
String wClause = " trailerName like '%" + attValue + "%'";
return singleWhere(wClause);
}
/**
* Return a list of all trailers in the Database.
* @return ArrayList<Trailer> list
*/
public ArrayList<Trailer> retrieveAllTrailers(){
return multiWhere("");
}
/**
* Method for retrieving trailers not already used on dispositions.
*
* @return List unused trailers.
*/
public ArrayList<Trailer> retrieveUnusedTrailers(int dispListId) {
return multiWhere(" trailer.trailerId != 0 and not exists (select * from disposition, dispositionList where disposition.trailerId = trailer.trailerId and disposition.dispListId = dispositionList.dispListId and dispositionList.dispListId = " + dispListId + ")");
}
/**
* Updates a trailer in the database.
* @param Trailer object
* @return int rc
*/
public int update(Trailer trailer){
int rc = -1;
String query = "UPDATE trailer SET "+
" supplierId = " + trailer.getSupplier() +
" WHERE trailerId = " + trailer.getTrailerId();
System.out.println(query);//Delete after tests
try{
Statement stmt = con.createStatement();
stmt.setQueryTimeout(5);
rc = stmt.executeUpdate(query);
stmt.close();
}catch(Exception e){
System.out.println(e);
}
return (rc);
}
/**
* Insert a trailer into the database.
* @param Trailer object
* @return int rc
* @throws Exception
*/
public int insert(Trailer trailer) throws Exception{
int nextId = DbMaxId.getMaxID("trailerId", "trailer");
//Increment id
nextId=nextId+1;
int rc = -1;
String query = "INSERT INTO trailer (trailerId, trailerName, supplierId) VALUES (?,?,?)";
System.out.println(query);
try{
trailer.setTrailerId(nextId);
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setInt(1, trailer.getTrailerId());
pstmt.setString(2, trailer.getTrailerName());
pstmt.setInt(3, trailer.getSupplier().getPartnerId());
pstmt.setQueryTimeout(5);
rc = pstmt.executeUpdate();
pstmt.close();
}catch(Exception e){
throw new Exception("Trailer not inserted");
}
return (rc);
}
/**
* Deletes a Trailer from database.
* @param Trailer object
* @return int rc
*/
public int delete(Trailer trailer){
int rc = -1;
String query = "DELETE FROM trailer WHERE trailerId = " + trailer.getTrailerId();
System.out.println(query);//Delete after tests
try{
Statement stmt = con.createStatement();
stmt.setQueryTimeout(5);
rc = stmt.executeUpdate(query);
stmt.close();
}catch(Exception e){
System.out.println(e);
}
return (rc);
}
/**
* Executes a query statement and builds a object out
* the results. It then returns a single trailer object.
* @param String WhereClause
* @return Trailer object
*/
private Trailer singleWhere(String wClause){
ResultSet results;
Trailer trailObj = new Trailer();
String query = buildQuery(wClause);
System.out.println(query);//Delete after tests
try{
Statement stmt = con.createStatement();
stmt.setQueryTimeout(5);
results = stmt.executeQuery(query);
if(results.next()){
trailObj = buildTrailer(results);
stmt.close();
}else
trailObj = null;
}catch(Exception e){
System.out.println(e);
}
return trailObj;
}
/**
* Builds a list of all the trailer objects and returns the list.
* @param String wClause
* @return ArrayList<Trailer>
*/
private ArrayList<Trailer> multiWhere(String wClause){
ResultSet results;
ArrayList<Trailer> list = new ArrayList<Trailer>();
String query = buildQuery(wClause);
System.out.println(query);
try{
Statement stmt = con.createStatement();
stmt.setQueryTimeout(5);
results = stmt.executeQuery(query);
while(results.next()){
Trailer trailObj = new Trailer();
trailObj = buildTrailer(results);
list.add(trailObj);
}//End while
//Close connection
stmt.close();
}catch(Exception e){
System.out.println(e);//Delete after test
}
return list;
}
/**
* Builds a trailer from the data in a resultset.
* @param ResultSet results
* @return Trailer object
*/
private Trailer buildTrailer(ResultSet results){
Trailer trailObj = new Trailer();
try{
trailObj.setTrailerId(results.getInt("trailerId"));
trailObj.setTrailerName(results.getString("trailerName"));
trailObj.setSupplier(dbbp.retrieveSupplierById(results.getInt("supplierId"))); //Set supplier and trailer together
}catch(Exception e){
System.out.println("Error building trailer");//Delete after tests
}
return trailObj;
}
/**
* Builds a SQL query that can be executed.
* @param String wClause
* @return String query
*/
private String buildQuery(String wClause){
String query = "SELECT trailerId, trailerName, supplierId FROM Trailer";
if(wClause.length() >0){//Change made here.
query=query+ " WHERE"+ wClause;
}
return query;
}
}
|
package io.github.namhyungu.algorithm.programmers.kakao.blind_recruitment.v2018;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class NewsClustering {
public int solution(String str1, String str2) {
List<String> set1 = filterString(toStringSet(str1.toLowerCase()));
List<String> set2 = filterString(toStringSet(str2.toLowerCase()));
Collections.sort(set1);
Collections.sort(set2);
int union = union(set1, set2);
int intersect = intersect(set1, set2);
if (intersect == 0 && union == 0) {
return 65536;
} else {
return (int) (((float) intersect / union) * 65536);
}
}
public List<String> toStringSet(String str) {
List<String> set = new ArrayList<>();
for (int i = 0; i < str.length() - 1; i++) {
String s = str.substring(i, i + 2);
set.add(s);
}
return set;
}
public List<String> filterString(List<String> list) {
List<String> filtered = new ArrayList<>();
for (String s : list) {
boolean isValid = true;
for (char c : s.toCharArray()) {
if (c < 'a' || c > 'z') {
isValid = false;
break;
}
}
if (isValid) {
filtered.add(s);
}
}
return filtered;
}
public int union(List<String> set1, List<String> set2) {
List<String> union = new ArrayList<>();
int idx1 = 0;
int idx2 = 0;
while (idx1 < set1.size() && idx2 < set2.size()) {
if (set1.get(idx1).compareTo(set2.get(idx2)) < 0) {
union.add(set1.get(idx1++));
} else if (set1.get(idx1).compareTo(set2.get(idx2)) > 0) {
union.add(set2.get(idx2++));
} else {
union.add(set1.get(idx1));
idx1++;
idx2++;
}
}
while (idx1 < set1.size()) {
union.add(set1.get(idx1++));
}
while (idx2 < set2.size()) {
union.add(set2.get(idx2++));
}
return union.size();
}
public int intersect(List<String> set1, List<String> set2) {
List<String> intersect = new ArrayList<>();
int idx1 = 0;
int idx2 = 0;
while (idx1 < set1.size() && idx2 < set2.size()) {
if (set1.get(idx1).compareTo(set2.get(idx2)) < 0) {
idx1++;
} else if (set1.get(idx1).compareTo(set2.get(idx2)) > 0) {
idx2++;
} else {
intersect.add(set1.get(idx1));
idx1++;
idx2++;
}
}
return intersect.size();
}
}
|
package org.Third.Chapter.CompletableFuture;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
public class TestFutureException {
/**
* one start ------------
* ---main thread wait future result---
* ----thread-1 set future result----
* Exception in thread "main" java.util.concurrent.ExecutionException: java.lang.RuntimeException: error exception
* at java.util.concurrent.CompletableFuture.reportGet(CompletableFuture.java:357)
* at java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1908)
* at org.Third.Chapter.CompletableFuture.TestFutureException.one(TestFutureException.java:31)
* at org.Third.Chapter.CompletableFuture.TestFutureException.main(TestFutureException.java:98)
* Caused by: java.lang.RuntimeException: error exception
* at org.Third.Chapter.CompletableFuture.TestFutureException.lambda$one$0(TestFutureException.java:25)
* at java.lang.Thread.run(Thread.java:748)
*/
public static void one() throws InterruptedException, ExecutionException {
System.out.println("one start ------------");
// 1.创建一个CompletableFuture对象
CompletableFuture<String> future = new CompletableFuture<>();
// 2.开启线程计算任务结果,并设置
new Thread(() -> {
// 2.1休眠3s,模拟任务计算
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 2.2设置计算结果到future
System.out.println("----" + Thread.currentThread().getName() + " set future result----");
future.completeExceptionally(new RuntimeException("error exception"));
}, "thread-1").start();
// 3.等待计算结果
System.out.println("---main thread wait future result---");
System.out.println(future.get());
// System.out.println(future.get(1000,TimeUnit.MILLISECONDS));
System.out.println("---main thread got future result---");
System.out.println("one end ------------");
System.out.println();
}
/**
* two start ------------
* ---main thread wait future result---
* ----thread-1 set future result----
* default
* ---main thread got future result---
* two end ------------
*/
public static void two() throws InterruptedException, ExecutionException {
System.out.println("two start ------------");
// 1.创建一个CompletableFuture对象
CompletableFuture<String> future = new CompletableFuture<>();
// 2.开启线程计算任务结果,并设置
new Thread(() -> {
// 2.1休眠3s,模拟任务计算
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 2.2设置计算结果到future
System.out.println("----" + Thread.currentThread().getName() + " set future result----");
future.completeExceptionally(new RuntimeException("error exception"));
}, "thread-1").start();
;
// 3.等待计算结果
System.out.println("---main thread wait future result---");
System.out.println(future.exceptionally(t -> "default").get());// 默认值
// System.out.println(future.get(1000,TimeUnit.MILLISECONDS));
System.out.println("---main thread got future result---");
System.out.println("two end ------------");
System.out.println();
}
public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException {
// one();
two();
}
}
|
import java.nio.file.*;
public class Main {
public static void main(String[] args) {
try {
Path catalogCopy = Paths.get(args[0]);
Path catalogCopyPlace = Paths.get(args[1]);
Files.walkFileTree(catalogCopy,
new CopyDirVisitor(catalogCopy, catalogCopyPlace, StandardCopyOption.REPLACE_EXISTING));
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
|
package com.fight.job.admin.controller;
import com.fight.job.admin.bean.convert.LogInfoConvert;
import com.fight.job.admin.service.LogInfoService;
import com.fight.job.admin.util.WebResult;
import com.fight.job.admin.util.WebResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* LogInfoController
* 日志Controller类
*
* @author luo
*/
@RestController
@RequestMapping("/log")
public class LogInfoController {
@Autowired
LogInfoService logService;
@GetMapping("/list")
public WebResult getLogList() {
return WebResultUtil.succcess(LogInfoConvert.convertToBeanList(logService.getJobList()));
}
@GetMapping("/list/{groupId}")
public WebResult getLogList(@PathVariable String groupId) {
return WebResultUtil.succcess(LogInfoConvert.convertToBeanList(logService.getJobList(groupId)));
}
}
|
package com.javarush.task.task18.task1812;
import java.io.IOException;
public interface AmigoOutputStream {
void flush() throws IOException;
void write(int b) throws IOException;
void write(byte[] b) throws IOException;
void write(byte[] b, int off, int len) throws IOException;
void close() throws IOException;
}
public class QuestionFileOutputStream implements AmigoOutputStream {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
private AmigoOutputStream a;
public QuestionFileOutputStream(AmigoOutputStream s) {
this.a = s;
}
public void flush() throws IOException {
a.flush();
}
public void write(int b) throws IOException {
a.write(b);
}
public void write(byte[] b) throws IOException {
a.write(b);
}
public void write(byte[] b, int off, int len) throws IOException {
a.write(b, off, len);
}
public void close() throws IOException {
System.out.println("Вы действительно хотите закрыть поток? Д/Н");
String s = reader.readLine();
if (s.equals("Д"))
a.close();
}
}
|
package com.tencent.mm.ui.chatting.b;
import com.tencent.mm.ui.chatting.b.b.m;
import com.tencent.mm.ui.chatting.b.j.6;
import com.tencent.mm.ui.widget.snackbar.a$c;
class j$6$1 implements a$c {
final /* synthetic */ 6 tOX;
j$6$1(6 6) {
this.tOX = 6;
}
public final void onShow() {
this.tOX.tOS.cuQ();
this.tOX.tOS.tOQ.setVisibility(4);
}
public final void onHide() {
this.tOX.tOS.cuQ();
}
public final void aSx() {
((m) this.tOX.tOS.bAG.O(m.class)).cvj();
}
}
|
package br.com.gmarques.devamil.bean;
import java.util.Date;
public class Action {
private Date time;
private String weapon;
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
public String getWeapon() {
return weapon;
}
public void setWeapon(String weapon) {
this.weapon = weapon;
}
}
|
public class Clefts extends Thing {
public Clefts(String name, String direction, ThingActions... thingActions) {
super(name,direction);
addThingAction(thingActions);
}
@Override
public void addThingAction(ThingActions... thingActions) {
super.addThingAction(thingActions);
}
public void action() {
}
public void getDescribe() {
System.out.print(" таинсвенные темные");
}
}
|
package cars;
import people.Driver;
public class Car {
private int engine_power;
public Car(int driving_experience, int car_accident, int engine_power){
new Driver(driving_experience,car_accident);
this.engine_power = engine_power;
System.out.println(String.format("The engine 111power of my car is %d horsepower.", engine_power));
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.commerceservices.order.strategies.impl;
import de.hybris.platform.commerceservices.enums.QuoteAction;
import de.hybris.platform.commerceservices.enums.QuoteUserType;
import de.hybris.platform.commerceservices.order.strategies.QuoteStateSelectionStrategy;
import de.hybris.platform.commerceservices.order.strategies.QuoteUserTypeIdentificationStrategy;
import de.hybris.platform.core.enums.QuoteState;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;
import de.hybris.platform.core.model.user.UserModel;
import org.springframework.beans.factory.annotation.Required;
import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNullStandardMessage;
/**
* Default implementation of {@link QuoteStateSelectionStrategy}
*/
public class DefaultQuoteStateSelectionStrategy implements QuoteStateSelectionStrategy
{
private Map<QuoteUserType, Map<QuoteAction, Set<QuoteState>>> userTypeActionStateMap;
private Map<QuoteUserType, Map<QuoteState, Set<QuoteAction>>> userTypeStateActionMap;
private Map<QuoteUserType, Map<QuoteAction, QuoteState>> userTypeActionStateTransitionMap;
private QuoteUserTypeIdentificationStrategy quoteUserTypeIdentificationStrategy;
@Override
public Set<QuoteState> getAllowedStatesForAction(final QuoteAction action, final UserModel userModel)
{
validateParameterNotNullStandardMessage("action", action);
validateParameterNotNullStandardMessage("userModel", userModel);
final Optional<QuoteUserType> currentQuoteUserType = getQuoteUserTypeIdentificationStrategy()
.getCurrentQuoteUserType(userModel);
if (currentQuoteUserType.isPresent())
{
final Set<QuoteState> allowedStates = getUserTypeActionStateMap().get(currentQuoteUserType.get()).get(action);
if (allowedStates != null)
{
return allowedStates;
}
}
return Collections.emptySet();
}
@Override
public Set<QuoteAction> getAllowedActionsForState(final QuoteState state, final UserModel userModel)
{
validateParameterNotNullStandardMessage("state", state);
validateParameterNotNullStandardMessage("userModel", userModel);
final Optional<QuoteUserType> currentQuoteUserType = getQuoteUserTypeIdentificationStrategy().getCurrentQuoteUserType(userModel);
if (currentQuoteUserType.isPresent())
{
final Set<QuoteAction> allowedActions = getUserTypeStateActionMap().get(currentQuoteUserType.get()).get(state);
if (allowedActions != null)
{
return allowedActions;
}
}
return Collections.emptySet();
}
@Override
public Optional<QuoteState> getTransitionStateForAction(final QuoteAction action, final UserModel userModel)
{
validateParameterNotNullStandardMessage("action", action);
validateParameterNotNullStandardMessage("userModel", userModel);
final Optional<QuoteUserType> currentQuoteUserType = getQuoteUserTypeIdentificationStrategy()
.getCurrentQuoteUserType(userModel);
if (currentQuoteUserType.isPresent())
{
final QuoteState transitionState = getUserTypeActionStateTransitionMap().get(currentQuoteUserType.get()).get(action);
if (transitionState != null)
{
return Optional.of(transitionState);
}
}
return Optional.empty();
}
protected Map<QuoteUserType, Map<QuoteState, Set<QuoteAction>>> getInvertedNestedMap(
final Map<QuoteUserType, Map<QuoteAction, Set<QuoteState>>> userTypeActionStateMap)
{
final Map<QuoteUserType, Map<QuoteState, Set<QuoteAction>>> userTypeStateActionMap = new HashMap();
for (final Entry<QuoteUserType, Map<QuoteAction, Set<QuoteState>>> entry : userTypeActionStateMap.entrySet())
{
userTypeStateActionMap.put(entry.getKey(), getInvertedMap(entry.getValue()));
}
return userTypeStateActionMap;
}
protected Map<QuoteState, Set<QuoteAction>> getInvertedMap(final Map<QuoteAction, Set<QuoteState>> actionStateMap)
{
final Map<QuoteState, Set<QuoteAction>> stateActionMap = new HashMap();
for (final QuoteAction action : actionStateMap.keySet())
{
final Set<QuoteState> states = actionStateMap.get(action);
for (final QuoteState state : states)
{
if (!stateActionMap.containsKey(state))
{
stateActionMap.put(state, new HashSet());
}
final Set<QuoteAction> allowedActions = stateActionMap.get(state);
allowedActions.add(action);
}
}
return stateActionMap;
}
protected Map<QuoteUserType, Map<QuoteAction, Set<QuoteState>>> getUserTypeActionStateMap()
{
return userTypeActionStateMap;
}
@Required
public void setUserTypeActionStateMap(final Map<QuoteUserType, Map<QuoteAction, Set<QuoteState>>> quoteUserTypeActionStateMap)
{
this.userTypeActionStateMap = quoteUserTypeActionStateMap;
// populates the inverted map (state,action) too
userTypeStateActionMap = getInvertedNestedMap(quoteUserTypeActionStateMap);
}
protected Map<QuoteUserType, Map<QuoteState, Set<QuoteAction>>> getUserTypeStateActionMap()
{
return userTypeStateActionMap;
}
protected Map<QuoteUserType, Map<QuoteAction, QuoteState>> getUserTypeActionStateTransitionMap()
{
return userTypeActionStateTransitionMap;
}
@Required
public void setUserTypeActionStateTransitionMap(
final Map<QuoteUserType, Map<QuoteAction, QuoteState>> userTypeActionStateTransitionMap)
{
this.userTypeActionStateTransitionMap = userTypeActionStateTransitionMap;
}
protected QuoteUserTypeIdentificationStrategy getQuoteUserTypeIdentificationStrategy()
{
return quoteUserTypeIdentificationStrategy;
}
@Required
public void setQuoteUserTypeIdentificationStrategy(
final QuoteUserTypeIdentificationStrategy quoteUserTypeIdentificationStrategy)
{
this.quoteUserTypeIdentificationStrategy = quoteUserTypeIdentificationStrategy;
}
}
|
package servlets;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import beans.User;
public class Access implements Filter {
public void init(FilterConfig config) throws ServletException {
}
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
HttpSession session = request.getSession();
//System.out.println(session.getAttribute("user"));
if(session.getAttribute("user") != null) { // session.getAttribute("user") != null
if (((User) session.getAttribute("user")).connected()) {
chain.doFilter(request, response);
}
}
else {
request.getRequestDispatcher("/login.html").forward(request, response);
}
}
public void destroy() {
}
}
|
package com.example.demo.Config;
import com.example.demo.entity.Animal;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "configure.czy")
public class Config {
private float offset = 0;
private int age = 10;
private String name = "";
Animal animal = new Animal();
public float getOffset() {
return offset;
}
public void setOffset(float offset) {
this.offset = offset;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Animal getAnimal() {
return animal;
}
public void setAnimal(Animal animal) {
this.animal = animal;
}
}
|
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.support.LdapContextSource;
import org.springframework.security.ldap.SpringSecurityAuthenticationSource;
public class TestLdap {
/**
* @param args
*/
static LdapTemplate ldapTemplate = null;
public static void main(String[] args) {
if (!loginLDAP("admin", "spr")){ // User ID and Application ID hard coded
System.out.println("false");
} else {
System.out.println("true");
}
}
public static boolean loginLDAP (String userId, String applicationId) {
String password = "password"; // Password Hard coded
if (getLdapTemplate(applicationId) == null) return false;
if (!(ldapTemplate.authenticate("", "(uid=" + userId + ")", password))){
System.out.println("authenticate block***");
return false;
}
return true;
}
public static LdapTemplate getLdapTemplate(String applicationId) {
if (ldapTemplate == null) {
try {
/*Properties properties = dbConPool.getConf(ArrayLIMSConfigConstants.APP_PROPERTY_FILE_NAME);
if (properties == null) return null; // cannot login without finding conf file
*/
String uri = "ldap://ldap.gene.com:389"; // Ldap uri
String base = "ou=people,dc=gene,dc=com";
LdapContextSource contextSource = new LdapContextSource(); // note: reading LDAP address from conf file can be a minimal threat, but taking that risk for now.
contextSource.setUrl(uri);
contextSource.setBase(base);
contextSource.setAuthenticationSource(new SpringSecurityAuthenticationSource());
contextSource.afterPropertiesSet();
ldapTemplate = new LdapTemplate(contextSource);
} catch (Exception e) {
return null;
}
}
return ldapTemplate;
}
}
|
package com.bdb.model;
import java.util.List;
public class ObjectNestedCollection {
public ObjectNestedCollection() {
}
public List getList() {
return list;
}
public Object getObject() {
return object;
}
public void setList(List list) {
this.list = list;
}
public void setObject(Object object) {
this.object = object;
}
private Object object;
private List list;
} |
package com.utpol.utpol;
import java.util.List;
/**
* The type Gov info.
*/
public class GovInfo {
private String party;
private String districtNumber;
private String leadPos;
private String location;
private List<CommitteeDetail> committees;
private List<String> interns;
private Boolean isSenate;
public GovInfo(){
}
public String getParty() {
return party;
}
public void setParty(String party) {
this.party = party;
}
public String getDistrictNumber() {
return districtNumber;
}
public void setDistrictNumber(String districtNumber) {
this.districtNumber = districtNumber;
}
public String getLeadPos() {
return leadPos;
}
public void setLeadPos(String leadPos) {
this.leadPos = leadPos;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public List<CommitteeDetail> getCommittees() {
return committees;
}
public void setCommittees(List<CommitteeDetail> committees) {
this.committees = committees;
}
public List<String> getInterns() {
return interns;
}
public void setInterns(List<String> interns) {
this.interns = interns;
}
public Boolean getSenate() {
return isSenate;
}
public void setSenate(Boolean senate) {
isSenate = senate;
}
}
|
package it.usi.xframe.xas.bfimpl;
/**
* Bean implementation class for Enterprise Bean: XasEcho
*/
public class XasEchoBean
extends it.usi.xframe.xas.bfimpl.XasEchoServiceFacade
implements javax.ejb.SessionBean {
private javax.ejb.SessionContext mySessionCtx;
/**
* getSessionContext
*/
public javax.ejb.SessionContext getSessionContext() {
return mySessionCtx;
}
/**
* setSessionContext
*/
public void setSessionContext(javax.ejb.SessionContext ctx) {
mySessionCtx = ctx;
}
/**
* ejbCreate
*/
public void ejbCreate() throws javax.ejb.CreateException {
}
/**
* ejbActivate
*/
public void ejbActivate() {
}
/**
* ejbPassivate
*/
public void ejbPassivate() {
}
/**
* ejbRemove
*/
public void ejbRemove() {
}
}
|
/*
* This file is part of LeagueLib.
* LeagueLib is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LeagueLib is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LeagueLib. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lolRiver.achimala.leaguelib.connection;
public enum LeagueServer {
NORTH_AMERICA("NA", "North America"),
EUROPE_WEST("EUW", "Europe West"),
EUROPE_NORDIC_AND_EAST("EUNE", "Europe Nordic & East"),
BRAZIL("BR", "Brazil"),
KOREA("KR", "Korea"),
LATIN_AMERICA_NORTH("LAN", "Latin America North"),
LATIN_AMERICA_SOUTH("LAS", "Latin America South"),
OCEANIA("OCE", "Oceania");
// Garena servers...
// PublicBetaEnvironment
private String _serverCode, _publicName;
private LeagueServer(String serverCode, String publicName) {
_serverCode = serverCode;
_publicName = publicName;
}
public static LeagueServer findServerByCode(String code) {
for(LeagueServer server : LeagueServer.values())
if(server.getServerCode().equalsIgnoreCase(code))
return server;
return null;
}
public String getServerCode() {
return _serverCode;
}
public String getPublicName() {
return _publicName;
}
public String toString() {
return "<LeagueServer:" + _publicName + " (" + _serverCode + ")>";
}
}
|
package io.muic.ooc.Commands;
import io.muic.ooc.Items.Potion;
import io.muic.ooc.Player;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Created by karn806 on 2/4/17.
*/
public class UseCommandTest {
@Test
public void apply() throws Exception {
Player player = new Player();
Potion potion = new Potion();
potion.setHealPoint(5);
player.setHp(10);
}
} |
package com.sporsimdi.action.facadeBean;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import com.sporsimdi.action.facade.TahakkukDetayFacade;
import com.sporsimdi.action.util.UtilDate;
import com.sporsimdi.model.entity.Tahakkuk;
import com.sporsimdi.model.entity.TahakkukDetay;
import com.sporsimdi.model.type.Status;
@Stateless
public class TahakkukDetayFacadeBean implements TahakkukDetayFacade {
@PersistenceContext(unitName = "sporsimdi")
EntityManager entityManager;
@Override
public void persist(TahakkukDetay tahakkukDetay) {
entityManager.persist(tahakkukDetay);
}
@Override
public void merge(TahakkukDetay tahakkukDetay) {
entityManager.merge(tahakkukDetay);
}
@Override
public void remove(TahakkukDetay tahakkukDetay) {
entityManager.remove(tahakkukDetay);
}
@Override
public void delete(TahakkukDetay tahakkukDetay) {
tahakkukDetay.setStatus(Status.PASSIVE);
entityManager.merge(tahakkukDetay);
}
@Override
public TahakkukDetay findById(long id) {
return entityManager.find(TahakkukDetay.class, id);
}
@SuppressWarnings("unchecked")
@Override
public List<TahakkukDetay> listAll() {
return entityManager.createQuery("select t from TahakkukDetay t").getResultList();
}
@SuppressWarnings("unchecked")
@Override
public List<TahakkukDetay> listByTahakkuk(Tahakkuk tahakkuk) {
return entityManager.createQuery("select td from TahakkukDetay td join fetch td.tahakkuk t where td.tahakkuk = :tahakkuk order by td.taksitNo")
.setParameter("tahakkuk", tahakkuk).getResultList();
}
@Override
public List<TahakkukDetay> listByTahakkukVadeTarihi(Tahakkuk tahakkuk, Date vadeTarihi) {
Format frm = new SimpleDateFormat("MM");
return listByTahakkukYilAy(tahakkuk, frm.format(vadeTarihi));
}
@SuppressWarnings("unchecked")
@Override
public List<TahakkukDetay> listByTahakkukYilAy(Tahakkuk tahakkuk, String yilAy) {
return entityManager
.createQuery(
"select td from TahakkukDetay td " + "join fetch td.tahakkuk t " + "where td.tahakkuk = :tahakkuk "
+ " and to_char(td.vadeTarihi,'YYYYMM') = :vadeTarihi " + "order by td.taksitNo").setParameter("tahakkuk", tahakkuk)
.setParameter("vadeTarihi", yilAy).getResultList();
}
@SuppressWarnings("unchecked")
@Override
public List<TahakkukDetay> listByTahakkukBetweenDates(Tahakkuk tahakkuk, UtilDate dateBegin, UtilDate dateEnd) {
/*
* UtilDate date = new UtilDate(); date.set(2013, 9, 19); UtilDate date2
* = new UtilDate(); date2.set(2013, 9, 20);
*/return entityManager
.createQuery(
"select td from TahakkukDetay td " + "join fetch td.tahakkuk t " + "where td.tahakkuk = :tahakkuk "
+ " and vadeTarihi between :dateBegin and :dateEnd " + "order by td.taksitNo").setParameter("tahakkuk", tahakkuk)
.setParameter("dateBegin", dateBegin.getTime()).setParameter("dateEnd", dateEnd.getTime()).getResultList();
// .setParameter("dateBegin", date.getTime()).setParameter("dateEnd",
// date2.getTime()).getResultList();
}
}
|
package com.bytedance.platform.godzilla.d;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public final class g {
public static b a;
public static h b;
private static final int c;
private static final int d;
private static b e;
private static h f = new h() {
public final void a(Throwable param1Throwable) {
if (g.b != null)
g.b.a(param1Throwable);
}
};
private static volatile ThreadPoolExecutor g;
private static volatile ThreadPoolExecutor h;
private static volatile ScheduledThreadPoolExecutor i;
private static volatile ThreadPoolExecutor j;
public static ThreadPoolExecutor a() {
// Byte code:
// 0: getstatic com/bytedance/platform/godzilla/d/g.g : Ljava/util/concurrent/ThreadPoolExecutor;
// 3: ifnonnull -> 168
// 6: ldc com/bytedance/platform/godzilla/d/g
// 8: monitorenter
// 9: getstatic com/bytedance/platform/godzilla/d/g.g : Ljava/util/concurrent/ThreadPoolExecutor;
// 12: ifnonnull -> 156
// 15: getstatic com/bytedance/platform/godzilla/d/g.e : Lcom/bytedance/platform/godzilla/d/b;
// 18: ifnull -> 108
// 21: getstatic com/bytedance/platform/godzilla/d/g.e : Lcom/bytedance/platform/godzilla/d/b;
// 24: getfield a : Lcom/bytedance/platform/godzilla/d/g$a;
// 27: ifnull -> 108
// 30: new com/bytedance/platform/godzilla/d/e
// 33: dup
// 34: getstatic com/bytedance/platform/godzilla/d/g.e : Lcom/bytedance/platform/godzilla/d/b;
// 37: getfield a : Lcom/bytedance/platform/godzilla/d/g$a;
// 40: getfield a : I
// 43: getstatic com/bytedance/platform/godzilla/d/g.e : Lcom/bytedance/platform/godzilla/d/b;
// 46: getfield a : Lcom/bytedance/platform/godzilla/d/g$a;
// 49: getfield b : I
// 52: getstatic com/bytedance/platform/godzilla/d/g.e : Lcom/bytedance/platform/godzilla/d/b;
// 55: getfield a : Lcom/bytedance/platform/godzilla/d/g$a;
// 58: getfield e : J
// 61: getstatic com/bytedance/platform/godzilla/d/g.e : Lcom/bytedance/platform/godzilla/d/b;
// 64: getfield a : Lcom/bytedance/platform/godzilla/d/g$a;
// 67: getfield f : Ljava/util/concurrent/TimeUnit;
// 70: getstatic com/bytedance/platform/godzilla/d/g.e : Lcom/bytedance/platform/godzilla/d/b;
// 73: getfield a : Lcom/bytedance/platform/godzilla/d/g$a;
// 76: getfield c : Ljava/util/concurrent/BlockingQueue;
// 79: getstatic com/bytedance/platform/godzilla/d/g.e : Lcom/bytedance/platform/godzilla/d/b;
// 82: getfield a : Lcom/bytedance/platform/godzilla/d/g$a;
// 85: getfield g : Ljava/util/concurrent/ThreadFactory;
// 88: getstatic com/bytedance/platform/godzilla/d/g.e : Lcom/bytedance/platform/godzilla/d/b;
// 91: getfield a : Lcom/bytedance/platform/godzilla/d/g$a;
// 94: getfield d : Ljava/util/concurrent/RejectedExecutionHandler;
// 97: ldc 'platform-io'
// 99: invokespecial <init> : (IIJLjava/util/concurrent/TimeUnit;Ljava/util/concurrent/BlockingQueue;Ljava/util/concurrent/ThreadFactory;Ljava/util/concurrent/RejectedExecutionHandler;Ljava/lang/String;)V
// 102: putstatic com/bytedance/platform/godzilla/d/g.g : Ljava/util/concurrent/ThreadPoolExecutor;
// 105: goto -> 156
// 108: new com/bytedance/platform/godzilla/d/e
// 111: dup
// 112: iconst_0
// 113: sipush #128
// 116: ldc2_w 60
// 119: getstatic java/util/concurrent/TimeUnit.SECONDS : Ljava/util/concurrent/TimeUnit;
// 122: new java/util/concurrent/SynchronousQueue
// 125: dup
// 126: invokespecial <init> : ()V
// 129: new com/bytedance/platform/godzilla/d/a
// 132: dup
// 133: ldc 'platform-io'
// 135: getstatic com/bytedance/platform/godzilla/d/g.f : Lcom/bytedance/platform/godzilla/d/h;
// 138: invokespecial <init> : (Ljava/lang/String;Lcom/bytedance/platform/godzilla/d/h;)V
// 141: new com/bytedance/platform/godzilla/d/g$2
// 144: dup
// 145: invokespecial <init> : ()V
// 148: ldc 'platform-io'
// 150: invokespecial <init> : (IIJLjava/util/concurrent/TimeUnit;Ljava/util/concurrent/BlockingQueue;Ljava/util/concurrent/ThreadFactory;Ljava/util/concurrent/RejectedExecutionHandler;Ljava/lang/String;)V
// 153: putstatic com/bytedance/platform/godzilla/d/g.g : Ljava/util/concurrent/ThreadPoolExecutor;
// 156: ldc com/bytedance/platform/godzilla/d/g
// 158: monitorexit
// 159: goto -> 168
// 162: astore_0
// 163: ldc com/bytedance/platform/godzilla/d/g
// 165: monitorexit
// 166: aload_0
// 167: athrow
// 168: getstatic com/bytedance/platform/godzilla/d/g.g : Ljava/util/concurrent/ThreadPoolExecutor;
// 171: areturn
// Exception table:
// from to target type
// 9 105 162 finally
// 108 156 162 finally
// 156 159 162 finally
// 163 166 162 finally
}
public static ThreadPoolExecutor b() {
// Byte code:
// 0: getstatic com/bytedance/platform/godzilla/d/g.h : Ljava/util/concurrent/ThreadPoolExecutor;
// 3: ifnonnull -> 193
// 6: ldc com/bytedance/platform/godzilla/d/g
// 8: monitorenter
// 9: getstatic com/bytedance/platform/godzilla/d/g.h : Ljava/util/concurrent/ThreadPoolExecutor;
// 12: ifnonnull -> 181
// 15: getstatic com/bytedance/platform/godzilla/d/g.e : Lcom/bytedance/platform/godzilla/d/b;
// 18: ifnull -> 123
// 21: getstatic com/bytedance/platform/godzilla/d/g.e : Lcom/bytedance/platform/godzilla/d/b;
// 24: getfield b : Lcom/bytedance/platform/godzilla/d/g$a;
// 27: ifnull -> 123
// 30: new com/bytedance/platform/godzilla/d/e
// 33: dup
// 34: getstatic com/bytedance/platform/godzilla/d/g.e : Lcom/bytedance/platform/godzilla/d/b;
// 37: getfield b : Lcom/bytedance/platform/godzilla/d/g$a;
// 40: getfield a : I
// 43: getstatic com/bytedance/platform/godzilla/d/g.e : Lcom/bytedance/platform/godzilla/d/b;
// 46: getfield b : Lcom/bytedance/platform/godzilla/d/g$a;
// 49: getfield b : I
// 52: getstatic com/bytedance/platform/godzilla/d/g.e : Lcom/bytedance/platform/godzilla/d/b;
// 55: getfield b : Lcom/bytedance/platform/godzilla/d/g$a;
// 58: getfield e : J
// 61: getstatic com/bytedance/platform/godzilla/d/g.e : Lcom/bytedance/platform/godzilla/d/b;
// 64: getfield b : Lcom/bytedance/platform/godzilla/d/g$a;
// 67: getfield f : Ljava/util/concurrent/TimeUnit;
// 70: getstatic com/bytedance/platform/godzilla/d/g.e : Lcom/bytedance/platform/godzilla/d/b;
// 73: getfield b : Lcom/bytedance/platform/godzilla/d/g$a;
// 76: getfield c : Ljava/util/concurrent/BlockingQueue;
// 79: getstatic com/bytedance/platform/godzilla/d/g.e : Lcom/bytedance/platform/godzilla/d/b;
// 82: getfield b : Lcom/bytedance/platform/godzilla/d/g$a;
// 85: getfield g : Ljava/util/concurrent/ThreadFactory;
// 88: getstatic com/bytedance/platform/godzilla/d/g.e : Lcom/bytedance/platform/godzilla/d/b;
// 91: getfield b : Lcom/bytedance/platform/godzilla/d/g$a;
// 94: getfield d : Ljava/util/concurrent/RejectedExecutionHandler;
// 97: ldc 'platform-default'
// 99: invokespecial <init> : (IIJLjava/util/concurrent/TimeUnit;Ljava/util/concurrent/BlockingQueue;Ljava/util/concurrent/ThreadFactory;Ljava/util/concurrent/RejectedExecutionHandler;Ljava/lang/String;)V
// 102: astore_0
// 103: aload_0
// 104: putstatic com/bytedance/platform/godzilla/d/g.h : Ljava/util/concurrent/ThreadPoolExecutor;
// 107: aload_0
// 108: getstatic com/bytedance/platform/godzilla/d/g.e : Lcom/bytedance/platform/godzilla/d/b;
// 111: getfield b : Lcom/bytedance/platform/godzilla/d/g$a;
// 114: getfield h : Z
// 117: invokevirtual allowCoreThreadTimeOut : (Z)V
// 120: goto -> 181
// 123: new com/bytedance/platform/godzilla/d/e
// 126: dup
// 127: getstatic com/bytedance/platform/godzilla/d/g.d : I
// 130: iconst_4
// 131: invokestatic min : (II)I
// 134: getstatic com/bytedance/platform/godzilla/d/g.d : I
// 137: iconst_4
// 138: invokestatic min : (II)I
// 141: ldc2_w 60
// 144: getstatic java/util/concurrent/TimeUnit.SECONDS : Ljava/util/concurrent/TimeUnit;
// 147: new java/util/concurrent/LinkedBlockingQueue
// 150: dup
// 151: invokespecial <init> : ()V
// 154: new com/bytedance/platform/godzilla/d/a
// 157: dup
// 158: ldc 'platform-default'
// 160: getstatic com/bytedance/platform/godzilla/d/g.f : Lcom/bytedance/platform/godzilla/d/h;
// 163: invokespecial <init> : (Ljava/lang/String;Lcom/bytedance/platform/godzilla/d/h;)V
// 166: ldc 'platform-default'
// 168: invokespecial <init> : (IIJLjava/util/concurrent/TimeUnit;Ljava/util/concurrent/BlockingQueue;Ljava/util/concurrent/ThreadFactory;Ljava/lang/String;)V
// 171: astore_0
// 172: aload_0
// 173: putstatic com/bytedance/platform/godzilla/d/g.h : Ljava/util/concurrent/ThreadPoolExecutor;
// 176: aload_0
// 177: iconst_1
// 178: invokevirtual allowCoreThreadTimeOut : (Z)V
// 181: ldc com/bytedance/platform/godzilla/d/g
// 183: monitorexit
// 184: goto -> 193
// 187: astore_0
// 188: ldc com/bytedance/platform/godzilla/d/g
// 190: monitorexit
// 191: aload_0
// 192: athrow
// 193: getstatic com/bytedance/platform/godzilla/d/g.h : Ljava/util/concurrent/ThreadPoolExecutor;
// 196: areturn
// Exception table:
// from to target type
// 9 120 187 finally
// 123 181 187 finally
// 181 184 187 finally
// 188 191 187 finally
}
public static ScheduledExecutorService c() {
// Byte code:
// 0: getstatic com/bytedance/platform/godzilla/d/g.i : Ljava/util/concurrent/ScheduledThreadPoolExecutor;
// 3: ifnonnull -> 122
// 6: ldc com/bytedance/platform/godzilla/d/g
// 8: monitorenter
// 9: getstatic com/bytedance/platform/godzilla/d/g.i : Ljava/util/concurrent/ScheduledThreadPoolExecutor;
// 12: ifnonnull -> 110
// 15: getstatic com/bytedance/platform/godzilla/d/g.e : Lcom/bytedance/platform/godzilla/d/b;
// 18: ifnull -> 78
// 21: getstatic com/bytedance/platform/godzilla/d/g.e : Lcom/bytedance/platform/godzilla/d/b;
// 24: getfield c : Lcom/bytedance/platform/godzilla/d/g$a;
// 27: ifnull -> 78
// 30: new com/bytedance/platform/godzilla/d/f
// 33: dup
// 34: getstatic com/bytedance/platform/godzilla/d/g.e : Lcom/bytedance/platform/godzilla/d/b;
// 37: getfield c : Lcom/bytedance/platform/godzilla/d/g$a;
// 40: getfield a : I
// 43: getstatic com/bytedance/platform/godzilla/d/g.e : Lcom/bytedance/platform/godzilla/d/b;
// 46: getfield c : Lcom/bytedance/platform/godzilla/d/g$a;
// 49: getfield g : Ljava/util/concurrent/ThreadFactory;
// 52: ldc 'platform-schedule'
// 54: invokespecial <init> : (ILjava/util/concurrent/ThreadFactory;Ljava/lang/String;)V
// 57: putstatic com/bytedance/platform/godzilla/d/g.i : Ljava/util/concurrent/ScheduledThreadPoolExecutor;
// 60: getstatic com/bytedance/platform/godzilla/d/g.i : Ljava/util/concurrent/ScheduledThreadPoolExecutor;
// 63: getstatic com/bytedance/platform/godzilla/d/g.e : Lcom/bytedance/platform/godzilla/d/b;
// 66: getfield c : Lcom/bytedance/platform/godzilla/d/g$a;
// 69: getfield h : Z
// 72: invokevirtual allowCoreThreadTimeOut : (Z)V
// 75: goto -> 110
// 78: new com/bytedance/platform/godzilla/d/f
// 81: dup
// 82: iconst_1
// 83: new com/bytedance/platform/godzilla/d/a
// 86: dup
// 87: ldc 'platform-schedule'
// 89: getstatic com/bytedance/platform/godzilla/d/g.f : Lcom/bytedance/platform/godzilla/d/h;
// 92: invokespecial <init> : (Ljava/lang/String;Lcom/bytedance/platform/godzilla/d/h;)V
// 95: ldc 'platform-schedule'
// 97: invokespecial <init> : (ILjava/util/concurrent/ThreadFactory;Ljava/lang/String;)V
// 100: putstatic com/bytedance/platform/godzilla/d/g.i : Ljava/util/concurrent/ScheduledThreadPoolExecutor;
// 103: getstatic com/bytedance/platform/godzilla/d/g.i : Ljava/util/concurrent/ScheduledThreadPoolExecutor;
// 106: iconst_1
// 107: invokevirtual allowCoreThreadTimeOut : (Z)V
// 110: ldc com/bytedance/platform/godzilla/d/g
// 112: monitorexit
// 113: goto -> 122
// 116: astore_0
// 117: ldc com/bytedance/platform/godzilla/d/g
// 119: monitorexit
// 120: aload_0
// 121: athrow
// 122: getstatic com/bytedance/platform/godzilla/d/g.i : Ljava/util/concurrent/ScheduledThreadPoolExecutor;
// 125: areturn
// 126: astore_0
// 127: goto -> 110
// Exception table:
// from to target type
// 9 60 116 finally
// 60 75 126 java/lang/Exception
// 60 75 116 finally
// 78 103 116 finally
// 103 110 126 java/lang/Exception
// 103 110 116 finally
// 110 113 116 finally
// 117 120 116 finally
}
public static ThreadPoolExecutor d() {
// Byte code:
// 0: getstatic com/bytedance/platform/godzilla/d/g.j : Ljava/util/concurrent/ThreadPoolExecutor;
// 3: ifnonnull -> 156
// 6: ldc com/bytedance/platform/godzilla/d/g
// 8: monitorenter
// 9: getstatic com/bytedance/platform/godzilla/d/g.j : Ljava/util/concurrent/ThreadPoolExecutor;
// 12: ifnonnull -> 144
// 15: getstatic com/bytedance/platform/godzilla/d/g.e : Lcom/bytedance/platform/godzilla/d/b;
// 18: ifnull -> 98
// 21: getstatic com/bytedance/platform/godzilla/d/g.e : Lcom/bytedance/platform/godzilla/d/b;
// 24: getfield d : Lcom/bytedance/platform/godzilla/d/g$a;
// 27: ifnull -> 98
// 30: new com/bytedance/platform/godzilla/d/e
// 33: dup
// 34: iconst_1
// 35: iconst_1
// 36: getstatic com/bytedance/platform/godzilla/d/g.e : Lcom/bytedance/platform/godzilla/d/b;
// 39: getfield d : Lcom/bytedance/platform/godzilla/d/g$a;
// 42: getfield e : J
// 45: getstatic com/bytedance/platform/godzilla/d/g.e : Lcom/bytedance/platform/godzilla/d/b;
// 48: getfield d : Lcom/bytedance/platform/godzilla/d/g$a;
// 51: getfield f : Ljava/util/concurrent/TimeUnit;
// 54: getstatic com/bytedance/platform/godzilla/d/g.e : Lcom/bytedance/platform/godzilla/d/b;
// 57: getfield d : Lcom/bytedance/platform/godzilla/d/g$a;
// 60: getfield c : Ljava/util/concurrent/BlockingQueue;
// 63: getstatic com/bytedance/platform/godzilla/d/g.e : Lcom/bytedance/platform/godzilla/d/b;
// 66: getfield d : Lcom/bytedance/platform/godzilla/d/g$a;
// 69: getfield g : Ljava/util/concurrent/ThreadFactory;
// 72: ldc 'platform-single'
// 74: invokespecial <init> : (IIJLjava/util/concurrent/TimeUnit;Ljava/util/concurrent/BlockingQueue;Ljava/util/concurrent/ThreadFactory;Ljava/lang/String;)V
// 77: astore_0
// 78: aload_0
// 79: putstatic com/bytedance/platform/godzilla/d/g.j : Ljava/util/concurrent/ThreadPoolExecutor;
// 82: aload_0
// 83: getstatic com/bytedance/platform/godzilla/d/g.e : Lcom/bytedance/platform/godzilla/d/b;
// 86: getfield d : Lcom/bytedance/platform/godzilla/d/g$a;
// 89: getfield h : Z
// 92: invokevirtual allowCoreThreadTimeOut : (Z)V
// 95: goto -> 144
// 98: new com/bytedance/platform/godzilla/d/e
// 101: dup
// 102: iconst_1
// 103: iconst_1
// 104: ldc2_w 60
// 107: getstatic java/util/concurrent/TimeUnit.SECONDS : Ljava/util/concurrent/TimeUnit;
// 110: new java/util/concurrent/LinkedBlockingQueue
// 113: dup
// 114: invokespecial <init> : ()V
// 117: new com/bytedance/platform/godzilla/d/a
// 120: dup
// 121: ldc 'platform-single'
// 123: getstatic com/bytedance/platform/godzilla/d/g.f : Lcom/bytedance/platform/godzilla/d/h;
// 126: invokespecial <init> : (Ljava/lang/String;Lcom/bytedance/platform/godzilla/d/h;)V
// 129: ldc 'platform-single'
// 131: invokespecial <init> : (IIJLjava/util/concurrent/TimeUnit;Ljava/util/concurrent/BlockingQueue;Ljava/util/concurrent/ThreadFactory;Ljava/lang/String;)V
// 134: astore_0
// 135: aload_0
// 136: putstatic com/bytedance/platform/godzilla/d/g.j : Ljava/util/concurrent/ThreadPoolExecutor;
// 139: aload_0
// 140: iconst_1
// 141: invokevirtual allowCoreThreadTimeOut : (Z)V
// 144: ldc com/bytedance/platform/godzilla/d/g
// 146: monitorexit
// 147: goto -> 156
// 150: astore_0
// 151: ldc com/bytedance/platform/godzilla/d/g
// 153: monitorexit
// 154: aload_0
// 155: athrow
// 156: getstatic com/bytedance/platform/godzilla/d/g.j : Ljava/util/concurrent/ThreadPoolExecutor;
// 159: areturn
// Exception table:
// from to target type
// 9 95 150 finally
// 98 144 150 finally
// 144 147 150 finally
// 151 154 150 finally
}
static {
int i = Runtime.getRuntime().availableProcessors();
c = i;
if (i > 0) {
i = c;
} else {
i = 1;
}
d = i;
}
public static final class a {
public int a;
public int b;
public BlockingQueue<Runnable> c;
public RejectedExecutionHandler d;
public long e;
public TimeUnit f;
public ThreadFactory g;
public boolean h;
}
public static interface b {}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\bytedance\platform\godzilla\d\g.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/ |
package com.collection;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
public class TestSet {
public static void main(String[] args) {
Set<String> setStr = new HashSet<>();
setStr.add("Quoc Long");
setStr.add("Tuan Phuong");
setStr.add("Ngoc Quan");
setStr.add("My Tinh");
setStr.add("Quoc Khanh");
Set<String> setStr2 = new TreeSet<>();
setStr2.add("Quoc Long");
setStr2.add("Tuan Phuong");
setStr2.add("Ngoc Quan");
setStr2.add("My Tinh");
setStr2.add("Quoc Khanh");
System.out.println(setStr);
System.out.println(setStr2);
Set<String> setStr3 = new TreeSet<>();
setStr3.add("1");
setStr3.add("2");
setStr3.add("4");
setStr3.add("12");
setStr3.add("11");
System.out.println(setStr3);
}
}
|
package com.paleimitations.schoolsofmagic.client.screen;
import com.mojang.blaze3d.matrix.MatrixStack;
import com.mojang.blaze3d.systems.RenderSystem;
import com.paleimitations.schoolsofmagic.References;
import com.paleimitations.schoolsofmagic.common.data.books.BookPage;
import com.paleimitations.schoolsofmagic.common.network.LetterPacket;
import com.paleimitations.schoolsofmagic.common.network.PacketHandler;
import com.paleimitations.schoolsofmagic.common.registries.BookPageRegistry;
import com.paleimitations.schoolsofmagic.common.registries.ItemRegistry;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.chat.NarratorChatListener;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.widget.button.Button;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.util.*;
import net.minecraft.util.text.StringTextComponent;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
@OnlyIn(Dist.CLIENT)
public class LetterScreen extends Screen {
private ItemStack stack;
private final int imageHeight = 166;
private final int imageWidth = 156;
public static final ResourceLocation LETTER = new ResourceLocation(References.MODID, "textures/gui/letter_ccw.png");
public static final ResourceLocation CLOSED_ENVELOPE = new ResourceLocation(References.MODID, "textures/gui/envelope_closed.png");
public static final ResourceLocation OPEN_ENVELOPE = new ResourceLocation(References.MODID, "textures/gui/envelope_open.png");
private int leftPos;
private int topPos;
private PlayerEntity player;
private final BookPage letter;
private Button sealButton, questButton, envelopeButton;
private Hand hand;
private int yOffset = 0;
private int phase;
private int tick;
public LetterScreen(ItemStack stack, Hand hand) {
super(NarratorChatListener.NO_TITLE);
this.stack = stack;
this.player = Minecraft.getInstance().player;
this.letter = BookPageRegistry.getBookPage("ccw_letter_1");
this.hand = hand;
}
private void updateButtonVisibility() {
sealButton.visible = (stack!=null && stack.getItem() == ItemRegistry.LETTER_CCW.get() && this.phase == 1 && (!stack.hasTag() || !stack.getTag().getBoolean("opened")));
questButton.visible = (stack!=null && stack.getItem() == ItemRegistry.LETTER_CCW.get() && stack.getOrCreateTag().getBoolean("opened") &&
stack.getOrCreateTag().getBoolean("quest") && tick > 40);
envelopeButton.visible = (stack!=null && stack.getItem() == ItemRegistry.LETTER_CCW.get() && stack.getOrCreateTag().getBoolean("opened") &&
tick > 40);
}
@Override
protected void init() {
super.init();
this.leftPos = (this.width - this.imageWidth) / 2;
this.topPos = (this.height - this.imageHeight) / 2;
sealButton = this.addButton(new Button((width - imageWidth) / 2 + 64, (height - imageHeight) / 2 + 87, 24, 24, StringTextComponent.EMPTY,
(pressable) -> this.openLetter()){
@Override
public void renderButton(MatrixStack matrix, int mouseX, int mouseY, float partial) {
if(visible && isHovered()) {
RenderSystem.color4f(1.0F, 1.0F, 1.0F, 1.0F);
minecraft.getTextureManager().bind(CLOSED_ENVELOPE);
this.blit(matrix, this.x, this.y, 173, 87, 24, 24);
}
}
});
questButton = this.addButton(new Button((width - imageWidth) / 2 + 152, (height - imageHeight) / 2 + 32,30,62, StringTextComponent.EMPTY,
(pressable) -> this.getQuestNote()){
@Override
public void renderButton(MatrixStack matrix, int mouseX, int mouseY, float partial) {
if(visible && isHovered()) {
RenderSystem.color4f(1.0F, 1.0F, 1.0F, 1.0F);
minecraft.getTextureManager().bind(LETTER);
this.blit(matrix, this.x, this.y, 209, 0, 30, 62);
}
}
});
envelopeButton = this.addButton(new Button((width - imageWidth) / 2 - 33, (height - imageHeight) / 2 + 28,37,122, StringTextComponent.EMPTY,
(pressable) -> this.closeLetter()){
@Override
public void renderButton(MatrixStack matrix, int mouseX, int mouseY, float partial) {
if(visible && isHovered()) {
RenderSystem.color4f(1.0F, 1.0F, 1.0F, 1.0F);
minecraft.getTextureManager().bind(LETTER);
this.blit(matrix, this.x, this.y, 216, 63, 37, 122);
}
}
});
this.updateButtonVisibility();
}
private void closeLetter() {
PacketHandler.sendToServer(new LetterPacket(player.getId(), hand, 1));
this.phase = 0;
}
private void getQuestNote() {
PacketHandler.sendToServer(new LetterPacket(player.getId(), hand, 2));
}
private void openLetter() {
this.phase = 2;
this.tick = 0;
}
@Override
public void render(MatrixStack matrix, int mouseX, int mouseY, float partialTick) {
this.stack = player.getItemInHand(hand);
this.updateButtonVisibility();
int offsetWidth = (width - imageWidth) / 2;
int offsetHeight = (height - imageHeight) / 2;
++tick;
if(stack.getOrCreateTag().getBoolean("opened")) {
if(this.tick > 40) {
int xOffset = this.tick < 60? (int) (-30*(-Math.cos(((double)tick-40+partialTick)*Math.PI/20d)-1d)) : 0;
if(stack.getOrCreateTag().getBoolean("quest")) {
RenderSystem.color4f(1.0F, 1.0F, 1.0F, 1.0F);
this.minecraft.getTextureManager().bind(LETTER);
this.blit(matrix,offsetWidth - xOffset + 152, offsetHeight + 32, 179, 0, 30, 62);
}
int xOffset2 = this.tick < 60? (int) (37*(-Math.cos(((double)tick-40+partialTick)*Math.PI/20d)-1d)) : 0;
RenderSystem.color4f(1.0F, 1.0F, 1.0F, 1.0F);
this.minecraft.getTextureManager().bind(LETTER);
this.blit(matrix,offsetWidth - xOffset2 - 33, offsetHeight + 28, 179, 63, 37, 122);
}
if(this.tick<20)
this.yOffset = (int) (height*(-Math.cos(((double)tick+partialTick)*Math.PI/20d)-1d));
else
this.yOffset = 0;
RenderSystem.color4f(1.0F, 1.0F, 1.0F, 1.0F);
this.minecraft.getTextureManager().bind(LETTER);
this.blit(matrix,offsetWidth, offsetHeight - yOffset,0,0, imageWidth, imageHeight);
if(letter!=null)
letter.drawPage(matrix, mouseX - offsetWidth, mouseY - offsetHeight - yOffset, offsetWidth, offsetHeight - yOffset, 20f, true, 0, 15728880, null);
}
else {
if(this.phase == 0) {
if(this.tick<40)
this.yOffset = (int) (height*(-Math.cos(((double)tick+partialTick)*Math.PI/40d)-1d));
else {
this.phase = 1;
this.yOffset = 0;
}
}
if(phase == 2) {
if(this.tick>20&&this.tick<60)
this.yOffset = (int) (height*(Math.cos(((double)tick-20d+partialTick)*Math.PI/40d)-1d));
RenderSystem.color4f(1.0F, 1.0F, 1.0F, 1.0F);
this.minecraft.getTextureManager().bind(OPEN_ENVELOPE);
this.blit(matrix, offsetWidth, offsetHeight - yOffset, 0, 0, imageWidth, imageHeight);
if(tick == 60) {
PacketHandler.sendToServer(new LetterPacket(player.getId(), hand, 0));
tick = 0;
}
}
else {
RenderSystem.color4f(1.0F, 1.0F, 1.0F, 1.0F);
this.minecraft.getTextureManager().bind(CLOSED_ENVELOPE);
this.blit(matrix, offsetWidth, offsetHeight - yOffset, 0, 0, imageWidth, imageHeight);
}
}
super.render(matrix, mouseX, mouseY, partialTick);
}
@Override
public boolean isPauseScreen() {
return false;
}
}
|
//
// Generated by JTB 1.3.2
//
package visitor;
import syntaxtree.*;
import java.util.*;
/**
* Provides default methods which visit each node in the tree in depth-first
* order. Your visitors may extend this class.
*/
public class PrintIdVisitor2 extends GJDepthFirst<Arginfo,Arginfo> {
//
// Auto class visitors--probably don't need to be overridden.
//
// symbol table
public Arginfo finaltable=new Arginfo();
Vector<String> vec;
int abcd=0;
public void exitfunc(int type,int num) {
//assert(false);
if(type==0){
System.out.print("Symbol not found");
}
else{
System.out.print("Type error");
}
System.exit(0);
}
public Arginfo visit(NodeList n, Arginfo argu) {
Arginfo _ret=null;
int _count=0;
for ( Enumeration<Node> e = n.elements(); e.hasMoreElements(); ) {
e.nextElement().accept(this,argu);
_count++;
}
return _ret;
}
public Arginfo visit(NodeListOptional n, Arginfo argu) {
if ( n.present() ) {
Arginfo _ret=null;
int _count=0;
for ( Enumeration<Node> e = n.elements(); e.hasMoreElements(); ) {
e.nextElement().accept(this,argu);
_count++;
}
return _ret;
}
else
return null;
}
public Arginfo visit(NodeOptional n, Arginfo argu) {
if ( n.present() )
return n.node.accept(this,argu);
else
return null;
}
public Arginfo visit(NodeSequence n, Arginfo argu) {
Arginfo _ret=null;
int _count=0;
for ( Enumeration<Node> e = n.elements(); e.hasMoreElements(); ) {
e.nextElement().accept(this,argu);
_count++;
}
return _ret;
}
public Arginfo visit(NodeToken n, Arginfo argu) { return null; }
//
// User-generated visitor methods below
//
/**
* f0 -> MainClass()
* f1 -> ( TypeDeclaration() )*
* f2 -> <EOF>
*/
public Arginfo visit(Goal n, Arginfo argu) {
finaltable=argu;
Arginfo _ret=null;
n.f0.accept(this, argu);
n.f1.accept(this, argu);
n.f2.accept(this, argu);
return _ret;
}
/**
* f0 -> "class"
* f1 -> Identifier()
* f2 -> "{"
* f3 -> "public"
* f4 -> "static"
* f5 -> "void"
* f6 -> "main"
* f7 -> "("
* f8 -> "String"
* f9 -> "["
* f10 -> "]"
* f11 -> Identifier()
* f12 -> ")"
* f13 -> "{"
* f14 -> PrintStatement()
* f15 -> "}"
* f16 -> "}"
*/
public Arginfo visit(MainClass n, Arginfo argu) {
Arginfo _ret=null;
Arginfo temp=new Arginfo(n.f1.f0.tokenImage);
temp.methodname=new String("main");
n.f0.accept(this, argu);
n.f1.accept(this, argu);
n.f2.accept(this, argu);
n.f3.accept(this, argu);
n.f4.accept(this, argu);
n.f5.accept(this, argu);
n.f6.accept(this, argu);
n.f7.accept(this, argu);
n.f8.accept(this, argu);
n.f9.accept(this, argu);
n.f10.accept(this, argu);
n.f11.accept(this, argu);
n.f12.accept(this, argu);
n.f13.accept(this, argu);
n.f14.accept(this, temp);
n.f15.accept(this, argu);
n.f16.accept(this, argu);
return _ret;
}
/**
* f0 -> ClassDeclaration()
* | ClassExtendsDeclaration()
*/
public Arginfo visit(TypeDeclaration n, Arginfo argu) {
Arginfo _ret=null;
n.f0.accept(this, argu);
return _ret;
}
/**
* f0 -> "class"
* f1 -> Identifier()
* f2 -> "{"
* f3 -> ( VarDeclaration() )*
* f4 -> ( MethodDeclaration() )*
* f5 -> "}"
*/
public Arginfo visit(ClassDeclaration n, Arginfo argu) {
Arginfo _ret=null;
Arginfo temp=new Arginfo(n.f1.f0.tokenImage);
n.f0.accept(this, argu);
n.f1.accept(this, argu);
n.f2.accept(this, argu);
n.f3.accept(this, argu);
n.f4.accept(this, temp);
n.f5.accept(this, argu);
return _ret;
}
/**
* f0 -> "class"
* f1 -> Identifier()
* f2 -> "extends"
* f3 -> Identifier()
* f4 -> "{"
* f5 -> ( VarDeclaration() )*
* f6 -> ( MethodDeclaration() )*
* f7 -> "}"
*/
public Arginfo visit(ClassExtendsDeclaration n, Arginfo argu) {
Arginfo _ret=null;
//System.out.println("Program type checked successfully");
//System.exit(0);
Arginfo temp=new Arginfo(n.f1.f0.tokenImage);
n.f0.accept(this, argu);
n.f1.accept(this, argu);
n.f2.accept(this, argu);
n.f3.accept(this, argu);
n.f4.accept(this, argu);
n.f5.accept(this, argu);
n.f6.accept(this, temp);
n.f7.accept(this, argu);
return _ret;
}
/**
* f0 -> Type()
* f1 -> Identifier()
* f2 -> ";"
*/
public Arginfo visit(VarDeclaration n, Arginfo argu) {
Arginfo _ret=null;
n.f0.accept(this, argu);
n.f1.accept(this, argu);
n.f2.accept(this, argu);
return _ret;
}
/**
* f0 -> "public"
* f1 -> Type()
* f2 -> Identifier()
* f3 -> "("
* f4 -> ( FormalParameterList() )?
* f5 -> ")"
* f6 -> "{"
* f7 -> ( VarDeclaration() )*
* f8 -> ( Statement() )*
* f9 -> "return"
* f10 -> Expression()
* f11 -> ";"
* f12 -> "}"
*/
public Arginfo visit(MethodDeclaration n, Arginfo argu) {
Arginfo _ret=null;
Arginfo temp=new Arginfo();
temp.classname=(temp.classname+argu.classname);
temp.methodname=(temp.methodname+n.f2.f0.tokenImage);
n.f0.accept(this, argu);
temp.isreq=1;
Arginfo abc=n.f1.accept(this, temp);
temp.isreq=0;
n.f2.accept(this, argu);
n.f3.accept(this, argu);
n.f4.accept(this, argu);
n.f5.accept(this, argu);
n.f6.accept(this, argu);
n.f7.accept(this, argu);
n.f8.accept(this, temp);
n.f9.accept(this, argu);
Arginfo expret=n.f10.accept(this, temp);
n.f11.accept(this, argu);
n.f12.accept(this, argu);
//if(abc==null) System.exit(0);
if(!abc.str.equals(new String("boolean"))&&!abc.str.equals(new String("integer"))&&!abc.str.equals(new String("intarray"))){
int flag=0;
Iterator it = finaltable.symboltable.entrySet().iterator();
while (it.hasNext()){
Map.Entry pair = (Map.Entry)it.next();
String cname=(String) pair.getKey();
if(cname.equals(abc.str)){
flag=1;
break;
}
}
if(flag==0){
//System.out.println(abc.str);
exitfunc(0,112);
}
}
if(!expret.str.equals(finaltable.symboltable.get(temp.classname).funcdec.get(temp.methodname).get(0))){
if(finaltable.symboltable.containsKey(expret.str)){
//String name=vartype;
int x=0;
int itr2=400;
String vartype=expret.str;
String tempstr=finaltable.symboltable.get(temp.classname).funcdec.get(temp.methodname).get(0);
while(true){
itr2--;
//if(itr2==0) break;
if(vartype.equals(tempstr)){
x=1;
break;
}
else{
vartype=finaltable.symboltable.get(vartype).parent;
if(vartype==null) break;
}
}
if(x==0){
exitfunc(1,222);
}
}
else{
exitfunc(1,20);
}
//System.out.println(expret.str+" "+n.f2.f0.tokenImage);
}
return _ret;
}
/**
* f0 -> FormalParameter()
* f1 -> ( FormalParameterRest() )*
*/
public Arginfo visit(FormalParameterList n, Arginfo argu) {
Arginfo _ret=null;
n.f0.accept(this, argu);
n.f1.accept(this, argu);
return _ret;
}
/**
* f0 -> Type()
* f1 -> Identifier()
*/
public Arginfo visit(FormalParameter n, Arginfo argu) {
Arginfo _ret=null;
n.f0.accept(this, argu);
n.f1.accept(this, argu);
return _ret;
}
/**
* f0 -> ","
* f1 -> FormalParameter()
*/
public Arginfo visit(FormalParameterRest n, Arginfo argu) {
Arginfo _ret=null;
n.f0.accept(this, argu);
n.f1.accept(this, argu);
return _ret;
}
/**
* f0 -> ArrayType()
* | BooleanType()
* | IntegerType()
* | Identifier()
*/
public Arginfo visit(Type n, Arginfo argu) {
Arginfo _ret=null;
Arginfo temp=n.f0.accept(this, argu);
return temp;
}
/**
* f0 -> "int"
* f1 -> "["
* f2 -> "]"
*/
public Arginfo visit(ArrayType n, Arginfo argu) {
Arginfo _ret=null;
n.f0.accept(this, argu);
n.f1.accept(this, argu);
n.f2.accept(this, argu);
Arginfo temp=new Arginfo();
temp.str="intarray";
return temp;
}
/**
* f0 -> "boolean"
*/
public Arginfo visit(BooleanType n, Arginfo argu) {
Arginfo _ret=null;
n.f0.accept(this, argu);
Arginfo temp=new Arginfo();
temp.str="boolean";
return temp;
}
/**
* f0 -> "int"
*/
public Arginfo visit(IntegerType n, Arginfo argu) {
Arginfo _ret=null;
n.f0.accept(this, argu);
Arginfo temp=new Arginfo();
temp.str="integer";
return temp;
}
/**
* f0 -> Block()
* | AssignmentStatement()
* | ArrayAssignmentStatement()
* | IfStatement()
* | WhileStatement()
* | PrintStatement()
*/
public Arginfo visit(Statement n, Arginfo argu) {
Arginfo _ret=null;
n.f0.accept(this, argu);
return _ret;
}
/**
* f0 -> "{"
* f1 -> ( Statement() )*
* f2 -> "}"
*/
public Arginfo visit(Block n, Arginfo argu) {
Arginfo _ret=null;
n.f0.accept(this, argu);
n.f1.accept(this, argu);
n.f2.accept(this, argu);
return _ret;
}
/**
* f0 -> Identifier()
* f1 -> "="
* f2 -> Expression()
* f3 -> ";"
*/
public Arginfo visit(AssignmentStatement n, Arginfo argu) {
Arginfo _ret=null;
String vartype=new String("");
Table classdec=finaltable.symboltable.get(argu.classname);
HashMap<String,String> metvars=classdec.methodvars.get(argu.methodname);
HashMap<String,String> classvars=classdec.varmap;
int itr=400;
while(classdec!=null){
itr--;
//if(itr==0) break;
if(metvars.containsKey(n.f0.f0.tokenImage)){
vartype=metvars.get(n.f0.f0.tokenImage);
}
else if(classvars.containsKey(n.f0.f0.tokenImage)){
vartype=classvars.get(n.f0.f0.tokenImage);
}
if(vartype.length()==0){
String classname=classdec.parent;
if(classname==null) break;
classdec=finaltable.symboltable.get(classname);
classvars=classdec.varmap;
}
else{
break;
}
}
if(vartype.length()==0){
exitfunc(0,0);
}
argu.isreq=1;
Arginfo temp1=n.f0.accept(this, argu);
n.f1.accept(this, argu);
Arginfo temp=n.f2.accept(this, argu);
argu.isreq=1;
n.f3.accept(this, argu);
// if(temp==null){
// System.out.println(vartype+" "+n.f0.f0.tokenImage+" "+argu.classname+" "+argu.methodname);
// exitfunc(1,0);
// }
vartype=temp.str;
if(!vartype.equals(temp1.str)){
//System.out.println(vartype+vartype.length());
//System.out.println(temp.str+temp.str.length());
//if(vartype==temp.str) System.out.println("njdnd");
int x=0;
if(finaltable.symboltable.containsKey(vartype)){
String name=vartype;
int itr2=400;
while(true){
itr2--;
//if(itr2==0) break;
if(vartype.equals(temp1.str)){
x=1;
break;
}
else{
vartype=finaltable.symboltable.get(vartype).parent;
}
}
}
else if(x==0){
exitfunc(1,33);
}
}
return _ret;
}
/**
* f0 -> Identifier()
* f1 -> "["
* f2 -> Expression()
* f3 -> "]"
* f4 -> "="
* f5 -> Expression()
* f6 -> ";"
*/
public Arginfo visit(ArrayAssignmentStatement n, Arginfo argu) {
Arginfo _ret=null;
String vartype=new String("");
Table classdec=finaltable.symboltable.get(argu.classname);
HashMap<String,String> metvars=classdec.methodvars.get(argu.methodname);
HashMap<String,String> classvars=classdec.varmap;
if(metvars.containsKey(n.f0.f0.tokenImage)){
vartype=metvars.get(n.f0.f0.tokenImage);
}
else if(classvars.containsKey(n.f0.f0.tokenImage)){
vartype=classvars.get(n.f0.f0.tokenImage);
}
else{
exitfunc(0,1);
}
if(!vartype.equals(new String("intarray"))){
exitfunc(1,1);
}
n.f0.accept(this, argu);
n.f1.accept(this, argu);
Arginfo temp1=n.f2.accept(this, argu);
n.f3.accept(this, argu);
n.f4.accept(this, argu);
Arginfo temp2=n.f5.accept(this, argu);
n.f6.accept(this, argu);
if(!(temp1.str.equals(new String("integer")))||!(temp2.str.equals(new String("integer")))){
exitfunc(1,2);
}
return _ret;
}
/**
* f0 -> IfthenElseStatement()
* | IfthenStatement()
*/
public Arginfo visit(IfStatement n, Arginfo argu) {
Arginfo _ret=null;
n.f0.accept(this, argu);
return _ret;
}
/**
* f0 -> "if"
* f1 -> "("
* f2 -> Expression()
* f3 -> ")"
* f4 -> Statement()
*/
public Arginfo visit(IfthenStatement n, Arginfo argu) {
Arginfo _ret=null;
n.f0.accept(this, argu);
n.f1.accept(this, argu);
Arginfo temp1=n.f2.accept(this, argu);
n.f3.accept(this, argu);
n.f4.accept(this, argu);
if(!(temp1.str.equals(new String("boolean")))){
exitfunc(1,3);
}
return _ret;
}
/**
* f0 -> "if"
* f1 -> "("
* f2 -> Expression()
* f3 -> ")"
* f4 -> Statement()
* f5 -> "else"
* f6 -> Statement()
*/
public Arginfo visit(IfthenElseStatement n, Arginfo argu) {
Arginfo _ret=null;
n.f0.accept(this, argu);
n.f1.accept(this, argu);
Arginfo temp1=n.f2.accept(this, argu);
n.f3.accept(this, argu);
n.f4.accept(this, argu);
n.f5.accept(this, argu);
n.f6.accept(this, argu);
if(!(temp1.str.equals(new String("boolean")))){
exitfunc(1,4);
}
return _ret;
}
/**
* f0 -> "while"
* f1 -> "("
* f2 -> Expression()
* f3 -> ")"
* f4 -> Statement()
*/
public Arginfo visit(WhileStatement n, Arginfo argu) {
Arginfo _ret=null;
n.f0.accept(this, argu);
n.f1.accept(this, argu);
Arginfo temp1=n.f2.accept(this, argu);
n.f3.accept(this, argu);
n.f4.accept(this, argu);
if(!(temp1.str.equals(new String("boolean")))){
exitfunc(1,5);
}
return _ret;
}
/**
* f0 -> "System.out.println"
* f1 -> "("
* f2 -> Expression()
* f3 -> ")"
* f4 -> ";"
*/
public Arginfo visit(PrintStatement n, Arginfo argu) {
Arginfo _ret=null;
n.f0.accept(this, argu);
n.f1.accept(this, argu);
Arginfo temp1=n.f2.accept(this, argu);
n.f3.accept(this, argu);
n.f4.accept(this, argu);
if(!(temp1.str.equals(new String("integer")))){
exitfunc(1,6);
}
return _ret;
}
/**
* f0 -> OrExpression()
* | AndExpression()
* | CompareExpression()
* | neqExpression()
* | PlusExpression()
* | MinusExpression()
* | TimesExpression()
* | DivExpression()
* | ArrayLookup()
* | ArrayLength()
* | MessageSend()
* | PrimaryExpression()
*/
public Arginfo visit(Expression n, Arginfo argu) {
Arginfo _ret=null;
Arginfo temp1=n.f0.accept(this, argu);
return temp1;
}
/**
* f0 -> PrimaryExpression()
* f1 -> "&&"
* f2 -> PrimaryExpression()
*/
public Arginfo visit(AndExpression n, Arginfo argu) {
Arginfo _ret=null;
Arginfo temp1=n.f0.accept(this, argu);
n.f1.accept(this, argu);
Arginfo temp2=n.f2.accept(this, argu);
if(!temp1.str.equals(new String("boolean"))||!temp2.str.equals(new String("boolean"))){
exitfunc(1,10);
}
return temp1;
}
/**
* f0 -> PrimaryExpression()
* f1 -> "||"
* f2 -> PrimaryExpression()
*/
public Arginfo visit(OrExpression n, Arginfo argu) {
Arginfo _ret=null;
Arginfo temp1=n.f0.accept(this, argu);
n.f1.accept(this, argu);
Arginfo temp2=n.f2.accept(this, argu);
if(!temp1.str.equals(new String("boolean"))||!temp2.str.equals(new String("boolean"))){
exitfunc(1,7);
}
return temp1;
}
/**
* f0 -> PrimaryExpression()
* f1 -> "<="
* f2 -> PrimaryExpression()
*/
public Arginfo visit(CompareExpression n, Arginfo argu) {
Arginfo _ret=null;
argu.isreq=2;
Arginfo temp1=n.f0.accept(this, argu);
n.f1.accept(this, argu);
Arginfo temp2=n.f2.accept(this, argu);
if(!temp1.str.equals(new String("integer"))||!temp2.str.equals(new String("integer"))){
//System.out.println(temp1.str+"rrc"+temp2.str);
exitfunc(1,8);
}
temp1.str=new String("boolean");
return temp1;
}
/**
* f0 -> PrimaryExpression()
* f1 -> "!="
* f2 -> PrimaryExpression()
*/
public Arginfo visit(neqExpression n, Arginfo argu) {
Arginfo _ret=null;
argu.isreq=2;
Arginfo temp1=n.f0.accept(this, argu);
n.f1.accept(this, argu);
Arginfo temp2=n.f2.accept(this, argu);
if((temp1.str.equals(new String("integer"))&&temp2.str.equals(new String("integer")))||(temp1.str.equals(new String("boolean"))&&temp2.str.equals(new String("boolean")))){
//exitfunc(1,8);
}
else{
exitfunc(1,9);
}
temp1.str=new String("boolean");
return temp1;
}
/**
* f0 -> PrimaryExpression()
* f1 -> "+"
* f2 -> PrimaryExpression()
*/
public Arginfo visit(PlusExpression n, Arginfo argu) {
Arginfo _ret=null;
argu.isreq=2;
Arginfo temp1=n.f0.accept(this, argu);
n.f1.accept(this, argu);
Arginfo temp2= n.f2.accept(this, argu);
if(!temp1.str.equals(new String("integer"))||!temp2.str.equals(new String("integer"))){
exitfunc(1,11);
}
return temp1;
}
/**
* f0 -> PrimaryExpression()
* f1 -> "-"
* f2 -> PrimaryExpression()
*/
public Arginfo visit(MinusExpression n, Arginfo argu) {
Arginfo _ret=null;
argu.isreq=2;
Arginfo temp1=n.f0.accept(this, argu);
n.f1.accept(this, argu);
Arginfo temp2=n.f2.accept(this, argu);
if(!temp1.str.equals(new String("integer"))||!temp2.str.equals(new String("integer"))){
exitfunc(1,12);
}
return temp1;
}
/**
* f0 -> PrimaryExpression()
* f1 -> "*"
* f2 -> PrimaryExpression()
*/
public Arginfo visit(TimesExpression n, Arginfo argu) {
Arginfo _ret=null;
argu.isreq=2;
Arginfo temp1=n.f0.accept(this, argu);
n.f1.accept(this, argu);
Arginfo temp2=n.f2.accept(this, argu);
if(!temp1.str.equals(new String("integer"))||!temp2.str.equals(new String("integer"))){
exitfunc(1,13);
}
return temp1;
}
/**
* f0 -> PrimaryExpression()
* f1 -> "/"
* f2 -> PrimaryExpression()
*/
public Arginfo visit(DivExpression n, Arginfo argu) {
Arginfo _ret=null;
argu.isreq=2;
Arginfo temp1=n.f0.accept(this, argu);
n.f1.accept(this, argu);
Arginfo temp2=n.f2.accept(this, argu);
if(!temp1.str.equals(new String("integer"))||!temp2.str.equals(new String("integer"))){
exitfunc(1,14);
}
return temp1;
}
/**
* f0 -> PrimaryExpression()
* f1 -> "["
* f2 -> PrimaryExpression()
* f3 -> "]"
*/
public Arginfo visit(ArrayLookup n, Arginfo argu) {
Arginfo _ret=null;
argu.isreq=2;
Arginfo temp1=n.f0.accept(this, argu);
n.f1.accept(this, argu);
Arginfo temp2=n.f2.accept(this, argu);
n.f3.accept(this, argu);
if(!temp1.str.equals(new String("intarray"))||!temp2.str.equals(new String("integer"))){
exitfunc(1,15);
}
return temp2;
}
/**
* f0 -> PrimaryExpression()
* f1 -> "."
* f2 -> "length"
*/
public Arginfo visit(ArrayLength n, Arginfo argu) {
Arginfo _ret=null;
argu.isreq=2;
Arginfo temp1=n.f0.accept(this, argu);
n.f1.accept(this, argu);
n.f2.accept(this, argu);
if(!temp1.str.equals(new String("intarray"))){
exitfunc(1,16);
}
temp1.str=new String("integer");
return temp1;
}
/**
* f0 -> PrimaryExpression()
* f1 -> "."
* f2 -> Identifier()
* f3 -> "("
* f4 -> ( ExpressionList() )?
* f5 -> ")"
*/
public Arginfo visit(MessageSend n, Arginfo argu) {
Arginfo _ret=null;
argu.isreq=1;
Arginfo temp1=n.f0.accept(this, argu);
n.f1.accept(this, argu);
argu.isreq=0;
n.f2.accept(this, argu);
argu.isreq=0;
n.f3.accept(this, argu);
Arginfo tempp=n.f4.accept(this, argu);
// String classname5=temp1.str;
// String methodname2=n.f2.f0.tokenImage;
// temp1.str=finaltable.symboltable.get(classname5).funcdec.get(methodname2).get(0);
// if(true) return temp1;
if(tempp==null){
//System.out.println(n.f2.f0.tokenImage);
//exitfunc(1,119);
tempp=new Arginfo();
}
n.f5.accept(this, argu);
String classname=temp1.str;
if(!finaltable.symboltable.containsKey(classname)){
exitfunc(0,12);
}
String methodname=n.f2.f0.tokenImage;
int itr=400;
while(true){
itr--;
//if(itr==0) break;
if(finaltable.symboltable.get(classname).funcdec.containsKey(methodname)){
break;
}
else{
classname=finaltable.symboltable.get(classname).parent;
if(classname==temp1.str||classname==null) break;
}
}
//System.out.println(classname+"djk"+methodname);
//exitfunc(1,10);
int flag=0;
if(classname!=null&&finaltable.symboltable.containsKey(classname)){
//System.out.println("cdjf");
if(!finaltable.symboltable.get(classname).funcdec.containsKey(methodname)) exitfunc(0,21);
if(finaltable.symboltable.get(classname).funcdec.containsKey(methodname)){
Vector<String> target=finaltable.symboltable.get(classname).funcdec.get(methodname);
//if(tempp==null) exitfunc(1,119);
if(tempp.vecstr.size()+1==target.size()){
int num=tempp.vecstr.size();
for(int i=0;i<num;i++){
if(!(tempp.vecstr.get(i)).equals(target.get(i+1))){
flag=1;
String classname2=tempp.vecstr.get(i);
String ori=classname2;
String classname3=target.get(i+1);
int itr2=400;
while(true){
itr2--;
if(itr2==0) break;
if(finaltable.symboltable.containsKey(classname2)){
if(classname3.equals(classname2)){
flag=0;
break;
}
else{
classname2=finaltable.symboltable.get(classname2).parent;
if(classname2==null||classname2.equals(ori)){
flag=1;
break;
}
}
}
}
if(flag==1){
break;
}
}
}
}
else{
flag=2;
}
if(flag==0) temp1.str=finaltable.symboltable.get(classname).funcdec.get(methodname).get(0);
else{
// System.out.println(classname+" "+methodname+" "+flag+" "+argu.classname+" "+argu.methodname);
// System.out.println(tempp.vecstr.size());
// System.out.println(target.size());
// for(int i=0;i<tempp.vecstr.size();i++){
// System.out.println(tempp.vecstr.get(i));
// }
exitfunc(1,122);
}
}
}
else{
exitfunc(0,10);
}
return temp1;
}
/**
* f0 -> Expression()
* f1 -> ( ExpressionRest() )*
*/
public Arginfo visit(ExpressionList n, Arginfo argu) {
Arginfo _ret=null;
Arginfo temp=n.f0.accept(this, argu);
Arginfo pre=new Arginfo();
pre.vecstr.add(temp.str);
pre.classname=argu.classname;
pre.methodname=argu.methodname;
pre.isreq=argu.isreq;
n.f1.accept(this, pre);
return pre;
}
/**
* f0 -> ","
* f1 -> Expression()
*/
public Arginfo visit(ExpressionRest n, Arginfo argu) {
Arginfo _ret=null;
n.f0.accept(this, argu);
Arginfo temp=n.f1.accept(this, argu);
argu.vecstr.add(temp.str);
return argu;
}
/**
* f0 -> IntegerLiteral()
* | TrueLiteral()
* | FalseLiteral()
* | Identifier()
* | ThisExpression()
* | ArrayAllocationExpression()
* | AllocationExpression()
* | NotExpression()
* | BracketExpression()
*/
public Arginfo visit(PrimaryExpression n, Arginfo argu) {
Arginfo _ret=null;
argu.isreq=1;
Arginfo temp1=n.f0.accept(this, argu);
return temp1;
}
/**
* f0 -> <INTEGER_LITERAL>
*/
public Arginfo visit(IntegerLiteral n, Arginfo argu) {
Arginfo _ret=null;
n.f0.accept(this, argu);
Arginfo temp1=new Arginfo();
temp1.str=new String("integer");
return temp1;
}
/**
* f0 -> "true"
*/
public Arginfo visit(TrueLiteral n, Arginfo argu) {
Arginfo _ret=null;
n.f0.accept(this, argu);
Arginfo temp1=new Arginfo();
temp1.str=new String("boolean");
return temp1;
}
/**
* f0 -> "false"
*/
public Arginfo visit(FalseLiteral n, Arginfo argu) {
Arginfo _ret=null;
n.f0.accept(this, argu);
Arginfo temp1=new Arginfo();
temp1.str=new String("boolean");
return temp1;
}
/**
* f0 -> <IDENTIFIER>
*/
public Arginfo visit(Identifier n, Arginfo argu) {
Arginfo _ret=null;
n.f0.accept(this, argu);
// String a="int";
// if(a.equals(n.f0.tokenImage)){
// System.out.println(argu.isreq);
// System.exit(0);
// }
if(argu.isreq==0){
// System.out.println(n.f0.tokenImage);
// if(abcd==10) System.exit(0);
// abcd++;
return _ret;
}
if(argu.isreq==10){
//exitfunc(1,90);
Arginfo temp2=new Arginfo();
temp2.str=n.f0.tokenImage;
return temp2;
}
Arginfo temp1=new Arginfo();
String vartype=new String("");
//System.out.println(argu.classname+"\t"+argu.methodname+"\t"+n.f0.tokenImage);
//exitfunc(1,90);
// if(finaltable.containsKey(argu.classname)){
// vartype=metvars.get(n.f0.tokenImage);
// }
//System.out.println(argu.classname);
//System.out.println(argu.methodname);
// if(!classdec.methodvars.containsKey(argu.methodname)&&((argu.classname).equals(new String("MyVisitor")))){
// System.out.println("noo"+argu.methodname);
// Iterator it2 = classdec.methodvars.entrySet().iterator();
// while (it2.hasNext()) {
// Map.Entry pair2 = (Map.Entry)it2.next();
// System.out.print("\tfunction Name: ");
// System.out.format("%-15s",pair2.getKey());
// }
// exitfunc(1,20);
// }
// Iterator it = metvars.entrySet().iterator();
// while (it.hasNext()) {
// Map.Entry pair = (Map.Entry)it.next();
// System.out.println(pair.getKey()+"*****************"+pair.getValue());
// it.remove();
// }
// System.out.println((n.f0.tokenImage));
//
//if(metvars==null)exitfunc(0,20);
//if(finaltable.symboltable.get(argu.classname).methodvars.get(argu.methodname).containsKey(n.f0.tokenImage)){
Table classdec=finaltable.symboltable.get(argu.classname);
HashMap<String,String> metvars=new HashMap<String,String>();
metvars=classdec.methodvars.get(argu.methodname);
HashMap<String,String> classvars=classdec.varmap;
String classname=argu.classname;
int itr=400;
while(true){
itr--;
//if(itr==0) break;
if(metvars.containsKey(n.f0.tokenImage)){
vartype=metvars.get(n.f0.tokenImage);
break;
}
else if(classvars.containsKey(n.f0.tokenImage)){
vartype=classvars.get(n.f0.tokenImage);
break;
}
else if(finaltable.symboltable.get(classname).parent!=null){
classname=finaltable.symboltable.get(classname).parent;
classvars=finaltable.symboltable.get(classname).varmap;
if(classname.equals(argu.classname)){
exitfunc(1,21);
}
}
else{
break;
}
}
// else if(finaltable.symboltable.containsKey(n.f0.tokenImage)){
// //exitfunc(0,20);
// vartype=n.f0.tokenImage;
// }
if(vartype.length()==0){
//System.out.println(argu.classname+" "+argu.methodname+" "+n.f0.tokenImage);
if(finaltable.symboltable.containsKey(n.f0.tokenImage)){
vartype=n.f0.tokenImage;
}
else{
exitfunc(0,20);
}
}
temp1.str=vartype;
//System.out.println(classname);
//temp1.str="identifier";
//temp1.classname=n.f0.tokenImage;
return temp1;
}
/**
* f0 -> "this"
*/
public Arginfo visit(ThisExpression n, Arginfo argu) {
Arginfo _ret=null;
n.f0.accept(this, argu);
Arginfo temp1=new Arginfo();
temp1.str=argu.classname;
//temp1.str="identifier";
temp1.classname=argu.classname;
return temp1;
}
/**
* f0 -> "new"
* f1 -> "int"
* f2 -> "["
* f3 -> Expression()
* f4 -> "]"
*/
public Arginfo visit(ArrayAllocationExpression n, Arginfo argu) {
Arginfo _ret=null;
n.f0.accept(this, argu);
n.f1.accept(this, argu);
n.f2.accept(this, argu);
Arginfo temp1=n.f3.accept(this, argu);
n.f4.accept(this, argu);
if(!temp1.str.equals(new String("integer"))){
exitfunc(1,16);
}
temp1.str=new String("intarray");
return temp1;
}
/**
* f0 -> "new"
* f1 -> Identifier()
* f2 -> "("
* f3 -> ")"
*/
public Arginfo visit(AllocationExpression n, Arginfo argu) {
Arginfo _ret=null;
argu.isreq=0;
n.f0.accept(this, argu);
n.f1.accept(this, argu);
n.f2.accept(this, argu);
n.f3.accept(this, argu);
Arginfo temp1=new Arginfo();
//temp1.str="identifier";
temp1.str=n.f1.f0.tokenImage;
return temp1;
}
/**
* f0 -> "!"
* f1 -> Expression()
*/
public Arginfo visit(NotExpression n, Arginfo argu) {
Arginfo _ret=null;
n.f0.accept(this, argu);
Arginfo temp1=n.f1.accept(this, argu);
if(!temp1.str.equals(new String("boolean"))){
exitfunc(1,17);
}
return temp1;
}
/**
* f0 -> "("
* f1 -> Expression()
* f2 -> ")"
*/
public Arginfo visit(BracketExpression n, Arginfo argu) {
Arginfo _ret=null;
n.f0.accept(this, argu);
Arginfo temp1=n.f1.accept(this, argu);
n.f2.accept(this, argu);
return temp1;
}
/**
* f0 -> Identifier()
* f1 -> ( IdentifierRest() )*
*/
public Arginfo visit(IdentifierList n, Arginfo argu) {
Arginfo _ret=null;
n.f0.accept(this, argu);
n.f1.accept(this, argu);
return _ret;
}
/**
* f0 -> ","
* f1 -> Identifier()
*/
public Arginfo visit(IdentifierRest n, Arginfo argu) {
Arginfo _ret=null;
n.f0.accept(this, argu);
n.f1.accept(this, argu);
return _ret;
}
}
|
package cn.jishuz.library.until;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import cn.jishuz.library.R;
import android.view.View.OnClickListener;
//这段代码网上搬过来的 主要目的是不重复造轮子 程序员应该要学会
public class Topbar extends RelativeLayout implements OnClickListener{
private ImageView backView;
private ImageView rightView;
private TextView titleView;
private String titleStr;
private int strSize;
private int strColor;
private Drawable leftDraw;
private Drawable rightDraw;
private onTitleBarClickListener onMyClickListener;
public Topbar(Context context) {
this(context, null);
}
public Topbar(Context context, AttributeSet attrs) {
this(context, attrs, R.style.AppTheme);
}
public Topbar(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
getConfig(context, attrs);
initView(context);
}
private void getConfig(Context context, AttributeSet attrs) {
// TypedArray是一个数组容器用于存放属性值
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.Topbar);
int count = ta.getIndexCount();
for (int i = 0; i < count; i++) {
int attr = ta.getIndex(i);
switch (attr) {
case R.styleable.Topbar_titleText:
titleStr = ta.getString(R.styleable.Topbar_titleText);
break;
case R.styleable.Topbar_titleColor:
// 默认颜色设置为黑色
strColor = ta.getColor(attr, Color.BLACK);
break;
case R.styleable.Topbar_titleSize:
// 默认设置为16sp,TypeValue也可以把sp转化为px
strSize = ta.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 10,
getResources().getDisplayMetrics()));
break;
case R.styleable.Topbar_leftBtn:
leftDraw = ta.getDrawable(R.styleable.Topbar_leftBtn);
break;
case R.styleable.Topbar_rightBtn:
rightDraw = ta.getDrawable(R.styleable.Topbar_rightBtn);
break;
}
}
// 用完务必回收容器
ta.recycle();
}
private void initView(Context context) {
View layout = LayoutInflater.from(context).inflate(R.layout.topbar, this, true);
backView = (ImageView) layout.findViewById(R.id.back_image);
titleView = (TextView) layout.findViewById(R.id.text_title);
rightView = (ImageView) layout.findViewById(R.id.right_image);
backView.setOnClickListener(this);
rightView.setOnClickListener(this);
if (null != leftDraw)
backView.setImageDrawable(leftDraw);
if (null != rightDraw)
rightView.setImageDrawable(rightDraw);
if (null != titleStr) {
titleView.setText(titleStr);
titleView.setTextSize(strSize);
titleView.setTextColor(strColor);
titleView.setTypeface(Typeface.DEFAULT);
}
}
/**
* 设置按钮点击监听接口
* @param callback
*/
public void setClickListener(onTitleBarClickListener listener) {
this.onMyClickListener = listener;
}
/**
* 导航栏点击监听接口
*/
public static interface onTitleBarClickListener {
/**
* 点击返回按钮回调
*/
void onBackClick();
void onRightClick();
}
@Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.back_image:
if (null != onMyClickListener)
onMyClickListener.onBackClick();
break;
case R.id.right_image:
if (null != onMyClickListener)
onMyClickListener.onRightClick();
break;
}
}
}
|
package com.p4square.ccbapi.model;
import javax.xml.bind.annotation.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
/**
* Representation of a Group Profile.
*/
@XmlRootElement(name="individual")
@XmlAccessorType(XmlAccessType.NONE)
public class GroupProfile {
@XmlAttribute(name="id")
private int id;
@XmlElement(name="name")
private String name;
@XmlElement(name="description")
private String description;
@XmlElement(name="image")
private String imageUrl;
@XmlElement(name="calendar_feed")
private String calendarFeedUrl;
@XmlElement(name="main_leader")
private IndividualProfile mainLeader;
@XmlElement(name="coach")
private IndividualProfile coach;
@XmlElement(name="director")
private IndividualProfile director;
@XmlElementWrapper(name="leaders")
@XmlElement(name="leader")
private List<IndividualProfile> leaders;
@XmlElementWrapper(name="participants")
@XmlElement(name="participant")
private List<IndividualProfile> participants;
@XmlElement(name="current_members")
private int currentMembers;
@XmlElement(name="group_capacity")
private String groupCapacity;
@XmlElementWrapper(name="addresses")
@XmlElement(name="address")
private List<Address> addresses;
@XmlElement(name="childcare_provided")
private boolean childcareProvided;
@XmlElement(name="listed")
private boolean listed;
@XmlElement(name="public_search_listed")
private boolean publicSearchListed;
@XmlElement(name="inactive")
private boolean inactive;
@XmlElement(name="notification")
private boolean notification;
@XmlElement(name="interaction_type", defaultValue = "Announcement Only")
private InteractionType interactionType;
@XmlElement(name="membership_type", defaultValue = "Invitation")
private MembershipType membershipType;
@XmlElementWrapper(name="user_defined_fields")
@XmlElement(name="user_defined_field")
private CustomFieldCollection<CustomPulldownFieldValue> customPulldownFields;
@XmlElement(name="campus")
private Reference campus;
@XmlElement(name="group_type")
private Reference groupType;
@XmlElement(name="department")
private Reference department;
@XmlElement(name="area")
private Reference area;
@XmlElement(name="meeting_day")
private Reference meetingDay;
@XmlElement(name="meeting_time")
private Reference meetingTime;
@XmlElement(name="creator")
private IndividualReference createdBy;
@XmlElement(name="created")
private LocalDateTime createdTime;
@XmlElement(name="modifier")
private IndividualReference modifiedBy;
@XmlElement(name="modified")
private LocalDateTime modifiedTime;
public GroupProfile() {
leaders = new ArrayList<>();
participants = new ArrayList<>();
addresses = new ArrayList<>();
customPulldownFields = new CustomFieldCollection<>();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getCalendarFeedUrl() {
return calendarFeedUrl;
}
public void setCalendarFeedUrl(String calendarFeedUrl) {
this.calendarFeedUrl = calendarFeedUrl;
}
public IndividualProfile getMainLeader() {
return mainLeader;
}
public void setMainLeader(IndividualProfile mainLeader) {
this.mainLeader = mainLeader;
}
public IndividualProfile getCoach() {
return coach;
}
public void setCoach(IndividualProfile coach) {
this.coach = coach;
}
public IndividualProfile getDirector() {
return director;
}
public void setDirector(IndividualProfile director) {
this.director = director;
}
public List<IndividualProfile> getLeaders() {
return leaders;
}
public void setLeaders(List<IndividualProfile> leaders) {
this.leaders = leaders;
}
public List<IndividualProfile> getParticipants() {
return participants;
}
public void setParticipants(List<IndividualProfile> participants) {
this.participants = participants;
}
public int getCurrentMembers() {
return currentMembers;
}
public void setCurrentMembers(int currentMembers) {
this.currentMembers = currentMembers;
}
public Integer getGroupCapacity() {
if (isGroupCapacityUnlimited()) {
return null;
} else {
return Integer.valueOf(this.groupCapacity);
}
}
public boolean isGroupCapacityUnlimited() {
return this.groupCapacity == null || "Unlimited".equals(this.groupCapacity);
}
public void setGroupCapacity(Integer groupCapacity) {
if (groupCapacity == null) {
this.groupCapacity = "Unlimited";
} else {
this.groupCapacity = groupCapacity.toString();
}
}
public List<Address> getAddresses() {
return addresses;
}
public void setAddresses(List<Address> addresses) {
this.addresses = addresses;
}
public boolean isChildcareProvided() {
return childcareProvided;
}
public void setChildcareProvided(boolean childcareProvided) {
this.childcareProvided = childcareProvided;
}
public boolean isListed() {
return listed;
}
public void setListed(boolean listed) {
this.listed = listed;
}
public boolean isPublicSearchListed() {
return publicSearchListed;
}
public void setPublicSearchListed(boolean publicSearchListed) {
this.publicSearchListed = publicSearchListed;
}
public boolean isActive() {
return !inactive;
}
public void setActive(boolean active) {
this.inactive = !inactive;
}
public boolean isNotification() {
return notification;
}
public void setNotification(boolean notification) {
this.notification = notification;
}
public InteractionType getInteractionType() {
return interactionType;
}
public void setInteractionType(InteractionType interactionType) {
this.interactionType = interactionType;
}
public MembershipType getMembershipType() {
return membershipType;
}
public void setMembershipType(MembershipType membershipType) {
this.membershipType = membershipType;
}
public CustomFieldCollection<CustomPulldownFieldValue> getCustomPulldownFields() {
return customPulldownFields;
}
public void setCustomPulldownFields(CustomFieldCollection<CustomPulldownFieldValue> customPulldownFields) {
this.customPulldownFields = customPulldownFields;
}
public Reference getCampus() {
return campus;
}
public void setCampus(Reference campus) {
this.campus = campus;
}
public Reference getGroupType() {
return groupType;
}
public void setGroupType(Reference groupType) {
this.groupType = groupType;
}
public Reference getDepartment() {
return department;
}
public void setDepartment(Reference department) {
this.department = department;
}
public Reference getArea() {
return area;
}
public void setArea(Reference area) {
this.area = area;
}
public Reference getMeetingDay() {
return meetingDay;
}
public void setMeetingDay(Reference meetingDay) {
this.meetingDay = meetingDay;
}
public Reference getMeetingTime() {
return meetingTime;
}
public void setMeetingTime(Reference meetingTime) {
this.meetingTime = meetingTime;
}
public IndividualReference getCreatedBy() {
return createdBy;
}
public void setCreatedBy(IndividualReference createdBy) {
this.createdBy = createdBy;
}
public LocalDateTime getCreatedTime() {
return createdTime;
}
public void setCreatedTime(LocalDateTime createdTime) {
this.createdTime = createdTime;
}
public IndividualReference getModifiedBy() {
return modifiedBy;
}
public void setModifiedBy(IndividualReference modifiedBy) {
this.modifiedBy = modifiedBy;
}
public LocalDateTime getModifiedTime() {
return modifiedTime;
}
public void setModifiedTime(LocalDateTime modifiedTime) {
this.modifiedTime = modifiedTime;
}
}
|
package com.rsm.yuri.projecttaxilivre.adddialog.di;
import com.rsm.yuri.projecttaxilivre.TaxiLivreAppModule;
import com.rsm.yuri.projecttaxilivre.adddialog.ui.AddDialogFragment;
import com.rsm.yuri.projecttaxilivre.domain.di.DomainModule;
import com.rsm.yuri.projecttaxilivre.lib.di.LibsModule;
import javax.inject.Singleton;
import dagger.Component;
/**
* Created by yuri_ on 27/02/2018.
*/
@Singleton
@Component(modules = {AddDialogModule.class, DomainModule.class, LibsModule.class, TaxiLivreAppModule.class})
public interface AddDialogComponent {
void inject(AddDialogFragment fragment);
}
|
package solution.cs3330.hw3;
public class Human extends GameCreature{
public Human(String name, int hp, Bag emptyBag) {
super(name, hp, emptyBag);
this.bag.addItem(new Weapon("Standard","Crowbar", 5, 30));
// TODO Auto-generated constructor stub
}
public boolean pickup(Item item) {
return this.bag.addItem(item);
}
public boolean drop(Item item) {
return this.bag.dropItem(item);
}
@Override
public boolean attack(GameCreature enemy, Item item) {
if (item == null || !(item instanceof Weapon)) return false;
enemy.injured(item.getPoints() * 2);
return true;
}
@Override
public boolean heal(Item item) {
if (item == null || !(item instanceof Healer)) return false;
this.health.heal(item.getPoints());
return true;
}
}
|
package com.philippe.app.util;
import com.philippe.app.domain.Event;
import java.util.function.BiPredicate;
public class FilteringUtil {
public static final String NATIVE = "native";
public static final BiPredicate<Event, String[]> filterByEventType =
(event, eventTypeArray) -> {
boolean filter = false;
for (String eventType: eventTypeArray){
if (eventType.equals(event.getEventType())) {
filter = true;
break;
}
}
return filter;
};
public static boolean hasNativeMaturity(final Event event) {
return event.getMaturity().equals(NATIVE);
}
}
|
package com.mochasoft.fk.exception;
/**
* <strong>Title : MochaException </strong>. <br>
* <strong>Description : 业务异常对象封装.</strong> <br>
* <strong>Create on : 2012-9-3 下午3:51:04 </strong>. <br>
* <p>
* <strong>Copyright (C) Mocha Software Co.,Ltd.</strong> <br>
* </p>
* @author wanghe wanghe@mochasoft.com.cn <br>
* @version <strong>Framework0.8</strong> <br>
* <br>
* <strong>修改历史: .</strong> <br>
* 修改人 修改日期 修改描述<br>
* -------------------------------------------<br>
* <br>
* <br>
*/
public class MochaException extends RuntimeException{
/**
* <code>serialVersionUID</code>-注释
*/
private static final long serialVersionUID = 1L;
/**
* <code>m_errorMessage</code>-业务组件层详细的错误信息
*/
private String m_errorMessage = null;
/**
* 构造函数
*/
public MochaException() {
super();
}
/**
* 构造函数
*
* @param message
* <code>异常消息</code>
*/
public MochaException(String message) {
super(message);
this.m_errorMessage = message;
}
/**
* 构造函数
*
* @param cause
* <code>可抛出的异常对象</code>
*/
public MochaException(Throwable cause) {
super(cause);
}
/**
* 构造函数
*
* @param message
* <code>异常消息</code>
* @param cause
* <code>可抛出的异常对象</code>
*/
public MochaException(String message, Throwable cause) {
super(message, cause);
}
/**
* @return Returns the errorMessage.
*/
public final String getErrorMessage() {
if (null != m_errorMessage && !"".equals(this.m_errorMessage)) {
return convertErrorMessage(this.m_errorMessage);
}
if (null != this.getCause()) {
return convertErrorMessage(this.getCause().getMessage());
}
return this.getMessage();
}
/**
* @param errorMessage
* The errorMessage to set.
*/
public final void setErrorMessage(String errorMessage) {
m_errorMessage = errorMessage;
}
/**
* 转换ErrorMessage的方法
*
* @param message -
* 原始的错误信息
* @return 转换后的错误信息
*/
private String convertErrorMessage(String message) {
if (null != message && !"".equals(message) && message.indexOf(":") > 0) {
return message.substring(message.indexOf("Exception:") + 1, message
.length());
} else {
return message;
}
}
}
|
package com.tencent.mm.ui.widget.textview;
import android.view.ViewTreeObserver.OnPreDrawListener;
class a$6 implements OnPreDrawListener {
final /* synthetic */ a uPp;
a$6(a aVar) {
this.uPp = aVar;
}
public final boolean onPreDraw() {
if (this.uPp.uPl) {
this.uPp.uPl = false;
a aVar = this.uPp;
aVar.ih.removeCallbacks(aVar.uPo);
aVar.ih.postDelayed(aVar.uPo, 100);
}
return true;
}
}
|
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import com.hogetvedt.crawler.models.WebLink;
import com.hogetvedt.crawler.spider.Spider;
import com.hogetvedt.crawler.spider.SpiderException;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
public class SpiderTest {
private final String MOCK_STATUS_URL = "https://httpbin.org/status/";
private Spider spider;
@Rule
public ExpectedException failure = ExpectedException.none();
@Before
public void setup() {
this.spider = new Spider();
}
// test null endpoint
@Test
public void crawlNullEndpoint() throws SpiderException {
failure.expect(SpiderException.class);
failure.expectMessage("Invalid URL");
WebLink link = new WebLink(null);
spider.crawl(link);
}
// test empty endpoint
@Test
public void crawlEmptyEndpoint() throws SpiderException {
failure.expect(SpiderException.class);
failure.expectMessage("Invalid URL");
WebLink link = new WebLink("");
spider.crawl(link);
}
// crawl good status
@Test
public void crawlStatusCode200() {
testGoodRequest("200");
}
@Test
public void crawlStatusCode201() {
testGoodRequest("201");
}
// crawl bad status
@Test
public void crawlStatusCode400() {
testBadRequest("400");
}
@Test
public void crawlStatusCode401() {
testBadRequest("401");
}
@Test
public void crawlStatusCode403() {
testBadRequest("403");
}
@Test
public void crawlStatusCode404() {
testBadRequest("404");
}
@Test
public void crawlStatusCode500() {
testBadRequest("500");
}
@Test
public void crawlStatusCode501() {
testBadRequest("501");
}
@Test
public void crawlStatusCode502() {
testBadRequest("502");
}
@Test
public void crawlStatusCode503() {
testBadRequest("503");
}
@Test
public void crawlStatusCode504() {
testBadRequest("504");
}
private void testGoodRequest(String statusCode) {
WebLink link = new WebLink(MOCK_STATUS_URL + statusCode);
try {
spider.crawl(link);
} catch (SpiderException e) {
e.printStackTrace();
}
Assert.assertEquals(1, spider.getHttpRequests().longValue());
Assert.assertEquals(1, spider.getSuccessfulRequests().longValue());
Assert.assertEquals(0, spider.getFailedRequests().longValue());
}
private void testBadRequest(String statusCode) {
WebLink link = new WebLink(MOCK_STATUS_URL + statusCode);
try {
spider.crawl(link);
} catch (SpiderException e) {
e.printStackTrace();
}
Assert.assertEquals(1, spider.getHttpRequests().longValue());
Assert.assertEquals(0, spider.getSuccessfulRequests().longValue());
Assert.assertEquals(1, spider.getFailedRequests().longValue());
}
private void createUrlEndpoint(String jsonBody) {
stubFor(get(urlEqualTo("/test"))
.willReturn(
aResponse()
.withStatus(200)
.withHeader("Content-type", "application/json")
.withBody(jsonBody)
)
);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.