blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 5
132
| path
stringlengths 2
382
| src_encoding
stringclasses 34
values | length_bytes
int64 9
3.8M
| score
float64 1.5
4.94
| int_score
int64 2
5
| detected_licenses
listlengths 0
142
| license_type
stringclasses 2
values | text
stringlengths 9
3.8M
| download_success
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
a027bba16ff23ef32d8f71f01276972d1a1c44bd
|
Java
|
morimizu/repo
|
/inventory-backend/src/main/java/com/benjaminrperry/product/Product.java
|
UTF-8
| 1,811
| 2.625
| 3
|
[] |
no_license
|
package com.benjaminrperry.product;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import com.benjaminrperry.category.Category;
@Entity
public class Product {
@Id
@GeneratedValue
private long id;
private String productNumber;
private String description;
@ManyToOne
private Category category;
public Product(){}
public Product(String productNumber, String description, Category category) {
super();
this.productNumber = productNumber;
this.description = description;
this.category = category;
}
/**
* @return the id
*/
public long getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(long id) {
this.id = id;
}
/**
* @return the productNumber
*/
public String getProductNumber() {
return productNumber;
}
/**
* @param productNumber the productNumber to set
*/
public void setProductNumber(String productNumber) {
this.productNumber = productNumber;
}
/**
* @return the description
*/
public String getDescription() {
return description;
}
/**
* @param description the description to set
*/
public void setDescription(String description) {
this.description = description;
}
/**
* @return the category
*/
public Category getCategory() {
return category;
}
/**
* @param category the category to set
*/
public void setCategory(Category category) {
this.category = category;
}
public void updateProperties(Product toCopy) {
this.productNumber = toCopy.getProductNumber();
this.description = toCopy.description;
this.productNumber = toCopy.productNumber;
}
}
| true
|
a27c9138ca849f323363d40c9153f2285044443f
|
Java
|
ines-vermeir/SoftwareProject2Groep9
|
/src/db/SessionDB.java
|
UTF-8
| 18,133
| 2.5
| 2
|
[] |
no_license
|
package db;
import java.util.ArrayList;
import java.util.Iterator;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import java.util.List;
import javax.persistence.Query;
import logic.Book;
import logic.Location;
import logic.Students_enrolled_in_session;
import logic.Training;
public class SessionDB {
private Session session= null;
public SessionDB()
{
super();
session = SingletonHibernate.getSessionFactory().openSession();
}
public void deleteSession(logic.Session mySession) {
Transaction t = null;
try {
t = session.beginTransaction();
session.delete(mySession);
t.commit();
}catch(HibernateException e) {
if(t!= null ) t.rollback();
e.printStackTrace();
}
}
public boolean insertSession (logic.Session mySession)
{
boolean succes = false;
Transaction t = null;
try
{
t = session.beginTransaction();
session.save(mySession);
t.commit();
succes = true;
} catch(HibernateException e)
{
if (t != null) t.rollback();
e.printStackTrace();
succes = false;
}
return succes;
}
public boolean updateSession (logic.Session mySession)
{
boolean succes = false;
//Session session = myFactory.openSession();
Transaction t = null;
try
{
t = session.beginTransaction();
session.update(mySession);
t.commit();
succes = true;
} catch(HibernateException e)
{
if (t != null) t.rollback();
e.printStackTrace();
succes = false;
}
return succes;
}
public boolean archiveSession (logic.Session mySession)
{
mySession.setArchive(1);
boolean succes = false;
Transaction t = null;
try
{
t = session.beginTransaction();
session.update(mySession);
t.commit();
succes = true;
}
catch (HibernateException e)
{
if ( t != null) t.rollback();
e.printStackTrace();
succes = false;
}
return succes;
}
public logic.Session getSessionByID (int sessionID)
{
logic.Session s = null;
Transaction t = null;
try
{
t = session.beginTransaction();
s = (logic.Session) session.get(logic.Session.class, sessionID);
t.commit();
} catch (HibernateException e)
{
if (t != null) t.rollback();
e.printStackTrace();
}
return s;
}
public ArrayList<logic.Session> getAllSessions()
{
ArrayList<logic.Session> list = null;
Transaction t = null;
try
{
t = session.beginTransaction();
list = (ArrayList<logic.Session>) session.createCriteria(logic.Session.class).list();
t.commit();
} catch (HibernateException e)
{
if (t != null) t.rollback();
e.printStackTrace();
}
return list;
}
public List<logic.Session> getAllSessionsOfTrainingID(int tid)
{
List<logic.Session> list = new ArrayList<logic.Session>();
//org.hibernate.Session session = myFactory.openSession();
Transaction t = session.beginTransaction();
for (Object oneObject : session.createQuery("FROM Session where archive =0 AND training_id = " + tid).getResultList()) {
list.add((logic.Session)oneObject);
}
t.commit();
//session.close();
return list;
}
public List<logic.Session> getAllSessionsOfTrainingID2(int tid)
{
List<logic.Session> list = new ArrayList<logic.Session>();
//org.hibernate.Session session = myFactory.openSession();
Transaction t = session.beginTransaction();
for (Object oneObject : session.createQuery("FROM Session where training_id = " + tid).getResultList()) {
list.add((logic.Session)oneObject);
}
t.commit();
//session.close();
return list;
}
//added by Sebastian
/* public List<Students_enrolled_in_session> getAllSessionsByEmployeeId(int id)
{
List<Students_enrolled_in_session> list = new ArrayList<Students_enrolled_in_session>();
//org.hibernate.Session session = myFactory.openSession();
Transaction t = session.beginTransaction();
for (Object oneObject : session.createQuery("FROM Students_enrolled_in_session where sessionID = " + id).getResultList()) {
list.add((Students_enrolled_in_session)oneObject);
}
t.commit();
//session.close();
return list;
}*/
//Added by Sebastian
public List<Students_enrolled_in_session> getAllEmployeesInSession(){
List<Students_enrolled_in_session> list = new ArrayList<Students_enrolled_in_session>();
for (Object oneObject : session.createQuery("FROM Students_enrolled_in_session").getResultList()) {
list.add((Students_enrolled_in_session)oneObject);
}
return list;
}
public int linkEmployee(int sessionID, int employeeIDenrolled) {
int result = 0;
Transaction t = null;
try {
t = session.beginTransaction();
@SuppressWarnings("rawtypes")
Query query =session.createNativeQuery("INSERT INTO Students_enrolled_in_session VALUES(:sessionID, :employeeIDenrolled)");
query.setParameter("sessionID", sessionID);
query.setParameter("employeeIDenrolled",employeeIDenrolled );
result= query.executeUpdate();
t.commit();
return result;
}catch(HibernateException e) {
if(t!= null ) t.rollback();
e.printStackTrace();
}
return result;
}
}
// Code SessionDAO:
//package db;
//
//import java.sql.PreparedStatement;
//import java.sql.ResultSet;
//import java.sql.Date;
//import java.sql.SQLException;
//import java.sql.Statement;
//import java.sql.Timestamp;
//import java.text.SimpleDateFormat;
//import java.util.ArrayList;
//import java.util.Calendar;
//import java.util.GregorianCalendar;
//
//import logic.Employee;
//import logic.Session;
//import logic.Location;
//
//public class SessionDAO extends BaseDAO {
//
// public SessionDAO() throws SQLException {
// super();
// }
//
// //deze functie update de locatie, datum en tijd van een sessie
// // eventueel nog toe te voegen: update van teachers, studentsEnrolled, studentsPresent
// public boolean updateSession (Session s) throws SQLException, Exception {
// boolean successvol = false;
// PreparedStatement p = null;
// String sql = "UPDATE Sessions SET locationID = ?, date = ?, startTime = ?, endTime = ? WHERE sessionID= ?";
// SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
// try{
// if(getConnection().isClosed() ){
// throw new Exception("fout");
// }
// p= getConnection().prepareStatement(sql);
// p.setInt(1, s.getLocation().getID());
// p.setTimestamp(2,new Timestamp( s.getDate().getTime().getTime()));
// p.setString(3, s.getStartTime());
// p.setString (4, s.getEndTime());
// p.setInt(4, s.getSessionID());
// if (p.executeUpdate() == 0){
// successvol = true;
// }
// return successvol;
//
// }finally{
// try{
// if( p != null){
// p.close();
// }
// }catch(SQLException e){
// System.out.println(e.getMessage());
// throw new RuntimeException("error");
// }
// }
//
// }
//
// public boolean insertSession(Session s) throws SQLException, Exception {
// boolean successvol = false;
// PreparedStatement p = null;
// String sql = "INSERT INTO Sessions VALUES (NULL,?,?,?,?,?)";
//
// //SimpleDateFormat format = new SimpleDateFormat ("yyyy-MM-dd");
//
// try{
// if(getConnection().isClosed() ){
// throw new Exception("fout");
// }
// p= getConnection().prepareStatement(sql);
// p.setInt(1, s.getTrainingID());
// p.setInt(2, s.getLocation().getID());
// p.setTimestamp (3, new Timestamp( s.getDate().getTime().getTime()));
// p.setString(4, s.getStartTime());
// p.setString(5, s.getEndTime());
// if (p.executeUpdate() == 0)
// {
// successvol = true;
// }
// Statement stmt = getConnection().createStatement();
// ResultSet r = stmt.executeQuery("SELECT LAST_INSERT_ID();");
// s.setSessionID(r.getInt("sessionID"));
//
// if (s.getTeachers() != null)
// {
// insertTeachers(s.getTeachers(), s.getSessionID());
// }
// if (s.getStudentsEnrolled() != null)
// {
// insertStudentsEnrolled(s.getStudentsEnrolled(), s.getSessionID());
// }
// if (s.getStudentsPresent() != null)
// {
// insertStudentsPresent(s.getStudentsEnrolled(), s.getSessionID());
// }
// if (s.getLocation() != null)
// {
// //insertLocation(s.getLocation());
// }
// return successvol;
// }finally{
// try{
// if( p != null){
// p.close();
// }
// }catch(SQLException e){
// System.out.println(e.getMessage());
// throw new RuntimeException("error");
// }
// }
//
// }
//
// //onderstaande functie heeft getLocation functie van LocationDAO nodig, kan daarna uit commentaar gehaald worden
//// public ArrayList<Session> getAllSessions() throws SQLException, Exception {
//// Statement stm = null;
//// ResultSet r = null;
//// String sql = "SELECT * FROM Sessions";
//// ArrayList<Session> sessions = new ArrayList<Session>();
//// ArrayList<String> teachers = null;
//// ArrayList<Integer> studentsenrolled = null;
//// ArrayList<Integer> studentspresent = null;
//// Session s = null;
//// Location l = null;
//// LocationDAO ld = new LocationDAO();
//// try {
//// if (getConnection().isClosed()) {
//// throw new Exception("error");
//// }
//// stm = getConnection().createStatement();
//// r = stm.executeQuery(sql);
//// while (r.next())
//// {
//// long milliseconds = r.getTimestamp("date").getTime() + (r.getTimestamp("date").getNanos() / 1000000);
//// Calendar c = GregorianCalendar.getInstance();
//// c.setTimeInMillis(milliseconds);
//// l = new Location(ld.getLocation(r.getInt("locationID")));
//// teachers = new ArrayList<String>(getAllTeachers(r.getInt("SessionID")));
//// studentsenrolled = new ArrayList<Integer>(getAllStudentsEnrolled(r.getInt("SessionID")));
//// studentspresent = new ArrayList<Integer>(getAllStudentsPresent(r.getInt("SessionID")));
//// s = new Session(r.getInt("SessionID"), r.getInt("TrainingID"), c, r.getString("startTime"), r.getString("endTime"), l, teachers, studentsenrolled, studentspresent);
//// sessions.add(s);
//// }
//// return sessions;
//// }finally{
//// try{
//// if(stm != null){
//// stm.close();
//// }
//// if(r != null){
//// r.close();
//// }
////
//// }catch(SQLException e){
//// System.out.println(e.getMessage());
//// throw new RuntimeException("fout");
//// }
//// }
//// }
//
// //onderstaande functie heeft getLocation functie van LocationDAO nodig, kan daarna uit commentaar gehaald worden
//// public Session getSession (int sID) throws Exception
//// {
//// PreparedStatement p = null;
//// ResultSet r = null;
//// String sql = "SELECT * FROM Sessions WHERE SesssionID = ?";
//// ArrayList<Session> sessions = new ArrayList<Session>();
//// ArrayList<String> teachers = null;
//// ArrayList<Integer> studentsenrolled = null;
//// ArrayList<Integer> studentspresent = null;
//// Session s = null;
//// Location l = null;
//// LocationDAO ld = new LocationDAO();
//// try{
//// if(getConnection().isClosed() ){
//// throw new Exception("fout");
//// }
//// p= getConnection().prepareStatement(sql);
//// p.setInt(1, sID);
//// r = p.executeQuery();
//// long milliseconds = r.getTimestamp("date").getTime() + (r.getTimestamp("date").getNanos() / 1000000);
//// Calendar c = GregorianCalendar.getInstance();
//// c.setTimeInMillis(milliseconds);
//// l = new Location(ld.getLocation(r.getInt("locationID")));
//// teachers = new ArrayList<String>(getAllTeachers(r.getInt("SessionID")));
//// studentsenrolled = new ArrayList<Integer>(getAllStudentsEnrolled(r.getInt("SessionID")));
//// studentspresent = new ArrayList<Integer>(getAllStudentsPresent(r.getInt("SessionID")));
//// s = new Session(r.getInt("SessionID"), r.getInt("TrainingID"), c, r.getString("startTime"), r.getString("endTime"), l, teachers, studentsenrolled, studentspresent);
//// return s;
//// }finally{
//// try{
//// if( p != null){
//// p.close();
//// }
//// }catch(SQLException e){
//// System.out.println(e.getMessage());
//// throw new RuntimeException("error");
//// }
//// }
////
//// }
//
// public boolean insertTeachers (ArrayList<String> t, int sID) throws SQLException, Exception // wordt gebruikt in insertSession()
// {
// boolean successvol = false;
// PreparedStatement p = null;
// String sql = "INSERT INTO Session_teachers VALUES (?,?)";
// try{
// if(getConnection().isClosed() ){
// throw new Exception("fout");
// }
// for (String s : t)
// {
// p= getConnection().prepareStatement(sql);
// p.setInt(1, sID);
// p.setString(2, s);
// if (p.executeUpdate() == 0)
// {
// successvol = true;
// }
// }
// return successvol;
// }finally{
// try{
// if( p != null){
// p.close();
// }
// }catch(SQLException e){
// System.out.println(e.getMessage());
// throw new RuntimeException("error");
// }
// }
// }
//
// public boolean insertStudentsPresent (ArrayList<Integer> sp, int sID) throws SQLException, Exception // wordt gebruikt in insertSession()
// {
// boolean successvol = false;
// PreparedStatement p = null;
// String sql = "INSERT INTO Students_present_in_session VALUES (?,?)";
// try{
// if(getConnection().isClosed() ){
// throw new Exception("fout");
// }
// for (int i : sp)
// {
// p= getConnection().prepareStatement(sql);
// p.setInt(1, sID);
// p.setInt(2, i);
// if (p.executeUpdate() == 0)
// {
// successvol = true;
// }
// }
// return successvol;
// }finally{
// try{
// if( p != null){
// p.close();
// }
// }catch(SQLException e){
// System.out.println(e.getMessage());
// throw new RuntimeException("error");
// }
// }
// }
//
// public boolean insertStudentsEnrolled (ArrayList<Integer> se, int sID) throws SQLException, Exception // wordt gebruikt in insertSession()
// {
// boolean successvol = false;
// PreparedStatement p = null;
// String sql = "INSERT INTO Students_enrolled_in_session VALUES (?,?)";
// try{
// if(getConnection().isClosed() ){
// throw new Exception("fout");
// }
// for (int i : se)
// {
// p= getConnection().prepareStatement(sql);
// p.setInt(1, sID);
// p.setInt(2, i);
// if (p.executeUpdate() == 0)
// {
// successvol = true;
// }
// }
// return successvol;
// }finally{
// try{
// if( p != null){
// p.close();
// }
// }catch(SQLException e){
// System.out.println(e.getMessage());
// throw new RuntimeException("error");
// }
// }
// }
//
//
// public ArrayList<String> getAllTeachers(int sID) throws SQLException, Exception // wordt gebruikt in getAllSessions() en getSession()
// {
// String teacher = null;
// PreparedStatement p = null;
// ResultSet r = null;
// String sql = "SELECT Teacher FROM Session_Teachers WHERE SessionID = ? ";
// ArrayList<String> teachers = new ArrayList<String>();
//
// try {
// if (getConnection().isClosed()) {
// throw new Exception ("error");
// }
// p= getConnection().prepareStatement(sql);
// p.setInt(1, sID);
// r = p.executeQuery();
//
// while (r.next()) {
// teacher = new String(r.getString("Teacher"));
// teachers.add(teacher);
// }
// return teachers;
// }finally{
// try{
// if( p != null){
// p.close();
// }
// }catch(SQLException e){
// System.out.println(e.getMessage());
// throw new RuntimeException("error");
// }
// }
// }
//
// public ArrayList<Integer> getAllStudentsEnrolled(int sID) throws SQLException, Exception // wordt gebruikt in getAllSessions() en getSession()
// {
// int emplID;
// PreparedStatement p = null;
// ResultSet r = null;
// String sql = "SELECT employeeID FROM Students_enrolled_in_session WHERE SessionID = ? ";
// ArrayList<Integer> studentsEnrolled = new ArrayList<Integer>();
//
// try {
// if (getConnection().isClosed()) {
// throw new Exception ("error");
// }
// p= getConnection().prepareStatement(sql);
// p.setInt(1, sID);
// r = p.executeQuery();
//
// while (r.next()) {
// emplID = r.getInt("employeeID");
// studentsEnrolled.add(emplID);
// }
// return studentsEnrolled;
// }finally{
// try{
// if( p != null){
// p.close();
// }
// }catch(SQLException e){
// System.out.println(e.getMessage());
// throw new RuntimeException("error");
// }
// }
// }
//
// public ArrayList<Integer> getAllStudentsPresent(int sID) throws SQLException, Exception // wordt gebruikt in getAllSessions() en getSession()
// {
// int emplID;
// PreparedStatement p = null;
// ResultSet r = null;
// String sql = "SELECT employeeID FROM Students_present_in_session WHERE SessionID = ? ";
// ArrayList<Integer> studentsPresent = new ArrayList<Integer>();
//
// try {
// if (getConnection().isClosed()) {
// throw new Exception ("error");
// }
// p= getConnection().prepareStatement(sql);
// p.setInt(1, sID);
// r = p.executeQuery();
//
// while (r.next()) {
// emplID = r.getInt("employeeID");
// studentsPresent.add(emplID);
// }
// return studentsPresent;
// }finally{
// try{
// if( p != null){
// p.close();
// }
// }catch(SQLException e){
// System.out.println(e.getMessage());
// throw new RuntimeException("error");
// }
// }
// }
//
//
//
//
//}
| true
|
c736b97f9b30e8861f8760488a089e5434efa4c3
|
Java
|
jtransc/jtransc-examples
|
/stress/src/main/java/com/stress/sub0/sub5/sub4/Class1574.java
|
UTF-8
| 394
| 2.1875
| 2
|
[] |
no_license
|
package com.stress.sub0.sub5.sub4;
import com.jtransc.annotation.JTranscKeep;
@JTranscKeep
public class Class1574 {
public static final String static_const_1574_0 = "Hi, my num is 1574 0";
static int static_field_1574_0;
int member_1574_0;
public void method1574()
{
System.out.println(static_const_1574_0);
}
public void method1574_1(int p0, String p1)
{
System.out.println(p1);
}
}
| true
|
83eee50a1f3487980f004f77dca0e7faabb12bc8
|
Java
|
ldwcmx/iddl
|
/iddl-common/src/main/java/com/it/iddl/common/weight/Weight.java
|
UTF-8
| 5,383
| 3.046875
| 3
|
[] |
no_license
|
/**
* iddl
*
* Intelligent Distributed Data Layer
*
* iddl-common
*/
package com.it.iddl.common.weight;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.iacrqq.util.StringUtil;
/**
*
* <p> 数据库权重配置,权重越大,被选中的机率越大.
*
* <p> 权重配置模式:
* <p> [r|R](\\d*) [w|W](\\d*) [p|P](\\d*) [q|Q](\\d*) [i|I](\\d*)
*
* <p> 字母r或R表示可以对数据库进行读操作, 后面跟一个数字表示读操作的权重,如果字母r或R后面没有数字,则默认是10;
*
* <p> 字母w或W表示可以对数据库进行写操作, 后面跟一个数字表示写操作的权重,如果字母w或W后面没有数字,则默认是10;
*
* <p> 字母p或P表示读操作的优先级, 数字越大优先级越高,读操作优先从优先级最高的数据库中读数据,
* 如果字母p或P后面没有数字,则默认优先级是0;
*
* <p> 字母q或Q表示写操作的优先级, 数字越大优先级越高,写操作优先从优先级最高的数据库中写数据,
* 如果字母q或Q后面没有数字,则默认优先级是0.
*
* <p> 字母i或I表示动态DBIndex, 和用户通过threadLocal指定的dbIndex结合,实现rw之上更灵活的路由
* 一个db可以同时配置多个i;不同的db可以配置相同的i,例如 db0:i0i2,db1:i1,db2:i1,db3:i2则
* 用户指定dbIndex=0,路由到db0;(只有db0有i0)
* 用户指定dbIndex=1,随机路由到db1和db2;(db1和db2都有i1)
* 用户指定dbIndex=2,随机路由到db0和db3;(db0和db3都有i2)
*
* <p> 如:db1: r10w10p2, db2: r20p2, db3: rp3,则对应如下三个Weight:
* db1: Weight(r10w10p2)
* db2: Weight(r20p2)
* db3: Weight(rp3)
*
* <p> 在这个例子中,对db1, db2,db3这三个数据库的读操作分成了两个优先级:
* p3->[db3]
* p2->[db1, db2]
*
* 当进行读操作时,因为db3的优先级最高,所以优先从db3读,
* 如果db3无法进行读操作,再从db1, db2中随机选一个,因为db2的读权重是20,而db1是10,所以db2被选中的机率比db1更大。
*
* <p> 如果在数据库名后面没有设置权重字符串,就认为权重字符串是null,
* 如: db1: r10w10, db2, db3,则对应如下三个Weight:
* db1: Weight(r10w10)
* db2: Weight(null)
* db3: Weight(null)
*
* <p> <b>当权重字符串是空时,相当于"r10w10p0q0",
* 对于上面的例子,实际的数据库权重配置是:db1: r10w10p0q0, db2: r10w10p0q0, db3: r10w10p0q0。<b>
*
* @author sihai
*
*/
public class Weight {
private static final Pattern WEIGHT_PATTERN_R = Pattern.compile("[R](\\d*)");
private static final Pattern WEIGHT_PATTERN_W = Pattern.compile("[W](\\d*)");
private static final Pattern WEIGHT_PATTERN_P = Pattern.compile("[P](\\d*)");
private static final Pattern WEIGHT_PATTERN_Q = Pattern.compile("[Q](\\d*)");
private static final Pattern WEIGHT_PATTERN_I = Pattern.compile("[I](\\d*)");
private String conf;
/**
* 读权重,默认是10
*/
public final int r;
/**
* 写权重,默认是10
*/
public final int w;
/**
* 读优先级,默认是0
*/
public final int p;
/**
* 写优先级,默认是0
*/
public final int q;
/**
* 在group的多个index
*/
public final Set<Integer> indexes;
public Weight(String conf) {
this.conf = conf;
// 当权重字符串是null时,相当于"r10w10p0q0",
if (StringUtil.isBlank(conf)) {
r = 10;
w = 10;
p = 0;
q = 0;
indexes = null;
} else {
conf = conf.trim().toUpperCase();
//如果字母'R'在weightStr中找不到,则读权重是0,
//如果字母'R'在weightStr中已找到了,但是在字母'R'后面没有数字,是读权重是10
r = getUnitWeight(conf, 'R', WEIGHT_PATTERN_R, 0, 10);
w = getUnitWeight(conf, 'W', WEIGHT_PATTERN_W, 0, 10);
p = getUnitWeight(conf, 'P', WEIGHT_PATTERN_P, 0, 0);
q = getUnitWeight(conf, 'Q', WEIGHT_PATTERN_Q, 0, 0);
indexes = getUnitWeights(conf, 'I', WEIGHT_PATTERN_I);
}
}
// 如果字符c在weightStr中找不到,则返回defaultValue1,
// 如果字符c在weightStr中已经找到了,但是在字母c后面没有数字,则返回defaultValue2,
// 否则返回字母c后面 的数字.
private static int getUnitWeight(String weightStr, char c, Pattern p, int defaultValue1, int defaultValue2) {
if (weightStr.indexOf(c) == -1) {
return defaultValue1;
} else {
Matcher m = p.matcher(weightStr);
m.find();
if (m.group(1).length() == 0) {
return defaultValue2;
} else {
return Integer.parseInt(m.group(1));
}
}
}
private static Set<Integer> getUnitWeights(String weightStr, char c, Pattern p) {
if (weightStr.indexOf(c) == -1) {
return null;
}
Set<Integer> is = new HashSet<Integer>();
int start = 0;
Matcher m = p.matcher(weightStr);
while (m.find(start)) {
if (m.group(1).length() != 0) {
is.add(Integer.valueOf(m.group(1)));
}
start = m.end();
}
return is;
}
public String getConf() {
return conf;
}
public static void main(String[] args) {
System.out.println(new Weight("wr0i1"));
System.out.println(new Weight("wr0i0I1"));
System.out.println(new Weight("i0w10I1r20"));
System.out.println(new Weight("i0w10I1r20i3"));
}
}
| true
|
e4d22a15dee028b1004dc9af0dfe21e0d8981cff
|
Java
|
ma343599083/HookApp
|
/app/src/main/java/com/example/hookapp/SPUtils.java
|
UTF-8
| 988
| 2.40625
| 2
|
[] |
no_license
|
package com.example.hookapp;
import android.content.Context;
import android.content.SharedPreferences;
public class SPUtils {
public static final String SP_NAME = "sp";
public static final String KEY_LOGIN = "sp";
public static SPUtils instance;
private static SharedPreferences mSP;
private SPUtils(Context context){
mSP = context.getApplicationContext().getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
}
public static SPUtils getInstance(Context context) {
if(instance == null){
synchronized (SPUtils.class){
if(instance == null){
instance = new SPUtils(context);
}
}
}
return instance;
}
void login(){
mSP.edit().putBoolean(KEY_LOGIN,true).apply();
}
void logout(){
mSP.edit().putBoolean(KEY_LOGIN,false).apply();
}
boolean isLogin(){
return mSP.getBoolean(KEY_LOGIN,false);
}
}
| true
|
055a23d37ed11cd85beadb9de30d8da3706fe043
|
Java
|
griffinperry/BASICinterpreter
|
/Assignments.java
|
UTF-8
| 1,049
| 3.171875
| 3
|
[] |
no_license
|
/**
Initially written by
@author Cay Hortsman BIG JAVA2
with major modificationn by Antonio Sanchez for
Cosc 20203 Programming Techniques
@version 1.05 2019-10-15
*/
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
public class Assignments {
Hashtable<String,Double> symbolTable = new Hashtable<String,Double>();
/**
* assigns the expression to the given variable, and stores this assignment into a hash table.
* @param line the String to be parsed for assigning an expression to a variable
*/
public void assignVar(String line) {
Scanner in = new Scanner(line);
EvaluatorVar e = new EvaluatorVar(symbolTable);
boolean execute = true;
while (in.hasNext())
{
String input = in.nextLine();
input = input.replaceAll("\\s+",""); // skipping blanks
Variable value = e.getAssignmentValue(input);
symbolTable.put(value.LHS,value.RHS); // direct Double casting
System.out.println( value.LHS + "=" + value.RHS);
}
}
}
| true
|
bc2e5c7ad835c49897b71f1b3299826c9235e430
|
Java
|
billhanyu/cell-society
|
/src/ui/ParamSlider.java
|
UTF-8
| 699
| 2.9375
| 3
|
[
"MIT"
] |
permissive
|
package ui;
import javafx.scene.control.Slider;
/**
* @author billyu
* Slider for parameter control
* initSlider will return the slider
*/
public class ParamSlider {
private int min, max, value, increment;
public ParamSlider (int min, int max, int value, int increment) {
this.min = min;
this.max = max;
this.value = value;
this.increment = increment;
}
public Slider initSlider() {
Slider slider = new Slider();
slider.setMin(min);
slider.setMax(max);
slider.setValue(value);
slider.setShowTickLabels(true);
slider.setShowTickMarks(true);
slider.setMajorTickUnit(50);
slider.setMinorTickCount(5);
slider.setBlockIncrement(increment);
return slider;
}
}
| true
|
0bac4ef6cb4bb5245bc6eda47c5dcf54aaae0ecb
|
Java
|
zhaohhit/gtl-java
|
/offices/src/main/java/cn/edu/cug/cs/gtl/offices/text/DocumentCreator.java
|
UTF-8
| 4,095
| 3.265625
| 3
|
[
"MIT"
] |
permissive
|
package cn.edu.cug.cs.gtl.offices.text;
import org.apache.lucene.document.*;
import java.util.ArrayList;
import java.util.List;
public class DocumentCreator {
public enum DocumentLevel {
DL_FILE, //为整个文件创建一个文档
DL_PARAGRAPH, //为文件中的每个自然段创建一个文档
DL_LINE //为文件中的每行文本创建一个文档
}
;
/**
* 为一个文件(WORD,PDF, Excel, PowerPoint等)创建文档;
* 首选出改文件中提取所有文本,然后根据级别创建Lucene文档对象
* 级别由level指定
*
* @param inputFile
* @param level
* @return
*/
public static List<Document> createFromFile(String inputFile, DocumentLevel level) {
switch (level) {
case DL_FILE: {
List<Document> docs = new ArrayList<>();
docs.add(createDoc4EachFile(inputFile));
return docs;
}
case DL_LINE:
case DL_PARAGRAPH: {
return createDoc4EachParagraph(inputFile);
}
default: {
List<Document> docs = new ArrayList<>();
Document doc = createDoc4EachFile(inputFile);
docs.add(doc);
return docs;
}
}
}
/**
* 为一个文件中的每个自然段构建一个文档对象
*
* @param inputFile
* @return
*/
private static List<Document> createDoc4EachParagraph(String inputFile) {
String[] paragraphs = TextExtractor.parseToParagraphs(inputFile);
List<Document> docs = new ArrayList<>();
long i = 0;
for (String p : paragraphs) {
// make a new, empty document
Document doc = new Document();
// Add the path of the file as a field named "path". Use a
// field that is indexed (i.e. searchable), but don't tokenize
// the field into separate words and don't index term frequency
// or positional information:
Field pathField = new StringField("path", inputFile, Field.Store.YES);
doc.add(pathField);
Field paragraphField = new LongPoint("paragraph", i);
doc.add(pathField);
// Add the contents of the file to a field named "contents". Specify a Reader,
// so that the text of the file is tokenized and indexed, but not stored.
// Note that FileReader expects the file to be in UTF-8 encoding.
// If that's not the case searching for special characters will fail.
Field contentField = new TextField("contents", paragraphs[0], Field.Store.YES);
doc.add(contentField);
docs.add(doc);
++i;
}
return docs;
}
/**
* 为一个文件创建一个文档,自然段默认为-1
*
* @param inputFile
* @return
*/
private static Document createDoc4EachFile(String inputFile) {
String text = TextExtractor.parseToString(inputFile);
// make a new, empty document
Document doc = new Document();
// Add the path of the file as a field named "path". Use a
// field that is indexed (i.e. searchable), but don't tokenize
// the field into separate words and don't index term frequency
// or positional information:
Field pathField = new StringField("path", inputFile, Field.Store.YES);
doc.add(pathField);
Field paragraphField = new LongPoint("paragraph", -1L);
doc.add(pathField);
// Add the contents of the file to a field named "contents". Specify a Reader,
// so that the text of the file is tokenized and indexed, but not stored.
// Note that FileReader expects the file to be in UTF-8 encoding.
// If that's not the case searching for special characters will fail.
Field contentField = new TextField("contents", text, Field.Store.YES);
doc.add(contentField);
return doc;
}
}
| true
|
d051a018016c43356fd25a5421b49927786465fb
|
Java
|
bowzar/thematic
|
/thematic-data-sharding/src/test/java/com/yulintu/thematic/data/sharding/test/TestCommon.java
|
UTF-8
| 1,534
| 1.914063
| 2
|
[] |
no_license
|
package com.yulintu.thematic.data.sharding.test;
import com.google.common.base.Predicate;
import com.google.common.base.Strings;
import com.yulintu.thematic.data.FileConnectionStringBuilder;
import com.yulintu.thematic.data.ProviderDb;
import com.yulintu.thematic.data.sharding.ProviderShardingImpl;
import com.yulintu.thematic.data.sharding.ShardElement;
import org.junit.Test;
import java.util.List;
public class TestCommon {
@Test
public void testConfiguration() {
FileConnectionStringBuilder builder = new FileConnectionStringBuilder();
builder.setConfigureFilePath("spring.datasource.shards.xml");
ProviderShardingImpl provider = new ProviderShardingImpl(builder.getConnectionString());
String zoneCode = "510181";
String code = zoneCode;
Predicate<ShardElement> predicate = c -> {
String zone = (String) c.getProperties().get("zone");
if (Strings.isNullOrEmpty(zone))
return false;
if ("86".equals(zone))
return true;
if (zone.startsWith(code) || code.startsWith(zone))
return true;
return false;
};
List<ProviderDb> z0 = provider.getEditShards(zoneCode, predicate);
List<ProviderDb> z1 = provider.getEditShards(zoneCode, predicate);
List<ProviderDb> z2 = provider.getEditShards(zoneCode, predicate);
zoneCode = "51";
List<ProviderDb> queryShards = provider.getQueryShards(zoneCode, predicate);
}
}
| true
|
34989e5cdff5076f311fe8605777a1a2a47894af
|
Java
|
abhinavsamanta/android
|
/SignUpActivity.java
|
UTF-8
| 9,308
| 2
| 2
|
[] |
no_license
|
package com.example.firebasenoteapp;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.UserInfo;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class SignUpActivity extends AppCompatActivity {
@BindView(R.id.textView3)
TextView textView3;
@BindView(R.id.Name)
EditText Name;
@BindView(R.id.email)
EditText email;
@BindView(R.id.signpassword)
EditText signpassword;
@BindView(R.id.signupbtn)
Button signupbtn;
FirebaseAuth firebaseAuth;
ProgressDialog progressDialog;
DatabaseReference databaseUsers;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
ButterKnife.bind(this);
sharedPreferences=getSharedPreferences("FIRENOTDATA", Context.MODE_PRIVATE);
editor=sharedPreferences.edit();
databaseUsers= FirebaseDatabase.getInstance().getReference("USERS");
firebaseAuth=FirebaseAuth.getInstance();
progressDialog=new ProgressDialog(this);
if(getIntent().hasExtra("MOBILE")){
signpassword.setVisibility(View.GONE);
}else{
signpassword.setVisibility(View.VISIBLE);
}
}
@OnClick(R.id.signupbtn)
public void onViewClicked() {
String name=Name.getText().toString();
String Email=email.getText().toString();
String password="";
if(getIntent().hasExtra("MOBILE")){
if(!name.equalsIgnoreCase("")){
if(!Email.equalsIgnoreCase("")){
String mobile=getIntent().getExtras().getString("MOBILE");
String uid=getIntent().getExtras().getString("UID");
UserInfo userInfo=new UserInfo() {
@NonNull
@Override
public String getUid() {
return uid;
}
@NonNull
@Override
public String getProviderId() {
return null;
}
@Nullable
@Override
public String getDisplayName() {
return name;
}
@Nullable
@Override
public Uri getPhotoUrl() {
return null;
}
@Nullable
@Override
public String getEmail() {
return Email;
}
@Nullable
@Override
public String getPhoneNumber() {
return mobile;
}
@Override
public boolean isEmailVerified() {
return false;
}
};
databaseUsers.child(uid).setValue(userInfo).addOnCompleteListener(this, new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
editor.putString("UID",uid);
editor.commit();
Toast.makeText(SignUpActivity.this, "User registered successfully", Toast.LENGTH_SHORT).show();
finish();
}else {
Toast.makeText(SignUpActivity.this, "Failed to register", Toast.LENGTH_SHORT).show();
}
}
});
}
}
}else {
password=signpassword.getText().toString();
registerUser(name,password,Email);
}
}
public void registerUser(String name,String password,String email){
if(!name.equalsIgnoreCase("")){
if(!email.equalsIgnoreCase("")){
if(!password.equalsIgnoreCase("")){
progressDialog.setMessage("registering");
progressDialog.show();
firebaseAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(this,new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
progressDialog.dismiss();
if(task.isSuccessful()){
FirebaseUser user=firebaseAuth.getCurrentUser();
String uid=user.getUid();
UserInfo userInfo=new UserInfo() {
@NonNull
@Override
public String getUid() {
return uid;
}
@NonNull
@Override
public String getProviderId() {
return null;
}
@Nullable
@Override
public String getDisplayName() {
return name;
}
@Nullable
@Override
public Uri getPhotoUrl() {
return null;
}
@Nullable
@Override
public String getEmail() {
return email;
}
@Nullable
@Override
public String getPhoneNumber() {
return null;
}
@Override
public boolean isEmailVerified() {
return false;
}
};
databaseUsers.child(uid).setValue(userInfo).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
editor.putString("UID",uid);
editor.commit();
Toast.makeText(SignUpActivity.this, "User successfully registered", Toast.LENGTH_SHORT).show();
finish();
}
}
});
}else {
Toast.makeText(SignUpActivity.this, "Error registered user", Toast.LENGTH_SHORT).show();
}
}
});
}else {
Toast.makeText(this,"please enter password",Toast.LENGTH_SHORT).show();
}
}else {
Toast.makeText(this,"please enter email",Toast.LENGTH_SHORT).show();
}
}else {
Toast.makeText(this,"please enter name",Toast.LENGTH_SHORT).show();
}
}
}
| true
|
6408ecfa6908ed1fc6736095321504071d84f026
|
Java
|
santiagocorbanini/cryptowalletsAPI
|
/src/main/java/com/clearpay/demo/Document/Wallet.java
|
UTF-8
| 1,247
| 2.125
| 2
|
[] |
no_license
|
package com.clearpay.demo.Document;
import org.bson.types.ObjectId;
import org.springframework.data.annotation.Id;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
public class Wallet {
@Id
private String id = new ObjectId().toString();
private String nameCurrency;
public double currency;
//Id de User class
private String idUser;
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
private Date fecha = new Date();
public Wallet() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getNameCurrency() {
return nameCurrency;
}
public void setNameCurrency(String nameCurrency) {
this.nameCurrency = nameCurrency;
}
public double getCurrency() {
return currency;
}
public void setCurrency(double currency) {
this.currency = currency;
}
public Date getFecha() {
return fecha;
}
public void setFecha(Date fecha) {
this.fecha = fecha;
}
public String getIdUser() {
return idUser;
}
public void setIdUser(String idUser) {
this.idUser = idUser;
}
}
| true
|
18d4ebff81d9b5212f7be3c5cdbe15648d3ace54
|
Java
|
BillLori/spring-boot-study
|
/spring-boot-rabbitmq/src/main/java/org/com/cay/springboot/controller/FanoutController.java
|
UTF-8
| 764
| 2.1875
| 2
|
[] |
no_license
|
package org.com.cay.springboot.controller;
import org.com.cay.springboot.rabbitmq.fanout.Sender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Author: Caychen
* Date: 2018/9/14
* Class: org.com.cay.springboot.controller.FanoutController
* Version: v1.0
* Desc:
*/
@RestController
public class FanoutController {
@Autowired
@Qualifier("fanout-sender")
private Sender sender;
@RequestMapping("/fanout")
public String hello(String name){
sender.send(name);
return "success";
}
}
| true
|
408aa295fefa996fdf0fe010993714940c7fc4a2
|
Java
|
jeniq/Project2
|
/src/com/company/Controller/Controller.java
|
UTF-8
| 3,073
| 3.46875
| 3
|
[] |
no_license
|
package com.company.Controller;
import com.company.Model.AlphabetWord;
import com.company.Model.Sentence;
import com.company.Model.Word;
import com.company.View.View;
import java.io.IOException;
import java.util.List;
/**
* This class performs operations with data.
* It reads data from file and then use parser to divide text.
* It consists methods to sort words, fill list of words by alphabet
* and print sentences of text.
*
* @version 16 June 2016
* @author Yevhen Hryshchenko
*/
public class Controller {
private AlphabetWord alphabetWord;
private Parser parser;
private View view;
private String path;
private WordFactory wordFactory;
private FileOperations fileOperations;
// Constructor
public Controller(AlphabetWord alphabetWord, View view, String path){
this.alphabetWord = alphabetWord;
this.view = view;
this.path = path;
wordFactory = new WordFactory();
parser = new Parser(wordFactory);
fileOperations = new FileOperations();
}
// The work method
public void processUser(){
try {
List<Sentence> sentences = parser.parseTextBySentence(fileOperations.readFile(path));
List<Word> workList = parser.parseTextByWords(sentences);
printSentences(sentences);
sortWords(workList);
fillByAlphabet(workList);
view.printText(alphabetWord.toString());
} catch (IOException e) {
view.printText(View.FILE_NOT_FOUND + path);
}
}
// Insertion sort
private void sortWords(List<Word> words){
Word temp;
int i;
for (int j = 1; j < words.size(); j++){
temp = words.get(j);
i = j - 1;
while ((i >= 0)
&& (words.get(i).compareTo(temp) > 0)){
words.set(i+1, words.get(i));
i--;
}
words.set(i + 1, temp);
}
}
/**
* This method groups words by alphabet.
* @param words input words
*/
private void fillByAlphabet(List<Word> words){
AlphabetWord letter;
letter = new AlphabetWord(Character.toString(words.get(0).toString().toLowerCase().charAt(0)));
for (int i = 1; i < words.size(); i++){
if (!letter.getName().equals(Character.toString(words.get(i).toString().toLowerCase().charAt(0)))){
alphabetWord.addWord(letter);
letter = new AlphabetWord(Character.toString(words.get(i).toString().charAt(0)));
}
if (!letter.getWords().contains(words.get(i))){
letter.addWord(words.get(i));
}
}
alphabetWord.addWord(letter);
}
/**
* This method prints sentences to console.
* @param sentences list of sentences
*/
private void printSentences(List<Sentence> sentences){
StringBuffer buffer = new StringBuffer();
for (Sentence s : sentences){
buffer.append(s);
}
view.printText(buffer.toString());
}
}
| true
|
4879621566ab01a77159c5b9e83e35841109b274
|
Java
|
flowcentraltechnologies/flowcentral
|
/flowcentral-application/src/main/java/com/flowcentraltech/flowcentral/application/data/SearchInputsDef.java
|
UTF-8
| 3,081
| 2.125
| 2
|
[] |
no_license
|
/*
* Copyright 2021-2023 FlowCentral Technologies Limited.
*
* 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.flowcentraltech.flowcentral.application.data;
import java.util.ArrayList;
import java.util.List;
import com.flowcentraltech.flowcentral.configuration.constants.SearchConditionType;
import com.tcdng.unify.core.UnifyException;
import com.tcdng.unify.core.data.Listable;
import com.tcdng.unify.core.util.DataUtils;
/**
* Search inputs definition.
*
* @author FlowCentral Technologies Limited
* @since 1.0
*/
public class SearchInputsDef implements Listable {
private List<SearchInputDef> searchInputDefList;
private String name;
private String description;
private SearchInputsDef(List<SearchInputDef> searchInputDefList, String name, String description) {
this.searchInputDefList = searchInputDefList;
this.name = name;
this.description = description;
}
@Override
public String getListDescription() {
return description;
}
@Override
public String getListKey() {
return name;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public List<SearchInputDef> getSearchInputDefList() {
return searchInputDefList;
}
public boolean isBlank() {
return searchInputDefList == null || searchInputDefList.isEmpty();
}
public static Builder newBuilder() {
return new Builder();
}
public static class Builder {
private String name;
private String description;
private List<SearchInputDef> searchInputDefList;
public Builder() {
this.searchInputDefList = new ArrayList<SearchInputDef>();
}
public Builder name(String name) {
this.name = name;
return this;
}
public Builder description(String description) {
this.description = description;
return this;
}
public Builder addSearchInputDef(SearchConditionType type, String fieldName, String widget, String label) {
searchInputDefList.add(new SearchInputDef(type, fieldName, widget, label));
return this;
}
public SearchInputsDef build() throws UnifyException {
return new SearchInputsDef(DataUtils.unmodifiableList(searchInputDefList), name, description);
}
}
}
| true
|
0028e57cca5c8725ec4079115cd955a3018742a3
|
Java
|
chandawade/sdetu-training
|
/src/basics/NumbersCalc.java
|
UTF-8
| 674
| 4.125
| 4
|
[] |
no_license
|
package basics;
public class NumbersCalc {
public static void main(String[] args) {
//call methods
printName();
int a = 10;
int b = 20;
addNumbers(a,b);
System.out.println(multiplyNumbers(a,b));
}
//methods
static void printName() { //this is passing no params
System.out.println("My name is Chanda");
}
static void addNumbers(int a, int b) { //passing in some parameters
//fx adds two numbers
int sum = a + b;
System.out.println("The sum of numbers " + a + " and " + b + " is " + sum);
}
static int multiplyNumbers(int numA, int numB) {
int product = numA * numB;
return product; //return gives value back to the fx.
}
}
| true
|
502ad6682163ff94751f9f365254007e6431b38d
|
Java
|
naoto-y/java_blog
|
/src/lib/MarkDownRender.java
|
UTF-8
| 4,558
| 2.875
| 3
|
[] |
no_license
|
package lib;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MarkDownRender {
public List<String> rendering(String filePath){
List<String> result = new ArrayList<>();
File file = new File(filePath);
FileReader fr;
try {
fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line;
int mode = 0;
while((line = br.readLine()) != null) {
mode = listCheck(line, mode);
result.add(convert(line, mode));
}
br.close();
} catch (FileNotFoundException e) {
result.add("<p>File Not Found</p>");
} catch (IOException e) {
result.add("<p>File EROOR</p>");
}
return result;
}
private String convert(String line, int mode) {
String converted;
Pattern headingP = Pattern.compile("^#{1,6} .*$");
Matcher headingM = headingP.matcher(line);
if(headingM.find()) {
int index = headingM.group().indexOf(" ");
converted = "<h" + index + ">" + headingM.group().substring(index + 1) + "</h" + index + ">";
return converted;
}
Pattern boldP = Pattern.compile("^[_|/*]{2}.*[_|/*]{2}$");
Matcher boldM = boldP.matcher(line);
if(boldM.find()) {
converted = "<b>" + boldM.group().substring(2, boldM.group().length() - 2) + "</b>";
return converted;
}
Pattern emP = Pattern.compile("^[_|/*].*[_|/*]$");
Matcher emM = emP.matcher(line);
if(emM.find()) {
converted = "<em>" + emM.group().substring(1, emM.group().length() - 1) + "</em>";
return converted;
}
Pattern delP = Pattern.compile("^~~.*~~");
Matcher delM = delP.matcher(line);
if(delM.find()) {
converted = "<del>"+ delM.group().substring(2, delM.group().length() - 2) +"</del>";
return converted;
}
Pattern hrP = Pattern.compile("^---$");
Matcher hrM = hrP.matcher(line);
if(hrM.find()) {
converted = "<hr>";
return converted;
}
Pattern olP = Pattern.compile("^[-|/*|/+] .*$");
Matcher olM = olP.matcher(line);
if(olM.find()) {
converted = "<li>" + olM.group().substring(2) + "</li>";
return converted;
}
Pattern ulP = Pattern.compile("^\\d\\. .*$");
Matcher ulM = ulP.matcher(line);
if(ulM.find()) {
int index = ulM.group().indexOf(" ");
converted = "<li>" + ulM.group().substring(index) + "</li>";
return converted;
}
return line;
}
private int listCheck(String line, int nowMode) {
int mode = 0;
Pattern olP = Pattern.compile("^[-|/*|/+] .*$");
Matcher olM = olP.matcher(line);
if(olM.find()) {
mode = 1;
}
Pattern ol2P = Pattern.compile("^ {2}[-|/*|/+] .*$");
Matcher ol2M = ol2P.matcher(line);
if(ol2M.find()) {
mode = 2;
}
Pattern ol4P = Pattern.compile("^ {4}[-|/*|/+] .*$");
Matcher ol4M = ol4P.matcher(line);
if(ol4M.find()) {
if(nowMode == 2) {
mode = 3;
} else {
mode = 2;
}
}
Pattern ol8P = Pattern.compile("^ {8}[-|/*|/+] .*$");
Matcher ol8M = ol8P.matcher(line);
if(ol8M.find()) {
mode = 3;
}
Pattern ulP = Pattern.compile("^\\d\\. .*$");
Matcher ulM = ulP.matcher(line);
if(ulM.find()) {
mode = 4;
}
Pattern ul2P = Pattern.compile("~ {2}\\d\\. .*$");
Matcher ul2M = ul2P.matcher(line);
if(ul2M.find()) {
mode = 5;
}
Pattern ul4P = Pattern.compile("^ {4}\\d\\. .*$");
Matcher ul4M = ul4P.matcher(line);
if(ul4M.find()) {
if(nowMode == 5) {
mode = 6;
} else {
mode = 5;
}
}
Pattern ul8P = Pattern.compile("^ {8}\\d\\. .*$");
Matcher ul8M = ul8P.matcher(line);
if(ul8M.find()) {
mode = 6;
}
return mode;
}
}
| true
|
d87140c55087670260cb77718dd3911df2f3788b
|
Java
|
cha63506/CompSecurity
|
/tinder-source/src/com/tinder/managers/ab$3.java
|
UTF-8
| 1,387
| 1.59375
| 2
|
[] |
no_license
|
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.tinder.managers;
import com.android.volley.NetworkResponse;
import com.android.volley.VolleyError;
import com.tinder.e.al;
import com.tinder.model.User;
// Referenced classes of package com.tinder.managers:
// ab
public final class c
implements com.android.volley.
{
final al a;
final User b;
final String c;
final ab d;
public final void a(VolleyError volleyerror)
{
if (volleyerror == null)
{
a.a(b);
return;
}
(new StringBuilder("superlike on ")).append(c).append(" FAILED ").append(volleyerror.getMessage());
if (volleyerror.a != null)
{
switch (volleyerror.a.a)
{
case 402:
default:
a.a(b);
return;
case 401:
a.b();
return;
case 403:
a.a();
break;
}
return;
} else
{
a.a(b);
return;
}
}
public Error(ab ab1, al al1, User user, String s)
{
d = ab1;
a = al1;
b = user;
c = s;
super();
}
}
| true
|
d53f75258cb42c5cea83d82e813a4c1ad13bb73b
|
Java
|
mehdi5256/Android_TunisiaTrip
|
/soatunisitatrip/app/src/main/java/android/mehdi/soatunisitatrip/SQLite/FavoriteContract.java
|
UTF-8
| 845
| 1.953125
| 2
|
[] |
no_license
|
package android.mehdi.soatunisitatrip.SQLite;
import android.provider.BaseColumns;
public class FavoriteContract {
public static final class FavoriteEntry implements BaseColumns{
public static final String TABLE_NAME = "favorite";
public static final String COLUMN_ATTRACTIONID = "attraction_id";
public static final String COLUMN_NOM = "attraction_name";
public static final String COLUMN_IMAGE = "attraction_image";
public static final String COLUMN_DESCRIPTION = "attraction_description";
public static final String COLUMN_SITEWEB = "attraction_siteweb";
public static final String COLUMN_EMAIL = "attraction_email";
public static final String COLUMN_TELEPHONE = "attraction_telephone";
public static final String COLUMN_ADRESSE = "attraction_adresse";
}
}
| true
|
bfbca6f5371ed73d28bc0b354e30da13333b3413
|
Java
|
C137leo/MyMeetUESTC
|
/app/src/main/java/cn/edu/uestc/meet_on_the_road_of_uestc/me/presenter/IPrenster.java
|
UTF-8
| 337
| 1.765625
| 2
|
[
"MIT"
] |
permissive
|
package cn.edu.uestc.meet_on_the_road_of_uestc.me.presenter;
import android.net.Uri;
import cn.edu.uestc.meet_on_the_road_of_uestc.me.view.IVew;
public interface IPrenster {
void getStuInfo();
void attchView(IVew iVew);
Uri isImageChange();
void drawFirstChartWithIPublish();
void drawSecondChartWithIAccept();
}
| true
|
3ace8a39c473dd74ac2cc4f0947aef58c8df608b
|
Java
|
thaisdalencar/random-picker
|
/src/main/java/br/com/agoravai/model/Participante.java
|
UTF-8
| 735
| 2.375
| 2
|
[] |
no_license
|
package br.com.agoravai.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity(name="PARTICIPANTES")
public class Participante {
@Id
@GeneratedValue
private Long id;
private String nome;
private int numero;
public Participante() {
}
public Participante(String nome, int numero) {
super();
this.nome = nome;
this.numero = numero;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public int getNumero() {
return numero;
}
public void setNumero(int numero) {
this.numero = numero;
}
}
| true
|
15ab3da8aee40137e054cd4fed68377326a26117
|
Java
|
BenMurrayTSI/LibraryOOPMaven
|
/src/main/java/com/softwareinstitute/training/murray/ben/Library.java
|
UTF-8
| 908
| 2.796875
| 3
|
[] |
no_license
|
package com.softwareinstitute.training.murray.ben;
import java.util.ArrayList;
import java.util.List;
public class Library {
List<LibraryItem> items = new ArrayList<>();
FantasyBook defaultFantasyBook = new FantasyBook();
BiographyBook defaultBiographyBook = new BiographyBook();
DocumentaryDVD defaultDocumentaryDVD = new DocumentaryDVD();
AnimationDVD defaultAnimationDVD = new AnimationDVD();
FantasyBook myFantasyBook = new FantasyBook("Two Towers", "Tolkien", "Paperback", 352);
DocumentaryDVD myDocumentaryDVD = new DocumentaryDVD("A", "B", "C", 4);
{
items.add(defaultFantasyBook);
items.add(defaultBiographyBook);
items.add(defaultDocumentaryDVD);
items.add(defaultAnimationDVD);
items.add(myFantasyBook);
items.add(myDocumentaryDVD);
}
public List<LibraryItem> getItems() {
return items;
}
}
| true
|
d10d66d1fbde614f00b5582b5619a31fa9bfdb22
|
Java
|
SimonaChiurato/2019-06-05-simulazione-JDK11
|
/src/main/java/it/polito/tdp/crimes/model/Vicino.java
|
UTF-8
| 691
| 2.703125
| 3
|
[] |
no_license
|
package it.polito.tdp.crimes.model;
public class Vicino implements Comparable<Vicino> {
private int distretto;
private double distanza;
public int getDistretto() {
return distretto;
}
public void setDistretto(int distretto) {
this.distretto = distretto;
}
public double getDistanza() {
return distanza;
}
public void setDistanza(double distanza) {
this.distanza = distanza;
}
public Vicino(int distretto, double distanza) {
super();
this.distretto = distretto;
this.distanza = distanza;
}
@Override
public int compareTo(Vicino o) {
// TODO Auto-generated method stub
return Double.compare(this.distanza, o.distanza);
}
}
| true
|
4933490c4693f241b163b8ddb4bd6b8ba9dfb941
|
Java
|
bleujin/craken
|
/test/net/ion/craken/node/crud/TestWalkReadChildren.java
|
UTF-8
| 3,778
| 2.421875
| 2
|
[] |
no_license
|
package net.ion.craken.node.crud;
import java.util.List;
import net.ion.craken.node.ReadNode;
import net.ion.craken.node.TransactionJob;
import net.ion.craken.node.WriteSession;
import net.ion.craken.node.crud.util.TraversalStrategy;
import net.ion.framework.util.Debug;
public class TestWalkReadChildren extends TestBaseCrud{
@Override
protected void setUp() throws Exception {
super.setUp();
session.tran(new TransactionJob<Void>() {
@Override
public Void handle(WriteSession wsession) throws Exception { // /gparent/parent/child1, /gparent/parent/child2
wsession.pathBy("/gparent").property("name", "gparent")
.child("parent1").property("name", "parent")
.child("child11").property("name", "child11").parent()
.child("child12").property("name", "child12")
.child("gchild").property("name", "gchild");
wsession.pathBy("/gparent")
.child("parent2").property("name", "parent2")
.child("child21").property("name", "child21").property("order", 1).parent()
.child("child22").property("name", "child22").property("order", 2)
.child("gchild").property("name", "gchild") ;
return null;
}
}) ;
}
public void testBreadthFirst() throws Exception {
List<ReadNode> list = session.pathBy("/gparent").walkChildren().strategy(TraversalStrategy.BreadthFirst).includeSelf(true).toList() ;
Debug.line(list);
assertEquals(9, list.size());
assertEquals("gparent", list.get(0).property("name").asString());
assertEquals("parent2", list.get(2).property("name").asString());
}
public void testDepthFirst() throws Exception {
long start = System.currentTimeMillis() ;
List<ReadNode> list = session.pathBy("/gparent").walkChildren().strategy(TraversalStrategy.DepthFirst).includeSelf(true).toList() ;
Debug.line(list);
assertEquals(9, list.size());
assertEquals("gparent", list.get(0).property("name").asString());
assertEquals("gchild", list.get(8).property("name").asString());
Debug.line(System.currentTimeMillis() - start );
}
public void testConnectWithFilter() throws Exception {
List<ReadNode> list = session.pathBy("/gparent").walkChildren().strategy(TraversalStrategy.BreadthFirst).includeSelf(false).in("name", "parent", "child1").toList() ;
assertEquals(1, list.size());
}
public void testSort() throws Exception {
session.pathBy("/gparent").walkChildren().strategy(TraversalStrategy.BreadthFirst).includeSelf(false).descending("order").debugPrint();
}
public void testEachNode() throws Exception {
session.pathBy("/gparent").walkChildren().strategy(TraversalStrategy.BreadthFirst).includeSelf(false).eq("name", "gchild").eachNode(new ReadChildrenEach<Void>() {
@Override
public Void handle(ReadChildrenIterator citer) {
while(citer.hasNext()){
Debug.line((WalkReadNode)citer.next());
}
return null;
}
}) ;
}
public void testEachTreeNode() throws Exception {
session.pathBy("/gparent").walkChildren().strategy(TraversalStrategy.BreadthFirst).includeSelf(false).in("name", "parent", "child1").asTreeChildren().eachTreeNode(new WalkChildrenEach<Void>() {
@Override
public Void handle(WalkChildrenIterator trc) {
for(WalkReadNode tnode : trc){
Debug.line(tnode);
}
return null;
}
}) ;
}
public void testReadChildrenIterator2ReadChildren() throws Exception {
session.pathBy("/gparent").walkChildren().strategy(TraversalStrategy.BreadthFirst).includeSelf(false).in("name", "parent", "child1").asTreeChildren().eachTreeNode(new WalkChildrenEach<Void>() {
@Override
public Void handle(WalkChildrenIterator trc) {
ReadChildren rc = trc.toReadChildren().startsWith("name", "child");
for(ReadNode tnode : rc){
Debug.line(tnode);
}
return null;
}
}) ;
}
}
| true
|
8f86726cf2f598d82450eeb726a0d1c2b4645a9c
|
Java
|
echirinosmayaudon/DAG-RICHIESTA-BADGE
|
/dag-intranet-20/modules/intranet-mef-siap-db/intranet-mef-siap-db-api/src/main/java/com/intranet/mef/job/siap/model/ProfilePictureFileBlobModel.java
|
UTF-8
| 1,449
| 1.789063
| 2
|
[] |
no_license
|
/**
* Copyright (c) 2000-present Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.intranet.mef.job.siap.model;
import aQute.bnd.annotation.ProviderType;
import java.sql.Blob;
/**
* The Blob model class for lazy loading the file column in ProfilePicture.
*
* @author Brian Wing Shun Chan
* @see ProfilePicture
* @generated
*/
@ProviderType
public class ProfilePictureFileBlobModel {
public ProfilePictureFileBlobModel() {
}
public ProfilePictureFileBlobModel(long personID) {
_personID = personID;
}
public ProfilePictureFileBlobModel(long personID, Blob fileBlob) {
_personID = personID;
_fileBlob = fileBlob;
}
public long getPersonID() {
return _personID;
}
public void setPersonID(long personID) {
_personID = personID;
}
public Blob getFileBlob() {
return _fileBlob;
}
public void setFileBlob(Blob fileBlob) {
_fileBlob = fileBlob;
}
private long _personID;
private Blob _fileBlob;
}
| true
|
466ca90c226127c627ac9d6e56505b0b1e2c04be
|
Java
|
hejunion/gwt-cx
|
/gwtcx/samples/sample-gxt-mgwt-basic-project/src/main/java/com/kiahu/sample/client/event/RevealAnimatableDisplayContentEvent.java
|
UTF-8
| 2,430
| 2.125
| 2
|
[] |
no_license
|
/**
* (C) Copyright 2012 Kiahu
*
* Licensed under the terms of the GNU General Public License version 3
* as published by the Free Software Foundation. You may obtain a copy of the
* License at: http://www.gnu.org/copyleft/gpl.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 com.kiahu.sample.client.event;
import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.event.shared.HasHandlers;
import com.googlecode.mgwt.mvp.client.Animation;
import com.gwtplatform.mvp.client.Presenter;
public class RevealAnimatableDisplayContentEvent extends
GwtEvent<RevealAnimatableDisplayContentEvent.RevealAnimatableDisplayContentHandler> {
public interface RevealAnimatableDisplayContentHandler extends EventHandler {
void onRevealAnimatableDisplayContent(
RevealAnimatableDisplayContentEvent event);
}
public interface RevealAnimatableDisplayContentHasHandlers extends HasHandlers {
HandlerRegistration addRevealAnimatableDisplayContentHandler(
RevealAnimatableDisplayContentHandler handler);
}
public static Type<RevealAnimatableDisplayContentHandler> TYPE = new Type<RevealAnimatableDisplayContentHandler>();
public static Type<RevealAnimatableDisplayContentHandler> getType() { return TYPE; }
public static void fire(HasHandlers source, Presenter<?, ?> content, Animation animation) {
source.fireEvent(new RevealAnimatableDisplayContentEvent(content, animation));
}
private Presenter<?,?> content;
private Animation animation;
public RevealAnimatableDisplayContentEvent(Presenter<?, ?> content,Animation animation) {
this.content = content;
this.animation=animation;
}
public Presenter<?, ?> getContent() {
return content;
}
public Animation getAnimation() {
return animation;
}
@Override
protected void dispatch(RevealAnimatableDisplayContentHandler handler) {
handler.onRevealAnimatableDisplayContent(this);
}
@Override
public Type<RevealAnimatableDisplayContentHandler> getAssociatedType() {
return getType();
}
}
| true
|
6c96f8abef706d697396b3f881dad18476f15c0c
|
Java
|
kroctus/PROYECTO-PARKING-Sindy-Gabriel
|
/src/main/java/reservas/ReservasVO.java
|
UTF-8
| 3,028
| 2.625
| 3
|
[] |
no_license
|
/*
* 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 reservas;
import clientes.ClienteDAO;
import clientes.ClienteVO;
import java.sql.Date;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author gabriel
*/
public class ReservasVO {
//Atributos de la clase
private String matricula;
private int numplaza;
private String pin_fijo;
private LocalDate feciniabono;
private LocalDate fecfinabono;
private double precio;
//Constructor por defecto
public ReservasVO() {
}
//Constructor parametrizado
public ReservasVO(String matricula, int numplaza, String pin_fijo, LocalDate feciniabono, LocalDate fecfinabono) throws SQLException {
this.matricula = matricula;
this.numplaza = numplaza;
this.pin_fijo = pin_fijo;
this.feciniabono = feciniabono;
this.fecfinabono = fecfinabono;
}
public ReservasVO(String matricula, int numplaza, String pin_fijo, LocalDate feciniabono, LocalDate fecfinabono, double precio) {
this.matricula = matricula;
this.numplaza = numplaza;
this.pin_fijo = pin_fijo;
this.feciniabono = feciniabono;
this.fecfinabono = fecfinabono;
this.precio = precio;
}
//Getters and setters
public String getMatricula() {
return matricula;
}
public void setMatricula(String matricula) {
this.matricula = matricula;
}
public int getNumplaza() {
return numplaza;
}
public void setNumplaza(int numplaza) {
this.numplaza = numplaza;
}
public String getPin_fijo() {
return pin_fijo;
}
public void setPin_fijo(String pin_fijo) {
this.pin_fijo = pin_fijo;
}
public LocalDate getFeciniabono() {
return feciniabono;
}
public void setFeciniabono(LocalDate feciniabono) {
this.feciniabono = feciniabono;
}
public LocalDate getFecfinabono() {
return fecfinabono;
}
public void setFecfinabono(LocalDate fecfinabono) {
this.fecfinabono = fecfinabono;
}
public double getPrecio() {
return precio;
}
public void setPrecio(double precio) {
this.precio = precio;
}
//ToString
@Override
public String toString() {
try {
return matricula + " : " + numplaza + " : " + pin_fijo + " : " + feciniabono + " : " + fecfinabono + " : " + Reservas.obtenerPrecio(matricula);
} catch (SQLException ex) {
Logger.getLogger(ReservasVO.class.getName()).log(Level.SEVERE, null, ex);
System.out.println(ex.getMessage());
}
return matricula + " : " + numplaza + " : " + pin_fijo + " : " + feciniabono + " : " + fecfinabono + " : " + precio;
}
}
| true
|
4a33e293aa7168d440fc66ef56ab35d34f21cc21
|
Java
|
BeyzaReyhan/VerteilteAnwendungen
|
/a02/Berechne.java
|
UTF-8
| 211
| 2.828125
| 3
|
[] |
no_license
|
package a02;
public class Berechne extends Thread {
F function;
int n;
public Berechne(F _f, int _n) {
this.function = _f;
this.n = _n;
}
public void run() {
System.out.println(function.f(n));
}
}
| true
|
16405878d77991574a13235d57b04d321f62101d
|
Java
|
EndPointCorp/com.endpoint.lg.support
|
/src/main/test/com/endpoint/lg/support/domain/streetview/TestStreetviewPov.java
|
UTF-8
| 3,335
| 2.28125
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright (C) 2014 Google Inc.
* Copyright (C) 2015 End Point Corporation
*
* 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.endpoint.lg.support.domain.streetview;
import static org.junit.Assert.*;
import interactivespaces.util.data.json.JsonBuilder;
import interactivespaces.util.data.json.JsonNavigator;
import java.util.Map;
import org.junit.Test;
import org.junit.BeforeClass;
import com.endpoint.lg.support.domain.streetview.StreetviewPov;
/**
* Test a <code>StreetviewPov</code>.
*
* @author Matt Vollrath <matt@endpoint.com>
*/
public class TestStreetviewPov {
private static final double TEST_HEADING = 98.5;
private static final double TEST_PITCH = 23.42;
private static final double OTHER_HEADING = 205;
private static final double OTHER_PITCH = -50.1111;
private static StreetviewPov pov;
@BeforeClass
public static void setup() {
pov = new StreetviewPov(TEST_HEADING, TEST_PITCH);
}
/**
* Test read access.
*/
@Test
public void testGetters() {
assertEquals(TEST_HEADING, pov.getHeading(), 0);
assertEquals(TEST_PITCH, pov.getPitch(), 0);
}
/**
* Test write methods.
*/
@Test
public void testSetters() {
StreetviewPov shifty = new StreetviewPov(TEST_HEADING, TEST_PITCH);
shifty.setAll(OTHER_HEADING, OTHER_PITCH);
assertEquals(OTHER_HEADING, shifty.getHeading(), 0);
assertEquals(OTHER_PITCH, shifty.getPitch(), 0);
}
/**
* Test comparisons.
*/
@Test
public void testComparison() {
StreetviewPov same = new StreetviewPov(TEST_HEADING, TEST_PITCH);
StreetviewPov different = new StreetviewPov(OTHER_HEADING, OTHER_PITCH);
assertTrue(pov.equals(same));
assertTrue(same.equals(pov));
assertFalse(pov.equals(different));
assertFalse(different.equals(pov));
assertFalse(same.equals(different));
assertFalse(different.equals(same));
}
/**
* Test POV translation.
*/
@Test
public void testTranslation() {
StreetviewPov translating = new StreetviewPov(TEST_HEADING, TEST_PITCH);
translating.translate(OTHER_HEADING, OTHER_PITCH);
assertEquals(TEST_HEADING + OTHER_HEADING, translating.getHeading(), 0);
assertEquals(TEST_PITCH + OTHER_PITCH, translating.getPitch(), 0);
}
/**
* Test serialization and deserialization.
*/
@Test
public void testSerialization() {
JsonBuilder deserialized = pov.getJsonBuilder();
Map<String, Object> data = deserialized.build();
assertEquals(pov.getMap(), data);
JsonNavigator message = new JsonNavigator(data);
StreetviewPov reconstructed = new StreetviewPov(message);
assertEquals(pov.getHeading(), reconstructed.getHeading(), 0);
assertEquals(pov.getPitch(), reconstructed.getPitch(), 0);
assertEquals(pov.getMap(), reconstructed.getMap());
}
}
| true
|
7ce01184e82002a2ab7e41999345b12dddee0089
|
Java
|
bigstar18/prjs
|
/prj/bigdata/tool-hadoop/src/main/java/org/hxx/hadoop/stat/GenerateInfo.java
|
UTF-8
| 374
| 1.828125
| 2
|
[] |
no_license
|
package org.hxx.hadoop.stat;
public class GenerateInfo {
public long start = 0;
public long end = 0;
public String endTime = "";
public long generate = 0;
public String table = "";
@Override
public String toString() {
return endTime + ": generate: table=" + table + ", generate=" + generate + " timeused=" + (end - start) / 1000
+ "s.";
}
}
| true
|
1275f396dbf5272192a369dc1c9e1c4cef655110
|
Java
|
ingluisespinel/SpringBootConsumeSOAP
|
/src/main/java/com/lhespinel/springboot/demo_consume_soap/DemoConsumeSoapApplication.java
|
UTF-8
| 353
| 1.640625
| 2
|
[] |
no_license
|
package com.lhespinel.springboot.demo_consume_soap;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoConsumeSoapApplication {
public static void main(String[] args) {
SpringApplication.run(DemoConsumeSoapApplication.class, args);
}
}
| true
|
d4ccdc7f6d4e41990631295562a198436f5778c0
|
Java
|
linxueyi2230/LifeHelper
|
/app/src/main/java/com/study/yang/lifehelper/defineview/RecordNameEditText.java
|
UTF-8
| 3,068
| 2.09375
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* 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.study.yang.lifehelper.defineview;
import android.content.Context;
import android.graphics.Rect;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import com.study.yang.lifehelper.R;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class RecordNameEditText extends EditText {
private Context mContext;
private InputMethodManager mInputMethodManager;
private String mDir;
private String mExtension;
public RecordNameEditText(Context context) {
super(context, null);
init(context);
}
public RecordNameEditText(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public RecordNameEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
private void init(Context context) {
mContext = context;
mInputMethodManager = (InputMethodManager) context
.getSystemService(Context.INPUT_METHOD_SERVICE);
}
public void initFileName(String dir, String extension, boolean englishOnly) {
mDir = dir;
mExtension = extension;
// 默认使用中文
if (!englishOnly) {
setText(getProperFileName(mContext.getString(R.string.default_record_name)));
} else {
SimpleDateFormat dataFormat = new SimpleDateFormat("MMddHHmmss");
setText(getProperFileName("rec_" + dataFormat.format(Calendar.getInstance().getTime())));
}
}
//判断存储路径下是否存在该文件,从而达到初始化的目的
private String getProperFileName(String name) {
String uniqueName = name;
if (isFileExisted(uniqueName)) {
int i = 2;
while (true) {
String temp = uniqueName + "(" + i + ")";
if (!isFileExisted(temp)) {
uniqueName = temp;
break;
}
i++;
}
}
return uniqueName;
}
private boolean isFileExisted(String name) {
String fullName = mDir + "/" + name.trim() + mExtension;
File file = new File(fullName);
return file.exists();
}
}
| true
|
eef991dc9582f468455dd39835b3f374889f0115
|
Java
|
kineta-Jiang/ont-sourcing
|
/src/test/java/com/ontology/sourcing/WalletTests01.java
|
UTF-8
| 5,530
| 2.046875
| 2
|
[
"MIT"
] |
permissive
|
package com.ontology.sourcing;
import com.github.ontio.common.Helper;
import com.github.ontio.crypto.MnemonicCode;
import com.github.ontio.crypto.SignatureScheme;
import com.github.ontio.sdk.wallet.Account;
import com.ontology.sourcing.service.util.ChainService;
import com.ontology.sourcing.util.GlobalVariable;
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.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Base64;
@RunWith(SpringRunner.class)
@SpringBootTest
@TestPropertySource(locations="file:/Volumes/Data/_work/201802_Ontology/ONTSouring/ont-sourcing/config/application-local.properties")
public class WalletTests01 {
//
@Autowired
ChainService chainService;
// 付款的数字钱包
private com.github.ontio.account.Account payerAccount = GlobalVariable.getInstanceOfAccount("6a62d116e416246f974229eee7d1b0894d8c2ab70446856e85e35b7f5d37adef");
/**
* 通过 Mnemonic phrase 创建钱包账户
*/
@Test
public void example01() {
//generate Mnemonic Code
String code = MnemonicCode.generateMnemonicCodesStr();
System.out.println(code);
// finger kitchen always promote torch section enough worth cigar ritual boost thought
}
@Test
public void example02() throws Exception {
String code = "finger kitchen always promote torch section enough worth cigar ritual boost thought";
// getRecord private key from Mnemonic Code
byte[] prikeyb = MnemonicCode.getPrikeyFromMnemonicCodesStrBip44(code);
String prikey = Helper.toHexString(prikeyb);
System.out.println(prikey);
// 0fb11f6ece9b9cba55936965c0eef8c15819bc74d7588c1feb3217b8948e1854
}
// TODO 反过来由私钥能推出助记词吗?
// 同一个 私钥,创建出来的 codeAddr 和 publicKey 都一样
// passphrase 通过 getGcmDecodedPrivateKey 得到 私钥
@Test
public void example03_1() throws Exception {
//
String passphrase = "123456";
String prikey = "0fb11f6ece9b9cba55936965c0eef8c15819bc74d7588c1feb3217b8948e1854";
String label = "test_label_01";
//
Account acct = chainService.ontSdk.getWalletMgr().createAccountFromPriKey(label, passphrase, prikey);
System.out.println(acct);
/*
{
"codeAddr":"ALcwsJqdFyPr4sd1bnS5bdnaBYDgfmCsBd",
"algorithm":"ECDSA",
"enc-alg":"aes-256-gcm",
"hash":"sha256",
"isDefault":false,
"key":"YfM2prI920MhudiqFvkJPb9pzq1iDHi8pe1i+rhEdcTAVvJ1OLo+xUDDuIgvZz/M",
"label":"test_label_01",
"lock":false,
"parameters":{
"curve":"P-256"
},
"publicKey":"03088ae9cc9116e49e8c1b5b712b75e18c7d65e520cbc199d26d1765732a547e14",
"salt":"wvvZ52UxshLbQ0+MwAlT7g==",
"signatureScheme":"SHA256withECDSA"
}
*/
// 再次运行
/*
{
"codeAddr":"ALcwsJqdFyPr4sd1bnS5bdnaBYDgfmCsBd",
"algorithm":"ECDSA",
"enc-alg":"aes-256-gcm",
"hash":"sha256",
"isDefault":false,
"key":"27NFnZoQ9X1lCJK/shBNj3VgFK2dqRbfLGtWldEsrxBaIwv3mmXgWG7BBVqNhQB8",
"label":"test_label_01",
"lock":false,
"parameters":{
"curve":"P-256"
},
"publicKey":"03088ae9cc9116e49e8c1b5b712b75e18c7d65e520cbc199d26d1765732a547e14",
"salt":"DmXuwvZbtZA2Xq1jINb27g==",
"signatureScheme":"SHA256withECDSA"
}
*/
}
@Test
public void example03_2() throws Exception {
//
String passphrase = "654321";
String prikey = "0fb11f6ece9b9cba55936965c0eef8c15819bc74d7588c1feb3217b8948e1854";
String label = "test_label_01";
//
Account acct = chainService.ontSdk.getWalletMgr().createAccountFromPriKey(label, passphrase, prikey);
System.out.println(acct);
/*
{
"codeAddr":"ALcwsJqdFyPr4sd1bnS5bdnaBYDgfmCsBd",
"algorithm":"ECDSA",
"enc-alg":"aes-256-gcm",
"hash":"sha256",
"isDefault":false,
"key":"B7axc/9hQD6taeRopEIPxF8QKggmmnhpbLwTXHl+10ifm1zdEqN5aP37dkhcWLLP",
"label":"test_label_01",
"lock":false,
"parameters":{
"curve":"P-256"
},
"publicKey":"03088ae9cc9116e49e8c1b5b712b75e18c7d65e520cbc199d26d1765732a547e14",
"salt":"sLyWi3xAOF0jW8itMdAfGQ==",
"signatureScheme":"SHA256withECDSA"
}
*/
}
@Test
public void example04() throws Exception {
/*
String encryptedPrikey = "YfM2prI920MhudiqFvkJPb9pzq1iDHi8pe1i+rhEdcTAVvJ1OLo+xUDDuIgvZz/M";
String passphrase = "123456";
String saltStr = "wvvZ52UxshLbQ0+MwAlT7g==";
String codeAddr = "ALcwsJqdFyPr4sd1bnS5bdnaBYDgfmCsBd";
*/
/*
String encryptedPrikey = "B7axc/9hQD6taeRopEIPxF8QKggmmnhpbLwTXHl+10ifm1zdEqN5aP37dkhcWLLP";
String passphrase = "654321";
String saltStr = "sLyWi3xAOF0jW8itMdAfGQ==";
String codeAddr = "ALcwsJqdFyPr4sd1bnS5bdnaBYDgfmCsBd";
*/
String encryptedPrikey = "BXsX1+P+t1+5RMEe0nRYacE8aynm+9hpyJwkMu41uTCRRe4FBPPh4l2uI+ATC/Pf";
String passphrase = "123456";
String saltStr = "40QV2Qf2T1tDNs+1aEY3BQ==";
String address = "AGbL9NGxBosqRxiD34ZXPHigeti5AZBnfP";
//
String prikey = getPrivateKey(encryptedPrikey, passphrase, saltStr, address);
//
System.out.println(prikey);
}
private String getPrivateKey(String encryptedPrikey, String passphrase, String saltStr, String address) throws Exception {
//
byte[] salt = Base64.getDecoder().decode(saltStr);
//
String privateKey = com.github.ontio.account.Account.getGcmDecodedPrivateKey(encryptedPrikey, passphrase, address, salt, 16384, SignatureScheme.SHA256WITHECDSA);
//
return privateKey;
}
@Test
public void example05() {
//
Account account = chainService.ontSdk.getWalletMgr().getWallet().getAccount("ALcwsJqdFyPr4sd1bnS5bdnaBYDgfmCsBd");
System.out.println(account);
// null
// 因为 chainService.ontSdk 没有设置 钱包文件,之前的操作都没有写入 钱包文件
}
}
| true
|
51442fc81fad551009b6e113f3e8cde0ed9a0ffc
|
Java
|
posii88/CTS
|
/Chain of responsability-joc/src/ro/ase/cts/chain/clase/ChainAbstract.java
|
UTF-8
| 315
| 2.28125
| 2
|
[] |
no_license
|
package ro.ase.cts.chain.clase;
public abstract class ChainAbstract {
ChainAbstract next;
String numeModul;
public ChainAbstract(String numeModul) {
super();
this.numeModul = numeModul;
}
public void setNext(ChainAbstract next) {
this.next = next;
}
public abstract void procesareMesaj(Mesaj mesaj) ;
}
| true
|
6864e4454ddd664af25a5e9cbb6f2254c99f18be
|
Java
|
LukasJuodeika/snake
|
/src/main/java/lt/ktu/zalciai/food/entities/PowerupWall.java
|
UTF-8
| 424
| 2.578125
| 3
|
[] |
no_license
|
package lt.ktu.zalciai.food.entities;
import lt.ktu.zalciai.collision.CollisionStrategy;
import java.awt.*;
public class PowerupWall extends Food {
public PowerupWall(Point point) {
super(point);
this.strategy = CollisionStrategy.ignoreWall();
}
@Override
public int getScore() {
return 2;
}
@Override
public String getColorHex() {
return "#00AA00";
}
}
| true
|
0e0e841524f9c288b84f0c12cf541e93a0765b7d
|
Java
|
MrJiangZM/cloud-project
|
/cloud-consumer-order80-feign/src/main/java/com/ming/blog/Order80Feign.java
|
UTF-8
| 573
| 1.578125
| 2
|
[] |
no_license
|
package com.ming.blog;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
/**
* @author MrJiangZM
* @date 2021/3/8 14:07
*/
@SpringBootApplication
@EnableFeignClients
@Slf4j
@EnableEurekaClient
public class Order80Feign {
public static void main(String[] args) {
SpringApplication.run(Order80Feign.class, args);
}
}
| true
|
cdcca9f20b6abaf439c20784f2d27ca9b684b7dd
|
Java
|
gsmalves/FeiraGugou
|
/src/Model/Aparicao.java
|
UTF-8
| 3,510
| 3.28125
| 3
|
[] |
no_license
|
/*****************************************************************************************
Autores: Johnny Quest Dantas Pereira, Gustavo dos Santos Menezes Alves
Componente Curricular: MI-Programação
Concluido em: 27/06/2018
Declaramos que este código foi elaborado por nós de forma individual e não contém nenhum
trecho de código de outro colega ou de outro autor, tais como provindos de livros e
apostilas, e páginas ou documentos eletrônicos da Internet. Qualquer trecho de código
de outra autoria que não a minha está destacado com uma citação para o autor e a fonte
do código, e estou ciente que estes trechos não serão considerados para fins de avaliação.
******************************************************************************************/
package Model;
import java.io.Serializable;
/**
* Toda Palavra possui uma árvore de objetos desse tipo, que possui referencia pra um arquivo e
* uma quantidade de vezes que tal palavra aparece nele.
* @authors Johnny e Gustavo
*/
public class Aparicao implements Comparable, Serializable{
private final Arquivo file;
private int qtVezes;
/**
* @param file Arquivo que essa aparição representará.
*/
public Aparicao(Arquivo file){
this.file = file;
}
/**
* Compara duas Aparições a partir da ordem alfabética.
* @param t Aparição a ser comparada.
* @return um número negativo caso essa Aparição deva vir "antes" da recebida, um número positivo
* caso contrário e 0 caso sejam iguais.
*/
@Override
public int compareTo(Object t) {
Aparicao temp = (Aparicao) t;
String a = file.getName();
String b = temp.getFile().getName();
return a.compareTo(b);
}
/**
* Compara duas Aparições a partir da quantidade de vezes que a palavra aparece no arquivo.
* @param a Aparição a ser comparada.
* @return um número negativo caso essa Aparição deva vir "antes" da recebida, um número positivo
* caso contrário e 0 caso tenham a mesma quantidade de vezes.
*/
public int compareToQtVezes(Aparicao a){
return qtVezes - a.getQtVezes();
}
/**
* @return quantidade de vezes que a palavra que possui essa Aparição aparece no arquivo que essa
* Aparição representa.
*/
public int getQtVezes() {
return qtVezes;
}
/**
* Soma em 1 a quantidade de vezes que a palavra que possui essa Aparicao aparece nesse arquivo.
*/
public void somaVezes(){
qtVezes++;
}
/**
* @return Uma string com o nome do arquivo e quantas vezes a palavra que possui essa Aparicao
* aparece nesse arquivo.
*/
@Override
public String toString(){
return file.getPath() + "\n\taparece " + qtVezes + " vezes.";
}
/**
* Verifica se duas Aparicoes são iguais a partir do nome dos seus arquivos.
* @param a Aparição a ser comparada.
* @return True caso sejam iguais, false caso contrário.
*/
@Override
public boolean equals(Object a){
Aparicao temp = (Aparicao) a;
return this.file.equals(temp.getFile());
}
/**
* @return O arquivo que esse objeto representa.
*/
public Arquivo getFile() {
return file;
}
/**
* Zera a quantidade de vezes que a palavra que possui essa aparição aparece no arquivo
* que essa aparição representa.
*/
public void zeraVezes() {
qtVezes = 0;
}
}
| true
|
f540b4ea7d963acc47218cbb4d5cde52881939d7
|
Java
|
Dangnh13/SpringBatchLearning
|
/src/main/java/com/springbatch/SpringBatchLearning/job/multiplelinefile/MultipleLineFileWriterConfig.java
|
UTF-8
| 427
| 2.1875
| 2
|
[] |
no_license
|
package com.springbatch.SpringBatchLearning.job.multiplelinefile;
import org.springframework.batch.item.ItemWriter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MultipleLineFileWriterConfig {
@Bean
public ItemWriter<Object> multipleLineFileWriter() {
return items -> items.forEach(System.out::println);
}
}
| true
|
3a998ec4228a3ff92ea9d7eb6552731f331f21f6
|
Java
|
tamirhassan/pdfxtk
|
/src/com/tamirhassan/pdfxtk/model/CharSegment.java
|
UTF-8
| 5,706
| 2.3125
| 2
|
[
"Apache-2.0"
] |
permissive
|
/**
* pdfXtk - PDF Extraction Toolkit
* Copyright (c) by the authors/contributors. All rights reserved.
* This project includes code from PDFBox and TouchGraph.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the names pdfXtk or PDF Extraction Toolkit; nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* http://pdfxtk.sourceforge.net
*
*/
package com.tamirhassan.pdfxtk.model;
import java.util.List;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.text.TextPosition;
import com.tamirhassan.pdfxtk.utils.Utils;
/**
* Text fragment element; represents a single character
* This class is identical in functionality to TextFragment!
* ... however, does not extend it in order to allow typing
* of lists ...
*
* @author Tamir Hassan, pdfanalyser@tamirhassan.com
* @version PDF Analyser 0.9
*/
public class CharSegment extends TextSegment
{
boolean overprint = false;
protected OpTuple sourceOp;
/**
* Constructor.
*
* @param x1 The x1 coordinate of the segment.
* @param x2 The x2 coordinate of the segment.
* @param y1 The y1 coordinate of the segment.
* @param y2 The y2 coordinate of the segment.
* @param text The textual contents of the segment.
* @param font The (main) font of the segment.
* @param fontSize The (main) font size in the segment.
*/
public CharSegment(
float x1,
float x2,
float y1,
float y2,
String text,
String fontName,
float fontSize
)
{
super(x1, x2, y1, y2, text, fontName, fontSize);
}
public CharSegment(
float x1,
float x2,
float y1,
float y2,
String text,
PDFont font,
float fontSize,
OpTuple sourceOp
)
{
super(x1, x2, y1, y2, text, Utils.findFontName(font), fontSize);
this.sourceOp = sourceOp;
}
public CharSegment(
float x1,
float x2,
float y1,
float y2
)
{
super(x1, x2, y1, y2);
}
// not in current use (I think) -- WRONG
// now by default sets level to zero (primitive)
public CharSegment(TextPosition tPos) {
super(tPos.getX(),
tPos.getX() + (tPos.getWidth()),
tPos.getY(),
tPos.getY() + (tPos.getFontSize() * tPos.getYScale()),
// tPos.getCharacter(),
tPos.getUnicode(),
// tPos.getFont().getBaseFont(),
Utils.findFontName(tPos.getFont()),
tPos.getFontSize() * tPos.getYScale());
// todo: trim the name of the font
// String fontName = tPos.getFont().getBaseFont();
String fontName = tPos.getFont().getFontDescriptor().getFontName();
}
/**
* This will create a TextFragment object from a TextPosition object.
* As of PDFBox 0.7.2, this is the method currently in use, which
* converts co-ordinates back to the original system.
*
* @param tPos - the TextPosition object; pageDim - page dimensions in order to
* convert co-ordinates
* @return The new TextFragment object
*/
public CharSegment(TextPosition tPos, GenericSegment pageDim)
{
super(tPos.getX(),
tPos.getX() + tPos.getWidth(),
pageDim.getY2() - tPos.getY(),
pageDim.getY2() - tPos.getY() + (tPos.getFontSize() * tPos.getYScale()),
// tPos.getCharacter(),
tPos.getUnicode(),
// tPos.getFont().getBaseFont(),
Utils.findFontName(tPos.getFont()),
tPos.getFontSize() * tPos.getYScale());
}
@Override
public List<AttributeTuple> getAttributes() {
List<AttributeTuple> attributeList = super.getAttributes();
if (sourceOp != null)
{
attributeList.add(new AttributeTuple("opindex", sourceOp.getOpIndex()));
attributeList.add(new AttributeTuple("argindex", sourceOp.getArgIndex()));
}
return attributeList;
}
public boolean isOverprint() {
return overprint;
}
public void setOverprint(boolean overprint) {
this.overprint = overprint;
}
public OpTuple getSourceOp() {
return sourceOp;
}
public void setSourceOp(OpTuple sourceOp) {
this.sourceOp = sourceOp;
}
}
| true
|
07d2d945c4c6e0534975332a34ba4a24e2184099
|
Java
|
divya0792/info-5100
|
/Assignment5/DessertShop/DessertItem.java
|
UTF-8
| 452
| 2.9375
| 3
|
[] |
no_license
|
package DessertShop;
public abstract class DessertItem {
private String name;
public DessertItem() {
}
public DessertItem(String name) {
if(name.length() > DessertShoppe.MAXIMUM_ITEM_NAME_SIZE) {
throw new IllegalArgumentException("name is greater than the limit");
}
this.name = name;
}
protected final String getName() {
return name;
}
public abstract int getCost();
}
| true
|
1d39e0dc02ddaadfb9487b22b6367c94ad2eb19a
|
Java
|
sgros/activity_flow_plugin
|
/TestApplications/TF-BETA-THERMATK-v5.7.1/DecompiledCode/JADX/src/main/java/org/telegram/p004ui/Components/C4038-$$Lambda$EmojiView$GifSearchAdapter$rB6iGH2IIIWpfXKf_CfIBRZyOE8.java
|
UTF-8
| 900
| 1.546875
| 2
|
[] |
no_license
|
package org.telegram.p004ui.Components;
import org.telegram.p004ui.Components.EmojiView.GifSearchAdapter;
import org.telegram.tgnet.RequestDelegate;
import org.telegram.tgnet.TLObject;
import org.telegram.tgnet.TLRPC.TL_error;
/* compiled from: lambda */
/* renamed from: org.telegram.ui.Components.-$$Lambda$EmojiView$GifSearchAdapter$rB6iGH2IIIWpfXKf_CfIBRZyOE8 */
public final /* synthetic */ class C4038-$$Lambda$EmojiView$GifSearchAdapter$rB6iGH2IIIWpfXKf_CfIBRZyOE8 implements RequestDelegate {
private final /* synthetic */ GifSearchAdapter f$0;
public /* synthetic */ C4038-$$Lambda$EmojiView$GifSearchAdapter$rB6iGH2IIIWpfXKf_CfIBRZyOE8(GifSearchAdapter gifSearchAdapter) {
this.f$0 = gifSearchAdapter;
}
public final void run(TLObject tLObject, TL_error tL_error) {
this.f$0.lambda$searchBotUser$1$EmojiView$GifSearchAdapter(tLObject, tL_error);
}
}
| true
|
0f94e110eb2fa74ff4db6cc4491a2ea4f5404021
|
Java
|
soon14/lottery-1
|
/lottery-service/src/main/java/com/oruit/app/service/PhonePageService.java
|
UTF-8
| 1,350
| 1.890625
| 2
|
[] |
no_license
|
package com.oruit.app.service;/**
* Created by wyt on 2017/9/1.
*/
import com.oruit.app.util.web.ResultBean;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.Map;
/**
* @author
* @create 2017-09-01 15:08
*/
public interface PhonePageService {
/**
* 浏览器端手机号注册领取红包
* @param request
* @return
*/
ResultBean PhonePageRegister(HttpServletRequest request) throws ParseException;
/**
* 浏览器端快乐十分选号
* @param request
* @return
*/
ResultBean BrowserChoose(HttpServletRequest request) throws ParseException;
/**
* 顶部开奖信息
* @param request
* @return
*/
ResultBean TopWinInfoH5(HttpServletRequest request);
/**
* 推广页获取期号
* @param request
* @return
*/
ResultBean getIssueno(HttpServletRequest request);
/**
* h5导流
* @param request
* @return
*/
ResultBean H5Guide(HttpServletRequest request) throws ParseException;
/**
* h5导流
* @param request
* @return
*/
ResultBean H5GuideSSQ(HttpServletRequest request) throws Exception;
/**
* h5是否绑定
* @param params
* @return
*/
ResultBean BangdingH5(Map<String, Object> params);
}
| true
|
a6dd41a25a7f0aba53a19666564e8e54f31bc15e
|
Java
|
ahdahddl/cytoscape
|
/core3/api/branches/user-beta1/model-api/src/main/java/org/cytoscape/model/events/TableTitleChangedEvent.java
|
UTF-8
| 426
| 2.3125
| 2
|
[] |
no_license
|
package org.cytoscape.model.events;
import org.cytoscape.event.AbstractCyEvent;
import org.cytoscape.model.CyTable;
public final class TableTitleChangedEvent extends AbstractCyEvent<CyTable> {
private String oldTitle;
public TableTitleChangedEvent(CyTable source, String oldTitle) {
super(source, TableTitleChangedListener.class);
this.oldTitle = oldTitle;
}
public String getOldTitle(){
return oldTitle;
}
}
| true
|
0ad397769bf2a894a2971e9195f42c1cca331dc0
|
Java
|
mah88/sfc-orchestrator
|
/src/main/java/org/project/sfc/com/MonitoringAgent/MonitoringEngine.java
|
UTF-8
| 7,666
| 1.648438
| 2
|
[] |
no_license
|
package org.project.sfc.com.MonitoringAgent;
import org.openbaton.catalogue.mano.common.AutoScalePolicy;
import org.openbaton.catalogue.mano.common.ScalingAlarm;
import org.openbaton.catalogue.mano.descriptor.VirtualDeploymentUnit;
import org.openbaton.catalogue.mano.record.VNFCInstance;
import org.openbaton.catalogue.mano.record.VirtualNetworkFunctionRecord;
import org.openbaton.catalogue.nfvo.Item;
import org.openbaton.catalogue.nfvo.Server;
import org.openbaton.catalogue.nfvo.VimInstance;
import org.openbaton.exceptions.MonitoringException;
import org.openbaton.exceptions.NotFoundException;
import org.openbaton.exceptions.VimDriverException;
import org.openbaton.monitoring.interfaces.MonitoringPlugin;
import org.openbaton.monitoring.interfaces.MonitoringPluginCaller;
import org.openbaton.plugin.utils.RabbitPluginBroker;
import org.openbaton.sdk.NFVORequestor;
import org.openbaton.sdk.api.exception.SDKException;
import org.openbaton.vim.drivers.VimDriverCaller;
import org.project.sfc.com.openbaton_nfvo.configurations.NfvoConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Scope;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import org.openbaton.vim.drivers.interfaces.VimDriver;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeoutException;
import org.openbaton.catalogue.security.Project;
/**
* Created by mah on 11/7/16.
*/
@Service
@Scope("singleton")
public class MonitoringEngine {
protected Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired private ConfigurableApplicationContext context;
private String projectId;
private MonitoringPlugin monitor;
private VimDriver Vim;
@Autowired private Environment env;
private NFVORequestor requestor;
@Autowired private NfvoConfiguration configuration;
private MonitoringManager monitoringManager;
public void initializeMonitor() throws NotFoundException {
log.debug("[Initialize Monitoring Engine]");
try {
this.monitor = new MonitoringPluginCaller("zabbix", "zabbix-plugin");
} catch (TimeoutException e) {
log.error(e.getMessage(), e);
} catch (NotFoundException e) {
log.error(e.getMessage(), e);
throw e;
} catch (IOException e) {
log.error(e.getMessage(), e);
}
//log.debug("MonitoringPluginCaller obtained");
/* (MonitoringPluginCaller)
((RabbitPluginBroker) context.getBean(RabbitPluginBroker.class))
.getMonitoringPluginCaller(
env.getProperty("spring.rabbitmq.host"),
env.getProperty("spring.rabbitmq.username"),
env.getProperty("spring.rabbitmq.password"),
Integer.parseInt(env.getProperty("spring.rabbitmq.port")),
"zabbix-plugin",
"zabbix",
env.getProperty("SFCO.rabbitmq.management.port"));*/
if (monitor == null) {
log.warn("MonitoringTask: Monitor was not found. Cannot start Monitoring...");
}
}
public void initializeVimDriver() throws NotFoundException, SDKException, ClassNotFoundException {
System.out.print("[Initialize VimDriver]");
try {
this.Vim = new VimDriverCaller("openstack");
} catch (TimeoutException e) {
log.error(e.getMessage(), e);
} catch (NotFoundException e) {
log.error(e.getMessage(), e);
throw e;
} catch (IOException e) {
log.error(e.getMessage(), e);
}
log.debug("VimDriverCaller obtained");
this.requestor =
new NFVORequestor(
configuration.getUsername(),
configuration.getPassword(),
null,
false,
configuration.getIP(),
configuration.getPort(),
"1");
/* (MonitoringPluginCaller)
((RabbitPluginBroker) context.getBean(RabbitPluginBroker.class))
.getMonitoringPluginCaller(
env.getProperty("spring.rabbitmq.host"),
env.getProperty("spring.rabbitmq.username"),
env.getProperty("spring.rabbitmq.password"),
Integer.parseInt(env.getProperty("spring.rabbitmq.port")),
"zabbix-plugin",
"zabbix",
env.getProperty("SFCO.rabbitmq.management.port"));*/
setProjectId();
if (Vim == null) {
log.warn("VimDriverTask: Vim was not found. Cannot get Info about VNF instances Location...");
}
}
private void setProjectId() throws ClassNotFoundException, SDKException {
if (projectId == null || projectId.isEmpty()) {
log.debug("Trying to connect to the NFVO...");
List<Project> projects = requestor.getProjectAgent().findAll();
log.debug("found " + projects.size() + " projects");
for (Project project : projects) {
if (project.getName().equals("default")) {
projectId = project.getId();
}
}
if (projectId == null) throw new SDKException("Project not found");
requestor.setProjectId(projectId);
}
}
public List<Item> getRawMeasurementResults(
VirtualNetworkFunctionRecord vnfr, String metric, String period)
throws MonitoringException, NotFoundException {
if (monitor == null) {
log.warn("Monitor is null then Initialize Monitoring Engine");
initializeMonitor();
}
ArrayList<Item> measurementResults = new ArrayList<Item>();
ArrayList<String> hostnames = new ArrayList<String>();
ArrayList<String> metrics = new ArrayList<String>();
metrics.add(metric);
log.debug(
"Getting all measurement results for vnfr " + vnfr.getId() + " on metric " + metric + ".");
for (VirtualDeploymentUnit vdu : vnfr.getVdu()) {
for (VNFCInstance vnfcInstance : vdu.getVnfc_instance()) {
if (vnfcInstance.getState() == null
|| vnfcInstance.getState().toLowerCase().equals("active")) {
hostnames.add(vnfcInstance.getHostname());
}
}
}
log.debug(
"Getting all measurement results for hostnames "
+ hostnames
+ " on metric "
+ metric
+ ".");
measurementResults.addAll(monitor.queryPMJob(hostnames, metrics, period));
log.debug(
"Got all measurement results for vnfr "
+ vnfr.getId()
+ " on metric "
+ metric
+ " -> "
+ measurementResults
+ ".");
return measurementResults;
}
public String getLocation(String vnf_instance_name)
throws NotFoundException, ClassNotFoundException, SDKException, VimDriverException {
if (Vim == null) {
log.warn("VimDriver is null then Initialize Monitoring Engine");
initializeVimDriver();
}
String Location = "";
// System.out.print("PROJECT ID is"+ requestor.getProjectId());
List<VimInstance> VimInstances = requestor.getVimInstanceAgent().findAll();
for (VimInstance Vim_instance : VimInstances) {
List<Server> VNF_instances = Vim.listServer(Vim_instance);
for (Server VNF_instance : VNF_instances) {
if (VNF_instance.getName().equals(vnf_instance_name)) {
if (VNF_instance.getHypervisorHostName() != null) {
Location = VNF_instance.getHypervisorHostName();
}
}
}
}
log.debug("Got Location for VNF instance " + vnf_instance_name + " -> " + Location + ".");
return Location;
}
}
| true
|
2d6e9126765ba29927b5a670152480bbd565304e
|
Java
|
Kiolk/BullsAndCows
|
/app/src/main/java/com/example/notepad/bullsandcows/ui/activity/listeners/UserNikClickListener.java
|
UTF-8
| 227
| 1.679688
| 2
|
[] |
no_license
|
package com.example.notepad.bullsandcows.ui.activity.listeners;
import android.view.View;
public class UserNikClickListener {
public interface ClickUserNik {
void clickItemNik(View pView, int pPosition);
}
}
| true
|
69655e804bbfa68024ad176498b57506c5649f7d
|
Java
|
GiseliSiqueira/POO2
|
/CadRespCaixaAutomatico/src/cadrespcaixaautomatico/CincoSaqueHandler.java
|
UTF-8
| 590
| 2.4375
| 2
|
[] |
no_license
|
/*
* 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 cadrespcaixaautomatico;
/**
*
* @author Giseli
*/
public class CincoSaqueHandler extends AbstractSaqueHandler{
@Override
public int[] verificaValor(int valor) {
int[] notasCinco = {(valor / 5),(valor % 5)};
return notasCinco;
}
@Override
public void valorAqui(int quantidade) {
System.out.printf("%d notas de 5\n", quantidade);
}
}
| true
|
496f50a46a1bf625118a1d2788e3f28b08458b28
|
Java
|
RodrigoRosmaninho/miect_stuff
|
/P-III/aula4/ex1/Disciplina.java
|
UTF-8
| 1,556
| 3.484375
| 3
|
[] |
no_license
|
package aula4.ex1;
public class Disciplina {
private String nome;
private String area;
private int ECTS;
private Professor responsavel;
private VetorDinamico<Estudante> alunos;
public Disciplina(String nome, String area, int eCTS, Professor responsavel) {
this.nome = nome;
this.area = area;
ECTS = eCTS;
this.responsavel = responsavel;
alunos = new VetorDinamico<Estudante>();
}
public boolean addAluno(Estudante e) {
if(alunos.contains(e)) return false;
alunos.add(e);
return true;
}
public boolean delAluno(int nMec) {
Estudante[] tmp = alunos.array(new Estudante[alunos.size()]);
for(Estudante e : tmp) {
if(e.nMec() == nMec) {
alunos.remove(e);
return true;
}
}
return false;
}
public boolean alunoInscrito(int nMec) {
Estudante[] tmp = alunos.array(new Estudante[alunos.size()]);
for(Estudante e : tmp) if(e.nMec() == nMec) return true;
return false;
}
public int numAlunos() {
return alunos.size();
}
@Override
public String toString() {
return "Disciplina: " + nome + " (" + ECTS + " ECTS) da Area de " + area + "\nResponsável: " + responsavel + "\nExistem " + numAlunos() + " Alunos Inscritos";
}
public Estudante[] getAlunos() {
return alunos.array(new Estudante[alunos.size()]);
}
public Estudante[] getAlunos(String tipo) {
VetorDinamico<Estudante> tmp = new VetorDinamico<Estudante>();
for(Estudante e : getAlunos()) {
if(e.getClass().getSimpleName().equals(tipo)) {
tmp.add(e);
}
}
return tmp.array(new Estudante[tmp.size()]);
}
}
| true
|
7c4866ebb3e671bae050fe631d815513ef1a6332
|
Java
|
jvfranco/backend_gestao_ativ_agricola
|
/src/main/java/com/gestao/agricola/model/TipoSolo.java
|
UTF-8
| 97
| 1.59375
| 2
|
[] |
no_license
|
package com.gestao.agricola.model;
public enum TipoSolo {
ARENOSO, ARGILOSO, MISTO
}
| true
|
58ddb443ee6e39248633fc1b0a4c467148e13bf9
|
Java
|
kaiwxin/MSRCPSP
|
/GARunner_MSRCPSP/src/msrcpsp/evolutionary_algorithms/genetic_algorithm/selections/RouletteWheelSelection.java
|
UTF-8
| 1,526
| 2.4375
| 2
|
[] |
no_license
|
// Decompiled by Jad v1.5.8e2. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://kpdus.tripod.com/jad.html
// Decompiler options: packimports(3) fieldsfirst ansi space
// Source File Name: RouletteWheelSelection.java
package msrcpsp.evolutionary_algorithms.genetic_algorithm.selections;
import java.util.*;
import msrcpsp.scheduling.BaseIntIndividual;
// Referenced classes of package msrcpsp.evolutionary_algorithms.genetic_algorithm.selections:
// BaseSelection, IndividualPair
public class RouletteWheelSelection extends BaseSelection
{
public RouletteWheelSelection()
{
}
public IndividualPair select(List population, Random generator)
{
double sum = 0.0D;
for (Iterator iterator = population.iterator(); iterator.hasNext();)
{
BaseIntIndividual individual = (BaseIntIndividual)iterator.next();
sum += 1.0D - individual.getEvalValue();
}
double value = generator.nextDouble() * sum;
BaseIntIndividual firstParent = chooseParent(population, value);
value = generator.nextDouble() * sum;
BaseIntIndividual secondParent = chooseParent(population, value);
return new IndividualPair(firstParent, secondParent);
}
private BaseIntIndividual chooseParent(List population, double value)
{
double currentSum = 0.0D;
for (Iterator iterator = population.iterator(); iterator.hasNext();)
{
BaseIntIndividual individual = (BaseIntIndividual)iterator.next();
currentSum += 1.0D - individual.getEvalValue();
if (currentSum > value)
return individual;
}
return null;
}
}
| true
|
88611e6ee391c27b7e30da7c0faa71e4b0748733
|
Java
|
aieves/aieve
|
/app/src/main/java/ai/eve/html/custom/BaseDialog.java
|
UTF-8
| 805
| 2.125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package ai.eve.html.custom;
import android.app.Dialog;
import android.content.Context;
import ai.eve.R;
/**
*
*
* @Description: TODO
* @author WYONG
* @date 2014-3-21 下午4:14:03
* @version V1.0
*
*/
public class BaseDialog extends Dialog {
private OnJsCallBack mOnJsCallBack;
public void setOnJsCallBack(OnJsCallBack onJsCallBack) {
this.mOnJsCallBack = onJsCallBack;
}
public BaseDialog(Context context) {
super(context);
getWindow().setBackgroundDrawableResource(R.drawable.eve_bg_dialog);
}
public BaseDialog(Context context, int theme) {
super(context, theme);
getWindow().setBackgroundDrawableResource(R.drawable.eve_bg_dialog);
}
public OnJsCallBack getmOnJsCallBack() {
return mOnJsCallBack;
}
}
| true
|
a52c57e2722a52eaa6f4a9b141296b92a13ebda2
|
Java
|
wang1784594241/JsDroid3
|
/server-apk/src/main/java/com/jsdroid/commons/SyncThread.java
|
UTF-8
| 956
| 2.8125
| 3
|
[] |
no_license
|
package com.jsdroid.commons;
public class SyncThread<T> extends Thread {
private T result;
private boolean end;
private Sync<T> sync;
public SyncThread(Sync<T> sync) {
this.sync = sync;
start();
}
public interface Sync<T> {
T run();
}
public T waitResult(long timeout) {
synchronized (SyncThread.this) {
if (!end) {
try {
SyncThread.this.wait(timeout);
} catch (InterruptedException e) {
}
}
}
try {
stop();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
@Override
public void run() {
try {
result = sync.run();
} finally {
synchronized (SyncThread.this) {
end = true;
SyncThread.this.notifyAll();
}
}
}
}
| true
|
a3fbbda33e401b1adbb2cc02d4dc8dfa4c67ae40
|
Java
|
AndrisBorbas/Prog3HF
|
/LangtonsAnt/src/langtonsant/entity/TileID.java
|
UTF-8
| 795
| 3.015625
| 3
|
[] |
no_license
|
package langtonsant.entity;
/**
* Handles updating the tiles inside the ants "brain"
* @author AndrisBorbas
*
*/
public class TileID {
private int currentID, lastID, max;
public TileID() {
currentID = 0;
lastID = 0;
max = 2;
}
public TileID(int id) {
setID(id);
}
public void setMax(int id) {
this.max = id;
}
public int getID() {
return currentID;
}
public int getlastID() {
return lastID;
}
public void setID(int id) {
this.currentID = id;
if (id == 0) {
this.lastID = max;
} else {
this.lastID = this.currentID - 1;
}
}
public int getNextID() {
if (currentID == max) {
return 0;
} else {
return (currentID + 1);
}
}
public void setlastID(int id) {
this.lastID = id;
}
public void swapID() {
lastID = currentID;
}
}
| true
|
a4e688389373a54132f48f96b5aca1838f39792c
|
Java
|
danielamora13/JPA-HIbernate
|
/JPA-Hibernate/src/main/java/com/example/JPA/Hibernate/persona/domain/Persona.java
|
UTF-8
| 4,626
| 2.15625
| 2
|
[] |
no_license
|
package com.example.JPA.Hibernate.persona.domain;
import com.example.JPA.Hibernate.StringPrefixedSequenceIdGenerator;
import com.example.JPA.Hibernate.persona.infraestructure.controller.input.PersonaInputDto;
import com.example.JPA.Hibernate.profesor.domain.Profesor;
import com.example.JPA.Hibernate.student.domain.Estudiante;
import lombok.*;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.Date;
import org.hibernate.annotations.Parameter;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Entity
public class Persona {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "persona_seq")
@GenericGenerator(
name = "persona_seq",
strategy = "com.example.JPA.Hibernate.StringPrefixedSequenceIdGenerator",
parameters = {
@Parameter(name = StringPrefixedSequenceIdGenerator.INCREMENT_PARAM, value = "1"),
@Parameter(name = StringPrefixedSequenceIdGenerator.VALUE_PREFIX_PARAMETER, value = "Persona_"),
@Parameter(name = StringPrefixedSequenceIdGenerator.NUMBER_FORMAT_PARAMETER, value = "%08d")
})
private String id;
@Column(nullable = false)
private String user;
@Column(nullable = false)
private String password;
@Column(nullable = false)
private String name;
private String surname;
@Column(nullable = false)
private String company_email;
@Column(nullable = false)
private String personal_email;
@Column(nullable = false)
private String city;
@Column(nullable = false)
private Boolean active;
@Column(nullable = false)
private Date created_date = new Date();
private String imagen_url;
private Date termination_date;
@OneToOne(mappedBy = "persona",
cascade = CascadeType.ALL,
orphanRemoval = true,
fetch = FetchType.LAZY
)
private Estudiante estudiante;
@OneToOne(mappedBy = "persona",
cascade = CascadeType.ALL,
orphanRemoval = true,
fetch = FetchType.LAZY
)
private Profesor profesor;
public Persona(PersonaInputDto personaInputDto){
setPersona(personaInputDto);
}
public Persona(String user,
String password,
String name,
String surname,
String company_email,
String personal_email,
String city,
Boolean active,
Date created_date,
String imagen_url,
Date termination_date) {
this.user = user;
this.password = password;
this.name = name;
this.surname = surname;
this.company_email = company_email;
this.personal_email = personal_email;
this.city = city;
this.active = active;
this.created_date = created_date;
this.imagen_url = imagen_url;
this.termination_date = termination_date;
}
public void setPersona(PersonaInputDto personaInputDto) {
if (personaInputDto == null) {
return;
}
if (personaInputDto.user != null) {
this.user = personaInputDto.user ;
}
if (personaInputDto.password != null) {
this.password = personaInputDto.password ;
}
if (personaInputDto.name != null) {
this.name = personaInputDto.name ;
}
if (personaInputDto.surname != null) {
this.surname = personaInputDto.surname ;
}
if (personaInputDto.company_email != null) {
this.company_email = personaInputDto.company_email ;
}
if (personaInputDto.personal_email != null) {
this.personal_email = personaInputDto.personal_email ;
}
if (personaInputDto.city != null) {
this.city = personaInputDto.city ;
}
if (personaInputDto.active != null) {
this.active = personaInputDto.active ;
}
if (personaInputDto.created_date != null) {
this.created_date = personaInputDto.created_date ;
}
if (personaInputDto.imagen_url != null) {
this.imagen_url = personaInputDto.imagen_url ;
}
if (personaInputDto.termination_date != null) {
this.termination_date = personaInputDto.termination_date ;
}
}
}
| true
|
41a3c21d740acb43158591ee47b113913288ad65
|
Java
|
Anechka2018/gameofwords
|
/app/src/main/java/com/example/a1/mainscreen.java
|
UTF-8
| 5,029
| 2.015625
| 2
|
[] |
no_license
|
package com.example.a1;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import java.util.Locale;
public class mainscreen extends Activity {
SharedPreferences a;
boolean b;
boolean c;
int d=0;
int e;
int f;
int g;
int h;
float i;
TextView j;
TextView k;
TextView l;
TextView m;
TextView n;
TextView o;
TextView p;
TextView q;
final String r="mGameState";
final String s="firstgame";
final String t="gamecount";
final String u="wincount";
final String v="loosecount";
final String w="attemtsall";
final String x="settings";
final String y="letters";
OnClickListener z= new OnClickListener(this) {
final /* synthetic */ mainscreen a;
{
this.a= r1;
}
public void onClick(View view) {
this.a.a=this.a.getSharedPreferences("settings", 0);
SharedPreferences.Editor edit = this.a.a.edit();
this.a.h=this.a.a.getInt("letters", 0);
TextView textView = (TextView) this.a.findViewById(view.getId());
TextView textView2 = (TextView) this.a.findViewById(2131427469);
switch (this.a.h) {
case 4:
textView2 = (TextView) this.a.findViewById(2131427464);
break;
case 5:
textView2 = (TextView) this.a.findViewById(2131427465);
break;
case 6:
textView2 = (TextView) this.a.findViewById(2131427466);
break;
case 7:
textView2 = (TextView) this.a.findViewById(2131427467);
break;
case 8:
textView2 = (TextView) this.a.findViewById(2131427468);
break;
}
textView2.setTextSize(14.0f);
switch (view.getId()) {
case 2131427464:
textView.setTextSize(24.0f);
edit.putInt("letters", 4);
break;
case 2131427465:
textView.setTextSize(24.0f);
edit.putInt("letters", 5);
break;
case 2131427466:
textView.setTextSize(24.0f);
edit.putInt("letters", 6);
break;
case 2131427467:
textView.setTextSize(24.0f);
edit.putInt("letters", 7);
break;
case 2131427468:
textView.setTextSize(24.0f);
edit.putInt("letters", 8);
break;
case 2131427469:
textView.setTextSize(24.0f);
edit.putInt("letters", 0);
break;
}
((SharedPreferences.Editor) edit).apply();
}
};
void a() {
this.a=getSharedPreferences("settings", 0);
this.b=this.a.getBoolean("mGameState", false);
this.c=this.a.getBoolean("firstgame", true);
this.d=this.a.getInt("gamecount", 0);
this.e=this.a.getInt("wincount", 0);
this.f=this.a.getInt("loosecount", 0);
this.g=this.a.getInt("attemtsall", 0);
this.h=this.a.getInt("letters", 0);
}
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(2130968605);
this.j = (TextView) findViewById(2131427460);
this.k = (TextView) findViewById(2131427463);
this.l = (TextView) findViewById(2131427464);
this.l.setOnClickListener(this.z);
this.m = (TextView) findViewById(2131427465);
this.m.setOnClickListener(this.z);
this.n = (TextView) findViewById(2131427466);
this.n.setOnClickListener(this.z);
this.o = (TextView) findViewById(2131427467);
this.o.setOnClickListener(this.z);
this.p = (TextView) findViewById(2131427468);
this.p.setOnClickListener(this.z);
this.q = (TextView) findViewById(2131427469);
this.q.setOnClickListener(this.z);
a();
switch (this.h) {
case 0:
this.q.getTextSize (24.0f);
break;
case 4:
this.l.getTextSize (24.0f);
break;
case 5:
this.m.getTextSize (24.0f);
break;
case 6:
this.n.getTextSize (24.0f);
break;
case 7:
this.o.getTextSize (24.0f);
break;
case 8:
this.p.getTextSize (24.0f);
break;
}
if (this.e>0){
this.i=((float) this.g)/((float) this.e);
}
if (!this.c && this.e > 0) {
this.k.setText("Victories: " + this.e + ", lesions: " + this.f + ", average guess with " + String.format(Locale.ENGLISH, "%(.2f", new Object[]{Float.valueOf(this.i)}) + " attempts");
}
this.j.setOnClickListener(new OnClickListener(this) {
final /* synthetic */ mainscreen a;
{
this.a = r1;
}
public void onClick(View view) {
this.a.startActivity(new Intent(this.a, game.class));
}
});
}
protected void onPostCreate(Bundle bundle) {
super.onPostCreate(bundle);
}
protected void onRestart() {
super.onRestart();
a();
if (this.e > 0) {
this.i = ((float) this.g) / ((float) this.e);
}
if (!this.c && this.e > 0) {
this.k.setText("Victories: " + this.e + ", lesions: " + this.f + ", average guess with " + String.format(Locale.ENGLISH, "%(.2f", new Object[]{Float.valueOf(this.i)}) + " attempts");
}
}
}
| true
|
598d748a877427aed76336c5eba8a4a9e8024d0d
|
Java
|
specktre/AndroidMvp
|
/app/src/main/java/com/specktre/androidmvp/userselection/UserSelectionViewState.java
|
UTF-8
| 1,923
| 2.484375
| 2
|
[
"MIT"
] |
permissive
|
package com.specktre.androidmvp.userselection;
import com.hannesdorfmann.mosby.mvp.viewstate.ViewState;
import com.specktre.domain.userselection.UserSelectionView;
public class UserSelectionViewState implements ViewState<UserSelectionView> {
private boolean usernameEditTextEnabled;
private boolean nextButtonEnabled;
private enum UserRepoState {
HAS_PUBLIC_REPOS, NO_PUBLIC_REPOS, USER_NOT_FOUND
}
private UserRepoState userRepoState = UserRepoState.USER_NOT_FOUND;
@Override
public void apply(UserSelectionView userSelectionView, boolean retained) {
if(usernameEditTextEnabled) {
userSelectionView.allowUsernameSelection();
} else {
userSelectionView.disallowUsernameSelection();
}
if(nextButtonEnabled) {
userSelectionView.allowProceedingToNextStep();
} else {
userSelectionView.disallowProceedingToNextStep();
}
switch(userRepoState) {
case HAS_PUBLIC_REPOS:
userSelectionView.displayUserIsFoundAndHasPublicRepos();
break;
case NO_PUBLIC_REPOS:
userSelectionView.displayErrorUserHasNoPublicRepos();
break;
case USER_NOT_FOUND:
userSelectionView.displayErrorUserIsNotFound();
break;
}
}
public void setUsernameEditTextEnabled(boolean enabled) {
this.usernameEditTextEnabled = enabled;
}
public void setNextButtonEnabled(boolean enabled) {
this.nextButtonEnabled = enabled;
}
public void setUserIsFoundAndHasPublicRepos() {
userRepoState = UserRepoState.HAS_PUBLIC_REPOS;
}
public void setUserHasNoPublicRepos() {
userRepoState = UserRepoState.NO_PUBLIC_REPOS;
}
public void setUserNotFound() {
userRepoState = UserRepoState.USER_NOT_FOUND;
}
}
| true
|
df759be3798a7be6abebd6fb0155974e500b107b
|
Java
|
amit-18/stockpredictor
|
/src/main/java/com/stockamarket/amit/stockpredictor/service/Symbols.java
|
UTF-8
| 2,815
| 2.359375
| 2
|
[] |
no_license
|
package com.stockamarket.amit.stockpredictor.service;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import com.stockamarket.amit.stockpredictor.constants.Constants;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import static com.stockamarket.amit.stockpredictor.constants.Constants.*;
@Slf4j
@Service
public class Symbols {
RestTemplate restTemplate = new RestTemplate();
List<String> symbols = new ArrayList<>();
HttpHeaders headers = new HttpHeaders();
HttpEntity<String> entity;
public void createConnection() {
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.set("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36 Edg/89.0.774.63");
headers.set("Host","www1.nseindia.com");
headers.set("Connection","keep-alive");
entity = new HttpEntity<String>(headers);
}
public List<String> getStockSymbols() {
createConnection();
String year_high = restTemplate.exchange(YEAR_HIGH_URL, HttpMethod.GET, entity, String.class).getBody();
String top_gainers = restTemplate.exchange(GAINERS_URL, HttpMethod.GET, entity, String.class).getBody();
String top_value = restTemplate.exchange(TOP_VALUE_URL, HttpMethod.GET, entity, String.class).getBody();
String top_volume = restTemplate.exchange(TOP_VOLUME_URL, HttpMethod.GET, entity, String.class).getBody();
extractFromJSON(year_high);
extractFromJSON(top_gainers);
extractFromJSON(top_value);
extractFromJSON(top_volume);
try {
String line = "";
String splitBy = ",";
BufferedReader br = new BufferedReader(new FileReader("src/main/resources/Sensex.csv"));
while ((line = br.readLine()) != null) {
String[] stock = line.split(splitBy);
symbols.add(stock[2]);
}
} catch (Exception e) {
log.error(e.getMessage());
}
return symbols.stream().distinct().collect(Collectors.toList());
}
public void extractFromJSON(String jsonStr) {
JSONObject reader = new JSONObject(jsonStr);
JSONArray jsonArray = reader.getJSONArray("data");
IntStream.range(0,jsonArray.length()).mapToObj(index -> ((JSONObject)jsonArray
.get(index)).optString("symbol"))
.collect(Collectors.toCollection(() -> symbols));
}
}
| true
|
cdf98e07eb52e05578ddbed90bd3bc312943bccc
|
Java
|
Gxyong/galley
|
/gxygalley/src/main/java/com/gxy/proxy/AnimatorListenerAdapterProxy.java
|
UTF-8
| 645
| 1.914063
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.gxy.proxy;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
public class AnimatorListenerAdapterProxy extends AnimatorListenerAdapter {
@Override
public void onAnimationCancel(Animator animator) {
}
@Override
public void onAnimationEnd(Animator animator) {
}
@Override
public void onAnimationRepeat(Animator animator) {
}
@Override
public void onAnimationStart(Animator animator) {
}
@Override
public void onAnimationPause(Animator animator) {
}
@Override
public void onAnimationResume(Animator animator) {
}
}
| true
|
f89b0c5c87a9aeb70548dfd4436c303e2b81a458
|
Java
|
jazzlly/java-example
|
/001.basic/src/main/java/com/java/examples/security/signature/VerSig.java
|
UTF-8
| 4,021
| 2.890625
| 3
|
[] |
no_license
|
package com.java.examples.security.signature;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class VerSig {
private static final String fileName = "/home/jiangrui/.signature_test/change.fmradio.frw.txt";
private static final String sigFileName = "/home/jiangrui/.signature_test/change.fmradio.frw.txt_sig";
private static final String pubKeyFile = "/home/jiangrui/.signature_test/pubkey";
private static PublicKey mPubKey;
private byte[] mSigToVerifies;
public static void main(String[] args) {
/* Verify a DSA signature */
VerSig verSig = new VerSig();
try {
verSig.loadPublicKey();
verSig.loadSignature();
verSig.verifySignature();
} catch (Exception e) {
System.err.println("Caught exception " + e.toString());
}
}
private void verifySignature() throws NoSuchAlgorithmException,
NoSuchProviderException, InvalidKeyException,
IOException, SignatureException {
Signature sig = Signature.getInstance("SHA1withDSA", "SUN");
sig.initVerify(mPubKey); // need public key to verify signature
FileInputStream datafis = new FileInputStream(fileName);
BufferedInputStream bufin = new BufferedInputStream(datafis);
byte[] buffer = new byte[1024];
int len;
while (bufin.available() != 0) {
len = bufin.read(buffer);
sig.update(buffer, 0, len);
}
bufin.close();
boolean verifies = sig.verify(mSigToVerifies);
System.out.println("signature verifies: " + verifies);
}
private void loadSignature() throws IOException {
FileInputStream sigfis = new FileInputStream(sigFileName);
mSigToVerifies = new byte[sigfis.available()];
sigfis.read(mSigToVerifies);
sigfis.close();
}
private void loadPublicKey() throws IOException,
NoSuchAlgorithmException, NoSuchProviderException,
InvalidKeySpecException {
// Read public key from file
FileInputStream keyfis = new FileInputStream(pubKeyFile);
byte[] mEncKey = new byte[keyfis.available()];
keyfis.read(mEncKey);
keyfis.close();
/*
* instantiate a DSA public key from its encoding
*
* KeyFactory class provides conversions between opaque keys (of type
* Key) and key specifications
*
* key specifications transparent representations of the underlying key
* material
*
* With an opaque key you can obtain the algorithm name, format name,
* and encoded key bytes, but not the key material which may consist of
* the key itself and the algorithm parameters used to calculate the key
*
* first you need a key specification assuming that the key was encoded
* according to the X.509 standard which is the case, for example, if
* the key was generated with the built-in DSA key-pair generator
* supplied by the SUN provider
*/
// Get key specification
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(mEncKey);
// Convert key specification to opaque key
KeyFactory keyFactory = KeyFactory.getInstance("DSA", "SUN");
mPubKey = keyFactory.generatePublic(pubKeySpec);
}
void loadPrivateKey(String fileName) throws IOException,
NoSuchAlgorithmException, InvalidKeySpecException {
FileInputStream keyfis = new FileInputStream(fileName);
byte[] encKey = new byte[keyfis.available()];
keyfis.read(encKey);
keyfis.close();
PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(encKey);
KeyFactory keyFactory = KeyFactory.getInstance("DSA");
PrivateKey privKey = keyFactory.generatePrivate(privKeySpec);
}
}
| true
|
61ac24567cb35997ffede8fdefbeba1b99db05f5
|
Java
|
gretchenfrage/PB
|
/src/phoebinary/PhoeBinaryFile.java
|
UTF-8
| 1,680
| 2.421875
| 2
|
[] |
no_license
|
package phoebinary;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import phoebinary.variabletypes.VarFolder;
public class PhoeBinaryFile {
private File file;
private List<Variable> variables;
private VariableTypeRegistry registry;
public PhoeBinaryFile(File fileIn) {
file = fileIn;
read();
}
public void read() {
try (FileInputStream stream = new FileInputStream(file)) {
PhoeBinaryParser parser = new PhoeBinaryParser(stream);
variables = parser.parse();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void () {
try (FileOutputStream stream = new FileOutputStream(file)) {
PhoeBinarySerializer serializer = new PhoeBinarySerializer(variables);
serializer.serialize(stream);
} catch (IOException e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
public List<Variable> getVariables() {
return (List<Variable>) ((ArrayList<Variable>) variables).clone();
}
public void addVariable(Variable v) {
variables.add(v);
}
public void removeVariable(Variable v) {
variables.remove(v);
}
public void clearVariables() {
variables = new ArrayList<Variable>();
}
public Variable getVariable(String rawPath) {
String[] path = rawPath.split("\\.");
Variable variable = Variable.getVariableNamed(path[0], variables);
if (variable instanceof VarFolder) {
return ((VarFolder) variable).getVariable(Variable.reducePath(path));
} else {
return variable;
}
}
}
| true
|
17955e3986fb402611864dbf57fc91e48cc1d1e9
|
Java
|
ixtf/social-sdk
|
/social-core/src/main/java/org/jzb/social/core/JSocial.java
|
UTF-8
| 975
| 2.546875
| 3
|
[] |
no_license
|
package org.jzb.social.core;
import java.util.UUID;
/*
* 描述:
*
* @author jzb
* @create 2017-10-24
*/
public class JSocial {
/**
* 获取随机字符串 Nonce Str
*
* @return String 随机字符串
*/
public static String generateNonceStr() {
return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
}
/**
* 生成 uuid, 即用来标识一笔单,也用做 nonce_str
*
* @return
*/
public static String generateUUID() {
return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
}
/**
* 获取当前时间戳,单位秒
*
* @return
*/
public static long getCurrentTimestamp() {
return System.currentTimeMillis() / 1000;
}
/**
* 获取当前时间戳,单位毫秒
*
* @return
*/
public static long getCurrentTimestampMs() {
return System.currentTimeMillis();
}
}
| true
|
9ca7c5a6c3e31461d5fe0c3efe04e1778e36018d
|
Java
|
bryandaniel1/chat-room
|
/netbeans/ChatRoom-ear/ChatRoom/src/java/chat/web/servlet/ImageServlet.java
|
UTF-8
| 7,913
| 2.265625
| 2
|
[] |
no_license
|
/*
* Copyright 2017 Bryan Daniel.
*
* 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 chat.web.servlet;
import chat.ejb.service.FileHandlingService;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.imageio.ImageIO;
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 javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
/**
* This HttpServlet class contains the functionality for retrieving image data
* from an upload or a file and writing that data to the response.
*
* @author Bryan Daniel
*/
@WebServlet(name = "ImageServlet", urlPatterns = {"/image"})
public class ImageServlet extends HttpServlet {
/**
* The key for the image value
*/
public static final String IMAGE_KEY = "image";
/**
* Serial version UID
*/
private static final long serialVersionUID = 5672625652451519035L;
/**
* The image handling service
*/
@EJB(beanName = "imageHandler")
private FileHandlingService imageHandler;
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String action = request.getParameter("action");
if (action != null) {
switch (action) {
case "preview":
HttpSession session = request.getSession();
sendPhoto(response, getPhotoBytesFromPart((Part) session.getAttribute(IMAGE_KEY)));
break;
case "view":
String username = request.getParameter("user");
sendPhoto(response, getPhotoBytesFromFile(username,
Long.parseLong(request.getParameter("image"))));
break;
default:
break;
}
}
}
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* This method converts the given Part object to a byte array used to
* display the image.
*
* @param part the Part object
* @return the byte array
*/
private byte[] getPhotoBytesFromPart(Part part) {
byte[] photoBytes = null;
ByteArrayOutputStream outputStream = null;
try {
try (InputStream is = part.getInputStream()) {
outputStream = new ByteArrayOutputStream();
int i;
while ((i = is.read()) != -1) {
outputStream.write(i);
}
photoBytes = outputStream.toByteArray();
}
} catch (Exception ex) {
photoBytes = null;
Logger.getLogger(ImageServlet.class.getName()).log(Level.SEVERE,
"An exception occurred in the getPhotoBytesFromPart method.", ex);
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException ex) {
Logger.getLogger(ImageServlet.class.getName()).log(Level.SEVERE,
"An exception occurred in the getPhotoBytesFromPart method while closing resources.", ex);
}
}
}
return photoBytes;
}
/**
* This method uses the given username and image number to retrieve the
* image file and return the byte array for the image.
*
* @param username the username
* @param imageNumber the number identifying the image
* @return the byte array
*/
private byte[] getPhotoBytesFromFile(String username, Long imageNumber) {
byte[] imageBytes = null;
BufferedImage image = null;
ByteArrayOutputStream outputStream = null;
try {
image = (BufferedImage) imageHandler.retrieveFromFileSystem(username, imageNumber);
} catch (FileNotFoundException ex) {
Logger.getLogger(ImageServlet.class.getName()).log(Level.SEVERE,
"An exception occurred in the getPhotoBytesFromFile method while retrieving the picture from the file system.", ex);
}
if (image != null) {
try {
outputStream = new ByteArrayOutputStream();
ImageIO.write(image, "png", outputStream);
imageBytes = outputStream.toByteArray();
} catch (IOException ex) {
Logger.getLogger(ImageServlet.class.getName()).log(Level.SEVERE,
"An exception occurred in the getPhotoBytesFromFile method while writing the image to output.", ex);
} finally {
if (outputStream != null) {
try {
outputStream.flush();
outputStream.close();
} catch (IOException ex) {
Logger.getLogger(ImageServlet.class.getName()).log(Level.SEVERE,
"An exception occurred in the getPhotoBytesFromFile method while closing resources.", ex);
}
}
}
}
return imageBytes;
}
/**
* This method performs the task of sending the photo data to the user.
*
* @param response the HttpServletResponse object
* @param photo the photo data
* @throws IOException if an IO exception occurs
*/
private void sendPhoto(HttpServletResponse response, byte[] photo) throws IOException {
response.setContentType("image/png");
try (OutputStream out = response.getOutputStream()) {
for (int i = 0; i < photo.length; i++) {
out.write(photo[i]);
}
} catch (IOException ex) {
Logger.getLogger(ImageServlet.class.getName()).log(Level.SEVERE, null, ex);
throw ex;
}
}
}
| true
|
4d033aca1271ae5fa1b76f1b12e566b49886e20e
|
Java
|
laurentperez/JGDPR
|
/src/main/java/eu/jgdpr/util/GDPRConstants.java
|
UTF-8
| 189
| 1.65625
| 2
|
[] |
no_license
|
package eu.jgdpr.util;
import eu.jgdpr.data.GDPRRisk;
public class GDPRConstants {
@GDPRRisk
public static final int RISK_UNASSESSED = -1;
private GDPRConstants() {
}
}
| true
|
7f70513185b91a912322484dedb779660887e7cf
|
Java
|
htools/htools
|
/src/main/java/io/github/htools/extract/modules/RemoveHtmlNav.java
|
UTF-8
| 501
| 2.203125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package io.github.htools.extract.modules;
import io.github.htools.extract.Extractor;
import io.github.htools.lib.Log;
/**
* Removes HTML tags from the content, leaving the content in between open and
* close tags.
* <p>
* @author jeroen
*/
public class RemoveHtmlNav extends RemoveNestedTags {
public static Log log = new Log(RemoveHtmlNav.class);
private RemoveHtmlNav(Extractor extractor, String process) {
super(extractor, process, "<nav(\\s|>)", "<\\s*/\\s*nav\\s*>");
}
}
| true
|
73bdb7bf9c347571edfff7bc89cbc6654feda7d3
|
Java
|
abhishek-1991/TFIDF_Calculation
|
/Spark/TFIDF.java
|
UTF-8
| 10,088
| 2.9375
| 3
|
[] |
no_license
|
/* Author Details:
* asrivas3 Abhishek Kumar Srivastava
*
* CSC-548 HW5 Problem #1
*/
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.*;
import scala.Tuple2;
import java.util.*;
/*
* Main class of the TFIDF Spark implementation.
* Author: Tyler Stocksdale
* Date: 10/31/2017
*/
public class TFIDF {
static boolean DEBUG = false;
//static boolean DEBUG = true;
public static void main(String[] args) throws Exception {
// Check for correct usage
if (args.length != 1) {
System.err.println("Usage: TFIDF <input dir>");
System.exit(1);
}
// Create a Java Spark Context
SparkConf conf = new SparkConf().setAppName("TFIDF");
JavaSparkContext sc = new JavaSparkContext(conf);
// Load our input data
// Output is: ( filePath , fileContents ) for each file in inputPath
String inputPath = args[0];
JavaPairRDD<String,String> filesRDD = sc.wholeTextFiles(inputPath);
// Get/set the number of documents (to be used in the IDF job)
long numDocs = filesRDD.count();
//Print filesRDD contents
if (DEBUG) {
List<Tuple2<String, String>> list = filesRDD.collect();
System.out.println("------Contents of filesRDD------");
for (Tuple2<String, String> tuple : list) {
System.out.println("(" + tuple._1 + ") , (" + tuple._2.trim() + ")");
}
System.out.println("--------------------------------");
}
/*
* Initial Job
* Creates initial JavaPairRDD from filesRDD
* Contains each word@document from the corpus and also attaches the document size for
* later use
*
* Input: ( filePath , fileContents )
* Map: ( (word@document) , docSize )
*/
JavaPairRDD<String,Integer> wordsRDD = filesRDD.flatMapToPair(
new PairFlatMapFunction<Tuple2<String,String>,String,Integer>() {
public Iterable<Tuple2<String,Integer>> call(Tuple2<String,String> x) {
// Collect data attributes
String[] filePath = x._1.split("/");
String document = filePath[filePath.length-1];
String fileContents = x._2;
String[] words = fileContents.split("\\s+");
int docSize = words.length;
// Output to Arraylist
ArrayList ret = new ArrayList();
for(String word : words) {
ret.add(new Tuple2(word.trim() + "@" + document, docSize));
}
return ret;
}
}
);
//Print wordsRDD contents
if (DEBUG) {
List<Tuple2<String, Integer>> list = wordsRDD.collect();
System.out.println("------Contents of wordsRDD------");
for (Tuple2<String, Integer> tuple : list) {
System.out.println("(" + tuple._1 + ") , (" + tuple._2 + ")");
}
System.out.println("--------------------------------");
}
/*
* TF Job (Word Count Job + Document Size Job)
* Gathers all data needed for TF calculation from wordsRDD
*
* Input: ( (word@document) , docSize )
* Map: ( (word@document) , (1/docSize) )
* Reduce: ( (word@document) , (wordCount/docSize) )
*/
JavaPairRDD<String,String> tfRDD = wordsRDD./**MAP**/flatMapToPair(
/************ YOUR CODE HERE ************/
new PairFlatMapFunction<Tuple2<String,Integer>,String,String>(){
public Iterable<Tuple2<String,String>> call(Tuple2<String,Integer> t){
String docSize = t._2.toString();
//list to return new key-value pair
ArrayList lst = new ArrayList();
lst.add(new Tuple2(t._1,"1/"+docSize));
return lst;
}
}
)./**REDUCE**/reduceByKey(
/************ YOUR CODE HERE ************/
new Function2<String,String,String>(){
public String call(String a, String b){
String[] x = a.split("/");
String[] y = b.split("/");
//Adding the count for same key.
Integer count = Integer.parseInt(x[0])+Integer.parseInt(y[0]);
return(count.toString()+"/"+x[1]);
}
}
);
//Print tfRDD contents
if (DEBUG) {
List<Tuple2<String, String>> list = tfRDD.collect();
System.out.println("-------Contents of tfRDD--------");
for (Tuple2<String, String> tuple : list) {
System.out.println("(" + tuple._1 + ") , (" + tuple._2 + ")");
}
System.out.println("--------------------------------");
}
/*
* IDF Job
* Gathers all data needed for IDF calculation from tfRDD
*
* Input: ( (word@document) , (wordCount/docSize) )
* Map: ( word , (1/document) )
* Reduce: ( word , (numDocsWithWord/document1,document2...) )
* Map: ( (word@document) , (numDocs/numDocsWithWord) )
*/
JavaPairRDD<String,String> idfRDD = tfRDD./**MAP**/flatMapToPair(
/************ YOUR CODE HERE ************/
new PairFlatMapFunction<Tuple2<String,String>,String,String>(){
public Iterable<Tuple2<String,String>> call(Tuple2<String,String> t){
String[] key = t._1.split("@");
//list to return new key-pairs
ArrayList lst = new ArrayList();
lst.add(new Tuple2(key[0],"1/"+key[1]));
return lst;
}
}
)./**REDUCE**/reduceByKey(
/************ YOUR CODE HERE ************/
new Function2<String,String,String>(){
public String call(String a, String b){
String[] x = a.split("/");
String[] y = b.split("/");
Integer count = Integer.parseInt(x[0])+Integer.parseInt(x[0]);
//appending the document names.
String value = count.toString()+"/";
for(int i=1;i<x.length;i++)
value = value + x[i] + ",";
for(int i=1;i<y.length;i++)
value = value + y[i] + ",";
return(value);
}
}
)./**MAP**/flatMapToPair(
/************ YOUR CODE HERE ************/
new PairFlatMapFunction<Tuple2<String,String>,String,String>(){
public Iterable<Tuple2<String,String>> call(Tuple2<String,String> t){
String[] value = t._2.split("/");
String[] doclst = value[1].split(",");
//using numDocs value that is already calculated before and adding it to the new generated value.
String numdocs = (new Long(numDocs)).toString();
ArrayList lst = new ArrayList();
for(String docname : doclst)
{
lst.add(new Tuple2(t._1+"@"+docname,numdocs+"/"+value[0]));
}
return lst;
}
}
);
//Print idfRDD contents
if (DEBUG) {
List<Tuple2<String, String>> list = idfRDD.collect();
System.out.println("-------Contents of idfRDD-------");
for (Tuple2<String, String> tuple : list) {
System.out.println("(" + tuple._1 + ") , (" + tuple._2 + ")");
}
System.out.println("--------------------------------");
}
/*
* TF * IDF Job
* Calculates final TFIDF value from tfRDD and idfRDD
*
* Input: ( (word@document) , (wordCount/docSize) ) [from tfRDD]
* Map: ( (word@document) , TF )
*
* Input: ( (word@document) , (numDocs/numDocsWithWord) ) [from idfRDD]
* Map: ( (word@document) , IDF )
*
* Union: ( (word@document) , TF ) U ( (word@document) , IDF )
* Reduce: ( (word@document) , TFIDF )
* Map: ( (document@word) , TFIDF )
*
* where TF = wordCount/docSize
* where IDF = ln(numDocs/numDocsWithWord)
* where TFIDF = TF * IDF
*/
JavaPairRDD<String,Double> tfFinalRDD = tfRDD.mapToPair(
new PairFunction<Tuple2<String,String>,String,Double>() {
public Tuple2<String,Double> call(Tuple2<String,String> x) {
double wordCount = Double.parseDouble(x._2.split("/")[0]);
double docSize = Double.parseDouble(x._2.split("/")[1]);
double TF = wordCount/docSize;
return new Tuple2(x._1, TF);
}
}
);
JavaPairRDD<String,Double> idfFinalRDD = idfRDD./**MAP**/mapToPair(
/************ YOUR CODE HERE ************/
new PairFunction<Tuple2<String,String>,String,Double>() {
public Tuple2<String,Double> call(Tuple2<String,String> t) {
String[] value = t._2.split("/");
double numdocs = Double.parseDouble(value[0]);
double numdocswithwords = Double.parseDouble(value[1]);
//calculating IDF
double IDF = Math.log(numdocs/numdocswithwords);
return new Tuple2(t._1, IDF);
}
}
);
JavaPairRDD<String,Double> tfidfRDD = tfFinalRDD.union(idfFinalRDD)./**REDUCE**/reduceByKey(
/************ YOUR CODE HERE ************/
new Function2<Double,Double,Double>() {
public Double call(Double a,Double b) {
//Calculating TFIDF
return (a*b);
}
}
)./**MAP**/flatMapToPair(
/************ YOUR CODE HERE ************/
new PairFlatMapFunction<Tuple2<String,Double>,String,Double>() {
public Iterable<Tuple2<String,Double>> call(Tuple2<String,Double> t){
String[] value = t._1.split("@");
//converting the results in the desired format
ArrayList res = new ArrayList();
res.add(new Tuple2(value[1]+"@"+value[0],t._2));
return res;
}
}
);
//Print tfidfRDD contents in sorted order
Map<String, Double> sortedMap = new TreeMap<>();
List<Tuple2<String, Double>> list = tfidfRDD.collect();
for (Tuple2<String, Double> tuple : list) {
sortedMap.put(tuple._1, tuple._2);
}
if(DEBUG) System.out.println("-------Contents of tfidfRDD-------");
for (String key : sortedMap.keySet()) {
System.out.println(key + "\t" + sortedMap.get(key));
}
if(DEBUG) System.out.println("--------------------------------");
}
}
| true
|
8e93dd6091398a49f45dd4d59de831218b1289bb
|
Java
|
lanmarti/Splay_Trees
|
/src/semisplay/TopStack.java
|
UTF-8
| 2,449
| 3.984375
| 4
|
[] |
no_license
|
package semisplay;
import java.util.ArrayList;
/**
* A utility class for conveniently traversing semisplay trees.
*/
public class TopStack extends ArrayList<Top> {
/**
* Retrieve (non-destructively) the element which is deepest in the stack.
* @return The bottommost element.
*/
public Top bottom() {
return get(0);
}
/**
* Push top onto the stack.
* @param top The element to push onto the stack.
*/
public void push(Top top) {
add(top);
}
/**
* Remove and return the topmost element.
* @return the previously topmost element
*/
public Top pop() {
return remove(size() - 1);
}
/**
* @return Retrieve (non-destructively, read-only) the topmost element.
*/
public Top peek() {
return get(size() - 1);
}
/**
* @return Whether the stack has at least one element.
*/
public boolean nonEmpty() {
return ! isEmpty();
}
/**
* @return The length of the path (is number of elements minus 1).
*/
public int length() {
return size() - 1;
}
/**
* Replace the topmost value of the stack with a new one.
* @param top The new topmost element.
* @return The previous topmost element.
*/
public Top swap(Top top) {
int last = size() - 1;
Top old = get(last);
set(last, top);
return old;
}
/**
* Replace the element at the given position in the stack.
* @param index The position where the replacement should occur.
* @param top The new element to be placed at that position.
* @return The previous element from that position.
*/
public Top replace(int index, Top top) {
Top old = get(index);
set(index, top);
return old;
}
/**
* @return Whether the stack contains at least one child + parent.
*/
public boolean hasParent() {
return size() >= 2;
}
/**
* @return The parent node for the topmost element.
*/
public Top getParent() {
return get(size() - 2);
}
/**
* @return Whether the stack contains a child + parent + grandparent.
*/
public boolean hasGrandParent() {
return size() >= 3;
}
/**
* @return The grandparent node for the topmost element.
*/
public Top getGrandParent() {
return get(size() - 3);
}
}
| true
|
e5c83e21bd7058dee57e7db7708721ab7fa180ee
|
Java
|
DevTechnician/homework
|
/homework252eichmj252/src/com/uw/homework252eichmj/AddTask_Dialog.java
|
UTF-8
| 1,739
| 1.859375
| 2
|
[] |
no_license
|
package com.uw.homework252eichmj;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebView.FindListener;
import android.widget.EditText;
public class AddTask_Dialog extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// TODO Auto-generated method stub
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View v = inflater.inflate(R.layout.add_task, null);
final EditText taskText = (EditText) v.findViewById(R.id.editText1);
final EditText taskDescriptionText = (EditText) v
.findViewById(R.id.editText2);
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(v)
// Add action buttons
.setPositiveButton("Add",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
if (!taskText.getText().toString().isEmpty() && !taskDescriptionText.getText()
.toString().isEmpty()) {
TaskList_Fragment.dbu.insertNewRow(taskText
.getText().toString(),
taskDescriptionText.getText()
.toString());
}
TaskList_Fragment.changeListData();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
return builder.create();
}
}
| true
|
182a292b3df9ced628a5f73cdf705001ef99841b
|
Java
|
acastef/Projekat-ISA-MRS-Tim11
|
/src/main/java/bioskopi/rs/services/TicketServiceImpl.java
|
UTF-8
| 8,015
| 2.46875
| 2
|
[] |
no_license
|
package bioskopi.rs.services;
import bioskopi.rs.domain.*;
import bioskopi.rs.domain.util.ValidationException;
import bioskopi.rs.repository.*;
import org.hibernate.StaleObjectStateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.orm.ObjectOptimisticLockingFailureException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.*;
import javax.validation.Valid;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
@Service("tickets")
public class TicketServiceImpl implements TicketService{
@Autowired
private TicketRepository ticketRepository;
@Autowired
private ProjectionRepository projectionRepository;
@Autowired
private RegisteredUserRepository registeredUserRepository;
@PersistenceContext
private EntityManager entityManager;
@Override
@Transactional
@Lock(LockModeType.PESSIMISTIC_WRITE)
public void add(Ticket ticket)
{
try{
long id = ticket.getProjection().getId();
Projection p = findById(id);
List<Ticket> tickets = ticketRepository.getListByProjectionId(p.getId());
for(Ticket t : tickets) {
if ((t.getProjection().getId() == ticket.getProjection().getId()) &&
(t.getSeat().getId() == ticket.getSeat().getId())) {
throw new ValidationException("Seat you chose is already taken!");
}
}
tickets.add(ticket);
p.setTickets(new HashSet<Ticket>(tickets));
save(p);
}catch(LockTimeoutException e){
throw new ValidationException("Seat you chosen is already taken, refresh page!");
}
}
public Projection findById(long id){
return projectionRepository.findById(id).get();
}
public Projection save(Projection p){
return projectionRepository.save(p);
}
@Override
public String delete(long id) {
try {
ticketRepository.deleteById(id);
return "Great Success!";
}
catch (Exception e){
return "Not great success :(";
}
}
@Transactional
@Override
public Boolean putToFastReservation(long id) {
try {
Ticket t = ticketRepository.getOne(id);
t.setFastReservation(true);
ticketRepository.save(t);
return true;
}
catch (StaleObjectStateException |OptimisticLockException | ObjectOptimisticLockingFailureException e){
throw new ValidationException("Tickets are stale, please refresh your page");
}
}
@Transactional
@Override
public Ticket update(Ticket t) {
if (t.getDiscount() <0 || t.getDiscount() > 100)
throw new ValidationException("Ticket discount can not be less than 0 or more than 100");
else
return ticketRepository.saveAndFlush(t);
}
@Transactional
@Override
public Boolean makeFastReservation(Ticket t) {
try {
long id = t.getOwner().getId();
RegisteredUser u = registeredUserRepository.findById(id).get();
t.setOwner(u);
Ticket oldT = ticketRepository.findById(t.getId()).get();
//oldT.setOwner(u);
t.setProjection(oldT.getProjection());
t.setTaken(true);
ticketRepository.save(t);
return true;
}
catch (StaleObjectStateException |OptimisticLockException | ObjectOptimisticLockingFailureException e){
throw new ValidationException("Tickets are stale, please refresh your page");
}
}
@Transactional
@Override
public void deleteReservation(long id) {
try{
Ticket t = ticketRepository.getOne(id);
ticketRepository.delete(t);
}catch (ValidationException e){
throw new ValidationException("Reservation doesn't exists!");
}
}
@Override
public Ticket getByProjectionId(long projId)
{
return ticketRepository.getByProjectionId(projId);
}
@Override
public List<Ticket> getListByProjectionId(long id) {
return ticketRepository.getListByProjectionId(id);
}
@Override
public List<Ticket> getTickets(long ownerId) {
List<Ticket> allTickets = ticketRepository.getAllTickets(ownerId);
return allTickets;
}
@Override
public Ticket getById(long id) {
return ticketRepository.getOne(id);
}
@Override
public HashMap<String, Integer> getVisitsByWeeks(long id) {
HashMap<String, Integer> totalVisitsPerWeek = new HashMap<String, Integer>();
List<Ticket> ticketList = ticketRepository.getTicketsForFacility(id);
for (Ticket selectedTicket: ticketList) {
//Projection p = projectionRepository.getOne(selectedTicket.getProjection());
String week = generateWeek(selectedTicket.getProjection().getDate());
// Ako ne postoji ubacuje 1 kao vrednost, inace poveacava vrednost za 1
totalVisitsPerWeek.merge(week, 1, Integer::sum);
}
return totalVisitsPerWeek;
}
@Override
public HashMap<String, Integer> getVisitsByMonths(long id) {
HashMap<String, Integer> totalVisitsPerMonth = new HashMap<String, Integer>();
List<Ticket> ticketList = ticketRepository.getTicketsForFacility(id);
for (Ticket selectedTicket: ticketList) {
//Projection p = projectionRepository.getOne(selectedTicket.getProjection());
String week = generateMonth(selectedTicket.getProjection().getDate());
// Ako ne postoji ubacuje 1 kao vrednost, inace poveacava vrednost za 1
totalVisitsPerMonth.merge(week, 1, Integer::sum);
}
return totalVisitsPerMonth;
}
@Override
public Integer getPricePerPeriod(long id, LocalDateTime d1, LocalDateTime d2) {
Integer totalEarnings = 0;
List<Ticket> ticketList = ticketRepository.getTicketsForFacility(id);
for (Ticket selectedTicket: ticketList) {
LocalDateTime dateOfTicket = selectedTicket.getProjection().getDate();
// equal stoji da obuhvati i taj dan koji je odabran
if ( (dateOfTicket.isBefore(d2) || dateOfTicket.equals(d2) ) &&
(dateOfTicket.isAfter(d1) || dateOfTicket.equals(d1) ) )
totalEarnings += selectedTicket.getProjection().getPrice();
}
return totalEarnings;
}
@Override
public List<Long> getTakenSeats(long VrId) {
return ticketRepository.getTakenSeats(VrId);
}
@Transactional
@Override
public Object changeOwner(long userId, long projId, long seatId) {
ticketRepository.changeTicketOwner(userId, projId, seatId);
return "Invitation accepted";
}
@Override
public HashMap<Long, Projection> getProjForTicket(long facId) {
HashMap<Long, Projection> d = new HashMap<Long, Projection>();
List<Ticket> tics = ticketRepository.getFastTickets(facId);
for (Ticket t: tics) {
Projection p = projectionRepository.findById(t.getProjection().getId()).get();
d.put(t.getId(), p);
}
return d;
}
private String generateMonth(LocalDateTime d) {
String retVal = d.getYear() + "-" + d.getMonth();
return retVal;
}
private String generateWeek(LocalDateTime d) {
LocalDateTime previous = d.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
LocalDateTime next = d.with(TemporalAdjusters.previous(DayOfWeek.MONDAY));
String retVal = previous.toString() + "," + next.toString();
return retVal;
}
}
| true
|
5c75c63a83d83273a10d85caeb78324cb907675c
|
Java
|
Viktor-Ros/MultycardTest
|
/src/test/java/TestUtils.java
|
UTF-8
| 2,363
| 3.015625
| 3
|
[] |
no_license
|
import java.util.ArrayList;
import java.util.List;
public class TestUtils {
private static String string1 = "T1001,, T1002, T1003";
private static String string2 = "T1004, , T1005, ";
private static String string3 = ",T1006,";
private static String[] array;
private static List<String> list1 = new ArrayList<>();
private static List<String> list2 = new ArrayList<>();
private static List<String> list3 = new ArrayList<>();
private static List<String> list4 = new ArrayList<>();
private static List<String> list5 = new ArrayList<>();
private static List<String> list6 = new ArrayList<>();
public static String getString1() {
return string1;
}
public static String getString2() {
return string2;
}
public static String getString3() {
return string3;
}
public static String[] getArray(){
if(array == null){
array = new String[5];
array[0] = "T1005, ,T1004,";
array[1] = " T1008, ,T1004, ,T1005, ";
array[2] = "T1009, ,T1005, ";
array[3] = "T1004, ,T1006, T1007, ";
array[4] = " T1006, ,T1001, ,";
}
return array;
}
public static List<String> getList1(){
if(list1.isEmpty()){
list1.add("T1001");
list1.add("T1002");
list1.add("T1003");
}
return list1;
}
public static List<String> getList2(){
if(list2.isEmpty()) {
list2.add("T1004");
list2.add("T1005");
}
return list2;
}
public static List<String> getList3(){
if(list3.isEmpty()) {
list3.add("T1006");
}
return list3;
}
public static List<String> getList4(){
if(list4.isEmpty()) {
list4.add("T1005, ,T1004,");
list4.add(" T1008, ,T1004, ,T1005, ");
}
return list4;
}
public static List<String> getList5(){
if(list5.isEmpty()) {
list5.add("list1");
list5.add("list2");
list5.add("list3");
}
return list5;
}
public static List<String> getList6(){
if(list6.isEmpty()) {
list6.add("list3");
list6.add("list1");
list6.add("list2");
}
return list6;
}
}
| true
|
211cfa59ec043d59a4d5a83770bf00d552035576
|
Java
|
pchelomatka/onetomanymanytoone
|
/src/main/java/main/rest/EmployeeController.java
|
UTF-8
| 1,313
| 2.328125
| 2
|
[] |
no_license
|
package main.rest;
import main.Service.EmployeeService;
import main.domain.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class EmployeeController {
@Autowired
private final EmployeeService employeeService;
public EmployeeController(EmployeeService employeeService) {
this.employeeService = employeeService;
}
@RequestMapping(value = "getAllEmployees")
public List<Employee> getAllEmployees() {
return employeeService.getAllEmployees();
}
@RequestMapping(value = "getOneEmployee")
public Employee getOneEmployee(Integer id) {
return employeeService.getOneEmployee(id);
}
@RequestMapping(value = "saveEmployee")
public Employee saveEmployee(@RequestParam String firstname, String lastname, Integer salary) {
return employeeService.saveEmployee(firstname, lastname, salary);
}
@RequestMapping(value = "deleteEmployee")
public void deleteEmployee(Integer id) {
employeeService.deleteEmployee(id);
}
}
| true
|
289b59dbad10488b3e181ed1496352397d20eabf
|
Java
|
QinyiXiong/PersonalPractice
|
/src/main/java/com/pansoft/mode/factory/Animal.java
|
UTF-8
| 89
| 2.078125
| 2
|
[] |
no_license
|
package com.pansoft.mode.factory;
public interface Animal {
String getName();
}
| true
|
9da6158a7e7b8e2134134b7d1c232b486b20dee7
|
Java
|
eduardomaldonadofernandez21/CompressFile
|
/src/main/java/Interfaz.java
|
UTF-8
| 18,423
| 2.359375
| 2
|
[] |
no_license
|
import java.awt.Color;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.util.zip.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import static java.util.Locale.filter;
import javax.swing.DefaultListModel;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.filechooser.FileNameExtensionFilter;
public class Interfaz extends javax.swing.JFrame {
private JFileChooser fc = new JFileChooser();
private JOptionPane dialog = new JOptionPane();
private DefaultListModel tablaFiles = new DefaultListModel();
private FileNameExtensionFilter filter = null;
private List<File> listAllFiles = new ArrayList<File>();
private List<File> listClickFiles = new ArrayList<File>();
private Tarea tarea;
private int nFilesCompress;
private class Tarea extends SwingWorker<Void, Integer>{
private String path;
private Tarea(String ruta){
this.path = ruta;
}
@Override
protected Void doInBackground() throws Exception {
cancelarButton.setVisible(true);
int nFilesTotal = listClickFiles.size();
try{
// Objeto para referenciar a los archivos que queremos comprimir
BufferedInputStream origin = null;
// Objeto para referenciar el archivo zip de salida
FileOutputStream dest = new FileOutputStream(path);
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
int BUFFER_SIZE = 4096;
// Buffer de transferencia para almacenar datos a comprimir
byte[] data = new byte[BUFFER_SIZE];
Iterator i = listClickFiles.iterator();
while(i.hasNext()){
if(isCancelled()){
out.close();
new File(path).delete();
return null;
}
File file = (File)i.next();
FileInputStream fi = new FileInputStream(file.getPath());
origin = new BufferedInputStream(fi, BUFFER_SIZE);
ZipEntry entry = new ZipEntry( file.getName() );
out.putNextEntry( entry );
// Leemos datos desde el archivo origen y se envían al archivo destino
int count;
while((count = origin.read(data, 0, BUFFER_SIZE)) != -1){
out.write(data, 0, count);
}
nFilesCompress++;
progresoBarra.setValue((int) (((double)nFilesCompress/nFilesTotal)*100));
// Cerramos el archivo origen, ya enviado a comprimir
origin.close();
}
// Cerramos el archivo zip
progresoBarra.setValue(100);
out.close();
}catch( Exception e ){
e.printStackTrace();
}
listClickFiles.clear();
return null;
}
@Override
public void done(){
System.out.println("Tarea terminada");
cancelarButton.setVisible(false);
}
}
public Interfaz() {
initComponents();
panelProgreso.setVisible(false);
progresoBarra.setStringPainted(true);
initFiltros();
listaFileZip.setModel(tablaFiles);
guardarButton.setEnabled(false);
this.setLocationRelativeTo(null);
this.setResizable(false);
}
private void initFiltros(){
fc.setFileSelectionMode(fc.DIRECTORIES_ONLY);
filter = new FileNameExtensionFilter("Carpeta","Folder");
fc.addChoosableFileFilter(filter);
fc.setAcceptAllFileFilterUsed(false);
}
/**
* 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() {
jScrollPane1 = new javax.swing.JScrollPane();
listaFileZip = new javax.swing.JList<>();
labelLista = new javax.swing.JLabel();
guardarButton = new javax.swing.JButton();
panelProgreso = new javax.swing.JPanel();
labelProgreso = new javax.swing.JLabel();
progresoBarra = new javax.swing.JProgressBar();
cancelarButton = new javax.swing.JButton();
labelFolder = new javax.swing.JLabel();
crearZipButton = new javax.swing.JButton();
labelFer = new javax.swing.JLabel();
labelEdu = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
listaFileZip.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
listaFileZipValueChanged(evt);
}
});
jScrollPane1.setViewportView(listaFileZip);
labelLista.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
labelLista.setText("Archivos en la carpeta: ");
guardarButton.setText("Comprimir archivos");
guardarButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
guardarButtonActionPerformed(evt);
}
});
labelProgreso.setText("% Progreso");
cancelarButton.setText("Cancelar");
cancelarButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelarButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout panelProgresoLayout = new javax.swing.GroupLayout(panelProgreso);
panelProgreso.setLayout(panelProgresoLayout);
panelProgresoLayout.setHorizontalGroup(
panelProgresoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelProgresoLayout.createSequentialGroup()
.addContainerGap(19, Short.MAX_VALUE)
.addGroup(panelProgresoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelProgresoLayout.createSequentialGroup()
.addComponent(labelProgreso, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(40, 40, 40))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelProgresoLayout.createSequentialGroup()
.addComponent(progresoBarra, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelProgresoLayout.createSequentialGroup()
.addComponent(cancelarButton, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(48, 48, 48))))
);
panelProgresoLayout.setVerticalGroup(
panelProgresoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelProgresoLayout.createSequentialGroup()
.addContainerGap()
.addComponent(labelProgreso)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(progresoBarra, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(cancelarButton))
);
labelFolder.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
labelFolder.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
crearZipButton.setText("Seleccionar carpeta");
crearZipButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
crearZipButtonActionPerformed(evt);
}
});
labelFer.setText("© Fernando Marcelo Alonso");
labelEdu.setText(" Eduardo Maldonado Fernández");
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.TRAILING)
.addGroup(layout.createSequentialGroup()
.addContainerGap(300, Short.MAX_VALUE)
.addComponent(guardarButton)
.addGap(42, 42, 42))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(32, 32, 32)
.addComponent(panelProgreso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(59, 59, 59)
.addComponent(crearZipButton)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 223, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(36, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(labelFer, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(labelEdu, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(labelLista)
.addGap(63, 63, 63))))
.addGroup(layout.createSequentialGroup()
.addGap(240, 240, 240)
.addComponent(labelFolder, javax.swing.GroupLayout.PREFERRED_SIZE, 227, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(labelFer)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(labelLista)
.addComponent(labelEdu))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(labelFolder, javax.swing.GroupLayout.DEFAULT_SIZE, 12, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(guardarButton))
.addGroup(layout.createSequentialGroup()
.addComponent(panelProgreso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(70, 70, 70)
.addComponent(crearZipButton)))
.addGap(26, 26, 26))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void crearZipButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_crearZipButtonActionPerformed
if(fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
labelFolder.setText(fc.getName(fc.getSelectedFile()));
addLista(fc.getSelectedFile());
}
}//GEN-LAST:event_crearZipButtonActionPerformed
private void guardarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_guardarButtonActionPerformed
if(fc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION){
String name = dialog.showInputDialog(null,"Introduzca el nombre del archivo comprimido *.zip","Nombre del archivo comprimido", JOptionPane.QUESTION_MESSAGE);
if(name == null || name.isEmpty()){
dialog.showMessageDialog(null,"No se ha introducido ningun nombre para el archivo a comprimir","Nombre en blanco", JOptionPane.ERROR_MESSAGE);
return;
}
int [] index = listaFileZip.getSelectedIndices();
for(int i = 0; i<index.length; i++){
listClickFiles.add(listAllFiles.get(index[i]));
}
nFilesCompress = 0;
generateTarea(fc.getSelectedFile().getPath()+"/"+name+".zip");
}
}//GEN-LAST:event_guardarButtonActionPerformed
private void generateTarea(String path){
progresoBarra.setValue(0);
panelProgreso.setVisible(true);
tarea = new Tarea(path);
tarea.execute();
}
private void listaFileZipValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_listaFileZipValueChanged
int [] index = listaFileZip.getSelectedIndices();
guardarButton.setEnabled(index.length != 0);
}//GEN-LAST:event_listaFileZipValueChanged
private void cancelarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelarButtonActionPerformed
guardarButton.setEnabled(false);
tarea.cancel(true);
listaFileZip.clearSelection();
dialog.showMessageDialog(null,"Se ha cancelado el archivo a comprimir","Zip cancelado", JOptionPane.INFORMATION_MESSAGE);
}//GEN-LAST:event_cancelarButtonActionPerformed
private void addLista(File folder){
listAllFiles.clear();
tablaFiles.clear();
for(File file : folder.listFiles()){
if(!file.isDirectory()){
listAllFiles.add(file);
tablaFiles.addElement(file.getName());
}
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Interfaz.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Interfaz.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Interfaz.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Interfaz.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Interfaz().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton cancelarButton;
private javax.swing.JButton crearZipButton;
private javax.swing.JButton guardarButton;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel labelEdu;
private javax.swing.JLabel labelFer;
private javax.swing.JLabel labelFolder;
private javax.swing.JLabel labelLista;
private javax.swing.JLabel labelProgreso;
private javax.swing.JList<String> listaFileZip;
private javax.swing.JPanel panelProgreso;
private javax.swing.JProgressBar progresoBarra;
// End of variables declaration//GEN-END:variables
}
| true
|
0f2f45cedab1b2b2dd92ac210c7f4f6b78b87e8b
|
Java
|
maestrokd/JL-IP2_Metro-V1
|
/src/com/infoPulse/lessons/DaoTools/DaoObjectsDDL.java
|
UTF-8
| 4,794
| 2.515625
| 3
|
[] |
no_license
|
package com.infoPulse.lessons.DaoTools;
import com.infoPulse.lessons.DatabaseTableClases.*;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.DaoManager;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import java.sql.SQLException;
public class DaoObjectsDDL {
private Dao<Driver, Integer> driverIntegerDao;
private Dao<Line, Integer> lineIntegerDao;
private Dao<Passenger, Integer> passengerIntegerDao;
private Dao<Station, Integer> stationIntegerDao;
private Dao<StationVisit, Integer> stationVisitIntegerDao;
private Dao<Train, Integer> trainIntegerDao;
private Dao<TrainRun, Integer> trainRunIntegerDao;
private Dao<Wagon, Integer> wagonIntegerDao;
// Constructors
public DaoObjectsDDL(){
ConnectionSource connectionSource = ConnectionSql.getInstance().getConnectionSource();
try {
driverIntegerDao = DaoManager.createDao(connectionSource, Driver.class);
lineIntegerDao = DaoManager.createDao(connectionSource, Line.class);
passengerIntegerDao = DaoManager.createDao(connectionSource, Passenger.class);
stationIntegerDao = DaoManager.createDao(connectionSource, Station.class);
stationVisitIntegerDao = DaoManager.createDao(connectionSource, StationVisit.class);
trainIntegerDao = DaoManager.createDao(connectionSource, Train.class);
trainRunIntegerDao = DaoManager.createDao(connectionSource, TrainRun.class);
wagonIntegerDao = DaoManager.createDao(connectionSource, Wagon.class);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void createTableDriver() {
try {
TableUtils.createTable(driverIntegerDao);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void dropTableDriver() {
try {
TableUtils.dropTable(driverIntegerDao, true);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void createTableLine() {
try {
TableUtils.createTable(lineIntegerDao);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void dropTableLine() {
try {
TableUtils.dropTable(lineIntegerDao, true);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void createTablePassenger() {
try {
TableUtils.createTable(passengerIntegerDao);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void dropTablePassenger() {
try {
TableUtils.dropTable(passengerIntegerDao, true);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void createTableStation() {
try {
TableUtils.createTable(stationIntegerDao);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void dropTableStation() {
try {
TableUtils.dropTable(stationIntegerDao, true);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void createTableStationVisit() {
try {
TableUtils.createTable(stationVisitIntegerDao);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void dropTableStationVisit() {
try {
TableUtils.dropTable(stationVisitIntegerDao, true);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void createTableTrain() {
try {
TableUtils.createTable(trainIntegerDao);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void dropTableTrain() {
try {
TableUtils.dropTable(trainIntegerDao, true);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void createTableTrainRun() {
try {
TableUtils.createTable(trainRunIntegerDao);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void dropTableTrainRun() {
try {
TableUtils.dropTable(trainRunIntegerDao, true);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void createTableWagon() {
try {
TableUtils.createTable(wagonIntegerDao);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void dropTableWagon() {
try {
TableUtils.dropTable(wagonIntegerDao, true);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
| true
|
2e6976ce461828cdd4698a0a086a078bc6fb9c26
|
Java
|
evazquezma/curso-hibernate
|
/hibernate009/src/main/java/es/pruebas/hibernate/model/Agregado.java
|
UTF-8
| 879
| 2.328125
| 2
|
[] |
no_license
|
package es.pruebas.hibernate.model;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="AGREGADO")
public class Agregado {
@Id
private TipoFactura tipo;
private Integer numeroFacturas;
private Float total;
public TipoFactura getTipo() {
return tipo;
}
public void setTipo(TipoFactura tipo) {
this.tipo = tipo;
}
public Integer getNumeroFacturas() {
return numeroFacturas;
}
public void setNumeroFacturas(Integer numeroFacturas) {
this.numeroFacturas = numeroFacturas;
}
public Float getTotal() {
return total;
}
public void setTotal(Float total) {
this.total = total;
}
@Override
public String toString() {
return "Agregado [tipo=" + tipo + ", numeroFacturas=" + numeroFacturas
+ ", total=" + total + "]";
}
}
| true
|
ccfc554071a55fabb112969cfe720a04e210507e
|
Java
|
mouadelfakir/hybris
|
/async/netty/DispatcherServletServerInitializer.java
|
UTF-8
| 1,687
| 2.046875
| 2
|
[] |
no_license
|
package de.hybris.platform.ycommercewebservices.web;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.ssl.SslContext;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.ServletContext;
/**
* Created by i306724 on 10/2/2016.
*/
public class DispatcherServletServerInitializer extends ChannelInitializer<SocketChannel> {
private final SslContext sslCtx;
private DispatcherServlet dispatcherServlet;
private ServletContext servletContext;
public DispatcherServletServerInitializer(SslContext sslCtx, DispatcherServlet dispatcherServlet, ServletContext servletContext) {
this.sslCtx = sslCtx;
this.dispatcherServlet = dispatcherServlet;
this.servletContext = servletContext;
}
@Override
public void initChannel(SocketChannel ch) {
ChannelPipeline p = ch.pipeline();
if (sslCtx != null) {
p.addLast(sslCtx.newHandler(ch.alloc()));
}
p.addLast(new HttpRequestDecoder());
// Uncomment the following line if you don't want to handle HttpChunks.
p.addLast(new HttpObjectAggregator(1048576));
p.addLast(new HttpResponseEncoder());
// Remove the following line if you don't want automatic content compression.
//p.addLast(new HttpContentCompressor());
p.addLast(new DispatcherServletServerHandler(dispatcherServlet, servletContext));
}
}
| true
|
3c39c7c8d19e54c346fb94cee2889c61241f5857
|
Java
|
chengchuankai0915/chenchuankai0915
|
/FourTeam/app/src/main/java/fourteam/cck/com/fourteam/cck/model/CommentModel.java
|
UTF-8
| 152
| 1.507813
| 2
|
[] |
no_license
|
package fourteam.cck.com.fourteam.cck.model;
/**
* Created by C-PC on 2017/12/14.
*/
public interface CommentModel {
void getData(String id);
}
| true
|
eadc00a418ed363c57cafc099ae9a94f8d4b85f9
|
Java
|
bienvxph05562/duan_1
|
/app/src/main/java/com/activity/myapplication/model/ListDetails9.java
|
UTF-8
| 1,171
| 2.265625
| 2
|
[] |
no_license
|
package com.activity.myapplication.model;
import com.activity.myapplication.R;
import java.util.ArrayList;
public class ListDetails9 {
public static ArrayList<Model> getList(){
ArrayList<Model> list = new ArrayList<>() ;
list.add(new Model(R.mipmap.logo, " Giao hữu bóng đá với ĐH Ngọai Thương", " Ngày 10-9 chúng ta có trận giao hữu bóng đá với đội bóng của ĐH Ngoại Thương tại sân bóng FPT. "));
list.add(new Model(R.mipmap.g, " Tập luyện ", " Ngày 16-9 chúng ta có buổi tập luyện cùng đội tuyển phủi EOC. "));
list.add(new Model(R.mipmap.futsal, " Giao lưu bóng đá futsal với trẻ HaNoi Buffalo", " Ngày 22-9 chúng ta có buổi giao bóng đá futsal tập luyện cùng đội trẻ HaNoi Buffalo. "));
list.add(new Model(R.mipmap.ttt, " Giao hữu cùng fan", " Ngày 27-9 chúng ta có buổi giao lưu cùng người hâm mộ. "));
list.add(new Model(R.mipmap.n, " Tổng kết tháng 9", " Ngày 30-9 chúng ta có buổi giao liên hoan tổng kết tháng 9 tại quán nước mía tại KTX Mỹ Đình. "));
return list ;
}
}
| true
|
64d36da13eda88ed45277e832d2fca99528facaa
|
Java
|
jennnyheo/Sheerhouse_Project
|
/src/main/java/com/main/sheerhouse/user/service/UserSearchServiceImpl.java
|
UTF-8
| 1,887
| 2.140625
| 2
|
[] |
no_license
|
package com.main.sheerhouse.user.service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.main.sheerhouse.commons.StartDateBetweenEndDate;
import com.main.sheerhouse.host.domain.HomeVO;
import com.main.sheerhouse.user.domain.CommentVO;
import com.main.sheerhouse.user.domain.ResultVO;
import com.main.sheerhouse.user.domain.SearchVO;
import com.main.sheerhouse.user.mapper.UserSearchResultMapper;
@Service
public class UserSearchServiceImpl implements UserSearchService {
@Autowired
private UserSearchResultMapper mapper;
@Override
public HomeVO searchDetailList(String home_seq) {
return mapper.getDetail(home_seq);
}
@Override
public List<HomeVO> searchResultList(SearchVO search) {
List<HomeVO> resultList = mapper.getResult(search);
List<HomeVO> homeList = new ArrayList<HomeVO>();
List<String> date = StartDateBetweenEndDate.getStartAndEnd(search.getCheckin(), search.getCheckout());
for(HomeVO home : resultList) {
if(date == null) { //체크인아웃 날짜가 지정되지 않은경우
homeList.add(home);
}else if(home.getUnused_date().equals("")){ //사용불가 날짜가 지정되지 않은경우
homeList.add(home);
}else {
String[] unused = home.getUnused_date().split(",");
List<String> ud = new ArrayList<String>(Arrays.asList(unused));
boolean check = true;
for(String d : date) {
if(ud.contains(d)) {
check = false;
break;
}
}
if(check) {
homeList.add(home);
}
}
}
return homeList;
}
@Override
public List<CommentVO> getCommentList(String home_seq) {
return mapper.getComment(home_seq);
}
@Override
public String searchHostEmail(String home_seq) {
return mapper.searchHostEmail(home_seq);
}
}
| true
|
f124cd04500d01f01b31c23a18d753fcc50fb3d5
|
Java
|
riyaswati04/ins1
|
/java/com/ia/actions/service/MakeInsightsApiRequest.java
|
UTF-8
| 4,763
| 2.046875
| 2
|
[] |
no_license
|
package com.ia.actions.service;
import static com.github.rholder.retry.StopStrategies.stopAfterAttempt;
import static com.github.rholder.retry.WaitStrategies.randomWait;
import static com.ia.log.LogUtil.getLogger;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import org.apache.commons.httpclient.ConnectTimeoutException;
import com.github.rholder.retry.Retryer;
import com.github.rholder.retry.RetryerBuilder;
import com.mashape.unirest.request.HttpRequest;
import com.google.common.base.Predicates;
import com.google.inject.Inject;
import com.ia.log.Logger;
import com.mashape.unirest.http.Unirest;
public class MakeInsightsApiRequest {
private final Logger logger = getLogger(getClass());
private final GenerateLinkPostProcess generateLinkPostProcess;
@Inject
public MakeInsightsApiRequest(final GenerateLinkPostProcess generateLinkPostProcess) {
super();
this.generateLinkPostProcess = generateLinkPostProcess;
}
public void executeAsync(final String signature, final String server, final String payload,
final String clientTransactionId, final int userId, final String emailId) {
final Thread callbackThread = new Thread(new Runnable() {
@Override
public void run() {
final Callable<Boolean> callable = new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
try {
logger.debug("Making call with url=%s, payload=%s", server, payload);
final HttpRequest httpRequest = Unirest.post(server)
.header("accept", "text/xml").field("payload", payload)
.field("signature", signature).getHttpRequest();
logger.info("Generated Status %s", httpRequest.asString().getStatus());
if (httpRequest.asString().getStatus() == 200) {
generateLinkPostProcess.autheticate(
httpRequest.asString().getBody(), clientTransactionId,
userId, emailId);
return true;
}
else if (httpRequest.asString().getStatus() == 400
|| httpRequest.asString().getStatus() == 404) {
generateLinkPostProcess.logError(httpRequest.asString().getBody(),
clientTransactionId, emailId);
return true;
}
return false;
}
catch (final Exception e) {
logger.error("Exception retrying %s", e);
}
finally {
// Unirest.shutdown();
}
return true;
}
};
final Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder()
/* If HTTP response is not 200 */
.retryIfResult(Predicates.<Boolean>equalTo(false))
.retryIfExceptionOfType(IOException.class)
.retryIfExceptionOfType(SocketTimeoutException.class)
.retryIfExceptionOfType(ConnectTimeoutException.class)
.retryIfExceptionOfType(ConnectException.class)
.retryIfExceptionOfType(ExecutionException.class)
.retryIfRuntimeException()
.retryIfException()
/* Attempt for 10 minutes */
.withStopStrategy(stopAfterAttempt(10))
/* Random wait between 20 to 60 seconds */
.withWaitStrategy(randomWait(5, SECONDS, 90, SECONDS))
.build();
try {
final boolean result = retryer.call(callable);
logger.info("result --->" + result);
}
catch (final Exception e) {
logger.error("Send error");
// logger.exception(LOG_ERROR_SEND_MESSAGE, e, server);
}
}
});
callbackThread.setDaemon(true);
callbackThread.start();
}
}
| true
|
57e976c47d09241a02645a5c223707715bc18931
|
Java
|
qingnan/Archs.RestApi.Sample
|
/archs.resteasy.api.sample/src/main/java/archs/resteasy/api/SimpleEurekaInstanceConfig.java
|
UTF-8
| 683
| 2.109375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package archs.resteasy.api;
import java.net.InetAddress;
import java.net.UnknownHostException;
import com.netflix.appinfo.MyDataCenterInstanceConfig;
import archs.resteasy.api.utils.Utils;
public class SimpleEurekaInstanceConfig extends MyDataCenterInstanceConfig {
@Override
public String getHostName(boolean refresh) {
try {
return InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
Utils.logError(e.toString());
}
return null;
}
@Override
public String getInstanceId() {
return getAppname() + "-" + getIpAddress() + ":" + getNonSecurePort();
}
@Override
public String getStatusPageUrlPath() {
return "/html/f5";
}
}
| true
|
a2cc4e3d994a8500f80ac7835ea43c24a81e753f
|
Java
|
kingel000/team3
|
/mainProject/src/main/java/main/project/web/banner/dao/BannerDAOImpl.java
|
UTF-8
| 1,151
| 2.046875
| 2
|
[] |
no_license
|
package main.project.web.banner.dao;
import javax.inject.Inject;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Repository;
import main.project.web.banner.vo.BannerVO;
@Repository("bannerDAO")
public class BannerDAOImpl implements IBannerDAO {
@Inject
private SqlSessionTemplate sqlSessionTemplate;
@Override
public BannerVO selectBanner() {
return sqlSessionTemplate.selectOne("main.project.web.banner.dao.IBannerDAO.selectBanner");
}
@Override
public void updateBanner(BannerVO bannerVO) {
sqlSessionTemplate.update("main.project.web.banner.dao.IBannerDAO.updateBanner", bannerVO);
}
@Override
public void updateBannerText(BannerVO bannerVO) {
sqlSessionTemplate.update("main.project.web.banner.dao.IBannerDAO.updateBannerText", bannerVO);
}
@Override
public void updateBanner2(BannerVO bannerVO) {
sqlSessionTemplate.update("main.project.web.banner.dao.IBannerDAO.updateBanner2", bannerVO);
}
@Override
public void updateBannerText2(BannerVO bannerVO) {
sqlSessionTemplate.update("main.project.web.banner.dao.IBannerDAO.updateBannerText2", bannerVO);
}
}
| true
|
e53b7d53f6359dbe6df0a5666ed20be132891a64
|
Java
|
adorsys/xs2a-connector-examples
|
/xs2a-connector/src/main/java/de/adorsys/aspsp/xs2a/connector/spi/impl/LoginAttemptResponse.java
|
UTF-8
| 1,147
| 1.960938
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2018-2020 adorsys GmbH & Co KG
*
* 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 de.adorsys.aspsp.xs2a.connector.spi.impl;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* Example:
* {
* "operationObjectId":"12345",
* "loginFailedCount":1,
* "objectType":"LoginAttemptResponse"
* }"
*/
@Data
@NoArgsConstructor
public class LoginAttemptResponse {
private int loginFailedCount = 1;
private String objectType;
public void incrementLoginFailedCount() {
++this.loginFailedCount;
}
public String getObjectType() {
return this.getClass().getSimpleName();
}
}
| true
|
9e1b1e222713cfccbb6817197b99a049cc1ea122
|
Java
|
wlyyyrl/itrs-service
|
/src/main/java/org/wlyyy/itrs/controller/DemandController.java
|
UTF-8
| 12,949
| 2.015625
| 2
|
[
"MIT"
] |
permissive
|
package org.wlyyy.itrs.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Order;
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.bind.annotation.RestController;
import org.wlyyy.common.domain.*;
import org.wlyyy.common.service.CachedSequenceManagementService;
import org.wlyyy.itrs.dict.EnumDemandStatus;
import org.wlyyy.itrs.domain.Demand;
import org.wlyyy.itrs.domain.PositionType;
import org.wlyyy.itrs.domain.User;
import org.wlyyy.itrs.domain.UserAgent;
import org.wlyyy.itrs.request.DemandQuery;
import org.wlyyy.itrs.request.UserQuery;
import org.wlyyy.itrs.request.rest.DemandQueryRequest;
import org.wlyyy.itrs.service.*;
import org.wlyyy.itrs.vo.DemandListItemVo;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
@RestController
public class DemandController {
@Autowired
private UserService userService;
@Autowired
private DepartmentService departmentService;
@Autowired
private DemandService demandService;
@Autowired
private PositionService positionService;
@Autowired
private AuthenticationService authenticationService;
@Autowired
private CachedSequenceManagementService cachedSequenceManagementService;
private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(DemandController.class);
/**
* 分页复杂条件查询招聘需求
*
* @param demandQueryRequest 查询对象
* @param pageNo 页码
* @param pageSize 分页大小
* @return 分页展示层招聘需求列表
*/
@RequestMapping(value = "/demand/list", method = RequestMethod.GET)
public BaseRestPageableResponse<DemandListItemVo> queryDemandList(DemandQueryRequest demandQueryRequest, int pageNo, int pageSize) {
final DemandQuery demandQuery = demandQueryRequest.buildDemandQuery(
id -> {
if (id == null) {
return null;
}
final PositionType positionType = positionService.findById(id);
if (positionType == null || positionType.getSubTypes() == null || positionType.getSubTypes().size() <= 0) {
return Collections.singletonList(id);
} else {
return positionType.getSubTypes().stream().map(PositionType::getId).collect(Collectors.toList());
}
}
);
Sort sort = new Sort(new Order(Sort.Direction.DESC, "gmt_modify"));
BaseServicePageableRequest<DemandQuery> request = new BaseServicePageableRequest<>(pageNo, pageSize,
demandQuery.setStatus(EnumDemandStatus.NORMAL.getCode()).setSort(sort));
BaseServicePageableResponse<Demand> demandResult = demandService.findByCondition(request);
if (!demandResult.isSuccess()) {
return new BaseRestPageableResponse<>(false, "查询招聘需求列表失败!", null,
demandResult.getPageNo(), demandResult.getPageSize(), demandResult.getTotal());
}
List<Demand> demandList = demandResult.getDatas();
List<DemandListItemVo> datas = demandList.stream().map(source -> DemandListItemVo.buildFromDomain(source,
(pid) -> userService.findById(pid).getRealName(),
(did) -> departmentService.findById(did).getDepartmentName(),
(ptid) -> positionService.findById(ptid).getChineseName()
)).collect(Collectors.toList());
return new BaseRestPageableResponse<>(true, "查询招聘需求列表成功!", datas,
demandResult.getPageNo(), demandResult.getPageSize(), demandResult.getTotal());
}
/**
* 分页查找当前用户发布的所有招聘需求
*
* @param pageNo 页码
* @param pageSize 分页大小
* @return 分页展示层招聘需求列表
*/
@RequestMapping(value = "/myProfile/mydemand/list", method = RequestMethod.GET)
public BaseRestPageableResponse<DemandListItemVo> queryMyDemandList(int pageNo, int pageSize) {
// 获取当前登录用户信息
UserAgent userAgent = authenticationService.isLogin().getData();
Sort sort = new Sort( new Order(Sort.Direction.DESC, "status"), new Order(Sort.Direction.DESC, "gmt_modify"));
BaseServicePageableRequest<DemandQuery> request = new BaseServicePageableRequest<>(pageNo, pageSize,
new DemandQuery().setPublisherId(userAgent.getId()).setSort(sort));
BaseServicePageableResponse<Demand> demandResult = demandService.findByCondition(request);
if (!demandResult.isSuccess()) {
return new BaseRestPageableResponse<>(false, "查询招聘需求列表失败!", null,
demandResult.getPageNo(), demandResult.getPageSize(), demandResult.getTotal());
}
List<Demand> demandList = demandResult.getDatas();
List<DemandListItemVo> datas = demandList.stream().map(source -> DemandListItemVo.buildFromDomain(source,
(pid) -> userService.findById(pid).getRealName(),
(did) -> departmentService.findById(did).getDepartmentName(),
(ptid) -> positionService.findById(ptid).getChineseName()
)).collect(Collectors.toList());
return new BaseRestPageableResponse<>(true, "查询招聘需求列表成功!", datas,
demandResult.getPageNo(), demandResult.getPageSize(), demandResult.getTotal());
}
/**
* 分页查找当前用户同部门的所有招聘需求(给部门领导用)
*
* @param pageNo 页码
* @param pageSize 分页大小
* @return 分页展示层招聘需求列表
*/
@RequestMapping(value = "/myProfile/mydemandFollowing/list", method = RequestMethod.GET)
public BaseRestPageableResponse<DemandListItemVo> queryMyDemandFollowingList(int pageNo, int pageSize) {
// 获取当前登录用户信息
UserAgent userAgent = authenticationService.isLogin().getData();
// 获取同部门的用户id
Long departmentId = userService.findById(userAgent.getId()).getDepartmentId();
BaseServicePageableRequest<UserQuery> requestUser = new BaseServicePageableRequest<>(1, Integer.MAX_VALUE,
new UserQuery().setDepartmentId(departmentId));
List<User> followingUserList = userService.findByCondition(requestUser).getDatas();
List<Long> followingUserId = followingUserList.stream().map(user -> user.getId()).collect(Collectors.toList());
Sort sort = new Sort( new Order(Sort.Direction.DESC, "status"), new Order(Sort.Direction.DESC, "gmt_modify"));
BaseServicePageableRequest<DemandQuery> requestDemand = new BaseServicePageableRequest<>(pageNo, pageSize,
new DemandQuery().setSort(sort));
BaseServicePageableResponse<Demand> demandResult = demandService.findByFollowing(requestDemand, followingUserId);
List<Demand> demandList = demandResult.getDatas();
List<DemandListItemVo> datas = demandList.stream().map(source -> DemandListItemVo.buildFromDomain(source,
(pid) -> userService.findById(pid).getRealName(),
(did) -> departmentService.findById(did).getDepartmentName(),
(ptid) -> positionService.findById(ptid).getChineseName()
)).collect(Collectors.toList());
return new BaseRestPageableResponse<>(true, "查询招聘需求列表成功!", datas,
demandResult.getPageNo(), demandResult.getPageSize(), demandResult.getTotal());
}
/**
* 查询最新职位需求
*
* @return 最新展示层招聘需求列表
*/
@RequestMapping(value = "/demand/new", method = RequestMethod.GET)
public BaseRestPageableResponse<DemandListItemVo> queryDemandListNew() {
Sort sort = new Sort(new Order(Sort.Direction.DESC, "gmt_modify"));
int pageNo = 1;
int pageSize = 8;
BaseServicePageableRequest<DemandQuery> request = new BaseServicePageableRequest<>(pageNo, pageSize,
new DemandQuery().setStatus(EnumDemandStatus.NORMAL.getCode()).setSort(sort));
BaseServicePageableResponse<Demand> demandResult = demandService.findByCondition(request);
if (!demandResult.isSuccess()) {
return new BaseRestPageableResponse<>(false, "查询最新招聘需求列表失败!", null,
demandResult.getPageNo(), demandResult.getPageSize(), demandResult.getTotal());
}
List<Demand> demandList = demandResult.getDatas();
List<DemandListItemVo> datas = demandList.stream().map(source -> DemandListItemVo.buildFromDomain(source,
(pid) -> userService.findById(pid).getRealName(),
(did) -> departmentService.findById(did).getDepartmentName(),
(ptid) -> positionService.findById(ptid).getChineseName()
)).collect(Collectors.toList());
return new BaseRestPageableResponse<>(true, "查询最新招聘需求列表成功!", datas,
demandResult.getPageNo(), demandResult.getPageSize(), demandResult.getTotal());
}
/**
* 发布招聘需求
*
* @param demand 招聘需求对象
* @return 是否发布成功
*/
@RequestMapping(value = "/myProfile/demand", method = RequestMethod.POST)
public BaseRestResponse<DemandListItemVo> postDemand(Demand demand) {
// 获取当前登录用户信息
UserAgent userAgent = authenticationService.isLogin().getData();
String demandNo = cachedSequenceManagementService.getBySequenceType("seq_demand_no").toString();
demand.setDemandNo(demandNo);
demand.setPublisherId(userAgent.getId());
demand.setHrName(userAgent.getRealName());
demand.setDepartmentId(userAgent.getDepartmentId());
demand.setStatus(EnumDemandStatus.NORMAL.getCode());
BaseServiceResponse<Long> insertDemandResult = demandService.insertDemand(demand);
if (!insertDemandResult.isSuccess()) {
return new BaseRestResponse<>(false, "Create fail", null);
}
Long demandId = insertDemandResult.getData();
return new BaseRestResponse<>(true, "Create success", null);
}
/**
* 修改招聘需求
*
* @param demand 招聘需求对象
* @return 是否修改成功
*/
@RequestMapping(value = "myProfile/demand", method = RequestMethod.PUT)
public BaseRestResponse<DemandListItemVo> updateDemand(Demand demand) {
// 获取当前登录用户信息
UserAgent userAgent = authenticationService.isLogin().getData();
// 非发布的hr不能修改该需求
// if (!userAgent.getId().equals(demand.getPublisherId())) {
// return new BaseRestResponse<>(false, "修改招聘需求失败!非发布的hr不能修改该需求!", null);
// }
BaseServiceResponse<Integer> updateDemandResult = demandService.updateDemand(demand);
if (!updateDemandResult.isSuccess()) {
return new BaseRestResponse<>(false, "Update fail", null);
}
int updateCount = updateDemandResult.getData();
return new BaseRestResponse<>(true, "Update success", null);
}
@RequestMapping(value = "/demand/get/{id}", method = RequestMethod.GET)
public BaseRestResponse<DemandListItemVo> findDemandById(@PathVariable("id") Long id) {
Demand demand = demandService.findById(id);
if (demand == null) {
return new BaseRestResponse<>(false, "未找到该需求", null);
} else {
DemandListItemVo demandListItemVo = DemandListItemVo.buildFromDomain(demand,
(pid) -> userService.findById(pid).getUserName(),
(did) -> departmentService.findById(did).getDepartmentName(),
(ptid) -> positionService.findById(ptid).getChineseName());
return new BaseRestResponse<>(true, "根据招聘需求id查找招聘需求成功!", demandListItemVo);
}
}
/**
* 根据招聘需求id逻辑删除该需求
*
* @param id
* @return
*/
@RequestMapping(value = "/myProfile/demand/delete/{id}", method = RequestMethod.GET)
public BaseRestResponse<String> deleteDemand(@PathVariable("id") Long id) {
BaseServiceResponse<Integer> deleteResult = demandService.deleteDemandLogically(id);
if (!deleteResult.isSuccess()) {
new BaseRestResponse<>(false, "下架该招聘需求失败!", null);
}
return new BaseRestResponse<>(true, "下架该招聘需求成功!", null);
}
}
| true
|
93d57cd7a69b557ba1a4fb207df9ca75c6dbf11b
|
Java
|
ZhanXDD/Software
|
/src/main/java/gui/BetsMadeGUI.java
|
UTF-8
| 1,544
| 2.703125
| 3
|
[] |
no_license
|
package gui;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import businessLogic.BLFacade;
import domain.Account;
import domain.BetMade;
import javax.swing.JScrollPane;
public class BetsMadeGUI extends JFrame{
private static final long serialVersionUID = 1L;
private Account ac;
private BLFacade facade;
private JScrollPane scrollPane = new JScrollPane();
private JPanel contentPane;
private DefaultListModel<BetMade> model;
private JList<BetMade> list;
/**
* Create the application.
*/
public BetsMadeGUI() {
facade = MainGUI.getBusinessLogic();
this.ac = facade.getUser(facade.getCurrentUserAccount());
setTitle("Bets Made");
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
model = new DefaultListModel<>();
contentPane.setLayout(null);
list = new JList<BetMade>();
list.setSize(436, 243);
list.setLocation(0, 10);
list.setModel(model);
scrollPane.setBounds(10, 10, 416, 243);
scrollPane.setViewportView(list);
contentPane.add(scrollPane);
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
System.out.println(ac);
List<BetMade> listOfBets = facade.getBetsMade(ac);
System.out.println(listOfBets);
for(BetMade bet: listOfBets) {
System.out.println(bet.toString());
model.addElement(bet);
}
}
}
| true
|
effb9ff7afb2449d24e6cc14cf15ec5aa0b7b127
|
Java
|
ZhuojianHuo/authority
|
/src/main/java/com/jonsson/entity/vo/CheckResult.java
|
UTF-8
| 271
| 1.6875
| 2
|
[
"MIT"
] |
permissive
|
package com.jonsson.entity.vo;
import io.jsonwebtoken.Claims;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
public class CheckResult {
private boolean success;
private Claims claims;
private String errCode;
}
| true
|
c180e87b42c38969a6ed62beeb384850bd1b66d6
|
Java
|
vovanky/java1
|
/HinhChuNhat.java
|
UTF-8
| 499
| 3.140625
| 3
|
[] |
no_license
|
package interface1;
public class HinhChuNhat implements HinhHoc {
public double chieudai,chieurong;
public HinhChuNhat(double d, double e){
this.chieudai= d;
this.chieurong= e;
}
public double dt(){
return chieudai*chieurong;
}
public double cv() {
// TODO Auto-generated method stub
return 2*(chieudai+chieurong);
}
public void println() {
System.out.println( "dien tich hinh chu nhat: "+ dt());
System.out.println( "chu vi hinh chu nhat: "+ cv());
}
}
| true
|
59f7107dd978a68fcd3ba40a3b08646e0a4b3c46
|
Java
|
djat/suprabrowser
|
/ss.core/src/ss/client/ui/widgets/warningdialogs/WarningDialogListener.java
|
UTF-8
| 184
| 1.578125
| 2
|
[] |
no_license
|
/**
*
*/
package ss.client.ui.widgets.warningdialogs;
/**
* @author zobo
*
*/
public interface WarningDialogListener {
public void performOK();
public void performCancel();
}
| true
|
770f8485f06d1ac0166de1836620834b418ce31a
|
Java
|
TheHunterDog/JavaHuiswerkWindesheim_2021
|
/src/com/company/Artiest.java
|
UTF-8
| 597
| 3.140625
| 3
|
[] |
no_license
|
package com.company;
public class Artiest {
private String naam;
public Artiest(String naam){
this.naam = naam;
}
public String toString() {
return this.naam+ "(een artiest)";
}
public String getNaam(){
return naam;
}
public boolean equals(Object other) {
if (other != null) {
if (other instanceof Artiest) {
Artiest otherA = (Artiest) other;
if(this.naam.equals(otherA.getNaam())){
return true;
}
}
}
return false;
}
}
| true
|
e3a1c745b9750eb677d315694168839be66171d8
|
Java
|
sutaiyun/actestDemo
|
/ElkDemo/src/main/java/ElkDemo.java
|
UTF-8
| 3,214
| 2.203125
| 2
|
[] |
no_license
|
/**
* Created by sutaiyun on 2016/9/6.
*/
import com.google.gson.Gson;
import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.boot.json.GsonJsonParser;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.filter.CharacterEncodingFilter;
@RestController
@EnableAutoConfiguration
public class ElkDemo {
static ElkClient client;
@RequestMapping("/")
String home() {
return "Hello World!";
}
@RequestMapping("/logs/perf")
public String QueryLogsPerf() {
return client.Query("logs", "perf");
}
/*
curl -XGET 'localhost:8080/logs/perf/_search?pretty' -d'
{
"query" : {
"term" : {
"content.result.country" : "canada"
}
}
}'
*/
@RequestMapping(value="/logs/perf/{queryType}", method = RequestMethod.GET)
public String QueryLogsPerfByJson(@PathVariable(value = "queryType") String queryType,
@RequestBody String queryJson) {
System.out.println("queryType are:" + queryType + " queryJson are:" + queryJson);
switch (queryType) {
case "term":
/*
curl -XGET 'localhost:8080/logs/perf/term' -d '
{ "content.result.country" : "canada" } '
*/
//return client.QueryByTerm("logs", "perf", "content.result.country", "china");
return client.QueryByTerm("logs", "perf", "content.result.adcode", "220203");
case "multiSearch":
/*
curl -XGET 'localhost:8080/logs/perf/multiSearch' -d '
{["content.result.country" : "canada", "content.result.adcode" : "123456"]}'
*/
MultiSearchItem[] items = new MultiSearchItem[2];
items[0] = new MultiSearchItem("content.result.country", "china");
items[1] = new MultiSearchItem("content.result.adcode", "220203");
return client.QueryByMultiSearch("logs", "perf", items);
default:
System.out.println("queryType are " + queryType);
break;
}
return "Null";
}
@RequestMapping(value="/logs/perf/{Id}", method = RequestMethod.POST)
public String SaveLogsPerf(@PathVariable(value = "Id") Integer id,
@RequestBody String perfJson) {
return client.Save("logs", "perf", id, perfJson);
}
@Bean
public ElkClient createElkClient() {
System.out.println("This is createElkClient!!!!");
client = new ElkClient();
return client;
}
@Bean
public CharacterEncodingFilter initializeCharacterEncodingFilter() {
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setEncoding("UTF-8");
filter.setForceEncoding(true);
return filter;
}
public static void main(String[] args) throws Exception {
SpringApplication.run(ElkDemo.class, args);
System.out.println("after run!!!!");
}
}
| true
|
2f447b1f29e196f4029280b0cc83a97b1fdfd3f7
|
Java
|
Derovi/GodsVsHeroes
|
/src/main/java/by/dero/gvh/PluginCommand.java
|
UTF-8
| 189
| 1.640625
| 2
|
[] |
no_license
|
package by.dero.gvh;
import org.bukkit.command.CommandSender;
public interface PluginCommand {
void execute(CommandSender sender, String[] arguments);
String getDescription();
}
| true
|
4af2c29770f983d705da0f3cb1d251bce151778e
|
Java
|
avril1113/Practice
|
/code/CombinationSum.java
|
UTF-8
| 974
| 3.109375
| 3
|
[] |
no_license
|
class Solution {
List<List<Integer>> output = new ArrayList();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
if (candidates == null || candidates.length == 0)
return output;
Arrays.sort(candidates);
if (candidates[0] > target)
return output;
getCombination(candidates, 0, target, new ArrayList<Integer>());
return output;
}
void getCombination(int[] array, int index, int target, List temp) {
for (int i = index; i < array.length; i++) {
if (array[i] > target)
return;
List<Integer> combination = new ArrayList(temp);
combination.add(array[i]);
if (array[i] == target) {
output.add(combination);
} else {
getCombination(array, i, target-array[i], combination);
}
}
}
}
| true
|
06d5f58557670fbcfd2bd2d17979fcd1e6dc9737
|
Java
|
StuartChartersE22/w7d5_MusicShopJava_Homework
|
/src/main/java/MusicShop/Instruments/Instances/Guitar.java
|
UTF-8
| 319
| 2.203125
| 2
|
[] |
no_license
|
package MusicShop.Instruments.Instances;
import MusicShop.Instruments.Instrument;
import MusicShop.Instruments.InstrumentType;
public class Guitar extends Instrument {
public Guitar(double suppliersPrice, double retailPrice) {
super(InstrumentType.STRING, suppliersPrice, retailPrice, "whockah");
}
}
| true
|
f0e6a974956496e6b012f62c4dde76f0788f51e1
|
Java
|
terracotaPie/ToyCompiler
|
/A5/src/compiler488/ast/Indentable.java
|
UTF-8
| 2,194
| 2.859375
| 3
|
[] |
no_license
|
package compiler488.ast;
import compiler488.codegen.Instruction;
import compiler488.parser.SyntaxErrorException;
import compiler488.semantics.SemanticObject;
import compiler488.symbol.SymbolTable;
import java.io.PrintStream;
import java.util.ArrayList;
/**
* Generic features of constructs that cannot be expected to print on a single
* line.
*/
public class Indentable extends AST {
/**
* Print the whitespace that should appear at the start of the line when
* indenting to this depth.
*
* @param out
* Where to print the whitespace.
* @param depth
* How much indentation to use.
*/
// TODO: Revert tabs
public static void printIndentOn(PrintStream out, int depth) {
for (; depth > 1; depth -= 2)
out.print(" ");
if (1 == depth)
out.print(" ");
}
/**
* Print the string after indenting to the indicated depth.
*
* @param out
* Where to print the string.
* @param depth
* How much indentation to use while printing.
*/
public static void printIndentOn(PrintStream out, int depth, String s) {
printIndentOn(out, depth);
out.print(s);
}
/**
* Print the string after indenting to the indicated depth, then terminate
* the line.
*
* @param out
* Where to print the string.
* @param depth
* How much indentation to use while printing.
*/
public static void printIndentOnLn(PrintStream out, int depth, String s) {
printIndentOn(out, depth);
out.println(s);
}
/**
* Print this objects <b>toString</b> after indenting to the indicated
* depth, then terminate the line.
*
* @param out
* Where to print the <b>toString</b>.
* @param depth
* How much indentation to use while printing.
*/
public void printOn(PrintStream out, int depth) {
Indentable.printIndentOnLn(out, depth, this.toString());
}
@Override
public boolean semantic_visit(SemanticObject semanticObject) {
/* Has to be overwritten by child */
return false;
}
public void table_visit(SymbolTable symbolTable){
//pass
}
@Override
public ArrayList<Instruction> machine_visit(SymbolTable symbolTable) {
return null;
}
}
| true
|
e7065373bcaf813ddce8c22abdbf0924f05e9325
|
Java
|
MyGitHub131/MyCoreJavaProject
|
/Collection_Sorting_Using Comparator Interface/src/com/alliswell/beans/University.java
|
UTF-8
| 241
| 2.25
| 2
|
[] |
no_license
|
package com.alliswell.beans;
public class University {
int id;
String name;
String branches;
public University(int id, String name, String branches) {
this.id = id;
this.name = name;
this.branches = branches;
}
}
| true
|
02097a62451e8c23dd6f67171172d5cff08d89b5
|
Java
|
phcp/LiferayScreensReactNative
|
/LiferayScreensReactNative/android/app/src/main/java/LiferayScreenlets/WebContent/List/WebContentListScreenletViewManager.java
|
UTF-8
| 4,836
| 1.867188
| 2
|
[] |
no_license
|
package LiferayScreenlets.WebContent.List;
import android.view.View;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.uimanager.SimpleViewManager;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.annotations.ReactProp;
import com.liferay.mobile.screens.base.list.BaseListListener;
import com.liferay.mobile.screens.context.LiferayServerContext;
import com.liferay.mobile.screens.util.LiferayLocale;
import com.liferay.mobile.screens.util.LiferayLogger;
import com.liferay.mobile.screens.webcontent.list.WebContentListScreenlet;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import LiferayScreenlets.Base.EventEmitter;
import LiferayScreenlets.Base.ThemesFinder;
import LiferayScreenlets.Base.ViewUpdater;
public class WebContentListScreenletViewManager extends SimpleViewManager<WebContentListScreenlet> implements BaseListListener {
private final String NAME = "WebContentListScreenlet";
private ThemedReactContext reactContext;
private WebContentListScreenlet screenlet;
@Override
public String getName() {
return NAME;
}
@Override
protected WebContentListScreenlet createViewInstance(ThemedReactContext reactContext) {
this.reactContext = reactContext;
this.screenlet = new WebContentListScreenlet(reactContext);
this.screenlet.render(com.liferay.mobile.screens.R.layout.webcontentlist_default);
this.screenlet.setListener(this);
return this.screenlet;
}
@ReactProp(name="screenletAttributes")
public void setConfiguration(WebContentListScreenlet screenlet, ReadableMap screenletAttributes) {
this.screenlet.removeAllViews();
String themeName = screenletAttributes.getString("theme");
this.screenlet.render(
ThemesFinder.getLayoutId(
this.reactContext,
"webcontentlist_",
themeName,
com.liferay.mobile.screens.R.layout.webcontentlist_default
)
);
this.screenlet.setAutoLoad(screenletAttributes.getBoolean("autoLoad"));
this.screenlet.setFolderId(screenletAttributes.getInt("folderId"));
long groupId = screenletAttributes.getInt("groupId") == 0
? LiferayServerContext.getGroupId()
: screenletAttributes.getInt("groupId");
this.screenlet.setGroupId(groupId);
this.screenlet.setLabelFields(parse(screenletAttributes.getString("labelFields")));
this.screenlet.setFirstPageSize(screenletAttributes.getInt("firstPageSize"));
this.screenlet.setPageSize(screenletAttributes.getInt("pageSize"));
this.screenlet.setLocale(new Locale(LiferayLocale.getDefaultSupportedLocale()));
if(!this.screenlet.isAutoLoad()) {
this.screenlet.loadPage(0);
}
}
private List<String> parse(String labelFields) {
if (labelFields == null) {
LiferayLogger.e("No labelFields configured");
labelFields = "";
}
List<String> parsedFields = new ArrayList();
String[] var3 = labelFields.split(",");
int var4 = var3.length;
for (int var5 = 0; var5 < var4; ++var5) {
String text = var3[var5];
parsedFields.add(text.trim());
}
return parsedFields;
}
// BaseListListener implementation
@Override
public void onListPageFailed(int i, Exception e) {
WritableMap event = Arguments.createMap();
event.putInt("pageNumber", i);
event.putString("error", e.toString());
EventEmitter.sendEvent(this.reactContext,"onWebContentListScreenletListPageFailed", event);
}
@Override
public void onListPageReceived(int i, int i1, List list, int i2) {
WritableMap event = Arguments.createMap();
event.putString("list", list.toString());
ViewUpdater.forceViewUpdate(this.reactContext, this.screenlet.getMeasuredWidth(), this.screenlet.getMeasuredHeight());
EventEmitter.sendEvent(this.reactContext,"onWebContentListScreenletListPageReceived", event);
}
@Override
public void onListItemSelected(Object o, View view) {
WritableMap event = Arguments.createMap();
event.putString("itemSelected", o.toString());
EventEmitter.sendEvent(this.reactContext,"onWebContentListScreenletListItemSelected", event);
}
@Override
public void error(Exception e, String s) {
WritableMap event = Arguments.createMap();
event.putString("error", e.toString());
EventEmitter.sendEvent(this.reactContext,"onWebContentListScreenletError", event);
}
}
| true
|
322b33cafd24c5e646fd96f39ffc5889ddab4ba3
|
Java
|
nex5turbo/MovieRecommendApp
|
/app/src/main/java/wonyong/by/movierecommend/Constants.java
|
UTF-8
| 2,093
| 1.90625
| 2
|
[] |
no_license
|
package wonyong.by.movierecommend;
import java.util.HashMap;
import java.util.Map;
public class Constants {
public final String NAVER_ID = "YUOz3v1oFnNd9meSfC6t"; //deprecated
public final String NAVER_PWD = "j3mHCWXLxM"; //deprecated
public final String MOVIE_BOXOFFICE_KEY = "927f426e5914b98a82fe8636620488b5"; //deprecated
public final String MOVIE_BOXOFFICE_URL = "http://www.kobis.or.kr/kobisopenapi/webservice/rest/boxoffice/searchDailyBoxOfficeList.json?"; //deprecated
public final String TMDB_MOVIE_SEARCH_URL = "https://api.themoviedb.org/3/search/movie?";
public final String TMDB_MOVIE_SIMILAR_SEARCH_URL = "https://api.themoviedb.org/3/movie/"; //need movie_id
public final String TMDB_POSTER_URL = "http://image.tmdb.org/t/p/w185";
public final String NO_POSTER_URL = "https://folo.co.kr/img/gm_noimage.png";
public final String TMBD_KEY = "c0e0fe5d77f2d08e7948ca71987e4caf";
public static final Map<Integer, String> GENRES_MAP = new HashMap<Integer, String>(){
{
put(28, "액션");
put(12, "어드벤쳐");
put(16, "애니메이션");
put(35, "코메디");
put(80, "범죄");
put(99, "다큐");
put(18, "드라마");
put(10751, "가족");
put(14, "판타지");
put(36, "역사");
put(27, "호러");
put(10402, "음악");
put(9648, "미스테리");
put(10749, "로맨스");
put(878, "공상과학");
put(10770, "TV영화");
put(53, "스릴러");
put(10752, "전쟁");
put(37, "서부");
}
};
public final int TYPE_MOVIE = 0; //deprecated
public final int TYPE_NAVER = 1; //deprecated
public final int TYPE_SERVER = 2;
public final int TYPE_SEARCH_TMDB = 3;
public final int TYPE_SEARCH_SIMILAR_TMDB = 4;
public final int TYPE_NUMBER_PAGES = 5;
public final int TYPE_RANK = 6;
public String getGenre(int genre_ids){return GENRES_MAP.get(genre_ids);}
}
| true
|
888188b72518bb90806000976a11f2950ee2f6b4
|
Java
|
Purushotam-Kumar/VolleyRecyclerView
|
/app/src/main/java/com/example/windows/assignment/RecyclerAdapter.java
|
UTF-8
| 1,838
| 2.53125
| 3
|
[] |
no_license
|
package com.example.windows.assignment;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import de.hdodenhof.circleimageview.CircleImageView;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder> {
private Context context;
private UserData[] data;
public RecyclerAdapter(Context context , UserData[] data){
this.context = context;
this.data = data;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.cardview, parent, false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
UserData user = data[position];
holder.name.setText(user.getName());
holder.age.setText(user.getAge());
holder.location.setText(user.getLocation());
Glide.with(holder.image.getContext()).load(user.getUrl()).into(holder.image);
}
@Override
public int getItemCount() {
return data.length;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
CircleImageView image;
TextView name;
TextView age;
TextView location;
public MyViewHolder(View itemView) {
super(itemView);
image = itemView.findViewById(R.id.user_image);
name = itemView.findViewById(R.id.user_name);
age = itemView.findViewById(R.id.user_age);
location = itemView.findViewById(R.id.user_location);
}
}
}
| true
|
12845a64364ab2563c62f9e8f3b85d31571b44ce
|
Java
|
eduardoAfernandes/Soletra.me
|
/src/main/java/controller/Pontuacao.java
|
UTF-8
| 5,153
| 2.46875
| 2
|
[] |
no_license
|
package controller;
import model.Jogador;
import sun.security.pkcs11.wrapper.Functions;
import util.FileUtils;
import util.SortUtils;
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 java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
//import java.io.PrintWriter;
/**
* @author Junior
*/
@WebServlet(name = "Pontuacao", urlPatterns = {"/Pontuacao"})
public class Pontuacao extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
ArrayList<Jogador> leArquivo() {
ArrayList<Jogador> listaDeJogadores = new ArrayList<>();
String caminhoDir = getServletContext().getRealPath("/WEB-INF/");
File f = new File(caminhoDir + "jogadores.txt");
System.out.println(caminhoDir);
FileReader leitor;
try {
leitor = new FileReader(f);
BufferedReader bf = new BufferedReader(leitor);
String linha = "";
int i = 0;
while ((linha = bf.readLine()) != null) {
String[] partes = linha.split(",");
Jogador jogador = new Jogador(
partes[0],
partes[1],
partes[2],
partes[3],
partes[4],
partes[5],
partes[6],
partes[7],
Integer.parseInt(partes[8])
);
listaDeJogadores.add(jogador);
i++;
}
leitor.close();
bf.close();
} catch (Exception ex) {
System.out.println("Não foi possível ler no arquivo");
System.out.println(ex.getMessage());
}
return listaDeJogadores;
}
void updateUser(ArrayList<String> writeContent) {
String caminhoDir = getServletContext().getRealPath("/WEB-INF/jogadores.txt");
FileUtils file = new FileUtils(caminhoDir);
// ArrayList<ArrayList<String>> fileContent = file.getFileContent(",");
int counter = 0;
for (String item : writeContent) {
if (counter > 0) {
file.writeFile(item, Boolean.TRUE);
} else {
file.writeFile(item, Boolean.FALSE);
}
counter++;
}
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String jogador = request.getParameter("jogador");
String pontos = request.getParameter("pontos");
String tipo = request.getParameter("tipo");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
if (tipo.equals("pegar")) {
for (Jogador item : leArquivo()) {
if (item.getNomeLogin().equals(jogador)) {
out.append(String.valueOf(item.getPontos())).close();
}
}
} else {
ArrayList<String> jogadoresArquivo = new ArrayList<>();
for (Jogador item : leArquivo()) {
if (item.getNomeLogin().equals(jogador)) {
item.setPontos(Integer.parseInt(pontos));
}
jogadoresArquivo.add(item.toString());
updateUser(jogadoresArquivo);
out.append(String.valueOf(item.getPontos())).close();
}
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the
// + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| true
|
3e1b4344541924af234de832a7e22020d8e7419b
|
Java
|
cepheis/ceph-frame
|
/ceph-rocketmq-client/src/main/java/com/cepheis/rocketmq/client/consumer/PushConsumerManager.java
|
UTF-8
| 5,788
| 2.125
| 2
|
[] |
no_license
|
package com.cepheis.rocketmq.client.consumer;
import com.cepheis.rocketmq.client.config.ConsumerConfig;
import com.google.common.collect.Iterables;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.exception.MQClientException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collection;
import java.util.Map;
public class PushConsumerManager {
private final Logger logger = LoggerFactory.getLogger(getClass());
private ConsumerConfig consumerConfig;
private DefaultMQPushConsumer pushConsumer;
public void init() throws MQClientException {
initConfig();
subscribe();
pushConsumer.start();
logger.info("PushConsumerManager start success.");
}
private void subscribe() throws MQClientException {
Map<String, Map<String, MessageHandler>> route =
consumerConfig.getMessageListener().getTopicTagHandlerRoute();
for (Map.Entry<String, Map<String, MessageHandler>> entry : route.entrySet()) {
Collection<String> tags = entry.getValue().keySet();
String tagPattern;
if (CollectionUtils.isEmpty(tags) || (tags.size() == 1 && Iterables.getOnlyElement(tags).equals("*"))) {
tagPattern = "*";
} else {
tagPattern = StringUtils.join(tags, " || ");
}
pushConsumer.subscribe(entry.getKey(), tagPattern);
if (logger.isInfoEnabled()) {
logger.info("Subscribe topic={}, pattern={}", entry.getKey(), tagPattern);
}
}
}
private void initConfig() {
if (consumerConfig == null) {
throw new RuntimeException("必须设置ClientConfig");
}
if (StringUtils.isBlank(consumerConfig.getNamesrvAddr())) {
throw new RuntimeException("必须设置namesrv的地址");
}
if (StringUtils.isBlank(consumerConfig.getConsumerGroup())) {
throw new RuntimeException("必须设置consumerGroup");
}
if (consumerConfig.getMessageListener() == null) {
throw new RuntimeException("必须设置MessageListener");
}
consumerConfig.getMessageListener().check();
checkForSubscribe(consumerConfig.getMessageListener().getTopicTagHandlerRoute());
logger.info("ConsumerConfig: {}", consumerConfig.toString());
pushConsumer = new DefaultMQPushConsumer(consumerConfig.getConsumerGroup());
pushConsumer.setVipChannelEnabled(false);
pushConsumer.setNamesrvAddr(consumerConfig.getNamesrvAddr());
pushConsumer.setMessageListener(consumerConfig.getMessageListener());
if (consumerConfig.getPersistConsumerOffsetInterval() != null) {
pushConsumer.setPersistConsumerOffsetInterval(consumerConfig.getPersistConsumerOffsetInterval());
}
if (consumerConfig.getMessageModel() != null) {
pushConsumer.setMessageModel(consumerConfig.getMessageModel());
}
if (consumerConfig.getConsumeTimestamp() != null) {
pushConsumer.setConsumeTimestamp(consumerConfig.getConsumeTimestamp());
}
if (consumerConfig.getAllocateMessageQueueStrategy() != null) {
pushConsumer.setAllocateMessageQueueStrategy(consumerConfig.getAllocateMessageQueueStrategy());
}
if (consumerConfig.getConsumeThreadMin() != null) {
pushConsumer.setConsumeThreadMin(consumerConfig.getConsumeThreadMin());
}
if (consumerConfig.getConsumeThreadMax() != null) {
pushConsumer.setConsumeThreadMax(consumerConfig.getConsumeThreadMax());
}
if (consumerConfig.getAdjustThreadPoolNumsThreshold() != null) {
pushConsumer.setAdjustThreadPoolNumsThreshold(consumerConfig.getAdjustThreadPoolNumsThreshold());
}
if (consumerConfig.getConsumeConcurrentlyMaxSpan() != null) {
pushConsumer.setConsumeConcurrentlyMaxSpan(consumerConfig.getConsumeConcurrentlyMaxSpan());
}
if (consumerConfig.getPullThresholdForQueue() != null) {
pushConsumer.setPullThresholdForQueue(consumerConfig.getPullThresholdForQueue());
}
if (consumerConfig.getPullInterval() != null) {
pushConsumer.setPullInterval(consumerConfig.getPullInterval());
}
if (consumerConfig.getConsumeMessageBatchMaxSize() != null) {
pushConsumer.setConsumeMessageBatchMaxSize(consumerConfig.getConsumeMessageBatchMaxSize());
}
if (consumerConfig.getPullBatchSize() != null) {
pushConsumer.setPullBatchSize(consumerConfig.getPullBatchSize());
}
if (consumerConfig.getPostSubscriptionWhenPull() != null) {
pushConsumer.setPostSubscriptionWhenPull(consumerConfig.getPostSubscriptionWhenPull());
}
}
private void checkForSubscribe(Map<String, Map<String, MessageHandler>> topicTagHandlerRoute) {
for (Map.Entry<String, Map<String, MessageHandler>> entry : topicTagHandlerRoute.entrySet()) {
String topic = entry.getKey();
Map<String, MessageHandler> tagToHandler = entry.getValue();
if (MapUtils.isEmpty(tagToHandler)) {
throw new IllegalArgumentException("必须设置handler, topic=" + topic);
}
}
}
public void destroy() {
if (pushConsumer != null) {
pushConsumer.shutdown();
}
}
public void setConsumerConfig(ConsumerConfig consumerConfig) {
this.consumerConfig = consumerConfig;
}
}
| true
|
98133e43b9db77823616a6d0392e98200405e41b
|
Java
|
MarcinWgn/sdl_java_suite
|
/android/sdl_android/src/androidTest/java/com/smartdevicelink/test/rpc/requests/RegisterAppInterfaceTests.java
|
UTF-8
| 14,538
| 1.664063
| 2
|
[] |
no_license
|
package com.smartdevicelink.test.rpc.requests;
import com.smartdevicelink.marshal.JsonRPCMarshaller;
import com.smartdevicelink.protocol.enums.FunctionID;
import com.smartdevicelink.proxy.RPCMessage;
import com.smartdevicelink.proxy.rpc.AppInfo;
import com.smartdevicelink.proxy.rpc.DeviceInfo;
import com.smartdevicelink.proxy.rpc.RegisterAppInterface;
import com.smartdevicelink.proxy.rpc.SdlMsgVersion;
import com.smartdevicelink.proxy.rpc.TTSChunk;
import com.smartdevicelink.proxy.rpc.TemplateColorScheme;
import com.smartdevicelink.proxy.rpc.enums.AppHMIType;
import com.smartdevicelink.proxy.rpc.enums.Language;
import com.smartdevicelink.test.BaseRpcTests;
import com.smartdevicelink.test.JsonUtils;
import com.smartdevicelink.test.TestValues;
import com.smartdevicelink.test.Validator;
import com.smartdevicelink.test.json.rpc.JsonFileReader;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertNotNull;
import static junit.framework.TestCase.assertNull;
import static junit.framework.TestCase.assertTrue;
import static junit.framework.TestCase.fail;
/**
* This is a unit test class for the SmartDeviceLink library project class :
* {@link com.smartdevicelink.proxy.rpc.RegisterAppInterface}
*/
public class RegisterAppInterfaceTests extends BaseRpcTests {
@Override
protected RPCMessage createMessage() {
RegisterAppInterface msg = new RegisterAppInterface();
msg.setSdlMsgVersion(TestValues.GENERAL_SDLMSGVERSION);
msg.setAppName(TestValues.GENERAL_STRING);
msg.setNgnMediaScreenAppName(TestValues.GENERAL_STRING);
msg.setFullAppID(TestValues.GENERAL_FULL_APP_ID);
msg.setLanguageDesired(TestValues.GENERAL_LANGUAGE);
msg.setHmiDisplayLanguageDesired(TestValues.GENERAL_LANGUAGE);
msg.setHashID(TestValues.GENERAL_STRING);
msg.setTtsName(TestValues.GENERAL_TTSCHUNK_LIST);
msg.setVrSynonyms(TestValues.GENERAL_STRING_LIST);
msg.setAppHMIType(TestValues.GENERAL_APPHMITYPE_LIST);
msg.setIsMediaApplication(TestValues.GENERAL_BOOLEAN);
msg.setDeviceInfo(TestValues.GENERAL_DEVICEINFO);
msg.setAppInfo(TestValues.GENERAL_APPINFO);
msg.setDayColorScheme(TestValues.GENERAL_DAYCOLORSCHEME);
msg.setNightColorScheme(TestValues.GENERAL_NIGHTCOLORSCHEME);
return msg;
}
@Override
protected String getMessageType() {
return RPCMessage.KEY_REQUEST;
}
@Override
protected String getCommandType() {
return FunctionID.REGISTER_APP_INTERFACE.toString();
}
@Override
protected JSONObject getExpectedParameters(int sdlVersion) {
JSONObject result = new JSONObject();
try {
result.put(RegisterAppInterface.KEY_SDL_MSG_VERSION, TestValues.JSON_SDLMSGVERSION);
result.put(RegisterAppInterface.KEY_APP_NAME, TestValues.GENERAL_STRING);
result.put(RegisterAppInterface.KEY_NGN_MEDIA_SCREEN_APP_NAME, TestValues.GENERAL_STRING);
result.put(RegisterAppInterface.KEY_APP_ID, TestValues.GENERAL_APP_ID);
result.put(RegisterAppInterface.KEY_FULL_APP_ID, TestValues.GENERAL_FULL_APP_ID);
result.put(RegisterAppInterface.KEY_LANGUAGE_DESIRED, TestValues.GENERAL_LANGUAGE);
result.put(RegisterAppInterface.KEY_HMI_DISPLAY_LANGUAGE_DESIRED, TestValues.GENERAL_LANGUAGE);
result.put(RegisterAppInterface.KEY_HASH_ID, TestValues.GENERAL_STRING);
result.put(RegisterAppInterface.KEY_TTS_NAME, TestValues.JSON_TTSCHUNKS);
result.put(RegisterAppInterface.KEY_VR_SYNONYMS, JsonUtils.createJsonArray(TestValues.GENERAL_STRING_LIST));
result.put(RegisterAppInterface.KEY_APP_HMI_TYPE, JsonUtils.createJsonArrayOfJsonNames(TestValues.GENERAL_APPHMITYPE_LIST, SDL_VERSION_UNDER_TEST));
result.put(RegisterAppInterface.KEY_IS_MEDIA_APPLICATION, TestValues.GENERAL_BOOLEAN);
result.put(RegisterAppInterface.KEY_DEVICE_INFO, TestValues.JSON_DEVICEINFO);
result.put(RegisterAppInterface.KEY_APP_INFO, TestValues.JSON_APPINFO);
result.put(RegisterAppInterface.KEY_DAY_COLOR_SCHEME, TestValues.JSON_DAYCOLORSCHEME);
result.put(RegisterAppInterface.KEY_NIGHT_COLOR_SCHEME, TestValues.JSON_NIGHTCOLORSCHEME);
} catch (JSONException e) {
fail(TestValues.JSON_FAIL);
}
return result;
}
/**
* Tests the expected values of the RPC message.
*/
@Test
public void testRpcValues() {
// Test Values
SdlMsgVersion testVersion = ((RegisterAppInterface) msg).getSdlMsgVersion();
String testName = ((RegisterAppInterface) msg).getAppName();
String testNgnName = ((RegisterAppInterface) msg).getNgnMediaScreenAppName();
String testAppId = ((RegisterAppInterface) msg).getAppID();
String testFullAppId = ((RegisterAppInterface) msg).getFullAppID();
Language testLang = ((RegisterAppInterface) msg).getLanguageDesired();
Language testHmiLang = ((RegisterAppInterface) msg).getHmiDisplayLanguageDesired();
String testHashId = ((RegisterAppInterface) msg).getHashID();
List<TTSChunk> testTts = ((RegisterAppInterface) msg).getTtsName();
List<String> testSynonyms = ((RegisterAppInterface) msg).getVrSynonyms();
List<AppHMIType> testApps = ((RegisterAppInterface) msg).getAppHMIType();
Boolean testMedia = ((RegisterAppInterface) msg).getIsMediaApplication();
DeviceInfo testDeviceInfo = ((RegisterAppInterface) msg).getDeviceInfo();
AppInfo testAppInfo = ((RegisterAppInterface) msg).getAppInfo();
TemplateColorScheme testDayColorScheme = ((RegisterAppInterface) msg).getDayColorScheme();
TemplateColorScheme testNightColorScheme = ((RegisterAppInterface) msg).getNightColorScheme();
// Valid Tests
assertTrue(TestValues.TRUE, Validator.validateSdlMsgVersion(TestValues.GENERAL_SDLMSGVERSION, testVersion));
assertEquals(TestValues.MATCH, TestValues.GENERAL_STRING, testName);
assertEquals(TestValues.MATCH, TestValues.GENERAL_STRING, testNgnName);
assertEquals(TestValues.MATCH, TestValues.GENERAL_APP_ID, testAppId);
assertEquals(TestValues.MATCH, TestValues.GENERAL_FULL_APP_ID, testFullAppId);
assertEquals(TestValues.MATCH, TestValues.GENERAL_LANGUAGE, testLang);
assertEquals(TestValues.MATCH, TestValues.GENERAL_LANGUAGE, testHmiLang);
assertEquals(TestValues.MATCH, TestValues.GENERAL_STRING, testHashId);
assertTrue(TestValues.TRUE, Validator.validateTtsChunks(TestValues.GENERAL_TTSCHUNK_LIST, testTts));
assertEquals(TestValues.MATCH, TestValues.GENERAL_STRING_LIST, testSynonyms);
assertEquals(TestValues.MATCH, TestValues.GENERAL_APPHMITYPE_LIST, testApps);
assertEquals(TestValues.MATCH, (Boolean) TestValues.GENERAL_BOOLEAN, testMedia);
assertTrue(TestValues.TRUE, Validator.validateDeviceInfo(TestValues.GENERAL_DEVICEINFO, testDeviceInfo));
assertTrue(TestValues.TRUE, Validator.validateAppInfo(TestValues.GENERAL_APPINFO, testAppInfo));
assertTrue(TestValues.TRUE, Validator.validateTemplateColorScheme(TestValues.GENERAL_DAYCOLORSCHEME, testDayColorScheme));
assertTrue(TestValues.TRUE, Validator.validateTemplateColorScheme(TestValues.GENERAL_NIGHTCOLORSCHEME, testNightColorScheme));
// Invalid/Null Tests
RegisterAppInterface msg = new RegisterAppInterface();
assertNotNull(TestValues.NOT_NULL, msg);
testNullBase(msg);
assertNull(TestValues.NULL, msg.getSdlMsgVersion());
assertNull(TestValues.NULL, msg.getAppName());
assertNull(TestValues.NULL, msg.getNgnMediaScreenAppName());
assertNull(TestValues.NULL, msg.getAppID());
assertNull(TestValues.NULL, msg.getFullAppID());
assertNull(TestValues.NULL, msg.getLanguageDesired());
assertNull(TestValues.NULL, msg.getHmiDisplayLanguageDesired());
assertNull(TestValues.NULL, msg.getHashID());
assertNull(TestValues.NULL, msg.getTtsName());
assertNull(TestValues.NULL, msg.getVrSynonyms());
assertNull(TestValues.NULL, msg.getAppHMIType());
assertNull(TestValues.NULL, msg.getIsMediaApplication());
assertNull(TestValues.NULL, msg.getDeviceInfo());
assertNull(TestValues.NULL, msg.getAppInfo());
assertNull(TestValues.NULL, msg.getDayColorScheme());
assertNull(TestValues.NULL, msg.getNightColorScheme());
}
/**
* Tests a valid JSON construction of this RPC message.
*/
@Test
public void testJsonConstructor() {
JSONObject commandJson = JsonFileReader.readId(getInstrumentation().getTargetContext(), getCommandType(), getMessageType());
assertNotNull(TestValues.NOT_NULL, commandJson);
try {
Hashtable<String, Object> hash = JsonRPCMarshaller.deserializeJSONObject(commandJson);
RegisterAppInterface cmd = new RegisterAppInterface(hash);
JSONObject body = JsonUtils.readJsonObjectFromJsonObject(commandJson, getMessageType());
assertNotNull(TestValues.NOT_NULL, body);
// Test everything in the json body.
assertEquals(TestValues.MATCH, JsonUtils.readStringFromJsonObject(body, RPCMessage.KEY_FUNCTION_NAME), cmd.getFunctionName());
assertEquals(TestValues.MATCH, JsonUtils.readIntegerFromJsonObject(body, RPCMessage.KEY_CORRELATION_ID), cmd.getCorrelationID());
JSONObject parameters = JsonUtils.readJsonObjectFromJsonObject(body, RPCMessage.KEY_PARAMETERS);
JSONArray ttsNameArray = JsonUtils.readJsonArrayFromJsonObject(parameters, RegisterAppInterface.KEY_TTS_NAME);
List<TTSChunk> ttsNameList = new ArrayList<TTSChunk>();
for (int index = 0; index < ttsNameArray.length(); index++) {
TTSChunk chunk = new TTSChunk(JsonRPCMarshaller.deserializeJSONObject((JSONObject) ttsNameArray.get(index)));
ttsNameList.add(chunk);
}
assertTrue(TestValues.TRUE, Validator.validateTtsChunks(ttsNameList, cmd.getTtsName()));
assertEquals(TestValues.MATCH, JsonUtils.readStringFromJsonObject(parameters, RegisterAppInterface.KEY_HMI_DISPLAY_LANGUAGE_DESIRED), cmd.getHmiDisplayLanguageDesired().toString());
JSONArray appHmiTypeArray = JsonUtils.readJsonArrayFromJsonObject(parameters, RegisterAppInterface.KEY_APP_HMI_TYPE);
for (int index = 0; index < appHmiTypeArray.length(); index++) {
AppHMIType appHmiTypeItem = AppHMIType.valueForString(appHmiTypeArray.get(index).toString());
assertEquals(TestValues.MATCH, appHmiTypeItem, cmd.getAppHMIType().get(index));
}
assertEquals(TestValues.MATCH, JsonUtils.readStringFromJsonObject(parameters, RegisterAppInterface.KEY_APP_ID), cmd.getAppID());
assertEquals(TestValues.MATCH, JsonUtils.readStringFromJsonObject(parameters, RegisterAppInterface.KEY_FULL_APP_ID), cmd.getFullAppID());
assertEquals(TestValues.MATCH, JsonUtils.readStringFromJsonObject(parameters, RegisterAppInterface.KEY_LANGUAGE_DESIRED), cmd.getLanguageDesired().toString());
JSONObject deviceInfoObj = JsonUtils.readJsonObjectFromJsonObject(parameters, RegisterAppInterface.KEY_DEVICE_INFO);
DeviceInfo deviceInfo = new DeviceInfo(JsonRPCMarshaller.deserializeJSONObject(deviceInfoObj));
assertTrue(TestValues.TRUE, Validator.validateDeviceInfo(deviceInfo, cmd.getDeviceInfo()));
assertEquals(TestValues.MATCH, JsonUtils.readStringFromJsonObject(parameters, RegisterAppInterface.KEY_APP_NAME), cmd.getAppName());
assertEquals(TestValues.MATCH, JsonUtils.readStringFromJsonObject(parameters, RegisterAppInterface.KEY_NGN_MEDIA_SCREEN_APP_NAME), cmd.getNgnMediaScreenAppName());
assertEquals(TestValues.MATCH, JsonUtils.readBooleanFromJsonObject(parameters, RegisterAppInterface.KEY_IS_MEDIA_APPLICATION), cmd.getIsMediaApplication());
JSONObject appInfoObj = JsonUtils.readJsonObjectFromJsonObject(parameters, RegisterAppInterface.KEY_APP_INFO);
AppInfo appInfo = new AppInfo(JsonRPCMarshaller.deserializeJSONObject(appInfoObj));
assertTrue(TestValues.TRUE, Validator.validateAppInfo(appInfo, cmd.getAppInfo()));
List<String> vrSynonymsList = JsonUtils.readStringListFromJsonObject(parameters, RegisterAppInterface.KEY_VR_SYNONYMS);
List<String> testSynonymsList = cmd.getVrSynonyms();
assertEquals(TestValues.MATCH, vrSynonymsList.size(), testSynonymsList.size());
assertTrue(TestValues.TRUE, Validator.validateStringList(vrSynonymsList, testSynonymsList));
JSONObject sdlMsgVersionObj = JsonUtils.readJsonObjectFromJsonObject(parameters, RegisterAppInterface.KEY_SDL_MSG_VERSION);
SdlMsgVersion sdlMsgVersion = new SdlMsgVersion(JsonRPCMarshaller.deserializeJSONObject(sdlMsgVersionObj));
assertTrue(TestValues.TRUE, Validator.validateSdlMsgVersion(sdlMsgVersion, cmd.getSdlMsgVersion()));
assertEquals(TestValues.MATCH, JsonUtils.readStringFromJsonObject(parameters, RegisterAppInterface.KEY_HASH_ID), cmd.getHashID());
JSONObject dayColorSchemeObj = JsonUtils.readJsonObjectFromJsonObject(parameters, RegisterAppInterface.KEY_DAY_COLOR_SCHEME);
TemplateColorScheme dayColorScheme = new TemplateColorScheme(JsonRPCMarshaller.deserializeJSONObject(dayColorSchemeObj));
assertTrue(TestValues.TRUE, Validator.validateTemplateColorScheme(dayColorScheme, cmd.getDayColorScheme()));
JSONObject nightColorSchemeObj = JsonUtils.readJsonObjectFromJsonObject(parameters, RegisterAppInterface.KEY_DAY_COLOR_SCHEME);
TemplateColorScheme nightColorScheme = new TemplateColorScheme(JsonRPCMarshaller.deserializeJSONObject(nightColorSchemeObj));
assertTrue(TestValues.TRUE, Validator.validateTemplateColorScheme(nightColorScheme, cmd.getDayColorScheme()));
} catch (JSONException e) {
fail(TestValues.JSON_FAIL);
}
}
}
| true
|
e4e0d3680d2da73940e423fc62b43146381240ba
|
Java
|
agapay-conqueror/AgapayApp
|
/Agapay/app/src/main/java/com/example/agapay/QuizWorldhistory.java
|
UTF-8
| 5,064
| 2.703125
| 3
|
[] |
no_license
|
package com.example.agapay;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
public class QuizWorldhistory extends AppCompatActivity {
private TextView countLabel;
private TextView questionLabel;
private Button choice1;
private Button choice2;
private String rightAnswer;
private int rightAnswerCount = 0;
private int quizCount = 1;
static final private int QUIZ_COUNT = 10;
ArrayList<ArrayList<String>> quizArray = new ArrayList<>();
String quizData[][] = {
//{"Question", "Right Answer", "choice1", "choice2", "choice3"},
{"(TRUE OR FALSE) World Historians use a thematic approach with one major focal points.", "False", "true"},
{"(TRUE OR FALSE) INTEGRATION, how processes of world history have drawn people of the world together.", "True", "False"},
{"(TRUE OR FALSE) DIFFERENCE, how patterns of world history reveal the diversity of the human experience.", "True", "False"},
{"(TRUE OR FALSE) Hegel Bently, has observed that the term world history has never been a clear signifier with a stable referent.", "False", "True"},
{"(TRUE OR FALSE) The Journal of Global History is a scholarly journal established in 2007.", "False", "True"},
{"(TRUE OR FALSE) WHA was established in 1982.", "True", "False"},
{"(TRUE OR FALSE) Sima Qian model is based on the Mandate of Heaven.", "True", "False"},
{"(TRUE OR FALSE) During Renaissance in Asia, history was written about states or nations.", "False", "True"},
{"(TRUE OR FALSE) Voltaire, in the 18th century, attempted to revolutionize the study of world history.", "True", "False"},
{"(TRUE OR FALSE) World History became a popular genre in the 20th century with universal history.", "True", "False"}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz_worldhistory);
countLabel = (TextView) findViewById(R.id.countLabel);
questionLabel = (TextView) findViewById(R.id.questionLabel);
choice1 = (Button) findViewById(R.id.choice1);
choice2 = (Button) findViewById(R.id.choice2);
//Create quizArray from quizData.
for (int i = 0; i < quizData.length; i++) {
//prepare Array.
ArrayList<String> tmpArray = new ArrayList<>();
tmpArray.add(quizData[i][0]); //QUESTION
tmpArray.add(quizData[i][1]); //RIGHT ANSWER
tmpArray.add(quizData[i][2]); //CHOICE1
//Add tmpArray to quiz Array.
quizArray.add(tmpArray);
}
showNextQuiz();
}
public void showNextQuiz() {
countLabel.setText("Q" + quizCount);
Random random = new Random();
int randomNum = random.nextInt(quizArray.size());
ArrayList<String> quiz = quizArray.get(randomNum);
questionLabel.setText(quiz.get(0));
rightAnswer = quiz.get(1);
//Remove "QUESTION" from quiz and shuffle
quiz.remove(0);
Collections.shuffle(quiz);
//set choices
choice1.setText(quiz.get(0));
choice2.setText(quiz.get(1));
//Remove this quiz from quizArray.
quizArray.remove(randomNum);
}
public void checkAnswer(View view) {
//get pushed Button
Button answerBtn = (Button) findViewById(view.getId());
String btnText = answerBtn.getText().toString();
String alertTitle;
if (btnText.equals(rightAnswer)) {
//CORRECT
alertTitle = "Correct!";
rightAnswerCount++;
} else {
//WRONG
alertTitle = "Wrong...";
}
//Create Dialog.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(alertTitle);
builder.setMessage("Answer : " + rightAnswer);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (quizCount == QUIZ_COUNT) {
//show result.
Intent intent = new Intent(getApplicationContext(), ResultQuiz.class);
intent.putExtra("RIGHT_ANSWER_COUNT", rightAnswerCount);
startActivity(intent);
} else {
quizCount++;
showNextQuiz();
}
}
});
builder.setCancelable(false);
builder.show();
}
public void btn_Exit(View view) {
startActivity(new Intent(getApplicationContext(), Highschool.class));
}
}
| true
|
cc834696252c601dea4f0704f1440c548539d0c7
|
Java
|
LV1992/design-pattern-study
|
/src/main/java/commad/CommandA.java
|
UTF-8
| 207
| 2.34375
| 2
|
[] |
no_license
|
package commad;
/**
* 抽象command类
*/
public class CommandA extends AbstractCommand{
@Override
void execute() {
Receiver receiver = new Receiver();
receiver.action();
}
}
| true
|