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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
06ea9886fe77d213c9b8bc36fbb5ada18ee4898b
|
Java
|
OsDevCorp/BRS
|
/app/src/main/java/com/misis/brs/Database/HometaskDao.java
|
UTF-8
| 2,173
| 2.578125
| 3
|
[] |
no_license
|
package com.misis.brs.Database;
import androidx.room.Dao;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import androidx.room.Update;
/**
* список всех возможных запросов к DB для объекта Hometask
*/
@Dao
public interface HometaskDao {
/**
* добавляет запись о дз в бд
* !!!!!!!
* при уже существующей записи метод вернёт -1
* @param hometask домашнее задание
* @return возврашает id добавленного элемента
*/
@Insert(onConflict = OnConflictStrategy.IGNORE)
long insert(Hometask hometask);
/**
* обновление дз
* @param hometask домашнее задание
* @return количество обновлённых записей
*/
@Update
int update(Hometask hometask);
//задел на будущее
/**
возвращает уже завершившиеся задания функция для фильтра заданий
@param deadline время для которого мы хотим вернуть все прошедшие записи
@return список домашних заданий
*/
@Query("SELECT * FROM hometask WHERE deadline < :deadline")
Hometask[] selectOverdue(long deadline);
/**
* возвращает предстоящие несделанные задания
* @param curTime время в секундах относительно которого счмтаем
* @return список домашних заданий
*/
@Query("SELECT * FROM hometask WHERE deadline > :curTime AND checkDone == 0")
Hometask[] selectUpcoming(long curTime);
@Query("SELECT * FROM hometask WHERE semester = :semester")
Hometask[] selectForSemester(int semester);
@Query("DELETE FROM hometask WHERE deadline = :deadline")
void deleteByDeadline(long deadline);
@Query("SELECT * FROM hometask WHERE deadline = :deadline")
Hometask selectHometaskByDate(long deadline);
}
| true
|
2919a256974b1dd0eaad5c8ea8e6a979cdad9548
|
Java
|
BrendaQu/revature-exercises
|
/src/com/company/Q1.java
|
UTF-8
| 646
| 4.125
| 4
|
[] |
no_license
|
package com.company;
//Q1: Ask user to give two double input for length and breadth of a rectangle and print area type casted to int.
import java.util.Scanner;
public class Q1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter length of rectangle (double type): ");
double length = scanner.nextDouble();
System.out.println("Please enter breadth of rectangle (double type): ");
double breadth = scanner.nextDouble();
double area = length * breadth;
System.out.println("Area: " + (int) area);
}
}
| true
|
0a3563ff09f4a13c7888eefdd363903cfa41ee1f
|
Java
|
gillax/mybatis-boot-sample
|
/src/main/java/example/mybatis/PersonMapper.java
|
UTF-8
| 421
| 2.078125
| 2
|
[] |
no_license
|
package example.mybatis;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.MapKey;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface PersonMapper {
@Select("SELECT * FROM people")
List<Person> findAll();
List<Person> findAllXml();
@MapKey("id")
@Select("SELECT * FROM people")
Map<Integer, Person> findAllMap();
}
| true
|
0dd2b7dfad86bb13a36c32e0f333f4ca133a107f
|
Java
|
Lxt000806/eclipse_workspace
|
/homeProject/src/com/house/home/dao/design/PrePlanAreaDao.java
|
UTF-8
| 6,575
| 1.78125
| 2
|
[] |
no_license
|
package com.house.home.dao.design;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.house.framework.bean.Result;
import com.house.framework.commons.orm.BaseDao;
import com.house.framework.commons.orm.Page;
import com.house.framework.commons.utils.DbUtil;
import com.house.framework.commons.utils.SpringContextHolder;
import com.house.home.entity.design.PrePlan;
import com.house.home.entity.design.PrePlanArea;
import com.house.home.entity.project.CustComplaint;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;
@SuppressWarnings("serial")
@Repository
public class PrePlanAreaDao extends BaseDao{
public Page<Map<String, Object>> findPlanAreaJqgridBySql(
Page<Map<String, Object>> page, PrePlan prePlan) {
List<Object> list = new ArrayList<Object>();
String sql=" select a.OldArea, a.OldPerimeter, a.OldHeight, a.OldPaveType, a.OldBeamLength, a.OldShowerLength, a.OldShowerWidth " +
",b.isDefaultArea,a.pk,a.pavetype,d.descr custDescr,b.descr fixAreaTypeDescr,a.Area,a.perimeter,a.Height ," +
" a.BeamLength ,a.ShowerLength ,a.ShowerWidth ,a.DispSeq,x1.NOTE pavetypedescr,a.fixareatype ," +
" a.descr,a.descr preplanAreaDescr ,isnull(p1.length,0) length1 ,isnull(p1.height,0) height1," +
" isnull(p2.length,0) length2,isnull(p2.height,0) height2,p1.pk p1pk,p2.pk p2pk," +
"isnull(p1.oldlength,0) oldlength1 ,isnull(p1.oldheight,0) oldheight1," +
" isnull(p2.oldlength,0) oldlength2,isnull(p2.oldheight,0) oldheight2 " +
" from tPrePlanArea a" +
" left join tFixAreaType b on b.Code=a.FixAreaType" +
" left join tcustomer d on a.CustCode=d.code " +
" left join txtdm x1 on x1.CBM=a.PaveType and x1.id='PAVETYPE'" +
" left join (select min(pk) pk,AreaPK from tPrePlanDoor where type='1' group by AreaPK ) ppd1 on ppd1.Areapk=a.pk " +
" left join (select min(pk) pk,AreaPK from tPrePlanDoor where type='2' group by AreaPK ) ppd2 on ppd2.Areapk=a.pk " +
" left join tPrePlanDoor p1 on p1.pk=ppd1.pk " +//门
" left join tPrePlanDoor p2 on p2.pk=ppd2.pk" + //窗
" where 1=1 ";
//" order by a.DispSeq ";
if(StringUtils.isNotBlank(prePlan.getCustCode())){
sql+=" and a.custCode = ? ";
list.add(prePlan.getCustCode());
}
if (StringUtils.isNotBlank(prePlan.getDescr())) {
sql += " and a.Descr like ? ";
list.add("%"+prePlan.getDescr()+"%");
}
sql+=" order by a.DispSeq ";
return this.findPageBySql(page, sql, list.toArray());
}
public Page<Map<String, Object>> findDoorWindJqgridBySql(
Page<Map<String, Object>> page, Integer pk) {
List<Object> list = new ArrayList<Object>();
String sql=" select x1.note typedescr,length,height,a.type,a.pk,a.oldHeight,a.oldLength from tPrePlanDoor a " +
" left join tXtdm x1 on x1.cbm=a.type and x1.id='DOORWINDOW' " +
" where 1=1 ";
if(pk!=null){
sql+=" and a.AreaPk = ? ";
list.add(pk);
}else {
sql+=" and a.AreaPk = 0 ";
}
sql+=" order by a.pk";
return this.findPageBySql(page, sql, list.toArray());
}
public String getNoByCustCode(String custCode){
String sql = " select No from tPrePlan where custCode= ? ";
List<Map<String,Object>> list = this.findBySql(sql, new Object[]{custCode});
if(list != null && list.size() > 0){
return list.get(0).get("No").toString() ;
}
return "";
}
@SuppressWarnings("deprecation")
public Result doSave(PrePlanArea prePlanArea) {
Assert.notNull(prePlanArea);
Result result = new Result();
Connection conn = null;
CallableStatement call = null;
try {
HibernateTemplate hibernateTemplate = SpringContextHolder
.getBean("hibernateTemplate");
Session session = SessionFactoryUtils.getSession(
hibernateTemplate.getSessionFactory(), true);
conn = session.connection();
call = conn.prepareCall("{Call pItemPlan_prePlanArea(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
call.setString(1, prePlanArea.getM_umState());
call.setString(2, prePlanArea.getCustCode());
call.setString(3, prePlanArea.getDescr());
call.setDouble(4, prePlanArea.getArea()==null?0:prePlanArea.getArea());
call.setDouble(5, prePlanArea.getPerimeter()==null?0:prePlanArea.getPerimeter());
call.setDouble(6, prePlanArea.getHeight()==null?0:prePlanArea.getHeight());
call.setDouble(7, prePlanArea.getBeamLength()==null?0:prePlanArea.getBeamLength());
call.setDouble(8, prePlanArea.getShowerLength()==null?0:prePlanArea.getShowerLength());
call.setDouble(9, prePlanArea.getShowerWidth()==null?0:prePlanArea.getShowerWidth());
call.setDouble(10, prePlanArea.getDispSeq()==null?0:prePlanArea.getDispSeq());
call.setString(11, prePlanArea.getLastUpdatedBy());
call.setString(12, prePlanArea.getPaveType());
call.setString(13, prePlanArea.getFixAreaType());
call.registerOutParameter(14, Types.INTEGER);
call.registerOutParameter(15, Types.NVARCHAR);
call.setString(16, prePlanArea.getDetailXml());
call.setInt(17, prePlanArea.getPk()==null?0:prePlanArea.getPk());
call.setString(18, prePlanArea.getCopyCustCode());
call.setString(19, prePlanArea.getModule());
call.execute();
result.setCode(String.valueOf(call.getInt(14)));
result.setInfo(call.getString(15));
System.out.println(result.getInfo());
} catch (Exception e) {
e.printStackTrace();
} finally {
DbUtil.close(null, call, conn);
}
return result;
}
public String getDWMaxPk(String type,Integer areaPk) {
String sql =" select max(pk) pk from tPrePlanDoor where type = ? and areaPk = ? ";
List<Map<String, Object>> list = this.findBySql(sql,new Object[] { type,areaPk });
if (list != null && list.size() > 0) {
return list.get(0).get("pk").toString();
}
return null;
}
public boolean getCanUpdateArea(String custCode) {
boolean result = false;
String sql =" select * from tCustomer a" +
" left join tCusttype b on b.Code = a.CustType " +
" where a.Code = ? and b.SignQuoteType = '2' and " +
" not exists( select 1 from tBaseItemChg in_a " +
" where in_a.CustCode = a.Code and TempNo is not null and status='2')";
List<Map<String, Object>> list = this.findBySql(sql,new Object[] {custCode});
if (list != null && list.size() > 0) {
result = true;
}
return result;
}
}
| true
|
715789c0d0c3f4dadecf3c532014a8ff336e6f0b
|
Java
|
gayathri3636/Java-Guide
|
/src/example/multiplecatchblocks.java
|
UTF-8
| 505
| 3.390625
| 3
|
[] |
no_license
|
package example;
public class multiplecatchblocks {
public static void main(String[] args) {
try {
int a[]=new int[6];
a[6]=9;
int i =12;
int j=10;
int k=i/j;
System.out.println(k);
}
catch(ArithmeticException e) {
System.out.println("rest of code after handling exception");
}
catch(ArrayIndexOutOfBoundsException a) {
System.out.println("array index outofbound");
}
//executed always with or without exception.
finally {
System.out.println("bye");
}
}
}
| true
|
6ec4af444558c077c1c715373096be3efcecfc4e
|
Java
|
XWxiaowei/JavaCode
|
/design-patterns/src/main/java/com/flyweight/ConcreteFlyweight.java
|
UTF-8
| 377
| 2.296875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.flyweight;
//
//
// Generated by StarUML(tm) Java Add-In
//
// @ Project : Untitled
// @ File Name : ConcreteFlyweight.java
// @ Date : 2016/9/28
// @ Author :
//
//
public class ConcreteFlyweight extends Flyweight {
@Override
public void operation(int extrinsicstate) {
System.out.println("共享具体Flyweight" + extrinsicstate);
}
}
| true
|
fc23205bae3fbd910bd4c1d5649ff61082692cbf
|
Java
|
fernando-romulo-silva/myStudies
|
/java/quarkus/understanding-quarkus/understanding-quarkus-chapter12-putting-together/understanding-quarkus-chapter12-part01-rest-number/src/main/java/org/agoncal/fascicle/quarkus/number/IsbnNumbers.java
|
UTF-8
| 961
| 2.4375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.agoncal.fascicle.quarkus.number;
import org.eclipse.microprofile.openapi.annotations.media.Schema;
import javax.json.bind.annotation.JsonbProperty;
@Schema(description = "Several formats of book ISBN numbers")
public class IsbnNumbers {
@Schema(required = true)
@JsonbProperty("isbn_10")
private String isbn10;
@Schema(required = true)
@JsonbProperty("isbn_13")
private String isbn13;
public String getIsbn10() {
return isbn10;
}
public void setIsbn10(String isbn10) {
this.isbn10 = isbn10;
}
public String getIsbn13() {
return isbn13;
}
public void setIsbn13(String isbn13) {
this.isbn13 = isbn13;
}
// ======================================
// = Methods hash, equals, toString =
// ======================================
@Override
public String toString() {
return "BookNumbers{" + "isbn10='" + isbn10 + '\'' + ", isbn13='" + isbn13 + '\'' + '}';
}
}
| true
|
490a79f9242c6bd525577184be2878add6706848
|
Java
|
aplucas/Projeto_ControlePonto
|
/src/controllers/CadastroApontamentoController.java
|
UTF-8
| 1,880
| 2.09375
| 2
|
[] |
no_license
|
package controllers;
import java.io.IOException;
import java.sql.Date;
import java.util.List;
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 models.ApontamentoHoras;
import models.Funcionarios;
import models.ValidacaoDataHora;
/**
* Servlet implementation class CadastroApontamentoController
*/
@WebServlet(name="ServletApontamento", urlPatterns="/CadastroApontamento.do")
public class CadastroApontamentoController extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Funcionarios> listaFunc = Funcionarios.buscarTodos();
request.getSession().setAttribute("listaFunc", listaFunc);
response.sendRedirect("views/CadastroApontamento/cadastro-apontamento.jsp");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ApontamentoHoras apont = new ApontamentoHoras(new Date(ValidacaoDataHora.retornaData(request.getParameter("dataCad")).getTime()), ValidacaoDataHora.retornaHora(request.getParameter("hrEntrada")), ValidacaoDataHora.retornaHora(request.getParameter("hrSaidaAlmoco")), ValidacaoDataHora.retornaHora(request.getParameter("hrVoltaAlmoco")), ValidacaoDataHora.retornaHora(request.getParameter("hrSaida")), Funcionarios.buscarIdFuncionario(request.getParameter("idfunc")));
ApontamentoHoras.cadastrar(apont);
List<ApontamentoHoras> listaApont = ApontamentoHoras.buscarTodos();
request.setAttribute("listaApont", listaApont);
response.sendRedirect("views/ConsultaApontamento/consulta-apontamento.jsp");
}
}
| true
|
64973b5aa06c7d115c771889114375b0493a505a
|
Java
|
EduardNewtonReboucasDore/TrabalhoEngSoft
|
/pedraPapelTesoura/src/edu/trabalho01/miniKataFizzBuzzParcial/MiniKataFizzBuzzParcial.java
|
UTF-8
| 271
| 2.75
| 3
|
[] |
no_license
|
package edu.trabalho01.miniKataFizzBuzzParcial;
public class MiniKataFizzBuzzParcial {
public static String getMiniKataFizzBuzzParcial(Integer numero) {
if(numero % 3 == 0 || numero % 5 == 0) return "FizzBuzz";
return (Integer.toString(numero));
}
}
| true
|
c58b00f9eb343cdd051a64e409d313b9c3dd70dd
|
Java
|
cckmit/fcs
|
/FBPM/PM-JCK/fcs-pm-facade-wsp/src/main/java/com/born/fcs/pm/ws/base/QueryPermissionPageBase.java
|
UTF-8
| 1,045
| 2.03125
| 2
|
[] |
no_license
|
package com.born.fcs.pm.ws.base;
import java.util.List;
/**
* 控制数据权限的分页查询
*
* 按人员维度查询 loginUserId
*
* 按部门维度查询 deptIdList
*
* 表单提交人 formSubmitManId
*
* @author wuzj 2016年4月29日
*
*/
public class QueryPermissionPageBase extends QueryPageBase {
private static final long serialVersionUID = 8350199751850099385L;
//当前登陆用户
private long loginUserId;
//用户所属部门列表
private List<Long> deptIdList;
//表单提交人
private long formSubmitManId;
public long getLoginUserId() {
return this.loginUserId;
}
public void setLoginUserId(long loginUserId) {
this.loginUserId = loginUserId;
}
public List<Long> getDeptIdList() {
return this.deptIdList;
}
public void setDeptIdList(List<Long> deptIdList) {
this.deptIdList = deptIdList;
}
public long getFormSubmitManId() {
return this.formSubmitManId;
}
public void setFormSubmitManId(long formSubmitManId) {
this.formSubmitManId = formSubmitManId;
}
}
| true
|
ed6d748a3476152ea280480cbde0bcbd4fe14fdb
|
Java
|
GeorgeMcLellan/GoalTrackingApp
|
/app/src/main/java/com/development/georgemcl/goaltracker/view/MainGoalView/MainGoalViewModel.java
|
UTF-8
| 954
| 2.390625
| 2
|
[] |
no_license
|
package com.development.georgemcl.goaltracker.view.MainGoalView;
import android.app.Application;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import com.development.georgemcl.goaltracker.data.repository.GoalRepository;
import com.development.georgemcl.goaltracker.model.Goal;
import java.util.List;
import io.reactivex.Completable;
/**
* ViewModel pattern for showing goals on the main screen
*/
public class MainGoalViewModel extends AndroidViewModel {
private GoalRepository mRepository;
private LiveData<List<Goal>> mMainGoals;
public MainGoalViewModel (Application application) {
super(application);
mRepository = new GoalRepository(application);
mMainGoals = mRepository.getMainGoals();
}
public LiveData<List<Goal>> getMainGoals() {
return mMainGoals;
}
public Completable insert(Goal goal) {
return mRepository.insert(goal);
}
}
| true
|
4b821bb1e14bcd862c2051993ddb3ada24e47c79
|
Java
|
RUCKUSJERRY/JSP
|
/Jsp99_Practice/src/com/test/biz/TBiz.java
|
UTF-8
| 182
| 1.609375
| 2
|
[] |
no_license
|
package com.test.biz;
import java.util.List;
import com.test.dto.TDto;
public interface TBiz {
public TDto loginUser(String id, String pw);
public List<TDto> selectList();
}
| true
|
c98c9b09caf56d1cfb36072276979dfd60a93666
|
Java
|
yangliuwilow/myProjectCode
|
/java_base/src/com/willow/annotation/Demo.java
|
UTF-8
| 722
| 2.796875
| 3
|
[] |
no_license
|
package com.willow.annotation;
import java.lang.annotation.Annotation;
@MyAnnotation(value = "123",name = "willow")
public class Demo {
public static void main(String[] args) {
Demo demo=new Demo();
Annotation[] annotation = Demo.class.getAnnotations();
System.out.println("#######"+annotation.length);
MyAnnotation myAnnotation=Demo.class.getAnnotation(MyAnnotation.class);
System.out.println("value:"+myAnnotation.name()+myAnnotation.value());
System.out.println("simpleName:"+Demo.class.getSimpleName());
Annotation[] declaredAnnotations = Demo.class.getDeclaredAnnotations();
System.out.println("simpleName:"+Demo.class.getTypeName());
}
}
| true
|
d3d3904203c4fc8d6d2f910e6f717422321c65c5
|
Java
|
pratt-eric000/CIT360
|
/interface/src/java/com/prt/models/Table.java
|
UTF-8
| 966
| 2.40625
| 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 com.prt.models;
import java.io.Serializable;
import java.util.ArrayList;
/**
*
* @author P-ratt
*/
public class Table implements Serializable {
private String id;
private String name;
private String description;
private ArrayList<Column> columns = new ArrayList<>();
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public ArrayList<Column> getColumns() {
return columns;
}
public void setColumns(ArrayList<Column> columns) {
this.columns = columns;
}
}
| true
|
bc02d4b413e1b82b3e68a57ddac26f8ac9a855b0
|
Java
|
aliali12345/old_learnhub
|
/src/main/java/org/learn/utils/FileUtil.java
|
UTF-8
| 2,841
| 2.53125
| 3
|
[] |
no_license
|
package org.learn.utils;
import org.learn.controller.PageController;
import org.learn.enums.ConstEnum;
import org.learn.enums.MessageEnum;
import org.learn.exception.CustomizeException;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.util.UUID;
public class FileUtil {
public static String getUploadRootPath(){
URL classes = FileUtil.class.getResource("/");
return classes.getPath();
}
/**
* 上传文件返回相对路径
* @param file
* @param dirName
* @return
*/
public static String uploadFile(MultipartFile file, String rootPath, String dirName){
String relPath = null;
if (file != null && !file.isEmpty()){
String dir = rootPath + File.separator + ConstEnum.UPLOAD_ROOT_PATH.getValue() + File.separator;
File dirFile = new File(dir);
if (!dirFile.exists()){
boolean flag = dirFile.mkdir();
if (!flag){
throw new CustomizeException(MessageEnum.DIR_CREATE_FAIL);
}
}
String originalFilename = file.getOriginalFilename();
if (originalFilename == null || originalFilename.length() > 50){
originalFilename = "";
}
int uuid = UUID.randomUUID().hashCode();
String newName = uuid + "_" + originalFilename;
dirName = dirName == null ? "" : dirName + File.separator;
relPath = dirName + newName;
String fullPath = dir + relPath;
File newFile = new File(fullPath);
try {
if (newFile.createNewFile()) {
file.transferTo(newFile);
}
} catch (IOException e) {
e.printStackTrace();
throw new CustomizeException(MessageEnum.FILE_UPLOAD_FAIL);
}
}
return relPath;
}
public static void outPutFile(HttpServletResponse response, String rootPath,String filePath) throws IOException {
URL url = PageController.class.getResource(filePath);
if (url != null) {
FileInputStream fileInputStream = new FileInputStream(rootPath + File.separator + filePath);
byte[] b = new byte[fileInputStream.available()];
int readSize = fileInputStream.read(b);
if (readSize > 0) {
ServletOutputStream outputStream = response.getOutputStream();
outputStream.write(b);
outputStream.flush();
outputStream.close();
}
}else {
throw new CustomizeException(MessageEnum.FILE_NOT_FOUND.getMsg());
}
}
}
| true
|
d57399547a2361b1fab94c874d2734501628e786
|
Java
|
ucfyao/code_test_manager
|
/src/main/java/com/chainfuture/code/service/AssetService.java
|
UTF-8
| 212
| 1.617188
| 2
|
[] |
no_license
|
package com.chainfuture.code.service;
import com.chainfuture.code.bean.Asset;
import java.util.List;
/**
* Created by admin on 2018/11/1.
*/
public interface AssetService {
List<Asset> getAssetList();
}
| true
|
4b0ed33af45a37d0ce872d8a755fd37fd96c54af
|
Java
|
chabala/swing-hacks-75
|
/src/main/java/org/chabala/swinghacks/_75/WaveformDisplaySimulator.java
|
UTF-8
| 1,910
| 2.984375
| 3
|
[] |
no_license
|
package org.chabala.swinghacks._75;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class WaveformDisplaySimulator {
public static void main(String[] args) {
SwingUtilities.invokeLater(WaveformDisplaySimulator::new);
}
private WaveformDisplaySimulator() {
JFrame frame = new JFrame("Waveform Display Simulator");
frame.setBounds(20, 200, 1880, 700);
File file = chooseFile(frame);
frame.setTitle("Waveform Display Simulator - " + file.getName());
WaveformPanelContainer container = new WaveformPanelContainer();
try (AudioInputStream audioInputStream =
AudioSystem.getAudioInputStream(new BufferedInputStream(new FileInputStream(file)))) {
container.setAudioToDisplay(audioInputStream);
} catch (IOException | UnsupportedAudioFileException e) {
throw new RuntimeException(e);
}
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(container, BorderLayout.CENTER);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.validate();
frame.repaint();
}
private File chooseFile(Component parent) {
final JFileChooser fc = new JFileChooser(new File("."));
fc.setFileFilter(new FileNameExtensionFilter("WAV files", "wav", "wave"));
int returnVal = fc.showOpenDialog(parent);
if (returnVal != JFileChooser.APPROVE_OPTION) {
System.exit(0);
}
return fc.getSelectedFile();
}
}
| true
|
b253f01360f73be83b63bce1ae16dc42fed23831
|
Java
|
Milan-Stankovic/ISA
|
/src/main/java/com/isa/ISA/dbModel/PolovanRekvizit.java
|
UTF-8
| 2,025
| 2.21875
| 2
|
[
"MIT"
] |
permissive
|
package com.isa.ISA.dbModel;
import java.util.Date;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import com.isa.ISA.dbModel.enums.StatusLicitacije;
import com.isa.ISA.dbModel.korisnici.Korisnik;
@Entity
public class PolovanRekvizit {
@Id
@GeneratedValue
private long id;
private String naziv;
private String opis;
private String slika;
@ManyToOne
private Korisnik postavio;
private Date kraj;
public String getSlika() {
return slika;
}
public void setSlika(String slika) {
this.slika = slika;
}
@OneToMany
private List<Ponuda> licitacija;
@Enumerated(EnumType.STRING)
private StatusLicitacije status;
public PolovanRekvizit(){}
public List<Ponuda> getLicitacija() {
return licitacija;
}
public void setLicitacija(List<Ponuda> licitacija) {
this.licitacija = licitacija;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Korisnik getPostavio() {
return postavio;
}
public void setPostavio(Korisnik postavio) {
this.postavio = postavio;
}
public Date getKraj() {
return kraj;
}
public void setKraj(Date kraj) {
this.kraj = kraj;
}
public String getNaziv() {
return naziv;
}
public String getOpis() {
return opis;
}
public StatusLicitacije getStatus() {
return status;
}
public void setNaziv(String naziv) {
this.naziv = naziv;
}
public void setOpis(String opis) {
this.opis = opis;
}
public void setStatus(StatusLicitacije status) {
this.status = status;
}
}
| true
|
1779a8200c22a6cf94851d42490c948871dd3b51
|
Java
|
Paladin1412/house
|
/java/classes/cn/jiguang/b/a.java
|
UTF-8
| 1,091
| 1.5625
| 2
|
[
"Apache-2.0"
] |
permissive
|
package cn.jiguang.b;
import android.os.IBinder;
import android.os.IInterface;
public abstract interface a
extends IInterface
{
public abstract int a(String paramString, int paramInt);
public abstract long a(String paramString, long paramLong);
public abstract String a(String paramString1, String paramString2);
public abstract void a(int paramInt, long paramLong, boolean paramBoolean, float paramFloat, double paramDouble, String paramString);
public abstract boolean a();
public abstract boolean a(String paramString, boolean paramBoolean);
public abstract void b(String paramString, int paramInt);
public abstract void b(String paramString, long paramLong);
public abstract void b(String paramString1, String paramString2);
public abstract void b(String paramString, boolean paramBoolean);
public abstract IBinder c(String paramString1, String paramString2);
}
/* Location: /Users/gaoht/Downloads/zirom/classes-dex2jar.jar!/cn/jiguang/b/a.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/
| true
|
08597314badbd81cc1202848a5d2f77bc77180f1
|
Java
|
skunal8197/class
|
/MP2/.svn/pristine/08/08597314badbd81cc1202848a5d2f77bc77180f1.svn-base
|
UTF-8
| 2,754
| 2.3125
| 2
|
[] |
no_license
|
package edu.ncsu.csc.itrust.action;
import java.util.List;
import junit.framework.TestCase;
import edu.ncsu.csc.itrust.beans.PatientBean;
import edu.ncsu.csc.itrust.beans.PersonnelBean;
import edu.ncsu.csc.itrust.beans.PrescriptionBean;
import edu.ncsu.csc.itrust.dao.DAOFactory;
import edu.ncsu.csc.itrust.datagenerators.TestDataGenerator;
import edu.ncsu.csc.itrust.testutils.TestDAOFactory;
public class ViewExpiredPrescriptionRecordsActionTest extends TestCase {
private DAOFactory factory = TestDAOFactory.getTestInstance();
private ViewExpiredPrescriptionsAction action;
private TestDataGenerator gen;
@Override
protected void setUp() throws Exception {
gen = new TestDataGenerator();
gen.clearAllTables();
gen.standardData();
}
public void testGetPatient() throws Exception {
action = new ViewExpiredPrescriptionsAction(factory, 9000000000L);
PatientBean patient = action.getPatient(1L);
assertEquals("Random", patient.getFirstName());
assertEquals("Person", patient.getLastName());
}
public void testGetRepresentees() throws Exception {
action = new ViewExpiredPrescriptionsAction(factory, 2L);
List<PatientBean> representees = action.getRepresentees();
assertEquals(6, representees.size());
assertEquals(1, representees.get(0).getMID());
assertEquals(3, representees.get(1).getMID());
}
public void testGetPrescribingDoctor() throws Exception {
action = new ViewExpiredPrescriptionsAction(factory, 2L);
PrescriptionBean prescription = new PrescriptionBean();
prescription.setVisitID(955L);
PersonnelBean personnel = action.getPrescribingDoctor(prescription);
assertEquals(9000000000L, personnel.getMID());
}
public void testGetPrescriptionsForPatient() throws Exception {
action = new ViewExpiredPrescriptionsAction(factory, 1L);
List<PrescriptionBean> prescriptions = action.getPrescriptionsForPatient(1L);
assertEquals(0, prescriptions.size());
action = new ViewExpiredPrescriptionsAction(factory, 2L);
prescriptions = action.getPrescriptionsForPatient(2L);
assertEquals(2, prescriptions.size());
assertEquals("009042407", prescriptions.get(0).getMedication().getNDCode());
assertEquals("009042407", prescriptions.get(1).getMedication().getNDCode());
prescriptions = action.getPrescriptionsForPatient(1L);
assertEquals(0, prescriptions.size());
action = new ViewExpiredPrescriptionsAction(factory, 9000000000L);
prescriptions = action.getPrescriptionsForPatient(2L);
assertEquals(3, prescriptions.size());
assertEquals("647641512", prescriptions.get(2).getMedication().getNDCode());
assertEquals("009042407", prescriptions.get(0).getMedication().getNDCode());
assertEquals("009042407", prescriptions.get(1).getMedication().getNDCode());
}
}
| true
|
b666cde1bc43a594560b9cd40e601f3cdfe94454
|
Java
|
primetraineesix/happy-new-year
|
/src/automationtest/Variables_Q2.java
|
UTF-8
| 551
| 3
| 3
|
[] |
no_license
|
package automationtest;
/**
* Created by Jay Vaghani
*/
public class Variables_Q2 {
int id;
String name;
public Variables_Q2(int id, String name) {
this.id = id;
this.name = name;
}
public void display() {
System.out.println("This is id " + id);
System.out.println(name);
}
public static void main(String[] args) {
Variables_Q2 obj = new Variables_Q2(101, "Jay");
obj.display();
Variables_Q2 obj1 = new Variables_Q2(102, "Prime");
obj1.display();
}
}
| true
|
97eda97ac9e09cecb8df8ffcf107726fab7da793
|
Java
|
PetrovNikolia/firm
|
/src/main/java/com/example/firm/exception/custom/MyBadRequest.java
|
UTF-8
| 322
| 2.1875
| 2
|
[] |
no_license
|
package com.example.firm.exception.custom;
import com.example.firm.exception.ErrorType;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class MyBadRequest extends RuntimeException {
private ErrorType errorType;
public MyBadRequest() {
this.errorType = ErrorType.BAD_REQUEST;
}
}
| true
|
e68b7eb7e2f0a7c8bf4452921b800fc0d0e5950e
|
Java
|
hmllr44/CricketHW
|
/src/CricketGame.java
|
UTF-8
| 3,794
| 3.625
| 4
|
[] |
no_license
|
public class CricketGame {
enum Outcome
{
TODO, TODOS, TODOOS; //TODO
}
/**
* Bowls the ball and updates the game state depending on the given outcome.
* Note that after a call to this method with Outcome.HIT,
* the ball will be in play (isInPlay() returns true).
*
* @param outcome outcome of this bowl
*/
void bowl(Outcome outcome) {
}
/**
* Returns the number of times the bowler has bowled so far during the current over,
* not counting wides or no-balls.
* @return number of bowls so far in the current over
*/
int getBowlCount() {
return 0; //TODO
}
/**
* Returns the number of innings that have been completed.
* @return number of completed innings
*/
int getCompletedInnings() {
return 0; //TODO
}
/**
* Returns the number of players out in the current innings.
* @return number of players out
*/
int getOuts() {
return 0; //TODO
}
/**
* Returns the number of completed overs for the current innings.
* @return number of overs for the current innings
*/
int getOverCount() {
return 0; //TODO
}
/**
*Returns the score for one of the two sides.
* @param battingSide battingSide - if true, returns the score for the side currently at bat;
* otherwise returns the score for the other side
* @return score for one of the two sides
*/
int getScore(boolean battingSide) {
return 0; //TODO
}
/**
* Returns true if the game has ended, false otherwise.
* @return true if the game has ended, false otherwise
*/
boolean isGameEnded() {
return true; //TODO
}
/**
* Returns true if the ball is currently in play. The ball is in play directly following a
* call to bowl(Outcome.HIT) and is taken out of play by a subsequent call to safe or runOut.
* @return true if the ball is currently in play, false otherwise
*/
boolean isInPlay() {
return true; //TODO
}
/**
* Returns true if batsmen are currently running. Batsmen are running directly following a
* call to tryRun and remain in a running state until a subsequent call to safe or runOut.
* @return true if batsmen are running, false otherwise
*/
boolean isRunning() {
return true; //TODO
}
/**
* Runs the batsman out (i.e., fielders knock over wicket while batsmen are running).
* Does not count as a run. After this method is called, isRunning() returns false and
* isInPlay() returns false. Does nothing if game is already over or if batsmen are not
* running.
*/
void runOut() {
}
/**
* Transitions from ball in play to ball not in play, without an out.
* If batsmen were running, that run is successfully completed and a run is added to the
* score, After this method is called, isRunning() returns false and isInPlay() returns false.
* Method does nothing if game is already over or ball is not in play.
*/
void safe() {
}
/**
* Starts the batsmen running from one end of the pitch to the other.
* After this method is called, isRunning() returns true. If the batsmen were already
* running, that run is assumed to have completed successfully and so a run is added
* to the score for the batting side. Method does nothing if game is already over or ball
* is not in play.
*/
void tryRun() {
}
/**
* Returns 0 if side 0 is batting or 1 if side 1 is batting.
* @return 0 if side 0 is batting or 1 if side 1 is batting
*/
int whichSideIsBatting() {
return 0; //TODO
}
}
| true
|
701e03cef5b2d5e4eba07d6575de5978070c0cb2
|
Java
|
WhyDoWeLiveWithoutMeaning/ICS_Grd11
|
/projects/PersonAssignment/Test.java
|
UTF-8
| 2,072
| 4.0625
| 4
|
[] |
no_license
|
/**
* This Program makes 100 Random People and Displays their Values
*
* @Author Eric Beaulne
* 2021/02/10
*/
package eric.projects.PersonAssignment;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.concurrent.ThreadLocalRandom;
public class Test {
public static void main(String[] args){
//Get all names
String[] firstNames = Names.getFirstNames();
String[] lastNames = Names.getLastNames();
Person[] people = new Person[100];
for (int i = 0; i < people.length; i++){
String randomFirstName = randomChoice(firstNames);
String randomLastname = randomChoice(lastNames);
LocalDate randomDateOfBirth = randomDate();
people[i] = new Person(randomFirstName, randomLastname, randomDateOfBirth);
}
for (int k = 0; k < people.length; k++) {
System.out.println("User "+ (k + 1) + "| " + people[k].toString());
}
Arrays.sort(people);
System.out.println();
for (int k = 0; k < people.length; k++) {
System.out.println("User "+ (k + 1) + "| " + people[k].toString());
}
}
public static String randomChoice(String[] arr){
int choice = (int) (Math.random() * arr.length);
return arr[choice];
}
public static LocalDate randomDate(){
long minDay = LocalDate.of(2003, 1, 1).toEpochDay();
long maxDay = LocalDate.of(2006, 12, 31).toEpochDay();
long randomDay = ThreadLocalRandom.current().nextLong(minDay, maxDay);
LocalDate randomDate = LocalDate.ofEpochDay(randomDay);
return randomDate;
}
public static LocalDate randomDate(int min, int max){
long minDay = LocalDate.of(min, 1, 1).toEpochDay();
long maxDay = LocalDate.of(max, 12, 31).toEpochDay();
long randomDay = ThreadLocalRandom.current().nextLong(minDay, maxDay);
LocalDate randomDate = LocalDate.ofEpochDay(randomDay);
return randomDate;
}
}
| true
|
1373730b9b5bc2e0b72e7eb3cf35312644006f8b
|
Java
|
thoslin/ELF
|
/server/marketdata/elf.server.marketdata.provider.dbf/src/main/java/elf/server/marketdata/provider/dbf/security/SecurityDataManager.java
|
GB18030
| 4,412
| 2.078125
| 2
|
[
"BSD-3-Clause"
] |
permissive
|
package elf.server.marketdata.provider.dbf.security;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import elf.api.marketdata.securitydata.SecurityData;
import elf.server.framework.config.Configuration;
import elf.server.marketdata.provider.dbf.security.sh.ShSecurityDataBuilder;
import elf.server.marketdata.provider.dbf.security.sh.dbf.ShSecurityData;
import elf.server.marketdata.provider.dbf.security.sh.dbf.ShSecurityDbfReader;
import elf.server.marketdata.provider.dbf.security.sh.submanager.ShAccruedInterestSubManager;
import elf.server.marketdata.provider.dbf.security.sh.submanager.ShConversionRateSubManager;
import elf.server.marketdata.provider.dbf.security.sz.SzSecurityDataBuilder;
import elf.server.marketdata.provider.dbf.security.sz.dbf.SzSecurityData;
import elf.server.marketdata.provider.dbf.security.sz.dbf.SzSecurityDbfReader;
/**
* @description
* @author zhaojing
* @create 2013-8-13 3:57:08
*/
@Service
public class SecurityDataManager {
private static final Logger LOGGER = LoggerFactory.getLogger(SecurityDataManager.class);
@Autowired
private SzSecurityDataBuilder szSecurityDataBuilder;
@Autowired
private ShSecurityDataBuilder shSecurityDataBuilder;
@Autowired
private ShAccruedInterestSubManager shAccruedInterestSubManager;
@Autowired
private ShConversionRateSubManager shConversionRateSubManager;
// @Value("${szdbf.security.location}")
private String szdbfFilePath;
// @Value("${shdbf.security.location}")
private String shdbfFilePath;
private List<SecurityData> szResults = new ArrayList<SecurityData>();
private List<SecurityData> shSResults = new ArrayList<SecurityData>();
@PostConstruct
public void readSzSecurityDataFromDBF() {
Configuration configuration = new Configuration(SecurityDataManager.class, "dbfsecurity.properties");
szdbfFilePath = configuration.getProperty("szdbf.security.location");
SzSecurityDbfReader szSecurityDbfReader = new SzSecurityDbfReader(szdbfFilePath);
List<SzSecurityData> szSecurityDatas = szSecurityDbfReader.readSzDbfSecurityDatas();
for (SzSecurityData szSecurityData : szSecurityDatas) {
SecurityData securityData = szSecurityDataBuilder.convert(szSecurityData);
LOGGER.debug("ȯID=" + securityData.getSymbol() + ",ȯ=" + securityData.getName() + ",=" + securityData.getExchange() + ",=" + securityData.getConversionRate() + ",ӦϢ=" + securityData.getAccruedInterest() + ",ǷԽ=" + securityData.getSuspensionFlag());
szResults.add(securityData);
}
}
@PostConstruct
public void readShSecurityDataFromDBF() {
Configuration configuration = new Configuration(SecurityDataManager.class, "dbfsecurity.properties");
shdbfFilePath = configuration.getProperty("shdbf.security.location");
ShSecurityDbfReader shSecurityDbfReader = new ShSecurityDbfReader(shdbfFilePath);
List<ShSecurityData> shSecurityDatas = shSecurityDbfReader.readShDbfSecurityDatas();
for (ShSecurityData shSecurityData : shSecurityDatas) {
Double accruedInterest = shAccruedInterestSubManager.getAccruedInterestDatas(shSecurityData.getS1());
shSecurityData.setYjlx(accruedInterest);
Double conversionRate = shConversionRateSubManager.getAccruedInterestDatas(shSecurityData.getS1());
shSecurityData.setConversionRate(conversionRate);
SecurityData securityData = shSecurityDataBuilder.convert(shSecurityData);
LOGGER.debug("ȯID=" + securityData.getSymbol() + ",ȯ=" + securityData.getName() + ",=" + securityData.getExchange() + ",=" + securityData.getConversionRate() + ",ӦϢ=" + securityData.getAccruedInterest() + ",ǷԽ=" + securityData.getSuspensionFlag());
shSResults.add(securityData);
}
}
public List<SecurityData> getSecurityDatas(String exchangeCode) {
if ("XSHE".equals(exchangeCode)) {
if (szResults.isEmpty()) {
readSzSecurityDataFromDBF();
}
return szResults;
}
if ("XSHG".equals(exchangeCode)) {
if (shSResults.isEmpty()) {
readShSecurityDataFromDBF();
}
return shSResults;
}
return new ArrayList<SecurityData>();
}
}
| true
|
31001562dc4488be13dd0e331575023af3e6d15d
|
Java
|
James0128/FoodOnline
|
/src/com/foodonline/dao/impl/OrderDtsDAOImpl.java
|
UTF-8
| 945
| 2.25
| 2
|
[] |
no_license
|
package com.foodonline.dao.impl;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import com.foodonline.dao.OrderDtsDAO;
import com.foodonline.entity.Orderdts;
public class OrderDtsDAOImpl implements OrderDtsDAO {
SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
//生成订单子表(订单明细)
@Override
public void addOrderDts(Orderdts dts) {
Session session=sessionFactory.getCurrentSession();
session.saveOrUpdate(dts);
}
//根据订单主表编号获取订单明细列表
@Override
public List getOrderDtsByOid(int oid) {
Session session=sessionFactory.getCurrentSession();
Criteria c=session.createCriteria(Orderdts.class);
c.add(Restrictions.eq("orders.oid", oid));
return c.list();
}
}
| true
|
83c9b68912e3fc814753c691f22194dfd16e9c3d
|
Java
|
vr-rajesh/Online-Dry-Cleaning-Booking-Application
|
/springbootapp/src/main/java/com/cg/services/IPaymentService.java
|
UTF-8
| 582
| 1.992188
| 2
|
[] |
no_license
|
package com.cg.services;
import java.util.List;
import com.cg.entities.Payment;
import com.cg.exception.PaymentNotFoundException;
public interface IPaymentService {
public Payment addPayment(Payment payment);
public Payment removePayment(long paymentid) throws PaymentNotFoundException;
public Payment updatePayment(long paymentid, Payment payment) throws PaymentNotFoundException;
public Payment getPayment(long paymentid) throws PaymentNotFoundException;
public List<Payment> getAllPaymentDetails();
// public List<Payment> getPaymentsByDate();
}
| true
|
9cbe827bcd1988a0b3b93daabed2b2dc85085f7e
|
Java
|
andynvt/Attendance-RFID
|
/src/main/java/sukien/view/SuKien_ThemDS.java
|
UTF-8
| 28,628
| 1.828125
| 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 sukien.view;
import static administrator.settings.Config.bg_Color1;
import static administrator.settings.Config.bg_Color2;
import canbo.model.CanBo_Model;
import canbo.view.CanBo_List;
import other.custom.GradientButton;
import dscanbo.controller.DSCanBo_Controller;
import dscanbo.model.DSCanBo_Model;
import dscanbo.view.DSCanBo_View;
import dssinhvien.controller.DSSinhVien_Controller;
import dssinhvien.model.DSSinhVien_Model;
import dssinhvien.view.DSSinhVien_View;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import javax.swing.JDialog;
import javax.swing.table.DefaultTableModel;
import other.custom.Alert;
import other.custom.TransitionPane;
import resources.Resources;
import sinhvien.model.SinhVien_Model;
import sinhvien.view.SinhVien_List;
import sukien.controller.SuKien_Controller;
/**
*
* @author chuna
*/
public class SuKien_ThemDS extends javax.swing.JDialog implements ActionListener {
private String[] columnNamesSV = {"Mã sinh viên", "Họ tên", "Mã thẻ"};
private String[] columnNamesCB = {"Mã cán bộ", "Họ tên", "Mã thẻ"};
final static int CANBO = 1;
final static int SINHVIEN = 2;
private static SuKien_ThemDS themDS;
private static SuKien_View VIEW = SuKien_View.getView();
private int choose;
private String mask;
private static SuKien_ChonKieuNhap chonDanhSach;
private CanBo_List canBo_List;
private SinhVien_List sinhVien_List;
private GradientButton btn_Them, btn_Huy;
private ArrayList<DSCanBo_Model> dSCanBo_Models = new ArrayList<>();
private ArrayList<CanBo_Model> canBo_Models = new ArrayList<>();
private ArrayList<SinhVien_Model> sinhVien_Models = new ArrayList<>();
private ArrayList<DSSinhVien_Model> dSSinhVien_Models = new ArrayList<>();
private ArrayList<DSCanBo_Model> dSCanBoTonTai;
private ArrayList<DSSinhVien_Model> dSSinhVienTonTai;
private JDialog dialog;
private String thatBai;
public SuKien_ThemDS(String mask) {
initComponents();
themDS = this;
this.mask = mask;
canBo_List = new CanBo_List();
sinhVien_List = new SinhVien_List();
createUI();
}
private void createUI() {
chonDanhSach = new SuKien_ChonKieuNhap(SuKien_ChonKieuNhap.HETHONG);
chonDanhSach.setLocationRelativeTo(VIEW);
chonDanhSach.setVisible(true);
btn_Them = new GradientButton(bg_Color1, bg_Color2, Resources.them_Icon);
btn_Huy = new GradientButton(bg_Color1, bg_Color2, Resources.huy_Icon);
pnl_Task.add(btn_Them);
pnl_Task.add(btn_Huy);
btn_Them.addActionListener(this);
btn_Huy.addActionListener(this);
pack();
dialog = new JDialog();
dialog.setSize(new Dimension(507, 175));
pnl_Duplicate.setVisible(false);
dialog.getContentPane().add(pnl_Confirm);
dialog.pack();
dialog.setResizable(false);
dialog.setAlwaysOnTop(true);
dialog.setLocationRelativeTo(this);
}
public static SuKien_ThemDS getThemDS() {
return themDS;
}
public void setChoose(int choose) {
this.choose = choose;
showTable();
}
public void showTable() {
switch (choose) {
case CANBO: {
showCanBoList();
pack();
break;
}
case SINHVIEN: {
showSinhVienList();
pack();
break;
}
}
}
public void showCanBoList() {
pnl_Table.removeAll();
pnl_Table.add(canBo_List);
canBo_List.execute();
pnl_Table.validate();
pnl_Table.repaint();
canBo_Models = CanBo_List.getListSelected();
}
public void showSinhVienList() {
pnl_Table.removeAll();
pnl_Table.add(sinhVien_List);
sinhVien_List.execute();
pnl_Table.validate();
pnl_Table.repaint();
sinhVien_Models = SinhVien_List.getListSelected();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
pnl_Confirm = new javax.swing.JPanel();
lblWarning = new javax.swing.JLabel();
btnCancel = new javax.swing.JButton();
lblTitle = new javax.swing.JLabel();
btnSkip = new javax.swing.JButton();
btnReplace = new javax.swing.JButton();
btnDetails = new javax.swing.JButton();
pnl_Duplicate = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
tblTonTai = new javax.swing.JTable();
pnl_Task = new javax.swing.JPanel();
pnl_Table = new javax.swing.JPanel();
pnl_Confirm.setBackground(new java.awt.Color(255, 255, 255));
lblWarning.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
lblWarning.setText("Có 1 cán bộ đã tồn tại trong hệ thống, bạn có muốn ghi đè lên dữ liệu cũ?");
lblWarning.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 10, 1, 10));
btnCancel.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
btnCancel.setText("Cancel");
btnCancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCancelActionPerformed(evt);
}
});
lblTitle.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
lblTitle.setText("Import 14 cán bộ từ file excel");
lblTitle.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 10, 1, 10));
btnSkip.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
btnSkip.setText("Bỏ qua");
btnSkip.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSkipActionPerformed(evt);
}
});
btnReplace.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
btnReplace.setText("Ghi đè");
btnReplace.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnReplaceActionPerformed(evt);
}
});
btnDetails.setText("Chi tiết");
btnDetails.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnDetailsActionPerformed(evt);
}
});
tblTonTai.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
tblTonTai.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
tblTonTai.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_NEXT_COLUMN);
tblTonTai.setFillsViewportHeight(true);
tblTonTai.setFocusable(false);
tblTonTai.setRequestFocusEnabled(false);
tblTonTai.setRowHeight(20);
tblTonTai.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
tblTonTai.setShowHorizontalLines(false);
tblTonTai.setShowVerticalLines(false);
jScrollPane2.setViewportView(tblTonTai);
javax.swing.GroupLayout pnl_DuplicateLayout = new javax.swing.GroupLayout(pnl_Duplicate);
pnl_Duplicate.setLayout(pnl_DuplicateLayout);
pnl_DuplicateLayout.setHorizontalGroup(
pnl_DuplicateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnl_DuplicateLayout.createSequentialGroup()
.addGap(0, 0, 0)
.addComponent(jScrollPane2)
.addGap(0, 0, 0))
);
pnl_DuplicateLayout.setVerticalGroup(
pnl_DuplicateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 128, Short.MAX_VALUE)
);
javax.swing.GroupLayout pnl_ConfirmLayout = new javax.swing.GroupLayout(pnl_Confirm);
pnl_Confirm.setLayout(pnl_ConfirmLayout);
pnl_ConfirmLayout.setHorizontalGroup(
pnl_ConfirmLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnl_ConfirmLayout.createSequentialGroup()
.addContainerGap()
.addGroup(pnl_ConfirmLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnl_ConfirmLayout.createSequentialGroup()
.addGroup(pnl_ConfirmLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblWarning, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lblTitle, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnl_ConfirmLayout.createSequentialGroup()
.addGap(10, 10, 10)
.addGroup(pnl_ConfirmLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnl_ConfirmLayout.createSequentialGroup()
.addComponent(btnDetails, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnReplace)
.addGap(18, 18, 18)
.addComponent(btnSkip)
.addGap(18, 18, 18)
.addComponent(btnCancel))
.addComponent(pnl_Duplicate, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(25, 25, 25))))
);
pnl_ConfirmLayout.setVerticalGroup(
pnl_ConfirmLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnl_ConfirmLayout.createSequentialGroup()
.addGap(8, 8, 8)
.addComponent(lblTitle, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblWarning, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(pnl_Duplicate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 24, Short.MAX_VALUE)
.addGroup(pnl_ConfirmLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnDetails)
.addComponent(btnReplace)
.addComponent(btnSkip)
.addComponent(btnCancel))
.addContainerGap())
);
pnl_Task.setMinimumSize(new java.awt.Dimension(0, 45));
pnl_Task.setPreferredSize(new java.awt.Dimension(0, 45));
pnl_Task.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 10, 2));
pnl_Table.setLayout(new java.awt.GridLayout(1, 0));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(pnl_Task, javax.swing.GroupLayout.DEFAULT_SIZE, 967, Short.MAX_VALUE)
.addComponent(pnl_Table, javax.swing.GroupLayout.DEFAULT_SIZE, 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()
.addComponent(pnl_Table, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(0, 0, 0)
.addComponent(pnl_Task, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
}// </editor-fold>//GEN-END:initComponents
private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
TransitionPane.closeDialogBox();
dialog.dispose();
}//GEN-LAST:event_btnCancelActionPerformed
private void btnSkipActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSkipActionPerformed
if (choose == CANBO) {
int countSuccess = 0;
DSCanBo_View.getController().add_canBoThamGia(dSCanBo_Models, mask);
updateCBTable();
if (!DSCanBo_Controller.getAdd_Failed().isEmpty()) {
thatBai = "";
SuKien_Controller.getAdd_Failed().forEach((t) -> {
thatBai += "Thêm cán bộ có mã " + t.getMaSK() + " thất bại.\n";
});
Alert.showMessageDialog(VIEW, thatBai);
countSuccess += dSCanBo_Models.size() - DSCanBo_Controller.getAdd_Failed().size();
}
if (countSuccess > 0) {
Alert.showMessageDialog(VIEW, "Đã thêm thành công " + countSuccess + " sinh viên.", "Thông báo");
}
} else if (choose == SINHVIEN) {
int countSuccess = 0;
DSSinhVien_View.getController().add_sinhVienThamGia(dSSinhVien_Models, mask);
updateDSSVTable();
if (!DSSinhVien_Controller.getAdd_Failed().isEmpty()) {
thatBai = "";
DSSinhVien_Controller.getAdd_Failed().forEach((t) -> {
thatBai += "Thêm sinh viên có mã " + t.getMaSV() + " thất bại.\n";
});
Alert.showMessageDialog(VIEW, thatBai);
countSuccess += dSSinhVien_Models.size() - DSSinhVien_Controller.getAdd_Failed().size();
}
if (countSuccess > 0) {
Alert.showMessageDialog(VIEW, "Đã thêm thành công " + countSuccess + " sinh viên.", "Thông báo");
}
}
}//GEN-LAST:event_btnSkipActionPerformed
private void btnReplaceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnReplaceActionPerformed
if (choose == CANBO) {
int countSuccess = 0;
DSCanBo_View.getController().update_canBoThamGia(dSCanBoTonTai, mask);
DSCanBo_View.getController().add_canBoThamGia(dSCanBo_Models, mask);
updateCBTable();
if (!DSCanBo_Controller.getAdd_Failed().isEmpty()) {
thatBai = "";
DSCanBo_Controller.getAdd_Failed().forEach((t) -> {
thatBai += "Thêm cán bộ có mã " + t.getMaCB() + " thất bại.\n";
});
Alert.showMessageDialog(VIEW, thatBai);
countSuccess += dSCanBo_Models.size() + DSCanBo_Controller.getAdd_Failed().size();
}
if (!DSCanBo_Controller.getUpdate_Failed().isEmpty()) {
thatBai = "";
DSCanBo_Controller.getUpdate_Failed().forEach((t) -> {
thatBai += "Ghi đè cán bộ có mã " + t.getMaCB() + " thất bại.\n";
});
Alert.showMessageDialog(VIEW, thatBai);
countSuccess += dSCanBoTonTai.size() + DSCanBo_Controller.getUpdate_Failed().size();
}
if (countSuccess > 0) {
Alert.showMessageDialog(VIEW, "Đã thêm thành công " + countSuccess + " cán bộ.", "Thông báo");
}
} else if (choose == SINHVIEN) {
int countSuccess = 0;
DSSinhVien_View.getController().update_sinhVienThamGia(dSSinhVienTonTai, mask);
DSSinhVien_View.getController().add_sinhVienThamGia(dSSinhVien_Models, mask);
updateDSSVTable();
if (!DSSinhVien_Controller.getAdd_Failed().isEmpty()) {
thatBai = "";
DSSinhVien_Controller.getAdd_Failed().forEach((t) -> {
thatBai += "Thêm sinh viên có mã " + t.getMaSV() + " thất bại.\n";
});
Alert.showMessageDialog(VIEW, thatBai);
countSuccess += dSSinhVien_Models.size() - DSSinhVien_Controller.getAdd_Failed().size();
}
if (!DSSinhVien_Controller.getUpdate_Failed().isEmpty()) {
thatBai = "";
DSSinhVien_Controller.getUpdate_Failed().forEach((t) -> {
thatBai += "Ghi đè sinh viên có mã " + t.getMaSV() + " thất bại.\n";
});
Alert.showMessageDialog(VIEW, thatBai);
countSuccess += dSSinhVienTonTai.size() - DSSinhVien_Controller.getUpdate_Failed().size();
}
if (countSuccess > 0) {
Alert.showMessageDialog(VIEW, "Đã thêm thành công " + countSuccess + " sinh viên.", "Thông báo");
}
}
}//GEN-LAST:event_btnReplaceActionPerformed
private void btnDetailsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDetailsActionPerformed
if (pnl_Duplicate.isVisible()) {
pnl_Duplicate.setVisible(false);
dialog.setSize(new Dimension(507, 175));
dialog.validate();
dialog.repaint();
dialog.setLocationRelativeTo(this);
} else {
pnl_Duplicate.setVisible(true);
dialog.setSize(new Dimension(507, 300));
dialog.validate();
dialog.repaint();
dialog.setLocationRelativeTo(this);
}
}//GEN-LAST:event_btnDetailsActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnCancel;
private javax.swing.JButton btnDetails;
private javax.swing.JButton btnReplace;
private javax.swing.JButton btnSkip;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JLabel lblTitle;
private javax.swing.JLabel lblWarning;
private javax.swing.JPanel pnl_Confirm;
private javax.swing.JPanel pnl_Duplicate;
private javax.swing.JPanel pnl_Table;
private javax.swing.JPanel pnl_Task;
private javax.swing.JTable tblTonTai;
// End of variables declaration//GEN-END:variables
@Override
public void actionPerformed(ActionEvent e) {
Object obj = e.getSource();
if (obj.equals(btn_Them)) {
if (choose == CANBO) {
checkDupCanBo();
importCB2Table();
} else if (choose == SINHVIEN) {
checkDupSinhVien();
importSV2Table();
}
} else if (obj.equals(btn_Huy)) {
dispose();
}
}
private void checkDupCanBo() {
Object[][] current_Data = DSCanBo_Controller.array2DSCanBo(canBo2DS(canBo_Models));
Object[][] old_Data = DSCanBo_Controller.array2DSCanBo(DSCanBo_View.getController().load_TatCaCanBo(mask));
dSCanBo_Models = new ArrayList<>();
dSCanBoTonTai = new ArrayList<>();
if (current_Data.length != 0) {
for (Object[] data_1 : current_Data) {
for (Object[] old_Data1 : old_Data) {
if (data_1[1].equals(old_Data1[1])) {
dSCanBoTonTai.add(new DSCanBo_Model(
String.valueOf(data_1[1]),
String.valueOf(data_1[2]),
String.valueOf(data_1[3])
));
Arrays.fill(data_1, "");
}
}
}
for (Object[] data_1 : current_Data) {
if (!data_1[1].equals("")) {
dSCanBo_Models.add(new DSCanBo_Model(
String.valueOf(data_1[1]),
String.valueOf(data_1[2]),
String.valueOf(data_1[3])
));
}
}
} else {
Alert.showMessageDialog(VIEW, "Bạn chưa chọn cán bộ nào", "Thông báo");
}
}
private void importCB2Table() {
DefaultTableModel listModel = new DefaultTableModel();
listModel.setColumnIdentifiers(columnNamesCB);
if (!dSCanBoTonTai.isEmpty()) {
TransitionPane.setAlwaysOnTop(false);
dSCanBoTonTai.forEach((t) -> {
Object[] obj = {t.getMaCB(), t.getTen(), t.getMaRFID()};
listModel.addRow(obj);
});
tblTonTai.setModel(listModel);
lblTitle.setText("Thêm " + canBo_Models.size() + " cán bộ từ danh sách.");
lblWarning.setText("<html>Có " + listModel.getRowCount() + " cán bộ đã có trong danh sách tham dự hiện tại.<br>"
+ " Bạn có muốn ghi đè lên dữ liệu cũ?");
dialog.setTitle("Xác nhận thêm danh sách cán bộ");
pnl_Duplicate.setVisible(false);
dialog.show();
} else {
int select = Alert.showQuestionDialog(this, "Bạn muốn thêm " + dSCanBo_Models.size() + " cán bộ này?", "Xác nhận thêm");
if (select == Alert.OK) {
int countSuccess = 0;
DSCanBo_View.getController().add_canBoThamGia(dSCanBo_Models, mask);
updateCBTable();
if (!DSCanBo_Controller.getAdd_Failed().isEmpty()) {
thatBai = "";
DSCanBo_Controller.getAdd_Failed().forEach((t) -> {
thatBai += "Thêm cán bộ có mã " + t.getMaCB() + " thất bại.\n";
});
Alert.showMessageDialog(VIEW, thatBai);
countSuccess += dSCanBo_Models.size() - DSCanBo_Controller.getAdd_Failed().size();
}
if (countSuccess > 0) {
Alert.showMessageDialog(VIEW, "Đã thêm thành công " + countSuccess + " cán bộ.", "Thông báo");
}
}
}
}
private void updateCBTable() {
dispose();
dialog.setVisible(false);
VIEW.getSuKien_Details().getdSThamGia().getdSCanBo_View().getPanelTable().getComboBoxItem().setSelectedIndex(0);
VIEW.getSuKien_Details().getdSThamGia().getdSCanBo_View().getPanelTable().initFilterAndButtons();
VIEW.getSuKien_Details().getdSThamGia().getdSCanBo_View().refresh();
VIEW.getBtn_LuuDS().setEnabled(false);
VIEW.getBtn_XoaDS().setEnabled(false);
VIEW.getSuKien_Details().getdSThamGia().showDSCanBo();
}
public ArrayList<DSCanBo_Model> canBo2DS(ArrayList<CanBo_Model> canBo_Models) {
ArrayList<DSCanBo_Model> dsCanBo = new ArrayList<>();
canBo_Models.forEach((t) -> {
dsCanBo.add(new DSCanBo_Model(t.getMaCB(), t.getTen(), t.getMaRFID()));
});
return dsCanBo;
}
// sinh viên
private void checkDupSinhVien() {
Object[][] current_Data = DSSinhVien_Controller.array2DSSinhVien(sinhVien2DS(sinhVien_Models));
Object[][] old_Data = DSSinhVien_Controller.array2DSSinhVien(DSSinhVien_View.getController().load_TatCaSinhVien(mask));
dSSinhVien_Models = new ArrayList<>();
dSSinhVienTonTai = new ArrayList<>();
if (current_Data.length != 0) {
for (Object[] data_1 : current_Data) {
for (Object[] old_Data1 : old_Data) {
if (data_1[1].equals(old_Data1[1])) {
dSSinhVienTonTai.add(new DSSinhVien_Model(
String.valueOf(data_1[1]),
String.valueOf(data_1[2]),
String.valueOf(data_1[3])
));
Arrays.fill(data_1, "");
}
}
}
for (Object[] data_1 : current_Data) {
if (!data_1[1].equals("")) {
dSSinhVien_Models.add(new DSSinhVien_Model(
String.valueOf(data_1[1]),
String.valueOf(data_1[2]),
String.valueOf(data_1[3])
));
}
}
} else {
Alert.showMessageDialog(VIEW, "Bạn chưa chọn sinh viên nào", "Thông báo");
}
}
private void importSV2Table() {
DefaultTableModel listModel = new DefaultTableModel();
listModel.setColumnIdentifiers(columnNamesSV);
if (!dSSinhVienTonTai.isEmpty()) {
TransitionPane.setAlwaysOnTop(false);
dSSinhVienTonTai.forEach((t) -> {
Object[] obj = {t.getMaSV(), t.getTen(), t.getMaRFID()};
listModel.addRow(obj);
});
tblTonTai.setModel(listModel);
lblTitle.setText("Thêm " + sinhVien_Models.size() + " sinh viên từ danh sách.");
lblWarning.setText("<html> Có " + listModel.getRowCount() + " sinh viên đã có trong danh sách tham dự hiện tại.<br>"
+ " Bạn có muốn ghi đè lên dữ liệu cũ?");
dialog.setTitle("Xác nhận thêm danh sách sinh viên");
pnl_Duplicate.setVisible(false);
dialog.show();
} else {
int select = Alert.showQuestionDialog(this, "Bạn muốn thêm " + dSSinhVien_Models.size() + " sinh viên này?", "Xác nhận thêm");
if (select == Alert.OK) {
int countSuccess = 0;
DSSinhVien_View.getController().add_sinhVienThamGia(dSSinhVien_Models, mask);
updateDSSVTable();
if (!DSSinhVien_Controller.getAdd_Failed().isEmpty()) {
thatBai = "";
DSSinhVien_Controller.getAdd_Failed().forEach((t) -> {
thatBai += "Thêm sinh viên có mã " + t.getMaSV() + " thất bại.\n";
});
Alert.showMessageDialog(VIEW, thatBai);
countSuccess += dSSinhVien_Models.size() - DSSinhVien_Controller.getAdd_Failed().size();
}
if (countSuccess > 0) {
Alert.showMessageDialog(VIEW, "Đã thêm thành công " + countSuccess + " sinh viên.", "Thông báo");
}
}
}
}
private void updateDSSVTable() {
dispose();
dialog.setVisible(false);
VIEW.getSuKien_Details().getdSThamGia().getdSSinhVien_View().getPanelTable().getComboBoxItem().setSelectedIndex(0);
VIEW.getSuKien_Details().getdSThamGia().getdSSinhVien_View().getPanelTable().initFilterAndButtons();
VIEW.getSuKien_Details().getdSThamGia().getdSSinhVien_View().refresh();
VIEW.getBtn_LuuDS().setEnabled(false);
VIEW.getBtn_XoaDS().setEnabled(false);
VIEW.getSuKien_Details().getdSThamGia().showDSSinhVien();
}
public ArrayList<DSSinhVien_Model> sinhVien2DS(ArrayList<SinhVien_Model> sinhVien_Models) {
ArrayList<DSSinhVien_Model> dsSinhVien = new ArrayList<>();
sinhVien_Models.forEach((t) -> {
dsSinhVien.add(new DSSinhVien_Model(t.getMaSV(), t.getTen(), t.getMaRFID()));
});
return dsSinhVien;
}
}
| true
|
d17b5cfa3c65156b3b42936ae71e180bfad4cce1
|
Java
|
vinods0905/java_Practices
|
/4th october finalkeywordurlnetworking/urlexample.java
|
UTF-8
| 358
| 2.703125
| 3
|
[] |
no_license
|
import java.net.*;
class urlexample{
public static void main(String args[]) throws Exception{
URL url=new URL("https://www.javatpoint.com/java-tutorial");
System.out.println("protocol:"+url.getProtocol());
System.out.println("host name:"+url.getHost());
System.out.println("portnumber:"+url.getPort());
System.out.println("filename:"+url.getFile());
}
}
| true
|
85937baa0764dbc427b490eee5ae63b4da4afe71
|
Java
|
sahilthakar10/Mplayer_U
|
/app/src/main/java/com/example/mplayer_u/remote/Api.java
|
UTF-8
| 301
| 1.601563
| 2
|
[] |
no_license
|
package com.example.mplayer_u.remote;
import com.example.mplayer_u.Model.Gson_Note_Data;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
public interface Api {
String BASE_URL = "https://knkcab.com/";
@GET("2.txt")
Call<List<Gson_Note_Data>> getHeroes();
}
| true
|
6b5be6616f3088c8c71af15b18fee0941dcb0f85
|
Java
|
Footing/Footing
|
/app/src/main/java/team/far/footing/ui/adapter/MapRyViewAdapter.java
|
UTF-8
| 5,077
| 1.953125
| 2
|
[] |
no_license
|
package team.far.footing.ui.adapter;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.afollestad.materialdialogs.MaterialDialog;
import com.afollestad.materialdialogs.Theme;
import com.balysv.materialripple.MaterialRippleLayout;
import java.text.DecimalFormat;
import java.util.List;
import team.far.footing.R;
import team.far.footing.model.bean.MapBean;
import team.far.footing.model.impl.MapModel;
import team.far.footing.ui.activity.ShowMapActivity;
import team.far.footing.util.TimeUtils;
/**
* Created by luoyy on 2015/8/19 0019.
*/
public class MapRyViewAdapter extends RecyclerView.Adapter<MapRyViewAdapter.ViewHolder> {
private List<MapBean> mapBeanList;
private Context context;
public MapRyViewAdapter(List<MapBean> mapBeanList, Context context) {
this.mapBeanList = mapBeanList;
this.context = context;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_mymap_recycler, null);
return new ViewHolder(v);
}
@Override
public void onBindViewHolder(ViewHolder holder, final int position) {
MapBean mapBean = mapBeanList.get(position);
String allTime = TimeUtils.formatTime(Long.parseLong(mapBean.getAll_time()));
String distance = new DecimalFormat("0.##").format((Double.parseDouble(mapBean.getAll_distance()) / 1000)) + "km";
String startTime = mapBean.getStart_time();
String startAddress = mapBean.getAddress();
String startCity = mapBean.getCity();
String startStreet = mapBean.getStreet();
holder.tvAlltime.setText(allTime);
holder.tvDistance.setText(distance);
holder.tvStarttime.setText(startTime);
if (startAddress != null) {
holder.tvStartAddress.setText(startAddress);
} else {
holder.tvStartAddress.setText("未知区");
}
if (startCity != null) {
holder.tvStartCity.setText(startCity);
} else {
holder.tvStartCity.setText("未知市");
}
if (startStreet != null) {
holder.tvStartStreet.setText(startStreet);
} else {
holder.tvStartStreet.setText("未知路");
}
holder.ripple.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context, ShowMapActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable("map", mapBeanList.get(position));
intent.putExtras(bundle);
context.startActivity(intent);
}
});
holder.ripple.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
new MaterialDialog.Builder(context).title("提示").backgroundColor(context.getResources().getColor(R.color.white)).content("是否删除该足迹").positiveText("删除").negativeText("取消").theme(Theme.LIGHT).callback(new MaterialDialog.ButtonCallback() {
@Override
public void onPositive(MaterialDialog dialog) {
MapModel.getInstance().delete_mapbean(mapBeanList.get(position));
mapBeanList.remove(position);
MapRyViewAdapter.this.notifyDataSetChanged();
dialog.dismiss();
}
}).show();
return true;
}
});
}
@Override
public int getItemCount() {
return mapBeanList.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
private TextView tvStarttime;
private TextView tvDistance;
private TextView tvAlltime;
private CardView CVFgToday;
private TextView tvStartCity;
private TextView tvStartAddress;
private TextView tvStartStreet;
private MaterialRippleLayout ripple;
public ViewHolder(View itemView) {
super(itemView);
tvDistance = (TextView) itemView.findViewById(R.id.tv_distance);
tvStarttime = (TextView) itemView.findViewById(R.id.tv_starttime);
tvStartStreet = (TextView) itemView.findViewById(R.id.tv_start_street);
tvAlltime = (TextView) itemView.findViewById(R.id.tv_alltime);
CVFgToday = (CardView) itemView.findViewById(R.id.cv_fg_friends);
tvStartCity = (TextView) itemView.findViewById(R.id.tv_start_city);
tvStartAddress = (TextView) itemView.findViewById(R.id.tv_start_address);
ripple = (MaterialRippleLayout) itemView.findViewById(R.id.ripple);
}
}
}
| true
|
68de3a966a04ab593c2993399669c3782f44fbf8
|
Java
|
dlanza1/parquet-mr
|
/parquet-hadoop/src/main/java/parquet/hadoop/api/DelegatingWriteSupport.java
|
UTF-8
| 976
| 2.4375
| 2
|
[
"Apache-2.0",
"BSD-3-Clause",
"BSD-2-Clause"
] |
permissive
|
package parquet.hadoop.api;
import org.apache.hadoop.conf.Configuration;
import parquet.io.api.RecordConsumer;
/**
*
* Helps composing write supports
*
* @author Julien Le Dem
*
* @param <T>
*/
public class DelegatingWriteSupport<T> extends WriteSupport<T> {
private final WriteSupport<T> delegate;
public DelegatingWriteSupport(WriteSupport<T> delegate) {
super();
this.delegate = delegate;
}
@Override
public WriteSupport.WriteContext init(Configuration configuration) {
return delegate.init(configuration);
}
@Override
public void prepareForWrite(RecordConsumer recordConsumer) {
delegate.prepareForWrite(recordConsumer);
}
@Override
public void write(T record) {
delegate.write(record);
}
@Override
public WriteSupport.FinalizedWriteContext finalizeWrite() {
return delegate.finalizeWrite();
}
@Override
public String toString() {
return getClass().getName() + "(" + delegate.toString() + ")";
}
}
| true
|
4c15f991fe81e3ddc72255db3c4b333a484c4481
|
Java
|
HenryEtherington/problemSet1
|
/Prob9.java
|
UTF-8
| 1,362
| 3.25
| 3
|
[] |
no_license
|
import javax.swing.JOptionPane;
public class Prob9 {
public static void main(String args[]) {
int i, total=0, over=0, under=0;
String weightAsString;
double lightest=0;
double[] weight;
weight = new double[10];
for(i = 0; i < weight.length; i++)
{
weightAsString = JOptionPane.showInputDialog("Please enter the weight in kilos of the animal: " );
weight[i] = Integer.parseInt(weightAsString);
total += weight[i];
lightest = weight[0];
if(weight[i] < lightest)
{
lightest = weight[i];
}
else if(weight[i] < 250)
{
under++;
}
else if(weight[i] > 400)
{
over++;
}
}
JOptionPane.showMessageDialog(null,"Weights: " + weight[0] + "," +
weight[1] + "," + weight[2] + "," + weight[3] + "," + weight[4] + "," +
weight[5] + "," + weight[6] + "," + weight[7] + "," + weight[8] + "," +
weight[9] + "\nNumber under 250 kg: " + under +
"\nPercentage over 400 kg: " + String.format("%.2f",(over/10f)* 100) + "%" +
"\nLightest animal: " + lightest + "kg" +
"\nAverage weight: " + String.format("%.2f",(total/10f)));
}
}
| true
|
0ea8941fc8d8205ebf6e5ce5d4286bb6faede029
|
Java
|
sebaspapu/ventaBoleteria
|
/src/parcial1/VentaBoletas.java
|
UTF-8
| 5,610
| 2.96875
| 3
|
[] |
no_license
|
/*
*
*/
package parcial1;
import java.util.Scanner;
import javax.swing.JOptionPane;
/**
*
* @author SEBAS TU NEW PAPU
*/
public class VentaBoletas {
static int CantidadP;
static int opcionesTribuna;
static String N[] ;
static String A[];
static String D[] ;
static int E[] ;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner valores = new Scanner(System.in);
Cliente Datos = new Cliente();
Estadio Tribunas = new Estadio();
//primer punto numero de personas que hay en la fila
CantidadP = Integer.parseInt(JOptionPane.showInputDialog(null,"Cuantas personas Hay en la Fila? "
+ "\n'Las cuales desean comprar Boletas'"));
System.out.println("En la Fila Hay "+CantidadP +" Personas\n");
//System.out.println("Cuantas personas Hay en la Fila? \n'las cuales desean comprar Boletas'");
//CantidadP = valores.nextInt();
N = new String[CantidadP];
A = new String[CantidadP];
D = new String[CantidadP];
E = new int [CantidadP];
//solicitar datos basicos al cliente
for(int i =0; i<CantidadP; i++){
//System.out.println("Ingrese el Nombre de la Persona N°"+(i+1)+" : ");
N[i] = JOptionPane.showInputDialog(null,"Ingrese el Nombre de la Persona N°"+(i+1)+" : ");
//n[i] = valores.next();
Datos.setNombre(N);
System.out.println("El nombre de la Persona N°"+(i+1)+" es: "+N[i]);
//System.out.println("Ingrese el Apellido de la Persona N°"+(i+1)+" : ");
A[i] = JOptionPane.showInputDialog("Ingrese el Apellido de la Persona N°"+(i+1)+" : ");
//A[i] = valores.next();
Datos.setApellido(A);
System.out.println("El Apellido de la Persona N°"+(i+1)+" es: "+A[i]);
//System.out.println("Ingrese el Documento de Identidad de la Persona N°"+(i+1)+" : ");
D[i] = JOptionPane.showInputDialog("Ingrese el Documento de Identidad de la Persona N°"+(i+1)+" : ");
//D[i] = valores.next();
Datos.setDocumentoIde(D);
System.out.println("El Documento de Identidad de la Persona N°"+(i+1)+" : "+D[i]);
//System.out.println("Ingrese la Edad de la Persona N°"+(i+1)+" : ");
E[i] = Integer.parseInt(JOptionPane.showInputDialog("Ingrese la Edad de la Persona N°"+(i+1)+" : "));
//E[i] = valores.nextInt();
while(E[i] < 18){
//System.out.println("Ingrese una Edad Mayor!");
JOptionPane.showMessageDialog(null,"¡Ingrese Una edad mayor!","VALIDACION DE EDAD",JOptionPane.INFORMATION_MESSAGE);
//System.out.println("Ingrese la Edad de la Persona N°"+(i+1)+" Nuevamente: ");
E[i] = Integer.parseInt(JOptionPane.showInputDialog("Ingrese la Edad de la Persona N°"+(i+1)+" Nuevamente: "));
//E[i] = valores.nextInt();
}
Datos.setEdad(E);
System.out.println("La edad de la Persona N°"+(i+1)+" es: "+E[i]);
System.out.println("\n");
}
for(int i=0; i<CantidadP; i++){
//System.out.println("Para el cliente N°"+n[i]+" en que Tribuna le gustaria comprar las boletas: ");
do{
opcionesTribuna = Integer.parseInt(JOptionPane.showInputDialog(null,"Para el cliente: "+N[i]+" ! "
+ "\n En que Tribuna le gustaria comprar las boletas: \n"
+ "\n1. TRIBUNA NORTE. \n(PRECIO SILLA: 5MIL)\n"
+ "\n2. TRIBUNA SUR. \n(PRECIO SILLA: 10MIL)\n"
+ "\n3. TRIBUNA ORIENTE. \n(PRECIO SILLA: 30MIL)\n"
+ "\n4. TRIBUNA OCCIDENTE. \n(PRECIO SILLA: 50MIL)\n"
+ "\n5. SALIR",
"SELECCIONE LA TRIBUNA",JOptionPane.INFORMATION_MESSAGE));
switch(opcionesTribuna){
case 1: Tribunas.TribunaNorte();
break;
case 2: Tribunas.TribunaSur();
break;
case 3: Tribunas.TribunaOriente();
break;
case 4: Tribunas.TribunaOccidente();
break;
case 5: System.out.println("\nSaliendo\n");
break;
}
JOptionPane.showMessageDialog(null,"\nEl nombre de la "+(i+1)+"'a. Persona es: "+N[i]
+"\nEl Apellido es: "+A[i]
+"\nEl numero de documento es: "+D[i]
+"\nLa Edad es: "+E[i]
+"\nLa cantidad de boletas Compradas es de: "+Tribunas.getSumaBoletas()
+"\nEl total a pagar de "+N[i]+" es: "+Tribunas.getTotalPagar()
+"\n"
);
opcionesTribuna = 5;
break;
}while(opcionesTribuna != 5);
}
}
}
| true
|
23ffd84a3c6a295e301e6c385cbb1ddbae58b7ca
|
Java
|
KauaiGuarilha/E_CupomFiscal-RESTful
|
/workspace/VendaProduto/src/main/java/br/com/vendaProduto/domain/Item_Cupom.java
|
UTF-8
| 2,075
| 2.28125
| 2
|
[] |
no_license
|
package br.com.vendaProduto.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
/**
*
* @author Kauai Guarilha
*/
@Entity
public class Item_Cupom {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id_item_cupom;
@ManyToOne
@JoinColumn(nullable = false)
private Produto produto;
@ManyToOne
@JoinColumn(nullable = false)
private Cupom cupom;
@Column(nullable = false)
private int quantidade;
@Column(nullable = false, precision = 6, scale = 2)
private double valor_unitario;
public Long getId_item_cupom() {
return id_item_cupom;
}
public void setId_item_cupom(Long id_item_cupom) {
this.id_item_cupom = id_item_cupom;
}
public Produto getProduto() {
return produto;
}
public void setProduto(Produto produto) {
this.produto = produto;
}
public Cupom getCupom() {
return cupom;
}
public void setCupom(Cupom cupom) {
this.cupom = cupom;
}
public int getQuantidade() {
return quantidade;
}
public void setQuantidade(int quantidade) {
this.quantidade = quantidade;
}
public double getValor_unitario() {
return valor_unitario;
}
public void setValor_unitario(double valor_unitario) {
this.valor_unitario = valor_unitario;
}
// Gerado o hashCode() and equals(Object obj), pra que entenda oque puxar no combobox
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id_item_cupom == null) ? 0 : id_item_cupom.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Item_Cupom other = (Item_Cupom) obj;
if (id_item_cupom == null) {
if (other.id_item_cupom != null)
return false;
} else if (!id_item_cupom.equals(other.id_item_cupom))
return false;
return true;
}
}
| true
|
f7210e9b7de66324cf2578239f5d02bbd179a25e
|
Java
|
khush7894/seat-plan-generator
|
/src/main/java/com/seating/plan/generator/system/entity/LkpCourse.java
|
UTF-8
| 2,456
| 2.3125
| 2
|
[] |
no_license
|
package com.seating.plan.generator.system.entity;
import java.io.Serializable;
import javax.persistence.*;
import java.util.Date;
import java.util.List;
/**
* The persistent class for the lkp_course database table.
*
*/
@Entity
@Table(name="lkp_course")
@NamedQuery(name="LkpCourse.findAll", query="SELECT l FROM LkpCourse l")
public class LkpCourse implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String code;
@Temporal(TemporalType.TIMESTAMP)
@Column(name="created_date")
private Date createdDate;
private String duration;
@Column(name="is_deleted")
private int isDeleted;
private String name;
@Column(name="total_semester")
private String totalSemester;
@Temporal(TemporalType.TIMESTAMP)
@Column(name="updated_date")
private Date updatedDate;
//bi-directional many-to-one association to Course
@OneToMany(mappedBy="lkpCourse")
private List<Course> courses;
public LkpCourse() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getCode() {
return this.code;
}
public void setCode(String code) {
this.code = code;
}
public Date getCreatedDate() {
return this.createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public String getDuration() {
return this.duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public int getIsDeleted() {
return this.isDeleted;
}
public void setIsDeleted(int isDeleted) {
this.isDeleted = isDeleted;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getTotalSemester() {
return this.totalSemester;
}
public void setTotalSemester(String totalSemester) {
this.totalSemester = totalSemester;
}
public Date getUpdatedDate() {
return this.updatedDate;
}
public void setUpdatedDate(Date updatedDate) {
this.updatedDate = updatedDate;
}
public List<Course> getCourses() {
return this.courses;
}
public void setCourses(List<Course> courses) {
this.courses = courses;
}
public Course addCours(Course cours) {
getCourses().add(cours);
cours.setLkpCourse(this);
return cours;
}
public Course removeCours(Course cours) {
getCourses().remove(cours);
cours.setLkpCourse(null);
return cours;
}
}
| true
|
31308e70e85958f37aa8db36fc73b57eec3bf3ef
|
Java
|
deepti102915/exercise.maven_concurrency2
|
/src/test/java/com/github/perschola/MyObjectTestPart2B.java
|
UTF-8
| 348
| 2.265625
| 2
|
[] |
no_license
|
package com.github.perschola;
import org.junit.Assert;
import org.junit.Test;
public class MyObjectTestPart2B {
@Test
public void testRun() { // TODO
// Given
MyObjectPart2B myObject = new MyObjectPart2B();
// when
myObject.run();
//then
Assert.assertNotNull(myObject.toString());
}
}
| true
|
90e5441e82b2d98d0b4dfe06456fc2392c1e74e2
|
Java
|
sk5593/service-found
|
/src/main/java/com/service/found/controller/IndexController.java
|
UTF-8
| 1,311
| 1.929688
| 2
|
[] |
no_license
|
package com.service.found.controller;
import com.github.pagehelper.PageInfo;
import com.service.found.entity.IndexEntity;
import com.service.found.service.IndexService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Set;
@RestController
@Slf4j
@RequestMapping("/api/index")
public class IndexController {
@Autowired
IndexService indexService;
@Autowired
RedisTemplate redisTemplate;
@RequestMapping("/index")
public PageInfo<IndexEntity> getIndexPage(int current,int size){
PageInfo<IndexEntity> indexEntityPageInfo = indexService.selectIndex(current, size);
return indexEntityPageInfo;
}
@RequestMapping("/latest")
public List<IndexEntity> getLatestData(@RequestParam("latestTime") long latestTime){
List<IndexEntity> latestData = indexService.getLatestData(latestTime);
return latestData;
}
}
| true
|
012f1addea5d1629da43cb503e38d8433300d375
|
Java
|
InverseLina/search
|
/src/main/java/com/jobscience/search/web/AppAuthRequest.java
|
UTF-8
| 13,430
| 1.578125
| 2
|
[] |
no_license
|
package com.jobscience.search.web;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.Cookie;
import com.jobscience.search.exception.InjectException;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.britesnow.snow.util.ObjectUtil;
import com.britesnow.snow.web.RequestContext;
import com.britesnow.snow.web.WebRequestType;
import com.britesnow.snow.web.auth.AuthRequest;
import com.britesnow.snow.web.auth.AuthToken;
import com.britesnow.snow.web.handler.annotation.WebModelHandler;
import com.britesnow.snow.web.param.annotation.WebModel;
import com.britesnow.snow.web.param.annotation.WebParam;
import com.britesnow.snow.web.param.annotation.WebUser;
import com.britesnow.snow.web.rest.annotation.WebPost;
import com.google.common.base.Charsets;
import com.google.common.base.Strings;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.hash.Hashing;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.inject.name.Named;
import com.jobscience.search.AppConfig;
import com.jobscience.search.auth.AuthCode;
import com.jobscience.search.auth.AuthException;
import com.jobscience.search.canvas.SignedRequest;
import com.jobscience.search.dao.ConfigManager;
import com.jobscience.search.dao.DBSetupManager;
import com.jobscience.search.dao.UserDao;
import com.jobscience.search.organization.OrgContextManager;
@Singleton
public class AppAuthRequest implements AuthRequest {
@Inject
private UserDao userDao;
@Inject
OrgContextManager orgHolder;
@Inject
private ConfigManager configManager;
@Inject
private DBSetupManager dbSetupManager;
@Inject(optional = true)
@Named("jss.passcode")
private String passCode;
@Inject(optional = true)
@Named("jss.sysadmin.pwd")
private String configPassword;
@Inject(optional = true)
@Named("force.ssl")
private boolean sslFlag;
@Inject
private WebResponseBuilder webResponseBuilder;
private static final Logger log = LoggerFactory.getLogger(AppAuthRequest.class);
static private final String COOKIE_ORG_USER_TOKEN = "ctoken";
static private final String COOKIE_ORG = "org";
static private final String COOKIE_ADMIN_TOKEN = "atoken";
static private final String COOKIE_PASSCODE = "pcode";
static private final String SESSION_EXPIRE_DURATION = "sessionExpireDuration";
private final Cache<String, Map> userCache;
public AppAuthRequest() {
userCache = CacheBuilder.newBuilder().expireAfterAccess(8, TimeUnit.MINUTES)
.maximumSize(100).build(new CacheLoader<String, Map>() {
@Override
public Map load(String ctoken) throws Exception {
return userDao.getUserByToken(ctoken);
}
});
}
@Override
public AuthToken authRequest(RequestContext rc) {
WebRequestType wrt = rc.getWebRequestType();
AuthToken authToken = null;
switch(wrt){
// All the dynamic resources, we need to auth
case WEB_RESOURCE:
case WEB_REST:
case WEB_TEMPLATE:
String orgName = rc.getParam("org");
if (orgName != null) {
setCookie(rc, COOKIE_ORG, orgName, 524160f);
}
return authWebRequest(rc);
// static files and generated files (.less, webbundle) we do not need to auth.
case GENERATED_ASSET:
case STATIC_FILE:break;
}
return authToken;
}
@WebPost("/passcode")
public WebResponse passcode(@WebParam("passcode") String code ,RequestContext rc) {
if (passCode != null && passCode.length() > 0 && passCode.equals(code)) {
String codeSha1 = sha1(code);
rc.setCookie(COOKIE_PASSCODE, codeSha1, true);
return webResponseBuilder.success(true);
}else{
rc.removeCookie(COOKIE_PASSCODE);
}
return webResponseBuilder.fail(new AuthException(AuthCode.NO_PASSCODE));
}
@WebPost("/admin-login")
public WebResponse adminLogin(RequestContext rc,
@WebParam("password") String password) throws SQLException {
if (configPassword.equals(password)) {
String passwordSha1 = sha1(password);
setCookie(rc, COOKIE_ADMIN_TOKEN, passwordSha1, 30f);
return webResponseBuilder.success();
} else {
rc.removeCookie(COOKIE_ADMIN_TOKEN);
}
return webResponseBuilder.fail();
}
@WebModelHandler(startsWith = "/")
public void home(@WebModel Map m, @WebUser Map user, RequestContext rc) {
m.put("JSS_VERSION", AppConfig.JSS_VERSION);
if (!rc.getPathInfo().startsWith("/admin")){
String orgName = null;
boolean isSysSchemaExist = dbSetupManager.checkSysTables().contains("config");
m.put("sys_schema", isSysSchemaExist);
try{
orgName = orgHolder.getOrgName();
}catch(Exception e){
log.warn("NO_ORG");
}
if(orgName == null){
rc.getWebModel().put("errorCode", "NO_ORG");
rc.getWebModel().put("errorMessage", "No organization selected, please, authenticate via SalesForce.com");
rc.getWebModel().put("success", "false");
}else{
if (orgName != null) {
m.put("user", user);
}
// check org is set or not
try {
Map configMap = configManager.getOrgInfo(orgHolder.getId());
configMap.put("instanceUrl", rc.getCookie("instanceUrl"));
m.put("orgConfigs", JSONObject.fromObject(configMap).toString());
} catch (Exception e) {
rc.removeCookie(COOKIE_ORG_USER_TOKEN);
}
}
}else{
//FIXME: for now do check here, cause the expection catcher just for rest methods.
boolean isAdmin = false;
if(user != null && user.containsKey("isAdmin")){
isAdmin = (Boolean) user.get("isAdmin");
}
if(!isAdmin){
rc.getWebModel().put("errorCode", AuthCode.NO_ADMIN_ACCESS.toString());
rc.getWebModel().put("errorMessage", "You have no privaliges to access for admin resources");
rc.getWebModel().put("success", "false");
}
}
}
public void updateCache(Map user){
userCache.put((String)user.get(COOKIE_ORG_USER_TOKEN), user);
}
private AuthToken authWebRequest(RequestContext rc){
rc.getRes().setHeader("P3P", "CP=\"IDC DSP COR CURa ADMa OUR IND PHY ONL COM STA\"");
AuthToken authToken = null;
String path = rc.getPathInfo();
String contextPath = rc.getContextPath();
if(path.equals("/admin/")){
String atoken = rc.getCookie(COOKIE_ADMIN_TOKEN);
if(!Strings.isNullOrEmpty(atoken) && atoken.equals(sha1(configPassword))){
Map adminUser = new HashMap();
adminUser.put("isAdmin", true);
authToken = new AuthToken();
authToken.setUser(adminUser);
}else{
rc.removeCookie(COOKIE_ADMIN_TOKEN);
}
}else if(path.equals("/sf-canvas")){
String signedRequest = rc.getParam("signed_request");
if (signedRequest != null) {
Integer orgId = null;
try{
orgId = orgHolder.getId();
}catch(Exception e){
e.printStackTrace();
rc.getWebModel().put("errorCode", "ERROR_ORG");
rc.getWebModel().put("errorMessage", "Organization is not correct, Please enter correct organization");
rc.getWebModel().put("success", "false");
}
if (orgId != null) {
String canvasappSecretStr = configManager.getConfig("canvasapp_secret", orgId);
try {
String signedRequestJson = SignedRequest.verifyAndDecodeAsJson(signedRequest, canvasappSecretStr);
rc.getWebModel().put("signedRequestJson", signedRequestJson);
Map userMap = userDao.checkAndUpdateUser(2, signedRequestJson, null, 0, null);
float expiration = ObjectUtil.getValue(configManager.getConfig(SESSION_EXPIRE_DURATION, orgHolder.getId()),Float.class,120f);
setCookie(rc, COOKIE_ORG_USER_TOKEN, (String)userMap.get("ctoken"), expiration);
updateCache(userMap);
String sfid = (String)orgHolder.getCurrentOrg().getOrgMap().get("sfid");
if(!Strings.isNullOrEmpty(sfid)&&!userDao.getSFIDbySF2(signedRequestJson).startsWith(sfid)){
rc.getWebModel().put("errorCode", "CANVAS_AUTH_ERROR");
rc.getWebModel().put("errorMessage", "Cannot Access Org SFID from SFCanvas does not match JSS Org SFID");
rc.getWebModel().put("success", "false");
}else{
Map user = getUserFromCToken(rc);
authToken = new AuthToken();
authToken.setUser(user);
}
} catch (Exception e) {
rc.getWebModel().put("errorCode", "CANVAS_AUTH_ERROR");
rc.getWebModel().put("errorMessage", "The app secret might be incorrect, Make sure you have correct secret");
rc.getWebModel().put("success", "false");
}
}
}else{
rc.getWebModel().put("errorCode", "CANVAS_AUTH_ERROR");
rc.getWebModel().put("errorMessage", "The signedRequest can't be empty.");
rc.getWebModel().put("success", "false");
}
}else if(path.equals(contextPath + "/") || path.equals(rc.getContextPath())){
if (passCode != null && passCode.length() > 0 ) {
String pcode = rc.getCookie(COOKIE_PASSCODE);
if (pcode == null || !pcode.equals(sha1(passCode))) {
rc.getWebModel().put("errorCode", AuthCode.NO_PASSCODE.toString());
rc.getWebModel().put("errorMessage", "No passcode exists or incorrect");
rc.getWebModel().put("success", "false");
return null;
}
Map user = getOrCreateUserFromCToken(rc);
authToken = new AuthToken();
authToken.setUser(user);
}
}else{
try {
Map user = getUserFromCToken(rc);
if(user == null){
rc.removeCookie(COOKIE_ORG_USER_TOKEN);
}
String atoken = rc.getCookie(COOKIE_ADMIN_TOKEN);
if(atoken != null){
if(user == null){
user = new HashMap();
}
user.put("isAdmin", true);
setCookie(rc, COOKIE_ADMIN_TOKEN, atoken, 30f);
}else{
rc.removeCookie(COOKIE_ADMIN_TOKEN);
}
if(user != null){
authToken = new AuthToken();
authToken.setUser(user);
}
} catch (Exception e) {
rc.removeCookie(COOKIE_ORG_USER_TOKEN);
log.warn("Does not have user token");
}
}
String servletPath = rc.getReq().getServletPath();
if("/getAutoCompleteData".equals(servletPath) || "/searchuiconfig".equals(servletPath)){
Enumeration rnames=rc.getReq().getParameterNames();
for (Enumeration e = rnames ; e.hasMoreElements() ;) {
String thisName=e.nextElement().toString();
String thisValue=rc.getReq().getParameter(thisName);
if(thisName != null && checkXPath(thisName)){
throw new InjectException("The input should not contains any metacharacters which may attack the project");
}
if(!"searchValues".equals(thisName) && !"value".equals(thisName) && !"configsJson".equals(thisName)){
if(thisValue != null && checkXPath(thisValue)){
throw new InjectException("The input should not contains any metacharacters which may attack the project");
}
}
}
}
return authToken;
}
private Map getOrCreateUserFromCToken(RequestContext rc){
Map user = getUserFromCToken(rc);
try{
if(user == null){
String ctoken = userDao.buildCToken(null);
userDao.insertUser(null, ctoken, 0l, null);
float expiration = ObjectUtil.getValue(configManager.getConfig(SESSION_EXPIRE_DURATION, orgHolder.getId()),Float.class,120f);
setCookie(rc, COOKIE_ORG_USER_TOKEN, ctoken, expiration);
user = userDao.getUserByToken(ctoken);
updateCache(user);
}
}catch(Exception e){
rc.getWebModel().put("errorCode", "NO_ORG");
rc.getWebModel().put("errorMessage", "Organization is not correct, Please enter correct organization");
rc.getWebModel().put("success", "false");
}
return user;
}
private Map getUserFromCToken(RequestContext rc){
Map user = null;
String ctoken = rc.getCookie(COOKIE_ORG_USER_TOKEN);
if (ctoken != null) {
user = userCache.getIfPresent(ctoken);
if (user == null) {
String orgName = null;
try {
orgName = orgHolder.getOrgName();
if (orgName != null) {
dbSetupManager.checkOrgExtra(orgHolder.getOrgName()).contains("jss_user");
}
user = userDao.getUserByToken(ctoken);
} catch (Exception e) {
rc.getWebModel().put("errorCode", "NO_ORG");
rc.getWebModel().put("errorMessage", "Organization is not correct, Please enter correct organization");
rc.getWebModel().put("success", "false");
}
}
}
if(user != null){
float expiration = ObjectUtil.getValue(configManager.getConfig(SESSION_EXPIRE_DURATION, orgHolder.getId()),Float.class,120f);
setCookie(rc, COOKIE_ORG_USER_TOKEN, ctoken, expiration);
}
return user;
}
private void setCookie(RequestContext rc, String name, String value, float expire){
if(sslFlag){
if(expire > 0) {
rc.getRes().addHeader("Set-Cookie",name+"="+value+";Max-Age="+(int) (expire * 60)+"path=/;Secure;HttpOnly");
}else{
rc.getRes().addHeader("Set-Cookie",name+"="+value+";Max-Age="+120 * 60+"path=/;Secure;HttpOnly");
}
}else{
Cookie cookie = new Cookie(name,value);
cookie.setPath("/");
if(expire > 0) {
cookie.setMaxAge((int) (expire * 60));
}else{
cookie.setMaxAge(120 * 60);
}
rc.getRes().addCookie(cookie);
}
}
static String sha1(String txt){
return Hashing.sha1().hashString(txt, Charsets.UTF_8).toString();
}
private boolean checkXPath(String queryString){
boolean flag = false;
String[] strings = {"\'","@","and","(",")","/","\"","=","[","]"};
for(String s:strings){
if(queryString.contains(s)){
flag = true;
}
}
return flag;
}
}
| true
|
750724e7b07206140b9a4b501b58e1ef589b42ed
|
Java
|
ArdyJunata/SDA
|
/SDA_Ardy/src/LatihanTree/Tree.java
|
UTF-8
| 3,312
| 3.234375
| 3
|
[] |
no_license
|
package LatihanTree;
public class Tree {
private Node root;
private int jumlah;
public Tree() {
root = null;
}
public void insert(String s) {
Convert c = new Convert(s);
s = c.inToPost();
Stck1 stk = new Stck1(s.length());
s = s + "#";
int i = 0;
char symbol = s.charAt(i);
Node newNode;
while (symbol != '#') {
if (symbol >= '0' && symbol <= '9' || symbol >= 'A'
&& symbol <= 'Z' || symbol >= 'a' && symbol <= 'z') {
newNode = new Node(symbol);
stk.push(newNode);
} else if (symbol == '+' || symbol == '-' || symbol == '/'
|| symbol == '*') {
Node ptr1 = stk.pop();
Node ptr2 = stk.pop();
newNode = new Node(symbol);
newNode.leftChild = ptr2;
newNode.rightChild = ptr1;
stk.push(newNode);
}
symbol = s.charAt(++i);
}
root = stk.pop();
}
public void traverse(String type) {
switch (type) {
case "pre":
System.out.print("Prefix:- ");
preOrder(root);
break;
case "in":
System.out.print("Infix :- ");
inOrder(root);
break;
case "post":
System.out.print("Postfix :- ");
postOrder(root);
break;
case "jumlah":
System.out.println("Calculate :- " + jumlahNilai(root));
default:
System.out.println("Invalid Choice");
}
}
private int jumlahNilai(Node localRoot) {
if (localRoot != null) {
if (localRoot.data == '+') {
return (jumlahNilai(localRoot.leftChild) + jumlahNilai(localRoot.rightChild));
} else if (localRoot.data == '-') {
return (jumlahNilai(localRoot.leftChild) - jumlahNilai(localRoot.rightChild));
} else if (localRoot.data == '*') {
return (jumlahNilai(localRoot.leftChild) * jumlahNilai(localRoot.rightChild));
} else if (localRoot.data == '/') {
return (jumlahNilai(localRoot.leftChild) / jumlahNilai(localRoot.rightChild));
} else {
return (Integer.parseInt(localRoot.data + ""));
}
}
return 0;
}
public int getJumlah() {
return jumlah;
}
private void preOrder(Node localRoot) {
if (localRoot != null) {
localRoot.displayNode();
preOrder(localRoot.leftChild);
preOrder(localRoot.rightChild);
}
}
private void inOrder(Node localRoot) {
if (localRoot != null) {
inOrder(localRoot.leftChild);
localRoot.displayNode();
inOrder(localRoot.rightChild);
}
}
private void postOrder(Node localRoot) {
if (localRoot != null) {
postOrder(localRoot.leftChild);
postOrder(localRoot.rightChild);
localRoot.displayNode();
}
}
}
| true
|
c5f37350c25779d811b6228633a9dee561d9eda1
|
Java
|
cdh0912/dreamcatcher2
|
/dreamcatcher/src/com/dreamcatcher/route/model/RouteDto.java
|
UTF-8
| 1,661
| 1.929688
| 2
|
[] |
no_license
|
package com.dreamcatcher.route.model;
public class RouteDto {
private int route_id;
private String title;
private String id;
private String name;
private String logtime;
private String route_url;
private int recommend;
private int rec_percent;
private int reply_count;
private int rep_percent;
public String getLogtime() {
return logtime;
}
public void setLogtime(String logtime) {
this.logtime = logtime;
}
public int getRec_percent() {
return rec_percent;
}
public void setRec_percent(int rec_percent) {
this.rec_percent = rec_percent;
}
public int getRep_percent() {
return rep_percent;
}
public void setRep_percent(int rep_percent) {
this.rep_percent = rep_percent;
}
public String getRoute_url() {
return route_url;
}
public void setRoute_url(String route_url) {
this.route_url = route_url;
}
public int getReply_count() {
return reply_count;
}
public void setReply_count(int reply_count) {
this.reply_count = reply_count;
}
public int getRoute_id() {
return route_id;
}
public void setRoute_id(int route_id) {
this.route_id = route_id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getRecommend() {
return recommend;
}
public void setRecommend(int recommend) {
this.recommend = recommend;
}
}
| true
|
672e99546f27a2deecd42fd32a08537427c2a42c
|
Java
|
Jabidex3/CoreJavaStandAloneShoppingApp
|
/src/com/shoppingapp/model/Customer.java
|
UTF-8
| 1,388
| 2.78125
| 3
|
[] |
no_license
|
package com.shoppingapp.model;
import java.util.ArrayList;
import java.util.List;
public class Customer {
private int customerId;
private String name;
private String email; //unique
private String password;
private List<Invoice> orders;
public Customer() {
super();
}
public Customer(int customerId, String name, String email, String password) {
super();
this.customerId = customerId;
this.name = name;
this.email = email;
this.password = password;
this.orders = new ArrayList<Invoice>();
}
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<Invoice> getOrders() {
return orders;
}
public void addOrder(Invoice order) {
this.orders.add(order);
}
public int orderListLength() {
return orders.size();
}
@Override
public String toString() {
return "Customer [customerId=" + customerId + ", name=" + name + ", email=" + email + ", password=" + password
+ ", orders=" + orders + "]";
}
}
| true
|
79a9d745dac5fd7db6a3a3efa94653a7462c72d9
|
Java
|
AnDev2023/RevoluTap
|
/app/src/main/java/com/github/budsterblue/revolutap/MenuFileChooser.java
|
UTF-8
| 13,218
| 2.15625
| 2
|
[
"BSD-3-Clause"
] |
permissive
|
package com.github.budsterblue.revolutap;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.view.MenuItem;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Objects;
import java.util.Scanner;
public class MenuFileChooser extends AppCompatActivity implements MenuFileArrayAdapter.ItemClickListener, MenuFileArrayAdapter.ItemLongClickListener {
private MenuFileArrayAdapter adapter;
private File cwd;
private String selectedFilePath;
private boolean useShortDirNames;
private RecyclerView recyclerView;
private LinearLayoutManager layoutManager;
private DividerItemDecoration dividerItemDecoration;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.choose);
Tools.setContext(this);
// set up the RecyclerView
recyclerView = findViewById(R.id.choose_recycler);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
registerForContextMenu(recyclerView);
dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),
layoutManager.getOrientation());
//Objects.requireNonNull(this.getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
adapter = null;
selectedFilePath = null;
// Get last dir
String prefLastDir = Tools.getSetting(R.string.lastDir, R.string.lastDirDefault);
useShortDirNames = Tools.getBooleanSetting(R.string.useShortDirNames, R.string.useShortDirNamesDefault);
if (prefLastDir.equals("")) {
prefLastDir = Tools.getPacksDir();
}
cwd = new File(prefLastDir);
if (prefLastDir.length() > 0 &&
cwd.exists() &&
cwd.getParentFile() != null &&
!cwd.getPath().equals(Tools.getPacksDir())
) {
cwd = cwd.getParentFile();
} else {
String[] browseLocationOrder = {
prefLastDir,
Tools.getPacksDir(),
};
for (String path: browseLocationOrder) {
if (path != null) {
cwd = new File(path);
if (cwd.canRead() && cwd.isDirectory()) {
break;
}
}
}
}
ToolsTracker.data("Opened file browser", "cwd", cwd.getAbsolutePath());
refresh();
}
// Show files
private String shortDirName(String s) {
String stripped = s;
// "[name] song"
if (s.charAt(0) == '[' && s.indexOf(']') != -1 && s.indexOf(']') < s.length() - 1) {
stripped = s.substring(s.indexOf(']') + 1).trim();
// "(name) song"
} else if (s.charAt(0) == '(' && s.indexOf(')') != -1 && s.indexOf(')') < s.length() - 1) {
stripped = s.substring(s.indexOf(')') + 1).trim();
// "#### song"
} else if (Character.isDigit(s.charAt(0))) {
int i = 0;
while (i < s.length() && s.charAt(i) != ' ' && !Character.isLetter(s.charAt(i))) {
i++;
}
if (i < (s.length() - 1)) {
stripped = s.substring(i).trim();
}
}
if (stripped.length() > 0) {
return stripped;
} else {
return s;
}
}
//private void ls(File dir) {
public void refresh() {
File dir = cwd;
if (dir == null) return;
// remove /data/user/0/com.github.budsterblue.revolutap/files from title
if (dir.getAbsolutePath().equals(Tools.getPacksDir())){
setTitle(dir.getAbsolutePath().replace(Tools.getAppDir() + "/", ""));
Objects.requireNonNull(this.getSupportActionBar()).setDisplayHomeAsUpEnabled(false);
} else {
setTitle(dir.getAbsolutePath().replace(Tools.getPacksDir() + "/", ""));
Objects.requireNonNull(this.getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
}
// Get lists
File[] l = dir.listFiles();
ArrayList<MenuFileItem> dl = new ArrayList<>();
ArrayList<MenuFileItem> fl = new ArrayList<>();
// Populate list
if (l != null){
for (File f : l) {
String s = f.getName();
if (!s.startsWith(".")) {
if (f.isDirectory()) {
if (useShortDirNames) s = shortDirName(s);
dl.add(new MenuFileItem(s, f.getAbsolutePath(), true, f));
} else if (Tools.isStepfile(s) || Tools.isLink(s) || Tools.isStepfilePack(s) || Tools.isText(s)) {
fl.add(new MenuFileItem(s, f.getAbsolutePath(), false, f));
}
}
}
}
Collections.sort(dl);
Collections.sort(fl);
dl.addAll(fl); // Add file list to end of directories list
// Display
if (adapter == null) {
adapter = new MenuFileArrayAdapter(this, dl);
adapter.setClickListener(this);
adapter.setLongClickListener(this);
recyclerView.addItemDecoration(dividerItemDecoration);
recyclerView.setAdapter(adapter);
} else {
adapter.updateData(dl);
}
}
@Override
public void onItemClick(View view, int position) {
MenuFileItem i = adapter.getItem(position);
if (i != null) {
onFileClick(i);
}
}
@Override
public void onItemLongClick(View view, int position) {
MenuFileItem i = adapter.getItem(position);
assert i != null;
selectedFilePath = i.getPath();
DialogInterface.OnClickListener delete_action = (dialog, id) -> {
try {
deleteFile(new File(selectedFilePath));
} catch (Exception e) {
ToolsTracker.error("MenuFileChooser.deleteFile", e, selectedFilePath);
Tools.error(
Tools.getString(R.string.MenuFilechooser_file_delete_error) +
selectedFilePath +
Tools.getString(R.string.Tools_error_msg) +
e.getMessage(),
Tools.cancel_action);
}
adapter.removeItem(position);
dialog.cancel();
};
Tools.alert(
Tools.getString(R.string.MenuFilechooser_file_delete),
R.drawable.ic_delete_forever_filled_black,
Tools.getString(R.string.MenuFilechooser_file_delete_confirm) +
i.getName(),
Tools.getString(R.string.Button_yes),
delete_action,
Tools.getString(R.string.Button_no),
Tools.cancel_action,
-1
);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onFileClick(new MenuFileItem("", cwd.getParent(), true, null));
return true;
}
return super.onOptionsItemSelected(item);
}
private String parseURL(File url) {
Scanner sc = null;
try {
sc = new Scanner(url);
String buffer;
while (sc.hasNextLine()) {
buffer = sc.nextLine();
if (buffer.contains("URL=")) {
sc.close();
return (buffer.substring(buffer.indexOf("URL=") + 4)).trim();
}
}
} catch (Exception e) {
ToolsTracker.error("MenuFileChooser.parseURL", e, url.getAbsolutePath());
}
if (sc != null) sc.close();
return null;
}
private void selectStepfile(String smFilePath) {
// Save preferences
// smFilePath = path
Tools.putSetting(R.string.smFilePath, smFilePath);
Tools.putSetting(R.string.lastDir, cwd.getPath());
String smFileName;
if (smFilePath.lastIndexOf('/') != -1) {
smFileName = smFilePath.substring(smFilePath.lastIndexOf('/') + 1);
} else {
smFileName = smFilePath;
}
if (!Tools.getBooleanSetting(R.string.autoStart, R.string.autoStartDefault)) {
Tools.toast(
Tools.getString(R.string.MenuFilechooser_selected_stepfile) +
smFileName +
Tools.getString(R.string.MenuFilechooser_start_info)
);
}
setResult(RESULT_OK);
finish();
}
private void displayTextFile(MenuFileItem i) {
/*using html, because otherwise the text size is too big. I'm not sure why;
the New User Notes box is plaintext and its text size is fine. */
//TODO make this into an activity?
try {
StringBuilder msg = new StringBuilder();
msg.append("<small>"); //<font size=\"2\"> doesn't work
BufferedReader r = new BufferedReader(new FileReader(i.getFile()));
while (true) {
String s = r.readLine();
if (s == null) break;
msg.append(s);
msg.append("<br/>");
}
r.close();
msg.append("</small>");
Tools.note(i.getName(), R.drawable.icon_small, Html.fromHtml(msg.toString()),
Tools.getString(R.string.Button_close), null, null, null, -1);
} catch (Exception e) {
ToolsTracker.error("MenuFileChooser.displayTextFile", e, i.getPath());
Tools.warning(
Tools.getString(R.string.MenuFilechooser_file_open_error) +
i.getName() +
Tools.getString(R.string.Tools_error_msg) +
e.getMessage(),
Tools.cancel_action,
-1
);
}
}
private void onFileClick(MenuFileItem i) {
selectedFilePath = i.getPath();
// Directory
if (i.isDirectory()) {
File f = new File(selectedFilePath);
//if (f.canRead() && !f.getAbsolutePath().equals(Tools.getAppDir().replace("/files", ""))) { // this is a hack, but it works
if (f.canRead()) { // && !f.getAbsolutePath().equals(Tools.getAppDir())
cwd = f;
String path;
// weird if else logic to prevent showing song folder as song is loading
if (Tools.getBooleanSetting(R.string.stepfileFolderCheck, R.string.stepfileFolderCheckDefault)) {
path = Tools.checkStepfileDir(f);
} else {
path = null;
}
if (path != null) {
selectStepfile(path);
} else {
refresh();
}
} else {
Tools.toast(
Tools.getString(R.string.MenuFilechooser_list_error) +
i.getPath() +
Tools.getString(R.string.Tools_permissions_error)
);
}
return;
// URL
} else if (Tools.isLink(selectedFilePath)) {
String link = parseURL(i.getFile());
Tools.toast("Opening link:\n" + link);
if (link == null || link.length() < 2) {
Tools.toast(
Tools.getString(R.string.MenuFilechooser_url_error)
);
} else {
Intent webBrowser = new Intent(Intent.ACTION_VIEW);
webBrowser.setData(Uri.parse(link));
startActivity(webBrowser);
}
// Stepfile
} else if (Tools.isStepfile(selectedFilePath)) {
selectStepfile(selectedFilePath);
// Stepfile pack?
} else if (Tools.isStepfilePack(selectedFilePath)) {
new ToolsUnzipper(this, selectedFilePath, false).unzip();
//Text file?
} else if (Tools.isText(selectedFilePath)) {
displayTextFile(i);
} else {
Tools.toast(
Tools.getString(R.string.MenuFilechooser_file_extension_error)
);
}
refresh();
}
// File deletion
private void deleteFile(File f) throws SecurityException {
if (f.isDirectory()) {
for (File nf : Objects.requireNonNull(f.listFiles())) {
deleteFile(nf);
}
}
if (!f.delete()) {
throw new SecurityException(f.getPath());
}
}
}
| true
|
e2703c622b3172ce874c8ee571d36cf38744c2c6
|
Java
|
freemanh/cjx-web
|
/src/main/java/com/chejixing/socket/parser/AuthMessageParser.java
|
UTF-8
| 824
| 2.21875
| 2
|
[] |
no_license
|
package com.chejixing.socket.parser;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import org.apache.mina.core.buffer.IoBuffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
@Component
@Qualifier("authMessageParser")
public class AuthMessageParser implements MessageBodyParser {
private static final Logger logger = LoggerFactory.getLogger(AuthMessageParser.class);
@Override
public Object getBody(IoBuffer buf) {
try {
String auth = buf.getString(Charset.forName(MessageBodyParser.STRING_CHARSET).newDecoder());
logger.debug("auth code:" + auth);
return auth;
} catch (CharacterCodingException e) {
throw new RuntimeException(e);
}
}
}
| true
|
8a719d57925e7b94bcf84adb1019ba88e6f0f3f8
|
Java
|
eneselibol/springbootcrudwtihthymeleaf
|
/src/main/java/com/eneselibol/crudwtihthymeleaf/controller/EmployeeController.java
|
UTF-8
| 6,585
| 2.125
| 2
|
[] |
no_license
|
package com.eneselibol.crudwtihthymeleaf.controller;
import com.eneselibol.crudwtihthymeleaf.model.Employee;
import com.eneselibol.crudwtihthymeleaf.model.Permits;
import com.eneselibol.crudwtihthymeleaf.model.Roles;
import com.eneselibol.crudwtihthymeleaf.repository.PermitsRepository;
import com.eneselibol.crudwtihthymeleaf.repository.RolesRepository;
import com.eneselibol.crudwtihthymeleaf.security.WebSecurityConfig;
import com.eneselibol.crudwtihthymeleaf.service.EmployeeService;
import com.eneselibol.crudwtihthymeleaf.service.PermitsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import java.util.List;
@Controller
public class EmployeeController {
@Autowired
private EmployeeService employeeService;
@Autowired
private PermitsService permitsService;
@Autowired
private RolesRepository rolesRepository;
@Autowired
private PermitsRepository permitsRepository;
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
@Autowired
private WebSecurityConfig webSecurityConfig;
@GetMapping("/")
public String viewHomePage(Model model) {
// User currentUser= (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
String username = ((UserDetails) principal).getUsername();
Employee employee = employeeService.getEmployeeByUsername(username);
model.addAttribute("listEmployees", employeeService.getEmployeeById(employee.getEmployeeId()));
} else {
String username = principal.toString();
}
// model.addAttribute("listEmployees", employeeService.getAllEmployees());
return "index";
}
@GetMapping("/allEmployee")
public String viewAllPermits(Model model) {
model.addAttribute("listEmployees", employeeService.getAllEmployees());
return "all_employees";
}
@GetMapping("/viewPermits/{id}")
public String viewPermitsList(@PathVariable(value = "id") long id, Model model) {
model.addAttribute("listPermits", permitsService.getPermitsByEmployeeId(id));
Employee employee = employeeService.getEmployeeById(id);
model.addAttribute("employee", employee);
return "employee_permits";
}
@GetMapping("/showNewEmployeeForm")
public String showNewEmployeeForm(Model model) {
List<Roles> roles = (List<Roles>) rolesRepository.findAll();
Employee employee = new Employee();
model.addAttribute("employee", employee);
model.addAttribute("roleLists", roles);
return "new_employee";
}
@GetMapping("/showNewPermitsForm/{id}")
public String showNewPermitsForm(@PathVariable(value = "id") long id, Model model) {
Permits permits = new Permits();
model.addAttribute("permits", permits);
Employee employee = employeeService.getEmployeeById(id);
model.addAttribute("employee", employee);
return "new_permits";
}
@PostMapping("/saveEmployee")
public String saveEmployee(@ModelAttribute("employee") Employee employee) {
String encodedPassword = encoder.encode(employee.getUser_id().getPassword());
employee.getUser_id().setPassword(encodedPassword);
employee.getUser_id().setEnabled(true);
employeeService.saveEmployee(employee);
return "redirect:/";
}
@PostMapping("/updateEmployee")
public String updateEmployee(@ModelAttribute("employee") Employee employee) {
employee.setEmployeeId(employee.getEmployeeId());
employeeService.saveEmployee(employee);
return "redirect:/";
}
@GetMapping("/showFormForUpdate/{id}")
public String showFormForUpdate(@PathVariable(value = "id") long id, Model model) {
Employee employee = employeeService.getEmployeeById(id);
model.addAttribute("employee", employee);
return "update_employee";
}
@GetMapping("/deleteEmployee/{id}")
public String deleteEmployee(@PathVariable(value = "id") long id) {
this.employeeService.deleteEmployeeById(id);
return "redirect:/";
}
@GetMapping("/403")
public String error403() {
return "error403";
}
@GetMapping("/deletePermits/{id}")
public String deletePermits(@PathVariable(value = "id") long id) {
this.permitsService.deletePermitsById(id);
return "redirect:/";
}
@GetMapping("/showFormForUpdatePermits/{id}")
public String showFormForUpdatePermits(@PathVariable(value = "id") long id, Model model) {
Permits permits = permitsService.getPermitsById(id);
model.addAttribute("permits", permits);
return "update_permits";
}
@PostMapping("/savePermits/{id}")
public String savePermits(@PathVariable(value = "id") long id, @ModelAttribute("permits") Permits permits) {
Employee employee = employeeService.getEmployeeById(id);
permits.setEmployee(employee);
permits.setStatus(0);
permitsService.savePermits(permits);
return "redirect:/";
}
@GetMapping("/showPendingPermits")
public String showPendingPermits(Model model) {
List<Permits> pendingPermits = (List<Permits>) permitsRepository.getAllByStatusZero();
Employee employee = new Employee();
model.addAttribute("employee", employee);
model.addAttribute("pendingPermits", pendingPermits);
return "pending_permits";
}
@GetMapping("/approvePermit/{id}")
public String approvePermit(@PathVariable(value = "id") long id,Model model) {
permitsService.permitApprove(id);
List<Permits> pendingPermits = (List<Permits>) permitsRepository.getAllByStatusZero();
Employee employee = new Employee();
model.addAttribute("employee", employee);
model.addAttribute("pendingPermits", pendingPermits);
return "pending_permits";
}
}
| true
|
4db02e9c89baa294e5ff8219298d80b3942d6ac7
|
Java
|
xuelianhan/basic-algos
|
/src/main/java/org/ict/algorithm/leetcode/breadthfirstsearch/WordLadder.java
|
UTF-8
| 11,143
| 3.828125
| 4
|
[] |
no_license
|
package org.ict.algorithm.leetcode.breadthfirstsearch;
import java.util.*;
/**
* A transformation sequence from the word beginWord to word endWord using a dictionary wordList is a sequence of
* words beginWord -> s1 -> s2 -> ... -> sk such that:
*
* Every adjacent pair of words differs by a single letter.
* Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList.
* sk == endWord
* Given two words, beginWord and endWord, and a dictionary wordList,
* return the number of words in the shortest transformation sequence from beginWord to endWord, or 0 if no such sequence exists.
*
* Example 1:
* Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
* Output: 5
* Explanation: One shortest transformation sequence is "hit" -> "hot" -> "dot" -> "dog" -> cog", which is 5 words long.
*
* Example 2:
* Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
* Output: 0
* Explanation: The endWord "cog" is not in wordList, therefore there is no valid transformation sequence.
*
* Constraints:
* 1 <= beginWord.length <= 10
* endWord.length == beginWord.length
* 1 <= wordList.length <= 5000
* wordList[i].length == beginWord.length
* beginWord, endWord, and wordList[i] consist of lowercase English letters.
* beginWord != endWord
* All the words in wordList are unique.
*
* Solution:
* The idea is to use BFS.
* We start from the given start word,
* traverse all words that adjacent (differ by one character) to it
* and keep doing so until we find the target word or we have traversed all words.
*
* @see <a href="https://algs4.cs.princeton.edu/41graph/WordLadder.java.html"></a>
* @see <a href="https://bradfieldcs.com/algos/graphs/word-ladder/"></a>
* @see <a href="https://www.geeksforgeeks.org/word-ladder-length-of-shortest-chain-to-reach-a-target-word/"></a>
* @see <a href="https://www.cs.cmu.edu/~adamchik/15-121/labs/HW-4%20Word%20Ladder/lab.html"></a>
* @see <a href="https://www.cs.cmu.edu/~adamchik/15-121/"></a>
* @see <a href="http://www.learn4master.com/algorithms/bread-first-search/leetcode-word-ladder-solution-in-java"></a>
*
* This problem is same as MinimumGeneticMutation of LC433
*
* LC127, Hard, frequency=55
* Tag: Amazon
*/
public class WordLadder {
public static void main(String[] args) {
String beginWord = "hit";
String endWord = "cog";
String[] wordArr = {"hot","dot","dog","lot","log","cog"};
int res = ladderLengthV3(beginWord, endWord, new ArrayList<>(Arrays.asList(wordArr)));
System.out.println(res);
}
/**
* Understanding the following Double-Direction Breadth First Solution
*
* Solution in ladderLengthV2 starts only from one-direction beginWord.
* We may also start from the beginWord and the endWord simultaneously.
* Once we meet the same word, we are done.
* The following code provides such a double-direction search solution.
* @param beginWord
* @param endWord
* @param wordList
* @return
*/
public static int ladderLengthV3(String beginWord, String endWord, List<String> wordList) {
Set<String> words = new HashSet<>(wordList);
if (!words.contains(endWord)) {
return 0;
}
Set<String> beginSet = new HashSet<>();
Set<String> endSet = new HashSet<>();
Set<String> visited = new HashSet<>();
beginSet.add(beginWord);
endSet.add(endWord);
int len = 1;
while(!beginSet.isEmpty() && !endSet.isEmpty()) {
if (beginSet.size() > endSet.size()) {
Set<String> temp = beginSet;
beginSet = endSet;
endSet = temp;
}
Set<String> middle = new HashSet<>();
for (String word : beginSet) {
char[] chr = word.toCharArray();
for (int i = 0; i < chr.length; i++) {
char old = chr[i];
for (char c = 'a'; c <= 'z'; c++) {
if (chr[i] == c) {
continue;
}
chr[i] = c;
String target = String.valueOf(chr);
if (endSet.contains(target)) {
return len + 1;
}
if (!visited.contains(target) && words.contains(target)) {
middle.add(target);
visited.add(target);
//for save memory
words.remove(target);
}
}
chr[i] = old;
}
}//one-level end
beginSet = middle;
len++;//search tree depth increment
}
return 0;
}
/**
* Understanding the following Breadth First Solution
* @param beginWord
* @param endWord
* @param wordList
* @return
*/
public static int ladderLengthV2(String beginWord, String endWord, List<String> wordList) {
Set<String> wordSet = new HashSet<>(wordList);
if (!wordSet.contains(endWord)) {
return 0;
}
/**
* beginWord is the first level.
*/
int level = 1;
Set<String> visited = new HashSet<>();
Queue<String> queue = new LinkedList<>();
queue.add(beginWord);
visited.add(beginWord);
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
String cur = queue.poll();
if (cur.equals(endWord)) {
return level;
}
/**
* Replace each character in the cur array,
* check the newly generated string whether in wordSet and has not been visited,
* then we add the newly generated string to the tail of the queue.
*/
char[] curArr = cur.toCharArray();
for (int j = 0; j < curArr.length; j++) {
char temp = curArr[j];
/**
* generate new string and push into the queue if it matches the condition.
* This step has many invalid attempts which can be cut off.
*/
for (char ch = 'a'; ch <= 'z'; ch++) {
curArr[j] = ch;
String generatedStr = new String(curArr);
if (!visited.contains(generatedStr) && wordSet.contains(generatedStr)) {
queue.offer(generatedStr);
/**
* marked generatedStr as visited is very important.
*/
visited.add(generatedStr);
}
}
curArr[j] = temp;
}
}
level++;
}
/**
* Not found such a sequence from beginWord to endWord.
*/
return 0;
}
/**
* This version is very slow when input huge data
* Returns length of the shortest chain to reach 'target' from 'start'
* using minimum number of adjacent moves.
* @param beginWord
* @param endWord
* @param wordList
* @return
*/
public int ladderLengthV1(String beginWord, String endWord, List<String> wordList) {
if (wordList == null || wordList.size() == 0) {
return 0;
}
if (beginWord == null || endWord == null) {
return 0;
}
if (beginWord.length() != endWord.length()) {
return 0;
}
Set<String> words = new HashSet<String>();
words.addAll(wordList);
if (!words.contains(endWord)) {
return 0;
}
//Create a queue for BFS and insert begin word as source vertex
Queue<String> queue = new LinkedList<>();
queue.add(beginWord);
Map<String, Boolean> visited = new HashMap<>();
Map<String, Integer> countMap = new HashMap<>();
visited.put(beginWord, true);
// Chain length for begin word is 1
countMap.put(beginWord, 1);
for(String word : words) {
if (!beginWord.equalsIgnoreCase(word)) {
visited.put(word, false);
countMap.put(word, 0);
}
}
while (!queue.isEmpty()) {
String cur = queue.poll();
System.out.println("cur:" + cur);
for (String word : words) {
System.out.println("word:" + word);
// Process a dictionary word if it is adjacent to current word (or vertex) of BFS
if (isDiffOne(cur, word) && (visited.get(word) == Boolean.FALSE)) {
int count = countMap.get(cur);//(countMap.get(cur) == null ? 0 : countMap.get(cur));
countMap.put(word, count + 1);
queue.add(word);
// Mark the word visited, so it will not be processed again.
visited.put(word, true);
// If the endWord is found, return current chain length directly.
if (word.equalsIgnoreCase(endWord)) {
return countMap.get(word);
}
}
}
}
return 0;
}
/**
* To check if two strings differ by exactly one character.
* @param a
* @param b
* @return
*/
public static boolean isDiffOne(String a, String b) {
if (a == null || b == null) {
return false;
}
if (a.length() != b.length()) {
return false;
}
// to store count of differences
int differ = 0;
for (int i = 0; i < a.length(); i++) {
if (a.charAt(i) != b.charAt(i)) {
differ++;
}
if (differ > 1) {
return false;
}
}
// If we assume no duplicates in the word list, then we can return true directly.
// The following return statement is equivalent on above assumption.
//return true
return (differ== 1 ? true : false);
}
/**
* Time Limit Exceeded
* beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
* "hit" -> "hot" -> "dot" -> "dog" -> cog", which is 5 words long
*
* --------hot--dot--dog--lot--log--cog--hit
* ---------0----1----2----3----4----5----6
* ----------------------------------------
* hot-0|---0----1----2----1----2----2----1
* dot-1|---1----0----1----1----2----2----2
* dog-2|---2----1----0----2----1----1----3
* lot-3|---1----1----2----0----1----2----2
* log-4|---2----2----1----1----0----1----3
* cog-5|---2----2----1----2----1----0----3
* hit-6|---1----2----3----2----3----3----0
*
* @param beginWord
* @param endWord
* @param wordList
* @return
*/
public static int ladderLength(String beginWord, String endWord, List<String> wordList) {
Set<String> wordSet = new HashSet<>(wordList);
if (!wordSet.contains(endWord)) {
return 0;
}
/**
* Add beginWord to the end of wordList.
*/
wordList.add(beginWord);
/**
* Build Distance Field for all the words in the wordList.
*/
int n = wordList.size();
int[][] dist = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
dist[i][j] = countDistance(wordList.get(i), wordList.get(j));
}
}
System.out.println(Arrays.deepToString(dist));
/**
* beginWord is the first level.
*/
int level = 1;
Set<Integer> visited = new HashSet<>();
Queue<Integer> queue = new LinkedList<>();
queue.add(n-1);
visited.add(n-1);
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
int cur = queue.poll();
if (wordList.get(cur).equals(endWord)) {
return level;
}
for (int j = 0; j < n; j++) {
if ((dist[cur][j] != 1 && dist[j][cur] != 1) || visited.contains(j)) {
continue;
}
queue.offer(j);
visited.add(j);
}
}
level++;
}
return 0;
}
public static int countDistance(String w1, String w2) {
int cnt = 0, n = w1.length();
for (int i = 0; i < n; i++) {
if (w1.charAt(i) != w2.charAt(i)) {
cnt++;
}
}
return cnt;
}
}
| true
|
eeb3f333dc6f98dc2e4196830e333d5633198c81
|
Java
|
Jonas-Szum/JavaParser-Function-Injector
|
/codio_env/cs474-hw1/test/edu/uic/cs474/hw1/Test30_OutsideClassReturnsNewLine.java
|
UTF-8
| 497
| 2.828125
| 3
|
[] |
no_license
|
package edu.uic.cs474.hw1;
import org.junit.Assert;
import org.junit.Test;
public class Test30_OutsideClassReturnsNewLine {
private Helper helper = new Helper();
@Test
public void test() {
String expected = "{-helper:This is\\na line change}";
Assert.assertEquals(expected, new Test30_OutsideClassReturnsNewLine().toString());
}
private static class Helper {
public String toString() {
return "This is\na line change";
}
}
}
| true
|
89dd66e270ce3f33d37167e54557ee67f51d1627
|
Java
|
fonuhuolian/XNohttp
|
/xnohttp/src/main/java/org/fonuhuolian/xnohttp/callback/XNoHttpCallBack.java
|
UTF-8
| 877
| 2.0625
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.fonuhuolian.xnohttp.callback;
import android.content.Context;
import org.fonuhuolian.toast.XToastUtils;
import org.fonuhuolian.xnohttp.base.XLoadingBaseDialog;
import org.fonuhuolian.xnohttp.base.XNoHttpBaseCallBack;
/**
* 作者: macpro on 2018/6/17.
* 邮箱: xxx.com
*/
public abstract class XNoHttpCallBack extends XNoHttpBaseCallBack {
public XNoHttpCallBack(Context context) {
super(context);
}
public XNoHttpCallBack(Context context, XLoadingBaseDialog XLoadingBaseDialog) {
super(context, XLoadingBaseDialog);
}
@Override
public void showXErrorMsg(int code, String errMsg) {
super.showXErrorMsg(code, errMsg);
if (code == 0)
XToastUtils.getInstance().shortToast(errMsg);
else
XToastUtils.getInstance().shortToast(errMsg + " 状态码:" + code);
}
}
| true
|
4a1586e08ff93268699335c29356853c2a70b2d4
|
Java
|
CTMM-TraIT/trait_bmia
|
/currentServer/software/nbia-web/src/gov/nih/nci/nbia/servlet/BasketDownloadServlet.java
|
UTF-8
| 2,131
| 2.421875
| 2
|
[] |
no_license
|
package gov.nih.nci.nbia.servlet;
import gov.nih.nci.nbia.util.NCIAConfig;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class BasketDownloadServlet extends HttpServlet {
/**
* This used to be in dataBasketBean.completeDownload.
* Moved here to avoid Tomahawk filter which loads everything in memory
**/
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
String fileName = (String)request.getSession().getAttribute("httpDownloadZipFileName");
if(fileName==null) {
response.sendError(500);
return;
}
response.setContentType("application/zip");
response.setHeader("Content-Disposition",
"attachment;filename=\"" + fileName + "\"");
File f = new File(NCIAConfig.getZipLocation() + "/" + fileName);
long fileLength = f.length();
InputStream in = new BufferedInputStream(new FileInputStream(f));
// Set header so that browser will know the file size
response.addHeader("Content-Length", String.valueOf(fileLength));
ServletOutputStream out = response.getOutputStream();
byte[] buf = new byte[4 * 1024]; // 4K buffer
int bytesRead;
try {
while ((bytesRead = in.read(buf)) != -1) {
out.write(buf, 0, bytesRead);
}
out.flush();
}
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
response.sendError(500);
}
}
}
}
| true
|
215a999ef91ff1b0adc97bcc6b990d0469d30ac0
|
Java
|
Arthur-qin/cloud-hub
|
/cloud-activity/src/main/java/com/arthur/cloud/activity/model/enums/ActivityEnums.java
|
UTF-8
| 390
| 2.359375
| 2
|
[] |
no_license
|
package com.arthur.cloud.activity.model.enums;
public enum ActivityEnums {
/**
* 待发布
*/
WAITING("待发布"),
/**
* 进行中
*/
PROGRESS("进行中"),
/**
* 已结束
*/
FINISH("已结束");
private String name;
ActivityEnums(String name){this.name = name;}
public String getName() {
return name;
}
}
| true
|
6c4a6385e2a0879ff92e9bfcbfffaa76db1d4048
|
Java
|
Rock-fact/mishpahug
|
/app/src/main/java/com/kor/foodmanager/ui/eventInfo/myEventInfoPending/MyEventInfoPendingFragment.java
|
UTF-8
| 3,466
| 1.929688
| 2
|
[] |
no_license
|
package com.kor.foodmanager.ui.eventInfo.myEventInfoPending;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.arellomobile.mvp.MvpAppCompatFragment;
import com.arellomobile.mvp.presenter.InjectPresenter;
import com.kor.foodmanager.R;
import com.kor.foodmanager.data.model.EventDto;
import com.kor.foodmanager.ui.IToolbar;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
public class MyEventInfoPendingFragment extends MvpAppCompatFragment implements MyEventInfoPendingAdapter.MyClickListener, IMyEventInfoPending {
@InjectPresenter
MyEventInfoPendingPresenter presenter;
@BindView(R.id.subscribers_list)
RecyclerView recyclerView;
@BindView(R.id.progressBar)
ProgressBar progressBar;
@BindView(R.id.date_txt)
TextView date;
@BindView(R.id.event_description)
TextView eventDescription;
private MyEventInfoPendingAdapter adapter;
private IToolbar iToolbar;
private Unbinder unbinder;
private EventDto event;
public MyEventInfoPendingFragment() {
}
public static MyEventInfoPendingFragment getNewInstance(EventDto event){
MyEventInfoPendingFragment myEventInfoPendingFragment=new MyEventInfoPendingFragment();
myEventInfoPendingFragment.event=event;
return myEventInfoPendingFragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState != null){
event = (EventDto)savedInstanceState.getSerializable("event");
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("event",event);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_my_event_info_pending, container, false);
unbinder = ButterKnife.bind(this, view);
date.setText(event.getDate());
eventDescription.setText(event.getDescription());
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(layoutManager);
adapter = presenter.getAdapter();
adapter.setSubscribers(event.getParticipants());
adapter.setListener(this);
recyclerView.setAdapter(adapter);
iToolbar = (IToolbar) getActivity();
iToolbar.setTitleToolbarEnable(event.getTitle(), false,true,false);
return view;
}
@Override
public void onDestroy() {
unbinder.unbind();
super.onDestroy();
}
public void userInfo(int adapterPosition) {
presenter.userInfo(adapterPosition);
}
@Override
public void showProgressFrame() {
progressBar.setVisibility(View.VISIBLE);
recyclerView.setVisibility(View.GONE);
}
@Override
public void hideProgressFrame() {
progressBar.setVisibility(View.GONE);
recyclerView.setVisibility(View.VISIBLE);
}
}
| true
|
d27deaba3c895369e554e89277962bb1d272c14b
|
Java
|
namendes/aggregated-delivery
|
/pactronics/site/components/src/main/java/com/bloomreach/commercedxp/demo/pactronics/spa/channel/WebsiteInfo.java
|
UTF-8
| 1,181
| 1.976563
| 2
|
[] |
no_license
|
package com.bloomreach.commercedxp.demo.pactronics.spa.channel;
import org.hippoecm.hst.configuration.channel.ChannelInfo;
import org.hippoecm.hst.core.parameters.FieldGroup;
import org.hippoecm.hst.core.parameters.FieldGroupList;
import org.hippoecm.hst.core.parameters.JcrPath;
import org.hippoecm.hst.core.parameters.Parameter;
@FieldGroupList({
@FieldGroup(
titleKey = "fields.channel",
value = {"logo", "logoSmall", "logoAlternative"}
)
})
public interface WebsiteInfo extends ChannelInfo {
@Parameter(name = "logo")
@JcrPath(
pickerSelectableNodeTypes = {"hippogallery:imageset"},
pickerInitialPath = "/content/gallery/logos"
)
String getLogoPath();
@Parameter(name = "logoSmall")
@JcrPath(
pickerSelectableNodeTypes = {"hippogallery:imageset"},
pickerInitialPath = "/content/gallery/logos"
)
String getLogoSmallPath();
@Parameter(name = "logoAlternative")
@JcrPath(
pickerSelectableNodeTypes = {"hippogallery:imageset"},
pickerInitialPath = "/content/gallery/logos"
)
String getLogoAlternativePath();
}
| true
|
7d069330db34a5cd06589cbd1365f661294e6dea
|
Java
|
HPxianliru/demo
|
/imgmap/src/main/java/com/imgmap/controller/CenterController.java
|
UTF-8
| 665
| 1.835938
| 2
|
[] |
no_license
|
package com.imgmap.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.imgmap.bean.User;
@Controller
@RequestMapping("/center")
@SuppressWarnings({"all"})
public class CenterController extends BaseController {
@RequestMapping("/project")
public String project(){
return "project";
}
}
| true
|
5d7e46152a12a0c24bac27913ea3dab56703c360
|
Java
|
SAC-CS-112-Pulido-Matthew/Dice
|
/src/Game.java
|
UTF-8
| 350
| 3.109375
| 3
|
[] |
no_license
|
public class Game {
public static void main(String[] args) {
int sidesTimesSix = 2; // enter 1 then sides = 6
int trials = 5; // number of rolls
Dice dice = new Dice (sidesTimesSix, trials);
for (int i = 0; i < trials; i++)
{
dice.getRoll();
dice.playGame();
}
dice.displayTrials();
dice.gameHistory();
}
}
| true
|
35681d73abec3c5a81a217de1ab2c89df5d70b82
|
Java
|
AmalAbdullaev/TreeAssist
|
/src/test/java/com/youngbrains/treeassist/web/rest/ProfileResourceIntTest.java
|
UTF-8
| 43,965
| 1.6875
| 2
|
[] |
no_license
|
package com.youngbrains.treeassist.web.rest;
import com.youngbrains.treeassist.TreeassistApp;
import com.youngbrains.treeassist.domain.Profile;
import com.youngbrains.treeassist.domain.User;
import com.youngbrains.treeassist.repository.ProfileRepository;
import com.youngbrains.treeassist.service.ProfileService;
import com.youngbrains.treeassist.service.dto.ProfileDTO;
import com.youngbrains.treeassist.service.mapper.ProfileMapper;
import com.youngbrains.treeassist.web.rest.errors.ExceptionTranslator;
import com.youngbrains.treeassist.service.dto.ProfileCriteria;
import com.youngbrains.treeassist.service.ProfileQueryService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.Validator;
import javax.persistence.EntityManager;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.List;
import static com.youngbrains.treeassist.web.rest.TestUtil.createFormattingConversionService;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import com.youngbrains.treeassist.domain.enumeration.HumanSex;
/**
* Test class for the ProfileResource REST controller.
*
* @see ProfileResource
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TreeassistApp.class)
public class ProfileResourceIntTest {
private static final String DEFAULT_FULL_NAME = "AAAAAAAAAA";
private static final String UPDATED_FULL_NAME = "BBBBBBBBBB";
private static final LocalDate DEFAULT_BIRTHDAY = LocalDate.ofEpochDay(0L);
private static final LocalDate UPDATED_BIRTHDAY = LocalDate.now(ZoneId.systemDefault());
private static final String DEFAULT_FAMILY_PHONES = "AAAAAAAAAA";
private static final String UPDATED_FAMILY_PHONES = "BBBBBBBBBB";
private static final String DEFAULT_BLOOD_TYPE = "AAAAAAAAAA";
private static final String UPDATED_BLOOD_TYPE = "BBBBBBBBBB";
private static final String DEFAULT_ALLERGIC_REACTIONS = "AAAAAAAAAA";
private static final String UPDATED_ALLERGIC_REACTIONS = "BBBBBBBBBB";
private static final HumanSex DEFAULT_SEX = HumanSex.MALE;
private static final HumanSex UPDATED_SEX = HumanSex.FEMALE;
private static final String DEFAULT_PHONE = "AAAAAAAAAA";
private static final String UPDATED_PHONE = "BBBBBBBBBB";
private static final Boolean DEFAULT_IS_VOLUNTEER = false;
private static final Boolean UPDATED_IS_VOLUNTEER = true;
private static final String DEFAULT_FCM_TOKEN = "AAAAAAAAAA";
private static final String UPDATED_FCM_TOKEN = "BBBBBBBBBB";
private static final String DEFAULT_LATITUDE = "AAAAAAAAAA";
private static final String UPDATED_LATITUDE = "BBBBBBBBBB";
private static final String DEFAULT_LONGITUDE = "AAAAAAAAAA";
private static final String UPDATED_LONGITUDE = "BBBBBBBBBB";
private static final String DEFAULT_ORGANIZATION = "AAAAAAAAAA";
private static final String UPDATED_ORGANIZATION = "BBBBBBBBBB";
private static final String DEFAULT_LOGIN = "AAAAAAAAAA";
private static final String UPDATED_LOGIN = "BBBBBBBBBB";
private static final String DEFAULT_EMAIL = "AAAAAAAAAA";
private static final String UPDATED_EMAIL = "BBBBBBBBBB";
@Autowired
private ProfileRepository profileRepository;
@Autowired
private ProfileMapper profileMapper;
@Autowired
private ProfileService profileService;
@Autowired
private ProfileQueryService profileQueryService;
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
@Autowired
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
@Autowired
private ExceptionTranslator exceptionTranslator;
@Autowired
private EntityManager em;
@Autowired
private Validator validator;
private MockMvc restProfileMockMvc;
private Profile profile;
private AccountResource accountResource;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
final ProfileResource profileResource = new ProfileResource(profileService, profileQueryService, accountResource);
this.restProfileMockMvc = MockMvcBuilders.standaloneSetup(profileResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setConversionService(createFormattingConversionService())
.setMessageConverters(jacksonMessageConverter)
.setValidator(validator).build();
}
/**
* Create an entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Profile createEntity(EntityManager em) {
Profile profile = new Profile()
.fullName(DEFAULT_FULL_NAME)
.birthday(DEFAULT_BIRTHDAY)
.familyPhones(DEFAULT_FAMILY_PHONES)
.bloodType(DEFAULT_BLOOD_TYPE)
.allergicReactions(DEFAULT_ALLERGIC_REACTIONS)
.sex(DEFAULT_SEX)
.phone(DEFAULT_PHONE)
.isVolunteer(DEFAULT_IS_VOLUNTEER)
.fcmToken(DEFAULT_FCM_TOKEN)
.latitude(DEFAULT_LATITUDE)
.longitude(DEFAULT_LONGITUDE)
.organization(DEFAULT_ORGANIZATION)
.login(DEFAULT_LOGIN)
.email(DEFAULT_EMAIL);
return profile;
}
@Before
public void initTest() {
profile = createEntity(em);
}
@Test
@Transactional
public void createProfile() throws Exception {
int databaseSizeBeforeCreate = profileRepository.findAll().size();
// Create the Profile
ProfileDTO profileDTO = profileMapper.toDto(profile);
restProfileMockMvc.perform(post("/api/profiles")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(profileDTO)))
.andExpect(status().isCreated());
// Validate the Profile in the database
List<Profile> profileList = profileRepository.findAll();
assertThat(profileList).hasSize(databaseSizeBeforeCreate + 1);
Profile testProfile = profileList.get(profileList.size() - 1);
assertThat(testProfile.getFullName()).isEqualTo(DEFAULT_FULL_NAME);
assertThat(testProfile.getBirthday()).isEqualTo(DEFAULT_BIRTHDAY);
assertThat(testProfile.getFamilyPhones()).isEqualTo(DEFAULT_FAMILY_PHONES);
assertThat(testProfile.getBloodType()).isEqualTo(DEFAULT_BLOOD_TYPE);
assertThat(testProfile.getAllergicReactions()).isEqualTo(DEFAULT_ALLERGIC_REACTIONS);
assertThat(testProfile.getSex()).isEqualTo(DEFAULT_SEX);
assertThat(testProfile.getPhone()).isEqualTo(DEFAULT_PHONE);
assertThat(testProfile.isIsVolunteer()).isEqualTo(DEFAULT_IS_VOLUNTEER);
assertThat(testProfile.getFcmToken()).isEqualTo(DEFAULT_FCM_TOKEN);
assertThat(testProfile.getLatitude()).isEqualTo(DEFAULT_LATITUDE);
assertThat(testProfile.getLongitude()).isEqualTo(DEFAULT_LONGITUDE);
assertThat(testProfile.getOrganization()).isEqualTo(DEFAULT_ORGANIZATION);
assertThat(testProfile.getLogin()).isEqualTo(DEFAULT_LOGIN);
assertThat(testProfile.getEmail()).isEqualTo(DEFAULT_EMAIL);
}
@Test
@Transactional
public void createProfileWithExistingId() throws Exception {
int databaseSizeBeforeCreate = profileRepository.findAll().size();
// Create the Profile with an existing ID
profile.setId(1L);
ProfileDTO profileDTO = profileMapper.toDto(profile);
// An entity with an existing ID cannot be created, so this API call must fail
restProfileMockMvc.perform(post("/api/profiles")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(profileDTO)))
.andExpect(status().isBadRequest());
// Validate the Profile in the database
List<Profile> profileList = profileRepository.findAll();
assertThat(profileList).hasSize(databaseSizeBeforeCreate);
}
@Test
@Transactional
public void getAllProfiles() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList
restProfileMockMvc.perform(get("/api/profiles?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(profile.getId().intValue())))
.andExpect(jsonPath("$.[*].fullName").value(hasItem(DEFAULT_FULL_NAME.toString())))
.andExpect(jsonPath("$.[*].birthday").value(hasItem(DEFAULT_BIRTHDAY.toString())))
.andExpect(jsonPath("$.[*].familyPhones").value(hasItem(DEFAULT_FAMILY_PHONES.toString())))
.andExpect(jsonPath("$.[*].bloodType").value(hasItem(DEFAULT_BLOOD_TYPE.toString())))
.andExpect(jsonPath("$.[*].allergicReactions").value(hasItem(DEFAULT_ALLERGIC_REACTIONS.toString())))
.andExpect(jsonPath("$.[*].sex").value(hasItem(DEFAULT_SEX.toString())))
.andExpect(jsonPath("$.[*].phone").value(hasItem(DEFAULT_PHONE.toString())))
.andExpect(jsonPath("$.[*].isVolunteer").value(hasItem(DEFAULT_IS_VOLUNTEER.booleanValue())))
.andExpect(jsonPath("$.[*].fcmToken").value(hasItem(DEFAULT_FCM_TOKEN.toString())))
.andExpect(jsonPath("$.[*].latitude").value(hasItem(DEFAULT_LATITUDE.toString())))
.andExpect(jsonPath("$.[*].longitude").value(hasItem(DEFAULT_LONGITUDE.toString())))
.andExpect(jsonPath("$.[*].organization").value(hasItem(DEFAULT_ORGANIZATION.toString())))
.andExpect(jsonPath("$.[*].login").value(hasItem(DEFAULT_LOGIN.toString())))
.andExpect(jsonPath("$.[*].email").value(hasItem(DEFAULT_EMAIL.toString())));
}
@Test
@Transactional
public void getProfile() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get the profile
restProfileMockMvc.perform(get("/api/profiles/{id}", profile.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.id").value(profile.getId().intValue()))
.andExpect(jsonPath("$.fullName").value(DEFAULT_FULL_NAME.toString()))
.andExpect(jsonPath("$.birthday").value(DEFAULT_BIRTHDAY.toString()))
.andExpect(jsonPath("$.familyPhones").value(DEFAULT_FAMILY_PHONES.toString()))
.andExpect(jsonPath("$.bloodType").value(DEFAULT_BLOOD_TYPE.toString()))
.andExpect(jsonPath("$.allergicReactions").value(DEFAULT_ALLERGIC_REACTIONS.toString()))
.andExpect(jsonPath("$.sex").value(DEFAULT_SEX.toString()))
.andExpect(jsonPath("$.phone").value(DEFAULT_PHONE.toString()))
.andExpect(jsonPath("$.isVolunteer").value(DEFAULT_IS_VOLUNTEER.booleanValue()))
.andExpect(jsonPath("$.fcmToken").value(DEFAULT_FCM_TOKEN.toString()))
.andExpect(jsonPath("$.latitude").value(DEFAULT_LATITUDE.toString()))
.andExpect(jsonPath("$.longitude").value(DEFAULT_LONGITUDE.toString()))
.andExpect(jsonPath("$.organization").value(DEFAULT_ORGANIZATION.toString()))
.andExpect(jsonPath("$.login").value(DEFAULT_LOGIN.toString()))
.andExpect(jsonPath("$.email").value(DEFAULT_EMAIL.toString()));
}
@Test
@Transactional
public void getAllProfilesByFullNameIsEqualToSomething() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList where fullName equals to DEFAULT_FULL_NAME
defaultProfileShouldBeFound("fullName.equals=" + DEFAULT_FULL_NAME);
// Get all the profileList where fullName equals to UPDATED_FULL_NAME
defaultProfileShouldNotBeFound("fullName.equals=" + UPDATED_FULL_NAME);
}
@Test
@Transactional
public void getAllProfilesByFullNameIsInShouldWork() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList where fullName in DEFAULT_FULL_NAME or UPDATED_FULL_NAME
defaultProfileShouldBeFound("fullName.in=" + DEFAULT_FULL_NAME + "," + UPDATED_FULL_NAME);
// Get all the profileList where fullName equals to UPDATED_FULL_NAME
defaultProfileShouldNotBeFound("fullName.in=" + UPDATED_FULL_NAME);
}
@Test
@Transactional
public void getAllProfilesByFullNameIsNullOrNotNull() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList where fullName is not null
defaultProfileShouldBeFound("fullName.specified=true");
// Get all the profileList where fullName is null
defaultProfileShouldNotBeFound("fullName.specified=false");
}
@Test
@Transactional
public void getAllProfilesByBirthdayIsEqualToSomething() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList where birthday equals to DEFAULT_BIRTHDAY
defaultProfileShouldBeFound("birthday.equals=" + DEFAULT_BIRTHDAY);
// Get all the profileList where birthday equals to UPDATED_BIRTHDAY
defaultProfileShouldNotBeFound("birthday.equals=" + UPDATED_BIRTHDAY);
}
@Test
@Transactional
public void getAllProfilesByBirthdayIsInShouldWork() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList where birthday in DEFAULT_BIRTHDAY or UPDATED_BIRTHDAY
defaultProfileShouldBeFound("birthday.in=" + DEFAULT_BIRTHDAY + "," + UPDATED_BIRTHDAY);
// Get all the profileList where birthday equals to UPDATED_BIRTHDAY
defaultProfileShouldNotBeFound("birthday.in=" + UPDATED_BIRTHDAY);
}
@Test
@Transactional
public void getAllProfilesByBirthdayIsNullOrNotNull() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList where birthday is not null
defaultProfileShouldBeFound("birthday.specified=true");
// Get all the profileList where birthday is null
defaultProfileShouldNotBeFound("birthday.specified=false");
}
@Test
@Transactional
public void getAllProfilesByBirthdayIsGreaterThanOrEqualToSomething() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList where birthday greater than or equals to DEFAULT_BIRTHDAY
defaultProfileShouldBeFound("birthday.greaterOrEqualThan=" + DEFAULT_BIRTHDAY);
// Get all the profileList where birthday greater than or equals to UPDATED_BIRTHDAY
defaultProfileShouldNotBeFound("birthday.greaterOrEqualThan=" + UPDATED_BIRTHDAY);
}
@Test
@Transactional
public void getAllProfilesByBirthdayIsLessThanSomething() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList where birthday less than or equals to DEFAULT_BIRTHDAY
defaultProfileShouldNotBeFound("birthday.lessThan=" + DEFAULT_BIRTHDAY);
// Get all the profileList where birthday less than or equals to UPDATED_BIRTHDAY
defaultProfileShouldBeFound("birthday.lessThan=" + UPDATED_BIRTHDAY);
}
@Test
@Transactional
public void getAllProfilesByFamilyPhonesIsEqualToSomething() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList where familyPhones equals to DEFAULT_FAMILY_PHONES
defaultProfileShouldBeFound("familyPhones.equals=" + DEFAULT_FAMILY_PHONES);
// Get all the profileList where familyPhones equals to UPDATED_FAMILY_PHONES
defaultProfileShouldNotBeFound("familyPhones.equals=" + UPDATED_FAMILY_PHONES);
}
@Test
@Transactional
public void getAllProfilesByFamilyPhonesIsInShouldWork() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList where familyPhones in DEFAULT_FAMILY_PHONES or UPDATED_FAMILY_PHONES
defaultProfileShouldBeFound("familyPhones.in=" + DEFAULT_FAMILY_PHONES + "," + UPDATED_FAMILY_PHONES);
// Get all the profileList where familyPhones equals to UPDATED_FAMILY_PHONES
defaultProfileShouldNotBeFound("familyPhones.in=" + UPDATED_FAMILY_PHONES);
}
@Test
@Transactional
public void getAllProfilesByFamilyPhonesIsNullOrNotNull() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList where familyPhones is not null
defaultProfileShouldBeFound("familyPhones.specified=true");
// Get all the profileList where familyPhones is null
defaultProfileShouldNotBeFound("familyPhones.specified=false");
}
@Test
@Transactional
public void getAllProfilesByBloodTypeIsEqualToSomething() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList where bloodType equals to DEFAULT_BLOOD_TYPE
defaultProfileShouldBeFound("bloodType.equals=" + DEFAULT_BLOOD_TYPE);
// Get all the profileList where bloodType equals to UPDATED_BLOOD_TYPE
defaultProfileShouldNotBeFound("bloodType.equals=" + UPDATED_BLOOD_TYPE);
}
@Test
@Transactional
public void getAllProfilesByBloodTypeIsInShouldWork() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList where bloodType in DEFAULT_BLOOD_TYPE or UPDATED_BLOOD_TYPE
defaultProfileShouldBeFound("bloodType.in=" + DEFAULT_BLOOD_TYPE + "," + UPDATED_BLOOD_TYPE);
// Get all the profileList where bloodType equals to UPDATED_BLOOD_TYPE
defaultProfileShouldNotBeFound("bloodType.in=" + UPDATED_BLOOD_TYPE);
}
@Test
@Transactional
public void getAllProfilesByBloodTypeIsNullOrNotNull() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList where bloodType is not null
defaultProfileShouldBeFound("bloodType.specified=true");
// Get all the profileList where bloodType is null
defaultProfileShouldNotBeFound("bloodType.specified=false");
}
@Test
@Transactional
public void getAllProfilesByAllergicReactionsIsEqualToSomething() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList where allergicReactions equals to DEFAULT_ALLERGIC_REACTIONS
defaultProfileShouldBeFound("allergicReactions.equals=" + DEFAULT_ALLERGIC_REACTIONS);
// Get all the profileList where allergicReactions equals to UPDATED_ALLERGIC_REACTIONS
defaultProfileShouldNotBeFound("allergicReactions.equals=" + UPDATED_ALLERGIC_REACTIONS);
}
@Test
@Transactional
public void getAllProfilesByAllergicReactionsIsInShouldWork() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList where allergicReactions in DEFAULT_ALLERGIC_REACTIONS or UPDATED_ALLERGIC_REACTIONS
defaultProfileShouldBeFound("allergicReactions.in=" + DEFAULT_ALLERGIC_REACTIONS + "," + UPDATED_ALLERGIC_REACTIONS);
// Get all the profileList where allergicReactions equals to UPDATED_ALLERGIC_REACTIONS
defaultProfileShouldNotBeFound("allergicReactions.in=" + UPDATED_ALLERGIC_REACTIONS);
}
@Test
@Transactional
public void getAllProfilesByAllergicReactionsIsNullOrNotNull() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList where allergicReactions is not null
defaultProfileShouldBeFound("allergicReactions.specified=true");
// Get all the profileList where allergicReactions is null
defaultProfileShouldNotBeFound("allergicReactions.specified=false");
}
@Test
@Transactional
public void getAllProfilesBySexIsEqualToSomething() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList where sex equals to DEFAULT_SEX
defaultProfileShouldBeFound("sex.equals=" + DEFAULT_SEX);
// Get all the profileList where sex equals to UPDATED_SEX
defaultProfileShouldNotBeFound("sex.equals=" + UPDATED_SEX);
}
@Test
@Transactional
public void getAllProfilesBySexIsInShouldWork() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList where sex in DEFAULT_SEX or UPDATED_SEX
defaultProfileShouldBeFound("sex.in=" + DEFAULT_SEX + "," + UPDATED_SEX);
// Get all the profileList where sex equals to UPDATED_SEX
defaultProfileShouldNotBeFound("sex.in=" + UPDATED_SEX);
}
@Test
@Transactional
public void getAllProfilesBySexIsNullOrNotNull() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList where sex is not null
defaultProfileShouldBeFound("sex.specified=true");
// Get all the profileList where sex is null
defaultProfileShouldNotBeFound("sex.specified=false");
}
@Test
@Transactional
public void getAllProfilesByPhoneIsEqualToSomething() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList where phone equals to DEFAULT_PHONE
defaultProfileShouldBeFound("phone.equals=" + DEFAULT_PHONE);
// Get all the profileList where phone equals to UPDATED_PHONE
defaultProfileShouldNotBeFound("phone.equals=" + UPDATED_PHONE);
}
@Test
@Transactional
public void getAllProfilesByPhoneIsInShouldWork() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList where phone in DEFAULT_PHONE or UPDATED_PHONE
defaultProfileShouldBeFound("phone.in=" + DEFAULT_PHONE + "," + UPDATED_PHONE);
// Get all the profileList where phone equals to UPDATED_PHONE
defaultProfileShouldNotBeFound("phone.in=" + UPDATED_PHONE);
}
@Test
@Transactional
public void getAllProfilesByPhoneIsNullOrNotNull() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList where phone is not null
defaultProfileShouldBeFound("phone.specified=true");
// Get all the profileList where phone is null
defaultProfileShouldNotBeFound("phone.specified=false");
}
@Test
@Transactional
public void getAllProfilesByIsVolunteerIsEqualToSomething() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList where isVolunteer equals to DEFAULT_IS_VOLUNTEER
defaultProfileShouldBeFound("isVolunteer.equals=" + DEFAULT_IS_VOLUNTEER);
// Get all the profileList where isVolunteer equals to UPDATED_IS_VOLUNTEER
defaultProfileShouldNotBeFound("isVolunteer.equals=" + UPDATED_IS_VOLUNTEER);
}
@Test
@Transactional
public void getAllProfilesByIsVolunteerIsInShouldWork() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList where isVolunteer in DEFAULT_IS_VOLUNTEER or UPDATED_IS_VOLUNTEER
defaultProfileShouldBeFound("isVolunteer.in=" + DEFAULT_IS_VOLUNTEER + "," + UPDATED_IS_VOLUNTEER);
// Get all the profileList where isVolunteer equals to UPDATED_IS_VOLUNTEER
defaultProfileShouldNotBeFound("isVolunteer.in=" + UPDATED_IS_VOLUNTEER);
}
@Test
@Transactional
public void getAllProfilesByIsVolunteerIsNullOrNotNull() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList where isVolunteer is not null
defaultProfileShouldBeFound("isVolunteer.specified=true");
// Get all the profileList where isVolunteer is null
defaultProfileShouldNotBeFound("isVolunteer.specified=false");
}
@Test
@Transactional
public void getAllProfilesByFcmTokenIsEqualToSomething() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList where fcmToken equals to DEFAULT_FCM_TOKEN
defaultProfileShouldBeFound("fcmToken.equals=" + DEFAULT_FCM_TOKEN);
// Get all the profileList where fcmToken equals to UPDATED_FCM_TOKEN
defaultProfileShouldNotBeFound("fcmToken.equals=" + UPDATED_FCM_TOKEN);
}
@Test
@Transactional
public void getAllProfilesByFcmTokenIsInShouldWork() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList where fcmToken in DEFAULT_FCM_TOKEN or UPDATED_FCM_TOKEN
defaultProfileShouldBeFound("fcmToken.in=" + DEFAULT_FCM_TOKEN + "," + UPDATED_FCM_TOKEN);
// Get all the profileList where fcmToken equals to UPDATED_FCM_TOKEN
defaultProfileShouldNotBeFound("fcmToken.in=" + UPDATED_FCM_TOKEN);
}
@Test
@Transactional
public void getAllProfilesByFcmTokenIsNullOrNotNull() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList where fcmToken is not null
defaultProfileShouldBeFound("fcmToken.specified=true");
// Get all the profileList where fcmToken is null
defaultProfileShouldNotBeFound("fcmToken.specified=false");
}
@Test
@Transactional
public void getAllProfilesByLatitudeIsEqualToSomething() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList where latitude equals to DEFAULT_LATITUDE
defaultProfileShouldBeFound("latitude.equals=" + DEFAULT_LATITUDE);
// Get all the profileList where latitude equals to UPDATED_LATITUDE
defaultProfileShouldNotBeFound("latitude.equals=" + UPDATED_LATITUDE);
}
@Test
@Transactional
public void getAllProfilesByLatitudeIsInShouldWork() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList where latitude in DEFAULT_LATITUDE or UPDATED_LATITUDE
defaultProfileShouldBeFound("latitude.in=" + DEFAULT_LATITUDE + "," + UPDATED_LATITUDE);
// Get all the profileList where latitude equals to UPDATED_LATITUDE
defaultProfileShouldNotBeFound("latitude.in=" + UPDATED_LATITUDE);
}
@Test
@Transactional
public void getAllProfilesByLatitudeIsNullOrNotNull() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList where latitude is not null
defaultProfileShouldBeFound("latitude.specified=true");
// Get all the profileList where latitude is null
defaultProfileShouldNotBeFound("latitude.specified=false");
}
@Test
@Transactional
public void getAllProfilesByLongitudeIsEqualToSomething() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList where longitude equals to DEFAULT_LONGITUDE
defaultProfileShouldBeFound("longitude.equals=" + DEFAULT_LONGITUDE);
// Get all the profileList where longitude equals to UPDATED_LONGITUDE
defaultProfileShouldNotBeFound("longitude.equals=" + UPDATED_LONGITUDE);
}
@Test
@Transactional
public void getAllProfilesByLongitudeIsInShouldWork() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList where longitude in DEFAULT_LONGITUDE or UPDATED_LONGITUDE
defaultProfileShouldBeFound("longitude.in=" + DEFAULT_LONGITUDE + "," + UPDATED_LONGITUDE);
// Get all the profileList where longitude equals to UPDATED_LONGITUDE
defaultProfileShouldNotBeFound("longitude.in=" + UPDATED_LONGITUDE);
}
@Test
@Transactional
public void getAllProfilesByLongitudeIsNullOrNotNull() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList where longitude is not null
defaultProfileShouldBeFound("longitude.specified=true");
// Get all the profileList where longitude is null
defaultProfileShouldNotBeFound("longitude.specified=false");
}
@Test
@Transactional
public void getAllProfilesByOrganizationIsEqualToSomething() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList where organization equals to DEFAULT_ORGANIZATION
defaultProfileShouldBeFound("organization.equals=" + DEFAULT_ORGANIZATION);
// Get all the profileList where organization equals to UPDATED_ORGANIZATION
defaultProfileShouldNotBeFound("organization.equals=" + UPDATED_ORGANIZATION);
}
@Test
@Transactional
public void getAllProfilesByOrganizationIsInShouldWork() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList where organization in DEFAULT_ORGANIZATION or UPDATED_ORGANIZATION
defaultProfileShouldBeFound("organization.in=" + DEFAULT_ORGANIZATION + "," + UPDATED_ORGANIZATION);
// Get all the profileList where organization equals to UPDATED_ORGANIZATION
defaultProfileShouldNotBeFound("organization.in=" + UPDATED_ORGANIZATION);
}
@Test
@Transactional
public void getAllProfilesByOrganizationIsNullOrNotNull() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList where organization is not null
defaultProfileShouldBeFound("organization.specified=true");
// Get all the profileList where organization is null
defaultProfileShouldNotBeFound("organization.specified=false");
}
@Test
@Transactional
public void getAllProfilesByLoginIsEqualToSomething() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList where login equals to DEFAULT_LOGIN
defaultProfileShouldBeFound("login.equals=" + DEFAULT_LOGIN);
// Get all the profileList where login equals to UPDATED_LOGIN
defaultProfileShouldNotBeFound("login.equals=" + UPDATED_LOGIN);
}
@Test
@Transactional
public void getAllProfilesByLoginIsInShouldWork() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList where login in DEFAULT_LOGIN or UPDATED_LOGIN
defaultProfileShouldBeFound("login.in=" + DEFAULT_LOGIN + "," + UPDATED_LOGIN);
// Get all the profileList where login equals to UPDATED_LOGIN
defaultProfileShouldNotBeFound("login.in=" + UPDATED_LOGIN);
}
@Test
@Transactional
public void getAllProfilesByLoginIsNullOrNotNull() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList where login is not null
defaultProfileShouldBeFound("login.specified=true");
// Get all the profileList where login is null
defaultProfileShouldNotBeFound("login.specified=false");
}
@Test
@Transactional
public void getAllProfilesByEmailIsEqualToSomething() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList where email equals to DEFAULT_EMAIL
defaultProfileShouldBeFound("email.equals=" + DEFAULT_EMAIL);
// Get all the profileList where email equals to UPDATED_EMAIL
defaultProfileShouldNotBeFound("email.equals=" + UPDATED_EMAIL);
}
@Test
@Transactional
public void getAllProfilesByEmailIsInShouldWork() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList where email in DEFAULT_EMAIL or UPDATED_EMAIL
defaultProfileShouldBeFound("email.in=" + DEFAULT_EMAIL + "," + UPDATED_EMAIL);
// Get all the profileList where email equals to UPDATED_EMAIL
defaultProfileShouldNotBeFound("email.in=" + UPDATED_EMAIL);
}
@Test
@Transactional
public void getAllProfilesByEmailIsNullOrNotNull() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
// Get all the profileList where email is not null
defaultProfileShouldBeFound("email.specified=true");
// Get all the profileList where email is null
defaultProfileShouldNotBeFound("email.specified=false");
}
@Test
@Transactional
public void getAllProfilesByUserIsEqualToSomething() throws Exception {
// Initialize the database
User user = UserResourceIntTest.createEntity(em);
em.persist(user);
em.flush();
profile.setUser(user);
profileRepository.saveAndFlush(profile);
Long userId = user.getId();
// Get all the profileList where user equals to userId
defaultProfileShouldBeFound("userId.equals=" + userId);
// Get all the profileList where user equals to userId + 1
defaultProfileShouldNotBeFound("userId.equals=" + (userId + 1));
}
/**
* Executes the search, and checks that the default entity is returned
*/
private void defaultProfileShouldBeFound(String filter) throws Exception {
restProfileMockMvc.perform(get("/api/profiles?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(profile.getId().intValue())))
.andExpect(jsonPath("$.[*].fullName").value(hasItem(DEFAULT_FULL_NAME)))
.andExpect(jsonPath("$.[*].birthday").value(hasItem(DEFAULT_BIRTHDAY.toString())))
.andExpect(jsonPath("$.[*].familyPhones").value(hasItem(DEFAULT_FAMILY_PHONES)))
.andExpect(jsonPath("$.[*].bloodType").value(hasItem(DEFAULT_BLOOD_TYPE)))
.andExpect(jsonPath("$.[*].allergicReactions").value(hasItem(DEFAULT_ALLERGIC_REACTIONS)))
.andExpect(jsonPath("$.[*].sex").value(hasItem(DEFAULT_SEX.toString())))
.andExpect(jsonPath("$.[*].phone").value(hasItem(DEFAULT_PHONE)))
.andExpect(jsonPath("$.[*].isVolunteer").value(hasItem(DEFAULT_IS_VOLUNTEER.booleanValue())))
.andExpect(jsonPath("$.[*].fcmToken").value(hasItem(DEFAULT_FCM_TOKEN)))
.andExpect(jsonPath("$.[*].latitude").value(hasItem(DEFAULT_LATITUDE)))
.andExpect(jsonPath("$.[*].longitude").value(hasItem(DEFAULT_LONGITUDE)))
.andExpect(jsonPath("$.[*].organization").value(hasItem(DEFAULT_ORGANIZATION)))
.andExpect(jsonPath("$.[*].login").value(hasItem(DEFAULT_LOGIN)))
.andExpect(jsonPath("$.[*].email").value(hasItem(DEFAULT_EMAIL)));
// Check, that the count call also returns 1
restProfileMockMvc.perform(get("/api/profiles/count?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(content().string("1"));
}
/**
* Executes the search, and checks that the default entity is not returned
*/
private void defaultProfileShouldNotBeFound(String filter) throws Exception {
restProfileMockMvc.perform(get("/api/profiles?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$").isArray())
.andExpect(jsonPath("$").isEmpty());
// Check, that the count call also returns 0
restProfileMockMvc.perform(get("/api/profiles/count?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(content().string("0"));
}
@Test
@Transactional
public void getNonExistingProfile() throws Exception {
// Get the profile
restProfileMockMvc.perform(get("/api/profiles/{id}", Long.MAX_VALUE))
.andExpect(status().isNotFound());
}
@Test
@Transactional
public void updateProfile() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
int databaseSizeBeforeUpdate = profileRepository.findAll().size();
// Update the profile
Profile updatedProfile = profileRepository.findById(profile.getId()).get();
// Disconnect from session so that the updates on updatedProfile are not directly saved in db
em.detach(updatedProfile);
updatedProfile
.fullName(UPDATED_FULL_NAME)
.birthday(UPDATED_BIRTHDAY)
.familyPhones(UPDATED_FAMILY_PHONES)
.bloodType(UPDATED_BLOOD_TYPE)
.allergicReactions(UPDATED_ALLERGIC_REACTIONS)
.sex(UPDATED_SEX)
.phone(UPDATED_PHONE)
.isVolunteer(UPDATED_IS_VOLUNTEER)
.fcmToken(UPDATED_FCM_TOKEN)
.latitude(UPDATED_LATITUDE)
.longitude(UPDATED_LONGITUDE)
.organization(UPDATED_ORGANIZATION)
.login(UPDATED_LOGIN)
.email(UPDATED_EMAIL);
ProfileDTO profileDTO = profileMapper.toDto(updatedProfile);
restProfileMockMvc.perform(put("/api/profiles")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(profileDTO)))
.andExpect(status().isOk());
// Validate the Profile in the database
List<Profile> profileList = profileRepository.findAll();
assertThat(profileList).hasSize(databaseSizeBeforeUpdate);
Profile testProfile = profileList.get(profileList.size() - 1);
assertThat(testProfile.getFullName()).isEqualTo(UPDATED_FULL_NAME);
assertThat(testProfile.getBirthday()).isEqualTo(UPDATED_BIRTHDAY);
assertThat(testProfile.getFamilyPhones()).isEqualTo(UPDATED_FAMILY_PHONES);
assertThat(testProfile.getBloodType()).isEqualTo(UPDATED_BLOOD_TYPE);
assertThat(testProfile.getAllergicReactions()).isEqualTo(UPDATED_ALLERGIC_REACTIONS);
assertThat(testProfile.getSex()).isEqualTo(UPDATED_SEX);
assertThat(testProfile.getPhone()).isEqualTo(UPDATED_PHONE);
assertThat(testProfile.isIsVolunteer()).isEqualTo(UPDATED_IS_VOLUNTEER);
assertThat(testProfile.getFcmToken()).isEqualTo(UPDATED_FCM_TOKEN);
assertThat(testProfile.getLatitude()).isEqualTo(UPDATED_LATITUDE);
assertThat(testProfile.getLongitude()).isEqualTo(UPDATED_LONGITUDE);
assertThat(testProfile.getOrganization()).isEqualTo(UPDATED_ORGANIZATION);
assertThat(testProfile.getLogin()).isEqualTo(UPDATED_LOGIN);
assertThat(testProfile.getEmail()).isEqualTo(UPDATED_EMAIL);
}
@Test
@Transactional
public void updateNonExistingProfile() throws Exception {
int databaseSizeBeforeUpdate = profileRepository.findAll().size();
// Create the Profile
ProfileDTO profileDTO = profileMapper.toDto(profile);
// If the entity doesn't have an ID, it will throw BadRequestAlertException
restProfileMockMvc.perform(put("/api/profiles")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(profileDTO)))
.andExpect(status().isBadRequest());
// Validate the Profile in the database
List<Profile> profileList = profileRepository.findAll();
assertThat(profileList).hasSize(databaseSizeBeforeUpdate);
}
@Test
@Transactional
public void deleteProfile() throws Exception {
// Initialize the database
profileRepository.saveAndFlush(profile);
int databaseSizeBeforeDelete = profileRepository.findAll().size();
// Delete the profile
restProfileMockMvc.perform(delete("/api/profiles/{id}", profile.getId())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
// Validate the database is empty
List<Profile> profileList = profileRepository.findAll();
assertThat(profileList).hasSize(databaseSizeBeforeDelete - 1);
}
@Test
@Transactional
public void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(Profile.class);
Profile profile1 = new Profile();
profile1.setId(1L);
Profile profile2 = new Profile();
profile2.setId(profile1.getId());
assertThat(profile1).isEqualTo(profile2);
profile2.setId(2L);
assertThat(profile1).isNotEqualTo(profile2);
profile1.setId(null);
assertThat(profile1).isNotEqualTo(profile2);
}
@Test
@Transactional
public void dtoEqualsVerifier() throws Exception {
TestUtil.equalsVerifier(ProfileDTO.class);
ProfileDTO profileDTO1 = new ProfileDTO();
profileDTO1.setId(1L);
ProfileDTO profileDTO2 = new ProfileDTO();
assertThat(profileDTO1).isNotEqualTo(profileDTO2);
profileDTO2.setId(profileDTO1.getId());
assertThat(profileDTO1).isEqualTo(profileDTO2);
profileDTO2.setId(2L);
assertThat(profileDTO1).isNotEqualTo(profileDTO2);
profileDTO1.setId(null);
assertThat(profileDTO1).isNotEqualTo(profileDTO2);
}
@Test
@Transactional
public void testEntityFromId() {
assertThat(profileMapper.fromId(42L).getId()).isEqualTo(42);
assertThat(profileMapper.fromId(null)).isNull();
}
}
| true
|
0227928bc252196a2862aea2f7e4556295c395df
|
Java
|
umangbhatia/workspace
|
/Recursion/src/NumberKeypadBetter.java
|
UTF-8
| 954
| 3.1875
| 3
|
[] |
no_license
|
import java.util.Scanner;
public class NumberKeypadBetter {
public static String[] text(int n, String[] options){
if(n==0){
String output[]={""};
return output;
}
int lastDigit = n%10;
String lastDigitOptions = options[lastDigit];
String[] smallOutput = text(n/10, options);
String output[]= new String[smallOutput.length*lastDigitOptions.length()];
int count=0;
for(int i=0; i<smallOutput.length; i++){
for(int j=0; j<lastDigitOptions.length();j++){
output[count]=smallOutput[i]+lastDigitOptions.charAt(j);
count++;
}
}
return output;
}
public static void printArr(String arr[]){
for(int i=0;i<arr.length;i++){
System.out.print(arr[i]+" ");
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String options[]={"","","abc","def","ghi"};
System.out.println("Enter n");
Scanner s = new Scanner(System.in);
int n = s.nextInt();
printArr(text(n, options));
}
}
| true
|
2617568bae538ee70853fd4b780bd3ceb3888518
|
Java
|
juliusnarh/AMS-CURRENT
|
/app/src/main/java/com/telpo/usb/finger/entities/Pc.java
|
UTF-8
| 2,296
| 1.992188
| 2
|
[] |
no_license
|
package com.telpo.usb.finger.entities;
// Generated Dec 14, 2017 8:28:43 PM by Hibernate Tools 4.3.1
/**
* Pc generated by hbm2java
*/
public class Pc implements java.io.Serializable {
private String pcid;
private String lbcid;
private String buyingcenter;
private String names;
private String address;
private String tel;
private String email;
private String location;
private String imageLocation;
public Pc() {
}
public Pc(String pcid, String lbcid, String buyingcenter, String names, String address, String tel, String email, String location, String imageLocation) {
this.pcid = pcid;
this.lbcid = lbcid;
this.buyingcenter = buyingcenter;
this.names = names;
this.address = address;
this.tel = tel;
this.email = email;
this.location = location;
this.imageLocation = imageLocation;
}
public String getPcid() {
return this.pcid;
}
public void setPcid(String pcid) {
this.pcid = pcid;
}
public String getLbcid() {
return this.lbcid;
}
public void setLbcid(String lbcid) {
this.lbcid = lbcid;
}
public String getBuyingcenter() {
return this.buyingcenter;
}
public void setBuyingcenter(String buyingcenter) {
this.buyingcenter = buyingcenter;
}
public String getNames() {
return this.names;
}
public void setNames(String names) {
this.names = names;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
public String getTel() {
return this.tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getLocation() {
return this.location;
}
public void setLocation(String location) {
this.location = location;
}
public String getImageLocation() {
return this.imageLocation;
}
public void setImageLocation(String imageLocation) {
this.imageLocation = imageLocation;
}
}
| true
|
6632483d8058e4e7d172e49d43e8dd09b847aba7
|
Java
|
mhtoyoda/bots
|
/icaptor-core/src/main/java/com/fiveware/model/message/MessageParameterAgentBot.java
|
UTF-8
| 1,072
| 2.09375
| 2
|
[] |
no_license
|
package com.fiveware.model.message;
import java.io.Serializable;
public class MessageParameterAgentBot implements Serializable{
private String typeParameterName;
private Boolean typeParameterExclusive;
private Boolean typeParameterCredential;
private String parameterValue;
public String getTypeParameterName() {
return typeParameterName;
}
public void setTypeParameterName(String typeParameterName) {
this.typeParameterName = typeParameterName;
}
public Boolean getTypeParameterExclusive() {
return typeParameterExclusive;
}
public void setTypeParameterExclusive(Boolean typeParameterExclusive) {
this.typeParameterExclusive = typeParameterExclusive;
}
public Boolean getTypeParameterCredential() {
return typeParameterCredential;
}
public void setTypeParameterCredential(Boolean typeParameterCredential) {
this.typeParameterCredential = typeParameterCredential;
}
public String getParameterValue() {
return parameterValue;
}
public void setParameterValue(String parameterValue) {
this.parameterValue = parameterValue;
}
}
| true
|
421137d3d8da02f1fd2b5162f19b797d7f424c73
|
Java
|
SystemaAS/syjservicescommon
|
/src/main/no/systema/jservices/common/dao/KosttDao.java
|
UTF-8
| 500
| 1.882813
| 2
|
[] |
no_license
|
package no.systema.jservices.common.dao;
import java.util.HashMap;
import java.util.Map;
import lombok.Data;
/**
* Teller for misc in Kostnadsföring
*
* @author fredrikmoller
* @dato 2018-09-19
*/
@Data
public class KosttDao implements IDao {
private String ktna;
private Integer ktnr;
private String kttyp; //key
private Map<String, Object> keys = new HashMap<String, Object>();
@Override
public Map<String, Object> getKeys() {
keys.put("kttyp", kttyp);
return keys;
}
}
| true
|
b2d63af13090b638864b9842614cec182d2dbaba
|
Java
|
caseyrodgers/cm
|
/src/main/java/hotmath/cm/assignment/AssignmentLessonPidSelector.java
|
UTF-8
| 9,429
| 2.140625
| 2
|
[] |
no_license
|
package hotmath.cm.assignment;
import hotmath.assessment.AssessmentPrescription;
import hotmath.assessment.InmhItemData;
import hotmath.assessment.RppWidget;
import hotmath.cm.util.CatchupMathProperties;
import hotmath.gwt.cm_admin.server.model.CustomQuizQuestionManager;
import hotmath.gwt.cm_core.client.model.CustomProblemModel;
import hotmath.gwt.cm_rpc.client.model.LessonModel;
import hotmath.gwt.cm_rpc.client.rpc.InmhItemData.CmResourceType;
import hotmath.gwt.cm_rpc_assignments.client.model.assignment.ProblemDto;
import hotmath.gwt.cm_rpc_assignments.client.model.assignment.ProblemDto.ProblemType;
import hotmath.gwt.cm_rpc_core.client.rpc.CmList;
import hotmath.gwt.shared.client.model.QuizQuestion;
import hotmath.inmh.INeedMoreHelpItem;
import hotmath.testset.ha.CustomProblemDao;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.jdbc.core.RowMapper;
public class AssignmentLessonPidSelector {
static Logger __logger = Logger.getLogger(AssignmentLessonPidSelector.class);
List<ProblemDto> problemsAll = new ArrayList<ProblemDto>();
int MAX_PIDS = 20;
int MAX_MULTI_CHOICE = 5;
final int count[] = new int[1];
final LessonModel lesson;
public AssignmentLessonPidSelector(Connection conn, final String lessonName, String lessonFile, String subject) throws Exception {
lesson = new LessonModel(lessonName, lessonFile);
InmhItemData itemData = new InmhItemData(new INeedMoreHelpItem(CmResourceType.PRACTICE.label(), lessonFile, lessonName));
try {
List<RppWidget> rpps = itemData.getWidgetPool(conn, "assignment_pid");
for (RppWidget w : rpps) {
for (RppWidget ew : AssessmentPrescription.expandProblemSetPids(w)) {
problemsAll.add(new ProblemDto(0, 0, "", ew.getFile(), 0));
}
}
} catch (Exception e) {
e.printStackTrace();
}
__logger.debug("Read RPPs: " + problemsAll.size());
/**
* Read any EPP problems for this lesson
*
*/
String sql = "select * " + " from inmh_link " + " where link_type = 'cmextra' " + " and file = ? " + " order by id desc";
List<ProblemDto> eppProblems = AssignmentDao.getInstance().getJdbcTemplate().query(sql, new Object[] { lessonFile }, new RowMapper<ProblemDto>() {
@Override
public ProblemDto mapRow(ResultSet rs, int rowNum) throws SQLException {
String pid = rs.getString("link_key");
pid = pid.split(":")[0]; // strip off any grade range
return new ProblemDto(0, 0, "", pid, 0);
}
});
__logger.debug("Read EPPs: " + eppProblems.size());
for (ProblemDto p : eppProblems) {
if (alreadyContains(problemsAll, p.getPid())) {
problemsAll.add(p);
}
}
/**
* Custom Quiz problems
*
* Add at most MAX_MULTI_CHOICE MC problems.
*
* combine both custom quiz questions and normal quiz questions
*
*/
CmList<QuizQuestion> cqQuestions = CustomQuizQuestionManager.getInstance().getQuestionsFor(conn, lessonFile, 999);
__logger.debug("Read Custom Quiz MC: " + cqQuestions.size());
Collection<ProblemDto> quizQuestions = new ArrayList<ProblemDto>();
for (QuizQuestion qq : cqQuestions) {
quizQuestions.add(new ProblemDto(0, 0, "", qq.getPid(), 0));
}
if (quizQuestions.size() <= MAX_MULTI_CHOICE) {
// only if needed
quizQuestions.addAll(getQuizProblems(MAX_MULTI_CHOICE, subject, lessonName));
__logger.debug("Read Quiz MC: " + quizQuestions.size());
}
int numMcProbs = 0;
for (ProblemDto qq : quizQuestions) {
/**
* if already have enough
*
*/
if (problemsAll.size() >= MAX_PIDS) {
break;
}
/**
* Dummy problems are used to link up custom programs and should not
* be included.
*/
if (qq.getPid().startsWith("dummy")) {
continue;
}
/**
* If this pid does not already exist add it only take
* MAX_MULTI_CHOICE
*/
if (!alreadyContains(problemsAll, qq.getPid())) {
problemsAll.add(qq);
if ((++numMcProbs) + 1 > MAX_MULTI_CHOICE) {
break;
}
}
}
AssignmentDao.getInstance().updateProblemTypes(problemsAll);
/** Sort so all Widget problems come first, then whiteboard then MC
*
*/
Collections.sort(problemsAll, new Comparator<ProblemDto>() {
@Override
public int compare(ProblemDto o1, ProblemDto o2) {
ProblemType p1 = o1.getProblemType();
ProblemType p2 = o2.getProblemType();
if(p1 == p2) {
return 0;
}
if(p1 == ProblemType.INPUT_WIDGET && p2 != ProblemType.INPUT_WIDGET) {
return -1;
}
else if(p2 == ProblemType.INPUT_WIDGET && p1 != ProblemType.INPUT_WIDGET) {
return 1;
}
else if(p1 == ProblemType.WHITEBOARD && p2 == ProblemType.MULTI_CHOICE) {
return -1;
}
else if(p2 == ProblemType.WHITEBOARD && p1 == ProblemType.MULTI_CHOICE) {
return 1;
}
else if(p1 == ProblemType.UNKNOWN) {
return 1;
}
else if(p2 == ProblemType.UNKNOWN) {
return -1;
}
else {
return 0;
}
}
});
/**
* Add the label to each
*
*/
int pCount = 0;
for (ProblemDto p : problemsAll) {
p.setLabel(getDefaultLabel(lessonName, (++pCount)));
}
/** Only do this if NOT THE LIVE server */
if(CatchupMathProperties.getInstance().getProperty("use.custom_problems","false").equals("true")) {
/** Add any custom problem associated with this lesson
*
*/
List<CustomProblemModel> customProblems = CustomProblemDao.getInstance().getCustomProblemsLinkedToLesson(lessonFile);
List<ProblemDto> problems = new ArrayList<ProblemDto>();
pCount=0;
for (CustomProblemModel p : customProblems) {
++pCount;
String subFolder=p.getTreePath()!=null?"/" + p.getTreePath():"";
String custProbName = p.getTeacher().getTeacherName() + subFolder + "/" + p.getComments();
ProblemDto prob = new ProblemDto(pCount,pCount,custProbName,p.getPid(),0);
prob.setProblemType(p.getProblemType());
problems.add(prob);
}
/** custom problems shown at top of list */
problemsAll.addAll(0, problems);
}
}
private boolean alreadyContains(List<ProblemDto> problemsAll2, String pid) {
for (ProblemDto d : problemsAll2) {
if (d.getPid().equals(pid)) {
return true;
}
}
return false;
}
/**
* Return at most numToGet quiz/MC problems. May return less than requested.
*
* @param numToGet
* @param subject
* @param lessonName
* @return
* @throws Exception
*/
private Collection<ProblemDto> getQuizProblems(int numToGet, final String subject, final String lessonName) throws Exception {
/**
* Add the MC, quiz questions
*
*/
String sql = "";
if (subject != null) {
sql = "select * from HA_PROGRAM_LESSONS_static where lesson = ? and subject = ? order by rand()";
} else {
sql = "select * from HA_PROGRAM_LESSONS_static where lesson = ? OR subject = ? order by rand()"; // get
// all
}
List<ProblemDto> problems = AssignmentDao.getInstance().getJdbcTemplate().query(sql, new Object[] { lessonName, subject }, new RowMapper<ProblemDto>() {
@Override
public ProblemDto mapRow(ResultSet rs, int rowNum) throws SQLException {
String defaultLabel = getDefaultLabel(lessonName, (++count[0]));
return new ProblemDto(0, 0, defaultLabel, rs.getString("pid"), 0);
}
});
if (problems.size() < numToGet) {
return problems;
} else {
return problems.subList(0, numToGet);
}
}
public List<ProblemDto> getProblems() {
return problemsAll;
}
private String getDefaultLabel(String lesson, int i) {
String filler = "";
if (i < 10) {
filler = " ";
}
return lesson + ": " + filler + i;
}
}
| true
|
213f2da56c569c133cdedc6a1c8c711741bce020
|
Java
|
vietthai2512/FinalProject-1
|
/src/main/java/com/zeroToHero/FinalProject/database/dbPrep/DBPrepMain.java
|
UTF-8
| 1,277
| 2.46875
| 2
|
[] |
no_license
|
package com.zeroToHero.FinalProject.database.dbPrep;
import com.zeroToHero.FinalProject.database.queries.prepQueries.CreateQuery;
import com.zeroToHero.FinalProject.database.queries.prepQueries.DropQuery;
import com.zeroToHero.FinalProject.database.queries.prepQueries.PopulateQuery;
import java.sql.SQLException;
public class DBPrepMain implements CreateQuery, PopulateQuery
{
public static void main(String[] args) throws SQLException {
switch (args[0])
{
case "create-tables":
new DBTablesCreate(CreateQuery.createAll.toString()).create();
break;
case "drop-tables":
new DBTablesDrop(DropQuery.dropTables).drop();
break;
case "populate-tables":
new DBTablesPopulate(PopulateQuery.insertAll.toString()).populate();
break;
case "setup-database":
new DBTablesDrop(DropQuery.dropTables).drop();
new DBTablesCreate(CreateQuery.createAll.toString()).create();
new DBTablesPopulate(PopulateQuery.insertAll.toString()).populate();
break;
default:
System.out.println("Usage: mvn exec:java -P {profile}");
}
}
}
| true
|
b303b44bf081fcb7ead19edff92d2af04f55f309
|
Java
|
CarlhuGit/Redis
|
/src/main/java/com/atguigu/test/JedisPoolTest.java
|
UTF-8
| 464
| 2.171875
| 2
|
[] |
no_license
|
package com.atguigu.test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
public class JedisPoolTest {
public static void main(String[] args)
{
JedisPool pool = JedisPoolUtils.getInstance();
Jedis jedis = null;
try
{
jedis = pool.getResource();
jedis.set("class0515","nbv5");
}catch (Exception e) {
e.printStackTrace();
}finally {
JedisPoolUtils.release(pool, jedis);
}
}
}
| true
|
aeda3aabbf65e5f2dfb8775b682e333d3f0bb91c
|
Java
|
cetusDownfall/exercises
|
/exercises/java-exercises/wireworld/WireAnim.java
|
UTF-8
| 6,479
| 2.453125
| 2
|
[] |
no_license
|
package cellularAutomata.wireworld;
import cellularAutomata.utils.*;
import javafx.animation.Animation;
import javafx.animation.Timeline;
import javafx.util.Duration;
import javafx.animation.KeyFrame;
import javafx.scene.image.WritableImage;
import javafx.scene.image.PixelWriter;
import javafx.scene.layout.BorderPane;
import javafx.scene.control.TextArea;
import cellularAutomata.wireworld.Wire.CellType;
import javafx.scene.*;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.VBox;
import javafx.scene.Node;
import javafx.scene.image.*;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.event.EventHandler;
import javafx.event.*;
import javafx.beans.value.*;
import javafx.beans.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.*;
import java.util.Scanner;
public class WireAnim extends AbstractCellularAnimation{
private WireDrawPoint cur;
private int dim;
private PixelWriter startingPen;
private Timeline tmln = new Timeline();
private Wire[][] wireMap;
private HashSet<Wire> wireHash = new HashSet<Wire>();
private void refreshStates(){
wireHash.clear();
for (Wire[] row : wireMap){
for (Wire wr : row){
wr.addTo(wireMap,wireHash);
}
}
}
@Override
public WritableImage getNextImage(){
WritableImage g = new WritableImage(getCurrentImage().getPixelReader(), wireMap.length,wireMap[0].length);
PixelWriter pen = g.getPixelWriter();
for (Wire wr : wireHash){
pen.setColor(wr.getPoint().getPos(1), wr.getPoint().getPos(0), wr.getNextState());
}
for (Wire wr : wireHash){
wr.update();
}
return g;
}
@Override
public WritableImage getCurrentImage(){
WritableImage g = new WritableImage(wireMap.length,wireMap[0].length);
PixelWriter pen = g.getPixelWriter();
for (int i = 0; i < wireMap.length; i++){
for (int j = 0; j < wireMap[i].length; j++){
pen.setColor(j,i,wireMap[i][j].getCurrentState());
}
}
return g;
}
public Wire[][] getWires(Image img){
PixelReader getter = img.getPixelReader();
Wire[][] outW = new Wire[(int)(img.getHeight()+.5)][(int)(img.getWidth()+.5)];
for (int i = 0; i < outW.length; i++){
for (int j = 0; j < outW[i].length; j++){
Color c = getter.getColor(j,i);
CellType t = CellType.DEAD;
if (c.equals(CellType.WIRE.getCurrentState())){
t=CellType.WIRE;
}else if (c.equals(CellType.HEAD.getCurrentState())){
t=CellType.HEAD;
}else if (c.equals(CellType.TAIL.getCurrentState())){
t=CellType.TAIL;
}else{
t = CellType.DEAD;
}
outW[i][j] = new Wire(i,j,t);
}
}
return outW;
}
@Override
public void setupAutomaton(ImageView startImv){
/*Image pre = startImv.getImage();
Wire[][] tmp = getWires(pre);
for (int i = 0; i < tmp.length; i++){
for (int j = 0; j < tmp[i].length; j++){
wireMap[i][j] = tmp[i][j];
}
}*/
refreshStates();
startImv.setImage(getCurrentImage());
tmln.stop();
tmln.getKeyFrames().clear();
cur.stop();
}
@Override
public void prepareAuto(WritableImage stImg,ImageView imv){
dim = (int) (stImg.getHeight()+.5);
imv.setImage(stImg);
PixelWriter startingPen = stImg.getPixelWriter();
if (wireMap == null){
wireMap = new Wire[dim][dim];
}
for (int i = 0; i < wireMap.length; i++){
for (int j = 0; j < wireMap[i].length; j++){
wireMap[i][j] = new Wire(i,j,CellType.DEAD);
}
}
Wire[][] temp = getWires(stImg);
for (int i = 0; i < wireMap.length; i++){
for (int j = 0; j < wireMap[i].length; j++){
wireMap[i][j] = temp[i][j];
startingPen.setColor(j,i,wireMap[i][j].getCurrentState());
}
}
cur = new WireDrawPoint(wireMap.length,wireMap[0].length);
tmln.setCycleCount(Timeline.INDEFINITE);
KeyFrame frm = new KeyFrame(
Duration.seconds(0.017),
new EventHandler<ActionEvent>(){
public void handle(ActionEvent ae){
if (cur.getDraw()){
wireMap[cur.getPos(0)][cur.getPos(1)].setCellType(cur.getType());
}
for (int i = -dim/180; i <= dim/180; i++){
for (int j = -dim/180; j <= dim/180; j++){
if (cur.getPos(0) + i >= 0 && cur.getPos(0) + i < dim && cur.getPos(1) + j >= 0 && cur.getPos(1) + j < dim){
startingPen.setColor(cur.getPos(1)+j,cur.getPos(0)+i,wireMap[cur.getPos(0)+i][cur.getPos(1)+j].getCurrentState());
}
}
}
cur.move();
for (int i = -dim/180; i <= dim/180; i++){
for (int j = -dim/180; j <= dim/180; j++){
if (cur.getPos(0) + i >= 0 && cur.getPos(0) + i < dim && cur.getPos(1) + j >= 0 && cur.getPos(1) + j < dim){
int a = cur.getPos(1)+j;
int b = cur.getPos(0)+i;
startingPen.setColor(a,b,cur.getDraw()?wireMap[b][a].getCurrentState():wireMap[b][a].getCurrentState().invert());
if (cur.getDraw()||cur.getSlow()){
if (i == 0 || j == 0){
startingPen.setColor(a,b,wireMap[b][a].getCurrentState().darker().invert());
}
}
}
}
}
if (!cur.getDraw()){
startingPen.setColor(cur.getPos(1),cur.getPos(0),wireMap[cur.getPos(0)][cur.getPos(1)].getCurrentState().invert());
}else{
startingPen.setColor(cur.getPos(1),cur.getPos(0),cur.getType().getCurrentState());
}
}
});
tmln.getKeyFrames().clear();
tmln.getKeyFrames().add(frm);
tmln.play();
}
@Override
public void setupPanel(Scene s){
s.setOnKeyPressed(new EventHandler<KeyEvent>(){
@Override
public void handle(KeyEvent ke){
boolean shift = false;
switch (ke.getCode()){
case H: cur.push('l',1);break;
case J: cur.push('d',1);break;
case K: cur.push('u',1);break;
case L: cur.push('r',1);break;
case W: cur.setType(CellType.WIRE);cur.setDraw(true);break;
case A: cur.setType(CellType.TAIL);cur.setDraw(true);break;
case S: cur.setType(CellType.HEAD);cur.setDraw(true);break;
case D: cur.setType(CellType.DEAD);cur.setDraw(true);break;
case SHIFT: cur.setSlow();shift = true;break;
}
}
});
s.setOnKeyReleased(new EventHandler<KeyEvent>(){
@Override
public void handle(KeyEvent ke){
switch (ke.getCode()){
case H: cur.push('l',0);break;
case J: cur.push('d',0);break;
case K: cur.push('u',0);break;
case L: cur.push('r',0);break;
case W:
case A:
case S:
case D: cur.setType(wireMap[cur.getPos(0)][cur.getPos(1)].getCellType());cur.setDraw(false);break;
case SHIFT: cur.setFast();break;
}
}
});
}
public static void main(String[] args){
launch(args);
}
}
| true
|
866c9bfcc1528cd612920855d620f8d3469aba6a
|
Java
|
cesariux23/congresos
|
/src/main/resources/entity/Municipio.java
|
UTF-8
| 961
| 2.09375
| 2
|
[] |
no_license
|
package entity;
// Generated 19/05/2017 05:19:01 PM by Hibernate Tools 4.3.1
/**
* Municipio generated by hbm2java
*/
public class Municipio implements java.io.Serializable {
private int idMunicipio;
private Estado estado;
private String nombre;
public Municipio() {
}
public Municipio(int idMunicipio, Estado estado, String nombre) {
this.idMunicipio = idMunicipio;
this.estado = estado;
this.nombre = nombre;
}
public int getIdMunicipio() {
return this.idMunicipio;
}
public void setIdMunicipio(int idMunicipio) {
this.idMunicipio = idMunicipio;
}
public Estado getEstado() {
return this.estado;
}
public void setEstado(Estado estado) {
this.estado = estado;
}
public String getNombre() {
return this.nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
}
| true
|
5a5f474e70c093b516968d2c7090d067d6794f55
|
Java
|
flywind2/joeis
|
/src/irvine/oeis/a233/A233428.java
|
UTF-8
| 665
| 2.421875
| 2
|
[] |
no_license
|
package irvine.oeis.a233;
// Generated by gen_pattern.pl - DO NOT EDIT here!
import irvine.oeis.GeneratingFunctionSequence;
/**
* A233428 Number of tilings of a <code>3 X 5n</code> rectangle with <code>3n</code> pentominoes of any shape.
* @author Georg Fischer
*/
public class A233428 extends GeneratingFunctionSequence {
/** Construct the sequence. */
public A233428() {
super(0, new long[] {-1, 116, -2754, 28828, -160178, 509733, -963854, 1114401, -801386,
358357, -97595, 15483, -1335, 58, -1},
new long[] {-1, 172, -4716, 56595, -364164, 1353076, -3014276, 4180766, -3711813,
2129818, -781787, 178168, -24000, 1780, -67, 1});
}
}
| true
|
ee3a5197c7f643b4eaca44912a754615ab4910e7
|
Java
|
lucky7886/Code9
|
/Programs/basics/src/basics/RecursionExample.java
|
UTF-8
| 499
| 3.78125
| 4
|
[] |
no_license
|
package basics;
import java.io.*;
public class RecursionExample {
public static void main(String[] args)throws Exception {
BufferedReader m = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a number: ");
int x = Integer.parseInt(m.readLine());
System.out.printf("The factorial of the number is: %d",fact(x));
}
public static int fact(int n)
{
if(n==1)
return 1;
else
{
System.out.printf("(%d-1) is passed:\n",n);
return n*fact(n-1);
}
}
}
| true
|
628840ada9b73348d6aac11fe5a2e656acd36e6f
|
Java
|
ashwith8790/hubbiproject
|
/src/main/java/com/hubster/model/GoalModel.java
|
UTF-8
| 665
| 2.140625
| 2
|
[] |
no_license
|
package com.hubster.model;
import java.util.List;
public class GoalModel {
private List<GoalModel> goalModel;
private int cgoal_id;
public int getCgoal_id() {
return cgoal_id;
}
public void setCgoal_id(int cgoal_id) {
this.cgoal_id = cgoal_id;
}
public List<GoalModel> getGoalModel() {
return goalModel;
}
public void setGoalModel(List<GoalModel> goalModel) {
this.goalModel = goalModel;
}
public String getGoal_group() {
return goal_group;
}
public void setGoal_group(String goal_group) {
this.goal_group = goal_group;
}
@Override
public String toString() {
return "" + goal_group + "";
}
private String goal_group;
}
| true
|
6e439d2230f61b3fd9f85384c8a7489e121ca508
|
Java
|
mwbuda/sabrasInterviewExamples
|
/interviewExample/src/sabras/example/account/AccountUtility.java
|
UTF-8
| 3,843
| 2.671875
| 3
|
[] |
no_license
|
package sabras.example.account;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
public class AccountUtility {
private AccountDao accountDao ;
public Collection<Account> getAccounts(Collection<String> categories) {
Set<String> uniqCats = new HashSet<String>(categories) ;
Collection<DbAccount> dbs = this.accountDao.getAccountsByCategory(uniqCats) ;
Collection<Account> results = new LinkedList<Account>() ;
for (DbAccount db : dbs) {
Account web = new Account() ;
this.doCopy(db, web);
results.add(web) ;
}
return results ;
}
public Collection<Account> processX(ArrayList<Account> accounts)
throws Throwable {
Collection<Account> notProcessedAccounts = new LinkedList<Account>() ;
Collection<Account> processedAccounts = new LinkedList<Account>() ;
boolean foundFirst = false ;
for ( int i = 0 ; i < accounts.size() ; i++) {
Account account = accounts.get(i) ;
if (
(account.getStatus() != null)
&&
(account.getStatus() != "A" || account.getStatus() != "B" || account.getStatus() != "C")
&&
!account.getHasBeenXProcessed()
) {
if (!foundFirst) {
account.addFunds(200);
foundFirst = true ;
}
account.setHasBeenXProcessed(true);
processedAccounts.add(account) ;
}
else {
account.setHandled(false);
notProcessedAccounts.add(account) ;
}
}
this.save(processedAccounts) ;
Collection<Account> results = new ArrayList<Account>() ;
results.addAll(processedAccounts) ;
results.addAll(notProcessedAccounts) ;
return results ;
}
public Collection<Account> save(Account... accounts)
throws Throwable {
return this.save(Arrays.asList(accounts)) ;
}
public Collection<Account> save(Collection<Account> accounts)
throws Throwable {
Date now = new Date() ;
Set<String> categories = new HashSet<String>() ;
for (Account account : accounts) categories.add(account.getId()) ;
Collection<DbAccount> dbAccts = this.accountDao.getAccountsByCategory(categories) ;
Collection<DbAccount> saveTheseDbAccts = new LinkedList<DbAccount>() ;
Map<String,DbAccount> seenCache = new HashMap<String,DbAccount>() ;
Iterator<DbAccount> daosIter = dbAccts.iterator() ;
for (Account web : accounts) {
String id = web.getId() ;
DbAccount db = null ;
if (seenCache.containsKey(id)) db = seenCache.get(id) ;
if (db == null) while (daosIter.hasNext()) {
DbAccount cdao = daosIter.next() ;
String cdaoId = cdao.getId() ;
seenCache.put(cdaoId, cdao) ;
if (!cdaoId.equals(id)) continue ;
db = cdao ;
}
if (db == null) db = new DbAccount() ;
web.setUpdateDate(now);
this.doCopy(web, db);
web.setHandled(true);
saveTheseDbAccts.add(db) ;
}
this.accountDao.saveAccounts(saveTheseDbAccts);
return accounts ;
}
private void doCopy(Account web, DbAccount dao) {
dao.setId(web.getId());
dao.setCategory(web.getCategory());
dao.setStatus(web.getStatus());
int namespaceIndex = web.getAccountName().indexOf(' ') ;
dao.setAccountHolderFirstName(web.getAccountName().substring(0, namespaceIndex));
dao.setAccountHolderLastName(web.getAccountName().substring(namespaceIndex + 1));
dao.setFunds(web.getFunds());
dao.setHasBeenXd(web.getHasBeenXProcessed());
}
private void doCopy(DbAccount dao, Account web) {
web.setId(dao.getId());
web.setCategory(dao.getCategory());
web.setStatus(dao.getStatus());
web.setAccountName(
dao.getAccountHolderFirstName() + " " + dao.getAccountHolderLastName()
);
web.setFunds(dao.getFunds());
web.setHasBeenXProcessed(dao.getHasBeenXd());
}
}
| true
|
dfad0f999b8ccecba6960ebbb854043330215c7c
|
Java
|
huyho1012/HahaloloScript
|
/src/main/Project/Newsfeed/Common/UpdateInfo/FirstUpdatePopUpUI.java
|
UTF-8
| 1,485
| 1.703125
| 2
|
[] |
no_license
|
package Newsfeed.Common.UpdateInfo;
public class FirstUpdatePopUpUI {
public static final String FORM_UPDATE_INFO = "//form[@class ='form-verify-account-info']";
public static final String DATE_SELECTED_DROPDOWN = "//input[@placeholder ='%s']";
public static final String DATE_SELECTED_ITEM = "//input[@placeholder ='%s']/parent::div/following-sibling::div//div[@class='option']";
public static final String GENDER_OPTION = "//input[@id = '%s']/following-sibling::label";
public static final String COUNTRY_DROPDOWN = "//select[@id ='select-country']";
public static final String COUNTRY_ITEM = "//input[@id = 'select-country-selectized']/parent::div/following-sibling::div//div[@class= 'option']";
public static final String ERROR_MESSAGE_VALIDATION_OF_DATE = "//input[@placeholder ='%s']/ancestor::div[contains(@class,'selectize-control')]/following-sibling::*[contains(@class,'invalid-feedback')]";
public static final String ERROR_MESSAGE_VALIDATION_COUNTRY = "//select[@id ='select-country']/following-sibling::div[contains(@class,'invalid-feedback')]";
public static final String BUTTON_UPDATE ="//div[@id='modal-addition-user-info']//button[contains(text(),'Cập nhật')]";
public static final String BUTTON_CANCEL ="//div[@id='modal-addition-user-info']//button[contains(text(),'Bỏ qua')]";
public static final String ERROR_MESSAGE_OF_BIRTHDAY ="//div[@id = 'day']/following-sibling::*[contains(@class,'invalid-feedback')]";
}
| true
|
a18d2e05cf9bb860a09d82cc0c20e2d54d0cfba9
|
Java
|
faygao52/FITII
|
/BoardManagementApp/MCUmanager/src/com/FSL/mcuTracker/EditInfo.java
|
UTF-8
| 9,332
| 1.8125
| 2
|
[] |
no_license
|
package com.FSL.mcuTracker;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import com.FSL.local.database.DBOpenHelper;
import com.FSL.local.database.DataBaseManager;
import com.FSL.mcuTracker.UploadUtil.OnUploadProcessListener;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class EditInfo extends ActionBarActivity implements
OnUploadProcessListener {
private final String TAG = "EditInfo";
TextView mTvBn;
EditText mEtMcob, mEtBr, mEtSr, mEtDes, mEtPic, mEtBn;
ImageView mImageView;
Button mBtnConfirm, mBtnUpload;
private Bundle bundle;
private Intent intent;
private String picPath;
private Uri photoUri;
private Boolean uploadPhoto = false;
private Boolean Online;
private String addr;
EditTask eTask = new EditTask();
String path = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
addr= prefs.getString("ip","http://10.192.244.114:8080/");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_info);
mEtBn = (EditText) findViewById(R.id.et_edit_bn);
mEtMcob = (EditText) findViewById(R.id.et_edit_mcob);
mEtBr = (EditText) findViewById(R.id.et_edit_br);
mEtSr = (EditText) findViewById(R.id.et_edit_sr);
mEtDes = (EditText) findViewById(R.id.et_edit_dcp);
mImageView = (ImageView) findViewById(R.id.iv_edit_pic);
intent = this.getIntent();
Online = intent.getBooleanExtra("Online", false);
Log.e(TAG,"On Create Online?"+Online);
mEtBn.setText(intent.getStringExtra("board_number"));
bundle = intent.getExtras();
Log.d(TAG,"size: "+bundle.size());
if (bundle.size()>4) {
mEtBn.setFocusable(false);
mEtBn.setFocusableInTouchMode(false);
if(bundle.getString("BoardNumber").equals("no record"))
mEtBn.setText(bundle.getString("ID"));
else
mEtBn.setText(bundle.getString("BoardNumber"));
mEtMcob.setText(bundle.getString("Master chip on board"));
mEtBr.setText(bundle.getString("BoardRev"));
mEtSr.setText(bundle.getString("SchematicRev"));
mEtDes.setText(bundle.getString("description"));
path = bundle.getString("Pic");
}
mBtnUpload = (Button) findViewById(R.id.btn_edit_upload);
mBtnConfirm = (Button) findViewById(R.id.btn_edit_submit);
if(!Online)
mBtnUpload.setVisibility(View.GONE);
this.getContentResolver();
mBtnConfirm.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG,"Online Mode:"+Online);
if(Online){
if (uploadPhoto)
toUploadFile();
else
eTask.execute();
}else
localStore();
}
});
mBtnUpload.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String SDState = Environment.getExternalStorageState();
if (SDState.equals(Environment.MEDIA_MOUNTED)) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// "android.media.action.IMAGE_CAPTURE"
ContentValues values = new ContentValues();
photoUri = EditInfo.this.getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
photoUri);
startActivityForResult(intent, 1);
uploadPhoto = true;
} else {
Toast.makeText(EditInfo.this, "take photo and upload",
Toast.LENGTH_LONG).show();
}
}
});
}
private void localStore() {
DBOpenHelper dbHelper = DataBaseManager.getInstance().getHelper();
SQLiteDatabase db = DataBaseManager.getInstance().openDatabase();
Boolean exist = dbHelper.isExist(db, mEtBn.getText().toString());
if(!exist)
dbHelper.insert(db,mEtBn.getText().toString(),mEtDes.getText().toString(),mEtMcob.getText().toString(),mEtBr.getText().toString(),mEtSr.getText().toString());
DataBaseManager.getInstance().closeDatabase();
intent = new Intent();
intent.setClass(EditInfo.this, IndexActivity.class);
intent.putExtra("Online", Online);
intent.putExtra("Local", true);
startActivity(intent);
EditInfo.this.finish();
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
String result = (String) msg.obj;
eTask.execute(result);
break;
default:
break;
}
super.handleMessage(msg);
}
};
private String toUploadFile() {
String fileKey = "pic";
UploadUtil uploadUtil = UploadUtil.getInstance();
;
uploadUtil.setOnUploadProcessListener(this);
Map<String, String> params = new HashMap<String, String>();
params.put("orderId", "11111");
String result = uploadUtil.uploadFile(picPath, fileKey,
addr+"FSL_WebServer/Pic", params);
return result;
}
private void ParsePhoto(int requestCode, Intent data) {
String[] pojo = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(photoUri, pojo, null, null, null);
if (cursor != null) {
int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
cursor.moveToFirst();
picPath = cursor.getString(columnIndex);
cursor.close();
}
Log.i(TAG, "imagePath = " + picPath);
if (picPath != null
&& (picPath.endsWith(".png") || picPath.endsWith(".PNG")
|| picPath.endsWith(".jpg") || picPath.endsWith(".JPG"))) {
Bitmap bm = BitmapFactory.decodeFile(picPath);
mImageView.setImageBitmap(bm);
} else {
Toast.makeText(this, "Wrong Path", Toast.LENGTH_LONG).show();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
ParsePhoto(requestCode, data);
}
super.onActivityResult(requestCode, resultCode, data);
}
private class EditTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
String result = "";
HttpClient hc = new DefaultHttpClient();
JSONObject jsonObj;
try {
HttpPost hp = new HttpPost(addr+"FSL_WebServer/MCUs");
jsonObj = buildUploadJson();
if (params.length == 1) {
jsonObj.put("Pic", params[0]);
Log.d(TAG, "PIC " + params[0]);
} else {
jsonObj.put("Pic", path);
}
Log.e(TAG,jsonObj.toString());
hp.setEntity(new StringEntity(jsonObj.toString()));
HttpResponse response = hc.execute(hp);
if (response.getStatusLine().getStatusCode() == 200) {
String mStrResult = EntityUtils.toString(response
.getEntity());
Log.d(TAG, mStrResult);
result = new JSONObject(mStrResult).getString("ID");
} else {
Log.e(TAG, "Connection Failed!"+response.getStatusLine().getStatusCode());
}
} catch (JSONException | IOException e) {
e.printStackTrace();
}
return result;
}
private JSONObject buildUploadJson() throws JSONException {
JSONObject jsonObj = new JSONObject();
if (bundle.size()<4) {
// add new by click button
jsonObj.put("Mode", "add");
jsonObj.put("BoardNumber", mEtBn.getText().toString());
}else if (bundle.getString("BoardNumber").equals("no record")) {
// add new by scan
jsonObj.put("Mode", "add");
jsonObj.put("BoardNumber", bundle.getString("ID"));
} else {
// modify info
jsonObj.put("ID", bundle.getString("ID"));
jsonObj.put("Mode", "modify");
jsonObj.put("BoardNumber", mEtBn.getText().toString());
}
User user = (User) getApplication();
String CoreID = user.getId();
jsonObj.put("Editor", CoreID);
jsonObj.put("Master chip on board", mEtMcob.getText().toString());
jsonObj.put("BoardRev", mEtBr.getText().toString());
jsonObj.put("SchematicRev", mEtSr.getText().toString());
jsonObj.put("description", mEtDes.getText().toString());
return jsonObj;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Bundle bundle = new Bundle();
Intent intent = new Intent();
intent.setClass(EditInfo.this, UnitManager.class);
bundle.putString("UID", result);
intent.putExtras(bundle);
startActivity(intent);
EditInfo.this.finish();
}
}
@Override
public void onUploadDone(int responseCode, String message) {
Message msg = Message.obtain();
msg.what = 1;
msg.obj = message;
handler.sendMessage(msg);
}
}
| true
|
f0e77fa5b68b708d782cfa8de958007392cb9b59
|
Java
|
iagoaraujo/si1-lab2-hackfest
|
/app/models/Hackfest.java
|
UTF-8
| 2,290
| 2.640625
| 3
|
[] |
no_license
|
package models;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity(name="hackfest")
public class Hackfest implements Comparable<Hackfest>{
@Id
@SequenceGenerator(name = "HACKFEST_SEQUENCE", sequenceName = "HACKFEST_SEQUENCE", allocationSize = 1, initialValue = 0)
@GeneratedValue(strategy = GenerationType.TABLE)
private Long id;
@Column
private String descricao;
@Column
private String nome;
@Temporal(value = TemporalType.DATE)
private Date data;
@OneToMany(cascade=CascadeType.ALL)
private List<Usuario> usuarios = new ArrayList<Usuario>();
@ElementCollection
private List<String> temas = new ArrayList<String>();
public Hackfest() {
}
public Hackfest(String nome, String descricao, Date data){
this.nome = nome;
this.descricao = descricao;
this.data = data;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Date getData() {
return data;
}
public void setData(Date data) {
this.data = data;
}
public Long getId() {
return id;
}
public void addUsuario(Usuario usuario){
usuarios.add(usuario);
}
public boolean hasUsuario(Usuario usuario){
return usuarios.contains(usuario);
}
public List<Usuario> getUsuarios(){
return usuarios;
}
@Override
public int compareTo(Hackfest hackfest) {
if(hackfest.getQtdInscritos()<getQtdInscritos()){
return 1;
}
else if(hackfest.getQtdInscritos()>getQtdInscritos()){
return -1;
}
return nome.compareToIgnoreCase(hackfest.getNome());
}
public int getQtdInscritos(){
return usuarios.size();
}
public List<String> getTemas() {
return temas;
}
public void addTema(String tema){
temas.add(tema);
}
}
| true
|
282d70362a9088b55b74a2ded39a4d4f46d109ed
|
Java
|
jhonmario14/clinica-back
|
/src/java/ModeloDAO/AnimalDAO.java
|
UTF-8
| 5,101
| 2.453125
| 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 ModeloDAO;
import Configuracion.conexion;
import InterfaceCRUD.CRUD;
import ModeloDTO.AnimalDTO;
import Configuracion.conexion;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Acer
*/
public class AnimalDAO implements CRUD<AnimalDTO>{
private static final String SQL_INSERT= "INSERT INTO public.\"Animales\"(num_historia, nombre, tamanio, especie, tipo_paciente, sexo, \"FK_num_ident_cliente\") VALUES (?, ?, ?, ?, ?, ?, ?);";
private static final String SQL_DELETE= "DELETE FROM Animales WHERE num_historia = ?";
private static final String SQL_UPDATE= "UPDATE public.\"Animales\" SET nombre=?, tamanio=?, especie=?, tipo_paciente=?, sexo=?, \"FK_num_ident_cliente\"=? WHERE num_historia =?;";
private static final String SQL_READ= "SELECT * FROM public.\"Animales\" WHERE num_historia = ?;";
private static final String SQL_READ_ALL= "SELECT * FROM public.\"Animales\";";
private static final conexion cnn = conexion.saberEstado();
@Override
public boolean insert(AnimalDTO obj) {
PreparedStatement ps = null;
try {
ps = cnn.getCnn().prepareStatement(SQL_INSERT);
ps.setString(1, obj.getNum_historia());
ps.setString(2, obj.getNombre());
ps.setString(3, obj.getTamanio());
ps.setString(4, obj.getEspecie());
ps.setString(5, obj.getTipo_paciente());
ps.setString(6, obj.getSexo());
ps.setString(7, obj.getFK_num_ident_cliente());
if(ps.executeUpdate() > 0){
return true;
}
} catch (SQLException ex) {
Logger.getLogger(AnimalDAO.class.getName()).log(Level.SEVERE, null, ex);
}finally{
cnn.cerrarConexion();//singleton
}
return false;
}
@Override
public boolean delete(Object key) {
PreparedStatement ps = null;
try {
ps = cnn.getCnn().prepareStatement(SQL_DELETE);
ps.setString(1, key.toString());
if(ps.executeUpdate() > 0){
return true;
}
} catch (SQLException ex) {
Logger.getLogger(AnimalDAO.class.getName()).log(Level.SEVERE, null, ex);
}finally{
cnn.cerrarConexion();//singleton
}
return false;
}
@Override
public boolean update(AnimalDTO obj) {
PreparedStatement ps = null;
try {
ps = cnn.getCnn().prepareStatement(SQL_UPDATE);
ps.setString(1, obj.getNombre());
ps.setString(2, obj.getTamanio());
ps.setString(3, obj.getEspecie());
ps.setString(4, obj.getTipo_paciente());
ps.setString(5, obj.getSexo());
ps.setString(6, obj.getFK_num_ident_cliente());
ps.setString(7, obj.getNum_historia());
if(ps.executeUpdate() > 0){
return true;
}
} catch (SQLException ex) {
Logger.getLogger(AnimalDAO.class.getName()).log(Level.SEVERE, null, ex);
}finally{
cnn.cerrarConexion();
}
return false;
}
@Override
public AnimalDTO read(Object key) {
AnimalDTO obj = null;
PreparedStatement ps = null;
ResultSet res = null;
try {
ps = cnn.getCnn().prepareStatement(SQL_READ);
ps.setString(1, key.toString());
res = ps.executeQuery();
while (res.next()) {
obj = new AnimalDTO(res.getString(1), res.getString(2), res.getString(3), res.getString(4), res.getString(5), res.getString(6), res.getString(7));
}
return obj;
} catch (SQLException ex) {
Logger.getLogger(AnimalDAO.class.getName()).log(Level.SEVERE, null, ex);
}finally{
cnn.cerrarConexion();
}
return obj;
}
@Override
public List<AnimalDTO> readAll() {
PreparedStatement ps = null;
ResultSet res = null;
ArrayList<AnimalDTO> animales = new ArrayList();
try {
ps = cnn.getCnn().prepareStatement(SQL_READ_ALL);
res = ps.executeQuery();
while(res.next()){
animales.add(new AnimalDTO(res.getString(1), res.getString(2), res.getString(3), res.getString(4), res.getString(5), res.getString(6), res.getString(7)));
}
} catch (SQLException ex) {
Logger.getLogger(AnimalDAO.class.getName()).log(Level.SEVERE, null, ex);
}finally{
cnn.cerrarConexion();
}
return animales;
}
}
| true
|
d18525d9066f2cbb17eac3b6dc9c37f7bb4a1c79
|
Java
|
ONSdigital/rm-case-service
|
/src/test/java/uk/gov/ons/ctp/response/casesvc/message/CaseReceiptReceiverTest.java
|
UTF-8
| 6,091
| 1.820313
| 2
|
[
"MIT",
"LicenseRef-scancode-proprietary-license"
] |
permissive
|
package uk.gov.ons.ctp.response.casesvc.message;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static uk.gov.ons.ctp.response.casesvc.representation.CategoryDTO.CategoryName.OFFLINE_RESPONSE_PROCESSED;
import static uk.gov.ons.ctp.response.casesvc.utility.Constants.QUESTIONNAIRE_RESPONSE;
import static uk.gov.ons.ctp.response.casesvc.utility.Constants.SYSTEM;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.xml.datatype.DatatypeConfigurationException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import uk.gov.ons.ctp.response.casesvc.domain.model.Case;
import uk.gov.ons.ctp.response.casesvc.domain.model.CaseEvent;
import uk.gov.ons.ctp.response.casesvc.message.feedback.CaseReceipt;
import uk.gov.ons.ctp.response.casesvc.message.feedback.InboundChannel;
import uk.gov.ons.ctp.response.casesvc.representation.CategoryDTO;
import uk.gov.ons.ctp.response.casesvc.service.CaseService;
import uk.gov.ons.ctp.response.lib.common.error.CTPException;
import uk.gov.ons.ctp.response.lib.common.time.DateTimeUtil;
/** To unit test CaseReceiptReceiver */
@RunWith(MockitoJUnitRunner.class)
public class CaseReceiptReceiverTest {
private static final String LINKED_CASE_ID = "fa622b71-f158-4d51-82dd-c3417e31e32c";
private static final String UNLINKED_CASE_ID = "fa622b71-f158-4d51-82dd-c3417e31e32d";
private static final Integer LINKED_CASE_PK = 1;
private static final String LINKED_CASE_REF = "123";
private static final String UNLINKED_CASE_REF = "456";
private static final String LINKED_PARTY_ID = "fa622b71-f158-4d51-82dd-c3417e31e32e";
private static final long CURRENT_TIME_IN_MILLISECONDS = 1594646202887L;
@InjectMocks private CaseReceiptReceiver caseReceiptReceiver;
@Mock private CaseService caseService;
@Mock(name = "dateTimeUtil")
private DateTimeUtil dateTimeUtil;
@Before
public void setup() {
Mockito.when(dateTimeUtil.getNowUTC()).thenReturn(new Timestamp(CURRENT_TIME_IN_MILLISECONDS));
}
/**
* ProcessLinkedOnlineCaseReceipt
*
* @throws DatatypeConfigurationException if giveMeCalendarForNow fails
* @throws CTPException if case state transition errors
*/
@Test
public void testProcessLinkedOnlineCaseReceipt()
throws CTPException, DatatypeConfigurationException {
Case existingCase = new Case();
existingCase.setCasePK(LINKED_CASE_PK);
existingCase.setPartyId(UUID.fromString(LINKED_PARTY_ID));
Mockito.when(caseService.findCaseById(UUID.fromString(LINKED_CASE_ID)))
.thenReturn(existingCase);
caseReceiptReceiver.process(
buildCaseReceipt(LINKED_CASE_ID, LINKED_CASE_REF, InboundChannel.ONLINE, LINKED_PARTY_ID));
Map<String, String> metadata = new HashMap<>();
metadata.put("partyId", LINKED_PARTY_ID);
verify(caseService, times(1))
.createCaseEvent(
eq(buildCaseEvent(LINKED_CASE_PK, OFFLINE_RESPONSE_PROCESSED, metadata)),
eq(new Timestamp(CURRENT_TIME_IN_MILLISECONDS)));
}
/**
* ProcessLinkedOfflineCaseReceipt
*
* @throws DatatypeConfigurationException if giveMeCalendarForNow fails
* @throws CTPException if case state transition errors
*/
@Test
public void testProcessLinkedOfflineCaseReceipt()
throws CTPException, DatatypeConfigurationException {
Case existingCase = new Case();
existingCase.setCasePK(LINKED_CASE_PK);
existingCase.setPartyId(UUID.fromString(LINKED_PARTY_ID));
Mockito.when(caseService.findCaseById(UUID.fromString(LINKED_CASE_ID)))
.thenReturn(existingCase);
caseReceiptReceiver.process(
buildCaseReceipt(LINKED_CASE_ID, null, InboundChannel.OFFLINE, LINKED_PARTY_ID));
Map<String, String> metadata = new HashMap<>();
metadata.put("partyId", LINKED_PARTY_ID);
verify(caseService, times(1))
.createCaseEvent(
eq(buildCaseEvent(LINKED_CASE_PK, OFFLINE_RESPONSE_PROCESSED, metadata)),
eq(new Timestamp(CURRENT_TIME_IN_MILLISECONDS)));
}
/**
* ProcessUnlinkedOnlineCaseReceipt
*
* @throws DatatypeConfigurationException if giveMeCalendarForNow fails
* @throws CTPException if case state transition errors
*/
@Test
public void testProcessUnlinkedOnlineCaseReceipt()
throws CTPException, DatatypeConfigurationException {
CaseReceipt caseReceipt =
buildCaseReceipt(
UNLINKED_CASE_ID, UNLINKED_CASE_REF, InboundChannel.ONLINE, LINKED_PARTY_ID);
caseReceiptReceiver.process(caseReceipt);
verify(caseService, times(0)).createCaseEvent(any(CaseEvent.class));
}
/**
* @param caseId the caseId
* @param caseRef the caseRef
* @param inboundChannel the inboundChannel
* @return the CaseReceipt
* @throws DatatypeConfigurationException datatype configuration exception thrown
*/
private CaseReceipt buildCaseReceipt(
String caseId, String caseRef, InboundChannel inboundChannel, String partyId)
throws DatatypeConfigurationException {
CaseReceipt caseReceipt = new CaseReceipt();
caseReceipt.setCaseId(caseId);
caseReceipt.setCaseRef(caseRef);
caseReceipt.setInboundChannel(inboundChannel);
caseReceipt.setPartyId(partyId);
return caseReceipt;
}
/**
* Build a CaseEvent
*
* @param casePK the Case Primary Key
* @param categoryName the name of the category
* @return the CaseEvent
*/
private CaseEvent buildCaseEvent(
int casePK, CategoryDTO.CategoryName categoryName, Map<String, String> metadata) {
CaseEvent caseEvent = new CaseEvent();
caseEvent.setCaseFK(casePK);
caseEvent.setCategory(categoryName);
caseEvent.setCreatedBy(SYSTEM);
caseEvent.setDescription(QUESTIONNAIRE_RESPONSE);
caseEvent.setMetadata(metadata);
return caseEvent;
}
}
| true
|
6cec7fb036c6f53eb65ffd54e7e9b1208d90dea7
|
Java
|
jineshshah3001/PicShare
|
/src/main/java/com/example/demo/service/UploadToS3.java
|
UTF-8
| 2,244
| 2.375
| 2
|
[] |
no_license
|
package com.example.demo.service;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.example.demo.entity.User;
@Service
public class UploadToS3 {
public String upload(String name,InputStream fs) {
String acessKey = System.getenv("Access_key");
String secret = System.getenv("secret");
BasicAWSCredentials cred = new BasicAWSCredentials(acessKey,secret);
String audioSrc;
AmazonS3 s3client = AmazonS3ClientBuilder
.standard()
.withCredentials(new AWSStaticCredentialsProvider(cred) )
.withRegion(Regions.US_EAST_2)
.build();
PutObjectRequest putReq = new PutObjectRequest("assignment2se",
name, fs, new ObjectMetadata())
.withCannedAcl(CannedAccessControlList.PublicRead);
s3client.putObject(putReq);
audioSrc ="http://" + "assignment2se" + ".s3.amazonaws.com/"+name;
return audioSrc;
}
public String uploadphoto(String name,InputStream fs) {
String acessKey = System.getenv("Access_key");
String secret = System.getenv("secret");
BasicAWSCredentials cred = new BasicAWSCredentials(acessKey,secret);
String photoSrc;
AmazonS3 s3client = AmazonS3ClientBuilder
.standard()
.withCredentials(new AWSStaticCredentialsProvider(cred) )
.withRegion(Regions.US_EAST_2)
.build();
PutObjectRequest putReq = new PutObjectRequest("assignment2se",
name, fs, new ObjectMetadata())
.withCannedAcl(CannedAccessControlList.PublicRead);
s3client.putObject(putReq);
photoSrc ="http://" + "assignment2se" + ".s3.amazonaws.com/"+name;
return photoSrc;
}
}
| true
|
3c80c96a0cec7539dafcac325a5e9ec20882e9aa
|
Java
|
prendConnor/FitnessApp
|
/app/src/test/java/com/example/cse110_project/HomeScreenUnitTest.java
|
UTF-8
| 1,956
| 2.171875
| 2
|
[] |
no_license
|
package com.example.cse110_project;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.test.core.app.ActivityScenario;
import androidx.test.ext.junit.rules.ActivityScenarioRule;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@RunWith(RobolectricTestRunner.class)
public class HomeScreenUnitTest {
@Rule
public ActivityScenarioRule<HomeScreen> scenarioRule = new ActivityScenarioRule<>(HomeScreen.class);
private ActivityScenario<HomeScreen> scenario;
private Button getStartedBtn;
private EditText firstName;
private EditText lastName;
private EditText heightFt;
private EditText heightInch;
private TextView pageTitle;
private TextView stepCount;
private TextView distanceCount;
private TextView estimatedDistanceCount;
@Before
public void setup() {
scenario = scenarioRule.getScenario();
}
private void init(HomeScreen homeScreen) {
getStartedBtn = homeScreen.findViewById(R.id.getStartedBtn);
pageTitle = homeScreen.findViewById(R.id.homeTitle);
stepCount = homeScreen.findViewById(R.id.homeDailyStepsCount);
distanceCount = homeScreen.findViewById(R.id.homeDailyDistanceCount);
estimatedDistanceCount = homeScreen.findViewById(R.id.homeDailyEstimateCount);
}
@Test
public void testComponentExists() {
scenario.onActivity(homeScreen -> {
init(homeScreen);
assertEquals(pageTitle.getText().toString(), "Home");
assertNotNull(stepCount.getText().toString());
assertNotNull(distanceCount.getText().toString());
assertNotNull(estimatedDistanceCount.getText().toString());
});
}
}
| true
|
a5531520b38607aea9eac1a3d8417649921b0d5a
|
Java
|
thierrydoucet/Mower
|
/Mower/src/test/java/fr/xebia/entretientechnique/thierrydoucet/mower/test/builder/InputStreamGardenBuilderTest.java
|
UTF-8
| 2,231
| 2.59375
| 3
|
[] |
no_license
|
package fr.xebia.entretientechnique.thierrydoucet.mower.test.builder;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.List;
import org.junit.Test;
import fr.xebia.entretientechnique.thierrydoucet.mower.bean.AutomaticMower;
import fr.xebia.entretientechnique.thierrydoucet.mower.bean.Lawn;
import fr.xebia.entretientechnique.thierrydoucet.mower.builder.GardenBuilder;
import fr.xebia.entretientechnique.thierrydoucet.mower.builder.InputStreamGardenBuilder;
import fr.xebia.entretientechnique.thierrydoucet.mower.command.AMowerCommand;
import fr.xebia.entretientechnique.thierrydoucet.mower.command.DMowerCommand;
import fr.xebia.entretientechnique.thierrydoucet.mower.command.GMowerCommand;
import fr.xebia.entretientechnique.thierrydoucet.mower.command.MowerCommand;
/**
* Test unitaire de la classe {@link InputStreamGardenBuilder}
*
* @author Thierry Doucet
*/
public class InputStreamGardenBuilderTest {
private final static String TEST_DATA = "5 10\n" + //
"1 2 E\n" + //
"GAD\n";
/**
* Test de la méthode {@link InputStreamGardenBuilder#buildGarden()}
*/
@Test
public void buildGardern() throws UnsupportedEncodingException {
GardenBuilder builder = new InputStreamGardenBuilder(
new ByteArrayInputStream(TEST_DATA.getBytes("ISO-8859-1")), Charset.forName("ISO-8859-1"));
builder.buildGarden();
Lawn lawn = builder.getLawn();
assertNotNull(lawn);
assertEquals(5, lawn.getDimension().width);
assertEquals(10, lawn.getDimension().height);
assertEquals(1, builder.getMowers().size());
AutomaticMower mower = builder.getMowers().iterator().next();
assertEquals("1, 2, E", mower.getPosition().toString());
assertEquals(3, builder.getCommands(mower).size());
List<MowerCommand> commands = builder.getCommands(mower);
assertThat(commands.get(0), instanceOf(GMowerCommand.class));
assertThat(commands.get(1), instanceOf(AMowerCommand.class));
assertThat(commands.get(2), instanceOf(DMowerCommand.class));
}
}
| true
|
9fa386d644bd145f82c813b77618805ca0914bd1
|
Java
|
ghuntley/TraceTogether_1.6.1.apk
|
/jadx/sources/o/C2707.java
|
UTF-8
| 6,371
| 2.28125
| 2
|
[] |
no_license
|
package o;
import java.io.FilterInputStream;
import java.io.InputStream;
/* renamed from: o.ҝІ reason: contains not printable characters */
public final class C2707 extends FilterInputStream {
/* renamed from: ı reason: contains not printable characters */
private final int f12520;
/* renamed from: Ɩ reason: contains not printable characters */
private int f12521;
/* renamed from: ǃ reason: contains not printable characters */
private C2708 f12522;
/* renamed from: ɩ reason: contains not printable characters */
private byte[] f12523;
/* renamed from: ɹ reason: contains not printable characters */
private int f12524;
/* renamed from: Ι reason: contains not printable characters */
private byte[] f12525;
/* renamed from: ι reason: contains not printable characters */
private byte[] f12526;
/* renamed from: І reason: contains not printable characters */
private int f12527;
/* renamed from: і reason: contains not printable characters */
private int[] f12528;
/* renamed from: Ӏ reason: contains not printable characters */
private int f12529 = Integer.MAX_VALUE;
public final boolean markSupported() {
return false;
}
public C2707(InputStream inputStream, int[] iArr, byte[] bArr, int i, boolean z, int i2) {
super(inputStream);
this.f12520 = Math.min(Math.max(i, 3), 16);
this.f12523 = new byte[8];
this.f12526 = new byte[8];
this.f12525 = new byte[8];
this.f12528 = new int[2];
this.f12527 = 8;
this.f12521 = 8;
this.f12524 = i2;
if (i2 == 2) {
System.arraycopy(bArr, 0, this.f12526, 0, 8);
}
this.f12522 = new C2708(iArr, this.f12520, true);
}
public final int read() {
m14402();
int i = this.f12527;
if (i >= this.f12521) {
return -1;
}
byte[] bArr = this.f12523;
this.f12527 = i + 1;
return bArr[i] & 255;
}
public final int read(byte[] bArr, int i, int i2) {
int i3 = i + i2;
int i4 = i;
while (i4 < i3) {
m14402();
int i5 = this.f12527;
if (i5 < this.f12521) {
byte[] bArr2 = this.f12523;
this.f12527 = i5 + 1;
bArr[i4] = bArr2[i5];
i4++;
} else if (i4 == i) {
return -1;
} else {
return i2 - (i3 - i4);
}
}
return i2;
}
public final long skip(long j) {
long j2 = 0;
while (j2 < j && read() != -1) {
j2++;
}
return j2;
}
public final int available() {
m14402();
return this.f12521 - this.f12527;
}
/* renamed from: Ι reason: contains not printable characters */
private void m14403() {
if (this.f12524 == 2) {
byte[] bArr = this.f12523;
System.arraycopy(bArr, 0, this.f12525, 0, bArr.length);
}
byte[] bArr2 = this.f12523;
C0416.m4707(((bArr2[0] << 24) & -16777216) + ((bArr2[1] << 16) & 16711680) + ((bArr2[2] << 8) & 65280) + (bArr2[3] & 255), (-16777216 & (bArr2[4] << 24)) + (16711680 & (bArr2[5] << 16)) + (65280 & (bArr2[6] << 8)) + (bArr2[7] & 255), false, this.f12520, this.f12522.f12532, this.f12522.f12531, this.f12528);
int[] iArr = this.f12528;
int i = iArr[0];
int i2 = iArr[1];
byte[] bArr3 = this.f12523;
bArr3[0] = (byte) (i >> 24);
bArr3[1] = (byte) (i >> 16);
bArr3[2] = (byte) (i >> 8);
bArr3[3] = (byte) i;
bArr3[4] = (byte) (i2 >> 24);
bArr3[5] = (byte) (i2 >> 16);
bArr3[6] = (byte) (i2 >> 8);
bArr3[7] = (byte) i2;
if (this.f12524 == 2) {
for (int i3 = 0; i3 < 8; i3++) {
byte[] bArr4 = this.f12523;
bArr4[i3] = (byte) (bArr4[i3] ^ this.f12526[i3]);
}
byte[] bArr5 = this.f12525;
System.arraycopy(bArr5, 0, this.f12526, 0, bArr5.length);
}
}
/* JADX WARNING: Removed duplicated region for block: B:13:0x0033 */
/* JADX WARNING: Removed duplicated region for block: B:17:0x004f */
/* renamed from: ɩ reason: contains not printable characters */
/* Code decompiled incorrectly, please refer to instructions dump. */
private int m14402() {
/*
r7 = this;
int r0 = r7.f12529
r1 = 2147483647(0x7fffffff, float:NaN)
if (r0 != r1) goto L_0x000f
java.io.InputStream r0 = r7.in
int r0 = r0.read()
r7.f12529 = r0
L_0x000f:
int r0 = r7.f12527
r1 = 8
if (r0 != r1) goto L_0x005b
byte[] r0 = r7.f12523
int r2 = r7.f12529
byte r3 = (byte) r2
r4 = 0
r0[r4] = r3
java.lang.String r0 = "unexpected block size"
if (r2 < 0) goto L_0x0055
r2 = 1
L_0x0022:
java.io.InputStream r3 = r7.in
byte[] r5 = r7.f12523
int r6 = 8 - r2
int r3 = r3.read(r5, r2, r6)
if (r3 <= 0) goto L_0x0031
int r2 = r2 + r3
if (r2 < r1) goto L_0x0022
L_0x0031:
if (r2 < r1) goto L_0x004f
r7.m14403()
java.io.InputStream r0 = r7.in
int r0 = r0.read()
r7.f12529 = r0
r7.f12527 = r4
int r0 = r7.f12529
if (r0 >= 0) goto L_0x004c
byte[] r0 = r7.f12523
r2 = 7
byte r0 = r0[r2]
r0 = r0 & 255(0xff, float:3.57E-43)
int r1 = r1 - r0
L_0x004c:
r7.f12521 = r1
goto L_0x005b
L_0x004f:
java.lang.IllegalStateException r1 = new java.lang.IllegalStateException
r1.<init>(r0)
throw r1
L_0x0055:
java.lang.IllegalStateException r1 = new java.lang.IllegalStateException
r1.<init>(r0)
throw r1
L_0x005b:
int r0 = r7.f12521
return r0
*/
throw new UnsupportedOperationException("Method not decompiled: o.C2707.m14402():int");
}
}
| true
|
f6667b13ced77f1dc0f7880557edec848a7bc09e
|
Java
|
mchackteam/obejscie
|
/src/main/java/net/jared/pr0xy/mc/status/NetHandlerStatusClient.java
|
UTF-8
| 3,661
| 1.914063
| 2
|
[] |
no_license
|
package net.jared.pr0xy.mc.status;
import java.util.ArrayList;
import java.util.UUID;
import net.jared.pr0xy.mc.play.INetHandler;
import net.jared.pr0xy.mc.server.Player;
import net.jared.pr0xy.mc.status.client.C00PacketServerQuery;
import net.jared.pr0xy.mc.status.client.C01PacketPing;
import net.jared.pr0xy.mc.status.server.S00PacketServerInfo;
import net.jared.pr0xy.mc.status.server.S01PacketPong;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.TextComponent;
public class NetHandlerStatusClient implements INetHandler
{
private Player handler;
public NetHandlerStatusClient(Player handler) {
this.handler = handler;
}
@Override
public int getState() {
return 2;
}
@SuppressWarnings("unused")
private void sendPing() {
S00PacketServerInfo.ServerStatusResponse res = new S00PacketServerInfo.ServerStatusResponse();
res.favicon = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAADAFBMVEU3bH4bQF1ifH9FdIBkf4ItaIFVe4JCc38SOlpTdX0nYnsqTGQhRF8mRl8+a3sYPlssYngUPVxce4E1a31Xd3wzanxOeIKljXswaHssZHobQ2AqZHwqYnovTmQtSmFOcn1AVGQ+cX9EWGc6bn8gQl00U2hTeYBFb3w4ansQRmdffYNPdX4tZ3uAfXh3dXJeaG5SYWs6VmgOOFkJNlgkXnaTgnUhW3Vzb21EXWseTGg2UGNZfYRLdoFZeH9deXxKcXw0aHopYHdnbnJZZGw6U2UiSGMyTGEVP14GOVtSe4JJdoBgeX1KYW4dUG0bSGOwmH9Qb3l5e3hxdHR9eXJscHJkaW0+WWoWSmgEM1g8b37JnnxBbnxKbHmahXaHfXQVQWFqgYJnfH+MgHePgXZJXWovUmcoSWILQWLn29/e1t7ou4rfroTOpoTEooK8nIGuknxac3owZXqhineCenNOXWgGQmhKWWYOPV60m4JieIBGc31oeXyainu2lHpweXolYXolT2nMrIrAm35mdHk+ZXgxWG0CPWL/8/bn4vH87PDpwZLUsYiokn2GgHtHZ3ZfbXI2W3AqV3Dy6fPt4+vm1dLNvbj/3Zb6z5bivpD7x473zovUpoK6l3yTh3t1fXtYZ3E+X3EoU2xra2tVYGcANGHZ1erk3ejy3tvi0tDZrYSdk4NTcXxfdHpYbXb//v/b0dbWyczgzMb/557ktIZ6g35ufXuMfXCCeW5+dG0AKlP25uj+6OC+v8nm0b/4voeBiYa9o4WKiH9RZHBgZWrMtajqyp6sopu9p5jxy5bWtZCUk47CqYuqnYdcfYXpt4KvkHPe2e3s4OTMw8jZxr+6trzbxLbdv6a7rKb/05K5n47etYulloNwgIDw0KyWoKzXuJ/y0JvtxZS2rIvuwoiUjoBPaXO5lnJlY17HxdD21r2mq7jkyrCsqKqhm5XItI/avo7Pytfgvp2EkJvLr5rTspn81phpeon/9aLWypl0h5UvXXfRpna/s6//8qj//KeggWASBg5AAAAMaElEQVRYw4zOQWqDQBTG8Ye2ilmUMGlkBgdkEBKpLkM30cYs0xuEbHoFt248Ye7U7zljVEpLf3nzMjD8QXrW1mqlk2SVPDz/T0bvSwerH63mNB/Ft35cmpJleT6f+3Pfa93bIlFa43tKTInFlEoSrTQfrYnasXTWa73WTCUKSktirJK1OKpVQCQPrsNYeq2gVS7ZTjb4jWSzlZBRg3iiBrKVpWy43QA502XGEE1pC1I2XCKdtdkCTTYbn6i1ELJtPrR4suU1Y8Zcr8YY/ANfrxZlPmXNQ55v8zwnygnwbAZhyOsnE+7NLawozBdeGGIX+ZhfdV3YxRSimdwspN2s/GRVxQMV3/iC7V/IH7ox3UM34HeI4xjLucQzVRHHRXGkChGM5emUpmlRVQVw4gRu89nN3Wl3stIBdxGOfb0Ef6nrYFffKeAuSiNWuI0Wr3BcuA9LiCOP80QieniNXlmNqcWH8IR4gzvPnMfjeSIQnud9fdNJxiwNA1EcDyHLLRlC0TGTpLHkAwimwfkobVwcekKun6BLoOdBQdJ2EFrsol0aHTo16VKSOXYRbPUTmEGCrnW0CIp3oUMXf9x73A2//4PjCYeFHco5EEKR4wAg/YcoRos0D1AA17Y+l1lt/fIyQaYkOQ47HH7LweyQaOxDzAJSCvlUGvtGTCn14ziiMY59fxHr2U+WBEFIJJymIsYsVFF4KYRAQjGhFDvC/rnR9n270TcaNm0z+IvCNJpV9If5/G2zXi+RijHhCTlEwVARISaQEigJfcNmkm17Xtj0aOhRL4QwxOLQda+nl0/V7H2abZJOic8WMTQ5hP1ywQSA1YtAQqaGYZPBGycA0On2XH3g+qvW3WRydPP7aMrFi2O+ImpJtWQt4HtjsaYIsDab1XYJLMsEw557NuhOpq3Rq1txD9a3n5tlIGuaajJfk+tqYGmWdvIt7wkBQgPUGdRYz6khBFCld/+8avc+xotqtzLUdeN09DW/Wk0jkdmdumapFkCynCSd4h8ACAL3/QAOhI5cULVwUKtwPo6EhA4ncFD6hKGAV6Cz2Ht1rVFMqqFNoXUpoJGPgbKylpaBqr+0qsy1FKuEhLTig6CasoGqANytjq2QTCVNg35Mnn6Ojo6gUbQpoUxXpI9qkIZnMGROJYy3TkiGpEiL2JbjmpprqVqZsm3A78DBfsGD5ODhlrIAg4ChgFcphldCVqRPzmJGSEgNT8JMjI9+hXidkZF5zPpc8cXG8oSE3unrvdXV09PTsN/WlKi7u6doaKZoadOz4ABNdZCOV01Xn59XSMbpeOzqvLzSlJS7p6eo2bGTibqHh4mSkrqH9tSuh4il0KWlpqaIx5WSaOjoqLDS1KiIvbOBAJBNkJBNdZFSKXV3vLr0iYlpummv6LzS0WjH0af8ld7s1ezGsWgfr+h58eDFxcnJy++LaaiCnYMtUji48dDr48kAkDlNoSmQUYUpVznw6cXQ1nLCTTmFVueovPaHxucvRTe2NbjT8B+J3rmPmZaWmc6bmpfQseZPqoOgq5rppcWaigChV62gdcGBTZFnkabd1qXhvnI4ZVKit6feza7K/2RT5re3dqi8v4nHIE5Ta5qaamzOxYiVt4XMyXW12L2l4OOKAJGAhZCgnmqgTWW/kt/Epoqpam20zMHtktfGksTHytfXxOzek5XHk7GV1NSwsaiUadXfifJ3TZCK4uS+sGiXapgACAL3/QCRhqTbLVFrkVcu3YjGlZNoaWm60aaSk6bf1oiSh4eTppKuh5Lz84imk7rRprppaZPExIcnWE2krbKX2q+wapbIAE2QoE+QrU+FTaLpkr+80bCoqNKxsZWwiPTTaNft1InR+YT5yoyUafOB29kt25aZi4uVk+203MGDzNiBk+q29ZcAEonXN4WFj5FXo71peaW9z33Oz89r/9eT9KfS5w1I6q7quaMi5LuUWvt4qbZIT1NOxbvwlv73vmpq5suI/M+YyADtrvKiVqE4V2cdlOj2icTmbqlswW7m02nZk9W4fk9y0q6VDUjZiZX7qW1abY+AKYDuu6/x3d3W1t3HlYjf5oGBANeHrTcuhV2gMa266vaHx89vnWxic1qUsdmIxPtrmc6Cr67eD8eJr6iUr/Cnu9GJu91ppqWl0IjQpdCIpcu2zJgA1IewsJSvp2louq7y+a7ZN1ItnG99bIfU7a7ZWqlCjs7aaZLz9GloaGinp5S80rzs5L29vb3V1evr69bfioxRxQCVu2hoaK+vp5SwscrGsRdWj0+PLr7YxHCgyp1SQk0pbs44hKqbT5gXtmqzImcRMwEa7/f1luOzmpqa45qXwC2YAI1eb31duBfPz3LnfX3nOJ8uvk9CgoxGIkPnF1GfTaGCbVcdIlMtmWs3okx1OWdMJTl47/2yyOHgioqYl5fMUeEckrGL2lAAxrO/7gEhJQQyZDDJG0LyHBNtb5AXNCZOGtDEwPWMoPbMcEIUzsEot1UPrxynLu0fUJ2K6BLp0LV401Fcu93ecB8f3/b7ph/hS+RvqVrf8h1Dr7qPKlt9EMJ1vti6+vlNTxeCyR009rfNv+pnLsRh+uk861eOr3Hkv8yieH5dIAL966L7WEr8HRohKgqh4rihW0nXyTbZLrUe2g6s1TXR5RDGZYst2//Gtfrzsdkk4/h031aJqXUWClPLCqdajkWUmFcEBWsdwYKsIlh8MYXdLMOWOYxtFOIy8s7j2ZgMBr6UjaPgskj4fV4dStCzFlI3j3tZx3JAimUtYAmy4CL7wnVZzCGU8MjjuBF3np2iOflrINXU+nIyJYJFRVAcxTO38gZ6OZAkGaiI5kEUmRzQVa/8xnuch26hchf9eZkP/N0punxeqaUasWcalIs8W6boAw1gUlERl/JBhAC41/T0S36NEfZG3BNWv6ua3o/Gr9FO582j3xw352liT6VSI9sGKyaXYzJANLvm5oeceZcCEGYpjZHFtT3ioFIK/ApZBOmJZJKSvLuhP2g8uR3uCI3p2Sz1kaJpcAEadiY5OIBGr0dlAUUBin5fgp5jtD+1/Pur00Qx911D3nSMic9DY7kyb/5XWDUtTgNhOHMLZIYwp8BAhhDSY5M0oXTNsfnqoSi26RICzULTjbBtt9CE1EMK2oMXFc/SLotbLwveFlZ7EXGP/gHRq/4Px2dOw8zz8fLAMFxEPlaVSnuqS2PZyXPZ8YS1LPheTogsQ59UU2G/au+XD4vF8/kka0ajslsEHckd/KnPewZnhmtGUwhRUahUileVVPYohRCuASVUAeF52XFHyy+m3q4zfbIsGurDARmt4/Cp8MF9yzV6ayjQQHEQKR/UyqkOClWcgJytMQzD4MvKPz8EVVUqnZHyoDZbsmmSqeS8eiUY+rE7+8a1SIhRDgJKkFMp5YODqKd4sNcLEejlwc184dIg5ANPrWLj9fsffVMlfp/pt5rFKU0vuH7p4DDEAOYUAhR4AQ0o6MU9omFsw2vh+PKiWq6GkaEAR3p/8ZO97NFZvF4/O03TTlz+4vpmaQpCvwEo1UINQS1cxzGPsWXbNpZd3ZPr5XL7ddmWPm9n87vddjluHWHDf2Tc3O9LO+JU5yQaNVotAlGIRQh6zB1DURAa03Ca6mlqmJmUzCaj5fuvd7NkMnjXj9yTp1eqezjcH+x3XMNTp12H16imIcDAixgDkXQH3ejUGE4KXS8mm2SlhE7CBMbfm5f7xU66koafxwo6qhL3vRuNDAWLlAINUQg0EYiWKEyNkamqU7Mzlm4O2Q1CDqqyTTI+iS53ye3ddjXutNtKbrIaHVd3PYRFhABFGDO+iAHQqEcB5ul43NGsINAgOw7K0Ttjksxud7vZfpwOU33gXnM+DxUvQEjTNGbNEEIoe1MF8rxtx4GCGJctyxZZuMcvdGk/v90lyabdbhdFEV1zJziORY1ZIkAwxhbP88B3pg6wMIRQtMVcbjSoZtlYtBtd/c3l5Xa/kdppUQzTLEt17q3hepCZawizBKw6K7YtC/CWyCw1kclBqEHA8zhe/43qZHZxMd9vVumw0If392mTu8rqQkXsNmtf5IFMWYTYZlKM819RZMUwWEerf3p+kiXz27vZPEmkbLVsd246ESexYSI3EC3iqJ4s54i3Y4vHvM3/h21pmOnYx2N8OqknWV1Lm+3i/xBZOh5/GRkm97uu6+bgWs77fdn3SciACfTPzvwcEkhI7vtsIzQ+vb16Pp/PF8/fvHki1fUV+yIPBt3v1/8A5HhvMz3IHMsAAAAASUVORK5CYII=";
TextComponent component = new TextComponent("§e§l§m>>§6§l§m---§f§m§l»§e§l Proxy by Team BlazingHack / NODE 1");
component.setBold(true);
component.setColor(ChatColor.RED);
// component.wait((long) 1.0, 1);
// component.setBold(true);
// component.setColor(ChatColor.RED);
res.description = component;
res.version = new S00PacketServerInfo.MinecraftProtocolVersionIdentifier();
res.version.name = "§8[§a§lBETA§8]";
//res.version.protocol = this.handler.protocolVersion;
// Pozwoli na wyswietlanie Version Name
res.version.protocol = 99;
/*if (res.version.protocol != 4 && res.version.protocol != 5 && res.version.protocol != 47 && res.version.protocol != 107) {
res.version.protocol = 5;
}*/
res.players = new S00PacketServerInfo.PlayerCountData();
res.players.max = 0;
res.players.online = 0;
ArrayList<S00PacketServerInfo.GameProfile> profiles = new ArrayList<S00PacketServerInfo.GameProfile>();
for (Player sh : Player.players) {
if (sh.name != null) {
S00PacketServerInfo.PlayerCountData players2;
S00PacketServerInfo.PlayerCountData players = players2 = res.players;
++players2.online;
profiles.add(new S00PacketServerInfo.GameProfile(new UUID(16384L, Long.MIN_VALUE).toString(), sh.name));
}
}
res.players.sample = profiles.toArray(new S00PacketServerInfo.GameProfile[profiles.size()]);
S00PacketServerInfo resPacket = new S00PacketServerInfo(res);
this.handler.packetSender.sendPacket(resPacket);
}
public void handle(C00PacketServerQuery packet) {
while (true) {
try {
Thread.sleep(10L);
if (this.handler.socket.isClosed()) {
return;
}
}
catch (InterruptedException ex) {}
if (this.handler.packetSender.priority.size() == 0 && this.handler.packetSender.packets.size() == 0 && this.handler.packetSender.customs.size() == 0) {
this.sendPing();
}
}
}
public void handle(C01PacketPing packet) {
this.handler.packetSender.sendPacket(new S01PacketPong(packet.time));
}
}
| true
|
56d75e2ee90eced793bf0e63098ca712d6ffe47e
|
Java
|
lennart-m/superfractals-and-visualizations
|
/Discrete Sets and Maps/src/de/lennartmeinhardt/math/discrete2d/set/shapes/BaseRectangle.java
|
UTF-8
| 1,223
| 3.546875
| 4
|
[] |
no_license
|
package de.lennartmeinhardt.math.discrete2d.set.shapes;
/**
* A simple immutable {@link DiscreteRectangle} implementation.
*
* @author Lennart Meinhardt
*/
public class BaseRectangle implements DiscreteRectangle {
// the bounds
private final int left;
private final int bottom;
private final int right;
private final int top;
/**
* Create a new {@link BaseRectangle} with given bounds.
*
* @param left the left bounds
* @param bottom the bottom bounds
* @param right the right bounds
* @param top the top bounds
*/
public BaseRectangle(int left, int bottom, int right, int top) {
this.left = left;
this.bottom = bottom;
this.right = right;
this.top = top;
}
/**
* Create a new {@link BaseRectangle} with given bounds.
*
* @param rectangle the bounds
*/
public BaseRectangle(DiscreteRectangle rectangle) {
this(rectangle.getLeft(), rectangle.getBottom(), rectangle.getRight(), rectangle.getTop());
}
@Override public int getLeft() {
return left;
}
@Override public int getBottom() {
return bottom;
}
@Override public int getRight() {
return right;
}
@Override public int getTop() {
return top;
}
}
| true
|
87a5e444ec36096f16cc3669b45d75ff155960f8
|
Java
|
debenito/AgendaLogic
|
/Agenda-v.1/src/junta/agenda/editor/ContenedorContacto.java
|
ISO-8859-10
| 2,112
| 3.28125
| 3
|
[] |
no_license
|
package junta.agenda.editor;
import java.awt.Point;
import junta.agenda.agrupacion.Agrupacion;
import junta.agenda.agrupacion.Contacto;
/**
*
* @author Jose Antonio de Benito Suarez
* @version v17/02/2016 Interfaz con metodos implementados por los tipos de
* contenedor existente
*/
public class ContenedorContacto implements Contenedor {
/**
* Parametros de inicializacion
*/
private int alto;
private int ancho;
private Point corner;
/**
* Contructor con parametros de inicializacion
*
* @param alto
* @param ancho
* @param corner
*/
public ContenedorContacto(int alto, int ancho, Point corner) {
this.corner = corner;
this.alto = alto;
this.ancho = ancho;
}
@Override
public void execute(AreaDelContenido area) {
area.setAlto(alto);
area.setAncho(ancho);
}
@Override
public void clickon(int x, int y, Agrupacion agrupacion) {
if (contiene(x, y))
System.out.println(llamar(agrupacion));
}
/**
* Metodo para realizar una llamada
*
* @param agrupacion
* @return LLamda a telefono
*/
public String llamar(Agrupacion agrupacion) {
return "LLamado al telefono" + ((Contacto) agrupacion).getTelefono();
}
/**
* Metodo para ver si la pulsacion esta dentro del areaContenida
*
* @param x
* @param y
* @return true si esta false sino
*/
private boolean contiene(int x, int y) {
return (corner.x <= x && x <= corner.x + ancho)
&& (corner.y <= y && y <= corner.y + alto);
}
@Override
public String dibujar(Agrupacion a) {
String cadena = "";
cadena += "Tamao Pizarra:" + alto + " " + ancho + "\n";
cadena += "Posicion Esquina:" + corner.x + " " + corner.y + "\n";
cadena += "Datos del contacto" + "\n";
cadena += "Nombre:" + a.getNombre() + "\n";
cadena += "Imagen" + ((Contacto) a).getImagen() + "\n";
cadena += "Apellidos" + ((Contacto) a).getApellidos() + "\n";
cadena += "Imagen" + ((Contacto) a).getTelefono() + "\n";
cadena += "==============================" + "\n";
return cadena;
}
@Override
public Contenedor createContenedor() {
return new ContenedorContacto(alto, ancho, corner);
}
}
| true
|
4f1c9ced131f61062b08cbb5541fac430a09de4c
|
Java
|
MierQQ/Lab2_Java
|
/src/main/java/Application/ExecutorPackage/Factory/Block/BlockClasses/SortBlock.java
|
UTF-8
| 1,130
| 2.984375
| 3
|
[] |
no_license
|
package Application.ExecutorPackage.Factory.Block.BlockClasses;
import Application.ExecutorPackage.Exceptions.BlockException;
import Application.ExecutorPackage.Factory.Block.BlockType;
import Application.ExecutorPackage.Factory.Block.IBlock;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class SortBlock implements IBlock {
@Override
public BlockType getBlockType() {
return BlockType.inOut;
}
@Override
public void execute(List<String> args, StringBuilder input) throws BlockException {
if (args.size() != 0) {
throw new BlockException("Wrong number of args");
}
StringBuilder buffer = new StringBuilder(input);
input.delete(0, input.length());
String[] strArray = buffer.toString().replace("\n", " ").split(" ");
var str = Arrays.stream(strArray).sorted(Comparator.comparing(String::toLowerCase)).toArray();
for (int i = 0; i < str.length; ++i) {
input.append(str[i]);
if (i != str.length - 1) {
input.append("\n");
}
}
}
}
| true
|
50e64655f92963a9bc46e6de71c46f3649fdd1d7
|
Java
|
alansparrow/honest_mockingbird_android
|
/app/src/main/java/com/trungbao/honestmockingbird/service/NewsFirebaseMessagingService.java
|
UTF-8
| 1,305
| 2.234375
| 2
|
[] |
no_license
|
package com.trungbao.honestmockingbird.service;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
/**
* Created by baotrungtn on 9/18/17.
*/
public class NewsFirebaseMessagingService extends FirebaseMessagingService{
private static final String TAG = "FirebaseFCMService";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.d(TAG, "My Token: " + FirebaseInstanceId.getInstance().getToken());
Log.d(TAG, "From: " + remoteMessage.getFrom());
Log.d(TAG, "Body: " + remoteMessage.getNotification().getBody());
final String title = remoteMessage.getNotification().getTitle();
final String body = remoteMessage.getNotification().getBody();
Handler h = new Handler(getApplicationContext().getMainLooper());
h.post(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), title, Toast.LENGTH_SHORT).show();
}
});
}
}
| true
|
82bcd4d9de64dbae8e93df47dbe739e84b78e1cd
|
Java
|
SavageLabs/SavageWands
|
/src/main/java/net/prosavage/savagewands/hooks/impl/VaultHook.java
|
UTF-8
| 702
| 1.984375
| 2
|
[] |
no_license
|
package net.prosavage.savagewands.hooks.impl;
import net.milkbowl.vault.economy.Economy;
import net.prosavage.savagewands.SavageWands;
import net.prosavage.savagewands.hooks.PluginHook;
import org.bukkit.plugin.RegisteredServiceProvider;
public class VaultHook implements PluginHook<VaultHook> {
@Override
public VaultHook setup() {
RegisteredServiceProvider<Economy> rsp = SavageWands.getInstance().getServer().getServicesManager().getRegistration(Economy.class);
if (rsp == null) {
return null;
}
SavageWands.econ = rsp.getProvider();
return this;
}
@Override
public String getName() {
return "Vault";
}
}
| true
|
caabc6eb2d346bc92ef6d1c70a05ebf4dc6ee450
|
Java
|
Calo-missile/GooglePlay
|
/app/src/main/java/com/hsc/googleplay/ui/view/RatioLayout.java
|
UTF-8
| 3,028
| 2.46875
| 2
|
[] |
no_license
|
package com.hsc.googleplay.ui.view;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.FrameLayout;
import com.hsc.googleplay.R;
import com.hsc.googleplay.utils.LogUtils;
/**
* 自定义控件,按比例来决定布局高度
* Created by 15827 on 2017/5/22.
*/
public class RatioLayout extends FrameLayout {
private float mRatio;
public RatioLayout(Context context) {
super(context);
}
public RatioLayout( Context context, AttributeSet attrs) {
super(context, attrs);
//获取属性值
//当自定义属性时,系统会自动生成属性相关id,此id通过R.styleable来引用
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RatioLayout);
// id = 属性名_具体属性字段名称
//系统自动生成RatioLayout_ratio,根据两个name值
mRatio = typedArray.getFloat(R.styleable.RatioLayout_ratio, -1);//宽高比例值
typedArray.recycle();//回收,提高具体性能
//LogUtils.i("ratio=" + mRatio);
}
public RatioLayout( Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// 1 获取宽度
// 2 根据宽度和比例ratio,计算控件的高度
// 3 重新测量控件
LogUtils.d("widthMeasureSpec: "+widthMeasureSpec);
// MeasureSpec.AT_MOST; 至多模式, 控件有多大显示多大, wrap_content
// MeasureSpec.EXACTLY; 确定模式, 类似宽高写死成dip, match_parent
// MeasureSpec.UNSPECIFIED; 未指定模式.
int widthMode = MeasureSpec.getMode(widthMeasureSpec);//获取宽度模式
int width = MeasureSpec.getSize(widthMeasureSpec); // 获取宽度值
int heightMode = MeasureSpec.getMode(heightMeasureSpec);//获取高度模式
int height = MeasureSpec.getSize(heightMeasureSpec); // 获取高度值
//宽度确定,高度不确定,mRatio合法,才计算高度值
if (widthMode == MeasureSpec.EXACTLY && heightMode != MeasureSpec.EXACTLY && mRatio > 0) {
//图片宽度 = 控件宽度 - 左侧内边距 - 右侧内边距
int imageWidth = width - getPaddingLeft() - getPaddingRight();
//图片高度 = 图片宽度 / 宽高比例
int imageHeight = (int) (imageWidth / mRatio + 0.5f);
// 控件高度 = 图片高度 + 上侧内边距 + 下侧内边距
height = imageHeight + getPaddingTop() + getPaddingBottom();
//根据最新的高度重新生成 heightMeasureSpec (高度模式是确定模式)
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
}
//按照最新的高度测量控件
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
| true
|
31b9deac7ba676c28fe7ef56c7f8e35af6fa4ed2
|
Java
|
KrotSV/ksp
|
/src/main/java/spring/tutorial/interfaces/EventLogger.java
|
UTF-8
| 143
| 1.976563
| 2
|
[] |
no_license
|
package spring.tutorial.interfaces;
import spring.tutorial.bins.Event;
public interface EventLogger {
public void logEvent(Event event);
}
| true
|
d310f602fbed28e459327f00d3ac139eec640576
|
Java
|
Seungwoon12/kh
|
/day15/src/oop/poly1/ZFlip.java
|
UTF-8
| 353
| 2.515625
| 3
|
[] |
no_license
|
package oop.poly1;
public class ZFlip extends Phone{
@Override
public void call() {
System.out.println("ZFilp의 전화 기능 실행!");
}
@Override
public void sms() {
System.out.println("ZFlip의 문자 기능 실행!");
}
@Override
public void camera() {
System.out.println("ZFilp의 카메라 기능 실행");
}
}
| true
|
c2914701c835a61c59099a7dabd4896c1746148e
|
Java
|
abcdfabcdf/6Days
|
/src/com/sixdays/userMember/controller/userProfileImageDeleteServlet.java
|
UTF-8
| 3,006
| 2.140625
| 2
|
[] |
no_license
|
package com.sixdays.userMember.controller;
import java.io.IOException;
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 org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
import com.sixdays.userMember.model.exception.MemberException;
import com.sixdays.userMember.model.service.userMemberService;
import com.sixdays.userMember.model.vo.userMember;
/**
* Servlet implementation class userProfileImageDeleteServlet
*/
@WebServlet("/pimgDelete.me")
public class userProfileImageDeleteServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public userProfileImageDeleteServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int maxSize = 1024*1024*10;
if(!ServletFileUpload.isMultipartContent(request)) {
request.setAttribute("msg", "multipart를 통한 전송이 아닙니다.");
request.getRequestDispatcher("views/common/errorPage.jsp").forward(request, response);
}
String root = request.getServletContext().getRealPath("/");
System.out.println("root : " + root);
String savePath = root + "resources/proimgUploadFiles";
MultipartRequest mrequest = new MultipartRequest(
request,
savePath,
maxSize,
"UTF-8",
new DefaultFileRenamePolicy()
);
String proimg = mrequest.getFilesystemName("proimg");
String userid = mrequest.getParameter("userid4");
HttpSession session = request.getSession(false);
userMember m = (userMember)session.getAttribute("member");
m.setProimg(proimg);
System.out.println("변경한 회원 정보 확인 :" + m);
userMemberService ms = new userMemberService();
try {
ms.deleteProImg(m);
System.out.println("회원 정보 수정 완료!");
response.sendRedirect("/6Days/pbSelect.bo?userId="+ userid);
} catch (MemberException e) {
e.printStackTrace();
request.setAttribute("msg", "회원정보 수정 중 에러 발생!");
request.setAttribute("exception", e);
request.getRequestDispatcher("views/common/errorPage.jsp").forward(request, response);
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
| true
|
38c492055ac12bd4c29f5b49f903915bec085566
|
Java
|
mihailtsanovv/https---github.com-mihailtsanovv-Workshop-ucn
|
/Code/src/DB/DBInvoice.java
|
UTF-8
| 4,136
| 2.78125
| 3
|
[] |
no_license
|
package DB;
import Control.CtrSale;
import DB.*;
import Model.*;
import java.sql.*;
import java.util.ArrayList;
public class DBInvoice implements IFDBInvoice {
private Connection con;
CtrSale sc = new CtrSale();
public DBInvoice() {
con = DBConnection.getInstance().getDBcon();
}
@Override
public ArrayList<Invoice> getAllInvoiceBySaleId(int saleId, boolean retriveAssociation) {
return miscWhere("saleId ="+ saleId, retriveAssociation);
}
@Override
public Invoice searchInvoiceId(int id, boolean retriveAssociation) {
String wClause = "id like '%" + id + "%'";
System.out.println("SearchC " + wClause);
return singleWhere(wClause, retriveAssociation);
}
@Override
public int insertInvoice(Invoice inv) throws Exception {
int nextInvoiceNo = GetMax.getMaxId("Select max(InvoiceNo) from Invoice");
nextInvoiceNo = nextInvoiceNo + 1;
System.out.println("next invoiceNo = " + nextInvoiceNo);
int rc = -1;
String query = "INSERT INTO Invoice(InvoiceNo, saleDate, saleId) VALUES('"
+ nextInvoiceNo
+ "','"
+ inv.getSale().getDate()
+ "','"
+ inv.getSale().getId()
+ "')";
System.out.println("insert : " + query);
try {
Statement stmt = con.createStatement();
stmt.setQueryTimeout(5);
rc = stmt.executeUpdate(query);
stmt.close();
}// end try
catch (SQLException ex) {
System.out.println("inv is not inserted correct");
throw new Exception("inv is not inserted correct");
}
return (rc);
}
private ArrayList<Invoice> miscWhere(String wClause,
boolean retrieveAssociation) {
ResultSet results;
ArrayList<Invoice> list = new ArrayList<Invoice>();
String query = buildQuery(wClause);
try { // read the Invoice from the database
Statement stmt = con.createStatement();
stmt.setQueryTimeout(5);
results = stmt.executeQuery(query);
while (results.next()) {
Invoice invObj = new Invoice();
invObj = buildInvoice(results);
list.add(invObj);
}// end while
stmt.close();
// if (retrieveAssociation) { // The invervisor and deinvment is to
// be
// // build as well
// for (Invoice invObj : list) {
// Invoice inverEmp = singleWhere(
// " ssn = '" + inverssn + "'", false);
// System.out.println("Supervisor is seleceted");
// // here the deinvment has to be selected as well
// }
// }// end if
} catch (Exception e) {
System.out.println("Query exception - select: " + e);
e.printStackTrace();
}
return list;
}
private String buildQuery(String wClause) {
String query = "SELECT * FROM Invoice";
if (wClause.length() > 0)
query = query + " WHERE " + wClause;
return query;
}
private Invoice buildInvoice(ResultSet results) {
Invoice invObj = new Invoice();
try {
invObj.setInvoiceNo(results.getInt("invoiceNo"));
invObj.setSaleDate(sc.findById(results.getInt("saleId")).getDate());
invObj.setSale(sc.findById(results.getInt("saleId")));
} catch (Exception e) {
System.out.println("error in building the Invoice object");
}
return invObj;
}
private Invoice singleWhere(String wClause, boolean retrieveAssociation) {
ResultSet results;
Invoice invObj = new Invoice();
String query = buildQuery(wClause);
System.out.println(query);
try { // read the Invoice from the database
Statement stmt = con.createStatement();
stmt.setQueryTimeout(5);
results = stmt.executeQuery(query);
if (results.next()) {
invObj = buildInvoice(results);
// assocaition is to be build
stmt.close();
} else { // no Invoice was found
invObj = null;
}
}// end try
catch (Exception e) {
System.out.println("Query exception: " + e);
}
return invObj;
}
@Override
public int deleteInvoice(int saleId) {
int rc = -1;
String query = "DELETE FROM Invoice WHERE saleId = '" + saleId + "'";
System.out.println(query);
try { // delete from Sale
Statement stmt = con.createStatement();
stmt.setQueryTimeout(5);
rc = stmt.executeUpdate(query);
stmt.close();
}// slut try
catch (Exception ex) {
System.out.println("Delete exception in Invoice db: " + ex);
}
return (rc);
}
}
| true
|
83bcfe70f7fb9251a966b3f034e6586cf7e53100
|
Java
|
zengsn/wesites
|
/src/legacy/_irest-massage-chair/src/main/java/com/gizwits/service/UserManagement.java
|
UTF-8
| 2,851
| 2.375
| 2
|
[] |
no_license
|
package com.gizwits.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import com.gizwits.dao.UserRepository;
import com.gizwits.domain.User;
/**
* @author Marvel
*/
@Service
public class UserManagement {
@Autowired
private UserRepository userRepository;
public User login(String phoneNumber, String password) {
User user = findByPhoneNumber(phoneNumber);
if (user == null || password == null || !password.equals(user.getPassword())) {
return null;
}
return user;
}
public User register(String phoneNumber, String password) {
if (findByPhoneNumber(phoneNumber) != null || password == null) {
return null;
}
User user = new User();
user.setName(phoneNumber); // 默认与手机号相同
user.setPhoneNumber(phoneNumber);
user.setPassword(password);
return userRepository.save(user);
}
// public User create(User user) {
// // 检查是否存在相同的phoneNumber
// if (user == null || findByPhoneNumber(user.getPhoneNumber()) != null) {
// return null;
// }
// return userRepository.save(user);
// }
public Page<User> findAll(Integer page, Integer size) {
return userRepository.findAll(new PageRequest(page, size));
}
// public List<User> findAll() {
// return userRepository.findAll();
// }
public User update(User user, String name) {
if (user == null) {
return null;
}
// 非必填项,不为null时才修改
if (name != null) {
user.setName(name);
}
return userRepository.save(user);
}
public User updatePassword(User user, String password) {
if (user == null || password == null) {
return null;
}
user.setPassword(password);
return userRepository.save(user);
}
public void delete(Long id) {
userRepository.delete(id);
}
public User findById(Long id) {
if (id == null) {
return null;
}
return userRepository.findOne(id);
}
public User findByPhoneNumber(String phoneNumber) {
if (phoneNumber == null) {
return null;
}
return userRepository.findByPhoneNumber(phoneNumber);
}
public Boolean exists(Long id) {
if (id == null) {
return null;
}
return userRepository.exists(id);
}
// TODO 短信验证
public Boolean validateCode(String code) {
if (code.isEmpty()) {
return false;
}
return true;
}
}
| true
|
d71bf607bc9e21c37c023ff96201c2c5918c8e63
|
Java
|
jenkinsci/jexl
|
/src/test/org/apache/commons/jexl/IfTest.java
|
UTF-8
| 5,390
| 2.90625
| 3
|
[
"Apache-2.0"
] |
permissive
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.jexl;
import junit.framework.TestCase;
/**
* Test cases for the if statement.
*
* @author Dion Gillard
* @since 1.1
*/
public class IfTest extends TestCase {
public IfTest(String testName) {
super(testName);
}
/**
* Make sure if true executes the true statement
*
* @throws Exception on any error
*/
public void testSimpleIfTrue() throws Exception {
Expression e = ExpressionFactory.createExpression("if (true) 1");
JexlContext jc = JexlHelper.createContext();
Object o = e.evaluate(jc);
assertEquals("Result is not 1", new Integer(1), o);
}
/**
* Make sure if false doesn't execute the true statement
*
* @throws Exception on any error
*/
public void testSimpleIfFalse() throws Exception {
Expression e = ExpressionFactory.createExpression("if (false) 1");
JexlContext jc = JexlHelper.createContext();
Object o = e.evaluate(jc);
assertNull("Return value is not empty", o);
}
/**
* Make sure if false executes the false statement
*
* @throws Exception on any error
*/
public void testSimpleElse() throws Exception {
Expression e = ExpressionFactory
.createExpression("if (false) 1; else 2;");
JexlContext jc = JexlHelper.createContext();
Object o = e.evaluate(jc);
assertEquals("Result is not 2", new Integer(2), o);
}
/**
* Test the if statement handles blocks correctly
*
* @throws Exception on any error
*/
public void testBlockIfTrue() throws Exception {
Expression e = ExpressionFactory
.createExpression("if (true) { 'hello'; }");
JexlContext jc = JexlHelper.createContext();
Object o = e.evaluate(jc);
assertEquals("Result is wrong", "hello", o);
}
/**
* Test the if statement handles blocks in the else statement correctly
*
* @throws Exception on any error
*/
public void testBlockElse() throws Exception {
Expression e = ExpressionFactory
.createExpression("if (false) {1;} else {2;}");
JexlContext jc = JexlHelper.createContext();
Object o = e.evaluate(jc);
assertEquals("Result is wrong", new Integer(2), o);
}
/**
* Test the if statement evaluates expressions correctly
*
* @throws Exception on any error
*/
public void testIfWithSimpleExpression() throws Exception {
Expression e = ExpressionFactory
.createExpression("if (x == 1) true;");
JexlContext jc = JexlHelper.createContext();
jc.getVars().put("x", new Integer(1));
Object o = e.evaluate(jc);
assertEquals("Result is not true", Boolean.TRUE, o);
}
/**
* Test the if statement evaluates arithmetic expressions correctly
*
* @throws Exception on any error
*/
public void testIfWithArithmeticExpression() throws Exception {
Expression e = ExpressionFactory
.createExpression("if ((x * 2) + 1 == 5) true;");
JexlContext jc = JexlHelper.createContext();
jc.getVars().put("x", new Integer(2));
Object o = e.evaluate(jc);
assertEquals("Result is not true", Boolean.TRUE, o);
}
/**
* Test the if statement evaluates decimal arithmetic expressions correctly
*
* @throws Exception on any error
*/
public void testIfWithDecimalArithmeticExpression() throws Exception {
Expression e = ExpressionFactory
.createExpression("if ((x * 2) == 5) true;");
JexlContext jc = JexlHelper.createContext();
jc.getVars().put("x", new Float(2.5f));
Object o = e.evaluate(jc);
assertEquals("Result is not true", Boolean.TRUE, o);
}
/**
* Test the if statement works with assignment
*
* @throws Exception on any error
*/
public void testIfWithAssignment() throws Exception {
Expression e = ExpressionFactory
.createExpression("if ((x * 2) == 5) {y = 1;} else {y = 2;}");
JexlContext jc = JexlHelper.createContext();
jc.getVars().put("x", new Float(2.5f));
e.evaluate(jc);
Object result = jc.getVars().get("y");
assertEquals("y has the wrong value", new Integer(1), result);
}
}
| true
|
4c36355bbfa7b0941e2c1636cdf56d9497f5cd35
|
Java
|
dawidkaluza/quizzer
|
/category-service/src/main/java/org/quizzer/category/dto/base/CategoryDtoMapper.java
|
UTF-8
| 520
| 2.140625
| 2
|
[] |
no_license
|
package org.quizzer.category.dto.base;
import org.quizzer.category.domain.Category;
import org.quizzer.category.dto.DtoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
@Component
public class CategoryDtoMapper implements DtoMapper<Category, CategoryDto> {
@Override
public CategoryDto toDto(Category category) {
CategoryDto categoryDto = new CategoryDto();
BeanUtils.copyProperties(category, categoryDto);
return categoryDto;
}
}
| true
|
cde8df420603b0f195621dfae553893118188245
|
Java
|
JisooOh94/Algorithm
|
/LeetCode/medium/Maximum_Points_You_Can_Obtain_from_Cards/Solution.java
|
UTF-8
| 1,200
| 3.078125
| 3
|
[] |
no_license
|
package medium.Maximum_Points_You_Can_Obtain_from_Cards;
import org.junit.Test;
import util.PerformanceUtil;
public class Solution {
@Test
public void execute() {
// int[] nums = new int[]{1,2,3,4,5,6,1}; int left = 3;
int[] nums = new int[]{1,79,80,1,1,1,200,1}; int left = 3;
PerformanceUtil.beforeTest();
System.out.println(maxScore(nums, left));
System.out.println(PerformanceUtil.afterTest());
}
private int recursion(int front, int rear, int left, int orgLeft, int[] nums, Integer[][] record) {
if (left == 0) return 0;
else if (record[front][rear - orgLeft] != null) {
return record[front][rear - orgLeft];
}
int max = Math.max(recursion(front + 1, rear, left - 1, orgLeft, nums, record) + nums[front], recursion(front, rear - 1, left - 1, orgLeft, nums, record) + nums[rear]);
record[front][rear - orgLeft] = max;
return max;
}
public int maxScore(int[] nums, int left) {
if(nums.length == 0) return nums[0];
else if(nums.length == left) {
int result = 0;
for(int num : nums) result += num;
return result;
}
Integer[][] record = new Integer[left][left];
return recursion(0, nums.length - 1, left, nums.length - left, nums, record);
}
}
| true
|
77a041280bfd9eec279f9783e599a9a48cab27bf
|
Java
|
nagendraksrivastava/doc-ocean-consumer-app-android
|
/app/src/main/java/customer/dococean/com/patient/network/response/myappointment/Address.java
|
UTF-8
| 1,598
| 2.171875
| 2
|
[
"MIT"
] |
permissive
|
package customer.dococean.com.patient.network.response.myappointment;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Address {
@SerializedName("address_line")
@Expose
private String addressLine;
@SerializedName("city")
@Expose
private Object city;
@SerializedName("latitude")
@Expose
private Double latitude;
@SerializedName("longitude")
@Expose
private Double longitude;
/**
*
* @return
* The addressLine
*/
public String getAddressLine() {
return addressLine;
}
/**
*
* @param addressLine
* The address_line
*/
public void setAddressLine(String addressLine) {
this.addressLine = addressLine;
}
/**
*
* @return
* The city
*/
public Object getCity() {
return city;
}
/**
*
* @param city
* The city
*/
public void setCity(Object city) {
this.city = city;
}
/**
*
* @return
* The latitude
*/
public Double getLatitude() {
return latitude;
}
/**
*
* @param latitude
* The latitude
*/
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
/**
*
* @return
* The longitude
*/
public Double getLongitude() {
return longitude;
}
/**
*
* @param longitude
* The longitude
*/
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
}
| true
|
9318f7ac1ee6eb90e869c510c945eae734417f6b
|
Java
|
YuChengHup/Hs-The-flower-shoping
|
/src/main/java/com/hs/mapper/SizeMapper.java
|
UTF-8
| 502
| 2.0625
| 2
|
[] |
no_license
|
package com.hs.mapper;
import com.hs.entity.Size;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* (Size)表数据库访问层
*
* @author makejava
* @since 2021-10-22 20:54:50
*/
public interface SizeMapper {
/**
* 通过ID查询单条数据
*
* @param sizId 主键
* @return 实例对象
*/
Size queryById(Integer sizId);
/**
* 查询指定行数据
*
* @return 对象列表
*/
List<Size> queryAll();
}
| true
|
45587ef108f6b12e48e75b7fb43d3f8339d30781
|
Java
|
Valexx55/adglow_dev
|
/adglowjse/src/main/java/imcdfi/IMCImpl.java
|
UTF-8
| 220
| 2.46875
| 2
|
[] |
no_license
|
package imcdfi;
public class IMCImpl implements IMCI {
public float calcula (Persona persona)
{
float imc = 0;
imc = (persona.getPeso()/(persona.getAltura()*persona.getAltura()));
return imc;
}
}
| true
|
55f5d431e0ebd45808a6df84712bc3e945b9cad1
|
Java
|
lkmoreira/YesChamix
|
/Old/yeschamixv2/trunk/codigo_fonte/WORKSPACE/yeschamixv2/src/br/com/gv8/yeschamix/configuracaobd/controller/ConfigService.java
|
UTF-8
| 776
| 2.171875
| 2
|
[] |
no_license
|
package br.com.gv8.yeschamix.configuracaobd.controller;
import br.com.gv8.yeschamix.configuracaobd.business.ConfigBOService;
import br.com.gv8.yeschamix.configuracaobd.business.ConfigBOServiceImpl;
public final class ConfigService{
private ConfigBOService service;
/*SINGLETON*/
private static ConfigService instance;
private ConfigService(){
service = new ConfigBOServiceImpl();
}
public static ConfigService getInstance() {
if( instance == null ){
instance = new ConfigService();
}
return instance;
}
/*SINGLETON*/
public String configurarBD(String login, String driver, String url, String user, String password) throws Exception {
return service.configurarBD(login, driver, url, user, password);
}
}
| true
|
4cb0a1859291a6b2abba5c1f4eebdc3aa357f629
|
Java
|
slowice/Best-Practice
|
/data/src/main/java/xb/data_construct/collection/CollectionSome.java
|
UTF-8
| 2,501
| 3.46875
| 3
|
[] |
no_license
|
package xb.data_construct.collection;
import lombok.extern.slf4j.Slf4j;
import java.util.*;
/**
* List Set Map有哪些实现类?是否线程安全?他们是怎么做到增删查的?
*/
@Slf4j
public class CollectionSome {
/**List
* 有序,可重复
* ArrayList,Vector,LinkedList
* ArrayList:底层数据结构是数组,查询快,增删慢。
* 底层是数组,增删元素需要重新生成数组,查找时间复杂度O(1)
* LinkedList:底层数据结构是链表,查询慢,增删快
* 增删的时间复杂度是O(1),查找的时间复杂度是O(N)
*/
List list = new ArrayList();
/**Set
* 无序不重复
* HashSet,LinkedHashSet,TreeSet
* HashSet:底层数据结构是哈希表.通过插入元素的hashcode不同来确保不重复
* LinkedHashSet:底层数据结构是链表和哈希表。链表保证元素有序,哈希表保证元素唯一
* TreeSet:底层数据结构是红黑树。(唯一,有序)
*/
//set去重:
public static void duplicateRemove(){
Set<String> names = new HashSet<>();
names.add("Tom");
names.add("Mary");
if (names.add("Peter")) {
log.info("Peter is added to the set");
}
if (!names.add("Tom")) {
log.info("Tom is already added to the set");
}
}
//set找交集
public static void intersection(){
Set<Integer> s1 = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5, 7, 9));
Set<Integer> s2 = new HashSet<>(Arrays.asList(2, 4, 6, 8));
log.info("s1 before intersection: " + s1);
s1.retainAll(s2);
log.info("s1 after intersection: " + s1);
}
//set找差集
public static void diffrentSet(){
Set<Integer> s1 = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5, 7, 9));
Set<Integer> s2 = new HashSet<>(Arrays.asList(2, 4, 6, 8));
log.info("s1 before difference: " + s1);
s1.removeAll(s2);
log.info("s1 after difference: " + s1);
}
/**Map
* Hashtable,LinkedHashMap,HashMap,TreeMap
* TreeMap:有序
* HashMap:无序
*/
public static void linkedHashMapTest(){
Map<String,String> map = new LinkedHashMap<>();
}
public static int testList(){
List<String> list = new ArrayList();
list.add("1");
return 0;
}
public static void main(String[] args) {
testList();
}
}
| true
|
fbe7ec64984a874c5211aeefe23235831bdcb06a
|
Java
|
shaya2468/oow_final
|
/backend/server/src/main/java/com/shaya/woo/entities/Position.java
|
UTF-8
| 2,747
| 2.375
| 2
|
[] |
no_license
|
package com.shaya.woo.entities;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
@Entity
public class Position {
@Id
@GeneratedValue
private Long id;
@ManyToOne
private Company company;
@Column(nullable = false)
private String name;
private String note;
private Boolean accepted;
private Integer created;
@OneToMany(mappedBy = "position")
private List<Description> descriptions = new ArrayList<>();
@ManyToOne
private Product product;
@OneToMany(mappedBy = "position")
private List<Standard> standards = new ArrayList<>();
@OneToMany(mappedBy = "position")
private List<Requirement> requirements = new ArrayList<>();
@OneToMany(mappedBy = "position")
private List<Stack> stacks = new ArrayList<>();
@OneToMany(mappedBy = "position")
private List<Benefit> benefits = new ArrayList<>();
protected Position() {
}
public Position(String name, String note, Boolean accepted, Integer created) {
this.name = name;
this.note = note;
this.accepted = accepted;
this.created = created;
}
public List<Requirement> getRequirements() {
return requirements;
}
public void setRequirements(List<Requirement> requirements) {
this.requirements = requirements;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Company getCompany() {
return company;
}
public void setCompany(Company company) {
this.company = company;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public List<Standard> getStandards() {
return standards;
}
public void setStandards(List<Standard> standards) {
this.standards = standards;
}
public List<Description> getDescriptions() {
return descriptions;
}
public void setDescriptions(List<Description> descriptions) {
this.descriptions = descriptions;
}
public List<Stack> getStacks() {
return stacks;
}
public void setStacks(List<Stack> stacks) {
this.stacks = stacks;
}
public List<Benefit> getBenefits() {
return benefits;
}
public void setBenefits(List<Benefit> benefits) {
this.benefits = benefits;
}
public Integer getCreated() {
return created;
}
public void setCreated(Integer created) {
this.created = created;
}
public Boolean getAccepted() {
return accepted;
}
public void setAccepted(Boolean accepted) {
this.accepted = accepted;
}
}
| true
|
1f01fd5df7ea6d5967e9ebfaaa496da7878f85fa
|
Java
|
wangqinyu/sky-root
|
/sky-adapter-kidcrm/src/main/java/com/sky/skyadapterkidcrm/service/inter/TaskResultService.java
|
UTF-8
| 435
| 1.898438
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.sky.skyadapterkidcrm.service.inter;
import com.sky.skyentity.bean.TaskResultParams;
import com.sky.skyentity.entity.TaskResult;
import com.sky.skyadapterkidcrm.exception.BaseException;
import java.util.List;
public interface TaskResultService {
//条件查询
List<TaskResult> findByParams(TaskResultParams taskResultParams);
//存储任务结果
void save(TaskResult taskResult) throws BaseException;
}
| true
|
9a51185ee111e70c02d6ec3811fb58f5f48f9cf2
|
Java
|
autotraderuk/traverson4j
|
/traverson4j-core/src/main/java/uk/co/autotrader/traverson/link/hal/EmbeddedArrayNameHandler.java
|
UTF-8
| 1,299
| 2.265625
| 2
|
[
"Apache-2.0"
] |
permissive
|
package uk.co.autotrader.traverson.link.hal;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import uk.co.autotrader.traverson.link.LinkDiscoverer;
import static java.util.Collections.emptyList;
class EmbeddedArrayNameHandler implements LinkDiscoverer {
private final LinksRelHandler fromLinks;
EmbeddedArrayNameHandler() {
this.fromLinks = new LinksRelHandler();
}
@Override
public String findHref(JSONObject resource, String rel) {
JSONObject embedded = resource.getJSONObject("_embedded");
if (embedded != null) {
for (Object value : embedded.values()) {
JSONArray embeddedCollection = safeCastToJsonArray(value);
for (int i = 0; i < embeddedCollection.size(); i++) {
JSONObject item = embeddedCollection.getJSONObject(i);
if (rel.equals(item.getString("name"))) {
return this.fromLinks.findHref(item, "self");
}
}
}
}
return null;
}
private JSONArray safeCastToJsonArray(Object object) {
if (object instanceof JSONArray) {
return (JSONArray) object;
}
return new JSONArray(emptyList());
}
}
| true
|