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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
3cf366fbd0b2a7b6748fb79a8cdb5b3a2fa6e947 | Java | sheffercool/windchill-2 | /util/LifeCycleUtility.java | UTF-8 | 12,112 | 1.882813 | 2 | [] | no_license | package ext.hydratight.util;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.Reader;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import wt.doc.WTDocument;
import wt.epm.EPMDocument;
import wt.fc.ObjectReference;
import wt.fc.Persistable;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.fc.WTObject;
import wt.fc.collections.WTArrayList;
import wt.fc.collections.WTList;
import wt.feedback.StatusFeedback;
import wt.inf.container.WTContainerHelper;
import wt.inf.container.WTContainerRef;
import wt.lifecycle.LifeCycleHelper;
import wt.lifecycle.LifeCycleManaged;
import wt.lifecycle.LifeCycleTemplateReference;
import wt.lifecycle.State;
import wt.method.MethodContext;
import wt.method.RemoteAccess;
import wt.method.RemoteMethodServer;
import wt.org.DirectoryContextProvider;
import wt.org.OrganizationServicesHelper;
import wt.org.OrganizationServicesManager;
import wt.org.WTOrganization;
import wt.part.WTPart;
import wt.pds.StatementSpec;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.session.SessionHelper;
import wt.util.WTContext;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.rmi.RemoteException;
import wt.lifecycle.LifeCycleException;
import wt.util.WTException;
import wt.util.WTInvalidParameterException;
/**
* Life Cycle Utility<br />
* Allows the reassigning of life cycles and setting of states.
*/
public class LifeCycleUtility
extends Utility
implements RemoteAccess
{
private static final String TEMPLATE_ARG = "-template";
private static final String STATE_ARG = "-state";
private static final String COMMENTS_ARG = "-comments";
private static final String TEMPLATE_HEAD = "template";
private static final String STATE_HEAD = "state";
private static final String COMMENTS_HEAD = "comments";
private static final String ORG_CLASS = "/wt.inf.container.OrgContainer/";
private static final String MISSING_ARG = "Missing Required Argument: One of {0}, {1} or {2} is required";
private static final String CONFLICTING_ARG = "Conflicting Arguments: {0}, {1} and {2} are mutually exclusive arguments";
private static final String MISSING_COMPLEMENTARY_ARG_1 = "Missing Required Argument: If using {0}, then {1} and {2} are also required";
private static final String MISSING_COMPLEMENTARY_ARG_2 = "Missing Required Argument: If using {0}, then {1} is also required";
private static final String INVALID_LIFE_CYCLE_NAME = "Invalid life cycle name: No life cycle by the name '{0}' exists! Try specifying an organisation";
private static final String INVALID_STATE_NAME = "Invalid state name: No state by the name '{0}' exists!";
private static final String NO_DATA = "Empty Input File: The provided CSV file is empty";
private static final String MISSING_COL = "Missing Required Column: One of {0} or {1} is required, along with {2}";
private static final String CONFLICTING_COL = "Conflicting Arguments: {0} and {1} are mutually exclusive columns";
private static final String MISSING_COMPLEMENTARY_COL = "";
private static final String MISSING_DATA = "";
private static final String MALFORMED_DATA = "";
private static String templateStr;
private static String stateStr;
private static LifeCycleTemplateReference template;
private static State state;
private static String comments;
static {
CLASS_NAME = "ext.hydratight.util.LifeCycleUtility";
UTILITY_NAME = "Life Cycle Utility";
}
public static void main(String [] args)
throws Exception, Throwable
{
WTContext.init(args);
if (args == null || args.length == 0 || getBooleanArg(args, HELP_ARG)) {
printHelp();
}
else {
Object obj = null;
print("Entering '" + UTILITY_NAME + "'... ");
try {
processCredentials(args);
router(args);
}
catch (Exception ex) {
obj = ex;
}
if (obj != null) {
for (boolean flag = true; flag;) {
if (obj instanceof InvocationTargetException) {
obj = ((InvocationTargetException)obj).getCause();
}
else if (obj instanceof RemoteException) {
obj = ((RemoteException)obj).getCause();
}
else {
flag = false;
}
}
if (debug) {
throw (Exception)obj;
}
((Throwable) (obj)).printStackTrace();
}
}
if (!debug) {
System.exit(0);
}
}
public static Boolean router(String as[])
throws Throwable
{
if (!WTContainerHelper.service.isAdministrator(WTContainerHelper.getExchangeRef(),
SessionHelper.manager.getPrincipal(), true)) {
return Boolean.FALSE;
}
processArgs(as);
idType = 1;
switch (idType) {
case 0:
//processFile();
break;
case 1:
process(findByNumber());
break;
case 2:
//process(findByOid());
break;
}
return Boolean.TRUE;
}
protected static void processArgs(String as[])
throws WTException
{
file = getStringArg(as, FILE_ARG);
number = getStringArg(as, NUMBER_ARG);
revision = getStringArg(as, REVISION_ARG);
oid = getStringArg(as, OID_ARG);
type = getStringArg(as, TYPE_ARG);
stateStr = getStringArg(as, STATE_ARG);
orgStr = getStringArg(as, ORG_ARG);
templateStr = getStringArg(as, TEMPLATE_ARG);
stateStr = getStringArg(as, STATE_ARG);
comments = getStringArg(as, COMMENTS_ARG);
log = getBooleanArg(as, LOG_ARG);
validateArgs();
}
/**
* Validates the arguments provided are sufficient for the utility to function in one of<br />
* its possible modes.<br />
* <br />
* There are three modes in which this utility can be run:
* <ol>
* <li>File - set life cycles on multiple objects based on a file</li>
* <li>Number - set life cycle of single object found by number</li>
* <li>OID - set life cycle of single object found by OID</li>
* </ol>
* File Mode:<br />
* The <i>required</i> options are -
* <ul>
* <li>File</li>
* </ul>
* The <i>optional</i> options are -
* <ul>
* <li>Revision</li>
* <li>Iteration (requires "Revision")</li>
* <li>Template (requires "Organisation")</li>
* <li>Organisation (only required if using "Template"</li>
* <li>State<li>
* <li>Comments</li>
* <li>Log</li>
* </ul>
* Number Mode:<br />
* The <i>required</i> options are -
* <ul>
* <li>Number</li>
* <li>Type</li>
* </ul>
* The <i>optional</i> options are -
* <ul>
* <li>Revision</li>
* <li>Iteration (requires "Revision")</li>
* <li>Template (requires "Organisation")</li>
* <li>Organisation (only required if using "Template"</li>
* <li>State<li>
* <li>Comments</li>
* <li>Log</li>
* </ul>
* OID Mode:<br />
* The <i>required</i> options are -
* <ul>
* <li>OID</li>
* </ul>
* The <i>optional</i> options are -
* <ul>
* <li>Type (if <i>full</i> OID is provided)</li>
* <li>Template (requires "Organisation")</li>
* <li>Organisation (only required if using "Template"</li>
* <li>State<li>
* <li>Comments</li>
* <li>Log</li>
* </ul>
*/
protected static void validateArgs()
throws IllegalArgumentException
{
try {
if (file == null && number == null && oid == null) {
throw new IllegalArgumentException(MessageFormat.format(MISSING_ARG, new Object[] {
FILE_ARG, NUMBER_ARG, OID_ARG
}));
}
if ((file != null && number != null) ||
(file != null && oid != null) ||
(number != null && oid != null)) {
throw new IllegalArgumentException(MessageFormat.format(CONFLICTING_ARG, new Object[] {
FILE_ARG, NUMBER_ARG, OID_ARG
}));
}
if (stateStr != null) {
try {
state = getState(stateStr);
}
catch (WTInvalidParameterException ex) {
throw new IllegalArgumentException(MessageFormat.format(INVALID_STATE_NAME,
new Object[] {
stateStr
}
));
}
}
if (file != null) {
idType = 0;
return;
}
if (number != null) {
if (revision != null && orgStr != null) {
idType = 1;
} else {
idType = 1;
//throw new IllegalArgumentException(MessageFormat.format(MISSING_COMPLEMENTARY_ARG_1, new Object[] {
// NUMBER_ARG, REVISION_ARG, ORG_ARG
//}));
}
}
if (oid != null) {
if (orgStr != null) {
idType = 2;
} else {
throw new IllegalArgumentException(MessageFormat.format(MISSING_COMPLEMENTARY_ARG_2, new Object[] {
NUMBER_ARG, ORG_ARG
}));
}
}
if (orgStr != null) {
try {
org = getOrganization(orgStr);
if (org == null) {
throw new WTException();
}
}
catch (WTException ex) {
throw new IllegalArgumentException(MessageFormat.format(INVALID_ORG_NAME,
new Object[] {
orgStr
}
));
}
}
if (templateStr != null) {
try {
template = getLifeCycleTemplateRef(orgStr, templateStr);
if (template == null) {
throw new LifeCycleException();
}
}
catch (WTException ex) {
throw new IllegalArgumentException(MessageFormat.format(INVALID_LIFE_CYCLE_NAME,
new Object[] {
templateStr
}
));
}
}
}
catch (IllegalArgumentException ex) {
print(ex.getMessage());
System.exit(0);
}
}
/**
* Sets templates based on details passed at the command line.
*/
private static void process(QueryResult qr)
throws WTException
{
WTObject obj = null;
WTList list = new WTArrayList();
while (qr.hasMoreElements()) {
obj = (WTObject)qr.nextElement();
if (obj instanceof LifeCycleManaged) {
list.add(obj);
}
}
set(list, template, state, comments);
}
private static void set(WTList objs, LifeCycleTemplateReference lctRef, State st, String cmm)
throws WTException
{
if (stateStr != null) {
LifeCycleHelper.service.reassign(objs, lctRef, null, st, cmm);
}
else {
LifeCycleHelper.service.reassign(objs, lctRef, null, true, cmm);
}
}
/**
* Get the life cycle template reference based on the name of the template and organisation.
*/
private static LifeCycleTemplateReference getLifeCycleTemplateRef(String og, String tp)
throws WTException, LifeCycleException
{
if (og == null) { // No organisation specifed ...
return getLifeCycleTemplateRef(tp);
}
if (og.indexOf(ORG_CLASS) < 0) { // Check if has full Container path or just organisation name
og = new StringBuilder().append(ORG_CLASS).append(og).toString();
}
WTContainerRef cont = WTContainerHelper.service.getByPath(og);
return LifeCycleHelper.service.getLifeCycleTemplateReference(tp, cont);
}
/**
* Get the life cycle template reference based on the name of the template only.
*/
private static LifeCycleTemplateReference getLifeCycleTemplateRef(String tp)
throws WTException, LifeCycleException
{
return LifeCycleHelper.service.getLifeCycleTemplateReference(tp);
}
/**
*
*/
private static State getState(String st)
throws WTInvalidParameterException
{
return State.toState(st.toUpperCase());
}
protected static void printHelp()
{
print("Usage: java ext.hydratight.util.LifeCycleUtility [args]\n" +
"Args:\n" +
"\t" + USERNAME_ARG + " [REQUIRED] <username of user to authenticate as>\n" +
"\t" + PASSWORD_ARG + " [REQUIRED] <password of user to authenticate as>\n" +
"\t" + FILE_ARG + " <full filepath of input csv file>\n" +
"\t" + TEMPLATE_ARG + " <new lifecycle template to set object(s) to>\n" +
"\t" + STATE_ARG + " <new state to set object(s) to>\n" +
"\t" + ORG_ARG + " <name of the organisation container>\n" +
"\t" + NUMBER_ARG + " <number of object to set lifecycle template on>\n" +
"\t" + REVISION_ARG + " <revision of the object to set lifecycle template on>\n" +
"\t" + OID_ARG + " <id of object to set lifecycle template on>\n" +
"\t" + TYPE_ARG + " <type of the object to set lifecycle template on>\n" +
"\t" + LOG_ARG + " <full filepath of log file>\n");
}
} | true |
da11e46033d1b248877ff38451376b6d2f4f21da | Java | carolasilva/trabalho-paa-lab | /src/com/company/models/AlunoAuxiliar.java | UTF-8 | 864 | 2.859375 | 3 | [] | no_license | package com.company.models;
public class AlunoAuxiliar implements Comparable<AlunoAuxiliar> {
private Aluno aluno;
private String nomeArquivo;
public AlunoAuxiliar(Aluno aluno, String nomeArquivo) {
this.aluno = aluno;
this.nomeArquivo = nomeArquivo;
}
public Aluno getAluno() {
return aluno;
}
public void setAluno(Aluno aluno) {
this.aluno = aluno;
}
public String getNomeArquivo() {
return nomeArquivo;
}
public void setNomeArquivo(String nomeArquivo) {
this.nomeArquivo = nomeArquivo;
}
@Override
public int compareTo(AlunoAuxiliar aluno) {
if (aluno == null)
return -1;
else if (this == null)
return 1;
else
return this.getAluno().getNome().compareTo(aluno.getAluno().getNome());
}
}
| true |
0317c3187f1db656f6d40c601fabe692e18a5afb | Java | Anushadomma/CaperAssignment | /app/src/main/java/com/example/caperassignment/CaperApiClient.java | UTF-8 | 1,324 | 2.0625 | 2 | [] | no_license | package com.example.caperassignment;
import android.app.Application;
import android.content.Context;
import android.view.animation.PathInterpolator;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class CaperApiClient {
private static Retrofit retrofit = null;
public static CaperApi getItem(){
if (retrofit == null) {
String jsonFileString = Utils.getAssetJsonData();
OkHttpClient okHttpClient=new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request newRequest=chain.request().newBuilder().build();
return chain.proceed(newRequest);
}
}).build();
retrofit=new Retrofit.Builder()
.baseUrl(jsonFileString)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit.create(CaperApi.class);
}
}
| true |
bf583be3f60befea0ef41e0283f6637ca6745e83 | Java | luxin763323387/commerce-springCloud | /commerce-alibaba-nacos-client/src/main/java/com/cn/lx/controller/SleuthTraceInfoController.java | UTF-8 | 869 | 2.09375 | 2 | [] | no_license | package com.cn.lx.controller;
import com.cn.lx.service.SleuthTraceInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 打印跟踪信息
*
* @author StevenLu
* @date 2021/8/15 下午2:50
*/
@Slf4j
@RestController
@RequestMapping("/sleuth")
public class SleuthTraceInfoController {
private final SleuthTraceInfoService traceInfoService;
public SleuthTraceInfoController(SleuthTraceInfoService sleuthTraceInfoService) {
this.traceInfoService = sleuthTraceInfoService;
}
/**
* <h2>打印日志跟踪信息</h2>
*/
@GetMapping("/trace-info")
public void logCurrentTraceInfo() {
traceInfoService.logCurrentTraceInfo();
}
}
| true |
8c6b49f4b6c09cdfdb64ad1d6e662c9c23f0970c | Java | lidingkui/imooc-news-dev | /imeek-news-dev-user/src/main/java/com/hubject/user/service/AppUserMngService.java | UTF-8 | 685 | 1.6875 | 2 | [] | no_license | package com.hubject.user.service;
import com.hubject.utils.PagedGridResult;
import java.util.Date;
public interface AppUserMngService {
/**
* 查询管理员列表
*/
public PagedGridResult queryAllUserList(String nickname,
Integer status,
Date startDate,
Date endDate,
Integer page,
Integer pageSize);
/**
* 冻结用户账号,或者解除冻结状态
*/
public void freezeUserOrNot(String userId, Integer doStatus);
}
| true |
9b85a0d0218b4b9fc3265f3cc80c4870de0da7ec | Java | pankaj101010/Carnation19-1 | /src/GroupA/NewTraingleDigit.java | UTF-8 | 483 | 3.140625 | 3 | [] | no_license | package GroupA;
public class NewTraingleDigit {
public static void main(String[] args) {
int line = 9;
for (int i = 0; i <= line; i++) {
for (int space = line; space >=i; space--) {
System.out.print(" ");
}
// if (i == 0) {
// System.out.print(0);
// } else {
for (int j = i; j >= 0; j--) {
System.out.print(j);
}
for (int j = 1; j <= i; j++) {
System.out.print(j);
}
//}
System.out.println();
}
}
}
| true |
57bb147d4f5c028819a85dc7269415f84ad8df31 | Java | justinba1010/GraphTheory | /MoserSpindleSquared.java | UTF-8 | 799 | 2.84375 | 3 | [] | no_license | import java.util.*;
public class MoserSpindleSquared{
public static void main(String[] args) {
String[] a = {"p0","p1","p2","p3","p4","p5","p6"};
ArrayList<String> l = new ArrayList<String>(Arrays.asList(a));
AdjMatrixGraph<String> moser = new AdjMatrixGraph(l);
moser.addEdge(0,1);
moser.addEdge(0,4);
moser.addEdge(0,5);
moser.addEdge(0,6);
moser.addEdge(1,2);
moser.addEdge(1,6);
moser.addEdge(2,3);
moser.addEdge(2,6);
moser.addEdge(3,4);
moser.addEdge(3,5);
moser.addEdge(4,5);
System.out.println(moser);
AdjMatrixGraph<String[]> moserSquared = moser.cartesianProduct(moser);
System.out.println(moserSquared);
for(Object[] node : moserSquared.nodes) {
System.out.println("("+node[0]+","+node[1]+")");
}
}
}
| true |
ca4359462e765dd4103cd6ad60ff44a7b8c20f76 | Java | vcheng19/CellSociety | /src/gridinitializers/SugarScapeGridInitializer.java | UTF-8 | 2,400 | 2.609375 | 3 | [
"MIT"
] | permissive | package gridinitializers;
import cellclasses.*;
import cellsociety_team24.Grid;
import filereadcheck.FileReader;
import javafx.scene.Group;
import ruleEnforcers.SugarScapeRuleEnforcer;
import ruleEnforcers.WaTorRuleEnforcer;
public class SugarScapeGridInitializer extends GridInitializer{
private int vision;
private int sugarMetabolism;
private int sugarAgent;
private int sugarAmount;
private int sugarGrowBackRate;
private int sugarGrowBackInterval;
private int lowerBoundAge = 60;
private int fertileLimitCutoff = 20;
private final String agentXTag = "agentX";
private final String agentYTag = "agentY";
private SugarScapeRuleEnforcer myRuleEnforcer;
public SugarScapeGridInitializer(Grid thisGrid, Group gr, FileReader fr){
super(thisGrid, gr, fr);
myRuleEnforcer = new SugarScapeRuleEnforcer(getGrid(), fr);
}
@Override
public void makeGrid() {
Cell[][]grid = new SugarScapeCell[getDimension()][getDimension()];
initializeParameters();
for(int i = 0; i < grid.length; i++){
for(int j = 0; j < grid[0].length; j++){
SugarScapeCell cell = new SugarScapeCell(i, j);
grid[i][j] = cell;
}
}
getThisGrid().setValues(grid, getWorldSize()/getDimension(), getGroup(), true);
getThisGrid().createCells(getWrap(), vision);
addAttributes(grid);
setGrid(grid);
}
public void initializeParameters(){
FileReader reader = getReader();
vision = Integer.parseInt(reader.readProperty("vision"));
sugarMetabolism = Integer.parseInt(reader.readProperty("sugarMetabolism"));
sugarAgent = Integer.parseInt(reader.readProperty("sugarAgent"));
sugarAmount = Integer.parseInt(reader.readProperty("sugarAmount"));
sugarGrowBackRate = Integer.parseInt(reader.readProperty("sugarGrowBackRate"));
sugarGrowBackInterval = Integer.parseInt(reader.readProperty("sugarGrowBackInterval"));
}
public void addAttributes(Cell[][]grid){
for(int i = 0; i < grid.length; i++){
for(int j = 0; j < grid.length; j++){
SugarScapeCell cell = (SugarScapeCell) grid[i][j];
cell.makeSugar(sugarAmount, sugarGrowBackRate, sugarGrowBackInterval);
cell.makeCircle(getGroup(), getWorldSize()/getDimension(), i, j);
if(doConfigCell(agentXTag, agentYTag, i, j)){
int maxAge = (int) (Math.random() * 59) + 1 + lowerBoundAge;
cell.makeAgent(vision, sugarAgent, sugarMetabolism, maxAge, maxAge = fertileLimitCutoff);
}
}
}
}
} | true |
8f1cbb1725e854df841c6ba823b8dd49b4ff99a5 | Java | Nomcebo/MonitorWebPlatformRepo | /MonitorWebPlatform002/src/java/com/boha/monitor/dto/TaskDTO.java | UTF-8 | 2,265 | 2.25 | 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.boha.monitor.dto;
import com.boha.monitor.data.Task;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author aubreyM
*/
public class TaskDTO implements Serializable {
private static final long serialVersionUID = 1L;
private Integer taskID, companyID, taskNumber;
private String taskName;
private String description;
private List<TaskPriceDTO> taskPriceList = new ArrayList<>();
private List<SubTaskDTO> subTaskList;
public TaskDTO() {
}
public TaskDTO(Task a) {
this.taskID = a.getTaskID();
this.taskName = a.getTaskName();
this.description = a.getDescription();
this.companyID = a.getCompany().getCompanyID();
this.taskNumber = a.getTaskNumber();
if (a.getSubTaskList() != null) {
}
}
public List<SubTaskDTO> getSubTaskList() {
return subTaskList;
}
public void setSubTaskList(List<SubTaskDTO> subTaskList) {
this.subTaskList = subTaskList;
}
public List<TaskPriceDTO> getTaskPriceList() {
return taskPriceList;
}
public void setTaskPriceList(List<TaskPriceDTO> taskPriceList) {
this.taskPriceList = taskPriceList;
}
public Integer getCompanyID() {
return companyID;
}
public void setCompanyID(Integer companyID) {
this.companyID = companyID;
}
public Integer getTaskNumber() {
return taskNumber;
}
public void setTaskNumber(Integer taskNumber) {
this.taskNumber = taskNumber;
}
public Integer getTaskID() {
return taskID;
}
public void setTaskID(Integer taskID) {
this.taskID = taskID;
}
public String getTaskName() {
return taskName;
}
public void setTaskName(String taskName) {
this.taskName = taskName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
| true |
3c7ee31cef640e1f74686fc771764c97aa56528c | Java | ramanaganesh0008/newJavaProgram | /NewjavaProgram/src/com/objectorientedprograms/RegexExpresson.java | UTF-8 | 614 | 2.578125 | 3 | [] | no_license | package com.objectorientedprograms;
public class RegexExpresson {
public static void main(String[] args) {
Utility u=new Utility();
UserDetails user=new UserDetails();
System.out.println("enter the first name");
user.setFname(u.inputString());
System.out.println("enter the last name");
user.setLname(u.inputString());
System.out.println("enter the mobile num");
user.setMobileNum(u.inputString());
System.out.println("enter the date");
user.setDate(u.inputString());
user.setDate(u.formatDate(user.getDate()));
System.out.println(u.convertString(user,u.getFileText()));
}
}
| true |
50025085ad8c4ebe142a757d2cd4f4ec3dcd5210 | Java | marekkalkowski/XmlParseRecruitmentTask | /src/main/java/com/merapar/interviewtask/InterviewApplication.java | UTF-8 | 416 | 1.742188 | 2 | [] | no_license | package com.merapar.interviewtask;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
@SpringBootApplication
public class InterviewApplication {
public static void main(String[] args) {
ApplicationContext cfx = SpringApplication.run(InterviewApplication.class, args);
}
}
| true |
62ba8ad73a65acc63fe91e93f664d34ba9dd14ae | Java | LIAN1988/freeline | /android-studio-plugin/src/actions/BaseAction.java | UTF-8 | 1,829 | 2.25 | 2 | [
"BSD-3-Clause"
] | permissive | package actions;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.project.Project;
import utils.NotificationUtils;
import java.io.File;
/**
* Created by pengwei on 16/9/11.
*/
public abstract class BaseAction extends AnAction {
protected Project currentProject;
protected File projectDir;
protected AnActionEvent anActionEvent;
@Override
public final void actionPerformed(AnActionEvent anActionEvent) {
saveDocument();
this.anActionEvent = anActionEvent;
this.currentProject = DataKeys.PROJECT.getData(anActionEvent.getDataContext());
this.projectDir = new File(currentProject.getBasePath());
actionPerformed();
}
private void saveDocument() {
FileDocumentManager.getInstance().saveAllDocuments();
ApplicationManager.getApplication().saveSettings();
}
public abstract void actionPerformed();
/**
* 检查Freeline是否存在
*
* @return
*/
protected boolean checkFreelineExist() {
File pyFile = new File(projectDir, "freeline.py");
if (pyFile.exists()) {
return true;
}
NotificationUtils.errorNotification("please install Freeline first");
return false;
}
/**
* 异步执行
*
* @param runnable
*/
protected void asyncTask(Runnable runnable) {
ApplicationManager.getApplication().executeOnPooledThread(runnable);
}
protected void invokeLater(Runnable runnable) {
ApplicationManager.getApplication().invokeLater(runnable);
}
}
| true |
8c769decb27d85cfd61b43e114d67322845d0e73 | Java | sukrupa/school-admin | /src/main/java/org/sukrupa/app/httpcommunicationservices/StudentsImageController.java | UTF-8 | 1,197 | 2.15625 | 2 | [] | no_license | package org.sukrupa.app.httpcommunicationservices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.View;
import org.sukrupa.app.services.StudentImageRepository;
import org.sukrupa.app.students.image.StudentImageController;
import java.io.FileNotFoundException;
@Controller
@RequestMapping("/getstudentimage")
public class StudentsImageController {
private StudentImageRepository studentImageRepository;
private org.sukrupa.app.students.image.StudentImageController studentImageController;
@Autowired
public StudentsImageController(StudentImageRepository studentImageRepository) {
this.studentImageRepository = studentImageRepository;
studentImageController = new org.sukrupa.app.students.image.StudentImageController(studentImageRepository);
}
@RequestMapping(value = "{id}/image")
public View getImage(@PathVariable String id) throws FileNotFoundException {
return studentImageController.getImage(id);
}
}
| true |
7bb568f397c229dba86aec3480b9ceffb956b777 | Java | chacanthus/ymt2-neo | /decompiled_java/com/badlogic/gdx/scenes/scene2d/actions/MoveToAction.java | UTF-8 | 1,476 | 2.421875 | 2 | [] | no_license | // 도박중독 예방 캠페인
// 당신 곁에 우리가 있어요!
// 감당하기 힘든 어려움을 혼자 견디고 계신가요?
// 무엇을 어떻게 해야 할지 막막한가요?
// 당신의 이야기를 듣고 도움을 줄 수 있는 정보를 찾아 드립니다.
// - 한국도박문제관리센터 (국번없이 1336, 24시간)
// - KL중독관리센터 (전화상담 080-7575-535/545)
// - 사행산업통합감독위원회 불법사행산업감시신고센터 (전화상담 1588-0112)
// - 불법도박 등 범죄수익 신고 (지역번호 + 1301)
package com.badlogic.gdx.scenes.scene2d.actions;
public class MoveToAction extends TemporalAction {
private float endX;
private float endY;
private float startX;
private float startY;
public MoveToAction() {
super();
}
protected void begin() {
this.startX = this.actor.getX();
this.startY = this.actor.getY();
}
public float getX() {
return this.endX;
}
public float getY() {
return this.endY;
}
public void setPosition(float x, float y) {
this.endX = x;
this.endY = y;
}
public void setX(float x) {
this.endX = x;
}
public void setY(float y) {
this.endY = y;
}
protected void update(float percent) {
this.actor.setPosition(this.startX + (this.endX - this.startX) * percent, this.startY + (this.endY - this.startY) * percent);
}
}
| true |
d23a8fe4d2cf8079104cb337f6e2e2155cfa174c | Java | balvindersingh1404/MRBS | /app/src/main/java/com/example/roombooking/roombooking/models/ApiResponse.java | UTF-8 | 795 | 2.390625 | 2 | [] | no_license | package com.example.roombooking.roombooking.models;
import java.util.ArrayList;
import java.util.List;
public class ApiResponse {
String message;
int status;
Data data;
private List<Data> datum = new ArrayList<Data>();
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
public List<Data> getDatum() {
return datum;
}
public void setDatum(List<Data> datum) {
this.datum = datum;
}
} | true |
72ffda8e25bcac12b1e6f95f2b30751293ba1afd | Java | killiandonnegan/Hangman | /Game.java | WINDOWS-1252 | 10,831 | 3.953125 | 4 | [] | no_license | import java.util.*;
import java.io.*;
class Game
{
public static void main(String args[])
{
char[] letters = Word(); //char array of letters
Play(letters); //calls play method with letters array as parameter
}
public static char[] Word() //selects random word, returns array of its characters
{
Dictionary Dictionary = new Dictionary(); //creates dictionary object
int size = Dictionary.getSize();
Random random = new Random(); //instance of the random class
int wordPosition = random.nextInt(size); //gets random position/index in the dictionary
String word = Dictionary.getWord(wordPosition); //gets word at that position/index
char[] letters = new char[word.length()]; //char array to store letters of the randomly selected word
for(int i = 0; i<letters.length; i++)
{
letters[i] = word.charAt(i); //fills array with characters
}
boolean hasLetters = false; //used to determine if the input has letters
//I chose to have my game only use strings that have at least one letter,
//A few of the words in the words.txt file have no letters which would be hard to guess
while(hasLetters == false) //while current word has no letters
{
for(int i = 0; i<letters.length; i++) //checks if word has any letters
{
if(Character.isLetter(letters[i])) //if it does sets boolean to true
{
hasLetters = true;
}
}
if(hasLetters == false) //if it doesn't have letters,
{
letters = Word(); //gets a new word
}
}
return letters; //returns this array
}
public static void Play(char[] letters) //majority of the game code
{
Scanner scan = new Scanner(System.in); //creates scanner
int length = letters.length; //length of word
char[] blanks = new char[length]; //char array to compare against characters of the word
for(int i = 0; i<length-1; i++)
{
if(Character.isLetter(letters[i]))
{
blanks[i] = '_'; //fills the positions where there is letters with underscores
}
else
{
blanks[i] = letters[i]; //if there is not a letter in the position, fill the blanks array with whatever is in the that position
}
}
//tells the player how the game works
System.out.println("Welcome to my recreation of Hangman in java.");
System.out.println(); //so the screen isn't cluttered
System.out.println("A random word has been selected for you from the 'words.txt' file.");
System.out.println("The word is "+length+ " characters long.");
System.out.println("You must guess the letters you think are in the word.");
System.out.println("For each wrong letter you guess you will lose a life.");
int lives = 7; //number of lives the player has
System.out.println(); //so the screen isn't cluttered
boolean gameOver = false; //if game is in progress or finished
while(!gameOver) //while game is in progress
{
System.out.println("Lives: "+lives); //before each guess display the amount of lives the player has and
System.out.println("The word is:"); //the word including their previous correct guesses
for(int i = 0; i<length-1; i++)
{
System.out.print(blanks[i]+" ");
}
System.out.println(); //so the screen isn't cluttered
System.out.println(); //so the screen isn't cluttered
System.out.println("Guess a letter.");
boolean validinput = false;
char input = scan.next().charAt(0); //inputted character
while(validinput == false) //ensures the user enters a letter
{
if(Character.isLetter(input))
{
validinput = true;
}
else //if they do not enter a letter, they are prompted to enter a letter again until they do so
{
System.out.println("Invalid input. Please enter a letter.");
input = scan.next().charAt(0);
}
}
int count = 0; //keeps track of how many times the guessed letter appears in the word
for(int i = 0; i<length-1; i++)
{
char inputCapital = Character.toUpperCase(input); //character the user inputted
char lettersCapital = Character.toUpperCase(letters[i]); //char at position i in word
if(lettersCapital == inputCapital) //if the inputted letter is in the word
{
blanks[i] = letters[i]; //put the letter in that position in blanks array
count++; //increase count if the letter is found in word
}
}
if(count == 1) //if letter is contained in the word once
{
System.out.println(" ");
System.out.println("This letter is contained once in the word.");
System.out.println(" ");
}
else if(count > 1) //if letter is contained in the word more than once
{
System.out.println(" ");
System.out.println("This letter is contained "+count+" times in the word.");
System.out.println(" ");
}
else //if letter is not contained 0 times in the word
{
System.out.println(" "); //so the screen isn't cluttered
System.out.println("This letter is not contained in the word.");
System.out.println(" "); //so the screen isn't cluttered
lives--;
}
Picture(lives); //picture method draws a hangman picture corresponding to the number of lives
if(lives==0) //if the player runs out of lives
{
System.out.println("Game Over.");
System.out.println("The word was:"); //shows what the word was
System.out.println(letters);
System.out.println(" "); //so the screen isn't cluttered
gameOver = true;
}
boolean same = true; //to store whether the blanks and letters array have equal values
//a.k.a if the player has won
for(int i = 0; i<letters.length-1; i++)
{
if(blanks[i] != letters[i])
{
same = false; //if at any index their values are not equal set same to false
}
}
if(same == true) //if they are the same, the user has won
{
System.out.println("Well done! You have successfully guessed the word:");
System.out.println(letters);
gameOver = true;
}
if(gameOver) //if the game is over
{
System.out.println("Would you like to play again? If so enter 'Y'."); //ask do they want to play again
char s = scan.next().charAt(0);
if(s == 'Y'||s=='y') //if they want to
{
System.out.println(""); //so the screen isn't cluttered
System.out.println(""); //so the screen isn't cluttered
System.out.println(""); //so the screen isn't cluttered
main(null); //calls main, which calls word and play and essentially runs the program again
}
else
{
System.out.println("Thanks for playing."); //if they dont say yes
}
}
}
}
public static void Picture(int lives) //prints to the screen the stage of the hangman corresponding to how many lives you have
{
if(lives==6) //6 lives
{
System.out.println();
System.out.println();
System.out.println();
System.out.println("______");
}
else if(lives == 5) //5 lives
{
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" | ");
System.out.println("___|___");
}
else if(lives==4) //4 lives
{
System.out.println(" -------");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" | ");
System.out.println("___|___");
}
else if(lives ==3) //3 lives
{
System.out.println(" -------");
System.out.println(" | O ");
System.out.println(" | ");
System.out.println(" | ");
System.out.println("___|___");
}
else if(lives ==2) //2 lives
{
System.out.println(" -------");
System.out.println(" | O ");
System.out.println(" | | ");
System.out.println(" | ");
System.out.println("___|___");
}
else if(lives ==1) //1 life
{
System.out.println(" -------");
System.out.println(" | O ");
System.out.println(" | /|\\ ");
System.out.println(" | ");
System.out.println("___|___");
}
else if(lives==0) //0 lives
{
System.out.println(" -------");
System.out.println(" | O ");
System.out.println(" | -|- ");
System.out.println(" | / \\");
System.out.println("___|___");
}
}
}
class Dictionary //given dictionary class
{
private String input[];
public Dictionary()
{
input = load("D://words.txt"); //change to wherever the file is stored on the machine you are on
}
public int getSize()
{
return input.length;
}
public String getWord(int n)
{
return input[n];
}
public String[] load(String file)
{
File aFile = new File(file);
StringBuffer contents = new StringBuffer();
BufferedReader input = null;
try {
input = new BufferedReader( new FileReader(aFile) );
String line = null;
int i = 0;
while (( line = input.readLine()) != null)
{
contents.append(line);
i++;
contents.append(System.getProperty("line.separator"));
}
}
catch (FileNotFoundException ex)
{
System.out.println("Can't find the file - are you sure the file is in this location: "+file);
ex.printStackTrace();
}
catch (IOException ex)
{
System.out.println("Input output exception while processing file");
ex.printStackTrace();
}
finally
{
try
{
if (input!= null)
{
input.close();
}
}catch (IOException ex)
{
System.out.println("Input output exception while processing file");
ex.printStackTrace();
}
}
String[] array = contents.toString().split("\n");
for(String s: array)
{
s.trim();
}
return array;
}
} | true |
d996294f51ec3d6640152f501b47112d33e4d9da | Java | Issac123abc/mygit | /dxg/dxg-parent/dxg-getway/src/main/java/com/xinjing/dxg/handler/AuthFilter.java | UTF-8 | 2,275 | 2.078125 | 2 | [] | no_license | package com.xinjing.dxg.handler;
import java.net.URI;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import com.xinjing.dxg.common.ApiResponse;
import com.xinjing.dxg.common.utils.StringUtil;
import com.xinjing.dxg.handler.common.AntUrlPathMatcher;
import com.xinjing.dxg.handler.common.utils.RedisUtil;
import com.xinjing.dxg.handler.common.utils.ResponseUtil;
import com.xinjing.dxg.handler.constant.FilterConstant;
import reactor.core.publisher.Mono;
/**
* 全局过滤器
* */
@Component
public class AuthFilter implements GlobalFilter, Ordered {
public final static String ATTRIBUTE_IGNORE_FILTER = "IgnoreFilter";
@Autowired
private AntUrlPathMatcher antUrlPathMatcher;
@Override
public int getOrder() {
return 100;
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
// 配置了IgnoreFilter过滤器的路径跳过检测
URI uri = exchange.getRequest().getURI();
String path = uri.getPath();
if (match(path)) {
return chain.filter(exchange);
}
String token = exchange.getRequest().getQueryParams().getFirst("token");
ApiResponse<String> apiResponse = null;
if (StringUtil.isBlank(token)) {
apiResponse = ApiResponse.buildRep(401, "Unauthorized", "没有权限");
return ResponseUtil.response(apiResponse, exchange);
} else {
String userId = RedisUtil.get(token);
if (StringUtil.isBlank(userId)) {
apiResponse = ApiResponse.buildRep(401, "Unauthorized", "没有权限");
return ResponseUtil.response(apiResponse, exchange);
} else {
RedisUtil.set(token, userId, 60000 * 30); // 续期30min
}
}
return chain.filter(exchange);
}
public boolean match(String url) {
List<String> authNotFilter = FilterConstant.authNotFilter;
boolean contains = authNotFilter.stream().map(s -> antUrlPathMatcher.pathMatchesUrl(s, url))
.collect(Collectors.toSet()).contains(true);
return contains;
}
}
| true |
92da7a6a1d41d8c7b0a7bb5a9f33e5f832cadd84 | Java | ssunku/SpringBootDemo | /src/main/java/com/springboot/demo/model/TestPlanResults.java | UTF-8 | 1,904 | 1.992188 | 2 | [] | no_license | package com.springboot.demo.model;
import java.util.concurrent.TimeUnit;
public class TestPlanResults {
private String planid;
private String planname;
private String createdtime;
private String endtime;
private String executiontime;
private String passcount;
private String failcount;
private String skipcount;
private String totaltests;
public String getPlanid() {
return planid;
}
public void setPlanid(String planid) {
this.planid = planid;
}
public String getPlanname() {
return planname;
}
public void setPlanname(String planname) {
this.planname = planname;
}
public String getCreatedtime() {
return createdtime;
}
public void setCreatedtime(String createdtime) {
this.createdtime = createdtime;
}
public String getEndtime() {
return endtime;
}
public void setEndtime(String endtime) {
this.endtime = endtime;
}
public String getExecutiontime() {
return executiontime;
}
public void setExecutiontime(String executiontime) {
Long l=TimeUnit.MILLISECONDS.toMinutes(Long.valueOf(executiontime));
this.executiontime = l.toString();
}
public String getPasscount() {
return passcount;
}
public void setPasscount(String passcount) {
this.passcount = passcount;
}
public String getFailcount() {
return failcount;
}
public void setFailcount(String failcount) {
this.failcount = failcount;
}
public String getSkipcount() {
return skipcount;
}
public void setSkipcount(String skipcount) {
this.skipcount = skipcount;
}
public String getTotaltests() {
return totaltests;
}
public void setTotaltests(String totaltests) {
this.totaltests = totaltests;
}
}
| true |
08af6cc6cde1f38659e750c19d803ce5ffa718e7 | Java | vo0a/bithumb-tech-spring-boot-webflux | /src/main/java/com/romkudev/api/quiz/service/QuizService.java | UTF-8 | 399 | 1.75 | 2 | [] | no_license | package com.romkudev.api.quiz.service;
import com.romkudev.api.quiz.domain.Attempt;
import com.romkudev.api.quiz.domain.Quiz;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public interface QuizService {
Mono<Quiz> createQuiz();
boolean checkAttempt(Attempt attempt);
Flux<Attempt> getStatsForUser(String alias);
Mono<Attempt> getResultById(long id);
}
| true |
d11dd7997a77030558ffc953187db2904f4fb984 | Java | cynhh40061/ctt | /CTT02PF/src/main/java/tw/com/ctt/dao/impl/MemberBetDaoImpl.java | UTF-8 | 23,392 | 1.859375 | 2 | [] | no_license | package tw.com.ctt.dao.impl;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONObject;
import tw.com.ctt.dao.IMemberBetDao;
import tw.com.ctt.model.MemBean;
import tw.com.ctt.model.PunchGameRecordsBean;
import tw.com.ctt.util.CalculateMemberRatio;
import tw.com.ctt.util.ShowLog;
import tw.com.ctt.util.StmtUtil;
public class MemberBetDaoImpl extends BaseDao implements IMemberBetDao {
/**
*
*/
private static final long serialVersionUID = -5393598519122647798L;
private static final Logger LOG = LogManager.getLogger(MemberBetDaoImpl.class.getName());
public void writeCommit() {
try {
if (this.WRITE_CONN == null || this.WRITE_CONN.isClosed()) {
LOG.debug("no connection");
} else {
this.WRITE_CONN.commit();
this.WRITE_CONN.setAutoCommit(true);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void writeRollback() {
try {
if (this.WRITE_CONN == null || this.WRITE_CONN.isClosed()) {
LOG.debug("no connection");
} else {
this.WRITE_CONN.rollback();
this.WRITE_CONN.setAutoCommit(true);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public boolean cancleAllPeriodOrder(long accId, long periodNum, int localId) {
Map<String, Object> insertMap = new ConcurrentHashMap<String, Object>();
try {
this.checkWrite();
if (this.WRITE_CONN == null || this.WRITE_CONN.isClosed()) {
LOG.debug("no connection");
return false;
} else {
this.WRITE_CONN.setAutoCommit(false);
List<Object> selectObj = new ArrayList<Object>();
String sql = "CALL `ctt_manager`.`cancle_bet_by_period`(? ,?)";
selectObj.add(periodNum);
selectObj.add(localId);
StmtUtil.callStored(this.WRITE_CONN, sql, selectObj);
selectObj.clear();
this.WRITE_CONN.setAutoCommit(true);
return true;
}
} catch (Exception e) {
LOG.info("cancleAllPeriodOrder_Exception===" + e);
return false;
} finally {
if (insertMap != null) {
insertMap.clear();
insertMap = null;
}
}
}
@Override
public boolean cancleMainOrder(long accId, long periodNum, int localId, long mainOrderId) {
Map<String, Object> insertMap = new ConcurrentHashMap<String, Object>();
try {
this.checkWrite();
if (this.WRITE_CONN == null || this.WRITE_CONN.isClosed()) {
LOG.debug("no connection");
return false;
} else {
this.WRITE_CONN.setAutoCommit(false);
List<Object> selectObj = new ArrayList<Object>();
String sql = "CALL `ctt_manager`.`cancle_bet_by_main_order`(? ,? ,?,'3')";
selectObj.add(periodNum);
selectObj.add(localId);
selectObj.add(mainOrderId);
StmtUtil.callStored(this.WRITE_CONN, sql, selectObj);
selectObj.clear();
this.WRITE_CONN.setAutoCommit(true);
return true;
}
} catch (Exception e) {
LOG.info("cancleMainOrder_Exception===" + e);
return false;
} finally {
if (insertMap != null) {
insertMap.clear();
insertMap = null;
}
}
}
@Override
public boolean cancleMidOrder(long accId, long periodNum, int localId, long mainOrderId) {
Map<String, Object> insertMap = new ConcurrentHashMap<String, Object>();
try {
this.checkWrite();
if (this.WRITE_CONN == null || this.WRITE_CONN.isClosed()) {
LOG.debug("no connection");
return false;
} else {
this.WRITE_CONN.setAutoCommit(false);
List<Object> selectObj = new ArrayList<Object>();
String sql = "CALL `ctt_manager`.`cancle_bet_by_mid_order`(? ,? ,?)";
selectObj.add(periodNum);
selectObj.add(localId);
selectObj.add(mainOrderId);
StmtUtil.callStored(this.WRITE_CONN, sql, selectObj);
selectObj.clear();
this.WRITE_CONN.setAutoCommit(true);
return true;
}
} catch (Exception e) {
LOG.info("cancleMidOrder_Exception===" + e);
return false;
} finally {
if (insertMap != null) {
insertMap.clear();
insertMap = null;
}
}
}
@Override
public long insertMainOrder(long accId, long startPeriodNum, long stopPeriodNum, String betData, long noOfPeriod, int localId, long minAuthId,
Date actionTime, BigDecimal amount, BigDecimal moneyUnit, int orderType, int handiCap, int bonusSetRatio, int noOfWinningPeriod,
int orderStatus, BigDecimal betRatio, boolean isDt, String dateOfTable, long totalNoOfBet) {
Map<String, Object> insertMap = new ConcurrentHashMap<String, Object>();
long orderId = 0;
try {
this.checkWrite();
if (this.WRITE_CONN == null || this.WRITE_CONN.isClosed()) {
LOG.debug("no connection");
return 0;
} else {
this.WRITE_CONN.setAutoCommit(false);
insertMap.put("acc_id", accId);
insertMap.put("start_period_num", startPeriodNum);
insertMap.put("stop_period_num", stopPeriodNum);
insertMap.put("bet_data", betData);
insertMap.put("no_of_period", noOfPeriod);
insertMap.put("game_id", localId);
insertMap.put("played_id", minAuthId);
insertMap.put("action_time", actionTime);
insertMap.put("amount", amount);
insertMap.put("money_unit", moneyUnit);
insertMap.put("order_type", orderType);
insertMap.put("order_status", orderStatus);
insertMap.put("bonus_set_ratio", bonusSetRatio);
insertMap.put("handi_cap", handiCap);
insertMap.put("bet_ratio", betRatio);
insertMap.put("is_dt", isDt);
orderId = StmtUtil.insertNoCommitByMap(this.WRITE_CONN, "ctt_manager.main_order_" + dateOfTable, insertMap);
if (orderId > 0) {
List<Object> selectObj = new ArrayList<Object>();
selectObj = new ArrayList<Object>();
String sql = "update `ctt_manager`.`ctt_member_acc` set balance = balance - ? where acc_id = ?";
selectObj.add(amount);
selectObj.add(accId);
StmtUtil.update(this.WRITE_CONN, sql, selectObj);
selectObj = null;
selectObj = new ArrayList<Object>();
sql = "INSERT INTO `ctt_manager`.`ctt_lottery_member_money_transfer_record`(acc_id,acc_name, balance, start_period_num, stop_period_num,local_id,played_id,record_order_type,money)(SELECT acc_id, acc_name, balance, ?, ? ,?, ?, ?, ? from `ctt_manager`.`ctt_member_acc` where acc_id=?)";
selectObj.add(startPeriodNum);
selectObj.add(stopPeriodNum);
selectObj.add(localId);
selectObj.add(minAuthId);
if (startPeriodNum != stopPeriodNum) {
selectObj.add("2"); // 追�???��
} else {
selectObj.add("1"); // ?�注??��
}
selectObj.add(amount);
selectObj.add(accId);
StmtUtil.insertNoCommit(this.WRITE_CONN, sql, selectObj);
this.WRITE_CONN.commit();
} else {
this.WRITE_CONN.rollback();
}
this.WRITE_CONN.setAutoCommit(true);
}
return orderId;
} catch (Exception e) {
orderId = 0;
LOG.info("insertMainOrder_Exception===" + e);
} finally {
if (insertMap != null) {
insertMap.clear();
insertMap = null;
}
}
return orderId;
}
@Override
public boolean insertMidOrder(long mainId, long midId, long accId, long periodNum, int localId, long minAuthId, BigDecimal amount,
BigDecimal fanDen, int orderType, long noOfBet, int orderStatus, String dateOfTable, BigDecimal maxBonus, long noOfBetTimes) {
Map<String, Object> insertMap = new ConcurrentHashMap<String, Object>();
try {
this.checkWrite();
if (this.WRITE_CONN == null || this.WRITE_CONN.isClosed()) {
LOG.debug("no connection");
return false;
} else {
this.WRITE_CONN.setAutoCommit(false);
insertMap.put("main_order_id", mainId);
insertMap.put("mid_order_id", midId);
insertMap.put("acc_id", accId);
insertMap.put("period_num", periodNum);
insertMap.put("game_id", localId);
insertMap.put("played_id", minAuthId);
insertMap.put("amount", amount);
insertMap.put("no_of_bet", noOfBet);
insertMap.put("max_bonus", maxBonus);
insertMap.put("no_of_bet_times", noOfBetTimes);
insertMap.put("order_status", orderStatus);
long count = StmtUtil.insertNoCommitByMap(this.WRITE_CONN, "ctt_manager.mid_order_" + dateOfTable, insertMap);
if (count == -1) {
return true;
}
}
} catch (Exception e) {
LOG.info("insertMidOrder_Exception===" + e);
return false;
} finally {
if (insertMap != null) {
insertMap.clear();
insertMap = null;
}
}
return false;
}
@Override
public boolean insertBetOrder(List<Map<String, Object>> subOrderList, String dateOfTable) {
LOG.debug("checkMemType");
StringBuilder sb = null;
PreparedStatement ps = null;
try {
sb = new StringBuilder();
this.checkRead();
if (this.WRITE_CONN == null || this.WRITE_CONN.isClosed()) {
// no connection
LOG.debug("CONNECTION IS NULL");
return false;
} else {
sb.append("INSERT INTO ctt_manager.bet_order_" + dateOfTable
+ " (main_order_id, mid_order_id, sub_order_id, acc_id, period_num, bet_data, game_id, played_id, amount, no_of_bet, order_status, bonus, baseline) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
if (this.WRITE_CONN.getAutoCommit()) {
this.WRITE_CONN.setAutoCommit(false);
}
ps = this.WRITE_CONN.prepareStatement(sb.toString());
int leaveCount = 0;
for (int i = 0; i < subOrderList.size(); i++) {
leaveCount++;
ps.setLong(1, (long) subOrderList.get(i).get("main_order_id"));
ps.setInt(2, (int) subOrderList.get(i).get("mid_order_id"));
ps.setInt(3, (int) subOrderList.get(i).get("sub_order_id"));
ps.setLong(4, (long) subOrderList.get(i).get("acc_id"));
ps.setLong(5, (long) subOrderList.get(i).get("period_num"));
ps.setString(6, (String) subOrderList.get(i).get("bet_data"));
ps.setInt(7, (int) subOrderList.get(i).get("game_id"));
ps.setLong(8, (long) subOrderList.get(i).get("played_id"));
ps.setBigDecimal(9, ((BigDecimal) subOrderList.get(i).get("amount")).setScale(2, BigDecimal.ROUND_DOWN));
ps.setLong(10, (long) subOrderList.get(i).get("no_of_bet"));
ps.setInt(11, (int) subOrderList.get(i).get("order_status"));
ps.setBigDecimal(12, ((BigDecimal) subOrderList.get(i).get("bonus")).setScale(2, BigDecimal.ROUND_DOWN));
ps.setBigDecimal(13, ((BigDecimal) subOrderList.get(i).get("baseline")).setScale(7, BigDecimal.ROUND_DOWN));
ps.addBatch();
if ((i + 1) % 500 == 0) {
leaveCount = 0;
int[] result2 = ps.executeBatch();
int cou2 = 0;
for (int j = 0; j < result2.length; j++) {
cou2 += result2[j];
}
if (result2.length != cou2) {
return false;
}
}
}
if (leaveCount != 0) {
int[] result = ps.executeBatch();
int cou = 0;
for (int i = 0; i < result.length; i++) {
cou += result[i];
}
if (result.length == cou) {
return true;
}
} else {
return true;
}
}
} catch (Exception e) {
LOG.info("Exception, " + e.getMessage());
ShowLog.err(LOG, e);
return false;
} finally {
if (sb != null) {
sb.setLength(0);
sb = null;
}
if (ps != null) {
try {
if (!ps.isClosed()) {
ps.close();
}
} catch (SQLException e) {
LOG.info("SQLException, " + e.getMessage());
ShowLog.err(LOG, e);
}
}
}
return false;
}
private String getMapString(Map<String, Object> map, String key) {
if (!map.keySet().contains(key) || map.get(key) == null) {
return "";
} else {
return "" + map.get(key);
}
}
@Override
public Map<String, Object> getMemMoney(long accId) {
StringBuilder sb = null;
List<Object> selectObj = null;
Map<String, Object> result = null;
List<Map<String, Object>> listMap = null;
try {
sb = new StringBuilder();
selectObj = new ArrayList<Object>();
result = new ConcurrentHashMap<String, Object>();
listMap = new ArrayList<Map<String, Object>>();
this.checkRead();
if (this.READ_CONN == null || this.READ_CONN.isClosed()) {
// no connection
LOG.debug("CONNECTION IS NULL");
return result;
} else {
sb.append("SELECT \n");
sb.append("acc_id,acc_name, balance \n");
sb.append("FROM \n");
sb.append("ctt_manager.ctt_member_acc WHERE acc_id = ? \n");
selectObj.add(accId);
listMap = StmtUtil.queryToMap(this.READ_CONN, sb.toString(), selectObj);
for (int i = 0; i < listMap.size(); i++) {
for (Object key : listMap.get(i).keySet()) {
result.put(key.toString(), listMap.get(i).get(key.toString()));
}
}
}
} catch (Exception e) {
LOG.info("Exception, " + e.getMessage());
ShowLog.err(LOG, e);
} finally {
if (listMap != null) {
listMap.clear();
listMap = null;
}
if (selectObj != null) {
selectObj.clear();
selectObj = null;
}
if (sb != null) {
sb.setLength(0);
sb = null;
}
}
return result;
}
@Override
public MemBean getAccDetailsForLog(long accId) {
StringBuilder sb = null;
List<Object> param = null;
List<Object> list = null;
MemBean bean = new MemBean();
try {
sb = new StringBuilder();
param = new ArrayList<Object>();
list = new ArrayList<Object>();
this.checkRead();
if (this.READ_CONN == null || this.READ_CONN.isClosed()) {
// no connection
LOG.debug("CONNECTION IS NULL");
return null;
} else {
sb.append("SELECT \n");
sb.append("member_real_name \n");
sb.append(",phone_number \n");
sb.append(",qq_acc \n");
sb.append(",wechat_acc \n");
sb.append(",(SELECT nickname FROM ctt_manager.ctt_member_acc WHERE acc_id = ?) AS nickname \n");
param.add(accId);
sb.append("FROM \n");
sb.append("ctt_manager.ctt_member_basic_setting \n");
sb.append("WHERE \n");
sb.append("acc_id = ? \n");
param.add(accId);
list = StmtUtil.queryToBean(this.READ_CONN, sb.toString(), param, bean);
if (list.size() == 1) {
bean = (MemBean) list.get(0);
}
}
} catch (Exception e) {
bean = null;
LOG.info("Exception, " + e.getMessage());
ShowLog.err(LOG, e);
} finally {
if (param != null) {
param = new ArrayList<Object>();
param = null;
}
if (sb != null) {
sb.setLength(0);
sb = null;
}
if (list != null) {
list.clear();
list = null;
}
}
return bean;
}
@Override
public Map<String, Object> searchRecordsTotle(long accId, String startTime, String endTime) {
StringBuilder sb = null;
List<Object> params = null;
List<Map<String, Object>> tmpMap = null;
Map<String, Object> map = null;
try {
sb = new StringBuilder();
params = new ArrayList<Object>();
this.checkRead();
if (this.READ_CONN == null || this.READ_CONN.isClosed()) {
LOG.debug("CONNECTION IS NULL");
return map;
} else {
sb.append("SELECT \n");
sb.append("COUNT(1) AS count \n");
sb.append(",SUM(A.bet) AS totleBet \n");
sb.append(",SUM(A.winGoal) AS totleWinGoal \n");
sb.append(",(SUM(A.bet)+SUM(A.winGoal)) AS totleNetAmount \n");
sb.append("FROM \n");
sb.append("( \n");
sb.append("SELECT \n");
sb.append(" p1_acc_id AS acc_id \n");
sb.append(" ,bet \n");
sb.append(" ,p1_acc_win_goal AS winGoal \n");
sb.append("FROM \n");
sb.append(" ctt_manager.ctt_game_punche_records \n");
sb.append("WHERE \n");
sb.append(" (start_time > DATE_FORMAT(?,'%Y/%m/%d %T.%f') && start_time < DATE_FORMAT(?,'%Y/%m/%d %T.%f')) \n");
params.add(startTime);
params.add(endTime);
sb.append(" AND p1_acc_id = ? \n");
params.add(accId);
sb.append("UNION ALL \n");
sb.append("SELECT \n");
sb.append(" p2_acc_id AS acc_id \n");
sb.append(" ,bet \n");
sb.append(" ,p2_acc_win_goal AS winGoal \n");
sb.append("FROM \n");
sb.append(" ctt_manager.ctt_game_punche_records \n");
sb.append("WHERE \n");
sb.append(" (start_time > DATE_FORMAT(?,'%Y/%m/%d %T.%f') && start_time < DATE_FORMAT(?,'%Y/%m/%d %T.%f')) \n");
params.add(startTime);
params.add(endTime);
sb.append(" AND p2_acc_id = ? \n");
params.add(accId);
sb.append(")A \n");
tmpMap = StmtUtil.queryToMap(READ_CONN, sb.toString(), params);
if (tmpMap.size() == 1 && Integer.parseInt(tmpMap.get(0).get("count").toString()) > 0) {
map = tmpMap.get(0);
}
}
} catch (Exception e) {
tmpMap = null;
LOG.debug("Exception, " + e.getMessage());
ShowLog.err(LOG, e);
} finally {
if (params != null) {
params.clear();
params = null;
}
if (sb != null) {
sb.setLength(0);
sb = null;
}
if (tmpMap != null) {
tmpMap.clear();
tmpMap = null;
}
}
return map;
}
@Override
public List<Map<String, Object>> searchRecords(long accId, String accName, String startTime, String endTime, int firstCount, int count) {
StringBuilder sb = null;
List<Object> params = null;
List<Object> list = null;
Map<String, Object> tmpMap = null;
List<Map<String, Object>> tmpMapList = null;
try {
sb = new StringBuilder();
params = new ArrayList<Object>();
this.checkRead();
tmpMapList = new ArrayList<Map<String, Object>>();
if (this.READ_CONN == null || this.READ_CONN.isClosed()) {
LOG.debug("CONNECTION IS NULL");
return null;
} else {
sb.append("SELECT \n");
sb.append(" game_id,server_id \n");
sb.append(" ,p1_acc_id AS acc_id \n");
sb.append(" ,start_time,end_time \n");
sb.append(" ,bet,p1_acc_start_balance AS acc_start_balance \n");
sb.append(" ,p1_acc_win_goal AS acc_win_goal \n");
sb.append(" ,game_process \n");
sb.append(" ,game_type, \n");
sb.append(" CASE WHEN result = 0 THEN TRUE ELSE FALSE END AS result \n");
sb.append("FROM \n");
sb.append(" ctt_manager.ctt_game_punche_records \n");
sb.append("WHERE \n");
sb.append(" (start_time > DATE_FORMAT(?,'%Y/%m/%d %T.%f') && start_time < DATE_FORMAT(?,'%Y/%m/%d %T.%f')) \n");
params.add(startTime);
params.add(endTime);
sb.append(" AND p1_acc_id = ? \n");
params.add(accId);
sb.append("UNION \n");
sb.append("SELECT \n");
sb.append(" game_id \n");
sb.append(" ,server_id \n");
sb.append(" ,p2_acc_id AS acc_id \n");
sb.append(" ,start_time,end_time,bet \n");
sb.append(" ,p2_acc_start_balance AS acc_start_balance \n");
sb.append(" ,p2_acc_win_goal AS acc_win_goal \n");
sb.append(" ,game_process \n");
sb.append(" ,game_type, \n");
sb.append(" CASE WHEN result = 1 THEN TRUE ELSE FALSE END AS result \n");
sb.append("FROM \n");
sb.append(" ctt_manager.ctt_game_punche_records \n");
sb.append("WHERE \n");
sb.append(" (start_time > DATE_FORMAT(?,'%Y/%m/%d %T.%f') && start_time < DATE_FORMAT(?,'%Y/%m/%d %T.%f')) \n");
params.add(startTime);
params.add(endTime);
sb.append(" AND p2_acc_id = ? \n");
params.add(accId);
sb.append("ORDER BY end_time DESC \n");
sb.append("limit ?,? \n");
params.add(firstCount);
params.add(count);
list = new ArrayList<Object>();
list = StmtUtil.queryToBean(READ_CONN, sb.toString(), params, new PunchGameRecordsBean());
if (list.size() > 0) {
for (int i = 0; i < list.size(); i++) {
PunchGameRecordsBean bean = (PunchGameRecordsBean) list.get(i);
JSONObject jsonMap = new JSONObject(bean.getGameProcess());
String searchKey[] = { "gameName", "accName", "accId", "gameId", "gameType", "startTime", "endTime", "startBalance",
"endBalance", "bet", "netAmount", "winGoal", "gameTimes", "gameProcess" };
Object searchByAccNameValue[] = { "三國猜拳王", accName, Long.parseLong("" + bean.getAccId()), "" + bean.getGameId(),
Integer.parseInt("" + bean.getGameType()), bean.getStartTime(), bean.getEndTime(),
new BigDecimal("" + bean.getAccStartBalance()),
new BigDecimal("" + bean.getAccStartBalance()).add(new BigDecimal("" + bean.getAccWinGoal())),
new BigDecimal("" + bean.getBet()), new BigDecimal("" + bean.getAccWinGoal()),
new BigDecimal("" + bean.getBet()).add(new BigDecimal("" + bean.getAccWinGoal())), jsonMap.get("gameTimes"),
jsonMap.get("gameProcess") };
tmpMap = new ConcurrentHashMap<String, Object>();
for (int k = 0; k < searchKey.length; k++) {
tmpMap.put(searchKey[k], searchByAccNameValue[k]);
}
tmpMapList.add(tmpMap);
}
}
}
} catch (Exception e) {
tmpMapList = null;
LOG.debug("Exception, " + e.getMessage());
ShowLog.err(LOG, e);
} finally {
if (params != null) {
params.clear();
params = null;
}
if (sb != null) {
sb.setLength(0);
sb = null;
}
if (list != null) {
list.clear();
list = null;
}
}
return tmpMapList;
}
public void sentURL(String url, String data, String accId, String tokenId) {
if (url != null && !url.isEmpty() && !"".equals(url.trim())) {
try {
HttpURLConnection conn = (HttpURLConnection) (new URL(url).openConnection());
conn.setRequestMethod("POST");
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("User-Agent", "Mozilla/5.0");
conn.setRequestProperty("Accept-Language", "utf-8");
conn.setDoOutput(true);
conn.setConnectTimeout(20);
conn.setReadTimeout(15);
conn.connect();
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes("data=" + data + "&accId=" + accId + "&tokenId=" + tokenId);
wr.flush();
wr.close();
wr = null;
int resCode = conn.getResponseCode();
LOG.info("Response Code:" + resCode);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuilder sb = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
sb.append(inputLine);
}
in.close();
in = null;
conn.disconnect();
conn = null;
resCode = 0;
inputLine = "";
inputLine = null;
LOG.info("Response Content:\n" + sb.toString());
if (sb != null) {
sb.setLength(0);
sb = null;
}
} catch (java.net.SocketTimeoutException e) {
// e.printStackTrace();
} catch (MalformedURLException e) {
// e.printStackTrace();
} catch (IOException e) {
// e.printStackTrace();
}
}
}
}
| true |
75af5bb1a04ea3fb03d2431a07bb42eefe3a58cb | Java | michall02/University | /university-data/src/main/java/pl/home/services/AddStudentService.java | UTF-8 | 141 | 1.921875 | 2 | [] | no_license | package pl.home.services;
import pl.home.models.Student;
public interface AddStudentService {
void saveStudent(Student studentDAO);
}
| true |
0320acb0f538024347b97c94be714c986ba4b63b | Java | thanhnhan2tn/constats | /Codes/JAVA_J2SE/JSON_Test/src/Main.java | UTF-8 | 1,889 | 3.4375 | 3 | [] | no_license | import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class Main {
// Parse test
public static <T> T parseObjectFromString(String hoten, String namsinh,
Class<T> clazz) throws Exception {
return clazz.getConstructor(new Class[] { String.class, String.class })
.newInstance(hoten, namsinh);
}
public static void main(String[] args) throws Exception {
/*
* // Chuỗi JSON mẫu mô tả một đối tượng Nic, ten bien name trong chuoi
* phu // thuoc vao phuong thuc get ben duoi, nen dat trung nhau, neu ko
* se bao // ket qua = null String jsonString =
* "{\"address\" : \"192.168.0.109\", \"netmask\" : \"255.255.255.0\", \"gateway\" : \"192.168.0.1\"}"
* ;
*
* // Phân tích try {
*
* // 1. Tạo ra một JSONParser JSONParser jsonParser = new JSONParser();
*
* // 2. Parser chuỗi JSON về một JSONObject JSONObject jsonObject =
* (JSONObject) jsonParser.parse(jsonString);
*
* // 3. Lấy các giá trị trong jsonObject thông qua các Key
*
* String address = (String) jsonObject.get("address");
* String netmask = (String) jsonObject.get("netmask");
* String gateway = (String)jsonObject.get("gateway");
*
* // Student student = new Student(id, name, email); Nic nic = new
* Nic(address, netmask, gateway);
*
* System.out.println("Address : " + nic.getAddress());
* System.out.println("Netmask : " + nic.getNetmask());
* System.out.println("Gateway : " + nic.getGateway());
*
* } catch (ParseException e) { e.printStackTrace(); }
*/
// ---------------Parse test
SinhVien obj1 = parseObjectFromString("Hieu Minh", "1993",
SinhVien.class);
System.out.println("Obj: " + "\n" + obj1.toString() + "hoten:"
+ obj1.getHoten() + "\n" + "Namsinh " + obj1.getNamsinh());
}
} | true |
b49c93b9bb08fe337561d4bc8040f2ef6f5923c1 | Java | danielsf2/Aplicativo-Academia | /TrabalhoLPV-2018/Trabalho de LPV 2018 - App Academia/src/br/com/academia/modelo/dao/UsuarioDao.java | ISO-8859-1 | 4,570 | 2.75 | 3 | [] | no_license | package br.com.academia.modelo.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import br.com.academia.modelo.Usuario;
import br.com.academia.utils.CriaConexao;
import br.com.academia.utils.MetodosPublicos;
public class UsuarioDao {
/**
* Rebe como parmetro um tipo usurio, trata os dados e tenta a insro na tabela do banco de dados.
*
* @param Usuario usuario
* @author Daniel Soares Ferreira
* @version 1.0
*/
public void cadastraUsuario(Usuario usuario) {
String sql = "INSERT INTO usuario (usuario,senha,papel) VALUES (?,?,?)";
Connection conexao = new CriaConexao().getConexao("aluno", "aluno");
try {
PreparedStatement st = conexao.prepareStatement(sql);
st.setString(1, usuario.getNome());
st.setLong(2, usuario.getSenha());
st.setString(3, usuario.getPapel());
st.execute();
new MetodosPublicos().telaDeSucesso();
st.close();
} catch (SQLException e) {
e.printStackTrace();
new MetodosPublicos().telaDeErro();
}
}//cadastraUsuario
/**
* Recebe como parametro um Long que deve ser um id do usuario, a partir desse parmetro tenta a insero
* no banco de dados.
*
* @param Long id
* @author Daniel Soares Ferreira
* @version 1.0
*/
public void removeUsuario(Long id) {
String sql = "DELETE FROM usuario WHERE id=?";
Connection conexao = new CriaConexao().getConexao("aluno", "aluno");
try {
PreparedStatement st = conexao.prepareStatement(sql);
st.setLong(1, id);
st.execute();
new MetodosPublicos().telaDeSucesso();
st.close();
} catch (SQLException e) {
e.printStackTrace();
new MetodosPublicos().telaDeErro();
}
}//removeUsuario
public void aualizaUsuario(Usuario usuario, Long id) {
String sql = "UPDATE usuario SET id=?,usuario=?,senha=?,papel=? WHERE id=?";
Connection conexao = new CriaConexao().getConexao("aluno", "aluno");
try {
PreparedStatement st = conexao.prepareStatement(sql);
st.setLong(1, usuario.getId());
st.setString(2, usuario.getNome());
st.setLong(3, usuario.getSenha());
st.setString(4, usuario.getPapel());
st.setLong(5, id);
st.execute();
new MetodosPublicos().telaDeSucesso();
st.close();
} catch (SQLException e) {
e.printStackTrace();
new MetodosPublicos().telaDeErro();
}
}//atualizaUsuario
/**
* Recebe como parmetro um Long que tem como contedo um id que identifica um usurio, pesquisa este id
* no Banco de Dados e retorna um Objeto Usurio caso tenha xito na consulta.
*
* @param Long id
* @return Usuario usuario
* @author Daniel Soares Ferreira
* @version 1.0
*/
public Usuario pesquisaUsuario(Long id) {
Usuario usuario = new Usuario();
String sql = "SELECT*FROM usuario WHERE id=?";
Connection conexao = new CriaConexao().getConexao("aluno", "aluno");
try {
PreparedStatement st = conexao.prepareStatement(sql);
st.setLong(1, id);
ResultSet rs = st.executeQuery();
rs.next();
usuario.setId(rs.getLong("id"));
usuario.setNome(rs.getString("usuario"));
usuario.setPapel(rs.getString("papel"));
usuario.setSenha(rs.getLong("senha"));
st.close();
rs.close();
} catch (SQLException e) {
e.printStackTrace();
new MetodosPublicos().telaDeErro();
}
return usuario;
}//pesquisaUsuario
/**
* Pesquisa todos os usuarios cadastrados na tabela do banco de dados, insere em uma lista e retorna a lista em caso
* de sucesso.
*
* @return List usuarios
* @author Daniel Soares Ferreira
* @version 1.0
*/
public List<Usuario> listaTodos(){
List<Usuario> usuarios = new ArrayList<>();
String sql = "SELECT*FROM usuario";
Connection conexao = new CriaConexao().getConexao("aluno", "aluno");
try {
PreparedStatement st = conexao.prepareStatement(sql);
ResultSet rs = st.executeQuery();
while(rs.next()) {
Usuario usuario = new Usuario();
usuario.setId(rs.getLong("id"));
usuario.setNome(rs.getString("usuario"));
usuario.setPapel(rs.getString("papel"));
usuario.setSenha(rs.getLong("senha"));
usuarios.add(usuario);
}
} catch (SQLException e) {
e.printStackTrace();
new MetodosPublicos().telaDeErro();
}
return usuarios;
}//listaTodos
}//UsuarioDao
| true |
ab0c0b721a4b4fa63eb835e13cbd4b3273474a97 | Java | yanchengdeng/SmartFit | /app/src/main/java/com/smartfit/fragments/CustomAnimationDemoFragment.java | UTF-8 | 5,404 | 2.09375 | 2 | [] | no_license | package com.smartfit.fragments;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.smartfit.R;
import com.smartfit.activities.BaseActivity;
import com.smartfit.activities.CustomeCoachActivity;
import com.smartfit.activities.CustomeDynamicActivity;
import com.smartfit.activities.CustomeMainActivity;
import com.smartfit.activities.LoginActivity;
import com.smartfit.activities.MainActivity;
import com.smartfit.activities.MainBusinessActivity;
import com.smartfit.activities.MessageActivity;
import com.smartfit.commons.Constants;
import com.smartfit.utils.IntentUtils;
import com.smartfit.utils.NetUtil;
import com.smartfit.utils.SharedPreferencesUtils;
import com.smartfit.views.pathmenu.FilterMenu;
import com.smartfit.views.pathmenu.FilterMenuLayout;
/**
* A placeholder fragment containing a simple view.
*/
public class CustomAnimationDemoFragment extends Fragment {
public CustomAnimationDemoFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_menu_with_custom_animation, container, false);
FilterMenuLayout filterMenuLayout = (FilterMenuLayout) rootView.findViewById(R.id.filter_menu);
attachMenu(filterMenuLayout);
filterMenuLayout.collapse(true);
return rootView;
}
private FilterMenu attachMenu(FilterMenuLayout layout) {
return new FilterMenu.Builder(getActivity())
.addItem(R.mipmap.icon_home5, getString(R.string.menu_main))
.addItem(R.mipmap.icon_home4, getString(R.string.menu_class))
.addItem(R.mipmap.icon_home1, getString(R.string.menu_dynamic))
.addItem(R.mipmap.icon_home2, getString(R.string.menu_info))
.addItem(R.mipmap.icon_home3, getString(R.string.menu_mine))
.attach(layout)
.withListener(listener)
.build();
}
FilterMenu.OnMenuChangeListener listener = new FilterMenu.OnMenuChangeListener() {
@Override
public void onMenuItemClick(View view, int position) {
switch (position) {
case 0:
if (!MainActivity.class.getName().equals(IntentUtils.getRunningActivityName(getActivity()))) {
Intent intent = new Intent(getActivity(), MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
}
//
break;
case 1:
if (NetUtil.isLogin(getActivity())) {
if (!MainBusinessActivity.class.getName().equals(IntentUtils.getRunningActivityName(getActivity()))) {
((BaseActivity) getActivity()).openActivity(MainBusinessActivity.class);
}
} else {
((BaseActivity) getActivity()).openActivity(LoginActivity.class);
}
break;
case 2:
if (NetUtil.isLogin(getActivity())) {
if (!CustomeDynamicActivity.class.getName().equals(IntentUtils.getRunningActivityName(getActivity()))) {
((BaseActivity) getActivity()).openActivity(CustomeDynamicActivity.class);
}
} else {
((BaseActivity) getActivity()).openActivity(LoginActivity.class);
}
break;
case 3:
if (NetUtil.isLogin(getActivity())) {
if (!MessageActivity.class.getName().equals(IntentUtils.getRunningActivityName(getActivity())))
((BaseActivity) getActivity()).openActivity(MessageActivity.class);
// ((BaseActivity) getActivity()).openActivity(ChatListActivity.class);
} else {
((BaseActivity) getActivity()).openActivity(LoginActivity.class);
}
break;
case 4:
if (NetUtil.isLogin(getActivity())) {
if (!CustomeMainActivity.class.getName().equals(IntentUtils.getRunningActivityName(getActivity()))) {
String isICF = SharedPreferencesUtils.getInstance().getString(Constants.IS_ICF, "0");
if (isICF.equals("1")) {
((BaseActivity) getActivity()).openActivity(CustomeCoachActivity.class);
} else {
((BaseActivity) getActivity()).openActivity(CustomeMainActivity.class);
}
}
} else {
((BaseActivity) getActivity()).openActivity(LoginActivity.class);
}
break;
}
}
@Override
public void onMenuCollapse() {
}
@Override
public void onMenuExpand() {
}
};
} | true |
b6343723e2b875f38a79dd6ff47aca870e29ec6d | Java | youye1/SSM | /testproject/demo-mvc/src/main/java/cn/youye/mvc/service/UserService.java | UTF-8 | 491 | 1.945313 | 2 | [] | no_license | package cn.youye.mvc.service;
import cn.youye.mvc.dao.UserDao;
import cn.youye.mvc.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* Created by pc on 2016/7/12.
*/
@Service
public class UserService {
@Autowired
UserDao userDao;
public User get(User user) {
user.setId("b41f12fd-4807-11e6-ba31-408d5cc10d3b");
return userDao.get(user);
}
}
| true |
dc77d649daeb9980175052740136329b5e84976f | Java | amaoxia/iSwap-Common | /iSwap-Common/src/com/common/utils/crypt/support/Util.java | UTF-8 | 2,926 | 3.390625 | 3 | [] | no_license | package com.common.utils.crypt.support;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Util {
/** 将Hex十六进制字符转换为byte字节 */
public static byte stringHEX2bytes(String str) {
return (byte) ("0123456789abcdef".indexOf(str.substring(0, 1)) * 16 + "0123456789abcdef"
.indexOf(str.substring(1)));
}
/** 将byte字节转换为Hex十六进制字符 */
public static String byte2HEX(byte b) {
return ("" + "0123456789abcdef".charAt(0xf & b >> 4) + "0123456789abcdef"
.charAt(b & 0xF));
}
/**
* 将表示16进制值的字符串转换为byte数组,
* 和public static String byteArr2HexStr(byte[] arrB)
* 互为可逆的转换过程
*
* @param strIn 需要转换的字符串
* @return 转换后的byte数组
* @throws Exception 本方法不处理任何异常,所有异常全部抛出
*/
public static byte[] hexStr2ByteArr(String strIn){
byte[] arrB = strIn.getBytes();
int iLen = arrB.length;
// 两个字符表示一个字节,所以字节数组长度是字符串长度除以2
byte[] arrOut = new byte[iLen / 2];
for (int i = 0; i < iLen; i = i + 2) {
String strTmp = new String(arrB, i, 2);
arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
}
return arrOut;
}
/**
* 将byte数组转换为表示16进制值的字符串,
* 如:byte[]{8,18}转换为:0813,
* 和public static byte[] hexStr2ByteArr(String strIn)
* 互为可逆的转换过程
*
* @param arrB 需要转换的byte数组
* @return 转换后的字符串
* @throws Exception 本方法不处理任何异常,所有异常全部抛出
*/
public static String byteArr2HexStr(byte[] arrB) {
int iLen = arrB.length;
//每个byte用两个字符才能表示,所以字符串的长度是数组长度的两倍
StringBuffer sb = new StringBuffer(iLen * 2);
for (int i = 0; i < iLen; i++) {
int intTmp = arrB[i];
//把负数转换为正数
while (intTmp < 0) {
intTmp = intTmp + 256;
}
//小于0F的数需要在前面补0
if (intTmp < 16) {
sb.append("0");
}
sb.append(Integer.toString(intTmp, 16));
}
return sb.toString();
}
public static String getMD5(String mds) {
String mdresult = "";
try {
MessageDigest md = MessageDigest.getInstance("MD5");
mdresult = md5bytes2string(md.digest(mds.getBytes()));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return mdresult;
}
public static String md5bytes2string(byte[] bytes) {
String result = "";
for (int i = 0; i < bytes.length; i++) {
result += byte2HEX(bytes[i]);
}
return result;
}
}
| true |
de84e1afd23f0c3921ada10ebadcb8a72a1c4fac | Java | xuezhongzhen/spring_mybaisplus | /src/main/java/com/xzz/service/impl/DeptServiceImpl.java | UTF-8 | 431 | 1.5 | 2 | [] | no_license | package com.xzz.service.impl;
import com.xzz.entity.Dept;
import com.xzz.mapper.DeptMapper;
import com.xzz.service.DeptService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 服务实现类
* </p>
*
* @author xzz
* @since 2020-08-27
*/
@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements DeptService {
}
| true |
edba54669524120ae9b66ee78b817f1571431120 | Java | lizhiying61f/PhotoAlbum | /app/src/main/java/com/zhiyingli/photoalbum/checkalbum/CheckAlbumInteractorImpl.java | UTF-8 | 3,731 | 2.21875 | 2 | [] | no_license | package com.zhiyingli.photoalbum.checkalbum;
import android.content.ContentResolver;
import android.database.Cursor;
import android.provider.MediaStore;
import android.text.TextUtils;
import com.zhiyingli.photoalbum.AppUtils;
import com.zhiyingli.photoalbum.bean.ImageFolder;
import com.zhiyingli.photoalbum.bean.ImageItem;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Created by zhiyingli on 2016/11/21.
*/
public class CheckAlbumInteractorImpl implements CheckAlbumInteractor{
private ImageFolder currentImageFolder;
private ImageFolder imageAll;
private ContentResolver mContentResolver;
private ArrayList<ImageFolder> mDirPaths = new ArrayList<>();
private HashMap<String, Integer> tmpDir = new HashMap<>();
private List<ImageItem> imageList = new ArrayList<>();
@Override
public void findAlbumItems(OnfinishedListener listener) {
listener.onFinished(creatAlbumList());
}
private List<ImageFolder> creatAlbumList() {
mContentResolver = AppUtils.getApplication().getContentResolver();
imageAll = new ImageFolder();
imageAll.setDir("全部照片");
currentImageFolder = imageAll;
mDirPaths.add(imageAll);
getOthers();
return mDirPaths;
}
private void getOthers() {
try {
Cursor mCursor = mContentResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
null, MediaStore.Images.Media.MIME_TYPE + " like ?",
new String[]{"image/%"},
MediaStore.Images.Media.DATE_MODIFIED + " DESC");
if (mCursor != null) {
if (mCursor.moveToFirst()) {
int mDate = mCursor.getColumnIndex(MediaStore.Images.Media.DATA);
int mId = mCursor.getColumnIndex(MediaStore.Images.Media._ID);
String path;
do {
path = mCursor.getString(mDate);
if (TextUtils.isEmpty(path)) {
continue;
}
if (!path.endsWith(".gif")) {
int id = mCursor.getInt(mId);
ImageItem imageItem = new ImageItem();
imageItem.setId(id);
imageItem.setPath(path);
imageAll.images.add(imageItem);
File parentFile = new File(path).getParentFile();
if (parentFile == null) {
continue;
}
ImageFolder imageFolder = null;
String dirPath = parentFile.getAbsolutePath();
if (!tmpDir.containsKey(dirPath)) {
imageFolder = new ImageFolder();
imageFolder.setDir(dirPath);
imageFolder.setFirstImagePath(path);
mDirPaths.add(imageFolder);
tmpDir.put(dirPath, mDirPaths.indexOf(imageFolder));
} else {
imageFolder = mDirPaths.get(tmpDir.get(dirPath));
}
imageFolder.images.add(imageItem);
}
} while (mCursor.moveToNext());
}
}
if (mCursor != null) {
mCursor.close();
}
tmpDir = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
| true |
0ef809a77533a297189bf873d855fc1d87791237 | Java | arnabm13/car-tracker | /api/cartracker-api/src/main/java/tracker/car/entity/Alert.java | UTF-8 | 1,607 | 2.359375 | 2 | [] | no_license | package tracker.car.entity;
import javax.persistence.*;
import java.sql.Timestamp;
@Entity
@NamedQueries({
@NamedQuery(name="Alert.findAllHighAlert",
query="SELECT a FROM Alert a WHERE a.timestamp> :pTS and a.priority='HIGH'"),
@NamedQuery(name="Alert.findByVin",
query = "SELECT a FROM Alert a WHERE a.vin=:pVin")
})
public class Alert {
@Id
@Column(columnDefinition = "varchar(36)")
private String id;
private String vin;
private Timestamp timestamp;
private String priority;
private String reason;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getVin() {
return vin;
}
public void setVin(String vin) {
this.vin = vin;
}
public Timestamp getTimestamp() {
return timestamp;
}
public void setTimestamp(Timestamp timestamp) {
this.timestamp = timestamp;
}
public String getPriority() {
return priority;
}
public void setPriority(String priority) {
this.priority = priority;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
@Override
public String toString() {
return "Alert{" +
"id='" + id + '\'' +
", vin='" + vin + '\'' +
", timestamp=" + timestamp +
", priority='" + priority + '\'' +
", reason='" + reason + '\'' +
'}';
}
}
| true |
f2cbd2dd8656b2d16cc13da8c83ecd4dd5a5b079 | Java | Qaeric/timetable2 | /src/main/java/timetable/client/admin/Entry.java | UTF-8 | 1,898 | 2.765625 | 3 | [] | no_license | package timetable.client.admin;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import timetable.Subject;
public class Entry extends JFrame
{
private static final long serialVersionUID = -1180069535459922422L;
protected JLabel jLabel1=new JLabel("Subject name:");
protected JLabel jLabel2=new JLabel("Room:");
public JTextArea subjectField=new JTextArea();
public JTextArea classField=new JTextArea();
protected JButton acceptButton=new JButton();
protected Subject subject;
public Entry()
{
this.setLocationRelativeTo( null );
this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
this.getContentPane().setLayout(null);
this.setPreferredSize(new Dimension(400, 250));
this.setBounds(new Rectangle(10,10,400,250));
jLabel1.setBounds(new Rectangle(40,30,100,25));
this.getContentPane().add(jLabel1,null);
jLabel2.setBounds(new Rectangle(40,65,100,25));
this.getContentPane().add(jLabel2,null);
subjectField.setBounds(new Rectangle(160,30,200,25));
this.getContentPane().add(subjectField,null);
classField.setBounds(new Rectangle(160,65,200,25));
this.getContentPane().add(classField,null);
acceptButton.setText("Accept");
acceptButton.setBounds(new Rectangle(150,145,100,25));
this.getContentPane().add(acceptButton,null);
}
void addAcceptListener(ActionListener listenForAcceptButton)
{
acceptButton.addActionListener(listenForAcceptButton);
}
public void modify(Subject subject)
{
this.subject = subject;
subjectField.setText(this.subject.getName());
String room = Integer.toString(this.subject.getRoom());
classField.setText(room);
}
}
| true |
48b580ed0f892528316b7ff22a0aafb31829e703 | Java | pritomsaha/Decision-Tree-Implementation | /src/FileReader.java | UTF-8 | 1,183 | 3.0625 | 3 | [] | no_license | import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class FileReader {
public static final String PATH_TO_DATA_FILE = "input.txt";
public BufferedReader reader = null;
public ArrayList<ArrayList<Double>> getRecords(){
//DataInputStream dis = null;
ArrayList<ArrayList<Double>> data=new ArrayList<ArrayList<Double>>();
try {
File f = new File(PATH_TO_DATA_FILE);
FileInputStream fis = new FileInputStream(f);
reader = new BufferedReader(new InputStreamReader(fis));
String line;
while((line=reader.readLine())!=null){
StringTokenizer st = new StringTokenizer(line, ",");
ArrayList<Double> arrayList=new ArrayList<Double>();
int l=st.countTokens();
for(int i=0;i<l;i++){
arrayList.add(Double.parseDouble(st.nextToken()));
}
data.add(arrayList);
}
} catch (Exception e) {
System.out.println("Uh oh, got an IOException error: " + e.getMessage());
}
return data;
}
}
| true |
0f03509d280c0d878fd6844dc29ed236b0605b52 | Java | qq454634668/hostelManage | /src/main/java/com/product/ProductApplication.java | UTF-8 | 1,318 | 1.796875 | 2 | [] | no_license | package com.product;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
@MapperScan("com.product.mapper")
//public class ProductApplication {
public class ProductApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(ProductApplication.class, args);
}
// @Bean
// public EmbeddedServletContainerCustomizer containerCustomizer() {
// return new EmbeddedServletContainerCustomizer() {
// @Override
// public void customize(ConfigurableEmbeddedServletContainer container) {
//// container.setSessionTimeout(3600);//单位为S
// container.setSessionTimeout(7200);//单位为S
// }
// };
// }
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(ProductApplication.class);
}
}
| true |
14280f1f8a3874bc54db8e5adbc3a3d93f4032e6 | Java | parkjye/acorn2020_java | /Step17_InputOutput/src/test/main/Quiz03_2.java | UTF-8 | 445 | 1.640625 | 2 | [] | no_license | package test.main;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class Quiz03_2 extends JFrame{
class JPanel01 extends JPanel {
public JButton Jbtn1;
public JScrollPane scroll;
public JTextArea textAea;
// public JPanelTest
}
public static void main(String[] args) {
JPanel Quix3_2 = new JPanel();
}//main
}//Quix3_2
| true |
7516f2f299cb172e7e48c31841b46ac144aaf8ad | Java | TTaiN/Amadeus4D | /src/main/java/ttain/amadeus/discord/modules/administration/commands/SetAvatar.java | UTF-8 | 628 | 2.1875 | 2 | [] | no_license | package ttain.amadeus.discord.modules.administration.commands;
import sx.blah.discord.api.IDiscordClient;
import sx.blah.discord.util.DiscordException;
import sx.blah.discord.util.Image;
import sx.blah.discord.util.RateLimitException;
/**
* -- Amadeus Discord System --
* Creator: Tai
* Date: 3/23/2017
* Package: ttain.amadeus.discord.modules.administration.commands
* Filename: SetAvatar.java
*/
public class SetAvatar
{
public SetAvatar(IDiscordClient client, String type, String url) throws DiscordException, RateLimitException
{
client.changeAvatar(Image.forUrl(type, url)); // format, url
}
}
| true |
a5084bda103b340a86388228d74c28e812ff739d | Java | codingWang/JavaStudy | /src/com/duwei/designpattern/abstractfactory/SummerTextField.java | UTF-8 | 238 | 2.34375 | 2 | [] | no_license | package com.duwei.designpattern.abstractfactory;
//Summer文本框类:具体产品
class SummerTextField implements TextField {
public void display() {
System.out.println("显示蓝色边框文本框。");
}
}
| true |
e231351117a4688b2ec537e46692f74ada2712db | Java | tiagoboeing/algoritmos-estrutura-de-dados | /semestres_anteriores/src/Lista13/OrdenacaoMergeSort.java | UTF-8 | 1,925 | 3.4375 | 3 | [] | no_license | package Lista13;
public class OrdenacaoMergeSort<T extends Comparable<T>> extends
OrdenacaoAbstract<T> {
@Override
public void ordenar() {
T[] info = getInfo();
int n = info.length - 1;
mergeSort(0, n);
}
public void mergeSort(int inicio, int fim) {
if (inicio < fim) {
int meio = (inicio + fim) / 2;
//System.out.println("p[" + inicio + "-" + fim + "]");
mergeSort(inicio, meio);
mergeSort(meio + 1, fim);
merge(inicio, fim, meio);
}
}
private void merge(int inicio, int fim, int meio) {
T[] info = getInfo();
//System.out.println("m[" + inicio + "-" + fim + "]");
int tamEsquerda = meio - inicio + 1;
T[] esquerda = (T[]) new Comparable[tamEsquerda];
for (int i = 0; i <= tamEsquerda - 1; i++) {
esquerda[i] = info[inicio + i];
}
int tamDireita = fim - meio;
T[] direita = (T[]) new Comparable[tamDireita];
for (int i = 0; i <= tamDireita - 1; i++) {
direita[i] = info[meio + 1 + i];
}
int cEsq = 0;
int cDir = 0;
int i = inicio;
for (; i <= fim; i++) {
if ((cEsq < tamEsquerda) && (cDir < tamDireita)) {//temos um par de elementos?
if (esquerda[cEsq].compareTo(direita[cDir]) < 0) {
info[i] = esquerda[cEsq];
cEsq++;
} else {
info[i] = direita[cDir];
cDir++;
}
} else {
break;
}
}
//copia da sobra
while (cEsq < tamEsquerda) {
info[i] = esquerda[cEsq];
cEsq++;
i++;
}
while (cDir < tamDireita) {
info[i] = direita[cDir];
cDir++;
i++;
}
}
}
| true |
aad48e6caca9c6b8690df3059542077533c3ba7e | Java | Youhao-Wang/CS455 | /PA4/RandomTextGenerator.java | UTF-8 | 3,506 | 2.90625 | 3 | [] | no_license | // Name:Youhao Wang
// USC loginid:youhaowa
// CS 455 PA4
// FLL 2016
/**
RandomTextGenerator class:
this class achieve main function of text generate.
*/
import java.io.PrintWriter;
import java.util.*;
public class RandomTextGenerator {
public static final int FIXED_SEED = 1;
public static final int MAX_LENGTH = 80;
private static int prefixLength;
private static int numWords;
private Scanner in;
private PrintWriter out;
private static boolean isDebug;
private HashMap<Prefix, ArrayList<String>> map;
private ArrayList<Prefix> allPrefix;
ArrayList<String> result;
private Random random;
public RandomTextGenerator(int prefixLength,int numWords, Scanner in,PrintWriter out,boolean isDebug){
this.prefixLength = prefixLength;
this.numWords = numWords;
this.in = in;
this.out = out;
this.isDebug = isDebug;
if(isDebug)
random = new Random(FIXED_SEED);
else
random = new Random();
map = new HashMap<Prefix, ArrayList<String>>();
allPrefix = new ArrayList<Prefix>();
result = new ArrayList<String>();
}
/**
read the data from soucefile and store them in the Hashmap.
*/
public void readSource(){
LinkedList<String> inial_list = new LinkedList<String> ();
for(int i = 0; i < prefixLength; i++){
if(in.hasNext()){
String str = in.next();
inial_list.add(str);
}
}
Prefix prefix = new Prefix(inial_list);
allPrefix.add(prefix);
ArrayList<String> successor;
while(in.hasNext()){
String next = in.next();
if(map.containsKey(prefix)){
successor = map.get(prefix);
}
else{
successor = new ArrayList<String>();
}
successor.add(next);
map.put(prefix,successor);
prefix = prefix.shiftIn(next);
allPrefix.add(prefix);
}
if(map.containsKey(prefix)){
successor = map.get(prefix);
}
else{
successor = new ArrayList<String>();
}
map.put(prefix,successor);
}
/**
Generate the words in the text.
*/
public void generateText(){
Prefix currentlPrefix = inialPrefix();
for(int i = 0; i < numWords; i++){
if(isDebug)
System.out.println("DEBUG: prefix :"+ currentlPrefix);
ArrayList<String> successor = map.get(currentlPrefix);
if(successor.isEmpty()){
if(isDebug)
System.out.println("DEBUG: successors: <END OF FILE> ");
currentlPrefix = inialPrefix();
i--;
}
else{
if(isDebug)
System.out.println("DEBUG: successors: "+ successor);
int len = successor.size();
int index = random.nextInt(len);
String str = successor.get(index);
result.add(str);
if(isDebug)
System.out.println("DEBUG: word generated: "+ str);
currentlPrefix = currentlPrefix.shiftIn(str);
}
}
}
/**
Write the text to the out file
*/
public void outToFile(){
ListIterator<String> iter = result.listIterator();
int countLine = 0;
String line = "";
while(iter.hasNext()){
String str = iter.next();
if( (line.length()+ str.length()) <= MAX_LENGTH){
line = line + str + " ";
}
else{
line = line.substring(0, line.length() -1);
out.println(line);
line = str + " ";
}
}
line = line.substring(0, line.length() -1);
line = line + ".";
out.println(line);
}
/**
Choose at random to become the initial prefix.
*/
private Prefix inialPrefix(){
int len = allPrefix.size();
int index = random.nextInt(len);
Prefix inial_prefix = allPrefix.get(index);
if(isDebug){
System.out.println("DEBUG: choose a new initial prefix :"+ inial_prefix);
}
return inial_prefix;
}
}
| true |
3f0a5efbc326fc867d48331940029e03a8b06082 | Java | ThomassenMichiel/AcaraFrontend | /src/main/java/be/acara/frontend/model/CartItemModel.java | UTF-8 | 279 | 1.84375 | 2 | [] | no_license | package be.acara.frontend.model;
import be.acara.frontend.controller.dto.EventDto;
import lombok.Data;
import java.math.BigDecimal;
@Data
public class CartItemModel {
private EventDto eventDto;
private int amount;
private BigDecimal itemTotal = BigDecimal.ZERO;
}
| true |
85873ce137677d822a0bfea99a66a91406968d4b | Java | dfreitasf/estudos-java | /curso-java-basico/src/com/loiane/cursojava/aula13/OperadoresAritmeticos.java | WINDOWS-1252 | 1,394 | 3.546875 | 4 | [] | no_license | package com.loiane.cursojava.aula13;
public class OperadoresAritmeticos {
public static void main(String[] args) {
int resultado = 1 + 2;
System.out.println(resultado);
resultado = resultado - 1;
System.out.println(resultado);
resultado = resultado * 2;
System.out.println(resultado);
resultado = resultado / 2;
System.out.println(resultado);
resultado = resultado + 8;
System.out.println(resultado);
resultado = resultado % 7;
System.out.println(resultado);
String primeiraString = "Esta ";
String segundaString = "uma String concatenada.";
String terceiraString = primeiraString + segundaString;
System.out.println(terceiraString);
resultado = resultado + 1;
System.out.println(resultado);
resultado--;
System.out.println(resultado);
resultado++;
System.out.println(resultado);
resultado = -resultado;
System.out.println(resultado);
boolean success = false;
System.out.println(success);
System.out.println(!success);
int i = 3;
i++;
// output 4
System.out.println(i);
++i;
// output 5
System.out.println(i);
// output 6
System.out.println(++i);
/*mesma coisa que:
i += 1;
System.out.println(i);*/
// output 6
System.out.println(i++);
/*mesma coisa que:
System.out.println(i);
i = i + 1; ou i += 1;*/
// output 7
System.out.println(i);
}
}
| true |
4365ab8954d6d2390e72eb1b16c7a3d7f8cbec14 | Java | Laloxx/Ookot | /src/main/java/mx/com/ookot/persistence/entity/OpPagos.java | UTF-8 | 3,332 | 2.03125 | 2 | [] | no_license | package mx.com.ookot.persistence.entity;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Column;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
@Table(name = "cat_instructores")
public class OpPagos implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Integer idPago;
private ClClientes cliente;
private BigDecimal importe;
private Status status;
private Date fechaPago;
private Date fechaVencimiento;
private OpClases clases;
public OpPagos() {
}
public OpPagos(ClClientes cliente, BigDecimal importe,
Status status, Date fechaPago, Date fechaVencimiento,
OpClases clases) {
this.cliente = cliente;
this.importe = importe;
this.status = status;
this.fechaPago = fechaPago;
this.fechaVencimiento = fechaVencimiento;
this.clases = clases;
}
/**
* @return the idPago
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "IdPago", unique = true, nullable = false)
public Integer getIdPago() {
return idPago;
}
/**
* @param idPago the idPago to set
*/
public void setIdPago(Integer idPago) {
this.idPago = idPago;
}
/**
* @return the cliente
*/
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "IdCliente", nullable = false)
public ClClientes getCliente() {
return cliente;
}
/**
* @param cliente the cliente to set
*/
public void setCliente(ClClientes cliente) {
this.cliente = cliente;
}
/**
* @return the importe
*/
@Column(name = "Importe", nullable = false, scale = 4)
public BigDecimal getImporte() {
return importe;
}
/**
* @param importe the importe to set
*/
public void setImporte(BigDecimal importe) {
this.importe = importe;
}
/**
* @return the status
*/
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "IdStatus", nullable = false)
public Status getStatus() {
return status;
}
/**
* @param status the status to set
*/
public void setStatus(Status status) {
this.status = status;
}
/**
* @return the fechaPago
*/
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "FechaPago", nullable = false, length = 19)
public Date getFechaPago() {
return fechaPago;
}
/**
* @param fechaPago the fechaPago to set
*/
public void setFechaPago(Date fechaPago) {
this.fechaPago = fechaPago;
}
/**
* @return the fechaVencimiento
*/
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "FechaVencimiento", nullable = false, length = 19)
public Date getFechaVencimiento() {
return fechaVencimiento;
}
/**
* @param fechaVencimiento the fechaVencimiento to set
*/
public void setFechaVencimiento(Date fechaVencimiento) {
this.fechaVencimiento = fechaVencimiento;
}
/**
* @return the clases
*/
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "IdClases", nullable = false)
public OpClases getClases() {
return clases;
}
/**
* @param clases the clases to set
*/
public void setClases(OpClases clases) {
this.clases = clases;
}
}
| true |
846dc167d578a55f6b4b6ba6f11aaa9ecd759c1a | Java | jangseohyun/java_study_2021 | /Test085.java | UHC | 1,869 | 4.03125 | 4 | [] | no_license | /*=============================
++++++++++迭(array)++++++++++
-迭 ⺻ Ȱ
===============================
Test085.java
=============================*/
//
// ڷκ л Է¹ް, ŭ ( ) Է¹
// ü л , , Ͽ ϴ α Ѵ.
// , 迭 ȰϿ ó ֵ Ѵ.
//
// л Է: 5
// 1 л Է: 90
// 2 л Է: 82
// 3 л Է: 64
// 4 л Է: 36
// 5 л Է: 98
// >> : 370
// >> : 74.0
// >> :
// 90: -16.0
// 82: -8.0
// 64: 10.0
// 36: 38.0
// 98: -24.0
// Ϸ ƹ Ű ʽÿ . . .
import java.util.Scanner;
public class Test085
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int sum=0;
double avg=0, dev=0;
System.out.print("л Է: ");
int num = sc.nextInt();
int[] students = new int[num];
for (int i=0; i<num; i++)
{
System.out.printf("%d л Է: ", (i+1));
students[i] = sc.nextInt();
sum += students[i];
}
avg = sum / students.length;
System.out.println(">> : "+sum);
System.out.println(">> : "+avg);
System.out.println(">> : ");
for (int j=0; j<num; j++)
{
dev = avg-students[j];
System.out.println(students[j]+": "+dev);
}
}
}
/*
[ ]
л Է: 5
1 л Է: 90
2 л Է: 82
3 л Է: 64
4 л Է: 36
5 л Է: 98
>> : 370
>> : 74.0
>> :
90: -16.0
82: -8.0
64: 10.0
36: 38.0
98: -24.0
Ϸ ƹ Ű ʽÿ . . .
*/ | true |
07eaf6efd2b2420e1df06375bb80c644a84d87a7 | Java | mihkelva/IdeaProjects | /Strings/src/com/company/Main.java | UTF-8 | 3,275 | 3.328125 | 3 | [] | no_license | package com.company;
public class Main {
public static void main(String[] args) {
String[] kuud = new String[] {"Jaanuar", "Veebruar", "Märts", "Aprill", "Mai", "Juuni", "Juuli", "August", "September", "Oktoober", "November", "Detsember"};
// E = 0, l = 1, a = 2, s = 3, " " = 4
String lause= "Elas metsas mutionu, keset kuuski noori vanu";
// otsime indeksit sellele sümbolile mis on indexOf sees (praegu tühikut)
int indeksiNumber = lause.indexOf("u");
// siin otsime lausest sümbolit Y. Näeme, et prinditakse väärtuseks -1
int indeksiNumberY = lause.indexOf("y");
System.out.println(indeksiNumberY);
System.out.println();
// esialgu saab indeksinumber väärtuseks 4 (realt 10).
// ta on while tsüklis senikaua kuni väärtus ei ole -1 (ei leia enam tühikut)
// indeksinumbrile lisame iga kord 1 juurde (fromIndex), et ta hakkaks lugema pärast tühikut
while(indeksiNumber != -1){
System.out.println(indeksiNumber);
indeksiNumber = lause.indexOf("u", indeksiNumber+1);
}
System.out.println();
System.out.println();
String isikukood = "19103315212";
String sugu = "";
// meetod substring tükeldab stringi. esimene parameeter on algus, teine lõpp
String esimeneNumber = isikukood.substring(0,1);
System.out.println(esimeneNumber);
// võrdleme numbreid == märgiga. Sõnu võrdleme .equals()
// || tähendab, et if() on tõene kui üks neist võrdustest on tõene
if(esimeneNumber.equals("1") || esimeneNumber.equals("3") || esimeneNumber.equals("5")){
sugu = "mees";
System.out.println("Oled " + sugu +"!");
} else if (esimeneNumber.equals("2") || esimeneNumber.equals("4") || esimeneNumber.equals("6")){
sugu = "naine";
System.out.println("Oled " + sugu +"!");
} else {
System.out.println("Vigane isikukood!");
}
String synniAasta = isikukood.substring(1,3);
System.out.println(synniAasta);
int pikkSynniAasta = 0;
switch (esimeneNumber) {
case "1":
case "2": {
pikkSynniAasta = (Integer.parseInt(synniAasta) + 1800);
break;
}
case "3":
case "4": {
pikkSynniAasta = (Integer.parseInt(synniAasta) + 1900);
break;
}
case "5":
case "6": {
pikkSynniAasta = (Integer.parseInt(synniAasta) + 2000);
break;
}
}
System.out.println(pikkSynniAasta);
String synniKuu = isikukood.substring(3,5);
int synniKuuNumber = Integer.parseInt(synniKuu);
System.out.println(synniKuu);
System.out.println(kuud[synniKuuNumber-1]);
// %s ja muutujate arv peab võrduma (4tk kummatki)
// printf vajab muutujaid , println mitte.
// printf ei tee ise automaatselt reavahetust
System.out.printf("Su isikukood on %s %n", isikukood);
System.out.printf("Oled %s ja oled sündinud kuupäeval %s %s ning %s aastal %n", sugu, isikukood.substring(5,7), kuud[synniKuuNumber-1], pikkSynniAasta);
}
}
| true |
6282548605c6a41d1c80fe7c6836fccc39831101 | Java | fabfabe/de.medizinplattform.git.github | /Medizinplattform/src/de/medizinplattform/managedbeans/RegisterBean.java | UTF-8 | 1,397 | 2.265625 | 2 | [] | no_license | package de.medizinplattform.managedbeans;
import javax.annotation.PreDestroy;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import de.medizinplattform.entities.Users;
@ManagedBean(name = "registerBean")
@RequestScoped
public class RegisterBean {
@ManagedProperty(value="#{users}")
private Users users;
public Users getUsers() {
return users;
}
public void setUsers(Users users) {
this.users = users;
}
public String name;
public String password;
public RegisterBean(){
System.out.println("RegisterBean started");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String registerUser(){
if(users != null){
System.out.println("Trying to create new user");
if(users.hasUser(name)==false){
users.createUser(name, password, "user");
return "succesful_registration.xhtml?faces-redirect=true";
}
else{
System.out.println("User " + name + " already exists");
}
}
return null;
}
@PreDestroy
public void cry(){
//System.out.println("RegisterBean is about to be destroyed");
}
}
| true |
2b267fd8e7a0d4ab18af91d9d6109e6b3fe113f0 | Java | ssdraid0/java-project | /java/src/algorithm/LinkedListQ.java | UTF-8 | 10,980 | 4.375 | 4 | [] | no_license | package algorithm;
import java.util.Stack;
/**
* 1.给定单链表的头结点和一个结点,删除该结点,返回删除后的单链表的头结点。 </br>
* {@link #remove(Node, Node)}。</br>
* 2.给定单链表的头结点和一个结点的值,删除该结点,返回删除后的单链表的头结点。 </br>
* {@link #remove(Node, int)}。</br>
* 3.输入一个单链表的头结点,从尾到头反过来打印出单链表每个结点的值,用递归实现。</br>
* {@link #printReverse(Node)}。</br>
* 4.输入一个单链表的头结点,反转单链表,返回反转后的头结点。</br>
* {@link #reverse(Node)}。</br>
* 5.输入两个有序的单链表的头结点,合并后仍然是有序的,返回合并后的头结点。</br>
* {@link #mergeSort(Node, Node)}。</br>
* 6.输入一个单链表的头结点,判断是否是环形。</br>
* {@link #hasCycle(Node)}。</br>
* 7.输入一个复杂单链表的头结点,其结点除了有一个next指向下一个结点外,</br>
* 还有一个other指向链表中的任一结点或者null。 复制这个单链表并返回头结点。</br>
* {@link #clone(ComplexNode)}。</br>
*/
public class LinkedListQ
{
public static void main(String[] args)
{
deleteNodeTest();
}
/**
* 输入一个单链表的头结点和一个值,把这个值添加到末尾。</br>
*/
public static Node add(Node head, int value)
{
Node node = new Node(value);
if (head == null) return node;
Node point = head;
while (point.next != null)
{
point = point.next;
}
point.next = node;
return head;
}
/**
* 输入一单链表的头结点和一个结点的值,删除该结点,返回删除后的单链表的头结点。</br>
*/
public static Node remove(Node head, int value)
{
if (head == null) return null;
if (head.value == value) return head.next;
if (head.next == null) return head;
Node point = head;
while (point.next.value != value)
{
point = point.next;
}
point.next = point.next.next;
return head;
}
/**
* 输入一单链表的头结点和一个下标index,获取单链表第index个结点,返回这个结点。</br>
* 第0个结点是头结点。</br>
*/
public static Node get(Node head, int index)
{
if (head == null || index < 0) return null;
for (int i = 0; i < index; i++)
head = head.next;
return head;
}
/**
* 给定单链表的头结点和一个结点,删除该结点,返回删除后的单链表的头结点。
*/
public static Node remove(Node head, Node del)
{
if (head == null) return null;
if (head == del) return head.next;
if (head.next == null) return head;
Node point = head;
while (point.next != del)
{
point = point.next;
}
point.next = point.next.next;
return head;
}
/**
* 输入一个单链表的头结点,反转单链表,返回反转后的头结点。</br>
*/
public static Node reverse(Node head)
{
if (head == null || head.next == null) return head;
Node prev = null;
Node next = null;
while (head != null)
{
next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}
/**
* 输入一个单链表的头结点,从尾到头反过来打印出单链表每个结点的值,用递归实现。</br>
*/
public static void printReverse(Node head)
{
if (head == null) return;
printReverse(head.next);
System.out.print(head.value);
}
/**
* 输入两个有序的单链表的头结点,合并后仍然是有序的,返回合并后的头结点。</br>
*/
public static Node mergeSort(Node head1, Node head2)
{
if (head1 == null)
{
return head2;
}
if (head2 == null)
{
return head1;
}
Node mergeHead = null;
if (head1.value <= head2.value)
{
mergeHead = head1;
mergeHead.next = mergeSort(head1.next, head2);
} else
{
mergeHead = head2;
mergeHead.next = mergeSort(head1, head2.next);
}
return mergeHead;
}
/**
* 输入一个单链表的头结点,判断是否是环形。</br>
* https://leetcode.com/problems/linked-list-cycle/</br>
*/
public static boolean hasCycle(Node head)
{
if (head == null || head.next == null) return false;
Node slow = head;
Node fast = head.next;
while (fast != null && fast != slow && fast.next != null)
{
slow = slow.next;
fast = fast.next.next;
}
if (fast == slow) return true;
else return false;
}
/**
* 输入两个单链表的头结点,存储的都是非负整数,新建一个链表,存储相加的结果,返回头结点。</br>
* 例如:两个单链表是2 -> 4 -> 3,5 -> 6 -> 4,相加的结果是7 -> 0 -> 8。</br>
* https://leetcode.com/problems/add-two-numbers/</br>
*/
public static Node addTwoNums(Node head1, Node head2)
{
Node prev = new Node(0);
Node head = prev;
int carry = 0;
while (head1 != null || head2 != null || carry != 0)
{
Node node = new Node(0);
int sum = ((head1 == null) ? 0 : head1.value) + ((head2 == null) ? 0 : head2.value) + carry;
node.value = sum % 10;
carry = sum / 10;
prev.next = node;
prev = node;
head1 = (head1 == null) ? null : head1.next;
head2 = (head2 == null) ? null : head2.next;
}
return head.next;
}
/**
* 输入两个单链表的头结点,返回它们的第一个相同结点(说明之后的每个结点也相同)。</br>
*/
public static Node findFirstCommon(Node head1, Node head2)
{
int len1 = getLength(head1), len2 = getLength(head2);
Node longNode = null, shortNode = null;
int dif = len1 - len2;
if (dif >= 0)
{
longNode = head1;
shortNode = head2;
} else
{
longNode = head2;
shortNode = head1;
}
dif = Math.abs(dif);
for (int i = 0; i < dif; i++)
{
longNode = longNode.next;
}
while (longNode != null && shortNode != null && longNode != shortNode)
{
longNode = longNode.next;
shortNode = shortNode.next;
}
return longNode;
}
/**
* 输入一个复杂单链表的头结点。</br>
* 其结点除了有一个next指向下一个结点外,还有一个other指向链表中的任一结点或者null。</br>
* 复制这个复杂单链表并返回头结点。</br>
* http://zhedahht.blog.163.com/blog/static/254111742010819104710337/</br>
*/
public static ComplexNode clone(ComplexNode head)
{
if (head == null) return null;
cloneNodes(head);
connectOtherNodes(head);
return reconnectNodes(head);
}
private static void cloneNodes(ComplexNode head)
{
while (head != null)
{
ComplexNode cloneNode = new ComplexNode();
cloneNode.value = head.value;
cloneNode.next = head.next;
cloneNode.other = null;
head.next = cloneNode;
head = cloneNode.next;
}
}
private static void connectOtherNodes(ComplexNode head)
{
while (head != null)
{
ComplexNode cloneNode = head.next;
if (head.other != null)
{
// 复制的结点的other指向原结点的other的下一个结点,建议画张图观察。
cloneNode.other = head.other.next;
}
head = cloneNode.next;
}
}
private static ComplexNode reconnectNodes(ComplexNode head)
{
ComplexNode cloneHead = head.next;
ComplexNode cloneNode = cloneHead;
while (head != null)
{
head.next = cloneNode.next;
head = head.next;
if (head != null)
{
cloneNode.next = head.next;
cloneNode = cloneNode.next;
}
}
return cloneHead;
}
/**
* 输入一个单链表的头结点,从尾到头反过来打印出单链表每个结点的值,用栈实现。</br>
*/
public static void printReverseUseStack(Node head)
{
if (head == null) return;
Stack<Integer> stack = new Stack<>();
while (head != null)
{
stack.push(head.value);
head = head.next;
}
while (!stack.isEmpty())
{
System.out.println(stack.pop());
}
}
private static int getLength(Node head)
{
int result = 0;
for (Node point = head; point != null; point = point.next)
{
result++;
}
return result;
}
private static void deleteNodeTest()
{
Node node1 = new Node();
Node node2 = new Node();
Node node3 = new Node();
node1.value = 1;
node2.value = 2;
node3.value = 3;
node1.next = node2;
node2.next = node3;
Node node = remove(node1, node3);
print(node);
Node head2 = remove(node1, 2);
print(head2);
}
private static void print(Node node)
{
while (node != null)
{
System.out.print(node.value + ",");
node = node.next;
}
System.out.println();
}
public static class Node
{
public int value;
public Node next;
public Node()
{}
public Node(int value)
{
this.value = value;
}
@Override
public String toString()
{
return Integer.toString(value);
}
}
private static class ComplexNode
{
public int value;
public ComplexNode next;
public ComplexNode other;
@Override
public String toString()
{
return Integer.toString(value);
}
}
}
| true |
2449785a2c6da79278b110f0bec69a1931a16a27 | Java | joseteodoro/simple-wallet-api | /src/main/java/br/jteodoro/wallet/models/AccountOperationEnum.java | UTF-8 | 929 | 2.609375 | 3 | [] | no_license | package br.jteodoro.wallet.models;
import java.util.Arrays;
import java.util.function.Predicate;
public enum AccountOperationEnum {
COMPRA_A_VISTA(1l, "COMPRA A VISTA", Op.DEBITO),
COMPRA_PARCELADA(2l, "COMPRA PARCELADA", Op.DEBITO),
SAQUE(3l, "SAQUE", Op.DEBITO),
PAGAMENTO(4l, "PAGAMENTO", Op.CREDITO);
private Long id;
private String naturalKey;
private int op;
private AccountOperationEnum(Long id, String naturalKey, int op) {
this.id = id;
this.naturalKey = naturalKey;
this.op = op;
}
public static AccountOperationEnum of(Long id) {
return Arrays.stream(values()).filter(p -> p.id.equals(id))
.findFirst().orElse(null);
}
public Long getId() {
return id;
}
public String getNaturalKey() {
return naturalKey;
}
public float applyOp(float value) {
return value * op;
}
}
| true |
2976669bbe6897339c59fcb532e4f28e0681f008 | Java | DAC84/javastravav3api | /src/test/java/javastrava/model/StravaAthleteZoneTest.java | UTF-8 | 377 | 1.960938 | 2 | [] | no_license | package javastrava.model;
import javastrava.model.StravaAthleteZone;
import javastrava.utils.BeanTest;
/**
* <p>
* Tests for {@link StravaAthleteZoneTest}
* </p>
*
* @author Dan Shannon
*
*/
public class StravaAthleteZoneTest extends BeanTest<StravaAthleteZone> {
@Override
protected Class<StravaAthleteZone> getClassUnderTest() {
return StravaAthleteZone.class;
}
}
| true |
3954007ff9da2de06c452dd39135f79da4b2838c | Java | focusxyhoo/leetcode | /src/leetcode/medium/T50_Pow.java | UTF-8 | 998 | 3.796875 | 4 | [] | no_license | package leetcode.medium;
/**
* created with IntelliJ IDEA
* author : focusxyhoo
* date : 2019-06-23
* time : 21:27
* description :
*/
public class T50_Pow {
public static void main(String[] args) {
System.out.println(myPow(2.0, 100));
System.out.println(Math.pow(2.0, 0.0));
}
// brute force
// time limit exceeded
public static double myPow(double x, int n) {
double sum = 1.0;
boolean flag = true;
if (n == 0) return 1.0;
if (n < 0) flag = false;
n = Math.abs(n);
for (int i = 1; i <= n; i++) {
sum *= x;
}
if (!flag) return 1 / sum;
return sum;
}
public static double myPow2(double x, int n) {
if (n < 0) return 1 / x * myPow2(1 / x, -(n + 1));
if (n == 0) return 1;
if (n == 2) return x * x;
if (n % 2 == 0) return myPow2(myPow2(x, n / 2), 2);
else return x * myPow2(myPow2(x, n / 2), 2);
}
}
| true |
6339e8bbccdb7521aa2df047fbbd1f28b848a652 | Java | roterdam/TbDA | /src/dk/brics/tajs/analysis/dom/view/AbstractView.java | UTF-8 | 823 | 2.1875 | 2 | [
"Apache-2.0"
] | permissive | package dk.brics.tajs.analysis.dom.view;
import static dk.brics.tajs.analysis.dom.DOMFunctions.createDOMProperty;
import dk.brics.tajs.analysis.State;
import dk.brics.tajs.analysis.dom.DOMSpec;
import dk.brics.tajs.analysis.dom.DOMWindow;
import dk.brics.tajs.analysis.dom.html.HTMLDocument;
import dk.brics.tajs.lattice.Value;
import dk.brics.tajs.dependency.Dependency;
import dk.brics.tajs.dependency.graph.DependencyGraphReference;
/**
* A base interface that all views shall derive from.
*/
public class AbstractView {
public static void build(State s) {
// AbstractView has no native object.
/*
* Properties.
*/
createDOMProperty(s, DOMWindow.WINDOW, "document", Value.makeObject(HTMLDocument.INSTANCES, new Dependency(), new DependencyGraphReference())
.setReadOnly(), DOMSpec.LEVEL_0);
}
}
| true |
13d9ede85811b10f4ff69e76c491fb1b8cdb531e | Java | lilibethcabrera/EmpresaAltice | /src/visual/PlanesCliente.java | ISO-8859-2 | 5,983 | 2.421875 | 2 | [] | no_license | package visual;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Calendar;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import logico.Cliente;
import logico.Factura;
import logico.Plan;
import visual.RegCliente;
import logico.Altice;
import java.awt.SystemColor;
import java.awt.Toolkit;
public class PlanesCliente extends JDialog {
private final JPanel contentPanel = new JPanel();
private static DefaultTableModel model;
private static Object[] fila;
private static JTable table;
private JButton btnCancelar;
private JButton btnFacturar;
private JButton btnEliminar;
private String selecte = "";
private static Cliente miCliente;
private int index;
public PlanesCliente(Cliente cliente) {
miCliente = cliente;
setIconImage(Toolkit.getDefaultToolkit().getImage(ListPlanes.class.getResource("/Imagenes/bill(1).png")));
getContentPane().setBackground(SystemColor.activeCaptionBorder);
setTitle("Planes Actuales");
setBounds(100, 100, 592, 357);
setLocationRelativeTo(null);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBackground(SystemColor.activeCaptionBorder);
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(new BorderLayout(0, 0));
{
JScrollPane scrollPane = new JScrollPane();
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
contentPanel.add(scrollPane, BorderLayout.CENTER);
{
table = new JTable();
table.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
index = table.getSelectedRow();
if(index >= 0) {
btnFacturar.setEnabled(true);
btnEliminar.setEnabled(true);
selecte = table.getValueAt(index, 0).toString();
}
}
});
model = new DefaultTableModel();
String[] columnNames = {"Id","Precio de Apertura","Mensualidad","Velocidad Internet","Minutos de Voz", "Cantidad de Canales", "Ultimo mes Facturado"};
model.setColumnIdentifiers(columnNames);
table.setModel(model);
scrollPane.setViewportView(table);
loadPlanes();
}
}
{
JPanel buttonPane = new JPanel();
buttonPane.setBackground(SystemColor.activeCaptionBorder);
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
btnFacturar = new JButton("Facturar");
btnFacturar.setEnabled(false);
btnFacturar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Plan plan = miCliente.getMisPlanes().get(index);
int mesActual = Calendar.getInstance().get(Calendar.MONTH) + 1;
if(plan.getUltimoMesFacturado() == mesActual) {
JOptionPane.showMessageDialog(null, "Ese plan ya fue facturado este mes", "Error!", JOptionPane.ERROR_MESSAGE);
}else {
int option = JOptionPane.showConfirmDialog(null, "Est seguro que desea facturar el plan de Id: " + plan.getId(),"Informacin",JOptionPane.WARNING_MESSAGE);
if(option == JOptionPane.OK_OPTION){
Factura factura = Altice.getInstance().facturar(plan, miCliente);
miCliente.agregarFactura(factura);
JOptionPane.showMessageDialog(null, "Operacin Satisfactoria", "Informacin", JOptionPane.INFORMATION_MESSAGE);
loadPlanes();
btnEliminar.setEnabled(false);
btnFacturar.setEnabled(false);
selecte = "";
}
}
}
});
buttonPane.add(btnFacturar);
}
{
btnEliminar = new JButton("Cancelar Suscripcion");
btnEliminar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Plan plan = Altice.getInstance().buscarPlanPorId(selecte);
int option = JOptionPane.showConfirmDialog(null, "Est seguro que desea cancelar el plan de Id: " + plan.getId(),"Informacin",JOptionPane.WARNING_MESSAGE);
if(option == JOptionPane.OK_OPTION){
miCliente.getMisPlanes().remove(miCliente.indicePlanPorId(selecte));
JOptionPane.showMessageDialog(null, "Operacin Satisfactoria", "Informacin", JOptionPane.INFORMATION_MESSAGE);
loadPlanes();
btnEliminar.setEnabled(false);
btnFacturar.setEnabled(false);
selecte = "";
}
}
});
btnEliminar.setEnabled(false);
btnEliminar.setActionCommand("OK");
buttonPane.add(btnEliminar);
getRootPane().setDefaultButton(btnEliminar);
}
{
btnCancelar = new JButton("Cancelar");
btnCancelar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
btnCancelar.setActionCommand("Cancel");
buttonPane.add(btnCancelar);
}
}
loadPlanes();
}
//{"Id","Precio de Apertura","Mensualidad","Velocidad Internet","Minutos de Voz", "Cantidad de Canales"};
public static void loadPlanes() {
model.setRowCount(0);
fila = new Object[model.getColumnCount()];
for(int i = 0; i < miCliente.getMisPlanes().size();i++) {
fila[0] = miCliente.getMisPlanes().get(i).getId();
fila[1] = miCliente.getMisPlanes().get(i).getPrecio_apertura();
fila[2] = miCliente.getMisPlanes().get(i).getMensualidad();
fila[3] = miCliente.getMisPlanes().get(i).getVelocidad_internet();
fila[4] = miCliente.getMisPlanes().get(i).getMinutos();
fila[5] = miCliente.getMisPlanes().get(i).getCanales();
fila[6] = miCliente.getMisPlanes().get(i).getUltimoMesFacturado();
model.addRow(fila);
}
}
}
| true |
389a176637b3b7a28373c106826c781769dd5d05 | Java | garyleefight/Algorithm | /leetcode/leet69.java | UTF-8 | 203 | 2.421875 | 2 | [] | no_license | public class Solution {
public int mySqrt(int x) {
long temp = x;
long i = 0;
while(i*i <= temp){
i++;
}
return (int)i-1;
}
}
// slow | true |
a22f1e583e7f03d38439be5cea26f0788755074c | Java | co1248/jspworkspace | /NonageShop/src/main/java/com/nonage/controller/ActionFactory.java | UTF-8 | 3,673 | 2.0625 | 2 | [] | no_license | package com.nonage.controller;
import com.nonage.controller.action.Action;
import com.nonage.controller.action.CartDeleteAction;
import com.nonage.controller.action.CartInsertAction;
import com.nonage.controller.action.CartListAction;
import com.nonage.controller.action.ContractAction;
import com.nonage.controller.action.FindZipNumAction;
import com.nonage.controller.action.IdCheckFormAction;
import com.nonage.controller.action.IndexAction;
import com.nonage.controller.action.JoinAction;
import com.nonage.controller.action.JoinFormAction;
import com.nonage.controller.action.LoginAction;
import com.nonage.controller.action.LoginFormAction;
import com.nonage.controller.action.LogoutAction;
import com.nonage.controller.action.MyPageAction;
import com.nonage.controller.action.OrderAllAction;
import com.nonage.controller.action.OrderDetailAction;
import com.nonage.controller.action.OrderInsertAction;
import com.nonage.controller.action.OrderListAction;
import com.nonage.controller.action.ProductDetailAction;
import com.nonage.controller.action.ProductKindAction;
import com.nonage.controller.action.QnaListAction;
import com.nonage.controller.action.QnaViewAction;
import com.nonage.controller.action.QnaWriteAction;
import com.nonage.controller.action.QnaWriteFormAction;
public class ActionFactory {
//싱글톤패턴
private static ActionFactory instance = new ActionFactory();
private ActionFactory() {
super();
}
public static ActionFactory getInstance() {
return instance;
}
public Action getAction(String command) {
Action action = null;
System.out.println("ActionFactory : " + command);
if(command.equals("index")) {
action = new IndexAction();//객체생성
} else if(command.equals("product_detail")) {
action = new ProductDetailAction();
} else if(command.equals("category")) {
action = new ProductKindAction();
} else if(command.equals("contract")) {
action = new ContractAction();
} else if(command.equals("join_form")) {
action = new JoinFormAction();
} else if(command.equals("id_check_form")) {
action = new IdCheckFormAction();
} else if(command.equals("find_zip_num")) {
action = new FindZipNumAction();
} else if(command.equals("join")) {
action = new JoinAction();
} else if(command.equals("login_form")) {
action = new LoginFormAction();
} else if(command.equals("login")) {
action = new LoginAction();
} else if(command.equals("find_id_form")) {
action = new JoinAction();
} else if(command.equals("logout")) {
action = new LogoutAction();
} else if(command.equals("cart_insert")) {
action = new CartInsertAction();
} else if(command.equals("cart_list")) {
action = new CartListAction();
} else if(command.equals("cart_delete")) {
action = new CartDeleteAction();
} else if (command.equals("order_insert")) {
action = new OrderInsertAction();
} else if (command.equals("order_list")) {
action = new OrderListAction();
} else if (command.equals("mypage")) {
action = new MyPageAction();
} else if (command.equals("order_all")) {
action = new OrderAllAction();
} else if (command.equals("order_detail")) {
action = new OrderDetailAction();
} else if (command.equals("qna_list")) {
action = new QnaListAction();
} else if (command.equals("qna_write_form")) {
action = new QnaWriteFormAction();
} else if (command.equals("qna_write")) {
action = new QnaWriteAction();
} else if (command.equals("qna_view")) {
action = new QnaViewAction();
}
return action;
}
} | true |
322acacd45b427d831292c78d8adef5f87efda0d | Java | SamJH/ChinaMobile | /src/com/oracle/servlet/LoginServlet.java | WINDOWS-1252 | 1,176 | 2.15625 | 2 | [] | no_license | package com.oracle.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.oracle.service.LoginService;
import com.oracle.service.Impl.LoginServiceImpl;
public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
String username = req.getParameter("username");
String password = req.getParameter("password");
LoginService login = new LoginServiceImpl();
String result = login.result(username, password, req.getSession());
if("error".equals(result)){
req.setAttribute("error", "û");
req.getRequestDispatcher("index.jsp").forward(req, resp);
}else{
req.getRequestDispatcher("main.jsp").forward(req, resp);
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
super.doPost(req, resp);
}
}
| true |
5bf4fa30ea982cf587db3d5a21a2d2dea89256e2 | Java | thomashw/ensf409 | /Lab 2/Date.java | UTF-8 | 2,011 | 4.09375 | 4 | [] | no_license | import java.lang.String;
class Date {
// Variables
private int day;
private int month;
private int year;
// Constructors
public Date()
{
this(0,0,0);
}
public Date( int d, int m , int y )
{
this.day = d;
this.month = m;
this.year = y;
}
/** public function that returns integer "day" */
public int get_day()
{
return this.day;
}
/** public function that returns integer "month" */
public int get_month()
{
return this.month;
}
/** public function that returns integer "year" */
public int get_year()
{
return this.year;
}
/** public function that sets integer "day" */
public void set_day( int d )
{
this.day = d;
}
/** public function that sets integer "month" */
public void set_month( int m )
{
this.month = m;
}
/** public function that sets integer "year" */
public void set_year( int y )
{
this.year = y;
}
/** public function that returns a string in DAY / MONTH / YEAR format */
public String toString()
{
return String.valueOf(day) + " / " + String.valueOf(month) + " / " + String.valueOf(year);
}
public static void main( String[] args )
{
// User set date
Date date1 = new Date( Integer.parseInt(args[0]), Integer.parseInt(args[1]), Integer.parseInt(args[2]) );
System.out.println( "User set date:");
System.out.println( "The day is the " + date1.get_day() );
System.out.println( "The month number is " + date1.get_month() );
System.out.println( "The year is " + date1.get_year() );
System.out.println( "The full date is " + date1.toString() );
// Machine set date with set() functions used
Date date2 = new Date();
date2.set_day(4);
date2.set_month(1);
date2.set_year(1989);
System.out.println( "\nMachine set date:");
System.out.println( "The day is the " + date2.get_day() );
System.out.println( "The month number is " + date2.get_month() );
System.out.println( "The year is " + date2.get_year() );
System.out.println( "The full date is " + date2.toString() );
}
}
| true |
0f2c53aca5f4b25a339d43b8ef8bf30ec6c197ae | Java | xiaodaguan/spiderplatform | /scheduler/src/main/java/cn/guanxiaoda/spider/scheduler/annotation/TaskGenerator.java | UTF-8 | 561 | 1.9375 | 2 | [] | no_license | package cn.guanxiaoda.spider.scheduler.annotation;
import cn.guanxiaoda.spider.core.enums.Entity;
import cn.guanxiaoda.spider.core.enums.Site;
import cn.guanxiaoda.spider.core.enums.Source;
import cn.guanxiaoda.spider.core.enums.Type;
import org.springframework.stereotype.Component;
import java.lang.annotation.*;
/**
* Created by guanxiaoda on 2018/1/13.
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Component
@Inherited
public @interface TaskGenerator {
Site site();
Source source();
Entity entity();
Type type();
}
| true |
e9db93385852d574cb562b04b54e391e54bb2a7e | Java | niccs/WineManagementSystem | /src/main/java/com/winery/codingChallange/wines/service/WineService.java | UTF-8 | 578 | 2.078125 | 2 | [] | no_license | package com.winery.codingChallange.wines.service;
import java.util.List;
import java.util.Set;
import com.winery.codingChallange.wines.model.GrapeComponent;
import com.winery.codingChallange.wines.model.Wine;
public interface WineService {
List<Wine> getWines();
Wine getWine(String id);
List<String>printYearBreakdown(Set<GrapeComponent> components);
List<String>printRegionBreakdown(Set<GrapeComponent> components);
List<String>printVarietyBreakdown(Set<GrapeComponent> components);
List<String>printYearAndVarietyBreakdown(Set<GrapeComponent> components);
}
| true |
3e518e1b57d9ecf9f383ceb01843bed06c832fe9 | Java | SergeyUdaltsov/Hbcu | /src/main/java/com/hbcu/model/Customer.java | UTF-8 | 3,819 | 2.40625 | 2 | [] | no_license | package com.hbcu.model;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.hbcu.model.contract.Contract;
import java.util.ArrayList;
import java.util.List;
@DynamoDBTable(tableName = "Customers")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Customer {
@DynamoDBAttribute(attributeName = "id")
@DynamoDBHashKey
private int id;
@DynamoDBAttribute(attributeName = "cn")
private String companyName;
@DynamoDBAttribute(attributeName = "email")
private String email;
@DynamoDBAttribute(attributeName = "c")
private List<Contract> contracts;
@DynamoDBAttribute(attributeName = "cont")
private String contacts;
@DynamoDBAttribute(attributeName = "desc")
private String description;
public Customer() {
this.contracts = new ArrayList<Contract>();
}
public int getId() {
return this.id;
}
public void setId(final int id) {
this.id = id;
}
public String getCompanyName() {
return this.companyName;
}
public void setCompanyName(final String companyName) {
this.companyName = companyName;
}
public String getEmail() {
return this.email;
}
public void setEmail(final String email) {
this.email = email;
}
public List<Contract> getContracts() {
return this.contracts;
}
public void setContracts(final List<Contract> contracts) {
this.contracts = contracts;
}
public String getContacts() {
return this.contacts;
}
public void setContacts(final String contacts) {
this.contacts = contacts;
}
public String getDescription() {
return this.description;
}
public void setDescription(final String description) {
this.description = description;
}
public static CustomerBuilder customerBuilder() {
return new CustomerBuilder();
}
@Override
public String toString() {
return "Customer{id=" + this.id + ", companyName='" + this.companyName + '\'' + ", email='" + this.email + '\'' + ", contracts=" + this.contracts + ", contacts='" + this.contacts + '\'' + ", description='" + this.description + '\'' + '}';
}
public static class CustomerBuilder {
private Customer customer;
public CustomerBuilder() {
this.customer = new Customer();
}
@JsonProperty("id")
public CustomerBuilder withId(int id) {
this.customer.setId(id);
return this;
}
@JsonProperty("cn")
public CustomerBuilder withCompanyName(String companyName) {
this.customer.setCompanyName(companyName);
return this;
}
@JsonProperty("c")
public CustomerBuilder withContracts(List<Contract> contracts) {
this.customer.setContracts(contracts);
return this;
}
@JsonProperty("cont")
public CustomerBuilder withContacts(String contacts) {
this.customer.setContacts(contacts);
return this;
}
@JsonProperty("email")
public CustomerBuilder withEmail(String email) {
this.customer.setEmail(email);
return this;
}
@JsonProperty("desc")
public CustomerBuilder withDescription(String description) {
this.customer.setDescription(description);
return this;
}
public Customer build() {
return this.customer;
}
}
} | true |
644aec007929366e30f039eab4b4c84b24565ff7 | Java | damianniesteruk/SaperClient | /test/ServerDataTest.java | UTF-8 | 576 | 1.75 | 2 | [] | no_license | /**
* @author Damian
*/
public class ServerDataTest {
@org.junit.Test
public void testBlankIPServer() {
}
@org.junit.Test
public void testIncorrectIPServer() {
}
@org.junit.Test
public void testCorrectIPServer() {
}
//==========================================================================
@org.junit.Test
public void testBlankPortServer() {
}
@org.junit.Test
public void testIncorrectPortServer() {
}
@org.junit.Test
public void testCorrectPortServer() {
}
}
| true |
140de548fc8c6bd21007d2ae59befeda92386d99 | Java | amanyadv/test-android | /Register/app/src/main/java/com/ibusl/android/register/fragment/ItemsFragment.java | UTF-8 | 2,394 | 2.125 | 2 | [] | no_license | package com.ibusl.android.register.fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import com.ibusl.android.register.R;
import com.ibusl.android.register.activity.CommonItemsViewActivity;
import com.ibusl.android.register.adapter.ItemsAdapter;
import butterknife.Bind;
import butterknife.ButterKnife;
public class ItemsFragment extends Fragment {
@Bind(R.id.items_list_view)
ListView listView;
public ItemsFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*/
public static ItemsFragment newInstance() {
return new ItemsFragment();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_items, container, false);
ButterKnife.bind(this, rootView);
listView.setBackgroundColor(0xffffffff);
listView.setDivider(null);
listView.setDividerHeight(0);
listView.setVerticalScrollBarEnabled(false);
listView.setAdapter(new ItemsAdapter(ItemsFragment.this.getActivity()));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(ItemsFragment.this.getActivity(),CommonItemsViewActivity.class);
intent.putExtra("item_type",position);
startActivity(intent);
}
});
return rootView;
}
@Override
public void onDestroyView() {
super.onDestroyView();
ButterKnife.unbind(ItemsFragment.this.getActivity());
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
}
@Override
public void onDetach() {
super.onDetach();
}
}
| true |
ae5fdeb6f9ee7ea30c8a41ac6edc8ea3afc61437 | Java | caychan/DesignPattern | /src/abstractFactory/Factory2.java | UTF-8 | 127 | 2.265625 | 2 | [] | no_license | package abstractFactory;
abstract class Factory2 {
abstract IProductA getProductA2();
abstract IProductB getProductB2();
}
| true |
314fb2f07e0b91d13cc66128e2cb68c7518c9963 | Java | selsama/ot-harjoitus | /SnakeGame/src/test/java/domain/SnakeHeadTest.java | UTF-8 | 6,159 | 3.21875 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package domain;
import javafx.scene.paint.*;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import snakegame.domain.*;
/**
*
* @author salmison
*/
public class SnakeHeadTest {
SnakeHead head;
@Before
public void setUp() {
head = new SnakeHead(10,10);
}
// TODO add test methods here.
// The methods must be annotated with annotation @Test. For example:
//
@Test
public void snakeHeadTurnLeftWorks(){
head.turnLeft();
assertTrue("SnakeHead doesn't turn left", Direction.LEFT == head.getDirection());
head.setDirection(Direction.RIGHT);
head.turnLeft();
assertFalse("SnakeHead shouldn't turn left when headed right", Direction.LEFT == head.getDirection());
}
@Test
public void snakeHeadTurnRightWorks(){
head.turnRight();
assertTrue("SnakeHead doesn't turn right", Direction.RIGHT == head.getDirection());
head.setDirection(Direction.LEFT);
head.turnRight();
assertFalse("SnakeHead shouldn't turn right when headed left", Direction.RIGHT == head.getDirection());
}
@Test
public void snakeHeadTurnDownWorks(){
head.turnDown();
assertFalse("SnakeHead should not turn down when headed up", Direction.DOWN == head.getDirection());
head.setDirection(Direction.RIGHT);
head.turnDown();
assertTrue("SnakeHead does not turn down", Direction.DOWN == head.getDirection());
}
@Test
public void snakeHeadTurnUpWorks(){
head.setDirection(Direction.RIGHT);
head.turnUp();
assertTrue("SnakeHead doesn't turn up", Direction.UP == head.getDirection());
head.setDirection(Direction.DOWN);
head.turnUp();
assertFalse("SnakeHead shouldn't turn up when headed down", Direction.UP == head.getDirection());
}
@Test
public void snakeHeadMoves(){
double startX=head.getShape().getX();
double startY=head.getShape().getY();
head.move();
assertTrue(startX!=head.getShape().getX() || startY!=head.getShape().getY());
}
@Test
public void snakeHeadMovesRight(){
head.setDirection(Direction.RIGHT);
double start = head.getShape().getX();
head.move();
assertTrue(start<head.getShape().getX());
}
@Test
public void snakeHeadMovesLeft(){
head.setDirection(Direction.LEFT);
double start = head.getShape().getX();
head.move();
assertTrue(start>head.getShape().getX());
}
@Test
public void snakeHeadMovesUp(){
head.setDirection(Direction.UP);
double start = head.getShape().getY();
head.move();
assertTrue(start>head.getShape().getY());
}
@Test
public void snakeHeadMovesDown(){
head.setDirection(Direction.DOWN);
double start = head.getShape().getY();
head.move();
assertTrue(start<head.getShape().getY());
}
@Test
public void snakeHeadDoesNotMoveVerticallyWhenGoingHorizontally(){
double start = head.getShape().getY();
head.setDirection(Direction.RIGHT);
head.move();
head.setDirection(Direction.LEFT);
head.move();
head.move();
assertEquals(start,head.getShape().getY(),0.01);
}
@Test
public void snakeHeadDoesNotMoveHorizontallyWhenGoingVertically(){
double start = head.getShape().getX();
head.setDirection(Direction.DOWN);
head.move();
head.setDirection(Direction.UP);
head.move();
head.move();
assertEquals(start,head.getShape().getX(),0.01);
}
@Test
public void leaveTailLeavesTail() {
assertTrue(head.leaveTail() instanceof SnakeTail);
}
@Test
public void leaveTailLeavesTailBehindSnake() {
Double headX = head.getShape().getX();
Double headY = head.getShape().getY();
head.setDirection(Direction.UP);
SnakeTail tail = head.leaveTail();
assertEquals("When going up: wrong x-coordinate",
headX, tail.getShape().getX(), 0.001);
assertEquals("When going up: wrong y-coordinate",
headY + 10, tail.getShape().getY(), 0.001);
head.setDirection(Direction.RIGHT);
tail = head.leaveTail();
assertEquals("When going right: wrong x-coordinate",
headX - 10, tail.getShape().getX(), 0.001);
assertEquals("When going right: wrong y-coordinate",
headY, tail.getShape().getY(), 0.001);
head.setDirection(Direction.DOWN);
tail = head.leaveTail();
assertEquals("When going down: wrong x-coordinate",
headX, tail.getShape().getX(), 0.001);
assertEquals("When going down: wrong y-coordinate",
headY - 10, tail.getShape().getY(), 0.001);
head.setDirection(Direction.LEFT);
tail = head.leaveTail();
assertEquals("When going left: wrong x-coordinate",
headX + 10, tail.getShape().getX(), 0.001);
assertEquals("When going left: wrong y-coordinate",
headY, tail.getShape().getY(), 0.001);
}
@Test
public void snakeHeadColorTest() {
assertEquals("Snake begins with wrong color", Color.MEDIUMVIOLETRED, head.getColor());
head.setColor(Color.CORAL);
if(head.getColor() == Color.MEDIUMVIOLETRED) {
fail("setColor does not change color");
}
assertEquals("setColor changes to wrong color", Color.CORAL, head.getColor());
}
//
// @Test
// public void snakeHeadDoesNotMoveRightAway(){
//
// }
// These are higher level tests, i think
// @Test
// public void snakeHeadMovesWhenKeyIsPressed(){
//
// }
}
| true |
2af34a1ff2eb770289abc837ca48a5455e1b4f36 | Java | anaivanovska/emt_rent_advertisement | /src/main/java/mk/com/ukim/finki/rent_advertisement/domain/model/Gender.java | UTF-8 | 100 | 1.796875 | 2 | [] | no_license | package mk.com.ukim.finki.rent_advertisement.domain.model;
public enum Gender {
Male, Female
}
| true |
768de9aeeff3c25e28b1d6d9ddf9368717d89836 | Java | Qhycm3649/export_parent | /export_cargo_service/src/main/java/com/xyou/service/cargo/impl/ExportProductServiceImpl.java | UTF-8 | 2,311 | 2.140625 | 2 | [] | no_license | package com.xyou.service.cargo.impl;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xyou.dao.cargo.ExportProductDao;
import com.xyou.domain.cargo.ExportProduct;
import com.xyou.domain.cargo.ExportProductExample;
import com.xyou.service.cargo.ExportProductService;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Date;
import java.util.List;
import java.util.UUID;
//报运商品的服务实现类
@Service
public class ExportProductServiceImpl implements ExportProductService {
@Autowired
private ExportProductDao exportProductDao;
//报运商品的分页列表
@Override
public PageInfo<ExportProduct> findByPage(ExportProductExample exportProductExample, int pageNum, int pageSize) {
//1. 设置开始页与页面大小
PageHelper.startPage(pageNum,pageSize);
//2. 设置所有
List<ExportProduct> list = exportProductDao.selectByExample(exportProductExample);
//3 /.构建一个PageInfo
PageInfo<ExportProduct> pageInfo = new PageInfo<>(list);
return pageInfo;
}
//根据条件查询全部的报运商品
@Override
public List<ExportProduct> findAll(ExportProductExample exportProductExample) {
return exportProductDao.selectByExample(exportProductExample);
}
//根据id查找报运商品
@Override
public ExportProduct findById(String id) {
ExportProduct exportProduct = exportProductDao.selectByPrimaryKey(id);
return exportProduct;
}
//添加报运商品
@Override
public void save(ExportProduct exportProduct) {
//设置主键
exportProduct.setId(UUID.randomUUID().toString());
exportProduct.setCreateTime(new Date());
exportProduct.setUpdateTime(new Date());
exportProductDao.insertSelective(exportProduct);
}
//更新报运商品
@Override
public void update(ExportProduct exportProduct) {
exportProduct.setUpdateTime(new Date());
exportProductDao.updateByPrimaryKeySelective(exportProduct);
}
//根据主键删除报运商品
@Override
public void delete(String id) {
exportProductDao.deleteByPrimaryKey(id);
}
}
| true |
0047f036d8dc0e9790a135c9f30f083b6b6f53d0 | Java | SpoorthiRajanna/NewRepository | /VehicleRental/src/com/service/PaymentService.java | UTF-8 | 172 | 1.765625 | 2 | [] | no_license | package com.service;
import java.util.ArrayList;
import com.bean.Payment;
public interface PaymentService {
public ArrayList<Payment> payment(String vid);
}
| true |
a330058df360a2d639c4e5903023d15552aff656 | Java | knittmann/countries_spring_boot | /src/main/java/com/example/springmvc/service/CountryService.java | UTF-8 | 1,005 | 2.34375 | 2 | [] | no_license | package com.example.springmvc.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.springmvc.entity.Country;
import com.example.springmvc.repo.CountryRepo;
@Service
public class CountryService {
@Autowired
CountryRepo repo;
public List<Country> getAllCountries() {
return repo.findAll();
}
public Country getCountryById(Long id) {
return repo.findById(id).get();
}
public void addNewCountry(Country country) {
// Country c = repo.getOne(country.getId());
// c.setId(country.getId());
// c.setName(country.getName());
// c.setCapitol(country.getCapitol());
// c.setPopulation(country.getPopulation());
repo.save(country);
}
public void deleteCountryById(Long id) {
repo.deleteById(id);
}
public void updateCountryPopulation(Country country) {
Country c = repo.getOne(country.getId());
c.setPopulation(country.getPopulation());
repo.save(country);
}
}
| true |
228627ce76b4990447bdef6bfd39ee9a9c600b3f | Java | jaikumxr/JAVA-Intermediate | /PepList/Arrays/SubarrayWithGivenSum.java | UTF-8 | 1,510 | 3.984375 | 4 | [
"MIT"
] | permissive |
// { Driver Code Starts
import java.util.*;
import java.lang.*;
import java.io.*;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int i = 0; i < t; i++) {
int n = sc.nextInt();
int s = sc.nextInt();
int[] m = new int[n];
for (int j = 0; j < n; j++) {
m[j] = sc.nextInt();
}
SubarrayWithGivenSum obj = new SubarrayWithGivenSum();
ArrayList<Integer> res = obj.subarraySum(m, n, s);
for (int ii = 0; ii < res.size(); ii++)
System.out.print(res.get(ii) + " ");
System.out.println();
}
}
}// } Driver Code Ends
class SubarrayWithGivenSum {
// Function to find a continuous sub-array which adds up to a given number.
static ArrayList<Integer> subarraySum(int[] arr, int n, int s) {
ArrayList<Integer> res = new ArrayList<>();
int l = 0;
int r = 0;
int sum = arr[0];
while(l!=arr.length-1){
if(sum<s){
r++;
sum+=arr[r];
} else if(sum>s) {
sum-=arr[l];
l++;
}
if (sum==s){
res.add(l+1); //as program requires the natural number index i.e. 1,2,3, etc
res.add(r+1);
return res;
}
}
res.add(-1);
return res;
}
} | true |
792293b4ab4e4fa17b2404a33a28e95987decaf0 | Java | mikepatel/Artificial-Intelligence | /Hw1/City.java | UTF-8 | 551 | 2.90625 | 3 | [] | no_license | /* Michael Patel
* mrpatel5
* CSC 520
* Homework 1
* Fall 2018
*
* City user-defined object:
* - city name
* - latitude North coordinate of city
* - longitude West coordinate of city
*/
public class City {
String name;
double latitude;
double longitude;
/*********************************************************************************************/
// Constructor
public City(String name, double latitude, double longitude) {
this.name = name;
this.latitude = latitude;
this.longitude = longitude;
}
} | true |
1a02127c96acd4d347c6f2006a06d2436ce7dfbc | Java | brokenq/itsnow | /backend/platform/src/main/java/dnt/itsnow/platform/web/support/PageRequestResponseBodyMethodProcessor.java | UTF-8 | 2,423 | 2.34375 | 2 | [] | no_license | /**
* Developer: Kadvin Date: 14-10-10 下午4:21
*/
package dnt.itsnow.platform.web.support;
import dnt.itsnow.platform.service.Page;
import org.springframework.core.MethodParameter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
/**
* <h1>处理Page<Record>的输出</h1>
*
* 处理方式就是将分页信息通过http头输出,实际数据通过http body输出
*/
public class PageRequestResponseBodyMethodProcessor extends RequestResponseBodyMethodProcessor {
public PageRequestResponseBodyMethodProcessor(
List<HttpMessageConverter<?>> messageConverters,
ContentNegotiationManager contentNegotiationManager) {
super(messageConverters, contentNegotiationManager);
}
@Override
public boolean supportsReturnType(MethodParameter returnType) {
return Page.class.isAssignableFrom(returnType.getParameterType());
}
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest) throws IOException, HttpMediaTypeNotAcceptableException {
Page page = (Page)returnValue;
ServletWebRequest request = (ServletWebRequest) webRequest;
HttpServletResponse response = request.getResponse();
response.setHeader(Page.TOTAL, String.valueOf(page.getTotalElements()));
response.setHeader(Page.PAGES, String.valueOf(page.getTotalPages()));
response.setHeader(Page.NUMBER, String.valueOf(page.getNumber() + 1));
response.setHeader(Page.REAL, String.valueOf(page.getNumberOfElements()));
response.setHeader(Page.SORT, String.valueOf(page.getSort()));
response.setHeader(Page.COUNT, String.valueOf(page.getSize()));
super.handleReturnValue(page.getContent(), returnType, mavContainer, webRequest);
}
}
| true |
47792ad9cbc790de10eae81351a60c60c281cb8e | Java | alesegdia/platgen | /src/com/alesegdia/platgen/sector/Sector.java | UTF-8 | 322 | 2.234375 | 2 | [] | no_license | package com.alesegdia.platgen.sector;
import com.alesegdia.platgen.region.Region;
import com.alesegdia.platgen.util.Rect;
public class Sector extends Rect {
public Region region;
public boolean isGap;
public int height; // valid if not gap
public Sector(int x, int y, int w, int h) {
super(x, y, w, h);
}
}
| true |
dbc486a0e355738e5b3898a00a953c68858305b4 | Java | ahmedcevizci/sensor-co2 | /src/test/java/info/alaz/sensor/co2/e2e/Co2SensorApiE2e.java | UTF-8 | 9,827 | 1.976563 | 2 | [] | no_license | package info.alaz.sensor.co2.e2e;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import info.alaz.sensor.co2.TestObjectCreator;
import info.alaz.sensor.co2.dto.MeasurementRequestDto;
import info.alaz.sensor.co2.entity.SensorStatus;
import info.alaz.sensor.co2.util.DateUtil;
import net.serenitybdd.junit.spring.integration.SpringIntegrationSerenityRunner;
import net.thucydides.core.annotations.Steps;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.context.embedded.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpStatus;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.jdbc.Sql;
import org.testcontainers.containers.DockerComposeContainer;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.ZoneId;
import java.time.ZonedDateTime;
@RunWith(SpringIntegrationSerenityRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestPropertySource("classpath:application-test.yml")
@ActiveProfiles("test")
public class Co2SensorApiE2e {
@ClassRule
public static DockerComposeContainer environment =
new DockerComposeContainer(new File("src/test/resources/docker-compose.yml"))
.withExposedService("postgresql-db", 5432);
private static ObjectMapper objectMapper;
@Steps
private Co2SensorSteps co2SensorSteps;
@LocalServerPort
private int port;
@BeforeClass
public static void setupClass() throws IOException {
objectMapper = new ObjectMapper();
objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
objectMapper.configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, true);
objectMapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true);
objectMapper.registerModule(new JavaTimeModule());
objectMapper.setDateFormat(new SimpleDateFormat(DateUtil.DATE_FORMAT_PATTERN));
}
@Before
public void setup() {
co2SensorSteps.setup(port);
}
public static <T> String getDtoAsJson(T dto) throws JsonProcessingException {
return objectMapper.writeValueAsString(dto);
}
@Test
@Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD, scripts = "classpath:testscripts/fillDB.sql")
@Sql(executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD, scripts = "classpath:testscripts/clearDB.sql")
public void as_user_I_want_to_create_a_new_normal_measurement_on_existing_sensor_which_has_no_previous_measurement() throws Exception {
//Given
//When
co2SensorSteps.createSensorMeasurementsOnSensor(TestObjectCreator.EXISTING_OK_SENSOR_ID, TestObjectCreator.NEW_NORMAL_MEASUREMENT);
//Then
co2SensorSteps.validateHttpStatus(HttpStatus.CREATED);
}
@Test
@Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD, scripts = "classpath:testscripts/fillDB.sql")
@Sql(executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD, scripts = "classpath:testscripts/clearDB.sql")
public void as_user_I_want_to_create_three_alerting_measurement_on_existing_ok_sensor_and_change_its_state_to_alert() throws Exception {
MeasurementRequestDto firstMeasurement = new MeasurementRequestDto(2200, ZonedDateTime.of(2019, 5, 5, 20, 0, 0, 0, ZoneId.systemDefault()));
MeasurementRequestDto secondMeasurement = new MeasurementRequestDto(2300, ZonedDateTime.of(2019, 5, 5, 21, 0, 0, 0, ZoneId.systemDefault()));
MeasurementRequestDto thirdMeasurement = new MeasurementRequestDto(2400, ZonedDateTime.of(2019, 5, 5, 22, 0, 0, 0, ZoneId.systemDefault()));
co2SensorSteps.createSensorMeasurementsOnSensor(TestObjectCreator.EXISTING_OK_SENSOR_ID2, firstMeasurement);
co2SensorSteps.validateHttpStatus(HttpStatus.CREATED);
co2SensorSteps.getSensorStatus(TestObjectCreator.EXISTING_OK_SENSOR_ID2);
co2SensorSteps.validateHttpStatus(HttpStatus.OK);
co2SensorSteps.validateSensorStatus(SensorStatus.WARN);
co2SensorSteps.createSensorMeasurementsOnSensor(TestObjectCreator.EXISTING_OK_SENSOR_ID2, secondMeasurement);
co2SensorSteps.validateHttpStatus(HttpStatus.CREATED);
co2SensorSteps.getSensorStatus(TestObjectCreator.EXISTING_OK_SENSOR_ID2);
co2SensorSteps.validateHttpStatus(HttpStatus.OK);
co2SensorSteps.validateSensorStatus(SensorStatus.WARN);
co2SensorSteps.createSensorMeasurementsOnSensor(TestObjectCreator.EXISTING_OK_SENSOR_ID2, thirdMeasurement);
co2SensorSteps.validateHttpStatus(HttpStatus.CREATED);
co2SensorSteps.getSensorStatus(TestObjectCreator.EXISTING_OK_SENSOR_ID2);
co2SensorSteps.validateHttpStatus(HttpStatus.OK);
co2SensorSteps.validateSensorStatus(SensorStatus.ALERT);
}
@Test
@Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD, scripts = "classpath:testscripts/fillDB.sql")
@Sql(executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD, scripts = "classpath:testscripts/clearDB.sql")
public void as_user_I_want_to_create_three_normal_measurement_on_existing_alerting_sensor_and_change_its_state_to_ok() throws Exception {
MeasurementRequestDto firstMeasurement = new MeasurementRequestDto(1900, ZonedDateTime.of(2019, 5, 5, 20, 0, 0, 0, ZoneId.systemDefault()));
MeasurementRequestDto secondMeasurement = new MeasurementRequestDto(1800, ZonedDateTime.of(2019, 5, 5, 21, 0, 0, 0, ZoneId.systemDefault()));
MeasurementRequestDto thirdMeasurement = new MeasurementRequestDto(1700, ZonedDateTime.of(2019, 5, 5, 22, 0, 0, 0, ZoneId.systemDefault()));
co2SensorSteps.createSensorMeasurementsOnSensor(TestObjectCreator.EXISTING_ALERT_SENSOR_ID, firstMeasurement);
co2SensorSteps.validateHttpStatus(HttpStatus.CREATED);
co2SensorSteps.getSensorStatus(TestObjectCreator.EXISTING_ALERT_SENSOR_ID);
co2SensorSteps.validateHttpStatus(HttpStatus.OK);
co2SensorSteps.validateSensorStatus(SensorStatus.ALERT);
co2SensorSteps.createSensorMeasurementsOnSensor(TestObjectCreator.EXISTING_ALERT_SENSOR_ID, secondMeasurement);
co2SensorSteps.validateHttpStatus(HttpStatus.CREATED);
co2SensorSteps.getSensorStatus(TestObjectCreator.EXISTING_ALERT_SENSOR_ID);
co2SensorSteps.validateHttpStatus(HttpStatus.OK);
co2SensorSteps.validateSensorStatus(SensorStatus.ALERT);
co2SensorSteps.createSensorMeasurementsOnSensor(TestObjectCreator.EXISTING_ALERT_SENSOR_ID, thirdMeasurement);
co2SensorSteps.validateHttpStatus(HttpStatus.CREATED);
co2SensorSteps.getSensorStatus(TestObjectCreator.EXISTING_ALERT_SENSOR_ID);
co2SensorSteps.validateHttpStatus(HttpStatus.OK);
co2SensorSteps.validateSensorStatus(SensorStatus.OK);
}
@Test
@Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD, scripts = "classpath:testscripts/fillDB.sql")
@Sql(executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD, scripts = "classpath:testscripts/clearDB.sql")
public void as_user_I_want_to_create_a_new_alarming_measurement_on_existing_sensor_which_has_no_previous_measurement() throws Exception {
//Given
//When
co2SensorSteps.createSensorMeasurementsOnSensor(TestObjectCreator.EXISTING_OK_SENSOR_ID, TestObjectCreator.NEW_ALARMING_MEASUREMENT);
//Then
co2SensorSteps.validateHttpStatus(HttpStatus.CREATED);
}
@Test
@Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD, scripts = "classpath:testscripts/fillDB.sql")
@Sql(executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD, scripts = "classpath:testscripts/clearDB.sql")
public void as_user_I_want_to_fetch_status_on_existing_sensor_which_has_no_previous_measurement() throws Exception {
//Given
//When
co2SensorSteps.getSensorStatus(TestObjectCreator.EXISTING_OK_SENSOR_ID);
//Then
co2SensorSteps.validateHttpStatus(HttpStatus.OK);
co2SensorSteps.validateSensorStatus(SensorStatus.OK);
}
@Test
@Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD, scripts = "classpath:testscripts/fillDB.sql")
@Sql(executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD, scripts = "classpath:testscripts/clearDB.sql")
public void as_user_I_want_to_fetch_metrics_on_alerting_existing_sensor_which_has_previous_measurements() throws Exception {
//Given
//When
co2SensorSteps.getSensorMetrics(TestObjectCreator.EXISTING_ALERT_SENSOR_ID);
//Then
co2SensorSteps.validateHttpStatus(HttpStatus.OK);
co2SensorSteps.validateSensorMetrics(2400, 1800);
}
@Test
@Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD, scripts = "classpath:testscripts/fillDB.sql")
@Sql(executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD, scripts = "classpath:testscripts/clearDB.sql")
public void as_user_I_want_to_list_alerts_on_alerting_existing_sensor_which_has_previous_measurements() throws Exception {
//Given
//When
co2SensorSteps.listAlerts(TestObjectCreator.EXISTING_ALERT_SENSOR_ID);
//Then
co2SensorSteps.validateHttpStatus(HttpStatus.OK);
co2SensorSteps.validateAlertList();
}
}
| true |
71ada86cf3ba1e04d490928e514259584c1e32eb | Java | anashish/imagePic | /androidimgprolibmaster/src/main/java/net/akhyar/android/imgpro/Channel.java | UTF-8 | 189 | 1.921875 | 2 | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | permissive | package net.akhyar.android.imgpro;
public class Channel {
public static final int RED = 0xff0000;
public static final int GREEN = 0x00ff00;
public static final int BLUE = 0x0000ff;
}
| true |
3cc7640370a5c9298f14cb1c6702ce38f953a1fa | Java | VINODRAMAKRISHNAN/java-ui-api-test-projects | /astadia.test.seleniumcucumber/src/test/java/test/cucumberbasic/StepsCucumberBasic.java | UTF-8 | 950 | 2.84375 | 3 | [] | no_license | package test.cucumberbasic;
import org.testng.Assert;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class StepsCucumberBasic {
int input = 0;
@Given("^I have entered (\\d+) into the calculator$")
public void i_have_entered_into_the_calculator(int arg1) throws Throwable {
input = input + arg1;
}
@Given("^You have entered (\\d+) into the calculator$")
public void you_have_entered_into_the_calculator(int arg1) throws Throwable {
input = input + arg1;
}
@When("^I press add$")
public void i_press_add() throws Throwable {
input = input + 100;
}
@Then("^the result should be (\\d+) on the screen$")
public void the_result_should_be_on_the_screen(int arg1) throws Throwable {
//Assert.areEqual(arg1.toS, , "Result Not matching expected value");
Assert.assertEquals(arg1, input,"Result Not matching expected value");
}
}
| true |
d0fede3f0ec3f9db7ab88908045d991a8b17a4d2 | Java | Obochuk/training | /src/epam/training/project2/src/test/model/entity/TestText.java | UTF-8 | 1,413 | 2.6875 | 3 | [] | no_license | package model.entity;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import static org.junit.Assert.assertEquals;
@RunWith(Parameterized.class)
public class TestText {
private Text text;
@Parameterized.Parameter
public String textValue;
@Parameterized.Parameter(1)
public Word word;
@Parameterized.Parameter(2)
public int expectedAmount;
@Parameterized.Parameter(3)
public List<Sentence> expectedSentences;
@Before
public void setUp(){
text = new Text(textValue);
}
@Parameterized.Parameters
public static Collection<Object[]> data(){
return Arrays.asList(new Object[][]{
{"Hello! Today we are gonna do some important stuff. One of it is catch some type of bugs. Second one is to get rid of it.",
new Word("it"), 2, Arrays.asList(new Sentence("Hello! "),
new Sentence("Today we are gonna do some important stuff. "),
new Sentence("One of it is catch some type of bugs. "),
new Sentence("Second one is to get rid of it."))
}
});
}
@Test
public void testGetSentences(){
assertEquals(expectedSentences, text.getSentences());
}
}
| true |
88277b862d06650241e6d17434d1645c6ea30cbc | Java | Paladin1412/house | /java/classes/cn/jiguang/a/a/a/g.java | UTF-8 | 3,269 | 1.882813 | 2 | [
"Apache-2.0"
] | permissive | package cn.jiguang.a.a.a;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import cn.jiguang.d.d;
import com.growingio.android.sdk.agent.VdsAgent;
final class g
implements LocationListener
{
private static final String[] z;
static
{
String[] arrayOfString = new String[4];
Object localObject1 = "9{\026q\t\030d(Y\t\037l\000J";
int i = -1;
int j = 0;
Object localObject3 = arrayOfString;
localObject1 = ((String)localObject1).toCharArray();
int k = localObject1.length;
int m;
int n;
int i1;
label42:
Object localObject2;
int i2;
label91:
label113:
Object localObject4;
int i3;
if (k <= 1)
{
m = 0;
n = j;
i1 = i;
j = m;
for (;;)
{
localObject2 = localObject1;
i2 = localObject2[m];
switch (j % 5)
{
default:
i = 103;
localObject2[m] = ((char)(i ^ i2));
j += 1;
if (k != 0) {
break label113;
}
m = k;
}
}
i = k;
localObject4 = localObject3;
i3 = n;
localObject2 = localObject1;
i2 = i1;
}
for (;;)
{
i1 = i2;
localObject1 = localObject2;
n = i3;
localObject3 = localObject4;
k = i;
m = j;
if (i > j) {
break label42;
}
localObject1 = new String((char[])localObject2).intern();
switch (i2)
{
default:
localObject4[i3] = localObject1;
localObject1 = "\022d\006Y\023\027d\013\030\013\027x\021]\t\033y_";
j = 1;
i = 0;
break;
case 0:
localObject4[i3] = localObject1;
localObject1 = "\021e5J\b\bb\001]\025:b\026Y\005\022n\001\002";
j = 2;
i = 1;
break;
case 1:
localObject4[i3] = localObject1;
j = 3;
localObject1 = "\021e5J\b\bb\001]\025;e\004Z\013\033o_";
i = 2;
break;
case 2:
localObject4[i3] = localObject1;
z = arrayOfString;
return;
i = 126;
break label91;
i = 11;
break label91;
i = 101;
break label91;
i = 56;
break label91;
m = 0;
i2 = i;
localObject2 = localObject1;
i3 = j;
localObject4 = localObject3;
i = k;
j = m;
}
}
}
g(f paramf) {}
public final void onLocationChanged(Location paramLocation)
{
VdsAgent.onLocationChanged(this, paramLocation);
d.c(z[0], z[1] + paramLocation);
if (paramLocation != null) {
f.a(this.a, paramLocation, f.a(this.a));
}
f.b(this.a);
}
public final void onProviderDisabled(String paramString)
{
d.a(z[0], z[2] + paramString);
f.b(this.a);
}
public final void onProviderEnabled(String paramString)
{
d.a(z[0], z[3] + paramString);
this.a.c();
this.a.b();
}
public final void onStatusChanged(String paramString, int paramInt, Bundle paramBundle) {}
}
/* Location: /Users/gaoht/Downloads/zirom/classes-dex2jar.jar!/cn/jiguang/a/a/a/g.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | true |
2447964f0c81790165f668642330cd3fd6e84eca | Java | Metatavu/jouko | /jouko-api/src/main/java/fi/metatavu/jouko/api/GprsApi.java | UTF-8 | 11,978 | 1.789063 | 2 | [
"MIT"
] | permissive | package fi.metatavu.jouko.api;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.protobuf.InvalidProtocolBufferException;
import fi.metatavu.jouko.api.device.DeviceCommunicator;
import fi.metatavu.jouko.api.device.Laiteviestit.*;
import fi.metatavu.jouko.api.model.ControllerEntity;
import fi.metatavu.jouko.api.model.DeviceEntity;
import fi.metatavu.jouko.api.model.GprsMessageEntity;
import fi.metatavu.jouko.api.model.MeasurementType;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Deals with the Gprs communication protocol
* Sets the API path to "/gprs" for the protocol
*
* @Path("/gprs")
*/
@Stateless
@Path("/gprs")
public class GprsApi {
@Inject
private Logger logger;
@Inject
private DeviceController deviceController;
@Inject
private DeviceCommunicator deviceCommunicator;
@Context
private HttpServletRequest request;
private static final Pattern MESSAGE_PATTERN = Pattern.compile("\\{([^}]*)\\}");
private static class InvalidDeviceException extends Exception {
public InvalidDeviceException(String msg) {
super(msg);
}
private static final long serialVersionUID = 8322806559664622171L;
}
private static class Envelope {
private DevEuiUplink devEuiUplink;
@JsonProperty("DevEUI_uplink")
public DevEuiUplink getDevEuiUplink() {
return devEuiUplink;
}
@JsonProperty("DevEUI_uplink")
public void setDevEuiUplink(DevEuiUplink devEuiUplink) {
this.devEuiUplink = devEuiUplink;
}
}
@JsonIgnoreProperties(ignoreUnknown=true)
private static class DevEuiUplink {
private String customerId;
private String devEui;
private int fPort;
private int fCntUp;
private String payloadHex;
@JsonProperty("CustomerID")
public String getCustomerId() {
return customerId;
}
@JsonProperty("CustomerID")
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
@JsonProperty("DevEUI")
public String getDevEui() {
return devEui;
}
@JsonProperty("DevEUI")
public void setDevEui(String devEui) {
this.devEui = devEui;
}
@JsonProperty("FPort")
public int getFPort() {
return fPort;
}
@JsonProperty("FPort")
public void setFPort(int fPort) {
this.fPort = fPort;
}
@JsonProperty("FCntUp")
public int getFCntUp() {
return fCntUp;
}
@JsonProperty("FCntUp")
public void setFCntUp(int fCntUp) {
this.fCntUp = fCntUp;
}
@JsonProperty("payload_hex")
public String getPayloadHex() {
return payloadHex;
}
@JsonProperty("payload_hex")
public void setPayloadHex(String payloadHex) {
this.payloadHex = payloadHex;
}
}
/**
* Creates API path to communicate with Lora device
* Handles lora communication protocol
*
* @POST
* @Path("/lora/")
*/
@POST
@Path("/lora/")
public Response communicateWithLoraDevice(
Envelope envelope,
@QueryParam("AS_ID") String asId,
@QueryParam("LrnDevEui") String lrnDevEui,
@QueryParam("LrnFPort") String lrnFPort,
@QueryParam("LrnInfos") String lrnInfos,
@QueryParam("Time") String time,
@QueryParam("Token") String token
) {
DevEuiUplink uplink = envelope.getDevEuiUplink();
String payloadHex = uplink.getPayloadHex();
String message;
try {
/**
* Decode payloadHex to message
*/
message = new String(Hex.decodeHex(payloadHex.toCharArray()),
StandardCharsets.US_ASCII);
} catch (DecoderException e) {
logger.error("Invalid hex string: {}", payloadHex);
return Response.status(400).entity("Invalid hex string").build();
}
String bodyParameters = String.format("%s%s%d%d%s",
uplink.getCustomerId(),
uplink.getDevEui(),
uplink.getFPort(),
uplink.getFCntUp(),
uplink.getPayloadHex());
String queryParameters = String.format(
"LrnDevEui=%s&LrnFPort=%s&LrnInfos=%s&AS_ID=%s&Time=%s",
lrnDevEui, lrnFPort, lrnInfos, asId, time);
String hashedStringNoKey = bodyParameters + queryParameters;
ControllerEntity controller = deviceController.findControllerByEui(uplink.getDevEui());
logger.info("Eui: {}", uplink.getDevEui());
logger.info("Controller: {}", controller);
if (controller == null) {
return Response.status(Status.BAD_REQUEST).entity("Controller not found").build();
}
String hashedStringKey = hashedStringNoKey + controller.getKey();
/**
* Create a hash using SHA-256 algorithm
*/
String hash = DigestUtils.sha256Hex(hashedStringKey.getBytes(StandardCharsets.UTF_8));
logger.info("kellonaika: {}", time);
logger.info("hash: {}", hash);
logger.info("token: {}", token);
if (!Objects.equals(hash, token)) {
return Response.status(Status.BAD_REQUEST).entity("Bad token").build();
}
Matcher messageMatcher = MESSAGE_PATTERN.matcher(message);
deviceCommunicator.notifyTimeSync(messageMatcher, controller);
Matcher messageMatcher2 = MESSAGE_PATTERN.matcher(message);
List<String> messages = new ArrayList<>();
long deviceId = -1;
GprsMessageEntity oldestMessage = deviceController.getQueuedGprsMessageForController(controller, deviceId);
if (oldestMessage != null) {
deviceCommunicator.sendLoraMessageFromQueue(oldestMessage.getContent(), controller);
deviceController.deleteGprsMessageFromController(controller, oldestMessage);
}
while (messageMatcher2.find()) {
logger.debug("WHILE MESSAGEMATCHER FIND");
String base64 = messageMatcher2.group(1);
byte[] bytes = Base64.decodeBase64(base64);
try {
ViestiLaitteelta viestiLaitteelta = ViestiLaitteelta.parseFrom(bytes);
if (viestiLaitteelta.hasMittaukset()) {
Mittaukset mittaukset = viestiLaitteelta.getMittaukset();
deviceId = mittaukset.getLaiteID();
unpackMittaukset(mittaukset);
}
} catch (InvalidDeviceException | InvalidProtocolBufferException ex) {
return Response
.status(400)
.entity(String.format("Protobuf error: %s", ex.getMessage()))
.build();
}
}
return Response.ok().build();
}
/**
@POST
@Path("/gprs/{eui}")
Creates API path for GPRS device communication
*/
@POST
@Path("/gprs/{eui}")
public Response communicateWithGprsDevice(@PathParam("eui") String eui, String content) {
// TODO basic auth using eui/key
ControllerEntity controller = deviceController.findControllerByEui(eui);
if (controller == null) {
return Response.status(Status.NOT_FOUND)
.entity("No device with eui")
.build();
}
Matcher messageMatcher = MESSAGE_PATTERN.matcher(content);
List<String> messages = new ArrayList<>();
long deviceId = -1;
while (messageMatcher.find()) {
String base64 = messageMatcher.group(1);
/**
* Decode base64 to message
*/
byte[] bytes = Base64.decodeBase64(base64);
try {
ViestiLaitteelta viestiLaitteelta = ViestiLaitteelta.parseFrom(bytes);
if (viestiLaitteelta.hasMittaukset()) {
Mittaukset mittaukset = viestiLaitteelta.getMittaukset();
deviceId = mittaukset.getLaiteID();
unpackMittaukset(mittaukset);
} else {
unpackAikasync(viestiLaitteelta, messages);
}
} catch (InvalidProtocolBufferException | InvalidDeviceException ex) {
return Response
.status(400)
.entity(String.format("Protobuf error: %s", ex.getMessage()))
.build();
}
}
/**
* If messages is empty we want to add messages from db
* If it's not empty we have timesync message there and we only want to respond that
*/
if (messages.isEmpty()) {
GprsMessageEntity oldestMessage = deviceController.getQueuedGprsMessageForController(controller, deviceId);
if (oldestMessage != null) {
messages.add(oldestMessage.getContent());
deviceController.deleteGprsMessageFromController(controller, oldestMessage);
}
}
return Response.ok(String.join(" ", messages)).build();
}
/**
* Unpacks messages from GPRS device
*
* @param mittaukset Measurements from GPRS device
* @throws InvalidDeviceException If device is not found
*/
private void unpackMittaukset(Mittaukset mittaukset) throws InvalidDeviceException {
long deviceId = mittaukset.getLaiteID();
DeviceEntity device = deviceController.findById(deviceId);
if (device == null) {
logger.error("Invalid device ID: {}", deviceId);
throw new InvalidDeviceException(String.format("Invalid device ID: %s", deviceId));
}
Instant endTime = Instant.ofEpochSecond(mittaukset.getAika());
long measurementLength = mittaukset.getPituusMinuutteina();
if (measurementLength == 0) {
measurementLength = 5;
}
int numMeasurements = mittaukset.getKeskiarvotCount();
Instant time = endTime.minus((numMeasurements / 3 ) * measurementLength, ChronoUnit.MINUTES);
int phaseNumber = 0;
boolean relayIsOpen = !mittaukset.hasReleOhjaukset();
for (int average : mittaukset.getKeskiarvotList()) {
deviceController.addPowerMeasurement(
device,
(double)average,
MeasurementType.AVERAGE,
time.atOffset(ZoneOffset.UTC),
time.plus(measurementLength, ChronoUnit.MINUTES).atOffset(ZoneOffset.UTC),
(phaseNumber++ % 3) + 1,
relayIsOpen
);
if ((phaseNumber % 3) == 0) {
time = time.plus(measurementLength, ChronoUnit.MINUTES);
}
}
}
/**
* Unpacks timesync message
*
* @param viestiLaitteelta is the message from the device
* @param messages is the list of messages
* @throws InvalidProtocolBufferException if the message is invalid
*/
private void unpackAikasync(ViestiLaitteelta viestiLaitteelta, List<String> messages) throws InvalidProtocolBufferException {
if (viestiLaitteelta.hasAikasynkLaitteelta()) {
AikasynkLaitteelta sync = viestiLaitteelta.getAikasynkLaitteelta();
long deviceTime = sync.getLaiteaika();
long myTime = Instant.now().getEpochSecond() * 1000;
ViestiLaitteelle replyMessage = ViestiLaitteelle
.newBuilder()
.setAikasynkLaitteelle(
AikasynkLaitteelle.newBuilder()
.setErotus(myTime - deviceTime)
.build())
.build();
String replyMessageString = String.format("{%s}",
/**
* Encode message to base64 string and replyMessage to byte array before base64 encoding
*/
Base64.encodeBase64String(replyMessage.toByteArray()));
/**
* If we end up here, we only want to send timesync message
*/
messages.clear();
messages.add(replyMessageString);
}
}
}
| true |
f089960218c245a9347e2d0ab12832b6236dfaee | Java | Snicfn711/PathfinderCharacterSheet | /app/src/main/java/com/pathfinderstattracker/pathfindercharactersheet/models/ISkill.java | UTF-8 | 807 | 2.234375 | 2 | [] | no_license | package com.pathfinderstattracker.pathfindercharactersheet.models;
import java.io.Serializable;
import java.util.UUID;
/**
* Created by Stephen Hagen on 1/10/2018.
*/
public interface ISkill extends Comparable<ISkill>, Serializable
{
UUID getSkillID();
void setSkillID(UUID skillID);
void setAddedStat(AbilityScoreEnum addedStat);
AbilityScoreEnum getAddedStat();
void setArmorCheckPenaltyApplied(boolean armorCheckPenaltyApplied);
boolean isArmorCheckPenaltyApplied();
void setSkillName(String skillName);
String getSkillName();
int getLevelUpPointsInvested();
void setLevelUpPointsInvested(int levelUpPointsInvested);
int getFavoredClassPointsInvested();
void setFavoredClassPointsInvested(int favoredClassPointsInvested);
int getTotalInvestedPoints();
}
| true |
42d13b631f7b7077006738ee8251bb59ac8a5325 | Java | liuyanjun528/changshnegshu | /annaru-upms-api/src/main/java/com/annaru/upms/service/ITbHisMzFeeDetailService.java | UTF-8 | 414 | 1.59375 | 2 | [
"Apache-2.0"
] | permissive | package com.annaru.upms.service;
import com.annaru.upms.entity.medical.TbHisMzFeeDetail;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* tb_his_mz_fee_detail(门诊收费明细表)
* @author lft
* @date 2019-05-09 11:14:28
*/
public interface ITbHisMzFeeDetailService extends IService<TbHisMzFeeDetail> {
TbHisMzFeeDetail getHisMzFeeDetail(String sfmxid,String xgbz,String yljgdm);
}
| true |
33e5f74ad010b035e18ea4fefc4b659b3ced8be3 | Java | leeef/AuctionOne | /app/src/main/java/com/hlnwl/auction/MainActivity.java | UTF-8 | 399 | 1.726563 | 2 | [] | no_license | package com.hlnwl.auction;
import com.hlnwl.auction.base.MyActivity;
public class MainActivity extends MyActivity {
@Override
protected int getLayoutId() {
return R.layout.activity_order;
}
@Override
protected int getTitleBarId() {
return 0;
}
@Override
protected void initView() {
}
@Override
protected void initData() {
}
}
| true |
b60daee28f3349d9a4f5a417449dc0ed123c76d3 | Java | dexter-aks/datastructures-algorithms | /src/com/leetcode/MinHeap.java | UTF-8 | 584 | 3.265625 | 3 | [] | no_license | package com.leetcode;
import java.util.PriorityQueue;
public class MinHeap {
private int size = 0;
private int k = 0;
private PriorityQueue<Integer> heap;
public MinHeap(int k, int[] nums) {
this.k = k;
heap = new PriorityQueue<>(k);
for (int num : nums) {
add(num);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public int add(int val) {
if (size == k) {
int min = heap.peek();
if (val > min) {
heap.poll();
heap.offer(val);
}
} else {
heap.offer(val);
size++;
}
return heap.peek();
}
} | true |
43a0aae5b901c9ba49bf5bfa885f9579daca1ac5 | Java | AngryDogs/tallink-test | /backend/src/main/api/conference/Config/WebConfig.java | UTF-8 | 731 | 1.9375 | 2 | [] | no_license | package conference.Config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import javax.servlet.http.HttpServletResponse;
/**
* Created by rain on 16/02/2017.
*/
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
| true |
3412ad741b7ba2b9c7677c3c15dcd704c3bff2dd | Java | gaohe1227/spring-boot-demo01 | /src/main/java/com/service/DemoService.java | UTF-8 | 1,030 | 1.9375 | 2 | [] | no_license | package com.service;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import com.jpadao.DemoRepository;
import com.model.Demo;
@Service
public class DemoService {
@Autowired
private DemoRepository demoRepository;
/**
* @throws Exception
* 事务处理案例
* @Title: save
* @Description: TODO
* @param @param demo
* @return void
* @throws
*/
@Transactional
public void save(Demo demo) throws Exception {
try {
demoRepository.save(demo);
//demoRepository.save(demo);
// System.out.println("***************************"+1/0);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//事务回滚
throw new Exception(e.getMessage());
}
}
}
| true |
5a1124c1a600133048d5491c18133b55ac1a356b | Java | Attonasi/tic_tac_toe | /client/src/main/rest/POST.java | UTF-8 | 658 | 2.609375 | 3 | [] | no_license | package main.rest;
import org.apache.http.client.HttpClient;
public class POST extends AbsRESTRequest {
/** The only purpose of this class is to force the user to understand they are
* making a new POST.
*
* @param client HTTPClient used in every RESTRequest.
* @param host String representing the domain name. "http://[something]"
* @param port String representing the port number of the server.
* @param flag String matching the REST endpoint on the server the instance of this
* class targets.
*/
public POST(HttpClient client, String host, String port, String flag) {
super(client, host, port, flag);
}
}
| true |
3ae5a74d9a0a75f1cf13071caa1e84deb2251c0f | Java | todobugs/gxclient-cli-java | /src/main/java/com/gxchain/client/jsonrpc/domain/JsonRpcMessage.java | UTF-8 | 597 | 2.140625 | 2 | [] | no_license | package com.gxchain.client.jsonrpc.domain;
/**
* @Title: JsonRpcMessage
* @Description: jsonRpc消息抽象类
* @Author: mingyi
* @created 2018年4月11日 下午5:59:02
*/
public abstract class JsonRpcMessage {
/**
* jsonrpc 信息体
*/
private String jsonrpc;
/**
* 消息id
*/
private String id;
public String getJsonrpc() {
return jsonrpc;
}
public void setJsonrpc(String jsonrpc) {
this.jsonrpc = jsonrpc;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
} | true |
0c84f677373da01aacc6bb9b7796194d32678538 | Java | marydan/RESTRelationTest | /src/main/java/com/stackroute/products/controller/CustomerController.java | UTF-8 | 1,560 | 2.234375 | 2 | [] | no_license | package com.stackroute.products.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.stackroute.products.model.Customer;
import com.stackroute.products.service.CustomerService;
@RestController
@RequestMapping("ust/customer")
public class CustomerController {
@Autowired
CustomerService custservice;
@PostMapping("/addCustomer")
public ResponseEntity<?> addCustomerdetails(@RequestBody Customer cust)
{
custservice.addCustomerDetails(cust);
return new ResponseEntity<String>("Record Added",HttpStatus.OK);
}
@GetMapping("/showcustomers")
public ResponseEntity<?> showCustomerdetails()
{
List<Customer> customers=custservice.viewcustomerDetails();
return new ResponseEntity<List<Customer>>(customers,HttpStatus.OK);
}
@DeleteMapping("/removeCustomer/{custid}")
public ResponseEntity<?> deleteCustomer(@PathVariable("custid") String id)
{
custservice.deleteCustomer(id);
return new ResponseEntity<String>("Deleted",HttpStatus.OK);
}
}
| true |
af1d8bf7193603f0dd513a3f86a02725f66b57a8 | Java | treejames/feitai-parent | /feitai-common/src/main/java/com/feitai/common/core/CoreThrowsAdvice.java | UTF-8 | 1,022 | 2.0625 | 2 | [] | no_license | package com.feitai.common.core;
import java.util.Locale;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
/**
* <b>1.基于SpringAOP(非web项目) ThrowsAdvice接口的异常处理转换类</b><br>
* <b>2.基于SpringAOP(非web项目) Aspect标记的异常处理转换类</b>
*
* @author chenzhigang
* @since 2015-07-07
*/
@Aspect
public class CoreThrowsAdvice{
private static final Log log = LogFactory.getLog(CoreThrowsAdvice.class);
@Autowired
private MessageSource messageSource;
@AfterThrowing(value="execution(* com.feitai.**.job..*Job.*(..))",argNames="exception",throwing="exception")
public void afterThrowing(Exception exception){
ExceptionResolver.resolveException(exception, Locale.getDefault(), messageSource);
}
}
| true |
09bb4b2ff99fb183b7607d28129c79f8695a48ff | Java | abhijeet-yahoo/jewels | /src/generated-sources/java/com/jiyasoft/jewelplus/domain/manufacturing/transactions/QPDCTranMt.java | UTF-8 | 4,258 | 1.671875 | 2 | [] | no_license | package com.jiyasoft.jewelplus.domain.manufacturing.transactions;
import static com.mysema.query.types.PathMetadataFactory.*;
import com.mysema.query.types.path.*;
import com.mysema.query.types.PathMetadata;
import javax.annotation.Generated;
import com.mysema.query.types.Path;
import com.mysema.query.types.path.PathInits;
/**
* QPDCTranMt is a Querydsl query type for PDCTranMt
*/
@Generated("com.mysema.query.codegen.EntitySerializer")
public class QPDCTranMt extends EntityPathBase<PDCTranMt> {
private static final long serialVersionUID = -742434527L;
private static final PathInits INITS = PathInits.DIRECT2;
public static final QPDCTranMt pDCTranMt = new QPDCTranMt("pDCTranMt");
public final StringPath createdBy = createString("createdBy");
public final DateTimePath<java.util.Date> createdDate = createDateTime("createdDate", java.util.Date.class);
public final BooleanPath currStk = createBoolean("currStk");
public final BooleanPath deactive = createBoolean("deactive");
public final DateTimePath<java.util.Date> deactiveDt = createDateTime("deactiveDt", java.util.Date.class);
public final com.jiyasoft.jewelplus.domain.manufacturing.masters.QDepartment department;
public final com.jiyasoft.jewelplus.domain.manufacturing.masters.QDepartment deptFrom;
public final com.jiyasoft.jewelplus.domain.manufacturing.masters.QDepartment deptTo;
public final com.jiyasoft.jewelplus.domain.manufacturing.masters.QDesign design;
public final NumberPath<Double> excessWt = createNumber("excessWt", Double.class);
public final NumberPath<Double> extraLoss = createNumber("extraLoss", Double.class);
public final NumberPath<Integer> id = createNumber("id", Integer.class);
public final DateTimePath<java.util.Date> issueDate = createDateTime("issueDate", java.util.Date.class);
public final NumberPath<Double> issWt = createNumber("issWt", Double.class);
public final NumberPath<Double> loss = createNumber("loss", Double.class);
public final StringPath modiBy = createString("modiBy");
public final DateTimePath<java.util.Date> modiDate = createDateTime("modiDate", java.util.Date.class);
public final NumberPath<Double> pcs = createNumber("pcs", Double.class);
public final NumberPath<Double> purityConv = createNumber("purityConv", Double.class);
public final NumberPath<Double> recWt = createNumber("recWt", Double.class);
public final NumberPath<Integer> refMtId = createNumber("refMtId", Integer.class);
public final StringPath remark = createString("remark");
public final NumberPath<Double> splitQty = createNumber("splitQty", Double.class);
public final NumberPath<Double> splitWt = createNumber("splitWt", Double.class);
public final TimePath<java.sql.Time> time = createTime("time", java.sql.Time.class);
public QPDCTranMt(String variable) {
this(PDCTranMt.class, forVariable(variable), INITS);
}
public QPDCTranMt(Path<? extends PDCTranMt> path) {
this(path.getType(), path.getMetadata(), path.getMetadata().isRoot() ? INITS : PathInits.DEFAULT);
}
public QPDCTranMt(PathMetadata<?> metadata) {
this(metadata, metadata.isRoot() ? INITS : PathInits.DEFAULT);
}
public QPDCTranMt(PathMetadata<?> metadata, PathInits inits) {
this(PDCTranMt.class, metadata, inits);
}
public QPDCTranMt(Class<? extends PDCTranMt> type, PathMetadata<?> metadata, PathInits inits) {
super(type, metadata, inits);
this.department = inits.isInitialized("department") ? new com.jiyasoft.jewelplus.domain.manufacturing.masters.QDepartment(forProperty("department"), inits.get("department")) : null;
this.deptFrom = inits.isInitialized("deptFrom") ? new com.jiyasoft.jewelplus.domain.manufacturing.masters.QDepartment(forProperty("deptFrom"), inits.get("deptFrom")) : null;
this.deptTo = inits.isInitialized("deptTo") ? new com.jiyasoft.jewelplus.domain.manufacturing.masters.QDepartment(forProperty("deptTo"), inits.get("deptTo")) : null;
this.design = inits.isInitialized("design") ? new com.jiyasoft.jewelplus.domain.manufacturing.masters.QDesign(forProperty("design"), inits.get("design")) : null;
}
}
| true |
a7a6783e76ec483ae82bbd6a84325ddf1ad1301a | Java | aminedarabid/ProxiBanqueSI-1 | /ProxiBanqueSI/src/main/java/com/objis/spring/dto/TransferDto.java | UTF-8 | 532 | 2.359375 | 2 | [] | no_license | package com.objis.spring.dto;
public class TransferDto {
private String from;
private String to;
private Double balance;
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public Double getBalance() {
return balance;
}
public void setBalance(Double balance) {
this.balance = balance;
}
}
| true |
152b0873f464c532b6c79f09dabdf9e484ba6936 | Java | SeanAndPenny/SND | /ylpt/src/main/java/com/wondersgroup/wszygl/controller/CwtjController.java | UTF-8 | 3,474 | 2.03125 | 2 | [] | no_license | package com.wondersgroup.wszygl.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.wondersgroup.api.beans.page.PageRequest;
import com.wondersgroup.api.beans.page.PageResult;
import com.wondersgroup.api.mybatis.manager.BaseMybatisManager;
import com.wondersgroup.frame.spr_mybt_mvc.basic.controller.BaseMybatisController;
import com.wondersgroup.wszygl.manager.CwtjManger;
import com.wondersgroup.wszygl.manager.CwtjXzJgManger;
import com.wondersgroup.wszygl.model.CwtjModel;
import com.wondersgroup.wszygl.model.SslistModel;
@Controller
@RequestMapping("/cwtj")
public class CwtjController extends BaseMybatisController<CwtjModel,String>{
@Autowired
public CwtjManger cwtjManger;
@Autowired
public CwtjXzJgManger cwtjXzJgManger;
@RequestMapping("/cwtj")//床位统计
public ModelAndView rycxList(HttpServletRequest request, HttpServletResponse response) {
ModelAndView result = new ModelAndView();
result.setViewName("wszygl/xqtj");
try {
/*PageRequest pageRequest = newPageRequest(request);
PageResult<CwtjModel> page = cwtjManger.pageSelect(pageRequest);
result.addObject("code", 0);
result.addObject("msg", "success");
result.addObject("count", page.getTotalCount());
result.addObject("data", page.getResult());*/
}catch(Exception e) {
logger.warn(e.getMessage());
result.addObject("code", 500);
result.addObject("msg", e.getMessage());
}
return result;
}
//床位统计下钻机构
@RequestMapping("/cwtjXzJg")
public ModelAndView cwtjXzJgList(HttpServletRequest request, HttpServletResponse response) {
String id = request.getParameter("p_id");
ModelAndView result = new ModelAndView();
result.setViewName("wszygl/cwtjXzJg");
try {
result.addObject("id", id);
PageRequest pageRequest = newPageRequest(request);
PageResult<CwtjModel> page = cwtjXzJgManger.pageSelect(pageRequest);
result.addObject("code", 0);
result.addObject("msg", "success");
result.addObject("count", page.getTotalCount());
result.addObject("data", page.getResult());
}catch(Exception e) {
logger.warn(e.getMessage());
result.addObject("code", 500);
result.addObject("msg", e.getMessage());
}
return result;
}
@RequestMapping("/cwtjXzJgecharts")
public ModelAndView cwtjXzJgecharts(HttpServletRequest request,HttpServletResponse response) {
ModelAndView result = new ModelAndView();
String id = request.getParameter("p_id");
try {
result.addObject("id", id);
List<CwtjModel>cwtjXzJgechartsechartsList = cwtjXzJgManger.getCwtjXzJg(id);
result.addObject("cwtjXzJgechartsechartsList", cwtjXzJgechartsechartsList);
}catch(Exception e) {
logger.warn(e.getMessage());
result.addObject("code", 500);
result.addObject("msg", e.getMessage());
}
return result;
}
@Override
public Class<CwtjModel> getEntityClass() {
// TODO Auto-generated method stub
return null;
}
@Override
public BaseMybatisManager<CwtjModel, String> getBaseManager() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getViewPath() {
// TODO Auto-generated method stub
return null;
}
}
| true |
b904f4008667cd2019b6bd75c582961e4fafe985 | Java | nuxeo/nuxeo-media-publishing | /nuxeo-media-publishing-core/src/main/java/org/nuxeo/ecm/media/publishing/MediaPublishingService.java | UTF-8 | 1,540 | 1.8125 | 2 | [] | no_license | /*
* (C) Copyright 2015 Nuxeo SA (http://nuxeo.com/) and others.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Contributors:
* Nelson Silva
*/
package org.nuxeo.ecm.media.publishing;
import org.nuxeo.ecm.core.api.DocumentModel;
import java.util.Map;
/**
* @since 7.3
*/
public interface MediaPublishingService {
/**
* Return a list of the available media publishing services for the given document
*/
String[] getAvailableProviders(DocumentModel doc);
/**
* Schedules an upload
* @param doc the Document to upload
* @param provider the id of the media publishing provider
* @return the id of the publishing work
*/
String publish(DocumentModel doc, String provider, String account, Map<String, String> options);
/**
* Unpublish the media
*
* @since 7.4
*/
void unpublish(DocumentModel doc, String provider);
/**
* Return the provider with the given name.
*/
MediaPublishingProvider getProvider(String provider);
}
| true |
3793a0e8b1c44b7598ae4e62b3e3677af9bf632a | Java | Nanguromo/OOSE_21 | /P5/src/Controller.java | UTF-8 | 11,474 | 3.34375 | 3 | [] | no_license | import java.util.*;
import java.io.IOException;
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.*;
/**
* The controller of the reminders application. The responsibilities of this
* class are light -- it's a thin layer between the View and the Model.
*/
public class Controller
{
private static final String REMINDER_FILE = "reminders.txt";
private ReminderList list;
private MainWindow window;
//private inner class MainWindow which is an implementation of ReminderObserver.
//No other class directly uses MainWindow. ReminderList is not coupled to this class due to it only using ReminderObserver objects in its list
private class MainWindow extends JFrame implements ReminderObserver
{
//another nested private inner class. Only MainWindow uses this so it would be simplest to nest it in here. Not necessary though
private class AddReminderWindow extends JFrame
{
private static final int PADDING = 10;
private Controller controller;
private JTextField taskWidget;
private JButton addButton;
private JButton closeButton;
/**
* Set everything up. We need to import a Controller reference, because
* this is where we tell the controller to add a reminder.
*/
public AddReminderWindow(Controller inController)
{
super("Add Reminder"); // Window title.
controller = inController;
// These are the important widgets.
taskWidget = new JTextField(50); // Space to enter some reminder text.
addButton = new JButton("Add"); // A button to add the reminder.
closeButton = new JButton("Close"); // A button to close the window.
// Now we do the boring window layout stuff.
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
buttonPanel.add(Box.createHorizontalGlue());
buttonPanel.add(addButton);
buttonPanel.add(Box.createRigidArea(new Dimension(PADDING, 0)));
buttonPanel.add(closeButton);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
contentPane.setBorder(BorderFactory.createEmptyBorder(PADDING, PADDING, PADDING, PADDING));
contentPane.add(taskWidget);
contentPane.add(Box.createRigidArea(new Dimension(0, PADDING)));
contentPane.add(buttonPanel);
getRootPane().setContentPane(contentPane);
// The add button tells the controller to add a new reminder.
addButton.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
// Retrieve the text entered by the user.
String task = taskWidget.getText();
if(task.length() > 0)
{
// *If* there is some text present, add a new reminder.
controller.addReminder(task, new Date(0l));
}
}
}
);
// The close button simply hides this window; i.e. making it invisible
// to the user (but still present in memory).
closeButton.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
setVisible(false);
}
}
);
// Trigger the window layout algorithm.
pack();
}
}
/**
* The main reminder application window. This contains a list of the reminders,
* along with an "add" button that opens an "add reminder" window, and a
* "remove" button that removes the currently-selected reminder.
*/
private JList<String> remindersWidget;
private JButton addButton;
private JButton removeButton;
private AddReminderWindow addReminderWindow;
private Controller controller;
private JPanel contentPane;
//private List<JLabel> labels;
//public MainWindow(Controller inController)
public MainWindow()
{
super("Reminder App"); // Window title.
setPreferredSize(new Dimension(400, 150)); // Window size
// Make the whole program close when this window is closed.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//controller = inController;
controller = Controller.this;
addReminderWindow = new AddReminderWindow(controller);//get this Controller instance
// Our important widgets:
remindersWidget = new JList<String>();
remindersWidget.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
addButton = new JButton("Add");
removeButton = new JButton("Remove");
// Boring window layout stuff.
//JPanel
contentPane = new JPanel(new BorderLayout());
JScrollPane scrollPane = new JScrollPane(remindersWidget);
JToolBar toolbar = new JToolBar();
contentPane.add(toolbar, BorderLayout.NORTH);
contentPane.add(scrollPane, BorderLayout.CENTER);
toolbar.add(addButton);
toolbar.add(removeButton);
getRootPane().setContentPane(contentPane);
// When the "add" button is clicked, make the "add reminder" window visible.
addButton.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
addReminderWindow.setVisible(true);
}
}
);
// When the "remove" button is clicked, tell the controller to remove
// the currently selected reminder.
removeButton.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
// Figure out which reminder is currently selected.
int index = remindersWidget.getSelectedIndex();
if(index != -1)
{
// If there *is* something currently selected, tell the
// controller to remove it.
controller.removeReminder(index);
}
}
}
);
//When main window close is clicked, write to output file upon exit
this.addWindowListener(
new WindowAdapter()
{
@Override
public void windowClosing(WindowEvent e)
{
//Controller.write();
//System.out.println("got heeere!!");
try
{
FileManager.write(REMINDER_FILE, list.getReminders());
} catch (IOException er)
{
System.err.println("Error whilst saving reminders!");
}
//setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
System.exit(0);
}
}
);
showReminders(controller.getReminders());
//showReminders(controller.getReminders());
// Trigger the layout algorithm.
pack();
}
/**
* Takes a list of Reminder objects and displays them in the window.
*/
public void showReminders(List<Reminder> reminders)
{
Vector<String> tasks = new Vector<String>();
for(Reminder rem : reminders)
{
tasks.add(rem.getTask());
}
remindersWidget.setListData(tasks);
contentPane.add(remindersWidget);
}
@Override
public void updateReminder()
{
//showReminders(list.getReminders());
/*Vector<String> tasks = new Vector<String>();
List<Reminder> reminders = list.getReminders();
for(Reminder rem: reminders)
{
tasks.add(rem.getTask());
}
for(String task: tasks)
{
contentPane.add(new JLabel(task, JLabel.LEFT));
}*/
showReminders(list.getReminders());
}
/*@Override
public void windowClosing(WindowEvent e)
{
//Controller.write();
try
{
FileManager.write(REMINDER_FILE, list.getReminders());
} catch (IOException er)
{
System.err.println("Error whilst saving reminders!");
}
System.exit(0);
}*/
}
/**
* Takes in an existing ReminderList -- the Model -- and populates it with
* data read from the reminders file.
*/
public Controller(ReminderList inReminderList)
{
list = inReminderList;
window = new MainWindow();
list.addObserver(window);
//list.addObserver(new MainWindow());
try
{
list.addReminders(FileManager.read(REMINDER_FILE));
list.notifyReminders();
}
catch(IOException e)
{
System.err.println("Warning: unable to open the reminders file! Continuing without it.");
}
}
/** Used by the UI when a reminder needs adding. */
public void addReminder(String task, Date dateObj)
{
list.addReminder(new Reminder(task, dateObj));
list.notifyReminders();
}
public void addObserver()
{
list.addObserver(new MainWindow());
}
/** Used by the UI when a reminder needs removing. */
public void removeReminder(int index)
{
list.removeReminder(index);
list.notifyReminders();
}
/** Used by the UI to obtain reminders to display. */
public List<Reminder> getReminders()
{
return list.getReminders();
}
public void setVisible(boolean bool)
{
window.setVisible(bool);
}
/*public void write()
{
try
{
FileManager.write(REMINDER_FILE, list.getReminders());
} catch (IOException e)
{
System.err.println("Error whilst saving reminders!");
}
}*/
public void test()
{
System.out.println("works");
}
} | true |
04234cc9aeadc69fd9cff9f21edcd5f7ffe658a6 | Java | JuliaChenJing/Advanced-Software-Design | /ObserverPatternSolution/src/email/EmailSender.java | UTF-8 | 560 | 2.859375 | 3 | [] | no_license | package email;
import java.util.Date;
import bank.domain.Account;
import bank.service.IObserver;
public class EmailSender implements IObserver {
//when new account is created, email will be sent to confirm
public void update(Account account) {
// check if account is new
if (account.getBalance() == 0.0) {
String string = "Account " + account.getAccountnumber()
+ " is created ";
sendEmail(string);
}
}
public void sendEmail(String string) {
System.out.println("Sending email --------" + new Date() + "---" + string +"\n");
}
}
| true |
5f88e47cec2487ed71f8d5e51be8f917a618f542 | Java | paper-lark/big-data-course | /candlestick-chart/src/main/java/CandlestickOutputFormat.java | UTF-8 | 900 | 2.3125 | 2 | [] | no_license | import models.CandlestickDescription;
import models.CandlestickKey;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.RecordWriter;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import java.io.IOException;
public class CandlestickOutputFormat extends FileOutputFormat<CandlestickKey, CandlestickDescription> {
@Override
public RecordWriter<CandlestickKey, CandlestickDescription> getRecordWriter(TaskAttemptContext job) throws IOException {
String ext = ".csv";
Path file = getDefaultWorkFile(job, ext);
FileSystem fs = file.getFileSystem(job.getConfiguration());
FSDataOutputStream fileOut = fs.create(file, false);
return new CandlestickRecordWriter(fileOut);
}
}
| true |
2bdc45a39481e1eaedb874dc0af4b9ce21843ec3 | Java | mnk-OneThing/DataStructures | /src/com/mnk/Searching/BinarySearch.java | UTF-8 | 548 | 3.4375 | 3 | [] | no_license | package com.mnk.Searching;
import java.util.Collections;
public class BinarySearch {
public static void main(String[] args) {
int a[] = { 11, 21, 32, 43, 58, 61, 99, 101, 245, 350 };
int findIndexOf = 245;
System.out.println(binarySearch(a, findIndexOf));
}
private static int binarySearch(int[] a, int findIndexOf) {
int p = 0, r = a.length-1,q=0;
while (p <= r) {
q = (p + r) / 2;
if (a[q] == findIndexOf) {
return q;
} else if (a[q] > findIndexOf) {
r=q-1;
} else {
p=q+1;
}
}
return -1;
}
}
| true |
0007828aee6c378a8c4a95aa569cf8bee521d48e | Java | zscomehuyue/porter | /manager/manager-core/src/main/java/cn/vbill/middleware/porter/manager/service/impl/PublicDataSourceServiceImpl.java | UTF-8 | 4,617 | 1.695313 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright ©2018 vbill.cn.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* </p>
*/
package cn.vbill.middleware.porter.manager.service.impl;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Properties;
import cn.vbill.middleware.porter.common.task.config.PublicSourceConfig;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.context.properties.source.ConfigurationPropertySource;
import org.springframework.boot.context.properties.source.MapConfigurationPropertySource;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONObject;
import cn.vbill.middleware.porter.manager.core.entity.PublicDataSource;
import cn.vbill.middleware.porter.manager.core.mapper.PublicDataSourceMapper;
import cn.vbill.middleware.porter.manager.service.PublicDataSourceService;
import cn.vbill.middleware.porter.manager.web.page.Page;
/**
* 公共数据源配置表 服务实现类
*
* @author: FairyHood
* @date: 2019-03-13 09:58:24
* @version: V1.0-auto
* @review: FairyHood/2019-03-13 09:58:24
*/
@Service
public class PublicDataSourceServiceImpl implements PublicDataSourceService {
private Logger logger = LoggerFactory.getLogger(PublicDataSourceServiceImpl.class);
@Autowired
private PublicDataSourceMapper publicDataSourceMapper;
@Override
public Integer insert(PublicDataSource publicDataSource) {
// 等权限类代码
publicDataSource.setCreator(-1L);
if (StringUtils.isBlank(publicDataSource.getCode())) {
logger.error("接口未传入数据识别码,请注意!!");
}
return publicDataSourceMapper.insert(publicDataSource);
}
@Override
public Integer update(Long id, PublicDataSource publicDataSource) {
// 等权限类代码
publicDataSource.setCreator(-1L);
if (StringUtils.isBlank(publicDataSource.getCode())) {
PublicSourceConfig config = JSONObject.parseObject(publicDataSource.getJsonText(),
PublicSourceConfig.class);
publicDataSource.setCode(config.getCode());
}
return publicDataSourceMapper.update(id, publicDataSource);
}
@Override
public Integer delete(Long id) {
return publicDataSourceMapper.delete(id);
}
@Override
public PublicDataSource selectById(Long id) {
return publicDataSourceMapper.selectById(id);
}
@Override
public Page<PublicDataSource> page(Page<PublicDataSource> page, Long id, String code, String name, String ipsite) {
Integer total = publicDataSourceMapper.pageAll(id, code, name, ipsite);
if (total > 0) {
page.setTotalItems(total);
page.setResult(publicDataSourceMapper.page(page, id, code, name, ipsite));
}
return page;
}
@Override
public Integer updateCancel(Long id) {
return publicDataSourceMapper.updateCancel(id);
}
@Override
public Integer updatePush(Long id, Integer ispush) {
return publicDataSourceMapper.updatePush(id, ispush);
}
@Override
public PublicSourceConfig dealxml(String code, String xmlTextStr) {
PublicSourceConfig config = new PublicSourceConfig();
Properties properties = new Properties();
try {
properties.load(new ByteArrayInputStream(xmlTextStr.getBytes()));
ConfigurationPropertySource source = new MapConfigurationPropertySource(properties);
Binder binder = new Binder(source);
config = binder.bind("", PublicSourceConfig.class).get();
} catch (IOException e) {
logger.error("解析xmlTextStr失败,请注意!!", e);
}
config.setCode(code);
return config;
}
}
| true |
3d2bb6271a15a33050e81df5ccaaf912e6f7ccd6 | Java | fotionkonomi/Job-Demo | /job-core/src/main/java/de/dh/lhind/demo/jobcore/business/service/base/AbstractJpaService.java | UTF-8 | 2,828 | 2.25 | 2 | [] | no_license | package de.dh.lhind.demo.jobcore.business.service.base;
import de.dh.lhind.demo.jobcore.business.common.BaseClassDTO;
import de.dh.lhind.demo.jobcore.business.service.exception.EntityNotFoundException;
import de.dh.lhind.demo.jobcore.business.service.exception.NoElementFoundException;
import de.dh.lhind.demo.jobcore.persistence.entities.common.BaseClass;
import de.dh.lhind.demo.jobcore.persistence.repository.ParentRepository;
import lombok.extern.log4j.Log4j;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
@Log4j
@Transactional
public abstract class AbstractJpaService<DTO extends BaseClassDTO, ENTITY extends BaseClass, ID>
implements BaseService<DTO, ID> {
@Autowired
protected ParentRepository<ENTITY, ID> repo;
@Autowired
protected ModelMapper modelMapper;
protected Class<ENTITY> classOfEntity;
protected Class<DTO> classOfDTO;
public AbstractJpaService(Class<ENTITY> classOfEntity, Class<DTO> classOfDTO) {
this.classOfEntity = classOfEntity;
this.classOfDTO = classOfDTO;
}
@Override
public DTO findById(ID id) {
Optional<ENTITY> optionalEntity = repo.findById(id);
Optional<DTO> optionalDTO = mapOptionalEntityToDTO(optionalEntity);
return optionalDTO.orElseThrow(() -> new EntityNotFoundException());
}
@Override
public DTO save(DTO dto) {
ENTITY mappedEntity = mapFromDTO(dto);
mappedEntity = repo.save(mappedEntity);
log.info(classOfEntity.getName() + " object saved successfully: " + mappedEntity);
return mapFromEntity(mappedEntity);
}
@Override
public List<DTO> findAll() {
List<ENTITY> entityList = repo.findAll();
List<DTO> dtoList = mapEntityListToDTO(entityList);
if(dtoList != null) {
return dtoList;
}
throw new NoElementFoundException();
}
@Override
public void deleteById(ID id) {
this.repo.deleteById(id);
}
protected ENTITY mapFromDTO(DTO dto) {
return modelMapper.map(dto, classOfEntity);
}
protected DTO mapFromEntity(ENTITY entity) {
return modelMapper.map(entity, classOfDTO);
}
private Optional<DTO> mapOptionalEntityToDTO(Optional<ENTITY> optionalEntity) {
return Optional.ofNullable(optionalEntity.isPresent() ? mapFromEntity(optionalEntity.get()) : null);
}
protected List<DTO> mapEntityListToDTO(Collection<ENTITY> entityList) {
List<DTO> dtoList = new ArrayList<>();
entityList.forEach(entity -> dtoList.add(mapFromEntity(entity)));
return dtoList;
}
}
| true |
d61067388534e08037abeb0d81769a4452e3a2d5 | Java | fernandojustino/focus | /src/main/java/com/focus/repository/UsuarioRepository.java | UTF-8 | 504 | 2.015625 | 2 | [] | no_license | package com.focus.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.focus.domain.security.Usuario;
public interface UsuarioRepository extends JpaRepository<Usuario, Integer > {
@Query("SELECT u FROM Usuario u where u.login = :login and u.password = :password")
Usuario findByLogin(@Param("login") String login, @Param("password") String senha);
}
| true |
2e3655779827bfe0d09c121553c810a0c0567fd5 | Java | VMAproject/sport | /src/main/java/com/sport/mvc/Controllers/smoll_fintess/StartController.java | UTF-8 | 540 | 1.828125 | 2 | [] | no_license | package com.sport.mvc.Controllers.smoll_fintess;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping(value = "/start/")
public class StartController {
//starts index
@RequestMapping("/")
public String ShowIndexStartPage() {
return "index";
}
//returns choose registration form page
@RequestMapping("/showChooseRegisterForm")
public String showChooseForm() {
return "chooseRegisterFormRegistry";
}
} | true |
1f36a199b0284a184c65ccc4292a5e944c224344 | Java | CrisCoboQAT/nosql_blog | /src/main/java/dao/BlogPostDAO.java | UTF-8 | 3,546 | 2.578125 | 3 | [] | no_license | package dao;
import java.util.List;
import java.util.regex.Pattern;
import org.bson.types.ObjectId;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.WriteResult;
public class BlogPostDAO
{
DBCollection postsCollection;
public BlogPostDAO(final DB blogDatabase)
{
postsCollection = blogDatabase.getCollection("posts");
}
public DBObject findById(String id)
{
DBObject post = postsCollection.findOne(new BasicDBObject("_id", new ObjectId(id)));
// fix up if a post has no likes
if (post != null)
{
List<DBObject> comments = (List<DBObject>)post.get("comments");
for (DBObject comment : comments)
{
if (!comment.containsField("num_likes"))
{
comment.put("num_likes", 0);
}
}
}
return post;
}
public List<DBObject> findByDateDescending(int limit)
{
DBCursor cursor = postsCollection.find().sort(new BasicDBObject().append("date", -1)).limit(limit);
return convertResult(cursor);
}
public List<DBObject> findByDateDescending()
{
DBCursor cursor = postsCollection.find().sort(new BasicDBObject("date", -1));
return convertResult(cursor);
}
public List<DBObject> findByBody(String term)
{
final Pattern regex = Pattern.compile(term, Pattern.CASE_INSENSITIVE);
BasicDBObject regexExpr = new BasicDBObject("$regex", regex);
DBCursor cursor = postsCollection.find(new BasicDBObject("body", regexExpr));
return convertResult(cursor);
}
public List<DBObject> findByCommentedUser(String user)
{
BasicDBObject regexExpr = new BasicDBObject("$regex", user);
DBCursor cursor = postsCollection.find(new BasicDBObject("comments.author", regexExpr));
return convertResult(cursor);
}
public List<DBObject> findByTagDateDescending(final String tag)
{
BasicDBObject query = new BasicDBObject("tags", tag);
DBCursor cursor = postsCollection.find(query).sort(new BasicDBObject().append("date", -1)).limit(10);
return convertResult(cursor);
}
public String addPost(String title, String body, List tags, String username)
{
System.out.println("inserting blog entry " + title + " " + body);
BasicDBObject post = new BasicDBObject("title", title);
post.append("author", username);
post.append("body", body);
post.append("tags", tags);
post.append("comments", new java.util.ArrayList());
post.append("date", new java.util.Date());
try
{
WriteResult result = postsCollection.insert(post);
System.out.println("Inserting blog post");
}
catch (Exception e)
{
System.out.println("Error inserting post");
return null;
}
return post.get("_id").toString();
}
public void addPostComment(final String name, final String email, final String body, final String id)
{
BasicDBObject comment = new BasicDBObject("author", name).append("body", body);
if (email != null && !email.equals(""))
{
comment.append("email", email);
}
postsCollection.update(new BasicDBObject("_id", new ObjectId(id)),
new BasicDBObject("$push", new BasicDBObject("comments", comment)), false, false);
}
public void likePost(final String id, final int ordinal)
{
postsCollection.update(new BasicDBObject("_id", new ObjectId(id)),
new BasicDBObject("$inc", new BasicDBObject("comments." + ordinal + ".num_likes", 1)));
}
private List<DBObject> convertResult(DBCursor cursor)
{
List<DBObject> posts;
try
{
posts = cursor.toArray();
}
finally
{
cursor.close();
}
return posts;
}
}
| true |
6535bcd3b4964d08c24a3d808edce54f82b2a47a | Java | Nilfan/First-Term-Tasks | /HM - Ninth task/src/Main.java | UTF-8 | 1,555 | 3.296875 | 3 | [] | no_license | /**
* Created by НР on 17-Nov-14.
*/
public class Main {
static boolean Search(LinkListNode linkListNode, LinkListNode farLinkListNode){
LinkListNode runner, fastRunner;
runner = linkListNode;
while(runner != farLinkListNode) {
if (linkListNode != null & linkListNode.nextLL != null & farLinkListNode != null & farLinkListNode.nextLL != null) {
fastRunner = farLinkListNode.nextLL;
} else {
return false;
}
runner = runner.nextLL;
farLinkListNode = fastRunner.nextLL;
}
return true;
}
static boolean Trying(LinkListNode[] linkList){
boolean ans;
if(linkList[0] == null){
System.out.println("It's empty\n");
return false;
}
ans = Search(linkList[0], linkList[0].nextLL);
if(ans){
System.out.println("Ring");
}
else{
System.out.println("Range");
}
return ans;
}
public static void main(String args[]){
LinkListNode[] line = LinkListNode.Test();
LinkListNode[] ring = LinkListNode.Ring();
LinkListNode[] ll = new LinkListNode[10];
Trying(ll);
if(!Trying(line)){
System.out.println("Okey\n");
}
else {
System.out.println("Error\n");
}
if(Trying(ring)){
System.out.println("Okey");
}
else {
System.out.println("Error");
}
}
}
| true |
ec30ef6b5cf2d41d2b8f193368624cdd0d5aaf6c | Java | Jorgelh/Tranformadores | /src/SolicitudMaterialesBodega/FormatoTabla.java | UTF-8 | 3,442 | 3.046875 | 3 | [] | no_license | package SolicitudMaterialesBodega;
import SolicitudesMateriales.*;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
public class FormatoTabla extends DefaultTableCellRenderer{
Color colorRosa=new Color(255,255,255);
Font normal = new Font( "Arial",Font.PLAIN,12);
//Font negrilla = new Font( "Helvetica",Font.BOLD,18 );
//Font cursiva = new Font( "Times new roman",Font.ITALIC,12 );
@Override
public Component getTableCellRendererComponent ( JTable table, Object value, boolean selected, boolean focused, int row, int column )
{
setEnabled(table == null || table.isEnabled());
setBackground(Color.getHSBColor(0,0,10));//color de fondo
table.setFont(new java.awt.Font("Tahoma", 0, 11));
//table.setFont(normal);//tipo de fuente
table.setForeground(Color.black);//color de texto
setHorizontalAlignment(0);//derecha
//si la celda esta vacia se reemplaza por el texto "<vacio>" y se rellena la celda de color negro y fuente color blanco
/* if(String.valueOf(table.getValueAt(row,column)).equals("")||String.valueOf(table.getValueAt(row,column)).equals("<vacio>")){
table.setValueAt("<vacio>", row, column);
setBackground(Color.black);
table.setForeground(Color.white);
table.setFont(cursiva);
}*/
/*--------*/
/*if(String.valueOf(table.getValueAt(row,column)).equals("jc Mouse")){
setBackground(Color.red);
table.setFont(negrilla);
setHorizontalAlignment(0);//centro
} */
/*--------*/
/* if(String.valueOf(table.getValueAt(row,column)).equals("de")){
setBackground(Color.yellow);
table.setFont(negrilla);
setHorizontalAlignment(0);//centro
}*/
/*--------*/
if(String.valueOf(table.getValueAt(row,column)).equals("0")){
setBackground(Color.RED);
table.setFont(normal);
setHorizontalAlignment(0);//centro
}
if(String.valueOf(table.getValueAt(row,column)).equals(" ")){
setBackground(Color.green);
table.setFont(normal);
setHorizontalAlignment(0);//centro
}
/*--------*/
//si la celda contiene números
/* if(isNumber(String.valueOf(table.getValueAt(row,column)))){
setBackground(Color.BLUE);
setHorizontalAlignment(4);//izquierda
} */
super.getTableCellRendererComponent(table, value, selected, focused, row, column);
return this;
}
public boolean isCellEditable(int row, int column){
return true;}
//
private boolean isNumber(String cadena){
try {
Double.parseDouble(cadena.replace(",", " "));
} catch (NumberFormatException nfe){
String newCadena = cadena.replace(".", "").replace(',', '.');
try{
Double.parseDouble(newCadena);
} catch (NumberFormatException nfe2){
return false;
}
}
return true;
}
}
| true |
0a422bf1faf38421292f88a70dd7e5982a43dc50 | Java | julmaralb/Grupo14SDP | /Workspace/Acme-Polyglot-2.0/src/test/java/services/LanguageExchangeServiceTest.java | UTF-8 | 9,620 | 2.359375 | 2 | [] | no_license | package services;
import java.util.Collection;
import java.util.Date;
import javax.transaction.Transactional;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.util.Assert;
import domain.LanguageExchange;
import domain.Polyglot;
import utilities.AbstractTest;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring/datasource.xml",
"classpath:spring/config/packages.xml" })
@Transactional
@TransactionConfiguration(defaultRollback = true)
public class LanguageExchangeServiceTest extends AbstractTest {
// Service under test -----------------------------------------------------
@Autowired
private LanguageExchangeService languageExchangeService;
// Other services ---------------------------------------------------------
// Tests ------------------------------------------------------------------
/**
* Acme-Polyglot - C-Level - 5.2
* A user who is authenticated as an administrator
* must be able to: Manage language exchanges, which includes
* creating, listing, editing, and cancelling them. Note that a
* polyglot is not allowed to edit or cancel an exchange that he or she's not created.
*
* Positive test case: A new language exchange is created.
*
*/
@Test
public void testLanguageExchangeCreate1() {
Collection<LanguageExchange> allBefore;
Collection<LanguageExchange> allAfter;
LanguageExchange languageExchange;
allBefore = languageExchangeService.findAll();
authenticate("polyglot1");
languageExchange = languageExchangeService.create();
languageExchange.setName("Name");
languageExchange.setRegistrationDate(new Date());
languageExchange.setExchangePlace("Place");
languageExchangeService.save(languageExchange);
allAfter= languageExchangeService.findAll();
Assert.isTrue(allAfter.size() == allBefore.size() + 1);
authenticate(null);
}
/**
* Acme-Polyglot - C-Level - 5.2
* A user who is authenticated as an administrator
* must be able to: Manage language exchanges, which includes
* creating, listing, editing, and cancelling them. Note that a
* polyglot is not allowed to edit or cancel an exchange that he or she's not created.
*
* Negative test case: A new language exchange is not created because it was not a polyglot.
*
*/
@Test(expected = AssertionError.class)
public void testLanguageExchangeCreate2() {
Collection<LanguageExchange> allBefore;
Collection<LanguageExchange> allAfter;
LanguageExchange languageExchange;
allBefore = languageExchangeService.findAll();
authenticate("admin");
languageExchange = languageExchangeService.create();
languageExchange.setName("Name");
languageExchange.setRegistrationDate(new Date());
languageExchange.setExchangePlace("Place");
languageExchangeService.save(languageExchange);
allAfter= languageExchangeService.findAll();
Assert.isTrue(allAfter.size() == allBefore.size() + 1);
authenticate(null);
}
/**
* Acme-Polyglot - C-Level - 5.2
* A user who is authenticated as an administrator
* must be able to: Manage language exchanges, which includes
* creating, listing, editing, and cancelling them. Note that a
* polyglot is not allowed to edit or cancel an exchange that he or she's not created.
*
* Positive test case: All language exchanges are listed.
*
*/
@Test
public void testLanguageExchangeList() {
Collection<LanguageExchange> all;
all = languageExchangeService.findAll();
Assert.isTrue(all.size()==6);
}
/**
* Acme-Polyglot - C-Level - 5.4
* A user who is authenticated as an administrator
* must be able to: List the language exchanges that he or she's joined.
*
* Positive test case: All language exchanges that polyglot1 has joined are listed.
*
*/
@Test
public void testLanguageExchangeListJoined() {
Collection<LanguageExchange> joined;
authenticate("polyglot1");
joined = languageExchangeService.findAllJoinedByPrincipal();
Assert.isTrue(joined.size()==4);
authenticate(null);
}
/**
* Acme-Polyglot - C-Level - 5.2
* A user who is authenticated as an administrator
* must be able to: Manage language exchanges, which includes
* creating, listing, editing, and cancelling them. Note that a
* polyglot is not allowed to edit or cancel an exchange that he or she's not created.
*
* Negative test case: The exchange is not cancelled becouse polyglot1 was not it's owner.
*
*/
@Test(expected = IllegalArgumentException.class)
public void testLanguageExchangeCancel1() {
LanguageExchange languageExchange;
authenticate("polyglot1");
languageExchange = languageExchangeService.findOne(53);
languageExchangeService.cancelLanguageExchange(languageExchange);
authenticate(null);
}
/**
* Acme-Polyglot - C-Level - 5.2
* A user who is authenticated as an administrator
* must be able to: Manage language exchanges, which includes
* creating, listing, editing, and cancelling them. Note that a
* polyglot is not allowed to edit or cancel an exchange that he or she's not created.
*
* Positive test case: The exchange is cancelled.
*
*/
@Test
public void testLanguageExchangeCancel2() {
LanguageExchange languageExchange;
authenticate("polyglot1");
languageExchange = languageExchangeService.findOne(50);
languageExchangeService.cancelLanguageExchange(languageExchange);
authenticate(null);
}
/**
* Acme-Polyglot - C-Level - 5.3
* A user who is authenticated as an administrator
* must be able to: Join or to unjoin an existing language exchange.
*
* Positive test case: Polyglot1 joins the exchange.
*
*/
@Test
public void testLanguageExchangeJoin1() {
LanguageExchange languageExchange;
Collection<Polyglot> participantsBefore;
Collection<Polyglot> participantsAfter;
authenticate("polyglot1");
languageExchange = languageExchangeService.findOne(53);
participantsBefore = languageExchange.getParticipants();
Assert.isTrue(participantsBefore.size() == 2);
languageExchangeService.joinLanguageExchange(languageExchange);
participantsAfter = languageExchange.getParticipants();
Assert.isTrue(participantsAfter.size() == 3);
authenticate(null);
}
/**
* Acme-Polyglot - C-Level - 5.3
* A user who is authenticated as an administrator
* must be able to: Join or to unjoin an existing language exchange.
*
* Positive test case: Polyglot1 joins the exchange and then unjoins it.
*
*/
@Test
public void testLanguageExchangeUnjoin1() {
LanguageExchange languageExchange;
Collection<Polyglot> participants;
authenticate("polyglot1");
languageExchange = languageExchangeService.findOne(53);
participants = languageExchange.getParticipants();
Assert.isTrue(participants.size() == 2);
languageExchangeService.joinLanguageExchange(languageExchange);
participants = languageExchange.getParticipants();
Assert.isTrue(participants.size() == 3);
languageExchangeService.unJoinLanguageExchange(languageExchange);
participants = languageExchange.getParticipants();
Assert.isTrue(participants.size() == 2);
authenticate(null);
}
/**
* Acme-Polyglot - C-Level - 5.3
* A user who is authenticated as an administrator
* must be able to: Join or to unjoin an existing language exchange.
*
* Negative test case: Polyglot1 can't unjoin an exchange he has not joined.
*
*/
@Test(expected = IllegalArgumentException.class)
public void testLanguageExchangeUnjoin2() {
LanguageExchange languageExchange;
authenticate("polyglot1");
languageExchange = languageExchangeService.findOne(53);
languageExchangeService.unJoinLanguageExchange(languageExchange);
authenticate(null);
}
/**
* Acme-Polyglot - C-Level - 5.3
* A user who is authenticated as an administrator
* must be able to: Join or to unjoin an existing language exchange.
*
* Negative test case: Polyglot1 can't join an exchange he already joined.
*
*/
@Test(expected = IllegalArgumentException.class)
public void testLanguageExchangeJoin2() {
LanguageExchange languageExchange;
authenticate("polyglot1");
languageExchange = languageExchangeService.findOne(50);
languageExchangeService.joinLanguageExchange(languageExchange);
authenticate(null);
}
/**
* Acme-Polyglot - C-Level - 4.2
* An actor who is not authenticated must be able to:
* List the exchanges that have been organised no more than three months ago.
*
* Positive test case: All language exchanges organised no more than three months ago.
* are listed.
*
*/
@Test
public void testLanguageExchangeList3MonthsAgo() {
Collection<LanguageExchange> result;
result = languageExchangeService.find3MonthsAgo();
Assert.isTrue(result.size()==0);
}
/**
* Acme-Polyglot - C-Level - 4.3
* An actor who is not authenticated must be able to:
* List the exchanges that are going to be organised in
* no more than three months time.
*
* Positive test case: All language exchanges organised no more than three months time.
* are listed.
*
*/
@Test
public void testLanguageExchangeList3MonthsTime() {
Collection<LanguageExchange> result;
result = languageExchangeService.find3MonthsTime();
Assert.isTrue(result.size()==5);
}
} | true |