blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
410
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
51
| license_type
stringclasses 2
values | repo_name
stringlengths 5
132
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
80
| visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.85k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 131
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
9.45M
| extension
stringclasses 32
values | content
stringlengths 3
9.45M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
313
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ae5808fbf5280e322fe266a536760e683c76788d | 31d41174d056e5d7bd926e773b3d2a7edd107aea | /src/main/java/com/sztouyun/advertisingsystem/model/system/HistoricalParamConfig.java | 2b6f70e23b9b2b40ee1a8a863975e87889cbaa40 | [] | no_license | foxbabe/ads | 76ed0bb60ca93c9bb2ef0feec4dfdf60adf8a6bb | 713d8abd599830180ad37dbc07892dae470e07e5 | refs/heads/master | 2020-04-07T07:57:31.790305 | 2018-11-08T03:06:26 | 2018-11-08T03:06:26 | 158,195,619 | 1 | 0 | null | 2018-11-19T09:31:47 | 2018-11-19T09:31:46 | null | UTF-8 | Java | false | false | 960 | java | package com.sztouyun.advertisingsystem.model.system;
import com.sztouyun.advertisingsystem.model.BaseRecordModel;
import lombok.Data;
import javax.persistence.Column;
import javax.persistence.Entity;
import java.util.Date;
@Entity
@Data
public class HistoricalParamConfig extends BaseRecordModel {
/**
* 所属分组
*/
@Column(nullable = false)
private Integer configGroup;
/**
* 参数类型
*/
@Column(nullable = false)
private Integer type;
/**
* 比较符
*/
@Column(name = "comparison_type")
private Integer comparisonType;
/**
* 标准值
*/
@Column(nullable = false)
private Double value;
/**
* 单位
*/
private Integer unit;
@Column(nullable = false)
private Date updatedTime;
/**
* 配置所属方ID
*/
@Column(nullable = false, columnDefinition = "varchar(36) default ''")
private String objectId;
}
| [
"[email protected]"
] | |
c4a2eba3f1c6014851094362a7c9e8887c9acd8a | 303634392a454ad72d149af68bf5b0480b09d811 | /projects/DackelCMDB-JavaBackend/DackelCMDBSpring_ALT/dackelcmdb-service/src/main/java/de/percsi/products/dackelcmdb/service/model/PropertyOfEntity.java | 51d2cb492668024377d59c242bfc2b2908ab77e9 | [
"MIT"
] | permissive | istvanpercsi/DackelCMDB | dacaee13d44317cb11dd8dafc02272008da2e69f | 79a089b101331ea5dde652cd86899fe507093e20 | refs/heads/master | 2022-02-04T19:57:43.436354 | 2022-01-13T22:53:19 | 2022-01-13T22:53:19 | 175,701,699 | 0 | 0 | MIT | 2022-01-13T22:53:20 | 2019-03-14T21:22:46 | Java | UTF-8 | Java | false | false | 225 | java | package de.percsi.products.dackelcmdb.service.model;
import lombok.Builder;
import lombok.Value;
@Value
@Builder
public class PropertyOfEntity {
Long id;
String name;
String systemName;
//TODO: other fields
}
| [
"[email protected]"
] | |
694e647c9a56177d329634cc20d56d91decc947b | 5483cc0f9f4d598dd49026b7f350e337bce1ed05 | /app/src/main/java/com/example/santos/sportquiz/ViewHolder/CategoryViewHolder.java | 16bd1646fcf8afe38bb32056a5d338eea544dc67 | [] | no_license | SantoshAcharya1200/SportQuiz2 | 384ef1363f8d6122bb019e0d090a0092bf66c2c1 | 739051bc6321bb38a9008c1a439747ab99e32c20 | refs/heads/master | 2020-05-21T07:10:16.707161 | 2019-05-26T10:03:27 | 2019-05-26T10:03:27 | 185,952,903 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,085 | java | package com.example.santos.sportquiz.ViewHolder;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.santos.sportquiz.Interface.ItemClickListner;
import com.example.santos.sportquiz.R;
/**
* Created by santosh on 2/17/2018.
*/
public class CategoryViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView category_name;
public ImageView category_image;
private ItemClickListner itemClickListner;
public CategoryViewHolder(View itemView) {
super(itemView);
category_image=(ImageView)itemView.findViewById(R.id.category_image);
category_name=(TextView)itemView.findViewById(R.id.category_name);
itemView.setOnClickListener(this);
}
public void setItemClickListner(ItemClickListner itemClickListner) {
this.itemClickListner = itemClickListner;
}
@Override
public void onClick(View view) {
itemClickListner.onClick(view,getAdapterPosition(),false);
}
}
| [
"[email protected]"
] | |
e0070f99251ad8caae9aa21d597389ea896252c3 | 755fbdf77dc72e47ba56ed0438b4506983da7fe7 | /xy365-web/src/main/java/com/xy365/web/aspect/ControllerAspect.java | 3911d9648ca0ab82ecec14886d00dd4b14d78c1b | [] | no_license | firefoxhu/xy365 | ef272c1ea5e8c95e50c46d6c8755ce024ef76758 | c3baa9bd87c4d0d36c910273acc78b6fea05a640 | refs/heads/master | 2020-03-25T04:14:46.863102 | 2019-04-09T10:55:24 | 2019-04-09T10:55:24 | 143,385,078 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 897 | java | package com.xy365.web.aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class ControllerAspect {
@Pointcut("execution(* com.xy365.web.controller.*.*(..))")
public void cut(){}
@Around("cut()")
public Object twiceAsOld(ProceedingJoinPoint joinPoint){
try {
long start = System.currentTimeMillis();
Object result = joinPoint.proceed();
long timeConsuming = System.currentTimeMillis() - start;
System.out.println("本次请求耗费了:"+timeConsuming+"毫秒");
return result;
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return null;
}
}
| [
"[email protected]"
] | |
fe0a1b815d6e70388e76e13dea4e5ecc29a5e633 | c2e895f62aea3d8e593e951337c6423ab8be76b8 | /src/main/java/org/starterapp/persistence/AppPMFProvider.java | 86fa2fa3ca96ebe4939a979f20de77e1a0dc5c96 | [
"MIT"
] | permissive | naikus/backend-starter-app | 24b5a707f712a12ba799d20151c5c45ed34d5eb6 | 688bd322437d33afb55557cdcec86781396bd426 | refs/heads/master | 2020-04-12T13:08:08.509017 | 2017-05-10T03:30:15 | 2017-05-10T03:30:15 | 12,478,649 | 0 | 0 | MIT | 2019-10-22T01:04:50 | 2013-08-30T05:18:07 | Java | UTF-8 | Java | false | false | 554 | java | package org.starterapp.persistence;
import javax.inject.Named;
import javax.inject.Singleton;
import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManagerFactory;
/**
* An implementation of EMP that provides entity manager factory for this app
*
* @author aniket
*/
@Singleton
@Named("AppPMF")
public class AppPMFProvider extends PMFProvider {
private static final PersistenceManagerFactory PMF
= JDOHelper.getPersistenceManagerFactory("starterapp-model");
@Override
public PersistenceManagerFactory get() {
return PMF;
}
}
| [
"[email protected]"
] | |
e1f542bab30396a3cfd742fb6bf41cb6ba90e7fc | f96e56efd69cf536516723735336b3de3a21d31b | /shanghai/customHG/src/com/bai/demo/adapter/Menu2Info4LeftListViewAdapter.java | c4734c1b868ff72c3e0e223afcfd248848ed0573 | [] | no_license | superman1982/android_demo | c94efe19ad1aec110528acf8ad8cc67e6027c121 | 558691665530f451f51f1ba17f14f55abf9cd873 | refs/heads/master | 2021-01-18T20:06:11.569432 | 2015-07-26T14:42:07 | 2015-07-26T14:42:07 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,333 | java | package com.bai.demo.adapter;
import java.util.List;
import java.util.Map;
import com.bai.demo.R;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class Menu2Info4LeftListViewAdapter extends BaseAdapter {
private LayoutInflater layoutInflater;
private List<Map<String,String>> data;
public Menu2Info4LeftListViewAdapter(Context context,List<Map<String,String>> data) {
this.layoutInflater=LayoutInflater.from(context);
this.data=data;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return data.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if(convertView==null){
convertView=layoutInflater.inflate(R.layout.right_menu2info4_listview_left_layout_item, null);
}
TextView tv_text=(TextView) convertView.findViewById(R.id.textview1);
tv_text.setText(data.get(position).get("item1"));
return convertView;
}
}
| [
"[email protected]"
] | |
30589f44ce173f4cf3a82336fe7c8c93d388258a | 909e2d926ed68defffb983d2d6192851a3c58532 | /myproject/src/com/jaimie/practice/GoTicket.java | 067ec6c80263aeac626cae218df4f5f3ec92115d | [] | no_license | Jaimieyeh/fju-java2019 | 70d08d4adf68bab14e36713f26b0df07eae34344 | 98911cf241ca5debfefc7f56200f16d6a5fd6889 | refs/heads/master | 2020-04-25T08:06:13.247559 | 2019-09-23T16:21:56 | 2019-09-23T16:21:56 | 172,634,912 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 282 | java | package com.jaimie.practice;
public class GoTicket {
String name;
int price = 700;
int number;
public GoTicket(String name, int number) {
this.name = name;
this.number = number;
}
public void print() {
System.out.print(name + "\t" + price + number);
}
}
| [
"user@es301n24"
] | user@es301n24 |
b2b18469f485b3342e9340568e038d6f841163ce | 0dbdcb76a5dfc8cb17412196794796ac3d6442f8 | /assignments/CoreJava/LambdaCalc/LambdaCalc.java | 9a1de25534d7dd24699ea6283885d2dfa448e624 | [] | no_license | Satyam005/IBM-FSD_BackEnd | 1bed02706f04328b8e4119c7e47631a4fce5a1af | dead90eb07be38372d513bb4bcc033eef692070c | refs/heads/master | 2020-04-30T08:49:13.288496 | 2019-04-08T06:17:53 | 2019-04-08T06:17:53 | 176,728,034 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,834 | java | //package com.assignments.core.java;
import java.util.function.BiFunction;
public class LambdaCalc {
public static void main(String args[]) {
LambdaCalc lamExp = new LambdaCalc();
BiFunction<Integer, Integer, Integer> addition = (Integer a, Integer b) -> a + b;
BiFunction<Integer, Integer, Integer> subtraction = (Integer a, Integer b) -> a - b;
BiFunction<Integer, Integer, Integer> multiplication = (Integer a, Integer b) -> a * b;
BiFunction<Integer, Integer, Integer> division = (Integer a, Integer b) -> a / b;
System.out.println("10 + 5 = " + lamExp.operate(10, 5, addition));
System.out.println("10 - 5 = " + lamExp.operate(10, 5, subtraction));
System.out.println("10 x 5 = " + lamExp.operate(10, 5, multiplication));
System.out.println("10 / 5 = " + lamExp.operate(10, 5, division));
//with type declaration
// MathOperation addition = (int a, int b) -> a + b;
//with out type declaration
// MathOperation subtraction = (a, b) -> a - b;
//with return statement along with curly braces
// MathOperation multiplication = (int a, int b) -> { return a * b; };
//without return statement and without curly braces
// MathOperation division = (int a, int b) -> a / b;
// System.out.println("10 + 5 = " + lamExp.operate(10, 5, addition));
// System.out.println("10 - 5 = " + lamExp.operate(10, 5, subtraction));
// System.out.println("10 x 5 = " + lamExp.operate(10, 5, multiplication));
// System.out.println("10 / 5 = " + lamExp.operate(10, 5, division));
}
private int operate(int a, int b, BiFunction<Integer, Integer, Integer>function) {
return function.apply(a, b);
}
} | [
"[email protected]"
] | |
c59dbfc006c53c22e99df24208275307f4681671 | 5b320ab3401ce3fe968ec57929dd8013474f5c09 | /02_Mobile Developer/01_Java(beginner) Programming Tutorials/065_The Final Check Box Program/apples.java | 0e7e5c0a50b2edea2517a1b4a4bc77206834ed49 | [] | no_license | abdibogor/Thenewboston | a7d701db4f233073b3bf0a422698e6accee885ff | 743ad015601fa308d74cca46bfc2159a01ad9821 | refs/heads/master | 2020-08-05T14:39:37.866343 | 2020-02-13T08:37:12 | 2020-02-13T08:37:12 | 212,581,907 | 0 | 0 | null | 2020-01-02T13:55:18 | 2019-10-03T13:03:56 | HTML | UTF-8 | Java | false | false | 228 | java | import javax.swing.JFrame;
class apples{
public static void main(String[] args) {
Gui go = new Gui();
go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
go.setSize(300,200);
go.setVisible(true);
}
} | [
"[email protected]"
] | |
071775531efb317557fd951df556890b2e44023c | d64379fdcd9a76b5e8b787a89337a4fe4a6f5270 | /BettingTotoro/src/member/model/dao/MemberDAO.java | c286a05bdb0003aab55f0a0c3755f44d36aacb80 | [] | no_license | hyeong0106/bettingTotoro | 6a61b79e8214863128431748b001bf9b28a48b97 | 2dac9f510a4363c7873d47f567f184946fdd76fa | refs/heads/master | 2020-07-23T03:36:24.849688 | 2019-09-10T01:49:25 | 2019-09-10T01:49:25 | 207,435,328 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 21,694 | java | package member.model.dao;
import static common.JDBCTemplate.close;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Properties;
import betting.model.vo.BettingOrder;
import betting.model.vo.BettingResult;
import member.model.vo.Member;
public class MemberDAO {
public static final int LOGIN_OK = 1;
public static final int WRONG_PASSWORD = 0;
public static final int ID_NOT_EXIST = -1;
private Properties prop = new Properties();
public MemberDAO() {
String fileName = getClass().getResource("/sql/member/member-query.properties")
.getPath();
try {
prop.load(new FileReader(fileName));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public int insertMember(Connection conn, Member m) {
int result = 0;
PreparedStatement pstmt = null;
String sql = prop.getProperty("insertMember");
try {
//미완성 쿼리를 가지고 statement객체 생성
pstmt = conn.prepareStatement(sql);
//미완성쿼리에 데이터 대입
pstmt.setString(1, m.getMemberId());
pstmt.setString(2, m.getPassword());
pstmt.setString(3, m.getMemberName());
pstmt.setString(4, m.getGender());
pstmt.setString(5, m.getEmail());
pstmt.setString(6, m.getPhone());
pstmt.setString(7, m.getHint());
//쿼리실행
result = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
close(pstmt);
}
return result;
}
public int loginCheck(Connection conn, Member m) {
int result = 0;
String sql = prop.getProperty("selectOne");
PreparedStatement pstmt =null;
ResultSet rset = null;
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, m.getMemberId());
rset = pstmt.executeQuery();
String memberId ="";
String password = "";
while(rset.next()) {
memberId =rset.getString("member_id");
password =rset.getString("password");
}
if(memberId.equals("")) {
result = ID_NOT_EXIST;
}
else if(memberId.equals(m.getMemberId())
&& password.equals(m.getPassword())) {
result = LOGIN_OK;
}
else if(memberId.equals(m.getMemberId()) && (!password.equals(m.getPassword()))) {
result = WRONG_PASSWORD;
}else if(password.equals(m.getPassword()) && (!memberId.equals(m.getMemberId()))) {
result = ID_NOT_EXIST;
}
}catch(SQLException e) {
e.printStackTrace();
}finally {
close(rset);
close(pstmt);
}
return result;
}
public Member selectOne(Connection conn, String id) {
Member m = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
String sql = prop.getProperty("selectOne");
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, id);
//쿼리실행
rset = pstmt.executeQuery();
//rset의 정보를 member객체에 옮겨담기
if(rset.next()) {
m = new Member();
m.setMemberNo(rset.getInt("member_No"));
m.setMemberId(rset.getString("member_id"));
m.setPassword(rset.getString("password"));
m.setMemberName(rset.getString("member_name"));
m.setGender(rset.getString("gender"));
m.setEmail(rset.getString("email"));
m.setPhone(rset.getString("phone"));
m.setHint(rset.getString("hint"));
m.setEnrollDate(rset.getDate("enrolldate"));
m.setPoint(rset.getInt("point"));
m.setScore(rset.getInt("score"));
}
// System.out.println("member@dao="+m);
} catch (SQLException e) {
e.printStackTrace();
} finally {
close(rset);
close(pstmt);
}
return m;
}
public Member selectOne(Connection conn, int member_no) {
Member m = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
String sql = prop.getProperty("selectOneByNo");
try {
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, member_no);
//쿼리실행
rset = pstmt.executeQuery();
//rset의 정보를 member객체에 옮겨담기
if(rset.next()) {
m = new Member();
m.setMemberNo(rset.getInt("member_No"));
m.setMemberId(rset.getString("member_id"));
m.setPassword(rset.getString("password"));
m.setMemberName(rset.getString("member_name"));
m.setGender(rset.getString("gender"));
m.setEmail(rset.getString("email"));
m.setPhone(rset.getString("phone"));
m.setHint(rset.getString("hint"));
m.setEnrollDate(rset.getDate("enrolldate"));
m.setPoint(rset.getInt("point"));
m.setScore(rset.getInt("score"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
close(rset);
close(pstmt);
}
return m;
}
public int checkIdDuplicate(Connection conn, String memberId_) {
int cnt= 0;
PreparedStatement pstmt =null;
ResultSet rset = null;
String sql = prop.getProperty("checkIdDuplicate");
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, memberId_);
rset = pstmt.executeQuery();
if(rset.next()) {
cnt = rset.getInt("cnt");
}
} catch (SQLException e) {
e.printStackTrace();
}
finally {
close(rset);
close(pstmt);
}
return cnt;
}
public String MemberSearchid(Connection conn,String searchname,String searchphone) {
String MemberSearchid = "";
PreparedStatement pstmt =null;
ResultSet rset = null;
String sql = prop.getProperty("selectMemberSearchId");
System.out.println(sql);
System.out.println("["+searchname+"]");
System.out.println("["+searchphone+"]");
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, searchname);
pstmt.setString(2, searchphone);
rset =pstmt.executeQuery();
if (rset.next()) {
MemberSearchid = rset.getString("member_id");
}
} catch (SQLException e) {
MemberSearchid = "등록된 아이디가 없습니다. 회원가입해주세요.";
e.printStackTrace();
}finally {
System.out.println("DAO의 MemberSearchid= "+MemberSearchid);
close(rset);
close(pstmt);
}
System.out.println("memberDAO="+MemberSearchid);
return MemberSearchid;
}
public Member MemberChangedPwd(Connection conn, Member pwd) {
int result = 0;
PreparedStatement pstmt =null;
String sql = prop.getProperty("MemberChangedPWd");
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1,pwd.getPassword());
pstmt.setString(2,pwd.getMemberId());
result = pstmt.executeUpdate();
if(result >0) {
System.out.println("업데이트되었습니다.");
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
System.out.println("PASSWORD의 값은 :"+ pwd.getPassword());
close(pstmt);
}
return pwd;
}
public int selectChangingMember(Connection conn, String searchid, String searchname, String searchphone,
String answer) {
int cnt =0;
Member m = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
String sql = prop.getProperty("selectChangingMember");
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, searchid);
pstmt.setString(2, searchname);
pstmt.setString(3, searchphone);
pstmt.setString(4, answer);
rset = pstmt.executeQuery();
if(rset.next()) {
cnt = rset.getInt("cnt");
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
close(rset);
close(pstmt);
}
return cnt;
}
public String MemberChangedPwd(Connection conn, String searchid,String changedpassword) {
int result=0;
String changedpwd ="";
PreparedStatement pstmt =null;
String sql = prop.getProperty("MemberChangedPWD");
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1,changedpassword);
pstmt.setString(2,searchid);
result = pstmt.executeUpdate();
if(result >0) {
System.out.println("업데이트되었습니다.");
changedpwd = changedpassword;
}
else {
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
close(pstmt);
}
return changedpwd;
}
public int updateMember(Connection conn, Member m) {
int result = 0;
PreparedStatement pstmt = null;
String sql = prop.getProperty("updateMember");
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, m.getPassword());
pstmt.setString(2, m.getMemberName());
pstmt.setString(3, m.getEmail());
pstmt.setString(4, m.getPhone());
pstmt.setString(5, m.getGender());
pstmt.setString(6, m.getMemberId());
//쿼리실행
result = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
close(pstmt);
}
return result;
}
public int deleteMember(Connection conn, String memberId) {
int result = 0;
PreparedStatement pstmt = null;
String sql = prop.getProperty("deleteMember");
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1,memberId);
result = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
close(pstmt);
}
return result;
}
public int giveBettingMoney(Connection conn, int memberNoList, int d, int e2) {
int result = 0;
PreparedStatement pstmt = null;
String sql = prop.getProperty("giveBettingMoney");
try {
pstmt = conn.prepareStatement(sql);
pstmt.setInt(3, memberNoList);
pstmt.setDouble(1, d);
pstmt.setDouble(2, e2);
result = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally {
close(pstmt);
}
return result;
}
public int UpdateMemberMoney(Connection conn, int member_no, int money, int money2) {
int result = 0;
PreparedStatement pstmt = null;
String sql = prop.getProperty("UpdateMemberMoney");
try {
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, money);
pstmt.setInt(2, money2);
pstmt.setInt(3, member_no);
result = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally {
close(pstmt);
}
return result;
}
public int getMemberNo(Connection conn, String memberId) {
int memberNo = 0;
PreparedStatement pstmt = null;
ResultSet rset = null;
String sql = prop.getProperty("getMemberNoByMemberId");
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, memberId);
rset = pstmt.executeQuery();
while(rset.next()) {
memberNo = rset.getInt("member_no");
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
close(rset);
close(pstmt);
}
return memberNo;
}
public ArrayList<BettingOrder> getBettingListByMemberNo(Connection conn, int memberno) {
ArrayList<BettingOrder> BOlist = new ArrayList<BettingOrder>();
PreparedStatement pstmt = null;
ResultSet rset =null;
String sql = prop.getProperty("getBettingListByMemberNo");
try {
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, memberno);
rset = pstmt.executeQuery();
while(rset.next()) {
BettingOrder BO = new BettingOrder();
BO.setBettingNo(rset.getInt("betting_no"));
BO.setBettingMoney(rset.getInt("Betting_money"));
BO.setBettingDate(rset.getString("Bettingdate"));
BO.setPass(rset.getInt("pass"));
BOlist.add(BO);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
close(rset);
close(pstmt);
}
return BOlist;
}
public int getBettingListByMemberNo(Connection conn, Member m) {
int result = 0;
PreparedStatement pstmt = null;
String sql = prop.getProperty("MadeItemList");
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, m.getMemberId());
result = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally {
close(pstmt);
}
return result;
}
public int selectChangingMember(Connection conn,Member searchpwd) {
int cnt =0;
Member m = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
String sql = prop.getProperty("selectChangingMember");
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, searchpwd.getMemberId());
pstmt.setString(2, searchpwd.getMemberName());
pstmt.setString(3, searchpwd.getPhone());
pstmt.setString(4, searchpwd.getHint());
rset = pstmt.executeQuery();
if(rset.next()) {
cnt = rset.getInt("cnt");
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
close(rset);
close(pstmt);
}
return cnt;
}
public int updateReasonFromMemberDel(Connection conn, String memberId, String content) {
int result = 0;
PreparedStatement pstmt = null;
String sql = prop.getProperty("updateReasonFromMemberDel");
try {
//미완성 쿼리를 가지고 statement객체 생성
pstmt = conn.prepareStatement(sql);
//미완성쿼리에 데이터 대입
pstmt.setString(1, content);
pstmt.setString(2, memberId);
//쿼리실행
result = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
close(pstmt);
}
return result;
}
public ArrayList<BettingOrder> getBettingListByMemberNo(Connection conn, int memberno, int cPage, int numPerPage) {
ArrayList<BettingOrder> BOlist = new ArrayList<BettingOrder>();
PreparedStatement pstmt = null;
ResultSet rset =null;
String sql = prop.getProperty("getBettingListByMemberNo");
try {
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, memberno);
pstmt.setInt(2, (cPage-1)*numPerPage+1);
pstmt.setInt(3, cPage*numPerPage);
rset = pstmt.executeQuery();
while(rset.next()) {
BettingOrder BO = new BettingOrder();
BO.setBettingOrderNo(rset.getInt("betting_order_no"));
BO.setBettingNo(rset.getInt("betting_no"));
BO.setBettingMoney(rset.getInt("Betting_money"));
BO.setBettingDate(rset.getString("Bettingdate"));
BO.setPass(rset.getInt("pass"));
BOlist.add(BO);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
close(rset);
close(pstmt);
}
return BOlist;
}
public int selectBettingCount(Connection conn, int memberno) {
PreparedStatement pstmt = null;
int totalMember = 0;
ResultSet rset = null;
String query = prop.getProperty("selectMemberBettingCount");
try{
//미완성쿼리문을 가지고 객체생성.
pstmt = conn.prepareStatement(query);
pstmt.setInt(1, memberno);
//쿼리문실행
rset = pstmt.executeQuery();
while(rset.next()){
totalMember = rset.getInt("cnt");
}
}catch(Exception e){
e.printStackTrace();
}finally{
close(rset);
close(pstmt);
}
return totalMember;
}
public ArrayList<Member> selectAllMember(Connection conn) {
ArrayList<Member> memberList = new ArrayList<Member>();
PreparedStatement pstmt = null;
ResultSet rset =null;
String sql = prop.getProperty("selectAllMemberPointTop");
try {
pstmt = conn.prepareStatement(sql);
rset = pstmt.executeQuery();
while(rset.next()) {
Member m = new Member();
m.setMemberNo(rset.getInt("member_No"));
m.setMemberId(rset.getString("member_id"));
m.setPassword(rset.getString("password"));
m.setMemberName(rset.getString("member_name"));
m.setGender(rset.getString("gender"));
m.setEmail(rset.getString("email"));
m.setPhone(rset.getString("phone"));
m.setHint(rset.getString("hint"));
m.setEnrollDate(rset.getDate("enrolldate"));
m.setPoint(rset.getInt("point"));
m.setScore(rset.getInt("score"));
memberList.add(m);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
close(rset);
close(pstmt);
}
return memberList;
}
public ArrayList<Member> selectScoreTop(Connection conn) {
ArrayList<Member> memberList = new ArrayList<Member>();
PreparedStatement pstmt = null;
ResultSet rset =null;
String sql = prop.getProperty("selectScoreTop");
try {
pstmt = conn.prepareStatement(sql);
rset = pstmt.executeQuery();
while(rset.next()) {
Member m = new Member();
m.setMemberNo(rset.getInt("member_No"));
m.setMemberId(rset.getString("member_id"));
m.setPassword(rset.getString("password"));
m.setMemberName(rset.getString("member_name"));
m.setGender(rset.getString("gender"));
m.setEmail(rset.getString("email"));
m.setPhone(rset.getString("phone"));
m.setHint(rset.getString("hint"));
m.setEnrollDate(rset.getDate("enrolldate"));
m.setPoint(rset.getInt("point"));
m.setScore(rset.getInt("score"));
memberList.add(m);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
close(rset);
close(pstmt);
}
return memberList;
}
public ArrayList<Member> selectScoreWorst(Connection conn) {
ArrayList<Member> memberList = new ArrayList<Member>();
PreparedStatement pstmt = null;
ResultSet rset =null;
String sql = prop.getProperty("selectScoreWorst");
try {
pstmt = conn.prepareStatement(sql);
rset = pstmt.executeQuery();
while(rset.next()) {
Member m = new Member();
m.setMemberNo(rset.getInt("member_No"));
m.setMemberId(rset.getString("member_id"));
m.setPassword(rset.getString("password"));
m.setMemberName(rset.getString("member_name"));
m.setGender(rset.getString("gender"));
m.setEmail(rset.getString("email"));
m.setPhone(rset.getString("phone"));
m.setHint(rset.getString("hint"));
m.setEnrollDate(rset.getDate("enrolldate"));
m.setPoint(rset.getInt("point"));
m.setScore(rset.getInt("score"));
memberList.add(m);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
close(rset);
close(pstmt);
}
return memberList;
}
public boolean checkLogin(Connection conn, String id) {
boolean Already = false;
PreparedStatement pstmt = null;
ResultSet rset =null;
String sql = prop.getProperty("checkLogin");
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, id);
rset=pstmt.executeQuery();
if(rset.next()) {
Already= true;
}
else {
Already= false;
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
close(rset);
close(pstmt);
}
return Already;
}
public int insertIntoLoginList(Connection conn, String id) {
int result = 0;
PreparedStatement pstmt = null;
String sql = prop.getProperty("insertIntoLoginList");
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, id);
result = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally {
close(pstmt);
}
return result;
}
public int updateLoginList(Connection conn, String memberId) {
int result = 0;
PreparedStatement pstmt = null;
String sql = prop.getProperty("updateLoginList");
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, memberId);
result = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally {
close(pstmt);
}
return result;
}
public int resetLoginList(Connection conn) {
int result = 0;
PreparedStatement pstmt = null;
String sql = prop.getProperty("resetLoginList");
try {
pstmt = conn.prepareStatement(sql);
result = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally {
close(pstmt);
}
return result;
}
public String selectBadeg(Connection conn, String memberId) {
String BadgeList = "";
PreparedStatement pstmt = null;
String sql = prop.getProperty("selectBadge");
ResultSet rset = null;
String s = "";
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, memberId);
rset = pstmt.executeQuery();
if(rset.next()) {
BadgeList = rset.getString("badge");
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
close(rset);
close(pstmt);
}
return BadgeList;
}
}
| [
"[email protected]"
] | |
c4723936f0cc40da7a9bf88a690b4bd00b5134f8 | e5596a5814b2fe4483ab316c736fa2ba8ac4fab4 | /demo/src/test/java/com/example/demo/repository/ItemRepositoryFT.java | a6ee987a0f5a53928999d24a793b59de40f710cd | [] | no_license | jdcyuen/mcellblock | a3643bc65f997bccf92553d6076cbb796d7331ee | 15cc3fa8613aeeaa460b0045b5becd4d9f8daf51 | refs/heads/master | 2020-06-01T16:32:25.575685 | 2019-08-08T20:32:24 | 2019-08-08T20:32:24 | 190,851,118 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,857 | java | package com.example.demo.repository;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.example.demo.repository.entity.Item;
import junit.framework.Assert;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ItemRepositoryFT {
@Autowired
ItemRepository itemRepo;
@Before
public void setUp() throws Exception {
}
@Test
public void findByCategoryTest() {
List<Item> items = itemRepo.findByCategory("Crystal");
Assert.assertTrue( items.size() > 0);
for(Item i : items) {
System.out.println(i.toString());
}
System.out.println("===============================");
}
@Test
public void findAll() {
List<Item> items = itemRepo.findAll();
Assert.assertTrue( items.size() > 0);
for(Item i : items) {
System.out.println(i.toString());
}
System.out.println("===============================");
}
@Test
public void findAllCategories() {
List<String> categories = itemRepo.findAllCategories();
Assert.assertTrue( categories.size() > 0);
for(String category : categories) {
System.out.println(category);
}
System.out.println("===============================");
}
@Test
public void findByCategoryAndId() {
Item item = itemRepo.findByCategoryAndId("Crystal", 1L);
Assert.assertNotNull(item);
System.out.println(item.toString());
System.out.println("===============================");
}
@Test
public void findById() {
Item item = itemRepo.findById(3L);
Assert.assertNotNull(item);
System.out.println(item.toString());
System.out.println("===============================");
}
}
| [
"[email protected]"
] | |
31a9c1389b99c411e62fa8f2cad6f70f5f75e053 | 1142756a0b3a0a4308cb45eaaddba30454320de3 | /onlineshopping/src/main/java/Ecom/onlineshopping/service/CartService.java | 059ada29dd39cf578bdaa187282a89cd0aaba977 | [] | no_license | Akilan1212/simple-online-shopping | ea243d6fbccbee5ab757e58c9de36491bc46a277 | 60201ac20c62e917f5e4e82fa56ab19cd5363bc6 | refs/heads/master | 2020-03-20T21:56:44.049425 | 2018-06-18T16:05:53 | 2018-06-18T16:05:53 | 137,769,988 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,151 | java | package Ecom.onlineshopping.service;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import Ecom.onlineshopping.model.UserModel;
import Ecom.shopingbackend.dao.CartLineDAO;
import Ecom.shopingbackend.dao.ProductDAO;
import Ecom.shopingbackend.dto.Cart;
import Ecom.shopingbackend.dto.CartLine;
import Ecom.shopingbackend.dto.Product;
@Service("cartService")
public class CartService {
@Autowired
private CartLineDAO cartLineDAO;
@Autowired
private ProductDAO productDAO;
@Autowired
private HttpSession session;
//returns the cart of the user who has logged in
private Cart getCart()
{
return ((UserModel)session.getAttribute("userModel")).getCart();
}
// returns the entire cart lines
public List<CartLine> getCartLines() {
return cartLineDAO.list(this.getCart().getId());
}
public String updateCartLine(int cartLineId, int count) {
// fetch the cart line
System.out.println("dummy data");
CartLine cartLine = cartLineDAO.get(cartLineId);
System.out.println("dummy data one");
if(cartLine == null) {
return "result=error";
}
else {
Product product = cartLine.getProduct();
double oldTotal = cartLine.getTotal();
if(product.getQuantity() <= count) {
count = product.getQuantity();
}
cartLine.setProductCount(count);
cartLine.setBuyingPrice(product.getUnitPrice());
cartLine.setTotal(product.getUnitPrice() * count);
cartLineDAO.update(cartLine);
Cart cart = this.getCart();
cart.setGrandTotal(cart.getGrandTotal() - oldTotal + cartLine.getTotal());
cartLineDAO.updateCart(cart);
return "result=updated";
}
}
public String deleteCartLine(int cartLineId) {
// fetch the cartLine
CartLine cartLine = cartLineDAO.get(cartLineId);
if(cartLine == null) {
return "result=error";
}
else {
// update the cart
Cart cart = this.getCart();
cart.setGrandTotal(cart.getGrandTotal() - cartLine.getTotal());
cart.setCartLines(cart.getCartLines() - 1);
cartLineDAO.updateCart(cart);
// remove the cart line
cartLineDAO.delete(cartLine);
return "result=deleted";
}
}
public String addCartLine(int productId) {
String response = null;
Cart cart = this.getCart();
CartLine cartLine = cartLineDAO.getByCartAndProduct(cart.getId(), productId);
if(cartLine == null) {
// add a new cartLine
cartLine = new CartLine();
// fetch the product
Product product = productDAO.get(productId);
cartLine.setCartId(cart.getId());
cartLine.setProduct(product);
cartLine.setBuyingPrice(product.getUnitPrice());
cartLine.setProductCount(1);
cartLine.setTotal(product.getUnitPrice());
cartLine.setAvailable(true);
cartLineDAO.add(cartLine);
cart.setCartLines(cart.getCartLines() + 1);
cart.setGrandTotal(cart.getGrandTotal() + cartLine.getTotal());
cartLineDAO.updateCart(cart);
response = "result=added";
}
return response;
}
}
| [
"[email protected]"
] | |
3c776cdfea8861a4d5cdf08ab7e9939b3983898f | 28513707f1411c4be1fd6b01b8f4d4f51dc7c7c3 | /interfaceLuo/src_0/com/jite/hibgen/model/TUserLoginlog.java | 3652103bb690cac0de887d4406e19093fb573d21 | [] | no_license | lluuoo/interfaceLuo | b4e38c3082751fcfbf6d766e36e65bc8e9dfdfaa | 91bf801c29cb2053b2a6b9ff2866b4668f586af9 | refs/heads/master | 2020-03-22T02:33:20.048119 | 2018-07-02T01:47:39 | 2018-07-02T01:47:39 | 139,377,876 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,006 | java | package com.jite.hibgen.model;
// Generated 2018-3-26 10:06:46 by Hibernate Tools 4.3.1.Final
import java.util.Date;
/**
* TUserLoginlog generated by hbm2java
*/
public class TUserLoginlog implements java.io.Serializable {
private Long id;
private Long userId;
private Date loginTime;
private Date logoutTime;
public TUserLoginlog() {
}
public TUserLoginlog(Long userId, Date loginTime, Date logoutTime) {
this.userId = userId;
this.loginTime = loginTime;
this.logoutTime = logoutTime;
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public Long getUserId() {
return this.userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Date getLoginTime() {
return this.loginTime;
}
public void setLoginTime(Date loginTime) {
this.loginTime = loginTime;
}
public Date getLogoutTime() {
return this.logoutTime;
}
public void setLogoutTime(Date logoutTime) {
this.logoutTime = logoutTime;
}
}
| [
"luo.163.com"
] | luo.163.com |
40bc1f4f9e50cbe7be76a9ff832429de4ff8f023 | 2560aaaae8e5559e8e43e737ba98a4d71a490381 | /Game/src/Interface/InterfaceConsole.java | 045334000510c665be8d38d329c6332513b3fcf6 | [] | no_license | bleubidon/RobotTurtles | b1746b215d6d987ee24f65e9ecf6099239f0c6dd | 1c6f83e7a1f2efca93d8a1b844248ee07d16d5af | refs/heads/master | 2021-05-24T13:24:52.699551 | 2020-02-26T15:36:34 | 2020-02-26T15:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,674 | java | package src.Interface;
import src.Cartes.Carte;
import src.Joueur;
import src.LogiqueDeJeu;
import src.Tuiles.Obstacle;
import src.Tuiles.Orientations;
import java.util.Scanner;
public class InterfaceConsole implements Interface {
private Scanner scanner = new Scanner(System.in);
@Override
public void actualiser() {
}
@Override
public String getTypeInterface() {
return "Console";
}
@Override
public void afficherMessage(String message) {
System.out.println(message);
}
@Override
public void afficherPlateau(LogiqueDeJeu logiqueDeJeu) {
int taillePlateau = logiqueDeJeu.getPlateau().getTaillePlateau();
for (int i = 0; i < taillePlateau; i++) {
for (int j = 0; j < taillePlateau; j++) {
System.out.print(logiqueDeJeu.getPlateau().getCase(i, j) == null ? "." : logiqueDeJeu.getPlateau().getCase(i, j));
System.out.print("\t");
}
System.out.println();
}
}
@Override
public ParametresInitPartie parametresMenu() {
int nombreJoueurs;
do {
System.out.println("Combien de joueurs ? (entre 2 et 4): ");
nombreJoueurs = Integer.parseInt(scanner.nextLine().trim());
} while (nombreJoueurs < 2 || nombreJoueurs > 4);
String modeJeu;
do {
System.out.println("Quel mode de jeu ? ('normal' / '3alasuite'): ");
modeJeu = scanner.nextLine();
} while (!modeJeu.equals("normal") && !modeJeu.equals("3alasuite"));
String modeCarteBug;
System.out.println("Jouer avec les cartes Bug ? (o/N): "); // Valeur par defaut = "N"
modeCarteBug = scanner.nextLine();
return new ParametresInitPartie(nombreJoueurs, modeJeu, modeCarteBug.equals("o"));
}
@Override
public String demanderAction(LogiqueDeJeu logiqueDeJeu) {
String action;
if (!logiqueDeJeu.isModeBug()) {
do {
System.out.println("Action ? (P/M/E (completer prgm/mur/executer prgm): ");
action = scanner.nextLine();
} while (!action.equals("P") && !action.equals("M") && !action.equals("E"));
} else {
do {
System.out.println("Action ? (P/M/E/B (completer prgm/mur/executer prgm/utiliser carte bug): ");
action = scanner.nextLine();
} while (!action.equals("P") && !action.equals("M") && !action.equals("E") && !action.equals("B"));
}
return action;
}
@Override
public void afficherCartesMain(String str_, LogiqueDeJeu logiqueDeJeu) {
System.out.println("Cartes dans votre main:");
for (Carte carteMain : logiqueDeJeu.getJoueurCourant().getCartesMain().getCartesMain()) {
System.out.println(carteMain.getTypeCarte());
}
}
@Override
public void afficherProgramme(LogiqueDeJeu logiqueDeJeu) {
System.out.println("Votre programme courant:");
for (Carte cartePrgm : logiqueDeJeu.getJoueurCourant().getProgramme().getProgramme()) {
System.out.println(cartePrgm.getTypeCarte());
}
}
@Override
public String demanderCarteAAjouterAProgramme() {
String carteStr;
do {
System.out.println("Indiquer carte (CARTE_BLEUE/CARTE_JAUNE/CARTE_VIOLETTE/LASER/NOT_A_CARD) a ajouter a votre programme");
carteStr = scanner.nextLine();
} while (!carteStr.equals("CARTE_BLEUE") && !carteStr.equals("CARTE_JAUNE") && !carteStr.equals("CARTE_VIOLETTE") && !carteStr.equals("LASER") && !carteStr.equals("NOT_A_CARD"));
return carteStr;
}
@Override
public Obstacle demanderObstacleAPlacer() {
String typeObstacle;
do {
System.out.println("Quel type d'obstacle voulez-vous placer ? (g/p)");
typeObstacle = scanner.nextLine();
} while (!typeObstacle.equals("g") && !typeObstacle.equals("p"));
int[] coordsObstacle = new int[2];
System.out.println("A quelles coordonees ?");
coordsObstacle[0] = Integer.parseInt(scanner.nextLine().trim());
coordsObstacle[1] = Integer.parseInt(scanner.nextLine().trim());
return new Obstacle(typeObstacle, coordsObstacle);
}
@Override
public int demanderCibleCarteBug(LogiqueDeJeu logiqueDeJeu) {
int cibleCarteBug;
do {
System.out.println("Entrez le numero du joueur a qui vous voulez poser votre carte bug:");
cibleCarteBug = Integer.parseInt(scanner.nextLine().trim());
} while (cibleCarteBug < 0 || cibleCarteBug > logiqueDeJeu.getNombreJoueurs() - 1 || cibleCarteBug == logiqueDeJeu.getJoueurCourant().getNumeroJoueur());
return cibleCarteBug;
}
@Override
public String demanderChoixDefausse() {
String choixCarteADefausser;
do {
System.out.println("Indiquer carte (CARTE_BLEUE/CARTE_JAUNE/CARTE_VIOLETTE/LASER/NOT_A_CARD) a defausser de votre main");
choixCarteADefausser = scanner.nextLine();
} while (!choixCarteADefausser.equals("CARTE_BLEUE") && !choixCarteADefausser.equals("CARTE_JAUNE") && !choixCarteADefausser.equals("CARTE_VIOLETTE") && !choixCarteADefausser.equals("LASER") && !choixCarteADefausser.equals("NOT_A_CARD"));
return choixCarteADefausser;
}
@Override
public void afficherResultats(LogiqueDeJeu logiqueDeJeu) {
System.out.println("\n////////////////////");
System.out.println("TERMINE, voici le classement");
for (Joueur joueur : logiqueDeJeu.getJoueurs()) {
System.out.print("Joueur " + joueur.getNumeroJoueur() + ": ");
System.out.print(joueur.getClassement() + "°");
switch (logiqueDeJeu.getModeJeu()) {
case "normal":
System.out.println();
break;
case "3alasuite":
System.out.println(" avec " + joueur.getScore() + " points");
break;
}
}
}
@Override
public void afficherFinManche(LogiqueDeJeu logiqueDeJeu) {
System.out.println("\n\\\\\\\\");
System.out.println("Fin de la manche " + (logiqueDeJeu.getNumeroManche() + 1) + " !");
for (Joueur joueur : logiqueDeJeu.getJoueurs()) {
System.out.print("Joueur " + joueur.getNumeroJoueur() + ": score courant = ");
System.out.println(joueur.getScore());
}
}
@Override
public void animationLaser(int[] pos, Orientations orient) {
}
@Override
public void stopLaser() {
}
}
| [
"[email protected]"
] | |
4c78a53069d624093d4a11cc583135dc93f91dba | 343e0f9f73acac93d9ad036b1b5f1c2a76ac17ed | /android/src/test/java/io/grpc/android/AndroidChannelBuilderTest.java | faf998f724df5c988bb7a6615d4805b16f224275 | [
"Apache-2.0"
] | permissive | dmvk/grpc-java | 70d4d3a97c04eb89db7983556b4ed7490d2aae52 | 8f51c2731929ac104706f3f33f689c1cc2e4cd8d | refs/heads/master | 2020-03-19T11:40:57.782194 | 2018-06-07T00:14:58 | 2018-06-07T00:14:58 | 136,468,807 | 0 | 0 | Apache-2.0 | 2018-06-07T11:41:00 | 2018-06-07T11:41:00 | null | UTF-8 | Java | false | false | 14,127 | java | /*
* Copyright 2018 The gRPC Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.grpc.android;
import static android.os.Build.VERSION_CODES.LOLLIPOP;
import static android.os.Build.VERSION_CODES.N;
import static com.google.common.truth.Truth.assertThat;
import static org.robolectric.RuntimeEnvironment.getApiLevel;
import static org.robolectric.Shadows.shadowOf;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import io.grpc.CallOptions;
import io.grpc.ClientCall;
import io.grpc.ManagedChannel;
import io.grpc.MethodDescriptor;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import org.robolectric.shadows.ShadowConnectivityManager;
import org.robolectric.shadows.ShadowNetwork;
import org.robolectric.shadows.ShadowNetworkInfo;
@RunWith(RobolectricTestRunner.class)
@Config(shadows = {AndroidChannelBuilderTest.ShadowDefaultNetworkListenerConnectivityManager.class})
public final class AndroidChannelBuilderTest {
private final NetworkInfo WIFI_CONNECTED =
ShadowNetworkInfo.newInstance(
NetworkInfo.DetailedState.CONNECTED, ConnectivityManager.TYPE_WIFI, 0, true, true);
private final NetworkInfo WIFI_DISCONNECTED =
ShadowNetworkInfo.newInstance(
NetworkInfo.DetailedState.DISCONNECTED, ConnectivityManager.TYPE_WIFI, 0, true, false);
private final NetworkInfo MOBILE_CONNECTED =
ShadowNetworkInfo.newInstance(
NetworkInfo.DetailedState.CONNECTED,
ConnectivityManager.TYPE_MOBILE,
ConnectivityManager.TYPE_MOBILE_MMS,
true,
true);
private final NetworkInfo MOBILE_DISCONNECTED =
ShadowNetworkInfo.newInstance(
NetworkInfo.DetailedState.DISCONNECTED,
ConnectivityManager.TYPE_MOBILE,
ConnectivityManager.TYPE_MOBILE_MMS,
true,
false);
private ConnectivityManager connectivityManager;
private ShadowConnectivityManager shadowConnectivityManager;
@Before
public void setUp() {
connectivityManager =
(ConnectivityManager)
RuntimeEnvironment.application.getSystemService(Context.CONNECTIVITY_SERVICE);
shadowConnectivityManager = shadowOf(connectivityManager);
}
@Test
public void channelBuilderClassFoundReflectively() {
// This should not throw with OkHttpChannelBuilder on the classpath
AndroidChannelBuilder.forTarget("target");
}
@Test
@Config(sdk = 23)
public void nullContextDoesNotThrow_api23() {
TestChannel delegateChannel = new TestChannel();
ManagedChannel androidChannel = new AndroidChannelBuilder.AndroidChannel(delegateChannel, null);
// Network change and shutdown should be no-op for the channel without an Android Context
shadowConnectivityManager.setActiveNetworkInfo(WIFI_CONNECTED);
RuntimeEnvironment.application.sendBroadcast(
new Intent(ConnectivityManager.CONNECTIVITY_ACTION));
androidChannel.shutdown();
assertThat(delegateChannel.resetCount).isEqualTo(0);
}
@Test
@Config(sdk = 24)
public void nullContextDoesNotThrow_api24() {
shadowConnectivityManager.setActiveNetworkInfo(MOBILE_DISCONNECTED);
TestChannel delegateChannel = new TestChannel();
ManagedChannel androidChannel = new AndroidChannelBuilder.AndroidChannel(delegateChannel, null);
// Network change and shutdown should be no-op for the channel without an Android Context
shadowConnectivityManager.setActiveNetworkInfo(MOBILE_CONNECTED);
androidChannel.shutdown();
assertThat(delegateChannel.resetCount).isEqualTo(0);
assertThat(delegateChannel.enterIdleCount).isEqualTo(0);
}
@Test
@Config(sdk = 23)
public void resetConnectBackoff_api23() {
TestChannel delegateChannel = new TestChannel();
ManagedChannel androidChannel =
new AndroidChannelBuilder.AndroidChannel(
delegateChannel, RuntimeEnvironment.application.getApplicationContext());
assertThat(delegateChannel.resetCount).isEqualTo(0);
// On API levels < 24, the broadcast receiver will invoke resetConnectBackoff() on the first
// connectivity action broadcast regardless of previous connection status
shadowConnectivityManager.setActiveNetworkInfo(WIFI_CONNECTED);
RuntimeEnvironment.application.sendBroadcast(
new Intent(ConnectivityManager.CONNECTIVITY_ACTION));
assertThat(delegateChannel.resetCount).isEqualTo(1);
// The broadcast receiver may fire when the active network status has not actually changed
RuntimeEnvironment.application.sendBroadcast(
new Intent(ConnectivityManager.CONNECTIVITY_ACTION));
assertThat(delegateChannel.resetCount).isEqualTo(1);
// Drop the connection
shadowConnectivityManager.setActiveNetworkInfo(null);
RuntimeEnvironment.application.sendBroadcast(
new Intent(ConnectivityManager.CONNECTIVITY_ACTION));
assertThat(delegateChannel.resetCount).isEqualTo(1);
// Notify that a new but not connected network is available
shadowConnectivityManager.setActiveNetworkInfo(MOBILE_DISCONNECTED);
RuntimeEnvironment.application.sendBroadcast(
new Intent(ConnectivityManager.CONNECTIVITY_ACTION));
assertThat(delegateChannel.resetCount).isEqualTo(1);
// Establish a connection
shadowConnectivityManager.setActiveNetworkInfo(MOBILE_CONNECTED);
RuntimeEnvironment.application.sendBroadcast(
new Intent(ConnectivityManager.CONNECTIVITY_ACTION));
assertThat(delegateChannel.resetCount).isEqualTo(2);
// Disconnect, then shutdown the channel and verify that the broadcast receiver has been
// unregistered
shadowConnectivityManager.setActiveNetworkInfo(null);
RuntimeEnvironment.application.sendBroadcast(
new Intent(ConnectivityManager.CONNECTIVITY_ACTION));
androidChannel.shutdown();
shadowConnectivityManager.setActiveNetworkInfo(MOBILE_CONNECTED);
RuntimeEnvironment.application.sendBroadcast(
new Intent(ConnectivityManager.CONNECTIVITY_ACTION));
assertThat(delegateChannel.resetCount).isEqualTo(2);
// enterIdle is not called on API levels < 24
assertThat(delegateChannel.enterIdleCount).isEqualTo(0);
}
@Test
@Config(sdk = 24)
public void resetConnectBackoffAndEnterIdle_api24() {
shadowConnectivityManager.setActiveNetworkInfo(MOBILE_DISCONNECTED);
TestChannel delegateChannel = new TestChannel();
ManagedChannel androidChannel =
new AndroidChannelBuilder.AndroidChannel(
delegateChannel, RuntimeEnvironment.application.getApplicationContext());
assertThat(delegateChannel.resetCount).isEqualTo(0);
assertThat(delegateChannel.enterIdleCount).isEqualTo(0);
// Establish an initial network connection
shadowConnectivityManager.setActiveNetworkInfo(MOBILE_CONNECTED);
assertThat(delegateChannel.resetCount).isEqualTo(1);
assertThat(delegateChannel.enterIdleCount).isEqualTo(0);
// Switch to another network to trigger enterIdle()
shadowConnectivityManager.setActiveNetworkInfo(WIFI_CONNECTED);
assertThat(delegateChannel.resetCount).isEqualTo(1);
assertThat(delegateChannel.enterIdleCount).isEqualTo(1);
// Switch to an offline network and then to null
shadowConnectivityManager.setActiveNetworkInfo(WIFI_DISCONNECTED);
shadowConnectivityManager.setActiveNetworkInfo(null);
assertThat(delegateChannel.resetCount).isEqualTo(1);
assertThat(delegateChannel.enterIdleCount).isEqualTo(1);
// Establish a connection
shadowConnectivityManager.setActiveNetworkInfo(MOBILE_CONNECTED);
assertThat(delegateChannel.resetCount).isEqualTo(2);
assertThat(delegateChannel.enterIdleCount).isEqualTo(1);
// Disconnect, then shutdown the channel and verify that the callback has been unregistered
shadowConnectivityManager.setActiveNetworkInfo(null);
androidChannel.shutdown();
shadowConnectivityManager.setActiveNetworkInfo(MOBILE_CONNECTED);
assertThat(delegateChannel.resetCount).isEqualTo(2);
assertThat(delegateChannel.enterIdleCount).isEqualTo(1);
}
@Test
@Config(sdk = 24)
public void newChannelWithConnection_entersIdleOnConnectionChange_api24() {
shadowConnectivityManager.setActiveNetworkInfo(MOBILE_CONNECTED);
TestChannel delegateChannel = new TestChannel();
ManagedChannel androidChannel =
new AndroidChannelBuilder.AndroidChannel(
delegateChannel, RuntimeEnvironment.application.getApplicationContext());
shadowConnectivityManager.setActiveNetworkInfo(WIFI_CONNECTED);
assertThat(delegateChannel.resetCount).isEqualTo(0);
assertThat(delegateChannel.enterIdleCount).isEqualTo(1);
androidChannel.shutdown();
}
@Test
@Config(sdk = 23)
public void shutdownNowUnregistersBroadcastReceiver_api23() {
TestChannel delegateChannel = new TestChannel();
ManagedChannel androidChannel =
new AndroidChannelBuilder.AndroidChannel(
delegateChannel, RuntimeEnvironment.application.getApplicationContext());
shadowConnectivityManager.setActiveNetworkInfo(null);
RuntimeEnvironment.application.sendBroadcast(
new Intent(ConnectivityManager.CONNECTIVITY_ACTION));
androidChannel.shutdownNow();
shadowConnectivityManager.setActiveNetworkInfo(WIFI_CONNECTED);
RuntimeEnvironment.application.sendBroadcast(
new Intent(ConnectivityManager.CONNECTIVITY_ACTION));
assertThat(delegateChannel.resetCount).isEqualTo(0);
}
@Test
@Config(sdk = 24)
public void shutdownNowUnregistersNetworkCallback_api24() {
shadowConnectivityManager.setActiveNetworkInfo(null);
TestChannel delegateChannel = new TestChannel();
ManagedChannel androidChannel =
new AndroidChannelBuilder.AndroidChannel(
delegateChannel, RuntimeEnvironment.application.getApplicationContext());
androidChannel.shutdownNow();
shadowConnectivityManager.setActiveNetworkInfo(WIFI_CONNECTED);
assertThat(delegateChannel.resetCount).isEqualTo(0);
}
/**
* Extends Robolectric ShadowConnectivityManager to handle Android N's
* registerDefaultNetworkCallback API.
*/
@Implements(value = ConnectivityManager.class)
public static class ShadowDefaultNetworkListenerConnectivityManager
extends ShadowConnectivityManager {
private HashSet<ConnectivityManager.NetworkCallback> defaultNetworkCallbacks = new HashSet<>();
public ShadowDefaultNetworkListenerConnectivityManager() {
super();
}
@Override
public void setActiveNetworkInfo(NetworkInfo activeNetworkInfo) {
if (getApiLevel() >= N) {
NetworkInfo previousNetworkInfo = getActiveNetworkInfo();
if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
notifyDefaultNetworkCallbacksOnAvailable(
ShadowNetwork.newInstance(activeNetworkInfo.getType() /* use type as network ID */));
} else if (previousNetworkInfo != null) {
notifyDefaultNetworkCallbacksOnLost(
ShadowNetwork.newInstance(
previousNetworkInfo.getType() /* use type as network ID */));
}
}
super.setActiveNetworkInfo(activeNetworkInfo);
}
private void notifyDefaultNetworkCallbacksOnAvailable(Network network) {
for (ConnectivityManager.NetworkCallback networkCallback : defaultNetworkCallbacks) {
networkCallback.onAvailable(network);
}
}
private void notifyDefaultNetworkCallbacksOnLost(Network network) {
for (ConnectivityManager.NetworkCallback networkCallback : defaultNetworkCallbacks) {
networkCallback.onLost(network);
}
}
@Implementation(minSdk = N)
protected void registerDefaultNetworkCallback(
ConnectivityManager.NetworkCallback networkCallback) {
defaultNetworkCallbacks.add(networkCallback);
}
@Implementation(minSdk = LOLLIPOP)
@Override
public void unregisterNetworkCallback(ConnectivityManager.NetworkCallback networkCallback) {
if (getApiLevel() >= N) {
if (networkCallback != null || defaultNetworkCallbacks.contains(networkCallback)) {
defaultNetworkCallbacks.remove(networkCallback);
}
}
super.unregisterNetworkCallback(networkCallback);
}
}
private static class TestChannel extends ManagedChannel {
int resetCount;
int enterIdleCount;
@Override
public ManagedChannel shutdown() {
return null;
}
@Override
public boolean isShutdown() {
return false;
}
@Override
public boolean isTerminated() {
return false;
}
@Override
public ManagedChannel shutdownNow() {
return null;
}
@Override
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
return false;
}
@Override
public <RequestT, ResponseT> ClientCall<RequestT, ResponseT> newCall(
MethodDescriptor<RequestT, ResponseT> methodDescriptor, CallOptions callOptions) {
return null;
}
@Override
public String authority() {
return null;
}
@Override
public void resetConnectBackoff() {
resetCount++;
}
@Override
public void enterIdle() {
enterIdleCount++;
}
}
}
| [
"[email protected]"
] | |
176dfd6272f518c854974ddf219c011e9507eb05 | 5827680a971ec56d5636d1ee112793b870f91122 | /[FINAL]/[FSXPlanner]/src/flightsim/simconnect/recv/SimConnectException.java | 139d975c699c6fa353da4b43e3646ab05c858d7c | [] | no_license | bily/fsxp | 61185fad6d87a1b0bc6d98dbdb8a02bd7e83c0cb | 39f1ff19a2fd5b86e764602baf543298d985b303 | refs/heads/master | 2021-01-20T04:33:10.510213 | 2012-08-12T07:28:23 | 2012-08-12T07:28:23 | 7,416,727 | 3 | 4 | null | null | null | null | UTF-8 | Java | false | false | 1,852 | java | package flightsim.simconnect.recv;
import flightsim.simconnect.Messages;
public enum SimConnectException {
NONE,
ERROR,
SIZE_MISMATCH,
UNRECOGNIZED_ID,
UNOPENED,
VERSION_MISMATCH,
TOO_MANY_GROUPS,
NAME_UNRECOGNIZED,
TOO_MANY_EVENT_NAMES,
EVENT_ID_DUPLICATE,
TOO_MANY_MAPS,
TOO_MANY_OBJECTS,
TOO_MANY_REQUESTS,
WEATHER_INVALID_PORT,
WEATHER_INVALID_METAR,
WEATHER_UNABLE_TO_GET_OBSERVATION,
WEATHER_UNABLE_TO_CREATE_STATION,
WEATHER_UNABLE_TO_REMOVE_STATION,
INVALID_DATA_TYPE,
INVALID_DATA_SIZE,
DATA_ERROR,
INVALID_ARRAY,
CREATE_OBJECT_FAILED,
LOAD_FLIGHTPLAN_FAILED,
OPERATION_INVALID_FOR_OJBECT_TYPE,
ILLEGAL_OPERATION,
ALREADY_SUBSCRIBED,
INVALID_ENUM,
DEFINITION_ERROR,
DUPLICATE_ID,
DATUM_ID,
OUT_OF_BOUNDS,
/** @since 0.5 */
ALREADY_CREATED,
/** @since 0.5 */
OBJECT_OUTSIDE_REALITY_BUBBLE,
/** @since 0.5 */
OBJECT_CONTAINER,
/** @since 0.5 */
OBJECT_AI,
/** @since 0.5 */
OBJECT_ATC,
/** @since 0.5 */
OBJECT_SCHEDULE;
public static final SimConnectException type(int i) {
SimConnectException[] values = values();
if ((i > values.length) || (i < 0)) return NONE; // default
else return values[i];
}
/**
* Returns a localised message giving the reason of the error
* @since 0.2
* @return exception cause message
*/
public String getLocalisedMessage() {
return Messages.get("Simconnect_exception_" + ordinal()); //$NON-NLS-1$
}
/**
* Returns a string in english giving the reason of the error
* @return exception cause message
* @since 0.2
*/
public String getMessage() {
return Messages.getDefault("Simconnect_exception_" + ordinal()); //$NON-NLS-1$
}
}
| [
"[email protected]"
] | |
8d3c58634da722f0b2590aa8bcabc40badfbb922 | 20c2e98f2cbaaf417aaa7f5e7e6474755946ca0f | /server/src/src/main/java/org/apollo/game/model/region/Region.java | 5c8526a409e36d61793eef130c9bf57d541d29f8 | [
"ISC"
] | permissive | Rune-Status/Bickets-aj8 | 596f8c70e0c6ee1cb9f26c58d7437d17c7b17540 | 3b6963c825500422f1e6590fbd06e271a1d7dfd8 | refs/heads/master | 2020-05-01T06:43:43.921008 | 2015-02-25T13:25:33 | 2015-02-25T13:25:33 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,443 | java | package org.apollo.game.model.region;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import org.apollo.game.model.Entity;
import org.apollo.game.model.Entity.EntityCategory;
import org.apollo.game.model.Position;
/**
* Represents a single region.
*
* @author Ryley Kimmel <[email protected]>
*/
public final class Region {
/**
* The size of one side of the region array.
*/
public static final int SIZE = 256;
/**
* The size of a region.
*/
public static final int REGION_SIZE = 64;
/**
* The maximum level a floor can be.
*/
public static final int MAXIMUM_HEIGHT_LEVEL = 4;
/**
* The tiles within the region.
*/
private final Tile[][] tiles = new Tile[MAXIMUM_HEIGHT_LEVEL][REGION_SIZE * REGION_SIZE];
/**
* A set of entities within this region.
*/
private final Set<Entity> entities = new HashSet<>();
/**
* Constructs a new {@link Region}.
*/
protected Region() {
for (int height = 0; height < MAXIMUM_HEIGHT_LEVEL; height++) {
for (int regionId = 0; regionId < REGION_SIZE * REGION_SIZE; regionId++) {
tiles[height][regionId] = new Tile();
}
}
}
/**
* Adds an {@link Entity} to this region.
*
* @param entity The entity to add.
*/
public void addEntity(Entity entity) {
entities.add(entity);
}
/**
* Removes an {@link Entity} from this region.
*
* @param entity The entity to remove.
*/
public void removeEntity(Entity entity) {
entities.remove(entity);
}
/**
* Tests whether or not the {@link #entities} {@link Set} contains the
* specified {@link Entity}.
*
* @param entity The entity.
* @return {@code true} if and only if the entities set contains the
* specified entity otherwise {@code false}.
*/
public boolean contains(Entity entity) {
return entities.contains(entity);
}
/**
* Gets the entities within this region.
*
* @return A {@link Set} of entities in this region.
*/
@SuppressWarnings("unchecked")
public <T extends Entity> Set<T> getEntities() {
return (Set<T>) entities;
}
/**
* Gets the entities of the specified {@link EntityCategory} within this
* region.
*
* @param category The category of entity to get.
* @return A {@link Set} of entities in this region.
*/
public <T extends Entity> Set<T> getEntities(EntityCategory category) {
Set<T> entities = getEntities();
return entities.stream().filter(e -> e.getCategory() == category).collect(Collectors.toSet());
}
/**
* Gets the entities on the specified {@link Position}.
*
* @param position The position.
* @return A {@link Set} of entities on the specified position.
*/
public <T extends Entity> Set<T> getEntities(Position position) {
Set<T> entities = getEntities();
return entities.stream().filter(e -> e.getPosition().equals(position)).collect(Collectors.toSet());
}
/**
* Gets the entities on the specified {@link Position} if they meet the
* specified {@link EntityCategory}.
*
* @param position The position.
* @param category The category of the entity.
* @return A {@link Set} of entities on the specified position.
*/
public <T extends Entity> Set<T> getEntities(Position position, EntityCategory category) {
Set<T> entities = getEntities(position);
return entities.stream().filter(e -> e.getCategory() == category).collect(Collectors.toSet());
}
/**
* Gets a single tile in this region from the specified height, x and y
* coordinates.
*
* @param height The height.
* @param x The x coordinate.
* @param y The y coordinate.
* @return The tile in this region for the specified attributes.
*/
public Tile getTile(int height, int x, int y) {
return tiles[height][x + y * REGION_SIZE];
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (entities == null ? 0 : entities.hashCode());
result = prime * result + Arrays.hashCode(tiles);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Region other = (Region) obj;
if (entities == null) {
if (other.entities != null) {
return false;
}
} else if (!entities.equals(other.entities)) {
return false;
}
if (!Arrays.deepEquals(tiles, other.tiles)) {
return false;
}
return true;
}
} | [
"[email protected]"
] | |
5b63ce1083a0b96d205a664ad8baf6dc96ea9ac2 | b1e30b54e0c56346388f761c0800a00d13f36cee | /CustomInputStreamDecorator/src/LowerCaseInputStream.java | 48f75e4b0cbf43f80e13c3e2dac1add12ab62d40 | [] | no_license | Manjunath-Jakaraddi/Design-Patterns | 1123a7d3c818368f6829399146920034e02d96c6 | 5bff2c2380fadcb2d111bad360298b319916edc8 | refs/heads/master | 2023-02-24T08:42:24.911018 | 2021-01-30T17:40:30 | 2021-01-30T17:40:30 | 280,499,478 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,014 | java | import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
public class LowerCaseInputStream extends FilterInputStream {
/**
* Creates a <code>FilterInputStream</code>
* by assigning the argument <code>in</code>
* to the field <code>this.in</code> so as
* to remember it for later use.
*
* @param in the underlying input stream, or <code>null</code> if
* this instance is to be created without an underlying stream.
*/
protected LowerCaseInputStream(InputStream in) {
super(in);
}
@Override
public int read() throws IOException {
int c = in.read();
return (c == -1 ? c : Character.toLowerCase((char)c));
}
public int read(byte[] b, int offset, int len) throws IOException {
int result = in.read(b, offset, len);
for(int i = offset; i< offset + result; i++) {
b[i] = (byte)Character.toLowerCase((char)b[i]);
}
return result;
}
}
| [
"[email protected]"
] | |
12586ac7137d321389e888efa3f0c4c8d963dca0 | e4e0172dfd3051c12df1c2f6dfe46dcde0f2e097 | /Seopung/src/com/kh/admin/controller/AdminListServlet.java | 72b530671503da9d5c28309b1aac1ea7438c5ec3 | [] | no_license | klee1123/Seopung | 836db97ce5a0d7846bfd8852120bb0add41ea587 | f83556f6b33e55a8d30cc9c149132aafb0dc76af | refs/heads/master | 2022-12-19T23:24:29.522924 | 2020-10-15T03:02:46 | 2020-10-15T03:02:46 | 296,011,647 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,080 | java | package com.kh.admin.controller;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.kh.Member.model.vo.LoginUser;
import com.kh.admin.model.service.AdminService;
import com.kh.admin.model.vo.Admin;
import com.kh.common.PageInfo;
/**
* Servlet implementation class AdminListServlet
*/
@WebServlet("/adminPage/list.ad")
public class AdminListServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public AdminListServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(request.getSession().getAttribute("loginUser") != null && ((LoginUser)request.getSession().getAttribute("loginUser")).getCategory() == 2) {
request.setCharacterEncoding("utf-8");
int listCount; // 현재 총 게시글 갯수
int currentPage; // 현재 페이지 (즉, 요청한 페이지)
int pageLimit; // 한 페이지 하단에 보여질 페이지 최대갯수
int boardLimit; // 한 페이지내에 보여질 게시글 최대갯수
int maxPage; // 전체 페이지들 중에서의 가장 마지막 페이지
int startPage; // 현재 페이지에 하단에 보여질 페이징 바의 시작수
int endPage; // 현재 페이지에 하단에 보여질 페이징 바의 끝 수
// 넘어온 값 뽑기
currentPage = Integer.parseInt(request.getParameter("currentPage"));
// 키필드
int keyfield;
if(request.getParameter("keyfield")!=null) {
keyfield = Integer.parseInt(request.getParameter("keyfield"));
}else {
keyfield = 1;
}
// 키워드
String keyword;
if(request.getParameter("keyword")!=null) {
keyword = request.getParameter("keyword");
}else {
keyword = "";
}
// 상태분류
String status;
if(request.getParameter("status")!=null) {
status = request.getParameter("status");
}else {
status = "";
}
// 상태분류와 키워드에 해당하는 데이터 수 조회
listCount = new AdminService().selectListCount(keyfield, keyword, status);
pageLimit = 5;
boardLimit = 10;
// 조회된 관리자수가 0일 경우 페이징오류 해결 위해서 (처리안하면 > >>가 보임)
if(listCount != 0) {
maxPage = (int)Math.ceil((double)listCount/boardLimit);
}else {
maxPage=1;
}
startPage = (currentPage-1)/pageLimit * pageLimit + 1;
endPage = startPage + pageLimit - 1;
if(maxPage<endPage) {
endPage = maxPage;
}
PageInfo pi = new PageInfo(listCount, currentPage, pageLimit, boardLimit, maxPage, startPage, endPage);
ArrayList<Admin> list = new AdminService().selectList(pi, keyfield, keyword, status);
request.setAttribute("pi", pi);
request.setAttribute("list", list);
request.setAttribute("keyfield", keyfield);
request.setAttribute("keyword", keyword);
request.setAttribute("status", status);
request.setAttribute("pageTitle", "관리자 목록");
request.getRequestDispatcher("../views/admin/manage_member/admin/manageAdminListView.jsp").forward(request, response);
}else {
request.setAttribute("errorMsg", "로그인 후 이용 가능한 서비스 입니다.");
request.getRequestDispatcher("../views/admin/common/errorPage.jsp").forward(request, response);
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
| [
"[email protected]"
] | |
26167536f99c6d42f54673ee465cf8ded445e891 | 3a58920d69dc866a4b88679cfc5125afa7ec2bce | /test/AdminUserFunctionalTest.java | 0e9f3c502b99f6b10b77eac6547cf8a195c5cc82 | [] | no_license | jeffchou/Baas-Contacts | e236a98c7c886bc14b8ca11e908607346f3ffd23 | 0864d7383299abb48d07a92adb6a5031594224fd | refs/heads/master | 2020-06-01T15:06:26.968935 | 2014-12-15T01:32:31 | 2014-12-15T01:32:31 | 27,751,803 | 2 | 0 | null | 2014-12-15T01:32:32 | 2014-12-09T05:52:07 | Java | UTF-8 | Java | false | false | 9,084 | java | /*
Copyright 2012-2013
Claudio Tesoriero - c.tesoriero-at-baasbox.com
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// @author: Marco Tibuzzi
import static play.test.Helpers.GET;
import static play.test.Helpers.HTMLUNIT;
import static play.test.Helpers.POST;
import static play.test.Helpers.PUT;
import static play.test.Helpers.contentAsString;
import static play.test.Helpers.fakeApplication;
import static play.test.Helpers.routeAndCall;
import static play.test.Helpers.running;
import static play.test.Helpers.testServer;
import java.util.UUID;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import com.fasterxml.jackson.databind.JsonNode;
import org.junit.Test;
import play.libs.F.Callback;
import play.mvc.Result;
import play.mvc.Http.Status;
import play.test.FakeRequest;
import play.test.TestBrowser;
import core.AbstractAdminTest;
import core.TestConfig;
public class AdminUserFunctionalTest extends AbstractAdminTest
{
private static final String USER_TEST = "user";
private static final String USER_NOT_PRESENT = "userNotPresent";
@Override
public String getRouteAddress()
{
return "/admin/user";
}
@Override
public String getMethod()
{
return GET;
}
@Override
protected void assertContent(String sContent)
{
Object obj = toJSON(sContent);
assertJSON(obj, "user");
}
protected void assertCheckUserUpdate(String sContent, String sUserName)
{
Object obj = toJSON(sContent);
assertJSON(obj, "user");
// Change role check
assertJSONString(obj, "\"name\":\"registered\"");
// Change attribute check
assertJSONString(obj, "\"quote\":\"I am very happy!\"");
}
@Test
public void testRouteUpdateNotExistentUser()
{
running
(
getFakeApplication(),
new Runnable()
{
public void run()
{
FakeRequest request = new FakeRequest(PUT, getRouteAddress() + "/" + USER_NOT_PRESENT);
request = request.withHeader(TestConfig.KEY_APPCODE, TestConfig.VALUE_APPCODE);
request = request.withHeader(TestConfig.KEY_AUTH, TestConfig.AUTH_ADMIN_ENC);
request = request.withJsonBody(getPayload("/adminUserUpdatePayload.json"), PUT);
Result result = routeAndCall(request);
assertRoute(result, "testRouteUpdateNotExitentUser", Status.BAD_REQUEST, USER_NOT_PRESENT + TestConfig.MSG_USER_MODIDY_NOT_PRESENT, true);
}
}
);
}
@Test
public void testRouteCreateAndUpdateUser()
{
running
(
getFakeApplication(),
new Runnable()
{
public void run()
{
String sFakeUser = routeCreateNewUser();
// Update user
FakeRequest request = new FakeRequest(PUT, getRouteAddress() + "/" + sFakeUser);
request = request.withHeader(TestConfig.KEY_APPCODE, TestConfig.VALUE_APPCODE);
request = request.withHeader(TestConfig.KEY_AUTH, TestConfig.AUTH_ADMIN_ENC);
request = request.withJsonBody(getPayload("/adminUserUpdatePayload.json"), PUT);
Result result = routeAndCall(request);
assertRoute(result, "testRouteCreateAndUpdateUser: Update user.", Status.OK, null, false);
String sPwd = getPayloadFieldValue("/adminUserCreatePayload.json", "password");
// Updates check
request = new FakeRequest(GET, "/user");
request = request.withHeader(TestConfig.KEY_APPCODE, TestConfig.VALUE_APPCODE);
request = request.withHeader(TestConfig.KEY_AUTH, TestConfig.encodeAuth(sFakeUser, sPwd));
request = request.withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED);
result = routeAndCall(request);
assertRoute(result, "testRouteCreateAndUpdateUser: Check updated user.", Status.OK, null, false);
assertRoute(result, "testRouteCreateAndUpdateUser check username", Status.OK, "name\":\""+sFakeUser+"\"", true);
assertRoute(result, "testRouteCreateAndUpdateUser check role", Status.OK, "roles\":[{\"name\":\"registered\",\"isrole\":true}", true);
assertCheckUserUpdate(contentAsString(result), sFakeUser);
}
}
);
}
@Test
public void testServerUpdateNotExistentUser()
{
running
(
getTestServer(),
HTMLUNIT,
new Callback<TestBrowser>()
{
public void invoke(TestBrowser browser)
{
setHeader(TestConfig.KEY_APPCODE, TestConfig.VALUE_APPCODE);
setHeader(TestConfig.KEY_AUTH, TestConfig.AUTH_ADMIN_ENC);
setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
httpRequest
(
getURLAddress() + "/" + USER_NOT_PRESENT,
PUT,
"/adminUserUpdatePayload.json"
);
assertServer("testServerUpdateNotExitentUser", Status.BAD_REQUEST, USER_NOT_PRESENT + TestConfig.MSG_USER_MODIDY_NOT_PRESENT, true);
}
}
);
}
@Test
public void testServerCreateAndUpdateUser()
{
running
(
getTestServer(),
HTMLUNIT,
new Callback<TestBrowser>()
{
public void invoke(TestBrowser browser)
{
String sFakeUser = serverCreateNewUser();
// Update user
setHeader(TestConfig.KEY_APPCODE, TestConfig.VALUE_APPCODE);
setHeader(TestConfig.KEY_AUTH, TestConfig.AUTH_ADMIN_ENC);
setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
httpRequest
(
getURLAddress() + "/" + sFakeUser,
PUT,
"/adminUserUpdatePayload.json"
);
assertServer("testServerCreateAndUpdateUser: Update user.", Status.OK, null, false);
String sPwd = getPayloadFieldValue("/adminUserCreatePayload.json", "password");
// Updates check
setHeader(TestConfig.KEY_APPCODE, TestConfig.VALUE_APPCODE);
setHeader(TestConfig.KEY_AUTH, TestConfig.encodeAuth(sFakeUser, sPwd));
setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED);
httpRequest(TestConfig.SERVER_URL + "/user", GET);
assertServer("testServerCreateAndUpdateUser: Check updated user.", Status.OK, null, false);
assertCheckUserUpdate(getResponse(), sFakeUser);
}
}
);
}
@Test
public void testServerUpdateUserNoRole()
{
running
(
getTestServer(),
HTMLUNIT,
new Callback<TestBrowser>()
{
public void invoke(TestBrowser browser)
{
String sFakeUser = serverCreateNewUser();
setHeader(TestConfig.KEY_APPCODE, TestConfig.VALUE_APPCODE);
setHeader(TestConfig.KEY_AUTH, TestConfig.AUTH_ADMIN_ENC);
setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
httpRequest
(
getURLAddress() + "/" + sFakeUser,
PUT,
"/adminUserUpdateNoRolePayload.json"
);
assertServer("testServerUpdateUserNoRole", Status.BAD_REQUEST, "The 'role' field is missing", true);
}
}
);
}
@Test
public void testServerUpdateUserNotExistentRole()
{
running
(
getTestServer(),
HTMLUNIT,
new Callback<TestBrowser>()
{
public void invoke(TestBrowser browser)
{
String sFakeUser = serverCreateNewUser();
setHeader(TestConfig.KEY_APPCODE, TestConfig.VALUE_APPCODE);
setHeader(TestConfig.KEY_AUTH, TestConfig.AUTH_ADMIN_ENC);
setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
httpRequest
(
getURLAddress() + "/" + sFakeUser,
PUT,
"/adminUserUpdateNotExistentRole.json"
);
assertServer("testServerUpdateUserNoRole", Status.BAD_REQUEST, " is not a role", true);
}
}
);
}
public String routeCreateNewUser()
{
String sFakeUser = USER_TEST + UUID.randomUUID();
// Prepare test user
JsonNode node = updatePayloadFieldValue("/adminUserCreatePayload.json", "username", sFakeUser);
// Create user
FakeRequest request = new FakeRequest(POST, getRouteAddress());
request = request.withHeader(TestConfig.KEY_APPCODE, TestConfig.VALUE_APPCODE);
request = request.withHeader(TestConfig.KEY_AUTH, TestConfig.AUTH_ADMIN_ENC);
request = request.withJsonBody(node, POST);
Result result = routeAndCall(request);
assertRoute(result, "Create user.", Status.CREATED, null, false);
return sFakeUser;
}
public String serverCreateNewUser()
{
String sFakeUser = USER_TEST + UUID.randomUUID();
// Prepare test user
JsonNode node = updatePayloadFieldValue("/adminUserCreatePayload.json", "username", sFakeUser);
// Create user
setHeader(TestConfig.KEY_APPCODE, TestConfig.VALUE_APPCODE);
setHeader(TestConfig.KEY_AUTH, TestConfig.AUTH_ADMIN_ENC);
setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
httpRequest
(
getURLAddress(),
POST,
node
);
assertServer("Create user.", Status.CREATED, null, false);
return sFakeUser;
}
}
| [
"[email protected]"
] | |
9351e7f061acaa73ecbd6d9fcc9b9832c633df00 | 8d75cf704ff59f44b9192f6da6545d2e45bf0eff | /app/src/androidTest/java/com/example/onlineticketingsystem/ExampleInstrumentedTest.java | b63bfa0bf06533e58460bb50873bf36420bad94b | [] | no_license | AshenSenevirathne/Online-Ticketing-System-Mobile-App | 2afce570cb94230b11866ca15f11d25f1dc3209c | 26267723e767de33cd286f3007cc974c1702e769 | refs/heads/master | 2022-12-25T20:35:32.134343 | 2020-10-13T08:42:26 | 2020-10-13T08:42:26 | 303,602,546 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 780 | java | package com.example.onlineticketingsystem;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.example.onlineticketingsystem", appContext.getPackageName());
}
} | [
"[email protected]"
] | |
5ca1778edc7092b01b55420ea00c1b5b9cecd17c | a5aefd65c28ddf8a27433d982c984f70bc05b268 | /COMP 401 - Foundations of Programming (Fall 2014)/Assignment 7/src/a7adept/ProfitCounter.java | 8f966864629e104685ce41c5d159e164cd379128 | [] | no_license | fangelod/Coursework | 63d2bbc7147caf963cfca24c076a3c3822dfa346 | 8306896e98329e06fe7945bcb55d219d4c8a7fcd | refs/heads/master | 2020-12-31T07:43:56.952769 | 2016-05-23T23:18:16 | 2016-05-23T23:18:16 | 59,520,854 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,358 | java | package a7adept;
import java.util.Observable;
import comp401.sushi.Plate;
public class ProfitCounter implements java.util.Observer {
private double total_profit = 0;
private int plate_count = 0;
public ProfitCounter() {
}
/* Input: Belt belt, PlateEvent event
* Output: None
* This method notifies the Observer that the
* observed object has changed
*/
@Override
public void update(Observable o, Object arg) {
Belt belt = (Belt) o;
PlateEvent event = (PlateEvent) arg;
if (event.getType() == PlateEvent.EventType.PLATE_PLACED) {
double added = event.getPlate().getProfit();
plate_count++;
total_profit += added;
} else if (event.getType() == PlateEvent.EventType.PLATE_REMOVED) {
if (event.getPlate() == null) {
//// Doesn't affect profit if there wasn't a plate to begin with
} else {
double removed = event.getPlate().getProfit();
plate_count--;
total_profit -= removed;
}
}
}
/* Input: none
* Output: double
* This method returns the sum of all profit for all
* plates currently on the belt
*/
public double getTotalBeltProfit() {
return total_profit;
}
/* Input: none
* Output: double
* This method returns the average profit per plate
* currently on the belt
*/
public double getAverageBeltProfit() {
return total_profit / plate_count;
}
}
| [
"[email protected]"
] | |
897cb741b19f8780cbfa5096dfdcfe880a3e1402 | 6c87b5bc4dddbe0607ce45e23985613aaba02f8a | /src/main/java/dynamic_programming/simple/DivisorGame_1025.java | 3464c7d7b5033cfcc875b0ded875cc5a175caad1 | [] | no_license | mrxiaobai-wen/study-leetcode | 8b05ea8e384c2d57de0cde6021e3b90adc91f56a | dc6972ed880955f0717665a92b2f1892c127660b | refs/heads/master | 2023-06-03T09:58:56.793326 | 2021-06-24T06:50:24 | 2021-06-24T06:50:24 | 233,186,677 | 0 | 0 | null | 2020-10-13T20:07:30 | 2020-01-11T06:23:09 | Java | UTF-8 | Java | false | false | 1,535 | java | package dynamic_programming.simple;
/**
* 1025. 除数博弈
* 爱丽丝和鲍勃一起玩游戏,他们轮流行动。爱丽丝先手开局。
* <p>
* 最初,黑板上有一个数字 N 。在每个玩家的回合,玩家需要执行以下操作:
* <p>
* 选出任一 x,满足 0 < x < N 且 N % x == 0 。
* 用 N - x 替换黑板上的数字 N 。
* 如果玩家无法执行这些操作,就会输掉游戏。
* <p>
* 只有在爱丽丝在游戏中取得胜利时才返回 True,否则返回 false。假设两个玩家都以最佳状态参与游戏。
* <p>
* <p>
* <p>
* 示例 1:
* <p>
* 输入:2
* 输出:true
* 解释:爱丽丝选择 1,鲍勃无法进行操作。
* 示例 2:
* <p>
* 输入:3
* 输出:false
* 解释:爱丽丝选择 1,鲍勃也选择 1,然后爱丽丝无法进行操作。
* <p>
* <p>
* 提示:
* <p>
* 1 <= N <= 1000
*/
public class DivisorGame_1025 {
public boolean divisorGame(int N) {
return dpFun(N);
}
private boolean dpFun(int n) {
if (n == 1) {
return false;
} else if (n == 2) {
return true;
}
boolean[] dp = new boolean[n + 1];
dp[1] = false;
dp[2] = true;
for (int i = 3; i <= n; i++) {
dp[i] = false;
for (int j = 1; j < i; j++) {
if (i % j == 0 && !dp[i - j]) {
dp[i] = true;
break;
}
}
}
return dp[n];
}
}
| [
"[email protected]"
] | |
ae16ad0c1e89a2cd0eec810533f6ac1a401611c9 | 8a158fa637afba4877a1102f73e453be37eb171e | /src/main/java/gameLogic/Game.java | b2352dc12348c92ab69911a9d0d00df8dc423a37 | [] | no_license | MykolasPinkevicius/jacksOrBetter | 871607cb0ab44e3db5c85242003f36acb7e052bb | 04f1c472474908f7148e0979362cb2b3c99270f6 | refs/heads/master | 2020-06-09T06:43:42.889699 | 2020-03-19T13:47:14 | 2020-03-19T13:47:14 | 193,393,493 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,111 | java | package gameLogic;
import lombok.Data;
import java.util.Scanner;
@Data
public class Game {
private boolean isOn = false;
public Card[] draw() {
return null;
}
public void play(Player player, Scanner sc) {
isOn = true;
int choice = 0;
while (isOn) {
System.out.println("--------------------");
System.out.println("Select 1 to Start game");
System.out.println("Select 2 to Change name");
System.out.println("Select 3 to View score");
System.out.println("Select 4 to Exit gameLogic");
choice = sc.nextInt();
switch(choice) {
case 1:
int weRollingBaby = 0;
while(weRollingBaby == 0) {
player.setScore(player.getScore()-1);
System.out.println("--------------------");
System.out.println("One score token taken");
System.out.println("--------------------");
System.out.println("Drawing five cards");
System.out.println("--------------------");
Deck d = new Deck();
Card[] drawn = d.drawCards(d.resetDeck());
System.out.println("--------------------");
System.out.println("We drawn");
System.out.println("--------------------");
for (int i = 0; i < 5; i++) {
System.out.println(drawn[i].getValue() + " of " + drawn[i].getSuit());
}
System.out.println("--------------------");
System.out.println("Select which cards you want to keep");
System.out.println("Just type true or false");
System.out.println("--------------------");
Boolean[] bool = new Boolean[5];
String[] str = new String[5];
System.out.println("First :");
str[0] = sc.nextLine();
str[0] = sc.nextLine();
if (str[0].toLowerCase().equals("true") || str[0].toLowerCase().equals("false")) {
bool[0] = Boolean.valueOf(str[0]);
} else {
System.out.println("False input, please input true or false");
str[0] = sc.nextLine();
bool[0] = Boolean.valueOf(str[0]);
}
System.out.println("Second :");
str[1] = sc.nextLine();
if (str[1].toLowerCase().equals("true") || str[1].toLowerCase().equals("false")) {
bool[1] = Boolean.valueOf(str[1]);
} else {
System.out.println("False input, please input true or false");
str[1] = sc.nextLine();
bool[1] = Boolean.valueOf(str[1]);
}
System.out.println("Third :");
str[2] = sc.nextLine();
if (str[2].toLowerCase().equals("true") || str[2].toLowerCase().equals("false")) {
bool[2] = Boolean.valueOf(str[2]);
} else {
System.out.println("False input, please input true or false");
str[2] = sc.nextLine();
bool[2] = Boolean.valueOf(str[2]);
}
System.out.println("Fourth :");
str[3] = sc.nextLine();
if (str[3].toLowerCase().equals("true") || str[3].toLowerCase().equals("false")) {
bool[3] = Boolean.valueOf(str[3]);
} else {
System.out.println("False input, please input true or false");
str[3] = sc.nextLine();
bool[3] = Boolean.valueOf(str[3]);
}
System.out.println("Fifth :");
str[4] = sc.nextLine();
if (str[4].toLowerCase().equals("true") || str[4].toLowerCase().equals("false")) {
bool[4] = Boolean.valueOf(str[4]);
} else {
System.out.println("False input, please input true or false");
str[4] = sc.nextLine();
bool[4] = Boolean.valueOf(str[4]);
}
for (int i = 0, j = 5; i < 5 && j < 10; i++, j++) {
if (bool[i]) {
drawn[i] = drawn[i];
} else {
drawn[i] = drawn[j];
}
}
System.out.println("--------------------");
System.out.println("We drawn");
System.out.println("--------------------");
for (int i = 0; i < 5; i++) {
System.out.println( drawn[i].getValue() +" of " + drawn[i].getSuit());
}
player.setScore(player.getScore() + d.getScore(drawn));
System.out.println("--------------------");
System.out.println("Player " + player.getName() + " total score is " + player.getScore());
System.out.println("--------------------");
System.out.println("--------------------");
System.out.println("Do you want to play more?");
System.out.println("Yes for repeat, no for exit");
System.out.println("--------------------");
String keepPlaying = sc.nextLine().toLowerCase();
if (keepPlaying.equals("yes")) {
weRollingBaby = 0;
} else {
weRollingBaby = 1;
}
System.out.println("--------------------");
}
break;
case 2:
String newName;
System.out.println("What is your new name");
newName = sc.nextLine();
newName = sc.nextLine();
player.setName(newName);
System.out.println("Your new name is " + player.getName());
break;
case 3:
System.out.println(player.getName() + " score is " + player.getScore());
break;
case 4:
isOn = false;
}
}
}
}
| [
"[email protected]"
] | |
98fba7f0ffa1d5d530227b3b558079aa4510a290 | ccefb640f12536991a5685c039e8468f7ae07171 | /app/src/main/java/rihoo/tourguideapp/ShootingRangesActivity.java | 1d4cc3417d88cfe218e324458d13ac82a320956c | [] | no_license | ronrihoo/Android_Basics__Project_6_Tour_Guide | af302df8c972a77664d42dde4a8a0f0bff33de4e | 3f1be2dde5f4d79cf952d430ae68114973be022b | refs/heads/master | 2021-01-20T20:36:20.138397 | 2016-07-05T00:37:31 | 2016-07-05T00:37:31 | 62,594,497 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,418 | java | package rihoo.tourguideapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
public class ShootingRangesActivity extends AppCompatActivity {
// Button
Button returnButton;
// Intent
Intent goBack;
// ListView
ListView listView;
// LocationAdapter
LocationAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_screen);
// Button
returnButton = (Button) findViewById(R.id.Button_Back_To_Main);
// Intent
goBack = new Intent(this, MainActivity.class);
// ListView
listView = (ListView) findViewById(R.id.ListView);
// Location Objects
ArrayList<Location> locations = new ArrayList<Location>();
// LocationAdapter
adapter = new LocationAdapter(this, locations, R.color.dallas_navy_gray);
// OnClickListener
returnButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(goBack);
}
});
locations.add(new Location(getResources().getString(R.string.shooting_range_1_name),
getResources().getString(R.string.shooting_range_1_address),
getResources().getString(R.string.shooting_range_1_phone)));
locations.add(new Location(getResources().getString(R.string.shooting_range_2_name),
getResources().getString(R.string.shooting_range_2_address),
getResources().getString(R.string.shooting_range_2_phone)));
locations.add(new Location(getResources().getString(R.string.shooting_range_3_name),
getResources().getString(R.string.shooting_range_3_address),
getResources().getString(R.string.shooting_range_3_phone)));
locations.add(new Location(getResources().getString(R.string.shooting_range_4_name),
getResources().getString(R.string.shooting_range_4_address),
getResources().getString(R.string.shooting_range_4_phone)));
listView.setAdapter(adapter);
}
}
| [
"[email protected]"
] | |
7a53783c7205dbf1196d336363da639bab32a756 | c86d2881d10352bc1d4a93e38c941414d600ec24 | /exercicios/src/fundamentos/TipoStringEquals.java | 1dc684f0202237395da504d793425ac9616608f4 | [] | no_license | Bbeluco/AulasJavaUdemy | 2977cc7d9809fadfcf7977d6a072d30a2432ef7d | b1754509b8af250baf439da0168e5b88ee2a72fe | refs/heads/main | 2023-04-14T04:34:38.327231 | 2021-04-30T14:19:27 | 2021-04-30T14:19:27 | 358,719,552 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 297 | java | package fundamentos;
public class TipoStringEquals {
public static void main(String[] args) {
System.out.println("2" == "2");
String s1 = new String("2");
System.out.println("2" == s1);
System.out.println("2".equals(s1));
//metodo equals compara apenas o conteudo da string
}
}
| [
"[email protected]"
] | |
b32421f1fae40a318de95b7653c6c8ce293666d0 | f33d8a160413e1452044b579c1061277df5da57c | /src/com/miage/projetandroid/activity/MainActivity.java | 7bb47d670e5fc0fea2676de0a20a8a2f6fe70fe4 | [] | no_license | prodevmiage/sourceProjANDROID | 08c8983ebfa0a4003b17182906f94aebe71524b6 | 253a23d2ac24221b16e8062abc943bcd4c29a9d8 | refs/heads/master | 2020-05-24T14:25:07.017140 | 2013-04-17T22:52:19 | 2013-04-17T22:52:19 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,843 | java | package com.miage.projetandroid.activity;
import java.util.ArrayList;
import java.util.HashMap;
import com.miage.projetandroid.R;
import com.miage.projetandroid.controller.EvenementAdapter;
import com.miage.projetandroid.controller.EvenementAdapter.EvenementAdapterListener;
import com.miage.projetandroid.model.Evenement;
import com.miage.projetandroid.model.Parametre;
import com.miage.projetandroid.persistance.EvenementController;
import com.miage.projetandroid.persistance.ParametreController;
import com.miage.projetandroid.persistance.TypeEvenementController;
import com.miage.projetandroid.persistance.ZoneController;
import com.miage.projetandroid.util.Constante;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ListActivity;
import android.content.Intent;
import android.graphics.Color;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class MainActivity extends Activity implements EvenementAdapterListener{
private LinearLayout layoutApplication;
private ParametreController paramController;
private EvenementController evtController;
private ZoneController zoneController;
private TypeEvenementController typeEvtController;
private TextView titreApplication;
private ImageView logo;
private LinearLayout barreTitre;
private LinearLayout fondEcran;
private ImageButton boutonHome;
private ImageButton boutonRecherche;
private ListView listeViewEvtAlaUne;
private Parametre param = new Parametre();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initialisation des controllers
paramController = new ParametreController();
evtController = new EvenementController();
zoneController = new ZoneController();
typeEvtController = new TypeEvenementController();
//Initialisation des composants d'écran
titreApplication = (TextView) findViewById(R.id.Mtitre_application);
logo = (ImageView) findViewById(R.id.Mlogo);
barreTitre = (LinearLayout) findViewById(R.id.MlayoutBarreTitre);
fondEcran = (LinearLayout) findViewById(R.id.MlayoutApplication);
boutonHome = (ImageButton) findViewById(R.id.MboutonHome);
boutonRecherche = (ImageButton) findViewById(R.id.MboutonAccesRecherche);
//gère l'évènement déclenché au click sur le bouton home
// cela provoque la récupération des données et l'affichage de la page home
boutonHome.setOnClickListener(new OnClickListener() {
public void onClick(View v) { gettingJson(); }
});
//bouton rechercher
boutonRecherche.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent=new Intent(MainActivity.this,RechercheActivity.class);
startActivity(intent);
finish();
}
});
//lancement de la récupération des données
gettingJson();
}
//fonction permettant de récupérer les données contenues dans les fichiers Json
final void gettingJson() {
final Thread checkUpdate = new Thread() {
public void run() {
param = paramController.initParametre();
final ArrayList<Evenement> listeEvt = evtController.initEvenement();
runOnUiThread(new Runnable() {
@Override
public void run() {
parametreComposant(param);
gestionAffichageEvenementAlaUne(listeEvt);
}
});
}
};
checkUpdate.start();
}
//fonction qui permet de paramétrer l'application
private void parametreComposant(Parametre p) {
/*barreTitre.setBackgroundColor(Color.parseColor(p.getCouleur_barreTitre().substring(1, p.getCouleur_barreTitre().length()-2)));
fondEcran.setBackgroundColor(Color.parseColor(p.getCouleur_fond().substring(1, p.getCouleur_fond().length()-2)));
titreApplication.setText(p.getTitreApplication().substring(1, p.getTitreApplication().length()-2));
titreApplication.setTextSize(p.getTaillePoliceTitre());
titreApplication.setTextColor(Color.parseColor(p.getCouleur_policeTitre().substring(1, p.getCouleur_policeTitre().length()-2)));
boutonHome.setBackgroundColor(Color.parseColor(p.getCouleur_bouton().substring(1, p.getCouleur_bouton().length()-2)));
boutonRecherche.setBackgroundColor(Color.parseColor(p.getCouleur_bouton().substring(1, p.getCouleur_bouton().length()-2)));
*/
barreTitre.setBackgroundColor(Color.parseColor(p.getCouleur_barreTitre()));
fondEcran.setBackgroundColor(Color.parseColor(p.getCouleur_fond()));
titreApplication.setText(p.getTitreApplication());
titreApplication.setTextSize(p.getTaillePoliceTitre());
titreApplication.setTextColor(Color.parseColor(p.getCouleur_policeTitre()));
boutonHome.setBackgroundColor(Color.parseColor(p.getCouleur_bouton()));
boutonRecherche.setBackgroundColor(Color.parseColor(p.getCouleur_bouton()));
}
private void gestionAffichageEvenementAlaUne(ArrayList<Evenement> listeEvt) {
ArrayList<Evenement> listEvtAlaUne = new ArrayList<Evenement>();
//Création et initialisation de l'Adapter pour les évènements
for(Evenement e:listeEvt){
if(e.getPublication() == 1){
listEvtAlaUne.add(e);
}
}
EvenementAdapter adapter = new EvenementAdapter(this, listeEvt);
//Ecoute des évènements sur la liste
adapter.addListener(this);
//Récupération du composant ListView
listeViewEvtAlaUne = (ListView) findViewById(R.id.MlisteEvenementUne);
//Initialisation de la liste avec les données
listeViewEvtAlaUne.setAdapter(adapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public void onClickEvenement(Evenement item, int position) {
Intent intent = new Intent(MainActivity.this, FicheDescEvenementActivity.class);
Bundle evenementBundle = new Bundle();
//mapping dans un objet bundle des information sur l'évènement sélectionné
evenementBundle.putInt(Constante.EXTRA_EVT_ID, item.getId());
evenementBundle.putString(Constante.EXTRA_EVT_NOM, item.getNom());
evenementBundle.putString(Constante.EXTRA_EVT_DESCRIPTION, item.getDescription());
evenementBundle.putInt(Constante.EXTRA_EVT_PUBLICATION, item.getPublication());
evenementBundle.putInt(Constante.EXTRA_EVT_IDTYPEEVT, item.getIdTypeEvt());
evenementBundle.putString(Constante.EXTRA_EVT_LOCALISATION, item.getLocalisation());
evenementBundle.putString(Constante.EXTRA_EVT_POSITIONGPS, item.getPositionGPS());
evenementBundle.putInt(Constante.EXTRA_EVT_IDZONE, item.getIdZone());
evenementBundle.putString(Constante.EXTRA_EVT_CONTACT_TEL, item.getContact_tel());
evenementBundle.putString(Constante.EXTRA_EVT_CONTACT_MAIL, item.getContact_mail());
evenementBundle.putString(Constante.EXTRA_EVT_INFOCONTACT, item.getInfoContact());
evenementBundle.putString(Constante.EXTRA_EVT_WEB, item.getWeb());
evenementBundle.putString(Constante.EXTRA_EVT_NATURE, item.getNature());
evenementBundle.putString(Constante.EXTRA_EVT_TARIF, item.getTarif());
evenementBundle.putString(Constante.EXTRA_EVT_PHOTO, item.getPhoto());
Bundle parametreBundle = new Bundle();
//mapping dans un objet bundle des informations sur le paramétrage de l'application
parametreBundle.putString(Constante.EXTRA_PARAM_FONTTITRE, param.getFontTitre());
parametreBundle.putString(Constante.EXTRA_PARAM_FONTTEXTE, param.getFontTexte());
parametreBundle.putInt(Constante.EXTRA_PARAM_TAILLEPOLICETITRE, param.getTaillePoliceTitre());
parametreBundle.putInt(Constante.EXTRA_PARAM_TAILLEPOLICETEXTE, param.getTaillePoliceTexte());
parametreBundle.putString(Constante.EXTRA_PARAM_COULEUR_BARRETITRE, param.getCouleur_barreTitre());
parametreBundle.putString(Constante.EXTRA_PARAM_COULEUR_FOND, param.getCouleur_fond());
parametreBundle.putString(Constante.EXTRA_PARAM_COULEUR_POLICETITRE, param.getCouleur_policeTitre());
parametreBundle.putString(Constante.EXTRA_PARAM_COULEUR_POLICE, param.getCouleur_police());
parametreBundle.putString(Constante.EXTRA_PARAM_COULEUR_BOUTON, param.getCouleur_bouton());
parametreBundle.putString(Constante.EXTRA_PARAM_COULEUR_THEME1, param.getCouleur_theme1());
parametreBundle.putString(Constante.EXTRA_PARAM_COULEUR_THEME2, param.getCouleur_theme2());
parametreBundle.putString(Constante.EXTRA_PARAM_COULEUR_THEME3, param.getCouleur_theme3());
parametreBundle.putString(Constante.EXTRA_PARAM_COULEUR_THEME4, param.getCouleur_theme4());
parametreBundle.putString(Constante.EXTRA_PARAM_COULEUR_THEME5, param.getCouleur_theme5());
parametreBundle.putString(Constante.EXTRA_PARAM_COULEUR_THEME6, param.getCouleur_theme6());
parametreBundle.putString(Constante.EXTRA_PARAM_COULEUR_THEME7, param.getCouleur_theme7());
parametreBundle.putString(Constante.EXTRA_PARAM_TITREAPPLICATION, param.getTitreApplication());
parametreBundle.putString(Constante.EXTRA_PARAM_LOGO, param.getLogo());
intent.putExtra(Constante.EXTRA_EVENEMENT, evenementBundle);
intent.putExtra(Constante.EXTRA_PARAMETRE, parametreBundle);
startActivity(intent);
finish();
}
}
| [
"[email protected]"
] | |
6263dc5647f2b71f45cd1cb5d2c77e13d7d276d3 | ba1d708ddd5ef15bc3fd128dfe606e2d40cbebfc | /AutoTest1/Chapter5/src/main/java/suit/Pay.java | ba4d7ce67fef88f993a7fe84fb2e9bbce9879dfa | [] | no_license | xiaoxiamifighting/AutoTest2 | 5a27fed2f310b38b6a16b65b8921315bdb914fc6 | baf881222793e858d0f66a57737ae2eaecdfe994 | refs/heads/master | 2022-07-15T09:44:14.242550 | 2019-08-28T07:12:10 | 2019-08-28T07:12:10 | 203,748,229 | 0 | 0 | null | 2022-06-21T01:43:25 | 2019-08-22T08:23:19 | Java | UTF-8 | Java | false | false | 172 | java | package suit;
import org.testng.annotations.Test;
public class Pay {
@Test
public void paySuccess(){
System.out.println("支付宝支付成功");
}
}
| [
"[email protected]"
] | |
f9fce16244ec8499943f548a933d4a40111fb128 | a56e5da7e49e2b8003c04bdccce33a290981662f | /movies-service/src/main/java/pt/ist/dsi/movies/domain/Actor.java | 96c30814cb606a4af0608dc5d3e222503dfb0ceb | [] | no_license | dsi-dev-sessions/02-rest-microservices | 9211935c7868895ca72c77ef10b719eff38a6fe8 | 5392edb21a8f704518fd86ad2ede8c47973cddf3 | refs/heads/master | 2020-06-14T12:39:51.959907 | 2016-11-28T23:55:50 | 2016-11-28T23:55:50 | 75,024,029 | 7 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,080 | java | package pt.ist.dsi.movies.domain;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
@Entity
public class Actor {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(unique = true)
private String name;
@ManyToMany(cascade = CascadeType.ALL, mappedBy = "actors")
private Set<Movie> movies;
protected Actor() {
}
public Actor(String name) {
this.name = name;
this.movies = new HashSet<>();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Movie> getMovies() {
return movies;
}
public void addMovie(Movie movie) {
movies.add(movie);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Actor)) {
return false;
}
Actor other = (Actor) obj;
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
return true;
}
@Override
public String toString() {
return "Actor [id=" + id + ", name=" + name + "]";
}
} | [
"[email protected]"
] | |
e880d5cdd68887200df2022b9fe163d428823955 | c8e66e512063401718d2a390d5ab24b49d9103b4 | /app/src/androidTest/java/com/jesse/test2/ApplicationTest.java | d3a7ee67af9ddc60f836bb6720262710f83d311e | [] | no_license | xiejinquan/recyclergetItemType | 1224173418cdc60fb13e56854bcd2c96a3ece649 | 1f95140e1a4687e15667ca285d15ce4183afc129 | refs/heads/master | 2021-01-10T01:19:34.840237 | 2016-01-26T02:48:56 | 2016-01-26T02:48:56 | 50,396,867 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 346 | java | package com.jesse.test2;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | [
"[email protected]"
] | |
0d4b32fa4f850128076de3103b10bb2b378accef | fac1909031c3de6e54eb60dffedb9aa3f9aa09b0 | /src/primitives/src/main/java/us/wellengineered/solder/primitives/AbstractYieldIterator.java | c06f2456bf87206b135a372dc70f78b90df979f7 | [
"MIT"
] | permissive | wellengineered-us/archive-solder-java | 2680f1c5086e8551b7a6b6ff346ca16039695a64 | 071361eb1608272cfa9c4556e68e0abbaf56e2ac | refs/heads/master | 2023-04-12T21:39:20.795440 | 2021-05-06T04:05:33 | 2021-05-06T04:05:33 | 364,779,783 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,509 | java | /*
Copyright ©2020 WellEngineered.us, all rights reserved.
Distributed under the MIT license: https://opensource.org/licenses/MIT
*/
package us.wellengineered.solder.primitives;
import us.wellengineered.solder.primitives.AbstractLifecycle;
import us.wellengineered.solder.primitives.LifecycleIterable;
import us.wellengineered.solder.primitives.LifecycleIterator;
import us.wellengineered.solder.primitives.MethodParameterModifier;
import us.wellengineered.solder.primitives.exceptions.FailFastException;
import java.util.Iterator;
import java.util.NoSuchElementException;
import static us.wellengineered.solder.primitives.Utils.failFastOnlyWhen;
/**
* Inspired by reverse-engineered C# compiler yield machine state machine enumerables/enumerators.
* NOTE: in this 'yield' implementation, hasNext() is not idempotent because we are dealing with non-buffered/streaming sources.
* We do cache a single non-null currentItem value, which is used as a machine state modifier to drive functionality.
* Special thanks to http://csharpindepth.com/Articles/Chapter6/IteratorBlockImplementation.aspx
* <p>
* An attempt to generalize the problem for a certain class of "pedestrian" iterators is the goal.
* For really complex implementations, multiple states may be required and are not supported (yet) by this class.
* NOTE: The running, after, and fault states have the same integer value by design.
*
* @param <TItem>
*/
public abstract class AbstractYieldIterator<TItem> extends AbstractLifecycle<Exception, Exception> implements LifecycleIterator<TItem>, LifecycleIterable<TItem>
{
protected AbstractYieldIterator()
{
this(ITERATOR_BEFORE_STATE);
}
protected AbstractYieldIterator(int machineState)
{
this.setMachineState(machineState);
this.initialThreadId = Thread.currentThread().getId();
}
protected static final int ITERABLE_BEFORE_ITERATOR_STATE = -2; // before the first call to iterator() from the creating thread
protected static final int ITERATOR_AFTER_STATE = -1; // "After" - the iterator has finished, either by reaching the end of the method or by hitting yield break
protected static final int ITERATOR_BEFORE_STATE = 0; // next() hasn't been called yet
private static final int ITERATOR_FAULT_STATE = -1; // "Fault" - the iterator threw an exception - internal use only
protected static final int ITERATOR_RESUME_STATE = 1; // it's yielded at least one value, and there's possibly more to come
protected static final int ITERATOR_RUNNING_STATE = -1; // "Running" - the iterator is currently executing code
private final long initialThreadId;
private TItem currentItem;
private boolean itemCached;
private long itemIndex;
private int machineState;
private TItem getCurrentItem()
{
return this.currentItem;
}
private void setCurrentItem(TItem currentItem)
{
this.currentItem = currentItem;
}
protected final long getInitialThreadId()
{
return this.initialThreadId;
}
public long getItemIndex()
{
return this.itemIndex;
}
private void setItemIndex(long itemIndex)
{
this.itemIndex = itemIndex;
}
protected final int getMachineState()
{
return this.machineState;
}
protected final void setMachineState(int machineState)
{
this.machineState = machineState;
}
public final boolean isAbandonedIfNewlyIterated()
{
return this.getMachineState() != ITERATOR_BEFORE_STATE;
}
private boolean isItemCached()
{
return this.itemCached;
}
private void setItemCached(boolean itemCached)
{
this.itemCached = itemCached;
}
@Override
public final boolean hasNext()
{
if (this.isItemCached()) // is there a cached current item value ready to yield?
return true;
else if (this.getMachineState() == ITERATOR_AFTER_STATE ||
this.getMachineState() == ITERATOR_RUNNING_STATE)
return false;
else if (this.getMachineState() == ITERATOR_BEFORE_STATE ||
this.getMachineState() == ITERATOR_RESUME_STATE)
{
try
{
final boolean result = this.moveNext(); // hasNext --> moveNext: not idempotent by design
return result;
}
catch (Exception ex)
{
throw new FailFastException(ex);
}
}
else
throw new NoSuchElementException(String.format("Invalid iterator machine state: %s", this.getMachineState()));
}
private void incrementItemIndex()
{
this.setItemIndex(this.getItemIndex() + 1);
}
@Override
public final Iterator<TItem> iterator()
{
if (Thread.currentThread().getId() == this.getInitialThreadId() &&
this.getMachineState() == ITERABLE_BEFORE_ITERATOR_STATE)
{
this.setMachineState(ITERATOR_BEFORE_STATE);
return this;
}
return this.newLifecycleIterator(ITERATOR_BEFORE_STATE);
}
@Override
public final LifecycleIterator<TItem> lifecycleIterator()
{
if (Thread.currentThread().getId() == this.getInitialThreadId() &&
this.getMachineState() == ITERABLE_BEFORE_ITERATOR_STATE)
{
this.setMachineState(ITERATOR_BEFORE_STATE);
return this;
}
return this.newLifecycleIterator(ITERATOR_BEFORE_STATE);
}
protected void maybeCreateBeforeYield() throws Exception
{
this.create();
}
protected void maybeDisposeAfterFault() throws Exception
{
this.dispose();
}
protected void maybeDisposeAfterYield() throws Exception
{
this.dispose();
}
protected boolean moveNext() throws Exception
{
boolean result;
MethodParameterModifier.Out<TItem> outValue;
try
{
while (this.getMachineState() == ITERATOR_BEFORE_STATE ||
this.getMachineState() == ITERATOR_RESUME_STATE)
{
switch (this.getMachineState())
{
case ITERATOR_BEFORE_STATE:
{
this.setMachineState(ITERATOR_RUNNING_STATE);
this.maybeCreateBeforeYield();
this.setItemIndex(-1);
this.onYieldStart();
this.setMachineState(ITERATOR_RESUME_STATE);
break;
}
case ITERATOR_RESUME_STATE:
{
this.setMachineState(ITERATOR_RUNNING_STATE);
failFastOnlyWhen(this.isItemCached(), "this.isItemCached()");
if (this.getItemIndex() > -1) // ???
this.onYieldResume();
outValue = new MethodParameterModifier.Out<>(Object.class);
result = this.onTryYield(outValue);
if (result)
{
failFastOnlyWhen(!outValue.isSet(), "!outValue.isSet()");
this.incrementItemIndex();
final TItem value = outValue.getValue();
this.onYieldReturn(value);
// we should not have a previously cached value, so this makes absolute sense...
this.setItemCached(true);
this.setCurrentItem(value);
this.setMachineState(ITERATOR_RESUME_STATE);
return true;
}
else
{
failFastOnlyWhen(outValue.isSet(), "outValue.isSet()");
this.onYieldComplete();
this.setItemCached(false);
this.setCurrentItem(null);
this.maybeDisposeAfterYield();
this.setMachineState(ITERATOR_AFTER_STATE);
return false;
}
}
}
}
}
catch (Exception ex)
{
this.onYieldFault(ex);
this.setItemCached(false);
this.setCurrentItem(null);
this.setMachineState(ITERATOR_FAULT_STATE);
this.maybeDisposeAfterFault();
throw ex; // re-throw
}
throw new NoSuchElementException(String.format("Invalid iterator machine state: %s", this.getMachineState()));
}
protected abstract LifecycleIterator<TItem> newLifecycleIterator(int state);
@Override
public final TItem next()
{
if (!this.isItemCached())
{
if (!this.hasNext()) // next --> hasNext --> moveNext: not idempotent by design
throw new NoSuchElementException(String.format("%s::hasNext() returned false.", this.getClass().getName()));
}
failFastOnlyWhen(!this.isItemCached(), "!this.isItemCached()");
final TItem currentItem = this.getCurrentItem();
this.setItemCached(false);
this.setCurrentItem(null);
return currentItem;
}
protected abstract boolean onTryYield(MethodParameterModifier.Out<TItem> outValue) throws Exception;
protected abstract void onYieldComplete() throws Exception;
protected abstract void onYieldFault(Exception ex);
protected abstract void onYieldResume() throws Exception;
protected abstract void onYieldReturn(TItem value) throws Exception;
protected abstract void onYieldStart() throws Exception;
}
| [
"[email protected]"
] | |
ab37e4cb2c896eea498a2871585e849b1d236888 | 2ffbed27040adbcfe6ba653bcb19522596ba13cf | /scooter-tools/src/main/java/com/iceicelee/scooter/tools/natapp/client/consult/ClientConsultHandler.java | 8d5041bcbfb0cfe6ecb3adc7dbd41524c6c7aa0e | [] | no_license | ys3721/scooter | d78bae591802b2d3a02b9be1cf882e31560f240a | e90b1e9641350b55d37f70570142c28c588fae67 | refs/heads/master | 2023-01-09T21:27:18.323208 | 2020-08-26T03:17:42 | 2020-08-26T03:17:42 | 264,699,577 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,985 | java | package com.iceicelee.scooter.tools.natapp.client.consult;
import com.google.protobuf.MessageLite;
import com.iceicelee.scooter.tools.logger.Loggers;
import com.iceicelee.scooter.tools.natapp.client.config.ProtoMessageRecogenazer;
import com.iceicelee.scooter.tools.natapp.client.processor.SCNoticeSomeOneConnectedMsgProcessorFactory;
import com.iceicelee.scooter.tools.natapp.message.ConsultMessageProto;
import com.iceicelee.scooter.tools.natapp.message.ConsultMessageProto.CSHandshakeMsg;
import com.iceicelee.scooter.tools.natapp.message.ConsultMessageProto.SCNoticeSomeOneConnectedMsg;
import com.iceicelee.scooter.tools.natapp.server.processor.CSHandshakeMsgProcessorFactory;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
/**
* 用于协商的handler
*
* @author: Yao Shuai
* @date: 2020/6/3 18:23
*/
public class ClientConsultHandler extends SimpleChannelInboundHandler<MessageLite> {
private String consultIp;
private int port;
public ClientConsultHandler(String consultIp) {
this.consultIp = consultIp;
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
CSHandshakeMsg csHandshakeMsg = CSHandshakeMsg.newBuilder()
.setClientInfo("Client no infos").build();
ctx.writeAndFlush(csHandshakeMsg);
Loggers.REVERSE_CLIENT.info("channelActive handshake msg is seed! 与远端服务已经链接!");
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, MessageLite msg) throws Exception {
MessageLite messageLite = (MessageLite) msg;
//先这么写八
switch (ProtoMessageRecogenazer.getMessageNum(messageLite)) {
case 1003:
SCNoticeSomeOneConnectedMsgProcessorFactory.getProcessor().process((SCNoticeSomeOneConnectedMsg) msg);
break;
default:
System.out.println("No processor for " + msg);
}
}
/* @Override
protected void channelRead0(ChannelHandlerContext ctx, SCMessage msg) throws Exception {
*//*Loggers.REVERSE_CLIENT.debug("收到了来自服务端的消息->" + msg);
byte[] scConsultMsgByte = new byte[byteBuf.readableBytes()];
byteBuf.readBytes(scConsultMsgByte);
SCHandshakeMsg scHandshakeMsg = SCHandshakeMsg.parseFrom(scConsultMsgByte);
Loggers.REVERSE_CLIENT.info("Server want me connection port " + scHandshakeMsg.getHandshakeResult());
String[] ports = scHandshakeMsg.getHandshakeResult().split(",");
this.port = Integer.parseInt(ports[0]);
int heWantPort = Integer.parseInt(ports[1]);
Loggers.REVERSE_CLIENT.info("Begin connect the 127.0.0.1 app port " + heWantPort);
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
EventLoopGroup workGroup = new NioEventLoopGroup();
ClientAppLocalHandler appLocalHandler = new ClientAppLocalHandler();
try {
Bootstrap b = new Bootstrap();
b.group(workGroup)
.channel(NioSocketChannel.class)
.handler(new LoggingHandler())
.handler(appLocalHandler);
ChannelFuture connFuture = b.connect("10.5.7.163", heWantPort);
connFuture.sync();
Channel appChannel = connFuture.channel();
Loggers.REVERSE_CLIENT.info("Connected the 127.0.0.1 app port " + heWantPort);
EventLoopGroup workGroup2 = new NioEventLoopGroup();
Bootstrap cb = new Bootstrap();
cb.group(workGroup2)
.channel(NioSocketChannel.class)
.handler(new LoggingHandler())
.handler(new ClientConmmunicationHandler(appChannel, appLocalHandler));
ChannelFuture connFuture2 = cb.connect(ClientConsultHandler.this.getConsultIp(), ClientConsultHandler.this.getPort());
connFuture2.sync();
Loggers.REVERSE_CLIENT.info(connFuture2.isSuccess()+"Back Connected the "+ClientConsultHandler.this.getConsultIp() +" port " + ClientConsultHandler.this.getPort());
} catch (Exception e) {
Loggers.REVERSE_CLIENT.error("链接失败!", e);
}
}
});
thread.start();*//*
}*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
ctx.close();
}
public String getConsultIp() {
return consultIp;
}
public void setConsultIp(String consultIp) {
this.consultIp = consultIp;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
}
| [
"[email protected]"
] | |
ff5d21e400b4aed907dd751b384b82779dbac700 | c9f3c8801d9a871735cf238129b3edbb70d2dff2 | /jakpum2/src/templet/DBCon.java | 2935a6e22cdb71d83cd5d5a09ae28110ae87eac2 | [] | no_license | vlavolns/jakpumpjt01 | 1584404422e3354f14c9a7b3087078e9183abccb | 1c833c81194e2c9e6aefde1d8128bd0c299aad8f | refs/heads/master | 2022-03-29T21:17:30.346758 | 2019-12-17T00:52:44 | 2019-12-17T00:52:44 | 227,760,853 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 666 | java | package templet;
import java.sql.*;
import java.sql.DriverManager;
public class DBCon {
public static Connection getCon() throws Exception{
Class.forName("oracle.jdbc.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","hr","hr");
return con;
}
public static void close(Connection con,PreparedStatement ps, ResultSet rs) {
if(rs!=null) {
try {rs.close();}catch(Exception ex) {ex.printStackTrace();}
}
if(ps!=null) {
try {ps.close();}catch(Exception ex) {ex.printStackTrace();}
}
if(con!=null) {
try {con.close();}catch(Exception ex) {ex.printStackTrace();}
}
}
}
| [
"w@USERMIC-G1L6S54"
] | w@USERMIC-G1L6S54 |
eeaf3c0eff500d92caee0d2a1d055378bd4dab64 | 7334d1a4701229670335cca2c6500111a41721b0 | /tpg/src/main/java/com/yhy/tpg/anim/AnimPoint.java | a44f6c9269d34c1a0b7e5229cda2e3855b95af0e | [
"Apache-2.0"
] | permissive | allwith/TabPager | 9cc1991829754d84895f4078b58c3b7f2a70ffbc | 075e50e5df987992ffa5fa2a41948bd64d59c617 | refs/heads/master | 2021-01-13T17:31:37.715722 | 2017-01-16T02:23:20 | 2017-01-16T02:23:20 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,286 | java | package com.yhy.tpg.anim;
public class AnimPoint {
public float x, y;
public float x1, y1;
public float x2, y2;
public int operation;
public AnimPoint(float x, float y) {
this.x = x;
this.y = y;
}
public AnimPoint(float x, float y, int operation) {
this(x, y);
this.operation = operation;
}
public AnimPoint(float x, float y, float x1, float y1, int operation) {
this(x, y, operation);
this.x1 = x1;
this.y1 = y1;
}
public AnimPoint(float x, float y, float x1, float y1, float x2, float y2, int operation) {
this(x, y, x1, y1, operation);
this.x2 = x2;
this.y2 = y2;
}
public static AnimPoint moveTo(float x, float y, int operation) {
return new AnimPoint(x, y, operation);
}
public static AnimPoint lineTo(float x, float y, int operation) {
return new AnimPoint(x, y, operation);
}
public static AnimPoint quadTo(float x, float y, float x1, float y1, int operation) {
return new AnimPoint(x, y, x1, y1, operation);
}
public static AnimPoint curveTo(float x, float y, float x1, float y1, float x2, float y2, int operation) {
return new AnimPoint(x, y, x1, y1, x2, y2, operation);
}
}
| [
"[email protected]"
] | |
296f0ea730e53d102de825371e31dcd85c00f43e | 441a45cc81a66ed83f96b24c9b9b9ffa4a1f9115 | /src/labs_advanced/day_1/assignment_05/BankCustomer.java | 64b30978d5578d6fc2e810fb7cd59c0ca6c4e790 | [] | no_license | Girish85/Java | 3e632d4903e73744718d54e1f8917c30e9d03542 | ef1e8df0e73ea1a15202ea77f654bc6f9af3ae45 | refs/heads/master | 2020-04-16T08:58:10.026103 | 2019-02-07T01:15:42 | 2019-02-07T01:15:42 | 165,445,647 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,774 | java | package labs_advanced.day_1.assignment_05;
import java.util.Random;
class Name
{
String fName;
String mName;
String lName;
}
enum AccountType {Salary,NonSalary};
public class BankCustomer {
Name name;
String emailId;
AccountType accountType;
String dateOfBirth;
char gender;
String martialStatus;
boolean isAvailChequeBook;
boolean isAvailDiscount;
boolean isAvailATMcard;
private int customerId;
private int accountNumber;
BankCustomer(Name name,String emailId,AccountType accountType,String dateOfBirth,char gender,String martialStatus)
{
this.name = name;
this.emailId = emailId;
this.accountType = accountType;
this.dateOfBirth = dateOfBirth;
this.gender = gender;
this.martialStatus = martialStatus;
priviliges();
getCustomerId();
getAccountNumber();
System.out.println("Customer Successfully Created the account");
System.out.println("Customer ID : "+customerId);
System.out.println("Account Number : "+accountNumber);
}
private void priviliges()
{
switch (accountType)
{
case Salary:
isAvailChequeBook = false;
isAvailDiscount = false;
isAvailATMcard = true;
break;
case NonSalary:
isAvailChequeBook = false;
isAvailDiscount = true;
isAvailATMcard = true;
}
}
private int getCustomerId()
{
customerId = 10000+new Random().nextInt(9999);
return customerId;
}
private int getAccountNumber()
{
accountNumber = 10000000+new Random().nextInt(9999999);
return accountNumber;
}
}
| [
"[email protected]"
] | |
383320c13258e48021e0c8b2f282217269216bb5 | efdeced948d830fac9b0b9258dd524283931a58b | /app/src/main/java/com/xiaofangfang/lifetatuor/Activity/WeatherSearch.java | c258648bdb2b488f56e39bdb7087598b9e4485f9 | [] | no_license | enjoy-learning-everything/lifeTutor | e562803b82fe35073f6fa47bd642102ec19cd079 | 2e2b32a6d67dfcbaae1c642e2ca2872f279b699e | refs/heads/master | 2023-04-27T05:51:33.913114 | 2019-08-28T08:01:42 | 2019-08-28T08:01:42 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,058 | java | package com.xiaofangfang.lifetatuor.Activity;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import com.xiaofangfang.lifetatuor.R;
/**
* 天气的搜索界面的显示效果
*/
public class WeatherSearch extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.weather_search);
initView();
}
SearchView citySearch;
TextView searchResult;
private void initView() {
citySearch = findViewById(R.id.citySearch);
citySearch.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
//如果输入的是回车,就进行搜索
return false;
}
});
}
}
| [
"[email protected]"
] | |
5af3053f7df3100179fec1bddb32e3e6a28785c4 | 46c1032cb1f482722c7b6d3f65072ea8a74a2002 | /src/Task/Car.java | 92f0356764661c5eedcee8ba260d673cffc59aae | [] | no_license | Denzap0/Zapol_Denis_Task5 | 8b9a08ae8176b07b7462d932188d14476d5b368e | d5bc41691b79f1711729595422edbb256a3ab6e7 | refs/heads/master | 2022-11-27T09:29:39.130394 | 2020-07-27T18:31:29 | 2020-07-27T18:31:29 | 282,928,868 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,241 | java | package Task;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
public abstract class Car implements Movable {
protected String colour;
protected int serialNum;
protected Date date;
protected Model model;
protected boolean state;
Car() {
colour = "White";
date = new Date();
model = Model.MERCEDES;
//state already false
}
Car(String colour, int serialNum, Date date, Model model, boolean state) {
this.colour = colour;
this.date = date;
this.model = model;
this.state = state;
}
public abstract void move();
public void stop() {
System.out.println("Car is stopped");
}
public String getColour() {
return colour;
}
public void setColour(String colour) {
this.colour = colour;
}
public int getSerialNum() {
return serialNum;
}
public void setSerialNum(int serialNum) {
this.serialNum = serialNum;
}
public String getDate() {
SimpleDateFormat dateF = new SimpleDateFormat("dd MM yyyy h:m:s");
return dateF.format(date);
}
public void setDate(Date date) {
this.date = date;
}
public Model getModel() {
return model;
}
public void setModel(Model model) {
this.model = model;
}
public boolean isState() {
return state;
}
public void setState(boolean state) {
this.state = state;
}
@Override
public String toString() {
StringBuilder strBuilder = new StringBuilder("Model: ");
strBuilder.append(model);
strBuilder.append(", colour: ");
strBuilder.append(colour);
strBuilder.append(", date: ");
strBuilder.append(date);
return strBuilder.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Car car = (Car) o;
return colour.equals(car.colour) &&
model == car.model;
}
@Override
public int hashCode() {
return Objects.hash(colour, serialNum, date, model, state);
}
}
| [
"[email protected]"
] | |
5c301d82b20299f7360a06dc3bd53dec304fcf18 | b70f0da1b18b34b1d1964480704fa879771d0fbc | /src/main/java/cn/gaoyuan/demo/algorithm/tree/thread/ThreadedBinaryTree.java | df406c2ac4403d1e6d771443509fb62f7daeffe4 | [] | no_license | gaoyuan888/gaoyuan-demo | df4f304b0f9f2076b8b1c434bb0b01dee0a41b7a | 9c3663f32cbb4f1d0a47a85b51fa073091c580a9 | refs/heads/master | 2022-07-01T04:44:07.611536 | 2020-02-27T02:21:10 | 2020-02-27T02:21:10 | 172,820,123 | 1 | 0 | null | 2022-06-21T01:59:27 | 2019-02-27T01:31:40 | Java | UTF-8 | Java | false | false | 2,920 | java | package cn.gaoyuan.demo.algorithm.tree.thread;
/**
* 功能描述:线索化二叉树
* <p>
* 线索化二叉树生成方式还是不是很清楚,遍历方法需要回头再仔细看一下
*
* @author yaoyizhou
* @date 2019/3/13 18:44
* @desc
*/
public class ThreadedBinaryTree {
ThreadedNode root;
/**
* 临时存储前驱节点
*/
ThreadedNode tmpPreNode;
/**
* 遍历线索二叉树
*/
public void threadIterate() {
//临时存储当前遍历节点
ThreadedNode node = root;
while (node != null) {
//循环找到最开始的节点
while (node.leftType == 0) {
node = node.left;
}
//打印当前节点的值
System.out.println(node.value);
//如果当前节点的右指针指向的是后继节点,可能后继节点还有后继节点
while (node.rightType == 1) {
node = node.right;
System.out.println(node.value);
}
// 替换遍历的节点
node = node.right;
}
}
/**
* 設置根节点
*
* @param root
*/
public void setRoot(ThreadedNode root) {
this.root = root;
}
/**
* 获取根节点
*/
public ThreadedNode getRoot() {
return root;
}
/**
* 前序遍历
*/
public void frontShow() {
root.frontShow();
}
/**
* 中序遍历
*/
public void middleShow() {
root.middleShow();
}
/**
* 后序遍历
*/
public void afterShow() {
root.afterShow();
}
/**
* 前序查找
*/
public ThreadedNode frontSearch(int i) {
return root.frontSearch(i);
}
/**
* 中序线索化二叉树
*/
public void threadNodes() {
threadNodes(root);
}
/**
* 中序线索化二叉树
*/
public void threadNodes(ThreadedNode node) {
//当前节点如果为null,直接返回
if (node == null) {
return;
}
//处理左子树
threadNodes(node.left);
//处理前驱节点
if (node.left == null) {
//让当前节点的左指针指向前驱节点
node.left = tmpPreNode;
node.leftType = 1;
}
//处理前驱的右指针,如果前驱节点的右指针是null(没有指向右子树)
if (tmpPreNode != null && tmpPreNode.right == null) {
//让前驱节点的右指针指向当前节点
tmpPreNode.right = node;
//改变前驱节点的右指针类型
tmpPreNode.rightType = 1;
}
//每处理一个节点,当前节点当前节点就是下一个节点的前驱节点
tmpPreNode = node;
//处理右子树
threadNodes(node.right);
}
}
| [
"[email protected]"
] | |
ae04cecf09e8e661227b06a226da12a1c37796c5 | 44b97d11457f1718a77923b4f3e5b3f6ad20ff26 | /chouqu/src/main/java/com/example/chouqu/util/SpUtil.java | 3b43c2bb4d85236b563839c439cc931b5f0da6f1 | [] | no_license | Baigaliaass/123456 | 30acbe97a7de63185c2d73dca514432f57b7f4ad | 2b941ab41a39acc3c0618a9a0186359f54b2a729 | refs/heads/master | 2020-05-18T00:13:36.265805 | 2019-04-29T11:20:36 | 2019-04-29T11:20:36 | 184,055,473 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,030 | java | package com.example.chouqu.util;
import android.content.Context;
import android.content.SharedPreferences;
import com.example.chouqu.base.BaseApp;
//Sharepreference
public class SpUtil {
/**
* 保存在手机里面的文件名
*/
private static final String FILE_NAME = "share_date";
/**
* 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法
* @param key
* @param object
*/
public static void setParam( String key, Object object){
String type = object.getClass().getSimpleName();
SharedPreferences sp = BaseApp.getBaseApp().getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
if("String".equals(type)){
editor.putString(key, (String)object);
}
else if("Integer".equals(type)){
editor.putInt(key, (Integer)object);
}
else if("Boolean".equals(type)){
editor.putBoolean(key, (Boolean)object);
}
else if("Float".equals(type)){
editor.putFloat(key, (Float)object);
}
else if("Long".equals(type)){
editor.putLong(key, (Long)object);
}
editor.commit();
}
/**
* 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值
* @param key
* @param defaultObject
* @return
*/
public static Object getParam(String key, Object defaultObject){
String type = defaultObject.getClass().getSimpleName();
SharedPreferences sp = BaseApp.getBaseApp().getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
if("String".equals(type)){
return sp.getString(key, (String)defaultObject);
}
else if("Integer".equals(type)){
return sp.getInt(key, (Integer)defaultObject);
}
else if("Boolean".equals(type)){
return sp.getBoolean(key, (Boolean)defaultObject);
}
else if("Float".equals(type)){
return sp.getFloat(key, (Float)defaultObject);
}
else if("Long".equals(type)){
return sp.getLong(key, (Long)defaultObject);
}
return null;
}
} | [
"[email protected]"
] | |
4a4a13ff469dcb875bd612df09750be78e5247c4 | fd8fadf30b2e357c1f432a303115ce5bf30ff57c | /src/h/nodelist_t.java | 883a10e011b28810c87ed8e8c25a8a4a37424000 | [] | no_license | lixinlin/plantuml-code | 6642e452ae8e6834942593a7ecd42f44418b8b6b | f558a8ec50f9ec617528dede774c3f46f1aac5ae | refs/heads/master | 2021-06-28T02:24:29.085869 | 2019-09-22T11:20:25 | 2019-09-22T11:20:25 | 214,447,468 | 0 | 0 | null | 2021-02-03T19:33:31 | 2019-10-11T13:45:25 | Java | UTF-8 | Java | false | false | 2,347 | java | /* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* Project Info: http://plantuml.com
*
* If you like this project or if you find it useful, you can support us at:
*
* http://plantuml.com/patreon (only 1$ per month!)
* http://plantuml.com/paypal
*
* This file is part of Smetana.
* Smetana is a partial translation of Graphviz/Dot sources from C to Java.
*
* (C) Copyright 2009-2020, Arnaud Roques
*
* This translation is distributed under the same Licence as the original C program:
*
*************************************************************************
* Copyright (c) 2011 AT&T Intellectual Property
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors: See CVS logs. Details at http://www.graphviz.org/
*************************************************************************
*
* THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC
* LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0]
*
* ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES
* RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
*
* You may obtain a copy of the License at
*
* http://www.eclipse.org/legal/epl-v10.html
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package h;
import java.util.Arrays;
import java.util.List;
import smetana.core.__ptr__;
//2 cvnwgrhim9meq1d0au3lunrpz
public interface nodelist_t extends __ptr__ {
public static List<String> DEFINITION = Arrays.asList(
"typedef struct",
"{",
"nodelistitem_t *first",
"nodelistitem_t *last",
"int sz",
"}",
"nodelist_t");
}
// typedef struct {
// nodelistitem_t *first;
// nodelistitem_t *last;
// int sz;
// } nodelist_t; | [
"arnaud_roques@2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5"
] | arnaud_roques@2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5 |
b2f6b469e6d38fc257e2981b4e58982fc792552c | 4f956b8abebf2a6eaa3ff0f6b13cc8663df1f2e5 | /src/power/lifePower.java | e06b494a5ec175cdeac3ac626169724feecd93ec | [
"MIT"
] | permissive | brookezkeene/breakout | e81a6ceeb37957a50a93e381b71e0b833bc7775f | d4b2b0f45e5d755e55f778990966e2d947fa44fe | refs/heads/master | 2021-06-22T10:59:38.436477 | 2019-08-15T18:57:30 | 2019-08-15T18:57:30 | 148,925,750 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 633 | java | package power;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
/**
* lifePower
*
* sub-class of Power, a power up that adds
* an extra life to player's total lives
*
* @author Brooke Keene
*/
public class lifePower extends Power {
/**
* Constructor
*
* @param x x-coordinate of Power
* @param y y-coordinate of Power
*/
public lifePower(int x, int y) {
super(x, y);
Image image = new Image(getClass().getClassLoader().getResourceAsStream("extralife.gif"));
power = new ImageView(image);
power.setX(x);
power.setY(y);
}
}
| [
"[email protected]"
] | |
b22bac26b2f4502d7a5e345f5a61f7e5b1746c24 | d76c7218a4218e59ca4bbc2d4d06cd04c9bdfb40 | /week-09/day-01/src/main/java/com/greenfoxacademy/restpractice/repositories/LogRepository.java | 0e68cdbd79310be06f9e3c5f1acfffd6f645629b | [] | no_license | green-fox-academy/agipetho | d07261235431f663ff372e3233b2ff1376ad4933 | 37d0047bddd4468ccebcc4110ec769891d1ef6e5 | refs/heads/master | 2021-02-07T12:48:34.669693 | 2020-07-12T18:02:22 | 2020-07-12T18:02:22 | 244,027,666 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 301 | java | package com.greenfoxacademy.restpractice.repositories;
import com.greenfoxacademy.restpractice.models.Log;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface LogRepository extends CrudRepository<Log, Long> {
}
| [
"[email protected]"
] | |
f0aadd95edb93f6edcfce86da2c3ff692e5f8058 | bb256f53aafe978dd8a6e0fb21594f97c8d9ba02 | /src/day_50_Inheritance/StaticBlockDemo.java | f89c292856a8f68d102c4dec3ed219c646a4f5d9 | [] | no_license | tumacho-hub/java-programming | ad8432e68636e267994035aa95aa0ee68270e000 | 438ded3444546710533c5a1c6c72516131134aa1 | refs/heads/master | 2023-08-14T17:24:06.387578 | 2021-10-22T03:25:24 | 2021-10-22T03:25:24 | 372,034,206 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,402 | java | package day_50_Inheritance;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class StaticBlockDemo {
static int num;
static List<String> carModels;
static {
System.out.println("Static initializer block");
num = 10;
carModels = new ArrayList<>();
carModels.addAll(Arrays.asList("Abarth",
"Alfa Romeo",
"Aston Martin",
"Audi",
"Bentley",
"BMW",
"Bugatti",
"Cadillac",
"Chevrolet",
"Chrysler",
"Citroën",
"Dacia",
"Daewoo",
"Daihatsu",
"Dodge",
"Donkervoort",
"DS",
"Ferrari",
"Fiat",
"Fisker",
"Ford",
"Honda",
"Hummer",
"Hyundai",
"Infiniti",
"Iveco",
"Jaguar",
"Jeep",
"Kia",
"KTM",
"Lada",
"Lamborghini",
"Lancia",
"Land Rover",
"Landwind",
"Lexus",
"Lotus",
"Maserati",
"Maybach",
"Mazda",
"McLaren",
"Mercedes-Benz",
"MG",
"Mini",
"Mitsubishi",
"Morgan",
"Nissan",
"Opel",
"Peugeot",
"Porsche",
"Renault",
"Rolls-Royce",
"Rover",
"Saab",
"Seat",
"Skoda",
"Smart",
"SsangYong",
"Subaru",
"Suzuki",
"Tesla",
"Toyota",
"Volkswagen",
"Volvo"));
}
{
System.out.println("Initializer block");
}
// below i have a constructor with no arguments
public StaticBlockDemo(){
System.out.println("Constructor method");
num += 5;
}
public StaticBlockDemo(int value){
System.out.println("Overload it constructor - value = "+ value);
num = value;
}
}
| [
"[email protected]"
] | |
cac1e789a1adecca6b8e79272c7719901cfc7378 | d5f09c7b0e954cd20dd613af600afd91b039c48a | /sources/com/ali/auth/third/login/UTConstants.java | 1a755a17ba158fb1452a60aa0f77cee3fb0f0114 | [] | no_license | t0HiiBwn/CoolapkRelease | af5e00c701bf82c4e90b1033f5c5f9dc8526f4b3 | a6a2b03e32cde0e5163016e0078391271a8d33ab | refs/heads/main | 2022-07-29T23:28:35.867734 | 2021-03-26T11:41:18 | 2021-03-26T11:41:18 | 345,290,891 | 5 | 2 | null | null | null | null | UTF-8 | Java | false | false | 1,478 | java | package com.ali.auth.third.login;
public class UTConstants {
public static final String E_AUTO_LOGIN_FAILURE = "auto_login_failure".toUpperCase();
public static final String E_AUTO_LOGIN_SUCCESS = "auto_login_success".toUpperCase();
public static final String E_COOOPERATION_BIND = "COOPERATION_TB_BIND";
public static final String E_COOOPERATION_ERROR = "COOPERATION_SYSTEM_ERROR";
public static final String E_COOOPERATION_LOGIN = "COOPERATION_TB_LOGIN";
public static final String E_COOOPERATION_TRUST = "COOPERATION_TRUST_LOGIN";
public static final String E_GENERATE_TAOBAO_SIGN = "GENERATE_TOPAPPLINK_TOKEN";
public static final String E_H5_LOGIN_CANCEL = "h5_login_cancel".toUpperCase();
public static final String E_H5_LOGIN_FAILURE = "h5_login_failure".toUpperCase();
public static final String E_H5_LOGIN_SUCCESS = "h5_login_success".toUpperCase();
public static final String E_H5_OPERATION_BIND_FAILURE = "h5_bind_failure".toUpperCase();
public static final String E_IV_LOGIN_FAILURE = "iv_login_failure".toUpperCase();
public static final String E_SSO_TOKEN_LOGIN = "SSO_TOKEN_LOGIN";
public static final String E_TB_LOGIN_CANCEL = "tb_login_cancel".toUpperCase();
public static final String E_TB_LOGIN_FAILURE = "tb_login_failure".toUpperCase();
public static final String E_TB_LOGIN_SUCCESS = "tb_login_success".toUpperCase();
public static final String E_TOP_TOKEN_LOGIN = "TOP_TOKEN_LOGIN";
}
| [
"[email protected]"
] | |
03acae08ea2578ed8f9e68a9ac5453066b48e69e | 24d8cf871b092b2d60fc85d5320e1bc761a7cbe2 | /JFreeChart/rev91-1269/left-branch-1269/tests/org/jfree/chart/renderer/xy/junit/XYBoxAndWhiskerRendererTests.java | bb8be9cf64a1570eba453f174bc90ad8accd7f94 | [] | no_license | joliebig/featurehouse_fstmerge_examples | af1b963537839d13e834f829cf51f8ad5e6ffe76 | 1a99c1788f0eb9f1e5d8c2ced3892d00cd9449ad | refs/heads/master | 2016-09-05T10:24:50.974902 | 2013-03-28T16:28:47 | 2013-03-28T16:28:47 | 9,080,611 | 3 | 2 | null | null | null | null | UTF-8 | Java | false | false | 3,751 | java |
package org.jfree.chart.renderer.xy.junit;
import java.awt.Color;
import java.awt.GradientPaint;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.jfree.chart.renderer.xy.XYBoxAndWhiskerRenderer;
import org.jfree.util.PublicCloneable;
public class XYBoxAndWhiskerRendererTests extends TestCase {
public static Test suite() {
return new TestSuite(XYBoxAndWhiskerRendererTests.class);
}
public XYBoxAndWhiskerRendererTests(String name) {
super(name);
}
public void testEquals() {
XYBoxAndWhiskerRenderer r1 = new XYBoxAndWhiskerRenderer();
XYBoxAndWhiskerRenderer r2 = new XYBoxAndWhiskerRenderer();
assertEquals(r1, r2);
r1.setPaint(new GradientPaint(1.0f, 2.0f, Color.yellow,
3.0f, 4.0f, Color.red));
assertFalse(r1.equals(r2));
r2.setPaint(new GradientPaint(1.0f, 2.0f, Color.yellow,
3.0f, 4.0f, Color.red));
assertEquals(r1, r2);
r1.setArtifactPaint(new GradientPaint(1.0f, 2.0f, Color.green,
3.0f, 4.0f, Color.red));
assertFalse(r1.equals(r2));
r2.setArtifactPaint(new GradientPaint(1.0f, 2.0f, Color.green,
3.0f, 4.0f, Color.red));
assertEquals(r1, r2);
r1.setBoxWidth(0.55);
assertFalse(r1.equals(r2));
r2.setBoxWidth(0.55);
assertEquals(r1, r2);
r1.setFillBox(!r1.getFillBox());
assertFalse(r1.equals(r2));
r2.setFillBox(!r2.getFillBox());
assertEquals(r1, r2);
r1.setBoxPaint(Color.yellow);
assertFalse(r1.equals(r2));
r2.setBoxPaint(Color.yellow);
assertEquals(r1, r2);
r1.setBoxPaint(null);
assertFalse(r1.equals(r2));
r2.setBoxPaint(null);
assertEquals(r1, r2);
}
public void testHashcode() {
XYBoxAndWhiskerRenderer r1 = new XYBoxAndWhiskerRenderer();
XYBoxAndWhiskerRenderer r2 = new XYBoxAndWhiskerRenderer();
assertTrue(r1.equals(r2));
int h1 = r1.hashCode();
int h2 = r2.hashCode();
assertEquals(h1, h2);
}
public void testCloning() {
XYBoxAndWhiskerRenderer r1 = new XYBoxAndWhiskerRenderer();
XYBoxAndWhiskerRenderer r2 = null;
try {
r2 = (XYBoxAndWhiskerRenderer) r1.clone();
}
catch (CloneNotSupportedException e) {
System.err.println("Failed to clone.");
}
assertTrue(r1 != r2);
assertTrue(r1.getClass() == r2.getClass());
assertTrue(r1.equals(r2));
}
public void testPublicCloneable() {
XYBoxAndWhiskerRenderer r1 = new XYBoxAndWhiskerRenderer();
assertTrue(r1 instanceof PublicCloneable);
}
public void testSerialization() {
XYBoxAndWhiskerRenderer r1 = new XYBoxAndWhiskerRenderer();
XYBoxAndWhiskerRenderer r2 = null;
try {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(buffer);
out.writeObject(r1);
out.close();
ObjectInput in = new ObjectInputStream(
new ByteArrayInputStream(buffer.toByteArray())
);
r2 = (XYBoxAndWhiskerRenderer) in.readObject();
in.close();
}
catch (Exception e) {
System.out.println(e.toString());
}
assertEquals(r1, r2);
}
}
| [
"[email protected]"
] | |
d8be7c4bbec5f3134de5360de3143c1273e56934 | c2ed2b1e50b6a83422d11fd317ef96b36822d4b4 | /core/src/test/java/com/inspiresoftware/lib/dto/geda/assembler/examples/simple/TestEntity10Interface3.java | 975af81f7ec116cee857fec0d564c10bce725c4f | [] | no_license | inspire-software/geda-genericdto | 48006aec3c9cd98c2178f5a83a644495d3805dcb | 5e453c78a61c38f72c21e75a754ff19b96cb8dc1 | refs/heads/master | 2022-12-21T15:36:22.950647 | 2021-02-27T16:34:47 | 2021-02-27T16:34:47 | 32,479,235 | 23 | 10 | null | 2022-12-16T05:21:07 | 2015-03-18T19:18:47 | Java | UTF-8 | Java | false | false | 769 | java |
/*
* This code is distributed under The GNU Lesser General Public License (LGPLv3)
* Please visit GNU site for LGPLv3 http://www.gnu.org/copyleft/lesser.html
*
* Copyright Denis Pavlov 2009
* Web: http://www.genericdtoassembler.org
* SVN: https://svn.code.sf.net/p/geda-genericdto/code/trunk/
* SVN (mirror): http://geda-genericdto.googlecode.com/svn/trunk/
*/
package com.inspiresoftware.lib.dto.geda.assembler.examples.simple;
import org.junit.Ignore;
/**
* Test DTO for Assembler.
*
* @author Denis Pavlov
* @since 1.0.0
*
*/
@Ignore
public interface TestEntity10Interface3 extends TestEntity10Interface2 {
/**
* @return test nested interface
*/
String getIm3();
/**
* @param im2 test nested interface
*/
void setIm3(String im2);
}
| [
"[email protected]"
] | |
fc19297d455b8fbbc5360183c6a488d3d108480d | f3fd591467d76447f59568f3a5ec2ae1f3e77cdc | /raas/src/main/java/com/controller/memberrequest_controller.java | a9645abe9d5aa170c1f1b73fce6b476fe8b6489e | [] | no_license | missaouib/raasdev | 9f03b4f5ae4500d0a069ab4ef079f8916a7b9ba8 | d25b1eb5ab841cad5af41cf0ae7559615d262d47 | refs/heads/master | 2021-09-05T15:10:15.036899 | 2018-01-29T05:49:39 | 2018-01-29T05:49:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,527 | java | package com.controller;
import java.security.Principal;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.core.env.Environment;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.dao.common_dao;
import com.service.memberRequestService;
import com.vo.memberRequest_vo;
import com.vo.registration_vo;
import com.wrapper.wrapper;
@Controller
public class memberrequest_controller {
@Autowired
private memberRequestService memberrequest_service;
@Autowired
private MessageSource messageSource;
@Autowired
private Environment env;
@Autowired
private JavaMailSender mailSender;
@Autowired
private common_dao comdao;
//send memberrequest
@RequestMapping(value = "/member_req", method = { RequestMethod.GET, RequestMethod.POST })
public String memberrequest(Locale locale, memberRequest_vo req, Model model, Principal principal,
HttpServletRequest request) throws Exception {
String username = principal.getName();
model.addAttribute("user", username);
int user_id = comdao.getuser_id(username);
List<wrapper> newlist = memberrequest_service.getmessage();
int message_id = newlist.get(0).getMessage_id();
final String token = UUID.randomUUID().toString();
System.out.println(token);
memberrequest_service.createVerificationTokenForUser(token, req, user_id);
final SimpleMailMessage email = constructEmailMessage(token, principal, req, locale, request);
mailSender.send(email);
return "/job/proposal";
}
//send email
private final SimpleMailMessage constructEmailMessage(final String token, Principal principal, memberRequest_vo req,
Locale locale, HttpServletRequest request) throws Exception {
String username = principal.getName();
int user_id = comdao.getuser_id(username);
final String recipientAddress = req.getEmail();
final String subject = "Registration Confirmation";
final String email_id = req.getEmail();
final String from = "[email protected]";
List<wrapper> newlist = memberrequest_service.getmessage();
int message_id = newlist.get(0).getMessage_id();
String message = newlist.get(0).getMessage();
System.out.println("message" + message + " " + message_id);
System.out.println(this.messageSource.getMessage("greeting", null, "Default greeting", null));
final String Url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
+ request.getContextPath();
final String confirmationUrl = Url + "/registrationConfirm?token=" + token + "&" + "email_id=" + email_id;
// final String messages = messageSource.getMessage("greeting",
// null,messages);
// System.out.println("messages"+messages);
final SimpleMailMessage email = new SimpleMailMessage();
email.setTo(recipientAddress);
email.setSubject(subject);
email.setText(message + " \r\n" + confirmationUrl);
email.setFrom(env.getProperty("[email protected]"));
memberrequest_service.saveemailcopy(email, email_id, from, user_id, message_id);
return email;
}
}
| [
"[email protected]"
] | |
af57f6b3c38daa739ae650a920e0e13e99794051 | 0071cd4051e08559e2e057acaae302ef168db7ca | /final project TIME TO SHINE (9.9.2017)/E-commerce_frontend/src/main/java/com/controller/ProductController.java | 88a5ca167f6c0fe52dae0e1e9288b034cf8a8042 | [] | no_license | sanjukta162/Advanced_Java | b087ccccf0a17675f054ccbf5a0a664bc5213171 | f7f77bdd60c990653ffa9203f022601a69b8ea33 | refs/heads/master | 2020-04-05T12:38:46.349109 | 2017-09-09T02:41:29 | 2017-09-09T02:41:29 | 95,199,351 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,972 | java | package com.controller;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import com.dao.CategoryDao;
import com.dao.ProductDao;
import com.dao.SupplierDao;
import com.model.Category;
import com.model.Product;
import com.model.Supplier;
@Controller
public class ProductController {
@Autowired
private ProductDao productdao;
@Autowired
private CategoryDao categorydao;
@Autowired
private SupplierDao supplierdao;
public ProductController(){
System.out.println("ProductController instantiated");
}
@RequestMapping(value="/addProduct",method=RequestMethod.GET)
public String listProduct(Model model)
{
List<Product> list=productdao.list();
model.addAttribute("product",new Product());
model.addAttribute("products", list);
return "addProduct";
}
@RequestMapping(value="/newProduct",method=RequestMethod.POST)
public String /*addProduct*/ newProduct(@ModelAttribute("product") Product product,HttpServletRequest request)
{
HttpSession s=request.getSession();
Category category = categorydao.getCategoryByName(product.getCategory().getCategoryName());
//categoryDao.save(category);
Supplier supplier = supplierdao.getSupplierByName(product.getSupplier().getName());
//supplierDao.save(supplier);
product.setCategory(category);
product.setSupplier(supplier);
product.setCategory_id(category.getId());
product.setSupplier_id(supplier.getId());
if(product.getId()==0)
{
productdao.save(product);
MultipartFile file=product.getImage();
// String originalfile=file.getOriginalFilename();
String fileloc=s.getServletContext().getRealPath("/resource/images/");
System.out.println(fileloc);
String filename=fileloc+"\\"+product.getId()+".jpg";
System.out.println(filename);
try{
byte b[]=file.getBytes();
FileOutputStream fos=new FileOutputStream(filename);
fos.write(b);
fos.close();
System.out.println(filename);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}}
else
{
productdao.update(product);
}
return "redirect:/addProduct";
}
@RequestMapping(value="/editProduct/{id}")
public String editP(@ModelAttribute("id") String id,Model model)
{
model.addAttribute("product", productdao.get(id));
model.addAttribute("categorys", categorydao.list());
model.addAttribute("suppliers", supplierdao.list());
return "addProduct";
}
@RequestMapping(value="/deleteProduct/{id}")
public String deleteProduct(@PathVariable("id") int id,Model model)
{
productdao.delete(id);
return "redirect:/addProduct";
}
//http://localhost:8080/E-commerce_frontend/all/product/viewproduct/1
//http://localhost:8080/E-commerce_frontend/all/product/viewproduct/2
//http://localhost:8080/E-commerce_frontend/all/product/viewproduct/3
//http://localhost:8080/E-commerce_frontend/all/product/viewproduct/191
//id=1,id=2,id=3
@RequestMapping("all/product/viewproduct/{id}")
public String getProductById (@PathVariable int id ,Model model){
Product product =productdao.getProductBYID(id);
model.addAttribute("product",product);
return "viewproduct";
}
@RequestMapping("/showproduct/{id}")
public String getselectedproductdetails(@PathVariable("id")int id,Model model)
{
Product product=productdao.getProductBYID(id);
model.addAttribute("product", product);
return "showproduct";
}
}
/* REQUEST MAPPING OF GETPRODUCT FORM !!*/
//http://localhost:8080/E-commerce_frontend/getproductform
/*@RequestMapping(value="/getproductform" )
public String getProductForm(Model model) {
//product = new Product();
List<Category> categories=productdao.getAllCategories();
model.addAttribute("categories",categories);
model.addAttribute("product",new Product());
return "productform";
}*/
/* REQUEST MAPPING OF OF ADMIN PAGE FOR GETTING PRODUCT FORM*/
/* @RequestMapping("/productform")
public String adminpage(Model model){
List<Product> products=productdao.getAllProducts();
//1st parameter is the KEY
//2nd parameter is the VALUE
model.addAttribute("product",products);
return "productform";
}*/
/* REQUEST MAPPING FOR SAVEPRODUCT*/
/* @RequestMapping("/saveproduct")
public String saveProduct (@Valid @ModelAttribute (name="product")Product product, BindingResult result,
Model model){
if(result.hasErrors())
{
List<Category> categories=productdao.getAllCategories();
model.addAttribute("categories",categories);
return "productform";
}
productdao.saveProduct(product);
//MultipartFile image=product.getImage();
return "redirect:/all/product/getallproducts";
}*/
/* @RequestMapping("/saveproduct")
public String saveProduct (@ModelAttribute(name="product")Product product){
productdao.saveProduct(product);
return "redirect:/all/product/getallproducts";
}
/*if(product.getId()==0)
{
}
else
{
productdao.editProduct(product);
}*/
//http://localhost:8080/E-commerce_frontend/all/product/getallproducts
/* @RequestMapping("/all/product/getallproducts")
public String getAllProducts(Model model) {
List<Product> products=productdao.getAllProducts();
//1st parameter is the KEY
//2nd parameter is the VALUE
model.addAttribute("products",products);
return "productlist";
}*/
/*@RequestMapping("/admin/product/deleteproduct/{id}")
public String deleteProductById(@PathVariable("id") int id) {
productdao.deleteProduct(id);
return "redirect:/all/product/getallproducts";
}
//("/admin/product/geteditform/{id}")
@RequestMapping("/geteditform/{id}")
public String getEditForm(@PathVariable int id,Model model){
List<Category> categories=productdao.getAllCategories();
model.addAttribute("categories",categories);
//select*from product where id=?
Product product =productdao.getProductById(id);
//productObj=Product - exists in table
model.addAttribute("productObj",product);
return "editform";
}*/
| [
"[email protected]"
] | |
7907eec0ecf18e391aa84d74f5e89a5e319e2370 | efde484d188782526572c754a2db87a4a575894d | /YYlib/app/src/main/java/yyl/utils/gson/reflect/typeimpl/ParameterizedTypeImpl.java | 931f2fd5c42a768912619fc1e7859cd461c7a087 | [] | no_license | yangyudaddy/yxlib | 4d7bc923b9c02679b5e1b24d5d532414053899c1 | 6c99ef9108abbf231c82782e2a862b2d4d76d3f2 | refs/heads/master | 2021-01-20T19:09:38.079181 | 2018-02-28T07:33:16 | 2018-02-28T07:33:16 | 64,806,949 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,791 | java | /*
* Copyright 2016 ikidou
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package yyl.utils.gson.reflect.typeimpl;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.Arrays;
import yyl.utils.gson.reflect.exception.TypeException;
@SuppressWarnings("SpellCheckingInspection")
public class ParameterizedTypeImpl implements ParameterizedType {
private final Class raw;
private final Type[] args;
private final Type owner;
public ParameterizedTypeImpl(Class raw, Type[] args, Type owner) {
this.raw = raw;
this.args = args != null ? args : new Type[0];
this.owner = owner;
checkArgs();
}
private void checkArgs() {
if (raw == null) {
throw new TypeException("raw class can't be null");
}
TypeVariable[] typeParameters = raw.getTypeParameters();
if (args.length != 0 && typeParameters.length != args.length) {
throw new TypeException(raw.getName() + " expect " + typeParameters.length + " arg(s), got " + args.length);
}
}
@Override
public Type[] getActualTypeArguments() {
return args;
}
@Override
public Type getRawType() {
return raw;
}
@Override
public Type getOwnerType() {
return owner;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(raw.getName());
if (args.length != 0) {
sb.append('<');
for (int i = 0; i < args.length; i++) {
if (i != 0) {
sb.append(", ");
}
Type type = args[i];
if (type instanceof Class) {
Class clazz = (Class) type;
if (clazz.isArray()) {
int count = 0;
do {
count++;
clazz = clazz.getComponentType();
} while (clazz.isArray());
sb.append(clazz.getName());
for (int j = count; j > 0; j--) {
sb.append("[]");
}
} else {
sb.append(clazz.getName());
}
} else {
sb.append(args[i].toString());
}
}
sb.append('>');
}
return sb.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ParameterizedTypeImpl that = (ParameterizedTypeImpl) o;
if (!raw.equals(that.raw)) return false;
// Probably incorrect - comparing Object[] arrays with Arrays.equals
if (!Arrays.equals(args, that.args)) return false;
return owner != null ? owner.equals(that.owner) : that.owner == null;
}
@Override
public int hashCode() {
int result = raw.hashCode();
result = 31 * result + Arrays.hashCode(args);
result = 31 * result + (owner != null ? owner.hashCode() : 0);
return result;
}
}
| [
"[email protected]"
] | |
a84717a2d205870174e9b1f7c198c0e83a5809eb | 9e040c76f529914625f6bd340d3e1814ea599a32 | /idm/openiam-idm-intf/src/main/java/org/openiam/spml2/interf/RemoteConnectorService.java | 949796beb1e352365b5b87026cd832072892dd1a | [] | no_license | Greenery/CafeBabe-R | 8b1110eedd4155d0123fcc5629367f16f7259660 | 16cea5007385313aaac49302fe4befff1bcf3692 | refs/heads/master | 2016-09-06T14:32:56.354065 | 2012-05-14T03:50:36 | 2012-05-14T03:50:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,983 | java | package org.openiam.spml2.interf;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.naming.ldap.LdapContext;
import org.openiam.connector.type.*;
import org.openiam.idm.srvc.mngsys.dto.ManagedSys;
/**
* Provides a consolidated interface that is to be used by all connectors..
* @author suneet
*
*/
@WebService(targetNamespace = "http://www.openiam.org/service/connector")
public interface RemoteConnectorService {
/**
* The add operation enables a requestor to create a new object on a target
* Attributes used by the operation are: <br>
* <li>PSOId: Unique identifier for the new object
* <li>containerId: Object where this new object should be created in. In a directory, it can be a base DN such as: ou=eng, dc=openiam, dc=org
* <li>data: Collection of data attributes that are to be stored in the target system
* <li>targetId: An id that is unique for the provider and is the system where this new object
* is to be created.
* <li>returnData:
* @param reqType
* @return
*/
@WebMethod(action="http://www.openiam.org/service/connector/RemoteConnectorService/add")
UserResponse add(
@WebParam(name = "reqType", targetNamespace = "")
UserRequest reqType);
/**
* The modify operation enables a requestor to update an existing user in the target system
* @param reqType
* @return
*/
@WebMethod(action="http://www.openiam.org/service/connector/RemoteConnectorService/modify")
UserResponse modify(
@WebParam(name = "reqType", targetNamespace = "")
UserRequest reqType);
/**
* The delete operation enables the requestor to remove a new user from the target system
* @param reqType
* @return
*/
@WebMethod(action="http://www.openiam.org/service/connector/RemoteConnectorService/delete")
UserResponse delete(
@WebParam(name = "reqType", targetNamespace = "")
UserRequest reqType);
@WebMethod(action="http://www.openiam.org/service/connector/RemoteConnectorService/lookup")
LookupResponse lookup(
@WebParam(name = "lookupRequest", targetNamespace = "")
LookupRequest lookupRequest);
@WebMethod(action="http://www.openiam.org/service/connector/RemoteConnectorService/search")
SearchResponse search(
@WebParam(name = "searchRequest", targetNamespace = "")
SearchRequest searchRequest);
/**
* The setPassword operation enables a requestor to specify a new password for an object
* @param request
* @return
*/
@WebMethod(action="http://www.openiam.org/service/connector/RemoteConnectorService/setPassword")
ResponseType setPassword(
@WebParam(name = "request", targetNamespace = "")
PasswordRequest request);
/**
* The resetPassword operation enables a requestor to change (to an unspecified value) the
* password for an object and to obtain that newly generated password value.
* @param request
* @return
*/
@WebMethod(action="http://www.openiam.org/service/connector/RemoteConnectorService/resetPassword")
ResponseType resetPassword(
@WebParam(name = "request", targetNamespace = "")
PasswordRequest request);
/**
* Suspend / disables a user
* @param request
* @return
*/
@WebMethod(action="http://www.openiam.org/service/connector/RemoteConnectorService/suspend")
ResponseType suspend(
@WebParam(name = "request", targetNamespace = "")
SuspendRequest request);
/**
* Restores a user that was previously disabled.
* @param request
* @return
*/
@WebMethod(action="http://www.openiam.org/service/connector/RemoteConnectorService/resume")
ResponseType resume(
@WebParam(name = "request", targetNamespace = "")
ResumeRequest request);
@WebMethod
public ResponseType testConnection(
@WebParam(name = "managedSys", targetNamespace = "")
ManagedSys managedSys);
}
| [
"[email protected]"
] | |
b4d9932c6f788d6d1243b82480e2366a61a28075 | 1daccb857396a58bb87e5a8bbc79123e261910a5 | /jse/src/bank/AccountService.java | 1d69ed3c6c7cefb6126e49600de84bfc55a29d46 | [] | no_license | WoojungLee/jse | 7a0271da10224015270ea6c6c6672cfd65949244 | 7ee33e29de0c753672e23b6b8cb94809fd282baa | refs/heads/master | 2021-01-10T14:37:02.048876 | 2016-02-17T09:06:34 | 2016-02-17T09:06:34 | 51,723,425 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 278 | java | package bank;
public interface AccountService {
// DB에서 CRUD(create, read, update, delete)
// 1. 통장개설
// 2. 입금
public String deposit(int money);
// 3. 출금
public String withdraw(int money);
// 4. 잔액조회
public String search();
}
| [
"user@user-PC"
] | user@user-PC |
a9c4efa26f55229ebebad92f2994a293881fe0d8 | c02d6e61c913dcbd8c199a937223532f40128556 | /security/src/main/java/com/taobao/easyweb/security/SecurityManager.java | 1fc2f9889f665ce3725f8d638359b134effe79a4 | [] | no_license | spade7/easyweb | b51f50b5b6c7e97c1849f44ac12a7ee76b3cf8bc | 448d369a209ae698b56ebc33ce22c80da17460fd | refs/heads/master | 2021-01-15T12:44:29.737006 | 2013-05-13T14:11:31 | 2013-05-13T14:11:31 | null | 0 | 0 | null | null | null | null | GB18030 | Java | false | false | 13,324 | java | package com.taobao.easyweb.security;
import groovy.lang.Script;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.taobao.easyweb.core.PaginationResult;
import com.taobao.easyweb.core.Result;
import com.taobao.easyweb.core.context.ThreadContext;
import com.taobao.easyweb.security.annotation.OnPerm;
import com.taobao.easyweb.security.dao.PermissionDAO;
import com.taobao.easyweb.security.dao.RoleDAO;
import com.taobao.easyweb.security.dao.UserDAO;
import com.taobao.easyweb.security.domain.Permission;
import com.taobao.easyweb.security.domain.Role;
import com.taobao.easyweb.security.domain.User;
@Component("ewSecurityManager")
public class SecurityManager {
@Resource(name = "ewUserDAO")
private UserDAO userDAO;
@Resource(name = "ewRoleDAO")
private RoleDAO roleDAO;
@Resource(name = "ewPermissionDAO")
private PermissionDAO permissionDAO;
// private Logger logger = LoggerUtil.getLogger();
public static Map<String, List<MethodSecurity>> securities = new ConcurrentHashMap<String, List<MethodSecurity>>();
public static Map<String, OnPerm> methodOnPerms = new ConcurrentHashMap<String, OnPerm>();
public static void add(Script script, String method, List<String> keys) {
modified = true;
for (String key : keys) {
MethodSecurity methodSecurity = new MethodSecurity();
methodSecurity.setKey(key);
methodSecurity.setClassName(script.getClass().getSimpleName());
methodSecurity.setPackageName(script.getClass().getPackage().getName());
methodSecurity.setMessages(keys.toString());
methodSecurity.setMethod(method);
add(key, methodSecurity);
}
}
public static void remove(Script script, String method, List<String> keys) {
for (String key : keys) {
MethodSecurity methodSecurity = new MethodSecurity();
methodSecurity.setKey(key);
methodSecurity.setClassName(script.getClass().getSimpleName());
methodSecurity.setPackageName(script.getClass().getPackage().getName());
methodSecurity.setMessages(keys.toString());
methodSecurity.setMethod(method);
if (securities.containsKey(key)) {
securities.get(key).remove(methodSecurity);
}
}
}
private static void add(String key, MethodSecurity methodSecurity) {
if (!securities.containsKey(key)) {
securities.put(key, new ArrayList<MethodSecurity>());
}
securities.get(key).add(methodSecurity);
}
/**
* 注册权限对象,在代码解析的时候调用
*
* @param key
* @param description
* @return
*/
public Permission regist(String key, String description) {
Permission permission = permissionDAO.queryByKey(key);
if (permission != null) {
return permission;
}
permission = new Permission();
permission.setKey(key);
permission.setDescription(description);
permissionDAO.save(permission);
return permission;
}
/**
* 暂时只删除权限对象,不删除关联权限
*
* @param permissionId
* @return
*/
public boolean deletePermission(Integer permissionId) {
int size = permissionDAO.delete(permissionId);
return size > 0;
}
public Result<String> addUserPermission(Integer userId, Integer permissionId) {
Result<String> result = new Result<String>(false);
Permission permission = permissionDAO.queryById(permissionId);
if (permission == null) {
result.addErrorMessage("权限不存在 id=" + permissionId);
return result;
}
User user = userDAO.queryById(userId);
if (user == null) {
result.addErrorMessage("用户不存在 id=" + userId);
return result;
}
result.setSuccess(true);
userDAO.applyPermission(userId, permissionId);
userPermissions.refresh(userId);
return result;
}
public void addUserRole(Integer userId, Integer roleId) {
userDAO.addRole(userId, roleId);
userPermissions.refresh(userId);
}
public void deleteUserRole(Integer userId, Integer roleId) {
userDAO.deleteRole(userId, roleId);
userPermissions.refresh(userId);
}
public boolean removeUserPermission(Integer userId, Integer permissionId) {
userDAO.removePermission(userId, permissionId);
userPermissions.refresh(userId);
return true;
}
public boolean addRolePermission(Integer roleId, Integer permissionId) {
Permission permission = permissionDAO.queryById(permissionId);
if (permission == null) {
return false;
}
Role role = roleDAO.queryById(roleId);
if (role == null) {
return false;
}
roleDAO.applyPermission(roleId, permissionId);
refreshRole(roleId);
return true;
}
public boolean removeRolePermission(Integer roleId, Integer permissionId) {
roleDAO.removePermission(roleId, permissionId);
refreshRole(roleId);
return true;
}
private void refreshRole(Integer roleId) {
List<Integer> users = queryRoleUserIds(roleId);
for (Integer user : users) {
userPermissions.refresh(user);
}
}
public List<Permission> queryRolePermissions(Integer roleId) {
List<Integer> ids = roleDAO.queryRolePermissions(roleId);
return permissionDAO.queryByIds(ids);
}
public List<Integer> queryRolePermissionIds(Integer roleId) {
return roleDAO.queryRolePermissions(roleId);
}
public Role queryRoleInfo(Integer roleId) {
return roleDAO.queryById(roleId);
}
public Result<String> addOrUpdateRole(Role role) {
Result<String> result = new Result<String>(false);
if (StringUtils.isBlank(role.getName())) {
result.addErrorMessage("角色名称不能为空");
return result;
}
Role tmp = roleDAO.queryByName(role.getName());
if (tmp == null && role.getId() == null) {
roleDAO.save(role);
result.setSuccess(true);
return result;
}
if (role.getId() != null && tmp == null) {
tmp = new Role();
tmp.setId(role.getId());
tmp.setName(role.getName());
tmp.setDescription(role.getDescription());
roleDAO.update(tmp);
}
result.setSuccess(true);
return result;
}
public List<User> queryRoleUsers(Integer roleId) {
List<Integer> ids = roleDAO.queryRoleUsers(roleId);
return userDAO.queryByIds(ids);
}
public List<Integer> queryRoleUserIds(Integer roleId) {
return roleDAO.queryRoleUsers(roleId);
}
public User queryUserByName(String name) {
User user = null;
try {
user = userCaches.get(name);
if (user.getName() == null) {
user = null;
}
} catch (ExecutionException e) {
// logger.error(e.getMessage());
}
if (user == null) {
user = new User();
user.setName(name);
try {
userDAO.save(user);
} catch (Throwable e) {
}
user = userDAO.queryByName(name);
userCaches.refresh(name);
}
return user;
}
public User queryUserAllInfo(String name) {
User user = queryUserByName(name);
if (user == null) {
return null;
}
user.setPermissions(queryUserPermissionKeys(user.getId()).keySet());
user.setRoles(queryUserRoles(user.getId()));
return user;
}
public User createUser(String name) {
User user = userDAO.queryByName(name);
if (user != null) {
return user;
}
user = new User();
user.setName(name);
userDAO.save(user);
return userDAO.queryByName(name);
}
public Role createRole(String name, String desc) {
Role role = roleDAO.queryByName(name);
if (role != null) {
return role;
}
role = new Role();
role.setName(name);
role.setDescription(desc);
roleDAO.save(role);
return roleDAO.queryByName(name);
}
/**
* 查询用户权限,用户从角色继承过来的权限也在这里体现。来源将在source说明中给出
*
* @param userId
* @return
*/
public List<Permission> queryUserPermissions(Integer userId) {
try {
return userPermissions.get(userId);
} catch (ExecutionException e) {
return Collections.emptyList();
}
}
public Map<String, Permission> queryUserPermissionKeys(Integer userId) {
List<Permission> permissions = queryUserPermissions(userId);
Map<String, Permission> permission = new HashMap<String, Permission>();
for (Permission perm : permissions) {
permission.put(perm.getKey(), perm);
}
return permission;
}
public Map<String, Permission> queryUserPermissionKeys(String authName) {
User user = queryUserByName(authName);
if (user != null) {
return queryUserPermissionKeys(user.getId());
}
return Collections.emptyMap();
}
public List<Role> queryUserRoles(Integer userId) {
List<Integer> roles = userDAO.queryUserRoles(userId);
return roleDAO.queryByIds(roles);
}
public PaginationResult<Permission> queryPermissions(int pageNumber) {
PaginationResult<Permission> result = new PaginationResult<Permission>(pageNumber, 10);
result.setTotalSize(permissionDAO.queryCount());
result.setModule(permissionDAO.queryPages(result.getStart(), result.getPageSize()));
return result;
}
public PaginationResult<User> queryUsers(int pageNumber) {
PaginationResult<User> result = new PaginationResult<User>(pageNumber, 10);
result.setTotalSize(userDAO.queryCount());
result.setModule(userDAO.queryAll(result.getStart(), result.getPageSize()));
return result;
}
public PaginationResult<Role> queryRoles(int pageNumber) {
PaginationResult<Role> result = new PaginationResult<Role>(pageNumber, 10);
result.setTotalSize(roleDAO.queryCount());
result.setModule(roleDAO.queryAll(result.getStart(), result.getPageSize()));
return result;
}
public void initSecurity(HttpServletRequest request) {
String name = (String) request.getAttribute("authName");
if (name == null) {
return;
}
User user = queryUserAllInfo(name);
ThreadContext.getContext().putContext("authUser", user);
}
public LoadingCache<String, User> userCaches = CacheBuilder.newBuilder().maximumSize(100).expireAfterWrite(10, TimeUnit.MINUTES).build(new CacheLoader<String, User>() {
public User load(String name) throws Exception {
User user = userDAO.queryByName(name);
if (user == null) {
user = new User();// 空的用户
}
return user;
}
});
public LoadingCache<Integer, List<Permission>> userPermissions = CacheBuilder.newBuilder().maximumSize(100).expireAfterWrite(10, TimeUnit.MINUTES).build(new CacheLoader<Integer, List<Permission>>() {
public List<Permission> load(Integer userId) throws Exception {
User user = userDAO.queryById(userId);
if (user == null) {
return Collections.emptyList();//
}
Set<Integer> permissionIds = new HashSet<Integer>();
List<Integer> userRoles = userDAO.queryUserRoles(user.getId());
List<Integer> rolePermissions = new ArrayList<Integer>();
if (!userRoles.isEmpty()) {
rolePermissions = roleDAO.queryRolesPermissions(userRoles);
permissionIds.addAll(rolePermissions);
}
List<Integer> userPermissions = userDAO.queryUserPermissions(user.getId());
permissionIds.addAll(userPermissions);
List<Permission> permissions = permissionDAO.queryByIds(new ArrayList<Integer>(permissionIds));
for (Permission permission : permissions) {
if (rolePermissions.contains(permission.getId())) {
permission.setDescription(permission.getDescription() + ";来自角色的权限");
}
if (userPermissions.contains(permission.getId())) {
permission.setDescription(permission.getDescription() + ";来自用户的权限");
}
}
return permissions;
}
});
private static volatile boolean modified = false;
Thread syncThread = new Thread(new Runnable() {
public void run() {
while (true) {
try {
if (modified) {
for (String key : securities.keySet()) {
regist(key, "系统同步");
}
modified = false;
}
Thread.sleep(3000);
} catch (Throwable e) {
}
}
}
});
@PostConstruct
public void init() {
syncThread.start();
}
public static void check(String[] roles, String[] users, String[] perms) {
User user = (User) ThreadContext.getContext().getContext("authUser");
if (user == null) {
throw new SecurityException("没有用户对象");
}
if (roles != null && roles.length > 0) {
for (String r : roles) {
if (user.getRoleNames().contains(r)) {
return;
}
}
}
if (users != null && users.length > 0) {
for (String r : users) {
if (user.getRoleNames().contains(r)) {
return;
}
}
}
if (perms != null && perms.length > 0) {
Set<String> userPermissions = user.getPermissions();
for (String p : perms) {
if (!userPermissions.contains(p)) {
throw new SecurityException("no permission " + p);
}
}
}
}
}
| [
"[email protected]"
] | |
3e00402c94bf81befd862396dbe11380b3b7a7d0 | 4682b0efc3824333c858ac3823297e2a4b37fa05 | /play-services-core/src/main/java/org/microg/gms/maps/markup/CircleImpl.java | 1dd8d40dd5a36057133e1bdf5494d13116764c40 | [
"Apache-2.0"
] | permissive | julienschmidt/android_packages_apps_GmsCore | a29c2505ab8e7064021026802613490fd8845a95 | 611fe016a0c529bc738155d2dcdb1f69dd6a830e | refs/heads/master | 2023-08-15T03:45:20.464877 | 2015-10-10T05:21:08 | 2015-10-10T05:21:08 | 38,508,731 | 1 | 1 | null | 2015-07-03T20:02:01 | 2015-07-03T20:02:01 | null | UTF-8 | Java | false | false | 4,447 | java | /*
* Copyright 2013-2015 microG Project Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.microg.gms.maps.markup;
import android.os.RemoteException;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.internal.ICircleDelegate;
import org.microg.gms.maps.GmsMapsTypeHelper;
import org.oscim.layers.vector.geometries.CircleDrawable;
import org.oscim.layers.vector.geometries.Drawable;
import org.oscim.layers.vector.geometries.Style;
import org.oscim.map.Map;
public class CircleImpl extends ICircleDelegate.Stub implements DrawableMarkup {
private final String id;
private final CircleOptions options;
private final MarkupListener listener;
private boolean removed = false;
public CircleImpl(String id, CircleOptions options, MarkupListener listener) {
this.id = id;
this.listener = listener;
this.options = options == null ? new CircleOptions() : options;
}
@Override
public void remove() throws RemoteException {
listener.remove(this);
removed = true;
}
@Override
public String getId() {
return id;
}
@Override
public void setCenter(LatLng center) throws RemoteException {
options.center(center);
listener.update(this);
}
@Override
public LatLng getCenter() throws RemoteException {
return options.getCenter();
}
@Override
public void setRadius(double radius) throws RemoteException {
options.radius(radius);
listener.update(this);
}
@Override
public double getRadius() throws RemoteException {
return options.getRadius();
}
@Override
public void setStrokeWidth(float width) throws RemoteException {
options.strokeWidth(width);
listener.update(this);
}
@Override
public float getStrokeWidth() throws RemoteException {
return options.getStrokeWidth();
}
@Override
public void setStrokeColor(int color) throws RemoteException {
options.strokeColor(color);
listener.update(this);
}
@Override
public int getStrokeColor() throws RemoteException {
return options.getStrokeColor();
}
@Override
public void setFillColor(int color) throws RemoteException {
options.fillColor(color);
listener.update(this);
}
@Override
public int getFillColor() throws RemoteException {
return options.getFillColor();
}
@Override
public void setZIndex(float zIndex) throws RemoteException {
options.zIndex(zIndex);
listener.update(this);
}
@Override
public float getZIndex() {
return options.getZIndex();
}
@Override
public void setVisible(boolean visible) throws RemoteException {
options.visible(visible);
listener.update(this);
}
@Override
public boolean isVisible() {
return options.isVisible();
}
@Override
public boolean equalsRemote(ICircleDelegate other) throws RemoteException {
return other != null && other.getId().equals(getId());
}
@Override
public int hashCodeRemote() throws RemoteException {
return id.hashCode();
}
@Override
public boolean onClick() {
return listener.onClick(this);
}
@Override
public Drawable getDrawable(Map map) {
if (!isVisible() || removed) return null;
return new CircleDrawable(
GmsMapsTypeHelper.fromLatLng(options.getCenter()),
options.getRadius() / 1000.0,
Style.builder()
.strokeColor(options.getStrokeColor())
.fillAlpha(1)
.fillColor(options.getFillColor())
.strokeWidth(options.getStrokeWidth()).build());
}
}
| [
"[email protected]"
] | |
de28a522976fb2a07e4a3633c505baa8eeab0775 | 4aa9b944c5d72b78009a91f8094d2e4ef9200180 | /src/test/java/com/kelaskoding/CatatPengeluaranApiApplicationTests.java | 8baff28e66656d17c143db2605d12c215c852ec5 | [] | no_license | hendrosteven/spring-demo-expenses-api | f3c94e70f531aaa635ba9272817d25839996362d | fc1754b3714a0233116d87cafbb1b92f5b99fe7a | refs/heads/master | 2022-12-06T08:13:03.583096 | 2020-08-17T09:04:25 | 2020-08-17T09:04:25 | 287,984,534 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 220 | java | package com.kelaskoding;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class CatatPengeluaranApiApplicationTests {
@Test
void contextLoads() {
}
}
| [
"[email protected]"
] | |
7edc342cee7b91666371b820f3158952b2b94f58 | 94b14303a49c9097787a5a457a688ad0393d3966 | /app/src/androidTest/java/com/ccdev/opcua_client/ExampleInstrumentedTest.java | d9eeb6479a29a8607df135ac54793a348300b2f7 | [] | no_license | sangjiexun/OpcUA-Client | 6cabf2ddb36c87eb5ad5c3b9e072a5a962c16ce5 | 53f2fc769366aee62c6586845cbbb713152e954a | refs/heads/master | 2022-12-02T18:39:40.605593 | 2020-07-29T11:33:17 | 2020-07-29T11:33:17 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 771 | java | package com.ccdev.opcua_client;
import android.content.Context;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.platform.app.InstrumentationRegistry;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.ccdev.opcua_client", appContext.getPackageName());
}
}
| [
"[email protected]"
] | |
877fa22600d76dc191cc1572715f8fbb603f1e6f | e5f13984e6f00f90dd5117d0208cc7b2a50cc0e8 | /GameLife/app/src/main/java/com/example/gamelife/leagueoflegends/models/Player.java | b593440809bc2af833ea9d216f952ce7f300d76c | [] | no_license | msd-11/and-project | d7c61f1237ba409f9ca1ae3f4082dbf48b2e448c | 9e9560ceb7d5a864f218cc8c760755ec8acd6d86 | refs/heads/main | 2023-05-04T18:47:10.031044 | 2021-05-20T15:02:32 | 2021-05-20T15:02:32 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 255 | java | package com.example.gamelife.leagueoflegends.models;
/**
* Player is the class that contain the username of the user
*/
public class Player {
private String summonerName;
public String getSummonerName() {
return summonerName;
}
}
| [
"[email protected]"
] | |
ab358d18f8ff75e3bc6ea28f80aeb2f3773b8412 | 81457b162b68f625d0181dd510eb22b3e3b393d2 | /board4_portfolio/src/com/company/controller2/BWriteAction.java | a5687bbbd37c684df3da78bb4c2bd631b7098be6 | [] | no_license | 2hansoul/portfolio | c2e055bb7f71ee451161ef3979eb997e611b0203 | 6ff5708b2398e26c3b46db03358ab4f678391dfa | refs/heads/master | 2023-05-04T17:23:25.478997 | 2021-05-05T15:38:42 | 2021-05-05T15:38:42 | 362,493,584 | 0 | 0 | null | null | null | null | UHC | Java | false | false | 2,077 | java | package com.company.controller2;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.company.dao.Bdao_list;
import com.company.dto.BDto;
import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
public class BWriteAction implements BAciton {
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
PrintWriter out =response.getWriter();
Bdao_list dao2=new Bdao_list();
BDto dto2=new BDto();
//1.경로설정
String path="/upload";
path=request.getServletContext().getRealPath(path);//서버에 담긴정보들
//댓글달기
int bgroup = -1, bstep = -1, bindent = -1, max=-1;
max = dao2.create_max();
bgroup = (int)(Math.ceil(max/(float)1000)) + 1;
bstep = bgroup * 1000;
bindent = 0;
////
MultipartRequest multi = new MultipartRequest(request, path, 1024*1024*5, "UTF-8", new DefaultFileRenamePolicy());
dto2.setBname(multi.getParameter("bname"));
dto2.setBpass(multi.getParameter("bpass"));
dto2.setBtitle(multi.getParameter("btitle"));
dto2.setBcontent(multi.getParameter("bcontent"));
dto2.setImg(multi.getFilesystemName("img"));
dto2.setBgroup(bgroup);
dto2.setBstep(bstep);
dto2.setBindent(bindent);
int result=dao2.create(dto2);
request.setAttribute("create", result);
System.out.println("글 쓰기"+result);
if(result>0) {
out.println("<script>alert('글쓰기성공'); location.href='"+request.getContextPath()+"/list.do';</script>");
}else {
out.println("<script>alert('관리자 문의 해주세요');history.go(-1);</script>");
}
}
}
| [
"2hans@DESKTOP-6NMVSP0"
] | 2hans@DESKTOP-6NMVSP0 |
0c1a8e7a31c54c318de34af0d0fede9c88e9e5d4 | 765d5447962f252184625798b7ffc964376b86c6 | /ComparisonClient/src/Indexer.java | 618c432a57b4171eec82b3cd67ea81e1364f0438 | [] | no_license | Drakus1/Nitish-Squad-Project | 5a52ed597b8fe0ea11390e95adb72233780c0bbf | 8ae4bc69b916afe8842dc2e6d3cdab9d9d3045ed | refs/heads/master | 2021-01-24T06:57:31.044198 | 2017-07-06T01:44:21 | 2017-07-06T01:44:21 | 93,330,470 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,614 | java |
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.Version;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.TermFreqVector;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.TermDocs;
import org.apache.lucene.index.TermEnum;
import org.apache.lucene.index.Term;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.FileReader;
@SuppressWarnings("deprecation")
public class Indexer {
/*
public static void main(String[] args) throws Exception {
String indexDir = "/Users/sam/Desktop/lia.meetlucene/MyIndex";
String dataDir = "/Users/sam/Desktop/lia.meetlucene/MyText";
long start = System.currentTimeMillis();
Indexer indexer = new Indexer(indexDir);
int numIndexed;
try {
numIndexed = indexer.index(dataDir, new TextFilesFilter());
} finally {
//indexer.close();
}
long end = System.currentTimeMillis();
System.out.println("Indexing " + numIndexed + " files took "
+ (end - start) + " milliseconds");
// My Code!!!
IndexReader reader = indexer.writer.getReader();
int dimensions = uniqueWords(reader);
int numDocuments = reader.numDocs();
Vector[] vectorArray = new Vector[numDocuments];
for (int i = 0; i < numDocuments; i++)
vectorArray[i] = new Vector(dimensions);
// for each term in the dictionary
TermEnum myTerms = reader.terms();
int currentDimension = 0;
while (myTerms.next()) {
// get current term
Term currentTerm = myTerms.term();
if (currentTerm.field() != "contents") continue;
// calculate idf(t)
double documentFreqTerm = (double) myTerms.docFreq();
double inverseDocFreq = 1 + Math.log(numDocuments / documentFreqTerm);
// for each document in the collection
TermDocs myDocs = reader.termDocs(currentTerm);
for (int j = 0; myDocs.next(); j++) {
// calculate tf-idf(term, document)
int termFreq = myDocs.freq();
double tfidf = termFreq * inverseDocFreq;
// set corresponding field in vector
vectorArray[j].setValue(currentDimension, tfidf);
}
myDocs.close();
currentDimension++;
}
myTerms.close();
indexer.close();
}
*/
/*
private static int uniqueWords(IndexReader reader) throws Exception {
TermEnum myEnum = reader.terms();
int uniques = 0;
while (myEnum.next()) {
Term t = myEnum.term();
if (t.field() == "contents") {
uniques++;
}
}
myEnum.close();
return uniques;
}
*/
private IndexWriter writer;
public IndexWriter getWriter() {
return this.writer;
}
public Indexer(String indexDir) throws IOException {
Directory dir = FSDirectory.open(new File(indexDir));
writer = new IndexWriter(dir,new StandardAnalyzer(Version.LUCENE_30),
true, IndexWriter.MaxFieldLength.UNLIMITED);
}
public void close() throws IOException {
writer.close();
}
public int index(String dataDir, FileFilter filter)
throws Exception {
File[] files = new File(dataDir).listFiles();
for (File f: files) {
if (!f.isDirectory() &&
!f.isHidden() &&
f.exists() &&
f.canRead() &&
(filter == null || filter.accept(f))) {
indexFile(f);
}
}
return writer.numDocs(); //5
}
private static class TextFilesFilter implements FileFilter {
public boolean accept(File path) {
return path.getName().toLowerCase() //6
.endsWith(".txt"); //6
}
}
protected Document getDocument(File f) throws Exception {
Document doc = new Document();
doc.add(new Field("contents", new FileReader(f), Field.TermVector.YES));
doc.add(new Field("filename", f.getName(),
Field.Store.YES, Field.Index.NOT_ANALYZED));
doc.add(new Field("fullpath", f.getCanonicalPath(),
Field.Store.YES, Field.Index.NOT_ANALYZED));
return doc;
}
private void indexFile(File f) throws Exception {
System.out.println("Indexing " + f.getCanonicalPath());
Document doc = getDocument(f);
writer.addDocument(doc); //10
}
}
| [
"[email protected]"
] | |
dbf7f7a58b7950b79f7e3b3e805ea0e9f3210878 | 91aa08f5d51a71bb4536f8ec130877d715226c03 | /app/src/main/java/com/lcanaveral/movile/traktapp/ui/episodes/Episode.java | b0aede61c986bee74f5fde9d8c5bb99a44dc0235 | [] | no_license | lcanaveral/recrutamento-android | f01be15be926bef86b475b1ddbadc6117e5c5a34 | d0bb7af215a1560be55fa85c39233bca0d77d698 | refs/heads/master | 2021-01-21T08:55:26.362006 | 2016-08-01T16:00:23 | 2016-08-01T16:00:23 | 64,362,676 | 0 | 0 | null | 2016-08-01T16:00:23 | 2016-07-28T03:52:45 | Java | UTF-8 | Java | false | false | 376 | java | package com.lcanaveral.movile.traktapp.ui.episodes;
import com.lcanaveral.movile.traktapp.api.payloads.EpisodePayload;
/**
* Created by lcanaveral on 7/30/16.
*/
public class Episode {
public String title;
public int number;
public Episode(EpisodePayload episodePayload){
title = episodePayload.title;
number = episodePayload.number;
}
}
| [
"[email protected]"
] | |
9b85d54ba73c178b78d10a2606c51b74b91a2531 | aa6997aba1475b414c1688c9acb482ebf06511d9 | /src/com/sun/org/apache/xml/internal/security/encryption/XMLCipherParameters.java | acd9adf4d4d92316caf0d7525ab8f161258f62cc | [] | no_license | yueny/JDKSource1.8 | eefb5bc88b80ae065db4bc63ac4697bd83f1383e | b88b99265ecf7a98777dd23bccaaff8846baaa98 | refs/heads/master | 2021-06-28T00:47:52.426412 | 2020-12-17T13:34:40 | 2020-12-17T13:34:40 | 196,523,101 | 4 | 2 | null | null | null | null | UTF-8 | Java | false | false | 2,533 | java | /*
* Copyright (c) 2007, 2015, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.encryption;
/**
* Constants
*/
public interface XMLCipherParameters {
String AES_128 =
"http://www.w3.org/2001/04/xmlenc#aes128-cbc";
String AES_256 =
"http://www.w3.org/2001/04/xmlenc#aes256-cbc";
String AES_192 =
"http://www.w3.org/2001/04/xmlenc#aes192-cbc";
String RSA_1_5 =
"http://www.w3.org/2001/04/xmlenc#rsa-1_5";
String RSA_OAEP =
"http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p";
String DIFFIE_HELLMAN =
"http://www.w3.org/2001/04/xmlenc#dh";
String TRIPLEDES_KEYWRAP =
"http://www.w3.org/2001/04/xmlenc#kw-tripledes";
String AES_128_KEYWRAP =
"http://www.w3.org/2001/04/xmlenc#kw-aes128";
String AES_256_KEYWRAP =
"http://www.w3.org/2001/04/xmlenc#kw-aes256";
String AES_192_KEYWRAP =
"http://www.w3.org/2001/04/xmlenc#kw-aes192";
String SHA1 =
"http://www.w3.org/2000/09/xmldsig#sha1";
String SHA256 =
"http://www.w3.org/2001/04/xmlenc#sha256";
String SHA512 =
"http://www.w3.org/2001/04/xmlenc#sha512";
String RIPEMD_160 =
"http://www.w3.org/2001/04/xmlenc#ripemd160";
String XML_DSIG =
"http://www.w3.org/2000/09/xmldsig#";
String N14C_XML =
"http://www.w3.org/TR/2001/REC-xml-c14n-20010315";
String N14C_XML_CMMNTS =
"http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments";
String EXCL_XML_N14C =
"http://www.w3.org/2001/10/xml-exc-c14n#";
String EXCL_XML_N14C_CMMNTS =
"http://www.w3.org/2001/10/xml-exc-c14n#WithComments";
}
| [
"[email protected]"
] | |
61901290dff5a3abeb7d7f33d51dd54fbc48e38e | 8e738262c71b8d33d8a6584b7efdb22c1f5f9330 | /admin-testcase/admin-common-testcase/src/main/java/no/valg/eva/admin/common/configuration/filter/Filter.java | 668845672a784f49a79f62b8ca14007a8d969664 | [] | no_license | runeks/admin-testcase | 49812deaa3c9659c21851194841a2757e859371a | 331ee44e959a67f68bdda5db36b3e3903ab32fbf | refs/heads/master | 2021-01-21T12:26:24.565098 | 2015-02-16T08:26:03 | 2015-02-16T08:26:03 | 27,547,846 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 160 | java | package no.valg.eva.admin.common.configuration.filter;
import java.io.Serializable;
public interface Filter<T> extends Serializable {
boolean filter(T t);
}
| [
"[email protected]"
] | |
1f2cc5fdefafd33f066aeec48caf63ef468b583c | 75afb9c9f59d25376a6194fac9cfb0908e71cf07 | /Project_2020_02_13/src/Outer/Run.java | 5c65a5704f1c5d8e21b1b13b9b7daa025b641e64 | [] | no_license | bbster/JAVA_EDU | 781cc3bf348acd63ce0b7164031e4ce7e0cfabf9 | 20d9c7829c63dbf1eac23b50084d05906fffa755 | refs/heads/master | 2020-12-28T16:12:30.134871 | 2020-03-03T09:49:22 | 2020-03-03T09:49:22 | 238,143,144 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 179 | java | package Outer;
public class Run {
public static void main(String[] args) {
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
inner.method();
}
}
| [
"[email protected]"
] | |
e9a5479a4252adabf84b620c63d7e18cac8b51ee | 2b1eeaa3998b0d0042e869c6f669ecbde0328d63 | /src/day6/Super_class.java | db57555d41f07c78c219f656dda7263fc4ec9999 | [] | no_license | rezafd23/shifted | ee8eb38e5ff12f7016231f754d902e6554f81077 | b4419a7a1f469980b0651451ec179cbddd1e34b6 | refs/heads/master | 2023-01-18T18:03:06.646574 | 2020-11-19T10:24:46 | 2020-11-19T10:24:46 | 314,155,748 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 191 | java | package day6;
class Super_class {
int num = 20;
// display method of superclass
public void display() {
System.out.println("This is the display method of superclass");
}
} | [
"[email protected]"
] | |
5e6b2ed1386348552940e0ead0eb8457fbb41165 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/5/5_c7cffd05d023e1e8ed34788abc7f8593cca44dc4/ExtendsTest/5_c7cffd05d023e1e8ed34788abc7f8593cca44dc4_ExtendsTest_t.java | 87648c7f91b13024357009f6d938f388b368eae1 | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 5,694 | java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.wicket.security;
import java.net.MalformedURLException;
import org.apache.wicket.ISessionFactory;
import org.apache.wicket.Request;
import org.apache.wicket.Response;
import org.apache.wicket.Session;
import org.apache.wicket.protocol.http.WebApplication;
import org.apache.wicket.security.actions.ActionFactory;
import org.apache.wicket.security.hive.HiveMind;
import org.apache.wicket.security.hive.config.PolicyFileHiveFactory;
import org.apache.wicket.security.pages.MockHomePage;
import org.apache.wicket.security.pages.MockLoginPage;
import org.apache.wicket.security.strategies.StrategyFactory;
import org.apache.wicket.security.swarm.SwarmWebApplication;
import org.apache.wicket.security.swarm.actions.SwarmActionFactory;
import org.apache.wicket.security.swarm.strategies.SwarmStrategyFactory;
import org.apache.wicket.util.tester.WicketTester;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Test if everything still works if we don't inherit from {@link SwarmWebApplication} but
* simply implement all the required interfaces. This simply runs all the tet from
* {@link GeneralTest} and if we don't get a {@link ClassCastException} or something like
* that everythings works ok.
* @author marrink
*/
public class ExtendsTest extends GeneralTest
{
private static final class TestApplication extends WebApplication implements WaspApplication,
ISessionFactory
{
private ActionFactory actionFactory;
private StrategyFactory strategyFactory;
/**
*
*/
public TestApplication()
{
super();
setSessionFactory(this);
}
protected Object getHiveKey()
{
// if we were using servlet-api 2.5 we could get the contextpath from the
// servletcontext
return "test";
}
protected void setUpHive()
{
PolicyFileHiveFactory factory = new PolicyFileHiveFactory();
try
{
factory.addPolicyFile(getServletContext().getResource("WEB-INF/policy.hive"));
factory.setAlias("TestPrincipal",
"org.apache.wicket.security.hive.authorization.TestPrincipal");
factory.setAlias("myPackage", "org.apache.wicket.security.pages");
}
catch (MalformedURLException e)
{
log.error(e.getMessage(), e);
}
HiveMind.registerHive(getHiveKey(), factory);
}
public Class getHomePage()
{
return MockHomePage.class;
}
public Class getLoginPage()
{
return MockLoginPage.class;
}
public Session newSession(Request request, Response response)
{
return new WaspSession(this, request);
}
/**
* @see org.apache.wicket.security.WaspApplication#getActionFactory()
*/
public ActionFactory getActionFactory()
{
return actionFactory;
}
/**
* @see org.apache.wicket.security.WaspApplication#getStrategyFactory()
*/
public StrategyFactory getStrategyFactory()
{
return strategyFactory;
}
/**
* @see org.apache.wicket.security.WaspWebApplication#setupActionFactory()
*/
protected void setupActionFactory()
{
if (actionFactory == null)
actionFactory = new SwarmActionFactory();
else
throw new IllegalStateException("Can not initialize ActionFactory more then once");
}
/**
* @see org.apache.wicket.security.WaspWebApplication#setupStrategyFactory()
*/
protected void setupStrategyFactory()
{
if (strategyFactory == null)
strategyFactory = new SwarmStrategyFactory(getHiveKey());
else
throw new IllegalStateException("Can not initialize StrategyFactory more then once");
}
/**
* triggers the setup of the factories and the hive. Please remember to call
* super.init when you override this method.
* @see org.apache.wicket.security.WaspWebApplication#init()
*/
protected void init()
{
setupActionFactory();
setUpHive();
setupStrategyFactory();
}
/**
* Destroys the strategy factory and the action factory. In that order. If you
* override ths method you must call super.destroy().
* @see Application#onDestroy()
*/
protected void onDestroy()
{
StrategyFactory factory = getStrategyFactory();
if (factory != null)
factory.destroy();
ActionFactory factory2 = getActionFactory();
if (factory2 != null)
factory2.destroy();
}
}
private static final Logger log = LoggerFactory.getLogger(ExtendsTest.class);
/**
* @see junit.framework.TestCase#setUp()
*/
protected void setUp() throws Exception
{
mock = new WicketTester(application = new TestApplication(), "src/test/java/"
+ getClass().getPackage().getName().replace('.', '/'));
}
}
| [
"[email protected]"
] | |
ad7095325ad23ef3b89f8c1acc48abbd88836fc4 | 05820facac3ed53d41154687d6dd9742dab85409 | /HackerRank/src/algorithms/gametheory/VerticalRooks.java | 648fdddeb4215a1ae0d5f757b45dc746682d727b | [] | no_license | sabotuer99/HackerRank-Java | 6db200c4133d6ff46f67f27d27c8e22e6ba71bbc | bfaf84723018957e91ee4bbdbc3ff44da868d777 | refs/heads/master | 2021-01-10T03:56:46.121473 | 2017-12-01T21:52:10 | 2017-12-01T21:52:10 | 47,937,026 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 905 | java | import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
for(int T = in.nextInt(); T > 0; T--){
int n = in.nextInt();
int[] heaps = new int[n];
for(int i = 0; i < n; i++){
heaps[i] = in.nextInt();
}
int nimSum = 0;
int[] hash = new int[n];
for(int i = 0; i < n; i++){
hash[i] = (Math.abs(heaps[i] - in.nextInt()) - 1);
nimSum ^= hash[i];
}
int omoves = 0;
for(int i = 0; i < n; i++){
omoves += (nimSum ^ hash[i]) < hash[i] ? 1 : 0;
}
System.out.println(omoves%2 == 0 ? "player-1" : "player-2");
}
}
}
| [
"[email protected]"
] | |
dc6948037780b7343b620acba7a680ba1c992593 | 790cb30f9a2ca55cba7ce467cd10fce983499ce8 | /ForEachLoop.java | ff50f84008eb5c3017932f8118e78a90d81c2b6c | [] | no_license | quanganh2001/java-basic-howkteam | 4a898de2a7498e93fba8ef1858558ef947565ff8 | 765e08c1f6c39c056101cbadc55a8c7df98449b3 | refs/heads/main | 2023-07-16T01:17:59.246070 | 2021-08-30T08:13:53 | 2021-08-30T08:13:53 | 400,226,004 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 186 | java | public class ForEachLoop {
public static void main(String[] args) {
int[] array = {1,2,4};
for (int a: array) {
System.out.println(a);
}
}
}
| [
"[email protected]"
] | |
316c14527d20d3fbe3f7516389f2ff70bfa52180 | 30057e353957920564ee07722427c3ff434d322f | /ProblemSolving/src/com/basics/string/RepeatedDNASequence.java | 82c61839d095d2be889a157b19a0031be1f1e9f1 | [] | no_license | mmanjunath998/Problem-Solving | a7f4e541b150ad3d28e545b7c990d47b020c79a9 | 32f21921f05ff351a6cdc52fe72e954633d9036a | refs/heads/master | 2020-09-09T15:06:46.232130 | 2019-12-04T08:04:58 | 2019-12-04T08:04:58 | 221,479,218 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,342 | java | package com.basics.string;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class RepeatedDNASequence {
public static void main(String[] args){
String str = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT";
System.out.println(find(str, 10));
}
public static List<String> find(String str, int k){
Set<String> result = new HashSet<>();
Set<String> visited = new HashSet<>();
for(int i=0; i<=str.length()-k; i++){
String sub = str.substring(i, i+k);
if(visited.contains(sub)){
result.add(sub);
}else{
visited.add(sub);
}
}
return new ArrayList<>(result);
}
public static List<String> findDNA(String str, int k){
Set<String> res = new HashSet<String>();
Set<String> visited = new HashSet<String>();
for(int i=0; i<str.length()-k; i++){
String sub = str.substring(i, i+k);
if(visited.contains(sub)){
res.add(sub);
}else{
visited.add(sub);
}
}
return new ArrayList<>(res);
}
public static boolean compareString(String str, int p1, int p2, int k){
for(int i=0; i<k; i++){
if(str.charAt(p1+i) != str.charAt(p1+i)){
return false;
}
}
return true;
}
/*
* 1: scan through the str i to n
* 2: for every i scan j = i+k to n
* 3: if we match found then compare twoStrings from
*
*
*
*/
}
| [
"[email protected]"
] | |
a46ac35488543a1f6317ccb1f194e1a0b6fd6ff8 | cab952c1934e2c3ff1926fea39e9f096e419b17b | /service-ribbon/src/main/java/com/forezp/serviceribbon/HelloService.java | 3f502f83367f15977ef3348fa7c4767458163c0c | [] | no_license | 755472363/za-Repository | 0eec9a42b07756cf176da24546637af862e3fe94 | c00a81cc7aa68a979e2295fa35cfabfc8971f17c | refs/heads/master | 2021-04-27T06:02:02.377441 | 2018-03-15T06:09:09 | 2018-03-15T06:09:09 | 122,605,115 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 660 | java | package com.forezp.serviceribbon;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class HelloService {
@Autowired
RestTemplate restTemplate;
@HystrixCommand(fallbackMethod = "hiError")
public String hiService(String name) {
String str = restTemplate.getForObject("http://SERVICE-HI/hi?name="+name,String.class);
return str;
}
public String hiError(String name) {
return "hi,"+name+",sorry,error!";
}
}
| [
"[email protected]"
] | |
7629cf8eade3d699a320a8030885c5b82caced69 | 995f73d30450a6dce6bc7145d89344b4ad6e0622 | /P40_HarmonyOS_2.0.0_Developer_Beta1/src/main/java/ohos/nfc/tag/NfcFTag.java | 845c2d35eadb68d04eeb39d0cac25af34e0addc1 | [] | no_license | morningblu/HWFramework | 0ceb02cbe42585d0169d9b6c4964a41b436039f5 | 672bb34094b8780806a10ba9b1d21036fd808b8e | refs/heads/master | 2023-07-29T05:26:14.603817 | 2021-09-03T05:23:34 | 2021-09-03T05:23:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,179 | java | package ohos.nfc.tag;
import java.util.Optional;
import ohos.aafwk.content.IntentParams;
public class NfcFTag extends TagManager {
private static final String EXTRA_PMM = "pmm";
private static final String EXTRA_SC = "systemcode";
private byte[] mPMm = null;
private byte[] mSystemCode = null;
public static Optional<NfcFTag> getInstance(TagInfo tagInfo) {
if (!tagInfo.isProfileSupported(4)) {
return Optional.empty();
}
return Optional.of(new NfcFTag(tagInfo));
}
public NfcFTag(TagInfo tagInfo) {
super(tagInfo, 4);
IntentParams orElse;
if (tagInfo.isProfileSupported(4) && (orElse = tagInfo.getProfileExtras(4).orElse(null)) != null) {
if (orElse.getParam(EXTRA_SC) instanceof byte[]) {
this.mSystemCode = (byte[]) orElse.getParam(EXTRA_SC);
}
if (orElse.getParam(EXTRA_PMM) instanceof byte[]) {
this.mPMm = (byte[]) orElse.getParam(EXTRA_PMM);
}
}
}
public byte[] getSystemCode() {
return this.mSystemCode;
}
public byte[] getPMm() {
return this.mPMm;
}
}
| [
"[email protected]"
] | |
a1b926c929758e76460110df944dece89c1410f3 | 1ed5c16927e98d62a160cf52ef563cd4a45e2122 | /backups/Proshop_report_pace.java | 78e6908743ac9a02f4f0989b040c70f2b6efa434 | [] | no_license | uksubs66/java-v2 | b1517d1866360ffca7356d61bb360233ea479f58 | baba766e11ca8bb1930db5cb0d3b645ed9e7250c | refs/heads/master | 2021-01-25T08:59:44.495711 | 2015-07-17T15:37:27 | 2015-07-17T15:37:27 | 39,220,401 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 84,649 | java | /***************************************************************************************
* Proshop_report_pace: This servlet will ouput all of the Pace of Play reports
*
*
* Called by: reports tab menu option
* proshop_sheet - control panel menu item
* self
*
*
* Created: 06/14/2006
*
*
* Revisions:
*
*
***************************************************************************************
*/
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.sql.*;
import java.lang.Math;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.NumberFormat;
// foretees imports
import com.foretees.common.parmClub;
import com.foretees.common.getClub;
public class Proshop_report_pace extends HttpServlet {
String rev = SystemUtils.REVLEVEL; // Software Revision Level (Version)
boolean g_debug = true;
DateFormat df_full = DateFormat.getDateInstance(DateFormat.MEDIUM);
NumberFormat nf = NumberFormat.getNumberInstance();
//*****************************************************
// Display a report selection menu page and offer help
//*****************************************************
//
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
HttpSession session = SystemUtils.verifyPro(req, out);
if (session == null) { return; }
Connection con = SystemUtils.getCon(session); // get DB connection
if (con == null) {
SystemUtils.buildDatabaseErrMsg("Can not establish connection.", "", out, true);
return;
}
Statement stmt = null;
ResultSet rs = null;
int multi = 0;
int paceofplay = 0;
String user = "";
String lname = "";
String fname = "";
String mname = "";
parmClub parm = new parmClub();
try {
getClub.getParms(con, parm); // get the club parms
} catch (Exception ignore) { }
multi = parm.multi;
paceofplay = parm.paceofplay;
String templott = (String)session.getAttribute("lottery"); // get lottery support indicator
int lottery = Integer.parseInt(templott);
out.println(SystemUtils.HeadTitle2("Pace of Play Reports"));
out.println("</head>");
out.println("<body bgcolor=\"#FFFFFF\" text=\"#000000\" link=\"#336633\" vlink=\"#336633\" alink=\"#000000\">");
SystemUtils.getProshopSubMenu(req, out, lottery); // required to allow submenus on this page
// if pace of play is not enabled for this club then ABORT :O
if (paceofplay == 0) {
out.println("<p> </p><p align=center>" +
"Pace of Play is not enabled for your club. This feature can be enabled by going to System Config | Club Setup | Club Options. " +
"</p>");
return;
}
// output client scripts to use for this page
out.println("<script>");
out.println("function reqReport(pTodo, pGetDate) {");
out.println(" var f = document.forms['frmWhichReport'];");
out.println(" f.todo.value = pTodo;");
out.println(" f.get_date.value = pGetDate;");
out.println(" f.submit();");
out.println("}");
out.println("function openHelpWindow() {");
out.println(" w = window.open ('/" +rev+ "/proshop_help_paceofplay_reports.htm','helpPopup','width=640,height=455,scrollbars=1,dependent=0,directories=0,location=0,menubar=0,resizable=1,status=0,toolbar=0');");
out.println(" w.creator = self;");
out.println("}");
out.println("</script>");
// start form to post
out.println("<form method=post action=\"/"+rev+"/servlet/Proshop_report_pace\" name=frmWhichReport id=frmWhichReport>");
out.println("<input type=hidden name=todo value=\"\">");
out.println("<input type=hidden name=get_date value=\"0\">");
// page header
out.println("<table cellspacing=25 align=center border=0>");
out.println(" <tr><td colspan=3 align=center><h2>Choose a Pace of Play Report</h2></td></tr>");
out.println(" <tr valign=top>");
out.println(" <td bgcolor=\"#F5F5DC\" align=center>");
out.println(" <table width=200>");
out.println("<tr bgcolor=\"#336633\"><td align=center><font color=white><b>By Member</b></font></td></tr>");
out.println("<tr><td align=center><a href=\"javascript:reqReport('mem-30', 0)\">Last 30 days</a></td></tr>");
out.println("<tr><td align=center><a href=\"javascript:reqReport('mem-tm', 0)\">This month</a></td></tr>");
out.println("<tr><td align=center><a href=\"javascript:reqReport('mem-lm', 0)\">Last month</a></td></tr>");
out.println("<tr><td align=center><a href=\"javascript:reqReport('mem-cd', 1)\">Custom date range</a></td></tr>");
out.println("<tr><td align=center><a href=\"javascript:reqReport('mem-ad', 0)\">All available data</a></td></tr>");
out.println("<tr><td><table cellpadding=0 cellspacing=0 align=center>");
out.println("<tr><td>Choose Member:<br>");
out.println("<select size=\"1\" name=\"username\">");
out.println("<option value=\"-ALL-\">All Members</option>");
try {
stmt = con.createStatement(); // create a statement
rs = stmt.executeQuery("SELECT username, name_last, name_first, name_mi FROM member2b " +
"ORDER BY name_last, name_first, name_mi");
while (rs.next()) {
user = rs.getString(1);
lname = rs.getString(2);
fname = rs.getString(3);
mname = rs.getString(4);
out.println("<option value=\"" + user + "\">" + lname + ", " + fname + " " + mname + "</option>");
}
stmt.close();
}
catch (Exception exc) {
SystemUtils.buildDatabaseErrMsg("Error getting member list.", exc.getMessage(), out, false);
return;
}
out.println("</select></td></tr></table></td></tr></table>");
if (user.equals("")) out.println("There are no members in the database at this time.<br><br>");
out.println(" </td>");
out.println(" <td bgcolor=\"#F5F5DC\" align=center>");
out.println(" <table width=200>");
out.println("<tr bgcolor=\"#336633\"><td align=center><font color=white><b>By Course</b></font></td></tr>");
out.println("<tr><td align=center><a href=\"javascript:reqReport('cor-30', 0)\">Last 30 days</a></td></tr>");
out.println("<tr><td align=center><a href=\"javascript:reqReport('cor-tm', 0)\">This month</a></td></tr>");
out.println("<tr><td align=center><a href=\"javascript:reqReport('cor-lm', 0)\">Last month</a></td></tr>");
out.println("<tr><td align=center><a href=\"javascript:reqReport('cor-cd', 1)\">Custom date range</a></td></tr>");
out.println("<tr><td align=center><a href=\"javascript:reqReport('cor-ad', 0)\">All available data</a></td></tr>");
// if multi - display select box with options
if (multi != 0) { // if multiple courses supported for this club
String courseName = "";
out.println("<tr><td><table cellpadding=0 cellspacing=0 align=center>");
out.println("<tr><td>Choose course:<br>");
out.println("<select name=course size=1>");
out.println("<option value=\"-ALL-\">-ALL-</option>");
try {
//
// Get the names of all courses for this club
//
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT clubparm_id, courseName FROM clubparm2 WHERE first_hr != 0");
while (rs.next()) {
courseName = rs.getString(1);
//out.println("<option value=\"" + rs.getInt(1) + "\">" + rs.getString(2) + "</option>");
out.println("<option>" + rs.getString(2) + "</option>");
}
stmt.close();
}
catch (Exception exc) {
SystemUtils.buildDatabaseErrMsg("Can not establish connection.", "", out, false);
return;
}
out.println("</select></td></tr></table>");
} // end if multiple courses for this club
out.println(" </td></tr></table>");
out.println(" </td>");
out.println(" <td bgcolor=\"#F5F5DC\" align=center>");
out.println(" <table width=200>");
out.println("<tr bgcolor=\"#336633\"><td align=center><font color=white><b>Feature Usage</b></font></td></tr>");
out.println("<tr><td align=center><a href=\"javascript:reqReport('use-30', 0)\">Last 30 days</a></td></tr>");
out.println("<tr><td align=center><a href=\"javascript:reqReport('use-tm', 0)\">This month</a></td></tr>");
out.println("<tr><td align=center><a href=\"javascript:reqReport('use-lm', 0)\">Last month</a></td></tr>");
out.println("<tr><td align=center><a href=\"javascript:reqReport('use-cd', 1)\">Custom date range</a></td></tr>");
out.println("<tr><td align=center><a href=\"javascript:reqReport('use-ad', 0)\">All available data</a></td></tr>");
out.println(" </table>");
out.println(" </td>");
out.println(" </tr>");
out.println(" <tr><td colspan=3 align=center><br>" +
"<!--<input type=\"button\" value=\"Home\" onclick=\"document.location.href='/" + rev + "/servlet/Proshop_announce'\" style=\"width:100px;text-decoration:underline;background:#8B8970\">" +
" -->" +
"<input type=\"button\" value=\"Help\" onclick=\"openHelpWindow()\" style=\"width:100px;text-decoration:underline;background:#8B8970\">" +
"</td></tr>");
out.println("</table>");
out.println("</form>");
out.println("</center>");
} // end of doGet routine
//*****************************************************
// Process initial report request to compute the
// dates needed for this report or direct to page
// that gets dates from user. Once dates are present
// in the request object call out appropriately
//*****************************************************
//
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
long edate = 0;
long sdate = 0;
int year = 0;
int month = 0;
int day = 0;
int start_year = 0;
int start_month = 0;
int start_day = 0;
int end_year = 0;
int end_month = 0;
int end_day = 0;
resp.setHeader("Pragma","no-cache"); // for HTTP 1.0
resp.setHeader("Cache-Control","no-store, no-cache, must-revalidate"); // for HTTP 1.1
resp.setDateHeader("Expires",0); // prevents caching at the proxy server
resp.setContentType("text/html");
PrintWriter out = resp.getWriter(); // normal output stream
HttpSession session = SystemUtils.verifyPro(req, out);
if (session == null) { return; }
Connection con = SystemUtils.getCon(session); // get DB connection
if (con == null) {
SystemUtils.buildDatabaseErrMsg("Can not establish connection.", "", out, true);
return;
}
String excel = (req.getParameter("excel") != null) ? req.getParameter("excel") : "";
String todo = (req.getParameter("todo") != null) ? req.getParameter("todo") : "";
String start_date = (req.getParameter("cal_box_0") != null) ? req.getParameter("cal_box_0") : "";
String end_date = (req.getParameter("cal_box_1") != null) ? req.getParameter("cal_box_1") : "";
String tmp_get_date = (req.getParameter("get_date") != null) ? req.getParameter("get_date") : "";
boolean get_date = (tmp_get_date.equals("1")) ? true : false;
String templott = (String)session.getAttribute("lottery"); // get lottery support indicator
int lottery = Integer.parseInt(templott);
// handle excel output
try{
if (excel.equals("yes")) { // if user requested Excel Spreadsheet Format
resp.setContentType("application/vnd.ms-excel"); // response in Excel Format
}
}
catch (Exception exc) {
}
out.println(SystemUtils.HeadTitle2("Pace of Play Reports"));
out.println("</head>");
out.println("<body bgcolor=\"#FFFFFF\" text=\"#000000\" link=\"#FFFFFF\" vlink=\"#FFFFFF\" alink=\"#FF0000\">");
SystemUtils.getProshopSubMenu(req, out, lottery); // required to allow submenus on this page
//
// If we need to get a custom date range lets display the calendars
// If not, then let check to see if we're display a report that needs them
// And if so, then make sure they are here and valid.
//
if (get_date) {
// get custom date range
getCustomDate(req, out, con);
return;
} else {
// check to see if the report we are building is a custom date range report
if (todo.endsWith("-cd")) {
// check to see if the date is here, and if not then jump to display calendar routine
if (start_date.equals("")) {
getCustomDate(req, out, con);
return;
}
// if no ending date then default to starting date for 1 day report
if (end_date.equals("")) end_date = start_date;
// if the date passed are in our long format already (from being passed around)
// then we can skip this first round of validation
try {
sdate = Integer.parseInt(start_date);
edate = Integer.parseInt(end_date);
} catch (Exception e) {
// make sure the dates here are valid, if not redisplay the calendars
try {
int dash1 = start_date.indexOf("-");
int dash2 = start_date.indexOf("-", dash1 + 1);
start_year = Integer.parseInt(start_date.substring(0, 4));
start_month = Integer.parseInt(start_date.substring(dash1 + 1, dash2));
start_day = Integer.parseInt(start_date.substring(dash2 + 1));
dash1 = end_date.indexOf("-");
dash2 = end_date.indexOf("-", dash1 + 1);
end_year = Integer.parseInt(end_date.substring(0, 4));
end_month = Integer.parseInt(end_date.substring(dash1 + 1, dash2));
end_day = Integer.parseInt(end_date.substring(dash2 + 1));
} catch (Exception e2) {
// invalid dates here, bailout and call form again
getCustomDate(req, out, con);
return;
}
// build our date variables for use in query
sdate = start_year * 10000; // create a date field of yyyymmdd
sdate = sdate + (start_month * 100);
sdate = sdate + start_day;
edate = end_year * 10000; // create a date field of yyyymmdd
edate = edate + end_month * 100;
edate = edate + end_day;
}
if (sdate > edate) {
// start date is after the end date, jump out and call form again
getCustomDate(req, out, con);
return;
}
// end of custom date range
} else {
// get a calendar object to compute either this month or last months dates
Calendar cal = new GregorianCalendar(); // get todays date
year = cal.get(Calendar.YEAR);
month = cal.get(Calendar.MONTH) + 1; // month starts at zero
day = cal.get(Calendar.DAY_OF_MONTH);
if (todo.endsWith("-30")) {
// setup dates for last 30 days
edate = year * 10000; // create a date field of yyyymmdd
edate += month * 100;
edate += day;
cal.add(Calendar.DATE,-30); // roll back 30 days
year = cal.get(Calendar.YEAR);
month = cal.get(Calendar.MONTH) + 1; // month starts at zero
day = cal.get(Calendar.DAY_OF_MONTH);
sdate = year * 10000; // create a date field of yyyymmdd
sdate += month * 100;
sdate += day;
} else {
// check to see if this is a last month report
if (todo.endsWith("-lm")) {
month--;
if (month == 0) {
month = 12;
year--;
}
sdate = (year * 10000) + (month * 100); // create a edate field of yyyymmdd for last month
edate = sdate;
sdate += 1;
edate += 31; // this is ok for query but not suitable for display purposes!
// end of last month
} else {
// check to see if this is a this month report
if (todo.endsWith("-tm")) {
sdate = (year * 10000) + (month * 100); // create a edate field of yyyymmdd
edate = sdate;
sdate += 1;
edate += day; // today (was 31)
} else {
// check to see if we're call todays report
if (todo.equals("today")) {
sdate = (year * 10000) + (month * 100) + day; // use todays date
}
} // end this month
} // end if else last month
} // end if mem last 30
} // end if not custom date range
} // end if we need to get custom dates
if (g_debug) out.println("<!-- sdate=" + sdate + " | edate=" + edate + " -->");
//
// DATES ARE SET - IF ALL DATA REPORT THEN NO DATES NEEDED
//
if (todo.startsWith("use-")) doUsageReport(req, sdate, edate, excel, out, con);
if (todo.startsWith("mem-")) doMemberReport(req, sdate, edate, excel, out, con);
if (todo.startsWith("cor-")) doCourseReport(req, sdate, edate, excel, out, con);
if (todo.equals("today")) {
doTodayReport(req, sdate, excel, out, con);
out.println("<p> </p>");
out.println("</body>");
out.println("</html>");
return;
}
out.println(" <br><p align=center><a href=\"/"+rev+"/servlet/Proshop_report_pace\" style=\"color:#336633\">Return to Pace of Play Report Menu</a></p>");
out.println("<p> </p>");
out.println("</body>");
out.println("</html>");
return;
}
private void doTodayReport(HttpServletRequest req, long pTodaysDate, String pExcel, PrintWriter out, Connection con) {
PreparedStatement pstmt = null;
Statement stmt = null;
ResultSet rs = null;
String pretty_date = "";
String courseName = (req.getParameter("course") != null) ? req.getParameter("course") : "";
// get pretty dates for the report
try {
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT DATE_FORMAT('" + pTodaysDate + "', '%W %M %D, %Y') AS pretty_date");
if (rs.next()) {
pretty_date = rs.getString("pretty_date");
}
rs.close();
stmt.close();
} catch (Exception e) {
SystemUtils.buildDatabaseErrMsg("Error getting formatted dates.", e.getMessage(), out, false);
return;
}
try {
pstmt = con.prepareStatement("" +
"SELECT *, ( " +
"SELECT AVG(t_18-t_start) AS 18_hole_pace " +
"FROM ( " +
"SELECT tp.courseName, pe.teecurr_id, " +
"MAX(IF(hole_number=0,hour(pe.hole_timestamp)*60+minute(pe.hole_timestamp),null)) AS t_start, " +
"MAX(IF(invert=9,hour(pe.hole_timestamp)*60+minute(pe.hole_timestamp),null)) AS t_9, " +
"MAX(IF(invert=18,hour(pe.hole_timestamp)*60+minute(pe.hole_timestamp),null)) AS t_18 " +
"FROM pace_entries pe, teecurr2 tp " +
"WHERE pe.teecurr_id = tp.teecurr_id " +
"AND (pe.hole_number = 0 OR pe.invert = 9 OR pe.invert = 18) " +
"GROUP BY pe.teecurr_id " +
") AS times " +
"WHERE t_start IS NOT NULL AND t_18 IS NOT NULL " +
"AND times.courseName = x.courseName " +
"AND x.pace_status_id IS NULL " +
"GROUP BY times.courseName " +
") AS Average " +
"FROM ( " +
"SELECT courseName, pace_status_id, pace_status_name, SUM(totals) AS overall " +
"FROM ( " +
"SELECT t.courseName, t.pace_status_id, COUNT(*) AS totals, p.pace_status_name " +
"FROM teecurr2 t, pace_status p " +
"WHERE t.pace_status_id > 0 " +
"AND t.date = ? " +
"AND t.pace_status_id = p.pace_status_id " +
((courseName.equals("-ALL-")) ? "" : "AND t.courseName = ? ") +
"GROUP BY t.courseName, t.pace_status_id " +
") AS z " +
"GROUP BY courseName, pace_status_id WITH ROLLUP) AS x " +
"ORDER BY courseName, pace_status_id;");
pstmt.clearParameters();
pstmt.setLong(1, pTodaysDate);
if (!courseName.equals("-ALL-")) {
pstmt.setString(2, courseName);
}
rs = pstmt.executeQuery();
String tmp_last = "";
String course = "";
String pace_status_name = "";
int pace_status_id = 0;
int overall = 0;
int tmp_gtotal = 0;
int tmp_total = 0;
int avg = 0;
double tmp_pcent = 0;
boolean tmp_header = false;
while (rs.next()) {
if (!tmp_header) {
out.print("<center><font size=+2>Pace of Play by Course Report ");
if (!courseName.equals("")) out.print("<br>for " + ((courseName.equals("-ALL-")) ? "each course" : courseName));
out.print("</font><br><font size=+1>for " + pretty_date + "</font>");
if (!pExcel.equals("yes")) { // if normal request
String todo = (req.getParameter("todo") != null) ? req.getParameter("todo") : "";
out.println("<center><form method=post action=\"/"+rev+"/servlet/Proshop_report_pace\" name=frmRequestExcel id=frmRequestExcel target=\"_blank\">");
out.println("<input type=hidden name=todo value=\"" + todo + "\">");
out.println("<input type=hidden name=cal_box_0 value=\"" + pTodaysDate + "\">");
out.println("<input type=hidden name=course value=\"" + courseName + "\">");
out.println("<input type=hidden name=excel value=\"yes\">");
out.println("<input type=submit value=\"Create Excel Spreadsheet\" style=\"text-decoration:underline; background:#8B8970\">");
out.println("</form>");
}
//out.println("</center> <br><br><table bgcolor=\"#F5F5DC\" align=center border=0 cellpadding=7 "+((multi==0) ? "" : "style=\"border: 2px solid #336633\"") + ">");
out.println("</center> <br><table bgcolor=\"#F5F5DC\" align=center border=0 cellpadding=6>");
tmp_header = true;
}
course = rs.getString("courseName");
pace_status_name = rs.getString("pace_status_name");
pace_status_id = rs.getInt("pace_status_id");
overall = rs.getInt("overall");
avg = rs.getInt("Average");
out.println("<tr>");
if (course == null && pace_status_id == 0) {
//out.println("<td colspan=2 align=center> <br><b><i>Total rounds with pace of play data: " + overall + "</i></b></td>"); // total rounds with pace data
//out.println("<td><b>" + nf.format(overall) + "</b></td><td><b>Rounds with pace of play data</b></td>"); // total rounds with pace data
out.println("<!--<td></td>-->" +
"<td width=300><b>Rounds with pace of play recorded:</b></td>" +
"<td colspan=2><b>" + nf.format(overall) + "</b></td>"); // total rounds with pace data
tmp_gtotal = overall;
} else {
if (pace_status_id == 0) tmp_total = overall;
// if we're switching courses OR going from the overall rollup
if (!tmp_last.equals(course)) {
out.println("<td> <b><u>" + course + "</u></b></td>" +
"<td><b>" + (buildDisplayValue(tmp_total, tmp_gtotal, pExcel)) + "</td></tr><tr>");
out.println("<td align=right>Average pace for 18 holes:</td>" +
"<td colspan=2>" + minToTime(avg) + "</td></tr><tr>");
} else {
// if avg is here then this is a sub rollup for each course
if (avg != 0) {
out.println("<td align=right>Average pace for 18 holes:</td>" +
"<td colspan=2>" + minToTime(avg) + "</td></tr><tr>");
}
}
if (pace_status_id != 0) {
out.println("<td align=right>Rounds " + pace_status_name + ":</td><td>");
out.print(buildDisplayValue(overall, tmp_total, pExcel));
out.print("</td>");
}
tmp_last = course;
} // end if grand rollup
out.println("</tr>");
} // end while loop
// if nothing was returned from the query then notify (this should never happen since the link won't appear if there is no data avail)
if (!tmp_header) {
out.println("<tr><td colspan=3><p>No tee times containing pace data were found for today.</p></td></tr>");
}
out.println("</table>");
out.println("<br><br><center>" +
"<input type=button value=\"Close\" style=\"width: 100px;text-decoration:underline; background:#8B8970\" onclick=\"window.close()\">" +
"</center>");
} catch (Exception exc) {
SystemUtils.buildDatabaseErrMsg(exc.toString(), "", out, false);
return;
}
}
private void doUsageReport(HttpServletRequest req, long pStartDate, long pEndDate, String pExcel, PrintWriter out, Connection con) {
PreparedStatement pstmt = null;
Statement stmt = null;
ResultSet rs = null;
String range_begin = "";
String range_end = "";
String course = "";
String header = "";
int oldest_pdate = 0;
int year = 0;
int month = 0;
int day = 0;
int edate = 0;
int multi = 0;
parmClub parm = new parmClub();
try {
getClub.getParms(con, parm);
multi = parm.multi;
} catch (Exception ignore) { }
// if it's an all available data request then subsitute the
// dates with the oldest tee time with pace data and todays date
if (pStartDate == 0 && pEndDate == 0) {
// lookup oldest date in teepast2 that has a pace status
boolean found = false;
try {
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT date FROM teepast2 WHERE pace_status_id <> 0 ORDER BY date ASC LIMIT 1");
while (rs.next()) {
pStartDate = rs.getInt(1);
}
} catch (Exception e) {
SystemUtils.buildDatabaseErrMsg("Error looking up oldest tee time with pace data.", e.getMessage(), out, false);
return;
}
// adjust pEndDate to today
Calendar cal_date = new GregorianCalendar();
year = cal_date.get(Calendar.YEAR);
month = cal_date.get(Calendar.MONTH) + 1; // month is zero based
day = cal_date.get(Calendar.DAY_OF_MONTH);
pEndDate = (year * 10000) + (month * 100) + day;
if (!found) pStartDate = (year * 10000) + (1 * 100) + 1;
} // end changeing pStartDate, pEndDate
if (g_debug) out.println("<!-- pStartDate=" + pStartDate + " | pEndDate=" + pEndDate + " -->");
// get pretty dates for the report
try {
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT DATE_FORMAT('" + pStartDate + "', '%W %M %D, %Y') AS range_begin, DATE_FORMAT('" + pEndDate + "', '%W %M %D, %Y') AS range_end");
if (rs.next()) {
range_begin = rs.getString("range_begin");
range_end = rs.getString("range_end");
}
rs.close();
stmt.close();
} catch (Exception e) {
SystemUtils.buildDatabaseErrMsg("Error getting formatted dates.", e.getMessage(), out, false);
return;
}
// setup our report header
header = "<center><font size=+2>Pace of play usage report " + ((multi == 1) ? "by course " : "") + "from<br></font>" +
"<font size=+1><nobr>" + range_begin + "</nobr> thru <nobr>" + range_end + "</nobr></font></center>";
// build and display the report data
try {
boolean tmp_header = false;
int wpace = 0; // total rounds w/ pace
int wopace = 0; // total rounds w/o pace
int rounds = 0; // total rounds
int pw = 0; // percent w/ pace
int pwo = 0; // percent w/o pace
String overall_tag = "";
pstmt = con.prepareStatement("" +
"SELECT *, ROUND(wpace / total * 100) AS pw, ROUND(wopace / total * 100) AS pwo FROM (" +
"SELECT " +
"courseName, " +
"COUNT(*) AS total, " +
"SUM((pace_status_id = 0)) AS wopace, " +
"SUM((pace_status_id > 0)) AS wpace " +
"FROM teepast2 " +
"WHERE date >= ? AND date <= ? " +
"GROUP BY courseName " +
((multi != 0) ? "WITH ROLLUP" : "") +
") AS z");
pstmt.clearParameters();
pstmt.setLong(1, pStartDate);
pstmt.setLong(2, pEndDate);
rs = pstmt.executeQuery();
while (rs.next()) {
if (!tmp_header) {
out.println(header);
if (!pExcel.equals("yes")) { // if normal request
String todo = (req.getParameter("todo") != null) ? req.getParameter("todo") : "";
out.println("<center><form method=post action=\"/"+rev+"/servlet/Proshop_report_pace\" name=frmRequestExcel id=frmRequestExcel target=\"_blank\">");
out.println("<input type=hidden name=todo value=\"" + todo + "\">");
out.println("<input type=hidden name=cal_box_0 value=\"" + pStartDate + "\">");
out.println("<input type=hidden name=cal_box_1 value=\"" + pEndDate + "\">");
out.println("<input type=hidden name=excel value=\"yes\">");
out.println("<input type=submit value=\"Create Excel Spreadsheet\" style=\"text-decoration:underline; background:#8B8970\">");
out.println("</form>");
}
out.println(" <br><br><table bgcolor=\"#F5F5DC\" align=center border=1 cellpadding=6>");
out.println("<tr bgcolor=\"#336633\">" +
((multi==1) ? "<td><font color=white><b>Course</b></font></td>" : "") +
"<td><font color=white><b>Rounds</b></font></td>" +
"<td><font color=white><b>With Pace</b></font></td>" +
"<td><font color=white><b>Without Pace</b></font></td>" +
"</tr>");
tmp_header = true;
}
course = rs.getString("courseName");
rounds = rs.getInt("total");
wpace = rs.getInt("wpace");
wopace = rs.getInt("wopace");
pw = rs.getInt("pw");
pwo = rs.getInt("pwo");
overall_tag = "";
if (multi == 1 && course == null) {
course = "Overall Totals";
out.println("<tr bgcolor=\"#336633\"><td colspan=4></td></tr>");
overall_tag = "<b>";
} else {
out.println("<tr>");
}
if (multi==1) out.println("<td>" + overall_tag + course + "</td>");
out.println("<td>" + overall_tag + nf.format(rounds) + "</td>");
out.println("<td>" + overall_tag + nf.format(wpace) + ((wpace == 0 || pExcel.equals("yes")) ? "" : " (" + pw + "%) ") + "</td>");
out.println("<td>" + overall_tag + nf.format(wopace) + ((wopace == 0 || pExcel.equals("yes")) ? "" : " (" + pwo + "%) ") + "</td>");
out.println("</tr>");
} // end while loop
// if nothing was returned from the query then notify
if (!tmp_header) {
out.println(header);
out.println("<p align=center><i>No tee times were found during the requested time<br>frame that contain pace of play data.</i></p>");
//out.println("The time frame searched was from " + range_begin + " to " + range_end + ".</p>");
} else {
out.println("</table>");
}
} catch (Exception exc) {
SystemUtils.buildDatabaseErrMsg(exc.toString(), "", out, false);
return;
}
}
private void doMemberReport(HttpServletRequest req, long pStartDate, long pEndDate, String pExcel, PrintWriter out, Connection con) {
String username = (req.getParameter("username") != null) ? req.getParameter("username") : "";
String todo = (req.getParameter("todo") != null) ? req.getParameter("todo") : "";
// jump out to other report
if (username.equals("-ALL-")) {
doMemberAvgReport(req, pStartDate, pEndDate, pExcel, out, con);
return;
}
PreparedStatement pstmt = null;
Statement stmt = null;
ResultSet rs = null;
String range_begin = "";
String range_end = "";
String courseName = "";
String header = "";
String name = "";
boolean found = false;
String tmp = (req.getParameter("details") != null) ? req.getParameter("details") : "";
boolean details = (tmp.equals("y")) ? true : false;
int year = 0;
int month = 0;
int day = 0;
int edate = 0;
int multi = 0;
long first_date = 0;
parmClub parm = new parmClub();
try {
getClub.getParms(con, parm);
multi = parm.multi;
} catch (Exception ignore) { }
//
// Before processing the report lets make sure this members has at least one
// round in teh database with pace of play recorded for it
//
// lookup oldest date in teepast2 that has a pace status for this member
try {
pstmt = con.prepareStatement("" +
"SELECT date " +
"FROM teepast2 " +
"WHERE pace_status_id <> 0 " +
"AND " +
"(" +
"username1 = ? OR " +
"username2 = ? OR " +
"username3 = ? OR " +
"username4 = ? OR " +
"username5 = ?" +
") " +
"ORDER BY date ASC LIMIT 1");
pstmt.clearParameters();
pstmt.setString(1, username);
pstmt.setString(2, username);
pstmt.setString(3, username);
pstmt.setString(4, username);
pstmt.setString(5, username);
rs = pstmt.executeQuery();
while (rs.next()) {
// if all data report then subsitute the start date of the report with this date
first_date = rs.getInt(1);
found = true;
}
} catch (Exception e) {
SystemUtils.buildDatabaseErrMsg("Error looking up oldest tee time with pace data.", e.getMessage(), out, false);
return;
}
// bail out if no rounds with pace data were found for this member
if (!found) {
// this member has no rounds with pace of play data collected
out.println("<p align=center><i>No tee times were found for this member during the requested time<br>frame that contain pace of play data.</i></p>");
return;
} // end if no records where found
// just because they have pace data doesn't mean they have pace data
// within the search range of this report
found = false; // reset to resue
// if it's all available data request then subsitute the end date with todays date
if (pStartDate == 0 && pEndDate == 0) {
// adjust pEndDate to today
Calendar cal_date = new GregorianCalendar();
year = cal_date.get(Calendar.YEAR);
month = cal_date.get(Calendar.MONTH) + 1; // month is zero based
day = cal_date.get(Calendar.DAY_OF_MONTH);
pEndDate = (year * 10000) + (month * 100) + day;
pStartDate = first_date;
} // end changeing pStartDate, pEndDate
// debug output
if (g_debug) out.println("<!-- username=" + username + " | pStartDate=" + pStartDate + " | pEndDate=" + pEndDate + " | details=" + ((details) ? "true" : "false") + " -->");
// get member's display name from their username
try {
pstmt = con.prepareStatement("SELECT name_last, name_mi, name_first FROM member2b WHERE username = ?");
pstmt.clearParameters();
pstmt.setString(1, username);
rs = pstmt.executeQuery();
if (rs.next()) {
name = rs.getString("name_first") + " " + rs.getString("name_last");
}
rs.close();
pstmt.close();
} catch (Exception e) {
SystemUtils.buildDatabaseErrMsg("Error getting members display name.", e.getMessage(), out, false);
return;
}
// get pretty dates for the report
try {
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT DATE_FORMAT('" + pStartDate + "', '%W %M %D, %Y') AS range_begin, DATE_FORMAT('" + pEndDate + "', '%W %M %D, %Y') AS range_end");
if (rs.next()) {
range_begin = rs.getString("range_begin");
range_end = rs.getString("range_end");
}
rs.close();
stmt.close();
} catch (Exception e) {
SystemUtils.buildDatabaseErrMsg("Error getting formatted dates.", e.getMessage(), out, false);
return;
}
// call out to details report
if (details) {
doMemberDetailsReport(req, pStartDate, pEndDate, pExcel, multi, username, todo, out, con);
return;
}
// setup our report header
header = "<center><font size=+2>Member pace of play report " + ((multi == 1) ? "by course " : "") + "from<br></font>" +
"<font size=+1><nobr>" + range_begin + "</nobr> thru <nobr>" + range_end + "</nobr><br>for<br>" + name +
"</font></center>";
out.println(header);
out.println(" <br><table bgcolor=\"#F5F5DC\" align=center border=1 cellpadding=7 "+((multi==0) ? "" : "style=\"border: 2px solid #336633\"") + ">");
// build and display the report data
try {
boolean tmp_first = true;
int pace_status_id = 0; // pace id
int rounds = 0; // total rounds
String pace_status_name = "";
String tmp_last = "";
pstmt = con.prepareStatement("" +
"SELECT t.courseName, COUNT(*) AS rounds, t.pace_status_id, p.pace_status_name " +
"FROM teepast2 t, pace_status p " +
"WHERE date >= ? AND date <= ? " +
"AND t.pace_status_id = p.pace_status_id " +
"AND (" +
"t.username1 = ? OR " +
"t.username2 = ? OR " +
"t.username3 = ? OR " +
"t.username4 = ? OR " +
"t.username5 = ?" +
") " +
"GROUP BY " + ((multi != 0) ? "t.courseName, " : "") +
"t.pace_status_id WITH ROLLUP");
pstmt.clearParameters();
pstmt.setLong(1, pStartDate);
pstmt.setLong(2, pEndDate);
pstmt.setString(3, username);
pstmt.setString(4, username);
pstmt.setString(5, username);
pstmt.setString(6, username);
pstmt.setString(7, username);
rs = pstmt.executeQuery();
while (rs.next()) {
found = true;
courseName = rs.getString("courseName");
rounds = rs.getInt("rounds");
pace_status_id = rs.getInt("pace_status_id");
pace_status_name = rs.getString("pace_status_name");
if (multi == 1 && !tmp_last.equals(courseName) && courseName != null) {
// don't draw a line above the first course
if (!tmp_first) {
out.println("<tr bgcolor=\"#336633\"><td colspan=4></td></tr>");
tmp_first = false;
}
out.println("<td colspan=2 align=center><b><u>" + courseName + "</u></b></td></tr><tr>");
tmp_last = courseName;
out.println("<tr>");
out.println("<td>" + nf.format(rounds) + " rounds</td>");
out.println("<td>" + pace_status_name + "</td>");
out.println("</tr>");
} else {
if (multi == 1 && courseName == null) {
out.println("<tr>");
out.println("<td colspan=2 align=center><b>Total Rounds with Pace Data: " + nf.format(rounds) + "</td>");
out.println("</tr>");
} else {
if (pace_status_id == 0) {
// total for course
out.println("<tr>");
out.println("<td colspan=2 align=center><i>" + nf.format(rounds) + " tracked rounds</i></td>");
out.println("</tr>");
if (multi != 0) out.println("<tr bgcolor=\"#336633\"><td colspan=4></td></tr>");
} else {
out.println("<tr>");
out.println("<td>" + nf.format(rounds) + " rounds</td>");
out.println("<td>" + pace_status_name + "</td>");
out.println("</tr>");
}
}
}
tmp_last = courseName;
} // end while loop
// if nothing was returned from the query then notify
if (!found) {
out.println("<p align=center><i>No tee times were found during the requested time<br>frame that contain pace of play data.</i></p>");
} else {
out.println("</table>");
out.println(" <br>");
// display a link to the detail report
out.println("<table align=center border=0><tr><td>");
out.println("<form method=post action=\"/"+rev+"/servlet/Proshop_report_pace\" name=frmWhichReport id=frmWhichReport>");
out.println("<input type=hidden name=todo value=\"" + todo + "\">");
out.println("<input type=hidden name=cal_box_0 value=\"" + pStartDate + "\">");
out.println("<input type=hidden name=cal_box_1 value=\"" + pEndDate + "\">");
out.println("<input type=hidden name=username value=\"" + username + "\">");
out.println("<input type=hidden name=details value=\"y\">");
out.println("<input type=submit name=btnSubmit value=\" Detailed Report \" style=\"background:#8B8970\">");
out.println("</form>");
out.println("</td></tr></table>");
}
} catch (Exception exc) {
SystemUtils.buildDatabaseErrMsg(exc.toString(), "", out, false);
return;
}
}
private void doMemberAvgReport(HttpServletRequest req, long pStartDate, long pEndDate, String pExcel, PrintWriter out, Connection con) {
String username = (req.getParameter("username") != null) ? req.getParameter("username") : "";
String todo = (req.getParameter("todo") != null) ? req.getParameter("todo") : "";
PreparedStatement pstmt = null;
Statement stmt = null;
ResultSet rs = null;
String range_begin = "";
String range_end = "";
String header = "";
int multi = 0;
int year = 0;
int month = 0;
int day = 0;
parmClub parm = new parmClub();
try {
getClub.getParms(con, parm);
multi = parm.multi;
} catch (Exception ignore) { }
// if it's an all available data request then subsitute the
// dates with the oldest tee time with pace data and todays date
if (pStartDate == 0 && pEndDate == 0) {
// lookup oldest date in teepast2 that has a pace status
boolean found = false;
try {
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT date FROM teepast2 WHERE pace_status_id <> 0 ORDER BY date ASC LIMIT 1");
while (rs.next()) {
pStartDate = rs.getInt(1);
found = true;
}
} catch (Exception e) {
SystemUtils.buildDatabaseErrMsg("Error looking up oldest tee time with pace data.", e.getMessage(), out, false);
return;
}
// adjust pEndDate to today
Calendar cal_date = new GregorianCalendar();
year = cal_date.get(Calendar.YEAR);
month = cal_date.get(Calendar.MONTH) + 1; // month is zero based
day = cal_date.get(Calendar.DAY_OF_MONTH);
pEndDate = (year * 10000) + (month * 100) + day;
if (!found) pStartDate = (year * 10000) + (1 * 100) + 1;
} // end changeing pStartDate, pEndDate
// get pretty dates for the report
try {
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT DATE_FORMAT('" + pStartDate + "', '%W %M %D, %Y') AS range_begin, DATE_FORMAT('" + pEndDate + "', '%W %M %D, %Y') AS range_end");
if (rs.next()) {
range_begin = rs.getString("range_begin");
range_end = rs.getString("range_end");
}
rs.close();
stmt.close();
} catch (Exception e) {
SystemUtils.buildDatabaseErrMsg("Error getting formatted dates.", e.getMessage(), out, false);
return;
}
// setup our report header
header = "<center><font size=+2>Member pace of play report " + ((multi == 1) ? "by course " : "") + "from<br></font>" +
"<font size=+1><nobr>" + range_begin + "</nobr> thru <nobr>" + range_end + "</nobr></font></center>";
out.println(header);
// include Excel export button
if (!pExcel.equals("yes")) {
out.println("<center><form method=post action=\"/"+rev+"/servlet/Proshop_report_pace\" name=frmRequestExcel id=frmRequestExcel target=\"_blank\">");
out.println("<input type=hidden name=todo value=\"" + todo + "\">");
out.println("<input type=hidden name=cal_box_0 value=\"" + pStartDate + "\">");
out.println("<input type=hidden name=cal_box_1 value=\"" + pEndDate + "\">");
out.println("<input type=hidden name=username value=\"-ALL-\">");
out.println("<input type=hidden name=excel value=\"yes\">");
out.println("<input type=submit value=\"Create Excel Spreadsheet\" style=\"text-decoration:underline; background:#8B8970\">");
out.println("</form>");
}
// show notes section
if (!pExcel.equals("yes")) {
out.println("<table align=center cellpadding=0 cellspacing=0>");
out.println("<tr valign=top>" +
"<td><font size=2><b>Note:</b> </font></td>" +
"<td><font size=2>Pace times shown are averages during the time period selected. The sample<br>column contains the number of rounds their pace times are based upon.</font></td></tr>" +
"</tr>");
out.println("</table>");
}
// start main table to hold query results
out.println(" <br><table bgcolor=\"#F5F5DC\" align=center border=1 cellpadding=7>");
// build and display the report data
try {
boolean tmp_first = true;
int pace_status_id = 0; // pace id
int rounds = 0; // total rounds
String pace_status_name = "";
String tmp_last = "";
pstmt = con.prepareStatement("" +
"SELECT name_last, name_first, username, courseName, " +
"AVG(t_9-t_start) AS front_9_pace, " +
"AVG(t_18 - t_9) AS back_9_pace, " +
"AVG(t_18 - t_start) AS 18_pace, " +
"COUNT(*) AS sample_size " +
"FROM (" +
"SELECT name_last, name_first, username, courseName, t_start, t_9, t_18 " +
"FROM member2b m2b, (" +
"SELECT username1, username2, username3, username4, username5, courseName, pe.teecurr_id, " +
"MAX(IF(hole_number=0,HOUR(pe.hole_timestamp)*60+MINUTE(pe.hole_timestamp),null)) AS t_start, " +
"MAX(IF(invert=9,HOUR(pe.hole_timestamp)*60+MINUTE(pe.hole_timestamp),null)) AS t_9, " +
"MAX(IF(invert=18,HOUR(pe.hole_timestamp)*60+MINUTE(pe.hole_timestamp),null)) AS t_18 " +
"FROM pace_entries pe, teepast2 tp " +
"WHERE pe.teecurr_id = tp.teecurr_id " +
"AND (pe.hole_number = 0 OR pe.invert = 9 OR pe.invert = 18) " +
((pStartDate == 0 && pEndDate == 0) ? "" : "AND tp.date >= ? AND tp.date <= ? ") +
"GROUP BY pe.teecurr_id " +
") AS times " +
"WHERE (times.username1 = m2b.username " +
"OR times.username2 = m2b.username " +
"OR times.username3 = m2b.username " +
"OR times.username4 = m2b.username " +
"OR times.username5 = m2b.username) " +
") AS user_times " +
"WHERE t_9 IS NOT NULL AND t_18 IS NOT NULL " +
"GROUP BY username, courseName " +
"ORDER BY name_last, name_first");
pstmt.clearParameters();
if (!(pStartDate == 0 && pEndDate == 0)) {
pstmt.setLong(1, pStartDate);
pstmt.setLong(2, pEndDate);
}
rs = pstmt.executeQuery();
String name = "";
String user = "";
String courseName = "";
int front9 = 0;
int back9 = 0;
int pace18 = 0;
int sample = 0;
//out.println("<table align=center bgcolor=\"\">");
out.println("<tr bgcolor=\"#336633\" style=\"font-weight:bold; color: white\">" +
"<td>Member Name</td>" +
((multi == 0) ? "" : "<td>Course</td>") +
"<td>18 Hole Pace</td>" +
"<td>Front 9 Pace</td>" +
"<td>Back 9 Pace</td>" +
"<td>Sample Size</td>" +
"</tr>");
while (rs.next()) {
name = rs.getString("name_last") + ", " + rs.getString("name_first");
user = rs.getString("username");
courseName = rs.getString("courseName");
front9 = rs.getInt("front_9_pace");
back9 = rs.getInt("back_9_pace");
pace18 = rs.getInt("18_pace");
sample = rs.getInt("sample_size");
out.println("<tr>");
out.println("<td>" + name + "</td>");
if (multi != 0) out.println("<td>" + courseName + "</td>");
out.println("<td>" + minToTime(pace18) + "</td>");
out.println("<td>" + minToTime(front9) + "</td>");
out.println("<td>" + minToTime(back9) + "</td>");
out.println("<td>" + sample + " Round" + ((sample > 1) ? "s" : "") + "</td>");
out.println("</tr>");
}
out.println("</table>");
} catch (Exception exc) {
SystemUtils.buildDatabaseErrMsg(exc.toString(), "", out, false);
return;
}
}
private void doMemberDetailsReport(HttpServletRequest req, long pStartDate, long pEndDate, String pExcel, int pMulti, String pUsername, String pTodo, PrintWriter out, Connection con) {
PreparedStatement pstmt = null;
Statement stmt = null;
ResultSet rs = null;
String range_begin = "";
String range_end = "";
String name = "";
String sort = (req.getParameter("sort") != null) ? req.getParameter("sort") : "";
out.println("<!-- *** DETAIL DATA *** sort=" + sort + " -->");
// member's display name from their username
try {
pstmt = con.prepareStatement("SELECT name_last, name_mi, name_first FROM member2b WHERE username = ?");
pstmt.clearParameters();
pstmt.setString(1, pUsername);
rs = pstmt.executeQuery();
if (rs.next()) {
name = rs.getString("name_first") + " " + rs.getString("name_last");
}
rs.close();
pstmt.close();
} catch (Exception e) {
SystemUtils.buildDatabaseErrMsg("Error getting members display name.", e.getMessage(), out, false);
return;
}
// get pretty dates for the report
try {
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT DATE_FORMAT('" + pStartDate + "', '%W %M %D, %Y') AS range_begin, DATE_FORMAT('" + pEndDate + "', '%W %M %D, %Y') AS range_end");
if (rs.next()) {
range_begin = rs.getString("range_begin");
range_end = rs.getString("range_end");
}
rs.close();
stmt.close();
} catch (Exception e) {
SystemUtils.buildDatabaseErrMsg("Error getting formatted dates.", e.getMessage(), out, false);
return;
}
out.println("<center><font size=+2>Member pace of play detail report " + ((pMulti == 1) ? "by course " : "") + "from<br></font>" +
"<font size=+1><nobr>" + range_begin + "</nobr> thru <nobr>" + range_end + "</nobr><br>for<br>" + name +
"</font></center>");
out.println(" <br><table border=\"1\" bgcolor=\"#F5F5DC\" align=center border=0 cellpadding=6 "+((pMulti==0) ? "" : "style=\"border: 2px solid #336633\"") + ">");
out.println(
"<tr bgcolor=\"#336633\">" +
"<td><font color=white><b><a href=\"javascript:fetchSorted('date')\">Date</a></b></font></td>" +
"<td><font color=white><b>Time</b></font></td>" +
((pMulti == 1) ? "<td><font color=white><b>Course</b></font></td>" : "") +
"<td><font color=white><b>Pace Time</font></td>" +
"<td><font color=white><b><a href=\"javascript:fetchSorted('pace')\">Pace</a></b></font></td>" +
"</tr>");
// build and display the report data
try {
boolean tmp_first = true;
int fb = 0;
int hr = 0;
int min = 0;
int pace_status_id = 0; // pace id
int rounds = 0; // total rounds
int teecurr_id = 0;
String pace_status_name = "";
String tmp_last = "";
String courseName = "";
String pretty_date = "";
String ampm = " AM";
String time = "";
String pace_time = "";
String player1 = "";
String player2 = "";
String player3 = "";
String player4 = "";
String player5 = "";
String p1cw = "";
String p2cw = "";
String p3cw = "";
String p4cw = "";
String p5cw = "";
String sql = "" +
"SELECT DATE_FORMAT(date, '%a. %b %D, %Y') AS pretty_date, t.*, p.pace_status_name " +
"FROM teepast2 t, pace_status p " +
"WHERE t.date >= ? AND t.date <= ? " +
"AND t.pace_status_id = p.pace_status_id " +
"AND (" +
"t.username1 = ? OR " +
"t.username2 = ? OR " +
"t.username3 = ? OR " +
"t.username4 = ? OR " +
"t.username5 = ?" +
") " +
"ORDER BY " +
((sort.equals("pace")) ? "t.pace_status_id, " : "") +
"t.date DESC, t.time";
out.println("<!-- " + sql + " -->");
pstmt = con.prepareStatement(sql);
pstmt.clearParameters();
pstmt.setLong(1, pStartDate);
pstmt.setLong(2, pEndDate);
pstmt.setString(3, pUsername);
pstmt.setString(4, pUsername);
pstmt.setString(5, pUsername);
pstmt.setString(6, pUsername);
pstmt.setString(7, pUsername);
rs = pstmt.executeQuery();
while (rs.next()) {
teecurr_id = rs.getInt("teecurr_id");
courseName = rs.getString("courseName");
pretty_date = rs.getString("pretty_date");
pace_status_id = rs.getInt("pace_status_id");
pace_status_name = rs.getString("pace_status_name");
player1 = rs.getString("player1");
player2 = rs.getString("player2");
player3 = rs.getString("player3");
player4 = rs.getString("player4");
player5 = rs.getString("player5");
p1cw = rs.getString("p1cw");
p2cw = rs.getString("p2cw");
p3cw = rs.getString("p3cw");
p4cw = rs.getString("p4cw");
p5cw = rs.getString("p5cw");
hr = rs.getInt("hr");
min = rs.getInt("min");
fb = rs.getInt("fb");
if (hr == 12) ampm = " PM";
if (hr == 0) hr = 12;
if (hr > 12) {
hr = hr - 12;
ampm = " PM";
}
time = hr + ":" + SystemUtils.ensureDoubleDigit(min) + ampm;
pace_time = getPaceTimeByTeeCurrID(teecurr_id, out, con);
if (pace_time.equals("")) pace_time = "N/A";
out.println("<tr>");
out.println("<td>" + pretty_date + "</td>");
out.println("<td>" + time + "</td>");
if (pMulti == 1) out.println("<td>" + courseName + "</td>");
out.println("<td>" + pace_time + ((fb == 1) ? "" : "<font size=1>(B)</font>") + "</td>");
out.println("<td>" + pace_status_name + "</td>");
out.println("</tr>");
out.println("<tr>");
out.print("<td colspan=" + ((pMulti == 1) ? "5" : "4") + "><font size=2>");
out.print(player1 + " <font size=1>(" + p1cw + ")</font>");
if (!player2.equals("") && !player2.equalsIgnoreCase("x")) out.print(", " + player2 + " <font size=1>(" + p2cw + ")</font>");
if (!player3.equals("") && !player3.equalsIgnoreCase("x")) out.print(", " + player3 + " <font size=1>(" + p3cw + ")</font>");
if (!player4.equals("") && !player4.equalsIgnoreCase("x")) out.print(", " + player4 + " <font size=1>(" + p4cw + ")</font>");
if (!player5.equals("") && !player5.equalsIgnoreCase("x")) out.print(", " + player5 + " <font size=1>(" + p5cw + ")</font>");
out.print("</font></td>");
out.println("</tr>");
out.println("<tr><td colspan=" + ((pMulti == 1) ? "5" : "4") + " bgcolor=\"#8B8970\"><img src=\"/" + rev + "/images/shim.gif\" width=1 height=1></td></tr>");
} // end while loop
out.println("</table>");
out.println("<br> ");
out.println("<table align=center border=0><tr><td>");
out.println("<form method=post action=\"/"+rev+"/servlet/Proshop_report_pace\" name=frmWhichReport id=frmWhichReport>");
out.println("<input type=hidden name=todo value=\"" + pTodo + "\">");
out.println("<input type=hidden name=cal_box_0 value=\"" + pStartDate + "\">");
out.println("<input type=hidden name=cal_box_1 value=\"" + pEndDate + "\">");
out.println("<input type=hidden name=username value=\"" + pUsername + "\">");
out.println("<input type=hidden name=details value=\"\">");
out.println("<input type=hidden name=sort value=\"\">");
out.println("<input type=submit name=btnSubmit value=\"Back to Summary Report\" style=\"background:#8B8970\">");
out.println("</form>");
out.println("</td></tr></table>");
out.println("<script>");
out.println("function fetchSorted(pBy) {");
out.println(" f = document.forms['frmWhichReport'];");
out.println(" f.sort.value = pBy;");
out.println(" f.details.value = 'y';");
out.println(" f.submit();");
out.println("}");
out.println("</script>");
} catch (Exception exc) {
SystemUtils.buildDatabaseErrMsg(exc.toString(), "", out, false);
return;
}
}
private void doCourseReport(HttpServletRequest req, long pStartDate, long pEndDate, String pExcel, PrintWriter out, Connection con) {
Statement stmt = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
int i = 0;
String sql = "";
String courseName = (req.getParameter("course") != null) ? req.getParameter("course") : "";
String range_begin = "";
String range_end = "";
int multi = 0;
parmClub parm = new parmClub();
try {
getClub.getParms(con, parm);
multi = parm.multi;
} catch (Exception ignore) { }
try {
if (pStartDate != 0 && pEndDate != 0) {
stmt = con.createStatement();
rs = stmt.executeQuery("" +
"SELECT " +
"DATE_FORMAT('" + pStartDate + "', '%W %M %D, %Y') AS b, " +
"DATE_FORMAT('" + pEndDate + "', '%W %M %D, %Y') AS e");
if (rs.next()) {
range_begin = rs.getString("b");
range_end = rs.getString("e");
}
rs.close();
stmt.close();
}
pstmt = con.prepareStatement("" +
"SELECT *, ( " +
"SELECT AVG(t_18-t_start) AS 18_hole_pace " +
"FROM ( " +
"SELECT tp.courseName, pe.teecurr_id, " +
"MAX(IF(hole_number=0,hour(pe.hole_timestamp)*60+minute(pe.hole_timestamp),null)) AS t_start, " +
"MAX(IF(invert=9,hour(pe.hole_timestamp)*60+minute(pe.hole_timestamp),null)) AS t_9, " +
"MAX(IF(invert=18,hour(pe.hole_timestamp)*60+minute(pe.hole_timestamp),null)) AS t_18 " +
"FROM pace_entries pe, teepast2 tp " +
"WHERE pe.teecurr_id = tp.teecurr_id " +
"AND (pe.hole_number = 0 OR pe.invert = 9 OR pe.invert = 18) " +
"GROUP BY pe.teecurr_id " +
") AS times " +
"WHERE t_start IS NOT NULL AND t_18 IS NOT NULL " +
"AND times.courseName = x.courseName " +
"AND x.pace_status_id IS NULL " +
"GROUP BY times.courseName " +
") AS Average " +
"FROM ( " +
"SELECT courseName, pace_status_id, pace_status_name, SUM(totals) AS overall " +
"FROM ( " +
"SELECT t.courseName, t.pace_status_id, COUNT(*) AS totals, p.pace_status_name " +
"FROM teepast2 t, pace_status p " +
"WHERE t.pace_status_id > 0 " +
((pStartDate == 0 && pEndDate == 0) ? "" : "AND t.date >= ? AND t.date <= ? ") +
"AND t.pace_status_id = p.pace_status_id " +
((courseName.equals("-ALL-")) ? "" : "AND t.courseName = ? ") +
"GROUP BY t.courseName, t.pace_status_id " +
") AS z " +
"GROUP BY courseName, pace_status_id WITH ROLLUP) AS x " +
"ORDER BY courseName, pace_status_id;");
pstmt.clearParameters();
if (pStartDate == 0 && pEndDate == 0) {
if (!courseName.equals("-ALL-")) {
pstmt.setString(1, courseName);
}
} else {
pstmt.setLong(1, pStartDate);
pstmt.setLong(2, pEndDate);
if (!courseName.equals("-ALL-")) {
pstmt.setString(3, courseName);
}
}
rs = pstmt.executeQuery();
String tmp_last = "";
String course = "";
String pace_status_name = "";
int pace_status_id = 0;
int overall = 0;
int tmp_gtotal = 0;
int tmp_total = 0;
int avg = 0;
double tmp_pcent = 0;
boolean tmp_header = false;
while (rs.next()) {
if (!tmp_header) {
out.print("<center><font size=+2>Pace of Play by Course Report ");
if (!courseName.equals("")) out.print("<br>for " + ((courseName.equals("-ALL-")) ? "each course" : courseName));
if (pStartDate == 0 && pEndDate == 0) {
out.print("</font><br><font size=+1>using all available data</font></center>");
} else {
if (pStartDate == pEndDate) {
out.print("</font><br><font size=+1>for " + range_begin + "</font>");
} else {
out.print(" from</font><br><font size=+1><nobr>" + range_begin + "</nobr> thru <nobr>" + range_end + "</nobr></font>");
}
}
if (!pExcel.equals("yes")) { // if normal request
String todo = (req.getParameter("todo") != null) ? req.getParameter("todo") : "";
out.println("<center><form method=post action=\"/"+rev+"/servlet/Proshop_report_pace\" name=frmRequestExcel id=frmRequestExcel target=\"_blank\">");
out.println("<input type=hidden name=todo value=\"" + todo + "\">");
out.println("<input type=hidden name=cal_box_0 value=\"" + pStartDate + "\">");
out.println("<input type=hidden name=cal_box_1 value=\"" + pEndDate + "\">");
out.println("<input type=hidden name=course value=\"" + courseName + "\">");
out.println("<input type=hidden name=excel value=\"yes\">");
out.println("<input type=submit value=\"Create Excel Spreadsheet\" style=\"text-decoration:underline; background:#8B8970\">");
out.println("</form>");
}
out.println("</center> <br><br><table bgcolor=\"#F5F5DC\" align=center border=0 cellpadding=6>");
tmp_header = true;
}
course = rs.getString("courseName");
pace_status_name = rs.getString("pace_status_name");
pace_status_id = rs.getInt("pace_status_id");
overall = rs.getInt("overall");
avg = rs.getInt("Average");
out.println("<tr>");
if (course == null && pace_status_id == 0) {
out.println("<td width=300><b>Rounds with pace of play recorded:</b></td>" +
"<td colspan=2><b>" + nf.format(overall) + "</b></td>"); // total rounds with pace data
tmp_gtotal = overall;
} else {
if (pace_status_id == 0) tmp_total = overall;
// if we're switching courses OR going from the overall rollup
if (!tmp_last.equals(course)) {
out.println("<td> <b><u>" + course + "</u></b></td>" +
"<td><b>" + (buildDisplayValue(tmp_total, tmp_gtotal, pExcel)) + "</td></tr><tr>");
out.println("<td align=right>Average pace for 18 holes:</td>" +
((!pExcel.equals("")) ? "<td></td>" : "") +
"<td colspan=2>" + minToTime(avg) + "</td></tr><tr>");
} else {
// if avg is here then this is a sub rollup for each course
if (avg != 0) {
out.println("<td align=right>Average pace for 18 holes:</td>" +
"<td colspan=2>" + minToTime(avg) + "</td></tr><tr>");
}
}
if (pace_status_id != 0) {
out.println("<td align=right>Rounds " + pace_status_name + ":</td><td>");
out.print(buildDisplayValue(overall, tmp_total, pExcel));
out.print("</td>");
}
tmp_last = course;
} // end if grand rollup
out.println("</tr>");
} // end while loop
// if nothing was returned from the query then notify
if (!tmp_header) {
out.println("<tr><td colspan=3><p>No tee times were found during the requested time frame that contain pace of play data.");
out.println("The time frame searched was from " + range_begin + " to " + range_end + ".</p></td></tr>");
}
out.println("</table>");
} catch (Exception exc) {
SystemUtils.buildDatabaseErrMsg(exc.toString(), "", out, false);
return;
}
} // end doCourseReport
//**************************************************
// Used by the custom date range reports this routine
// presents the user with date selection options
// and reposts the date back to request the report
//**************************************************
//
private void getCustomDate(HttpServletRequest req, PrintWriter out, Connection con) {
Statement stmt = null;
ResultSet rs = null;
String fname = "";
String lname = "";
String mname = "";
String user = "";
String todo = (req.getParameter("todo") != null) ? req.getParameter("todo") : "";
String course = (req.getParameter("course") != null) ? req.getParameter("course") : "";
String username = (req.getParameter("username") != null) ? req.getParameter("username") : "";
// our oldest date variables (how far back calendars go)
int oldest_mm = 0;
int oldest_dd = 0;
int oldest_yy = 0;
// lookup oldest date in teepast2 that has a pace status
try {
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT mm,dd,yy,pace_status_id FROM teepast2 WHERE pace_status_id <> 0 ORDER BY date ASC LIMIT 1");
while (rs.next()) {
oldest_mm = rs.getInt(1);
oldest_dd = rs.getInt(2);
oldest_yy = rs.getInt(3);
}
} catch (Exception e) {
SystemUtils.buildDatabaseErrMsg("Error looking up oldest tee time with pace data.", e.getMessage(), out, false);
return;
}
// set calendar vars
Calendar cal_date = new GregorianCalendar();
int cal_year = cal_date.get(Calendar.YEAR);
int cal_month = cal_date.get(Calendar.MONTH) + 1; // month is zero based
int cal_day = cal_date.get(Calendar.DAY_OF_MONTH);
// include files for dynamic calendars
out.println("<link rel=\"stylesheet\" href=\"/" +rev+ "/calv30-styles.css\">");
out.println("<script type=\"text/javascript\" src=\"/" +rev+ "/calv30-scripts.js\"></script>");
//out.println("<font size=\"2\" face=\"Arial, Helvetica, Sans-serif\"><center>");
// start main table for this page
out.println("<table border=\"0\" align=\"center\">");
out.println("<tr><td>");
// output instructions
out.println("<table border=\"1\" cellpadding=\"5\" bgcolor=\"#336633\" align=\"center\">");
out.println("<tr><td align=\"center\">");
out.println("<font face=\"verdana\" color=\"#FFFFFF\" size=\"2\">");
out.println("<font size=\"3\"><b>Pace of Play Report</b></font><br>");
out.println("<br>Select the date range below.<br>");
out.println("<b>Note:</b> Only rounds before today will be included in the counts.<br><br>");
out.println("Click on <b>Generate Report</b> to build the report.</font></td></tr>");
out.println("</table><br>");
// start date submission form
out.println("<form action=\"/" +rev+ "/servlet/Proshop_report_pace\" method=\"post\">");
out.println("<input type=hidden name=todo value=\""+ todo +"\">");
out.println("<input type=hidden name=username value=\""+ username +"\">");
out.println("<input type=hidden name=course value=\""+ course +"\">");
// output table that hold calendars and their related text boxes
out.println("<table align=center border=0>\n<tr valign=top>\n<td align=center>");
out.println(" <div id=cal_elem_0 style=\"position: relative; top: 0px; left: 0px; width: 180px; height: 150px\"></div>");
out.println(" <input type=text name=cal_box_0 id=cal_box_0>");
out.println("</td>\n<td> </td>\n<td align=center>");
out.println(" <div id=cal_elem_1 style=\"position: relative; top: 0px; left: 0px; width: 180px; height: 150px\"></div>");
out.println(" <input type=text name=cal_box_1 id=cal_box_1>");
out.println("</td>\n</tr></table>\n");
// report button (go)
out.println("<p align=\"center\"><input type=\"submit\" value=\" Generate Report \" style=\"background:#8B8970\"></p>");
// end date submission form
out.println("</form>");
// output back button form
out.println("<form method=\"get\" action=\"/" +rev+ "/servlet/Proshop_report_pace\">");
out.println("<p align=\"center\"><input type=\"submit\" value=\" Cancel \" style=\"background:#8B8970\"></p>");
out.println("</form>");
// end of main page table
out.println("</td></tr></table>");
// start calendar javascript setup code
out.println("<script type=\"text/javascript\">");
out.println("var g_cal_bg_color = '#F5F5DC';");
out.println("var g_cal_header_color = '#8B8970';");
out.println("var g_cal_border_color = '#8B8970';");
out.println("var g_cal_count = 2;"); // number of calendars on this page
out.println("var g_cal_year = new Array(g_cal_count - 1);");
out.println("var g_cal_month = new Array(g_cal_count - 1);");
out.println("var g_cal_beginning_month = new Array(g_cal_count - 1);");
out.println("var g_cal_ending_month = new Array(g_cal_count - 1);");
out.println("var g_cal_beginning_day = new Array(g_cal_count - 1);");
out.println("var g_cal_ending_day = new Array(g_cal_count - 1);");
out.println("var g_cal_beginning_year = new Array(g_cal_count - 1);");
out.println("var g_cal_ending_year = new Array(g_cal_count - 1);");
// set calendar date parts in js
out.println("g_cal_month[0] = " + cal_month + ";");
out.println("g_cal_year[0] = " + cal_year + ";");
out.println("g_cal_beginning_month[0] = " + oldest_mm + ";");
out.println("g_cal_beginning_year[0] = " + oldest_yy + ";");
out.println("g_cal_beginning_day[0] = " + oldest_dd + ";");
out.println("g_cal_ending_month[0] = " + cal_month + ";");
out.println("g_cal_ending_day[0] = " + cal_day + ";");
out.println("g_cal_ending_year[0] = " + cal_year + ";");
out.println("g_cal_month[1] = " + cal_month + ";");
out.println("g_cal_year[1] = " + cal_year + ";");
out.println("g_cal_beginning_month[1] = " + oldest_mm + ";");
out.println("g_cal_beginning_year[1] = " + oldest_yy + ";");
out.println("g_cal_beginning_day[1] = " + oldest_dd + ";");
out.println("g_cal_ending_month[1] = " + cal_month + ";");
out.println("g_cal_ending_day[1] = " + cal_day + ";");
out.println("g_cal_ending_year[1] = " + cal_year + ";");
out.println("function sd(pCal, pMonth, pDay, pYear) {");
out.println(" f = document.getElementById(\"cal_box_\"+pCal);");
out.println(" f.value = pYear + \"-\" + pMonth + \"-\" + pDay;");
out.println("}");
out.println("</script>");
out.println("<script type=\"text/javascript\">\n doCalendar('0');\n doCalendar('1');\n</script>");
}
//**************************************************
// Pass the teecurr_id of a tee time and get the
// pace time back
//**************************************************
//
private static String getPaceTimeByTeeCurrID(int pTeeCurrID, PrintWriter out, Connection con) {
ResultSet rs = null;
PreparedStatement pstmt = null;
String hole_time = "";
String tmp_stime = "";
String retVal = "";
int hole_num = 0;
int diff = 0;
int fb = 0;
int invert = 0;
//int course_id = SystemUtils.getClubParmIdFromTeeCurrID(pTeeCurrID, con);
try {
// get the front/back indicator for this tee time
pstmt = con.prepareStatement("SELECT fb FROM teecurr2 WHERE teecurr_id = ?");
pstmt.clearParameters();
pstmt.setInt(1, pTeeCurrID);
rs = pstmt.executeQuery();
if (rs.next()) fb = rs.getInt("fb");
rs.close();
// get the highest hole number we have a pace entry for
pstmt = con.prepareStatement("SELECT hole_timestamp, hole_number, invert FROM pace_entries WHERE teecurr_id = ? ORDER BY invert DESC LIMIT 1");
pstmt.clearParameters();
pstmt.setInt(1, pTeeCurrID);
rs = pstmt.executeQuery();
if (rs.next()) {
hole_num = rs.getInt("hole_number");
invert = rs.getInt("invert");
hole_time = rs.getString("hole_timestamp");
}
rs.close();
// there is not enough data - return default
if (hole_num < 1) return retVal;
//if (!(invert == 18 || invert == 9)) return retVal;
// get the their starting time
pstmt = con.prepareStatement("SELECT hole_timestamp FROM pace_entries WHERE teecurr_id = ? AND hole_number = 0");
pstmt.clearParameters();
pstmt.setInt(1, pTeeCurrID);
rs = pstmt.executeQuery();
if (rs.next()) tmp_stime = rs.getString("hole_timestamp");
rs.close();
Statement stmt = con.createStatement();
rs = stmt.executeQuery("SELECT HOUR(SUBTIME(\"" + tmp_stime + "\", \"" + hole_time + "\")) AS hr, MINUTE(SUBTIME(\"" + tmp_stime + "\", \"" + hole_time + "\")) AS min");
//if (rs.next()) retVal = rs.getInt("hr") + ":" + SystemUtils.ensureDoubleDigit(rs.getInt("min"));
if (rs.next()) retVal = rs.getInt("hr") + "h " + rs.getInt("min") + "min";
if (invert != 18) retVal += " <font size=1>(thru " + hole_num + ")</font>";
} catch (Exception e) {
SystemUtils.buildDatabaseErrMsg(e.getMessage(), e.toString(), out, false);
return retVal;
}
return retVal;
}
//**************************************************
// Convert minutes to nice human readable format
//**************************************************
//
private static String minToTime(int pMinutes) {
return (pMinutes / 60) + "h " + (pMinutes % 60) + "min";
}
//**************************************************
// Common Method for Displaying Values
//**************************************************
//
private String buildDisplayValue(int pSubTotal, int pGrandTotal, String pExcel) {
String retVal = "";
if (pSubTotal < 1 || pGrandTotal < 1) {
return "" + nf.format(pSubTotal) + "</td><td>";
} else {
double tmp = (pSubTotal * 100) / pGrandTotal;
if (pExcel.equals("")) {
return nf.format(pSubTotal) + "</td><td><font size=\"2\">(" + ((tmp < 1) ? "<1" : nf.format(tmp)) + "%)";
} else {
return nf.format(pSubTotal) + "</td><td>";
}
}
} // end buildDisplayValue
} // end class | [
"[email protected]"
] | |
73db86584541d2947c2be8c70f4cad1673fabae8 | 1d27d2a1723e08b5d6c4ee874f7100787c5f0d6f | /04.DbAppsIntroduction-Exercise/src/p09_increase_age_stored_procedure/Main.java | 472c18f3b8dfa4a94b840d915f011ee94898b625 | [] | no_license | AleksandarBoev/Software-University-Databases-Frameworks-Hibernate-and-Spring-Data | 87e0ecfd51734cbe76c9e39bb0eae1f1dfdc01e3 | 23728e724fc145a0ab0f617287919c565a3cbe8a | refs/heads/master | 2020-04-02T21:12:24.658526 | 2018-12-18T16:52:05 | 2018-12-18T16:52:05 | 154,790,922 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,570 | java | package p09_increase_age_stored_procedure;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.*;
import java.util.Properties;
/*
Stored procedure code:
DELIMITER $$
CREATE PROCEDURE usp_get_older(minionId INT)
BEGIN
UPDATE minions
SET age = age + 1
WHERE id = minionId;
END$$
*/
public class Main {
public static void main(String[] args) throws SQLException, IOException {
Properties credentials = new Properties();
credentials.setProperty("user", "root");
credentials.setProperty("password", "");
Connection connectionToDb = DriverManager.getConnection(
"jdbc:mysql://127.0.0.1/minions_db", credentials
);
PreparedStatement sqlCallProcedure = connectionToDb.prepareStatement(
"CALL usp_get_older(?)"
);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
Integer minionId = Integer.parseInt(reader.readLine());
reader.close();
sqlCallProcedure.setInt(1, minionId);
sqlCallProcedure.execute();
PreparedStatement sqlGetCertainMinion = connectionToDb.prepareStatement(
"SELECT name, age FROM minions WHERE id = ?"
);
sqlGetCertainMinion.setInt(1, minionId);
ResultSet resultSet = sqlGetCertainMinion.executeQuery();
while (resultSet.next()) {
System.out.printf("%s %d", resultSet.getString("name"), resultSet.getInt("age"));
}
connectionToDb.close();
}
}
| [
"[email protected]"
] | |
ed1e3f4b31abaee09ff95e87a93bc542680eb87b | 3a6d0ae4cf9ec941b9d4b9e345ead8326c6c998e | /src/Database/CommonCodes/DatabaseTextBinder.java | 6770c700d41b7dbab43acd0ff5084e612926e303 | [] | no_license | aukgit/JavaBootstrapper | 73366182a3de21a90f124c93583334ba1ef54418 | c9b7f85eaa16e0fc35f06b266f9c7bdb734db796 | refs/heads/master | 2016-09-03T06:57:16.353880 | 2015-01-08T18:54:09 | 2015-01-08T18:54:09 | 28,774,515 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,034 | java | /*
* 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 Database.CommonCodes;
import Common.Codes;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.text.JTextComponent;
/**
*
* @author Alim
*/
public class DatabaseTextBinder {
public static void DbBindTextBoxes(JFrame frame, boolean fieldNamesAppend, boolean read, boolean insert, boolean update) {
String[] fields = null;
ArrayList<JTextComponent> list = Codes.getAllTextBox(frame);
for (JTextComponent textBox : list) {
//binding property name
textBox.getAccessibleContext().setAccessibleName("helllo 2");
String accessName = textBox.getAccessibleContext().getAccessibleName();
System.out.println(accessName);
}
//
// if (read) {
//
// db.setSpecialQueryFields_(fieldNamesAppend, fields);
// }
}
}
| [
"[email protected]"
] | |
f3244d2d69ec1aff5de66c7e0ffab3ce80edde89 | 70600ee951346053c9cf2ba5d4a75170cc47274c | /Test/src/com/algorithm/T1.java | 327c7bd4c129ef936b878340e4ce82eb3d3e8df0 | [] | no_license | fangyue6/MyJavaCode | 8884a2e7597a44297c1a74a00d5a218d5a49ecd3 | d6d9f04e7d3455962a9ddf316d64d38e898d3bfa | refs/heads/master | 2020-04-05T13:40:58.129718 | 2017-07-08T10:56:43 | 2017-07-08T10:56:43 | 94,976,522 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 336 | java | package com.algorithm;
import java.util.Scanner;
public class T1 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n=in.nextInt();
double s=0.0;
for(int i=2;i<=n;i++){
s = s + Math.pow(0.5, i);
}
String string = String.format("%.1f", n-1+s);
System.out.println(string);
}
}
| [
"yue.fang.ser"
] | yue.fang.ser |
2a8d97c9ca73e5c4ffc7fd55019c06e4b8935088 | 062a70522c8821e57b618fa20b872fb161fc533c | /src/main/java/com/gestankbratwurst/eproaddons/addons/customitems/CustomItemTask.java | 99e62d53db581a50b8aee9c38a14b5912481abc5 | [] | no_license | Flo0/EproAddons | b119977cb125cd947857939dd9033286338b6fad | 84f36f2ca56d62c0bd2ccd8f9570185553fc08aa | refs/heads/master | 2023-01-20T21:37:53.646660 | 2020-11-28T19:25:08 | 2020-11-28T19:25:08 | 316,806,533 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 426 | java | package com.gestankbratwurst.eproaddons.addons.customitems;
/*******************************************************
* Copyright (C) Gestankbratwurst [email protected]
*
* This file is part of EproAddons and was created at the 23.11.2020
*
* EproAddons can not be copied and/or distributed without the express
* permission of the owner.
*
*/
public interface CustomItemTask {
boolean isDone();
void tick();
}
| [
"[email protected]"
] | |
1a60034037ada6074ee23f43c029310c0657e068 | 3b1d783f7462627ec2ae9a8b34b3d38cbfda28c6 | /src/test.java | 87d4cecfbf6fb6cc5f0fde5c354dfa25dec0fe04 | [] | no_license | chiaragii/Demo | 074f40121a3d8aaeaaf954938cabb249ffc3e0b6 | db7d0d21102c0508be4f1870fb9e1669fe025b42 | refs/heads/master | 2023-01-21T04:11:25.048454 | 2020-12-01T09:19:51 | 2020-12-01T09:19:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 70 | java | public class test {
private int a = 0;
private String name;
}
| [
"[email protected]"
] | |
f1965b283e36b14dfc89d7ca8abe79cea559a37d | 379299e5540f04452ad17f23931fa724f58cfbdc | /sql-processor/src/main/java/org/sqlproc/engine/type/SqlCharType.java | 9cc8198c8bc84fa889b4066921484b99793a5bc0 | [] | no_license | hudec/sql-processor | e9e7d8162f27e36b0d2cc4885c796acdf5e667b0 | 83aaf54d634673d3903abec57a91fc6b6fc8bd28 | refs/heads/master | 2023-08-29T01:35:17.719273 | 2020-03-09T11:49:29 | 2020-03-09T11:49:29 | 1,592,013 | 22 | 9 | null | 2022-12-16T05:14:46 | 2011-04-09T16:55:26 | Java | UTF-8 | Java | false | false | 513 | java | package org.sqlproc.engine.type;
/**
* The META type CHARACTER.
*
* @author <a href="mailto:[email protected]">Vladimir Hudec</a>
*/
public abstract class SqlCharType extends SqlDefaultType {
/**
* {@inheritDoc}
*/
@Override
public Class<?>[] getClassTypes() {
return new Class[] { Character.class, char.class };
}
/**
* {@inheritDoc}
*/
@Override
public String[] getMetaTypes() {
return new String[] { "CHARACTER", "CHAR" };
}
}
| [
"[email protected]"
] | |
afeeb5a609d0950e4dd31d4c33fc2da4bbc6b334 | a273d77fae52e1fda6fff819781e31d467838f02 | /src/main/java/com/webtrekk/email/messaging/EmailEventCountSink.java | ccccc4ae0d760991a0a7398ea5765eae15360769 | [
"Apache-2.0"
] | permissive | VladimirYushkevich/email-service | 688c9d80a2623202ecb5cb7158910d6b5915d8a7 | 6b63ff182f41fd705b88381c190e85594e117270 | refs/heads/master | 2020-04-09T02:26:34.924434 | 2019-06-14T19:58:31 | 2019-06-14T19:58:31 | 159,941,118 | 0 | 0 | Apache-2.0 | 2018-12-28T00:01:45 | 2018-12-01T12:13:41 | Java | UTF-8 | Java | false | false | 1,398 | java | package com.webtrekk.email.messaging;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.Materialized;
import org.apache.kafka.streams.kstream.Serialized;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.stereotype.Component;
import static com.webtrekk.email.utils.KafkaUtils.booleanStringFrom;
@Component
@EnableBinding(EmailChannels.class)
@Slf4j
public class EmailEventCountSink {
private final Materialized materializedCount;
public EmailEventCountSink(@Qualifier("materializedCount") Materialized materializedCount) {
this.materializedCount = materializedCount;
}
@StreamListener(EmailChannels.STORE_IN)
@SuppressWarnings("unchecked")
public void processCounts(KStream<String, Long> counts) {
log.info("::consuming from channel: {}", EmailChannels.STORE_IN);
counts
.map((k, v) -> new KeyValue<>(booleanStringFrom(v), "0"))
.groupByKey(Serialized.with(Serdes.String(), Serdes.String()))
.count(materializedCount)
.toStream();
}
}
| [
"[email protected]"
] | |
1f8f9256a8d4bd8dabd353b683621a4ecfd7cad0 | d8d684c60c30a0a348f3c9e5db51a0385337f20f | /src/snail007/SysConfig.java | e54a1b65c125236a28758df75f59e90dcb6d2b6c | [
"MIT"
] | permissive | wolfwhoami/goproxy-jui | f81c0e52c0bd0791ffd1fe7540a9548e3db3ea6f | 0f620e3aa7bebdaa2597a48dc3ecdac892b5107c | refs/heads/master | 2021-05-18T04:30:23.430086 | 2019-11-15T05:59:53 | 2019-11-15T05:59:53 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,738 | java | package snail007;
import javax.swing.JOptionPane;
import snail007.bean.ConfigBean;
public class SysConfig extends PFrame {
/**
* Creates new form SysConfig
*/
public SysConfig() {
super();
initComponents();
jCheckBox1.setSelected(Utils.config.IsStartupAutoHide);
jCheckBox2.setSelected(Utils.config.IsGlobalHttpProxy);
jCheckBox3.setSelected(Utils.config.IsAutostart);
jTextField1.setText(Utils.config.GlobalHttpProxyIP);
jTextField2.setText(Utils.config.GlobalHttpProxyPort);
}
/**
* This method is called from within the constructor to initialize the
* form. WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jCheckBox1 = new javax.swing.JCheckBox();
jCheckBox2 = new javax.swing.JCheckBox();
jTextField1 = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jTextField2 = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jCheckBox3 = new javax.swing.JCheckBox();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("系统配置");
jCheckBox1.setText("启动时隐藏");
jCheckBox2.setText("全局HTTP代理");
jCheckBox2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBox2ActionPerformed(evt);
}
});
jTextField1.setText("127.0.0.1");
jTextField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField1ActionPerformed(evt);
}
});
jLabel1.setText("端口:");
jLabel2.setText("IP:");
jButton1.setText("保存");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jCheckBox3.setText("开机启动");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(183, 183, 183)
.addComponent(jButton1))
.addGroup(layout.createSequentialGroup()
.addGap(17, 17, 17)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jCheckBox2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel2)
.addGap(3, 3, 3)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jCheckBox3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jCheckBox1)))))
.addContainerGap(19, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(16, 16, 16)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jCheckBox1)
.addComponent(jCheckBox3))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jCheckBox2)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 96, Short.MAX_VALUE)
.addComponent(jButton1)
.addContainerGap())
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void jCheckBox2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox2ActionPerformed
if (jCheckBox2.isSelected()) {
String ip = jTextField1.getText().trim();
String port = jTextField2.getText().trim();
if (ip.isEmpty() || port.isEmpty()) {
jCheckBox2.setSelected(false);
JOptionPane.showMessageDialog(null, "请输入IP和端口");
return;
}
}
}//GEN-LAST:event_jCheckBox2ActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
ConfigBean bean = new ConfigBean();
bean.IsStartupAutoHide = jCheckBox1.isSelected();
bean.IsGlobalHttpProxy = jCheckBox2.isSelected();
bean.IsAutostart = jCheckBox3.isSelected();
bean.GlobalHttpProxyIP = jTextField1.getText();
bean.GlobalHttpProxyPort = jTextField2.getText();
if (Utils.saveConfigBean(bean)) {
JOptionPane.showMessageDialog(null, "保存成功");
Utils.reloadConfig();
this.dispose();
} else {
JOptionPane.showMessageDialog(null, "保存失败");
}
}//GEN-LAST:event_jButton1ActionPerformed
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextField1ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JCheckBox jCheckBox1;
private javax.swing.JCheckBox jCheckBox2;
private javax.swing.JCheckBox jCheckBox3;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
// End of variables declaration//GEN-END:variables
}
| [
"[email protected]"
] | |
9b836b453f526e479cfbcc261cd2cca5c08f3bb1 | 89912a387ac8e4071c245e7f0fd7a42138b13c97 | /src/main/java/com/bawei/mapper/PlanMapper.java | 45f6a7b2390f8faaae1da362325ce7dc3dcc9563 | [] | no_license | shier38/yearWork_demo1 | e60536b13fe6ed23939132d2d769cff81e5f96a4 | dfebb73e3588171c9b7641d8085fe5728ff5eea2 | refs/heads/master | 2022-12-21T00:11:11.010085 | 2020-01-18T12:18:08 | 2020-01-18T12:18:08 | 234,730,552 | 0 | 0 | null | 2022-12-16T04:54:30 | 2020-01-18T12:20:41 | JavaScript | UTF-8 | Java | false | false | 833 | java | package com.bawei.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import com.bawei.entity.Department;
import com.bawei.entity.Plan;
public interface PlanMapper {
void addPlan(List<Plan> planList);
List<Plan> list(Plan p);
@Select("select p.*,d.name dname from zhunneng_2019plan p\r\n" +
" LEFT JOIN zhunneng_department d on p.dept_id=d.id where p.id=#{id} group by p.id")
Plan show(Plan p);
@Select("select * from zhunneng_department ")
List<Department> dlist();
@Update("update zhunneng_2019plan set name=#{name},amount=#{amount},manager=#{manager},content=#{content},dept_id=#{dept_id} where id=#{id}")
void update(Plan p);
void delAll(Integer[] ids);
}
| [
"[email protected]"
] | |
800c37d7ad0a61bb3b35fad1220fdd087a41ab9a | 20214f24b29f1a4378430caf5ccf80cb8d6e07b5 | /Fisher/src/cn/bean/Label.java | 70a878ed7a9912bfbafa842506d03286aec0d82e | [] | no_license | gdut732/tieba7321025 | fcc38442580129aa7448817023c1970480235b12 | 6950d127dd55c3ae8d231a2b8b7767fa02aaae18 | refs/heads/master | 2021-08-15T22:41:18.759187 | 2017-11-18T13:25:04 | 2017-11-18T13:25:04 | 108,237,207 | 0 | 0 | null | null | null | null | WINDOWS-1252 | Java | false | false | 451 | java | package cn.bean;
public class Label {
private int lno;//ID
private String name;//×ÜÀà±êÇ©Ãû
public Label(int lno, String name) {
super();
this.lno = lno;
this.name = name;
}
public Label() {
super();
}
public int getLno() {
return lno;
}
public void setLno(int lno) {
this.lno = lno;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| [
"[email protected]"
] | |
7986fdc601c952bf46042baed2db4376728d0697 | aa623c778fd88082cf59f442ad3cb671253ffc37 | /src/main/java/com/tencentcloudapi/dayu/v20180709/models/DescribeCCIpAllowDenyResponse.java | 21951c15eb2125cf0418a0785c5627befb73e765 | [
"Apache-2.0"
] | permissive | zjm9109/tencentcloud-sdk-java | 1eac89cedd70c8111c300d050f2c2f2ab1839189 | a31d2d50f75dc740457289db0bf93ed8b3994c73 | refs/heads/master | 2020-09-30T10:32:57.836303 | 2019-12-05T14:18:17 | 2019-12-05T14:18:17 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,029 | java | /*
* Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencentcloudapi.dayu.v20180709.models;
import com.tencentcloudapi.common.AbstractModel;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import java.util.HashMap;
public class DescribeCCIpAllowDenyResponse extends AbstractModel{
/**
* 该字段被RecordList字段替代了,请不要使用
*/
@SerializedName("Data")
@Expose
private KeyValue [] Data;
/**
* 记录数
*/
@SerializedName("Total")
@Expose
private Long Total;
/**
* 返回黑/白名单的记录,
"Key":"ip"时,"Value":值表示ip;
"Key":"domain"时, "Value":值表示域名;
"Key":"type"时,"Value":值表示黑白名单类型(white为白名单,block为黑名单);
"Key":"protocol"时,"Value":值表示CC防护的协议(http或https);
*/
@SerializedName("RecordList")
@Expose
private KeyValueRecord [] RecordList;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
@SerializedName("RequestId")
@Expose
private String RequestId;
/**
* 获取该字段被RecordList字段替代了,请不要使用
* @return Data 该字段被RecordList字段替代了,请不要使用
*/
public KeyValue [] getData() {
return this.Data;
}
/**
* 设置该字段被RecordList字段替代了,请不要使用
* @param Data 该字段被RecordList字段替代了,请不要使用
*/
public void setData(KeyValue [] Data) {
this.Data = Data;
}
/**
* 获取记录数
* @return Total 记录数
*/
public Long getTotal() {
return this.Total;
}
/**
* 设置记录数
* @param Total 记录数
*/
public void setTotal(Long Total) {
this.Total = Total;
}
/**
* 获取返回黑/白名单的记录,
"Key":"ip"时,"Value":值表示ip;
"Key":"domain"时, "Value":值表示域名;
"Key":"type"时,"Value":值表示黑白名单类型(white为白名单,block为黑名单);
"Key":"protocol"时,"Value":值表示CC防护的协议(http或https);
* @return RecordList 返回黑/白名单的记录,
"Key":"ip"时,"Value":值表示ip;
"Key":"domain"时, "Value":值表示域名;
"Key":"type"时,"Value":值表示黑白名单类型(white为白名单,block为黑名单);
"Key":"protocol"时,"Value":值表示CC防护的协议(http或https);
*/
public KeyValueRecord [] getRecordList() {
return this.RecordList;
}
/**
* 设置返回黑/白名单的记录,
"Key":"ip"时,"Value":值表示ip;
"Key":"domain"时, "Value":值表示域名;
"Key":"type"时,"Value":值表示黑白名单类型(white为白名单,block为黑名单);
"Key":"protocol"时,"Value":值表示CC防护的协议(http或https);
* @param RecordList 返回黑/白名单的记录,
"Key":"ip"时,"Value":值表示ip;
"Key":"domain"时, "Value":值表示域名;
"Key":"type"时,"Value":值表示黑白名单类型(white为白名单,block为黑名单);
"Key":"protocol"时,"Value":值表示CC防护的协议(http或https);
*/
public void setRecordList(KeyValueRecord [] RecordList) {
this.RecordList = RecordList;
}
/**
* 获取唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @return RequestId 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
public String getRequestId() {
return this.RequestId;
}
/**
* 设置唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @param RequestId 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
public void setRequestId(String RequestId) {
this.RequestId = RequestId;
}
/**
* 内部实现,用户禁止调用
*/
public void toMap(HashMap<String, String> map, String prefix) {
this.setParamArrayObj(map, prefix + "Data.", this.Data);
this.setParamSimple(map, prefix + "Total", this.Total);
this.setParamArrayObj(map, prefix + "RecordList.", this.RecordList);
this.setParamSimple(map, prefix + "RequestId", this.RequestId);
}
}
| [
"[email protected]"
] | |
7873775bc39d477507cbe462988daecd144e97dd | 88483bbcd6b6b3038233d0a7ebda6c493e4ef589 | /JavaEE Framework/SSM2017案例/ssm_case/src/main/java/com/gs/bean/Cash.java | 36dd35bb396555c0b5b691c59b68082ed4414d57 | [] | no_license | tjy1985001/Teaching | 5760eab3cd3e6c4cd1332c80fcf8098c160a7deb | 31e090c866493443b5a944c043fbfb2f1c90c372 | refs/heads/master | 2020-06-06T22:37:51.921889 | 2018-12-10T03:45:51 | 2018-12-10T03:45:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,663 | java | package com.gs.bean;
import java.math.BigDecimal;
import java.sql.Timestamp;
/**
* Created by Administrator on 2017/12/4.
*/
public class Cash {
private Long id;
private BigDecimal money;
private Timestamp cashTime;
private String cashCustomer;
private Long cashType;
private Long payType;
private Long userId;
private Timestamp createTime;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public BigDecimal getMoney() {
return money;
}
public void setMoney(BigDecimal money) {
this.money = money;
}
public Timestamp getCashTime() {
return cashTime;
}
public void setCashTime(Timestamp cashTime) {
this.cashTime = cashTime;
}
public String getCashCustomer() {
return cashCustomer;
}
public void setCashCustomer(String cashCustomer) {
this.cashCustomer = cashCustomer;
}
public Long getCashType() {
return cashType;
}
public void setCashType(Long cashType) {
this.cashType = cashType;
}
public Long getPayType() {
return payType;
}
public void setPayType(Long payType) {
this.payType = payType;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Timestamp getCreateTime() {
return createTime;
}
public void setCreateTime(Timestamp createTime) {
this.createTime = createTime;
}
}
| [
"[email protected]"
] | |
920b3810d2cc3c659ed0b3058e334eca25d5e4a2 | 70375ad64773d74e8882e45b2f7351b7739fa629 | /src/test/java/org/apache/ibatis/submitted/xml_external_ref/Dog.java | 91236e2e38ff901e5f9c4692805198c3007e494d | [
"Apache-2.0",
"BSD-3-Clause"
] | permissive | yangfancoming/mybatis | 104e64e3f1659ebe1228413f16c4a373e8bedd1c | 7cd9c6093a608a0e0da32155e75d1fddd090c8d5 | refs/heads/master | 2022-09-22T21:09:10.430995 | 2021-05-30T10:37:34 | 2021-05-30T10:37:34 | 195,225,348 | 0 | 0 | Apache-2.0 | 2022-09-08T01:01:18 | 2019-07-04T11:00:52 | Java | UTF-8 | Java | false | false | 90 | java |
package org.apache.ibatis.submitted.xml_external_ref;
public class Dog extends Pet {
}
| [
"[email protected]"
] | |
c042cf3166106ee9fdd17b83bc0bf50aba0abca0 | c84211b58757f75d6b4b586fb0d21b836ec06b2e | /src/main/java/com/test/entity/Fruit88.java | 9778c872858a781aec1701124d31d3f4b34d8a79 | [] | no_license | stuartwdouglas/jcon-crud | b935d51b51353e565ac448daa1ad16d76fa8f007 | 25039371a7242951090a7feda51e2485e415e743 | refs/heads/main | 2023-08-24T01:18:55.216263 | 2021-10-07T11:36:41 | 2021-10-07T11:36:41 | 413,622,405 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,132 | java | package com.test.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
@Entity
@Table(name = "known_fruits88")
public class Fruit88 {
@Id
@SequenceGenerator(
name = "fruitsSequence88",
sequenceName = "known_fruits_id_seq88",
allocationSize = 1,
initialValue = 4)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "fruitsSequence88")
private Integer id;
@Column(length = 40, unique = true)
private String name;
public Fruit88() {
}
public Fruit88(String name) {
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| [
"[email protected]"
] | |
f9c73e32de8847daf2fc2ecfa5fa642b142ed42f | 88a3c0811fa08ac32b2af50135997364cc8fb598 | /app/src/main/java/com/linglingyi/com/model/BenefitModel.java | 496b732f7f41a3df7b8d7e132e5dee63704312df | [] | no_license | Niepeng666/WYCK | 448d8634b690a66225cc4c55cbb0a0faf265787d | 4259ac40c07e6c580682c94a7f9728b7ae491276 | refs/heads/master | 2022-04-24T05:52:37.866435 | 2020-04-10T08:55:19 | 2020-04-10T08:55:19 | 254,588,455 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,715 | java | package com.linglingyi.com.model;
import java.io.Serializable;
/**
* @author: lilingfei
* @description:
* @date: 2019/4/4
*/
public class BenefitModel implements Serializable {
/**
* createTime : 2019-06-07 09:47
* merchantCnName : 李玲飞
* money : 938.00
* moneyType : 代还分润
* tradeType : YKXE
* trxAmt : 0.46
* typeName : 分润
*/
private String createTime;
private String merchantCnName;
private String money;
private String moneyType;
private String tradeType;
private String trxAmt;
private String typeName;
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public String getMerchantCnName() {
return merchantCnName;
}
public void setMerchantCnName(String merchantCnName) {
this.merchantCnName = merchantCnName;
}
public String getMoney() {
return money;
}
public void setMoney(String money) {
this.money = money;
}
public String getMoneyType() {
return moneyType;
}
public void setMoneyType(String moneyType) {
this.moneyType = moneyType;
}
public String getTradeType() {
return tradeType;
}
public void setTradeType(String tradeType) {
this.tradeType = tradeType;
}
public String getTrxAmt() {
return trxAmt;
}
public void setTrxAmt(String trxAmt) {
this.trxAmt = trxAmt;
}
public String getTypeName() {
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}
}
| [
"[email protected]"
] | |
e603954e8842bf7e379cebbb1700ede59390e34f | 866b2b2b1042e1f28822d0e71935b9e5cb63c143 | /src/main/java/com/tryingpfq/transaction/dao/ITranDao.java | f17ffcf764a1d2b802e3c013086d5c0fe38f68c9 | [] | no_license | tryingpfq/dayPractice | 603c51825edf9b06866ed6055ee17a2265bbd68e | 197a6f66bf2706870e25910f6759fc7ed39c8c75 | refs/heads/master | 2022-07-07T06:57:37.989402 | 2021-07-06T07:45:06 | 2021-07-06T07:45:06 | 194,786,859 | 0 | 0 | null | 2022-06-29T17:42:55 | 2019-07-02T04:14:08 | Java | UTF-8 | Java | false | false | 280 | java | package com.tryingpfq.transaction.dao;
import com.tryingpfq.transaction.enity.TranEntity;
/**
* @author tryingpfq
* @date 2020/5/19
**/
public interface ITranDao {
void save(TranEntity entity);
void update(TranEntity entity);
void delete(TranEntity entity);
}
| [
"[email protected]"
] | |
edef5c05a3292907813232ff16ff48d7a6b130e6 | 0eba0fde52366ec469aedb366dcc4b0384294f4d | /src/main/java/com/kodilla/testing/shape/Circle.java | 1eca1dc026c27622da55dab08345cbb274282904 | [] | no_license | Kaja89/kodilla-course-modul-6-4-zadanie | 33453e0b43e7254a618a51b810f89b2b663f9a3b | 25f0664c0bfc88d0615a2ca0e96d4c1d85db74d9 | refs/heads/master | 2021-05-02T03:15:41.631643 | 2018-02-10T18:46:43 | 2018-02-10T18:46:43 | 120,894,581 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 481 | java | package com.kodilla.testing.shape;
public class Circle implements Shape {
private int r;
private String name;
public Circle(int r, String name) {
this.r = r;
this.name = name;
}
public int getR() {
return r;
}
public String getShapeName() {
return name;
}
public double getField(){
return 2 * 3.14 * r;
}
public String toString(){
return name + " " + "field: " + getField();
}
}
| [
"[email protected]"
] | |
d7ba780d43b7bb3c9c86f7bcc9b94af31cc51f1e | 071a9fa7cfee0d1bf784f6591cd8d07c6b2a2495 | /corpus/norm-class/sling/1928.java | 80db920c4e0a6ee6d7a793d9d34997f5eea79a0d | [
"MIT"
] | permissive | masud-technope/ACER-Replication-Package-ASE2017 | 41a7603117f01382e7e16f2f6ae899e6ff3ad6bb | cb7318a729eb1403004d451a164c851af2d81f7a | refs/heads/master | 2021-06-21T02:19:43.602864 | 2021-02-13T20:44:09 | 2021-02-13T20:44:09 | 187,748,164 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,063 | java | licensed apache software foundation asf contributor license agreements notice file distributed work additional copyright ownership asf licenses file apache license version license file compliance license copy license http apache org licenses license required applicable law agreed writing software distributed license distributed basis warranties conditions kind express implied license specific language governing permissions limitations license org apache sling crankstart launcher java closeable java io exception ioexception java util hash map hashmap java util map java util concurrent callable org apache sling provisioning model model org osgi framework bundle org osgi framework bundle context bundlecontext org osgi framework bundle exception bundleexception org osgi framework launch framework org osgi framework launch framework factory frameworkfactory org slf logger org slf logger factory loggerfactory setup osg i osgi framework based provisioning model suppress warnings suppresswarnings serial framework setup frameworksetup hash map hashmap string object callable object logger log logger factory loggerfactory get logger getlogger get class getclass suppress warnings suppresswarnings unchecked require string key desired type desiredtype illegal state exception illegalstateexception object key illegal state exception illegalstateexception missing required object key get class getclass is assignable from isassignablefrom desired type desiredtype class cast exception classcastexception object key desired type desiredtype get name getname object call exception model model require launcher model key model log info setting osg i osgi framework properties map string string fprops framework properties frameworkproperties model get properties getproperties log info starting osg i osgi framework framework factory frameworkfactory factory framework factory frameworkfactory get class getclass get class loader getclassloader load class loadclass org apache felix framework framework factory frameworkfactory new instance newinstance framework framework factory new framework newframework fprops framework start run mode filter runmodefilter rm filter rmfilter run mode filter runmodefilter configurations cfg configurations framework get bundle context getbundlecontext model rm filter rmfilter set shutdown hook setshutdownhook framework closeable cfg log info osg i osgi framework started log info ins talling installing bundles provisioning model bundles installer bundlesinstaller bundles installer bundlesinstaller model rm filter rmfilter bundle context bundlecontext framework get bundle context getbundlecontext install bundles installbundles launcher crankstart filter cfg may be configure maybeconfigure todo gradually inc rease increase start levels launchpad reuse default startup handler defaultstartuphandler code bundle bundles get bundles getbundles log info starting bundles bundles installed bundles length started failed bundle bundles is fragment isfragment started start started bundle exception bundleexception failed log warn error starting bundle get symbolic name getsymbolicname cfg may be configure maybeconfigure failed log info bundles started started log info bundles started failed start total started failed bundles length log info osg i osgi setup waiting framework framework wait for stop waitforstop is fragment isfragment bundle get headers getheaders fragment host set shutdown hook setshutdownhook framework osgi framework osgiframework closeable to close toclose shutdown framework jvm exits runtime get runtime getruntime add shutdown hook addshutdownhook thread override osgi framework osgiframework osgi framework osgiframework get state getstate bundle active log info stopping osg i osgi framework osgi framework osgiframework log info waiting osg i osgi framework exit osgi framework osgiframework wait for stop waitforstop log info osg i osgi framework stopped exception log error exception stop ping stopping osg i osgi framework closeable to close toclose close io exception ioexception ignore | [
"[email protected]"
] | |
7b1f4581bf3dea445350f0f0902055821be93182 | 51c3050325d2584824915efba70f003dd943ffa6 | /pulltorefresh/src/main/java/com/hankkin/library/RefreshListHeader.java | 3cf17a15f174082befd5071a96f22625d00dab1d | [] | no_license | beyond-snail/xywf | 2fff68e7e47238b8bae2256968adae52261844c2 | 87888ba76d1a8b3d86276a55aff625eeea406042 | refs/heads/master | 2021-05-06T07:04:48.164434 | 2018-10-29T08:23:16 | 2018-10-29T08:23:16 | 113,928,842 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,284 | java | package com.hankkin.library;
import com.handmark.pulltorefresh.library.R;
import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class RefreshListHeader extends LinearLayout {
private LinearLayout mContainer;
private ImageView mArrowImageView;
private ImageView mProgressBar;
private TextView mHintTextView;
private int mState = STATE_NORMAL;
private Animation mRotateUpAnim;
private Animation mRotateDownAnim;
protected AnimationDrawable mFooterChrysanthemumAd;
private final int ROTATE_ANIM_DURATION = 180;
public final static int STATE_NORMAL = 0;
public final static int STATE_READY = 1;
public final static int STATE_REFRESHING = 2;
public RefreshListHeader(Context context) {
super(context);
initView(context);
}
/**
* @param context
* @param attrs
*/
public RefreshListHeader(Context context, AttributeSet attrs) {
super(context, attrs);
initView(context);
}
private void initView(Context context) {
LayoutParams lp = new LayoutParams(LayoutParams.FILL_PARENT, 0);
mContainer = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.xlistview_header1, null);
addView(mContainer, lp);
setGravity(Gravity.BOTTOM);
mArrowImageView = (ImageView) findViewById(R.id.xlistview_header_arrow);
mHintTextView = (TextView) findViewById(R.id.xlistview_header_hint_textview);
mProgressBar = (ImageView) findViewById(R.id.xlistview_header_progressbar);
mFooterChrysanthemumAd = (AnimationDrawable) mProgressBar.getDrawable();
mRotateUpAnim = new RotateAnimation(0.0f, -180.0f, Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);
mRotateUpAnim.setDuration(ROTATE_ANIM_DURATION);
mRotateUpAnim.setFillAfter(true);
mRotateDownAnim = new RotateAnimation(-180.0f, 0.0f, Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);
mRotateDownAnim.setDuration(ROTATE_ANIM_DURATION);
mRotateDownAnim.setFillAfter(true);
}
public void setState(int state) {
if (state == mState)
return;
if (state == STATE_REFRESHING) {
mArrowImageView.clearAnimation();
mArrowImageView.setVisibility(View.INVISIBLE);
mProgressBar.setVisibility(View.VISIBLE);
mFooterChrysanthemumAd.start();
} else {
mArrowImageView.setVisibility(View.VISIBLE);
mProgressBar.setVisibility(View.INVISIBLE);
mFooterChrysanthemumAd.stop();
}
switch (state) {
case STATE_NORMAL:
if (mState == STATE_READY) {
mArrowImageView.startAnimation(mRotateDownAnim);
}
if (mState == STATE_REFRESHING) {
mArrowImageView.clearAnimation();
}
mHintTextView.setText(R.string.xlistview_header_hint_normal);
break;
case STATE_READY:
if (mState != STATE_READY) {
mArrowImageView.clearAnimation();
mArrowImageView.startAnimation(mRotateUpAnim);
mHintTextView.setText(R.string.xlistview_header_hint_ready);
}
break;
case STATE_REFRESHING:
mHintTextView.setText(R.string.xlistview_header_hint_loading);
mFooterChrysanthemumAd.start();
break;
default:
}
mState = state;
}
public void setVisiableHeight(int height) {
if (height < 0)
height = 0;
LayoutParams lp = (LayoutParams) mContainer.getLayoutParams();
lp.height = height;
mContainer.setLayoutParams(lp);
}
public int getVisiableHeight() {
return mContainer.getHeight();
}
}
| [
"wu15979937502"
] | wu15979937502 |
dd603c6329f7b7d476dd8e22b584f4dda8f96d46 | 0fe206bbb45574dc64631e2b565e3d268b014536 | /src/main/java/com/pricemonitor/tools/Template.java | 3689cd814b0bb8d67d6a5bf52e634dcc099ad4f8 | [] | no_license | mikhail-kh1988/Price_monitor | cc8ee113488da73d83c3effa9f1a09b70fa3d22c | 434ec8d0334b9ddd61a526339aca862d15898d89 | refs/heads/master | 2023-07-18T02:20:32.787271 | 2021-09-08T10:43:28 | 2021-09-08T10:43:28 | 399,785,716 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 750 | java | package com.pricemonitor.tools;
import com.pricemonitor.entity.Price;
import java.util.List;
public class Template{
private String merchantName;
private String productName;
private java.util.List<Price> priceList;
public String getMerchantName() {
return merchantName;
}
public void setMerchantName(String merchantName) {
this.merchantName = merchantName;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public List<Price> getPriceList() {
return priceList;
}
public void setPriceList(List<Price> priceList) {
this.priceList = priceList;
}
} | [
"[email protected]"
] | |
f724fbcc20eba785049fdf4c8aac30a2197aa7ff | 82059ed835572ae804ba3d6603abe20ff9a3aa85 | /entities/src/test/java/de/kisner/otrcast/model/xml/cut/TestXmlFileName.java | 599126ff215f6175b7f556bba2d7e3ae0f82854f | [] | no_license | thorsten-k/otrcast | e5db7cfaffae93abb27223aed83f097f638b3eb2 | 6bb283d5eefc41908f22f939fd972a4c42d3356e | refs/heads/master | 2023-07-22T23:34:14.574435 | 2023-07-09T06:46:05 | 2023-07-09T06:46:05 | 39,729,765 | 0 | 6 | null | 2023-01-03T13:14:29 | 2015-07-26T15:12:51 | Java | UTF-8 | Java | false | false | 770 | java | package de.kisner.otrcast.model.xml.cut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.kisner.otrcast.test.OtrXmlTestBootstrap;
public class TestXmlFileName extends AbstractXmlCutTest<FileName>
{
final static Logger logger = LoggerFactory.getLogger(TestXmlFileName.class);
public TestXmlFileName(){super(FileName.class);}
public static FileName create(boolean withChildren){return (new TestXmlFileName()).build(withChildren);}
public FileName build(boolean withChilds)
{
FileName xml = new FileName();
xml.setValue("myFile.mp4");
return xml;
}
public static void main(String[] args)
{
OtrXmlTestBootstrap.init();
TestXmlFileName test = new TestXmlFileName();
test.saveReferenceXml();
}
} | [
"[email protected]"
] | |
a21060b1924d20e9e7f38c51ea63ca369f1146cf | e0f13e1839adb80398fa8fd1b2df9d2d24b7fcfa | /chaos-test/src/main/java/cn/amos/chaos/test/dao/entity/UserGroupEntity.java | 5fdb54a2f1f4cdbbc8d52d4907a960392cb82673 | [] | no_license | AmosWang0626/chaos | 617d41490d62bb7c7ac1743148b452bf17480842 | 4736fb9dc89d3ebd25ebbba4c377da9434a6d1ed | refs/heads/master | 2023-06-23T09:23:18.242936 | 2023-02-23T14:44:58 | 2023-02-23T14:44:58 | 118,746,909 | 1 | 0 | null | 2023-06-14T22:32:56 | 2018-01-24T10:01:04 | Java | UTF-8 | Java | false | false | 1,364 | java | package cn.amos.chaos.test.dao.entity;
import lombok.*;
import lombok.experimental.Accessors;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Objects;
/**
* DESCRIPTION: user & group
*
* @author <a href="mailto:[email protected]">amos.wang</a>
* @date 2019/11/27
*/
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
@Builder
@Entity
@Table(name = "DEV_USER_GROUP")
@IdClass(UserGroupIds.class)
public class UserGroupEntity implements Serializable {
@Id
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id")
private UserEntity user;
@Id
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "group_id")
private GroupEntity group;
private Integer type;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof UserGroupEntity)) return false;
UserGroupEntity that = (UserGroupEntity) o;
return Objects.equals(user.getId(), that.user.getId()) &&
Objects.equals(group.getId(), that.group.getId()) &&
Objects.equals(type, that.type);
}
@Override
public int hashCode() {
if (user == null || group == null) {
return super.hashCode();
}
return Objects.hash(user.getId(), group.getId(), type);
}
}
| [
"[email protected]"
] | |
ca1be4de97edfcfa69be51f0b5609aacae867818 | 49c0977f40f3cf0522a98906fba47fe31eb4da1f | /FoodWastageManagement/src/userInterface/ngo/ngoManager/NGORestaurantRequestViewJPanel.java | c80337f126571f1bbf369d9d77e80cf91634d03d | [] | no_license | hipstermartin/food-wastage-management | 251c462639ed02b2bd2fbd364355bbeccf6cad18 | c2e3fdecdfe20e2bd216cb8366a9c2bd9f4ae553 | refs/heads/master | 2023-03-07T13:04:14.544101 | 2023-02-26T05:12:26 | 2023-02-26T05:12:26 | 232,054,612 | 4 | 5 | null | null | null | null | UTF-8 | Java | false | false | 11,285 | java | /*
* 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 userInterface.ngo.ngoManager;
import business.util.request.RequestItem;
import business.workQueue.CollectionWorkRequest;
import java.awt.CardLayout;
import javax.swing.JPanel;
import javax.swing.table.DefaultTableModel;
/**
*
* @author mites
*/
public class NGORestaurantRequestViewJPanel extends javax.swing.JPanel {
/**
* Creates new form NGORestaurantRequestViewJPanel
*/
private JPanel userProcessContainer;
private CollectionWorkRequest collectionWorkRequest;
public NGORestaurantRequestViewJPanel(JPanel userProcessContainer, CollectionWorkRequest collectionWorkRequest) {
initComponents();
this.userProcessContainer = userProcessContainer;
this.collectionWorkRequest = collectionWorkRequest;
populateTable();
populateData();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
lblHeader = new javax.swing.JLabel();
lblRequestFrom = new javax.swing.JLabel();
lblRequestFromVal = new javax.swing.JLabel();
lblRequestDate = new javax.swing.JLabel();
lblRequestDateVal = new javax.swing.JLabel();
lblRequestStatus = new javax.swing.JLabel();
lblRequestStatusVal = new javax.swing.JLabel();
lblQuantity = new javax.swing.JLabel();
lblQuantityVal = new javax.swing.JLabel();
lblCost = new javax.swing.JLabel();
lblCostVal = new javax.swing.JLabel();
jScrollPane = new javax.swing.JScrollPane();
tblRequestDetails = new javax.swing.JTable();
btnBack = new javax.swing.JButton();
setBackground(new java.awt.Color(204, 255, 204));
lblHeader.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
lblHeader.setText("NGO Manager - View Request Details");
lblRequestFrom.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
lblRequestFrom.setText("Request from:");
lblRequestFromVal.setText("<request_from>");
lblRequestDate.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
lblRequestDate.setText("Request Date:");
lblRequestDateVal.setText("<request_date>");
lblRequestStatus.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
lblRequestStatus.setText("Request status:");
lblRequestStatusVal.setText("<request_status>");
lblQuantity.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
lblQuantity.setText("Food Quantity:");
lblQuantityVal.setText("<quantity>");
lblCost.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
lblCost.setText("Pickup Cost:");
lblCostVal.setText("<cost>");
tblRequestDetails.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Quantity", "Type", "Hours to perish"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane.setViewportView(tblRequestDetails);
if (tblRequestDetails.getColumnModel().getColumnCount() > 0) {
tblRequestDetails.getColumnModel().getColumn(0).setResizable(false);
tblRequestDetails.getColumnModel().getColumn(1).setResizable(false);
tblRequestDetails.getColumnModel().getColumn(2).setResizable(false);
}
btnBack.setText("<<BACK");
btnBack.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnBackActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(27, 27, 27)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnBack)
.addComponent(lblRequestFrom)
.addGroup(layout.createSequentialGroup()
.addComponent(lblCost)
.addGap(47, 47, 47)
.addComponent(lblCostVal))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(lblRequestStatus)
.addGap(26, 26, 26))
.addGroup(layout.createSequentialGroup()
.addComponent(lblRequestDate)
.addGap(35, 35, 35)))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(lblQuantity)
.addGap(33, 33, 33)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblQuantityVal)
.addComponent(lblRequestDateVal)
.addComponent(lblRequestStatusVal)
.addComponent(lblRequestFromVal)))
.addComponent(lblHeader, javax.swing.GroupLayout.PREFERRED_SIZE, 503, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGap(78, 78, 78)
.addComponent(jScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(113, 113, 113))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(39, 39, 39)
.addComponent(lblHeader)
.addGap(48, 48, 48)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblRequestFrom)
.addComponent(lblRequestFromVal))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblRequestDate)
.addComponent(lblRequestDateVal))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblRequestStatus)
.addComponent(lblRequestStatusVal))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblQuantity)
.addComponent(lblQuantityVal))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblCost)
.addComponent(lblCostVal))
.addGap(18, 18, 18)
.addComponent(jScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(38, 38, 38)
.addComponent(btnBack)
.addGap(49, 49, 49))
);
}// </editor-fold>//GEN-END:initComponents
private void btnBackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBackActionPerformed
// TODO add your handling code here:
userProcessContainer.remove(this);
CardLayout layout = (CardLayout) userProcessContainer.getLayout();
layout.previous(userProcessContainer);
}//GEN-LAST:event_btnBackActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnBack;
private javax.swing.JScrollPane jScrollPane;
private javax.swing.JLabel lblCost;
private javax.swing.JLabel lblCostVal;
private javax.swing.JLabel lblHeader;
private javax.swing.JLabel lblQuantity;
private javax.swing.JLabel lblQuantityVal;
private javax.swing.JLabel lblRequestDate;
private javax.swing.JLabel lblRequestDateVal;
private javax.swing.JLabel lblRequestFrom;
private javax.swing.JLabel lblRequestFromVal;
private javax.swing.JLabel lblRequestStatus;
private javax.swing.JLabel lblRequestStatusVal;
private javax.swing.JTable tblRequestDetails;
// End of variables declaration//GEN-END:variables
private void populateTable() {
DefaultTableModel dtm = (DefaultTableModel) tblRequestDetails.getModel();
dtm.setRowCount(0);
for (RequestItem ri : collectionWorkRequest.getRequestItems()) {
if (ri.getQuantity() > 0) {
Object row[] = new Object[3];
row[0] = ri;
row[1] = ri.getQuantity();
row[2] = ri.getHoursToPerish();
dtm.addRow(row);
}
}
}
private void populateData() {
String status = collectionWorkRequest.getStatus();
lblRequestStatusVal.setText(status);
lblRequestFromVal.setText(collectionWorkRequest.getRaisedByRestaurant());
lblRequestDateVal.setText(collectionWorkRequest.getRequestDate() + "");
lblQuantityVal.setText(collectionWorkRequest.getTotalQuantity() + " pounds");
String cost = collectionWorkRequest.getDeliveryCost() == 0 ? "Undelivered" : "$" + collectionWorkRequest.getDeliveryCost();
lblCostVal.setText(cost);
}
}
| [
"[email protected]"
] | |
7bb67bd6390c41a3b2fdfd1c549e590f2f9514b8 | 0c62103df45d9021a12e9b12982a83392c393c24 | /hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestFSSchedulerNode.java | 3927b00f68efcc10ef439d0c72247c13cae2452b | [
"LicenseRef-scancode-unknown",
"CC-PDDC",
"LGPL-2.1-only",
"GCC-exception-3.1",
"GPL-2.0-only",
"EPL-1.0",
"Classpath-exception-2.0",
"BSD-3-Clause",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-other-permissive",
"CDDL-1.0",
"MIT",
"CC-BY-2.5",
"CC-BY-3.0",
"MPL-2.0-no-copyleft-exception",
"AGPL-3.0-only",
"LicenseRef-scancode-proprietary-license",
"BSD-2-Clause",
"BSD-2-Clause-Views",
"LicenseRef-scancode-jdom",
"MPL-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-protobuf",
"CDDL-1.1"
] | permissive | maobaolong/hadoop | f934d4dc0ba45162230adf90819699071ca1171d | f378621546df760aef8d2560b6e9469260bdd4bf | refs/heads/trunk | 2021-06-15T11:16:40.192051 | 2017-05-01T06:32:20 | 2017-05-01T06:32:20 | 89,907,623 | 0 | 1 | Apache-2.0 | 2020-02-09T09:16:47 | 2017-05-01T08:05:13 | Java | UTF-8 | Java | false | false | 15,728 | java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair;
import org.apache.hadoop.yarn.api.records.*;
import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer;
import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode;
import org.apache.hadoop.yarn.util.resource.Resources;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import java.util.ArrayList;
import java.util.Collections;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Test scheduler node, especially preemption reservations.
*/
public class TestFSSchedulerNode {
private final ArrayList<RMContainer> containers = new ArrayList<>();
private RMNode createNode() {
RMNode node = mock(RMNode.class);
when(node.getTotalCapability()).thenReturn(Resource.newInstance(8192, 8));
when(node.getHostName()).thenReturn("host.domain.com");
return node;
}
private void createDefaultContainer() {
createContainer(Resource.newInstance(1024, 1), null);
}
private RMContainer createContainer(
Resource request, ApplicationAttemptId appAttemptId) {
RMContainer container = mock(RMContainer.class);
Container containerInner = mock(Container.class);
ContainerId id = mock(ContainerId.class);
when(id.getContainerId()).thenReturn((long)containers.size());
when(containerInner.getResource()).
thenReturn(Resources.clone(request));
when(containerInner.getId()).thenReturn(id);
when(containerInner.getExecutionType()).
thenReturn(ExecutionType.GUARANTEED);
when(container.getApplicationAttemptId()).thenReturn(appAttemptId);
when(container.getContainerId()).thenReturn(id);
when(container.getContainer()).thenReturn(containerInner);
when(container.getExecutionType()).thenReturn(ExecutionType.GUARANTEED);
when(container.getAllocatedResource()).
thenReturn(Resources.clone(request));
containers.add(container);
return container;
}
private void saturateCluster(FSSchedulerNode schedulerNode) {
while (!Resources.isNone(schedulerNode.getUnallocatedResource())) {
createDefaultContainer();
schedulerNode.allocateContainer(containers.get(containers.size() - 1));
schedulerNode.containerStarted(containers.get(containers.size() - 1).
getContainerId());
}
}
private FSAppAttempt createStarvingApp(FSSchedulerNode schedulerNode,
Resource request) {
FSAppAttempt starvingApp = mock(FSAppAttempt.class);
ApplicationAttemptId appAttemptId =
mock(ApplicationAttemptId.class);
when(starvingApp.getApplicationAttemptId()).thenReturn(appAttemptId);
when(starvingApp.assignContainer(schedulerNode)).thenAnswer(
new Answer<Resource>() {
@Override
public Resource answer(InvocationOnMock invocationOnMock)
throws Throwable {
Resource response = Resource.newInstance(0, 0);
while (!Resources.isNone(request) &&
!Resources.isNone(schedulerNode.getUnallocatedResource())) {
RMContainer container = createContainer(request, appAttemptId);
schedulerNode.allocateContainer(container);
Resources.addTo(response, container.getAllocatedResource());
Resources.subtractFrom(request,
container.getAllocatedResource());
}
return response;
}
});
when(starvingApp.isStarved()).thenAnswer(
new Answer<Boolean>() {
@Override
public Boolean answer(InvocationOnMock invocationOnMock)
throws Throwable {
return !Resources.isNone(request);
}
}
);
when(starvingApp.getPendingDemand()).thenReturn(request);
return starvingApp;
}
private void finalValidation(FSSchedulerNode schedulerNode) {
assertEquals("Everything should have been released",
Resources.none(), schedulerNode.getAllocatedResource());
assertTrue("No containers should be reserved for preemption",
schedulerNode.containersForPreemption.isEmpty());
assertTrue("No resources should be reserved for preemptors",
schedulerNode.resourcesPreemptedForApp.isEmpty());
assertEquals(
"No amount of resource should be reserved for preemptees",
Resources.none(),
schedulerNode.getTotalReserved());
}
private void allocateContainers(FSSchedulerNode schedulerNode) {
FairScheduler.assignPreemptedContainers(schedulerNode);
}
/**
* Allocate and release a single container.
*/
@Test
public void testSimpleAllocation() {
RMNode node = createNode();
FSSchedulerNode schedulerNode = new FSSchedulerNode(node, false);
createDefaultContainer();
assertEquals("Nothing should have been allocated, yet",
Resources.none(), schedulerNode.getAllocatedResource());
schedulerNode.allocateContainer(containers.get(0));
assertEquals("Container should be allocated",
containers.get(0).getContainer().getResource(),
schedulerNode.getAllocatedResource());
schedulerNode.releaseContainer(containers.get(0).getContainerId(), true);
assertEquals("Everything should have been released",
Resources.none(), schedulerNode.getAllocatedResource());
// Check that we are error prone
schedulerNode.releaseContainer(containers.get(0).getContainerId(), true);
finalValidation(schedulerNode);
}
/**
* Allocate and release three containers with launch.
*/
@Test
public void testMultipleAllocations() {
RMNode node = createNode();
FSSchedulerNode schedulerNode = new FSSchedulerNode(node, false);
createDefaultContainer();
createDefaultContainer();
createDefaultContainer();
assertEquals("Nothing should have been allocated, yet",
Resources.none(), schedulerNode.getAllocatedResource());
schedulerNode.allocateContainer(containers.get(0));
schedulerNode.containerStarted(containers.get(0).getContainerId());
schedulerNode.allocateContainer(containers.get(1));
schedulerNode.containerStarted(containers.get(1).getContainerId());
schedulerNode.allocateContainer(containers.get(2));
assertEquals("Container should be allocated",
Resources.multiply(containers.get(0).getContainer().getResource(), 3.0),
schedulerNode.getAllocatedResource());
schedulerNode.releaseContainer(containers.get(1).getContainerId(), true);
schedulerNode.releaseContainer(containers.get(2).getContainerId(), true);
schedulerNode.releaseContainer(containers.get(0).getContainerId(), true);
finalValidation(schedulerNode);
}
/**
* Allocate and release a single container.
*/
@Test
public void testSimplePreemption() {
RMNode node = createNode();
FSSchedulerNode schedulerNode = new FSSchedulerNode(node, false);
// Launch containers and saturate the cluster
saturateCluster(schedulerNode);
assertEquals("Container should be allocated",
Resources.multiply(containers.get(0).getContainer().getResource(),
containers.size()),
schedulerNode.getAllocatedResource());
// Request preemption
FSAppAttempt starvingApp = createStarvingApp(schedulerNode,
Resource.newInstance(1024, 1));
schedulerNode.addContainersForPreemption(
Collections.singletonList(containers.get(0)), starvingApp);
assertEquals(
"No resource amount should be reserved for preemptees",
containers.get(0).getAllocatedResource(),
schedulerNode.getTotalReserved());
// Preemption occurs release one container
schedulerNode.releaseContainer(containers.get(0).getContainerId(), true);
allocateContainers(schedulerNode);
assertEquals("Container should be allocated",
schedulerNode.getTotalResource(),
schedulerNode.getAllocatedResource());
// Release all remaining containers
for (int i = 1; i < containers.size(); ++i) {
schedulerNode.releaseContainer(containers.get(i).getContainerId(), true);
}
finalValidation(schedulerNode);
}
/**
* Allocate and release three containers requested by two apps.
*/
@Test
public void testComplexPreemption() {
RMNode node = createNode();
FSSchedulerNode schedulerNode = new FSSchedulerNode(node, false);
// Launch containers and saturate the cluster
saturateCluster(schedulerNode);
assertEquals("Container should be allocated",
Resources.multiply(containers.get(0).getContainer().getResource(),
containers.size()),
schedulerNode.getAllocatedResource());
// Preempt a container
FSAppAttempt starvingApp1 = createStarvingApp(schedulerNode,
Resource.newInstance(2048, 2));
FSAppAttempt starvingApp2 = createStarvingApp(schedulerNode,
Resource.newInstance(1024, 1));
// Preemption thread kicks in
schedulerNode.addContainersForPreemption(
Collections.singletonList(containers.get(0)), starvingApp1);
schedulerNode.addContainersForPreemption(
Collections.singletonList(containers.get(1)), starvingApp1);
schedulerNode.addContainersForPreemption(
Collections.singletonList(containers.get(2)), starvingApp2);
// Preemption happens
schedulerNode.releaseContainer(containers.get(0).getContainerId(), true);
schedulerNode.releaseContainer(containers.get(2).getContainerId(), true);
schedulerNode.releaseContainer(containers.get(1).getContainerId(), true);
allocateContainers(schedulerNode);
assertEquals("Container should be allocated",
schedulerNode.getTotalResource(),
schedulerNode.getAllocatedResource());
// Release all containers
for (int i = 3; i < containers.size(); ++i) {
schedulerNode.releaseContainer(containers.get(i).getContainerId(), true);
}
finalValidation(schedulerNode);
}
/**
* Allocate and release three containers requested by two apps in two rounds.
*/
@Test
public void testMultiplePreemptionEvents() {
RMNode node = createNode();
FSSchedulerNode schedulerNode = new FSSchedulerNode(node, false);
// Launch containers and saturate the cluster
saturateCluster(schedulerNode);
assertEquals("Container should be allocated",
Resources.multiply(containers.get(0).getContainer().getResource(),
containers.size()),
schedulerNode.getAllocatedResource());
// Preempt a container
FSAppAttempt starvingApp1 = createStarvingApp(schedulerNode,
Resource.newInstance(2048, 2));
FSAppAttempt starvingApp2 = createStarvingApp(schedulerNode,
Resource.newInstance(1024, 1));
// Preemption thread kicks in
schedulerNode.addContainersForPreemption(
Collections.singletonList(containers.get(0)), starvingApp1);
schedulerNode.addContainersForPreemption(
Collections.singletonList(containers.get(1)), starvingApp1);
schedulerNode.addContainersForPreemption(
Collections.singletonList(containers.get(2)), starvingApp2);
// Preemption happens
schedulerNode.releaseContainer(containers.get(1).getContainerId(), true);
allocateContainers(schedulerNode);
schedulerNode.releaseContainer(containers.get(2).getContainerId(), true);
schedulerNode.releaseContainer(containers.get(0).getContainerId(), true);
allocateContainers(schedulerNode);
assertEquals("Container should be allocated",
schedulerNode.getTotalResource(),
schedulerNode.getAllocatedResource());
// Release all containers
for (int i = 3; i < containers.size(); ++i) {
schedulerNode.releaseContainer(containers.get(i).getContainerId(), true);
}
finalValidation(schedulerNode);
}
/**
* Allocate and release a single container and delete the app in between.
*/
@Test
public void testPreemptionToCompletedApp() {
RMNode node = createNode();
FSSchedulerNode schedulerNode = new FSSchedulerNode(node, false);
// Launch containers and saturate the cluster
saturateCluster(schedulerNode);
assertEquals("Container should be allocated",
Resources.multiply(containers.get(0).getContainer().getResource(),
containers.size()),
schedulerNode.getAllocatedResource());
// Preempt a container
FSAppAttempt starvingApp = createStarvingApp(schedulerNode,
Resource.newInstance(1024, 1));
schedulerNode.addContainersForPreemption(
Collections.singletonList(containers.get(0)), starvingApp);
schedulerNode.releaseContainer(containers.get(0).getContainerId(), true);
// Stop the application then try to satisfy the reservation
// and observe that there are still free resources not allocated to
// the deleted app
when(starvingApp.isStopped()).thenReturn(true);
allocateContainers(schedulerNode);
assertNotEquals("Container should be allocated",
schedulerNode.getTotalResource(),
schedulerNode.getAllocatedResource());
// Release all containers
for (int i = 1; i < containers.size(); ++i) {
schedulerNode.releaseContainer(containers.get(i).getContainerId(), true);
}
finalValidation(schedulerNode);
}
/**
* Preempt a bigger container than the preemption request.
*/
@Test
public void testPartialReservedPreemption() {
RMNode node = createNode();
FSSchedulerNode schedulerNode = new FSSchedulerNode(node, false);
// Launch containers and saturate the cluster
saturateCluster(schedulerNode);
assertEquals("Container should be allocated",
Resources.multiply(containers.get(0).getContainer().getResource(),
containers.size()),
schedulerNode.getAllocatedResource());
// Preempt a container
Resource originalStarvingAppDemand = Resource.newInstance(512, 1);
FSAppAttempt starvingApp = createStarvingApp(schedulerNode,
originalStarvingAppDemand);
schedulerNode.addContainersForPreemption(
Collections.singletonList(containers.get(0)), starvingApp);
// Preemption occurs
schedulerNode.releaseContainer(containers.get(0).getContainerId(), true);
// Container partially reassigned
allocateContainers(schedulerNode);
assertEquals("Container should be allocated",
Resources.subtract(schedulerNode.getTotalResource(),
Resource.newInstance(512, 0)),
schedulerNode.getAllocatedResource());
// Cleanup simulating node update
schedulerNode.getPreemptionList();
// Release all containers
for (int i = 1; i < containers.size(); ++i) {
schedulerNode.releaseContainer(containers.get(i).getContainerId(), true);
}
finalValidation(schedulerNode);
}
}
| [
"[email protected]"
] | |
0cea1c3be32cb8ffcbc983b11c2a031f2610af8b | 1151c5b6fddb9cc31e38fdb0c40d7f1e009e7830 | /jiangdaxianService_seckill-service/src/main/java/com/jiangdaxian/seckill/constant/SeckillConstant.java | e60f56db65e20134eeeb56f45170d6cde2a9070a | [] | no_license | jdx100424/jiangdaxianService_seckill | 1967d9335ee0475941c590e1b21acb5b4c82891f | 45ec8991e809fef093b6971b34a52d5f6ac63d88 | refs/heads/master | 2020-03-18T17:45:51.562273 | 2018-06-03T07:54:34 | 2018-06-03T07:54:34 | 135,048,931 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 157 | java | package com.jiangdaxian.seckill.constant;
public class SeckillConstant {
//0,草稿,1,启动,2停止
public static final Integer STATUS_OK = 1;
}
| [
"[email protected]"
] | |
4974061828cc3fcf07b363732519c6b0ed058ca7 | cc717334e08b4967de4912c8c10bd80396b52cd7 | /src/TeeTarjoilu.java | 6fc1edca77fd86ab5641794f5895fed5e69ab354 | [] | no_license | Nosseman/Juoma-Automaatti-GUI | 571f4394f2bec2e5b1cb4768349ae7ca8fff9e95 | f34642db52a774095cd7c908a881d0e2c79476f4 | refs/heads/master | 2020-08-30T07:48:31.624074 | 2019-10-30T09:25:05 | 2019-10-30T09:25:05 | 218,310,118 | 0 | 0 | null | null | null | null | ISO-8859-1 | Java | false | false | 2,131 | java | import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
public class TeeTarjoilu extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JLabel lblTee;
private JLabel lblKuva;
private JLabel lblOleHyva;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TeeTarjoilu frame = new TeeTarjoilu();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public TeeTarjoilu() {
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
setSize(200, 200);
setLocationRelativeTo(null);
lblTee = new JLabel("T\u00E4ss\u00E4 teesi:");
lblTee.setHorizontalAlignment(SwingConstants.CENTER);
lblTee.setFont(new Font("Ravie", Font.PLAIN, 13));
contentPane.add(lblTee, BorderLayout.NORTH);
lblKuva = new JLabel("");
lblKuva.setHorizontalAlignment(SwingConstants.CENTER);
Image tea = new ImageIcon(this.getClass().getResource("tee.png")).getImage();
lblKuva.setIcon(new ImageIcon(tea));
contentPane.add(lblKuva, BorderLayout.CENTER);
lblOleHyva = new JLabel("Ole hyv\u00E4!");
lblOleHyva.setHorizontalAlignment(SwingConstants.CENTER);
lblOleHyva.setFont(new Font("Ravie", Font.PLAIN, 13));
contentPane.add(lblOleHyva, BorderLayout.SOUTH);
}
//luodaan olio juoman tarjoilulle jossa
// tarjoillaan juoma tai ilmoitetaan sen loppuneen
public void tarjoaTee(automaatti ja, TeeTarjoilu tt) {
if (ja.getTee() < 10) {
JOptionPane.showMessageDialog(null, "Raaka-aine loppu. Täytä säiliö!", "Virhe!", JOptionPane.ERROR_MESSAGE);
} else {
tt.setVisible(true);
}}
}
| [
"[email protected]"
] | |
e0b9893a77456f47d1aa94328f0cb0b6f494f014 | 945336e95ca96e752880ece499d5c9a2932a7d93 | /src/CodeChef/FallForCode2_2019/NehruGift.java | 1846cdea6597f976bff0da5a923f9b6522d6d296 | [
"Apache-2.0"
] | permissive | manxist256/MovingBit | 8c5a0438b96421f10b1a90e51fafdd2bdbf609be | 793ac93b647a888dccbd86891244ff79f0f5451e | refs/heads/master | 2020-04-07T02:45:44.713862 | 2019-12-29T13:45:36 | 2019-12-29T13:45:36 | 157,988,805 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,064 | java | package CodeChef.FallForCode2_2019;
import java.io.*;
import java.util.InputMismatchException;
public class NehruGift {
static InputReader in = new InputReader(System.in);
private static void solve() {
TrieDictionary trieDictionary = new TrieDictionary();
PrintWriter printWriter = new PrintWriter(System.out);
int N = in.nextInt();
for (int i = 0; i < N; i++) {
trieDictionary.insertWord(in.next());
}
int Q = in.nextInt();
for (int i = 0; i < Q; i++) {
String prefix = in.next();
Node walker = trieDictionary.buildPossibilities(prefix);
if (walker == null) {
printWriter.println(-1);
continue;
}
printWriter.print(walker.count);
printWriter.print(" ");
trieDictionary.asLeftAsPossible(walker, prefix, printWriter);
printWriter.print(" ");
trieDictionary.asRightAsPossible(walker, prefix, printWriter);
printWriter.println();
}
printWriter.flush();
}
public static void main(String[] args) throws Exception {
solve();
}
}
class Node {
char c;
Node[] arr;
int count = 0;
boolean word;
public Node () {
this.arr = new Node[5];
}
}
class TrieDictionary {
Node root;
public TrieDictionary() {
root = new Node();
}
public void insertWord(String word) {
int i = 0, max = word.length();
Node walker = root;
walker.count += max;
while (i < max) {
char c = word.charAt(i);
int index = c - 97;
if (walker.arr[index] == null) {
Node newnode = new Node();
newnode.c = c;
walker.arr[index] = newnode;
}
walker = walker.arr[index];
walker.count += ((max-1) - i);
if (i == word.length() - 1) {
walker.word = true;
}
i++;
}
}
public Node buildPossibilities(String pattern) {
Node walker = root;
int i = 0;
try {
while (i < pattern.length()) {
walker = walker.arr[pattern.charAt(i) - 97];
i++;
}
} catch (Exception e) {
return null;
}
return walker;
}
public void asLeftAsPossible(Node walker, String prefix, PrintWriter printWriter) {
printWriter.print(prefix);
outer : while (true) {
if (walker.word) {
return;
}
for (int i = 0; i < 5; i++) {
if (walker.arr[i] != null) {
printWriter.print(walker.arr[i].c);
walker = walker.arr[i];
continue outer;
}
}
break;
}
}
public void asRightAsPossible(Node walker, String prefix, PrintWriter printWriter) {
printWriter.print(prefix);
outer : while (true) {
for (int i = 4; i >= 0; i--) {
if (walker.arr[i] != null) {
printWriter.print(walker.arr[i].c);
walker = walker.arr[i];
continue outer;
}
}
break;
}
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
public String next() {
return nextString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public Long nextLong() {
return Long.parseLong(nextString());
}
public Double nextDouble() {
return Double.parseDouble(nextString());
}
public int[] nextIntArray(int N) {
int A[] = new int[N];
for (int i = 0; i < N; i++) {
A[i] = nextInt();
}
return A;
}
public long[] nextLongArray(int N) {
long A[] = new long[N];
for (int i = 0; i < N; i++) {
A[i] = nextLong();
}
return A;
}
public double[] nextDoubleArray(int N) {
double A[] = new double[N];
for (int i = 0; i < N; i++) {
A[i] = nextDouble();
}
return A;
}
} | [
"[email protected]"
] | |
465d10ea50629f86d282c655715db581879914dd | 18c74e962ad801279ed8d5f6c2138346cac00afe | /src/main/java/lesson2/DatabaseApp.java | f3321fb2d427dd359479c882b86d88c0358251a0 | [] | no_license | Maksimandr/Geekbrains_Java3_HomeWorks | b1e476e021088e689e3caddfd2feb12f222f15e1 | 50382c4c3f8178ee245b5c61c25c8a96b65e0a65 | refs/heads/master | 2023-06-04T04:59:49.956492 | 2021-06-23T09:11:12 | 2021-06-23T09:11:12 | 371,132,185 | 0 | 0 | null | 2021-06-23T09:01:58 | 2021-05-26T18:25:22 | Java | UTF-8 | Java | false | false | 1,339 | java | package lesson2;
import java.sql.*;
/**
* код с урока проверять не надо
*/
public class DatabaseApp {
private static final String DATABASE_URL = "jdbc:sqlite:javadb.db";
private static Connection connection;
private static Statement statement;
static {
try {
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection(DATABASE_URL);
statement = connection.createStatement();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws SQLException {
DatabaseApp databaseApp = new DatabaseApp();
databaseApp.createTable();
databaseApp.insertNewBike("asdsdf", "123456");
}
public void createTable() throws SQLException {
String createTable = "create table bike (" +
"id integer not null primary key, " +
"model varchar(30) not null, " +
"serial_no varchar(10))";
statement.execute(createTable);
}
public void insertNewBike(String model, String serial) throws SQLException {
String insertSql = "insert into bike (model, serial_no) values ('" + model + "', '" + serial + "')";
statement.execute(insertSql);
}
}
| [
"[email protected]"
] | |
efd1c64d5ce009b1a1a0288bb9809541f58d4f22 | fb7f0262c03fac0d9ba2f3e14fa3ad92d563ee9f | /crm-test/src/main/java/com/crm/test/task/ScheduledTask.java | 2e07744db41039e2cd417b24e478edf8f34de7da | [] | no_license | TwinStarBoy/crm-test-dev | 1f32d2546d6f5cc147bf11cd5809adc363fbc840 | 7dce14cb9cd32dd3d3c6db67bc47fa0a932bdf48 | refs/heads/master | 2021-09-18T12:56:56.476168 | 2018-07-14T08:19:06 | 2018-07-14T08:19:06 | 120,623,482 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,859 | java | package com.crm.test.task;
import java.util.Map;
import javax.mail.internet.MimeMessage;
import org.apache.commons.collections.map.HashedMap;
import org.apache.velocity.app.VelocityEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.ui.velocity.VelocityEngineUtils;
@Component
public class ScheduledTask {
private static final Logger logger = LoggerFactory.getLogger(ScheduledTask.class);
@Autowired
private JavaMailSender mailSender;
@Autowired
private VelocityEngine velocityEngine;
@Value("${spring.mail.username}")
private String sendMailAccount;
public String[] getMailBuyBackAcceptArray(String mailBuyBackAcceptGroup){
String[] acceptors = mailBuyBackAcceptGroup.split(",");
return acceptors;
}
public String[] getMailExceptionInformArray(String mailExceptionInformGroup){
String[] acceptors = mailExceptionInformGroup.split(",");
return acceptors;
}
public void sendTemplateMail(String acceptorAccount,String emailContent) throws Exception {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom(sendMailAccount);
helper.setTo(acceptorAccount);
helper.setSubject("提醒邮件");
Map<String, Object> model = new HashedMap();
model.put("emailContent", emailContent);
String text = VelocityEngineUtils.mergeTemplateIntoString(
velocityEngine, "template.vm", "UTF-8", model);
helper.setText(text, true);
mailSender.send(mimeMessage);
}
}
| [
"[email protected]"
] | |
dc41e41d01d6f57d45d9678e001b19966c30497b | 11187223798fa347f87c459a055c26306e13db23 | /PJ_CS/src/com/pj/pkg/subject.java | fb49a025eac7c4cdd43652f49ea12103f528b592 | [] | no_license | WichitaW/PJ_CS | 30109d5e23c7ef87134b4cabde03486fb1f7614b | fc69ad4cbaa195dd5148ae77856de4c23afd9a88 | refs/heads/master | 2021-05-04T18:23:45.761149 | 2018-02-16T15:06:49 | 2018-02-16T15:06:49 | 120,169,239 | 0 | 0 | null | null | null | null | TIS-620 | Java | false | false | 4,235 | java | package com.pj.pkg;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.Color;
import javax.swing.SwingConstants;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class subject extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
subject frame = new subject();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public subject() {
initialize();
}
/**
* Create the frame.
*/
public void initialize() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setIconImage(Toolkit.getDefaultToolkit().getImage(index.class.getResource("/com/pj/img/large_PSU_logo.gif")));
setTitle("ระบบจัดตารางสอนของคณาจารย์ ภาควิชาวิทยาการคอมพิวเตอร์");
setBounds(300, 100, 700, 500);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
JLabel label = new JLabel("จัดการข้อมูลรายวิชา");
label.setHorizontalAlignment(SwingConstants.CENTER);
label.setForeground(Color.BLACK);
label.setFont(new Font("Angsana New", Font.BOLD, 26));
JButton addSubject = new JButton("\u0E40\u0E1E\u0E34\u0E48\u0E21");
addSubject.setForeground(Color.BLACK);
addSubject.setFont(new Font("Angsana New", Font.BOLD, 20));
JButton showSubject = new JButton("เรียกดู/แก้ไข");
showSubject.setForeground(Color.BLACK);
showSubject.setFont(new Font("Angsana New", Font.BOLD, 20));
JButton backhome = new JButton("กลับหน้าหลัก");
backhome.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//back index
index index = new index();
dispose();
index.main(null);
}
});
backhome.setForeground(Color.BLACK);
backhome.setFont(new Font("Angsana New", Font.BOLD, 20));
backhome.setBackground(Color.WHITE);
GroupLayout gl_contentPane = new GroupLayout(contentPane);
gl_contentPane.setHorizontalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPane.createSequentialGroup()
.addContainerGap()
.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
.addComponent(label, GroupLayout.PREFERRED_SIZE, 658, GroupLayout.PREFERRED_SIZE)
.addGroup(gl_contentPane.createSequentialGroup()
.addGap(229)
.addComponent(addSubject, GroupLayout.PREFERRED_SIZE, 203, GroupLayout.PREFERRED_SIZE))
.addGroup(gl_contentPane.createSequentialGroup()
.addGap(229)
.addComponent(showSubject, GroupLayout.PREFERRED_SIZE, 203, GroupLayout.PREFERRED_SIZE))
.addGroup(gl_contentPane.createSequentialGroup()
.addGap(229)
.addComponent(backhome, GroupLayout.PREFERRED_SIZE, 203, GroupLayout.PREFERRED_SIZE)))
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
gl_contentPane.setVerticalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(Alignment.TRAILING, gl_contentPane.createSequentialGroup()
.addContainerGap(92, Short.MAX_VALUE)
.addGap(82)
.addComponent(label, GroupLayout.PREFERRED_SIZE, 31, GroupLayout.PREFERRED_SIZE)
.addGap(60)
.addComponent(addSubject, GroupLayout.PREFERRED_SIZE, 38, GroupLayout.PREFERRED_SIZE)
.addGap(28)
.addComponent(showSubject, GroupLayout.PREFERRED_SIZE, 38, GroupLayout.PREFERRED_SIZE)
.addGap(60)
.addComponent(backhome, GroupLayout.PREFERRED_SIZE, 33, GroupLayout.PREFERRED_SIZE)
.addGap(72))
);
contentPane.setLayout(gl_contentPane);
}
}
| [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.