blob_id
stringlengths 40
40
| __id__
int64 225
39,780B
| directory_id
stringlengths 40
40
| path
stringlengths 6
313
| content_id
stringlengths 40
40
| detected_licenses
list | license_type
stringclasses 2
values | repo_name
stringlengths 6
132
| repo_url
stringlengths 25
151
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
70
| visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 7.28k
689M
⌀ | star_events_count
int64 0
131k
| fork_events_count
int64 0
48k
| gha_license_id
stringclasses 23
values | gha_fork
bool 2
classes | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_updated_at
timestamp[ns] | gha_pushed_at
timestamp[ns] | gha_size
int64 0
40.4M
⌀ | gha_stargazers_count
int32 0
112k
⌀ | gha_forks_count
int32 0
39.4k
⌀ | gha_open_issues_count
int32 0
11k
⌀ | gha_language
stringlengths 1
21
⌀ | gha_archived
bool 2
classes | gha_disabled
bool 1
class | content
stringlengths 7
4.37M
| src_encoding
stringlengths 3
16
| language
stringclasses 1
value | length_bytes
int64 7
4.37M
| extension
stringclasses 24
values | filename
stringlengths 4
174
| language_id
stringclasses 1
value | entities
list | contaminating_dataset
stringclasses 0
values | malware_signatures
list | redacted_content
stringlengths 7
4.37M
| redacted_length_bytes
int64 7
4.37M
| alphanum_fraction
float32 0.25
0.94
| alpha_fraction
float32 0.25
0.94
| num_lines
int32 1
84k
| avg_line_length
float32 0.76
99.9
| std_line_length
float32 0
220
| max_line_length
int32 5
998
| is_vendor
bool 2
classes | is_generated
bool 1
class | max_hex_length
int32 0
319
| hex_fraction
float32 0
0.38
| max_unicode_length
int32 0
408
| unicode_fraction
float32 0
0.36
| max_base64_length
int32 0
506
| base64_fraction
float32 0
0.5
| avg_csv_sep_count
float32 0
4
| is_autogen_header
bool 1
class | is_empty_html
bool 1
class | shard
stringclasses 16
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
555e78fc3328b3f12fa0d863cc50ef0d6c89d3e8 | 22,780,506,585,585 | e4a988ead5dd4bcd01811dd597d511e8114b0c62 | /EMS-master/EMS-master/ems-leave-service/src/main/java/com/ems/leave/controller/LeaveController.java | 0dc5052666e6f4aefbfac9c19fa56d1dd7f9bebd | []
| no_license | Deepak1888/ems | https://github.com/Deepak1888/ems | 5a2f4625c0cda789f7491030c02276980d65b595 | 7972383cb631f11b7f9ad16d6cff4984109b201e | refs/heads/master | 2023-01-10T12:13:09.694000 | 2019-06-26T06:54:45 | 2019-06-26T06:54:45 | 193,846,726 | 1 | 0 | null | false | 2023-01-07T06:44:19 | 2019-06-26T06:53:39 | 2023-01-01T08:30:39 | 2023-01-07T06:44:17 | 3,081 | 1 | 0 | 26 | Java | false | false | package com.ems.leave.controller;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.ems.leave.constant.LeaveConstants;
import com.ems.leave.model.LeaveData;
import com.ems.leave.model.Response;
import com.ems.leave.service.LeaveServiceImpl;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
/**
*
* @author yogesh.patil
*
*/
@RestController
public class LeaveController implements LeaveConstants {
@Autowired
LeaveServiceImpl leaveService;
@RequestMapping("/getLeaveDataForAllEmployees")
@HystrixCommand(fallbackMethod = "getDataFallBack")
public JSONObject getLeaveDataForAllEmployees() {
System.out.println("inside getLeaveDataForAllEmployees method ..............");
JSONObject jsonObject = leaveService.getLeaveDataForAllEmployees();
JSONArray cities = (JSONArray) jsonObject.get("leaveRecords");
if(cities.isEmpty())
throw new RuntimeException();
return jsonObject;
}
@SuppressWarnings("unchecked")
public JSONObject getDataFallBack() {
System.out.println("inside getDataFallBack method --------------");
JSONObject obj = new JSONObject();
JSONArray arr= new JSONArray();
obj.put("leaveRecords", arr);
return obj;
}
@RequestMapping("/getLeaveDataByEmployeeId/{empid}")
public JSONObject getLeaveData(@PathVariable String empid) {
JSONObject jsonObject = leaveService.getLeaveDataByEmployeeId(empid);
return jsonObject;
}
@RequestMapping(value = "/applyLeave", method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public Response submitLeave(@RequestBody LeaveData leaveData) {
Response responseMessage = leaveService.applyLeave(leaveData);
return responseMessage;
}
}
| UTF-8 | Java | 2,097 | java | LeaveController.java | Java | [
{
"context": "ica.annotation.HystrixCommand;\n\n/**\n * \n * @author yogesh.patil\n *\n */\n@RestController\npublic class Lea",
"end": 738,
"score": 0.7084579467773438,
"start": 736,
"tag": "NAME",
"value": "yo"
},
{
"context": ".annotation.HystrixCommand;\n\n/**\n * \n * @author yogesh.patil\n *\n */\n@RestController\npublic class Leave",
"end": 740,
"score": 0.5297898650169373,
"start": 738,
"tag": "USERNAME",
"value": "ge"
},
{
"context": "nnotation.HystrixCommand;\n\n/**\n * \n * @author yogesh.patil\n *\n */\n@RestController\npublic class LeaveControll",
"end": 748,
"score": 0.6899117827415466,
"start": 740,
"tag": "NAME",
"value": "sh.patil"
}
]
| null | []
| package com.ems.leave.controller;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.ems.leave.constant.LeaveConstants;
import com.ems.leave.model.LeaveData;
import com.ems.leave.model.Response;
import com.ems.leave.service.LeaveServiceImpl;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
/**
*
* @author yogesh.patil
*
*/
@RestController
public class LeaveController implements LeaveConstants {
@Autowired
LeaveServiceImpl leaveService;
@RequestMapping("/getLeaveDataForAllEmployees")
@HystrixCommand(fallbackMethod = "getDataFallBack")
public JSONObject getLeaveDataForAllEmployees() {
System.out.println("inside getLeaveDataForAllEmployees method ..............");
JSONObject jsonObject = leaveService.getLeaveDataForAllEmployees();
JSONArray cities = (JSONArray) jsonObject.get("leaveRecords");
if(cities.isEmpty())
throw new RuntimeException();
return jsonObject;
}
@SuppressWarnings("unchecked")
public JSONObject getDataFallBack() {
System.out.println("inside getDataFallBack method --------------");
JSONObject obj = new JSONObject();
JSONArray arr= new JSONArray();
obj.put("leaveRecords", arr);
return obj;
}
@RequestMapping("/getLeaveDataByEmployeeId/{empid}")
public JSONObject getLeaveData(@PathVariable String empid) {
JSONObject jsonObject = leaveService.getLeaveDataByEmployeeId(empid);
return jsonObject;
}
@RequestMapping(value = "/applyLeave", method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public Response submitLeave(@RequestBody LeaveData leaveData) {
Response responseMessage = leaveService.applyLeave(leaveData);
return responseMessage;
}
}
| 2,097 | 0.787315 | 0.787315 | 60 | 33.950001 | 27.85404 | 130 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.383333 | false | false | 0 |
d02894cf7ba72cd80d07e79adcb15a2fedd38739 | 27,187,142,997,969 | f365f4c3ec89f5556bc5b5b0fe8f3bf7692d60c8 | /archer-web/src/main/java/cn/exrick/xboot/task/engine/memory/MemoryTaskFlow.java | 66f933bccd2ac9566562288a9ed4501b2058bc04 | []
| no_license | moutainhigh/archer-task | https://github.com/moutainhigh/archer-task | df88853f5a7f768809ec730a468716337cb833ad | 1b277fda5cfe7d501d2a2a8d450f6d9650a27456 | refs/heads/master | 2020-09-05T19:36:28.544000 | 2019-10-12T13:31:54 | 2019-10-12T13:31:54 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.exrick.xboot.task.engine.memory;
import cn.exrick.xboot.task.engine.TaskFlowAdapter;
import cn.exrick.xboot.task.engine.TaskUnit;
import cn.hutool.core.collection.ConcurrentHashSet;
import cn.hutool.core.util.RandomUtil;
import com.google.api.client.util.Sets;
import org.springframework.util.CollectionUtils;
import java.util.Set;
import java.util.concurrent.*;
/**
* Created by feng on 2019/9/5 0005
*/
public class MemoryTaskFlow extends TaskFlowAdapter {
/**
* 执行器
*/
private ExecutorService executor;
/**
* 控制任务等待
*/
private boolean isWaiting;
/**
*
*/
private MemoryTaskNode rootNode;
private ConcurrentHashSet<MemoryTaskNode> executingTaskNode = new ConcurrentHashSet<>();
@Override
public void loadTask() {
rootNode = createTask();
executor = Executors.newFixedThreadPool(5);
}
@Override
public void start() {
Set<MemoryTaskNode> executableNodes = process(rootNode);
while (!CollectionUtils.isEmpty(executableNodes)) {
Set<MemoryTaskNode> executableNodeTemps = Sets.newHashSet();
executableNodes.forEach(item -> {
executableNodeTemps.addAll(process(item));
});
executableNodes = executableNodeTemps;
}
}
@Override
public void recovery() {
isWaiting = false;
}
@Override
public void suspend() {
isWaiting = true;
}
@Override
public void kill() {
executor.shutdownNow();
}
@Override
public Set<MemoryTaskNode> queryPhase() {
return executingTaskNode;
}
private Set<MemoryTaskNode> process(MemoryTaskNode node) {
Set<MemoryTaskNode> executableNodes = Sets.newHashSet();
// if (CollectionUtils.isEmpty(node.getNextNodes())) {
// System.out.println("The task flow done!");
// return executableNodes;
// }
//execute
waitFor();
if (executor.isShutdown()) return executableNodes;
executingTaskNode.add(node);
Future<TaskUnit.ExecuteResult> future = executor.submit(new Callable<TaskUnit.ExecuteResult>() {
@Override
public TaskUnit.ExecuteResult call() {
if (node.getTaskUnit() == null) return TaskUnit.ExecuteResult.SUCCESS;
return node.getTaskUnit().execute();
}
});
TaskUnit.ExecuteResult result = null;
try {
result = future.get();
} catch (Exception e) {
e.printStackTrace();
return executableNodes;
} finally {
executingTaskNode.remove(node);
}
if (result == TaskUnit.ExecuteResult.FAIL) {
System.err.println("The task flow fail!");
return executableNodes;
}
node.getNextNodes().forEach(item -> {
//传递信号量
node.next();
//判断信号量是否以准备好,如果是则执行任务
if (item.isReady()) executableNodes.add((MemoryTaskNode) item);
});
return executableNodes;
}
private void waitFor() {
while (isWaiting) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private MemoryTaskNode createTask() {
MemoryTaskNode rootNode = this.createStartNode();
MemoryTaskNode taskNode1 = createNode("任务1");
rootNode.addNextNode(taskNode1);
MemoryTaskNode taskNode2 = createNode("任务2");
MemoryTaskNode taskNode3 = createNode("任务3");
taskNode1.addNextNode(taskNode2).addNextNode(taskNode3);
MemoryTaskNode taskNode4 = createNode("任务4");
taskNode2.addNextNode(taskNode4);
taskNode3.addNextNode(taskNode4);
MemoryTaskNode endNode = this.createEndNode();
taskNode4.addNextNode(endNode);
return rootNode;
}
private MemoryTaskNode createNode(String taskName) {
MemoryTaskUnit taskUnit = new MemoryTaskUnit(taskName) {
@Override
public ExecuteResult execute() {
System.out.println(taskName + "任务启动");
for (int i = 0; i < RandomUtil.randomInt(5); i++) {
System.out.println(taskName + "任务执行中...");
try {
waitFor();
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(taskName + "任务完成");
return ExecuteResult.SUCCESS;
}
};
return new MemoryTaskNode(taskUnit);
}
private MemoryTaskNode createStartNode() {
return new MemoryTaskNode(new MemoryTaskUnit("开始节点") {
@Override
public ExecuteResult execute() {
return ExecuteResult.SUCCESS;
}
});
}
private MemoryTaskNode createEndNode() {
return new MemoryTaskNode(new MemoryTaskUnit("结束节点") {
@Override
public ExecuteResult execute() {
System.out.println("The task flow done!");
executor.shutdownNow();
return ExecuteResult.SUCCESS;
}
});
}
}
| UTF-8 | Java | 4,518 | java | MemoryTaskFlow.java | Java | [
{
"context": "\nimport java.util.concurrent.*;\n\n/**\n * Created by feng on 2019/9/5 0005\n */\npublic class MemoryTaskFlow ",
"end": 399,
"score": 0.9974958896636963,
"start": 395,
"tag": "USERNAME",
"value": "feng"
}
]
| null | []
| package cn.exrick.xboot.task.engine.memory;
import cn.exrick.xboot.task.engine.TaskFlowAdapter;
import cn.exrick.xboot.task.engine.TaskUnit;
import cn.hutool.core.collection.ConcurrentHashSet;
import cn.hutool.core.util.RandomUtil;
import com.google.api.client.util.Sets;
import org.springframework.util.CollectionUtils;
import java.util.Set;
import java.util.concurrent.*;
/**
* Created by feng on 2019/9/5 0005
*/
public class MemoryTaskFlow extends TaskFlowAdapter {
/**
* 执行器
*/
private ExecutorService executor;
/**
* 控制任务等待
*/
private boolean isWaiting;
/**
*
*/
private MemoryTaskNode rootNode;
private ConcurrentHashSet<MemoryTaskNode> executingTaskNode = new ConcurrentHashSet<>();
@Override
public void loadTask() {
rootNode = createTask();
executor = Executors.newFixedThreadPool(5);
}
@Override
public void start() {
Set<MemoryTaskNode> executableNodes = process(rootNode);
while (!CollectionUtils.isEmpty(executableNodes)) {
Set<MemoryTaskNode> executableNodeTemps = Sets.newHashSet();
executableNodes.forEach(item -> {
executableNodeTemps.addAll(process(item));
});
executableNodes = executableNodeTemps;
}
}
@Override
public void recovery() {
isWaiting = false;
}
@Override
public void suspend() {
isWaiting = true;
}
@Override
public void kill() {
executor.shutdownNow();
}
@Override
public Set<MemoryTaskNode> queryPhase() {
return executingTaskNode;
}
private Set<MemoryTaskNode> process(MemoryTaskNode node) {
Set<MemoryTaskNode> executableNodes = Sets.newHashSet();
// if (CollectionUtils.isEmpty(node.getNextNodes())) {
// System.out.println("The task flow done!");
// return executableNodes;
// }
//execute
waitFor();
if (executor.isShutdown()) return executableNodes;
executingTaskNode.add(node);
Future<TaskUnit.ExecuteResult> future = executor.submit(new Callable<TaskUnit.ExecuteResult>() {
@Override
public TaskUnit.ExecuteResult call() {
if (node.getTaskUnit() == null) return TaskUnit.ExecuteResult.SUCCESS;
return node.getTaskUnit().execute();
}
});
TaskUnit.ExecuteResult result = null;
try {
result = future.get();
} catch (Exception e) {
e.printStackTrace();
return executableNodes;
} finally {
executingTaskNode.remove(node);
}
if (result == TaskUnit.ExecuteResult.FAIL) {
System.err.println("The task flow fail!");
return executableNodes;
}
node.getNextNodes().forEach(item -> {
//传递信号量
node.next();
//判断信号量是否以准备好,如果是则执行任务
if (item.isReady()) executableNodes.add((MemoryTaskNode) item);
});
return executableNodes;
}
private void waitFor() {
while (isWaiting) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private MemoryTaskNode createTask() {
MemoryTaskNode rootNode = this.createStartNode();
MemoryTaskNode taskNode1 = createNode("任务1");
rootNode.addNextNode(taskNode1);
MemoryTaskNode taskNode2 = createNode("任务2");
MemoryTaskNode taskNode3 = createNode("任务3");
taskNode1.addNextNode(taskNode2).addNextNode(taskNode3);
MemoryTaskNode taskNode4 = createNode("任务4");
taskNode2.addNextNode(taskNode4);
taskNode3.addNextNode(taskNode4);
MemoryTaskNode endNode = this.createEndNode();
taskNode4.addNextNode(endNode);
return rootNode;
}
private MemoryTaskNode createNode(String taskName) {
MemoryTaskUnit taskUnit = new MemoryTaskUnit(taskName) {
@Override
public ExecuteResult execute() {
System.out.println(taskName + "任务启动");
for (int i = 0; i < RandomUtil.randomInt(5); i++) {
System.out.println(taskName + "任务执行中...");
try {
waitFor();
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(taskName + "任务完成");
return ExecuteResult.SUCCESS;
}
};
return new MemoryTaskNode(taskUnit);
}
private MemoryTaskNode createStartNode() {
return new MemoryTaskNode(new MemoryTaskUnit("开始节点") {
@Override
public ExecuteResult execute() {
return ExecuteResult.SUCCESS;
}
});
}
private MemoryTaskNode createEndNode() {
return new MemoryTaskNode(new MemoryTaskUnit("结束节点") {
@Override
public ExecuteResult execute() {
System.out.println("The task flow done!");
executor.shutdownNow();
return ExecuteResult.SUCCESS;
}
});
}
}
| 4,518 | 0.705829 | 0.697177 | 183 | 23 | 20.799065 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.202186 | false | false | 0 |
0ffac2b5991db6cf218fcedc75fc49613e08dae5 | 29,953,101,960,556 | 7b163cb37c1a9fccdace89935d4a5be932b2af77 | /ProjetoDACEJB/src/main/java/br/edu/ifpb/dac/ejb/mdbeans/NotificacoesMBean.java | 28fea961b736389cd36b94075ee223909ad6e55e | []
| no_license | ifpb/projeto-dac | https://github.com/ifpb/projeto-dac | e1756a3d082ea6f93490132ada5bb1d94004110a | a95ea6daf9e6cb23d3eee837985ceaf281c36408 | refs/heads/master | 2022-10-02T04:34:50.544000 | 2020-02-21T12:17:18 | 2020-02-21T12:17:18 | 226,317,115 | 1 | 1 | null | false | 2022-09-08T01:04:33 | 2019-12-06T11:40:35 | 2020-02-21T12:18:12 | 2022-09-08T01:04:32 | 262 | 1 | 1 | 5 | Java | false | false | package br.edu.ifpb.dac.ejb.mdbeans;
import br.edu.ifpb.dac.ejb.sessionbeans.NotificacoesController;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.EJB;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import java.util.logging.Level;
import java.util.logging.Logger;
@MessageDriven(mappedName = "jms/notificacoes", activationConfig = {
@ActivationConfigProperty(propertyName = "messageSelector", propertyValue = "tipo = 'tempo'")})
public class NotificacoesMBean implements MessageListener {
private static final Logger log = Logger.getLogger(NotificacoesMBean.class.getName());
@EJB
private NotificacoesController notificacoesController;
@Override
public void onMessage(Message message) {
TextMessage textMessage = (TextMessage) message;
try {
notificacoesController.salvaNotificacao(textMessage.getText());
} catch (JMSException e) {
log.log(Level.WARNING, "Problema ao salvar notificação");
}
}
}
| UTF-8 | Java | 1,106 | java | NotificacoesMBean.java | Java | []
| null | []
| package br.edu.ifpb.dac.ejb.mdbeans;
import br.edu.ifpb.dac.ejb.sessionbeans.NotificacoesController;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.EJB;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import java.util.logging.Level;
import java.util.logging.Logger;
@MessageDriven(mappedName = "jms/notificacoes", activationConfig = {
@ActivationConfigProperty(propertyName = "messageSelector", propertyValue = "tipo = 'tempo'")})
public class NotificacoesMBean implements MessageListener {
private static final Logger log = Logger.getLogger(NotificacoesMBean.class.getName());
@EJB
private NotificacoesController notificacoesController;
@Override
public void onMessage(Message message) {
TextMessage textMessage = (TextMessage) message;
try {
notificacoesController.salvaNotificacao(textMessage.getText());
} catch (JMSException e) {
log.log(Level.WARNING, "Problema ao salvar notificação");
}
}
}
| 1,106 | 0.75 | 0.75 | 34 | 31.470589 | 27.607794 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.558824 | false | false | 0 |
f7055d3f8ba88fc9ff08a2ec80783113223d8ad5 | 27,547,920,253,564 | 23c9dcc425b76a593d45a248a72a86e5022e2ea1 | /edxMITpractice/ps2/FilterTest.java | 96454abe3d7e057eaf4db2e214f77828316331bd | []
| no_license | tiborh/java | https://github.com/tiborh/java | c54436ba982fdd7e64eaeb1ed3b65e8e1a7f2a94 | 5e0fafd44a1f6eeea6482030513d4241ac5cb26b | refs/heads/master | 2020-04-07T05:18:03.702000 | 2017-04-03T00:40:57 | 2017-04-03T00:40:57 | 54,286,999 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ps2;
import static org.junit.Assert.*;
import java.time.Instant;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
public class FilterTest {
/*
* writtenBy Tests
* 1. Assume that list is never empty (test in MyFilterTest
* 2. Assume that user is never zero length string (test in MyFilterTest)
* 3. If one tweet is in the list, that one item is returned if username matches
* 4. test with uppercase, mix case
* a. as "username"
* b. as "author" in tweet
* 5. If no match, empty list is returned.
* 6. Check if one item is matched
* 7. Check if multiple items are matched.
* 8. Check with username which is a substring of a user string
* a. beginning of string
* b. middle of string
* c. end of string
* 9. Check with author which is a substring of a username
* a.-c. same as above
*
* inTimespan
* 1. Assume neither list is empty (test in MyFilterTest
* 2. try zero match
* a. above range
* b. below range
* 3. try one match
* a. one of one (skipped)
* b. one of multi
* 4. try multiple matches
* a. all of multi
* b. some of multi
* 5. try matches on the edges of the timespan (included in multi-multi)
* 6. try matches in the middle of the timespan
* 7. try matches only minimum time outside the timespan (how much is minimum?)
* 8. test for correct order (included in 4)
*
* containing
* 0. Wordiness of Strings is not checked)
* 1. Assume list is not empty (test in MyFilterTest
* 2. Assume word is not zero length (test in MyFilterTest
* 3. Assume that each word is longer than zero (test in MyFilterTest
* 4. Check when none matches
* 5. try one match
* 6. try multi matches
* 7. test case insensivity
* 8. test that full word matches only
* 9. test when match is at front of the string
* 10. test when match is at the back of the string
* 11. test when match is somewhere in the middle of the string
* 12. test when only one word matches
* 13. test when multiple words match
* 14. Question: what about words in quotes or followed by punctuation?
* TODO: mask regex metacharacters
*/
private static final Instant d0 = Instant.parse("2016-02-17T09:59:00Z");
private static final Instant d1 = Instant.parse("2016-02-17T10:00:00Z");
private static final Instant d2 = Instant.parse("2016-02-17T11:00:00Z");
private static final Instant d3 = Instant.parse("2016-02-17T11:00:20Z");
private static final Instant d4 = Instant.parse("2016-02-17T11:00:30Z");
private static final Instant d5 = Instant.parse("2016-02-17T11:00:40Z");
private static final Instant d6 = Instant.parse("2016-02-17T11:00:45Z");
private static final Tweet tweet0 = new Tweet(0, "aLysSa", "it reasonable to talk about @rivest a lot", d1);
private static final Tweet tweet1 = new Tweet(1, "alyssa", "is it reasonable to talk about rivest so much?", d1);
private static final Tweet tweet2 = new Tweet(2, "bbitdiddle", "rivest talk in 30 minutes #hype", d2);
private static final Tweet tweet3 = new Tweet(3, "alyssa", "Is @Abe around?", d3);
private static final Tweet tweet4 = new Tweet(4, "alys", "Is @any around?", d4);
private static final Tweet tweet5 = new Tweet(5, "diddle", "Is @bbit around?", d5);
private static final Tweet tweet6 = new Tweet(6, "diddl", "Is @any around?", d6);
@Test(expected=AssertionError.class)
public void testAssertionsEnabled() {
assert false; // make sure assertions are enabled with VM argument: -ea
}
@Test
public void testWrittenByEmptyTweets() {
List<Tweet> writtenBy = Filter.writtenBy(Arrays.asList(), "alyssa");
assertEquals("expected zero length list",0,writtenBy.size());
}
@Test
public void testWrittenBySingleTweetSingleResult() {
List<Tweet> writtenBy = Filter.writtenBy(Arrays.asList(tweet1), "alyssa");
assertEquals("expected singleton list", 1, writtenBy.size());
assertTrue("expected list to contain tweet", writtenBy.contains(tweet1));
}
@Test
public void testWrittenByMultipleTweetsAuthorSubstringFrontZeroResult() {
List<Tweet> writtenBy = Filter.writtenBy(Arrays.asList(tweet1, tweet2), "a");
assertEquals("expected singleton list", 0, writtenBy.size());
}
@Test
public void testWrittenByMultipleTweetsSingleResult() {
List<Tweet> writtenBy = Filter.writtenBy(Arrays.asList(tweet1, tweet2), "alyssa");
assertEquals("expected singleton list", 1, writtenBy.size());
assertTrue("expected list to contain tweet", writtenBy.contains(tweet1));
}
@Test
public void testWrittenByMultipleTweetsAuthorSubtringFrontSingleResult() {
List<Tweet> writtenBy = Filter.writtenBy(Arrays.asList(tweet1, tweet4), "alys");
assertEquals("expected singleton list", 1, writtenBy.size());
assertTrue("expected list to contain tweet", writtenBy.contains(tweet4));
}
@Test
public void testWrittenByMultipleTweetsAuthorSubtringMidSingleResult() {
List<Tweet> writtenBy = Filter.writtenBy(Arrays.asList(tweet2, tweet6), "diddl");
assertEquals("expected singleton list", 1, writtenBy.size());
assertTrue("expected list to contain tweet", writtenBy.contains(tweet6));
}
@Test
public void testWrittenByMultipleTweetsAuthorSubtringEndSingleResult() {
List<Tweet> writtenBy = Filter.writtenBy(Arrays.asList(tweet2, tweet5), "diddle");
assertEquals("expected singleton list", 1, writtenBy.size());
assertTrue("expected list to contain tweet", writtenBy.contains(tweet5));
}
@Test
public void testWrittenByMultipleTweetsMultipleResults() {
List<Tweet> writtenBy = Filter.writtenBy(Arrays.asList(tweet1, tweet3), "alyssa");
assertEquals("expected singleton list", 2, writtenBy.size());
assertTrue("expected list to contain tweet", writtenBy.contains(tweet1));
assertTrue("expected list to contain tweet", writtenBy.contains(tweet3));
}
@Test
public void testWrittenByMultipleTweetsMixedCaseUsername() {
List<Tweet> writtenBy = Filter.writtenBy(Arrays.asList(tweet1, tweet2), "AlySsA");
assertEquals("expected singleton list", 1, writtenBy.size());
assertTrue("expected list to contain tweet", writtenBy.contains(tweet1));
}
@Test
public void testWrittenByMultipleTweetsMixedCaseTweetAuthor() {
List<Tweet> writtenBy = Filter.writtenBy(Arrays.asList(tweet0, tweet2), "alyssa");
assertEquals("expected singleton list", 1, writtenBy.size());
assertTrue("expected list to contain tweet", writtenBy.contains(tweet0));
}
@Test
public void testWrittenByMultipleTweetsAuthorSubstringEndZeroResult() {
List<Tweet> writtenBy = Filter.writtenBy(Arrays.asList(tweet1, tweet2), "lysa");
assertEquals("expected singleton list", 0, writtenBy.size());
}
@Test
public void testWrittenByMultipleTweetsAuthorSubstringMiddleZeroResult() {
List<Tweet> writtenBy = Filter.writtenBy(Arrays.asList(tweet1, tweet2), "lys");
assertEquals("expected singleton list", 0, writtenBy.size());
}
@Test
public void testInTimespanMultipleTweetsZeroResultAboveRange() {
Instant testStart = Instant.parse("2016-02-17T09:00:00Z");
Instant testEnd = Instant.parse("2016-02-17T09:59:59Z");
List<Tweet> inTimespan = Filter.inTimespan(Arrays.asList(tweet1, tweet2), new Timespan(testStart, testEnd));
assertTrue("expected non-empty list", inTimespan.isEmpty());
}
@Test
public void testInTimespanMultipleTweetsZeroResultBelowRange() {
Instant testStart = Instant.parse("2016-02-17T11:00:01Z");
Instant testEnd = Instant.parse("2016-02-17T12:59:59Z");
List<Tweet> inTimespan = Filter.inTimespan(Arrays.asList(tweet1, tweet2), new Timespan(testStart, testEnd));
assertTrue("expected non-empty list", inTimespan.isEmpty());
}
@Test
public void testInTimespanMultipleTweetsZeroResultBelowRangeMinimumDiff() {
Instant testStart = Instant.parse("2016-02-17T11:00:01Z");
Instant testEnd = Instant.parse("2016-02-17T12:59:59.999999999Z");
List<Tweet> inTimespan = Filter.inTimespan(Arrays.asList(tweet1, tweet2), new Timespan(testStart, testEnd));
assertTrue("expected non-empty list", inTimespan.isEmpty());
}
@Test
public void testInTimespanMultipleTweetsSingleResultMiddle() {
Instant testStart = Instant.parse("2016-02-17T10:59:00Z");
Instant testEnd = Instant.parse("2016-02-17T11:00:10Z");
List<Tweet> inTimespan = Filter.inTimespan(Arrays.asList(tweet1, tweet2, tweet3), new Timespan(testStart, testEnd));
assertFalse("expected non-empty list", inTimespan.isEmpty());
assertTrue("expected list to contain tweets", inTimespan.containsAll(Arrays.asList(tweet2)));
}
@Test
public void testInTimespanMultipleTweetsSingleResultFirst() {
Instant testStart = Instant.parse("2016-02-17T09:59:00Z");
Instant testEnd = Instant.parse("2016-02-17T10:00:10Z");
List<Tweet> inTimespan = Filter.inTimespan(Arrays.asList(tweet1, tweet2, tweet3), new Timespan(testStart, testEnd));
assertFalse("expected non-empty list", inTimespan.isEmpty());
assertTrue("expected list to contain tweets", inTimespan.containsAll(Arrays.asList(tweet1)));
}
@Test
public void testInTimespanMultipleTweetsSingleResultLast() {
Instant testStart = Instant.parse("2016-02-17T11:00:10Z");
Instant testEnd = Instant.parse("2016-02-17T11:00:20Z");
List<Tweet> inTimespan = Filter.inTimespan(Arrays.asList(tweet1, tweet2, tweet3), new Timespan(testStart, testEnd));
assertFalse("expected non-empty list", inTimespan.isEmpty());
assertTrue("expected list to contain tweets", inTimespan.containsAll(Arrays.asList(tweet3)));
}
@Test
public void testInTimespanMultipleTweetsMultipleResultsAll() {
Instant testStart = Instant.parse("2016-02-17T09:00:00Z");
Instant testEnd = Instant.parse("2016-02-17T12:00:00Z");
List<Tweet> inTimespan = Filter.inTimespan(Arrays.asList(tweet1, tweet2), new Timespan(testStart, testEnd));
assertFalse("expected non-empty list", inTimespan.isEmpty());
assertTrue("expected list to contain tweets", inTimespan.containsAll(Arrays.asList(tweet1, tweet2)));
assertEquals("expected same order", 0, inTimespan.indexOf(tweet1));
assertEquals("expected same order", 1, inTimespan.indexOf(tweet2));
}
@Test
public void testInTimespanMultipleTweetsMultipleResultsSome() {
Instant testStart = Instant.parse("2016-02-17T09:00:00Z");
Instant testEnd = Instant.parse("2016-02-17T11:00:10Z");
List<Tweet> inTimespan = Filter.inTimespan(Arrays.asList(tweet3, tweet2, tweet1), new Timespan(testStart, testEnd));
assertFalse("expected non-empty list", inTimespan.isEmpty());
assertTrue("expected list to contain tweets", inTimespan.containsAll(Arrays.asList(tweet2, tweet1)));
assertEquals("expected same order", 0, inTimespan.indexOf(tweet2));
assertEquals("expected same order", 1, inTimespan.indexOf(tweet1));
}
@Test
public void testInTimespanMultipleTweetsMultipleResultsBorders() {
Instant testStart = Instant.parse("2016-02-17T10:00:00Z");
Instant testEnd = Instant.parse("2016-02-17T11:00:00Z");
List<Tweet> inTimespan = Filter.inTimespan(Arrays.asList(tweet1, tweet2), new Timespan(testStart, testEnd));
assertFalse("expected non-empty list", inTimespan.isEmpty());
assertTrue("expected list to contain tweets", inTimespan.containsAll(Arrays.asList(tweet1, tweet2)));
assertEquals("expected same order", 0, inTimespan.indexOf(tweet1));
assertEquals("expected same order", 1, inTimespan.indexOf(tweet2));
}
@Test
public void testContainingSingleMatchFront() {
List<Tweet> containing = Filter.containing(Arrays.asList(tweet1, tweet2), Arrays.asList("is"));
assertFalse("expected non-empty list", containing.isEmpty());
assertTrue("expected list to contain tweets", containing.containsAll(Arrays.asList(tweet1)));
}
@Test
public void testContainingSingleMatchMiddle() {
List<Tweet> containing = Filter.containing(Arrays.asList(tweet1, tweet2), Arrays.asList("talk"));
assertFalse("expected non-empty list", containing.isEmpty());
assertTrue("expected list to contain tweets", containing.containsAll(Arrays.asList(tweet1, tweet2)));
assertEquals("expected same order", 0, containing.indexOf(tweet1));
}
@Test
public void testContainingSingleMatchEnd0() {
List<Tweet> containing = Filter.containing(Arrays.asList(tweet0, tweet1, tweet2), Arrays.asList("lot"));
assertFalse("expected non-empty list", containing.isEmpty());
assertTrue("expected list to contain tweets", containing.containsAll(Arrays.asList(tweet0)));
}
// Non-working test case
@Test
public void testContainingSingleMatchEnd1() {
List<Tweet> containing = Filter.containing(Arrays.asList(tweet1, tweet2), Arrays.asList("much\\?"));
assertFalse("expected non-empty list", containing.isEmpty());
assertTrue("expected list to contain tweets", containing.containsAll(Arrays.asList(tweet1)));
}
@Test
public void testContainingSingleMatchUsernameRef() {
List<Tweet> containing = Filter.containing(Arrays.asList(tweet1, tweet4), Arrays.asList("@any"));
assertFalse("expected non-empty list", containing.isEmpty());
assertTrue("expected list to contain tweets", containing.containsAll(Arrays.asList(tweet4)));
}
@Test
public void testContainingSingleMatchCaseInsensitive() {
List<Tweet> containing = Filter.containing(Arrays.asList(tweet1, tweet2), Arrays.asList("taLK"));
assertFalse("expected non-empty list", containing.isEmpty());
assertTrue("expected list to contain tweets", containing.containsAll(Arrays.asList(tweet1, tweet2)));
assertEquals("expected same order", 0, containing.indexOf(tweet1));
}
@Test
public void testContainingBothMatchOnlyInOne() {
List<Tweet> containing = Filter.containing(Arrays.asList(tweet1, tweet2), Arrays.asList("talk","much"));
assertFalse("expected non-empty list", containing.isEmpty());
assertEquals("expected to get back only one match:",1,containing.size());
assertTrue("expected list to contain first tweet", containing.containsAll(Arrays.asList(tweet1)));
}
@Test
public void testContainingBothMatchOnlyInBoth() {
List<Tweet> containing = Filter.containing(Arrays.asList(tweet0, tweet1), Arrays.asList("talk","reasonable"));
assertFalse("expected non-empty list", containing.isEmpty());
assertEquals("expected to get back both tweets:",2,containing.size());
assertTrue("expected list to contain tweets in order", containing.containsAll(Arrays.asList(tweet0,tweet1)));
}
@Test
public void testContainingNoMatch() {
List<Tweet> containing = Filter.containing(Arrays.asList(tweet1, tweet2), Arrays.asList("saint"));
assertTrue("expected non-empty list", containing.isEmpty());
}
@Test
public void testContainingNoMatchSubstringFront() {
List<Tweet> containing = Filter.containing(Arrays.asList(tweet1, tweet2), Arrays.asList("reason"));
assertTrue("expected non-empty list", containing.isEmpty());
}
@Test
public void testContainingNoMatchSubstringEnd() {
List<Tweet> containing = Filter.containing(Arrays.asList(tweet1, tweet2), Arrays.asList("able"));
assertTrue("expected non-empty list", containing.isEmpty());
}
@Test
public void testContainingNoMatchSubstringMiddle() {
List<Tweet> containing = Filter.containing(Arrays.asList(tweet1, tweet2), Arrays.asList("v"));
assertTrue("expected non-empty list", containing.isEmpty());
}
/*
* Warning: all the tests you write here must be runnable against any Filter
* class that follows the spec. It will be run against several staff
* implementations of Filter, which will be done by overwriting
* (temporarily) your version of Filter with the staff's version.
* DO NOT strengthen the spec of Filter or its methods.
*
* In particular, your test cases must not call helper methods of your own
* that you have put in Filter, because that means you're testing a stronger
* spec than Filter says. If you need such helper methods, define them in a
* different class. If you only need them in this test class, then keep them
* in this test class.
*/
}
| UTF-8 | Java | 17,512 | java | FilterTest.java | Java | [
{
"context": "4. test with uppercase, mix case\n * a. as \"username\"\n * b. as \"author\" in tweet\n * 5. If n",
"end": 497,
"score": 0.9979830980300903,
"start": 489,
"tag": "USERNAME",
"value": "username"
},
{
"context": "private static final Tweet tweet0 = new Tweet(0, \"aLysSa\", \"it reasonable to talk about @rivest a lot\", d1",
"end": 2930,
"score": 0.9996760487556458,
"start": 2924,
"tag": "USERNAME",
"value": "aLysSa"
},
{
"context": " Tweet(0, \"aLysSa\", \"it reasonable to talk about @rivest a lot\", d1);\n private static final Tweet tweet",
"end": 2969,
"score": 0.955547571182251,
"start": 2963,
"tag": "USERNAME",
"value": "rivest"
},
{
"context": "private static final Tweet tweet1 = new Tweet(1, \"alyssa\", \"is it reasonable to talk about rivest so much?",
"end": 3043,
"score": 0.9996203184127808,
"start": 3037,
"tag": "USERNAME",
"value": "alyssa"
},
{
"context": "private static final Tweet tweet2 = new Tweet(2, \"bbitdiddle\", \"rivest talk in 30 minutes #hype\", d2);\n pri",
"end": 3165,
"score": 0.9983550906181335,
"start": 3155,
"tag": "USERNAME",
"value": "bbitdiddle"
},
{
"context": "private static final Tweet tweet3 = new Tweet(3, \"alyssa\", \"Is @Abe around?\", d3);\n private static fina",
"end": 3268,
"score": 0.9996873736381531,
"start": 3262,
"tag": "USERNAME",
"value": "alyssa"
},
{
"context": "ic final Tweet tweet3 = new Tweet(3, \"alyssa\", \"Is @Abe around?\", d3);\n private static final Tweet twe",
"end": 3279,
"score": 0.9915086627006531,
"start": 3275,
"tag": "USERNAME",
"value": "@Abe"
},
{
"context": "private static final Tweet tweet4 = new Tweet(4, \"alys\", \"Is @any around?\", d4);\n private static fina",
"end": 3353,
"score": 0.9993234872817993,
"start": 3349,
"tag": "USERNAME",
"value": "alys"
},
{
"context": "atic final Tweet tweet4 = new Tweet(4, \"alys\", \"Is @any around?\", d4);\n private static final Tweet twe",
"end": 3364,
"score": 0.9739640355110168,
"start": 3360,
"tag": "USERNAME",
"value": "@any"
},
{
"context": "private static final Tweet tweet5 = new Tweet(5, \"diddle\", \"Is @bbit around?\", d5);\n private static fin",
"end": 3440,
"score": 0.9978666305541992,
"start": 3434,
"tag": "NAME",
"value": "diddle"
},
{
"context": "ic final Tweet tweet5 = new Tweet(5, \"diddle\", \"Is @bbit around?\", d5);\n private static final Tweet twe",
"end": 3452,
"score": 0.999457061290741,
"start": 3447,
"tag": "USERNAME",
"value": "@bbit"
},
{
"context": "private static final Tweet tweet6 = new Tweet(6, \"diddl\", \"Is @any around?\", d6);\n \n @Test(expected",
"end": 3527,
"score": 0.9992348551750183,
"start": 3522,
"tag": "NAME",
"value": "diddl"
},
{
"context": "tic final Tweet tweet6 = new Tweet(6, \"diddl\", \"Is @any around?\", d6);\n \n @Test(expected=AssertionE",
"end": 3538,
"score": 0.9581723213195801,
"start": 3534,
"tag": "USERNAME",
"value": "@any"
},
{
"context": "t> writtenBy = Filter.writtenBy(Arrays.asList(), \"alyssa\");\n \n assertEquals(\"expected zero l",
"end": 3857,
"score": 0.998307466506958,
"start": 3851,
"tag": "NAME",
"value": "alyssa"
},
{
"context": "ttenBy = Filter.writtenBy(Arrays.asList(tweet1), \"alyssa\");\n \n assertEquals(\"expected single",
"end": 4097,
"score": 0.9978525638580322,
"start": 4091,
"tag": "NAME",
"value": "alyssa"
},
{
"context": " Filter.writtenBy(Arrays.asList(tweet1, tweet2), \"alyssa\");\n \n assertEquals(\"expected single",
"end": 4694,
"score": 0.998103141784668,
"start": 4688,
"tag": "NAME",
"value": "alyssa"
},
{
"context": " Filter.writtenBy(Arrays.asList(tweet2, tweet6), \"diddl\");\n \n assertEquals(\"expected single",
"end": 5385,
"score": 0.994914710521698,
"start": 5380,
"tag": "NAME",
"value": "diddl"
},
{
"context": " Filter.writtenBy(Arrays.asList(tweet2, tweet5), \"diddle\");\n \n assertEquals(\"expected single",
"end": 5735,
"score": 0.7960329055786133,
"start": 5729,
"tag": "NAME",
"value": "diddle"
},
{
"context": " Filter.writtenBy(Arrays.asList(tweet1, tweet3), \"alyssa\");\n \n assertEquals(\"expected single",
"end": 6072,
"score": 0.8600465059280396,
"start": 6066,
"tag": "USERNAME",
"value": "alyssa"
},
{
"context": " Filter.writtenBy(Arrays.asList(tweet1, tweet2), \"AlySsA\");\n \n assertEquals(\"expected single",
"end": 6488,
"score": 0.9989569187164307,
"start": 6482,
"tag": "USERNAME",
"value": "AlySsA"
},
{
"context": " Filter.writtenBy(Arrays.asList(tweet0, tweet2), \"alyssa\");\n \n assertEquals(\"expected single",
"end": 6825,
"score": 0.8948711156845093,
"start": 6819,
"tag": "USERNAME",
"value": "alyssa"
},
{
"context": " Filter.writtenBy(Arrays.asList(tweet1, tweet2), \"lysa\");\n \n assertEquals(\"expected single",
"end": 7168,
"score": 0.7927718162536621,
"start": 7164,
"tag": "USERNAME",
"value": "lysa"
},
{
"context": " Filter.writtenBy(Arrays.asList(tweet1, tweet2), \"lys\");\n \n assertEquals(\"expected single",
"end": 7431,
"score": 0.9780415892601013,
"start": 7428,
"tag": "USERNAME",
"value": "lys"
},
{
"context": "ining(Arrays.asList(tweet1, tweet4), Arrays.asList(\"@any\"));\n \n assertFalse(\"expected non-em",
"end": 14198,
"score": 0.864956796169281,
"start": 14194,
"tag": "USERNAME",
"value": "@any"
}
]
| null | []
| package ps2;
import static org.junit.Assert.*;
import java.time.Instant;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
public class FilterTest {
/*
* writtenBy Tests
* 1. Assume that list is never empty (test in MyFilterTest
* 2. Assume that user is never zero length string (test in MyFilterTest)
* 3. If one tweet is in the list, that one item is returned if username matches
* 4. test with uppercase, mix case
* a. as "username"
* b. as "author" in tweet
* 5. If no match, empty list is returned.
* 6. Check if one item is matched
* 7. Check if multiple items are matched.
* 8. Check with username which is a substring of a user string
* a. beginning of string
* b. middle of string
* c. end of string
* 9. Check with author which is a substring of a username
* a.-c. same as above
*
* inTimespan
* 1. Assume neither list is empty (test in MyFilterTest
* 2. try zero match
* a. above range
* b. below range
* 3. try one match
* a. one of one (skipped)
* b. one of multi
* 4. try multiple matches
* a. all of multi
* b. some of multi
* 5. try matches on the edges of the timespan (included in multi-multi)
* 6. try matches in the middle of the timespan
* 7. try matches only minimum time outside the timespan (how much is minimum?)
* 8. test for correct order (included in 4)
*
* containing
* 0. Wordiness of Strings is not checked)
* 1. Assume list is not empty (test in MyFilterTest
* 2. Assume word is not zero length (test in MyFilterTest
* 3. Assume that each word is longer than zero (test in MyFilterTest
* 4. Check when none matches
* 5. try one match
* 6. try multi matches
* 7. test case insensivity
* 8. test that full word matches only
* 9. test when match is at front of the string
* 10. test when match is at the back of the string
* 11. test when match is somewhere in the middle of the string
* 12. test when only one word matches
* 13. test when multiple words match
* 14. Question: what about words in quotes or followed by punctuation?
* TODO: mask regex metacharacters
*/
private static final Instant d0 = Instant.parse("2016-02-17T09:59:00Z");
private static final Instant d1 = Instant.parse("2016-02-17T10:00:00Z");
private static final Instant d2 = Instant.parse("2016-02-17T11:00:00Z");
private static final Instant d3 = Instant.parse("2016-02-17T11:00:20Z");
private static final Instant d4 = Instant.parse("2016-02-17T11:00:30Z");
private static final Instant d5 = Instant.parse("2016-02-17T11:00:40Z");
private static final Instant d6 = Instant.parse("2016-02-17T11:00:45Z");
private static final Tweet tweet0 = new Tweet(0, "aLysSa", "it reasonable to talk about @rivest a lot", d1);
private static final Tweet tweet1 = new Tweet(1, "alyssa", "is it reasonable to talk about rivest so much?", d1);
private static final Tweet tweet2 = new Tweet(2, "bbitdiddle", "rivest talk in 30 minutes #hype", d2);
private static final Tweet tweet3 = new Tweet(3, "alyssa", "Is @Abe around?", d3);
private static final Tweet tweet4 = new Tweet(4, "alys", "Is @any around?", d4);
private static final Tweet tweet5 = new Tweet(5, "diddle", "Is @bbit around?", d5);
private static final Tweet tweet6 = new Tweet(6, "diddl", "Is @any around?", d6);
@Test(expected=AssertionError.class)
public void testAssertionsEnabled() {
assert false; // make sure assertions are enabled with VM argument: -ea
}
@Test
public void testWrittenByEmptyTweets() {
List<Tweet> writtenBy = Filter.writtenBy(Arrays.asList(), "alyssa");
assertEquals("expected zero length list",0,writtenBy.size());
}
@Test
public void testWrittenBySingleTweetSingleResult() {
List<Tweet> writtenBy = Filter.writtenBy(Arrays.asList(tweet1), "alyssa");
assertEquals("expected singleton list", 1, writtenBy.size());
assertTrue("expected list to contain tweet", writtenBy.contains(tweet1));
}
@Test
public void testWrittenByMultipleTweetsAuthorSubstringFrontZeroResult() {
List<Tweet> writtenBy = Filter.writtenBy(Arrays.asList(tweet1, tweet2), "a");
assertEquals("expected singleton list", 0, writtenBy.size());
}
@Test
public void testWrittenByMultipleTweetsSingleResult() {
List<Tweet> writtenBy = Filter.writtenBy(Arrays.asList(tweet1, tweet2), "alyssa");
assertEquals("expected singleton list", 1, writtenBy.size());
assertTrue("expected list to contain tweet", writtenBy.contains(tweet1));
}
@Test
public void testWrittenByMultipleTweetsAuthorSubtringFrontSingleResult() {
List<Tweet> writtenBy = Filter.writtenBy(Arrays.asList(tweet1, tweet4), "alys");
assertEquals("expected singleton list", 1, writtenBy.size());
assertTrue("expected list to contain tweet", writtenBy.contains(tweet4));
}
@Test
public void testWrittenByMultipleTweetsAuthorSubtringMidSingleResult() {
List<Tweet> writtenBy = Filter.writtenBy(Arrays.asList(tweet2, tweet6), "diddl");
assertEquals("expected singleton list", 1, writtenBy.size());
assertTrue("expected list to contain tweet", writtenBy.contains(tweet6));
}
@Test
public void testWrittenByMultipleTweetsAuthorSubtringEndSingleResult() {
List<Tweet> writtenBy = Filter.writtenBy(Arrays.asList(tweet2, tweet5), "diddle");
assertEquals("expected singleton list", 1, writtenBy.size());
assertTrue("expected list to contain tweet", writtenBy.contains(tweet5));
}
@Test
public void testWrittenByMultipleTweetsMultipleResults() {
List<Tweet> writtenBy = Filter.writtenBy(Arrays.asList(tweet1, tweet3), "alyssa");
assertEquals("expected singleton list", 2, writtenBy.size());
assertTrue("expected list to contain tweet", writtenBy.contains(tweet1));
assertTrue("expected list to contain tweet", writtenBy.contains(tweet3));
}
@Test
public void testWrittenByMultipleTweetsMixedCaseUsername() {
List<Tweet> writtenBy = Filter.writtenBy(Arrays.asList(tweet1, tweet2), "AlySsA");
assertEquals("expected singleton list", 1, writtenBy.size());
assertTrue("expected list to contain tweet", writtenBy.contains(tweet1));
}
@Test
public void testWrittenByMultipleTweetsMixedCaseTweetAuthor() {
List<Tweet> writtenBy = Filter.writtenBy(Arrays.asList(tweet0, tweet2), "alyssa");
assertEquals("expected singleton list", 1, writtenBy.size());
assertTrue("expected list to contain tweet", writtenBy.contains(tweet0));
}
@Test
public void testWrittenByMultipleTweetsAuthorSubstringEndZeroResult() {
List<Tweet> writtenBy = Filter.writtenBy(Arrays.asList(tweet1, tweet2), "lysa");
assertEquals("expected singleton list", 0, writtenBy.size());
}
@Test
public void testWrittenByMultipleTweetsAuthorSubstringMiddleZeroResult() {
List<Tweet> writtenBy = Filter.writtenBy(Arrays.asList(tweet1, tweet2), "lys");
assertEquals("expected singleton list", 0, writtenBy.size());
}
@Test
public void testInTimespanMultipleTweetsZeroResultAboveRange() {
Instant testStart = Instant.parse("2016-02-17T09:00:00Z");
Instant testEnd = Instant.parse("2016-02-17T09:59:59Z");
List<Tweet> inTimespan = Filter.inTimespan(Arrays.asList(tweet1, tweet2), new Timespan(testStart, testEnd));
assertTrue("expected non-empty list", inTimespan.isEmpty());
}
@Test
public void testInTimespanMultipleTweetsZeroResultBelowRange() {
Instant testStart = Instant.parse("2016-02-17T11:00:01Z");
Instant testEnd = Instant.parse("2016-02-17T12:59:59Z");
List<Tweet> inTimespan = Filter.inTimespan(Arrays.asList(tweet1, tweet2), new Timespan(testStart, testEnd));
assertTrue("expected non-empty list", inTimespan.isEmpty());
}
@Test
public void testInTimespanMultipleTweetsZeroResultBelowRangeMinimumDiff() {
Instant testStart = Instant.parse("2016-02-17T11:00:01Z");
Instant testEnd = Instant.parse("2016-02-17T12:59:59.999999999Z");
List<Tweet> inTimespan = Filter.inTimespan(Arrays.asList(tweet1, tweet2), new Timespan(testStart, testEnd));
assertTrue("expected non-empty list", inTimespan.isEmpty());
}
@Test
public void testInTimespanMultipleTweetsSingleResultMiddle() {
Instant testStart = Instant.parse("2016-02-17T10:59:00Z");
Instant testEnd = Instant.parse("2016-02-17T11:00:10Z");
List<Tweet> inTimespan = Filter.inTimespan(Arrays.asList(tweet1, tweet2, tweet3), new Timespan(testStart, testEnd));
assertFalse("expected non-empty list", inTimespan.isEmpty());
assertTrue("expected list to contain tweets", inTimespan.containsAll(Arrays.asList(tweet2)));
}
@Test
public void testInTimespanMultipleTweetsSingleResultFirst() {
Instant testStart = Instant.parse("2016-02-17T09:59:00Z");
Instant testEnd = Instant.parse("2016-02-17T10:00:10Z");
List<Tweet> inTimespan = Filter.inTimespan(Arrays.asList(tweet1, tweet2, tweet3), new Timespan(testStart, testEnd));
assertFalse("expected non-empty list", inTimespan.isEmpty());
assertTrue("expected list to contain tweets", inTimespan.containsAll(Arrays.asList(tweet1)));
}
@Test
public void testInTimespanMultipleTweetsSingleResultLast() {
Instant testStart = Instant.parse("2016-02-17T11:00:10Z");
Instant testEnd = Instant.parse("2016-02-17T11:00:20Z");
List<Tweet> inTimespan = Filter.inTimespan(Arrays.asList(tweet1, tweet2, tweet3), new Timespan(testStart, testEnd));
assertFalse("expected non-empty list", inTimespan.isEmpty());
assertTrue("expected list to contain tweets", inTimespan.containsAll(Arrays.asList(tweet3)));
}
@Test
public void testInTimespanMultipleTweetsMultipleResultsAll() {
Instant testStart = Instant.parse("2016-02-17T09:00:00Z");
Instant testEnd = Instant.parse("2016-02-17T12:00:00Z");
List<Tweet> inTimespan = Filter.inTimespan(Arrays.asList(tweet1, tweet2), new Timespan(testStart, testEnd));
assertFalse("expected non-empty list", inTimespan.isEmpty());
assertTrue("expected list to contain tweets", inTimespan.containsAll(Arrays.asList(tweet1, tweet2)));
assertEquals("expected same order", 0, inTimespan.indexOf(tweet1));
assertEquals("expected same order", 1, inTimespan.indexOf(tweet2));
}
@Test
public void testInTimespanMultipleTweetsMultipleResultsSome() {
Instant testStart = Instant.parse("2016-02-17T09:00:00Z");
Instant testEnd = Instant.parse("2016-02-17T11:00:10Z");
List<Tweet> inTimespan = Filter.inTimespan(Arrays.asList(tweet3, tweet2, tweet1), new Timespan(testStart, testEnd));
assertFalse("expected non-empty list", inTimespan.isEmpty());
assertTrue("expected list to contain tweets", inTimespan.containsAll(Arrays.asList(tweet2, tweet1)));
assertEquals("expected same order", 0, inTimespan.indexOf(tweet2));
assertEquals("expected same order", 1, inTimespan.indexOf(tweet1));
}
@Test
public void testInTimespanMultipleTweetsMultipleResultsBorders() {
Instant testStart = Instant.parse("2016-02-17T10:00:00Z");
Instant testEnd = Instant.parse("2016-02-17T11:00:00Z");
List<Tweet> inTimespan = Filter.inTimespan(Arrays.asList(tweet1, tweet2), new Timespan(testStart, testEnd));
assertFalse("expected non-empty list", inTimespan.isEmpty());
assertTrue("expected list to contain tweets", inTimespan.containsAll(Arrays.asList(tweet1, tweet2)));
assertEquals("expected same order", 0, inTimespan.indexOf(tweet1));
assertEquals("expected same order", 1, inTimespan.indexOf(tweet2));
}
@Test
public void testContainingSingleMatchFront() {
List<Tweet> containing = Filter.containing(Arrays.asList(tweet1, tweet2), Arrays.asList("is"));
assertFalse("expected non-empty list", containing.isEmpty());
assertTrue("expected list to contain tweets", containing.containsAll(Arrays.asList(tweet1)));
}
@Test
public void testContainingSingleMatchMiddle() {
List<Tweet> containing = Filter.containing(Arrays.asList(tweet1, tweet2), Arrays.asList("talk"));
assertFalse("expected non-empty list", containing.isEmpty());
assertTrue("expected list to contain tweets", containing.containsAll(Arrays.asList(tweet1, tweet2)));
assertEquals("expected same order", 0, containing.indexOf(tweet1));
}
@Test
public void testContainingSingleMatchEnd0() {
List<Tweet> containing = Filter.containing(Arrays.asList(tweet0, tweet1, tweet2), Arrays.asList("lot"));
assertFalse("expected non-empty list", containing.isEmpty());
assertTrue("expected list to contain tweets", containing.containsAll(Arrays.asList(tweet0)));
}
// Non-working test case
@Test
public void testContainingSingleMatchEnd1() {
List<Tweet> containing = Filter.containing(Arrays.asList(tweet1, tweet2), Arrays.asList("much\\?"));
assertFalse("expected non-empty list", containing.isEmpty());
assertTrue("expected list to contain tweets", containing.containsAll(Arrays.asList(tweet1)));
}
@Test
public void testContainingSingleMatchUsernameRef() {
List<Tweet> containing = Filter.containing(Arrays.asList(tweet1, tweet4), Arrays.asList("@any"));
assertFalse("expected non-empty list", containing.isEmpty());
assertTrue("expected list to contain tweets", containing.containsAll(Arrays.asList(tweet4)));
}
@Test
public void testContainingSingleMatchCaseInsensitive() {
List<Tweet> containing = Filter.containing(Arrays.asList(tweet1, tweet2), Arrays.asList("taLK"));
assertFalse("expected non-empty list", containing.isEmpty());
assertTrue("expected list to contain tweets", containing.containsAll(Arrays.asList(tweet1, tweet2)));
assertEquals("expected same order", 0, containing.indexOf(tweet1));
}
@Test
public void testContainingBothMatchOnlyInOne() {
List<Tweet> containing = Filter.containing(Arrays.asList(tweet1, tweet2), Arrays.asList("talk","much"));
assertFalse("expected non-empty list", containing.isEmpty());
assertEquals("expected to get back only one match:",1,containing.size());
assertTrue("expected list to contain first tweet", containing.containsAll(Arrays.asList(tweet1)));
}
@Test
public void testContainingBothMatchOnlyInBoth() {
List<Tweet> containing = Filter.containing(Arrays.asList(tweet0, tweet1), Arrays.asList("talk","reasonable"));
assertFalse("expected non-empty list", containing.isEmpty());
assertEquals("expected to get back both tweets:",2,containing.size());
assertTrue("expected list to contain tweets in order", containing.containsAll(Arrays.asList(tweet0,tweet1)));
}
@Test
public void testContainingNoMatch() {
List<Tweet> containing = Filter.containing(Arrays.asList(tweet1, tweet2), Arrays.asList("saint"));
assertTrue("expected non-empty list", containing.isEmpty());
}
@Test
public void testContainingNoMatchSubstringFront() {
List<Tweet> containing = Filter.containing(Arrays.asList(tweet1, tweet2), Arrays.asList("reason"));
assertTrue("expected non-empty list", containing.isEmpty());
}
@Test
public void testContainingNoMatchSubstringEnd() {
List<Tweet> containing = Filter.containing(Arrays.asList(tweet1, tweet2), Arrays.asList("able"));
assertTrue("expected non-empty list", containing.isEmpty());
}
@Test
public void testContainingNoMatchSubstringMiddle() {
List<Tweet> containing = Filter.containing(Arrays.asList(tweet1, tweet2), Arrays.asList("v"));
assertTrue("expected non-empty list", containing.isEmpty());
}
/*
* Warning: all the tests you write here must be runnable against any Filter
* class that follows the spec. It will be run against several staff
* implementations of Filter, which will be done by overwriting
* (temporarily) your version of Filter with the staff's version.
* DO NOT strengthen the spec of Filter or its methods.
*
* In particular, your test cases must not call helper methods of your own
* that you have put in Filter, because that means you're testing a stronger
* spec than Filter says. If you need such helper methods, define them in a
* different class. If you only need them in this test class, then keep them
* in this test class.
*/
}
| 17,512 | 0.67251 | 0.640703 | 396 | 43.222221 | 36.93642 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.861111 | false | false | 0 |
4a2dbd154fde407c9798ebc1685d7b1196b50d4b | 15,144,054,701,302 | b4da0278e83810d0d740afe24f56ff18fd836c39 | /core/src/main/java/com/wangyin/ak47/core/handler/LoggingTrafficHandler.java | 4630fd2fdc834071b316daf62b49a68f250fe167 | [
"Apache-2.0"
]
| permissive | xshwlx/Ak47 | https://github.com/xshwlx/Ak47 | 9066f8bf28da1d7ca034014659b53c4561100aca | 80d86f42cd5420cf6e1f14788cad7ebda3a526b0 | refs/heads/master | 2021-01-16T22:25:33.693000 | 2015-01-30T03:13:44 | 2015-01-30T03:13:44 | 30,329,475 | 1 | 0 | null | true | 2015-02-05T00:39:44 | 2015-02-05T00:39:40 | 2015-02-05T00:39:43 | 2015-01-30T03:13:44 | 786 | 0 | 0 | 0 | Java | null | null | package com.wangyin.ak47.core.handler;
import com.wangyin.ak47.common.Logger;
import com.wangyin.ak47.core.HandlerContext;
import com.wangyin.ak47.core.Message;
import com.wangyin.ak47.core.Promise;
public class LoggingTrafficHandler<O, I> extends HandlerAdapter<O, I> {
private static final Logger log = new Logger(LoggingTrafficHandler.class);
@Override
public void doSend(HandlerContext<O, I> ctx, Message<O> msg,
Promise<O, I> promise) throws Exception {
log.info("Send {} bytes to {}.", msg.getBuffer().readableBytes(), ctx.channel().getRemoteAddress().toString());
ctx.send(msg, promise);
}
@Override
public void doReceived(HandlerContext<O, I> ctx, Message<I> msg) throws Exception {
log.info("Received {} bytes from {}.", msg.getBuffer().readableBytes(), ctx.channel().getRemoteAddress().toString());
ctx.fireReceived(msg);
}
}
| UTF-8 | Java | 932 | java | LoggingTrafficHandler.java | Java | []
| null | []
| package com.wangyin.ak47.core.handler;
import com.wangyin.ak47.common.Logger;
import com.wangyin.ak47.core.HandlerContext;
import com.wangyin.ak47.core.Message;
import com.wangyin.ak47.core.Promise;
public class LoggingTrafficHandler<O, I> extends HandlerAdapter<O, I> {
private static final Logger log = new Logger(LoggingTrafficHandler.class);
@Override
public void doSend(HandlerContext<O, I> ctx, Message<O> msg,
Promise<O, I> promise) throws Exception {
log.info("Send {} bytes to {}.", msg.getBuffer().readableBytes(), ctx.channel().getRemoteAddress().toString());
ctx.send(msg, promise);
}
@Override
public void doReceived(HandlerContext<O, I> ctx, Message<I> msg) throws Exception {
log.info("Received {} bytes from {}.", msg.getBuffer().readableBytes(), ctx.channel().getRemoteAddress().toString());
ctx.fireReceived(msg);
}
}
| 932 | 0.682403 | 0.671674 | 26 | 34.846153 | 36.09996 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.884615 | false | false | 0 |
bf5007152497e124b18153db14efd638200d7089 | 8,065,948,603,586 | 0c8c46ed0ad26aadd2a15cde5118a88368ed5011 | /RxRetrofitDaggerMvp/app/src/main/java/com/example/rxretrofitdaggermvp/injector/component/ActivityComponent.java | 51d758c1fc005ccc3af1b16aec1dc70a24966f3f | []
| no_license | wherego/MVP-4 | https://github.com/wherego/MVP-4 | f479da869b0ed08853879754464bda39ff6883d9 | 4721d01b53d211b348f94f279d07ac36d65ca4c5 | refs/heads/master | 2021-01-20T12:28:51.753000 | 2017-04-20T02:28:34 | 2017-04-20T02:28:34 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.rxretrofitdaggermvp.injector.component;
import com.example.rxretrofitdaggermvp.injector.module.ActivityModule;
import com.example.rxretrofitdaggermvp.injector.scope.PerActivity;
import com.example.rxretrofitdaggermvp.ui.activities.MainActivity;
import com.example.rxretrofitdaggermvp.ui.activities.NewsDetailActivity;
import dagger.Component;
/**
* Created by MrKong on 2017/4/1.
*/
@PerActivity
@Component(dependencies = AppComponent.class, modules = ActivityModule.class)
public interface ActivityComponent {
void inject(MainActivity activity);
void inject(NewsDetailActivity newsDetailActivity);
}
| UTF-8 | Java | 637 | java | ActivityComponent.java | Java | [
{
"context": "vity;\n\nimport dagger.Component;\n\n/**\n * Created by MrKong on 2017/4/1.\n */\n\n@PerActivity\n@Component(depende",
"end": 390,
"score": 0.9994617104530334,
"start": 384,
"tag": "USERNAME",
"value": "MrKong"
}
]
| null | []
| package com.example.rxretrofitdaggermvp.injector.component;
import com.example.rxretrofitdaggermvp.injector.module.ActivityModule;
import com.example.rxretrofitdaggermvp.injector.scope.PerActivity;
import com.example.rxretrofitdaggermvp.ui.activities.MainActivity;
import com.example.rxretrofitdaggermvp.ui.activities.NewsDetailActivity;
import dagger.Component;
/**
* Created by MrKong on 2017/4/1.
*/
@PerActivity
@Component(dependencies = AppComponent.class, modules = ActivityModule.class)
public interface ActivityComponent {
void inject(MainActivity activity);
void inject(NewsDetailActivity newsDetailActivity);
}
| 637 | 0.825746 | 0.816327 | 20 | 30.799999 | 29.071636 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.45 | false | false | 0 |
29aafbbc221dcd0bcdc68f43778ab02089b1584f | 2,851,858,293,709 | 2d9c90d1661a00d43d5bc85cea71667f51cb469b | /src/main/java/com/demo/stringbasic/MyStringCompare.java | 91d185dd840213011480a449aacbafb5360bb861 | []
| no_license | shahjadealam/bench-practice | https://github.com/shahjadealam/bench-practice | d61b4073b01e2dff4f09de2960b31f1269c7ad4e | 3ad9b122c2b6b6465fab10f89adfed3a7bf9d9e8 | refs/heads/master | 2020-09-24T15:20:53.878000 | 2019-12-04T05:52:33 | 2019-12-04T05:52:33 | 225,788,966 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.demo.stringbasic;
import java.util.Scanner;
public class MyStringCompare {
public static void main(String[] args) {
try (Scanner sc = new Scanner(System.in)) {
int testCount = sc.nextInt();
while (testCount != 0) {
int len1 = sc.nextInt();
int len2 = sc.nextInt();
String str1 = sc.next();
String str2 = sc.next();
int maxlength = 0;
int result = 0;
if (str1.length() == len1 && str2.length() == len2) {
for (int i = 0; i <= len1 - 1; i++) {
for (int j = 0; j <= len2 - 1; j++) {
if (str1.charAt(i) == str2.charAt(j)) {
maxlength++;
i++;
result = maxlength;
} else
maxlength = 0;
}
}
} else
System.out.println("Invalid Length Entered");
testCount--;
}
} catch (
Exception e) {
}
}
}
| UTF-8 | Java | 835 | java | MyStringCompare.java | Java | []
| null | []
| package com.demo.stringbasic;
import java.util.Scanner;
public class MyStringCompare {
public static void main(String[] args) {
try (Scanner sc = new Scanner(System.in)) {
int testCount = sc.nextInt();
while (testCount != 0) {
int len1 = sc.nextInt();
int len2 = sc.nextInt();
String str1 = sc.next();
String str2 = sc.next();
int maxlength = 0;
int result = 0;
if (str1.length() == len1 && str2.length() == len2) {
for (int i = 0; i <= len1 - 1; i++) {
for (int j = 0; j <= len2 - 1; j++) {
if (str1.charAt(i) == str2.charAt(j)) {
maxlength++;
i++;
result = maxlength;
} else
maxlength = 0;
}
}
} else
System.out.println("Invalid Length Entered");
testCount--;
}
} catch (
Exception e) {
}
}
}
| 835 | 0.529341 | 0.505389 | 45 | 17.555555 | 16.458103 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.266667 | false | false | 0 |
040a3ef7999dee840afe2a7b8d05555ba1adfb06 | 22,076,131,916,421 | bb8adca8a8839c78e5450c10ed064af2ce0912a9 | /MyMP3Player/app/src/main/java/lab/android/mymp3player/MainActivity.java | f0a50962b077f327bddbf65ce8dff9d5695c8139 | []
| no_license | jasperyen/android-examples | https://github.com/jasperyen/android-examples | c96c4907ab7ad4780bc25cc59a3bf148aeac53db | 098a0e1f3fbff6567c0eb396580af6b29a251c3b | refs/heads/master | 2021-01-20T06:17:58.299000 | 2017-04-30T16:38:51 | 2017-04-30T16:38:51 | 89,852,521 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package lab.android.mymp3player;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
private final String TAG = this.getClass().getName();
Button btnPlay, btnStop, btnPause,
btnLoud, btnWisper, btnFile, btnRaw;
MediaPlayer mplayer;
Handler UIhandler;
ProgressBar timeBar;
TextView tim, songname;
Thread timthread;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final AudioManager audioManager = (AudioManager) this.getSystemService(AUDIO_SERVICE);
btnPlay = (Button) findViewById(R.id.play);
btnStop = (Button) findViewById(R.id.stop);
btnPause = (Button) findViewById(R.id.pause);
btnLoud = (Button) findViewById(R.id.loud);
btnWisper = (Button) findViewById(R.id.whispered);
btnFile = (Button) findViewById(R.id.file);
btnRaw = (Button) findViewById(R.id.raw);
timeBar = (ProgressBar) findViewById(R.id.TimeBar);
tim = (TextView) findViewById(R.id.timtxt);
songname = (TextView) findViewById(R.id.songname);
btnPlay.setEnabled(false);
btnStop.setEnabled(false);
btnPause.setEnabled(false);
btnLoud.setEnabled(true);
btnWisper.setEnabled(true);
btnFile.setEnabled(true);
btnRaw.setEnabled(true);
UIhandler = new Handler() {
@Override
public void handleMessage (Message message) {
int currtime = message.arg1;
Date date = new Date();
date.setTime(currtime);
tim.setText((new SimpleDateFormat("mm:ss")).format(date));
}
};
timthread = new Thread(){
@Override
public void run() {
int milli;
Message msg;
while (true) {
if (mplayer == null || !mplayer.isPlaying()) {
try {
sleep(Long.MAX_VALUE);
} catch (InterruptedException e) {
Log.i(TAG, e.toString());
}
}
milli = mplayer.getCurrentPosition();
timeBar.setProgress(milli);
msg = new Message();
msg.arg1 = milli;
UIhandler.sendMessage(msg);
try {
sleep(1000);
} catch (InterruptedException e) {
Log.i(TAG, e.toString());
}
}
}
};
timthread.start();
btnRaw.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
if (mplayer != null && mplayer.isPlaying())
stop(mplayer);
mplayer = MediaPlayer.create(MainActivity.this, R.raw.sample);
songname.setText("RAW file !");
timeBar.setMax(mplayer.getDuration());
btnPlay.setEnabled(true);
}
});
btnFile.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
Intent picker = new Intent(Intent.ACTION_GET_CONTENT);
picker.setType("audio/mpeg");
picker.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, false);
Intent chosenIntent = Intent.createChooser(picker, "Chose an audio file.");
startActivityForResult(chosenIntent, 0);
}
});
btnPlay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mplayer.isPlaying())
return;
play(mplayer);
}
});
btnStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!mplayer.isPlaying())
return;
stop(mplayer);
songname.setText("");
}
});
btnPause.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!mplayer.isPlaying())
return;
pause(mplayer);
}
});
btnLoud.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
audioManager.adjustVolume(AudioManager.ADJUST_RAISE, 5);
}
});
btnWisper.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
audioManager.adjustVolume(AudioManager.ADJUST_LOWER, 5);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode != 0 || resultCode != RESULT_OK)
return;
if (mplayer != null && mplayer.isPlaying())
stop(mplayer);
Log.i(TAG, "resultCode : " + resultCode);
Log.i(TAG, "URI : " + data.getData());
try {
mplayer = MediaPlayer.create(MainActivity.this, data.getData());
songname.setText( getRealPathFromURI(MainActivity.this, data.getData()) );
//songname.setText( (new File("" + data.getData())).getPath() );
timeBar.setMax(mplayer.getDuration());
btnPlay.setEnabled(true);
} catch (Exception e) {
Log.w(TAG, e.toString());
e.printStackTrace();
songname.setText("File Path Error !");
}
}
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
/**
*
* 執行播放動作 初始化界面
*
* @param player
*/
private void play (MediaPlayer player) {
player.start();
btnStop.setEnabled(true);
btnPause.setEnabled(true);
timthread.interrupt();
}
private void stop (MediaPlayer player) {
player.stop();
timthread.interrupt();
timeBar.setProgress(0);
Message msg = new Message();
msg.arg1 = 0;
UIhandler.sendMessage(msg);
btnPause.setEnabled(false);
btnStop.setEnabled(false);
btnPlay.setEnabled(false);
}
private void pause (MediaPlayer player) {
player.pause();
timthread.interrupt();
timeBar.setProgress(player.getCurrentPosition());
Message msg = new Message();
msg.arg1 = player.getCurrentPosition();
UIhandler.sendMessage(msg);
btnPause.setEnabled(false);
btnStop.setEnabled(false);
}
}
| UTF-8 | Java | 8,013 | java | MainActivity.java | Java | []
| null | []
| package lab.android.mymp3player;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
private final String TAG = this.getClass().getName();
Button btnPlay, btnStop, btnPause,
btnLoud, btnWisper, btnFile, btnRaw;
MediaPlayer mplayer;
Handler UIhandler;
ProgressBar timeBar;
TextView tim, songname;
Thread timthread;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final AudioManager audioManager = (AudioManager) this.getSystemService(AUDIO_SERVICE);
btnPlay = (Button) findViewById(R.id.play);
btnStop = (Button) findViewById(R.id.stop);
btnPause = (Button) findViewById(R.id.pause);
btnLoud = (Button) findViewById(R.id.loud);
btnWisper = (Button) findViewById(R.id.whispered);
btnFile = (Button) findViewById(R.id.file);
btnRaw = (Button) findViewById(R.id.raw);
timeBar = (ProgressBar) findViewById(R.id.TimeBar);
tim = (TextView) findViewById(R.id.timtxt);
songname = (TextView) findViewById(R.id.songname);
btnPlay.setEnabled(false);
btnStop.setEnabled(false);
btnPause.setEnabled(false);
btnLoud.setEnabled(true);
btnWisper.setEnabled(true);
btnFile.setEnabled(true);
btnRaw.setEnabled(true);
UIhandler = new Handler() {
@Override
public void handleMessage (Message message) {
int currtime = message.arg1;
Date date = new Date();
date.setTime(currtime);
tim.setText((new SimpleDateFormat("mm:ss")).format(date));
}
};
timthread = new Thread(){
@Override
public void run() {
int milli;
Message msg;
while (true) {
if (mplayer == null || !mplayer.isPlaying()) {
try {
sleep(Long.MAX_VALUE);
} catch (InterruptedException e) {
Log.i(TAG, e.toString());
}
}
milli = mplayer.getCurrentPosition();
timeBar.setProgress(milli);
msg = new Message();
msg.arg1 = milli;
UIhandler.sendMessage(msg);
try {
sleep(1000);
} catch (InterruptedException e) {
Log.i(TAG, e.toString());
}
}
}
};
timthread.start();
btnRaw.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
if (mplayer != null && mplayer.isPlaying())
stop(mplayer);
mplayer = MediaPlayer.create(MainActivity.this, R.raw.sample);
songname.setText("RAW file !");
timeBar.setMax(mplayer.getDuration());
btnPlay.setEnabled(true);
}
});
btnFile.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
Intent picker = new Intent(Intent.ACTION_GET_CONTENT);
picker.setType("audio/mpeg");
picker.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, false);
Intent chosenIntent = Intent.createChooser(picker, "Chose an audio file.");
startActivityForResult(chosenIntent, 0);
}
});
btnPlay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mplayer.isPlaying())
return;
play(mplayer);
}
});
btnStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!mplayer.isPlaying())
return;
stop(mplayer);
songname.setText("");
}
});
btnPause.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!mplayer.isPlaying())
return;
pause(mplayer);
}
});
btnLoud.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
audioManager.adjustVolume(AudioManager.ADJUST_RAISE, 5);
}
});
btnWisper.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
audioManager.adjustVolume(AudioManager.ADJUST_LOWER, 5);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode != 0 || resultCode != RESULT_OK)
return;
if (mplayer != null && mplayer.isPlaying())
stop(mplayer);
Log.i(TAG, "resultCode : " + resultCode);
Log.i(TAG, "URI : " + data.getData());
try {
mplayer = MediaPlayer.create(MainActivity.this, data.getData());
songname.setText( getRealPathFromURI(MainActivity.this, data.getData()) );
//songname.setText( (new File("" + data.getData())).getPath() );
timeBar.setMax(mplayer.getDuration());
btnPlay.setEnabled(true);
} catch (Exception e) {
Log.w(TAG, e.toString());
e.printStackTrace();
songname.setText("File Path Error !");
}
}
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
/**
*
* 執行播放動作 初始化界面
*
* @param player
*/
private void play (MediaPlayer player) {
player.start();
btnStop.setEnabled(true);
btnPause.setEnabled(true);
timthread.interrupt();
}
private void stop (MediaPlayer player) {
player.stop();
timthread.interrupt();
timeBar.setProgress(0);
Message msg = new Message();
msg.arg1 = 0;
UIhandler.sendMessage(msg);
btnPause.setEnabled(false);
btnStop.setEnabled(false);
btnPlay.setEnabled(false);
}
private void pause (MediaPlayer player) {
player.pause();
timthread.interrupt();
timeBar.setProgress(player.getCurrentPosition());
Message msg = new Message();
msg.arg1 = player.getCurrentPosition();
UIhandler.sendMessage(msg);
btnPause.setEnabled(false);
btnStop.setEnabled(false);
}
}
| 8,013 | 0.550645 | 0.548642 | 292 | 26.352739 | 23.004814 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.558219 | false | false | 0 |
d519436ec08684ccf541c6bf7f9f01cc648f7e04 | 4,200,478,045,922 | de1a3fc6bed04e3acbbc42801186cd54a60dc2c1 | /SAAJ-First-lab1/src/ForAttachment.java | 7ca000c4382cb60177b7647d559d2f24bdab7048 | []
| no_license | HemantKGupta/J2EE_WS | https://github.com/HemantKGupta/J2EE_WS | 70505875f9b2168655c3d5dd5d01700f11ad8ec7 | c7d245608dfc5fc571a94a8bc1748280a899dfd6 | refs/heads/master | 2020-05-21T12:06:21.580000 | 2014-03-30T14:24:46 | 2014-03-30T14:24:46 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.activation.DataHandler;
import javax.xml.namespace.QName;
import javax.xml.soap.AttachmentPart;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPBodyElement;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
public class ForAttachment {
ForAttachment() throws SOAPException, MalformedURLException, IOException
{
MessageFactory factory = MessageFactory.newInstance();
//1. Create soap message
SOAPMessage reqMsg = factory.createMessage();
//2. Create part
SOAPPart soapPart = reqMsg.getSOAPPart();
//3. Create envolove
SOAPEnvelope soapenv = soapPart.getEnvelope();
//4. Create body
SOAPBody soapbody = soapenv.getBody();
// 5. Add body element with qname and prefix
SOAPBodyElement ele=soapbody.addBodyElement(new QName ("","celsiusToFarenheit","q0"));
// Add a child to body element
SOAPElement ele2=ele.addChildElement(new QName ("","celsius","q0"));
ele2.addTextNode("56");
// AttachmentPart attach = reqMsg.createAttachmentPart();
// String stringAttach = "ZSRDXOIJ";
// attach.setContent(stringAttach , "text/plain");
// attach.setContentId("an update");
// reqMsg.addAttachmentPart(attach);
// reqMsg.writeTo(System.out);
URL url = new URL("http://localhost:8080/Simple/pic31882.jpg");
DataHandler dataHand = new DataHandler(url);
AttachmentPart attach2 = reqMsg.createAttachmentPart(dataHand);
attach2.setContentId("attch_image");
reqMsg.addAttachmentPart(attach2);
reqMsg.writeTo(System.out);
}
public static void main(String[] args) throws MalformedURLException, SOAPException, IOException {
ForAttachment m = new ForAttachment();
}
}
| UTF-8 | Java | 1,959 | java | ForAttachment.java | Java | []
| null | []
| import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.activation.DataHandler;
import javax.xml.namespace.QName;
import javax.xml.soap.AttachmentPart;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPBodyElement;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
public class ForAttachment {
ForAttachment() throws SOAPException, MalformedURLException, IOException
{
MessageFactory factory = MessageFactory.newInstance();
//1. Create soap message
SOAPMessage reqMsg = factory.createMessage();
//2. Create part
SOAPPart soapPart = reqMsg.getSOAPPart();
//3. Create envolove
SOAPEnvelope soapenv = soapPart.getEnvelope();
//4. Create body
SOAPBody soapbody = soapenv.getBody();
// 5. Add body element with qname and prefix
SOAPBodyElement ele=soapbody.addBodyElement(new QName ("","celsiusToFarenheit","q0"));
// Add a child to body element
SOAPElement ele2=ele.addChildElement(new QName ("","celsius","q0"));
ele2.addTextNode("56");
// AttachmentPart attach = reqMsg.createAttachmentPart();
// String stringAttach = "ZSRDXOIJ";
// attach.setContent(stringAttach , "text/plain");
// attach.setContentId("an update");
// reqMsg.addAttachmentPart(attach);
// reqMsg.writeTo(System.out);
URL url = new URL("http://localhost:8080/Simple/pic31882.jpg");
DataHandler dataHand = new DataHandler(url);
AttachmentPart attach2 = reqMsg.createAttachmentPart(dataHand);
attach2.setContentId("attch_image");
reqMsg.addAttachmentPart(attach2);
reqMsg.writeTo(System.out);
}
public static void main(String[] args) throws MalformedURLException, SOAPException, IOException {
ForAttachment m = new ForAttachment();
}
}
| 1,959 | 0.731496 | 0.719755 | 57 | 32.36842 | 22.570459 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.894737 | false | false | 0 |
7a6bfb419e09b78839789891863fcd08daf5c0d9 | 3,573,412,848,376 | 480bdf0f7b8f5ad089a9a4f6e18f700fffdb3596 | /src/main/java/org/logika/inference/SilogismoHipotetico.java | fe05e6a6d2182aa41aed92e8a2d5ad7fdf2a3207 | []
| no_license | hmvictor/logika | https://github.com/hmvictor/logika | 9b492d445d1d6737c5498e4720eaab30a1609355 | a2f329fd11c24235743ecb9740c23855cff5fafe | refs/heads/master | 2022-11-25T01:56:14.139000 | 2020-03-30T00:10:46 | 2020-03-30T00:10:46 | 209,922,937 | 0 | 0 | null | false | 2022-11-16T09:22:06 | 2019-09-21T04:11:08 | 2020-03-30T00:11:52 | 2022-11-16T09:22:02 | 68 | 0 | 0 | 2 | Java | false | false | package org.logika.inference;
import static org.logika.exp.BinaryOperator.MATERIAL_IMPLICATION;
import org.logika.exp.Expression;
import org.logika.exp.Sentence;
import org.logika.inference.Transformation.Matching;
/**
*
* @author Víctor
*/
public class SilogismoHipotetico implements InferenceRule {
@Override
public Expression apply(Expression... expressions) {
return Transformation.given(
new Matching(0, MATERIAL_IMPLICATION.pattern("a", "b")),
new Matching(1, MATERIAL_IMPLICATION.pattern("b", "c"))
).then((Transformation.TransformationContext context) -> {
return MATERIAL_IMPLICATION.of(context.getExpressionMap().get("a"), context.getExpressionMap().get("c"));
}).apply(expressions);
}
public static void main(String[] args) {
Expression exp = new SilogismoHipotetico().apply(
MATERIAL_IMPLICATION.of(new Sentence('A'), new Sentence('B')),
MATERIAL_IMPLICATION.of(new Sentence('B'), new Sentence('C')));
System.out.println(exp);
}
}
| UTF-8 | Java | 1,115 | java | SilogismoHipotetico.java | Java | [
{
"context": "ce.Transformation.Matching;\r\n\r\n/**\r\n *\r\n * @author Víctor\r\n */\r\npublic class SilogismoHipotetico implements",
"end": 250,
"score": 0.9998161196708679,
"start": 244,
"tag": "NAME",
"value": "Víctor"
}
]
| null | []
| package org.logika.inference;
import static org.logika.exp.BinaryOperator.MATERIAL_IMPLICATION;
import org.logika.exp.Expression;
import org.logika.exp.Sentence;
import org.logika.inference.Transformation.Matching;
/**
*
* @author Víctor
*/
public class SilogismoHipotetico implements InferenceRule {
@Override
public Expression apply(Expression... expressions) {
return Transformation.given(
new Matching(0, MATERIAL_IMPLICATION.pattern("a", "b")),
new Matching(1, MATERIAL_IMPLICATION.pattern("b", "c"))
).then((Transformation.TransformationContext context) -> {
return MATERIAL_IMPLICATION.of(context.getExpressionMap().get("a"), context.getExpressionMap().get("c"));
}).apply(expressions);
}
public static void main(String[] args) {
Expression exp = new SilogismoHipotetico().apply(
MATERIAL_IMPLICATION.of(new Sentence('A'), new Sentence('B')),
MATERIAL_IMPLICATION.of(new Sentence('B'), new Sentence('C')));
System.out.println(exp);
}
}
| 1,115 | 0.64991 | 0.648115 | 31 | 33.935482 | 30.676182 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.580645 | false | false | 0 |
312687dbc070a48f9eb2d0f9cdcd56554224ef20 | 12,369,505,859,993 | 69ada6133d99c6873af47eba81a864d4faff8908 | /app/src/main/java/jemboy/nodejscommunication/Main/MainActivity.java | 4365becd35cf065e88bcab587c3190ad48df0d7d | [
"MIT"
]
| permissive | jemboy/app-bakery | https://github.com/jemboy/app-bakery | 4b23385335ac5b59e249bf0c3c94dabade5c553f | ce255e8f90ba1954a6091397e9b2ec59ef3d5a14 | refs/heads/master | 2016-07-28T06:34:11.238000 | 2016-01-09T17:52:36 | 2016-01-09T17:52:36 | 42,640,955 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package jemboy.nodejscommunication.Main;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.app.Activity;
import org.json.JSONArray;
import org.json.JSONObject;
import jemboy.nodejscommunication.Network.DownloadAppTask;
import jemboy.nodejscommunication.Network.DownloadBitmapTask;
import jemboy.nodejscommunication.R;
import jemboy.nodejscommunication.Utility.Constants;
import jemboy.nodejscommunication.Utility.NetworkChecker;
public class MainActivity extends Activity implements OnTaskCompleted {
ImageView[] imageViews;
Button downloadButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new DownloadAppTask(MainActivity.this, Constants.SERVER).execute();
imageViews = new ImageView[]{
(ImageView)findViewById(R.id.topleft),
(ImageView)findViewById(R.id.topcenter),
(ImageView)findViewById(R.id.topright),
(ImageView)findViewById(R.id.bottomleft),
(ImageView)findViewById(R.id.bottomcenter),
(ImageView)findViewById(R.id.bottomright)
};
downloadButton = (Button)findViewById(R.id.button);
downloadButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (NetworkChecker.isNetworkAvailable(getApplicationContext()))
new DownloadAppTask(MainActivity.this, Constants.SERVER).execute();
else
downloadButton.setError("Connection to the server could not be established!");
}
});
}
public void onDownloadAppCompleted(String response) {
if (response != null) {
try {
Log.d("Response:", response);
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
ImageView imageView = imageViews[i];
JSONObject jsonObject = jsonArray.getJSONObject(i);
String link = jsonObject.getString("link");
String thumbnail = jsonObject.getString("thumbnail");
imageView.setOnClickListener(new LovelyListener(MainActivity.this, link));
new DownloadBitmapTask(getApplicationContext(), imageView).execute(thumbnail);
}
} catch (Exception e) {
e.printStackTrace();
}
}
else {
downloadButton.setError("Oops.. something went wrong!", null);
}
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void onStop() {
super.onStop();
}
@Override
public void onDestroy() {
super.onDestroy();
}
} | UTF-8 | Java | 3,004 | java | MainActivity.java | Java | []
| null | []
| package jemboy.nodejscommunication.Main;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.app.Activity;
import org.json.JSONArray;
import org.json.JSONObject;
import jemboy.nodejscommunication.Network.DownloadAppTask;
import jemboy.nodejscommunication.Network.DownloadBitmapTask;
import jemboy.nodejscommunication.R;
import jemboy.nodejscommunication.Utility.Constants;
import jemboy.nodejscommunication.Utility.NetworkChecker;
public class MainActivity extends Activity implements OnTaskCompleted {
ImageView[] imageViews;
Button downloadButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new DownloadAppTask(MainActivity.this, Constants.SERVER).execute();
imageViews = new ImageView[]{
(ImageView)findViewById(R.id.topleft),
(ImageView)findViewById(R.id.topcenter),
(ImageView)findViewById(R.id.topright),
(ImageView)findViewById(R.id.bottomleft),
(ImageView)findViewById(R.id.bottomcenter),
(ImageView)findViewById(R.id.bottomright)
};
downloadButton = (Button)findViewById(R.id.button);
downloadButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (NetworkChecker.isNetworkAvailable(getApplicationContext()))
new DownloadAppTask(MainActivity.this, Constants.SERVER).execute();
else
downloadButton.setError("Connection to the server could not be established!");
}
});
}
public void onDownloadAppCompleted(String response) {
if (response != null) {
try {
Log.d("Response:", response);
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
ImageView imageView = imageViews[i];
JSONObject jsonObject = jsonArray.getJSONObject(i);
String link = jsonObject.getString("link");
String thumbnail = jsonObject.getString("thumbnail");
imageView.setOnClickListener(new LovelyListener(MainActivity.this, link));
new DownloadBitmapTask(getApplicationContext(), imageView).execute(thumbnail);
}
} catch (Exception e) {
e.printStackTrace();
}
}
else {
downloadButton.setError("Oops.. something went wrong!", null);
}
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void onStop() {
super.onStop();
}
@Override
public void onDestroy() {
super.onDestroy();
}
} | 3,004 | 0.627497 | 0.627164 | 85 | 34.35294 | 26.518232 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.588235 | false | false | 0 |
15b1ac4c6de36c5dcb5fd5bbc11869da16a27e8a | 17,703,855,194,900 | b7b63ac05d77e6204f205865291f4c117a2e5b64 | /src/main/java/it/polimi/ingsw/PSP29/Controller/Turn/HestiaTurn.java | bcac132d8dbe8285b2eb1c86b95393606ac9901c | []
| no_license | CarloManco/ing-sw-2019-Grassi-Manco-Martiri | https://github.com/CarloManco/ing-sw-2019-Grassi-Manco-Martiri | f7687a70fd30e13d7b72cb207a00c81b89ee672c | a9390799fed2ee04a804dcc2eddd902ec16c89bf | refs/heads/master | 2023-01-19T23:46:06.200000 | 2020-07-03T15:42:36 | 2020-07-03T15:42:36 | 245,206,103 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package it.polimi.ingsw.PSP29.Controller.Turn;
import it.polimi.ingsw.PSP29.model.*;
import it.polimi.ingsw.PSP29.virtualView.ClientHandler;
import it.polimi.ingsw.PSP29.virtualView.Server;
import java.util.ArrayList;
/**
* @author Letizia Grassi, Luca Martiri
*/
public class HestiaTurn extends GodTurn{
public HestiaTurn(Turn turn) { super(turn);}
/**
* allows w to build two times but the second building can't be a border box
* @param m match played
* @param ch clientHandler that must build
* @param server manage the interaction with client
* @return true if w has built at least once
*/
@Override
public boolean build(Match m, ClientHandler ch, Server server) {
Player p = m.getPlayer(ch.getName());
int wID=2;
boolean nopower = super.build(m,ch,server);
if(!nopower)
return false;
if(p.getWorker(0).getMoved()) wID = 0;
if(p.getWorker(1).getMoved()) wID = 1;
ArrayList<Coordinate> coordinates = whereCanBuild(m, ch, wID, 2);
if(coordinates.size()!=0) {
server.write(ch, "serviceMessage", "BORD-" + m.printBoard());
server.write(ch, "serviceMessage", "MSGE-You can use Hestia power\n");
server.write(ch, "serviceMessage", "LIST-1) YES\n2) NO\n");
server.write(ch, "interactionServer", "INDX-Would you like to build again but not in a border box? ");
String answer = server.read(ch);
if(answer == null){
for(ClientHandler chl : server.getClientHandlers()){
server.write(chl, "serviceMessage", "WINM-Player disconnected\n");
}
ch.resetConnected();
ch.closeConnection();
return false;
}else{
while(!answer.equals("1") && !answer.equals("2")){
server.write(ch, "serviceMessage", "MSGE-Invalid input\n");
server.write(ch, "serviceMessage", "LIST-1) YES\n2) NO\n");
server.write(ch, "interactionServer", "INDX-Would you like to build again but not in a border box? ");
answer = server.read(ch);
if(answer == null){
for(ClientHandler chl : server.getClientHandlers()){
server.write(chl, "serviceMessage", "WINM-Player disconnected\n");
}
ch.resetConnected();
ch.closeConnection();
return false;
}
}
}
if (answer.equals("1")) {
Coordinate c1 = null;
server.write(ch, "serviceMessage", "MSGE-Hestia's power activated \n");
server.write(ch, "serviceMessage", "LIST-" + printCoordinates(coordinates));
server.write(ch, "interactionServer", "TURN-Where you want to build?\n");
int id;
while (true) {
try{
String msg = server.read(ch);
if (msg == null) {
for(ClientHandler chl : server.getClientHandlers()){
server.write(chl, "serviceMessage", "WINM-Player disconnected\n");
}
ch.resetConnected();
ch.closeConnection();
return false;
} else {
id = Integer.parseInt(msg);
}
if (id < 0 || id >= coordinates.size()) {
server.write(ch, "serviceMessage", "MSGE-Invalid input\n");
server.write(ch, "interactionServer", "TURN-Try another index: ");
continue;
}
break;
}catch (NumberFormatException e){
server.write(ch, "serviceMessage", "MSGE-Invalid input\n");
server.write(ch, "interactionServer", "TURN-Try another index: ");
}
}
c1 = coordinates.get(id);
m.updateBuilding(c1);
return true;
}
}
return nopower;
}
/**
* create and arrayList of box where the player can build
* @param match game played
* @param ch client handler that must build
* @param id id of the worker chosen
* @param n number of times that player can build
* @return arrayList of box
*/
public ArrayList<Coordinate> whereCanBuild(Match match, ClientHandler ch, int id, int n) {
ArrayList<Coordinate> coordinates = new ArrayList<>();
Player player = match.getPlayer(ch.getName());
for (int i = 0; i < match.getRows(); i++) {
for (int j = 0; j < match.getColumns(); j++) {
Coordinate c = new Coordinate(i, j);
if (canBuildIn(match, player.getWorker(id), c, n)) {
coordinates.add(new Coordinate(i, j));
}
}
}
return coordinates;
}
/**
*
* @param match game played
* @param w worker of the player
* @param c coordinate where worker should build
* @param n number of times that player can build
* @return true if the worker can build in c
*/
public boolean canBuildIn(Match match,Worker w,Coordinate c, int n){
if(n==1){
return super.canBuildIn(match, w, c);
}
else {
if(!w.getPosition().isNear(c) || match.getBoard()[c.getX()][c.getY()].getLevel()==4 || !match.getBoard()[c.getX()][c.getY()].isEmpty() || c.getY()==match.getColumns()-1 || c.getY()==0 || c.getX()==match.getRows()-1 || c.getX()==0){
return false;
}
else{
return true;
}
}
}
}
| UTF-8 | Java | 6,043 | java | HestiaTurn.java | Java | [
{
"context": "rver;\n\nimport java.util.ArrayList;\n\n/**\n * @author Letizia Grassi, Luca Martiri\n */\npublic class HestiaTurn extends",
"end": 250,
"score": 0.9998560547828674,
"start": 236,
"tag": "NAME",
"value": "Letizia Grassi"
},
{
"context": "va.util.ArrayList;\n\n/**\n * @author Letizia Grassi, Luca Martiri\n */\npublic class HestiaTurn extends GodTurn{\n\n ",
"end": 264,
"score": 0.9998372793197632,
"start": 252,
"tag": "NAME",
"value": "Luca Martiri"
}
]
| null | []
| package it.polimi.ingsw.PSP29.Controller.Turn;
import it.polimi.ingsw.PSP29.model.*;
import it.polimi.ingsw.PSP29.virtualView.ClientHandler;
import it.polimi.ingsw.PSP29.virtualView.Server;
import java.util.ArrayList;
/**
* @author <NAME>, <NAME>
*/
public class HestiaTurn extends GodTurn{
public HestiaTurn(Turn turn) { super(turn);}
/**
* allows w to build two times but the second building can't be a border box
* @param m match played
* @param ch clientHandler that must build
* @param server manage the interaction with client
* @return true if w has built at least once
*/
@Override
public boolean build(Match m, ClientHandler ch, Server server) {
Player p = m.getPlayer(ch.getName());
int wID=2;
boolean nopower = super.build(m,ch,server);
if(!nopower)
return false;
if(p.getWorker(0).getMoved()) wID = 0;
if(p.getWorker(1).getMoved()) wID = 1;
ArrayList<Coordinate> coordinates = whereCanBuild(m, ch, wID, 2);
if(coordinates.size()!=0) {
server.write(ch, "serviceMessage", "BORD-" + m.printBoard());
server.write(ch, "serviceMessage", "MSGE-You can use Hestia power\n");
server.write(ch, "serviceMessage", "LIST-1) YES\n2) NO\n");
server.write(ch, "interactionServer", "INDX-Would you like to build again but not in a border box? ");
String answer = server.read(ch);
if(answer == null){
for(ClientHandler chl : server.getClientHandlers()){
server.write(chl, "serviceMessage", "WINM-Player disconnected\n");
}
ch.resetConnected();
ch.closeConnection();
return false;
}else{
while(!answer.equals("1") && !answer.equals("2")){
server.write(ch, "serviceMessage", "MSGE-Invalid input\n");
server.write(ch, "serviceMessage", "LIST-1) YES\n2) NO\n");
server.write(ch, "interactionServer", "INDX-Would you like to build again but not in a border box? ");
answer = server.read(ch);
if(answer == null){
for(ClientHandler chl : server.getClientHandlers()){
server.write(chl, "serviceMessage", "WINM-Player disconnected\n");
}
ch.resetConnected();
ch.closeConnection();
return false;
}
}
}
if (answer.equals("1")) {
Coordinate c1 = null;
server.write(ch, "serviceMessage", "MSGE-Hestia's power activated \n");
server.write(ch, "serviceMessage", "LIST-" + printCoordinates(coordinates));
server.write(ch, "interactionServer", "TURN-Where you want to build?\n");
int id;
while (true) {
try{
String msg = server.read(ch);
if (msg == null) {
for(ClientHandler chl : server.getClientHandlers()){
server.write(chl, "serviceMessage", "WINM-Player disconnected\n");
}
ch.resetConnected();
ch.closeConnection();
return false;
} else {
id = Integer.parseInt(msg);
}
if (id < 0 || id >= coordinates.size()) {
server.write(ch, "serviceMessage", "MSGE-Invalid input\n");
server.write(ch, "interactionServer", "TURN-Try another index: ");
continue;
}
break;
}catch (NumberFormatException e){
server.write(ch, "serviceMessage", "MSGE-Invalid input\n");
server.write(ch, "interactionServer", "TURN-Try another index: ");
}
}
c1 = coordinates.get(id);
m.updateBuilding(c1);
return true;
}
}
return nopower;
}
/**
* create and arrayList of box where the player can build
* @param match game played
* @param ch client handler that must build
* @param id id of the worker chosen
* @param n number of times that player can build
* @return arrayList of box
*/
public ArrayList<Coordinate> whereCanBuild(Match match, ClientHandler ch, int id, int n) {
ArrayList<Coordinate> coordinates = new ArrayList<>();
Player player = match.getPlayer(ch.getName());
for (int i = 0; i < match.getRows(); i++) {
for (int j = 0; j < match.getColumns(); j++) {
Coordinate c = new Coordinate(i, j);
if (canBuildIn(match, player.getWorker(id), c, n)) {
coordinates.add(new Coordinate(i, j));
}
}
}
return coordinates;
}
/**
*
* @param match game played
* @param w worker of the player
* @param c coordinate where worker should build
* @param n number of times that player can build
* @return true if the worker can build in c
*/
public boolean canBuildIn(Match match,Worker w,Coordinate c, int n){
if(n==1){
return super.canBuildIn(match, w, c);
}
else {
if(!w.getPosition().isNear(c) || match.getBoard()[c.getX()][c.getY()].getLevel()==4 || !match.getBoard()[c.getX()][c.getY()].isEmpty() || c.getY()==match.getColumns()-1 || c.getY()==0 || c.getX()==match.getRows()-1 || c.getX()==0){
return false;
}
else{
return true;
}
}
}
}
| 6,029 | 0.506702 | 0.501076 | 145 | 40.675861 | 32.244514 | 243 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.910345 | false | false | 0 |
7376835b694f2b7a7dacbb93cca635400fcf83b0 | 2,662,879,766,634 | 4b5ef8a3a3a6deaf8c60dfd4a6dc18ef65e198c6 | /G8_GoNature/G8_GoNautre/src/gui/VisitsReportController.java | 1964e852d84c30ed544189446a72edecebd91574 | []
| no_license | AlonIvshin/GoNature | https://github.com/AlonIvshin/GoNature | 512868bce1e0a82588a6d690de3f0de4c3e79596 | eab96e7d561279229abb8723d6cffef4fc6bedf3 | refs/heads/main | 2023-07-03T01:31:43.947000 | 2021-08-03T18:34:14 | 2021-08-03T18:34:14 | 392,416,624 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package gui;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.time.YearMonth;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.ResourceBundle;
import javax.imageio.ImageIO;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import com.jfoenix.controls.JFXComboBox;
import Controllers.ReportsControl;
import alerts.CustomAlerts;
import client.ChatClient;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.SnapshotParameters;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.chart.XYChart.Data;
import javafx.scene.chart.XYChart.Series;
import javafx.scene.control.Label;
import javafx.scene.control.Tooltip;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.image.WritableImage;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import javafx.util.Duration;
import logic.GoNatureFinals;
import logic.VisitReport;
/**
* Gets month that picked from previous page.
* Loads all visitors stay time and entrance time into a line chart.
*/
public class VisitsReportController implements Initializable {
@FXML
private AnchorPane rootPane;
@FXML
private Label headerLabel;
@FXML
private LineChart<Number, Number> stayTime_chart;
@FXML
private NumberAxis stayX2;
@FXML
private NumberAxis stayY;
@FXML
public LineChart<Number, Number> entranceTime_chart;
@FXML
private NumberAxis enterX2;
@FXML
private NumberAxis enterY;
@FXML
private Label lblMonth;
@FXML
private JFXComboBox<String> comboBox;
@FXML
private JFXComboBox<String> dataComboBox;
private int monthNumber; // the month number
private XYChart.Series<Number, Number> series3; // Refactor
private XYChart.Series<Number, Number> series2; // Refactor
private XYChart.Series<Number, Number> series1; // Refactor
private XYChart.Series<Number, Number> series4; // Refactor
private XYChart.Series<Number, Number> series5; // Refactor
private XYChart.Series<Number, Number> series6; // Refactor
@Override
public void initialize(URL location, ResourceBundle resources) {
init();
}
private void init() {
lblMonth.setText(GoNatureFinals.MONTHS[monthNumber]); // set the name of the month
initGraphs();
Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(0.3), new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
initComboBox();
entranceTime_chart.getData().clear();
stayTime_chart.getData().clear();
loadEntranceSolosData(comboBox.getSelectionModel().getSelectedItem());
loadEntranceSubscribersData(comboBox.getSelectionModel().getSelectedItem());
loadEntranceGroupData(comboBox.getSelectionModel().getSelectedItem());
loadStayTimeSolosData(comboBox.getSelectionModel().getSelectedItem());
loadStayTimeSubscribersData(comboBox.getSelectionModel().getSelectedItem());
loadStayTimeGroupData(comboBox.getSelectionModel().getSelectedItem());
entranceTime_chart.getData().add(series1);
entranceTime_chart.getData().add(series3);
entranceTime_chart.getData().add(series5);
stayTime_chart.getData().add(series2);
stayTime_chart.getData().add(series4);
stayTime_chart.getData().add(series6);
setToolTip();
}
}));
timeline.setCycleCount(1);
timeline.play();
}
/**
* Setter for class variable monthNumber
*
* @param month The current month
*/
public void setMonthNumber(int month) {
this.monthNumber = month;
}
@SuppressWarnings("unused")
private void loadEntranceGroupData(String option) {
ArrayList<VisitReport> rep3 = new ArrayList<VisitReport>();
if (!option.equals("Show whole month"))
rep3 = ReportsControl.reportsManager.countGroupsEnterTimeWithDays(monthNumber, option);
else
rep3 = ReportsControl.reportsManager.countGroupsEnterTime(monthNumber);
// rep3 = (ArrayList<VisitReport>) ChatClient.responseFromServer.getResultSet(); // Refactor
series5 = new Series<Number, Number>();
double hour, min, time;
int maxNumOfVisitors = 0, sum;
for (int i = 0; i < rep3.size(); i++) {
sum = rep3.get(i).getSum();
if (maxNumOfVisitors < sum) {
maxNumOfVisitors = sum;
}
hour = Double.parseDouble(rep3.get(i).getData().substring(0, 2));
min = Double.parseDouble(rep3.get(i).getData().substring(3, 5)) / 60;
time = hour + min;
series5.getData().add(new Data<Number, Number>(time, sum));
}
series5.setName("Groups");
maxNumOfVisitors++;
if (maxNumOfVisitors % 2 != 0)
maxNumOfVisitors++;
}
@SuppressWarnings("unchecked")
private void loadStayTimeGroupData(String option) {
ArrayList<VisitReport> rep3 = new ArrayList<VisitReport>();
double hour, min, time;
int maxNumOfVisitors = 0, sum;
rep3 = new ArrayList<VisitReport>();
if (!option.equals("Show whole month"))
ReportsControl.countGroupsVisitTimeWithDay(monthNumber, option);
else
ReportsControl.countGroupsVisitTime(monthNumber);
rep3 = (ArrayList<VisitReport>) ChatClient.responseFromServer.getResultSet();
double totalNumOfVisitors = 0;
/* Sum total visitors at this date */
for (int i = 0; i < rep3.size(); i++)
totalNumOfVisitors += rep3.get(i).getSum();
series6 = new Series<Number, Number>();
hour = 0;
min = 0;
time = 0;
maxNumOfVisitors = 0;
sum = 0;
for (int i = 0; i < rep3.size(); i++) {
sum = rep3.get(i).getSum();
if (maxNumOfVisitors < sum) {
maxNumOfVisitors = sum;
}
hour = Double.parseDouble(rep3.get(i).getData().substring(0, 2));
min = Double.parseDouble(rep3.get(i).getData().substring(3, 5)) / 60;
time = hour + min;
series6.getData().add(new Data<Number, Number>(time, sum / totalNumOfVisitors * 100));
}
series6.setName("Groups");
}
private void loadEntranceSubscribersData(String option) {
ArrayList<VisitReport> rep2 = new ArrayList<VisitReport>();
if (!option.equals("Show whole month"))
rep2 = ReportsControl.reportsManager.countSubsEnterTimeWithDays(monthNumber, option);
else
rep2 = ReportsControl.reportsManager.countSubsEnterTime(monthNumber);
// rep2 = (ArrayList<VisitReport>) ChatClient.responseFromServer.getResultSet(); // Refactor
series3 = new Series<Number, Number>();
double hour, min, time;
int maxNumOfVisitors = 0, sum;
for (int i = 0; i < rep2.size(); i++) {
sum = rep2.get(i).getSum();
if (maxNumOfVisitors < sum) {
maxNumOfVisitors = sum;
}
hour = Double.parseDouble(rep2.get(i).getData().substring(0, 2));
min = Double.parseDouble(rep2.get(i).getData().substring(3, 5)) / 60;
time = hour + min;
series3.getData().add(new Data<Number, Number>(time, sum));
}
series3.setName("Subscribers");
}
@SuppressWarnings("unchecked")
private void loadStayTimeSubscribersData(String option) {
ArrayList<VisitReport> rep2 = new ArrayList<VisitReport>();
double hour, min, time;
int maxNumOfVisitors = 0, sum;
rep2 = new ArrayList<VisitReport>();
if (!option.equals("Show whole month"))
ReportsControl.countSubsVisitTimeWithDay(monthNumber, option);
else
ReportsControl.countSubsVisitTime(monthNumber);
rep2 = (ArrayList<VisitReport>) ChatClient.responseFromServer.getResultSet();
double totalNumOfVisitors = 0;
/* Sum total visitors at this date */
for (int i = 0; i < rep2.size(); i++)
totalNumOfVisitors += rep2.get(i).getSum();
series4 = new Series<Number, Number>();
hour = 0;
min = 0;
time = 0;
maxNumOfVisitors = 0;
sum = 0;
for (int i = 0; i < rep2.size(); i++) {
sum = rep2.get(i).getSum();
if (maxNumOfVisitors < sum) {
maxNumOfVisitors = sum;
}
hour = Double.parseDouble(rep2.get(i).getData().substring(0, 2));
min = Double.parseDouble(rep2.get(i).getData().substring(3, 5)) / 60;
time = hour + min;
series4.getData().add(new Data<Number, Number>(time, sum / totalNumOfVisitors * 100));
}
series4.setName("Subscribers");
}
private void loadEntranceSolosData(String option) {
ArrayList<VisitReport> rep = new ArrayList<VisitReport>();
if (!option.equals("Show whole month"))
rep = ReportsControl.reportsManager.countSolosEnterTimeWithDays(monthNumber, option);
else
rep = ReportsControl.reportsManager.countSolosEnterTime(monthNumber);
// rep = (ArrayList<VisitReport>) ChatClient.responseFromServer.getResultSet(); // Refactor
series1 = new Series<Number, Number>();
double hour, min, time;
int maxNumOfVisitors = 0, sum;
for (int i = 0; i < rep.size(); i++) {
sum = rep.get(i).getSum();
if (maxNumOfVisitors < sum) {
maxNumOfVisitors = sum;
}
hour = Double.parseDouble(rep.get(i).getData().substring(0, 2));
min = Double.parseDouble(rep.get(i).getData().substring(3, 5)) / 60;
time = hour + min;
series1.getData().add(new Data<Number, Number>(time, sum));
}
series1.setName("Solos ");
}
@SuppressWarnings("unchecked")
private void loadStayTimeSolosData(String option) {
ArrayList<VisitReport> rep = new ArrayList<VisitReport>();
double hour, min, time;
int maxNumOfVisitors = 0, sum;
if (!option.equals("Show whole month"))
ReportsControl.countSolosVisitTimeWithDay(monthNumber, option);
else
ReportsControl.countSolosVisitTime(monthNumber);
rep = new ArrayList<VisitReport>();
rep = (ArrayList<VisitReport>) ChatClient.responseFromServer.getResultSet();
double totalNumOfVisitors = 0;
/* Sum total visitors at this date */
for (int i = 0; i < rep.size(); i++)
totalNumOfVisitors += rep.get(i).getSum();
series2 = new Series<Number, Number>();
hour = 0;
min = 0;
time = 0;
maxNumOfVisitors = 0;
sum = 0;
for (int i = 0; i < rep.size(); i++) {
sum = rep.get(i).getSum();
if (maxNumOfVisitors < sum) {
maxNumOfVisitors = sum;
}
hour = Double.parseDouble(rep.get(i).getData().substring(0, 2));
min = Double.parseDouble(rep.get(i).getData().substring(3, 5)) / 60;
time = hour + min;
series2.getData().add(new Data<Number, Number>(time, sum / totalNumOfVisitors * 100));
}
series2.setName("Solos ");
}
private void initGraphs() {
enterX2.setAutoRanging(false);
enterX2.setLowerBound(7.5);
enterX2.setUpperBound(19);
enterX2.setMinorTickVisible(false);
enterX2.setTickUnit(0.5);
enterY.setAutoRanging(true);
enterY.setLowerBound(0);
enterY.setMinorTickVisible(false);
stayX2.setAutoRanging(false);
stayX2.setLowerBound(0.0);
stayX2.setUpperBound(10.0);
stayX2.setMinorTickVisible(false);
stayX2.setTickUnit(0.5);
stayY.setAutoRanging(true);
stayY.setLowerBound(0);
stayY.setTickUnit(1);
stayY.setMinorTickVisible(false);
}
private void setToolTip() {
for (XYChart.Series<Number, Number> s : stayTime_chart.getData()) {
for (XYChart.Data<Number, Number> d : s.getData()) {
Tooltip.install(d.getNode(), new Tooltip(d.getYValue() + "%"));
d.getNode().setOnMouseEntered(event -> d.getNode().getStyleClass().add("onHover"));
d.getNode().setOnMouseExited(event -> d.getNode().getStyleClass().remove("onHover"));
}
}
for (XYChart.Series<Number, Number> s : entranceTime_chart.getData()) {
for (XYChart.Data<Number, Number> d : s.getData()) {
Tooltip.install(d.getNode(), new Tooltip(d.getYValue() + " Visitors"));
d.getNode().setOnMouseEntered(event -> d.getNode().getStyleClass().add("onHover"));
d.getNode().setOnMouseExited(event -> d.getNode().getStyleClass().remove("onHover"));
}
}
}
private void initComboBox() {
int days = findNumOfDays();
ObservableList<String> month_days = FXCollections.observableArrayList();
month_days.add("Show whole month");
for (int i = 1; i <= days; i++) {
month_days.add(String.valueOf(i));
}
comboBox.getItems().addAll(month_days);
comboBox.getSelectionModel().select(0);
comboBox.valueProperty().addListener((obs, oldItem, newItem) -> {
if (newItem == null) {
} else {
if (dataComboBox.getSelectionModel().getSelectedItem().equals("Show All")) {
entranceTime_chart.getData().clear();
stayTime_chart.getData().clear();
loadEntranceSolosData(comboBox.getSelectionModel().getSelectedItem());
loadEntranceSubscribersData(comboBox.getSelectionModel().getSelectedItem());
loadEntranceGroupData(comboBox.getSelectionModel().getSelectedItem());
loadStayTimeSolosData(comboBox.getSelectionModel().getSelectedItem());
loadStayTimeSubscribersData(comboBox.getSelectionModel().getSelectedItem());
loadStayTimeGroupData(comboBox.getSelectionModel().getSelectedItem());
entranceTime_chart.getData().add(series1);
entranceTime_chart.getData().add(series3);
entranceTime_chart.getData().add(series5);
stayTime_chart.getData().add(series2);
stayTime_chart.getData().add(series4);
stayTime_chart.getData().add(series6);
setToolTip();
} else if (dataComboBox.getSelectionModel().getSelectedItem().equals("Solo Visits")) {
entranceTime_chart.getData().clear();
stayTime_chart.getData().clear();
loadEntranceSolosData(comboBox.getSelectionModel().getSelectedItem());
loadStayTimeSolosData(comboBox.getSelectionModel().getSelectedItem());
entranceTime_chart.getData().add(series1);
stayTime_chart.getData().add(series2);
setToolTip();
} else if (dataComboBox.getSelectionModel().getSelectedItem().equals("Subscribers Visits")) {
entranceTime_chart.getData().clear();
stayTime_chart.getData().clear();
loadEntranceSubscribersData(comboBox.getSelectionModel().getSelectedItem());
loadStayTimeSubscribersData(comboBox.getSelectionModel().getSelectedItem());
entranceTime_chart.getData().add(series3);
stayTime_chart.getData().add(series4);
setToolTip();
} else if (dataComboBox.getSelectionModel().getSelectedItem().equals("Group Visits")) {
entranceTime_chart.getData().clear();
stayTime_chart.getData().clear();
loadEntranceGroupData(comboBox.getSelectionModel().getSelectedItem());
loadStayTimeGroupData(comboBox.getSelectionModel().getSelectedItem());
entranceTime_chart.getData().add(series5);
stayTime_chart.getData().add(series6);
setToolTip();
}
}
});
dataComboBox.getItems().addAll("Show All", "Solo Visits", "Subscribers Visits", "Group Visits");
dataComboBox.getSelectionModel().select(0);
dataComboBox.valueProperty().addListener((obs, oldItem, newItem) -> {
if (newItem == null) {
} else {
if (newItem.equals("Show All")) {
entranceTime_chart.getData().clear();
stayTime_chart.getData().clear();
loadEntranceSolosData(comboBox.getSelectionModel().getSelectedItem());
loadEntranceSubscribersData(comboBox.getSelectionModel().getSelectedItem());
loadEntranceGroupData(comboBox.getSelectionModel().getSelectedItem());
loadStayTimeSolosData(comboBox.getSelectionModel().getSelectedItem());
loadStayTimeSubscribersData(comboBox.getSelectionModel().getSelectedItem());
loadStayTimeGroupData(comboBox.getSelectionModel().getSelectedItem());
entranceTime_chart.getData().add(series1);
entranceTime_chart.getData().add(series3);
entranceTime_chart.getData().add(series5);
stayTime_chart.getData().add(series2);
stayTime_chart.getData().add(series4);
stayTime_chart.getData().add(series6);
setToolTip();
} else if (newItem.equals("Solo Visits")) {
entranceTime_chart.getData().clear();
stayTime_chart.getData().clear();
loadEntranceSolosData(comboBox.getSelectionModel().getSelectedItem());
loadStayTimeSolosData(comboBox.getSelectionModel().getSelectedItem());
entranceTime_chart.getData().add(series1);
stayTime_chart.getData().add(series2);
setToolTip();
} else if (newItem.equals("Subscribers Visits")) {
entranceTime_chart.getData().clear();
stayTime_chart.getData().clear();
loadEntranceSubscribersData(comboBox.getSelectionModel().getSelectedItem());
loadStayTimeSubscribersData(comboBox.getSelectionModel().getSelectedItem());
entranceTime_chart.getData().add(series3);
stayTime_chart.getData().add(series4);
setToolTip();
} else if (newItem.equals("Group Visits")) {
entranceTime_chart.getData().clear();
stayTime_chart.getData().clear();
loadEntranceGroupData(comboBox.getSelectionModel().getSelectedItem());
loadStayTimeGroupData(comboBox.getSelectionModel().getSelectedItem());
entranceTime_chart.getData().add(series5);
stayTime_chart.getData().add(series6);
setToolTip();
}
}
});
}
@FXML
private void saveReportAsPdf() {
File directory = new File(System.getProperty("user.home") + "/Desktop/reports/");
if (!directory.exists()) {
directory.mkdir();
}
WritableImage nodeshot = rootPane.snapshot(new SnapshotParameters(), null);
String fileName = "Visits Report - month number " + monthNumber + ".pdf";
File file = new File("test.png");
try {
ImageIO.write(SwingFXUtils.fromFXImage(nodeshot, null), "png", file);
} catch (IOException e) {
e.printStackTrace();
}
PDDocument doc = new PDDocument();
PDPage page = new PDPage();
PDImageXObject pdimage;
PDPageContentStream content;
try {
pdimage = PDImageXObject.createFromFile("test.png", doc);
content = new PDPageContentStream(doc, page);
content.drawImage(pdimage, 50, 100, 500, 600);
content.close();
doc.addPage(page);
doc.save(System.getProperty("user.home") + "/Desktop/reports/" + fileName);
doc.close();
file.delete();
new CustomAlerts(AlertType.INFORMATION, "Success", "Success",
"The report was saved in your desktop under reports folder").showAndWait();
} catch (IOException ex) {
System.out.println("faild to create pdf");
ex.printStackTrace();
}
Stage stage = (Stage) rootPane.getScene().getWindow();
stage.close();
}
private int findNumOfDays() {
String month = null;
if (monthNumber < 10)
month = "0" + monthNumber;
else
month = String.valueOf(monthNumber);
YearMonth ym = YearMonth.parse(Calendar.getInstance().get(Calendar.YEAR) + "-" + month);
return ym.lengthOfMonth();
}
} | UTF-8 | Java | 18,477 | java | VisitsReportController.java | Java | [
{
"context": "talNumOfVisitors * 100));\n\t\t}\n\n\t\tseries2.setName(\"Solos \");\n\n\n\t}\n\n\tprivate void initGraphs() {\n\t\tent",
"end": 10447,
"score": 0.9786140322685242,
"start": 10442,
"tag": "NAME",
"value": "Solos"
}
]
| null | []
| package gui;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.time.YearMonth;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.ResourceBundle;
import javax.imageio.ImageIO;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import com.jfoenix.controls.JFXComboBox;
import Controllers.ReportsControl;
import alerts.CustomAlerts;
import client.ChatClient;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.SnapshotParameters;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.chart.XYChart.Data;
import javafx.scene.chart.XYChart.Series;
import javafx.scene.control.Label;
import javafx.scene.control.Tooltip;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.image.WritableImage;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import javafx.util.Duration;
import logic.GoNatureFinals;
import logic.VisitReport;
/**
* Gets month that picked from previous page.
* Loads all visitors stay time and entrance time into a line chart.
*/
public class VisitsReportController implements Initializable {
@FXML
private AnchorPane rootPane;
@FXML
private Label headerLabel;
@FXML
private LineChart<Number, Number> stayTime_chart;
@FXML
private NumberAxis stayX2;
@FXML
private NumberAxis stayY;
@FXML
public LineChart<Number, Number> entranceTime_chart;
@FXML
private NumberAxis enterX2;
@FXML
private NumberAxis enterY;
@FXML
private Label lblMonth;
@FXML
private JFXComboBox<String> comboBox;
@FXML
private JFXComboBox<String> dataComboBox;
private int monthNumber; // the month number
private XYChart.Series<Number, Number> series3; // Refactor
private XYChart.Series<Number, Number> series2; // Refactor
private XYChart.Series<Number, Number> series1; // Refactor
private XYChart.Series<Number, Number> series4; // Refactor
private XYChart.Series<Number, Number> series5; // Refactor
private XYChart.Series<Number, Number> series6; // Refactor
@Override
public void initialize(URL location, ResourceBundle resources) {
init();
}
private void init() {
lblMonth.setText(GoNatureFinals.MONTHS[monthNumber]); // set the name of the month
initGraphs();
Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(0.3), new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
initComboBox();
entranceTime_chart.getData().clear();
stayTime_chart.getData().clear();
loadEntranceSolosData(comboBox.getSelectionModel().getSelectedItem());
loadEntranceSubscribersData(comboBox.getSelectionModel().getSelectedItem());
loadEntranceGroupData(comboBox.getSelectionModel().getSelectedItem());
loadStayTimeSolosData(comboBox.getSelectionModel().getSelectedItem());
loadStayTimeSubscribersData(comboBox.getSelectionModel().getSelectedItem());
loadStayTimeGroupData(comboBox.getSelectionModel().getSelectedItem());
entranceTime_chart.getData().add(series1);
entranceTime_chart.getData().add(series3);
entranceTime_chart.getData().add(series5);
stayTime_chart.getData().add(series2);
stayTime_chart.getData().add(series4);
stayTime_chart.getData().add(series6);
setToolTip();
}
}));
timeline.setCycleCount(1);
timeline.play();
}
/**
* Setter for class variable monthNumber
*
* @param month The current month
*/
public void setMonthNumber(int month) {
this.monthNumber = month;
}
@SuppressWarnings("unused")
private void loadEntranceGroupData(String option) {
ArrayList<VisitReport> rep3 = new ArrayList<VisitReport>();
if (!option.equals("Show whole month"))
rep3 = ReportsControl.reportsManager.countGroupsEnterTimeWithDays(monthNumber, option);
else
rep3 = ReportsControl.reportsManager.countGroupsEnterTime(monthNumber);
// rep3 = (ArrayList<VisitReport>) ChatClient.responseFromServer.getResultSet(); // Refactor
series5 = new Series<Number, Number>();
double hour, min, time;
int maxNumOfVisitors = 0, sum;
for (int i = 0; i < rep3.size(); i++) {
sum = rep3.get(i).getSum();
if (maxNumOfVisitors < sum) {
maxNumOfVisitors = sum;
}
hour = Double.parseDouble(rep3.get(i).getData().substring(0, 2));
min = Double.parseDouble(rep3.get(i).getData().substring(3, 5)) / 60;
time = hour + min;
series5.getData().add(new Data<Number, Number>(time, sum));
}
series5.setName("Groups");
maxNumOfVisitors++;
if (maxNumOfVisitors % 2 != 0)
maxNumOfVisitors++;
}
@SuppressWarnings("unchecked")
private void loadStayTimeGroupData(String option) {
ArrayList<VisitReport> rep3 = new ArrayList<VisitReport>();
double hour, min, time;
int maxNumOfVisitors = 0, sum;
rep3 = new ArrayList<VisitReport>();
if (!option.equals("Show whole month"))
ReportsControl.countGroupsVisitTimeWithDay(monthNumber, option);
else
ReportsControl.countGroupsVisitTime(monthNumber);
rep3 = (ArrayList<VisitReport>) ChatClient.responseFromServer.getResultSet();
double totalNumOfVisitors = 0;
/* Sum total visitors at this date */
for (int i = 0; i < rep3.size(); i++)
totalNumOfVisitors += rep3.get(i).getSum();
series6 = new Series<Number, Number>();
hour = 0;
min = 0;
time = 0;
maxNumOfVisitors = 0;
sum = 0;
for (int i = 0; i < rep3.size(); i++) {
sum = rep3.get(i).getSum();
if (maxNumOfVisitors < sum) {
maxNumOfVisitors = sum;
}
hour = Double.parseDouble(rep3.get(i).getData().substring(0, 2));
min = Double.parseDouble(rep3.get(i).getData().substring(3, 5)) / 60;
time = hour + min;
series6.getData().add(new Data<Number, Number>(time, sum / totalNumOfVisitors * 100));
}
series6.setName("Groups");
}
private void loadEntranceSubscribersData(String option) {
ArrayList<VisitReport> rep2 = new ArrayList<VisitReport>();
if (!option.equals("Show whole month"))
rep2 = ReportsControl.reportsManager.countSubsEnterTimeWithDays(monthNumber, option);
else
rep2 = ReportsControl.reportsManager.countSubsEnterTime(monthNumber);
// rep2 = (ArrayList<VisitReport>) ChatClient.responseFromServer.getResultSet(); // Refactor
series3 = new Series<Number, Number>();
double hour, min, time;
int maxNumOfVisitors = 0, sum;
for (int i = 0; i < rep2.size(); i++) {
sum = rep2.get(i).getSum();
if (maxNumOfVisitors < sum) {
maxNumOfVisitors = sum;
}
hour = Double.parseDouble(rep2.get(i).getData().substring(0, 2));
min = Double.parseDouble(rep2.get(i).getData().substring(3, 5)) / 60;
time = hour + min;
series3.getData().add(new Data<Number, Number>(time, sum));
}
series3.setName("Subscribers");
}
@SuppressWarnings("unchecked")
private void loadStayTimeSubscribersData(String option) {
ArrayList<VisitReport> rep2 = new ArrayList<VisitReport>();
double hour, min, time;
int maxNumOfVisitors = 0, sum;
rep2 = new ArrayList<VisitReport>();
if (!option.equals("Show whole month"))
ReportsControl.countSubsVisitTimeWithDay(monthNumber, option);
else
ReportsControl.countSubsVisitTime(monthNumber);
rep2 = (ArrayList<VisitReport>) ChatClient.responseFromServer.getResultSet();
double totalNumOfVisitors = 0;
/* Sum total visitors at this date */
for (int i = 0; i < rep2.size(); i++)
totalNumOfVisitors += rep2.get(i).getSum();
series4 = new Series<Number, Number>();
hour = 0;
min = 0;
time = 0;
maxNumOfVisitors = 0;
sum = 0;
for (int i = 0; i < rep2.size(); i++) {
sum = rep2.get(i).getSum();
if (maxNumOfVisitors < sum) {
maxNumOfVisitors = sum;
}
hour = Double.parseDouble(rep2.get(i).getData().substring(0, 2));
min = Double.parseDouble(rep2.get(i).getData().substring(3, 5)) / 60;
time = hour + min;
series4.getData().add(new Data<Number, Number>(time, sum / totalNumOfVisitors * 100));
}
series4.setName("Subscribers");
}
private void loadEntranceSolosData(String option) {
ArrayList<VisitReport> rep = new ArrayList<VisitReport>();
if (!option.equals("Show whole month"))
rep = ReportsControl.reportsManager.countSolosEnterTimeWithDays(monthNumber, option);
else
rep = ReportsControl.reportsManager.countSolosEnterTime(monthNumber);
// rep = (ArrayList<VisitReport>) ChatClient.responseFromServer.getResultSet(); // Refactor
series1 = new Series<Number, Number>();
double hour, min, time;
int maxNumOfVisitors = 0, sum;
for (int i = 0; i < rep.size(); i++) {
sum = rep.get(i).getSum();
if (maxNumOfVisitors < sum) {
maxNumOfVisitors = sum;
}
hour = Double.parseDouble(rep.get(i).getData().substring(0, 2));
min = Double.parseDouble(rep.get(i).getData().substring(3, 5)) / 60;
time = hour + min;
series1.getData().add(new Data<Number, Number>(time, sum));
}
series1.setName("Solos ");
}
@SuppressWarnings("unchecked")
private void loadStayTimeSolosData(String option) {
ArrayList<VisitReport> rep = new ArrayList<VisitReport>();
double hour, min, time;
int maxNumOfVisitors = 0, sum;
if (!option.equals("Show whole month"))
ReportsControl.countSolosVisitTimeWithDay(monthNumber, option);
else
ReportsControl.countSolosVisitTime(monthNumber);
rep = new ArrayList<VisitReport>();
rep = (ArrayList<VisitReport>) ChatClient.responseFromServer.getResultSet();
double totalNumOfVisitors = 0;
/* Sum total visitors at this date */
for (int i = 0; i < rep.size(); i++)
totalNumOfVisitors += rep.get(i).getSum();
series2 = new Series<Number, Number>();
hour = 0;
min = 0;
time = 0;
maxNumOfVisitors = 0;
sum = 0;
for (int i = 0; i < rep.size(); i++) {
sum = rep.get(i).getSum();
if (maxNumOfVisitors < sum) {
maxNumOfVisitors = sum;
}
hour = Double.parseDouble(rep.get(i).getData().substring(0, 2));
min = Double.parseDouble(rep.get(i).getData().substring(3, 5)) / 60;
time = hour + min;
series2.getData().add(new Data<Number, Number>(time, sum / totalNumOfVisitors * 100));
}
series2.setName("Solos ");
}
private void initGraphs() {
enterX2.setAutoRanging(false);
enterX2.setLowerBound(7.5);
enterX2.setUpperBound(19);
enterX2.setMinorTickVisible(false);
enterX2.setTickUnit(0.5);
enterY.setAutoRanging(true);
enterY.setLowerBound(0);
enterY.setMinorTickVisible(false);
stayX2.setAutoRanging(false);
stayX2.setLowerBound(0.0);
stayX2.setUpperBound(10.0);
stayX2.setMinorTickVisible(false);
stayX2.setTickUnit(0.5);
stayY.setAutoRanging(true);
stayY.setLowerBound(0);
stayY.setTickUnit(1);
stayY.setMinorTickVisible(false);
}
private void setToolTip() {
for (XYChart.Series<Number, Number> s : stayTime_chart.getData()) {
for (XYChart.Data<Number, Number> d : s.getData()) {
Tooltip.install(d.getNode(), new Tooltip(d.getYValue() + "%"));
d.getNode().setOnMouseEntered(event -> d.getNode().getStyleClass().add("onHover"));
d.getNode().setOnMouseExited(event -> d.getNode().getStyleClass().remove("onHover"));
}
}
for (XYChart.Series<Number, Number> s : entranceTime_chart.getData()) {
for (XYChart.Data<Number, Number> d : s.getData()) {
Tooltip.install(d.getNode(), new Tooltip(d.getYValue() + " Visitors"));
d.getNode().setOnMouseEntered(event -> d.getNode().getStyleClass().add("onHover"));
d.getNode().setOnMouseExited(event -> d.getNode().getStyleClass().remove("onHover"));
}
}
}
private void initComboBox() {
int days = findNumOfDays();
ObservableList<String> month_days = FXCollections.observableArrayList();
month_days.add("Show whole month");
for (int i = 1; i <= days; i++) {
month_days.add(String.valueOf(i));
}
comboBox.getItems().addAll(month_days);
comboBox.getSelectionModel().select(0);
comboBox.valueProperty().addListener((obs, oldItem, newItem) -> {
if (newItem == null) {
} else {
if (dataComboBox.getSelectionModel().getSelectedItem().equals("Show All")) {
entranceTime_chart.getData().clear();
stayTime_chart.getData().clear();
loadEntranceSolosData(comboBox.getSelectionModel().getSelectedItem());
loadEntranceSubscribersData(comboBox.getSelectionModel().getSelectedItem());
loadEntranceGroupData(comboBox.getSelectionModel().getSelectedItem());
loadStayTimeSolosData(comboBox.getSelectionModel().getSelectedItem());
loadStayTimeSubscribersData(comboBox.getSelectionModel().getSelectedItem());
loadStayTimeGroupData(comboBox.getSelectionModel().getSelectedItem());
entranceTime_chart.getData().add(series1);
entranceTime_chart.getData().add(series3);
entranceTime_chart.getData().add(series5);
stayTime_chart.getData().add(series2);
stayTime_chart.getData().add(series4);
stayTime_chart.getData().add(series6);
setToolTip();
} else if (dataComboBox.getSelectionModel().getSelectedItem().equals("Solo Visits")) {
entranceTime_chart.getData().clear();
stayTime_chart.getData().clear();
loadEntranceSolosData(comboBox.getSelectionModel().getSelectedItem());
loadStayTimeSolosData(comboBox.getSelectionModel().getSelectedItem());
entranceTime_chart.getData().add(series1);
stayTime_chart.getData().add(series2);
setToolTip();
} else if (dataComboBox.getSelectionModel().getSelectedItem().equals("Subscribers Visits")) {
entranceTime_chart.getData().clear();
stayTime_chart.getData().clear();
loadEntranceSubscribersData(comboBox.getSelectionModel().getSelectedItem());
loadStayTimeSubscribersData(comboBox.getSelectionModel().getSelectedItem());
entranceTime_chart.getData().add(series3);
stayTime_chart.getData().add(series4);
setToolTip();
} else if (dataComboBox.getSelectionModel().getSelectedItem().equals("Group Visits")) {
entranceTime_chart.getData().clear();
stayTime_chart.getData().clear();
loadEntranceGroupData(comboBox.getSelectionModel().getSelectedItem());
loadStayTimeGroupData(comboBox.getSelectionModel().getSelectedItem());
entranceTime_chart.getData().add(series5);
stayTime_chart.getData().add(series6);
setToolTip();
}
}
});
dataComboBox.getItems().addAll("Show All", "Solo Visits", "Subscribers Visits", "Group Visits");
dataComboBox.getSelectionModel().select(0);
dataComboBox.valueProperty().addListener((obs, oldItem, newItem) -> {
if (newItem == null) {
} else {
if (newItem.equals("Show All")) {
entranceTime_chart.getData().clear();
stayTime_chart.getData().clear();
loadEntranceSolosData(comboBox.getSelectionModel().getSelectedItem());
loadEntranceSubscribersData(comboBox.getSelectionModel().getSelectedItem());
loadEntranceGroupData(comboBox.getSelectionModel().getSelectedItem());
loadStayTimeSolosData(comboBox.getSelectionModel().getSelectedItem());
loadStayTimeSubscribersData(comboBox.getSelectionModel().getSelectedItem());
loadStayTimeGroupData(comboBox.getSelectionModel().getSelectedItem());
entranceTime_chart.getData().add(series1);
entranceTime_chart.getData().add(series3);
entranceTime_chart.getData().add(series5);
stayTime_chart.getData().add(series2);
stayTime_chart.getData().add(series4);
stayTime_chart.getData().add(series6);
setToolTip();
} else if (newItem.equals("Solo Visits")) {
entranceTime_chart.getData().clear();
stayTime_chart.getData().clear();
loadEntranceSolosData(comboBox.getSelectionModel().getSelectedItem());
loadStayTimeSolosData(comboBox.getSelectionModel().getSelectedItem());
entranceTime_chart.getData().add(series1);
stayTime_chart.getData().add(series2);
setToolTip();
} else if (newItem.equals("Subscribers Visits")) {
entranceTime_chart.getData().clear();
stayTime_chart.getData().clear();
loadEntranceSubscribersData(comboBox.getSelectionModel().getSelectedItem());
loadStayTimeSubscribersData(comboBox.getSelectionModel().getSelectedItem());
entranceTime_chart.getData().add(series3);
stayTime_chart.getData().add(series4);
setToolTip();
} else if (newItem.equals("Group Visits")) {
entranceTime_chart.getData().clear();
stayTime_chart.getData().clear();
loadEntranceGroupData(comboBox.getSelectionModel().getSelectedItem());
loadStayTimeGroupData(comboBox.getSelectionModel().getSelectedItem());
entranceTime_chart.getData().add(series5);
stayTime_chart.getData().add(series6);
setToolTip();
}
}
});
}
@FXML
private void saveReportAsPdf() {
File directory = new File(System.getProperty("user.home") + "/Desktop/reports/");
if (!directory.exists()) {
directory.mkdir();
}
WritableImage nodeshot = rootPane.snapshot(new SnapshotParameters(), null);
String fileName = "Visits Report - month number " + monthNumber + ".pdf";
File file = new File("test.png");
try {
ImageIO.write(SwingFXUtils.fromFXImage(nodeshot, null), "png", file);
} catch (IOException e) {
e.printStackTrace();
}
PDDocument doc = new PDDocument();
PDPage page = new PDPage();
PDImageXObject pdimage;
PDPageContentStream content;
try {
pdimage = PDImageXObject.createFromFile("test.png", doc);
content = new PDPageContentStream(doc, page);
content.drawImage(pdimage, 50, 100, 500, 600);
content.close();
doc.addPage(page);
doc.save(System.getProperty("user.home") + "/Desktop/reports/" + fileName);
doc.close();
file.delete();
new CustomAlerts(AlertType.INFORMATION, "Success", "Success",
"The report was saved in your desktop under reports folder").showAndWait();
} catch (IOException ex) {
System.out.println("faild to create pdf");
ex.printStackTrace();
}
Stage stage = (Stage) rootPane.getScene().getWindow();
stage.close();
}
private int findNumOfDays() {
String month = null;
if (monthNumber < 10)
month = "0" + monthNumber;
else
month = String.valueOf(monthNumber);
YearMonth ym = YearMonth.parse(Calendar.getInstance().get(Calendar.YEAR) + "-" + month);
return ym.lengthOfMonth();
}
} | 18,477 | 0.713969 | 0.702278 | 541 | 33.15527 | 26.123796 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.946396 | false | false | 0 |
a3a6b871bc70fe607cb0f5c9c1d6d7d260afb21e | 27,487,790,727,880 | f4c7b4f31569ba1e754ed06656ff23778ab55704 | /study/spring/zstudy/zstudy3/src/main/java/com/study/spring/util/CommonUtil.java | 8c1b83704c8406d8ce531b032b3c074f1dbbcdd7 | []
| no_license | SALLY1945/sally1945.github.io | https://github.com/SALLY1945/sally1945.github.io | ff1fd8883934e23699277ee5c6903d1e748ea4e3 | 4fd52c4c1f0ce94de19636b37db8e34a7e38c1f4 | refs/heads/master | 2019-08-05T08:08:32.510000 | 2018-01-28T00:23:26 | 2018-01-28T00:23:26 | 49,801,336 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.study.spring.util;
public class CommonUtil {
public static String masterSelect() {
String select = "<select id='master'>" +
"<option>분류 선택</option>" +
"<option value='period'>기간</option>" +
"<option value='grade'>직급</option>" +
"<option value='member'>회원</option>" +
"</select>";
return select;
}
}
| UTF-8 | Java | 359 | java | CommonUtil.java | Java | []
| null | []
| package com.study.spring.util;
public class CommonUtil {
public static String masterSelect() {
String select = "<select id='master'>" +
"<option>분류 선택</option>" +
"<option value='period'>기간</option>" +
"<option value='grade'>직급</option>" +
"<option value='member'>회원</option>" +
"</select>";
return select;
}
}
| 359 | 0.619469 | 0.619469 | 14 | 23.214285 | 16.506184 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.071429 | false | false | 0 |
8800ac14b04a2fd26f1a0a9eb1ae9857a5d1fde4 | 11,622,181,571,466 | 9ecca1b282ba17b26153da3d62bd7654ca017f72 | /app/models/Location.java | 9f38369c7f33049f499b09fad2387b86d0349440 | []
| no_license | simpelers/rhok | https://github.com/simpelers/rhok | 40da40ed0a205ca612ea56b0d198e68dc591f6b7 | 3167c8a7c5d1c72d6cc5130d0eb268b02333a4ab | refs/heads/master | 2020-12-25T19:14:53.928000 | 2011-12-09T02:59:06 | 2011-12-09T02:59:06 | 2,902,924 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package models;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.OneToOne;
import org.hibernate.annotations.CascadeType;
import play.db.jpa.Model;
@Entity
public class Location extends Model
{
private String name;
private double latitude;
private double longitude;
public Location(String aName, double aLatitude, double aLongitude)
{
setName(aName);
latitude = aLatitude;
longitude = aLongitude;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/**
* @return the lat
*/
public double getLatitude()
{
return latitude;
}
/**
* @param aLat the lat to set
*/
public void setLatitude(double latitude)
{
latitude = latitude;
}
/**
* @return the long
*/
public double getLongitude()
{
return longitude;
}
/**
* @param aL the long to set
*/
public void setLongitude(double longitude)
{
longitude = longitude;
}
}
| UTF-8 | Java | 1,099 | java | Location.java | Java | []
| null | []
| package models;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.OneToOne;
import org.hibernate.annotations.CascadeType;
import play.db.jpa.Model;
@Entity
public class Location extends Model
{
private String name;
private double latitude;
private double longitude;
public Location(String aName, double aLatitude, double aLongitude)
{
setName(aName);
latitude = aLatitude;
longitude = aLongitude;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/**
* @return the lat
*/
public double getLatitude()
{
return latitude;
}
/**
* @param aLat the lat to set
*/
public void setLatitude(double latitude)
{
latitude = latitude;
}
/**
* @return the long
*/
public double getLongitude()
{
return longitude;
}
/**
* @param aL the long to set
*/
public void setLongitude(double longitude)
{
longitude = longitude;
}
}
| 1,099 | 0.613285 | 0.613285 | 66 | 15.651515 | 15.201169 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false | 0 |
a030dddc2a8ad4d13d36d01e93b1b4071f136e34 | 15,187,004,427,671 | 3822dad61967a49d53e9c86f9fa444c2cd021ed2 | /src/servlet/Subscribe.java | 00969ccf13297e0d6ac53a9f9f459f5a2369c8bf | [
"MIT"
]
| permissive | gmarciani/godot-web | https://github.com/gmarciani/godot-web | 91bdd6bfe2857dbd9d2b12727d20e310af2eb65d | 9e7e9026dca578e7f531394f7ffa4384f6a61cbf | refs/heads/master | 2020-04-11T09:12:01.068000 | 2015-12-13T16:24:41 | 2015-12-13T16:24:41 | 11,534,841 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /* WebGodot: Godot Server-Side Implementation.
Copyright 2013 Giacomo Marciani <giacomo.marciani@gmail.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.bean.SubscriberBean;
import controller.ControllerSubscription;
import exception.GodotSyntaxException;
@WebServlet("/Subscribe")
public class Subscribe extends HttpServlet {
private static final long serialVersionUID = 1L;
private ControllerSubscription controllerSubscription;
public Subscribe() {
super();
this.controllerSubscription = ControllerSubscription.getInstance();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
String mail = request.getParameter("mail");
SubscriberBean subscriberBean = new SubscriberBean()
.setName(name)
.setMail(mail);
try {
this.controllerSubscription.insertSubscriber(subscriberBean);
return;
} catch (GodotSyntaxException exc) {
response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE); //406
return;
}
}
}
| UTF-8 | Java | 2,047 | java | Subscribe.java | Java | [
{
"context": "erver-Side Implementation. \n \n Copyright 2013 Giacomo Marciani <giacomo.marciani@gmail.com>\n\n Licensed under t",
"end": 88,
"score": 0.9998633861541748,
"start": 72,
"tag": "NAME",
"value": "Giacomo Marciani"
},
{
"context": "tation. \n \n Copyright 2013 Giacomo Marciani <giacomo.marciani@gmail.com>\n\n Licensed under the Apache License, Version 2",
"end": 116,
"score": 0.9999342560768127,
"start": 90,
"tag": "EMAIL",
"value": "giacomo.marciani@gmail.com"
}
]
| null | []
| /* WebGodot: Godot Server-Side Implementation.
Copyright 2013 <NAME> <<EMAIL>>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.bean.SubscriberBean;
import controller.ControllerSubscription;
import exception.GodotSyntaxException;
@WebServlet("/Subscribe")
public class Subscribe extends HttpServlet {
private static final long serialVersionUID = 1L;
private ControllerSubscription controllerSubscription;
public Subscribe() {
super();
this.controllerSubscription = ControllerSubscription.getInstance();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
String mail = request.getParameter("mail");
SubscriberBean subscriberBean = new SubscriberBean()
.setName(name)
.setMail(mail);
try {
this.controllerSubscription.insertSubscriber(subscriberBean);
return;
} catch (GodotSyntaxException exc) {
response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE); //406
return;
}
}
}
| 2,018 | 0.76893 | 0.763068 | 63 | 31.492064 | 29.229727 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.190476 | false | false | 0 |
1cc7ed8387b3eb2c2212e537d0a89a4b3717b6ad | 2,508,260,969,352 | e7ed4c945a59eecdb4885d12f78a35210ff4ca6c | /app/src/main/java/com/avaya/android/vantage/aaadevbroadcast/activities/MainActivityK155.java | 9ca5e8099e083cbc263400ed355e4a67a42da793 | []
| no_license | AvayaCalaPoCDevGroup/AvayaBroadcastConnectAndroid | https://github.com/AvayaCalaPoCDevGroup/AvayaBroadcastConnectAndroid | 4b3b29bff367491b627f6c05dc735009fbe8ff87 | 25469c8f70a8769d901993d2dc2b16cad65c136b | refs/heads/master | 2021-04-18T08:09:51.218000 | 2020-12-14T20:25:35 | 2020-12-14T20:25:35 | 249,520,233 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.avaya.android.vantage.aaadevbroadcast.activities;
import android.app.Dialog;
import android.app.KeyguardManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import androidx.annotation.NonNull;
import com.avaya.android.vantage.aaadevbroadcast.views.DialogAAADEVMessages;
import com.google.android.material.tabs.TabLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.RelativeLayout;
import android.widget.ToggleButton;
import com.avaya.android.vantage.aaadevbroadcast.Constants;
import com.avaya.android.vantage.aaadevbroadcast.ElanApplication;
import com.avaya.android.vantage.aaadevbroadcast.R;
import com.avaya.android.vantage.aaadevbroadcast.Utils;
import com.avaya.android.vantage.aaadevbroadcast.callshistory.CallHistoryFragment;
import com.avaya.android.vantage.aaadevbroadcast.contacts.ContactsFragment;
import com.avaya.android.vantage.aaadevbroadcast.csdk.CallAdaptor;
import com.avaya.android.vantage.aaadevbroadcast.csdk.ConfigParametersNames;
import com.avaya.android.vantage.aaadevbroadcast.csdk.SDKManager;
import com.avaya.android.vantage.aaadevbroadcast.fragments.ActiveCallFragment;
import com.avaya.android.vantage.aaadevbroadcast.fragments.CallStatusFragment;
import com.avaya.android.vantage.aaadevbroadcast.fragments.ContactDetailsFragment;
import com.avaya.android.vantage.aaadevbroadcast.fragments.ContactEditFragment;
import com.avaya.android.vantage.aaadevbroadcast.fragments.DialerFragment;
import com.avaya.android.vantage.aaadevbroadcast.fragments.VideoCallFragment;
import com.avaya.android.vantage.aaadevbroadcast.fragments.JoinMeetingFragment;
import com.avaya.android.vantage.aaadevbroadcast.model.UIAudioDevice;
import com.avaya.android.vantage.aaadevbroadcast.model.UICallState;
import com.avaya.android.vantage.aaadevbroadcast.views.adapters.CallStateEventHandler;
import com.avaya.android.vantage.aaadevbroadcast.views.interfaces.IHardButtonListener;
import com.avaya.deskphoneservices.HardButtonType;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import static com.avaya.android.vantage.aaadevbroadcast.Constants.DigitKeys;
import static com.avaya.android.vantage.aaadevbroadcast.model.UICallState.ESTABLISHED;
import static com.avaya.android.vantage.aaadevbroadcast.model.UICallState.FAILED;
import static com.avaya.android.vantage.aaadevbroadcast.model.UICallState.REMOTE_ALERTING;
import static com.avaya.android.vantage.aaadevbroadcast.model.UICallState.TRANSFERRING;
public class MainActivityK155 extends BaseActivity implements IHardButtonListener {
private static final String TAG = "MainActivityK155";
private RelativeLayout tabOne;
private RelativeLayout tabSelectorWrapper;
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(newBase);
Utils.overrideFontScaleAndDensityK155(this);
}
/**
* key up event received from platform via MEDIA_BUTTON intent
*
* @param hardButton
*/
@Override
public void onKeyUp(@NonNull HardButtonType hardButton) {
//test for K155 special buttons:
try {
UIAudioDevice activeAudioDevice = mAudioDeviceViewAdaptor.getActiveAudioDevice();
int activeCallId = SDKManager.getInstance().getCallAdaptor().getActiveCallId();
ToggleButton dialerOffHook = mSectionsPagerAdapter.getDialerFragment().offHook;
KeyguardManager kgMgr = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
boolean isLocked = (kgMgr != null) && kgMgr.isDeviceLocked() && !ElanApplication.isPinAppLock;
switch (hardButton) {
case AUDIO_MUTE://video mute
if (mAudioMute.isEnabled()) {
Log.d(TAG, "PHYSICAL KEY AUDIO MUTE");
mAudioMute.performClick();
}
break;
case VIDEO_MUTE://video mute
if (mVideoMute.isEnabled()) {
Log.d(TAG, "PHYSICAL KEY VIDEO MUTE");
mVideoMute.performClick();
}
break;
case SPEAKER://speaker
Log.d(TAG, "PHYSICAL KEY SPEAKER HOOK");
if (isLocked && (SDKManager.getInstance().getCallAdaptor().getNumOfCalls() == 0)) {
Log.v(TAG, "cancel off hook on lock");
return;
}
mAudioDeviceViewAdaptor.setUserRequestedDevice(UIAudioDevice.SPEAKER);
updateAudioSelectionUI(UIAudioDevice.SPEAKER);
saveAudioSelection(Constants.AUDIO_PREF_KEY, UIAudioDevice.SPEAKER.toString());
if (!dialerOffHook.isChecked() && (activeCallId == 0)) {
if (SDKManager.getInstance().getCallAdaptor().isAlertingCall() == 0) {
prepareOffHook();
}
try {
if (isFragmentVisible(DIALER_FRAGMENT)) {
((DialerFragment) getVisibleFragment(DIALER_FRAGMENT)).offHook.performClick();
changeUiForFullScreenInLandscape(false);
if (isFragmentVisible(CONTACTS_DETAILS_FRAGMENT))
((ContactDetailsFragment) getVisibleFragment(CONTACTS_DETAILS_FRAGMENT)). mBackListener.back();
}
} catch (NullPointerException e) {
e.printStackTrace();
}
} else if ((activeAudioDevice == UIAudioDevice.SPEAKER)) {
if (activeCallId > 0) {
SDKManager.getInstance().getCallAdaptor().endCall(activeCallId);
try {
if (isFragmentVisible(DIALER_FRAGMENT) && !isFragmentVisible(ACTIVE_VIDEO_CALL_FRAGMENT)) {
changeUiForFullScreenInLandscape(false);
if (isFragmentVisible(CONTACTS_DETAILS_FRAGMENT))
((ContactDetailsFragment) getVisibleFragment(CONTACTS_DETAILS_FRAGMENT)). mBackListener.back();
}
} catch (NullPointerException e) {
e.printStackTrace();
}
try {
if (isFragmentVisible(DIALER_FRAGMENT))
((DialerFragment) getVisibleFragment(DIALER_FRAGMENT)).setMode(DialerFragment.DialMode.EDIT);
} catch (NullPointerException e) {
e.printStackTrace();
}
} else if (dialerOffHook.isChecked()) {
resetDialer();
mSectionsPagerAdapter.getDialerFragment().offHook.performClick();
}
} else {
Log.w(TAG, "onKeyUp SPEAKER: unexpected state activeCallId=" + activeCallId + " activeAudioDevice=" + activeAudioDevice + " dialerOffHook.isChecked()=" + dialerOffHook.isChecked());
}
break;
case HEADSET://transducer
Log.d(TAG, "PHYSICAL KEY TRANSDUCER SELECTION");
if (isLocked && (SDKManager.getInstance().getCallAdaptor().getNumOfCalls() == 0)) {
Log.v(TAG, "cancel off hook on lock");
return;
}
int device = getHeadsetByPriority();
String prefValue = mSharedPref.getString(Constants.AUDIO_PREF_KEY, (UIAudioDevice.SPEAKER).toString());
assert prefValue != null;
UIAudioDevice savedDevice = UIAudioDevice.valueOf(prefValue.toUpperCase());
List<UIAudioDevice> devices = Arrays.asList(UIAudioDevice.BLUETOOTH_HEADSET, UIAudioDevice.RJ9_HEADSET, UIAudioDevice.WIRED_HEADSET, UIAudioDevice.WIRED_USB_HEADSET);
if (devices.contains(savedDevice)) {
device = savedDevice.getUIId();
}
if (!dialerOffHook.isChecked() && (activeCallId == 0)) {
prepareOffHook();
this.onClick(findViewById(device));
try {
if (isFragmentVisible(DIALER_FRAGMENT)) {
((DialerFragment) getVisibleFragment(DIALER_FRAGMENT)).offHook.performClick();
changeUiForFullScreenInLandscape(false);
if (isFragmentVisible(CONTACTS_DETAILS_FRAGMENT))
((ContactDetailsFragment) getVisibleFragment(CONTACTS_DETAILS_FRAGMENT)). mBackListener.back();
}
} catch (NullPointerException e) {
e.printStackTrace();
}
} else if (dialerOffHook.isChecked() && (activeAudioDevice != UIAudioDevice.SPEAKER) && (activeAudioDevice != UIAudioDevice.HANDSET) && (activeAudioDevice != UIAudioDevice.WIRELESS_HANDSET)) { //there is active call via Headset
if (activeCallId > 0) {
SDKManager.getInstance().getCallAdaptor().endCall(activeCallId);
try {
if (isFragmentVisible(DIALER_FRAGMENT)) {
changeUiForFullScreenInLandscape(false);
if (isFragmentVisible(CONTACTS_DETAILS_FRAGMENT))
((ContactDetailsFragment) getVisibleFragment(CONTACTS_DETAILS_FRAGMENT)). mBackListener.back();
}
} catch (NullPointerException e) {
e.printStackTrace();
}
} else {
resetDialer();
try {
if (isFragmentVisible(DIALER_FRAGMENT)) {
((DialerFragment) getVisibleFragment(DIALER_FRAGMENT)).offHook.performClick();
changeUiForFullScreenInLandscape(false);
if (isFragmentVisible(CONTACTS_DETAILS_FRAGMENT))
((ContactDetailsFragment) getVisibleFragment(CONTACTS_DETAILS_FRAGMENT)). mBackListener.back();
}
} catch (NullPointerException e) {
e.printStackTrace();
}
}
} else if (activeCallId > 0 && (activeAudioDevice == UIAudioDevice.SPEAKER || activeAudioDevice == UIAudioDevice.HANDSET || activeAudioDevice == UIAudioDevice.WIRELESS_HANDSET)) { // there is an active call on speaker and headset was pressed
View transientView = new View(this);
transientView.setId(device);
onClick(transientView);
} else if (activeCallId > 0 && SDKManager.getInstance().getCallAdaptor().getCall(activeCallId).getState() == UICallState.NOT_RELEVANT) {
SDKManager.getInstance().getCallAdaptor().endCall(activeCallId);
} else {
Log.w(TAG, "onKeyUp HEADSET: unexpected state activeCallId=" + activeCallId + " activeAudioDevice=" + activeAudioDevice + " dialerOffHook.isChecked()=" + dialerOffHook.isChecked());
}
break;
}
}catch (NullPointerException e){
Log.e(TAG, "NPE in onKeyUp(@NonNull HardButtonType hardButton):", e);
}
}
@NonNull
private int getHeadsetByPriority() {
/*Bluetooth headset (if paired and connected)
USB wired headset (if connected)
3.5mm wired headset (if connected)
RJ9 headset (connection state is a don't care)*/
int device = R.id.containerHeadset;
for (UIAudioDevice uiAudioDevice : mAudioDeviceViewAdaptor.getAudioDeviceList()) {
if (uiAudioDevice == UIAudioDevice.BLUETOOTH_HEADSET) {
device = R.id.containerBTHeadset;
break;
}
if (uiAudioDevice == UIAudioDevice.WIRED_USB_HEADSET) {
device = R.id.containerUsbHeadset;
}
if ((device != R.id.containerUsbHeadset) && (uiAudioDevice == UIAudioDevice.WIRED_HEADSET)) {
device = R.id.container35Headset;
}
}
return device;
}
/**
* key down event received from platform via MEDIA_BUTTON intent
*
* @param hardButton
*/
@Override
public void onKeyDown(@NonNull HardButtonType hardButton) {
if (!ElanApplication.isMainActivityVisible()) {
Intent intent = new Intent(this, MainActivityK155.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(MainActivityK155.BRING_TO_FOREGROUND_INTENT);
intent.putExtra(HARD_BUTTON, hardButton);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
try {
pendingIntent.send();
} catch (PendingIntent.CanceledException e) {
Log.e(TAG, "failed to activate MainActivity from pending intent while it was not visible");
}
setIntent(null);
}
}
@Override
void tabLayoutAddOnTabSelectedListener(){
Log.d(TAG, "tabLayoutAddOnTabSelectedListener");
mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
Log.v("TabTest", "onTabSelected");
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
Log.v("TabTest", "onTabUnselected");
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
contactsTabFilterMenuListnerSetup(tabSelectorWrapper);
}
});
mVideoMute.setVisibility(View.INVISIBLE);
}
@Override
protected void initMoreViews() {
tabOne = (RelativeLayout) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
searchButton = findViewById(R.id.search_button);
addcontactButton = findViewById(R.id.addcontact_button);
filterButton = findViewById(R.id.filterRecent);
filterButton.setImageResource(R.drawable.ic_expand_more);
}
/**
* Modifies the UI to adopt screen orientation
* @param show
*/
@Override
public void changeUiForFullScreenInLandscape(boolean show){
try {
if (show) {
mBrandView.setVisibility(View.GONE);
mUser.setVisibility(View.GONE);
mStatusLayout.setVisibility(View.GONE);
mOpenUser.setVisibility(View.GONE);
mErrorStatus.setVisibility(View.GONE);
appBar.setVisibility(View.INVISIBLE);
appBar.getLayoutParams().height = 0;
mTabLayout.setVisibility(View.GONE);
mTabLayout.getLayoutParams().height = 0;
dialerView.setVisibility(View.GONE);
mViewPager.getLayoutParams().height = 675;
} else {
mBrandView.setVisibility(View.VISIBLE);
mUser.setVisibility(View.VISIBLE);
mStatusLayout.setVisibility(View.VISIBLE);
mOpenUser.setVisibility(View.VISIBLE);
mErrorStatus.setVisibility(View.VISIBLE);
appBar.setVisibility(View.VISIBLE);
appBar.getLayoutParams().height = 100;
mTabLayout.setVisibility(View.VISIBLE);
mTabLayout.getLayoutParams().height = 100;
dialerView.setVisibility(View.GONE);
mViewPager.getLayoutParams().height = 430;
}
checkForErrors();
}catch (Exception e){
e.printStackTrace();
}
}
@Override
protected void initViewPager() {
mUIDeskphoneServiceAdaptor.setHardButtonListener(this);
super.initViewPager();
}
protected void onPageScrolledLogic(){
if (mTabLayout.getVisibility()==View.GONE && (isFragmentVisible(CONTACTS_DETAILS_FRAGMENT) || isFragmentVisible(CONTACTS_EDIT_FRAGMENT)) )
mViewPager.setEnabledSwipe(false);
else
mViewPager.setEnabledSwipe(true);
}
protected void onPageSelectedCondition() {
if (mSectionsPagerAdapter.getFragmentContacts() != null && mSectionsPagerAdapter.getFragmentContacts().mSearchView != null && mSectionsPagerAdapter.getFragmentContacts().mSearchView.getVisibility() == View.VISIBLE) {
if (isFragmentVisible(CONTACTS_FRAGMENT) && !isFragmentVisible(CONTACTS_EDIT_FRAGMENT))
mSectionsPagerAdapter.getFragmentContacts().removeSearchResults();
}
}
@Override
public void changeButtonsVisibility(Tabs tab){
switch (tab) {
case Dialer:
case Favorites:
searchButton.setVisibility(View.INVISIBLE);
addcontactButton.setVisibility(View.INVISIBLE);
filterButton.setVisibility(View.INVISIBLE);
return;
case Contacts:
searchButton.setVisibility(View.VISIBLE);
setAddContactVisibility();
filterButton.setVisibility(View.INVISIBLE);
return;
case History:
searchButton.setVisibility(View.INVISIBLE);
addcontactButton.setVisibility(View.INVISIBLE);
filterButton.setVisibility(View.VISIBLE);
return;
}
}
@Override
void setupMoreOnClickListenersForDevice(){
addcontactButton.setOnClickListener(this);
filterButton.setOnClickListener(this);
searchButton.setOnClickListener(this);
}
void fullScreenViewResizeLogic(int startDimension){
boolean isToResize = false;
FragmentManager fragmentManager = MainActivityK155.this.getSupportFragmentManager();
List<Fragment> fragments = fragmentManager.getFragments();
for(Fragment fragment : fragments){
if(fragment != null && fragment.isVisible() && fragment instanceof ContactDetailsFragment ) {
isToResize = true;
break;
}else if ( fragment != null && fragment.isVisible() && fragment instanceof ContactsFragment){
if( ((ContactsFragment) fragment).isSearchLayoutVisible() ){
isToResize = true;
break;
}
}
}
if(!isToResize) {
if(mViewPager!=null && mViewPager.getLayoutParams()!=null)
mViewPager.getLayoutParams().height = 430;
}
}
int onKeyDownDeviceLogic(int keyCode, KeyEvent event){
if (!isToLockPressButton) {
try {
if(isFragmentVisible(CONTACTS_DETAILS_FRAGMENT)||isFragmentVisible(CONTACTS_EDIT_FRAGMENT) || isFragmentVisible(JOIN_MEETING_FRAGMENT)){
isToBlockBakcPress = true;
}
isToLockPressButton = true;
int keyunicode = event.getUnicodeChar(event.getMetaState());
char character = (char) keyunicode;
String digit = "" + character;
if(keyCode == KeyEvent.KEYCODE_BACK && !isLockState(this)) {
if (mSelectPhoneNumber.getVisibility() == View.VISIBLE) {
mSlideSelectPhoneNumber.collapse(mSelectPhoneNumber);
}
try {
if (((ActiveCallFragment) getVisibleFragment(ACTIVE_CALL_FRAGMENT)).mMoreCallFeatures.getVisibility() == View.VISIBLE) {
((ActiveCallFragment) getVisibleFragment(ACTIVE_CALL_FRAGMENT)).mMoreCallFeaturesClick();
return 1;
}
}catch (Exception e){
e.printStackTrace();
}
mViewPager.setEnabledSwipe(true);
if (!isFragmentVisible(ACTIVE_CALL_FRAGMENT) && !isFragmentVisible(ACTIVE_VIDEO_CALL_FRAGMENT)) {
changeUiForFullScreenInLandscape(false);
if (isFragmentVisible(CONTACTS_EDIT_FRAGMENT)) {
((ContactEditFragment) getVisibleFragment(CONTACTS_EDIT_FRAGMENT)).cancelOnClickListener();
//changeUiForFullScreenInLandscape(true);
} else if (isFragmentVisible(CONTACTS_DETAILS_FRAGMENT)) {
((ContactDetailsFragment) getVisibleFragment(CONTACTS_DETAILS_FRAGMENT)).mDeletePopUp.setVisibility(View.GONE);
((ContactDetailsFragment) getVisibleFragment(CONTACTS_DETAILS_FRAGMENT)).mBackListener.back();
changeUiForFullScreenInLandscape(false);
} else if (isFragmentVisible(JOIN_MEETING_FRAGMENT)){
((JoinMeetingFragment) getVisibleFragment(JOIN_MEETING_FRAGMENT)).onBackPressed();
}
if(isFragmentVisible(CONTACTS_FRAGMENT) && ((ContactsFragment) getVisibleFragment(CONTACTS_FRAGMENT)).isSearchLayoutVisible()){
((ContactsFragment) getVisibleFragment(CONTACTS_FRAGMENT)).removeSearchResults();
CallStatusFragment callStatusFragment = (CallStatusFragment) getSupportFragmentManager().findFragmentByTag(CallStateEventHandler.CALL_STATUS_TAG);
assert callStatusFragment != null;
if( (Objects.requireNonNull(callStatusFragment.getView()).getVisibility()==View.INVISIBLE || callStatusFragment.getView().getVisibility()==View.GONE) && SDKManager.getInstance().getCallAdaptor().hasActiveHeldOrInitiatingCall()) {
callStatusFragment.showCallStatus();
}
return 0;
}
}else if (mCallViewAdaptor.getNumOfCalls() < CallAdaptor.MAX_NUM_CALLS){
((ActiveCallFragment) getVisibleFragment(ACTIVE_CALL_FRAGMENT)).mBackArrowOnClickListener();
//changeUiForFullScreenInLandscape(false);
return 1;
}
}
if(isFragmentVisible(DIALER_FRAGMENT) && mSectionsPagerAdapter!=null && mSectionsPagerAdapter.getDialerFragment()!=null ) {
if (digit.matches("[\\d]") || digit.matches("#") || digit.matches("\\*")) {
if(!isFragmentVisible(CONTACTS_EDIT_FRAGMENT) && !isFragmentVisible(JOIN_MEETING_FRAGMENT))
mSectionsPagerAdapter.getDialerFragment().dialFromKeyboard(digit);
} else if (event.getKeyCode() == KeyEvent.KEYCODE_DEL) {
mSectionsPagerAdapter.getDialerFragment().deleteDigit();
}
}
if (DigitKeys.contains(event.getKeyCode()) &&
( (getVisibleFragment(CONTACTS_FRAGMENT))==null || (getVisibleFragment(CONTACTS_FRAGMENT))!=null &&((ContactsFragment) getVisibleFragment(CONTACTS_FRAGMENT)).isSearchLayoutVisible() ==false ) ) {
if (keyCode != KeyEvent.KEYCODE_0) {
// mSectionsPagerAdapter.getDialerFragment().onHardKeyClick(digit);
if( getVisibleFragment(ACTIVE_CALL_FRAGMENT) !=null && !((ActiveCallFragment) getVisibleFragment(ACTIVE_CALL_FRAGMENT)).mHoldCallButton.isChecked()) {
((ActiveCallFragment) getVisibleFragment(ACTIVE_CALL_FRAGMENT)).sendDTMF(digit.charAt(0));
}else{
if(isFragmentVisible(CONTACTS_EDIT_FRAGMENT)==false)
mSectionsPagerAdapter.getDialerFragment().onHardKeyClick(digit);
}
}else {
zeroOrPlus = "0";
}
mViewPager.setCurrentItem(0, false);
searchButton.setVisibility(View.INVISIBLE);
addcontactButton.setVisibility(View.INVISIBLE);
try {
if (isFragmentVisible(DIALER_FRAGMENT) && isFragmentVisible(CONTACTS_DETAILS_FRAGMENT) ) {
changeUiForFullScreenInLandscape(false);
((ContactDetailsFragment) getVisibleFragment(CONTACTS_DETAILS_FRAGMENT)). mBackListener.back();
}
} catch (NullPointerException e) {
e.printStackTrace();
}
if (isFragmentVisible(ACTIVE_VIDEO_CALL_FRAGMENT) || isFragmentVisible(CONTACTS_DETAILS_FRAGMENT) || isFragmentVisible(CONTACTS_EDIT_FRAGMENT)) {
changeUiForFullScreenInLandscape(true);
}
event.startTracking();
return 1;
}
}catch (Exception e){
e.printStackTrace();
}
}
return -1;
}
@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
try {
if (keyCode == KeyEvent.KEYCODE_0) {
if (isFragmentVisible(DIALER_FRAGMENT) && mSectionsPagerAdapter != null && mSectionsPagerAdapter.getDialerFragment() != null) {
mSectionsPagerAdapter.getDialerFragment().dialFromKeyboard("+");
zeroOrPlus = "+";
}
}
}catch (Exception e){
e.printStackTrace();
}
if(DigitKeys.contains(event.getKeyCode())) {
return true;
}else
return super.onKeyLongPress(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
isToLockPressButton = false;
String key = KeyEvent.keyCodeToString(event.getKeyCode()).replace("KEYCODE_", "");
sendAccessibilityEvent(key, findViewById(R.id.dialer_display));
if (keyCode == KeyEvent.KEYCODE_0) {
if(mSectionsPagerAdapter!=null && mSectionsPagerAdapter.getDialerFragment()!=null ) {
//mSectionsPagerAdapter.getDialerFragment().onHardKeyClick(zeroOrPlus);
if(getVisibleFragment(ACTIVE_CALL_FRAGMENT) !=null && !((ActiveCallFragment) getVisibleFragment(ACTIVE_CALL_FRAGMENT)).mHoldCallButton.isChecked()) {
((ActiveCallFragment) getVisibleFragment(ACTIVE_CALL_FRAGMENT)).sendDTMF(zeroOrPlus.charAt(0));
}else{
mSectionsPagerAdapter.getDialerFragment().onHardKeyClick(zeroOrPlus);
}
}
}
if(DigitKeys.contains(event.getKeyCode())) {
if(isOnKeyDownHappened == false) {
int keyunicode = event.getUnicodeChar(event.getMetaState());
char character = (char) keyunicode;
String digit = "" + character;
if (isFragmentVisible(DIALER_FRAGMENT) && mSectionsPagerAdapter != null && mSectionsPagerAdapter.getDialerFragment() != null) {
if (digit.matches("[\\d]") || digit.matches("#") || digit.matches("\\*")) {
if( (getVisibleFragment(CONTACTS_EDIT_FRAGMENT)) ==null
&& ((ContactsFragment) getVisibleFragment(CONTACTS_FRAGMENT)).isSearchLayoutVisible() ==false && getVisibleFragment(JOIN_MEETING_FRAGMENT) == null ) {
mSectionsPagerAdapter.getDialerFragment().dialFromKeyboard(digit);
}
} else if (event.getKeyCode() == KeyEvent.KEYCODE_DEL) {
mSectionsPagerAdapter.getDialerFragment().deleteDigit();
}
}
if (DigitKeys.contains(event.getKeyCode()) && getVisibleFragment(CONTACTS_FRAGMENT)!=null
&& ((ContactsFragment) getVisibleFragment(CONTACTS_FRAGMENT)).isSearchLayoutVisible() ==false
&& !isFragmentVisible(CONTACTS_EDIT_FRAGMENT)) {
if (keyCode != KeyEvent.KEYCODE_0) {
//mSectionsPagerAdapter.getDialerFragment().onHardKeyClick(digit);
if(getVisibleFragment(ACTIVE_CALL_FRAGMENT) !=null && !((ActiveCallFragment) getVisibleFragment(ACTIVE_CALL_FRAGMENT)).mHoldCallButton.isChecked()) {
((ActiveCallFragment) getVisibleFragment(ACTIVE_CALL_FRAGMENT)).sendDTMF(digit.charAt(0));
}else {
mSectionsPagerAdapter.getDialerFragment().onHardKeyClick(digit);
}
} else {
zeroOrPlus = "0";
}
mViewPager.setCurrentItem(0, false);
searchButton.setVisibility(View.INVISIBLE);
addcontactButton.setVisibility(View.INVISIBLE);
try {
if (isFragmentVisible(DIALER_FRAGMENT) && isFragmentVisible(CONTACTS_DETAILS_FRAGMENT)) {
changeUiForFullScreenInLandscape(false);
((ContactDetailsFragment) getVisibleFragment(CONTACTS_DETAILS_FRAGMENT)).mBackListener.back();
}
} catch (NullPointerException e) {
e.printStackTrace();
}
event.startTracking();
}
}
isOnKeyDownHappened = false;
return true;
}else {
return super.onKeyUp(keyCode, event);
}
}
boolean onDialerInteractionDeviceLogic(String number){
FragmentManager fragmentManager = MainActivityK155.this.getSupportFragmentManager();
List<Fragment> fragments = fragmentManager.getFragments();
for (Fragment fragment : fragments) {
if (fragment != null && fragment.isVisible())
if (fragment instanceof DialerFragment) {
mCallViewAdaptor.addDigitToOffHookDialCall(number.charAt(0));
} else if (fragment instanceof ActiveCallFragment && (((ActiveCallFragment) fragment).getCallState() == UICallState.ESTABLISHED)) {
((ActiveCallFragment) fragment).sendDTMF(number.charAt(0));
return false;
}
}
return true;
}
void expandPhoneNumberSlide(){
mSlideSelectPhoneNumber.expand(mSelectPhoneNumber);
}
void setTabIconsDeviceLogic(){
if (tabOne == null)
return;
tabImage = tabOne.findViewById(R.id.tab_image);
tabImage.setImageResource(R.drawable.ic_contacts);
tabSelector = tabOne.findViewById(R.id.tab_selector);
checkFilterButtonState();
tabSelectorWrapper = tabOne.findViewById(R.id.filter);
if (SDKManager.getInstance().getDeskPhoneServiceAdaptor().getConfigBooleanParam(ConfigParametersNames.ENABLE_FAVORITES) == true && SDKManager.getInstance().getDeskPhoneServiceAdaptor().getConfigBooleanParam(ConfigParametersNames.ENABLE_CALL_LOG) == true){
if ( (Objects.requireNonNull(mTabLayout.getTabAt(2)).getCustomView() == null && (SDKManager.getInstance().getCallAdaptor().getNumOfCalls() == 0) || !mSectionsPagerAdapter.isCallAddParticipant()))
Objects.requireNonNull(mTabLayout.getTabAt(2)).setCustomView(tabOne);
else if (Objects.requireNonNull(mTabLayout.getTabAt(1)).getCustomView() == null && SDKManager.getInstance().getCallAdaptor().getNumOfCalls() > 0 )
Objects.requireNonNull(mTabLayout.getTabAt(1)).setCustomView(tabOne);
}else if( SDKManager.getInstance().getDeskPhoneServiceAdaptor().getConfigBooleanParam(ConfigParametersNames.ENABLE_FAVORITES) == true && SDKManager.getInstance().getDeskPhoneServiceAdaptor().getConfigBooleanParam(ConfigParametersNames.ENABLE_CALL_LOG) != true ) {
if ( ( mTabLayout.getTabAt(2)!=null && Objects.requireNonNull(mTabLayout.getTabAt(2)).getCustomView() == null && (SDKManager.getInstance().getCallAdaptor().getNumOfCalls() == 0) || !mSectionsPagerAdapter.isCallAddParticipant()))
Objects.requireNonNull(mTabLayout.getTabAt(2)).setCustomView(tabOne);
else if ( mTabLayout.getTabAt(1)!=null && Objects.requireNonNull(mTabLayout.getTabAt(1)).getCustomView() == null && SDKManager.getInstance().getCallAdaptor().getNumOfCalls() > 0 )
Objects.requireNonNull(mTabLayout.getTabAt(1)).setCustomView(tabOne);
}else if( SDKManager.getInstance().getDeskPhoneServiceAdaptor().getConfigBooleanParam(ConfigParametersNames.ENABLE_FAVORITES) != true && SDKManager.getInstance().getDeskPhoneServiceAdaptor().getConfigBooleanParam(ConfigParametersNames.ENABLE_CALL_LOG) == true ) {
if ( ( mTabLayout.getTabAt(1)!=null && Objects.requireNonNull(mTabLayout.getTabAt(1)).getCustomView() == null && (SDKManager.getInstance().getCallAdaptor().getNumOfCalls() == 0) || !mSectionsPagerAdapter.isCallAddParticipant()))
Objects.requireNonNull(mTabLayout.getTabAt(1)).setCustomView(tabOne);
else if ( mTabLayout.getTabAt(0)!=null && Objects.requireNonNull(mTabLayout.getTabAt(0)).getCustomView() == null && SDKManager.getInstance().getCallAdaptor().getNumOfCalls() > 0 )
Objects.requireNonNull(mTabLayout.getTabAt(0)).setCustomView(tabOne);
}else if( SDKManager.getInstance().getDeskPhoneServiceAdaptor().getConfigBooleanParam(ConfigParametersNames.ENABLE_FAVORITES) != true && SDKManager.getInstance().getDeskPhoneServiceAdaptor().getConfigBooleanParam(ConfigParametersNames.ENABLE_CALL_LOG) != true ) {
if ( ( mTabLayout.getTabAt(1)!=null && Objects.requireNonNull(mTabLayout.getTabAt(1)).getCustomView() == null && (SDKManager.getInstance().getCallAdaptor().getNumOfCalls() == 0) || !mSectionsPagerAdapter.isCallAddParticipant()))
Objects.requireNonNull(mTabLayout.getTabAt(1)).setCustomView(tabOne);
else if ( mTabLayout.getTabAt(0)!=null && Objects.requireNonNull(mTabLayout.getTabAt(0)).getCustomView() == null && SDKManager.getInstance().getCallAdaptor().getNumOfCalls() > 0 )
Objects.requireNonNull(mTabLayout.getTabAt(0)).setCustomView(tabOne);
}
}
private void contactsTabFilterMenuListnerSetup(View v){
try{
if(showingFirst == true){
FragmentManager fragmentManager = MainActivityK155.this.getSupportFragmentManager();
List<Fragment> fragments = fragmentManager.getFragments();
for(Fragment fragment : fragments){
if(fragment != null && fragment.isVisible())
if (fragment instanceof ContactsFragment && ((ContactsFragment) fragment).isUserVisibleHint()) {
((ContactsFragment) fragment).hideMenus();
tabSelector.setImageResource(R.drawable.triangle_copy);
showingFirst = false;
break;
}
}
}else{
try {
FragmentManager fragmentManager = MainActivityK155.this.getSupportFragmentManager();
List<Fragment> fragments = fragmentManager.getFragments();
for (Fragment fragment : fragments) {
if (fragment != null && fragment.isVisible())
if (fragment instanceof ContactsFragment && ((ContactsFragment) fragment).isUserVisibleHint() && !fragment.isDetached()) {
((ContactsFragment) fragment).onClick(v);
tabSelector.setImageResource(R.drawable.triangle);
showingFirst = true;
break;
}
}
}catch (Exception e){
e.printStackTrace();
}
}
}catch (Exception e){
e.printStackTrace();
}
}
@Override
void backDeviceLogic(Tabs selectedTab){
CallStatusFragment callStatusFragment = (CallStatusFragment) getSupportFragmentManager().findFragmentByTag(CallStateEventHandler.CALL_STATUS_TAG);
int mNumActiveCalls = mCallStateEventHandler.mCalls.size();
assert callStatusFragment != null;
if( Objects.requireNonNull(callStatusFragment.getView()).getVisibility()!=View.VISIBLE && mNumActiveCalls>0 && !isFragmentVisible(ACTIVE_CALL_FRAGMENT)) {
callStatusFragment.showCallStatus();
}
if (selectedTab == Tabs.History) {
mSectionsPagerAdapter.getFragmentCallHistory().hideMenus();
filterButton.setVisibility(View.VISIBLE);
}
}
void onClickUser(){
mLastClickTime = SystemClock.elapsedRealtime();
mUser.setContentDescription(mLoggedUserExtension.getText().toString() + " " + mLoggedUserNumber.getText().toString() + " " + getString(R.string.user_content_description));
mSlideSelecAudioDevice.collapse(mToggleAudioMenu);
if (mListPreferences.getVisibility() == View.GONE || mListPreferences.getVisibility() == View.INVISIBLE) {
mSlideUserPreferences.expand(mListPreferences);
mFrameAll.setVisibility(View.VISIBLE);
mHandler.postDelayed(mLayoutCloseRunnable, Constants.LAYOUT_DISAPPEAR_TIME);
mOpenUser.setImageDrawable(getDrawable(R.drawable.ic_expand_less));
} else {
mOpenUser.setImageDrawable(getDrawable(R.drawable.ic_expand_more));
mSlideUserPreferences.collapse(mListPreferences);
mHandler.removeCallbacks(mLayoutCloseRunnable);
}
}
void onClickTransducerButton(){
mSlideUserPreferences.collapse(mListPreferences);
if (mToggleAudioMenu.getVisibility() == View.VISIBLE) {
mSlideSelecAudioDevice.collapse(mToggleAudioMenu);
mHandler.removeCallbacks(mLayoutCloseRunnable);
} else {
mSlideSelecAudioDevice.expand(mToggleAudioMenu);
mFrameAll.setVisibility(View.VISIBLE);
mHandler.postDelayed(mLayoutCloseRunnable, Constants.LAYOUT_DISAPPEAR_TIME);
}
}
@Override
void onClickSearchButton(){
if ((mToggleAudioMenu.getVisibility() == View.INVISIBLE || mToggleAudioMenu.getVisibility() == View.GONE && mListPreferences.getVisibility() == View.GONE)) {
changeUiForFullScreenInLandscape(true);
mSectionsPagerAdapter.getFragmentContacts().searchLayout.setVisibility(View.VISIBLE);
mSectionsPagerAdapter.getFragmentContacts().mAdd.setVisibility(View.INVISIBLE);
mSectionsPagerAdapter.getFragmentContacts().mSearchView.setQuery("", false);
mSectionsPagerAdapter.getFragmentContacts().mSearchView.requestFocus();
Utils.openKeyboard(this);
mSectionsPagerAdapter.getFragmentContacts().hideMenus();
tabSelector.setImageResource(R.drawable.triangle_copy);
showingFirst = false;
CallStatusFragment callStatusFragment_search_button = (CallStatusFragment) getSupportFragmentManager().findFragmentByTag(CallStateEventHandler.CALL_STATUS_TAG);
assert callStatusFragment_search_button != null;
if (Objects.requireNonNull(callStatusFragment_search_button.getView()).getVisibility() == View.VISIBLE) {
callStatusFragment_search_button.hideCallStatus();
Utils.hideKeyboard(this);
}
mViewPager.setEnabledSwipe(false);
}
}
@Override
void changeUIFor155(){
FragmentManager fragmentManager = MainActivityK155.this.getSupportFragmentManager();
List<Fragment> fragments = fragmentManager.getFragments();
for (Fragment fragment : fragments) {
if (fragment != null && fragment.isVisible())
if (fragment instanceof VideoCallFragment && !fragment.isDetached()) {
changeUiForFullScreenInLandscape(true);
break;
} else {
changeUiForFullScreenInLandscape(false);
}
}
}
void collapseSlideSelecAudioDevice(){
mSlideSelecAudioDevice.collapse(mToggleAudioMenu);
}
void collapseSlideUserPreferences(){
mSlideUserPreferences.collapse(mListPreferences);
}
void collapseSlideSelectPhoneNumber(){
mSlideSelectPhoneNumber.collapse(mSelectPhoneNumber);
}
@Override
void setTransducerButtonCheckedFor155(){
FragmentManager fragmentManager = MainActivityK155.this.getSupportFragmentManager();
List<Fragment> fragments = fragmentManager.getFragments();
for(Fragment fragment : fragments){
if(fragment != null && fragment.isVisible())
if (fragment instanceof DialerFragment) {
((DialerFragment) fragment).transducerButton.setChecked(false);
}else if (fragment instanceof ActiveCallFragment){
((ActiveCallFragment) fragment).transducerButton.setChecked(false);
}
}
}
@Override
protected void setBackgroundResource(int resId){
if (isFragmentVisible(DIALER_FRAGMENT)) {
((DialerFragment) getVisibleFragment(DIALER_FRAGMENT)).offHook.setBackgroundResource(resId);
}
ActiveCallFragment fragment = (ActiveCallFragment) (getSupportFragmentManager().findFragmentByTag(CallStateEventHandler.ACTIVE_CALL_TAG));
if (fragment != null) {
fragment.offHook.setBackgroundResource(resId);
}
}
@Override
void OnCallEndedChangeUIForDevice(){
try {
if (isFragmentVisible(DIALER_FRAGMENT)) {
((DialerFragment) getVisibleFragment(DIALER_FRAGMENT)).offHook.setChecked(false);
((DialerFragment) getVisibleFragment(DIALER_FRAGMENT)).setMode(DialerFragment.DialMode.EDIT);
}
}catch (NullPointerException e){
e.printStackTrace();
}
searchAddFilterIconViewController();
Tabs selectedTab = Tabs.Favorites;
for (Tabs t : mTabIndexMap.keySet()) {
if (mViewPager!=null && mViewPager.getCurrentItem() == mTabIndexMap.get(t)) {
selectedTab = t;
}
}
if(selectedTab== Tabs.Contacts) {
if (isFragmentVisible(CONTACTS_FRAGMENT))
mSectionsPagerAdapter.getFragmentContacts().removeSearchResults();
}
if (isFragmentVisible(CONTACTS_DETAILS_FRAGMENT) || isFragmentVisible(CONTACTS_EDIT_FRAGMENT)){
changeUiForFullScreenInLandscape(true);
}
else {
changeUiForFullScreenInLandscape(false);
}
}
@Override
void OnCallEndedChangesForDevice(){
hideMenus();
checkFilterButtonState();
}
/**
* Setting {@link ToggleButton} for audio selection on or off based on parameters provided
*
* @param isOn boolean based on which {@link ToggleButton} is set
*/
@Override
public void setOffhookButtosChecked(boolean isOn) {
mSelectAudio.setChecked(isOn);
if (mSectionsPagerAdapter.getDialerFragment() != null && mSectionsPagerAdapter.getDialerFragment().offHook != null){
mSectionsPagerAdapter.getDialerFragment().offHook.setChecked(isOn);
}
ActiveCallFragment fragment = (ActiveCallFragment) (getSupportFragmentManager().findFragmentByTag(CallStateEventHandler.ACTIVE_CALL_TAG));
if (fragment != null && fragment.offHook != null) {
fragment.offHook.setChecked(isOn);
}
}
@Override
public void setOffHookButtonsBasedCallState(int callId, UICallState state){
boolean isChecked=false;
int offhookCallId = SDKManager.getInstance().getCallAdaptor().getOffhookCallId();
if (offhookCallId != 0 && offhookCallId != callId)
isChecked=true;
else if (state == ESTABLISHED || state == REMOTE_ALERTING || state ==FAILED || state==TRANSFERRING) {
isChecked=true;
}
setOffhookButtosChecked(isChecked);
}
void onDeviceChangedDeviceLogic(int resId, boolean active){
if (mSectionsPagerAdapter.getDialerFragment() != null && mSectionsPagerAdapter.getDialerFragment().offHook != null){
if(isFragmentVisible(CONTACTS_DETAILS_FRAGMENT)==true) {
((ContactDetailsFragment) getVisibleFragment(CONTACTS_DETAILS_FRAGMENT)).isBackORDeletePressed = true;
}
mSectionsPagerAdapter.getDialerFragment().offHook.setChecked(active);
mSectionsPagerAdapter.getDialerFragment().offHook.setBackgroundResource(resId);
}
ActiveCallFragment fragment = (ActiveCallFragment) (getSupportFragmentManager().findFragmentByTag(CallStateEventHandler.ACTIVE_CALL_TAG));
if (fragment != null && fragment.offHook != null) {
fragment.offHook.setChecked(active);
fragment.offHook.setBackgroundResource(resId);
}
}
@Override
void prepareOffhookChangeUIforDevice(){
if(!isFragmentVisible(ACTIVE_VIDEO_CALL_FRAGMENT)
&& isFragmentVisible(CONTACTS_FRAGMENT) == false
&& (getVisibleFragment(CONTACTS_FRAGMENT))!=null
&& ((ContactsFragment) getVisibleFragment(CONTACTS_FRAGMENT)).isSearchLayoutVisible() ==false)
{
changeUiForFullScreenInLandscape(false);
}
if (isFragmentVisible(CONTACTS_DETAILS_FRAGMENT) && (SDKManager.getInstance().getCallAdaptor().getActiveCallIdWithoutOffhook()) == 0)
((ContactDetailsFragment) getVisibleFragment(CONTACTS_DETAILS_FRAGMENT)). mBackListener.back();
}
@Override
void onIncomingCallEndedCahngeUIForDevice(){
searchAddFilterIconViewController();
if( (isFragmentVisible(CONTACTS_DETAILS_FRAGMENT) || isFragmentVisible(CONTACTS_EDIT_FRAGMENT) || isFragmentVisible(ACTIVE_VIDEO_CALL_FRAGMENT)) && !isFragmentVisible(DIALER_FRAGMENT) ){
changeUiForFullScreenInLandscape(true);
if( isFragmentVisible(ACTIVE_CALL_FRAGMENT) && !isFragmentVisible(ACTIVE_VIDEO_CALL_FRAGMENT))
changeUiForFullScreenInLandscape(false);
}else if( (isFragmentVisible(CONTACTS_DETAILS_FRAGMENT) || isFragmentVisible(CONTACTS_EDIT_FRAGMENT) || isFragmentVisible(ACTIVE_VIDEO_CALL_FRAGMENT)) ) {
changeUiForFullScreenInLandscape(true);
}else if ( mSectionsPagerAdapter.getFragmentContacts() != null && mSectionsPagerAdapter.getFragmentContacts().isSearchLayoutVisible()){
changeUiForFullScreenInLandscape(true);
}else{
changeUiForFullScreenInLandscape(false);
}
}
@Override
void onIncomingCallStartedDeviceLogic(){
hideMenus();
checkFilterButtonState();
if(isFragmentVisible(CONTACTS_FRAGMENT) && (getVisibleFragment(CONTACTS_FRAGMENT)) !=null){
((ContactsFragment) getVisibleFragment(CONTACTS_FRAGMENT)).handleIncomingCall();
}
if(isFragmentVisible(HISTORY_FRAGMENT) && getVisibleFragment(HISTORY_FRAGMENT) != null){
((CallHistoryFragment) getVisibleFragment(HISTORY_FRAGMENT)).handleIncomingCall();
}
}
@Override
boolean onBackPressedDeviceLogic(){
if (isToBlockBakcPress == true){
isToBlockBakcPress = false;
return false;
}
return true;
}
@Override
protected void setVideoControlsVisibility(int visible) {
if (mSectionsPagerAdapter.getDialerFragment() != null)
mSectionsPagerAdapter.getDialerFragment().setVideoButtonVisibility(visible);
}
/**
* Set appropriate state for add contact button on K155 devices
*/
private void setAddContactVisibility() {
if (Utils.isModifyContactsEnabled() && !mSectionsPagerAdapter.isCallAddParticipant()) {
addcontactButton.setVisibility(View.VISIBLE);
} else {
addcontactButton.setVisibility(View.INVISIBLE);
}
}
}
| UTF-8 | Java | 49,541 | java | MainActivityK155.java | Java | []
| null | []
| package com.avaya.android.vantage.aaadevbroadcast.activities;
import android.app.Dialog;
import android.app.KeyguardManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import androidx.annotation.NonNull;
import com.avaya.android.vantage.aaadevbroadcast.views.DialogAAADEVMessages;
import com.google.android.material.tabs.TabLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.RelativeLayout;
import android.widget.ToggleButton;
import com.avaya.android.vantage.aaadevbroadcast.Constants;
import com.avaya.android.vantage.aaadevbroadcast.ElanApplication;
import com.avaya.android.vantage.aaadevbroadcast.R;
import com.avaya.android.vantage.aaadevbroadcast.Utils;
import com.avaya.android.vantage.aaadevbroadcast.callshistory.CallHistoryFragment;
import com.avaya.android.vantage.aaadevbroadcast.contacts.ContactsFragment;
import com.avaya.android.vantage.aaadevbroadcast.csdk.CallAdaptor;
import com.avaya.android.vantage.aaadevbroadcast.csdk.ConfigParametersNames;
import com.avaya.android.vantage.aaadevbroadcast.csdk.SDKManager;
import com.avaya.android.vantage.aaadevbroadcast.fragments.ActiveCallFragment;
import com.avaya.android.vantage.aaadevbroadcast.fragments.CallStatusFragment;
import com.avaya.android.vantage.aaadevbroadcast.fragments.ContactDetailsFragment;
import com.avaya.android.vantage.aaadevbroadcast.fragments.ContactEditFragment;
import com.avaya.android.vantage.aaadevbroadcast.fragments.DialerFragment;
import com.avaya.android.vantage.aaadevbroadcast.fragments.VideoCallFragment;
import com.avaya.android.vantage.aaadevbroadcast.fragments.JoinMeetingFragment;
import com.avaya.android.vantage.aaadevbroadcast.model.UIAudioDevice;
import com.avaya.android.vantage.aaadevbroadcast.model.UICallState;
import com.avaya.android.vantage.aaadevbroadcast.views.adapters.CallStateEventHandler;
import com.avaya.android.vantage.aaadevbroadcast.views.interfaces.IHardButtonListener;
import com.avaya.deskphoneservices.HardButtonType;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import static com.avaya.android.vantage.aaadevbroadcast.Constants.DigitKeys;
import static com.avaya.android.vantage.aaadevbroadcast.model.UICallState.ESTABLISHED;
import static com.avaya.android.vantage.aaadevbroadcast.model.UICallState.FAILED;
import static com.avaya.android.vantage.aaadevbroadcast.model.UICallState.REMOTE_ALERTING;
import static com.avaya.android.vantage.aaadevbroadcast.model.UICallState.TRANSFERRING;
public class MainActivityK155 extends BaseActivity implements IHardButtonListener {
private static final String TAG = "MainActivityK155";
private RelativeLayout tabOne;
private RelativeLayout tabSelectorWrapper;
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(newBase);
Utils.overrideFontScaleAndDensityK155(this);
}
/**
* key up event received from platform via MEDIA_BUTTON intent
*
* @param hardButton
*/
@Override
public void onKeyUp(@NonNull HardButtonType hardButton) {
//test for K155 special buttons:
try {
UIAudioDevice activeAudioDevice = mAudioDeviceViewAdaptor.getActiveAudioDevice();
int activeCallId = SDKManager.getInstance().getCallAdaptor().getActiveCallId();
ToggleButton dialerOffHook = mSectionsPagerAdapter.getDialerFragment().offHook;
KeyguardManager kgMgr = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
boolean isLocked = (kgMgr != null) && kgMgr.isDeviceLocked() && !ElanApplication.isPinAppLock;
switch (hardButton) {
case AUDIO_MUTE://video mute
if (mAudioMute.isEnabled()) {
Log.d(TAG, "PHYSICAL KEY AUDIO MUTE");
mAudioMute.performClick();
}
break;
case VIDEO_MUTE://video mute
if (mVideoMute.isEnabled()) {
Log.d(TAG, "PHYSICAL KEY VIDEO MUTE");
mVideoMute.performClick();
}
break;
case SPEAKER://speaker
Log.d(TAG, "PHYSICAL KEY SPEAKER HOOK");
if (isLocked && (SDKManager.getInstance().getCallAdaptor().getNumOfCalls() == 0)) {
Log.v(TAG, "cancel off hook on lock");
return;
}
mAudioDeviceViewAdaptor.setUserRequestedDevice(UIAudioDevice.SPEAKER);
updateAudioSelectionUI(UIAudioDevice.SPEAKER);
saveAudioSelection(Constants.AUDIO_PREF_KEY, UIAudioDevice.SPEAKER.toString());
if (!dialerOffHook.isChecked() && (activeCallId == 0)) {
if (SDKManager.getInstance().getCallAdaptor().isAlertingCall() == 0) {
prepareOffHook();
}
try {
if (isFragmentVisible(DIALER_FRAGMENT)) {
((DialerFragment) getVisibleFragment(DIALER_FRAGMENT)).offHook.performClick();
changeUiForFullScreenInLandscape(false);
if (isFragmentVisible(CONTACTS_DETAILS_FRAGMENT))
((ContactDetailsFragment) getVisibleFragment(CONTACTS_DETAILS_FRAGMENT)). mBackListener.back();
}
} catch (NullPointerException e) {
e.printStackTrace();
}
} else if ((activeAudioDevice == UIAudioDevice.SPEAKER)) {
if (activeCallId > 0) {
SDKManager.getInstance().getCallAdaptor().endCall(activeCallId);
try {
if (isFragmentVisible(DIALER_FRAGMENT) && !isFragmentVisible(ACTIVE_VIDEO_CALL_FRAGMENT)) {
changeUiForFullScreenInLandscape(false);
if (isFragmentVisible(CONTACTS_DETAILS_FRAGMENT))
((ContactDetailsFragment) getVisibleFragment(CONTACTS_DETAILS_FRAGMENT)). mBackListener.back();
}
} catch (NullPointerException e) {
e.printStackTrace();
}
try {
if (isFragmentVisible(DIALER_FRAGMENT))
((DialerFragment) getVisibleFragment(DIALER_FRAGMENT)).setMode(DialerFragment.DialMode.EDIT);
} catch (NullPointerException e) {
e.printStackTrace();
}
} else if (dialerOffHook.isChecked()) {
resetDialer();
mSectionsPagerAdapter.getDialerFragment().offHook.performClick();
}
} else {
Log.w(TAG, "onKeyUp SPEAKER: unexpected state activeCallId=" + activeCallId + " activeAudioDevice=" + activeAudioDevice + " dialerOffHook.isChecked()=" + dialerOffHook.isChecked());
}
break;
case HEADSET://transducer
Log.d(TAG, "PHYSICAL KEY TRANSDUCER SELECTION");
if (isLocked && (SDKManager.getInstance().getCallAdaptor().getNumOfCalls() == 0)) {
Log.v(TAG, "cancel off hook on lock");
return;
}
int device = getHeadsetByPriority();
String prefValue = mSharedPref.getString(Constants.AUDIO_PREF_KEY, (UIAudioDevice.SPEAKER).toString());
assert prefValue != null;
UIAudioDevice savedDevice = UIAudioDevice.valueOf(prefValue.toUpperCase());
List<UIAudioDevice> devices = Arrays.asList(UIAudioDevice.BLUETOOTH_HEADSET, UIAudioDevice.RJ9_HEADSET, UIAudioDevice.WIRED_HEADSET, UIAudioDevice.WIRED_USB_HEADSET);
if (devices.contains(savedDevice)) {
device = savedDevice.getUIId();
}
if (!dialerOffHook.isChecked() && (activeCallId == 0)) {
prepareOffHook();
this.onClick(findViewById(device));
try {
if (isFragmentVisible(DIALER_FRAGMENT)) {
((DialerFragment) getVisibleFragment(DIALER_FRAGMENT)).offHook.performClick();
changeUiForFullScreenInLandscape(false);
if (isFragmentVisible(CONTACTS_DETAILS_FRAGMENT))
((ContactDetailsFragment) getVisibleFragment(CONTACTS_DETAILS_FRAGMENT)). mBackListener.back();
}
} catch (NullPointerException e) {
e.printStackTrace();
}
} else if (dialerOffHook.isChecked() && (activeAudioDevice != UIAudioDevice.SPEAKER) && (activeAudioDevice != UIAudioDevice.HANDSET) && (activeAudioDevice != UIAudioDevice.WIRELESS_HANDSET)) { //there is active call via Headset
if (activeCallId > 0) {
SDKManager.getInstance().getCallAdaptor().endCall(activeCallId);
try {
if (isFragmentVisible(DIALER_FRAGMENT)) {
changeUiForFullScreenInLandscape(false);
if (isFragmentVisible(CONTACTS_DETAILS_FRAGMENT))
((ContactDetailsFragment) getVisibleFragment(CONTACTS_DETAILS_FRAGMENT)). mBackListener.back();
}
} catch (NullPointerException e) {
e.printStackTrace();
}
} else {
resetDialer();
try {
if (isFragmentVisible(DIALER_FRAGMENT)) {
((DialerFragment) getVisibleFragment(DIALER_FRAGMENT)).offHook.performClick();
changeUiForFullScreenInLandscape(false);
if (isFragmentVisible(CONTACTS_DETAILS_FRAGMENT))
((ContactDetailsFragment) getVisibleFragment(CONTACTS_DETAILS_FRAGMENT)). mBackListener.back();
}
} catch (NullPointerException e) {
e.printStackTrace();
}
}
} else if (activeCallId > 0 && (activeAudioDevice == UIAudioDevice.SPEAKER || activeAudioDevice == UIAudioDevice.HANDSET || activeAudioDevice == UIAudioDevice.WIRELESS_HANDSET)) { // there is an active call on speaker and headset was pressed
View transientView = new View(this);
transientView.setId(device);
onClick(transientView);
} else if (activeCallId > 0 && SDKManager.getInstance().getCallAdaptor().getCall(activeCallId).getState() == UICallState.NOT_RELEVANT) {
SDKManager.getInstance().getCallAdaptor().endCall(activeCallId);
} else {
Log.w(TAG, "onKeyUp HEADSET: unexpected state activeCallId=" + activeCallId + " activeAudioDevice=" + activeAudioDevice + " dialerOffHook.isChecked()=" + dialerOffHook.isChecked());
}
break;
}
}catch (NullPointerException e){
Log.e(TAG, "NPE in onKeyUp(@NonNull HardButtonType hardButton):", e);
}
}
@NonNull
private int getHeadsetByPriority() {
/*Bluetooth headset (if paired and connected)
USB wired headset (if connected)
3.5mm wired headset (if connected)
RJ9 headset (connection state is a don't care)*/
int device = R.id.containerHeadset;
for (UIAudioDevice uiAudioDevice : mAudioDeviceViewAdaptor.getAudioDeviceList()) {
if (uiAudioDevice == UIAudioDevice.BLUETOOTH_HEADSET) {
device = R.id.containerBTHeadset;
break;
}
if (uiAudioDevice == UIAudioDevice.WIRED_USB_HEADSET) {
device = R.id.containerUsbHeadset;
}
if ((device != R.id.containerUsbHeadset) && (uiAudioDevice == UIAudioDevice.WIRED_HEADSET)) {
device = R.id.container35Headset;
}
}
return device;
}
/**
* key down event received from platform via MEDIA_BUTTON intent
*
* @param hardButton
*/
@Override
public void onKeyDown(@NonNull HardButtonType hardButton) {
if (!ElanApplication.isMainActivityVisible()) {
Intent intent = new Intent(this, MainActivityK155.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(MainActivityK155.BRING_TO_FOREGROUND_INTENT);
intent.putExtra(HARD_BUTTON, hardButton);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
try {
pendingIntent.send();
} catch (PendingIntent.CanceledException e) {
Log.e(TAG, "failed to activate MainActivity from pending intent while it was not visible");
}
setIntent(null);
}
}
@Override
void tabLayoutAddOnTabSelectedListener(){
Log.d(TAG, "tabLayoutAddOnTabSelectedListener");
mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
Log.v("TabTest", "onTabSelected");
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
Log.v("TabTest", "onTabUnselected");
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
contactsTabFilterMenuListnerSetup(tabSelectorWrapper);
}
});
mVideoMute.setVisibility(View.INVISIBLE);
}
@Override
protected void initMoreViews() {
tabOne = (RelativeLayout) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
searchButton = findViewById(R.id.search_button);
addcontactButton = findViewById(R.id.addcontact_button);
filterButton = findViewById(R.id.filterRecent);
filterButton.setImageResource(R.drawable.ic_expand_more);
}
/**
* Modifies the UI to adopt screen orientation
* @param show
*/
@Override
public void changeUiForFullScreenInLandscape(boolean show){
try {
if (show) {
mBrandView.setVisibility(View.GONE);
mUser.setVisibility(View.GONE);
mStatusLayout.setVisibility(View.GONE);
mOpenUser.setVisibility(View.GONE);
mErrorStatus.setVisibility(View.GONE);
appBar.setVisibility(View.INVISIBLE);
appBar.getLayoutParams().height = 0;
mTabLayout.setVisibility(View.GONE);
mTabLayout.getLayoutParams().height = 0;
dialerView.setVisibility(View.GONE);
mViewPager.getLayoutParams().height = 675;
} else {
mBrandView.setVisibility(View.VISIBLE);
mUser.setVisibility(View.VISIBLE);
mStatusLayout.setVisibility(View.VISIBLE);
mOpenUser.setVisibility(View.VISIBLE);
mErrorStatus.setVisibility(View.VISIBLE);
appBar.setVisibility(View.VISIBLE);
appBar.getLayoutParams().height = 100;
mTabLayout.setVisibility(View.VISIBLE);
mTabLayout.getLayoutParams().height = 100;
dialerView.setVisibility(View.GONE);
mViewPager.getLayoutParams().height = 430;
}
checkForErrors();
}catch (Exception e){
e.printStackTrace();
}
}
@Override
protected void initViewPager() {
mUIDeskphoneServiceAdaptor.setHardButtonListener(this);
super.initViewPager();
}
protected void onPageScrolledLogic(){
if (mTabLayout.getVisibility()==View.GONE && (isFragmentVisible(CONTACTS_DETAILS_FRAGMENT) || isFragmentVisible(CONTACTS_EDIT_FRAGMENT)) )
mViewPager.setEnabledSwipe(false);
else
mViewPager.setEnabledSwipe(true);
}
protected void onPageSelectedCondition() {
if (mSectionsPagerAdapter.getFragmentContacts() != null && mSectionsPagerAdapter.getFragmentContacts().mSearchView != null && mSectionsPagerAdapter.getFragmentContacts().mSearchView.getVisibility() == View.VISIBLE) {
if (isFragmentVisible(CONTACTS_FRAGMENT) && !isFragmentVisible(CONTACTS_EDIT_FRAGMENT))
mSectionsPagerAdapter.getFragmentContacts().removeSearchResults();
}
}
@Override
public void changeButtonsVisibility(Tabs tab){
switch (tab) {
case Dialer:
case Favorites:
searchButton.setVisibility(View.INVISIBLE);
addcontactButton.setVisibility(View.INVISIBLE);
filterButton.setVisibility(View.INVISIBLE);
return;
case Contacts:
searchButton.setVisibility(View.VISIBLE);
setAddContactVisibility();
filterButton.setVisibility(View.INVISIBLE);
return;
case History:
searchButton.setVisibility(View.INVISIBLE);
addcontactButton.setVisibility(View.INVISIBLE);
filterButton.setVisibility(View.VISIBLE);
return;
}
}
@Override
void setupMoreOnClickListenersForDevice(){
addcontactButton.setOnClickListener(this);
filterButton.setOnClickListener(this);
searchButton.setOnClickListener(this);
}
void fullScreenViewResizeLogic(int startDimension){
boolean isToResize = false;
FragmentManager fragmentManager = MainActivityK155.this.getSupportFragmentManager();
List<Fragment> fragments = fragmentManager.getFragments();
for(Fragment fragment : fragments){
if(fragment != null && fragment.isVisible() && fragment instanceof ContactDetailsFragment ) {
isToResize = true;
break;
}else if ( fragment != null && fragment.isVisible() && fragment instanceof ContactsFragment){
if( ((ContactsFragment) fragment).isSearchLayoutVisible() ){
isToResize = true;
break;
}
}
}
if(!isToResize) {
if(mViewPager!=null && mViewPager.getLayoutParams()!=null)
mViewPager.getLayoutParams().height = 430;
}
}
int onKeyDownDeviceLogic(int keyCode, KeyEvent event){
if (!isToLockPressButton) {
try {
if(isFragmentVisible(CONTACTS_DETAILS_FRAGMENT)||isFragmentVisible(CONTACTS_EDIT_FRAGMENT) || isFragmentVisible(JOIN_MEETING_FRAGMENT)){
isToBlockBakcPress = true;
}
isToLockPressButton = true;
int keyunicode = event.getUnicodeChar(event.getMetaState());
char character = (char) keyunicode;
String digit = "" + character;
if(keyCode == KeyEvent.KEYCODE_BACK && !isLockState(this)) {
if (mSelectPhoneNumber.getVisibility() == View.VISIBLE) {
mSlideSelectPhoneNumber.collapse(mSelectPhoneNumber);
}
try {
if (((ActiveCallFragment) getVisibleFragment(ACTIVE_CALL_FRAGMENT)).mMoreCallFeatures.getVisibility() == View.VISIBLE) {
((ActiveCallFragment) getVisibleFragment(ACTIVE_CALL_FRAGMENT)).mMoreCallFeaturesClick();
return 1;
}
}catch (Exception e){
e.printStackTrace();
}
mViewPager.setEnabledSwipe(true);
if (!isFragmentVisible(ACTIVE_CALL_FRAGMENT) && !isFragmentVisible(ACTIVE_VIDEO_CALL_FRAGMENT)) {
changeUiForFullScreenInLandscape(false);
if (isFragmentVisible(CONTACTS_EDIT_FRAGMENT)) {
((ContactEditFragment) getVisibleFragment(CONTACTS_EDIT_FRAGMENT)).cancelOnClickListener();
//changeUiForFullScreenInLandscape(true);
} else if (isFragmentVisible(CONTACTS_DETAILS_FRAGMENT)) {
((ContactDetailsFragment) getVisibleFragment(CONTACTS_DETAILS_FRAGMENT)).mDeletePopUp.setVisibility(View.GONE);
((ContactDetailsFragment) getVisibleFragment(CONTACTS_DETAILS_FRAGMENT)).mBackListener.back();
changeUiForFullScreenInLandscape(false);
} else if (isFragmentVisible(JOIN_MEETING_FRAGMENT)){
((JoinMeetingFragment) getVisibleFragment(JOIN_MEETING_FRAGMENT)).onBackPressed();
}
if(isFragmentVisible(CONTACTS_FRAGMENT) && ((ContactsFragment) getVisibleFragment(CONTACTS_FRAGMENT)).isSearchLayoutVisible()){
((ContactsFragment) getVisibleFragment(CONTACTS_FRAGMENT)).removeSearchResults();
CallStatusFragment callStatusFragment = (CallStatusFragment) getSupportFragmentManager().findFragmentByTag(CallStateEventHandler.CALL_STATUS_TAG);
assert callStatusFragment != null;
if( (Objects.requireNonNull(callStatusFragment.getView()).getVisibility()==View.INVISIBLE || callStatusFragment.getView().getVisibility()==View.GONE) && SDKManager.getInstance().getCallAdaptor().hasActiveHeldOrInitiatingCall()) {
callStatusFragment.showCallStatus();
}
return 0;
}
}else if (mCallViewAdaptor.getNumOfCalls() < CallAdaptor.MAX_NUM_CALLS){
((ActiveCallFragment) getVisibleFragment(ACTIVE_CALL_FRAGMENT)).mBackArrowOnClickListener();
//changeUiForFullScreenInLandscape(false);
return 1;
}
}
if(isFragmentVisible(DIALER_FRAGMENT) && mSectionsPagerAdapter!=null && mSectionsPagerAdapter.getDialerFragment()!=null ) {
if (digit.matches("[\\d]") || digit.matches("#") || digit.matches("\\*")) {
if(!isFragmentVisible(CONTACTS_EDIT_FRAGMENT) && !isFragmentVisible(JOIN_MEETING_FRAGMENT))
mSectionsPagerAdapter.getDialerFragment().dialFromKeyboard(digit);
} else if (event.getKeyCode() == KeyEvent.KEYCODE_DEL) {
mSectionsPagerAdapter.getDialerFragment().deleteDigit();
}
}
if (DigitKeys.contains(event.getKeyCode()) &&
( (getVisibleFragment(CONTACTS_FRAGMENT))==null || (getVisibleFragment(CONTACTS_FRAGMENT))!=null &&((ContactsFragment) getVisibleFragment(CONTACTS_FRAGMENT)).isSearchLayoutVisible() ==false ) ) {
if (keyCode != KeyEvent.KEYCODE_0) {
// mSectionsPagerAdapter.getDialerFragment().onHardKeyClick(digit);
if( getVisibleFragment(ACTIVE_CALL_FRAGMENT) !=null && !((ActiveCallFragment) getVisibleFragment(ACTIVE_CALL_FRAGMENT)).mHoldCallButton.isChecked()) {
((ActiveCallFragment) getVisibleFragment(ACTIVE_CALL_FRAGMENT)).sendDTMF(digit.charAt(0));
}else{
if(isFragmentVisible(CONTACTS_EDIT_FRAGMENT)==false)
mSectionsPagerAdapter.getDialerFragment().onHardKeyClick(digit);
}
}else {
zeroOrPlus = "0";
}
mViewPager.setCurrentItem(0, false);
searchButton.setVisibility(View.INVISIBLE);
addcontactButton.setVisibility(View.INVISIBLE);
try {
if (isFragmentVisible(DIALER_FRAGMENT) && isFragmentVisible(CONTACTS_DETAILS_FRAGMENT) ) {
changeUiForFullScreenInLandscape(false);
((ContactDetailsFragment) getVisibleFragment(CONTACTS_DETAILS_FRAGMENT)). mBackListener.back();
}
} catch (NullPointerException e) {
e.printStackTrace();
}
if (isFragmentVisible(ACTIVE_VIDEO_CALL_FRAGMENT) || isFragmentVisible(CONTACTS_DETAILS_FRAGMENT) || isFragmentVisible(CONTACTS_EDIT_FRAGMENT)) {
changeUiForFullScreenInLandscape(true);
}
event.startTracking();
return 1;
}
}catch (Exception e){
e.printStackTrace();
}
}
return -1;
}
@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
try {
if (keyCode == KeyEvent.KEYCODE_0) {
if (isFragmentVisible(DIALER_FRAGMENT) && mSectionsPagerAdapter != null && mSectionsPagerAdapter.getDialerFragment() != null) {
mSectionsPagerAdapter.getDialerFragment().dialFromKeyboard("+");
zeroOrPlus = "+";
}
}
}catch (Exception e){
e.printStackTrace();
}
if(DigitKeys.contains(event.getKeyCode())) {
return true;
}else
return super.onKeyLongPress(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
isToLockPressButton = false;
String key = KeyEvent.keyCodeToString(event.getKeyCode()).replace("KEYCODE_", "");
sendAccessibilityEvent(key, findViewById(R.id.dialer_display));
if (keyCode == KeyEvent.KEYCODE_0) {
if(mSectionsPagerAdapter!=null && mSectionsPagerAdapter.getDialerFragment()!=null ) {
//mSectionsPagerAdapter.getDialerFragment().onHardKeyClick(zeroOrPlus);
if(getVisibleFragment(ACTIVE_CALL_FRAGMENT) !=null && !((ActiveCallFragment) getVisibleFragment(ACTIVE_CALL_FRAGMENT)).mHoldCallButton.isChecked()) {
((ActiveCallFragment) getVisibleFragment(ACTIVE_CALL_FRAGMENT)).sendDTMF(zeroOrPlus.charAt(0));
}else{
mSectionsPagerAdapter.getDialerFragment().onHardKeyClick(zeroOrPlus);
}
}
}
if(DigitKeys.contains(event.getKeyCode())) {
if(isOnKeyDownHappened == false) {
int keyunicode = event.getUnicodeChar(event.getMetaState());
char character = (char) keyunicode;
String digit = "" + character;
if (isFragmentVisible(DIALER_FRAGMENT) && mSectionsPagerAdapter != null && mSectionsPagerAdapter.getDialerFragment() != null) {
if (digit.matches("[\\d]") || digit.matches("#") || digit.matches("\\*")) {
if( (getVisibleFragment(CONTACTS_EDIT_FRAGMENT)) ==null
&& ((ContactsFragment) getVisibleFragment(CONTACTS_FRAGMENT)).isSearchLayoutVisible() ==false && getVisibleFragment(JOIN_MEETING_FRAGMENT) == null ) {
mSectionsPagerAdapter.getDialerFragment().dialFromKeyboard(digit);
}
} else if (event.getKeyCode() == KeyEvent.KEYCODE_DEL) {
mSectionsPagerAdapter.getDialerFragment().deleteDigit();
}
}
if (DigitKeys.contains(event.getKeyCode()) && getVisibleFragment(CONTACTS_FRAGMENT)!=null
&& ((ContactsFragment) getVisibleFragment(CONTACTS_FRAGMENT)).isSearchLayoutVisible() ==false
&& !isFragmentVisible(CONTACTS_EDIT_FRAGMENT)) {
if (keyCode != KeyEvent.KEYCODE_0) {
//mSectionsPagerAdapter.getDialerFragment().onHardKeyClick(digit);
if(getVisibleFragment(ACTIVE_CALL_FRAGMENT) !=null && !((ActiveCallFragment) getVisibleFragment(ACTIVE_CALL_FRAGMENT)).mHoldCallButton.isChecked()) {
((ActiveCallFragment) getVisibleFragment(ACTIVE_CALL_FRAGMENT)).sendDTMF(digit.charAt(0));
}else {
mSectionsPagerAdapter.getDialerFragment().onHardKeyClick(digit);
}
} else {
zeroOrPlus = "0";
}
mViewPager.setCurrentItem(0, false);
searchButton.setVisibility(View.INVISIBLE);
addcontactButton.setVisibility(View.INVISIBLE);
try {
if (isFragmentVisible(DIALER_FRAGMENT) && isFragmentVisible(CONTACTS_DETAILS_FRAGMENT)) {
changeUiForFullScreenInLandscape(false);
((ContactDetailsFragment) getVisibleFragment(CONTACTS_DETAILS_FRAGMENT)).mBackListener.back();
}
} catch (NullPointerException e) {
e.printStackTrace();
}
event.startTracking();
}
}
isOnKeyDownHappened = false;
return true;
}else {
return super.onKeyUp(keyCode, event);
}
}
boolean onDialerInteractionDeviceLogic(String number){
FragmentManager fragmentManager = MainActivityK155.this.getSupportFragmentManager();
List<Fragment> fragments = fragmentManager.getFragments();
for (Fragment fragment : fragments) {
if (fragment != null && fragment.isVisible())
if (fragment instanceof DialerFragment) {
mCallViewAdaptor.addDigitToOffHookDialCall(number.charAt(0));
} else if (fragment instanceof ActiveCallFragment && (((ActiveCallFragment) fragment).getCallState() == UICallState.ESTABLISHED)) {
((ActiveCallFragment) fragment).sendDTMF(number.charAt(0));
return false;
}
}
return true;
}
void expandPhoneNumberSlide(){
mSlideSelectPhoneNumber.expand(mSelectPhoneNumber);
}
void setTabIconsDeviceLogic(){
if (tabOne == null)
return;
tabImage = tabOne.findViewById(R.id.tab_image);
tabImage.setImageResource(R.drawable.ic_contacts);
tabSelector = tabOne.findViewById(R.id.tab_selector);
checkFilterButtonState();
tabSelectorWrapper = tabOne.findViewById(R.id.filter);
if (SDKManager.getInstance().getDeskPhoneServiceAdaptor().getConfigBooleanParam(ConfigParametersNames.ENABLE_FAVORITES) == true && SDKManager.getInstance().getDeskPhoneServiceAdaptor().getConfigBooleanParam(ConfigParametersNames.ENABLE_CALL_LOG) == true){
if ( (Objects.requireNonNull(mTabLayout.getTabAt(2)).getCustomView() == null && (SDKManager.getInstance().getCallAdaptor().getNumOfCalls() == 0) || !mSectionsPagerAdapter.isCallAddParticipant()))
Objects.requireNonNull(mTabLayout.getTabAt(2)).setCustomView(tabOne);
else if (Objects.requireNonNull(mTabLayout.getTabAt(1)).getCustomView() == null && SDKManager.getInstance().getCallAdaptor().getNumOfCalls() > 0 )
Objects.requireNonNull(mTabLayout.getTabAt(1)).setCustomView(tabOne);
}else if( SDKManager.getInstance().getDeskPhoneServiceAdaptor().getConfigBooleanParam(ConfigParametersNames.ENABLE_FAVORITES) == true && SDKManager.getInstance().getDeskPhoneServiceAdaptor().getConfigBooleanParam(ConfigParametersNames.ENABLE_CALL_LOG) != true ) {
if ( ( mTabLayout.getTabAt(2)!=null && Objects.requireNonNull(mTabLayout.getTabAt(2)).getCustomView() == null && (SDKManager.getInstance().getCallAdaptor().getNumOfCalls() == 0) || !mSectionsPagerAdapter.isCallAddParticipant()))
Objects.requireNonNull(mTabLayout.getTabAt(2)).setCustomView(tabOne);
else if ( mTabLayout.getTabAt(1)!=null && Objects.requireNonNull(mTabLayout.getTabAt(1)).getCustomView() == null && SDKManager.getInstance().getCallAdaptor().getNumOfCalls() > 0 )
Objects.requireNonNull(mTabLayout.getTabAt(1)).setCustomView(tabOne);
}else if( SDKManager.getInstance().getDeskPhoneServiceAdaptor().getConfigBooleanParam(ConfigParametersNames.ENABLE_FAVORITES) != true && SDKManager.getInstance().getDeskPhoneServiceAdaptor().getConfigBooleanParam(ConfigParametersNames.ENABLE_CALL_LOG) == true ) {
if ( ( mTabLayout.getTabAt(1)!=null && Objects.requireNonNull(mTabLayout.getTabAt(1)).getCustomView() == null && (SDKManager.getInstance().getCallAdaptor().getNumOfCalls() == 0) || !mSectionsPagerAdapter.isCallAddParticipant()))
Objects.requireNonNull(mTabLayout.getTabAt(1)).setCustomView(tabOne);
else if ( mTabLayout.getTabAt(0)!=null && Objects.requireNonNull(mTabLayout.getTabAt(0)).getCustomView() == null && SDKManager.getInstance().getCallAdaptor().getNumOfCalls() > 0 )
Objects.requireNonNull(mTabLayout.getTabAt(0)).setCustomView(tabOne);
}else if( SDKManager.getInstance().getDeskPhoneServiceAdaptor().getConfigBooleanParam(ConfigParametersNames.ENABLE_FAVORITES) != true && SDKManager.getInstance().getDeskPhoneServiceAdaptor().getConfigBooleanParam(ConfigParametersNames.ENABLE_CALL_LOG) != true ) {
if ( ( mTabLayout.getTabAt(1)!=null && Objects.requireNonNull(mTabLayout.getTabAt(1)).getCustomView() == null && (SDKManager.getInstance().getCallAdaptor().getNumOfCalls() == 0) || !mSectionsPagerAdapter.isCallAddParticipant()))
Objects.requireNonNull(mTabLayout.getTabAt(1)).setCustomView(tabOne);
else if ( mTabLayout.getTabAt(0)!=null && Objects.requireNonNull(mTabLayout.getTabAt(0)).getCustomView() == null && SDKManager.getInstance().getCallAdaptor().getNumOfCalls() > 0 )
Objects.requireNonNull(mTabLayout.getTabAt(0)).setCustomView(tabOne);
}
}
private void contactsTabFilterMenuListnerSetup(View v){
try{
if(showingFirst == true){
FragmentManager fragmentManager = MainActivityK155.this.getSupportFragmentManager();
List<Fragment> fragments = fragmentManager.getFragments();
for(Fragment fragment : fragments){
if(fragment != null && fragment.isVisible())
if (fragment instanceof ContactsFragment && ((ContactsFragment) fragment).isUserVisibleHint()) {
((ContactsFragment) fragment).hideMenus();
tabSelector.setImageResource(R.drawable.triangle_copy);
showingFirst = false;
break;
}
}
}else{
try {
FragmentManager fragmentManager = MainActivityK155.this.getSupportFragmentManager();
List<Fragment> fragments = fragmentManager.getFragments();
for (Fragment fragment : fragments) {
if (fragment != null && fragment.isVisible())
if (fragment instanceof ContactsFragment && ((ContactsFragment) fragment).isUserVisibleHint() && !fragment.isDetached()) {
((ContactsFragment) fragment).onClick(v);
tabSelector.setImageResource(R.drawable.triangle);
showingFirst = true;
break;
}
}
}catch (Exception e){
e.printStackTrace();
}
}
}catch (Exception e){
e.printStackTrace();
}
}
@Override
void backDeviceLogic(Tabs selectedTab){
CallStatusFragment callStatusFragment = (CallStatusFragment) getSupportFragmentManager().findFragmentByTag(CallStateEventHandler.CALL_STATUS_TAG);
int mNumActiveCalls = mCallStateEventHandler.mCalls.size();
assert callStatusFragment != null;
if( Objects.requireNonNull(callStatusFragment.getView()).getVisibility()!=View.VISIBLE && mNumActiveCalls>0 && !isFragmentVisible(ACTIVE_CALL_FRAGMENT)) {
callStatusFragment.showCallStatus();
}
if (selectedTab == Tabs.History) {
mSectionsPagerAdapter.getFragmentCallHistory().hideMenus();
filterButton.setVisibility(View.VISIBLE);
}
}
void onClickUser(){
mLastClickTime = SystemClock.elapsedRealtime();
mUser.setContentDescription(mLoggedUserExtension.getText().toString() + " " + mLoggedUserNumber.getText().toString() + " " + getString(R.string.user_content_description));
mSlideSelecAudioDevice.collapse(mToggleAudioMenu);
if (mListPreferences.getVisibility() == View.GONE || mListPreferences.getVisibility() == View.INVISIBLE) {
mSlideUserPreferences.expand(mListPreferences);
mFrameAll.setVisibility(View.VISIBLE);
mHandler.postDelayed(mLayoutCloseRunnable, Constants.LAYOUT_DISAPPEAR_TIME);
mOpenUser.setImageDrawable(getDrawable(R.drawable.ic_expand_less));
} else {
mOpenUser.setImageDrawable(getDrawable(R.drawable.ic_expand_more));
mSlideUserPreferences.collapse(mListPreferences);
mHandler.removeCallbacks(mLayoutCloseRunnable);
}
}
void onClickTransducerButton(){
mSlideUserPreferences.collapse(mListPreferences);
if (mToggleAudioMenu.getVisibility() == View.VISIBLE) {
mSlideSelecAudioDevice.collapse(mToggleAudioMenu);
mHandler.removeCallbacks(mLayoutCloseRunnable);
} else {
mSlideSelecAudioDevice.expand(mToggleAudioMenu);
mFrameAll.setVisibility(View.VISIBLE);
mHandler.postDelayed(mLayoutCloseRunnable, Constants.LAYOUT_DISAPPEAR_TIME);
}
}
@Override
void onClickSearchButton(){
if ((mToggleAudioMenu.getVisibility() == View.INVISIBLE || mToggleAudioMenu.getVisibility() == View.GONE && mListPreferences.getVisibility() == View.GONE)) {
changeUiForFullScreenInLandscape(true);
mSectionsPagerAdapter.getFragmentContacts().searchLayout.setVisibility(View.VISIBLE);
mSectionsPagerAdapter.getFragmentContacts().mAdd.setVisibility(View.INVISIBLE);
mSectionsPagerAdapter.getFragmentContacts().mSearchView.setQuery("", false);
mSectionsPagerAdapter.getFragmentContacts().mSearchView.requestFocus();
Utils.openKeyboard(this);
mSectionsPagerAdapter.getFragmentContacts().hideMenus();
tabSelector.setImageResource(R.drawable.triangle_copy);
showingFirst = false;
CallStatusFragment callStatusFragment_search_button = (CallStatusFragment) getSupportFragmentManager().findFragmentByTag(CallStateEventHandler.CALL_STATUS_TAG);
assert callStatusFragment_search_button != null;
if (Objects.requireNonNull(callStatusFragment_search_button.getView()).getVisibility() == View.VISIBLE) {
callStatusFragment_search_button.hideCallStatus();
Utils.hideKeyboard(this);
}
mViewPager.setEnabledSwipe(false);
}
}
@Override
void changeUIFor155(){
FragmentManager fragmentManager = MainActivityK155.this.getSupportFragmentManager();
List<Fragment> fragments = fragmentManager.getFragments();
for (Fragment fragment : fragments) {
if (fragment != null && fragment.isVisible())
if (fragment instanceof VideoCallFragment && !fragment.isDetached()) {
changeUiForFullScreenInLandscape(true);
break;
} else {
changeUiForFullScreenInLandscape(false);
}
}
}
void collapseSlideSelecAudioDevice(){
mSlideSelecAudioDevice.collapse(mToggleAudioMenu);
}
void collapseSlideUserPreferences(){
mSlideUserPreferences.collapse(mListPreferences);
}
void collapseSlideSelectPhoneNumber(){
mSlideSelectPhoneNumber.collapse(mSelectPhoneNumber);
}
@Override
void setTransducerButtonCheckedFor155(){
FragmentManager fragmentManager = MainActivityK155.this.getSupportFragmentManager();
List<Fragment> fragments = fragmentManager.getFragments();
for(Fragment fragment : fragments){
if(fragment != null && fragment.isVisible())
if (fragment instanceof DialerFragment) {
((DialerFragment) fragment).transducerButton.setChecked(false);
}else if (fragment instanceof ActiveCallFragment){
((ActiveCallFragment) fragment).transducerButton.setChecked(false);
}
}
}
@Override
protected void setBackgroundResource(int resId){
if (isFragmentVisible(DIALER_FRAGMENT)) {
((DialerFragment) getVisibleFragment(DIALER_FRAGMENT)).offHook.setBackgroundResource(resId);
}
ActiveCallFragment fragment = (ActiveCallFragment) (getSupportFragmentManager().findFragmentByTag(CallStateEventHandler.ACTIVE_CALL_TAG));
if (fragment != null) {
fragment.offHook.setBackgroundResource(resId);
}
}
@Override
void OnCallEndedChangeUIForDevice(){
try {
if (isFragmentVisible(DIALER_FRAGMENT)) {
((DialerFragment) getVisibleFragment(DIALER_FRAGMENT)).offHook.setChecked(false);
((DialerFragment) getVisibleFragment(DIALER_FRAGMENT)).setMode(DialerFragment.DialMode.EDIT);
}
}catch (NullPointerException e){
e.printStackTrace();
}
searchAddFilterIconViewController();
Tabs selectedTab = Tabs.Favorites;
for (Tabs t : mTabIndexMap.keySet()) {
if (mViewPager!=null && mViewPager.getCurrentItem() == mTabIndexMap.get(t)) {
selectedTab = t;
}
}
if(selectedTab== Tabs.Contacts) {
if (isFragmentVisible(CONTACTS_FRAGMENT))
mSectionsPagerAdapter.getFragmentContacts().removeSearchResults();
}
if (isFragmentVisible(CONTACTS_DETAILS_FRAGMENT) || isFragmentVisible(CONTACTS_EDIT_FRAGMENT)){
changeUiForFullScreenInLandscape(true);
}
else {
changeUiForFullScreenInLandscape(false);
}
}
@Override
void OnCallEndedChangesForDevice(){
hideMenus();
checkFilterButtonState();
}
/**
* Setting {@link ToggleButton} for audio selection on or off based on parameters provided
*
* @param isOn boolean based on which {@link ToggleButton} is set
*/
@Override
public void setOffhookButtosChecked(boolean isOn) {
mSelectAudio.setChecked(isOn);
if (mSectionsPagerAdapter.getDialerFragment() != null && mSectionsPagerAdapter.getDialerFragment().offHook != null){
mSectionsPagerAdapter.getDialerFragment().offHook.setChecked(isOn);
}
ActiveCallFragment fragment = (ActiveCallFragment) (getSupportFragmentManager().findFragmentByTag(CallStateEventHandler.ACTIVE_CALL_TAG));
if (fragment != null && fragment.offHook != null) {
fragment.offHook.setChecked(isOn);
}
}
@Override
public void setOffHookButtonsBasedCallState(int callId, UICallState state){
boolean isChecked=false;
int offhookCallId = SDKManager.getInstance().getCallAdaptor().getOffhookCallId();
if (offhookCallId != 0 && offhookCallId != callId)
isChecked=true;
else if (state == ESTABLISHED || state == REMOTE_ALERTING || state ==FAILED || state==TRANSFERRING) {
isChecked=true;
}
setOffhookButtosChecked(isChecked);
}
void onDeviceChangedDeviceLogic(int resId, boolean active){
if (mSectionsPagerAdapter.getDialerFragment() != null && mSectionsPagerAdapter.getDialerFragment().offHook != null){
if(isFragmentVisible(CONTACTS_DETAILS_FRAGMENT)==true) {
((ContactDetailsFragment) getVisibleFragment(CONTACTS_DETAILS_FRAGMENT)).isBackORDeletePressed = true;
}
mSectionsPagerAdapter.getDialerFragment().offHook.setChecked(active);
mSectionsPagerAdapter.getDialerFragment().offHook.setBackgroundResource(resId);
}
ActiveCallFragment fragment = (ActiveCallFragment) (getSupportFragmentManager().findFragmentByTag(CallStateEventHandler.ACTIVE_CALL_TAG));
if (fragment != null && fragment.offHook != null) {
fragment.offHook.setChecked(active);
fragment.offHook.setBackgroundResource(resId);
}
}
@Override
void prepareOffhookChangeUIforDevice(){
if(!isFragmentVisible(ACTIVE_VIDEO_CALL_FRAGMENT)
&& isFragmentVisible(CONTACTS_FRAGMENT) == false
&& (getVisibleFragment(CONTACTS_FRAGMENT))!=null
&& ((ContactsFragment) getVisibleFragment(CONTACTS_FRAGMENT)).isSearchLayoutVisible() ==false)
{
changeUiForFullScreenInLandscape(false);
}
if (isFragmentVisible(CONTACTS_DETAILS_FRAGMENT) && (SDKManager.getInstance().getCallAdaptor().getActiveCallIdWithoutOffhook()) == 0)
((ContactDetailsFragment) getVisibleFragment(CONTACTS_DETAILS_FRAGMENT)). mBackListener.back();
}
@Override
void onIncomingCallEndedCahngeUIForDevice(){
searchAddFilterIconViewController();
if( (isFragmentVisible(CONTACTS_DETAILS_FRAGMENT) || isFragmentVisible(CONTACTS_EDIT_FRAGMENT) || isFragmentVisible(ACTIVE_VIDEO_CALL_FRAGMENT)) && !isFragmentVisible(DIALER_FRAGMENT) ){
changeUiForFullScreenInLandscape(true);
if( isFragmentVisible(ACTIVE_CALL_FRAGMENT) && !isFragmentVisible(ACTIVE_VIDEO_CALL_FRAGMENT))
changeUiForFullScreenInLandscape(false);
}else if( (isFragmentVisible(CONTACTS_DETAILS_FRAGMENT) || isFragmentVisible(CONTACTS_EDIT_FRAGMENT) || isFragmentVisible(ACTIVE_VIDEO_CALL_FRAGMENT)) ) {
changeUiForFullScreenInLandscape(true);
}else if ( mSectionsPagerAdapter.getFragmentContacts() != null && mSectionsPagerAdapter.getFragmentContacts().isSearchLayoutVisible()){
changeUiForFullScreenInLandscape(true);
}else{
changeUiForFullScreenInLandscape(false);
}
}
@Override
void onIncomingCallStartedDeviceLogic(){
hideMenus();
checkFilterButtonState();
if(isFragmentVisible(CONTACTS_FRAGMENT) && (getVisibleFragment(CONTACTS_FRAGMENT)) !=null){
((ContactsFragment) getVisibleFragment(CONTACTS_FRAGMENT)).handleIncomingCall();
}
if(isFragmentVisible(HISTORY_FRAGMENT) && getVisibleFragment(HISTORY_FRAGMENT) != null){
((CallHistoryFragment) getVisibleFragment(HISTORY_FRAGMENT)).handleIncomingCall();
}
}
@Override
boolean onBackPressedDeviceLogic(){
if (isToBlockBakcPress == true){
isToBlockBakcPress = false;
return false;
}
return true;
}
@Override
protected void setVideoControlsVisibility(int visible) {
if (mSectionsPagerAdapter.getDialerFragment() != null)
mSectionsPagerAdapter.getDialerFragment().setVideoButtonVisibility(visible);
}
/**
* Set appropriate state for add contact button on K155 devices
*/
private void setAddContactVisibility() {
if (Utils.isModifyContactsEnabled() && !mSectionsPagerAdapter.isCallAddParticipant()) {
addcontactButton.setVisibility(View.VISIBLE);
} else {
addcontactButton.setVisibility(View.INVISIBLE);
}
}
}
| 49,541 | 0.608526 | 0.605902 | 1,025 | 47.332684 | 45.646057 | 272 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.476098 | false | false | 0 |
595f36e8cf708d3cf9de47c99c70c8edd9e29c54 | 30,691,836,308,217 | 4df72d14c264c6db0c5b09a707842d4a89b606ea | /src/com/vivek/interview/Test.java | b1c1201bdb3961a6d92bf44cd0cc5e568f9120c4 | []
| no_license | vivek-vedhagiri/coding-works | https://github.com/vivek-vedhagiri/coding-works | a210e828958a350bdb101d1e13278ad428c02b07 | 937e31f9f51826dfb06fb159ac34469fe05d1334 | refs/heads/master | 2020-08-10T06:00:36.666000 | 2019-10-10T20:22:43 | 2019-10-10T20:22:43 | 214,276,655 | 0 | 0 | null | false | 2019-10-10T20:18:34 | 2019-10-10T20:12:23 | 2019-10-10T20:12:25 | 2019-10-10T20:16:59 | 0 | 0 | 0 | 1 | null | false | false | package com.vivek.interview;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Test {
public static void main(String args[]) {
List<String> list = Stream.of("foo","boo","coo").collect(Collectors.toList());
List<String> list1 = new ArrayList<String>();
}
}
| UTF-8 | Java | 376 | java | Test.java | Java | []
| null | []
| package com.vivek.interview;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Test {
public static void main(String args[]) {
List<String> list = Stream.of("foo","boo","coo").collect(Collectors.toList());
List<String> list1 = new ArrayList<String>();
}
}
| 376 | 0.672872 | 0.670213 | 18 | 18.888889 | 21.640726 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.222222 | false | false | 0 |
46b18e70e8eb08d74d80d6aaf797d43d487fcd7c | 27,934,467,304,023 | 874831055b2de4bef4f4be03bd4ac1ac5b4842b7 | /java/src/leetcode/question_297.java | 2944708b3d87f162ff052ff075b6e44e36b1b742 | []
| no_license | codychen123/algorithm | https://github.com/codychen123/algorithm | 1cd2dbf4e193672121f0e2b366cf434b07c80776 | b1b40be7dea3b6681d226a56edbf644fc3ef7ae9 | refs/heads/main | 2023-03-26T13:37:35.270000 | 2021-03-25T01:48:56 | 2021-03-25T01:48:56 | 342,179,113 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package leetcode;
import java.util.ArrayList;
import java.util.LinkedList;
public class question_297 {
public static void main(String[] args) {
}
// Encodes a tree to a single string.
public StringBuilder sb;
String sep = ",";
String NullNode = "#";
public String serialize(TreeNode root) {
sb = new StringBuilder();
return buildSerialize(root);
}
public String buildSerialize(TreeNode root) {
if (root == null) {
sb.append(NullNode).append(sep);
return sb.toString();
}
sb.append(root.val).append(sep);
buildSerialize(root.left);
buildSerialize(root.right);
return sb.toString();
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
LinkedList<String> nodeNum = new LinkedList<String>();
for (String s:data.split(sep)) {
nodeNum.add(s);
}
return buildDeserialize(nodeNum);
}
public TreeNode buildDeserialize(LinkedList<String> nodeNum) {
if (nodeNum.isEmpty()) {
return null;
}
String numStr = nodeNum.removeFirst();
if (numStr.equals(NullNode)) {
return null;
}
TreeNode root = new TreeNode(Integer.parseInt(numStr));
root.left = buildDeserialize(nodeNum);
root.right = buildDeserialize(nodeNum);
return root;
}
}
| UTF-8 | Java | 1,440 | java | question_297.java | Java | []
| null | []
| package leetcode;
import java.util.ArrayList;
import java.util.LinkedList;
public class question_297 {
public static void main(String[] args) {
}
// Encodes a tree to a single string.
public StringBuilder sb;
String sep = ",";
String NullNode = "#";
public String serialize(TreeNode root) {
sb = new StringBuilder();
return buildSerialize(root);
}
public String buildSerialize(TreeNode root) {
if (root == null) {
sb.append(NullNode).append(sep);
return sb.toString();
}
sb.append(root.val).append(sep);
buildSerialize(root.left);
buildSerialize(root.right);
return sb.toString();
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
LinkedList<String> nodeNum = new LinkedList<String>();
for (String s:data.split(sep)) {
nodeNum.add(s);
}
return buildDeserialize(nodeNum);
}
public TreeNode buildDeserialize(LinkedList<String> nodeNum) {
if (nodeNum.isEmpty()) {
return null;
}
String numStr = nodeNum.removeFirst();
if (numStr.equals(NullNode)) {
return null;
}
TreeNode root = new TreeNode(Integer.parseInt(numStr));
root.left = buildDeserialize(nodeNum);
root.right = buildDeserialize(nodeNum);
return root;
}
}
| 1,440 | 0.596528 | 0.594444 | 52 | 26.692308 | 18.179171 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.480769 | false | false | 0 |
cf238e0ead64a638ce0c02be65c56239db877e40 | 24,215,025,628,081 | b8a0d1442363e1c68036c1967baef06d22cc4048 | /src/main/java/com/asiainfo/p5/io/nio/NIOTest.java | aae6815a5395ee870cd4c879269b35de5b0930b6 | []
| no_license | zhangzhiwang/GuPaoEdu | https://github.com/zhangzhiwang/GuPaoEdu | 941460fbbafd6c9d45b8ac6fe947cdc0dd2133b5 | b7e09548dd23f192e7a7346a1e5ac4072708c1d7 | refs/heads/master | 2022-12-22T09:06:33.369000 | 2021-07-28T10:29:41 | 2021-07-28T10:29:41 | 214,958,076 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.asiainfo.p5.io.nio;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* NIO
*
* @author zhangzhiwang
* @date Jan 10, 2020 7:28:51 PM
*/
public class NIOTest {
public static void main(String[] args) {
try (FileInputStream fileInputStream = new FileInputStream("/Users/zhangzhiwang/Downloads/QQ20191226-120140-HD.mp4");
FileOutputStream fileOutputStream = new FileOutputStream("/Users/zhangzhiwang/Desktop/QQ20191226-120140-HD.mp4");
// 创建管道
FileChannel inChannel = fileInputStream.getChannel();
FileChannel outChannel = fileOutputStream.getChannel();
) {
// 初始化缓冲区
// 方式1:
ByteBuffer buffer = ByteBuffer.allocate(10);
// // 方式2:
// ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[10]);
int i = 0;
while((i = inChannel.read(buffer)) != -1) {// 读取数据到缓冲区,返回读取字节的个数,上限是缓冲数组的长度,即最多读取缓冲数组长度个字节
buffer.flip();// 从读转化为写
outChannel.write(buffer);
buffer.clear();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 1,209 | java | NIOTest.java | Java | [
{
"context": "io.channels.FileChannel;\n\n/**\n * NIO\n *\n * @author zhangzhiwang\n * @date Jan 10, 2020 7:28:51 PM\n */\npublic class",
"end": 202,
"score": 0.998104989528656,
"start": 190,
"tag": "USERNAME",
"value": "zhangzhiwang"
}
]
| null | []
| package com.asiainfo.p5.io.nio;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* NIO
*
* @author zhangzhiwang
* @date Jan 10, 2020 7:28:51 PM
*/
public class NIOTest {
public static void main(String[] args) {
try (FileInputStream fileInputStream = new FileInputStream("/Users/zhangzhiwang/Downloads/QQ20191226-120140-HD.mp4");
FileOutputStream fileOutputStream = new FileOutputStream("/Users/zhangzhiwang/Desktop/QQ20191226-120140-HD.mp4");
// 创建管道
FileChannel inChannel = fileInputStream.getChannel();
FileChannel outChannel = fileOutputStream.getChannel();
) {
// 初始化缓冲区
// 方式1:
ByteBuffer buffer = ByteBuffer.allocate(10);
// // 方式2:
// ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[10]);
int i = 0;
while((i = inChannel.read(buffer)) != -1) {// 读取数据到缓冲区,返回读取字节的个数,上限是缓冲数组的长度,即最多读取缓冲数组长度个字节
buffer.flip();// 从读转化为写
outChannel.write(buffer);
buffer.clear();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 1,209 | 0.699352 | 0.653099 | 39 | 26.717949 | 29.417376 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.230769 | false | false | 0 |
81ee1ed71c9f86eebf2e61820bea945b6efb48c4 | 30,356,828,859,890 | 97f299b5414b83438a8adcff14a9d944c67241f1 | /s1/block2/VariableNames.java | f2013c89163f0621c5b117ae17b6163c8750ec01 | [
"BSD-2-Clause"
]
| permissive | scalingbits/dhbwjava | https://github.com/scalingbits/dhbwjava | abfd61f07bd4adae29a5d8ae4cd1cf24db4c5f55 | ed101efb5d491381c6cad2810a45171adfcadb5c | refs/heads/master | 2022-05-16T22:23:00.788000 | 2022-03-29T09:36:16 | 2022-03-29T09:36:16 | 169,788,624 | 3 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package s1.block2;
/**
*
* @author s@scalingbits.com
*/
public class VariableNames {
int maxvalue;
int maxValue;
int max_value;
//int max value;
int end;
int End;
//int 10%ofSum;
int sum10;
int _10PercentOfSum;
public static void main(String[] args) {
int x,y;
x = y = 8;
//(x = y) = 8;
x = (y = 8);
x = (y = 8)+1;
System.out.println(x);
System.out.println(y);
}
}
| UTF-8 | Java | 437 | java | VariableNames.java | Java | [
{
"context": "package s1.block2;\n\n/**\n *\n * @author s@scalingbits.com\n */\npublic class VariableNames {\n\nint maxvalue;\ni",
"end": 55,
"score": 0.9999117255210876,
"start": 38,
"tag": "EMAIL",
"value": "s@scalingbits.com"
}
]
| null | []
| package s1.block2;
/**
*
* @author <EMAIL>
*/
public class VariableNames {
int maxvalue;
int maxValue;
int max_value;
//int max value;
int end;
int End;
//int 10%ofSum;
int sum10;
int _10PercentOfSum;
public static void main(String[] args) {
int x,y;
x = y = 8;
//(x = y) = 8;
x = (y = 8);
x = (y = 8)+1;
System.out.println(x);
System.out.println(y);
}
}
| 427 | 0.533181 | 0.503433 | 30 | 13.566667 | 11.17343 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 0 |
6bd0cc69c0f1de60588bd39d66a76551ce9a86c8 | 23,441,931,513,129 | 117ab086ce89f2dff2de58a47a86431be4a5bebb | /app/src/main/java/com/cmpe277/groupay/MainActivity.java | 47773d52f44a9b983a8cbd0cb3cab76f9d897262 | []
| no_license | yuyuho/Groupay | https://github.com/yuyuho/Groupay | 078fbb23bf2ad66398ea39411f2a0a6244a1d091 | 5c6e69505104cb2ca50a35da02a33b7214667724 | refs/heads/master | 2021-01-19T08:46:06.305000 | 2015-05-15T04:49:05 | 2015-05-15T04:49:05 | 35,310,726 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cmpe277.groupay;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import java.util.UUID;
public class MainActivity extends Activity {
private static final int oneSec = 1000;
Handler timeHandler;
private ImageView mImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageView = (ImageView)findViewById(R.id.icon_login);
mImageView.setImageResource(R.drawable.logo);
timeHandler = new Handler();
//////////////////
///////////////////Hack
Bitmap icon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_logo2);
Data.get().getmEventList().add(new Event( Data.get().getMyName(), icon, "Birthday", 2000, 10, 2, Data.get().getmEventList().size()));
Data.get().getmEventList().add(new Event( "Ryan", icon, "ToyRus", 2015, 12, 1, Data.get().getmEventList().size()));
Data.get().getmEventList().get(0).addItem( new Item("Cake"));
Data.get().getmEventList().get(0).addItem( new Item("Candle"));
Data.get().getmEventList().get(0).addItem( new Item("fork"));
Data.get().getmEventList().get(0).addItem( new Item("plate"));
Data.get().getmEventList().get(0).addItem( new Item("flower"));
Data.get().getmEventList().get(0).addItem( new Item("Balloon"));
ItemInfo itemInfo = new ItemInfo();
itemInfo.setItemPrice(0.44);
itemInfo.setStore("Amazon");
Data.get().getmEventList().get(0).getItemAtIndex(1).addItemInfo(itemInfo);
itemInfo = new ItemInfo();
itemInfo.setItemPrice(0.99);
itemInfo.setStore("ebay");
Data.get().getmEventList().get(0).getItemAtIndex(1).addItemInfo(itemInfo);
Data.get().getmEventList().get(0).getItemAtIndex(1).setItemStatus(Item.itemStatusEnum.waitForVote);
Data.get().getmEventList().get(0).getItemAtIndex(2).setItemStatus(Item.itemStatusEnum.bought);
Data.get().getmEventList().get(0).getItemAtIndex(3).setItemStatus(Item.itemStatusEnum.waitToBeBuy);
Data.get().getmEventList().get(0).getItemAtIndex(4).setItemStatus(Item.itemStatusEnum.approved);
Data.get().getmEventList().get(0).getItemAtIndex(5).setItemStatus(Item.itemStatusEnum.requestProof);
itemInfo = new ItemInfo();
itemInfo.setItemPrice(0.999);
itemInfo.setStore("ebay");
Data.get().getmEventList().get(0).getItemAtIndex(2).addItemInfo(itemInfo);
itemInfo = new ItemInfo();
itemInfo.setMemberName("John");
itemInfo.setItemPrice(0.999);
itemInfo.setStore("Target");
itemInfo.setDescription("Plastic, White");
Data.get().getmEventList().get(0).getItemAtIndex(3).setItemFinalInfo(itemInfo);
ItemInfo finalInfo = new ItemInfo();
finalInfo.setItemPrice(200);
finalInfo.setMemberName("Carol");
finalInfo.setDescription("White plastic plate");
finalInfo.setStore("Michael's");
Bitmap receipt = BitmapFactory.decodeResource(this.getResources(),
R.drawable.ic_receipt);
finalInfo.setRecipe(receipt);
Data.get().getmEventList().get(0).getItemAtIndex(4).setItemFinalInfo(finalInfo);
finalInfo = new ItemInfo();
finalInfo.setItemPrice(300);
finalInfo.setMemberName("Judy");
finalInfo.setDescription("Red and paper");
finalInfo.setStore("Michael's");
receipt = BitmapFactory.decodeResource(this.getResources(),
R.drawable.ic_receipt);
finalInfo.setRecipe(receipt);
Data.get().getmEventList().get(0).getItemAtIndex(5).setItemFinalInfo(finalInfo);
Data.get().getEvent(1).addItem( new Item("Robot"));
Data.get().getEvent(1).addItem( new Item("Kitchen Top"));
Data.get().getmEventList().get(0).addMember("Cynthia");
Data.get().getmEventList().get(0).addMember("Abraham");
Data.get().getmEventList().get(1).addMember("Elliot");
UUID eventID1 = Data.get().getEvent(0).getEventID();
Data.get().getMe().addNewEvent(eventID1);
UUID eventID2 = Data.get().getEvent(1).getEventID();
Data.get().getMe().addNewEvent(eventID2);
Data.get().getMe().setNotify(eventID1,"vote for an item");
Data.get().getMe().setNotify(eventID2,"An item is waiting to be bought");
Data.get().getMe().setNotify(eventID2,"request proof");
timeHandler.postDelayed(new Runnable() {
@Override
public void run() {
final Intent mainIntent = new Intent(MainActivity.this, SignInActivity.class);
startActivity(mainIntent);
finish();
}
}, oneSec);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
| UTF-8 | Java | 5,352 | java | MainActivity.java | Java | [
{
"context": "= new ItemInfo();\n itemInfo.setMemberName(\"John\");\n itemInfo.setItemPrice(0.999);\n ",
"end": 2926,
"score": 0.9998618364334106,
"start": 2922,
"tag": "NAME",
"value": "John"
},
{
"context": "tItemPrice(200);\n finalInfo.setMemberName(\"Carol\");\n finalInfo.setDescription(\"White plasti",
"end": 3265,
"score": 0.9997803568840027,
"start": 3260,
"tag": "NAME",
"value": "Carol"
},
{
"context": "tItemPrice(300);\n finalInfo.setMemberName(\"Judy\");\n finalInfo.setDescription(\"Red and pape",
"end": 3720,
"score": 0.9997693300247192,
"start": 3716,
"tag": "NAME",
"value": "Judy"
},
{
"context": "ion(\"Red and paper\");\n finalInfo.setStore(\"Michael's\");\n receipt = BitmapFactory.decodeResource",
"end": 3812,
"score": 0.7969987392425537,
"start": 3803,
"tag": "NAME",
"value": "Michael's"
},
{
"context": " Data.get().getmEventList().get(0).addMember(\"Cynthia\");\n Data.get().getmEventList().get(0).addM",
"end": 4239,
"score": 0.999849796295166,
"start": 4232,
"tag": "NAME",
"value": "Cynthia"
},
{
"context": " Data.get().getmEventList().get(0).addMember(\"Abraham\");\n Data.get().getmEventList().get(1).addM",
"end": 4303,
"score": 0.9998458623886108,
"start": 4296,
"tag": "NAME",
"value": "Abraham"
},
{
"context": " Data.get().getmEventList().get(1).addMember(\"Elliot\");\n UUID eventID1 = Data.get().getEvent(0)",
"end": 4366,
"score": 0.9998205900192261,
"start": 4360,
"tag": "NAME",
"value": "Elliot"
}
]
| null | []
| package com.cmpe277.groupay;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import java.util.UUID;
public class MainActivity extends Activity {
private static final int oneSec = 1000;
Handler timeHandler;
private ImageView mImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageView = (ImageView)findViewById(R.id.icon_login);
mImageView.setImageResource(R.drawable.logo);
timeHandler = new Handler();
//////////////////
///////////////////Hack
Bitmap icon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_logo2);
Data.get().getmEventList().add(new Event( Data.get().getMyName(), icon, "Birthday", 2000, 10, 2, Data.get().getmEventList().size()));
Data.get().getmEventList().add(new Event( "Ryan", icon, "ToyRus", 2015, 12, 1, Data.get().getmEventList().size()));
Data.get().getmEventList().get(0).addItem( new Item("Cake"));
Data.get().getmEventList().get(0).addItem( new Item("Candle"));
Data.get().getmEventList().get(0).addItem( new Item("fork"));
Data.get().getmEventList().get(0).addItem( new Item("plate"));
Data.get().getmEventList().get(0).addItem( new Item("flower"));
Data.get().getmEventList().get(0).addItem( new Item("Balloon"));
ItemInfo itemInfo = new ItemInfo();
itemInfo.setItemPrice(0.44);
itemInfo.setStore("Amazon");
Data.get().getmEventList().get(0).getItemAtIndex(1).addItemInfo(itemInfo);
itemInfo = new ItemInfo();
itemInfo.setItemPrice(0.99);
itemInfo.setStore("ebay");
Data.get().getmEventList().get(0).getItemAtIndex(1).addItemInfo(itemInfo);
Data.get().getmEventList().get(0).getItemAtIndex(1).setItemStatus(Item.itemStatusEnum.waitForVote);
Data.get().getmEventList().get(0).getItemAtIndex(2).setItemStatus(Item.itemStatusEnum.bought);
Data.get().getmEventList().get(0).getItemAtIndex(3).setItemStatus(Item.itemStatusEnum.waitToBeBuy);
Data.get().getmEventList().get(0).getItemAtIndex(4).setItemStatus(Item.itemStatusEnum.approved);
Data.get().getmEventList().get(0).getItemAtIndex(5).setItemStatus(Item.itemStatusEnum.requestProof);
itemInfo = new ItemInfo();
itemInfo.setItemPrice(0.999);
itemInfo.setStore("ebay");
Data.get().getmEventList().get(0).getItemAtIndex(2).addItemInfo(itemInfo);
itemInfo = new ItemInfo();
itemInfo.setMemberName("John");
itemInfo.setItemPrice(0.999);
itemInfo.setStore("Target");
itemInfo.setDescription("Plastic, White");
Data.get().getmEventList().get(0).getItemAtIndex(3).setItemFinalInfo(itemInfo);
ItemInfo finalInfo = new ItemInfo();
finalInfo.setItemPrice(200);
finalInfo.setMemberName("Carol");
finalInfo.setDescription("White plastic plate");
finalInfo.setStore("Michael's");
Bitmap receipt = BitmapFactory.decodeResource(this.getResources(),
R.drawable.ic_receipt);
finalInfo.setRecipe(receipt);
Data.get().getmEventList().get(0).getItemAtIndex(4).setItemFinalInfo(finalInfo);
finalInfo = new ItemInfo();
finalInfo.setItemPrice(300);
finalInfo.setMemberName("Judy");
finalInfo.setDescription("Red and paper");
finalInfo.setStore("Michael's");
receipt = BitmapFactory.decodeResource(this.getResources(),
R.drawable.ic_receipt);
finalInfo.setRecipe(receipt);
Data.get().getmEventList().get(0).getItemAtIndex(5).setItemFinalInfo(finalInfo);
Data.get().getEvent(1).addItem( new Item("Robot"));
Data.get().getEvent(1).addItem( new Item("Kitchen Top"));
Data.get().getmEventList().get(0).addMember("Cynthia");
Data.get().getmEventList().get(0).addMember("Abraham");
Data.get().getmEventList().get(1).addMember("Elliot");
UUID eventID1 = Data.get().getEvent(0).getEventID();
Data.get().getMe().addNewEvent(eventID1);
UUID eventID2 = Data.get().getEvent(1).getEventID();
Data.get().getMe().addNewEvent(eventID2);
Data.get().getMe().setNotify(eventID1,"vote for an item");
Data.get().getMe().setNotify(eventID2,"An item is waiting to be bought");
Data.get().getMe().setNotify(eventID2,"request proof");
timeHandler.postDelayed(new Runnable() {
@Override
public void run() {
final Intent mainIntent = new Intent(MainActivity.this, SignInActivity.class);
startActivity(mainIntent);
finish();
}
}, oneSec);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
| 5,352 | 0.653587 | 0.637706 | 130 | 40.169231 | 31.025829 | 141 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.846154 | false | false | 0 |
8e7a48d5289dcd87e2a810470201656cfdf5b81a | 438,086,681,237 | 86a8478989830f20d743911ec50e69dc612617e5 | /app/src/main/java/cn/biaoshi360/bsh/activity/checkworkattendance/attendanceteam/adapter/ExpandableItemAdapter22.java | 59e9ba63fcbf6a18a61057f1c75b191316c5462e | []
| no_license | AndroidDeveloperWen/thePro | https://github.com/AndroidDeveloperWen/thePro | 95c34bf103ac0be93efd968e772ea8ef5bffe99a | 56094d5ebe36f7da9e699afcc045fb78912d3e16 | refs/heads/master | 2018-10-16T16:37:49.282000 | 2018-10-16T04:25:07 | 2018-10-16T04:25:07 | 108,623,946 | 7 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.biaoshi360.bsh.activity.checkworkattendance.attendanceteam.adapter;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import java.util.List;
import cn.biaoshi360.bsh.R;
import cn.biaoshi360.bsh.activity.checkworkattendance.attendanceteam.Mod.DPersonMod;
import cn.biaoshi360.bsh.activity.checkworkattendance.attendanceteam.Mod.DepartMod;
import cn.biaoshi360.bsh.util.ToastHelper;
/**
* Created by luoxw on 2016/8/9.
*/
// 展开相当于插入 所以 pos 会变
public class ExpandableItemAdapter22 extends BaseMultiItemQuickAdapter22<MultiItemEntity22, BaseViewHolder22> {
private static final String TAG = ExpandableItemAdapter22.class.getSimpleName();
public static final int TYPE_DEPART = 0;
public static final int TYPE_PER = 1;
public static final int TYPE_PERSON = 2;
OnChildCheck onChildCheck;
OnPartentCheck onPartentCheck;
/**
* Same as QuickAdapter#QuickAdapter(Context,int) but with
* some initialization data.
*
* @param data A new list is created out of this one to avoid mutable list
*/
public ExpandableItemAdapter22(List<MultiItemEntity22> data) {
super(data);
addItemType(TYPE_DEPART, R.layout.person_choose_first_adapter);
addItemType(TYPE_PER, R.layout.person_choose_second_adapter);
}
@Override
protected void convert(final BaseViewHolder22 helper, final MultiItemEntity22 item) {
switch (helper.getItemViewType()) {
case TYPE_DEPART:
// switch (helper.getLayoutPosition() %
// 3) {
// case 0:
// helper.setImageResource(R.id.iv_head, R.mipmap.head_img0);
// break;
// case 1:
// helper.setImageResource(R.id.iv_head, R.mipmap.head_img1);
// break;
// case 2:
// helper.setImageResource(R.id.iv_head, R.mipmap.head_img2);
// break;
// }
final DepartMod lv0 = (DepartMod)item;
helper.setText(R.id.tv_firstitem, lv0.getName())
// .setText(R.id.sub_title, lv0.getDepartment_id())
.setImageResource(R.id.group_indictor, lv0.isExpanded() ? R.drawable.expandlist_indictor_back : R.drawable.expandlist_indictor_right);
helper.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int pos = helper.getAdapterPosition();
Log.d(TAG, "Level 0 item pos: " + pos);
if (lv0.isExpanded()) {
collapse(pos);
} else {
// if (pos % 3 == 0) {
// expandAll(pos, false);
// } else {
expand(pos);
// }
}
}
});
helper.setOnClickListener(R.id.choose, new View.OnClickListener() {
@Override
public void onClick(View v) {
int pos = helper.getAdapterPosition();
Log.e(TAG, "Level 0 item pos: " + pos);
onPartentCheck.partent(pos);
}
});
helper.setOnCheckedChangeListener(R.id.choose, new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
break;
case TYPE_PER:
final DPersonMod lv1 = (DPersonMod)item;
helper.setText(R.id.tv_seconditem, lv1.getNice_name());
// .setText(R.id.sub_title, lv1.getNice_name())
// .setImageResource(R.id.iv, lv1.isExpanded() ? R.mipmap.arrow_b : R.mipmap.arrow_r);
if (((DPersonMod) item).isAdd()){
helper.setChecked(R.id.choose,true);
}else {
helper.setChecked(R.id.choose,false);
}
helper.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int pos = helper.getAdapterPosition();
Log.d(TAG, "Level 1 item pos: " + pos);
if (((DPersonMod) item).isAdd()){
}else {
}
// if (lv1.isExpanded()) {
// collapse(pos, false);
// } else {
// expand(pos, false);
// }
}
});
helper.setOnClickListener(R.id.choose, new View.OnClickListener() {
@Override
public void onClick(View v) {
int pos = helper.getAdapterPosition();
Log.e(TAG, "Level 1 item pos: " + pos);
onChildCheck.childCheck(pos);
}
});
break;
}
}
public interface OnChildCheck{
void childCheck(int pos);
}
public interface OnPartentCheck{
void partent(int pos);
}
public void setOnChildCheck(OnChildCheck onChildCheck) {
this.onChildCheck = onChildCheck;
}
public void setOnPartentCheck(OnPartentCheck onPartentCheck) {
this.onPartentCheck = onPartentCheck;
}
}
| UTF-8 | Java | 5,848 | java | ExpandableItemAdapter22.java | Java | [
{
"context": "iaoshi360.bsh.util.ToastHelper;\n\n/**\n * Created by luoxw on 2016/8/9.\n */\n// 展开相当于插入 所以 pos 会变\npublic clas",
"end": 459,
"score": 0.9995731711387634,
"start": 454,
"tag": "USERNAME",
"value": "luoxw"
}
]
| null | []
| package cn.biaoshi360.bsh.activity.checkworkattendance.attendanceteam.adapter;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import java.util.List;
import cn.biaoshi360.bsh.R;
import cn.biaoshi360.bsh.activity.checkworkattendance.attendanceteam.Mod.DPersonMod;
import cn.biaoshi360.bsh.activity.checkworkattendance.attendanceteam.Mod.DepartMod;
import cn.biaoshi360.bsh.util.ToastHelper;
/**
* Created by luoxw on 2016/8/9.
*/
// 展开相当于插入 所以 pos 会变
public class ExpandableItemAdapter22 extends BaseMultiItemQuickAdapter22<MultiItemEntity22, BaseViewHolder22> {
private static final String TAG = ExpandableItemAdapter22.class.getSimpleName();
public static final int TYPE_DEPART = 0;
public static final int TYPE_PER = 1;
public static final int TYPE_PERSON = 2;
OnChildCheck onChildCheck;
OnPartentCheck onPartentCheck;
/**
* Same as QuickAdapter#QuickAdapter(Context,int) but with
* some initialization data.
*
* @param data A new list is created out of this one to avoid mutable list
*/
public ExpandableItemAdapter22(List<MultiItemEntity22> data) {
super(data);
addItemType(TYPE_DEPART, R.layout.person_choose_first_adapter);
addItemType(TYPE_PER, R.layout.person_choose_second_adapter);
}
@Override
protected void convert(final BaseViewHolder22 helper, final MultiItemEntity22 item) {
switch (helper.getItemViewType()) {
case TYPE_DEPART:
// switch (helper.getLayoutPosition() %
// 3) {
// case 0:
// helper.setImageResource(R.id.iv_head, R.mipmap.head_img0);
// break;
// case 1:
// helper.setImageResource(R.id.iv_head, R.mipmap.head_img1);
// break;
// case 2:
// helper.setImageResource(R.id.iv_head, R.mipmap.head_img2);
// break;
// }
final DepartMod lv0 = (DepartMod)item;
helper.setText(R.id.tv_firstitem, lv0.getName())
// .setText(R.id.sub_title, lv0.getDepartment_id())
.setImageResource(R.id.group_indictor, lv0.isExpanded() ? R.drawable.expandlist_indictor_back : R.drawable.expandlist_indictor_right);
helper.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int pos = helper.getAdapterPosition();
Log.d(TAG, "Level 0 item pos: " + pos);
if (lv0.isExpanded()) {
collapse(pos);
} else {
// if (pos % 3 == 0) {
// expandAll(pos, false);
// } else {
expand(pos);
// }
}
}
});
helper.setOnClickListener(R.id.choose, new View.OnClickListener() {
@Override
public void onClick(View v) {
int pos = helper.getAdapterPosition();
Log.e(TAG, "Level 0 item pos: " + pos);
onPartentCheck.partent(pos);
}
});
helper.setOnCheckedChangeListener(R.id.choose, new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
break;
case TYPE_PER:
final DPersonMod lv1 = (DPersonMod)item;
helper.setText(R.id.tv_seconditem, lv1.getNice_name());
// .setText(R.id.sub_title, lv1.getNice_name())
// .setImageResource(R.id.iv, lv1.isExpanded() ? R.mipmap.arrow_b : R.mipmap.arrow_r);
if (((DPersonMod) item).isAdd()){
helper.setChecked(R.id.choose,true);
}else {
helper.setChecked(R.id.choose,false);
}
helper.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int pos = helper.getAdapterPosition();
Log.d(TAG, "Level 1 item pos: " + pos);
if (((DPersonMod) item).isAdd()){
}else {
}
// if (lv1.isExpanded()) {
// collapse(pos, false);
// } else {
// expand(pos, false);
// }
}
});
helper.setOnClickListener(R.id.choose, new View.OnClickListener() {
@Override
public void onClick(View v) {
int pos = helper.getAdapterPosition();
Log.e(TAG, "Level 1 item pos: " + pos);
onChildCheck.childCheck(pos);
}
});
break;
}
}
public interface OnChildCheck{
void childCheck(int pos);
}
public interface OnPartentCheck{
void partent(int pos);
}
public void setOnChildCheck(OnChildCheck onChildCheck) {
this.onChildCheck = onChildCheck;
}
public void setOnPartentCheck(OnPartentCheck onPartentCheck) {
this.onPartentCheck = onPartentCheck;
}
}
| 5,848 | 0.508067 | 0.49691 | 155 | 36.587097 | 29.538992 | 158 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.541936 | false | false | 0 |
c9036d6c2789d0cae4835c8f47c5dcd9781dae93 | 16,870,631,556,223 | 6b5d11cfbc73d5b96e9495240115cb9b75f94e03 | /app/src/main/java/com/example/howell/webcamforcompany/Const.java | 05184d459607e9750e4be32f44c1593d105a6c24 | []
| no_license | appsigma/EcamCompanyAS | https://github.com/appsigma/EcamCompanyAS | d4b6d6b835733f705572c0601c1400135f07518e | e490356317fa5b0d6a9290a377576c6939366932 | refs/heads/master | 2021-05-12T16:42:41.774000 | 2017-12-12T05:04:41 | 2017-12-12T05:04:41 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.howell.webcamforcompany;
/**
* @author 霍之昊
*
* 类说明
*/
public interface Const {
/*Login const*/
public static final String ApplicationId = "yancao";
public static final String ApplicationVersion = "1.0.0";
public static final String PasswordType = "Common";
public static final String InternetUser = "InternetUser";
public static final String PUUser = "PUUser";
public static final int TRUE = 1;
public static final int FALSE = 0;
public static final int FAVOURITEACTIVITY = 1;
public static final int VIDEOSOURCEACTIVITY = 2;
}
| UTF-8 | Java | 575 | java | Const.java | Java | [
{
"context": "m.example.howell.webcamforcompany;\n/**\n * @author 霍之昊 \n *\n * 类说明\n */\npublic interface Const {\n\t/*Login ",
"end": 63,
"score": 0.9998138546943665,
"start": 60,
"tag": "NAME",
"value": "霍之昊"
},
{
"context": "netUser\";\n\tpublic static final String PUUser = \"PUUser\";\n\tpublic static final int TRUE = 1;\n\tpublic stat",
"end": 389,
"score": 0.6198209524154663,
"start": 385,
"tag": "USERNAME",
"value": "User"
}
]
| null | []
| package com.example.howell.webcamforcompany;
/**
* @author 霍之昊
*
* 类说明
*/
public interface Const {
/*Login const*/
public static final String ApplicationId = "yancao";
public static final String ApplicationVersion = "1.0.0";
public static final String PasswordType = "Common";
public static final String InternetUser = "InternetUser";
public static final String PUUser = "PUUser";
public static final int TRUE = 1;
public static final int FALSE = 0;
public static final int FAVOURITEACTIVITY = 1;
public static final int VIDEOSOURCEACTIVITY = 2;
}
| 575 | 0.744227 | 0.731794 | 18 | 30.277779 | 20.794779 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.111111 | false | false | 0 |
0b338c7a582c9b923784588b18fd4a4fe228c885 | 7,490,422,978,459 | 31632f2122718fb386b6627a58b6b5657097fd84 | /accountService/src/main/java/com/bank/account/config/ConfigAccount.java | f5adfcfe33d2af450a0817c89f6444dfbecfd89c | []
| no_license | javapr89/myappsample | https://github.com/javapr89/myappsample | aa1df4db5d41231f5d2aa8bfbf9cd16a68758b3a | e9c7cd5c142d916585b8c701a1e897187e7b827b | refs/heads/main | 2023-01-12T06:08:51.413000 | 2020-11-13T12:54:12 | 2020-11-13T12:54:12 | 312,579,577 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bank.account.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.bank.account.repository.AccountRepositoryDAO;
import com.bank.account.service.AccountServiceI;
import com.bank.account.service.AccountServiceImpl;
@Configuration
public class ConfigAccount {
//service Bean
@Bean
public AccountServiceI getaccountservicebean()
{
return new AccountServiceImpl();
}
/*
* public AccountRepositoryDAO getAccountRepositoryDAO() { return new
* AccountRepositoryDAO(); }
*/
}
| UTF-8 | Java | 588 | java | ConfigAccount.java | Java | []
| null | []
| package com.bank.account.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.bank.account.repository.AccountRepositoryDAO;
import com.bank.account.service.AccountServiceI;
import com.bank.account.service.AccountServiceImpl;
@Configuration
public class ConfigAccount {
//service Bean
@Bean
public AccountServiceI getaccountservicebean()
{
return new AccountServiceImpl();
}
/*
* public AccountRepositoryDAO getAccountRepositoryDAO() { return new
* AccountRepositoryDAO(); }
*/
}
| 588 | 0.785714 | 0.785714 | 29 | 19.275862 | 22.650106 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.862069 | false | false | 0 |
6a5562136ff05e1edbd5e1b5d815614655815e14 | 7,490,422,980,190 | 58847e1696150553999e8229c3a0ddf256c96a0f | /StorageTransferService/src/main/java/com/sunlight/storage/transfer/logic/depend/fallback/WarehouseServiceFallBack.java | 575a74864d4f0f4ca529b66754c9dedaf05c3fd8 | []
| no_license | zhoufanz/spring-cloud | https://github.com/zhoufanz/spring-cloud | d1d28673a213436bf7286d2eeaae9a9b587d9b43 | 7a905e908ce78cc48d1c69efbbeccd627695a028 | refs/heads/master | 2021-01-25T13:12:07.682000 | 2018-03-02T07:07:32 | 2018-03-02T07:07:32 | 123,542,624 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sunlight.storage.transfer.logic.depend.fallback;
import com.sunlight.storage.transfer.logic.depend.service.WarehouseServiceClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
import java.util.Map;
/**
* Created by Nicholas on 16/12/28.
*/
@Component
public class WarehouseServiceFallBack implements WarehouseServiceClient {
@Override
public void checkWarehouseArea(@RequestParam("queryCriterias") String queryCriterias, @RequestParam("warehouseId") Integer warehouseId) {
}
@Override
public List<Map<String, String>> findWarehouseByUserId(@PathVariable("id") int id) {
return null;
}
@Override
public Map<String, Object> findWarehouseById(@PathVariable("id") int id) {
return null;
}
@Override
public Map<String, Object> findWarehouseAreaById(@PathVariable("id") int id) {
return null;
}
@Override
public Integer findCheckAreaIdByIds(@PathVariable("warehouseId") int warehouseId) {
return null;
}
}
| UTF-8 | Java | 1,163 | java | WarehouseServiceFallBack.java | Java | [
{
"context": "til.List;\nimport java.util.Map;\n\n/**\n * Created by Nicholas on 16/12/28.\n */\n@Component\npublic class Warehous",
"end": 388,
"score": 0.999647319316864,
"start": 380,
"tag": "NAME",
"value": "Nicholas"
}
]
| null | []
| package com.sunlight.storage.transfer.logic.depend.fallback;
import com.sunlight.storage.transfer.logic.depend.service.WarehouseServiceClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
import java.util.Map;
/**
* Created by Nicholas on 16/12/28.
*/
@Component
public class WarehouseServiceFallBack implements WarehouseServiceClient {
@Override
public void checkWarehouseArea(@RequestParam("queryCriterias") String queryCriterias, @RequestParam("warehouseId") Integer warehouseId) {
}
@Override
public List<Map<String, String>> findWarehouseByUserId(@PathVariable("id") int id) {
return null;
}
@Override
public Map<String, Object> findWarehouseById(@PathVariable("id") int id) {
return null;
}
@Override
public Map<String, Object> findWarehouseAreaById(@PathVariable("id") int id) {
return null;
}
@Override
public Integer findCheckAreaIdByIds(@PathVariable("warehouseId") int warehouseId) {
return null;
}
}
| 1,163 | 0.736887 | 0.731728 | 40 | 28.075001 | 34.02454 | 141 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false | 0 |
e43474a343d8ce94c99e925734700e63951e6449 | 9,603,546,892,195 | f5ec8bece047224fed97fbec1d5759410549353f | /podium-common/src/main/java/nl/thehyve/podium/common/exceptions/ActionNotAllowed.java | 0fedd69c14eb20bfe9e7c88bfe9636d5772bc368 | [
"LicenseRef-scancode-philippe-de-muyter",
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
]
| permissive | thehyve/podium | https://github.com/thehyve/podium | f271e8deb4a8d5385acc89c163f998e2c806ae09 | 158e222bd03d23a4696c94b1e45aa1bfcead8038 | refs/heads/dev | 2023-01-27T14:04:53.239000 | 2021-09-13T20:35:59 | 2021-09-13T20:35:59 | 80,543,393 | 13 | 5 | NOASSERTION | false | 2023-01-07T06:48:17 | 2017-01-31T17:23:37 | 2022-02-17T12:01:08 | 2023-01-07T06:48:17 | 26,420 | 12 | 5 | 23 | Java | false | false | /*
* Copyright (c) 2017 The Hyve and respective contributors.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the file LICENSE in the root of this repository.
*/
package nl.thehyve.podium.common.exceptions;
import nl.thehyve.podium.common.enumeration.Status;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public class ActionNotAllowed extends Exception {
public ActionNotAllowed(String msg) {
super(msg);
}
public ActionNotAllowed(String msg, Throwable t) {
super(msg, t);
}
public static ActionNotAllowed forStatus(Status status) {
return new ActionNotAllowed("Action not allowed in status: " + status.name());
}
}
| UTF-8 | Java | 876 | java | ActionNotAllowed.java | Java | []
| null | []
| /*
* Copyright (c) 2017 The Hyve and respective contributors.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the file LICENSE in the root of this repository.
*/
package nl.thehyve.podium.common.exceptions;
import nl.thehyve.podium.common.enumeration.Status;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public class ActionNotAllowed extends Exception {
public ActionNotAllowed(String msg) {
super(msg);
}
public ActionNotAllowed(String msg, Throwable t) {
super(msg, t);
}
public static ActionNotAllowed forStatus(Status status) {
return new ActionNotAllowed("Action not allowed in status: " + status.name());
}
}
| 876 | 0.732877 | 0.726027 | 28 | 30.285715 | 27.565321 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.392857 | false | false | 0 |
959e29e0cf2c30be8d02e2f63362889c8e833411 | 33,492,154,991,376 | c3e4b52a91519f19de9ecf7175f99878b003b771 | /lmf/lvmofangCanRun/GreenCube-Server/src/main/java/com/cnd/greencube/server/business/impl/LoginBusinessImpl.java | 1fe06a972d7659832e9acda4516cb68d8c6d2a5f | []
| no_license | chenlian2015/clserver | https://github.com/chenlian2015/clserver | 99f4d25ee5e8540caa7f7d4fe8f724db4e8fb09a | b75cb07582c1266b7d8ed7befec56b89c8dfeafc | refs/heads/master | 2021-01-23T18:22:37.435000 | 2017-03-07T12:03:02 | 2017-03-07T12:03:02 | 82,997,444 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright 2005-2020 GreenTube Team All rights reserved.
* Support: Huxg
* License: CND team license
*/
package com.cnd.greencube.server.business.impl;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;
import com.cnd.greencube.server.business.LoginBusiness;
import com.cnd.greencube.server.dao.UserDao;
import com.cnd.greencube.server.dao.redis.JedisTemplate;
import com.cnd.greencube.server.dao.redis.JedisTemplate.JedisAction;
import com.cnd.greencube.server.dao.redis.RedisDaoSupportImpl;
import com.cnd.greencube.server.entity.User;
import com.cnd.greencube.server.util.encrypt.Encryption;
import com.thoughtworks.xstream.XStream;
/**
* 登录服务实现类
*
* @version 1.0
*/
@Service("LoginBusinessImpl")
public class LoginBusinessImpl extends BaseBusinessImpl<User, String> implements LoginBusiness {
// 登录缓存
public static final String LOGIN_USER_CACHE = "MAP_USER_CACHE1";
@Resource(name = "jedisTemplate")
protected JedisTemplate jedisTemplate;
@Resource(name = "UserDaoImpl")
protected UserDao userDao;
/**
* 登录接口
*
* @param username
* -- 用户名
* @param pwd
* -- 密码
* @param verifycode
* -- 验证码
* @param pwdEncrypted
* -- 是否已经对密码做了MD5加密,如果名为密码则传递false,如果是已加密的密码则传递true
* @param usertype
* -- 用户类型
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public User login(final String username, final String pwd, final String verifycode, boolean pwdEncrypted, String usertype) throws Exception {
try {
final String password = !pwdEncrypted ? Encryption.encodeMD5(pwd) : pwd;
User user = (User) jedisTemplate.execute(new JedisAction() {
@Override
public Object action(Jedis jedis) {
String id = jedis.hget(LOGIN_USER_CACHE, username + ":" + password);
User user = null;
if (!StringUtils.isEmpty(id)) {
String xml = jedis.hget(RedisDaoSupportImpl.POOL + "User", id);
if (!StringUtils.isEmpty(xml)) {
try {
XStream x = new XStream();
user = (User) x.fromXML(xml);
} catch (Exception e) {
}
}
}
return user;
}
});
if (user == null)
user = userDao.getUserByUserNameAndPassword(username, password);
return user;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 退出登录接口
*
* @param userid
* -- 用户id
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
@Transactional
public void logout(String userid) {
// 设置用户退出时间
final User user = super.get(userid);
if (user != null) {
user.setLastLoginTime(null);
super.update(user);
jedisTemplate.execute(new JedisAction() {
@Override
public Object action(Jedis jedis) {
XStream x = new XStream();
String userxml = x.toXML(user);
jedis.hset(RedisDaoSupportImpl.POOL + "User", user.getId(), userxml);
return null;
}
});
}
}
} | UTF-8 | Java | 3,232 | java | LoginBusinessImpl.java | Java | [
{
"context": " -- 用户名\n\t * @param pwd\n\t * -- 密码\n\t * @param verifycode\n\t * -- 验证码\n\t * @",
"end": 1300,
"score": 0.689915657043457,
"start": 1298,
"tag": "PASSWORD",
"value": "密码"
}
]
| null | []
| /*
* Copyright 2005-2020 GreenTube Team All rights reserved.
* Support: Huxg
* License: CND team license
*/
package com.cnd.greencube.server.business.impl;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;
import com.cnd.greencube.server.business.LoginBusiness;
import com.cnd.greencube.server.dao.UserDao;
import com.cnd.greencube.server.dao.redis.JedisTemplate;
import com.cnd.greencube.server.dao.redis.JedisTemplate.JedisAction;
import com.cnd.greencube.server.dao.redis.RedisDaoSupportImpl;
import com.cnd.greencube.server.entity.User;
import com.cnd.greencube.server.util.encrypt.Encryption;
import com.thoughtworks.xstream.XStream;
/**
* 登录服务实现类
*
* @version 1.0
*/
@Service("LoginBusinessImpl")
public class LoginBusinessImpl extends BaseBusinessImpl<User, String> implements LoginBusiness {
// 登录缓存
public static final String LOGIN_USER_CACHE = "MAP_USER_CACHE1";
@Resource(name = "jedisTemplate")
protected JedisTemplate jedisTemplate;
@Resource(name = "UserDaoImpl")
protected UserDao userDao;
/**
* 登录接口
*
* @param username
* -- 用户名
* @param pwd
* -- 密码
* @param verifycode
* -- 验证码
* @param pwdEncrypted
* -- 是否已经对密码做了MD5加密,如果名为密码则传递false,如果是已加密的密码则传递true
* @param usertype
* -- 用户类型
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public User login(final String username, final String pwd, final String verifycode, boolean pwdEncrypted, String usertype) throws Exception {
try {
final String password = !pwdEncrypted ? Encryption.encodeMD5(pwd) : pwd;
User user = (User) jedisTemplate.execute(new JedisAction() {
@Override
public Object action(Jedis jedis) {
String id = jedis.hget(LOGIN_USER_CACHE, username + ":" + password);
User user = null;
if (!StringUtils.isEmpty(id)) {
String xml = jedis.hget(RedisDaoSupportImpl.POOL + "User", id);
if (!StringUtils.isEmpty(xml)) {
try {
XStream x = new XStream();
user = (User) x.fromXML(xml);
} catch (Exception e) {
}
}
}
return user;
}
});
if (user == null)
user = userDao.getUserByUserNameAndPassword(username, password);
return user;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 退出登录接口
*
* @param userid
* -- 用户id
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
@Transactional
public void logout(String userid) {
// 设置用户退出时间
final User user = super.get(userid);
if (user != null) {
user.setLastLoginTime(null);
super.update(user);
jedisTemplate.execute(new JedisAction() {
@Override
public Object action(Jedis jedis) {
XStream x = new XStream();
String userxml = x.toXML(user);
jedis.hset(RedisDaoSupportImpl.POOL + "User", user.getId(), userxml);
return null;
}
});
}
}
} | 3,232 | 0.675649 | 0.671429 | 119 | 24.890757 | 24.471485 | 142 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.210084 | false | false | 0 |
38bf2e9e0eaf5fe10217d88fb67a20e751f1630f | 16,621,523,455,658 | 71d5ae8408cbb5a9713c12a3999f17c1c47fb621 | /appglu-java-client/src/main/java/com/appglu/AppGluHttpInternalServerErrorException.java | d402d94246060d7a6e9f4caa6efb2ae8201ddf45 | [
"Apache-2.0"
]
| permissive | michelzanini/appglu-androidsdk | https://github.com/michelzanini/appglu-androidsdk | 861431ce37868a0f1f1559fbaeabc248a0f092dd | da494fe92a77688735e87df3e5fe0de9d50640e2 | refs/heads/master | 2016-09-09T22:04:13.001000 | 2013-05-15T03:50:19 | 2013-05-15T03:50:19 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*******************************************************************************
* Copyright 2013 AppGlu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.appglu;
import org.springframework.http.HttpStatus;
/**
* Represents an HTTP status error code of 500 (Generic Server Error).
* @since 1.0.0
*/
@SuppressWarnings("serial")
public class AppGluHttpInternalServerErrorException extends AppGluHttpServerException {
static final int STATUS_CODE = HttpStatus.INTERNAL_SERVER_ERROR.value();
static final String ERROR_MESSAGE = "An unexpected error occurred while processing your request. Please try again later.";
static final Error GENERIC_SERVER_ERROR = new Error(ErrorCode.GENERIC_SERVER_ERROR, ERROR_MESSAGE);
public AppGluHttpInternalServerErrorException() {
super(STATUS_CODE, GENERIC_SERVER_ERROR);
}
}
| UTF-8 | Java | 1,437 | java | AppGluHttpInternalServerErrorException.java | Java | []
| null | []
| /*******************************************************************************
* Copyright 2013 AppGlu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.appglu;
import org.springframework.http.HttpStatus;
/**
* Represents an HTTP status error code of 500 (Generic Server Error).
* @since 1.0.0
*/
@SuppressWarnings("serial")
public class AppGluHttpInternalServerErrorException extends AppGluHttpServerException {
static final int STATUS_CODE = HttpStatus.INTERNAL_SERVER_ERROR.value();
static final String ERROR_MESSAGE = "An unexpected error occurred while processing your request. Please try again later.";
static final Error GENERIC_SERVER_ERROR = new Error(ErrorCode.GENERIC_SERVER_ERROR, ERROR_MESSAGE);
public AppGluHttpInternalServerErrorException() {
super(STATUS_CODE, GENERIC_SERVER_ERROR);
}
}
| 1,437 | 0.676409 | 0.666667 | 38 | 36.815788 | 35.035213 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.631579 | false | false | 0 |
aa4a5a13681fa182221752914b49fb6fb0743f80 | 16,621,523,457,743 | a922ef53c17abac1b560351fca0a4ed12c1494d5 | /second_project/app/src/main/java/com/example/hpuser/second_project/MainActivity.java | 13b83bc18ea765790a9284266fef4ec7afe51796 | []
| no_license | akshatrana22/android-test-basics | https://github.com/akshatrana22/android-test-basics | 9f19203d60fa24427feb15b67d8f246249ca38c6 | ea2bab16c6d07e76ad2db468f1de14a6bcb61de5 | refs/heads/master | 2020-03-19T06:10:38.438000 | 2018-06-04T10:25:19 | 2018-06-04T10:25:19 | 135,997,276 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.hpuser.second_project;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText e1;
EditText e2;
EditText e3;
Button b1;
Button b2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e1= findViewById(R.id.name_1);
e2= findViewById(R.id.fees_1);
e3= findViewById(R.id.course_1);
b1= findViewById(R.id.display_1);
b2= findViewById(R.id.submit_2);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String s = String.valueOf(e1.getText());
int f = Integer.parseInt(e2.getText().toString());
int c = Integer.parseInt(e3.getText().toString());
Toast.makeText(getApplicationContext(), "name is" + e1 + "course is" + c + "fees is" + f, Toast.LENGTH_LONG).show();
}
});
}
}
| UTF-8 | Java | 1,269 | java | MainActivity.java | Java | []
| null | []
| package com.example.hpuser.second_project;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText e1;
EditText e2;
EditText e3;
Button b1;
Button b2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e1= findViewById(R.id.name_1);
e2= findViewById(R.id.fees_1);
e3= findViewById(R.id.course_1);
b1= findViewById(R.id.display_1);
b2= findViewById(R.id.submit_2);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String s = String.valueOf(e1.getText());
int f = Integer.parseInt(e2.getText().toString());
int c = Integer.parseInt(e3.getText().toString());
Toast.makeText(getApplicationContext(), "name is" + e1 + "course is" + c + "fees is" + f, Toast.LENGTH_LONG).show();
}
});
}
}
| 1,269 | 0.636722 | 0.620173 | 43 | 28.418604 | 25.912403 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.627907 | false | false | 0 |
6cb4d07bfb78e02b8308aff61d3297f54c9bc3b6 | 25,804,163,535,152 | f71f0b521a292233cfc81217b230be95057239cc | /src/main/java/com/java7developer/chapter3/AgentFinder.java | 30fbd0992961c033dacf6a2881d5de272ed36ff8 | []
| no_license | shiningguang/javaDeveloper | https://github.com/shiningguang/javaDeveloper | b90a30532639dab36113172b7f39c7b80aa69804 | 8e189a12ec8071c40866b749c4d7050b6c515f18 | refs/heads/master | 2020-04-19T09:19:36.641000 | 2016-09-08T04:41:55 | 2016-09-08T04:41:55 | 67,668,401 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.java7developer.chapter3;
import java.util.List;
/**
* Code for listing 3_1 - AgentFinder interface
*/
public interface AgentFinder {
public List<Agent> findAllAgents();
}
| UTF-8 | Java | 191 | java | AgentFinder.java | Java | []
| null | []
| package com.java7developer.chapter3;
import java.util.List;
/**
* Code for listing 3_1 - AgentFinder interface
*/
public interface AgentFinder {
public List<Agent> findAllAgents();
}
| 191 | 0.732984 | 0.712042 | 12 | 14.916667 | 17.337139 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 0 |
8b180e60b9022934338cacf62016cc51b7b5c22c | 12,094,627,926,876 | 30e616ef6f662bb71c33017a59c0e8ec149a21a8 | /cometd-java/cometd-java-server/cometd-java-server-websocket/cometd-java-server-websocket-tests/src/test/java/org/cometd/server/websocket/BayeuxClientTest.java | 365b4ca87aac77f4019a4d964b1314c40297882d | [
"Apache-2.0"
]
| permissive | cometd/cometd | https://github.com/cometd/cometd | b17aa4b3eb5781e7aca751b5b475989ae7dfe237 | 1d2d31401833dd95d11800bf53602aad0b1c68a7 | refs/heads/6.0.x | 2023-08-30T21:50:40.019000 | 2023-08-25T09:27:43 | 2023-08-25T09:27:43 | 1,765,693 | 426 | 192 | Apache-2.0 | false | 2023-09-11T07:37:04 | 2011-05-18T11:55:11 | 2023-09-05T09:19:14 | 2023-09-11T07:37:04 | 25,521 | 554 | 210 | 61 | Java | false | false | /*
* Copyright (c) 2008-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cometd.server.websocket;
import java.io.IOException;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import org.cometd.bayeux.Channel;
import org.cometd.bayeux.MarkedReference;
import org.cometd.bayeux.Message;
import org.cometd.bayeux.client.ClientSessionChannel;
import org.cometd.bayeux.server.BayeuxServer;
import org.cometd.bayeux.server.SecurityPolicy;
import org.cometd.bayeux.server.ServerChannel;
import org.cometd.bayeux.server.ServerMessage;
import org.cometd.bayeux.server.ServerMessage.Mutable;
import org.cometd.bayeux.server.ServerSession;
import org.cometd.client.BayeuxClient;
import org.cometd.client.BayeuxClient.State;
import org.cometd.client.http.jetty.JettyHttpClientTransport;
import org.cometd.client.transport.ClientTransport;
import org.cometd.common.HashMapMessage;
import org.cometd.server.DefaultSecurityPolicy;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.util.BlockingArrayQueue;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class BayeuxClientTest extends ClientServerWebSocketTest {
@ParameterizedTest
@MethodSource("wsTypes")
public void testHandshakeDenied(String wsType) throws Exception {
prepareAndStart(wsType, null);
BayeuxClient client = newBayeuxClient(wsType);
long backOffIncrement = 500;
client.setBackOffStrategy(new BayeuxClient.BackOffStrategy.Linear(backOffIncrement, -1));
SecurityPolicy oldPolicy = bayeux.getSecurityPolicy();
bayeux.setSecurityPolicy(new DefaultSecurityPolicy() {
@Override
public boolean canHandshake(BayeuxServer server, ServerSession session, ServerMessage message) {
return false;
}
});
try {
AtomicReference<CountDownLatch> latch = new AtomicReference<>(new CountDownLatch(1));
client.getChannel(Channel.META_HANDSHAKE).addListener((ClientSessionChannel.MessageListener)(channel, message) -> {
Assertions.assertFalse(message.isSuccessful());
latch.get().countDown();
});
client.handshake();
Assertions.assertTrue(latch.get().await(5, TimeUnit.SECONDS));
// Be sure it does not retry
latch.set(new CountDownLatch(1));
Assertions.assertFalse(latch.get().await(backOffIncrement * 2, TimeUnit.MILLISECONDS));
Assertions.assertTrue(client.waitFor(5000, State.DISCONNECTED));
} finally {
bayeux.setSecurityPolicy(oldPolicy);
disconnectBayeuxClient(client);
}
}
@ParameterizedTest
@MethodSource("wsTypes")
public void testPublish(String wsType) throws Exception {
prepareAndStart(wsType, null);
BlockingArrayQueue<String> results = new BlockingArrayQueue<>();
String channelName = "/chat/msg";
MarkedReference<ServerChannel> channel = bayeux.createChannelIfAbsent(channelName);
channel.getReference().addListener(new ServerChannel.MessageListener() {
@Override
public boolean onMessage(ServerSession from, ServerChannel channel, Mutable message) {
results.add(from.getId());
results.add(channel.getId());
results.add(String.valueOf(message.getData()));
return true;
}
});
BayeuxClient client = newBayeuxClient(wsType);
client.handshake();
Assertions.assertTrue(client.waitFor(5000, State.CONNECTED));
String data = "Hello World";
client.getChannel(channelName).publish(data);
String id = results.poll(10, TimeUnit.SECONDS);
Assertions.assertEquals(client.getId(), id);
Assertions.assertEquals(channelName, results.poll(10, TimeUnit.SECONDS));
Assertions.assertEquals(data, results.poll(10, TimeUnit.SECONDS));
disconnectBayeuxClient(client);
}
@ParameterizedTest
@MethodSource("wsTypes")
public void testWaitFor(String wsType) throws Exception {
prepareAndStart(wsType, null);
BlockingArrayQueue<String> results = new BlockingArrayQueue<>();
String channelName = "/chat/msg";
MarkedReference<ServerChannel> channel = bayeux.createChannelIfAbsent(channelName);
channel.getReference().addListener(new ServerChannel.MessageListener() {
@Override
public boolean onMessage(ServerSession from, ServerChannel channel, Mutable message) {
results.add(from.getId());
results.add(channel.getId());
results.add(String.valueOf(message.getData()));
return true;
}
});
BayeuxClient client = newBayeuxClient(wsType);
long wait = 1000L;
long start = System.nanoTime();
client.handshake(wait);
long stop = System.nanoTime();
Assertions.assertTrue(TimeUnit.NANOSECONDS.toMillis(stop - start) < wait);
Assertions.assertNotNull(client.getId());
String data = "Hello World";
CountDownLatch latch = new CountDownLatch(1);
client.getChannel(channelName).addListener((ClientSessionChannel.MessageListener)(c, m) -> latch.countDown());
client.getChannel(channelName).publish(data);
Assertions.assertEquals(client.getId(), results.poll(1, TimeUnit.SECONDS));
Assertions.assertEquals(channelName, results.poll(1, TimeUnit.SECONDS));
Assertions.assertEquals(data, results.poll(1, TimeUnit.SECONDS));
Assertions.assertTrue(latch.await(5, TimeUnit.SECONDS));
disconnectBayeuxClient(client);
}
@ParameterizedTest
@MethodSource("wsTypes")
public void testAuthentication(String wsType) throws Exception {
prepareAndStart(wsType, null);
AtomicReference<String> sessionId = new AtomicReference<>();
class A extends DefaultSecurityPolicy implements ServerSession.RemovedListener {
@Override
public boolean canHandshake(BayeuxServer server, ServerSession session, ServerMessage message) {
Map<String, Object> ext = message.getExt();
if (ext == null) {
return false;
}
Object authn = ext.get("authentication");
if (!(authn instanceof Map)) {
return false;
}
@SuppressWarnings("unchecked")
Map<String, Object> authentication = (Map<String, Object>)authn;
String token = (String)authentication.get("token");
if (token == null) {
return false;
}
sessionId.set(session.getId());
session.addListener(this);
return true;
}
@Override
public void removed(ServerSession session, ServerMessage message, boolean timeout) {
sessionId.set(null);
}
}
A authenticator = new A();
SecurityPolicy oldPolicy = bayeux.getSecurityPolicy();
bayeux.setSecurityPolicy(authenticator);
try {
BayeuxClient client = newBayeuxClient(wsType);
Map<String, Object> authentication = new HashMap<>();
authentication.put("token", "1234567890");
Message.Mutable fields = new HashMapMessage();
fields.getExt(true).put("authentication", authentication);
client.handshake(fields);
Assertions.assertTrue(client.waitFor(5000, State.CONNECTED));
Assertions.assertEquals(client.getId(), sessionId.get());
disconnectBayeuxClient(client);
Assertions.assertNull(sessionId.get());
} finally {
bayeux.setSecurityPolicy(oldPolicy);
}
}
@ParameterizedTest
@MethodSource("wsTypes")
public void testClient(String wsType) throws Exception {
prepareAndStart(wsType, null);
BayeuxClient client = newBayeuxClient(wsType);
CountDownLatch handshakeLatch = new CountDownLatch(1);
client.getChannel(Channel.META_HANDSHAKE).addListener((ClientSessionChannel.MessageListener)(channel, message) -> {
logger.info("<< {} @ {}", message, channel);
if (message.isSuccessful()) {
handshakeLatch.countDown();
}
});
CountDownLatch connectLatch = new CountDownLatch(1);
client.getChannel(Channel.META_CONNECT).addListener((ClientSessionChannel.MessageListener)(channel, message) -> {
logger.info("<< {} @ {}", message, channel);
if (message.isSuccessful()) {
connectLatch.countDown();
}
});
CountDownLatch subscribeLatch = new CountDownLatch(1);
client.getChannel(Channel.META_SUBSCRIBE).addListener((ClientSessionChannel.MessageListener)(channel, message) -> {
logger.info("<< {} @ {}", message, channel);
if (message.isSuccessful()) {
subscribeLatch.countDown();
}
});
CountDownLatch unsubscribeLatch = new CountDownLatch(1);
client.getChannel(Channel.META_SUBSCRIBE).addListener((ClientSessionChannel.MessageListener)(channel, message) -> {
logger.info("<< {} @ {}", message, channel);
if (message.isSuccessful()) {
unsubscribeLatch.countDown();
}
});
client.handshake();
Assertions.assertTrue(handshakeLatch.await(5, TimeUnit.SECONDS));
Assertions.assertTrue(connectLatch.await(5, TimeUnit.SECONDS));
CountDownLatch publishLatch = new CountDownLatch(1);
ClientSessionChannel.MessageListener subscriber = (channel, message) -> {
logger.info(" < {} @ {}", message, channel);
publishLatch.countDown();
};
ClientSessionChannel aChannel = client.getChannel("/a/channel");
aChannel.subscribe(subscriber);
Assertions.assertTrue(subscribeLatch.await(5, TimeUnit.SECONDS));
String data = "data";
aChannel.publish(data);
Assertions.assertTrue(publishLatch.await(5, TimeUnit.SECONDS));
aChannel.unsubscribe(subscriber);
Assertions.assertTrue(unsubscribeLatch.await(5, TimeUnit.SECONDS));
disconnectBayeuxClient(client);
}
@Disabled("TODO: verify why it does not work; I suspect the setAllowedTransport() does not play since the WSUpgradeFilter kicks in first")
@ParameterizedTest
@MethodSource("wsTypes")
public void testHandshakeOverWebSocketReportsHTTPFailure(String wsType) throws Exception {
prepareAndStart(wsType, null);
// No transports on server, to make the client fail
bayeux.setAllowedTransports();
BayeuxClient client = newBayeuxClient(wsType);
CountDownLatch latch = new CountDownLatch(1);
client.getChannel(Channel.META_HANDSHAKE).addListener((ClientSessionChannel.MessageListener)(channel, message) -> {
// Verify the failure object is there
@SuppressWarnings("unchecked")
Map<String, Object> failure = (Map<String, Object>)message.get("failure");
Assertions.assertNotNull(failure);
// Verify that the transport is there
Assertions.assertEquals("websocket", failure.get(Message.CONNECTION_TYPE_FIELD));
// Verify the original message is there
Assertions.assertNotNull(failure.get("message"));
// Verify the HTTP status code is there
Assertions.assertEquals(400, failure.get("httpCode"));
// Verify the exception string is there
Assertions.assertNotNull(failure.get("exception"));
latch.countDown();
});
client.handshake();
Assertions.assertTrue(latch.await(5, TimeUnit.SECONDS));
disconnectBayeuxClient(client);
}
// The test filter is not called because the WebSocketUpgradeFilter is added first.
// Also, the WS implementation adds headers directly to HttpFields, and flushes the
// response so they cannot be removed/intercepted before they are sent to the client.
@Disabled
@ParameterizedTest
@MethodSource("wsTypes")
public void testWebSocketResponseHeadersRemoved(String wsType) throws Exception {
prepareAndStart(wsType, null);
context.addFilter(new FilterHolder(new Filter() {
@Override
public void init(FilterConfig filterConfig) {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
try {
// Wrap the response to remove the header
chain.doFilter(request, new HttpServletResponseWrapper((HttpServletResponse)response) {
@Override
public void addHeader(String name, String value) {
if (!"Sec-WebSocket-Accept".equals(name)) {
super.addHeader(name, value);
}
}
});
} finally {
((HttpServletResponse)response).setHeader("Sec-WebSocket-Accept", null);
}
}
@Override
public void destroy() {
}
}), cometdServletPath, EnumSet.of(DispatcherType.REQUEST, DispatcherType.ASYNC));
ClientTransport webSocketTransport = newWebSocketTransport(wsType, null);
ClientTransport longPollingTransport = newLongPollingTransport(null);
BayeuxClient client = new BayeuxClient(cometdURL, webSocketTransport, longPollingTransport);
CountDownLatch latch = new CountDownLatch(1);
client.getChannel(Channel.META_CONNECT).addListener((ClientSessionChannel.MessageListener)(channel, message) -> {
if (message.isSuccessful()) {
Assertions.assertEquals(JettyHttpClientTransport.NAME, client.getTransport().getName());
latch.countDown();
}
});
client.handshake();
Assertions.assertTrue(latch.await(5, TimeUnit.SECONDS));
disconnectBayeuxClient(client);
}
@ParameterizedTest
@MethodSource("wsTypes")
public void testCustomTransportURL(String wsType) throws Exception {
prepareAndStart(wsType, null);
ClientTransport transport = newWebSocketTransport(wsType, cometdURL, null);
// Pass a bogus URL that must not be used
BayeuxClient client = new BayeuxClient("http://foo/bar", transport);
client.handshake();
Assertions.assertTrue(client.waitFor(5000, State.CONNECTED));
disconnectBayeuxClient(client);
}
}
| UTF-8 | Java | 16,152 | java | BayeuxClientTest.java | Java | [
{
"context": "Map<>();\n authentication.put(\"token\", \"1234567890\");\n Message.Mutable fields = ",
"end": 8610,
"score": 0.5452255606651306,
"start": 8609,
"tag": "KEY",
"value": "1"
},
{
"context": "ap<>();\n authentication.put(\"token\", \"1234567890\");\n Message.Mutable fields = new HashM",
"end": 8619,
"score": 0.7556423544883728,
"start": 8610,
"tag": "PASSWORD",
"value": "234567890"
}
]
| null | []
| /*
* Copyright (c) 2008-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cometd.server.websocket;
import java.io.IOException;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import org.cometd.bayeux.Channel;
import org.cometd.bayeux.MarkedReference;
import org.cometd.bayeux.Message;
import org.cometd.bayeux.client.ClientSessionChannel;
import org.cometd.bayeux.server.BayeuxServer;
import org.cometd.bayeux.server.SecurityPolicy;
import org.cometd.bayeux.server.ServerChannel;
import org.cometd.bayeux.server.ServerMessage;
import org.cometd.bayeux.server.ServerMessage.Mutable;
import org.cometd.bayeux.server.ServerSession;
import org.cometd.client.BayeuxClient;
import org.cometd.client.BayeuxClient.State;
import org.cometd.client.http.jetty.JettyHttpClientTransport;
import org.cometd.client.transport.ClientTransport;
import org.cometd.common.HashMapMessage;
import org.cometd.server.DefaultSecurityPolicy;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.util.BlockingArrayQueue;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class BayeuxClientTest extends ClientServerWebSocketTest {
@ParameterizedTest
@MethodSource("wsTypes")
public void testHandshakeDenied(String wsType) throws Exception {
prepareAndStart(wsType, null);
BayeuxClient client = newBayeuxClient(wsType);
long backOffIncrement = 500;
client.setBackOffStrategy(new BayeuxClient.BackOffStrategy.Linear(backOffIncrement, -1));
SecurityPolicy oldPolicy = bayeux.getSecurityPolicy();
bayeux.setSecurityPolicy(new DefaultSecurityPolicy() {
@Override
public boolean canHandshake(BayeuxServer server, ServerSession session, ServerMessage message) {
return false;
}
});
try {
AtomicReference<CountDownLatch> latch = new AtomicReference<>(new CountDownLatch(1));
client.getChannel(Channel.META_HANDSHAKE).addListener((ClientSessionChannel.MessageListener)(channel, message) -> {
Assertions.assertFalse(message.isSuccessful());
latch.get().countDown();
});
client.handshake();
Assertions.assertTrue(latch.get().await(5, TimeUnit.SECONDS));
// Be sure it does not retry
latch.set(new CountDownLatch(1));
Assertions.assertFalse(latch.get().await(backOffIncrement * 2, TimeUnit.MILLISECONDS));
Assertions.assertTrue(client.waitFor(5000, State.DISCONNECTED));
} finally {
bayeux.setSecurityPolicy(oldPolicy);
disconnectBayeuxClient(client);
}
}
@ParameterizedTest
@MethodSource("wsTypes")
public void testPublish(String wsType) throws Exception {
prepareAndStart(wsType, null);
BlockingArrayQueue<String> results = new BlockingArrayQueue<>();
String channelName = "/chat/msg";
MarkedReference<ServerChannel> channel = bayeux.createChannelIfAbsent(channelName);
channel.getReference().addListener(new ServerChannel.MessageListener() {
@Override
public boolean onMessage(ServerSession from, ServerChannel channel, Mutable message) {
results.add(from.getId());
results.add(channel.getId());
results.add(String.valueOf(message.getData()));
return true;
}
});
BayeuxClient client = newBayeuxClient(wsType);
client.handshake();
Assertions.assertTrue(client.waitFor(5000, State.CONNECTED));
String data = "Hello World";
client.getChannel(channelName).publish(data);
String id = results.poll(10, TimeUnit.SECONDS);
Assertions.assertEquals(client.getId(), id);
Assertions.assertEquals(channelName, results.poll(10, TimeUnit.SECONDS));
Assertions.assertEquals(data, results.poll(10, TimeUnit.SECONDS));
disconnectBayeuxClient(client);
}
@ParameterizedTest
@MethodSource("wsTypes")
public void testWaitFor(String wsType) throws Exception {
prepareAndStart(wsType, null);
BlockingArrayQueue<String> results = new BlockingArrayQueue<>();
String channelName = "/chat/msg";
MarkedReference<ServerChannel> channel = bayeux.createChannelIfAbsent(channelName);
channel.getReference().addListener(new ServerChannel.MessageListener() {
@Override
public boolean onMessage(ServerSession from, ServerChannel channel, Mutable message) {
results.add(from.getId());
results.add(channel.getId());
results.add(String.valueOf(message.getData()));
return true;
}
});
BayeuxClient client = newBayeuxClient(wsType);
long wait = 1000L;
long start = System.nanoTime();
client.handshake(wait);
long stop = System.nanoTime();
Assertions.assertTrue(TimeUnit.NANOSECONDS.toMillis(stop - start) < wait);
Assertions.assertNotNull(client.getId());
String data = "Hello World";
CountDownLatch latch = new CountDownLatch(1);
client.getChannel(channelName).addListener((ClientSessionChannel.MessageListener)(c, m) -> latch.countDown());
client.getChannel(channelName).publish(data);
Assertions.assertEquals(client.getId(), results.poll(1, TimeUnit.SECONDS));
Assertions.assertEquals(channelName, results.poll(1, TimeUnit.SECONDS));
Assertions.assertEquals(data, results.poll(1, TimeUnit.SECONDS));
Assertions.assertTrue(latch.await(5, TimeUnit.SECONDS));
disconnectBayeuxClient(client);
}
@ParameterizedTest
@MethodSource("wsTypes")
public void testAuthentication(String wsType) throws Exception {
prepareAndStart(wsType, null);
AtomicReference<String> sessionId = new AtomicReference<>();
class A extends DefaultSecurityPolicy implements ServerSession.RemovedListener {
@Override
public boolean canHandshake(BayeuxServer server, ServerSession session, ServerMessage message) {
Map<String, Object> ext = message.getExt();
if (ext == null) {
return false;
}
Object authn = ext.get("authentication");
if (!(authn instanceof Map)) {
return false;
}
@SuppressWarnings("unchecked")
Map<String, Object> authentication = (Map<String, Object>)authn;
String token = (String)authentication.get("token");
if (token == null) {
return false;
}
sessionId.set(session.getId());
session.addListener(this);
return true;
}
@Override
public void removed(ServerSession session, ServerMessage message, boolean timeout) {
sessionId.set(null);
}
}
A authenticator = new A();
SecurityPolicy oldPolicy = bayeux.getSecurityPolicy();
bayeux.setSecurityPolicy(authenticator);
try {
BayeuxClient client = newBayeuxClient(wsType);
Map<String, Object> authentication = new HashMap<>();
authentication.put("token", "1<PASSWORD>");
Message.Mutable fields = new HashMapMessage();
fields.getExt(true).put("authentication", authentication);
client.handshake(fields);
Assertions.assertTrue(client.waitFor(5000, State.CONNECTED));
Assertions.assertEquals(client.getId(), sessionId.get());
disconnectBayeuxClient(client);
Assertions.assertNull(sessionId.get());
} finally {
bayeux.setSecurityPolicy(oldPolicy);
}
}
@ParameterizedTest
@MethodSource("wsTypes")
public void testClient(String wsType) throws Exception {
prepareAndStart(wsType, null);
BayeuxClient client = newBayeuxClient(wsType);
CountDownLatch handshakeLatch = new CountDownLatch(1);
client.getChannel(Channel.META_HANDSHAKE).addListener((ClientSessionChannel.MessageListener)(channel, message) -> {
logger.info("<< {} @ {}", message, channel);
if (message.isSuccessful()) {
handshakeLatch.countDown();
}
});
CountDownLatch connectLatch = new CountDownLatch(1);
client.getChannel(Channel.META_CONNECT).addListener((ClientSessionChannel.MessageListener)(channel, message) -> {
logger.info("<< {} @ {}", message, channel);
if (message.isSuccessful()) {
connectLatch.countDown();
}
});
CountDownLatch subscribeLatch = new CountDownLatch(1);
client.getChannel(Channel.META_SUBSCRIBE).addListener((ClientSessionChannel.MessageListener)(channel, message) -> {
logger.info("<< {} @ {}", message, channel);
if (message.isSuccessful()) {
subscribeLatch.countDown();
}
});
CountDownLatch unsubscribeLatch = new CountDownLatch(1);
client.getChannel(Channel.META_SUBSCRIBE).addListener((ClientSessionChannel.MessageListener)(channel, message) -> {
logger.info("<< {} @ {}", message, channel);
if (message.isSuccessful()) {
unsubscribeLatch.countDown();
}
});
client.handshake();
Assertions.assertTrue(handshakeLatch.await(5, TimeUnit.SECONDS));
Assertions.assertTrue(connectLatch.await(5, TimeUnit.SECONDS));
CountDownLatch publishLatch = new CountDownLatch(1);
ClientSessionChannel.MessageListener subscriber = (channel, message) -> {
logger.info(" < {} @ {}", message, channel);
publishLatch.countDown();
};
ClientSessionChannel aChannel = client.getChannel("/a/channel");
aChannel.subscribe(subscriber);
Assertions.assertTrue(subscribeLatch.await(5, TimeUnit.SECONDS));
String data = "data";
aChannel.publish(data);
Assertions.assertTrue(publishLatch.await(5, TimeUnit.SECONDS));
aChannel.unsubscribe(subscriber);
Assertions.assertTrue(unsubscribeLatch.await(5, TimeUnit.SECONDS));
disconnectBayeuxClient(client);
}
@Disabled("TODO: verify why it does not work; I suspect the setAllowedTransport() does not play since the WSUpgradeFilter kicks in first")
@ParameterizedTest
@MethodSource("wsTypes")
public void testHandshakeOverWebSocketReportsHTTPFailure(String wsType) throws Exception {
prepareAndStart(wsType, null);
// No transports on server, to make the client fail
bayeux.setAllowedTransports();
BayeuxClient client = newBayeuxClient(wsType);
CountDownLatch latch = new CountDownLatch(1);
client.getChannel(Channel.META_HANDSHAKE).addListener((ClientSessionChannel.MessageListener)(channel, message) -> {
// Verify the failure object is there
@SuppressWarnings("unchecked")
Map<String, Object> failure = (Map<String, Object>)message.get("failure");
Assertions.assertNotNull(failure);
// Verify that the transport is there
Assertions.assertEquals("websocket", failure.get(Message.CONNECTION_TYPE_FIELD));
// Verify the original message is there
Assertions.assertNotNull(failure.get("message"));
// Verify the HTTP status code is there
Assertions.assertEquals(400, failure.get("httpCode"));
// Verify the exception string is there
Assertions.assertNotNull(failure.get("exception"));
latch.countDown();
});
client.handshake();
Assertions.assertTrue(latch.await(5, TimeUnit.SECONDS));
disconnectBayeuxClient(client);
}
// The test filter is not called because the WebSocketUpgradeFilter is added first.
// Also, the WS implementation adds headers directly to HttpFields, and flushes the
// response so they cannot be removed/intercepted before they are sent to the client.
@Disabled
@ParameterizedTest
@MethodSource("wsTypes")
public void testWebSocketResponseHeadersRemoved(String wsType) throws Exception {
prepareAndStart(wsType, null);
context.addFilter(new FilterHolder(new Filter() {
@Override
public void init(FilterConfig filterConfig) {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
try {
// Wrap the response to remove the header
chain.doFilter(request, new HttpServletResponseWrapper((HttpServletResponse)response) {
@Override
public void addHeader(String name, String value) {
if (!"Sec-WebSocket-Accept".equals(name)) {
super.addHeader(name, value);
}
}
});
} finally {
((HttpServletResponse)response).setHeader("Sec-WebSocket-Accept", null);
}
}
@Override
public void destroy() {
}
}), cometdServletPath, EnumSet.of(DispatcherType.REQUEST, DispatcherType.ASYNC));
ClientTransport webSocketTransport = newWebSocketTransport(wsType, null);
ClientTransport longPollingTransport = newLongPollingTransport(null);
BayeuxClient client = new BayeuxClient(cometdURL, webSocketTransport, longPollingTransport);
CountDownLatch latch = new CountDownLatch(1);
client.getChannel(Channel.META_CONNECT).addListener((ClientSessionChannel.MessageListener)(channel, message) -> {
if (message.isSuccessful()) {
Assertions.assertEquals(JettyHttpClientTransport.NAME, client.getTransport().getName());
latch.countDown();
}
});
client.handshake();
Assertions.assertTrue(latch.await(5, TimeUnit.SECONDS));
disconnectBayeuxClient(client);
}
@ParameterizedTest
@MethodSource("wsTypes")
public void testCustomTransportURL(String wsType) throws Exception {
prepareAndStart(wsType, null);
ClientTransport transport = newWebSocketTransport(wsType, cometdURL, null);
// Pass a bogus URL that must not be used
BayeuxClient client = new BayeuxClient("http://foo/bar", transport);
client.handshake();
Assertions.assertTrue(client.waitFor(5000, State.CONNECTED));
disconnectBayeuxClient(client);
}
}
| 16,153 | 0.655089 | 0.65026 | 393 | 40.099236 | 30.690491 | 142 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.760814 | false | false | 0 |
4dab8a0035fbf1199112702d22adcefcd4a0d0bf | 29,033,978,936,334 | 93fab8072b3f4764755116db01aa53d7b666464d | /src/main/java/generated/model/TipoReceta_.java | 3f07818bfc5558bfdc2e8651de67e3cabed32ca2 | []
| no_license | giosgu/rsmee | https://github.com/giosgu/rsmee | 79b5303ed770d5f9fb437da0cee8e6f416b6d60c | 5b3fa9848f74cd76f5f3e628dd41a5152541b43b | refs/heads/master | 2021-01-23T08:29:25.898000 | 2017-10-13T19:37:46 | 2017-10-13T19:37:46 | 102,525,012 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package generated.model;
import javax.annotation.Generated;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
import model.TipoReceta;
@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(TipoReceta.class)
public abstract class TipoReceta_ {
public static volatile SingularAttribute<TipoReceta, String> codigo;
public static volatile SingularAttribute<TipoReceta, String> descripcion;
}
| UTF-8 | Java | 508 | java | TipoReceta_.java | Java | []
| null | []
| package generated.model;
import javax.annotation.Generated;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
import model.TipoReceta;
@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(TipoReceta.class)
public abstract class TipoReceta_ {
public static volatile SingularAttribute<TipoReceta, String> codigo;
public static volatile SingularAttribute<TipoReceta, String> descripcion;
}
| 508 | 0.811024 | 0.811024 | 16 | 29.625 | 27.294401 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6875 | false | false | 0 |
5a29e4826f1c30573e22bf1c2cdc4b0d31513503 | 11,158,325,094,873 | 3e359d3542d96c8e9bc4c81df8884cf528fa0a32 | /app/src/main/java/com/grab/grabtest/api/NewsAPI.java | a6eb53f458e6a267048a103da579985c37be6996 | []
| no_license | kapur2511/GrabAssignment | https://github.com/kapur2511/GrabAssignment | a2a74a90c800bd5eb4e135247916de8eaf2c771b | 3f9b636421870c90fd70b69759c63436f88c75e4 | refs/heads/master | 2020-05-26T23:07:08.924000 | 2019-05-27T07:11:12 | 2019-05-27T07:11:12 | 188,408,376 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright (C) 23-May-2019 Cricbuzz.com
* All rights reserved.
*
* http://www.cricbuzz.com
* @author: kshitiz.kapur
*/
/*
* @author: kshitiz.kapur
*/
package com.grab.grabtest.api;
import com.grab.grabtest.mvp.model.NewsListModel;
import java.util.Map;
import io.reactivex.Observable;
import retrofit2.Response;
import retrofit2.http.GET;
import retrofit2.http.QueryMap;
public interface NewsAPI {
//News API
@GET("top-headlines")
Observable<Response<NewsListModel>> loadNews(@QueryMap Map<String, Object> params);
}
| UTF-8 | Java | 548 | java | NewsAPI.java | Java | [
{
"context": "eserved.\n *\n * http://www.cricbuzz.com\n * @author: kshitiz.kapur\n */\n\n/*\n * @author: kshitiz.kapur\n */\n\npackage co",
"end": 124,
"score": 0.945585310459137,
"start": 111,
"tag": "NAME",
"value": "kshitiz.kapur"
},
{
"context": ".com\n * @author: kshitiz.kapur\n */\n\n/*\n * @author: kshitiz.kapur\n */\n\npackage com.grab.grabtest.api;\n\nimport com.g",
"end": 158,
"score": 0.9704822897911072,
"start": 145,
"tag": "NAME",
"value": "kshitiz.kapur"
}
]
| null | []
| /*
* Copyright (C) 23-May-2019 Cricbuzz.com
* All rights reserved.
*
* http://www.cricbuzz.com
* @author: kshitiz.kapur
*/
/*
* @author: kshitiz.kapur
*/
package com.grab.grabtest.api;
import com.grab.grabtest.mvp.model.NewsListModel;
import java.util.Map;
import io.reactivex.Observable;
import retrofit2.Response;
import retrofit2.http.GET;
import retrofit2.http.QueryMap;
public interface NewsAPI {
//News API
@GET("top-headlines")
Observable<Response<NewsListModel>> loadNews(@QueryMap Map<String, Object> params);
}
| 548 | 0.722628 | 0.706204 | 29 | 17.896551 | 19.441059 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.310345 | false | false | 0 |
65986b502669ca1f34ee5f37f89b55cd5940545b | 29,497,835,409,640 | 15a3f0df5e39f006fa2b7838fc4a30ba6ea75f83 | /src/KhamSucKhoe/JDialogSearchGiaVP.java | 3bd28609a07f8c4cb4aa425dcf5f5eef8acd32be | []
| no_license | dvthanhbt/HosData | https://github.com/dvthanhbt/HosData | 9b2078dd362d9dfc8a2dcf278c159ee98c81395e | 4a546e4ef9cb2e485389a3062e411c00adcdd0ea | refs/heads/master | 2016-09-06T03:19:47.501000 | 2014-04-07T23:10:46 | 2014-04-07T23:10:46 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 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 KhamSucKhoe;
import DataDB2.FillData;
import DataDB2.IntegerRenderer;
import java.awt.event.KeyEvent;
import java.sql.ResultSet;
import javax.swing.JOptionPane;
import javax.swing.RowFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
/**
*
* @author bvndc
*/
public class JDialogSearchGiaVP extends javax.swing.JDialog {
/**
* Creates new form JDialogSearchGiaVP
*/
ActionGiaVP actGiaVP = new ActionGiaVP();
private String giaVPID;
private String tenGiaVP;
private Float giaTH;
private TableRowSorter<TableModel> sorter;
private DefaultTableModel tableModel;
public JDialogSearchGiaVP(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
txtTenDichVu = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
btnGetDichVu = new javax.swing.JButton();
btnClose = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Danh mục dịch vụ");
setResizable(false);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowOpened(java.awt.event.WindowEvent evt) {
formWindowOpened(evt);
}
});
jLabel1.setText("Tên dịch vụ:");
txtTenDichVu.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
txtTenDichVuKeyPressed(evt);
}
public void keyReleased(java.awt.event.KeyEvent evt) {
txtTenDichVuKeyReleased(evt);
}
});
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jTable1.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
jTable1.setFillsViewportHeight(true);
jTable1.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jTable1KeyPressed(evt);
}
});
jScrollPane1.setViewportView(jTable1);
btnGetDichVu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/PlayHS.png"))); // NOI18N
btnGetDichVu.setText("Chọn dịch vụ");
btnGetDichVu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnGetDichVuActionPerformed(evt);
}
});
btnClose.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/GoToParentFolderHS.png"))); // NOI18N
btnClose.setText("Đóng");
btnClose.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCloseActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtTenDichVu)
.addContainerGap())
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 684, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGap(237, 237, 237)
.addComponent(btnGetDichVu)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnClose)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(txtTenDichVu, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 333, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnGetDichVu)
.addComponent(btnClose))
.addContainerGap(17, Short.MAX_VALUE))
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void btnCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCloseActionPerformed
setGiaVPID("");
setTenGiaVP("");
setGiaTH(null);
this.dispose();
}//GEN-LAST:event_btnCloseActionPerformed
private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
try {
loadData();
txtTenDichVu.setText(getGiaVPID());
txtTenDichVuKeyReleased(null);
}catch (Exception e){
e.printStackTrace();
}
}//GEN-LAST:event_formWindowOpened
private void txtTenDichVuKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtTenDichVuKeyPressed
if (evt.getKeyCode() == KeyEvent.VK_UP || evt.getKeyCode() == KeyEvent.VK_DOWN){
jTable1.requestFocus();
}
}//GEN-LAST:event_txtTenDichVuKeyPressed
private void btnGetDichVuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGetDichVuActionPerformed
if (jTable1.getSelectedRow() >= 0){
setGiaVPID(jTable1.getValueAt(jTable1.getSelectedRow(), 0).toString());
setTenGiaVP(jTable1.getValueAt(jTable1.getSelectedRow(), 1).toString());
setGiaTH(Float.parseFloat(jTable1.getValueAt(jTable1.getSelectedRow(), 3).toString()));
this.dispose();
} else {
JOptionPane.showMessageDialog(null, "Chưa chọn dịch vu!");
}
}//GEN-LAST:event_btnGetDichVuActionPerformed
private void jTable1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTable1KeyPressed
if (evt.getKeyCode() == KeyEvent.VK_ENTER){
btnGetDichVuActionPerformed(null);
}
}//GEN-LAST:event_jTable1KeyPressed
private void txtTenDichVuKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtTenDichVuKeyReleased
try {
sorter.setRowFilter(RowFilter.regexFilter("(?i)" + txtTenDichVu.getText()));
} catch (Exception ex) {
System.err.println("Bad regex pattern");
}
}//GEN-LAST:event_txtTenDichVuKeyReleased
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(JDialogSearchGiaVP.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(JDialogSearchGiaVP.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(JDialogSearchGiaVP.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(JDialogSearchGiaVP.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
JDialogSearchGiaVP dialog = new JDialogSearchGiaVP(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnClose;
private javax.swing.JButton btnGetDichVu;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
private javax.swing.JTextField txtTenDichVu;
// End of variables declaration//GEN-END:variables
public String getGiaVPID() {
return giaVPID;
}
public void setGiaVPID(String giaVPID) {
this.giaVPID = giaVPID;
}
public String getTenGiaVP() {
return tenGiaVP;
}
public void setTenGiaVP(String tenGiaVP) {
this.tenGiaVP = tenGiaVP;
}
private void loadData() throws Exception {
String[] header = {"Mã số", "Tên dịch vu", "Đơn vị", "Đơn giá"};
ResultSet rs = actGiaVP.getListGiaVP();
FillData fillData = new FillData();
fillData.fillDataJTable(jTable1, header, rs);
TableCellRenderer tcr;
tcr = new IntegerRenderer();
jTable1.getColumnModel().getColumn(3).setCellRenderer(tcr);
tableModel = (DefaultTableModel) jTable1.getModel();
sorter = new TableRowSorter<TableModel>(tableModel);
jTable1.setRowSorter(sorter);
}
public Float getGiaTH() {
return giaTH;
}
public void setGiaTH(Float giaTH) {
this.giaTH = giaTH;
}
}
| UTF-8 | Java | 11,802 | java | JDialogSearchGiaVP.java | Java | [
{
"context": "vax.swing.table.TableRowSorter;\n\n/**\n *\n * @author bvndc\n */\npublic class JDialogSearchGiaVP extends javax",
"end": 576,
"score": 0.9996092915534973,
"start": 571,
"tag": "USERNAME",
"value": "bvndc"
}
]
| null | []
| /*
* 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 KhamSucKhoe;
import DataDB2.FillData;
import DataDB2.IntegerRenderer;
import java.awt.event.KeyEvent;
import java.sql.ResultSet;
import javax.swing.JOptionPane;
import javax.swing.RowFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
/**
*
* @author bvndc
*/
public class JDialogSearchGiaVP extends javax.swing.JDialog {
/**
* Creates new form JDialogSearchGiaVP
*/
ActionGiaVP actGiaVP = new ActionGiaVP();
private String giaVPID;
private String tenGiaVP;
private Float giaTH;
private TableRowSorter<TableModel> sorter;
private DefaultTableModel tableModel;
public JDialogSearchGiaVP(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
txtTenDichVu = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
btnGetDichVu = new javax.swing.JButton();
btnClose = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Danh mục dịch vụ");
setResizable(false);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowOpened(java.awt.event.WindowEvent evt) {
formWindowOpened(evt);
}
});
jLabel1.setText("Tên dịch vụ:");
txtTenDichVu.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
txtTenDichVuKeyPressed(evt);
}
public void keyReleased(java.awt.event.KeyEvent evt) {
txtTenDichVuKeyReleased(evt);
}
});
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jTable1.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
jTable1.setFillsViewportHeight(true);
jTable1.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jTable1KeyPressed(evt);
}
});
jScrollPane1.setViewportView(jTable1);
btnGetDichVu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/PlayHS.png"))); // NOI18N
btnGetDichVu.setText("Chọn dịch vụ");
btnGetDichVu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnGetDichVuActionPerformed(evt);
}
});
btnClose.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/GoToParentFolderHS.png"))); // NOI18N
btnClose.setText("Đóng");
btnClose.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCloseActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtTenDichVu)
.addContainerGap())
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 684, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGap(237, 237, 237)
.addComponent(btnGetDichVu)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnClose)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(txtTenDichVu, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 333, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnGetDichVu)
.addComponent(btnClose))
.addContainerGap(17, Short.MAX_VALUE))
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void btnCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCloseActionPerformed
setGiaVPID("");
setTenGiaVP("");
setGiaTH(null);
this.dispose();
}//GEN-LAST:event_btnCloseActionPerformed
private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
try {
loadData();
txtTenDichVu.setText(getGiaVPID());
txtTenDichVuKeyReleased(null);
}catch (Exception e){
e.printStackTrace();
}
}//GEN-LAST:event_formWindowOpened
private void txtTenDichVuKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtTenDichVuKeyPressed
if (evt.getKeyCode() == KeyEvent.VK_UP || evt.getKeyCode() == KeyEvent.VK_DOWN){
jTable1.requestFocus();
}
}//GEN-LAST:event_txtTenDichVuKeyPressed
private void btnGetDichVuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGetDichVuActionPerformed
if (jTable1.getSelectedRow() >= 0){
setGiaVPID(jTable1.getValueAt(jTable1.getSelectedRow(), 0).toString());
setTenGiaVP(jTable1.getValueAt(jTable1.getSelectedRow(), 1).toString());
setGiaTH(Float.parseFloat(jTable1.getValueAt(jTable1.getSelectedRow(), 3).toString()));
this.dispose();
} else {
JOptionPane.showMessageDialog(null, "Chưa chọn dịch vu!");
}
}//GEN-LAST:event_btnGetDichVuActionPerformed
private void jTable1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTable1KeyPressed
if (evt.getKeyCode() == KeyEvent.VK_ENTER){
btnGetDichVuActionPerformed(null);
}
}//GEN-LAST:event_jTable1KeyPressed
private void txtTenDichVuKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtTenDichVuKeyReleased
try {
sorter.setRowFilter(RowFilter.regexFilter("(?i)" + txtTenDichVu.getText()));
} catch (Exception ex) {
System.err.println("Bad regex pattern");
}
}//GEN-LAST:event_txtTenDichVuKeyReleased
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(JDialogSearchGiaVP.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(JDialogSearchGiaVP.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(JDialogSearchGiaVP.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(JDialogSearchGiaVP.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
JDialogSearchGiaVP dialog = new JDialogSearchGiaVP(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnClose;
private javax.swing.JButton btnGetDichVu;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
private javax.swing.JTextField txtTenDichVu;
// End of variables declaration//GEN-END:variables
public String getGiaVPID() {
return giaVPID;
}
public void setGiaVPID(String giaVPID) {
this.giaVPID = giaVPID;
}
public String getTenGiaVP() {
return tenGiaVP;
}
public void setTenGiaVP(String tenGiaVP) {
this.tenGiaVP = tenGiaVP;
}
private void loadData() throws Exception {
String[] header = {"Mã số", "Tên dịch vu", "Đơn vị", "Đơn giá"};
ResultSet rs = actGiaVP.getListGiaVP();
FillData fillData = new FillData();
fillData.fillDataJTable(jTable1, header, rs);
TableCellRenderer tcr;
tcr = new IntegerRenderer();
jTable1.getColumnModel().getColumn(3).setCellRenderer(tcr);
tableModel = (DefaultTableModel) jTable1.getModel();
sorter = new TableRowSorter<TableModel>(tableModel);
jTable1.setRowSorter(sorter);
}
public Float getGiaTH() {
return giaTH;
}
public void setGiaTH(Float giaTH) {
this.giaTH = giaTH;
}
}
| 11,802 | 0.638759 | 0.633064 | 285 | 40.280701 | 32.16021 | 166 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.568421 | false | false | 0 |
f2690e8eb9325f1d206dad23d5b18137fde32893 | 317,827,627,086 | 4440a0b004f665c5d09fa9c2dce4f3c1d16c484b | /pkg_game/pkg_command/TakeCommand.java | ba77272a77c3d48d42c33c4016d88ce4e86d7117 | []
| no_license | BrendanVKM/Zuul-project-slime | https://github.com/BrendanVKM/Zuul-project-slime | 7c45555046a541811d5639616c772bef651d2c86 | b94a35dac034b632a31a1996c17f28a751de691d | refs/heads/main | 2023-08-23T22:09:24.937000 | 2021-09-17T09:24:09 | 2021-09-17T09:24:09 | 339,676,929 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pkg_game.pkg_command;
import pkg_game.GameEngine;
public class TakeCommand extends Command {
/**
* Execution of the Memorize command
*/
@Override
public void execute(final Command pCom, final GameEngine pGameEngine) {
if (!pCom.hasSecondWord())
pGameEngine.getGui().println("Absorb what ?");
else {
String vSW = pCom.getSecondWord();
int vNumber = pGameEngine.getPlayer().take(vSW);
if (vNumber == 0)
pGameEngine.getGui().println("You don't have enough space to absorb this.");
else if (vNumber == 1) {
if (pGameEngine.getPlayer().getCurrentRoom().equals(pGameEngine.getRooms().get("onMagistone"))
&& vSW.equals("magistone")) {
pGameEngine.getPlayer().getCurrentRoom().setImage("takeMagistone");
pGameEngine.getGui().showImage(pGameEngine.getPlayer().getCurrentRoom().getImageName());
}
pGameEngine.getGui()
.println("You absorb " + vSW + "\n" + pGameEngine.getPlayer().getCurrentRoom().getItemsString()
+ "\n" + pGameEngine.getPlayer().getInventoryString());
} else if (vNumber == 3) {
if (pGameEngine.getVeldora() != null) {
pGameEngine.getPlayer().getInventory()
.setItem(pGameEngine.getVeldora().getItems().getItem("dragonSoul"));
pGameEngine.getGui().println(pGameEngine.getVeldora().PlayerAbsorbVeldora()
+ "\n You have acquired the sould of Veldora.");
pGameEngine.nullVeldora();
}
} else
pGameEngine.getGui().println("What is this ? Is it there ?");
}
} // execute(.)
} // TakeCommand | UTF-8 | Java | 1,884 | java | TakeCommand.java | Java | []
| null | []
| package pkg_game.pkg_command;
import pkg_game.GameEngine;
public class TakeCommand extends Command {
/**
* Execution of the Memorize command
*/
@Override
public void execute(final Command pCom, final GameEngine pGameEngine) {
if (!pCom.hasSecondWord())
pGameEngine.getGui().println("Absorb what ?");
else {
String vSW = pCom.getSecondWord();
int vNumber = pGameEngine.getPlayer().take(vSW);
if (vNumber == 0)
pGameEngine.getGui().println("You don't have enough space to absorb this.");
else if (vNumber == 1) {
if (pGameEngine.getPlayer().getCurrentRoom().equals(pGameEngine.getRooms().get("onMagistone"))
&& vSW.equals("magistone")) {
pGameEngine.getPlayer().getCurrentRoom().setImage("takeMagistone");
pGameEngine.getGui().showImage(pGameEngine.getPlayer().getCurrentRoom().getImageName());
}
pGameEngine.getGui()
.println("You absorb " + vSW + "\n" + pGameEngine.getPlayer().getCurrentRoom().getItemsString()
+ "\n" + pGameEngine.getPlayer().getInventoryString());
} else if (vNumber == 3) {
if (pGameEngine.getVeldora() != null) {
pGameEngine.getPlayer().getInventory()
.setItem(pGameEngine.getVeldora().getItems().getItem("dragonSoul"));
pGameEngine.getGui().println(pGameEngine.getVeldora().PlayerAbsorbVeldora()
+ "\n You have acquired the sould of Veldora.");
pGameEngine.nullVeldora();
}
} else
pGameEngine.getGui().println("What is this ? Is it there ?");
}
} // execute(.)
} // TakeCommand | 1,884 | 0.549363 | 0.547771 | 39 | 47.333332 | 33.260689 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.358974 | false | false | 0 |
cb7e133571eb3a61662b011312a7a0ca548074a2 | 2,379,411,908,775 | 5947605a5aace2e8147be47173e7d27abae7a8b1 | /seven-system-schedule/src/main/java/com/zhujuming/vip/service/impl/HelloServiceImpl.java | 6d42af94bcda5808931d1ce6e3832c8a78060317 | []
| no_license | Zhujuming/seven-system-parent | https://github.com/Zhujuming/seven-system-parent | 73920d0411372bb93b619bd90cadd171194f0f4e | a98b86161f1f8e7598b582b3eec1e1b36471a4f1 | refs/heads/master | 2022-06-27T07:31:20.236000 | 2019-12-05T09:56:52 | 2019-12-05T09:56:52 | 222,361,541 | 1 | 0 | null | false | 2022-06-21T02:15:35 | 2019-11-18T04:10:22 | 2019-12-05T09:57:50 | 2022-06-21T02:15:31 | 187,479 | 0 | 0 | 4 | Java | false | false | //package com.zhujuming.vip.schedule.service.impl;
//
//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
//import com.baomidou.mybatisplus.core.metadata.IPage;
//import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
//import com.zhujuming.vip.common.constants.ResponseCode;
//import com.zhujuming.vip.common.model.TAllStaffEntity;
//import com.zhujuming.vip.common.vo.ResponseVO;
//import com.zhujuming.vip.schedule.mapper.StaffRepository;
//import com.zhujuming.vip.schedule.service.HelloService;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//
//import java.util.*;
//
//@Slf4j
//@Service
//public class HelloServiceImpl implements HelloService {
//
//
// @Autowired
// private StaffRepository staffRepository;
//
// /**
// * selectOne():根据条件查询一条数据
// * <p>
// * 注:这个方法的sql语句就是where id = 1 and last_name = 更新测试,
// * 若是符合这个条件的记录不止一条,那么就会报错。
// */
// @Override
// public ResponseVO selectOneTest(Long staffId) {
// try {
//
// TAllStaffEntity tAllStaffEntity = new TAllStaffEntity();
// tAllStaffEntity.setStaffId(staffId);
// TAllStaffEntity tAllStaffEntity1 = staffRepository.selectOne(new QueryWrapper<>(tAllStaffEntity));
// return new ResponseVO(ResponseCode.OK, tAllStaffEntity1);
// } catch (Exception e) {
// log.info("Error HelloServiceImpl.selectOneTest");
// log.warn("Error msg:{}", e);
// e.printStackTrace();
// return new ResponseVO(ResponseCode.OPERATE_ERROR);
// }
// }
//
// /**
// * selectById():根据id查询:
// */
// @Override
// public ResponseVO selectByIdTest(Integer id) {
// try {
// TAllStaffEntity tAllStaffEntity = staffRepository.selectById(id);
// return new ResponseVO(ResponseCode.OK, tAllStaffEntity);
// } catch (Exception e) {
// log.info("Error HelloServiceImpl.selectByIdTest");
// log.warn("Error msg:{}", e);
// e.printStackTrace();
// return new ResponseVO(ResponseCode.OPERATE_ERROR);
// }
// }
//
// /**
// * selectByMap():根据查询条件返回多条数据
// * <p>
// * 注:查询条件用map集合封装,columnMap,写的是数据表中的列名,而非实体类的属性名。
// * 比如属性名为lastName,数据表中字段为last_name,这里应该写的是last_name。selectByMap方法返回值用list集合接收。
// */
// @Override
// public ResponseVO selectByMapTest(String phone, String chineseName) {
// try {
// Map<String, Object> columnMap = new HashMap<>();
// columnMap.put("phone", phone);//写表中的列名
// columnMap.put("chinese_name", chineseName);
// List<TAllStaffEntity> tAllStaffEntities = staffRepository.selectByMap(columnMap);
// return new ResponseVO(ResponseCode.OK, tAllStaffEntities);
// } catch (Exception e) {
// log.info("Error HelloServiceImpl.selectByMapTest");
// log.warn("Error msg:{}", e);
// e.printStackTrace();
// return new ResponseVO(ResponseCode.OPERATE_ERROR);
// }
// }
//
// /**
// * selectBatchIds():通过id批量查询
// * <p>
// * 注:把需要查询的id都add到list集合中,然后调用selectBatchIds方法,
// * 传入该list集合即可,该方法返回的是对应id的所有记录,所有返回值也是用list接收。
// */
// @Override
// public ResponseVO selectBatchIdsTest(Integer[] ids) {
// try {
// List<Integer> idList = new ArrayList<>();
// // 访问数组,直接下标就可以了
// for (int i = 0; i < ids.length; i++) {
// idList.add(ids[i]);
// }
// List<TAllStaffEntity> tAllStaffEntities = staffRepository.selectBatchIds(idList);
// return new ResponseVO(ResponseCode.OK, tAllStaffEntities);
// } catch (Exception e) {
// log.info("Error HelloServiceImpl.selectBatchIdsTest");
// log.warn("Error msg:{}", e);
// e.printStackTrace();
// return new ResponseVO(ResponseCode.OPERATE_ERROR);
// }
// }
//
// /**
// * selectPage():分页查询
// * <p>
// * 注:selectPage方法就是分页查询,在page中传入分页信息,后者为null的分页条件,
// * 这里先让其为null,讲了条件构造器再说其用法。这个分页其实并不是物理分页,而是内存分页。
// * 也就是说,查询的时候并没有limit语句。等配置了分页插件后才可以实现真正的分页。
// */
// @Override
// public ResponseVO selectPageTest(Integer currentPage, Integer size) {
// try {
// IPage<TAllStaffEntity> tAllStaffEntityIPage = staffRepository.selectPage(new Page<>(currentPage, size), null);
// return new ResponseVO(ResponseCode.OK, tAllStaffEntityIPage);
// } catch (Exception e) {
// log.info("Error HelloServiceImpl.selectPageTest");
// log.warn("Error msg:{}", e);
// e.printStackTrace();
// return new ResponseVO(ResponseCode.OPERATE_ERROR);
// }
// }
//
// /**
// * 使用插件实现分页查询
// *
// * @param page 页数
// * @param pageSize 每页条数
// * @return
// */
// @Override
// public ResponseVO selectListPageTest(Integer page, Integer pageSize) {
// try {
// TAllStaffEntity tAllStaffEntity = new TAllStaffEntity();
// Page<TAllStaffEntity> p = new Page<>(page, pageSize);
// p.setRecords(staffRepository.selectPageExt(p, tAllStaffEntity));
// List<TAllStaffEntity> records = p.getRecords();
// return new ResponseVO(ResponseCode.OK, records);
// } catch (Exception e) {
// throw new RuntimeException(e.getMessage());
// }
// }
//
// /**
// * 插入一条记录
// *
// * @return 插入成功记录数
// */
// @Override
// public ResponseVO insertTest() {
// try {
// TAllStaffEntity entity = new TAllStaffEntity();
// entity.setCreateBy("520");
// entity.setCreateTime(new Date());
// entity.setUpdateBy("520");
// entity.setUpdateTime(new Date());
// entity.setIsDel(0);
// entity.setStaffId(1315l);
// entity.setLoginName("seven");
// entity.setEnglishName("seven");
// entity.setChineseName("七");
// entity.setFullName("seven(七)");
// entity.setGender("男");
// entity.setPhone("0");
// entity.setBgId(0714);
// entity.setBgName("爱玩事群");
// entity.setOrgCode("777");
// entity.setOrgName("爱玩科技有限公司");
// entity.setWorkPlaceId(1);
// entity.setWorkPlaceName("天堂总部");
// entity.setTenantId(77777l);
// int insert = staffRepository.insert(entity);
// return new ResponseVO(ResponseCode.OK, insert);
// } catch (Exception e) {
// e.printStackTrace();
// return new ResponseVO(ResponseCode.OPERATE_ERROR);
// }
// }
//
// /**
// * 根据 ID 删除
// *
// * @param id 主键ID
// * @return 删除成功记录数
// */
// @Override
// public ResponseVO deleteByIdTest(Integer id) {
// try {
// int num = staffRepository.deleteById(id);
// return new ResponseVO(ResponseCode.OK, num);
// } catch (Exception e) {
// e.printStackTrace();
// return new ResponseVO(ResponseCode.OPERATE_ERROR);
// }
// }
//
// /**
// * 根据 columnMap 条件,删除记录
// *
// * 注:该方法与selectByMap类似,将条件封装在columnMap中,然后调用deleteByMap方法,传入columnMap即可,返回值是Integer类型,表示影响的行数。
// * @return 删除成功记录数
// */
// @Override
// public ResponseVO deleteByMapTest(String loginName, java.lang.Integer isDel) {
// try {
// Map<String,Object> columnMap = new HashMap<>();
// columnMap.put("login_name",loginName);
// columnMap.put("is_del",isDel);
// int num = staffRepository.deleteByMap(columnMap);
// return new ResponseVO(ResponseCode.OK, num);
// } catch (Exception e) {
// e.printStackTrace();
// return new ResponseVO(ResponseCode.OPERATE_ERROR);
// }
// }
//
// /**
// * 删除(根据ID 批量删除)
// *
// * 注:该方法和selectBatchIds类似,把需要删除的记录的id装进idList,然后调用deleteBatchIds,传入idList即可。
// * @param ids 主键ID列表(不能为 null 以及 empty)
// * @return 删除成功记录数
// */
// @Override
// public ResponseVO deleteBatchIdsTest(Integer[] ids) {
// try {
// List<Integer> idList = new ArrayList<>();
// // 访问数组,直接下标就可以了
// for (int i = 0; i < ids.length; i++) {
// idList.add(ids[i]);
// }
// int num = staffRepository.deleteBatchIds(idList);
// return new ResponseVO(ResponseCode.OK, num);
// } catch (Exception e) {
// e.printStackTrace();
// return new ResponseVO(ResponseCode.OPERATE_ERROR);
// }
// }
//
//
// /**
// * updateById()(根据id进行更新)
// * 注:根据id进行更新,没有传值的属性就不会更新
// * @param id 主键ID
// * @return 删除更新记录数
// */
// @Override
// public ResponseVO updateByIdTest(Long id) {
// try {
// TAllStaffEntity entity = new TAllStaffEntity();
// entity.setId(id);
// entity.setFullName("zhuzhu狭");
// int num = staffRepository.updateById(entity);//
// return new ResponseVO(ResponseCode.OK, num);
// } catch (Exception e) {
// e.printStackTrace();
// return new ResponseVO(ResponseCode.OPERATE_ERROR);
// }
// }
//
// @Override
// @Transactional
// public ResponseVO updateTime() {
// try {
// TAllStaffEntity entity = new TAllStaffEntity();
// entity.setId(1l);
// entity.setCreateTime(new Date());
// entity.setUpdateTime(new Date());
// int num = staffRepository.updateById(entity);
// return new ResponseVO(ResponseCode.OK,num);
// } catch (Exception e) {
// e.printStackTrace();
// return new ResponseVO(ResponseCode.OPERATE_ERROR);
// }
// }
//
//}
| UTF-8 | Java | 11,154 | java | HelloServiceImpl.java | Java | [
{
"context": "/ * 注:这个方法的sql语句就是where id = 1 and last_name = 更新测试,\n// * 若是符合这个条件的记录不止一条,那么就会报错。\n// */\n// ",
"end": 1035,
"score": 0.5517225861549377,
"start": 1033,
"tag": "NAME",
"value": "更新"
},
{
"context": "taffId(1315l);\n// entity.setLoginName(\"seven\");\n// entity.setEnglishName(\"seven\");\n",
"end": 6103,
"score": 0.9546108245849609,
"start": 6098,
"tag": "NAME",
"value": "seven"
},
{
"context": "me(\"seven\");\n// entity.setEnglishName(\"seven\");\n// entity.setChineseName(\"七\");\n// ",
"end": 6149,
"score": 0.9736922383308411,
"start": 6144,
"tag": "NAME",
"value": "seven"
},
{
"context": "ineseName(\"七\");\n// entity.setFullName(\"seven(七)\");\n// entity.setGender(\"男\");\n// ",
"end": 6234,
"score": 0.86738520860672,
"start": 6229,
"tag": "NAME",
"value": "seven"
},
{
"context": "tity.setId(id);\n// entity.setFullName(\"zhuzhu狭\");\n// int num = staffRepository.update",
"end": 9203,
"score": 0.7657000422477722,
"start": 9196,
"tag": "NAME",
"value": "zhuzhu狭"
}
]
| null | []
| //package com.zhujuming.vip.schedule.service.impl;
//
//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
//import com.baomidou.mybatisplus.core.metadata.IPage;
//import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
//import com.zhujuming.vip.common.constants.ResponseCode;
//import com.zhujuming.vip.common.model.TAllStaffEntity;
//import com.zhujuming.vip.common.vo.ResponseVO;
//import com.zhujuming.vip.schedule.mapper.StaffRepository;
//import com.zhujuming.vip.schedule.service.HelloService;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//
//import java.util.*;
//
//@Slf4j
//@Service
//public class HelloServiceImpl implements HelloService {
//
//
// @Autowired
// private StaffRepository staffRepository;
//
// /**
// * selectOne():根据条件查询一条数据
// * <p>
// * 注:这个方法的sql语句就是where id = 1 and last_name = 更新测试,
// * 若是符合这个条件的记录不止一条,那么就会报错。
// */
// @Override
// public ResponseVO selectOneTest(Long staffId) {
// try {
//
// TAllStaffEntity tAllStaffEntity = new TAllStaffEntity();
// tAllStaffEntity.setStaffId(staffId);
// TAllStaffEntity tAllStaffEntity1 = staffRepository.selectOne(new QueryWrapper<>(tAllStaffEntity));
// return new ResponseVO(ResponseCode.OK, tAllStaffEntity1);
// } catch (Exception e) {
// log.info("Error HelloServiceImpl.selectOneTest");
// log.warn("Error msg:{}", e);
// e.printStackTrace();
// return new ResponseVO(ResponseCode.OPERATE_ERROR);
// }
// }
//
// /**
// * selectById():根据id查询:
// */
// @Override
// public ResponseVO selectByIdTest(Integer id) {
// try {
// TAllStaffEntity tAllStaffEntity = staffRepository.selectById(id);
// return new ResponseVO(ResponseCode.OK, tAllStaffEntity);
// } catch (Exception e) {
// log.info("Error HelloServiceImpl.selectByIdTest");
// log.warn("Error msg:{}", e);
// e.printStackTrace();
// return new ResponseVO(ResponseCode.OPERATE_ERROR);
// }
// }
//
// /**
// * selectByMap():根据查询条件返回多条数据
// * <p>
// * 注:查询条件用map集合封装,columnMap,写的是数据表中的列名,而非实体类的属性名。
// * 比如属性名为lastName,数据表中字段为last_name,这里应该写的是last_name。selectByMap方法返回值用list集合接收。
// */
// @Override
// public ResponseVO selectByMapTest(String phone, String chineseName) {
// try {
// Map<String, Object> columnMap = new HashMap<>();
// columnMap.put("phone", phone);//写表中的列名
// columnMap.put("chinese_name", chineseName);
// List<TAllStaffEntity> tAllStaffEntities = staffRepository.selectByMap(columnMap);
// return new ResponseVO(ResponseCode.OK, tAllStaffEntities);
// } catch (Exception e) {
// log.info("Error HelloServiceImpl.selectByMapTest");
// log.warn("Error msg:{}", e);
// e.printStackTrace();
// return new ResponseVO(ResponseCode.OPERATE_ERROR);
// }
// }
//
// /**
// * selectBatchIds():通过id批量查询
// * <p>
// * 注:把需要查询的id都add到list集合中,然后调用selectBatchIds方法,
// * 传入该list集合即可,该方法返回的是对应id的所有记录,所有返回值也是用list接收。
// */
// @Override
// public ResponseVO selectBatchIdsTest(Integer[] ids) {
// try {
// List<Integer> idList = new ArrayList<>();
// // 访问数组,直接下标就可以了
// for (int i = 0; i < ids.length; i++) {
// idList.add(ids[i]);
// }
// List<TAllStaffEntity> tAllStaffEntities = staffRepository.selectBatchIds(idList);
// return new ResponseVO(ResponseCode.OK, tAllStaffEntities);
// } catch (Exception e) {
// log.info("Error HelloServiceImpl.selectBatchIdsTest");
// log.warn("Error msg:{}", e);
// e.printStackTrace();
// return new ResponseVO(ResponseCode.OPERATE_ERROR);
// }
// }
//
// /**
// * selectPage():分页查询
// * <p>
// * 注:selectPage方法就是分页查询,在page中传入分页信息,后者为null的分页条件,
// * 这里先让其为null,讲了条件构造器再说其用法。这个分页其实并不是物理分页,而是内存分页。
// * 也就是说,查询的时候并没有limit语句。等配置了分页插件后才可以实现真正的分页。
// */
// @Override
// public ResponseVO selectPageTest(Integer currentPage, Integer size) {
// try {
// IPage<TAllStaffEntity> tAllStaffEntityIPage = staffRepository.selectPage(new Page<>(currentPage, size), null);
// return new ResponseVO(ResponseCode.OK, tAllStaffEntityIPage);
// } catch (Exception e) {
// log.info("Error HelloServiceImpl.selectPageTest");
// log.warn("Error msg:{}", e);
// e.printStackTrace();
// return new ResponseVO(ResponseCode.OPERATE_ERROR);
// }
// }
//
// /**
// * 使用插件实现分页查询
// *
// * @param page 页数
// * @param pageSize 每页条数
// * @return
// */
// @Override
// public ResponseVO selectListPageTest(Integer page, Integer pageSize) {
// try {
// TAllStaffEntity tAllStaffEntity = new TAllStaffEntity();
// Page<TAllStaffEntity> p = new Page<>(page, pageSize);
// p.setRecords(staffRepository.selectPageExt(p, tAllStaffEntity));
// List<TAllStaffEntity> records = p.getRecords();
// return new ResponseVO(ResponseCode.OK, records);
// } catch (Exception e) {
// throw new RuntimeException(e.getMessage());
// }
// }
//
// /**
// * 插入一条记录
// *
// * @return 插入成功记录数
// */
// @Override
// public ResponseVO insertTest() {
// try {
// TAllStaffEntity entity = new TAllStaffEntity();
// entity.setCreateBy("520");
// entity.setCreateTime(new Date());
// entity.setUpdateBy("520");
// entity.setUpdateTime(new Date());
// entity.setIsDel(0);
// entity.setStaffId(1315l);
// entity.setLoginName("seven");
// entity.setEnglishName("seven");
// entity.setChineseName("七");
// entity.setFullName("seven(七)");
// entity.setGender("男");
// entity.setPhone("0");
// entity.setBgId(0714);
// entity.setBgName("爱玩事群");
// entity.setOrgCode("777");
// entity.setOrgName("爱玩科技有限公司");
// entity.setWorkPlaceId(1);
// entity.setWorkPlaceName("天堂总部");
// entity.setTenantId(77777l);
// int insert = staffRepository.insert(entity);
// return new ResponseVO(ResponseCode.OK, insert);
// } catch (Exception e) {
// e.printStackTrace();
// return new ResponseVO(ResponseCode.OPERATE_ERROR);
// }
// }
//
// /**
// * 根据 ID 删除
// *
// * @param id 主键ID
// * @return 删除成功记录数
// */
// @Override
// public ResponseVO deleteByIdTest(Integer id) {
// try {
// int num = staffRepository.deleteById(id);
// return new ResponseVO(ResponseCode.OK, num);
// } catch (Exception e) {
// e.printStackTrace();
// return new ResponseVO(ResponseCode.OPERATE_ERROR);
// }
// }
//
// /**
// * 根据 columnMap 条件,删除记录
// *
// * 注:该方法与selectByMap类似,将条件封装在columnMap中,然后调用deleteByMap方法,传入columnMap即可,返回值是Integer类型,表示影响的行数。
// * @return 删除成功记录数
// */
// @Override
// public ResponseVO deleteByMapTest(String loginName, java.lang.Integer isDel) {
// try {
// Map<String,Object> columnMap = new HashMap<>();
// columnMap.put("login_name",loginName);
// columnMap.put("is_del",isDel);
// int num = staffRepository.deleteByMap(columnMap);
// return new ResponseVO(ResponseCode.OK, num);
// } catch (Exception e) {
// e.printStackTrace();
// return new ResponseVO(ResponseCode.OPERATE_ERROR);
// }
// }
//
// /**
// * 删除(根据ID 批量删除)
// *
// * 注:该方法和selectBatchIds类似,把需要删除的记录的id装进idList,然后调用deleteBatchIds,传入idList即可。
// * @param ids 主键ID列表(不能为 null 以及 empty)
// * @return 删除成功记录数
// */
// @Override
// public ResponseVO deleteBatchIdsTest(Integer[] ids) {
// try {
// List<Integer> idList = new ArrayList<>();
// // 访问数组,直接下标就可以了
// for (int i = 0; i < ids.length; i++) {
// idList.add(ids[i]);
// }
// int num = staffRepository.deleteBatchIds(idList);
// return new ResponseVO(ResponseCode.OK, num);
// } catch (Exception e) {
// e.printStackTrace();
// return new ResponseVO(ResponseCode.OPERATE_ERROR);
// }
// }
//
//
// /**
// * updateById()(根据id进行更新)
// * 注:根据id进行更新,没有传值的属性就不会更新
// * @param id 主键ID
// * @return 删除更新记录数
// */
// @Override
// public ResponseVO updateByIdTest(Long id) {
// try {
// TAllStaffEntity entity = new TAllStaffEntity();
// entity.setId(id);
// entity.setFullName("zhuzhu狭");
// int num = staffRepository.updateById(entity);//
// return new ResponseVO(ResponseCode.OK, num);
// } catch (Exception e) {
// e.printStackTrace();
// return new ResponseVO(ResponseCode.OPERATE_ERROR);
// }
// }
//
// @Override
// @Transactional
// public ResponseVO updateTime() {
// try {
// TAllStaffEntity entity = new TAllStaffEntity();
// entity.setId(1l);
// entity.setCreateTime(new Date());
// entity.setUpdateTime(new Date());
// int num = staffRepository.updateById(entity);
// return new ResponseVO(ResponseCode.OK,num);
// } catch (Exception e) {
// e.printStackTrace();
// return new ResponseVO(ResponseCode.OPERATE_ERROR);
// }
// }
//
//}
| 11,154 | 0.572566 | 0.569182 | 283 | 34.498234 | 24.452213 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.526502 | false | false | 0 |
ad2ddb17bd32c7f76b939fca623f80e8193bfb85 | 33,114,197,900,823 | ba6d21737748c6d50abb80a247e692c164783c6c | /unified-response-format/src/main/java/com/global/format/response/IRpcResult.java | daa231023400688141a40b8d8fa465d37381e702 | []
| no_license | Wismyluckstar/Spring-tool | https://github.com/Wismyluckstar/Spring-tool | 3cd0220a3278bd663a1b384111eff7004b449923 | 612e337eeaf320cd6cc5e2637f813d6e5d14c886 | refs/heads/master | 2022-11-27T14:32:26.305000 | 2020-08-05T15:13:28 | 2020-08-05T15:13:28 | 285,266,640 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.global.format.response;
public interface IRpcResult<T> extends IApiResult<T> {
boolean checkSuccess();
}
| UTF-8 | Java | 122 | java | IRpcResult.java | Java | []
| null | []
| package com.global.format.response;
public interface IRpcResult<T> extends IApiResult<T> {
boolean checkSuccess();
}
| 122 | 0.762295 | 0.762295 | 5 | 23.4 | 20.655266 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 0 |
4a040832cb055996243d288f8b4cc13aa0ae8884 | 4,183,298,180,639 | a37218043f51511d053126293e38fefa5bcf4752 | /YambLib/src/rs/ac/bg/fon/silab/lib/domain/DCRed.java | 808d823f8aceb2ca1e773a72ff4860f919c8cab8 | []
| no_license | marinaguzvic/Yamb | https://github.com/marinaguzvic/Yamb | 9cc719e8dd16ab4cee4dcb8b19499ec7bf5df2c2 | e64baba108cc34d49344dbcef6297ac702c580ee | refs/heads/master | 2020-05-21T12:54:50.702000 | 2019-05-13T10:31:28 | 2019-05-13T10:31:28 | 186,053,367 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 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 rs.ac.bg.fon.silab.lib.domain;
import java.io.Serializable;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import rs.ac.bg.fon.silab.lib.domain.constants.Constants;
/**
*
* @author MARINA
*/
public class DCRed implements GeneralDObject, Serializable {
static List<DCRed> redovi = new ArrayList<>();
private Long redId;
private String naziv;
private String customWhereCondition;
@Override
public String getCustomWhereCondition() {
return customWhereCondition;
}
public void setCustomWhereCondition(String customWhereCondition) {
this.customWhereCondition = customWhereCondition;
}
public static DCRed getInstance() {
DCRed newRed = new DCRed(0L);
if (redovi.contains(newRed)) {
return redovi.get(redovi.indexOf(newRed));
} else {
redovi.add(newRed);
return newRed;
}
}
public static DCRed getInstance(Long redId) {
DCRed newPolje = new DCRed(redId);
if (redovi.contains(newPolje)) {
return redovi.get(redovi.indexOf(newPolje));
} else {
redovi.add(newPolje);
return newPolje;
}
}
public static DCRed getInstance(Long redId, String naziv) {
DCRed newRed = new DCRed(redId, naziv);
if (redovi.contains(newRed)) {
DCRed existingRed = redovi.get(redovi.indexOf(newRed));
existingRed.update(newRed);
return existingRed;
} else {
redovi.add(newRed);
return newRed;
}
}
private DCRed(Long redId) {
this.redId = redId;
}
private DCRed(Long redId, String naziv) {
this.redId = redId;
this.naziv = naziv;
}
@Override
public String getAtrValue() {
return "'" + naziv + "'";
}
@Override
public String setAtrValue() {
return Constants.Red.NAZIV + "='" + naziv + "'";
}
@Override
public String getClassName() {
return Constants.Red.CLASS_NAME;
}
@Override
public String getColumnNames() {
return Constants.Red.BROJ + "," + Constants.Red.NAZIV;
}
@Override
public String getWhereCondition() {
return Constants.Red.RED_ID + "=" + redId;
}
@Override
public String getNameByColumn(int column) {
return new String[]{Constants.Red.RED_ID, Constants.Red.BROJ, Constants.Red.NAZIV}[column];
}
@Override
public void checkConstraints() throws Exception {
System.out.println("Checking constratints for Red");
}
@Override
public void setKey(ResultSet rs) throws Exception {
try {
if (rs.next()) {
redId = rs.getLong(1);
}
} catch (SQLException ex) {
ex.printStackTrace();
throw new Exception("The key was not returned");
}
}
@Override
public String[] getColumns() {
return new String[]{Constants.Red.RED_ID, Constants.Red.BROJ, Constants.Red.NAZIV};
}
@Override
public Object getValue(String column) {
switch (column) {
case Constants.Red.RED_ID:
return redId;
case Constants.Red.NAZIV:
return naziv;
default:
return null;
}
}
@Override
public String[] getPrimaryKeyColumns() {
return new String[]{Constants.Red.RED_ID};
}
public String getNaziv() {
return naziv;
}
public void setNaziv(String naziv) {
this.naziv = naziv;
}
public Long getRedId() {
return redId;
}
public void setRedId(Long redId) {
this.redId = redId;
}
@Override
public int hashCode() {
int hash = 3;
hash = 83 * hash + Objects.hashCode(this.redId);
hash = 83 * hash + Objects.hashCode(this.naziv);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final DCRed other = (DCRed) obj;
if (!Objects.equals(this.redId, other.redId)) {
return false;
}
return true;
}
@Override
public void setValue(String column, ResultSet rs, GeneralDObject gdo) {
try {
switch (column) {
case Constants.Red.RED_ID:
redId = rs.getLong(column);
break;
case Constants.Red.NAZIV:
naziv = rs.getString(column);
break;
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
@Override
public void update(GeneralDObject gdo) {
naziv = ((DCRed) gdo).getNaziv();
}
@Override
public GeneralDObject getInstance(ResultSet rs) {
try {
return getInstance(rs.getLong(Constants.Red.RED_ID));
} catch (SQLException ex) {
ex.printStackTrace();
return null;
}
}
}
| UTF-8 | Java | 5,475 | java | DCRed.java | Java | [
{
"context": "lib.domain.constants.Constants;\n\n/**\n *\n * @author MARINA\n */\npublic class DCRed implements GeneralDObject,",
"end": 471,
"score": 0.9974272847175598,
"start": 465,
"tag": "NAME",
"value": "MARINA"
}
]
| null | []
| /*
* 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 rs.ac.bg.fon.silab.lib.domain;
import java.io.Serializable;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import rs.ac.bg.fon.silab.lib.domain.constants.Constants;
/**
*
* @author MARINA
*/
public class DCRed implements GeneralDObject, Serializable {
static List<DCRed> redovi = new ArrayList<>();
private Long redId;
private String naziv;
private String customWhereCondition;
@Override
public String getCustomWhereCondition() {
return customWhereCondition;
}
public void setCustomWhereCondition(String customWhereCondition) {
this.customWhereCondition = customWhereCondition;
}
public static DCRed getInstance() {
DCRed newRed = new DCRed(0L);
if (redovi.contains(newRed)) {
return redovi.get(redovi.indexOf(newRed));
} else {
redovi.add(newRed);
return newRed;
}
}
public static DCRed getInstance(Long redId) {
DCRed newPolje = new DCRed(redId);
if (redovi.contains(newPolje)) {
return redovi.get(redovi.indexOf(newPolje));
} else {
redovi.add(newPolje);
return newPolje;
}
}
public static DCRed getInstance(Long redId, String naziv) {
DCRed newRed = new DCRed(redId, naziv);
if (redovi.contains(newRed)) {
DCRed existingRed = redovi.get(redovi.indexOf(newRed));
existingRed.update(newRed);
return existingRed;
} else {
redovi.add(newRed);
return newRed;
}
}
private DCRed(Long redId) {
this.redId = redId;
}
private DCRed(Long redId, String naziv) {
this.redId = redId;
this.naziv = naziv;
}
@Override
public String getAtrValue() {
return "'" + naziv + "'";
}
@Override
public String setAtrValue() {
return Constants.Red.NAZIV + "='" + naziv + "'";
}
@Override
public String getClassName() {
return Constants.Red.CLASS_NAME;
}
@Override
public String getColumnNames() {
return Constants.Red.BROJ + "," + Constants.Red.NAZIV;
}
@Override
public String getWhereCondition() {
return Constants.Red.RED_ID + "=" + redId;
}
@Override
public String getNameByColumn(int column) {
return new String[]{Constants.Red.RED_ID, Constants.Red.BROJ, Constants.Red.NAZIV}[column];
}
@Override
public void checkConstraints() throws Exception {
System.out.println("Checking constratints for Red");
}
@Override
public void setKey(ResultSet rs) throws Exception {
try {
if (rs.next()) {
redId = rs.getLong(1);
}
} catch (SQLException ex) {
ex.printStackTrace();
throw new Exception("The key was not returned");
}
}
@Override
public String[] getColumns() {
return new String[]{Constants.Red.RED_ID, Constants.Red.BROJ, Constants.Red.NAZIV};
}
@Override
public Object getValue(String column) {
switch (column) {
case Constants.Red.RED_ID:
return redId;
case Constants.Red.NAZIV:
return naziv;
default:
return null;
}
}
@Override
public String[] getPrimaryKeyColumns() {
return new String[]{Constants.Red.RED_ID};
}
public String getNaziv() {
return naziv;
}
public void setNaziv(String naziv) {
this.naziv = naziv;
}
public Long getRedId() {
return redId;
}
public void setRedId(Long redId) {
this.redId = redId;
}
@Override
public int hashCode() {
int hash = 3;
hash = 83 * hash + Objects.hashCode(this.redId);
hash = 83 * hash + Objects.hashCode(this.naziv);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final DCRed other = (DCRed) obj;
if (!Objects.equals(this.redId, other.redId)) {
return false;
}
return true;
}
@Override
public void setValue(String column, ResultSet rs, GeneralDObject gdo) {
try {
switch (column) {
case Constants.Red.RED_ID:
redId = rs.getLong(column);
break;
case Constants.Red.NAZIV:
naziv = rs.getString(column);
break;
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
@Override
public void update(GeneralDObject gdo) {
naziv = ((DCRed) gdo).getNaziv();
}
@Override
public GeneralDObject getInstance(ResultSet rs) {
try {
return getInstance(rs.getLong(Constants.Red.RED_ID));
} catch (SQLException ex) {
ex.printStackTrace();
return null;
}
}
}
| 5,475 | 0.565114 | 0.563836 | 221 | 23.773756 | 20.344175 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.380091 | false | false | 0 |
50401dce230d2ee6d92485d74dcd2bc33624574d | 14,405,320,345,598 | 800fe8fecebe32268f6f6492ed4856f0d539d7ea | /src/main/java/au/gov/nehta/model/clinical/common/address/StreetType.java | 015746078571148b6a763caf37d381bfbc3ac542 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"BSD-2-Clause"
]
| permissive | AuDigitalHealth/clinical-document-library-java | https://github.com/AuDigitalHealth/clinical-document-library-java | 6c1199a287cd8701a21bfa81a1f56e44d3bdca74 | 217483c9a2dc18aa7aa262bb22a7175888550839 | refs/heads/master | 2021-07-25T04:32:21.870000 | 2021-07-19T06:08:05 | 2021-07-19T06:08:05 | 197,092,272 | 6 | 5 | NOASSERTION | false | 2021-02-04T03:12:55 | 2019-07-16T00:37:05 | 2020-11-24T23:44:35 | 2021-02-04T03:12:55 | 44,993 | 3 | 3 | 0 | XSLT | false | false | package au.gov.nehta.model.clinical.common.address;
import java.util.StringJoiner;
public enum StreetType {
Undefined(null, null),
Access("Accs", "Access"),
Alley("Ally", "Alley"),
Alleyway("Alwy", "Alleyway"),
Amble("Ambl", "Amble"),
Anchorage("Ancg", "Anchorage"),
Approach("App", "Approach"),
Arcade("Arc", "Arcade"),
Artery("Art", "Artery"),
Avenue("Ave", "Avenue"),
Basin("Basn", "Basin"),
Beach("Bch", "Beach"),
Bend("Bend", "Bend"),
Block("Blk", "Block"),
Boulevard("Bvd", "Boulevard"),
Brace("Brce", "Brace"),
Brae("Brae", "Brae"),
Break("Brk", "Break"),
Bridge("Bdge", "Bridge"),
Broadway("Bdwy", "Broadway"),
Brow("Brow", "Brow"),
Bypass("Bypa", "Bypass"),
Byway("Bywy", "Byway"),
Causeway("Caus", "Causeway"),
Centre("Ctr", "Centre"),
Centreway("Cnwy", "Centreway"),
Chase("Ch", "Chase"),
Circle("Cir", "Circle"),
Circlet("Clt", "Circlet"),
Circuit("Cct", "Circuit"),
Circus("Crcs", "Circus"),
Close("Cl", "Close"),
Colonnade("Clde", "Colonnade"),
Common("Cmmn", "Common"),
Concourse("Con", "Concourse"),
Copse("Cps", "Copse"),
/// Corner
/// The code "Crn" is specified in the Australian Standards document. However, most of the other street type codes come
/// from the Australia Post site and this is the only value that is different. The code for Corner from Australia Post is
/// "Cnr"
Corner("Crn", "Corner"),
Corso("Cso", "Corso"),
Court("Ct", "Court"),
Courtyard("Ctyd", "Courtyard"),
Cove("Cove", "Cove"),
Crescent("Cres", "Crescent"),
Crest("Crst", "Crest"),
Cross("Crss", "Cross"),
Crossing("Crsg", "Crossing"),
Crossroad("Crd", "Crossroad"),
Crossway("Cowy", "Crossway"),
Cruiseway("Cuwy", "Cruiseway"),
CulDeSac("Cds", "Cul-De-Sac"),
Cutting("Cttg", "Cutting"),
Dale("Dale", "Dale"),
Dell("Dell", "Dell"),
Deviation("Devn", "Deviation"),
Dip("Dip", "Dip"),
Distributor("Dstr", "Distributor"),
Drive("Dr", "Drive"),
Driveway("Drwy", "Driveway"),
Edge("Edge", "Edge"),
Elbow("Elb", "Elbow"),
End("End", "End"),
Entrance("Ent", "Entrance"),
Esplanade("Esp", "Esplanade"),
Estate("Est", "Estate"),
Expressway("Exp", "Expressway"),
Extension("Extn", "Extension"),
Fairway("Fawy", "Fairway"),
FireTrack("Ftrk", "Fire Track"),
Firetrail("Fitr", "Firetrail"),
Flat("Flat", "Flat"),
Follow("Folw", "Follow"),
Footway("Ftwy", "Footway"),
Foreshore("Fshr", "Foreshore"),
Formation("Form", "Formation"),
Freeway("Fwy", "Freeway"),
Front("Frnt", "Front"),
Frontage("Frtg", "Frontage"),
Gap("Gap", "Gap"),
Garden("Gdn", "Garden"),
Gardens("Gdns", "Gardens"),
Gate("Gte", "Gate"),
Gates("Gtes", "Gates"),
Glade("Gld", "Glade"),
Glen("Glen", "Glen"),
Grange("Gra", "Grange"),
Green("Grn", "Green"),
Ground("Grnd", "Ground"),
Grove("Gr", "Grove"),
Gully("Gly", "Gully"),
Heights("Hts", "Heights"),
Highroad("Hrd", "Highroad"),
Highway("Hwy", "Highway"),
Hill("Hill", "Hill"),
Interchange("Intg", "Interchange"),
Intersection("Intn", "Intersection"),
Junction("Jnc", "Junction"),
Key("Key", "Key"),
Landing("Ldg", "Landing"),
Lane("Lane", "Lane"),
Laneway("Lnwy", "Laneway"),
Lees("Lees", "Lees"),
Line("Line", "Line"),
Link("Link", "Link"),
Little("Lt", "Little"),
Lookout("Lkt", "Lookout"),
Loop("Loop", "Loop"),
Lower("Lwr", "Lower"),
Mall("Mall", "Mall"),
Meander("Mndr", "Meander"),
Mew("Mew", "Mew"),
Mews("Mews", "Mews"),
Motorway("Mwy", "Motorway"),
Mount("Mt", "Mount"),
Nook("Nook", "Nook"),
Outlook("Otlk", "Outlook"),
Parade("Pde", "Parade"),
Park("Park", "Park"),
Parklands("Pkld", "Parklands"),
Parkway("Pkwy", "Parkway"),
Part("Part", "Part"),
Pass("Pass", "Pass"),
Path("Path", "Path"),
Pathway("Phwy", "Pathway"),
Piazza("Piaz", "Piazza"),
Place("Pl", "Place"),
Plateau("Plat", "Plateau"),
Plaza("Plza", "Plaza"),
Pocket("Pkt", "Pocket"),
Point("Pnt", "Point"),
Port("Port", "Port"),
Promenade("Prom", "Promenade"),
Quad("Quad", "Quad"),
Quadrangle("Qdgl", "Quadrangle"),
Quadrant("Qdrt", "Quadrant"),
Quay("Qy", "Quay"),
Quays("Qys", "Quays"),
Ramble("Rmbl", "Ramble"),
Ramp("Ramp", "Ramp"),
Range("Rnge", "Range"),
Reach("Rch", "Reach"),
Reserve("Res", "Reserve"),
Rest("Rest", "Rest"),
Retreat("Rtt", "Retreat"),
Ride("Ride", "Ride"),
Ridge("Rdge", "Ridge"),
Ridgeway("Rgwy", "Ridgeway"),
RightOfWay("Rowy", "Right Of Way"),
Ring("Ring", "Ring"),
Rise("Rise", "Rise"),
River("Rvr", "River"),
Riverway("Rvwy", "Riverway"),
Riviera("Rvra", "Riviera"),
Road("Rd", "Road"),
Roads("Rds", "Roads"),
Roadside("Rdsd", "Roadside"),
Roadway("Rdwy", "Roadway"),
Ronde("Rnde", "Ronde"),
Rosebowl("Rsbl", "Rosebowl"),
Rotary("Rty", "Rotary"),
Round("Rnd", "Round"),
Route("Rte", "Route"),
Row("Row", "Row"),
Rue("Rue", "Rue"),
Run("Run", "Run"),
ServiceWay("Swy", "Service Way"),
Siding("Sdng", "Siding"),
Slope("Slpe", "Slope"),
Sound("Snd", "Sound"),
Spur("Spur", "Spur"),
Square("Sq", "Square"),
Stairs("Strs", "Stairs"),
StateHighway("Shwy", "State Highway"),
Steps("Stps", "Steps"),
Strand("Stra", "Strand"),
Street("St", "Street"),
Strip("Strp", "Strip"),
Subway("Sbwy", "Subway"),
Tarn("Tarn", "Tarn"),
Terrace("Tce", "Terrace"),
Thoroughfare("Thor", "Thoroughfare"),
Tollway("Tlwy", "Tollway"),
Top("Top", "Top"),
Tor("Tor", "Tor"),
Towers("Twrs", "Towers"),
Track("Trk", "Track"),
Trail("Trl", "Trail"),
Trailer("Trlr", "Trailer"),
Triangle("Tri", "Triangle"),
Trunkway("Tkwy", "Trunkway"),
Turn("Turn", "Turn"),
Underpass("Upas", "Underpass"),
Upper("Upr", "Upper"),
Vale("Vale", "Vale"),
Viaduct("Vdct", "Viaduct"),
View("View", "View"),
Villas("Vlls", "Villas"),
Vista("Vsta", "Vista"),
Wade("Wade", "Wade"),
Walk("Walk", "Walk"),
Walkway("Wkwy", "Walkway"),
Way("Way", "Way"),
Wharf("Whrf", "Wharf"),
Wynd("Wynd", "Wynd"),
Yard("Yard", "Yard");
private String code;
private String name;
StreetType(String code, String name) {
this.code = code;
this.name = name;
}
public String getCode() {
return code;
}
public String getName() {
return name;
}
@Override
public String toString() {
return new StringJoiner(", ", StreetType.class.getSimpleName() + "[", "")
.add("code='" + code + "'")
.add("name='" + name + "'")
.toString();
}
}
| UTF-8 | Java | 7,126 | java | StreetType.java | Java | [
{
"context": "null),\n\n Access(\"Accs\", \"Access\"),\n\n Alley(\"Ally\", \"Alley\"),\n\n Alleyway(\"Alwy\", \"Alleyway\"),\n\n ",
"end": 184,
"score": 0.995220422744751,
"start": 180,
"tag": "NAME",
"value": "Ally"
}
]
| null | []
| package au.gov.nehta.model.clinical.common.address;
import java.util.StringJoiner;
public enum StreetType {
Undefined(null, null),
Access("Accs", "Access"),
Alley("Ally", "Alley"),
Alleyway("Alwy", "Alleyway"),
Amble("Ambl", "Amble"),
Anchorage("Ancg", "Anchorage"),
Approach("App", "Approach"),
Arcade("Arc", "Arcade"),
Artery("Art", "Artery"),
Avenue("Ave", "Avenue"),
Basin("Basn", "Basin"),
Beach("Bch", "Beach"),
Bend("Bend", "Bend"),
Block("Blk", "Block"),
Boulevard("Bvd", "Boulevard"),
Brace("Brce", "Brace"),
Brae("Brae", "Brae"),
Break("Brk", "Break"),
Bridge("Bdge", "Bridge"),
Broadway("Bdwy", "Broadway"),
Brow("Brow", "Brow"),
Bypass("Bypa", "Bypass"),
Byway("Bywy", "Byway"),
Causeway("Caus", "Causeway"),
Centre("Ctr", "Centre"),
Centreway("Cnwy", "Centreway"),
Chase("Ch", "Chase"),
Circle("Cir", "Circle"),
Circlet("Clt", "Circlet"),
Circuit("Cct", "Circuit"),
Circus("Crcs", "Circus"),
Close("Cl", "Close"),
Colonnade("Clde", "Colonnade"),
Common("Cmmn", "Common"),
Concourse("Con", "Concourse"),
Copse("Cps", "Copse"),
/// Corner
/// The code "Crn" is specified in the Australian Standards document. However, most of the other street type codes come
/// from the Australia Post site and this is the only value that is different. The code for Corner from Australia Post is
/// "Cnr"
Corner("Crn", "Corner"),
Corso("Cso", "Corso"),
Court("Ct", "Court"),
Courtyard("Ctyd", "Courtyard"),
Cove("Cove", "Cove"),
Crescent("Cres", "Crescent"),
Crest("Crst", "Crest"),
Cross("Crss", "Cross"),
Crossing("Crsg", "Crossing"),
Crossroad("Crd", "Crossroad"),
Crossway("Cowy", "Crossway"),
Cruiseway("Cuwy", "Cruiseway"),
CulDeSac("Cds", "Cul-De-Sac"),
Cutting("Cttg", "Cutting"),
Dale("Dale", "Dale"),
Dell("Dell", "Dell"),
Deviation("Devn", "Deviation"),
Dip("Dip", "Dip"),
Distributor("Dstr", "Distributor"),
Drive("Dr", "Drive"),
Driveway("Drwy", "Driveway"),
Edge("Edge", "Edge"),
Elbow("Elb", "Elbow"),
End("End", "End"),
Entrance("Ent", "Entrance"),
Esplanade("Esp", "Esplanade"),
Estate("Est", "Estate"),
Expressway("Exp", "Expressway"),
Extension("Extn", "Extension"),
Fairway("Fawy", "Fairway"),
FireTrack("Ftrk", "Fire Track"),
Firetrail("Fitr", "Firetrail"),
Flat("Flat", "Flat"),
Follow("Folw", "Follow"),
Footway("Ftwy", "Footway"),
Foreshore("Fshr", "Foreshore"),
Formation("Form", "Formation"),
Freeway("Fwy", "Freeway"),
Front("Frnt", "Front"),
Frontage("Frtg", "Frontage"),
Gap("Gap", "Gap"),
Garden("Gdn", "Garden"),
Gardens("Gdns", "Gardens"),
Gate("Gte", "Gate"),
Gates("Gtes", "Gates"),
Glade("Gld", "Glade"),
Glen("Glen", "Glen"),
Grange("Gra", "Grange"),
Green("Grn", "Green"),
Ground("Grnd", "Ground"),
Grove("Gr", "Grove"),
Gully("Gly", "Gully"),
Heights("Hts", "Heights"),
Highroad("Hrd", "Highroad"),
Highway("Hwy", "Highway"),
Hill("Hill", "Hill"),
Interchange("Intg", "Interchange"),
Intersection("Intn", "Intersection"),
Junction("Jnc", "Junction"),
Key("Key", "Key"),
Landing("Ldg", "Landing"),
Lane("Lane", "Lane"),
Laneway("Lnwy", "Laneway"),
Lees("Lees", "Lees"),
Line("Line", "Line"),
Link("Link", "Link"),
Little("Lt", "Little"),
Lookout("Lkt", "Lookout"),
Loop("Loop", "Loop"),
Lower("Lwr", "Lower"),
Mall("Mall", "Mall"),
Meander("Mndr", "Meander"),
Mew("Mew", "Mew"),
Mews("Mews", "Mews"),
Motorway("Mwy", "Motorway"),
Mount("Mt", "Mount"),
Nook("Nook", "Nook"),
Outlook("Otlk", "Outlook"),
Parade("Pde", "Parade"),
Park("Park", "Park"),
Parklands("Pkld", "Parklands"),
Parkway("Pkwy", "Parkway"),
Part("Part", "Part"),
Pass("Pass", "Pass"),
Path("Path", "Path"),
Pathway("Phwy", "Pathway"),
Piazza("Piaz", "Piazza"),
Place("Pl", "Place"),
Plateau("Plat", "Plateau"),
Plaza("Plza", "Plaza"),
Pocket("Pkt", "Pocket"),
Point("Pnt", "Point"),
Port("Port", "Port"),
Promenade("Prom", "Promenade"),
Quad("Quad", "Quad"),
Quadrangle("Qdgl", "Quadrangle"),
Quadrant("Qdrt", "Quadrant"),
Quay("Qy", "Quay"),
Quays("Qys", "Quays"),
Ramble("Rmbl", "Ramble"),
Ramp("Ramp", "Ramp"),
Range("Rnge", "Range"),
Reach("Rch", "Reach"),
Reserve("Res", "Reserve"),
Rest("Rest", "Rest"),
Retreat("Rtt", "Retreat"),
Ride("Ride", "Ride"),
Ridge("Rdge", "Ridge"),
Ridgeway("Rgwy", "Ridgeway"),
RightOfWay("Rowy", "Right Of Way"),
Ring("Ring", "Ring"),
Rise("Rise", "Rise"),
River("Rvr", "River"),
Riverway("Rvwy", "Riverway"),
Riviera("Rvra", "Riviera"),
Road("Rd", "Road"),
Roads("Rds", "Roads"),
Roadside("Rdsd", "Roadside"),
Roadway("Rdwy", "Roadway"),
Ronde("Rnde", "Ronde"),
Rosebowl("Rsbl", "Rosebowl"),
Rotary("Rty", "Rotary"),
Round("Rnd", "Round"),
Route("Rte", "Route"),
Row("Row", "Row"),
Rue("Rue", "Rue"),
Run("Run", "Run"),
ServiceWay("Swy", "Service Way"),
Siding("Sdng", "Siding"),
Slope("Slpe", "Slope"),
Sound("Snd", "Sound"),
Spur("Spur", "Spur"),
Square("Sq", "Square"),
Stairs("Strs", "Stairs"),
StateHighway("Shwy", "State Highway"),
Steps("Stps", "Steps"),
Strand("Stra", "Strand"),
Street("St", "Street"),
Strip("Strp", "Strip"),
Subway("Sbwy", "Subway"),
Tarn("Tarn", "Tarn"),
Terrace("Tce", "Terrace"),
Thoroughfare("Thor", "Thoroughfare"),
Tollway("Tlwy", "Tollway"),
Top("Top", "Top"),
Tor("Tor", "Tor"),
Towers("Twrs", "Towers"),
Track("Trk", "Track"),
Trail("Trl", "Trail"),
Trailer("Trlr", "Trailer"),
Triangle("Tri", "Triangle"),
Trunkway("Tkwy", "Trunkway"),
Turn("Turn", "Turn"),
Underpass("Upas", "Underpass"),
Upper("Upr", "Upper"),
Vale("Vale", "Vale"),
Viaduct("Vdct", "Viaduct"),
View("View", "View"),
Villas("Vlls", "Villas"),
Vista("Vsta", "Vista"),
Wade("Wade", "Wade"),
Walk("Walk", "Walk"),
Walkway("Wkwy", "Walkway"),
Way("Way", "Way"),
Wharf("Whrf", "Wharf"),
Wynd("Wynd", "Wynd"),
Yard("Yard", "Yard");
private String code;
private String name;
StreetType(String code, String name) {
this.code = code;
this.name = name;
}
public String getCode() {
return code;
}
public String getName() {
return name;
}
@Override
public String toString() {
return new StringJoiner(", ", StreetType.class.getSimpleName() + "[", "")
.add("code='" + code + "'")
.add("name='" + name + "'")
.toString();
}
}
| 7,126 | 0.520067 | 0.520067 | 439 | 15.232347 | 16.685644 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.95672 | false | false | 0 |
896c9ee1f1e734da7425e749bdafbd8e7fbe284b | 28,458,453,339,049 | f34bd7131d5cf52ec88aee3e043cb37ffdd12784 | /src/main/java/br/gov/esmpu/sie/model/Aluno.java | 727c077a150d3e184e40b14bb543b7346dcf244c | []
| no_license | binzera/neo | https://github.com/binzera/neo | c67ea5486575554b94bd54dd0492820896ecf159 | 5d95b7a56a882649937b2cbf25a710b171037682 | refs/heads/master | 2018-01-08T12:45:10.560000 | 2015-11-10T20:03:15 | 2015-11-10T20:03:15 | 44,811,543 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.gov.esmpu.sie.model;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.codehaus.jackson.annotate.JsonBackReference;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonManagedReference;
/**
* The persistent class for the ALUNOS database table.
*
*/
@Entity
@Table(name="ALUNOS")
@NamedQuery(name="Aluno.findAll", query="SELECT a FROM Aluno a")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Aluno implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="ID_ALUNO")
private long idAluno;
@Column(name="ANO_CONC_FUND")
private BigDecimal anoConcFund;
@Column(name="ANO_CONC_MEDIO")
private BigDecimal anoConcMedio;
@Column(name="COD_OPERADOR")
private BigDecimal codOperador;
private BigDecimal concorrencia;
@Column(name="CURSO_FUND_ITEM")
private BigDecimal cursoFundItem;
@Column(name="CURSO_FUND_TAB")
private BigDecimal cursoFundTab;
@Column(name="CURSO_MEDIO_ITEM")
private BigDecimal cursoMedioItem;
@Column(name="CURSO_MEDIO_TAB")
private BigDecimal cursoMedioTab;
@Column(name="DEFICIENCIA_ITEM")
private BigDecimal deficienciaItem;
@Column(name="DEFICIENCIA_TAB")
private BigDecimal deficienciaTab;
@Temporal(TemporalType.DATE)
@Column(name="DT_ALTERACAO")
private Date dtAlteracao;
@Temporal(TemporalType.DATE)
@Column(name="DT_NASCIMENTO")
private Date dtNascimento;
@Column(name="ENDERECO_FISICO")
private String enderecoFisico;
@Column(name="ESTADO_CIVIL_ITEM")
private BigDecimal estadoCivilItem;
@Column(name="ESTADO_CIVIL_TAB")
private BigDecimal estadoCivilTab;
@Column(name="ETNIA_ITEM")
private BigDecimal etniaItem;
@Column(name="ETNIA_TAB")
private BigDecimal etniaTab;
@Column(name="FATOR_RH")
private String fatorRh;
@Lob
private byte[] foto;
@Lob
@Column(name="FOTO_WEB")
private byte[] fotoWeb;
@Temporal(TemporalType.DATE)
@Column(name="HR_ALTERACAO")
private Date hrAlteracao;
@Column(name="ID_ESCOLA_FUND")
private BigDecimal idEscolaFund;
@Column(name="ID_ESCOLA_MEDIO")
private BigDecimal idEscolaMedio;
@Column(name="ID_TUTOR_FIN")
private BigDecimal idTutorFin;
@Column(name="NACIONALIDADE_ITEM")
private BigDecimal nacionalidadeItem;
@Column(name="NACIONALIDADE_TAB")
private BigDecimal nacionalidadeTab;
@Column(name="NOME_MAE")
private String nomeMae;
@Column(name="NOME_PAI")
private String nomePai;
private String sexo;
@Column(name="TIPO_SANGUINEO")
private String tipoSanguineo;
private String url;
//bi-directional many-to-one association to Cidade
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="ID_NATURALIDADE")
@JsonManagedReference
private Cidade cidade1;
//bi-directional many-to-one association to Cidade
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="ID_LOCAL_FUND")
@JsonManagedReference
private Cidade cidade2;
//bi-directional many-to-one association to Cidade
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="ID_LOCAL_MEDIO")
@JsonManagedReference
private Cidade cidade3;
//bi-directional many-to-one association to Pessoa
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="ID_RESPONSAVEL")
@JsonManagedReference
private Pessoa pessoa1;
//bi-directional many-to-one association to Pessoa
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="ID_PESSOA")
@JsonManagedReference
private Pessoa pessoa2;
//bi-directional many-to-one association to CursosAluno
@OneToMany(mappedBy="aluno")
@JsonBackReference
private List<CursosAluno> cursosAlunos;
public Aluno() {
}
public long getIdAluno() {
return this.idAluno;
}
public void setIdAluno(long idAluno) {
this.idAluno = idAluno;
}
public BigDecimal getAnoConcFund() {
return this.anoConcFund;
}
public void setAnoConcFund(BigDecimal anoConcFund) {
this.anoConcFund = anoConcFund;
}
public BigDecimal getAnoConcMedio() {
return this.anoConcMedio;
}
public void setAnoConcMedio(BigDecimal anoConcMedio) {
this.anoConcMedio = anoConcMedio;
}
public BigDecimal getCodOperador() {
return this.codOperador;
}
public void setCodOperador(BigDecimal codOperador) {
this.codOperador = codOperador;
}
public BigDecimal getConcorrencia() {
return this.concorrencia;
}
public void setConcorrencia(BigDecimal concorrencia) {
this.concorrencia = concorrencia;
}
public BigDecimal getCursoFundItem() {
return this.cursoFundItem;
}
public void setCursoFundItem(BigDecimal cursoFundItem) {
this.cursoFundItem = cursoFundItem;
}
public BigDecimal getCursoFundTab() {
return this.cursoFundTab;
}
public void setCursoFundTab(BigDecimal cursoFundTab) {
this.cursoFundTab = cursoFundTab;
}
public BigDecimal getCursoMedioItem() {
return this.cursoMedioItem;
}
public void setCursoMedioItem(BigDecimal cursoMedioItem) {
this.cursoMedioItem = cursoMedioItem;
}
public BigDecimal getCursoMedioTab() {
return this.cursoMedioTab;
}
public void setCursoMedioTab(BigDecimal cursoMedioTab) {
this.cursoMedioTab = cursoMedioTab;
}
public BigDecimal getDeficienciaItem() {
return this.deficienciaItem;
}
public void setDeficienciaItem(BigDecimal deficienciaItem) {
this.deficienciaItem = deficienciaItem;
}
public BigDecimal getDeficienciaTab() {
return this.deficienciaTab;
}
public void setDeficienciaTab(BigDecimal deficienciaTab) {
this.deficienciaTab = deficienciaTab;
}
public Date getDtAlteracao() {
return this.dtAlteracao;
}
public void setDtAlteracao(Date dtAlteracao) {
this.dtAlteracao = dtAlteracao;
}
public Date getDtNascimento() {
return this.dtNascimento;
}
public void setDtNascimento(Date dtNascimento) {
this.dtNascimento = dtNascimento;
}
public String getEnderecoFisico() {
return this.enderecoFisico;
}
public void setEnderecoFisico(String enderecoFisico) {
this.enderecoFisico = enderecoFisico;
}
public BigDecimal getEstadoCivilItem() {
return this.estadoCivilItem;
}
public void setEstadoCivilItem(BigDecimal estadoCivilItem) {
this.estadoCivilItem = estadoCivilItem;
}
public BigDecimal getEstadoCivilTab() {
return this.estadoCivilTab;
}
public void setEstadoCivilTab(BigDecimal estadoCivilTab) {
this.estadoCivilTab = estadoCivilTab;
}
public BigDecimal getEtniaItem() {
return this.etniaItem;
}
public void setEtniaItem(BigDecimal etniaItem) {
this.etniaItem = etniaItem;
}
public BigDecimal getEtniaTab() {
return this.etniaTab;
}
public void setEtniaTab(BigDecimal etniaTab) {
this.etniaTab = etniaTab;
}
public String getFatorRh() {
return this.fatorRh;
}
public void setFatorRh(String fatorRh) {
this.fatorRh = fatorRh;
}
public byte[] getFoto() {
return this.foto;
}
public void setFoto(byte[] foto) {
this.foto = foto;
}
public byte[] getFotoWeb() {
return this.fotoWeb;
}
public void setFotoWeb(byte[] fotoWeb) {
this.fotoWeb = fotoWeb;
}
public Date getHrAlteracao() {
return this.hrAlteracao;
}
public void setHrAlteracao(Date hrAlteracao) {
this.hrAlteracao = hrAlteracao;
}
public BigDecimal getIdEscolaFund() {
return this.idEscolaFund;
}
public void setIdEscolaFund(BigDecimal idEscolaFund) {
this.idEscolaFund = idEscolaFund;
}
public BigDecimal getIdEscolaMedio() {
return this.idEscolaMedio;
}
public void setIdEscolaMedio(BigDecimal idEscolaMedio) {
this.idEscolaMedio = idEscolaMedio;
}
public BigDecimal getIdTutorFin() {
return this.idTutorFin;
}
public void setIdTutorFin(BigDecimal idTutorFin) {
this.idTutorFin = idTutorFin;
}
public BigDecimal getNacionalidadeItem() {
return this.nacionalidadeItem;
}
public void setNacionalidadeItem(BigDecimal nacionalidadeItem) {
this.nacionalidadeItem = nacionalidadeItem;
}
public BigDecimal getNacionalidadeTab() {
return this.nacionalidadeTab;
}
public void setNacionalidadeTab(BigDecimal nacionalidadeTab) {
this.nacionalidadeTab = nacionalidadeTab;
}
public String getNomeMae() {
return this.nomeMae;
}
public void setNomeMae(String nomeMae) {
this.nomeMae = nomeMae;
}
public String getNomePai() {
return this.nomePai;
}
public void setNomePai(String nomePai) {
this.nomePai = nomePai;
}
public String getSexo() {
return this.sexo;
}
public void setSexo(String sexo) {
this.sexo = sexo;
}
public String getTipoSanguineo() {
return this.tipoSanguineo;
}
public void setTipoSanguineo(String tipoSanguineo) {
this.tipoSanguineo = tipoSanguineo;
}
public String getUrl() {
return this.url;
}
public void setUrl(String url) {
this.url = url;
}
public Cidade getCidade1() {
return this.cidade1;
}
public void setCidade1(Cidade cidade1) {
this.cidade1 = cidade1;
}
public Cidade getCidade2() {
return this.cidade2;
}
public void setCidade2(Cidade cidade2) {
this.cidade2 = cidade2;
}
public Cidade getCidade3() {
return this.cidade3;
}
public void setCidade3(Cidade cidade3) {
this.cidade3 = cidade3;
}
public Pessoa getPessoa1() {
return this.pessoa1;
}
public void setPessoa1(Pessoa pessoa1) {
this.pessoa1 = pessoa1;
}
public Pessoa getPessoa2() {
return this.pessoa2;
}
public void setPessoa2(Pessoa pessoa2) {
this.pessoa2 = pessoa2;
}
public List<CursosAluno> getCursosAlunos() {
return this.cursosAlunos;
}
public void setCursosAlunos(List<CursosAluno> cursosAlunos) {
this.cursosAlunos = cursosAlunos;
}
public CursosAluno addCursosAluno(CursosAluno cursosAluno) {
getCursosAlunos().add(cursosAluno);
cursosAluno.setAluno(this);
return cursosAluno;
}
public CursosAluno removeCursosAluno(CursosAluno cursosAluno) {
getCursosAlunos().remove(cursosAluno);
cursosAluno.setAluno(null);
return cursosAluno;
}
} | UTF-8 | Java | 10,353 | java | Aluno.java | Java | []
| null | []
| package br.gov.esmpu.sie.model;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.codehaus.jackson.annotate.JsonBackReference;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonManagedReference;
/**
* The persistent class for the ALUNOS database table.
*
*/
@Entity
@Table(name="ALUNOS")
@NamedQuery(name="Aluno.findAll", query="SELECT a FROM Aluno a")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Aluno implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="ID_ALUNO")
private long idAluno;
@Column(name="ANO_CONC_FUND")
private BigDecimal anoConcFund;
@Column(name="ANO_CONC_MEDIO")
private BigDecimal anoConcMedio;
@Column(name="COD_OPERADOR")
private BigDecimal codOperador;
private BigDecimal concorrencia;
@Column(name="CURSO_FUND_ITEM")
private BigDecimal cursoFundItem;
@Column(name="CURSO_FUND_TAB")
private BigDecimal cursoFundTab;
@Column(name="CURSO_MEDIO_ITEM")
private BigDecimal cursoMedioItem;
@Column(name="CURSO_MEDIO_TAB")
private BigDecimal cursoMedioTab;
@Column(name="DEFICIENCIA_ITEM")
private BigDecimal deficienciaItem;
@Column(name="DEFICIENCIA_TAB")
private BigDecimal deficienciaTab;
@Temporal(TemporalType.DATE)
@Column(name="DT_ALTERACAO")
private Date dtAlteracao;
@Temporal(TemporalType.DATE)
@Column(name="DT_NASCIMENTO")
private Date dtNascimento;
@Column(name="ENDERECO_FISICO")
private String enderecoFisico;
@Column(name="ESTADO_CIVIL_ITEM")
private BigDecimal estadoCivilItem;
@Column(name="ESTADO_CIVIL_TAB")
private BigDecimal estadoCivilTab;
@Column(name="ETNIA_ITEM")
private BigDecimal etniaItem;
@Column(name="ETNIA_TAB")
private BigDecimal etniaTab;
@Column(name="FATOR_RH")
private String fatorRh;
@Lob
private byte[] foto;
@Lob
@Column(name="FOTO_WEB")
private byte[] fotoWeb;
@Temporal(TemporalType.DATE)
@Column(name="HR_ALTERACAO")
private Date hrAlteracao;
@Column(name="ID_ESCOLA_FUND")
private BigDecimal idEscolaFund;
@Column(name="ID_ESCOLA_MEDIO")
private BigDecimal idEscolaMedio;
@Column(name="ID_TUTOR_FIN")
private BigDecimal idTutorFin;
@Column(name="NACIONALIDADE_ITEM")
private BigDecimal nacionalidadeItem;
@Column(name="NACIONALIDADE_TAB")
private BigDecimal nacionalidadeTab;
@Column(name="NOME_MAE")
private String nomeMae;
@Column(name="NOME_PAI")
private String nomePai;
private String sexo;
@Column(name="TIPO_SANGUINEO")
private String tipoSanguineo;
private String url;
//bi-directional many-to-one association to Cidade
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="ID_NATURALIDADE")
@JsonManagedReference
private Cidade cidade1;
//bi-directional many-to-one association to Cidade
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="ID_LOCAL_FUND")
@JsonManagedReference
private Cidade cidade2;
//bi-directional many-to-one association to Cidade
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="ID_LOCAL_MEDIO")
@JsonManagedReference
private Cidade cidade3;
//bi-directional many-to-one association to Pessoa
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="ID_RESPONSAVEL")
@JsonManagedReference
private Pessoa pessoa1;
//bi-directional many-to-one association to Pessoa
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="ID_PESSOA")
@JsonManagedReference
private Pessoa pessoa2;
//bi-directional many-to-one association to CursosAluno
@OneToMany(mappedBy="aluno")
@JsonBackReference
private List<CursosAluno> cursosAlunos;
public Aluno() {
}
public long getIdAluno() {
return this.idAluno;
}
public void setIdAluno(long idAluno) {
this.idAluno = idAluno;
}
public BigDecimal getAnoConcFund() {
return this.anoConcFund;
}
public void setAnoConcFund(BigDecimal anoConcFund) {
this.anoConcFund = anoConcFund;
}
public BigDecimal getAnoConcMedio() {
return this.anoConcMedio;
}
public void setAnoConcMedio(BigDecimal anoConcMedio) {
this.anoConcMedio = anoConcMedio;
}
public BigDecimal getCodOperador() {
return this.codOperador;
}
public void setCodOperador(BigDecimal codOperador) {
this.codOperador = codOperador;
}
public BigDecimal getConcorrencia() {
return this.concorrencia;
}
public void setConcorrencia(BigDecimal concorrencia) {
this.concorrencia = concorrencia;
}
public BigDecimal getCursoFundItem() {
return this.cursoFundItem;
}
public void setCursoFundItem(BigDecimal cursoFundItem) {
this.cursoFundItem = cursoFundItem;
}
public BigDecimal getCursoFundTab() {
return this.cursoFundTab;
}
public void setCursoFundTab(BigDecimal cursoFundTab) {
this.cursoFundTab = cursoFundTab;
}
public BigDecimal getCursoMedioItem() {
return this.cursoMedioItem;
}
public void setCursoMedioItem(BigDecimal cursoMedioItem) {
this.cursoMedioItem = cursoMedioItem;
}
public BigDecimal getCursoMedioTab() {
return this.cursoMedioTab;
}
public void setCursoMedioTab(BigDecimal cursoMedioTab) {
this.cursoMedioTab = cursoMedioTab;
}
public BigDecimal getDeficienciaItem() {
return this.deficienciaItem;
}
public void setDeficienciaItem(BigDecimal deficienciaItem) {
this.deficienciaItem = deficienciaItem;
}
public BigDecimal getDeficienciaTab() {
return this.deficienciaTab;
}
public void setDeficienciaTab(BigDecimal deficienciaTab) {
this.deficienciaTab = deficienciaTab;
}
public Date getDtAlteracao() {
return this.dtAlteracao;
}
public void setDtAlteracao(Date dtAlteracao) {
this.dtAlteracao = dtAlteracao;
}
public Date getDtNascimento() {
return this.dtNascimento;
}
public void setDtNascimento(Date dtNascimento) {
this.dtNascimento = dtNascimento;
}
public String getEnderecoFisico() {
return this.enderecoFisico;
}
public void setEnderecoFisico(String enderecoFisico) {
this.enderecoFisico = enderecoFisico;
}
public BigDecimal getEstadoCivilItem() {
return this.estadoCivilItem;
}
public void setEstadoCivilItem(BigDecimal estadoCivilItem) {
this.estadoCivilItem = estadoCivilItem;
}
public BigDecimal getEstadoCivilTab() {
return this.estadoCivilTab;
}
public void setEstadoCivilTab(BigDecimal estadoCivilTab) {
this.estadoCivilTab = estadoCivilTab;
}
public BigDecimal getEtniaItem() {
return this.etniaItem;
}
public void setEtniaItem(BigDecimal etniaItem) {
this.etniaItem = etniaItem;
}
public BigDecimal getEtniaTab() {
return this.etniaTab;
}
public void setEtniaTab(BigDecimal etniaTab) {
this.etniaTab = etniaTab;
}
public String getFatorRh() {
return this.fatorRh;
}
public void setFatorRh(String fatorRh) {
this.fatorRh = fatorRh;
}
public byte[] getFoto() {
return this.foto;
}
public void setFoto(byte[] foto) {
this.foto = foto;
}
public byte[] getFotoWeb() {
return this.fotoWeb;
}
public void setFotoWeb(byte[] fotoWeb) {
this.fotoWeb = fotoWeb;
}
public Date getHrAlteracao() {
return this.hrAlteracao;
}
public void setHrAlteracao(Date hrAlteracao) {
this.hrAlteracao = hrAlteracao;
}
public BigDecimal getIdEscolaFund() {
return this.idEscolaFund;
}
public void setIdEscolaFund(BigDecimal idEscolaFund) {
this.idEscolaFund = idEscolaFund;
}
public BigDecimal getIdEscolaMedio() {
return this.idEscolaMedio;
}
public void setIdEscolaMedio(BigDecimal idEscolaMedio) {
this.idEscolaMedio = idEscolaMedio;
}
public BigDecimal getIdTutorFin() {
return this.idTutorFin;
}
public void setIdTutorFin(BigDecimal idTutorFin) {
this.idTutorFin = idTutorFin;
}
public BigDecimal getNacionalidadeItem() {
return this.nacionalidadeItem;
}
public void setNacionalidadeItem(BigDecimal nacionalidadeItem) {
this.nacionalidadeItem = nacionalidadeItem;
}
public BigDecimal getNacionalidadeTab() {
return this.nacionalidadeTab;
}
public void setNacionalidadeTab(BigDecimal nacionalidadeTab) {
this.nacionalidadeTab = nacionalidadeTab;
}
public String getNomeMae() {
return this.nomeMae;
}
public void setNomeMae(String nomeMae) {
this.nomeMae = nomeMae;
}
public String getNomePai() {
return this.nomePai;
}
public void setNomePai(String nomePai) {
this.nomePai = nomePai;
}
public String getSexo() {
return this.sexo;
}
public void setSexo(String sexo) {
this.sexo = sexo;
}
public String getTipoSanguineo() {
return this.tipoSanguineo;
}
public void setTipoSanguineo(String tipoSanguineo) {
this.tipoSanguineo = tipoSanguineo;
}
public String getUrl() {
return this.url;
}
public void setUrl(String url) {
this.url = url;
}
public Cidade getCidade1() {
return this.cidade1;
}
public void setCidade1(Cidade cidade1) {
this.cidade1 = cidade1;
}
public Cidade getCidade2() {
return this.cidade2;
}
public void setCidade2(Cidade cidade2) {
this.cidade2 = cidade2;
}
public Cidade getCidade3() {
return this.cidade3;
}
public void setCidade3(Cidade cidade3) {
this.cidade3 = cidade3;
}
public Pessoa getPessoa1() {
return this.pessoa1;
}
public void setPessoa1(Pessoa pessoa1) {
this.pessoa1 = pessoa1;
}
public Pessoa getPessoa2() {
return this.pessoa2;
}
public void setPessoa2(Pessoa pessoa2) {
this.pessoa2 = pessoa2;
}
public List<CursosAluno> getCursosAlunos() {
return this.cursosAlunos;
}
public void setCursosAlunos(List<CursosAluno> cursosAlunos) {
this.cursosAlunos = cursosAlunos;
}
public CursosAluno addCursosAluno(CursosAluno cursosAluno) {
getCursosAlunos().add(cursosAluno);
cursosAluno.setAluno(this);
return cursosAluno;
}
public CursosAluno removeCursosAluno(CursosAluno cursosAluno) {
getCursosAlunos().remove(cursosAluno);
cursosAluno.setAluno(null);
return cursosAluno;
}
} | 10,353 | 0.76007 | 0.756592 | 494 | 19.959515 | 18.394529 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.1417 | false | false | 0 |
205704f6c96feb07cd99bc08fce75a09b12ccc70 | 31,894,427,187,977 | 32849c12dafdbb8c22c1c3717531017bc80f9480 | /Lec8/src/Task1.java | 644f948dc0eff1757da525d9f560556c746e8c3a | []
| no_license | ibelecka/JavaLessons | https://github.com/ibelecka/JavaLessons | beda92514c72838238600604459f03b04ba63729 | 820af2941e5d8b7581c5fb52192adce0132d65b2 | refs/heads/master | 2020-09-11T07:05:12.383000 | 2019-12-02T17:52:14 | 2019-12-02T17:52:14 | 221,982,028 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | //➢Create a method which has 2 arguments one of type boolean and
//another double and this method should return String value as
//concatenation of arguments
class Work {
String schedule (boolean weekDay, double hours) {
return weekDay + " " + hours;
}
}
public class Task1 {
public static void main(String[] args) {
Work work = new Work();
System.out.println(work.schedule(false, 5.5));
}
}
| UTF-8 | Java | 413 | java | Task1.java | Java | []
| null | []
| //➢Create a method which has 2 arguments one of type boolean and
//another double and this method should return String value as
//concatenation of arguments
class Work {
String schedule (boolean weekDay, double hours) {
return weekDay + " " + hours;
}
}
public class Task1 {
public static void main(String[] args) {
Work work = new Work();
System.out.println(work.schedule(false, 5.5));
}
}
| 413 | 0.698297 | 0.688564 | 20 | 19.549999 | 22.035143 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.95 | false | false | 0 |
94e9b5cbc368a55b737675254a7a1675affcae90 | 601,295,471,492 | 19ea715d721f33d144a3ad0e639015e873dc5858 | /src/com/ai/uint/ejb/vo/CommonEjbSVRequestVO.java | b18e6a9e7d70640a85753781954c141b37219296 | []
| no_license | liduote/UINT_PRODUCT | https://github.com/liduote/UINT_PRODUCT | 47fb90e3c4fac4540ac5ebda7176744d696f84a4 | b4cbef1c6300e8f7e29a55629dd83e1d6de7e971 | refs/heads/master | 2018-01-03T22:25:30.265000 | 2016-10-18T15:15:32 | 2016-10-18T15:15:32 | 71,261,408 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ai.uint.ejb.vo;
import java.io.Serializable;
public class CommonEjbSVRequestVO implements Serializable {
private static final long serialVersionUID = 1L;
public final static String EJB_SV_PROVIDER_CODE_CHNL_PRECHECK_TASK_FINSH = "CHNL_PRECHECK_TASK_FINSH";
public final static String EJB_SV_PROVIDER_CODE_CHANNEL_UPDATE = "CHANNEL_UPDATE";
public final static String EJB_SV_PROVIDER_CODE_CHANNEL_RECEIVE = "CHANNEL_RECEIVE";
public final static String EJB_SV_PROVIDER_CODE_CHANNEL_CREATE_WF = "CHANNEL_CREATE_WF";
public final static String EJB_SV_PROVIDER_CODE_CHNL_LIQUIDATION_TASK_FINISH = "CHNL_LIQUIDATION_TASK_FINISH";
public final static String EJB_SV_PROVIDER_CODE_CHNL_ORDER_SYNC_RESULT = "CHNL_ORDER_SYNC_RESULT";
public final static String EJB_SV_PROVIDER_CODE_WAIT_PREV_ACTION = "WAIT_PREV_ACTION";
public final static String EJB_SV_PROVIDER_CODE_CHNL_REL_CHNL_CHG_RESULT = "CHNL_REL_CHNL_CHG_RESULT";
public final static String EJB_SV_PROVIDER_CODE_PRE_VALIDATE_RESULT = "PRE_VALIDATE_RESULT";
public final static String EJB_SV_PROVIDER_CODE_CHANNEL_PARAM_RECEIVE = "CHANNEL_PARAM_RECEIVE";
public final static String EJB_SV_PROVIDER_CODE_APPLE_AUTH_RECEIVE = "APPLE_AUTH_RECEIVE";
private String ejbSVProviderCode;
private Object inputBusiParam;
public void setEjbSVProviderCode(String ejbSVProviderCode)
{
this.ejbSVProviderCode = ejbSVProviderCode;
}
public String getEjbSVProviderCode()
{
return this.ejbSVProviderCode;
}
public void setInputBusiParam(Object inputBusiParam)
{
this.inputBusiParam = inputBusiParam;
}
public Object getInputBusiParam()
{
return this.inputBusiParam;
}
}
| UTF-8 | Java | 1,661 | java | CommonEjbSVRequestVO.java | Java | []
| null | []
| package com.ai.uint.ejb.vo;
import java.io.Serializable;
public class CommonEjbSVRequestVO implements Serializable {
private static final long serialVersionUID = 1L;
public final static String EJB_SV_PROVIDER_CODE_CHNL_PRECHECK_TASK_FINSH = "CHNL_PRECHECK_TASK_FINSH";
public final static String EJB_SV_PROVIDER_CODE_CHANNEL_UPDATE = "CHANNEL_UPDATE";
public final static String EJB_SV_PROVIDER_CODE_CHANNEL_RECEIVE = "CHANNEL_RECEIVE";
public final static String EJB_SV_PROVIDER_CODE_CHANNEL_CREATE_WF = "CHANNEL_CREATE_WF";
public final static String EJB_SV_PROVIDER_CODE_CHNL_LIQUIDATION_TASK_FINISH = "CHNL_LIQUIDATION_TASK_FINISH";
public final static String EJB_SV_PROVIDER_CODE_CHNL_ORDER_SYNC_RESULT = "CHNL_ORDER_SYNC_RESULT";
public final static String EJB_SV_PROVIDER_CODE_WAIT_PREV_ACTION = "WAIT_PREV_ACTION";
public final static String EJB_SV_PROVIDER_CODE_CHNL_REL_CHNL_CHG_RESULT = "CHNL_REL_CHNL_CHG_RESULT";
public final static String EJB_SV_PROVIDER_CODE_PRE_VALIDATE_RESULT = "PRE_VALIDATE_RESULT";
public final static String EJB_SV_PROVIDER_CODE_CHANNEL_PARAM_RECEIVE = "CHANNEL_PARAM_RECEIVE";
public final static String EJB_SV_PROVIDER_CODE_APPLE_AUTH_RECEIVE = "APPLE_AUTH_RECEIVE";
private String ejbSVProviderCode;
private Object inputBusiParam;
public void setEjbSVProviderCode(String ejbSVProviderCode)
{
this.ejbSVProviderCode = ejbSVProviderCode;
}
public String getEjbSVProviderCode()
{
return this.ejbSVProviderCode;
}
public void setInputBusiParam(Object inputBusiParam)
{
this.inputBusiParam = inputBusiParam;
}
public Object getInputBusiParam()
{
return this.inputBusiParam;
}
}
| 1,661 | 0.784467 | 0.783865 | 44 | 36.75 | 38.02877 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.295455 | false | false | 0 |
1ea8ff58c18fcb03b42f40c77f2a0385c23f831b | 5,892,695,178,079 | 98584a4da85aa36aaa4f57c0e28dacd5202febfc | /HeadFirstDesignPatterns/src/proxy/automat/StanWygrana.java | 937a6bb6645fe57da6aa1b12765c66962575aa8e | []
| no_license | jpowelski/design_patterns | https://github.com/jpowelski/design_patterns | aa057c1bff545d29492dd87304a2bbeef1a6ddfc | 221b086b1c0252ebd9739637342cc2bb14ba45d9 | refs/heads/master | 2020-05-31T23:10:32.153000 | 2014-05-12T19:11:09 | 2014-05-12T19:11:09 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package proxy.automat;
import java.rmi.RemoteException;
public class StanWygrana implements Stan {
private transient AutomatSprzedający automat;
public StanWygrana(AutomatSprzedający automatSprzedający) {
this.automat = automatSprzedający;
}
@Override
public void włóżMonetę() {
System.out.println("Proszę czekać na gumę");
}
@Override
public void zwróćMonetę() {
System.out.println("Niestety, nie można zwrócić monety po przekręceniu gałki");
}
@Override
public void przekręćGałkę() {
System.out.println("Nie dostaniesz gumy tylko dlatego bo przekręciłeś drugi raz");
}
@Override
public void wydaj() throws RemoteException {
System.out.println("WYGRAŁEŚ! Dostajesz drugą gumę");
automat.zwolnijGume();
if (automat.pobierzLiczba() == 0){
automat.ustawStan(automat.pobierzStanBrakGum());
} else{
if (automat.pobierzLiczba() > 0){
automat.ustawStan(automat.pobierzStanNieMaMonety());
} else{
System.out.println("ups, koniec gum");
automat.ustawStan(automat.pobierzStanBrakGum());
}
}
}
}
| UTF-8 | Java | 1,082 | java | StanWygrana.java | Java | []
| null | []
| package proxy.automat;
import java.rmi.RemoteException;
public class StanWygrana implements Stan {
private transient AutomatSprzedający automat;
public StanWygrana(AutomatSprzedający automatSprzedający) {
this.automat = automatSprzedający;
}
@Override
public void włóżMonetę() {
System.out.println("Proszę czekać na gumę");
}
@Override
public void zwróćMonetę() {
System.out.println("Niestety, nie można zwrócić monety po przekręceniu gałki");
}
@Override
public void przekręćGałkę() {
System.out.println("Nie dostaniesz gumy tylko dlatego bo przekręciłeś drugi raz");
}
@Override
public void wydaj() throws RemoteException {
System.out.println("WYGRAŁEŚ! Dostajesz drugą gumę");
automat.zwolnijGume();
if (automat.pobierzLiczba() == 0){
automat.ustawStan(automat.pobierzStanBrakGum());
} else{
if (automat.pobierzLiczba() > 0){
automat.ustawStan(automat.pobierzStanNieMaMonety());
} else{
System.out.println("ups, koniec gum");
automat.ustawStan(automat.pobierzStanBrakGum());
}
}
}
}
| 1,082 | 0.73384 | 0.731939 | 44 | 22.90909 | 23.542822 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.636364 | false | false | 0 |
2b12f7df0ac2edf847814eba3293a291189a90f6 | 28,879,360,146,063 | 3b5a6eab0747ac5f4c661fe55d2d7bde4f143fab | /Union/src/main/java/com/revature/servlet/ApproveEvent.java | 59bc5499440e335a83b06475336eddc34c1ee6c8 | []
| no_license | dvosecky/Union | https://github.com/dvosecky/Union | 21d91370d66e3a02e49f6b76272c597b417ffef9 | 7078af43dfa188b2d90f0cf4183d064e861b8c0a | refs/heads/master | 2020-04-01T15:37:36.370000 | 2018-10-29T03:56:23 | 2018-10-29T03:56:23 | 153,344,142 | 0 | 0 | null | false | 2018-10-29T00:46:57 | 2018-10-16T19:41:39 | 2018-10-29T00:30:45 | 2018-10-29T00:46:57 | 17,348 | 0 | 0 | 0 | CSS | false | null | package com.revature.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 org.apache.log4j.Logger;
import com.revature.services.EventService;
/* RETURNS EITHER
* 200 success code if successfully approves event
* 400 error code if lacking input
* 401 error code if lacking credentials
* 500 error code for all other cases
*/
public class ApproveEvent extends HttpServlet{
private static final Logger log = Logger.getLogger(ApproveEvent.class);
private static final long serialVersionUID = 974941227212480366L;
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
log.info("Received a request to approve an event.");
//Getting info from parameters and making conversions to integers
String proxyString = req.getParameter("acc_id");
if (proxyString == null) {
log.warn("Sending error back: did not find account id in parameters of request.");
res.sendError(401);
return;
}
Integer acc_id = Integer.getInteger(proxyString);
proxyString = req.getParameter("ev_id");
if (proxyString == null) {
log.warn("Sending error back: did not find event id in parameters of request.");
res.sendError(400);
return;
}
Integer ev_id = Integer.getInteger(proxyString);
//Accessing service layer to approve event.
boolean result = EventService.approveEvent(acc_id, ev_id);
//Checking results and sending back appropriate http code in response.
log.trace("Checking boolean result of event approval.");
if (result) {
res.sendError(200);
}
log.warn("Sending error back: approval of event unsuccessful.");
res.sendError(500);
}
}
| UTF-8 | Java | 1,807 | java | ApproveEvent.java | Java | []
| null | []
| package com.revature.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 org.apache.log4j.Logger;
import com.revature.services.EventService;
/* RETURNS EITHER
* 200 success code if successfully approves event
* 400 error code if lacking input
* 401 error code if lacking credentials
* 500 error code for all other cases
*/
public class ApproveEvent extends HttpServlet{
private static final Logger log = Logger.getLogger(ApproveEvent.class);
private static final long serialVersionUID = 974941227212480366L;
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
log.info("Received a request to approve an event.");
//Getting info from parameters and making conversions to integers
String proxyString = req.getParameter("acc_id");
if (proxyString == null) {
log.warn("Sending error back: did not find account id in parameters of request.");
res.sendError(401);
return;
}
Integer acc_id = Integer.getInteger(proxyString);
proxyString = req.getParameter("ev_id");
if (proxyString == null) {
log.warn("Sending error back: did not find event id in parameters of request.");
res.sendError(400);
return;
}
Integer ev_id = Integer.getInteger(proxyString);
//Accessing service layer to approve event.
boolean result = EventService.approveEvent(acc_id, ev_id);
//Checking results and sending back appropriate http code in response.
log.trace("Checking boolean result of event approval.");
if (result) {
res.sendError(200);
}
log.warn("Sending error back: approval of event unsuccessful.");
res.sendError(500);
}
}
| 1,807 | 0.753735 | 0.729939 | 55 | 31.854546 | 26.812763 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.8 | false | false | 0 |
53bf9c306973e7d4eb220c1efe494115f1e6ba7d | 4,071,629,040,541 | 30fa90830b5c0818a7eb833865c2691da04d0fd8 | /src/Highscores_Database.java | c7a8f9d321781ea16f82a5f5e23cb2e37f437f61 | []
| no_license | Kor-Phaeron/Ro-sham-bo | https://github.com/Kor-Phaeron/Ro-sham-bo | 6e14832b3a7c00dae2c19d02a032920398f1aea9 | f4ada88a34a0ffd774982e330097afe37f67eea2 | refs/heads/master | 2022-11-13T05:37:24.860000 | 2020-07-12T20:28:58 | 2020-07-12T20:28:58 | 276,068,729 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.sql.Connection;
import java.sql.DriverManager;
public class Highscores_Database {
static final String host = "192.168.1.17";
static final String port = "5432";
static final String db_name = "ro_sham_bo";
static final String user = "pi";
static final String pwd = "admin";
public static void main(String[] args) {
Highscores_Database obj_HighscoresDatabase = new Highscores_Database();
System.out.println(obj_HighscoresDatabase.getConnection());
}
public Connection getConnection() {
Connection connection = null;
try {
Class.forName("org.postgresql.Driver");
connection = DriverManager
.getConnection("jdbc:postgresql://"+ host + ":" + port + "/" + db_name,
user, pwd);
} catch (Exception e) {
e.printStackTrace();
System.err.println(e.getClass().getName()+": "+e.getMessage());
System.exit(0);
}
return connection;
}
}
| UTF-8 | Java | 1,038 | java | Highscores_Database.java | Java | [
{
"context": "cores_Database {\n\n static final String host = \"192.168.1.17\";\n static final String port = \"5432\";\n stat",
"end": 140,
"score": 0.9997684955596924,
"start": 128,
"tag": "IP_ADDRESS",
"value": "192.168.1.17"
},
{
"context": "e = \"ro_sham_bo\";\n static final String user = \"pi\";\n static final String pwd = \"admin\";\n\n pub",
"end": 264,
"score": 0.9949735403060913,
"start": 262,
"tag": "USERNAME",
"value": "pi"
},
{
"context": "tring user = \"pi\";\n static final String pwd = \"admin\";\n\n public static void main(String[] args) {\n ",
"end": 303,
"score": 0.9994175434112549,
"start": 298,
"tag": "PASSWORD",
"value": "admin"
}
]
| null | []
| import java.sql.Connection;
import java.sql.DriverManager;
public class Highscores_Database {
static final String host = "192.168.1.17";
static final String port = "5432";
static final String db_name = "ro_sham_bo";
static final String user = "pi";
static final String pwd = "<PASSWORD>";
public static void main(String[] args) {
Highscores_Database obj_HighscoresDatabase = new Highscores_Database();
System.out.println(obj_HighscoresDatabase.getConnection());
}
public Connection getConnection() {
Connection connection = null;
try {
Class.forName("org.postgresql.Driver");
connection = DriverManager
.getConnection("jdbc:postgresql://"+ host + ":" + port + "/" + db_name,
user, pwd);
} catch (Exception e) {
e.printStackTrace();
System.err.println(e.getClass().getName()+": "+e.getMessage());
System.exit(0);
}
return connection;
}
}
| 1,043 | 0.588632 | 0.575145 | 33 | 30.454546 | 24.250074 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.545455 | false | false | 0 |
88ecbd084ea764f86ec18674cf44586fa5014517 | 30,356,828,893,117 | 8f40353fccaafa8280d038bac7fc455ce95bd568 | /src/main/java/com/secondhand/service/impl/UserServiceImpl.java | aaf4b886c4d626e16a9dea1f445dc1401fef001d | []
| no_license | lmTLL/batter | https://github.com/lmTLL/batter | e7ec82624b77ed326e898b1d4bc3b9f120c0c644 | cad64ce66938fe3b16dc03b2ef4531c0f84a6f39 | refs/heads/master | 2020-04-17T11:27:33.044000 | 2019-01-21T09:56:41 | 2019-01-21T09:56:41 | 166,541,624 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.secondhand.service.impl;
import com.qfedu.vo.ResultVo;
import com.secondhand.dao.UserMapper;
import com.secondhand.entity.User;
import com.secondhand.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userDao;
@Override
public ResultVo login(String name, String password) {
User user = userDao.selectByName(name);
if(user!=null) {
if(user.getPassword().equals(password)) {
return ResultVo.setOK(user);
}
}
return ResultVo.setERROR();
}
@Override
public User queryByName(String name) {
return userDao.selectByName(name);
}
@Override
public ResultVo add(User user) {
int ret = userDao.insertSelective(user);
if (ret>0){
return ResultVo.setOK("注册成功");
}else {
return ResultVo.setERROR();
}
}
}
| UTF-8 | Java | 1,073 | java | UserServiceImpl.java | Java | []
| null | []
| package com.secondhand.service.impl;
import com.qfedu.vo.ResultVo;
import com.secondhand.dao.UserMapper;
import com.secondhand.entity.User;
import com.secondhand.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userDao;
@Override
public ResultVo login(String name, String password) {
User user = userDao.selectByName(name);
if(user!=null) {
if(user.getPassword().equals(password)) {
return ResultVo.setOK(user);
}
}
return ResultVo.setERROR();
}
@Override
public User queryByName(String name) {
return userDao.selectByName(name);
}
@Override
public ResultVo add(User user) {
int ret = userDao.insertSelective(user);
if (ret>0){
return ResultVo.setOK("注册成功");
}else {
return ResultVo.setERROR();
}
}
}
| 1,073 | 0.649765 | 0.648826 | 44 | 23.204546 | 19.447575 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.363636 | false | false | 0 |
e6b151d3b6439967120dee332d015523cac098cd | 12,910,671,752,663 | 49bada98ab00313f386a81bca1e3e22fc7d5288f | /src/main/java/me/sapien/plugin/sapien/Sapien.java | 29002631304e708cdd6f7280dc9be5a171bf8088 | []
| no_license | fdemir/sapien | https://github.com/fdemir/sapien | 80015f3ed6df49f37567ad0e2bacbabd76ca0856 | 9f8b436fa6754baf6a259914e3170ea0acc03d66 | refs/heads/master | 2022-09-20T07:02:23.166000 | 2020-05-30T01:43:25 | 2020-05-30T01:43:25 | 267,301,313 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package me.sapien.plugin.sapien;
import me.sapien.plugin.sapien.Command.BaseCommand;
import me.sapien.plugin.sapien.Command.CommandList.SapienCommand;
import me.sapien.plugin.sapien.Config.Config;
import me.sapien.plugin.sapien.Core.Function;
import me.sapien.plugin.sapien.Core.Loader;
import me.sapien.plugin.sapien.Engine.Runtime;
import me.sapien.plugin.sapien.Engine.Temp;
import me.sapien.plugin.sapien.Util.CCommand;
import org.bukkit.command.SimpleCommandMap;
import org.bukkit.event.Listener;
import org.bukkit.plugin.SimplePluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import java.lang.reflect.Field;
import java.util.Arrays;
public final class Sapien extends JavaPlugin implements Listener {
private static Sapien instance;
private static SimpleCommandMap scm;
private SimplePluginManager spm;
public static Sapien getInstance() {
return instance;
}
public static SimpleCommandMap getCommandMap() {
return scm;
}
public Temp temp;
public Runtime runtime;
public Function function;
private Config config;
private Loader loader;
@Override
public void onLoad() {
instance = this;
this.temp = new Temp();
this.runtime = new Runtime(temp);
this.config = new Config();
this.function = new Function();
this.loader = new Loader();
setupSimpleCommandMap();
}
@Override
public void onEnable() {
config.init();
runtime.init();
function.loadAll();
loader.loadAllScripts();
new SapienCommand(this);
getLogger().info("Sapien has been enabled.");
}
public void registerCommands(CCommand... commands) {
Arrays.stream(commands).forEach(command -> scm.register("Sapien", command));
}
public void setupSimpleCommandMap() {
spm = (SimplePluginManager) this.getServer().getPluginManager();
Field f = null;
try {
f = SimplePluginManager.class.getDeclaredField("commandMap");
} catch (Exception e) {
e.printStackTrace();
}
f.setAccessible(true);
try {
scm = (SimpleCommandMap) f.get(spm);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onDisable() {
runtime.terminate();
getLogger().info("Sapien has been disabled.");
}
}
| UTF-8 | Java | 2,426 | java | Sapien.java | Java | []
| null | []
| package me.sapien.plugin.sapien;
import me.sapien.plugin.sapien.Command.BaseCommand;
import me.sapien.plugin.sapien.Command.CommandList.SapienCommand;
import me.sapien.plugin.sapien.Config.Config;
import me.sapien.plugin.sapien.Core.Function;
import me.sapien.plugin.sapien.Core.Loader;
import me.sapien.plugin.sapien.Engine.Runtime;
import me.sapien.plugin.sapien.Engine.Temp;
import me.sapien.plugin.sapien.Util.CCommand;
import org.bukkit.command.SimpleCommandMap;
import org.bukkit.event.Listener;
import org.bukkit.plugin.SimplePluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import java.lang.reflect.Field;
import java.util.Arrays;
public final class Sapien extends JavaPlugin implements Listener {
private static Sapien instance;
private static SimpleCommandMap scm;
private SimplePluginManager spm;
public static Sapien getInstance() {
return instance;
}
public static SimpleCommandMap getCommandMap() {
return scm;
}
public Temp temp;
public Runtime runtime;
public Function function;
private Config config;
private Loader loader;
@Override
public void onLoad() {
instance = this;
this.temp = new Temp();
this.runtime = new Runtime(temp);
this.config = new Config();
this.function = new Function();
this.loader = new Loader();
setupSimpleCommandMap();
}
@Override
public void onEnable() {
config.init();
runtime.init();
function.loadAll();
loader.loadAllScripts();
new SapienCommand(this);
getLogger().info("Sapien has been enabled.");
}
public void registerCommands(CCommand... commands) {
Arrays.stream(commands).forEach(command -> scm.register("Sapien", command));
}
public void setupSimpleCommandMap() {
spm = (SimplePluginManager) this.getServer().getPluginManager();
Field f = null;
try {
f = SimplePluginManager.class.getDeclaredField("commandMap");
} catch (Exception e) {
e.printStackTrace();
}
f.setAccessible(true);
try {
scm = (SimpleCommandMap) f.get(spm);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onDisable() {
runtime.terminate();
getLogger().info("Sapien has been disabled.");
}
}
| 2,426 | 0.658285 | 0.658285 | 90 | 25.955555 | 20.125668 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.544444 | false | false | 0 |
e3421f31602b514681a0875a757b0786213b2455 | 22,943,715,305,185 | 754dde7e7fba3f6392b01e7ca2037efd828df349 | /src/controller/PhotoController.java | db659ecaef4996d003bab04af5c650e9d3ad63c2 | []
| no_license | bendorado/PhotoAlbumFX | https://github.com/bendorado/PhotoAlbumFX | ea56171ecec131035e70bc2f0c1267221e4c417a | a900a77a62075c73b417f81dd1e3658df761f508 | refs/heads/master | 2020-09-12T11:26:45.812000 | 2020-01-09T13:37:55 | 2020-01-09T13:37:55 | 222,406,455 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package controller;
import handler.UserHandler;
import handler.ViewHandler;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.effect.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.FlowPane;
import javafx.scene.paint.Color;
import javafx.stage.FileChooser;
import model.Album;
import model.Photo;
import view.WindowFactory;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.net.URL;
import java.util.ResourceBundle;
public class PhotoController extends AlbumController {
static Album currentAlbum;
static int selectedPhotoIndex;
static Photo selectedPhoto;
@FXML private Label lblAlbumTitle;
@FXML private Label lblPhotoTitle;
@FXML private ScrollPane scrollPane;
@FXML private FlowPane flowPane;
@FXML private Button btnAdd;
@FXML private Button btnDelete;
@FXML private Button btnSlideshow;
@FXML private Button btnBack;
public PhotoController(ViewHandler viewHandler, UserHandler userHandler) {
super(viewHandler, userHandler);
}
@Override
public void initialize(URL location, ResourceBundle resources) {
currentAlbum = userHandler.getCurrentAlbum(selectedAlbumIndex);
lblAlbumTitle.setText(currentAlbum.getTitle());
updatePhotoTiles();
}
@FXML
void handleBtnAdd(ActionEvent event) {
File file = getFileDialog();
// No file chosen
if(file == null){
return;
}
else{
// Check, if file is already in photoList
for(Photo photo : currentAlbum.getPhotoList()){
if(photo.getImageFile().equals(file)){
return;
}
}
}
currentAlbum.addPhoto(new Photo(file.getName(),file));
userHandler.saveUsers();
updatePhotoTiles();
}
@FXML
void handleBtnBack(ActionEvent event) {
currentAlbum = null;
viewHandler.launchWindow(WindowFactory.ALBUM);
}
@FXML
void handleBtnDelete(ActionEvent event) {
currentAlbum.deletePhoto(selectedPhoto);
selectedPhoto = null;
userHandler.saveUsers();
updatePhotoTiles();
}
@FXML
void handleBtnLogout(ActionEvent event) {
currentAlbum = null;
viewHandler.launchWindow(WindowFactory.LOGIN);
userHandler.clearCurrentUser();
}
@FXML
void handleBtnSlideshow(ActionEvent event) {
viewHandler.launchWindow(WindowFactory.SLIDESHOW);
}
private void updatePhotoTiles(){
// Starts with an empty layout
flowPane.getChildren().clear();
for(Photo photo : currentAlbum.getPhotoList()){
Image image = new Image(new ByteArrayInputStream(photo.getByteArray()));
ImageView imageView = new ImageView(image);
imageView.setFitHeight(150.0);
imageView.setPreserveRatio(true);
// When clicked the ImageView has to get the focus
imageView.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
imageView.requestFocus();
selectedPhoto = photo;
}
});
// ChangeListener observing wether the image is selected (has focus) or not.
// Applies visual effects to the selected image and sets/unsets the selectedPhot attribute depending on the focus.
imageView.focusedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
if(newValue){
imageView.setEffect(new DropShadow(20, Color.DIMGREY));
imageView.setScaleX(0.9);
imageView.setScaleY(0.9);
lblPhotoTitle.setText(photo.getTitle());
}
if(oldValue){
imageView.setEffect(null);
imageView.setScaleX(1);
imageView.setScaleY(1);
lblPhotoTitle.setText("");
}
}
});
// Each imageView is added to the layout.
flowPane.getChildren().add(imageView);
}
}
private File getFileDialog(){
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Choose a Photo");
FileChooser.ExtensionFilter extensionFilter = new FileChooser.ExtensionFilter("*.jpg, *.png","*.jpg", "*.png");
fileChooser.getExtensionFilters().add(extensionFilter);
return fileChooser.showOpenDialog(btnAdd.getScene().getWindow());
}
}
| UTF-8 | Java | 5,229 | java | PhotoController.java | Java | []
| null | []
| package controller;
import handler.UserHandler;
import handler.ViewHandler;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.effect.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.FlowPane;
import javafx.scene.paint.Color;
import javafx.stage.FileChooser;
import model.Album;
import model.Photo;
import view.WindowFactory;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.net.URL;
import java.util.ResourceBundle;
public class PhotoController extends AlbumController {
static Album currentAlbum;
static int selectedPhotoIndex;
static Photo selectedPhoto;
@FXML private Label lblAlbumTitle;
@FXML private Label lblPhotoTitle;
@FXML private ScrollPane scrollPane;
@FXML private FlowPane flowPane;
@FXML private Button btnAdd;
@FXML private Button btnDelete;
@FXML private Button btnSlideshow;
@FXML private Button btnBack;
public PhotoController(ViewHandler viewHandler, UserHandler userHandler) {
super(viewHandler, userHandler);
}
@Override
public void initialize(URL location, ResourceBundle resources) {
currentAlbum = userHandler.getCurrentAlbum(selectedAlbumIndex);
lblAlbumTitle.setText(currentAlbum.getTitle());
updatePhotoTiles();
}
@FXML
void handleBtnAdd(ActionEvent event) {
File file = getFileDialog();
// No file chosen
if(file == null){
return;
}
else{
// Check, if file is already in photoList
for(Photo photo : currentAlbum.getPhotoList()){
if(photo.getImageFile().equals(file)){
return;
}
}
}
currentAlbum.addPhoto(new Photo(file.getName(),file));
userHandler.saveUsers();
updatePhotoTiles();
}
@FXML
void handleBtnBack(ActionEvent event) {
currentAlbum = null;
viewHandler.launchWindow(WindowFactory.ALBUM);
}
@FXML
void handleBtnDelete(ActionEvent event) {
currentAlbum.deletePhoto(selectedPhoto);
selectedPhoto = null;
userHandler.saveUsers();
updatePhotoTiles();
}
@FXML
void handleBtnLogout(ActionEvent event) {
currentAlbum = null;
viewHandler.launchWindow(WindowFactory.LOGIN);
userHandler.clearCurrentUser();
}
@FXML
void handleBtnSlideshow(ActionEvent event) {
viewHandler.launchWindow(WindowFactory.SLIDESHOW);
}
private void updatePhotoTiles(){
// Starts with an empty layout
flowPane.getChildren().clear();
for(Photo photo : currentAlbum.getPhotoList()){
Image image = new Image(new ByteArrayInputStream(photo.getByteArray()));
ImageView imageView = new ImageView(image);
imageView.setFitHeight(150.0);
imageView.setPreserveRatio(true);
// When clicked the ImageView has to get the focus
imageView.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
imageView.requestFocus();
selectedPhoto = photo;
}
});
// ChangeListener observing wether the image is selected (has focus) or not.
// Applies visual effects to the selected image and sets/unsets the selectedPhot attribute depending on the focus.
imageView.focusedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
if(newValue){
imageView.setEffect(new DropShadow(20, Color.DIMGREY));
imageView.setScaleX(0.9);
imageView.setScaleY(0.9);
lblPhotoTitle.setText(photo.getTitle());
}
if(oldValue){
imageView.setEffect(null);
imageView.setScaleX(1);
imageView.setScaleY(1);
lblPhotoTitle.setText("");
}
}
});
// Each imageView is added to the layout.
flowPane.getChildren().add(imageView);
}
}
private File getFileDialog(){
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Choose a Photo");
FileChooser.ExtensionFilter extensionFilter = new FileChooser.ExtensionFilter("*.jpg, *.png","*.jpg", "*.png");
fileChooser.getExtensionFilters().add(extensionFilter);
return fileChooser.showOpenDialog(btnAdd.getScene().getWindow());
}
}
| 5,229 | 0.635686 | 0.633391 | 157 | 32.305733 | 24.606628 | 126 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.585987 | false | false | 0 |
3eee265a4cf840ace5d806390fa4a15da8418ef1 | 2,284,922,656,510 | 575869a4b4082bc1e98d6af42f98decbbb872578 | /app/models/User.java | 9b6ca62e33dcb9570111aac675a03789dbd32866 | []
| no_license | sonphamhong/java_play | https://github.com/sonphamhong/java_play | f34e95869de014a07b716292c4d4b7438af61058 | 601517e25221c8da6ae3b49b78ba8a066422c3b4 | refs/heads/master | 2021-01-10T03:36:02.371000 | 2015-06-07T06:55:45 | 2015-06-07T06:55:45 | 36,604,803 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package models;
import java.util.*;
import javax.persistence.*;
import play.db.ebean.*;
@Entity
public class User extends Model{
@Id
public Long user_id;
public String email;
public String password;
@ManyToOne
public Company company;
@OneToMany(mappedBy="user_comm")
public List<Communication> communications;
public static Finder<String,User> find = new Finder<String,User>(
String.class, User.class
);
public ArrayList communicate_user(){
communications = this.communications;
ArrayList al = new ArrayList();
// System.out.print(communications);
for(Communication comm : communications){
al.add(comm.comm_with_user.email);
}
return al;
}
public static HashMap get_all_communications(){
HashMap hm = new HashMap();
List<User> users = User.find.all();
for(User user:users){
ArrayList al = new ArrayList();
al = user.communicate_user();
hm.put(user.email, al);
}
System.out.print(hm.get("user4@example.com"));
return hm;
}
}
| UTF-8 | Java | 1,000 | java | User.java | Java | [
{
"context": "t(user.email, al);\n\t\t}\n\t\tSystem.out.print(hm.get(\"user4@example.com\"));\n\t\treturn hm;\n\t\t\n\t}\n}\n",
"end": 974,
"score": 0.9998771548271179,
"start": 957,
"tag": "EMAIL",
"value": "user4@example.com"
}
]
| null | []
| package models;
import java.util.*;
import javax.persistence.*;
import play.db.ebean.*;
@Entity
public class User extends Model{
@Id
public Long user_id;
public String email;
public String password;
@ManyToOne
public Company company;
@OneToMany(mappedBy="user_comm")
public List<Communication> communications;
public static Finder<String,User> find = new Finder<String,User>(
String.class, User.class
);
public ArrayList communicate_user(){
communications = this.communications;
ArrayList al = new ArrayList();
// System.out.print(communications);
for(Communication comm : communications){
al.add(comm.comm_with_user.email);
}
return al;
}
public static HashMap get_all_communications(){
HashMap hm = new HashMap();
List<User> users = User.find.all();
for(User user:users){
ArrayList al = new ArrayList();
al = user.communicate_user();
hm.put(user.email, al);
}
System.out.print(hm.get("<EMAIL>"));
return hm;
}
}
| 990 | 0.697 | 0.696 | 47 | 20.276596 | 16.814005 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.744681 | false | false | 0 |
f85a6a596d654406d6e30a0b9c27ee1b4219319b | 15,255,723,856,674 | 6ab01047a2e983735f6ddd251986242101a40dbe | /core/src/com/davidbyttow/catfight/Catfight.java | 368e98fedfcbfe52b73fca385c532a4b087952df | []
| no_license | davidbyttow/catfight | https://github.com/davidbyttow/catfight | 57876a8cb2e6d51af6e7446c306a77854588b31a | a05275ed223770de8eb2b76858e4b98e3562964b | refs/heads/master | 2021-01-22T08:47:43.615000 | 2017-06-04T19:55:51 | 2017-06-04T19:55:51 | 92,633,529 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.davidbyttow.catfight;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.davidbyttow.catfight.game.GameScreen;
public class Catfight extends Game {
public SpriteBatch batcher;
@Override
public void create () {
batcher = new SpriteBatch();
Assets.load();
setScreen(new GameScreen(this));
}
@Override
public void render () {
Gdx.gl.glClearColor(0.5f, 0.5f, 0.5f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
super.render();
}
@Override
public void dispose () {
batcher.dispose();
}
}
| UTF-8 | Java | 633 | java | Catfight.java | Java | []
| null | []
| package com.davidbyttow.catfight;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.davidbyttow.catfight.game.GameScreen;
public class Catfight extends Game {
public SpriteBatch batcher;
@Override
public void create () {
batcher = new SpriteBatch();
Assets.load();
setScreen(new GameScreen(this));
}
@Override
public void render () {
Gdx.gl.glClearColor(0.5f, 0.5f, 0.5f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
super.render();
}
@Override
public void dispose () {
batcher.dispose();
}
}
| 633 | 0.726698 | 0.707741 | 30 | 20.1 | 15.929742 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.4 | false | false | 0 |
e84244b8ec4da83a77759002f4ebba4b4aeac18d | 22,728,966,940,939 | 783c8c0099c9be58926f57a270b2db326fe3787a | /dependencyLibs/Core/src/org/droidplanner/core/drone/variables/Navigation.java | cfe69bd8f73d909fb2c8af117644af40dd497b65 | []
| no_license | QuadrocopterFHK/DroneKit-Android | https://github.com/QuadrocopterFHK/DroneKit-Android | 2e87398485820bd145bc801e9359b2c0a01e30b3 | e380a67984ceff50897733c2eae7db3728cb5839 | refs/heads/develop | 2018-12-28T00:11:08.628000 | 2015-06-09T01:58:14 | 2015-06-09T01:58:14 | 37,342,667 | 1 | 1 | null | true | 2015-06-12T20:20:35 | 2015-06-12T20:20:35 | 2015-06-12T08:35:57 | 2015-06-12T19:35:40 | 56,770 | 0 | 0 | 0 | null | null | null | package org.droidplanner.core.drone.variables;
import org.droidplanner.core.drone.DroneInterfaces.DroneEventsType;
import org.droidplanner.core.drone.DroneVariable;
import org.droidplanner.core.model.Drone;
public class Navigation extends DroneVariable {
private double nav_pitch;
private double nav_roll;
private double nav_bearing;
public Navigation(Drone myDrone) {
super(myDrone);
}
public void setNavPitchRollYaw(float nav_pitch, float nav_roll, short nav_bearing) {
if(this.nav_pitch != nav_pitch || this.nav_roll != nav_roll || this.nav_bearing != nav_bearing) {
this.nav_pitch = nav_pitch;
this.nav_roll = nav_roll;
this.nav_bearing = nav_bearing;
myDrone.notifyDroneEvent(DroneEventsType.NAVIGATION);
}
}
public double getNavPitch() {
return nav_pitch;
}
public double getNavRoll() {
return nav_roll;
}
public double getNavBearing() {
return nav_bearing;
}
}
| UTF-8 | Java | 962 | java | Navigation.java | Java | []
| null | []
| package org.droidplanner.core.drone.variables;
import org.droidplanner.core.drone.DroneInterfaces.DroneEventsType;
import org.droidplanner.core.drone.DroneVariable;
import org.droidplanner.core.model.Drone;
public class Navigation extends DroneVariable {
private double nav_pitch;
private double nav_roll;
private double nav_bearing;
public Navigation(Drone myDrone) {
super(myDrone);
}
public void setNavPitchRollYaw(float nav_pitch, float nav_roll, short nav_bearing) {
if(this.nav_pitch != nav_pitch || this.nav_roll != nav_roll || this.nav_bearing != nav_bearing) {
this.nav_pitch = nav_pitch;
this.nav_roll = nav_roll;
this.nav_bearing = nav_bearing;
myDrone.notifyDroneEvent(DroneEventsType.NAVIGATION);
}
}
public double getNavPitch() {
return nav_pitch;
}
public double getNavRoll() {
return nav_roll;
}
public double getNavBearing() {
return nav_bearing;
}
}
| 962 | 0.704782 | 0.704782 | 38 | 24.31579 | 25.769325 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.105263 | false | false | 0 |
5b7e2cea8b2d16962a6862f17449fa284faf51f7 | 31,112,743,161,018 | 5d77abfba31d2f0a5cb2f92f937904859785e7ff | /Java/java_examples Hyd/BASICS/CLASSES6Interfaces/MobileApp.java | 8e6be243a3af16a2093303a9d0c0bfee07f1d856 | []
| no_license | thinkpavan/artefacts | https://github.com/thinkpavan/artefacts | d93a1c0be0b6158cb0976aae9af9c6a016ebfdae | 04bcf95450243dfe2f4fa8f09d96274034428e4d | refs/heads/master | 2020-04-01T20:24:34.142000 | 2016-07-07T16:27:47 | 2016-07-07T16:27:47 | 62,716,135 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /* This class is a Application class
Author : Team - J
Version: 1.0*/
class MobileApp {
public static void main( String args[]) throws Exception{
int i;
IRatePlan r;
cust c1 = new cust ( "suresh","HappyHourPlan");
cust c2 = new cust ( "raghu","RegularPlan");
RegularPlan rp;
r= c1.getRatePlan();
System.out.println(" Cust one bill ");
c1.PrintCustDetails();
r.CalculateBill();
r= c2.getRatePlan();
System.out.println(" Cust two bill ");
c2.PrintCustDetails();
r.CalculateBill();
rp = (RegularPlan ) r;
System.out.println(" IRatePlan.CONST = " + IRatePlan.CONST);
System.out.println(" IRatePlan.x = " + IRatePlan.x);
System.out.println(" r.CONST = " + r.CONST);
System.out.println(" r.x = " + r.x);
System.out.println(" rp.CONST = " + rp.CONST);
System.out.println(" rp.x = " + rp.x);
}
}
| UTF-8 | Java | 837 | java | MobileApp.java | Java | [
{
"context": "/* This class is a Application class\nAuthor : Team - J \nVersion: 1.0*/\n\nclass MobileApp { \n\t\n\tpublic st",
"end": 54,
"score": 0.9917649626731873,
"start": 46,
"tag": "NAME",
"value": "Team - J"
},
{
"context": "suresh\",\"HappyHourPlan\");\n\t\tcust c2 = new cust ( \"raghu\",\"RegularPlan\");\n\t\tRegularPlan rp;\n\t\tr= c1.getRat",
"end": 256,
"score": 0.6170873045921326,
"start": 251,
"tag": "NAME",
"value": "raghu"
}
]
| null | []
| /* This class is a Application class
Author : <NAME>
Version: 1.0*/
class MobileApp {
public static void main( String args[]) throws Exception{
int i;
IRatePlan r;
cust c1 = new cust ( "suresh","HappyHourPlan");
cust c2 = new cust ( "raghu","RegularPlan");
RegularPlan rp;
r= c1.getRatePlan();
System.out.println(" Cust one bill ");
c1.PrintCustDetails();
r.CalculateBill();
r= c2.getRatePlan();
System.out.println(" Cust two bill ");
c2.PrintCustDetails();
r.CalculateBill();
rp = (RegularPlan ) r;
System.out.println(" IRatePlan.CONST = " + IRatePlan.CONST);
System.out.println(" IRatePlan.x = " + IRatePlan.x);
System.out.println(" r.CONST = " + r.CONST);
System.out.println(" r.x = " + r.x);
System.out.println(" rp.CONST = " + rp.CONST);
System.out.println(" rp.x = " + rp.x);
}
}
| 835 | 0.639188 | 0.62963 | 29 | 27.827587 | 17.690966 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.241379 | false | false | 0 |
b70c15db36ff6e80c88c0f5a17b3535d3c50dafc | 27,685,359,203,599 | 87924925c3cfb8412c80f53e21c2b55ce616c2b5 | /src/test/java/eu/erasmuswithoutpaper/registry/validators/imobilitiesvalidator/AbstractIMobilitiesService.java | df859db593fd5e7f13dfefc63e654181a450116d | [
"MIT"
]
| permissive | erasmus-without-paper/ewp-registry-service | https://github.com/erasmus-without-paper/ewp-registry-service | c0a2bcd94fed3d894a9b6b24cc7fbc4a033ad8d7 | 57c9d0bed2993e8cd88a42ef973e1d9e5256c413 | refs/heads/master | 2023-07-12T23:06:15.207000 | 2023-07-04T13:00:21 | 2023-07-04T13:00:21 | 75,407,663 | 4 | 5 | MIT | false | 2023-02-28T10:53:36 | 2016-12-02T15:30:26 | 2023-01-12T14:20:59 | 2023-02-28T10:53:32 | 2,329 | 4 | 4 | 30 | Java | false | false | package eu.erasmuswithoutpaper.registry.validators.imobilitiesvalidator;
import java.io.IOException;
import eu.erasmuswithoutpaper.registry.internet.Request;
import eu.erasmuswithoutpaper.registry.internet.Response;
import eu.erasmuswithoutpaper.registry.validators.AbstractApiService;
import eu.erasmuswithoutpaper.registryclient.RegistryClient;
public abstract class AbstractIMobilitiesService extends AbstractApiService {
protected final String getUrl;
/**
* @param getUrl
* The endpoint at which to listen for get requests.
* @param registryClient
* Initialized and refreshed {@link RegistryClient} instance.
*/
public AbstractIMobilitiesService(String getUrl, RegistryClient registryClient) {
super(registryClient);
this.getUrl = getUrl;
}
public String getEndpoint() {
return getUrl;
}
@Override
public Response handleInternetRequest(Request request) throws IOException {
try {
if (request.getUrl().startsWith(this.getUrl)) {
return this.handleIMobilitiesGetInternetRequest(request);
}
return null;
} catch (ErrorResponseException e) {
return e.response;
}
}
/**
* @param request
* The request for which a response is to be generated
* @return {@link Response} object.
* @throws ErrorResponseException
* This can be thrown instead of returning the error response (a shortcut).
*/
protected abstract Response handleIMobilitiesGetInternetRequest(Request request)
throws ErrorResponseException;
}
| UTF-8 | Java | 1,540 | java | AbstractIMobilitiesService.java | Java | []
| null | []
| package eu.erasmuswithoutpaper.registry.validators.imobilitiesvalidator;
import java.io.IOException;
import eu.erasmuswithoutpaper.registry.internet.Request;
import eu.erasmuswithoutpaper.registry.internet.Response;
import eu.erasmuswithoutpaper.registry.validators.AbstractApiService;
import eu.erasmuswithoutpaper.registryclient.RegistryClient;
public abstract class AbstractIMobilitiesService extends AbstractApiService {
protected final String getUrl;
/**
* @param getUrl
* The endpoint at which to listen for get requests.
* @param registryClient
* Initialized and refreshed {@link RegistryClient} instance.
*/
public AbstractIMobilitiesService(String getUrl, RegistryClient registryClient) {
super(registryClient);
this.getUrl = getUrl;
}
public String getEndpoint() {
return getUrl;
}
@Override
public Response handleInternetRequest(Request request) throws IOException {
try {
if (request.getUrl().startsWith(this.getUrl)) {
return this.handleIMobilitiesGetInternetRequest(request);
}
return null;
} catch (ErrorResponseException e) {
return e.response;
}
}
/**
* @param request
* The request for which a response is to be generated
* @return {@link Response} object.
* @throws ErrorResponseException
* This can be thrown instead of returning the error response (a shortcut).
*/
protected abstract Response handleIMobilitiesGetInternetRequest(Request request)
throws ErrorResponseException;
}
| 1,540 | 0.745455 | 0.745455 | 49 | 30.428572 | 27.691448 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.306122 | false | false | 0 |
967df8ad36096bac9913b240f7e1a6a42abd4e86 | 31,009,663,893,039 | bc7beb9dce8437f9f8fc59481b2c26a04cae1afe | /src/main/java/com/ml_sma/entity/Sentiment.java | c61f6ee1caa25b855e15f513dd047512041b7f56 | []
| no_license | Hamza-Nait/Scraping-backend-java | https://github.com/Hamza-Nait/Scraping-backend-java | a824715d43401afc929ee685e30bb472c47d3f6f | fcc7f68f7b57525a5cc4fea445fc500087be46b0 | refs/heads/master | 2022-11-14T20:06:52.865000 | 2020-07-13T09:18:19 | 2020-07-13T09:18:19 | 279,254,975 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ml_sma.entity;
import lombok.ToString;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.io.Serializable;
import java.util.List;
@Document
@ToString
public class Sentiment implements Serializable {
@Id
private String id;
private Float negative;
private Float neutral;
private Float positive;
private String target;
public Sentiment(Float negative, Float neutral, Float positive, String target) {
this.negative = negative;
this.neutral = neutral;
this.positive = positive;
this.target = target;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Float getNegative() {
return negative;
}
public void setNegative(Float negative) {
this.negative = negative;
}
public Float getNeutral() {
return neutral;
}
public void setNeutral(Float neutral) {
this.neutral = neutral;
}
public Float getPositive() {
return positive;
}
public void setPositive(Float positive) {
this.positive = positive;
}
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
} | UTF-8 | Java | 1,363 | java | Sentiment.java | Java | []
| null | []
| package com.ml_sma.entity;
import lombok.ToString;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.io.Serializable;
import java.util.List;
@Document
@ToString
public class Sentiment implements Serializable {
@Id
private String id;
private Float negative;
private Float neutral;
private Float positive;
private String target;
public Sentiment(Float negative, Float neutral, Float positive, String target) {
this.negative = negative;
this.neutral = neutral;
this.positive = positive;
this.target = target;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Float getNegative() {
return negative;
}
public void setNegative(Float negative) {
this.negative = negative;
}
public Float getNeutral() {
return neutral;
}
public void setNeutral(Float neutral) {
this.neutral = neutral;
}
public Float getPositive() {
return positive;
}
public void setPositive(Float positive) {
this.positive = positive;
}
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
} | 1,363 | 0.637564 | 0.637564 | 70 | 18.485714 | 17.752861 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 0 |
f5276b227081f764419058ff907d1965e94711e0 | 1,047,972,083,123 | f99219f925534275478429cd7b02ab8d975638f2 | /src/main/java/com/order/ordermanagement/user/repository/CartRepository.java | 44c38b4f2016e1473766d2db68f62359dc4e5858 | []
| no_license | lisheela/userms | https://github.com/lisheela/userms | e5466cfed03bbad69aa448039d8ee05e4a093775 | 017cdc32b52974802a0f575f64db4f54ab727307 | refs/heads/main | 2023-08-06T04:52:21.534000 | 2021-09-12T10:26:53 | 2021-09-12T10:26:53 | 402,309,270 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.order.ordermanagement.user.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.order.ordermanagement.user.entity.Cart;
@Repository
public interface CartRepository extends JpaRepository<Cart, String>{
}
| UTF-8 | Java | 312 | java | CartRepository.java | Java | []
| null | []
| package com.order.ordermanagement.user.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.order.ordermanagement.user.entity.Cart;
@Repository
public interface CartRepository extends JpaRepository<Cart, String>{
}
| 312 | 0.814103 | 0.814103 | 11 | 26.363636 | 27.340521 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false | 0 |
67a11282ddce61539e072cd53757fcacff6f7981 | 17,085,379,930,520 | 6ce8571e57510b3bdd9fd918c1aa981c36a8b313 | /MathLibrary-master/app/src/main/java/com/uonagent/mathlibrary/LibraryClientFragment.java | 566cb7ade6a3a6edca27c19a19b3aad28f0bed44 | []
| no_license | RomaPrograms/LibraryApp | https://github.com/RomaPrograms/LibraryApp | 3afc8128b1c34b65ec8d38d2c3fb0f73d61c09ab | efddf2462fa5ef74f5c2376b25fd177d3534f547 | refs/heads/master | 2020-11-25T19:53:00.618000 | 2019-12-18T11:08:44 | 2019-12-18T11:08:44 | 228,819,507 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.uonagent.mathlibrary;
import android.content.ContentValues;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.NumberPicker;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
public class LibraryClientFragment extends Fragment {
private static final String ARG_PARAM = "_id";
private String mParam;
ReadersDB readersDB;
LibraryDB libraryDB;
ListView listView;
SimpleCursorAdapter adapter;
public Cursor cursor;
public static LibraryClientFragment newInstance(String param) {
LibraryClientFragment fragment = new LibraryClientFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM, param);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam = getArguments().getString(ARG_PARAM);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_library_client, container, false);
libraryDB = new LibraryDB(getContext());
readersDB = new ReadersDB(getContext());
SQLiteDatabase databaseL = libraryDB.getWritableDatabase();
SQLiteDatabase databaseR = readersDB.getWritableDatabase();
cursor = databaseL.query(libraryDB.TABLE_NAME, null, null,
null, null, null, null);
String[] s = {libraryDB.TITLE, libraryDB.AUTHOR, libraryDB.ISBN, libraryDB.QUANTITY};
int[] is = {R.id.title_common, R.id.author_common, R.id.isbn_common, R.id.quant_common};
adapter = new CustomAdapter(getActivity().getApplicationContext(), R.layout.card_common, cursor, s, is);
listView = (ListView) view.findViewById(R.id.recyclerClient);
listView.setAdapter(adapter);
Cursor c = ((CustomAdapter) listView.getAdapter()).getCursor();
listView.setOnItemClickListener((parent, itemClicked, position, id) -> {
c.moveToPosition(position);
Log.i("ВЫБРАНА КНИГА ", c.getString(c.getColumnIndex(libraryDB.TITLE)));
final String[] items = {"Взять", "Информация", "Отмена"};
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Выберите действие");
builder.setItems(items, (dialogInterface, i) -> {
if (i == 0) {
if (c.getInt(c.getColumnIndex(libraryDB.QUANTITY)) != 0) {
dialogInterface.dismiss();
AlertDialog.Builder builder1 = new AlertDialog.Builder(getContext());
NumberPicker picker = new NumberPicker(getActivity());
picker.setMinValue(1);
picker.setMaxValue(c.getInt(c.getColumnIndex(libraryDB.QUANTITY)));
picker.setValue(1);
picker.setWrapSelectorWheel(true);
NumberPicker.OnValueChangeListener listener = (numberPicker, i12, i1) -> {
};
picker.setOnValueChangedListener(listener);
builder1.setView(picker);
builder1.setTitle("Сколько книг хотите взять?");
builder1.setPositiveButton("Взять", ((dialogInterface1, i1) -> {
dialogInterface1.dismiss();
ContentValues cv = new ContentValues();
Cursor readersCursor = databaseR.query(readersDB.TABLE_NAME, null, readersDB.USER_ID +
" = '" + mParam + "'", null, null, null, null);
if (readersCursor.moveToFirst()) {
String taken = readersCursor.getString(readersCursor.getColumnIndex(readersDB.TAKEN_BOOKS));
if (taken != null) {
String[] arr = taken.split(",");
int i2 = 0;
String[] o = new String[0];
boolean flag = false;
for (String it : arr) {
o = it.split(":");
AlertDialog.Builder builder2 = new AlertDialog.Builder(getContext());
builder2.setTitle(c.getString(c.getColumnIndex("_id")));
builder2.create().show();
if (o[0].equals(c.getString(c.getColumnIndex("_id")))) {
flag = true;
break;
}
++i2;
}
if (flag) {
String tmp = o[0];
int quantNew = Integer.parseInt(o[1]) + picker.getValue();
tmp += ":" + quantNew;
arr[i2] = tmp;
StringBuilder stringBuilder = new StringBuilder("");
for (String it : arr) {
String putter = it + ",";
stringBuilder.append(putter);
}
cv.clear();
cv.put(readersDB.TAKEN_BOOKS, stringBuilder.toString());
databaseR.update(readersDB.TABLE_NAME, cv, "_id='" + mParam + "'", null);
} else {
cv.clear();
cv.put(readersDB.TAKEN_BOOKS, taken + c.getString(c.getColumnIndex("_id")) + ":" +
picker.getValue() + ",");
databaseR.update(readersDB.TABLE_NAME, cv, "_id='" + mParam + "'", null);
}
} else {
cv.clear();
cv.put(readersDB.TAKEN_BOOKS, c.getString(c.getColumnIndex("_id")) + ":" +
picker.getValue() + ",");
databaseR.update(readersDB.TABLE_NAME, cv, "_id='" + mParam + "'", null);
}
cv.clear();
String readers = c.getString(c.getColumnIndex(libraryDB.READERS));
if (readers != null) {
String[] readArr = readers.split(",");
String[] u = new String[0];
int i3 = 0;
boolean flag = false;
for (String it : readArr) {
u = it.split(":");
if (u[0].equals(mParam)) {
flag = true;
break;
}
++i3;
}
if (flag) {
String tmp2 = mParam;
int remNew = Integer.parseInt(u[1]) + picker.getValue();
tmp2 += ":" + remNew;
readArr[i3] = tmp2;
StringBuilder stringBuilder1 = new StringBuilder("");
for (String it : readArr) {
String putter = it + ",";
stringBuilder1.append(putter);
}
cv.put(libraryDB.READERS, stringBuilder1.toString());
databaseL.update(libraryDB.TABLE_NAME, cv, "_id='" +
c.getInt(c.getColumnIndex("_id")) + "'", null);
} else {
cv.put(libraryDB.READERS, readers + mParam + ":" + picker.getValue() + ",");
databaseL.update(libraryDB.TABLE_NAME, cv, "_id='" +
c.getInt(c.getColumnIndex("_id")) + "'", null);
}
} else {
cv.put(libraryDB.READERS, mParam + ":" + picker.getValue() + ",");
databaseL.update(libraryDB.TABLE_NAME, cv, "_id='" +
c.getInt(c.getColumnIndex("_id")) + "'", null);
}
}
cv.clear();
int newQuant = c.getInt(c.getColumnIndex(libraryDB.QUANTITY)) - picker.getValue();
cv.put(libraryDB.QUANTITY, newQuant);
databaseL.update(libraryDB.TABLE_NAME, cv, "_id='" +
c.getInt(c.getColumnIndex("_id")) + "'", null);
adapter.swapCursor(databaseL.query(libraryDB.TABLE_NAME, null, null,
null, null, null, null));
c.requery();
//Log.i("Выбрано", " " + picker.getValue());
}));
builder1.setNegativeButton("Отмена", (dialogInterface12, i13) -> {
dialogInterface12.dismiss();
});
AlertDialog np = builder1.create();
np.show();
} else {
dialogInterface.dismiss();
AlertDialog.Builder builder1 = new AlertDialog.Builder(getContext());
builder1.setTitle("Книг нет");
builder1.setNegativeButton("ОК", (dialogInterface13, i14) -> {
dialogInterface13.dismiss();
});
AlertDialog df = builder1.create();
df.show();
}
} else if (i == 1) {
dialogInterface.dismiss();
startActivity(new Intent("com.uonagent.mathlibrary.WebActivity")
.putExtra("url", c.getString(c.getColumnIndex(libraryDB.DESCRIPTION))));
} else if (i == 2) {
dialogInterface.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
});
return view;
}
public class CustomAdapter extends SimpleCursorAdapter {
private Context mContext;
private Context appContext;
private int layout;
private Cursor cr;
private final LayoutInflater inflater;
public CustomAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to, 0);
this.layout = layout;
this.mContext = context;
this.inflater = LayoutInflater.from(context);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return inflater.inflate(layout, null);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
super.bindView(view, context, cursor);
//TextView title = (TextView) view.findViewById(R.id.title_common);
//TextView author = (TextView) view.findViewById(R.id.author_common);
TextView isbn = (TextView) view.findViewById(R.id.isbn_common);
TextView quant = (TextView) view.findViewById(R.id.quant_common);
isbn.setText("ISBN: " + cursor.getString(cursor.getColumnIndex(libraryDB.ISBN)));
quant.setText("Доступно книг: " + cursor.getString(cursor.getColumnIndex(libraryDB.QUANTITY)));
ImageView cover = (ImageView) view.findViewById(R.id.cover_common);
ContextWrapper cw = new ContextWrapper(getActivity().getApplicationContext());
File directory = cw.getDir("covers", Context.MODE_PRIVATE);
File mypath = new File(directory, "book_" +
cursor.getInt(cursor.getColumnIndex("_id")) + ".png");
if (mypath.exists()) {
try {
Bitmap coverBmp;
coverBmp = MediaStore.Images.Media.getBitmap(getActivity().getApplicationContext().getContentResolver(), Uri.fromFile(mypath));
cover.setImageBitmap(coverBmp);
} catch (IOException e) {
e.printStackTrace();
}
} else {
cover.setImageResource(R.drawable.ic_book);
}
}
}
}
| UTF-8 | Java | 14,529 | java | LibraryClientFragment.java | Java | []
| null | []
| package com.uonagent.mathlibrary;
import android.content.ContentValues;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.NumberPicker;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
public class LibraryClientFragment extends Fragment {
private static final String ARG_PARAM = "_id";
private String mParam;
ReadersDB readersDB;
LibraryDB libraryDB;
ListView listView;
SimpleCursorAdapter adapter;
public Cursor cursor;
public static LibraryClientFragment newInstance(String param) {
LibraryClientFragment fragment = new LibraryClientFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM, param);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam = getArguments().getString(ARG_PARAM);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_library_client, container, false);
libraryDB = new LibraryDB(getContext());
readersDB = new ReadersDB(getContext());
SQLiteDatabase databaseL = libraryDB.getWritableDatabase();
SQLiteDatabase databaseR = readersDB.getWritableDatabase();
cursor = databaseL.query(libraryDB.TABLE_NAME, null, null,
null, null, null, null);
String[] s = {libraryDB.TITLE, libraryDB.AUTHOR, libraryDB.ISBN, libraryDB.QUANTITY};
int[] is = {R.id.title_common, R.id.author_common, R.id.isbn_common, R.id.quant_common};
adapter = new CustomAdapter(getActivity().getApplicationContext(), R.layout.card_common, cursor, s, is);
listView = (ListView) view.findViewById(R.id.recyclerClient);
listView.setAdapter(adapter);
Cursor c = ((CustomAdapter) listView.getAdapter()).getCursor();
listView.setOnItemClickListener((parent, itemClicked, position, id) -> {
c.moveToPosition(position);
Log.i("ВЫБРАНА КНИГА ", c.getString(c.getColumnIndex(libraryDB.TITLE)));
final String[] items = {"Взять", "Информация", "Отмена"};
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Выберите действие");
builder.setItems(items, (dialogInterface, i) -> {
if (i == 0) {
if (c.getInt(c.getColumnIndex(libraryDB.QUANTITY)) != 0) {
dialogInterface.dismiss();
AlertDialog.Builder builder1 = new AlertDialog.Builder(getContext());
NumberPicker picker = new NumberPicker(getActivity());
picker.setMinValue(1);
picker.setMaxValue(c.getInt(c.getColumnIndex(libraryDB.QUANTITY)));
picker.setValue(1);
picker.setWrapSelectorWheel(true);
NumberPicker.OnValueChangeListener listener = (numberPicker, i12, i1) -> {
};
picker.setOnValueChangedListener(listener);
builder1.setView(picker);
builder1.setTitle("Сколько книг хотите взять?");
builder1.setPositiveButton("Взять", ((dialogInterface1, i1) -> {
dialogInterface1.dismiss();
ContentValues cv = new ContentValues();
Cursor readersCursor = databaseR.query(readersDB.TABLE_NAME, null, readersDB.USER_ID +
" = '" + mParam + "'", null, null, null, null);
if (readersCursor.moveToFirst()) {
String taken = readersCursor.getString(readersCursor.getColumnIndex(readersDB.TAKEN_BOOKS));
if (taken != null) {
String[] arr = taken.split(",");
int i2 = 0;
String[] o = new String[0];
boolean flag = false;
for (String it : arr) {
o = it.split(":");
AlertDialog.Builder builder2 = new AlertDialog.Builder(getContext());
builder2.setTitle(c.getString(c.getColumnIndex("_id")));
builder2.create().show();
if (o[0].equals(c.getString(c.getColumnIndex("_id")))) {
flag = true;
break;
}
++i2;
}
if (flag) {
String tmp = o[0];
int quantNew = Integer.parseInt(o[1]) + picker.getValue();
tmp += ":" + quantNew;
arr[i2] = tmp;
StringBuilder stringBuilder = new StringBuilder("");
for (String it : arr) {
String putter = it + ",";
stringBuilder.append(putter);
}
cv.clear();
cv.put(readersDB.TAKEN_BOOKS, stringBuilder.toString());
databaseR.update(readersDB.TABLE_NAME, cv, "_id='" + mParam + "'", null);
} else {
cv.clear();
cv.put(readersDB.TAKEN_BOOKS, taken + c.getString(c.getColumnIndex("_id")) + ":" +
picker.getValue() + ",");
databaseR.update(readersDB.TABLE_NAME, cv, "_id='" + mParam + "'", null);
}
} else {
cv.clear();
cv.put(readersDB.TAKEN_BOOKS, c.getString(c.getColumnIndex("_id")) + ":" +
picker.getValue() + ",");
databaseR.update(readersDB.TABLE_NAME, cv, "_id='" + mParam + "'", null);
}
cv.clear();
String readers = c.getString(c.getColumnIndex(libraryDB.READERS));
if (readers != null) {
String[] readArr = readers.split(",");
String[] u = new String[0];
int i3 = 0;
boolean flag = false;
for (String it : readArr) {
u = it.split(":");
if (u[0].equals(mParam)) {
flag = true;
break;
}
++i3;
}
if (flag) {
String tmp2 = mParam;
int remNew = Integer.parseInt(u[1]) + picker.getValue();
tmp2 += ":" + remNew;
readArr[i3] = tmp2;
StringBuilder stringBuilder1 = new StringBuilder("");
for (String it : readArr) {
String putter = it + ",";
stringBuilder1.append(putter);
}
cv.put(libraryDB.READERS, stringBuilder1.toString());
databaseL.update(libraryDB.TABLE_NAME, cv, "_id='" +
c.getInt(c.getColumnIndex("_id")) + "'", null);
} else {
cv.put(libraryDB.READERS, readers + mParam + ":" + picker.getValue() + ",");
databaseL.update(libraryDB.TABLE_NAME, cv, "_id='" +
c.getInt(c.getColumnIndex("_id")) + "'", null);
}
} else {
cv.put(libraryDB.READERS, mParam + ":" + picker.getValue() + ",");
databaseL.update(libraryDB.TABLE_NAME, cv, "_id='" +
c.getInt(c.getColumnIndex("_id")) + "'", null);
}
}
cv.clear();
int newQuant = c.getInt(c.getColumnIndex(libraryDB.QUANTITY)) - picker.getValue();
cv.put(libraryDB.QUANTITY, newQuant);
databaseL.update(libraryDB.TABLE_NAME, cv, "_id='" +
c.getInt(c.getColumnIndex("_id")) + "'", null);
adapter.swapCursor(databaseL.query(libraryDB.TABLE_NAME, null, null,
null, null, null, null));
c.requery();
//Log.i("Выбрано", " " + picker.getValue());
}));
builder1.setNegativeButton("Отмена", (dialogInterface12, i13) -> {
dialogInterface12.dismiss();
});
AlertDialog np = builder1.create();
np.show();
} else {
dialogInterface.dismiss();
AlertDialog.Builder builder1 = new AlertDialog.Builder(getContext());
builder1.setTitle("Книг нет");
builder1.setNegativeButton("ОК", (dialogInterface13, i14) -> {
dialogInterface13.dismiss();
});
AlertDialog df = builder1.create();
df.show();
}
} else if (i == 1) {
dialogInterface.dismiss();
startActivity(new Intent("com.uonagent.mathlibrary.WebActivity")
.putExtra("url", c.getString(c.getColumnIndex(libraryDB.DESCRIPTION))));
} else if (i == 2) {
dialogInterface.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
});
return view;
}
public class CustomAdapter extends SimpleCursorAdapter {
private Context mContext;
private Context appContext;
private int layout;
private Cursor cr;
private final LayoutInflater inflater;
public CustomAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to, 0);
this.layout = layout;
this.mContext = context;
this.inflater = LayoutInflater.from(context);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return inflater.inflate(layout, null);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
super.bindView(view, context, cursor);
//TextView title = (TextView) view.findViewById(R.id.title_common);
//TextView author = (TextView) view.findViewById(R.id.author_common);
TextView isbn = (TextView) view.findViewById(R.id.isbn_common);
TextView quant = (TextView) view.findViewById(R.id.quant_common);
isbn.setText("ISBN: " + cursor.getString(cursor.getColumnIndex(libraryDB.ISBN)));
quant.setText("Доступно книг: " + cursor.getString(cursor.getColumnIndex(libraryDB.QUANTITY)));
ImageView cover = (ImageView) view.findViewById(R.id.cover_common);
ContextWrapper cw = new ContextWrapper(getActivity().getApplicationContext());
File directory = cw.getDir("covers", Context.MODE_PRIVATE);
File mypath = new File(directory, "book_" +
cursor.getInt(cursor.getColumnIndex("_id")) + ".png");
if (mypath.exists()) {
try {
Bitmap coverBmp;
coverBmp = MediaStore.Images.Media.getBitmap(getActivity().getApplicationContext().getContentResolver(), Uri.fromFile(mypath));
cover.setImageBitmap(coverBmp);
} catch (IOException e) {
e.printStackTrace();
}
} else {
cover.setImageResource(R.drawable.ic_book);
}
}
}
}
| 14,529 | 0.466953 | 0.462723 | 285 | 49.592983 | 30.795578 | 147 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 0 |
22bf007e307d1a18ee89b63df2e1e7c3ee61005f | 12,232,066,877,359 | 8093f7ccdce467d12c91bc38d0e9e24cf6c1e062 | /src/main/taller/opciones/OpcionTaller.java | b7329967470b1ed2dee8f0d0845b192f878a119d | []
| no_license | vicen1daw/Actividad_9_2 | https://github.com/vicen1daw/Actividad_9_2 | e71a0491f4fc03ddc6d4465c5889b552be11bd23 | 18bebae5d69c40147753a0fafa867944ecd0474c | refs/heads/master | 2023-04-05T19:23:32.923000 | 2021-04-22T01:24:45 | 2021-04-22T01:24:45 | 359,763,068 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 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 main.taller.opciones;
import main.taller.Box;
import main.taller.Taller;
import main.util.GestorIO;
import main.util.Intervalo;
/**
*
* @author jrmd
*/
public abstract class OpcionTaller extends Opcion{
protected Taller taller;
public OpcionTaller(String titulo, Taller taller) {
super(titulo);
this.taller = taller;
}
} | UTF-8 | Java | 576 | java | OpcionTaller.java | Java | [
{
"context": "import main.util.Intervalo;\r\n\r\n/**\r\n *\r\n * @author jrmd\r\n */\r\npublic abstract class OpcionTaller extends Op",
"end": 359,
"score": 0.9940500855445862,
"start": 355,
"tag": "USERNAME",
"value": "jrmd"
}
]
| null | []
| /*
* 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 main.taller.opciones;
import main.taller.Box;
import main.taller.Taller;
import main.util.GestorIO;
import main.util.Intervalo;
/**
*
* @author jrmd
*/
public abstract class OpcionTaller extends Opcion{
protected Taller taller;
public OpcionTaller(String titulo, Taller taller) {
super(titulo);
this.taller = taller;
}
} | 576 | 0.680556 | 0.680556 | 25 | 21.120001 | 21.210035 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.48 | false | false | 0 |
63370448e4b99cbbe2ec380659bd67d521370feb | 19,172,734,040,813 | 047ca8517f808b8025823ad330de68033f3c66e6 | /blog-app/src/main/java/com/kiki/blog/app/repository/PostRepository.java | 7099a5fc3ee630e2387159c09c09fa8678684c4a | []
| no_license | Kiki-ooops/blog-spring | https://github.com/Kiki-ooops/blog-spring | de9a4cd40924d6d0d97108c5f904acc979473301 | 46cfa1ef9c1b7ce365485cfc2e41c958bb696a12 | refs/heads/master | 2023-09-01T04:35:05.211000 | 2021-11-03T07:04:51 | 2021-11-03T07:04:51 | 376,622,161 | 0 | 0 | null | false | 2021-09-08T20:30:42 | 2021-06-13T19:14:46 | 2021-09-08T20:21:05 | 2021-09-08T20:30:42 | 454 | 0 | 0 | 0 | Java | false | false | package com.kiki.blog.app.repository;
import com.kiki.blog.app.entity.PostEntity;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
import java.util.UUID;
public interface PostRepository extends PagingAndSortingRepository<PostEntity, UUID> {
List<PostEntity> findAllByUserId(UUID userId);
PostEntity findPostEntityByIdAndUserId(UUID postId, UUID userId);
}
| UTF-8 | Java | 414 | java | PostRepository.java | Java | []
| null | []
| package com.kiki.blog.app.repository;
import com.kiki.blog.app.entity.PostEntity;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
import java.util.UUID;
public interface PostRepository extends PagingAndSortingRepository<PostEntity, UUID> {
List<PostEntity> findAllByUserId(UUID userId);
PostEntity findPostEntityByIdAndUserId(UUID postId, UUID userId);
}
| 414 | 0.818841 | 0.818841 | 12 | 33.333332 | 29.454296 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 0 |
a1044f23dbdfd1bb7bf70df407db55d963d9e19e | 17,557,826,335,030 | 113581805f78561b3b9bd6cf663e4bff359b95c3 | /app/src/main/java/com/testing/azarkovic/testing/Fragments/LoginFragment.java | 5aa947a0f667a6af0e2bf68903b617445a4522b9 | []
| no_license | Azkv/T1RobExt | https://github.com/Azkv/T1RobExt | d85be491e53084863b991054bebd793f6f50714a | c67e26cef36d26048cea9f7d8e1ffe61057fc719 | refs/heads/master | 2021-01-13T00:56:18.236000 | 2016-03-14T15:07:45 | 2016-03-14T15:07:45 | 53,477,739 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.testing.azarkovic.testing.Fragments;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.j256.ormlite.dao.Dao;
import com.testing.azarkovic.testing.Database.Model.User;
import com.testing.azarkovic.testing.Globals;
import com.testing.azarkovic.testing.Main;
import com.testing.azarkovic.testing.R;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
/**
* Created by azarkovic on 7.3.2016..
*/
public class LoginFragment extends Fragment implements ZXingScannerView.ResultHandler
{
private ZXingScannerView scannerView;
public LoginFragment()
{
}
public void SaveUser(String uid, String name, String surname, String arrivalDate, String language, String room)
{
Globals.user = new User(uid,name,surname,arrivalDate,language,room);
try {
Dao d = ((Main)getActivity()).getHelper().getDaoForClass(User.class);
d.create(Globals.user);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.login_fragment_layout,container,false);
scannerView = (ZXingScannerView) v.findViewById(R.id.login_scanner);
ArrayList<BarcodeFormat> formats = new ArrayList<BarcodeFormat>();
formats.add(BarcodeFormat.QR_CODE);
scannerView.setFormats(formats);
scannerView.setResultHandler(this);
return v;
}
@Override
public void onResume() {
super.onResume();
scannerView.setResultHandler(this);
scannerView.startCamera();
}
@Override
public void onPause() {
super.onPause();
scannerView.stopCamera();
}
@Override
public void onDestroyView() {
super.onDestroyView();
((Main)this.getActivity()).goToLobby();
}
@Override
public void handleResult(Result result)
{
String rez_s = result.getText();
rez_s = "123#Alen#Zarkovic#25.01.2016#Croatian#1132";
String[] data = rez_s.split("#");
SaveUser(data[0], data[1], data[2], data[3], data[4], data[5]);
getFragmentManager().beginTransaction()
.setCustomAnimations(R.anim.slide_up_and_fade_out, R.anim.slide_up_and_fade_out,R.anim.slide_down_and_fade_in, R.anim.slide_down_and_fade_in)
.remove(this)
.commit();
}
}
| UTF-8 | Java | 2,723 | java | LoginFragment.java | Java | [
{
"context": "scanner.zxing.ZXingScannerView;\n\n/**\n * Created by azarkovic on 7.3.2016..\n */\npublic class LoginFragment exte",
"end": 655,
"score": 0.999691367149353,
"start": 646,
"tag": "USERNAME",
"value": "azarkovic"
},
{
"context": "ng rez_s = result.getText();\n rez_s = \"123#Alen#Zarkovic#25.01.2016#Croatian#1132\";\n Strin",
"end": 2299,
"score": 0.7489795684814453,
"start": 2295,
"tag": "NAME",
"value": "Alen"
},
{
"context": "z_s = result.getText();\n rez_s = \"123#Alen#Zarkovic#25.01.2016#Croatian#1132\";\n String[] data ",
"end": 2308,
"score": 0.7662925720214844,
"start": 2300,
"tag": "NAME",
"value": "Zarkovic"
}
]
| null | []
| package com.testing.azarkovic.testing.Fragments;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.j256.ormlite.dao.Dao;
import com.testing.azarkovic.testing.Database.Model.User;
import com.testing.azarkovic.testing.Globals;
import com.testing.azarkovic.testing.Main;
import com.testing.azarkovic.testing.R;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
/**
* Created by azarkovic on 7.3.2016..
*/
public class LoginFragment extends Fragment implements ZXingScannerView.ResultHandler
{
private ZXingScannerView scannerView;
public LoginFragment()
{
}
public void SaveUser(String uid, String name, String surname, String arrivalDate, String language, String room)
{
Globals.user = new User(uid,name,surname,arrivalDate,language,room);
try {
Dao d = ((Main)getActivity()).getHelper().getDaoForClass(User.class);
d.create(Globals.user);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.login_fragment_layout,container,false);
scannerView = (ZXingScannerView) v.findViewById(R.id.login_scanner);
ArrayList<BarcodeFormat> formats = new ArrayList<BarcodeFormat>();
formats.add(BarcodeFormat.QR_CODE);
scannerView.setFormats(formats);
scannerView.setResultHandler(this);
return v;
}
@Override
public void onResume() {
super.onResume();
scannerView.setResultHandler(this);
scannerView.startCamera();
}
@Override
public void onPause() {
super.onPause();
scannerView.stopCamera();
}
@Override
public void onDestroyView() {
super.onDestroyView();
((Main)this.getActivity()).goToLobby();
}
@Override
public void handleResult(Result result)
{
String rez_s = result.getText();
rez_s = "123#Alen#Zarkovic#25.01.2016#Croatian#1132";
String[] data = rez_s.split("#");
SaveUser(data[0], data[1], data[2], data[3], data[4], data[5]);
getFragmentManager().beginTransaction()
.setCustomAnimations(R.anim.slide_up_and_fade_out, R.anim.slide_up_and_fade_out,R.anim.slide_down_and_fade_in, R.anim.slide_down_and_fade_in)
.remove(this)
.commit();
}
}
| 2,723 | 0.673155 | 0.66177 | 91 | 28.923077 | 28.790348 | 157 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.692308 | false | false | 0 |
609ba83da5748bd6c4ec59989a421c97353b8ae3 | 26,001,732,011,751 | 8cb3aee451fba0fce69cf85c56c9d1a9334f1609 | /IoTHeartMedicoClient/src/br/uefs/ecomp/IoTHeartMedicoClient/controller/MedicoController.java | 606ff0b6aab125fafd85855872c93df82da54210 | []
| no_license | vvalmeidas/iotHeart-Cloud | https://github.com/vvalmeidas/iotHeart-Cloud | 7668118a2a44e824ec281b2e22cbd1fab47abb79 | 3f5ef65a8f9f96128c11ed1e8ad0e7099f671597 | refs/heads/master | 2021-07-15T10:16:21.610000 | 2017-10-20T01:40:29 | 2017-10-20T01:40:29 | 104,938,034 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.uefs.ecomp.IoTHeartMedicoClient.controller;
import java.io.IOException;
import java.net.InetAddress;
import br.uefs.ecomp.IoTHeartMedicoClient.exceptions.LoginNegadoException;
import br.uefs.ecomp.IoTHeartMedicoClient.exceptions.MedicoJaExisteException;
import br.uefs.ecomp.IoTHeartMedicoClient.exceptions.PacienteNaoExisteException;
import br.uefs.ecomp.IoTHeartMedicoClient.exceptions.PainelNaoIniciadoException;
import br.uefs.ecomp.IoTHeartMedicoClient.model.PainelDeControle;
import br.uefs.ecomp.IoTHeartUtil.util.ComunicacaoImpossivelException;
/**
* Classe responsável por gerenciar as ações que um cliente médico pode realizar no sistema
* @author Valmir Vinicius
*/
public class MedicoController {
/** IP do servidor ao qual o médico se conectará */
private InetAddress ipServidor;
/** Porta do processo a qual o médico se conectará */
private int portaProcessoServidor;
/** Painel gerenciado pelo médico */
private PainelDeControle painel;
/**
* Obtém o IP do servidor ao qual o médico está conectado
* @return IP do servidor
*/
public InetAddress getIpServidor() {
return ipServidor;
}
/**
* Obtém a porta do processo ao qual o médico está conectado
* @return porta do processo ao qual o médico está conectado
*/
public int getPortaProcesso() {
return portaProcessoServidor;
}
/**
* Obtém a instância do painel de controle que um médico está utilizando
* @return instância do painel de controle que um médico está utilizando
*/
public PainelDeControle getPainel() {
return painel;
}
/**
* Obtém uma instância do controller do médico
*/
public MedicoController() {
//define as configurações inicias da classe
ipServidor = null;
portaProcessoServidor = -1;
};
/**
* Define o caminho do servidor ao qual o médico poderá conectar-se
* @param ipServidor ip do servidor
* @param portaProcessoServidor porta do processo na qual o médico pode conectar-se
*/
public void definirCaminhoServidor(InetAddress ipServidor, int portaProcessoServidor) {
this.ipServidor = ipServidor;
this.portaProcessoServidor = portaProcessoServidor;
}
/**
* Inicia o plantão de um médico, criando um painel próprio para ele
* @param crm crm do médico
* @param senhaMedico senha do médico
* @throws ComunicacaoImpossivelException caso o servidor não tenha sido iniciado
* @throws ClassNotFoundException caso alguma classe fundamental à execução não seja encontrada
* @throws IOException caso ocorra algum erro durante a entrada ou saída de dados na comunicação
* @throws LoginNegadoException caso o crm e/ou senha informados sejam incorretos
* @throws MedicoJaExisteException caso o médico que deseja logar já esteja conectado
*/
public void iniciarPlantao(String crm, String senhaMedico) throws ComunicacaoImpossivelException, ClassNotFoundException, IOException, LoginNegadoException, MedicoJaExisteException {
if(ipServidor == null || portaProcessoServidor == -1) { //caso o endereço do servidor ainda não esteja definido
throw new ComunicacaoImpossivelException();
}
if(crm == null || senhaMedico == null || crm.trim().compareTo("") == 0 || senhaMedico.trim().compareTo("") == 0) { //caso sejam inseridos dados em formatos incorretos ou faltando informações
throw new IllegalArgumentException("Um ou mais dados estão ausentes ou foram informados incorretamente");
}
if(painel != null) { //caso o médico em questão já esteja conectado
throw new MedicoJaExisteException();
}
painel = new PainelDeControle(ipServidor, portaProcessoServidor); //cria uma nova instância de painel
painel.loginMedico(crm, senhaMedico); //tenta realizar o login do médico
if(!painel.isConectado()) { //caso as informações do médico estejam incorretas e o login não seja permitido
throw new LoginNegadoException();
}
}
/**
* Finaliza o plantão do médico associado a esta instância de controller
* @throws ClassNotFoundException caso alguma classe fundamental à execução não seja encontrada
* @throws IOException caso ocorra algum erro de entrada ou saída
* @throws PainelNaoIniciadoException caso o painel ainda não tenha sido iniciado
*/
public void finalizarPlantao() throws ClassNotFoundException, IOException, PainelNaoIniciadoException {
if(painel != null && painel.getMedicoResponsavel() != null) { //caso o painel do médico ainda não tenha sido iniciado
painel.logoutMedico(); //solicita o logout do médico
if(painel.isConectado()) { //caso o logout não tenha sido bem sucedido, indicando que o médico não havia logado anteriormente
throw new PainelNaoIniciadoException();
}
painel = null; //torna o painel nulo após a finalização do plantão
} else { //caso o painel ainda não tenha sido iniciado
throw new PainelNaoIniciadoException();
}
}
/**
* Inicia o monitoramento de um paciente
* @param cpf cpf do paciente que será monitorado
* @throws IOException caso ocorra algum erro de entrada ou saída
* @throws PainelNaoIniciadoException caso o painel ainda não tenha sido iniciado
* @throws ClassNotFoundException caso alguma classe fundamental à execução não seja encontrada
* @throws PacienteNaoExisteException caso o cpf informado esteja associado a um paciente existente no sistema
*/
public void iniciarMonitoramentoDePaciente(String cpf) throws IOException, PainelNaoIniciadoException, ClassNotFoundException, PacienteNaoExisteException {
if(painel != null && painel.getMedicoResponsavel() != null) { //caso o painel tenha sido iniciado
if(!painel.definirPacienteMonitorado(cpf)) { //solicita o inicio do monitoramento ao painel e verifica se ele não foi bem sucedido
throw new PacienteNaoExisteException();
}
} else { //caso o painel não tenha sido iniciado
throw new PainelNaoIniciadoException();
}
}
}
| ISO-8859-1 | Java | 6,053 | java | MedicoController.java | Java | [
{
"context": "liente médico pode realizar no sistema\r\n * @author Valmir Vinicius\r\n */\r\npublic class MedicoController {\r\n /** IP",
"end": 701,
"score": 0.9997239112854004,
"start": 686,
"tag": "NAME",
"value": "Valmir Vinicius"
}
]
| null | []
| package br.uefs.ecomp.IoTHeartMedicoClient.controller;
import java.io.IOException;
import java.net.InetAddress;
import br.uefs.ecomp.IoTHeartMedicoClient.exceptions.LoginNegadoException;
import br.uefs.ecomp.IoTHeartMedicoClient.exceptions.MedicoJaExisteException;
import br.uefs.ecomp.IoTHeartMedicoClient.exceptions.PacienteNaoExisteException;
import br.uefs.ecomp.IoTHeartMedicoClient.exceptions.PainelNaoIniciadoException;
import br.uefs.ecomp.IoTHeartMedicoClient.model.PainelDeControle;
import br.uefs.ecomp.IoTHeartUtil.util.ComunicacaoImpossivelException;
/**
* Classe responsável por gerenciar as ações que um cliente médico pode realizar no sistema
* @author <NAME>
*/
public class MedicoController {
/** IP do servidor ao qual o médico se conectará */
private InetAddress ipServidor;
/** Porta do processo a qual o médico se conectará */
private int portaProcessoServidor;
/** Painel gerenciado pelo médico */
private PainelDeControle painel;
/**
* Obtém o IP do servidor ao qual o médico está conectado
* @return IP do servidor
*/
public InetAddress getIpServidor() {
return ipServidor;
}
/**
* Obtém a porta do processo ao qual o médico está conectado
* @return porta do processo ao qual o médico está conectado
*/
public int getPortaProcesso() {
return portaProcessoServidor;
}
/**
* Obtém a instância do painel de controle que um médico está utilizando
* @return instância do painel de controle que um médico está utilizando
*/
public PainelDeControle getPainel() {
return painel;
}
/**
* Obtém uma instância do controller do médico
*/
public MedicoController() {
//define as configurações inicias da classe
ipServidor = null;
portaProcessoServidor = -1;
};
/**
* Define o caminho do servidor ao qual o médico poderá conectar-se
* @param ipServidor ip do servidor
* @param portaProcessoServidor porta do processo na qual o médico pode conectar-se
*/
public void definirCaminhoServidor(InetAddress ipServidor, int portaProcessoServidor) {
this.ipServidor = ipServidor;
this.portaProcessoServidor = portaProcessoServidor;
}
/**
* Inicia o plantão de um médico, criando um painel próprio para ele
* @param crm crm do médico
* @param senhaMedico senha do médico
* @throws ComunicacaoImpossivelException caso o servidor não tenha sido iniciado
* @throws ClassNotFoundException caso alguma classe fundamental à execução não seja encontrada
* @throws IOException caso ocorra algum erro durante a entrada ou saída de dados na comunicação
* @throws LoginNegadoException caso o crm e/ou senha informados sejam incorretos
* @throws MedicoJaExisteException caso o médico que deseja logar já esteja conectado
*/
public void iniciarPlantao(String crm, String senhaMedico) throws ComunicacaoImpossivelException, ClassNotFoundException, IOException, LoginNegadoException, MedicoJaExisteException {
if(ipServidor == null || portaProcessoServidor == -1) { //caso o endereço do servidor ainda não esteja definido
throw new ComunicacaoImpossivelException();
}
if(crm == null || senhaMedico == null || crm.trim().compareTo("") == 0 || senhaMedico.trim().compareTo("") == 0) { //caso sejam inseridos dados em formatos incorretos ou faltando informações
throw new IllegalArgumentException("Um ou mais dados estão ausentes ou foram informados incorretamente");
}
if(painel != null) { //caso o médico em questão já esteja conectado
throw new MedicoJaExisteException();
}
painel = new PainelDeControle(ipServidor, portaProcessoServidor); //cria uma nova instância de painel
painel.loginMedico(crm, senhaMedico); //tenta realizar o login do médico
if(!painel.isConectado()) { //caso as informações do médico estejam incorretas e o login não seja permitido
throw new LoginNegadoException();
}
}
/**
* Finaliza o plantão do médico associado a esta instância de controller
* @throws ClassNotFoundException caso alguma classe fundamental à execução não seja encontrada
* @throws IOException caso ocorra algum erro de entrada ou saída
* @throws PainelNaoIniciadoException caso o painel ainda não tenha sido iniciado
*/
public void finalizarPlantao() throws ClassNotFoundException, IOException, PainelNaoIniciadoException {
if(painel != null && painel.getMedicoResponsavel() != null) { //caso o painel do médico ainda não tenha sido iniciado
painel.logoutMedico(); //solicita o logout do médico
if(painel.isConectado()) { //caso o logout não tenha sido bem sucedido, indicando que o médico não havia logado anteriormente
throw new PainelNaoIniciadoException();
}
painel = null; //torna o painel nulo após a finalização do plantão
} else { //caso o painel ainda não tenha sido iniciado
throw new PainelNaoIniciadoException();
}
}
/**
* Inicia o monitoramento de um paciente
* @param cpf cpf do paciente que será monitorado
* @throws IOException caso ocorra algum erro de entrada ou saída
* @throws PainelNaoIniciadoException caso o painel ainda não tenha sido iniciado
* @throws ClassNotFoundException caso alguma classe fundamental à execução não seja encontrada
* @throws PacienteNaoExisteException caso o cpf informado esteja associado a um paciente existente no sistema
*/
public void iniciarMonitoramentoDePaciente(String cpf) throws IOException, PainelNaoIniciadoException, ClassNotFoundException, PacienteNaoExisteException {
if(painel != null && painel.getMedicoResponsavel() != null) { //caso o painel tenha sido iniciado
if(!painel.definirPacienteMonitorado(cpf)) { //solicita o inicio do monitoramento ao painel e verifica se ele não foi bem sucedido
throw new PacienteNaoExisteException();
}
} else { //caso o painel não tenha sido iniciado
throw new PainelNaoIniciadoException();
}
}
}
| 6,044 | 0.749455 | 0.748784 | 134 | 42.5 | 41.524269 | 192 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.686567 | false | false | 0 |
90bac87aeaec30b17189bee383e8cc3197a7817c | 7,851,200,234,020 | 784a6144ec6eadab1dc50ae50f1347aa798b67b8 | /Tools/src/com/tools/Person.java | d5363c2721a767f894be68303679cd807113c442 | []
| no_license | karthiksirimulla/ProjectsAndPractice | https://github.com/karthiksirimulla/ProjectsAndPractice | b6ee1825f771a8ddbc6f6afead570395ecd1f87f | 5689cb545068f93244332e19573ffec60e83a0cc | refs/heads/master | 2020-04-14T17:42:42.153000 | 2019-01-03T15:54:01 | 2019-01-03T15:54:01 | 163,991,028 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tools;
public class Person implements Comparable<Person>
{
@Override
public int compareTo( Person o )
{
// TODO Auto-generated method stub
return 0;
}
}
| UTF-8 | Java | 213 | java | Person.java | Java | []
| null | []
| package com.tools;
public class Person implements Comparable<Person>
{
@Override
public int compareTo( Person o )
{
// TODO Auto-generated method stub
return 0;
}
}
| 213 | 0.586854 | 0.58216 | 13 | 14.384615 | 16.652737 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.153846 | false | false | 0 |
16a41ab583b5d28954d575a1987721a3590bc35e | 8,890,582,313,908 | 24d1d31f7d88b33d871680e6dfd421ed87bfd13b | /wan_android/src/main/java/com/example/wan/ui/WanAndroidMainActivity.java | 9352319a0f0e2d35c4b0d095190d8d833f84b8a6 | []
| no_license | FunnyLee/MvpPractice | https://github.com/FunnyLee/MvpPractice | d9a6e54cf43056eaa9cf598f7b16a8a4095d5eeb | 81803a61d0f8ceac4d2b3da1cbf641e56c143799 | refs/heads/master | 2021-07-14T05:46:46.279000 | 2020-05-29T06:03:31 | 2020-05-29T06:03:31 | 147,638,023 | 4 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.wan.ui;
import android.view.MenuItem;
import android.widget.Toast;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.example.base.base.BaseActivity;
import com.example.base.base.BaseFragment;
import com.example.base.router.RouterManager;
import com.example.wan.R;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
@Route(path = RouterManager.WAN_ANDROID_MAIN_ACTIVITY)
public class WanAndroidMainActivity extends BaseActivity {
private BottomNavigationView mBottomNavigationView;
private List<BaseFragment> mFragmentList = new ArrayList<>();
private Fragment mCurrentFragment = null;
@Override
protected int getLayoutId() {
return R.layout.activity_wan_android_main;
}
@Override
protected void initView() {
Toast.makeText(this, getClass().getName(), Toast.LENGTH_SHORT).show();
mBottomNavigationView = findViewById(R.id.bottom_navigation);
initFragment();
showFragment(0);
}
@Override
protected void initData() {
}
@Override
protected void initEvent() {
mBottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_home) {
showFragment(0);
} else if (id == R.id.action_project) {
showFragment(1);
} else if (id == R.id.action_system) {
showFragment(2);
} else if (id == R.id.action_me) {
}
return true;
}
});
}
private void initFragment() {
HomeFragment homeFragment = (HomeFragment) ARouter.getInstance().build(RouterManager.HOME_FRAGMENT).navigation();
ProjectFragment projectFragment = (ProjectFragment) ARouter.getInstance().build(RouterManager.PROJECT_FRAGMENT).navigation();
SystemFragment systemFragment = (SystemFragment) ARouter.getInstance().build(RouterManager.SYSTEM_FRAGMENT).navigation();
mFragmentList.add(homeFragment);
mFragmentList.add(projectFragment);
mFragmentList.add(systemFragment);
}
/**
* 替换Fragment
*
* @param fragment
*/
private void switchFragment(Fragment fragment, @IdRes int id) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(id, fragment);
transaction.commit();
}
/**
* 使用show、hide来管理fragment
*/
private void showFragment(int position) {
if (mFragmentList != null && mFragmentList.size() > 0) {
Fragment fragment = mFragmentList.get(position);
if (null != fragment && mCurrentFragment != fragment) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
if (mCurrentFragment != null) {
transaction.hide(mCurrentFragment);
}
mCurrentFragment = fragment;
if (!fragment.isAdded()) {
transaction.add(R.id.frame_layout, fragment);
} else {
transaction.show(fragment);
}
transaction.commit();
}
}
}
}
| UTF-8 | Java | 3,862 | java | WanAndroidMainActivity.java | Java | []
| null | []
| package com.example.wan.ui;
import android.view.MenuItem;
import android.widget.Toast;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.example.base.base.BaseActivity;
import com.example.base.base.BaseFragment;
import com.example.base.router.RouterManager;
import com.example.wan.R;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
@Route(path = RouterManager.WAN_ANDROID_MAIN_ACTIVITY)
public class WanAndroidMainActivity extends BaseActivity {
private BottomNavigationView mBottomNavigationView;
private List<BaseFragment> mFragmentList = new ArrayList<>();
private Fragment mCurrentFragment = null;
@Override
protected int getLayoutId() {
return R.layout.activity_wan_android_main;
}
@Override
protected void initView() {
Toast.makeText(this, getClass().getName(), Toast.LENGTH_SHORT).show();
mBottomNavigationView = findViewById(R.id.bottom_navigation);
initFragment();
showFragment(0);
}
@Override
protected void initData() {
}
@Override
protected void initEvent() {
mBottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_home) {
showFragment(0);
} else if (id == R.id.action_project) {
showFragment(1);
} else if (id == R.id.action_system) {
showFragment(2);
} else if (id == R.id.action_me) {
}
return true;
}
});
}
private void initFragment() {
HomeFragment homeFragment = (HomeFragment) ARouter.getInstance().build(RouterManager.HOME_FRAGMENT).navigation();
ProjectFragment projectFragment = (ProjectFragment) ARouter.getInstance().build(RouterManager.PROJECT_FRAGMENT).navigation();
SystemFragment systemFragment = (SystemFragment) ARouter.getInstance().build(RouterManager.SYSTEM_FRAGMENT).navigation();
mFragmentList.add(homeFragment);
mFragmentList.add(projectFragment);
mFragmentList.add(systemFragment);
}
/**
* 替换Fragment
*
* @param fragment
*/
private void switchFragment(Fragment fragment, @IdRes int id) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(id, fragment);
transaction.commit();
}
/**
* 使用show、hide来管理fragment
*/
private void showFragment(int position) {
if (mFragmentList != null && mFragmentList.size() > 0) {
Fragment fragment = mFragmentList.get(position);
if (null != fragment && mCurrentFragment != fragment) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
if (mCurrentFragment != null) {
transaction.hide(mCurrentFragment);
}
mCurrentFragment = fragment;
if (!fragment.isAdded()) {
transaction.add(R.id.frame_layout, fragment);
} else {
transaction.show(fragment);
}
transaction.commit();
}
}
}
}
| 3,862 | 0.645086 | 0.643786 | 113 | 33.035397 | 29.418533 | 133 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.469027 | false | false | 0 |
37e8c627f68c743c2da51128d0fbbe9260149fb4 | 8,890,582,314,508 | 6aaef343eee19858a03ebec46b5d3abc95d1b4f5 | /src/com/jnfan/Test.java | f21c19066919b87f299bef3200591f76448c7ea5 | []
| no_license | JustFromNow/test1 | https://github.com/JustFromNow/test1 | 81fbfdc99a5e0fdc01a0d215addf02831698b627 | becbdf96691239348ee8a6b443243c76262c674d | refs/heads/master | 2020-03-19T20:19:18.347000 | 2018-06-11T09:00:44 | 2018-06-11T09:00:44 | 136,896,372 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jnfan;
public class Test {
public static void main(String[] args) {
System.out.println("this is gitdemo!");
System.out.println("this is second commit test !");
System.out.println("这是第三次提交,上一次只commit但没有push");
}
}
| GB18030 | Java | 283 | java | Test.java | Java | []
| null | []
| package com.jnfan;
public class Test {
public static void main(String[] args) {
System.out.println("this is gitdemo!");
System.out.println("this is second commit test !");
System.out.println("这是第三次提交,上一次只commit但没有push");
}
}
| 283 | 0.660079 | 0.660079 | 12 | 19.083334 | 20.410204 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.333333 | false | false | 0 |
b8b9320ec89f4a505ef4f51b84c96841c2db2915 | 16,217,796,527,912 | d9dc411d4eed63b78663df97ddb25147f71b83be | /br31-server/src/main/java/okbem/br31/server/util/apphealth/AppHealth.java | 608522b1f36ef321a0c573df862d741a5ef73041 | []
| no_license | okbem/br31 | https://github.com/okbem/br31 | 4da10eb6d3b08b349f539fd757e43d05222505d1 | 1bfbfa18444970bf3a767706fe65f1cc2766fdc0 | refs/heads/master | 2020-04-13T19:16:55.628000 | 2019-02-01T16:36:58 | 2019-02-01T16:36:58 | 163,397,803 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package okbem.br31.server.util.apphealth;
import java.time.LocalDateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.health.Health;
import org.springframework.stereotype.Component;
@Component
public class AppHealth {
private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(java.lang.invoke.MethodHandles.lookup().lookupClass());
@lombok.Getter
private Health health;
public AppHealth(
@Value("${management.apphealth.init-status}")
String status
) {
this.change(status);
}
public void change(String status) {
status = status.trim().toUpperCase();
Health.Builder builder;
switch (status) {
case "DOWN":
builder = Health.down();
break;
case "OUT_OF_SERVICE":
builder = Health.outOfService();
break;
case "UP":
builder = Health.up();
break;
default:
throw new IllegalArgumentException(
"Invalid status code: " +
status + ". " +
"The following status codes are currently available: " +
"DOWN, OUT_OF_SERVICE, UP"
);
}
this.health = builder
.withDetail("date", LocalDateTime.now().toString())
.build();
logger.info("AppHealth changed to {}", status);
}
}
| UTF-8 | Java | 1,471 | java | AppHealth.java | Java | []
| null | []
|
package okbem.br31.server.util.apphealth;
import java.time.LocalDateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.health.Health;
import org.springframework.stereotype.Component;
@Component
public class AppHealth {
private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(java.lang.invoke.MethodHandles.lookup().lookupClass());
@lombok.Getter
private Health health;
public AppHealth(
@Value("${management.apphealth.init-status}")
String status
) {
this.change(status);
}
public void change(String status) {
status = status.trim().toUpperCase();
Health.Builder builder;
switch (status) {
case "DOWN":
builder = Health.down();
break;
case "OUT_OF_SERVICE":
builder = Health.outOfService();
break;
case "UP":
builder = Health.up();
break;
default:
throw new IllegalArgumentException(
"Invalid status code: " +
status + ". " +
"The following status codes are currently available: " +
"DOWN, OUT_OF_SERVICE, UP"
);
}
this.health = builder
.withDetail("date", LocalDateTime.now().toString())
.build();
logger.info("AppHealth changed to {}", status);
}
}
| 1,471 | 0.583956 | 0.581237 | 62 | 22.693548 | 24.714884 | 140 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.370968 | false | false | 0 |
79d2d06bb22722f46d3307b294be05af23678eaf | 16,217,796,526,756 | ba9db08b560a01224c76e1284d8d99e834a298cf | /src/main/java/nl/martenm/servertutorialplus/commands/sub/npc/NpcAddCommand.java | a39617ac017f2e527adf168d4a53dccfc1aff1d9 | []
| no_license | MartenM/ServerTutorialPlus | https://github.com/MartenM/ServerTutorialPlus | 931a1aa59d2b84adc6af1a66293f75e02a48d2b0 | 2c8dec7eb38252c2e103d9040f7bb6ed0e07b11c | refs/heads/master | 2023-07-24T12:50:36.389000 | 2022-09-08T08:35:25 | 2022-09-08T08:35:25 | 128,547,877 | 14 | 17 | null | false | 2023-07-16T18:20:51 | 2018-04-07T16:38:34 | 2023-04-20T16:33:27 | 2023-07-16T18:20:51 | 171 | 13 | 12 | 40 | Java | false | false | package nl.martenm.servertutorialplus.commands.sub.npc;
import net.md_5.bungee.api.ChatColor;
import nl.martenm.servertutorialplus.ServerTutorialPlus;
import nl.martenm.servertutorialplus.helpers.PluginUtils;
import nl.martenm.servertutorialplus.language.Lang;
import nl.martenm.servertutorialplus.managers.NPCManager;
import nl.martenm.servertutorialplus.objects.NPCInfo;
import nl.martenm.simplecommands.SimpleCommand;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
public class NpcAddCommand extends SimpleCommand {
public NpcAddCommand() {
super("add", "Used to create a NPC", null, true);
}
@Override
public boolean onCommand(CommandSender sender, Command command, String s, String[] args) {
NPCManager npcManager = ServerTutorialPlus.getInstance().getNpcManager();
if(Bukkit.getVersion().contains("1.8") || Bukkit.getVersion().contains("1.9")){
for(int i = 0; i < 3; i++) sender.sendMessage(" ");
String warningPrefix = ChatColor.translateAlternateColorCodes('&', "&8[&4&l!&r&8]&r ");
sender.sendMessage(warningPrefix + ChatColor.GREEN + "Hey there!" + ChatColor.RESET + " We noticed that you are trying to use ST NPCs on a version lower then 1.10 :(");
sender.sendMessage(warningPrefix + ChatColor.translateAlternateColorCodes('&', "Minecraft has progressed a &6&lLOT&r since this the update this server is running on. New methods have been implemented to create cool features!"));
sender.sendMessage(warningPrefix + ChatColor.translateAlternateColorCodes('&', "&cSadly&r, this also means that some things might not work on lower versions. ST NPCs do not work on versions lower then 1.10..."));
sender.sendMessage(warningPrefix + ChatColor.translateAlternateColorCodes('&', "It would require &ca lot of time&r to keep updating for backwards compatibility and it would remove the ability to create &anew&r features that use new methods."));
sender.sendMessage(" ");
sender.sendMessage(warningPrefix + ChatColor.translateAlternateColorCodes('&',ChatColor.YELLOW + "To create an NPC you could use another plugin to spawn the NPC and use the command &r/st npc bind <npc id> <server tutorial>&e to bind it to a tutorial."));
return true;
}
if(args.length < 3){
sender.sendMessage(Lang.WRONG_COMMAND_FORMAT + "/st npc add <NPC id> <ServerTutorial> <livingEntity>");
return true;
}
Player player = (Player) sender;
if(npcManager.getNPC(args[0]) != null){
sender.sendMessage(Lang.NPC_ID_EXIST.toString());
return true;
}
EntityType et;
try{
et = EntityType.valueOf(args[2]);
} catch (Exception e){
sender.sendMessage(Lang.NPC_TESTED_MOBS + PluginUtils.allMobs());
sender.sendMessage(Lang.NPC_WRONG_TYPE.toString().replace("%type%", args[2]));
return true;
}
NPCInfo info = npcManager.createNPC(et, player.getLocation(), args[0], args[1]);
sender.sendMessage(Lang.NPC_CREATION_SUCCESS.toString().replace("%id%", info.getId()).replace("%tutorial%", info.getServerTutorialID()));
return true;
}
}
| UTF-8 | Java | 3,381 | java | NpcAddCommand.java | Java | []
| null | []
| package nl.martenm.servertutorialplus.commands.sub.npc;
import net.md_5.bungee.api.ChatColor;
import nl.martenm.servertutorialplus.ServerTutorialPlus;
import nl.martenm.servertutorialplus.helpers.PluginUtils;
import nl.martenm.servertutorialplus.language.Lang;
import nl.martenm.servertutorialplus.managers.NPCManager;
import nl.martenm.servertutorialplus.objects.NPCInfo;
import nl.martenm.simplecommands.SimpleCommand;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
public class NpcAddCommand extends SimpleCommand {
public NpcAddCommand() {
super("add", "Used to create a NPC", null, true);
}
@Override
public boolean onCommand(CommandSender sender, Command command, String s, String[] args) {
NPCManager npcManager = ServerTutorialPlus.getInstance().getNpcManager();
if(Bukkit.getVersion().contains("1.8") || Bukkit.getVersion().contains("1.9")){
for(int i = 0; i < 3; i++) sender.sendMessage(" ");
String warningPrefix = ChatColor.translateAlternateColorCodes('&', "&8[&4&l!&r&8]&r ");
sender.sendMessage(warningPrefix + ChatColor.GREEN + "Hey there!" + ChatColor.RESET + " We noticed that you are trying to use ST NPCs on a version lower then 1.10 :(");
sender.sendMessage(warningPrefix + ChatColor.translateAlternateColorCodes('&', "Minecraft has progressed a &6&lLOT&r since this the update this server is running on. New methods have been implemented to create cool features!"));
sender.sendMessage(warningPrefix + ChatColor.translateAlternateColorCodes('&', "&cSadly&r, this also means that some things might not work on lower versions. ST NPCs do not work on versions lower then 1.10..."));
sender.sendMessage(warningPrefix + ChatColor.translateAlternateColorCodes('&', "It would require &ca lot of time&r to keep updating for backwards compatibility and it would remove the ability to create &anew&r features that use new methods."));
sender.sendMessage(" ");
sender.sendMessage(warningPrefix + ChatColor.translateAlternateColorCodes('&',ChatColor.YELLOW + "To create an NPC you could use another plugin to spawn the NPC and use the command &r/st npc bind <npc id> <server tutorial>&e to bind it to a tutorial."));
return true;
}
if(args.length < 3){
sender.sendMessage(Lang.WRONG_COMMAND_FORMAT + "/st npc add <NPC id> <ServerTutorial> <livingEntity>");
return true;
}
Player player = (Player) sender;
if(npcManager.getNPC(args[0]) != null){
sender.sendMessage(Lang.NPC_ID_EXIST.toString());
return true;
}
EntityType et;
try{
et = EntityType.valueOf(args[2]);
} catch (Exception e){
sender.sendMessage(Lang.NPC_TESTED_MOBS + PluginUtils.allMobs());
sender.sendMessage(Lang.NPC_WRONG_TYPE.toString().replace("%type%", args[2]));
return true;
}
NPCInfo info = npcManager.createNPC(et, player.getLocation(), args[0], args[1]);
sender.sendMessage(Lang.NPC_CREATION_SUCCESS.toString().replace("%id%", info.getId()).replace("%tutorial%", info.getServerTutorialID()));
return true;
}
}
| 3,381 | 0.688554 | 0.681751 | 64 | 51.828125 | 62.199917 | 266 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.921875 | false | false | 0 |
24ee34f64d03a5e672be44909f691fdde7f84bc3 | 3,951,369,919,140 | 6d21f6847ee8163bd2017606b6f128ad08b5e2aa | /src/main/java/com/softeq/repository/entity/ParsingRequest.java | 0b210220beae2ba3e27f2770bd8a24c3cbb58b3c | []
| no_license | frikki84/WebCrawlerJAcoco | https://github.com/frikki84/WebCrawlerJAcoco | 01b3e65be1ae8d148333cdf9f9dda279a9b8a291 | 2d84a1eb8fda9845bb16f4cd6416bc95fb26b2c8 | refs/heads/master | 2023-05-28T05:17:08.391000 | 2021-06-02T19:32:52 | 2021-06-02T19:32:52 | 373,183,757 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.softeq.repository.entity;
import java.time.LocalDateTime;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* Entity to registrate every attempt to use this application
*/
@Data
@Entity
@Table(name = "parsing_entity")
@AllArgsConstructor
@NoArgsConstructor
public class ParsingRequest {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "create_time")
private LocalDateTime creationTime;
@Column(name = "search_url")
private String searchUrl;
@OneToMany(mappedBy = "request", fetch = FetchType.EAGER, cascade = CascadeType.REMOVE, orphanRemoval = true)
private List<SearchWord> searchWords;
}
| UTF-8 | Java | 1,072 | java | ParsingRequest.java | Java | []
| null | []
| package com.softeq.repository.entity;
import java.time.LocalDateTime;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* Entity to registrate every attempt to use this application
*/
@Data
@Entity
@Table(name = "parsing_entity")
@AllArgsConstructor
@NoArgsConstructor
public class ParsingRequest {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "create_time")
private LocalDateTime creationTime;
@Column(name = "search_url")
private String searchUrl;
@OneToMany(mappedBy = "request", fetch = FetchType.EAGER, cascade = CascadeType.REMOVE, orphanRemoval = true)
private List<SearchWord> searchWords;
}
| 1,072 | 0.779851 | 0.779851 | 41 | 25.121952 | 21.484192 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.536585 | false | false | 0 |
3e559a9caeeb4a3af16279f725e4c5294286b8e2 | 16,338,055,637,997 | 8a9cb15e3b48cc0773df471756dc7ef1dbb3c721 | /src/main/java/com/ataccama/dbViewer/DbViewerApplication.java | 5187708c4aaab50e934917c6707a298d45867efe | []
| no_license | LukasDurcak/Ataccama-Task | https://github.com/LukasDurcak/Ataccama-Task | 31cdaff26e780425f026d9f724a1b5e43e666fd7 | 34c22fa36726086875ee4dc18d4c09ea12f1df97 | refs/heads/master | 2023-04-30T02:40:17.805000 | 2021-05-19T09:47:51 | 2021-05-19T09:47:51 | 368,817,138 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ataccama.dbViewer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan({
"com.ataccama.rest",
"com.ataccama.db.dao",
"com.ataccama.services",
"com.ataccama.connectionsManagers"})
@EntityScan(basePackages = {"com.ataccama.db.entity"})
public class DbViewerApplication {
public static void main(String[] args) {
SpringApplication.run(DbViewerApplication.class, args);
}
}
| UTF-8 | Java | 628 | java | DbViewerApplication.java | Java | []
| null | []
| package com.ataccama.dbViewer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan({
"com.ataccama.rest",
"com.ataccama.db.dao",
"com.ataccama.services",
"com.ataccama.connectionsManagers"})
@EntityScan(basePackages = {"com.ataccama.db.entity"})
public class DbViewerApplication {
public static void main(String[] args) {
SpringApplication.run(DbViewerApplication.class, args);
}
}
| 628 | 0.807325 | 0.807325 | 21 | 28.904762 | 22.861706 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.857143 | false | false | 0 |
e509e66897a19154ad7df8dc109ccebaba13aa71 | 21,199,958,634,143 | 05948ca1cd3c0d2bcd65056d691c4d1b2e795318 | /classes/com/xiaoenai/app/b/a.java | bfb6c4dab584c47aebcfb5f122f18bae4d643ebe | []
| no_license | waterwitness/xiaoenai | https://github.com/waterwitness/xiaoenai | 356a1163f422c882cabe57c0cd3427e0600ff136 | d24c4d457d6ea9281a8a789bc3a29905b06002c6 | refs/heads/master | 2021-01-10T22:14:17.059000 | 2016-10-08T08:39:11 | 2016-10-08T08:39:11 | 70,317,042 | 0 | 8 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.xiaoenai.app.b;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Parcelable;
import com.xiaoenai.app.utils.d.i;
import java.io.File;
public class a
{
private static final String a = i.a + File.separator + ".image";
private final Activity b;
private String c;
private a d;
public a(Activity paramActivity)
{
this.b = paramActivity;
}
public void a(int paramInt1, int paramInt2)
{
if (paramInt2 == -1) {
switch (paramInt1)
{
}
}
File localFile;
do
{
return;
localFile = new File(a + File.separator + this.c);
com.xiaoenai.app.utils.f.a.c("getAbsolutePath:" + localFile.getAbsolutePath(), new Object[0]);
} while (this.d == null);
this.d.a(localFile);
}
public void a(a parama)
{
this.d = parama;
this.c = (System.currentTimeMillis() + ".jpg");
if (Environment.getExternalStorageState().equals("mounted"))
{
Object localObject = new File(a);
if (!((File)localObject).exists()) {
((File)localObject).mkdirs();
}
parama = new Intent("android.media.action.IMAGE_CAPTURE");
localObject = Uri.fromFile(new File((File)localObject, this.c));
parama.putExtra("orientation", 0);
parama.putExtra("output", (Parcelable)localObject);
this.b.startActivityForResult(parama, 32);
return;
}
com.xiaoenai.app.utils.f.a.a("take photo error!", new Object[0]);
}
public static abstract interface a
{
public abstract void a(File paramFile);
}
}
/* Location: E:\apk\xiaoenai2\classes-dex2jar.jar!\com\xiaoenai\app\b\a.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | UTF-8 | Java | 1,784 | java | a.java | Java | []
| null | []
| package com.xiaoenai.app.b;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Parcelable;
import com.xiaoenai.app.utils.d.i;
import java.io.File;
public class a
{
private static final String a = i.a + File.separator + ".image";
private final Activity b;
private String c;
private a d;
public a(Activity paramActivity)
{
this.b = paramActivity;
}
public void a(int paramInt1, int paramInt2)
{
if (paramInt2 == -1) {
switch (paramInt1)
{
}
}
File localFile;
do
{
return;
localFile = new File(a + File.separator + this.c);
com.xiaoenai.app.utils.f.a.c("getAbsolutePath:" + localFile.getAbsolutePath(), new Object[0]);
} while (this.d == null);
this.d.a(localFile);
}
public void a(a parama)
{
this.d = parama;
this.c = (System.currentTimeMillis() + ".jpg");
if (Environment.getExternalStorageState().equals("mounted"))
{
Object localObject = new File(a);
if (!((File)localObject).exists()) {
((File)localObject).mkdirs();
}
parama = new Intent("android.media.action.IMAGE_CAPTURE");
localObject = Uri.fromFile(new File((File)localObject, this.c));
parama.putExtra("orientation", 0);
parama.putExtra("output", (Parcelable)localObject);
this.b.startActivityForResult(parama, 32);
return;
}
com.xiaoenai.app.utils.f.a.a("take photo error!", new Object[0]);
}
public static abstract interface a
{
public abstract void a(File paramFile);
}
}
/* Location: E:\apk\xiaoenai2\classes-dex2jar.jar!\com\xiaoenai\app\b\a.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | 1,784 | 0.636771 | 0.626121 | 70 | 24.5 | 23.146582 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.542857 | false | false | 0 |
cb017ff10c17875f9e63ba59e570ce8c00b239ce | 21,199,958,633,647 | e30435a5c47117fae5b866fbedc27c2927467ecc | /demolibrary/src/main/java/walke/demolibrary/pinpu/PriorityQueueTest.java | fe1e4537c0bb14e9a93fe6d4b5cbd50a58ee352d | []
| no_license | walkeZ/WalkeBase | https://github.com/walkeZ/WalkeBase | 5f7217ad265d728fe059a6833fed4cc021a98458 | 983e5de108b8472bba8b263062d455ae7a4dfdb9 | refs/heads/master | 2023-08-16T15:32:49.796000 | 2023-08-09T02:57:31 | 2023-08-09T03:08:29 | 124,983,227 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package walke.demolibrary.pinpu;
import androidx.annotation.Nullable;
import java.util.Comparator;
import java.util.PriorityQueue;
import walke.demolibrary.pinpu.queue.PrintTask;
import walke.demolibrary.pinpu.queue.Priority;
import walke.demolibrary.pinpu.queue.TaskQueue;
public class PriorityQueueTest {
public static void main(String[] args) {
test1();
}
public static void test1() {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
PriorityQueue<Student> queue = new PriorityQueue<>(new Comparator<Student>() {
@Override
public int compare(Student st1, Student st2) {
return st1.getId() - st2.getId();
}
});
queue.add(new Student(2, "王昭君", 18));
queue.add(new Student(1, "吕布", 19));
queue.add(new Student(4, "貂蝉", 16));
queue.add(new Student(3, "赵云", 17));
System.out.println("PriorityQueueTest poll(原4), " + queue.poll() + ", " + queue.size());
System.out.println("PriorityQueueTest peek, " + queue.peek() + ", " + queue.size());
queue.add(new Student(0, "吕布0", 20));
System.out.println("PriorityQueueTest remove, " + queue.remove() + ", " + queue.size());
System.out.println("PriorityQueueTest peek, " + queue.peek() + ", " + queue.size());
//I PriorityQueueTest test12 poll(原4), Student{id=1, name='吕布', age=19}, 3
//I PriorityQueueTest test12 peek, Student{id=2, name='王昭君', age=18}, 3
//I PriorityQueueTest test12 remove, Student{id=0, name='吕布0', age=20}, 3
//I PriorityQueueTest test12 peek, Student{id=2, name='王昭君', age=18}, 3
}
}
public static void test12() {
PriorityQueue<Student> queue = new PriorityQueue<>(32, new Comparator<Student>() {
@Override
public int compare(Student st1, Student st2) {
return st1.getId() - st2.getId();
}
});
queue.add(new Student(2, "王昭君", 18));
queue.add(new Student(1, "吕布", 19));
queue.add(new Student(4, "貂蝉", 16));
Student zy = new Student(3, "赵云", 17);
queue.add(zy);
Student zs = new Student(2, "张三", 33);
boolean contains = queue.contains(zs);
System.out.println("PriorityQueueTest test12 contains, " + contains + ", " + queue.contains(new Student(20, "张三", 33)));
// if (contains) queue.remove(zs); // 移除
System.out.println("PriorityQueueTest test12 contains, " + queue.contains(zy));
zy.setId(30);
System.out.println("PriorityQueueTest test12 contains, " + queue.contains(zy));
// I PriorityQueueTest test12 contains, true, false
// I PriorityQueueTest test12 contains, true
// I PriorityQueueTest test12 contains, true
System.out.println("PriorityQueueTest test12 poll(原4), " + queue.poll() + ", " + queue.size());
System.out.println("PriorityQueueTest test12 peek, " + queue.peek() + ", " + queue.size());
queue.add(new Student(0, "吕布0", 20));
System.out.println("PriorityQueueTest test12 remove, " + queue.remove() + ", " + queue.size());
System.out.println("PriorityQueueTest test12 peek, " + queue.peek() + ", " + queue.size());
// I PriorityQueueTest poll(原4), Student{id=1, name='吕布', age=19}, 3
// I PriorityQueueTest peek, Student{id=2, name='王昭君', age=18}, 3
// I PriorityQueueTest remove, Student{id=0, name='吕布0', age=20}, 3
// I PriorityQueueTest peek, Student{id=2, name='王昭君', age=18}, 3
while (queue.peek() != null) {
System.out.println("PriorityQueueTest test12 ----> while poll, " + queue.poll());
}
// 有 if (contains) queue.remove(zs); // 移除
//I PriorityQueueTest test12 contains, true, false
//I PriorityQueueTest test12 contains, true
//I PriorityQueueTest test12 contains, true
//I PriorityQueueTest test12 poll(原4), Student{id=1, name='吕布', age=19}, 2
//I PriorityQueueTest test12 peek, Student{id=4, name='貂蝉', age=16}, 2
//I PriorityQueueTest test12 remove, Student{id=0, name='吕布0', age=20}, 2
//I PriorityQueueTest test12 peek, Student{id=4, name='貂蝉', age=16}, 2
//I PriorityQueueTest test12 ----> while poll, Student{id=4, name='貂蝉', age=16}
//I PriorityQueueTest test12 ----> while poll, Student{id=30, name='赵云', age=17}
// // 注释: if (contains) queue.remove(zs); // 移除
//I PriorityQueueTest poll(原4), Student{id=1, name='吕布', age=19}, 3
//I PriorityQueueTest peek, Student{id=2, name='王昭君', age=18}, 3
//I PriorityQueueTest remove, Student{id=0, name='吕布0', age=20}, 3
//I PriorityQueueTest peek, Student{id=2, name='王昭君', age=18}, 3
//I PriorityQueueTest test12 contains, true, false
//I PriorityQueueTest test12 contains, true
//I PriorityQueueTest test12 contains, true
//I PriorityQueueTest test12 poll(原4), Student{id=1, name='吕布', age=19}, 3
//I PriorityQueueTest test12 peek, Student{id=2, name='王昭君', age=18}, 3
//I PriorityQueueTest test12 remove, Student{id=0, name='吕布0', age=20}, 3
//I PriorityQueueTest test12 peek, Student{id=2, name='王昭君', age=18}, 3
//I PriorityQueueTest test12 ----> while poll, Student{id=2, name='王昭君', age=18}
//I PriorityQueueTest test12 ----> while poll, Student{id=4, name='貂蝉', age=16}
//I PriorityQueueTest test12 ----> while poll, Student{id=30, name='赵云', age=17}
}
public static void test2() {
// 开一个窗口,这样会让优先级更加明显。
TaskQueue taskQueue = new TaskQueue(1);
taskQueue.start(); // // 某机构开始工作。
// 为了显示出优先级效果,我们预添加3个在前面堵着,让后面的优先级效果更明显。
taskQueue.add(new PrintTask(111));
taskQueue.add(new PrintTask(112));
taskQueue.add(new PrintTask(122));
for (int i = 0; i < 10; i++) { // 从第0个人开始。
PrintTask task = new PrintTask(i);
if (1 == i) {
task.setPriority(Priority.LOW); // 让第2个进入的人最后办事。
} else if (8 == i) {
task.setPriority(Priority.HIGH); // 让第9个进入的人第二个办事。
} else if (9 == i) {
task.setPriority(Priority.Immediately); // 让第10(i=9)个进入的人第一个办事。
}
// ... 其它进入的人,按照进入顺序办事。
taskQueue.add(task);
}
// I PrintTask TaskQueue start
// I PrintTask TaskQueue start
// I PrintTask sequence 9
// I PrintTask sequence 8
// I PrintTask sequence 2
// I PrintTask sequence 7
// I PrintTask sequence 112
// I PrintTask sequence 5
// I PrintTask sequence 0
// I PrintTask sequence 3
// I PrintTask sequence 111
// I PrintTask sequence 6
// I PrintTask sequence 4
// I PrintTask sequence 122
// I PrintTask sequence 1
taskQueue.start();
}
public static class Student {
private int id;
private String name;
private int age;
public Student(int i, String name, int age) {
this.id = i;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public boolean equals(@Nullable Object obj) {
// return super.equals(obj);
if (this == obj) { //判断一下如果是同一个对象直接返回true,提高效率
return true;
}
if (obj == null || obj.getClass() != this.getClass()) { //如果传进来的对象为null或者二者为不同类,直接返回false
return false;
}
//也可以以下方法:
// if (obj == null || !(obj instanceof Rectangle)) { //如果传进来的对象为null或者二者为不同类,直接返回false
// return false;
// }
Student rectangle = (Student) obj; //向下转型
//比较长宽是否相等,注意:浮点数的比较不能简单地用==,会有精度的误差,用Math.abs或者Double.compare
return this.id == rectangle.getId();
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
}
| UTF-8 | Java | 9,396 | java | PriorityQueueTest.java | Java | [
{
"context": " });\n\n queue.add(new Student(2, \"王昭君\", 18));\n queue.add(new Student(1, \"吕布\"",
"end": 808,
"score": 0.9998435974121094,
"start": 805,
"tag": "NAME",
"value": "王昭君"
},
{
"context": "王昭君\", 18));\n queue.add(new Student(1, \"吕布\", 19));\n queue.add(new Student(4, \"貂蝉\"",
"end": 857,
"score": 0.9998040199279785,
"start": 855,
"tag": "NAME",
"value": "吕布"
},
{
"context": "\"吕布\", 19));\n queue.add(new Student(4, \"貂蝉\", 16));\n queue.add(new Student(3, \"赵云\"",
"end": 906,
"score": 0.9998642206192017,
"start": 904,
"tag": "NAME",
"value": "貂蝉"
},
{
"context": "\"貂蝉\", 16));\n queue.add(new Student(3, \"赵云\", 17));\n\n System.out.println(\"Priority",
"end": 955,
"score": 0.9997174143791199,
"start": 953,
"tag": "NAME",
"value": "赵云"
},
{
"context": "ue.size());\n queue.add(new Student(0, \"吕布0\", 20));\n System.out.println(\"PriorityQ",
"end": 1204,
"score": 0.9997851848602295,
"start": 1201,
"tag": "NAME",
"value": "吕布0"
},
{
"context": "ityQueueTest test12 poll(原4), Student{id=1, name='吕布', age=19}, 3\n //I PriorityQueueTest t",
"end": 1485,
"score": 0.9998137354850769,
"start": 1483,
"tag": "NAME",
"value": "吕布"
},
{
"context": "riorityQueueTest test12 peek, Student{id=2, name='王昭君', age=18}, 3\n //I PriorityQueueTest t",
"end": 1570,
"score": 0.9998348355293274,
"start": 1567,
"tag": "NAME",
"value": "王昭君"
},
{
"context": "orityQueueTest test12 remove, Student{id=0, name='吕布0', age=20}, 3\n //I PriorityQueueTest t",
"end": 1657,
"score": 0.9998207688331604,
"start": 1654,
"tag": "NAME",
"value": "吕布0"
},
{
"context": "riorityQueueTest test12 peek, Student{id=2, name='王昭君', age=18}, 3\n }\n }\n\n public static v",
"end": 1742,
"score": 0.9998061060905457,
"start": 1739,
"tag": "NAME",
"value": "王昭君"
},
{
"context": " }\n });\n\n queue.add(new Student(2, \"王昭君\", 18));\n queue.add(new Student(1, \"吕布\", 19",
"end": 2093,
"score": 0.9998159408569336,
"start": 2090,
"tag": "NAME",
"value": "王昭君"
},
{
"context": "2, \"王昭君\", 18));\n queue.add(new Student(1, \"吕布\", 19));\n queue.add(new Student(4, \"貂蝉\", 16",
"end": 2138,
"score": 0.9997875690460205,
"start": 2136,
"tag": "NAME",
"value": "吕布"
},
{
"context": "(1, \"吕布\", 19));\n queue.add(new Student(4, \"貂蝉\", 16));\n Student zy = new Student(3, \"赵云\",",
"end": 2183,
"score": 0.9998255968093872,
"start": 2181,
"tag": "NAME",
"value": "貂蝉"
},
{
"context": " \"貂蝉\", 16));\n Student zy = new Student(3, \"赵云\", 17);\n queue.add(zy);\n\n Student zs",
"end": 2231,
"score": 0.9996803402900696,
"start": 2229,
"tag": "NAME",
"value": "赵云"
},
{
"context": "ue.add(zy);\n\n Student zs = new Student(2, \"张三\", 33);\n boolean contains = queue.contains(",
"end": 2302,
"score": 0.9990559816360474,
"start": 2300,
"tag": "NAME",
"value": "张三"
},
{
"context": "contains + \", \" + queue.contains(new Student(20, \"张三\", 33)));\n// if (contains) queue.remove(zs)",
"end": 2476,
"score": 0.9984639883041382,
"start": 2474,
"tag": "NAME",
"value": "张三"
},
{
"context": " queue.size());\n queue.add(new Student(0, \"吕布0\", 20));\n System.out.println(\"PriorityQueue",
"end": 3143,
"score": 0.9997832179069519,
"start": 3140,
"tag": "NAME",
"value": "吕布0"
},
{
"context": " PriorityQueueTest poll(原4), Student{id=1, name='吕布', age=19}, 3\n // I PriorityQueueTest pee",
"end": 3421,
"score": 0.9997977614402771,
"start": 3419,
"tag": "NAME",
"value": "吕布"
},
{
"context": "/ I PriorityQueueTest peek, Student{id=2, name='王昭君', age=18}, 3\n // I PriorityQueueTest rem",
"end": 3497,
"score": 0.9998283386230469,
"start": 3494,
"tag": "NAME",
"value": "王昭君"
},
{
"context": " I PriorityQueueTest remove, Student{id=0, name='吕布0', age=20}, 3\n // I PriorityQueueTest pee",
"end": 3575,
"score": 0.9998098611831665,
"start": 3572,
"tag": "NAME",
"value": "吕布0"
},
{
"context": "/ I PriorityQueueTest peek, Student{id=2, name='王昭君', age=18}, 3\n\n while (queue.peek() != null",
"end": 3651,
"score": 0.9998409152030945,
"start": 3648,
"tag": "NAME",
"value": "王昭君"
},
{
"context": "ityQueueTest test12 poll(原4), Student{id=1, name='吕布', age=19}, 2\n //I PriorityQueueTest test1",
"end": 4099,
"score": 0.9997846484184265,
"start": 4097,
"tag": "NAME",
"value": "吕布"
},
{
"context": "riorityQueueTest test12 peek, Student{id=4, name='貂蝉', age=16}, 2\n //I PriorityQueueTest test1",
"end": 4179,
"score": 0.9997787475585938,
"start": 4177,
"tag": "NAME",
"value": "貂蝉"
},
{
"context": "orityQueueTest test12 remove, Student{id=0, name='吕布0', age=20}, 2\n //I PriorityQueueTest test1",
"end": 4262,
"score": 0.99978107213974,
"start": 4259,
"tag": "NAME",
"value": "吕布0"
},
{
"context": "riorityQueueTest test12 peek, Student{id=4, name='貂蝉', age=16}, 2\n //I PriorityQueueTest test1",
"end": 4342,
"score": 0.9997248649597168,
"start": 4340,
"tag": "NAME",
"value": "貂蝉"
},
{
"context": "Test test12 ----> while poll, Student{id=4, name='貂蝉', age=16}\n //I PriorityQueueTest test12 -",
"end": 4434,
"score": 0.9997262954711914,
"start": 4432,
"tag": "NAME",
"value": "貂蝉"
},
{
"context": "est test12 ----> while poll, Student{id=30, name='赵云', age=17}\n\n // // 注释: if (contains) queu",
"end": 4524,
"score": 0.999752938747406,
"start": 4522,
"tag": "NAME",
"value": "赵云"
},
{
"context": " PriorityQueueTest poll(原4), Student{id=1, name='吕布', age=19}, 3\n //I PriorityQueueTest peek,",
"end": 4657,
"score": 0.9997838139533997,
"start": 4655,
"tag": "NAME",
"value": "吕布"
},
{
"context": " //I PriorityQueueTest peek, Student{id=2, name='王昭君', age=18}, 3\n //I PriorityQueueTest remov",
"end": 4731,
"score": 0.9998435974121094,
"start": 4728,
"tag": "NAME",
"value": "王昭君"
},
{
"context": "/I PriorityQueueTest remove, Student{id=0, name='吕布0', age=20}, 3\n //I PriorityQueueTest peek,",
"end": 4807,
"score": 0.9997800588607788,
"start": 4804,
"tag": "NAME",
"value": "吕布0"
},
{
"context": " //I PriorityQueueTest peek, Student{id=2, name='王昭君', age=18}, 3\n //I PriorityQueueTest test1",
"end": 4881,
"score": 0.999829113483429,
"start": 4878,
"tag": "NAME",
"value": "王昭君"
},
{
"context": "ityQueueTest test12 poll(原4), Student{id=1, name='吕布', age=19}, 3\n //I PriorityQueueTest test1",
"end": 5131,
"score": 0.999805748462677,
"start": 5129,
"tag": "NAME",
"value": "吕布"
},
{
"context": "riorityQueueTest test12 peek, Student{id=2, name='王昭君', age=18}, 3\n //I PriorityQueueTest test1",
"end": 5212,
"score": 0.9998331069946289,
"start": 5209,
"tag": "NAME",
"value": "王昭君"
},
{
"context": "orityQueueTest test12 remove, Student{id=0, name='吕布0', age=20}, 3\n //I PriorityQueueTest test1",
"end": 5295,
"score": 0.9998264312744141,
"start": 5292,
"tag": "NAME",
"value": "吕布0"
},
{
"context": "riorityQueueTest test12 peek, Student{id=2, name='王昭君', age=18}, 3\n //I PriorityQueueTest test1",
"end": 5376,
"score": 0.9998361468315125,
"start": 5373,
"tag": "NAME",
"value": "王昭君"
},
{
"context": "Test test12 ----> while poll, Student{id=2, name='王昭君', age=18}\n //I PriorityQueueTest test12 -",
"end": 5469,
"score": 0.9998326301574707,
"start": 5466,
"tag": "NAME",
"value": "王昭君"
},
{
"context": "Test test12 ----> while poll, Student{id=4, name='貂蝉', age=16}\n //I PriorityQueueTest test12 -",
"end": 5558,
"score": 0.9997960925102234,
"start": 5556,
"tag": "NAME",
"value": "貂蝉"
},
{
"context": "est test12 ----> while poll, Student{id=30, name='赵云', age=17}\n }\n\n\n public static void test2() ",
"end": 5648,
"score": 0.9997761845588684,
"start": 5646,
"tag": "NAME",
"value": "赵云"
},
{
"context": " \"id=\" + id +\n \", name='\" + name + '\\'' +\n \", age=\" + age +\n ",
"end": 8626,
"score": 0.9856271147727966,
"start": 8622,
"tag": "NAME",
"value": "name"
}
]
| null | []
| package walke.demolibrary.pinpu;
import androidx.annotation.Nullable;
import java.util.Comparator;
import java.util.PriorityQueue;
import walke.demolibrary.pinpu.queue.PrintTask;
import walke.demolibrary.pinpu.queue.Priority;
import walke.demolibrary.pinpu.queue.TaskQueue;
public class PriorityQueueTest {
public static void main(String[] args) {
test1();
}
public static void test1() {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
PriorityQueue<Student> queue = new PriorityQueue<>(new Comparator<Student>() {
@Override
public int compare(Student st1, Student st2) {
return st1.getId() - st2.getId();
}
});
queue.add(new Student(2, "王昭君", 18));
queue.add(new Student(1, "吕布", 19));
queue.add(new Student(4, "貂蝉", 16));
queue.add(new Student(3, "赵云", 17));
System.out.println("PriorityQueueTest poll(原4), " + queue.poll() + ", " + queue.size());
System.out.println("PriorityQueueTest peek, " + queue.peek() + ", " + queue.size());
queue.add(new Student(0, "吕布0", 20));
System.out.println("PriorityQueueTest remove, " + queue.remove() + ", " + queue.size());
System.out.println("PriorityQueueTest peek, " + queue.peek() + ", " + queue.size());
//I PriorityQueueTest test12 poll(原4), Student{id=1, name='吕布', age=19}, 3
//I PriorityQueueTest test12 peek, Student{id=2, name='王昭君', age=18}, 3
//I PriorityQueueTest test12 remove, Student{id=0, name='吕布0', age=20}, 3
//I PriorityQueueTest test12 peek, Student{id=2, name='王昭君', age=18}, 3
}
}
public static void test12() {
PriorityQueue<Student> queue = new PriorityQueue<>(32, new Comparator<Student>() {
@Override
public int compare(Student st1, Student st2) {
return st1.getId() - st2.getId();
}
});
queue.add(new Student(2, "王昭君", 18));
queue.add(new Student(1, "吕布", 19));
queue.add(new Student(4, "貂蝉", 16));
Student zy = new Student(3, "赵云", 17);
queue.add(zy);
Student zs = new Student(2, "张三", 33);
boolean contains = queue.contains(zs);
System.out.println("PriorityQueueTest test12 contains, " + contains + ", " + queue.contains(new Student(20, "张三", 33)));
// if (contains) queue.remove(zs); // 移除
System.out.println("PriorityQueueTest test12 contains, " + queue.contains(zy));
zy.setId(30);
System.out.println("PriorityQueueTest test12 contains, " + queue.contains(zy));
// I PriorityQueueTest test12 contains, true, false
// I PriorityQueueTest test12 contains, true
// I PriorityQueueTest test12 contains, true
System.out.println("PriorityQueueTest test12 poll(原4), " + queue.poll() + ", " + queue.size());
System.out.println("PriorityQueueTest test12 peek, " + queue.peek() + ", " + queue.size());
queue.add(new Student(0, "吕布0", 20));
System.out.println("PriorityQueueTest test12 remove, " + queue.remove() + ", " + queue.size());
System.out.println("PriorityQueueTest test12 peek, " + queue.peek() + ", " + queue.size());
// I PriorityQueueTest poll(原4), Student{id=1, name='吕布', age=19}, 3
// I PriorityQueueTest peek, Student{id=2, name='王昭君', age=18}, 3
// I PriorityQueueTest remove, Student{id=0, name='吕布0', age=20}, 3
// I PriorityQueueTest peek, Student{id=2, name='王昭君', age=18}, 3
while (queue.peek() != null) {
System.out.println("PriorityQueueTest test12 ----> while poll, " + queue.poll());
}
// 有 if (contains) queue.remove(zs); // 移除
//I PriorityQueueTest test12 contains, true, false
//I PriorityQueueTest test12 contains, true
//I PriorityQueueTest test12 contains, true
//I PriorityQueueTest test12 poll(原4), Student{id=1, name='吕布', age=19}, 2
//I PriorityQueueTest test12 peek, Student{id=4, name='貂蝉', age=16}, 2
//I PriorityQueueTest test12 remove, Student{id=0, name='吕布0', age=20}, 2
//I PriorityQueueTest test12 peek, Student{id=4, name='貂蝉', age=16}, 2
//I PriorityQueueTest test12 ----> while poll, Student{id=4, name='貂蝉', age=16}
//I PriorityQueueTest test12 ----> while poll, Student{id=30, name='赵云', age=17}
// // 注释: if (contains) queue.remove(zs); // 移除
//I PriorityQueueTest poll(原4), Student{id=1, name='吕布', age=19}, 3
//I PriorityQueueTest peek, Student{id=2, name='王昭君', age=18}, 3
//I PriorityQueueTest remove, Student{id=0, name='吕布0', age=20}, 3
//I PriorityQueueTest peek, Student{id=2, name='王昭君', age=18}, 3
//I PriorityQueueTest test12 contains, true, false
//I PriorityQueueTest test12 contains, true
//I PriorityQueueTest test12 contains, true
//I PriorityQueueTest test12 poll(原4), Student{id=1, name='吕布', age=19}, 3
//I PriorityQueueTest test12 peek, Student{id=2, name='王昭君', age=18}, 3
//I PriorityQueueTest test12 remove, Student{id=0, name='吕布0', age=20}, 3
//I PriorityQueueTest test12 peek, Student{id=2, name='王昭君', age=18}, 3
//I PriorityQueueTest test12 ----> while poll, Student{id=2, name='王昭君', age=18}
//I PriorityQueueTest test12 ----> while poll, Student{id=4, name='貂蝉', age=16}
//I PriorityQueueTest test12 ----> while poll, Student{id=30, name='赵云', age=17}
}
public static void test2() {
// 开一个窗口,这样会让优先级更加明显。
TaskQueue taskQueue = new TaskQueue(1);
taskQueue.start(); // // 某机构开始工作。
// 为了显示出优先级效果,我们预添加3个在前面堵着,让后面的优先级效果更明显。
taskQueue.add(new PrintTask(111));
taskQueue.add(new PrintTask(112));
taskQueue.add(new PrintTask(122));
for (int i = 0; i < 10; i++) { // 从第0个人开始。
PrintTask task = new PrintTask(i);
if (1 == i) {
task.setPriority(Priority.LOW); // 让第2个进入的人最后办事。
} else if (8 == i) {
task.setPriority(Priority.HIGH); // 让第9个进入的人第二个办事。
} else if (9 == i) {
task.setPriority(Priority.Immediately); // 让第10(i=9)个进入的人第一个办事。
}
// ... 其它进入的人,按照进入顺序办事。
taskQueue.add(task);
}
// I PrintTask TaskQueue start
// I PrintTask TaskQueue start
// I PrintTask sequence 9
// I PrintTask sequence 8
// I PrintTask sequence 2
// I PrintTask sequence 7
// I PrintTask sequence 112
// I PrintTask sequence 5
// I PrintTask sequence 0
// I PrintTask sequence 3
// I PrintTask sequence 111
// I PrintTask sequence 6
// I PrintTask sequence 4
// I PrintTask sequence 122
// I PrintTask sequence 1
taskQueue.start();
}
public static class Student {
private int id;
private String name;
private int age;
public Student(int i, String name, int age) {
this.id = i;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public boolean equals(@Nullable Object obj) {
// return super.equals(obj);
if (this == obj) { //判断一下如果是同一个对象直接返回true,提高效率
return true;
}
if (obj == null || obj.getClass() != this.getClass()) { //如果传进来的对象为null或者二者为不同类,直接返回false
return false;
}
//也可以以下方法:
// if (obj == null || !(obj instanceof Rectangle)) { //如果传进来的对象为null或者二者为不同类,直接返回false
// return false;
// }
Student rectangle = (Student) obj; //向下转型
//比较长宽是否相等,注意:浮点数的比较不能简单地用==,会有精度的误差,用Math.abs或者Double.compare
return this.id == rectangle.getId();
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
}
| 9,396 | 0.557939 | 0.526388 | 215 | 39.539536 | 29.828611 | 128 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.097674 | false | false | 0 |
a73d6c7db9a24c2a5587fd2d541865fb28a04a68 | 21,260,088,170,836 | a60d7543e9cf369db9a39d235b0ce07eb721aa12 | /hippo-rest/src/main/java/com/yoterra/hippo/security/ActiveUser.java | 578f571dbcd913d071a47f0962e1188fa877ae5c | []
| no_license | nawelmohamed/hippo | https://github.com/nawelmohamed/hippo | 7bd0da5b78f41178a314531d98d792ddfbc07aa8 | 8d4e81a4219e7e27a2a012aeaa3fc671a7d4221b | refs/heads/master | 2023-09-04T18:31:43.908000 | 2021-08-26T11:54:52 | 2021-08-26T11:54:52 | 428,688,345 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.yoterra.hippo.security;
import java.util.Objects;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import com.yoterra.hippo.jpa.entities.users.User;
import com.yoterra.hippo.security.model.AuthToken;
import com.yoterra.hippo.security.model.FirebaseAuthentication;
import com.yoterra.utils.Opt;
public class ActiveUser {
public static boolean is(User usr) {
return Objects.equals(get().getId(), usr.getId());
}
public static boolean is(User usr, boolean required) {
Long uid = usr.getId();
User au = get(required);
return Opt.getOrDef(au, false, User::getId, uid::equals);
}
public static Long getId() {
return get(true).getId();
}
public static Long getId(boolean required) {
return Opt.get(get(required), User::getId);
}
public static User get() {
return get(true);
}
public static User get(boolean required) {
User user = Opt.get(getUserPrincipal(false), UserPrincipal::getUser);
return req(user, required, "No user");
}
public static UserPrincipal getUserPrincipal() {
return getUserPrincipal(true);
}
public static UserPrincipal getUserPrincipal(boolean required) {
UserPrincipal userPrincipal = null;
Object principal = getAuthentication().getPrincipal();
if (principal instanceof UserPrincipal) {
userPrincipal = (UserPrincipal) principal;
}
return req(userPrincipal, required, "No user principal");
}
public static FirebaseAuthentication getAuthentication() {
return getAuthentication(true);
}
public static FirebaseAuthentication getAuthentication(boolean required) {
FirebaseAuthentication authentication = (FirebaseAuthentication) SecurityContextHolder.getContext().getAuthentication();
return req(authentication, required, "No authentication");
}
public static AuthToken getToken() {
return getToken(true);
}
public static AuthToken getToken(boolean required) {
AuthToken authToken = Opt.get(getAuthentication(), FirebaseAuthentication::getToken);
return req(authToken, required, "No authentication token");
}
public static void setAuthentication(FirebaseAuthentication authentication) {
SecurityContextHolder.getContext().setAuthentication(authentication);
}
public static String extractToken(HttpServletRequest request) {
String bearerToken = null;
String authorization = request.getHeader("Authorization");
if (StringUtils.startsWith(authorization, "Bearer ")) {
bearerToken = StringUtils.substringAfter(authorization, "Bearer ");
}
return bearerToken;
}
private static <T> T req(T obj, boolean required, String message) {
return required ? Opt.req(obj, ()->new IllegalStateException(message)) : obj;
}
}
| UTF-8 | Java | 2,775 | java | ActiveUser.java | Java | []
| null | []
| package com.yoterra.hippo.security;
import java.util.Objects;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import com.yoterra.hippo.jpa.entities.users.User;
import com.yoterra.hippo.security.model.AuthToken;
import com.yoterra.hippo.security.model.FirebaseAuthentication;
import com.yoterra.utils.Opt;
public class ActiveUser {
public static boolean is(User usr) {
return Objects.equals(get().getId(), usr.getId());
}
public static boolean is(User usr, boolean required) {
Long uid = usr.getId();
User au = get(required);
return Opt.getOrDef(au, false, User::getId, uid::equals);
}
public static Long getId() {
return get(true).getId();
}
public static Long getId(boolean required) {
return Opt.get(get(required), User::getId);
}
public static User get() {
return get(true);
}
public static User get(boolean required) {
User user = Opt.get(getUserPrincipal(false), UserPrincipal::getUser);
return req(user, required, "No user");
}
public static UserPrincipal getUserPrincipal() {
return getUserPrincipal(true);
}
public static UserPrincipal getUserPrincipal(boolean required) {
UserPrincipal userPrincipal = null;
Object principal = getAuthentication().getPrincipal();
if (principal instanceof UserPrincipal) {
userPrincipal = (UserPrincipal) principal;
}
return req(userPrincipal, required, "No user principal");
}
public static FirebaseAuthentication getAuthentication() {
return getAuthentication(true);
}
public static FirebaseAuthentication getAuthentication(boolean required) {
FirebaseAuthentication authentication = (FirebaseAuthentication) SecurityContextHolder.getContext().getAuthentication();
return req(authentication, required, "No authentication");
}
public static AuthToken getToken() {
return getToken(true);
}
public static AuthToken getToken(boolean required) {
AuthToken authToken = Opt.get(getAuthentication(), FirebaseAuthentication::getToken);
return req(authToken, required, "No authentication token");
}
public static void setAuthentication(FirebaseAuthentication authentication) {
SecurityContextHolder.getContext().setAuthentication(authentication);
}
public static String extractToken(HttpServletRequest request) {
String bearerToken = null;
String authorization = request.getHeader("Authorization");
if (StringUtils.startsWith(authorization, "Bearer ")) {
bearerToken = StringUtils.substringAfter(authorization, "Bearer ");
}
return bearerToken;
}
private static <T> T req(T obj, boolean required, String message) {
return required ? Opt.req(obj, ()->new IllegalStateException(message)) : obj;
}
}
| 2,775 | 0.758919 | 0.758559 | 93 | 28.838709 | 28.267269 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.763441 | false | false | 0 |
96a833f51b35e87c8c225f1bf71a30fa76059c41 | 31,155,692,820,477 | 646138db6c5756d210c23c98a2186ad193f0e57a | /MyPet/app/src/main/java/com/david/mypet/Login.java | f9afa10c8e2306503ace06024cc38f9ac0d0c932 | [
"MIT"
]
| permissive | davld-R/Moviles-6A-2020 | https://github.com/davld-R/Moviles-6A-2020 | 7431a4008243063921815dccab056fbd7162c488 | 47b29c6308bab752ab88ff141fd4217f058f9984 | refs/heads/master | 2023-06-12T23:05:30.039000 | 2021-06-29T03:50:59 | 2021-06-29T03:50:59 | 295,465,837 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.david.mypet;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;
public class Login extends AppCompatActivity {
Context context;
SharedPreferences sharedPref;
String usr, pwd;
EditText et_reg, et_con;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
context = this;
sharedPref = context.getSharedPreferences("File", context.MODE_PRIVATE);
usr = sharedPref.getString("n_usr", "-");
pwd = sharedPref.getString("pwd_usr", "-");
et_reg = findViewById(R.id.et_reg);
et_con = findViewById(R.id.et_con);
}
public void start(View v) {
Intent intent = new Intent(context, MainActivity.class);
startActivity(intent);
}
public void exit(View v) {
finish();
}
public void next(View v) {
Intent intent = new Intent(context, Register.class);
startActivity(intent);
}
public void login(View v) {
String u = et_reg.getText().toString();
String p = et_con.getText().toString();
if(u.compareTo(usr) == 0 && p.compareTo(pwd) == 0) {
Intent intent = new Intent(context, MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(context, "Credenciales incorrectas", Toast.LENGTH_LONG).show();
}
}
}
| UTF-8 | Java | 1,893 | java | Login.java | Java | []
| null | []
| package com.david.mypet;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;
public class Login extends AppCompatActivity {
Context context;
SharedPreferences sharedPref;
String usr, pwd;
EditText et_reg, et_con;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
context = this;
sharedPref = context.getSharedPreferences("File", context.MODE_PRIVATE);
usr = sharedPref.getString("n_usr", "-");
pwd = sharedPref.getString("pwd_usr", "-");
et_reg = findViewById(R.id.et_reg);
et_con = findViewById(R.id.et_con);
}
public void start(View v) {
Intent intent = new Intent(context, MainActivity.class);
startActivity(intent);
}
public void exit(View v) {
finish();
}
public void next(View v) {
Intent intent = new Intent(context, Register.class);
startActivity(intent);
}
public void login(View v) {
String u = et_reg.getText().toString();
String p = et_con.getText().toString();
if(u.compareTo(usr) == 0 && p.compareTo(pwd) == 0) {
Intent intent = new Intent(context, MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(context, "Credenciales incorrectas", Toast.LENGTH_LONG).show();
}
}
}
| 1,893 | 0.656101 | 0.655045 | 79 | 22.962025 | 22.819292 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.582278 | false | false | 0 |
8907f6752c5a3717d797a07e14b76e4a3e1fab17 | 13,108,240,212,595 | 857d903812f361101d2838e1109916df5c2f7966 | /cloud-config-client/src/main/java/com/hr/controller/ConfigClientController.java | dd2cdbf06a77f6c63480f29a6584b9aad87422c7 | []
| no_license | huran111/spring-cloud | https://github.com/huran111/spring-cloud | 491dc0356e55d19ce8775ca1054102d4e011a437 | bc064988bc6cc93c622924440d22a891c0170539 | refs/heads/master | 2020-04-17T17:35:27.285000 | 2019-05-06T03:18:21 | 2019-05-06T03:18:21 | 166,788,740 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hr.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author 胡冉
* @Description: TODO
* @date 2019/1/1511:23
* @copyright {@link www.hndfsj.com}
*/
@RestController
public class ConfigClientController {
@Value("${aaaaa}")
private String aaaaa;
@GetMapping(value = "/aaaaa")
public String getAAAAAProFile() {
return aaaaa;
}
@Value("${bbbbb}")
private String bbbbb;
@GetMapping(value = "/bbbbb")
public String getBBBBBProFile() {
return bbbbb;
}
}
| UTF-8 | Java | 676 | java | ConfigClientController.java | Java | [
{
"context": "b.bind.annotation.RestController;\n\n/**\n * @author 胡冉\n * @Description: TODO\n * @date 2019/1/1511:23\n * ",
"end": 227,
"score": 0.999581515789032,
"start": 225,
"tag": "NAME",
"value": "胡冉"
}
]
| null | []
| package com.hr.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author 胡冉
* @Description: TODO
* @date 2019/1/1511:23
* @copyright {@link www.hndfsj.com}
*/
@RestController
public class ConfigClientController {
@Value("${aaaaa}")
private String aaaaa;
@GetMapping(value = "/aaaaa")
public String getAAAAAProFile() {
return aaaaa;
}
@Value("${bbbbb}")
private String bbbbb;
@GetMapping(value = "/bbbbb")
public String getBBBBBProFile() {
return bbbbb;
}
}
| 676 | 0.686012 | 0.669643 | 30 | 21.4 | 17.910147 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.266667 | false | false | 0 |
f69e8d7d1ea6bb49849acaf6c7c75ac730c2e206 | 1,889,785,676,571 | 808c78b46356720a25af84692199e6efcd067fba | /de.hub.citygml.emf.ecore/src/net/opengis/citygml/waterbody/impl/WaterbodyFactoryImpl.java | 44a31b56c406132a506159c5f1cde93324124a67 | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | markus1978/citygml4emf | https://github.com/markus1978/citygml4emf | d4cc45107e588a435b1f9ddfdeb17ae77f46e9e7 | 06fe29a850646043ea0ffb7b1353d28115e16a53 | refs/heads/master | 2016-09-05T10:14:46.360000 | 2013-02-11T11:19:06 | 2013-02-11T11:19:06 | 8,071,822 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* <copyright>
* </copyright>
*
* $Id$
*/
package net.opengis.citygml.waterbody.impl;
import net.opengis.citygml.waterbody.BoundedByWaterSurfacePropertyType;
import net.opengis.citygml.waterbody.DocumentRoot;
import net.opengis.citygml.waterbody.WaterBodyType;
import net.opengis.citygml.waterbody.WaterClosureSurfaceType;
import net.opengis.citygml.waterbody.WaterGroundSurfaceType;
import net.opengis.citygml.waterbody.WaterSurfaceType;
import net.opengis.citygml.waterbody.WaterbodyFactory;
import net.opengis.citygml.waterbody.WaterbodyPackage;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EDataType;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.impl.EFactoryImpl;
import org.eclipse.emf.ecore.plugin.EcorePlugin;
import org.eclipse.emf.ecore.xml.type.XMLTypeFactory;
import org.eclipse.emf.ecore.xml.type.XMLTypePackage;
/**
* <!-- begin-user-doc -->
* An implementation of the model <b>Factory</b>.
* <!-- end-user-doc -->
* @generated
*/
public class WaterbodyFactoryImpl extends EFactoryImpl implements WaterbodyFactory {
/**
* Creates the default factory implementation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static WaterbodyFactory init() {
try {
WaterbodyFactory theWaterbodyFactory = (WaterbodyFactory)EPackage.Registry.INSTANCE.getEFactory("http://www.opengis.net/citygml/waterbody/1.0");
if (theWaterbodyFactory != null) {
return theWaterbodyFactory;
}
}
catch (Exception exception) {
EcorePlugin.INSTANCE.log(exception);
}
return new WaterbodyFactoryImpl();
}
/**
* Creates an instance of the factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public WaterbodyFactoryImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public EObject create(EClass eClass) {
switch (eClass.getClassifierID()) {
case WaterbodyPackage.BOUNDED_BY_WATER_SURFACE_PROPERTY_TYPE: return createBoundedByWaterSurfacePropertyType();
case WaterbodyPackage.DOCUMENT_ROOT: return createDocumentRoot();
case WaterbodyPackage.WATER_BODY_TYPE: return createWaterBodyType();
case WaterbodyPackage.WATER_CLOSURE_SURFACE_TYPE: return createWaterClosureSurfaceType();
case WaterbodyPackage.WATER_GROUND_SURFACE_TYPE: return createWaterGroundSurfaceType();
case WaterbodyPackage.WATER_SURFACE_TYPE: return createWaterSurfaceType();
default:
throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier");
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object createFromString(EDataType eDataType, String initialValue) {
switch (eDataType.getClassifierID()) {
case WaterbodyPackage.WATER_BODY_CLASS_TYPE:
return createWaterBodyClassTypeFromString(eDataType, initialValue);
case WaterbodyPackage.WATER_BODY_FUNCTION_TYPE:
return createWaterBodyFunctionTypeFromString(eDataType, initialValue);
case WaterbodyPackage.WATER_BODY_USAGE_TYPE:
return createWaterBodyUsageTypeFromString(eDataType, initialValue);
case WaterbodyPackage.WATER_LEVEL_TYPE:
return createWaterLevelTypeFromString(eDataType, initialValue);
default:
throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier");
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String convertToString(EDataType eDataType, Object instanceValue) {
switch (eDataType.getClassifierID()) {
case WaterbodyPackage.WATER_BODY_CLASS_TYPE:
return convertWaterBodyClassTypeToString(eDataType, instanceValue);
case WaterbodyPackage.WATER_BODY_FUNCTION_TYPE:
return convertWaterBodyFunctionTypeToString(eDataType, instanceValue);
case WaterbodyPackage.WATER_BODY_USAGE_TYPE:
return convertWaterBodyUsageTypeToString(eDataType, instanceValue);
case WaterbodyPackage.WATER_LEVEL_TYPE:
return convertWaterLevelTypeToString(eDataType, instanceValue);
default:
throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier");
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public BoundedByWaterSurfacePropertyType createBoundedByWaterSurfacePropertyType() {
BoundedByWaterSurfacePropertyTypeImpl boundedByWaterSurfacePropertyType = new BoundedByWaterSurfacePropertyTypeImpl();
return boundedByWaterSurfacePropertyType;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DocumentRoot createDocumentRoot() {
DocumentRootImpl documentRoot = new DocumentRootImpl();
return documentRoot;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public WaterBodyType createWaterBodyType() {
WaterBodyTypeImpl waterBodyType = new WaterBodyTypeImpl();
return waterBodyType;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public WaterClosureSurfaceType createWaterClosureSurfaceType() {
WaterClosureSurfaceTypeImpl waterClosureSurfaceType = new WaterClosureSurfaceTypeImpl();
return waterClosureSurfaceType;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public WaterGroundSurfaceType createWaterGroundSurfaceType() {
WaterGroundSurfaceTypeImpl waterGroundSurfaceType = new WaterGroundSurfaceTypeImpl();
return waterGroundSurfaceType;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public WaterSurfaceType createWaterSurfaceType() {
WaterSurfaceTypeImpl waterSurfaceType = new WaterSurfaceTypeImpl();
return waterSurfaceType;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String createWaterBodyClassTypeFromString(EDataType eDataType, String initialValue) {
return (String)XMLTypeFactory.eINSTANCE.createFromString(XMLTypePackage.Literals.STRING, initialValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String convertWaterBodyClassTypeToString(EDataType eDataType, Object instanceValue) {
return XMLTypeFactory.eINSTANCE.convertToString(XMLTypePackage.Literals.STRING, instanceValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String createWaterBodyFunctionTypeFromString(EDataType eDataType, String initialValue) {
return (String)XMLTypeFactory.eINSTANCE.createFromString(XMLTypePackage.Literals.STRING, initialValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String convertWaterBodyFunctionTypeToString(EDataType eDataType, Object instanceValue) {
return XMLTypeFactory.eINSTANCE.convertToString(XMLTypePackage.Literals.STRING, instanceValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String createWaterBodyUsageTypeFromString(EDataType eDataType, String initialValue) {
return (String)XMLTypeFactory.eINSTANCE.createFromString(XMLTypePackage.Literals.STRING, initialValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String convertWaterBodyUsageTypeToString(EDataType eDataType, Object instanceValue) {
return XMLTypeFactory.eINSTANCE.convertToString(XMLTypePackage.Literals.STRING, instanceValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String createWaterLevelTypeFromString(EDataType eDataType, String initialValue) {
return (String)XMLTypeFactory.eINSTANCE.createFromString(XMLTypePackage.Literals.STRING, initialValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String convertWaterLevelTypeToString(EDataType eDataType, Object instanceValue) {
return XMLTypeFactory.eINSTANCE.convertToString(XMLTypePackage.Literals.STRING, instanceValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public WaterbodyPackage getWaterbodyPackage() {
return (WaterbodyPackage)getEPackage();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @deprecated
* @generated
*/
@Deprecated
public static WaterbodyPackage getPackage() {
return WaterbodyPackage.eINSTANCE;
}
} //WaterbodyFactoryImpl
| UTF-8 | Java | 8,415 | java | WaterbodyFactoryImpl.java | Java | []
| null | []
| /**
* <copyright>
* </copyright>
*
* $Id$
*/
package net.opengis.citygml.waterbody.impl;
import net.opengis.citygml.waterbody.BoundedByWaterSurfacePropertyType;
import net.opengis.citygml.waterbody.DocumentRoot;
import net.opengis.citygml.waterbody.WaterBodyType;
import net.opengis.citygml.waterbody.WaterClosureSurfaceType;
import net.opengis.citygml.waterbody.WaterGroundSurfaceType;
import net.opengis.citygml.waterbody.WaterSurfaceType;
import net.opengis.citygml.waterbody.WaterbodyFactory;
import net.opengis.citygml.waterbody.WaterbodyPackage;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EDataType;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.impl.EFactoryImpl;
import org.eclipse.emf.ecore.plugin.EcorePlugin;
import org.eclipse.emf.ecore.xml.type.XMLTypeFactory;
import org.eclipse.emf.ecore.xml.type.XMLTypePackage;
/**
* <!-- begin-user-doc -->
* An implementation of the model <b>Factory</b>.
* <!-- end-user-doc -->
* @generated
*/
public class WaterbodyFactoryImpl extends EFactoryImpl implements WaterbodyFactory {
/**
* Creates the default factory implementation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static WaterbodyFactory init() {
try {
WaterbodyFactory theWaterbodyFactory = (WaterbodyFactory)EPackage.Registry.INSTANCE.getEFactory("http://www.opengis.net/citygml/waterbody/1.0");
if (theWaterbodyFactory != null) {
return theWaterbodyFactory;
}
}
catch (Exception exception) {
EcorePlugin.INSTANCE.log(exception);
}
return new WaterbodyFactoryImpl();
}
/**
* Creates an instance of the factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public WaterbodyFactoryImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public EObject create(EClass eClass) {
switch (eClass.getClassifierID()) {
case WaterbodyPackage.BOUNDED_BY_WATER_SURFACE_PROPERTY_TYPE: return createBoundedByWaterSurfacePropertyType();
case WaterbodyPackage.DOCUMENT_ROOT: return createDocumentRoot();
case WaterbodyPackage.WATER_BODY_TYPE: return createWaterBodyType();
case WaterbodyPackage.WATER_CLOSURE_SURFACE_TYPE: return createWaterClosureSurfaceType();
case WaterbodyPackage.WATER_GROUND_SURFACE_TYPE: return createWaterGroundSurfaceType();
case WaterbodyPackage.WATER_SURFACE_TYPE: return createWaterSurfaceType();
default:
throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier");
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object createFromString(EDataType eDataType, String initialValue) {
switch (eDataType.getClassifierID()) {
case WaterbodyPackage.WATER_BODY_CLASS_TYPE:
return createWaterBodyClassTypeFromString(eDataType, initialValue);
case WaterbodyPackage.WATER_BODY_FUNCTION_TYPE:
return createWaterBodyFunctionTypeFromString(eDataType, initialValue);
case WaterbodyPackage.WATER_BODY_USAGE_TYPE:
return createWaterBodyUsageTypeFromString(eDataType, initialValue);
case WaterbodyPackage.WATER_LEVEL_TYPE:
return createWaterLevelTypeFromString(eDataType, initialValue);
default:
throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier");
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String convertToString(EDataType eDataType, Object instanceValue) {
switch (eDataType.getClassifierID()) {
case WaterbodyPackage.WATER_BODY_CLASS_TYPE:
return convertWaterBodyClassTypeToString(eDataType, instanceValue);
case WaterbodyPackage.WATER_BODY_FUNCTION_TYPE:
return convertWaterBodyFunctionTypeToString(eDataType, instanceValue);
case WaterbodyPackage.WATER_BODY_USAGE_TYPE:
return convertWaterBodyUsageTypeToString(eDataType, instanceValue);
case WaterbodyPackage.WATER_LEVEL_TYPE:
return convertWaterLevelTypeToString(eDataType, instanceValue);
default:
throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier");
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public BoundedByWaterSurfacePropertyType createBoundedByWaterSurfacePropertyType() {
BoundedByWaterSurfacePropertyTypeImpl boundedByWaterSurfacePropertyType = new BoundedByWaterSurfacePropertyTypeImpl();
return boundedByWaterSurfacePropertyType;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DocumentRoot createDocumentRoot() {
DocumentRootImpl documentRoot = new DocumentRootImpl();
return documentRoot;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public WaterBodyType createWaterBodyType() {
WaterBodyTypeImpl waterBodyType = new WaterBodyTypeImpl();
return waterBodyType;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public WaterClosureSurfaceType createWaterClosureSurfaceType() {
WaterClosureSurfaceTypeImpl waterClosureSurfaceType = new WaterClosureSurfaceTypeImpl();
return waterClosureSurfaceType;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public WaterGroundSurfaceType createWaterGroundSurfaceType() {
WaterGroundSurfaceTypeImpl waterGroundSurfaceType = new WaterGroundSurfaceTypeImpl();
return waterGroundSurfaceType;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public WaterSurfaceType createWaterSurfaceType() {
WaterSurfaceTypeImpl waterSurfaceType = new WaterSurfaceTypeImpl();
return waterSurfaceType;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String createWaterBodyClassTypeFromString(EDataType eDataType, String initialValue) {
return (String)XMLTypeFactory.eINSTANCE.createFromString(XMLTypePackage.Literals.STRING, initialValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String convertWaterBodyClassTypeToString(EDataType eDataType, Object instanceValue) {
return XMLTypeFactory.eINSTANCE.convertToString(XMLTypePackage.Literals.STRING, instanceValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String createWaterBodyFunctionTypeFromString(EDataType eDataType, String initialValue) {
return (String)XMLTypeFactory.eINSTANCE.createFromString(XMLTypePackage.Literals.STRING, initialValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String convertWaterBodyFunctionTypeToString(EDataType eDataType, Object instanceValue) {
return XMLTypeFactory.eINSTANCE.convertToString(XMLTypePackage.Literals.STRING, instanceValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String createWaterBodyUsageTypeFromString(EDataType eDataType, String initialValue) {
return (String)XMLTypeFactory.eINSTANCE.createFromString(XMLTypePackage.Literals.STRING, initialValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String convertWaterBodyUsageTypeToString(EDataType eDataType, Object instanceValue) {
return XMLTypeFactory.eINSTANCE.convertToString(XMLTypePackage.Literals.STRING, instanceValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String createWaterLevelTypeFromString(EDataType eDataType, String initialValue) {
return (String)XMLTypeFactory.eINSTANCE.createFromString(XMLTypePackage.Literals.STRING, initialValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String convertWaterLevelTypeToString(EDataType eDataType, Object instanceValue) {
return XMLTypeFactory.eINSTANCE.convertToString(XMLTypePackage.Literals.STRING, instanceValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public WaterbodyPackage getWaterbodyPackage() {
return (WaterbodyPackage)getEPackage();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @deprecated
* @generated
*/
@Deprecated
public static WaterbodyPackage getPackage() {
return WaterbodyPackage.eINSTANCE;
}
} //WaterbodyFactoryImpl
| 8,415 | 0.726441 | 0.726203 | 276 | 29.48913 | 31.133942 | 148 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.521739 | false | false | 0 |
f71978badb28fb6601d9e738edfb7c989229f468 | 22,806,276,353,361 | 23e9ea1b44f3bbde69f13c8533b55849ec7cdf07 | /src/main/java/wadstagram/controller/ControlErrorrer.java | 4a8d042a0f271513e846486c4030db366022dfe9 | []
| no_license | willberthos/wadstagram | https://github.com/willberthos/wadstagram | 4e17be38b4cab7e658b8ba399d6f2948e87ab7b4 | 3455970bb21da0301e0a0484be684263b8b5324e | refs/heads/master | 2021-06-18T08:44:31.750000 | 2017-06-21T16:21:26 | 2017-06-21T16:21:26 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package wadstagram.controller;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.context.annotation.Profile;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Profile("production")
@RestController
public class ControlErrorrer implements ErrorController {
@RequestMapping(value = "/error")
public String error(HttpServletResponse response) throws IOException {
response.sendRedirect("/oops");
return "";
}
@Override
public String getErrorPath() {
return "/error";
}
}
| UTF-8 | Java | 715 | java | ControlErrorrer.java | Java | []
| null | []
| package wadstagram.controller;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.context.annotation.Profile;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Profile("production")
@RestController
public class ControlErrorrer implements ErrorController {
@RequestMapping(value = "/error")
public String error(HttpServletResponse response) throws IOException {
response.sendRedirect("/oops");
return "";
}
@Override
public String getErrorPath() {
return "/error";
}
}
| 715 | 0.766434 | 0.766434 | 24 | 28.791666 | 23.637857 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.416667 | false | false | 0 |
651ea1a2879ba0fc927bde38e3a2b1ccc19810d5 | 14,370,960,603,593 | fd7b5dac23d9a3dc60ae105e0c6b26b3c9f0746b | /src/main/java/com/meteorice/devilfish/util/json/JsonUtil.java | 8032e42de67504bb97a37f3376c1782d715f1658 | [
"MIT"
]
| permissive | meteorice/devilfish | https://github.com/meteorice/devilfish | 2566580f4d8ed327dde9da99cf0ff577a54d9c2a | 7d4a84b9cb4de9da2a6b92c2a030f6e03a828c0e | refs/heads/master | 2020-04-16T18:18:23.384000 | 2019-02-15T03:00:58 | 2019-02-15T03:00:58 | 165,813,566 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.meteorice.devilfish.util.json;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
public class JsonUtil {
/**
* 普通mapper
*/
private static final ObjectMapper mapper = new ObjectMapper();
/**
* 带顺序的mapper
*/
private static final ObjectMapper orderMapper = new ObjectMapper();
static {
//map根据key排序
orderMapper.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS);
//开启字段排序
orderMapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
//------------------------->通用设置<-------------------------------
// 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
orderMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// 设置输出时包含属性的风格
orderMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
}
/**
* Get json mapper object mapper.
*
* @return the object mapper
*/
public static ObjectMapper getJsonMapper() {
return mapper;
}
}
| UTF-8 | Java | 1,522 | java | JsonUtil.java | Java | []
| null | []
| package com.meteorice.devilfish.util.json;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
public class JsonUtil {
/**
* 普通mapper
*/
private static final ObjectMapper mapper = new ObjectMapper();
/**
* 带顺序的mapper
*/
private static final ObjectMapper orderMapper = new ObjectMapper();
static {
//map根据key排序
orderMapper.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS);
//开启字段排序
orderMapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
//------------------------->通用设置<-------------------------------
// 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
orderMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// 设置输出时包含属性的风格
orderMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
}
/**
* Get json mapper object mapper.
*
* @return the object mapper
*/
public static ObjectMapper getJsonMapper() {
return mapper;
}
}
| 1,522 | 0.682979 | 0.682979 | 46 | 29.652174 | 28.784218 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.391304 | false | false | 0 |
636f31cacb30021c0f8b664473094f799a1fe4ed | 32,349,693,675,556 | 3e64ffa82024eb3fb9e22a193b2319101e71264c | /src/VentaProducto/Venta.java | eed1a3b0546868230655115a94d8946b6f5eea28 | []
| no_license | UlisesAlexanderAM/Ejercicios1 | https://github.com/UlisesAlexanderAM/Ejercicios1 | 823f799267e98d8ccdfd69dca47fe2a8ec4cf498 | 90fff4a2d012bc508f1f4f177b0aaafa658a9f00 | refs/heads/master | 2021-01-16T10:43:26.429000 | 2020-07-04T03:29:26 | 2020-07-04T03:29:26 | 243,087,985 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package VentaProducto;
import java.util.ArrayList;
import static Ejercicios.Imprimir.imprimir;
import static Ejercicios.Leer.leerCadena;
import static Ejercicios.Leer.leerEntero;
public class Venta {
private int idVenta, flag=0;
private Inventario productos;
private final ArrayList <Producto> productosVenta = new ArrayList<>();
private ArrayList <Integer> cantidadVendida = new ArrayList<>();
Venta(Inventario productos){
this.productos = productos;
}
Venta(int id,Inventario productos){
idVenta=id;
this.productos = productos;
}
public void agregarProducto(){
String nombre;
imprimir("Los productos en inventario son los siguientes: ");
for (int i = 0; i < productos.getProductos().size(); i++) {
imprimir("%n"+productos.getProductos().get(i).getNombreProducto());
}
while (flag==0){
nombre=leerCadena("%nIngrese el nombre producto a agregar: ");
if (productos.buscarProducto(nombre)){
int indice,cantidad;
Producto producto;
indice=productos.buscarIndiceProducto(nombre);
producto=productos.getProductos().get(indice);
productosVenta.add(producto);
cantidad=leerEntero("%nIngrese la cantidad vendida de "+producto.getNombreProducto()+
": ");
cantidadVendida.add(cantidad);
productos.modificarCantidadPorVenta(indice,cantidad);
}else {
imprimir("%nNombre no valido");
flag=1;
}
}
}
public void setIdVenta(int idVenta) {
this.idVenta = idVenta;
}
public int getIdVenta() {
return idVenta;
}
public void imprimirProductosVenta(){
for (Producto producto : productosVenta){
imprimir("%n"+producto.getNombreProducto()+
": "+producto.getCantidadProducto());
}
}
}
| UTF-8 | Java | 2,012 | java | Venta.java | Java | []
| null | []
| package VentaProducto;
import java.util.ArrayList;
import static Ejercicios.Imprimir.imprimir;
import static Ejercicios.Leer.leerCadena;
import static Ejercicios.Leer.leerEntero;
public class Venta {
private int idVenta, flag=0;
private Inventario productos;
private final ArrayList <Producto> productosVenta = new ArrayList<>();
private ArrayList <Integer> cantidadVendida = new ArrayList<>();
Venta(Inventario productos){
this.productos = productos;
}
Venta(int id,Inventario productos){
idVenta=id;
this.productos = productos;
}
public void agregarProducto(){
String nombre;
imprimir("Los productos en inventario son los siguientes: ");
for (int i = 0; i < productos.getProductos().size(); i++) {
imprimir("%n"+productos.getProductos().get(i).getNombreProducto());
}
while (flag==0){
nombre=leerCadena("%nIngrese el nombre producto a agregar: ");
if (productos.buscarProducto(nombre)){
int indice,cantidad;
Producto producto;
indice=productos.buscarIndiceProducto(nombre);
producto=productos.getProductos().get(indice);
productosVenta.add(producto);
cantidad=leerEntero("%nIngrese la cantidad vendida de "+producto.getNombreProducto()+
": ");
cantidadVendida.add(cantidad);
productos.modificarCantidadPorVenta(indice,cantidad);
}else {
imprimir("%nNombre no valido");
flag=1;
}
}
}
public void setIdVenta(int idVenta) {
this.idVenta = idVenta;
}
public int getIdVenta() {
return idVenta;
}
public void imprimirProductosVenta(){
for (Producto producto : productosVenta){
imprimir("%n"+producto.getNombreProducto()+
": "+producto.getCantidadProducto());
}
}
}
| 2,012 | 0.599901 | 0.597913 | 61 | 31.983606 | 24.242283 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.57377 | false | false | 0 |
caafbba80345d8b566c361a86291b0373c109dc5 | 19,705,309,975,074 | 3a9caa64427cf2c29e3511adea6d671a70c3bbe3 | /com/google/android/gms/measurement/zzc.java | 1629be5fb84e57264ba404dd9908257cc786d06a | []
| no_license | DrOpossum/HAG-APP-obfuscated | https://github.com/DrOpossum/HAG-APP-obfuscated | 9590d1f77ecccd63c4f5eeec1561e9e995005f48 | f801ce550c03e6d8c78b7e01e2c6deaf39900ede | refs/heads/master | 2020-02-25T12:10:31.442000 | 2017-08-15T12:48:12 | 2017-08-15T12:48:12 | 100,375,772 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.google.android.gms.measurement;
import com.google.android.gms.common.internal.zzx;
import com.google.android.gms.internal.zzmq;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public final class zzc {
private final zzf zzaUi;
private boolean zzaUj;
private long zzaUk;
private long zzaUl;
private long zzaUm;
private long zzaUn;
private long zzaUo;
private boolean zzaUp;
private final Map<Class<? extends zze>, zze> zzaUq;
private final List<zzi> zzaUr;
private final zzmq zzqW;
zzc(zzc com_google_android_gms_measurement_zzc) {
this.zzaUi = com_google_android_gms_measurement_zzc.zzaUi;
this.zzqW = com_google_android_gms_measurement_zzc.zzqW;
this.zzaUk = com_google_android_gms_measurement_zzc.zzaUk;
this.zzaUl = com_google_android_gms_measurement_zzc.zzaUl;
this.zzaUm = com_google_android_gms_measurement_zzc.zzaUm;
this.zzaUn = com_google_android_gms_measurement_zzc.zzaUn;
this.zzaUo = com_google_android_gms_measurement_zzc.zzaUo;
this.zzaUr = new ArrayList(com_google_android_gms_measurement_zzc.zzaUr);
this.zzaUq = new HashMap(com_google_android_gms_measurement_zzc.zzaUq.size());
for (Entry entry : com_google_android_gms_measurement_zzc.zzaUq.entrySet()) {
zze zzg = zzg((Class) entry.getKey());
((zze) entry.getValue()).zza(zzg);
this.zzaUq.put(entry.getKey(), zzg);
}
}
zzc(zzf com_google_android_gms_measurement_zzf, zzmq com_google_android_gms_internal_zzmq) {
zzx.zzz(com_google_android_gms_measurement_zzf);
zzx.zzz(com_google_android_gms_internal_zzmq);
this.zzaUi = com_google_android_gms_measurement_zzf;
this.zzqW = com_google_android_gms_internal_zzmq;
this.zzaUn = 1800000;
this.zzaUo = 3024000000L;
this.zzaUq = new HashMap();
this.zzaUr = new ArrayList();
}
private static <T extends zze> T zzg(Class<T> cls) {
try {
return (zze) cls.newInstance();
} catch (Throwable e) {
throw new IllegalArgumentException("dataType doesn't have default constructor", e);
} catch (Throwable e2) {
throw new IllegalArgumentException("dataType default constructor is not accessible", e2);
}
}
final void zzAA() {
this.zzaUm = this.zzqW.elapsedRealtime();
if (this.zzaUl != 0) {
this.zzaUk = this.zzaUl;
} else {
this.zzaUk = this.zzqW.currentTimeMillis();
}
this.zzaUj = true;
}
final zzf zzAB() {
return this.zzaUi;
}
final zzg zzAC() {
return this.zzaUi.zzAC();
}
final boolean zzAD() {
return this.zzaUp;
}
final void zzAE() {
this.zzaUp = true;
}
public final zzc zzAu() {
return new zzc(this);
}
public final Collection<zze> zzAv() {
return this.zzaUq.values();
}
public final List<zzi> zzAw() {
return this.zzaUr;
}
public final long zzAx() {
return this.zzaUk;
}
public final void zzAy() {
zzAC().zze(this);
}
public final boolean zzAz() {
return this.zzaUj;
}
public final void zzM(long j) {
this.zzaUl = j;
}
public final void zzb(zze com_google_android_gms_measurement_zze) {
zzx.zzz(com_google_android_gms_measurement_zze);
Class cls = com_google_android_gms_measurement_zze.getClass();
if (cls.getSuperclass() != zze.class) {
throw new IllegalArgumentException();
}
com_google_android_gms_measurement_zze.zza(zzf(cls));
}
public final <T extends zze> T zze(Class<T> cls) {
return (zze) this.zzaUq.get(cls);
}
public final <T extends zze> T zzf(Class<T> cls) {
zze com_google_android_gms_measurement_zze = (zze) this.zzaUq.get(cls);
if (com_google_android_gms_measurement_zze != null) {
return com_google_android_gms_measurement_zze;
}
T zzg = zzg(cls);
this.zzaUq.put(cls, zzg);
return zzg;
}
}
| UTF-8 | Java | 4,275 | java | zzc.java | Java | []
| null | []
| package com.google.android.gms.measurement;
import com.google.android.gms.common.internal.zzx;
import com.google.android.gms.internal.zzmq;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public final class zzc {
private final zzf zzaUi;
private boolean zzaUj;
private long zzaUk;
private long zzaUl;
private long zzaUm;
private long zzaUn;
private long zzaUo;
private boolean zzaUp;
private final Map<Class<? extends zze>, zze> zzaUq;
private final List<zzi> zzaUr;
private final zzmq zzqW;
zzc(zzc com_google_android_gms_measurement_zzc) {
this.zzaUi = com_google_android_gms_measurement_zzc.zzaUi;
this.zzqW = com_google_android_gms_measurement_zzc.zzqW;
this.zzaUk = com_google_android_gms_measurement_zzc.zzaUk;
this.zzaUl = com_google_android_gms_measurement_zzc.zzaUl;
this.zzaUm = com_google_android_gms_measurement_zzc.zzaUm;
this.zzaUn = com_google_android_gms_measurement_zzc.zzaUn;
this.zzaUo = com_google_android_gms_measurement_zzc.zzaUo;
this.zzaUr = new ArrayList(com_google_android_gms_measurement_zzc.zzaUr);
this.zzaUq = new HashMap(com_google_android_gms_measurement_zzc.zzaUq.size());
for (Entry entry : com_google_android_gms_measurement_zzc.zzaUq.entrySet()) {
zze zzg = zzg((Class) entry.getKey());
((zze) entry.getValue()).zza(zzg);
this.zzaUq.put(entry.getKey(), zzg);
}
}
zzc(zzf com_google_android_gms_measurement_zzf, zzmq com_google_android_gms_internal_zzmq) {
zzx.zzz(com_google_android_gms_measurement_zzf);
zzx.zzz(com_google_android_gms_internal_zzmq);
this.zzaUi = com_google_android_gms_measurement_zzf;
this.zzqW = com_google_android_gms_internal_zzmq;
this.zzaUn = 1800000;
this.zzaUo = 3024000000L;
this.zzaUq = new HashMap();
this.zzaUr = new ArrayList();
}
private static <T extends zze> T zzg(Class<T> cls) {
try {
return (zze) cls.newInstance();
} catch (Throwable e) {
throw new IllegalArgumentException("dataType doesn't have default constructor", e);
} catch (Throwable e2) {
throw new IllegalArgumentException("dataType default constructor is not accessible", e2);
}
}
final void zzAA() {
this.zzaUm = this.zzqW.elapsedRealtime();
if (this.zzaUl != 0) {
this.zzaUk = this.zzaUl;
} else {
this.zzaUk = this.zzqW.currentTimeMillis();
}
this.zzaUj = true;
}
final zzf zzAB() {
return this.zzaUi;
}
final zzg zzAC() {
return this.zzaUi.zzAC();
}
final boolean zzAD() {
return this.zzaUp;
}
final void zzAE() {
this.zzaUp = true;
}
public final zzc zzAu() {
return new zzc(this);
}
public final Collection<zze> zzAv() {
return this.zzaUq.values();
}
public final List<zzi> zzAw() {
return this.zzaUr;
}
public final long zzAx() {
return this.zzaUk;
}
public final void zzAy() {
zzAC().zze(this);
}
public final boolean zzAz() {
return this.zzaUj;
}
public final void zzM(long j) {
this.zzaUl = j;
}
public final void zzb(zze com_google_android_gms_measurement_zze) {
zzx.zzz(com_google_android_gms_measurement_zze);
Class cls = com_google_android_gms_measurement_zze.getClass();
if (cls.getSuperclass() != zze.class) {
throw new IllegalArgumentException();
}
com_google_android_gms_measurement_zze.zza(zzf(cls));
}
public final <T extends zze> T zze(Class<T> cls) {
return (zze) this.zzaUq.get(cls);
}
public final <T extends zze> T zzf(Class<T> cls) {
zze com_google_android_gms_measurement_zze = (zze) this.zzaUq.get(cls);
if (com_google_android_gms_measurement_zze != null) {
return com_google_android_gms_measurement_zze;
}
T zzg = zzg(cls);
this.zzaUq.put(cls, zzg);
return zzg;
}
}
| 4,275 | 0.618246 | 0.613567 | 139 | 29.755396 | 24.603281 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.532374 | false | false | 0 |
c786f616b1ef21ad4016bd6dcd20f9f341e350e7 | 7,584,912,245,461 | d6b9495addae33d3c114240d5b50a2b0222abfb6 | /server/src/auto_test/java/feature/AutoTestEntryPoint.java | 6723e4d7f9bb53841ee57d600cf832b14ae6440f | []
| no_license | originalrusyn/novotvir | https://github.com/originalrusyn/novotvir | b63eea7f2c760aca2bfb7ebfd85dc4b4ccfd000d | 1cadc987115c9a564e1dc88fd76daa7041466dbb | refs/heads/master | 2020-06-12T13:09:44.158000 | 2015-05-08T17:00:32 | 2015-05-08T17:00:32 | 10,725,379 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package feature;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
import org.junit.runner.RunWith;
import static cucumber.api.SnippetType.CAMELCASE;
// @author: Mykhaylo Titov on 13.09.14 22:50.
@RunWith(Cucumber.class)
@CucumberOptions(
tags = "@T",
//glue = "classpath:features/registration",
features = "classpath:features",
monochrome = false,
format = "html:target/build/reports/tests/cucumber",
strict = false,
snippets = CAMELCASE)
public class AutoTestEntryPoint {
}
| UTF-8 | Java | 558 | java | AutoTestEntryPoint.java | Java | [
{
"context": "c cucumber.api.SnippetType.CAMELCASE;\n\n// @author: Mykhaylo Titov on 13.09.14 22:50.\n@RunWith(Cucumber.class)\n@Cucu",
"end": 202,
"score": 0.9998960494995117,
"start": 188,
"tag": "NAME",
"value": "Mykhaylo Titov"
}
]
| null | []
| package feature;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
import org.junit.runner.RunWith;
import static cucumber.api.SnippetType.CAMELCASE;
// @author: <NAME> on 13.09.14 22:50.
@RunWith(Cucumber.class)
@CucumberOptions(
tags = "@T",
//glue = "classpath:features/registration",
features = "classpath:features",
monochrome = false,
format = "html:target/build/reports/tests/cucumber",
strict = false,
snippets = CAMELCASE)
public class AutoTestEntryPoint {
}
| 550 | 0.695341 | 0.677419 | 20 | 26.9 | 17.334648 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.55 | false | false | 0 |
6db38ec0237d9cc21fc2562100a0c90d39ced373 | 27,839,978,061,818 | 74360ddb842727175e67027b194d1c1e12ab3b8b | /app/src/main/java/com/yy/doorplate/adapter/StudentNewCXXKAdapter.java | 35027d2acfdd5d539a6e00ca3c0a9a2d950f43ea | []
| no_license | xumingda/Doorplate_6 | https://github.com/xumingda/Doorplate_6 | 2effad18d4824e23378b304cdb7ba59e8b5dbdf2 | 03b8ad3c6b685128014cfd53bfd62e24ac36d260 | refs/heads/master | 2020-07-04T11:10:31.247000 | 2019-08-14T04:46:42 | 2019-08-14T04:46:42 | 202,265,838 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.yy.doorplate.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.yy.doorplate.R;
import com.yy.doorplate.model.StudentInfoModel;
import java.util.List;
public class StudentNewCXXKAdapter extends BaseAdapter{
private String TAG="ShowAdapter";
private List<StudentInfoModel> studentInfoModelList;
private Context mContext;
public StudentNewCXXKAdapter(Context context, List<StudentInfoModel> studentInfoModelList){
mContext=context;
this.studentInfoModelList=studentInfoModelList;
}
public void setDate(List<StudentInfoModel> studentInfoModelList){
this.studentInfoModelList=studentInfoModelList;
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return studentInfoModelList.get(arg0);
}
@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int pos, View view, ViewGroup arg2) {
// TODO Auto-generated method stub
ViewHolder vh;
if (view == null) {
view = LayoutInflater.from(mContext).inflate(R.layout.new_cx_item_attend_student, null);
vh = new ViewHolder();
vh.txt_item_attend = (TextView) view.findViewById(R.id.txt_item_attend);
view.setTag(vh);
} else {
vh = (ViewHolder) view.getTag();
}
StudentInfoModel studentInfoModel=studentInfoModelList.get(pos);
vh.txt_item_attend.setText(studentInfoModel.xm);
return view;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return studentInfoModelList.size() ;
}
class ViewHolder {
TextView txt_item_attend;
}
}
| UTF-8 | Java | 1,955 | java | StudentNewCXXKAdapter.java | Java | []
| null | []
| package com.yy.doorplate.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.yy.doorplate.R;
import com.yy.doorplate.model.StudentInfoModel;
import java.util.List;
public class StudentNewCXXKAdapter extends BaseAdapter{
private String TAG="ShowAdapter";
private List<StudentInfoModel> studentInfoModelList;
private Context mContext;
public StudentNewCXXKAdapter(Context context, List<StudentInfoModel> studentInfoModelList){
mContext=context;
this.studentInfoModelList=studentInfoModelList;
}
public void setDate(List<StudentInfoModel> studentInfoModelList){
this.studentInfoModelList=studentInfoModelList;
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return studentInfoModelList.get(arg0);
}
@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int pos, View view, ViewGroup arg2) {
// TODO Auto-generated method stub
ViewHolder vh;
if (view == null) {
view = LayoutInflater.from(mContext).inflate(R.layout.new_cx_item_attend_student, null);
vh = new ViewHolder();
vh.txt_item_attend = (TextView) view.findViewById(R.id.txt_item_attend);
view.setTag(vh);
} else {
vh = (ViewHolder) view.getTag();
}
StudentInfoModel studentInfoModel=studentInfoModelList.get(pos);
vh.txt_item_attend.setText(studentInfoModel.xm);
return view;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return studentInfoModelList.size() ;
}
class ViewHolder {
TextView txt_item_attend;
}
}
| 1,955 | 0.677238 | 0.67468 | 73 | 25.780823 | 24.216629 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.452055 | false | false | 0 |
7bec75ed8a436c3eb61fcaa3c56ce6f25e00805d | 9,929,964,418,004 | 9fe2dc694a8a6f9a426c6b424ef20b62b11e7e4e | /src/TrainingProjects/scanner/Scan.java | c90558e005cc6f43c9ace74084a9c96631406bdf | []
| no_license | 3888/JavaTrainingProjects | https://github.com/3888/JavaTrainingProjects | e6c600cc164737c681a04bfb035852ec90682e84 | 3f21c7b31cbb42c40a52bbaaa892ddff5c192747 | refs/heads/master | 2021-10-27T14:54:04.454000 | 2020-05-13T16:43:02 | 2020-05-13T16:43:02 | 77,374,206 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package TrainingProjects.scanner;
import java.util.*;
public class Scan {
int x;
public void Scan() {
System.out.println("Если Майкл весит");
Scanner scan = new Scanner(System.in);
x = scan.nextInt();
System.out.println("Тогда Джордж весит " + (x + 1) + " кг");
}
}
| UTF-8 | Java | 313 | java | Scan.java | Java | [
{
"context": "\n\n\tpublic void Scan() {\n\t\tSystem.out.println(\"Если Майкл весит\");\n\t\tScanner scan = new Scanner(System.in);",
"end": 138,
"score": 0.9704433679580688,
"start": 133,
"tag": "NAME",
"value": "Майкл"
}
]
| null | []
| package TrainingProjects.scanner;
import java.util.*;
public class Scan {
int x;
public void Scan() {
System.out.println("Если Майкл весит");
Scanner scan = new Scanner(System.in);
x = scan.nextInt();
System.out.println("Тогда Джордж весит " + (x + 1) + " кг");
}
}
| 313 | 0.654804 | 0.651246 | 15 | 17.733334 | 18.53813 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.2 | false | false | 0 |
cb6338d807ee2b0554ca5f790e8f837178632a83 | 26,766,236,199,145 | 30f3a18086c19c4e847c09fc3da8f597436338f1 | /Chapter 2/chapter2/src/org/pepi/chapter2/Zad5.java | e574c75b811885368b4e0d0e57df804c0a1f2add | []
| no_license | pepiii/Other | https://github.com/pepiii/Other | 8e53f47bfc05e730e7e7e4bfff045588b4c5c5d8 | 17c03da395588a7bcfa509709058cba2e421ffe1 | refs/heads/master | 2020-04-09T14:54:59.523000 | 2018-12-22T10:27:06 | 2018-12-22T10:27:06 | 160,411,093 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.pepi.chapter2;
public class Zad5 {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = "World";
Object o = s1 + " " + s2;
System.out.println(o);
String finals = (String) o;
}
}
| UTF-8 | Java | 241 | java | Zad5.java | Java | [
{
"context": "atic void main(String[] args) {\n\t\t\n\t\tString s1 = \"Hello\";\n\t\tString s2 = \"World\";\n\t\t\n\t\tObject o = s1 + \" \"",
"end": 114,
"score": 0.8153178095817566,
"start": 109,
"tag": "NAME",
"value": "Hello"
},
{
"context": " args) {\n\t\t\n\t\tString s1 = \"Hello\";\n\t\tString s2 = \"World\";\n\t\t\n\t\tObject o = s1 + \" \" + s2;\n\t\tSystem.out.pri",
"end": 137,
"score": 0.8862756490707397,
"start": 132,
"tag": "NAME",
"value": "World"
}
]
| null | []
| package org.pepi.chapter2;
public class Zad5 {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = "World";
Object o = s1 + " " + s2;
System.out.println(o);
String finals = (String) o;
}
}
| 241 | 0.580913 | 0.556017 | 18 | 12.388889 | 13.111229 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.555556 | false | false | 15 |
928d59b490c87daba762fb7d6813818327fe3c0c | 31,009,663,935,663 | e9df688ef76e5cd4545fdd66f2a37f241da96331 | /src/main/java/br/com/is/View/Equipe_view.java | 74793a954fadfe39241d05e85caba34ad9e73cd5 | []
| no_license | rsportella/iipdesk | https://github.com/rsportella/iipdesk | fb328db2659405cc804849fefb78b46b728c0222 | 3ddf4f125a097a4e242352d85bc1a1605a4debc3 | refs/heads/master | 2021-08-24T09:03:27.275000 | 2017-12-08T23:33:13 | 2017-12-08T23:33:13 | 106,038,109 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.is.View;
import br.com.is.DAO.Generico;
import br.com.is.Entitys.Equipe;
import br.com.is.DAO.GenericoDAO;
import br.com.is.DAO.QueryCriteria;
import br.com.is.DAO.ServicoDAO;
import br.com.is.Entitys.Pessoa;
import br.com.is.Entitys.Servico;
import static br.com.is.View.JanelaPrincipal.jDesktopPane;
import br.com.is.utils.Formatacao;
import br.com.is.utils.Support;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
public class Equipe_view extends javax.swing.JInternalFrame {
Equipe eq = new Equipe();
public static Pessoa ps = new Pessoa();
public Equipe_view() {
initComponents();
resetField();
}
public Equipe_view(Pessoa ps) {
initComponents();
this.ps = ps;
ftfCpf.setText(ps.getCpf());
tfdNome.setText(ps.getNome());
}
public Equipe_view(Equipe equ) {
initComponents();
this.eq = equ;
Formatacao.reformatarCpf(ftfCpf);
tfdCodigo.setText(String.valueOf(this.eq.getCodigo()));
tfdTitulo.setText(this.eq.getTitulo());
txaDescricao.setText(this.eq.getDescricao());
ftfCpf.setText(this.eq.getResponsavel().getCpf());
tfdNome.setText(this.eq.getResponsavel().getNome());
new ServicoDAO(new Servico()).PopulaTabela(tblServicos, equ);
btnAdicionar.setEnabled(true);
btnEditar.setEnabled(true);
}
private void resetField() {
tfdCodigo.setText(String.valueOf(new GenericoDAO<Equipe>(eq).ProximoCodigo()));
tfdTitulo.setText("");
txaDescricao.setText("");
tfdNome.setText("");
ftfCpf.setText("");
Formatacao.reformatarCpf(ftfCpf);
btnAdicionar.setEnabled(false);
btnEditar.setEnabled(false);
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel2 = new javax.swing.JPanel();
background = new javax.swing.JPanel();
jTabbedPane1 = new javax.swing.JTabbedPane();
jPanel1 = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
tblServicos = new javax.swing.JTable();
btnAdicionar = new javax.swing.JButton();
btnEditar = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
tfdNome = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
tfdCodigo = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
tfdTitulo = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
txaDescricao = new javax.swing.JTextArea();
ftfCpf = new javax.swing.JFormattedTextField();
btnLocalizar = new javax.swing.JButton();
btnSalvar = new javax.swing.JButton();
btnSair = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
setTitle("Equipe");
tblServicos.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
}
));
jScrollPane2.setViewportView(tblServicos);
btnAdicionar.setText("Adicionar");
btnAdicionar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAdicionarActionPerformed(evt);
}
});
btnEditar.setText("Editar");
btnEditar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnEditarActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 455, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(btnAdicionar)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnEditar)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 172, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnAdicionar)
.addComponent(btnEditar))
.addContainerGap())
);
jTabbedPane1.addTab("Serviços", jPanel1);
jLabel4.setText("Responsável");
tfdNome.setOpaque(false);
jLabel2.setText("Código");
tfdCodigo.setEditable(false);
jLabel1.setText("Título *");
jLabel3.setText("Descrição");
txaDescricao.setColumns(20);
txaDescricao.setRows(5);
jScrollPane1.setViewportView(txaDescricao);
ftfCpf.setOpaque(false);
btnLocalizar.setText("Localizar");
btnLocalizar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLocalizarActionPerformed(evt);
}
});
btnSalvar.setText("Salvar");
btnSalvar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSalvarActionPerformed(evt);
}
});
btnSair.setText("Fechar");
btnSair.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSairActionPerformed(evt);
}
});
jButton3.setText("Listar");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
javax.swing.GroupLayout backgroundLayout = new javax.swing.GroupLayout(background);
background.setLayout(backgroundLayout);
backgroundLayout.setHorizontalGroup(
backgroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(backgroundLayout.createSequentialGroup()
.addContainerGap()
.addGroup(backgroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTabbedPane1, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane1)
.addComponent(tfdTitulo)
.addGroup(backgroundLayout.createSequentialGroup()
.addComponent(ftfCpf, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(tfdNome)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnLocalizar))
.addGroup(backgroundLayout.createSequentialGroup()
.addGroup(backgroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(tfdCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1)
.addComponent(jLabel3)
.addComponent(jLabel4)
.addGroup(backgroundLayout.createSequentialGroup()
.addComponent(btnSalvar)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnSair)))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
backgroundLayout.setVerticalGroup(
backgroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(backgroundLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tfdCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tfdTitulo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(backgroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(tfdNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(ftfCpf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnLocalizar))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jTabbedPane1)
.addGap(11, 11, 11)
.addGroup(backgroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnSair)
.addComponent(btnSalvar)
.addComponent(jButton3))
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(background, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(background, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSairActionPerformed
dispose();
}//GEN-LAST:event_btnSairActionPerformed
private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarActionPerformed
eq.setTitulo(tfdTitulo.getText());
eq.setDescricao(txaDescricao.getText());
eq.setResponsavel(this.ps);
btnAdicionar.setEnabled(true);
new Generico<Equipe>(eq).Gravar();
}//GEN-LAST:event_btnSalvarActionPerformed
private void btnLocalizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLocalizarActionPerformed
Pessoa_listar_view peliv = new Pessoa_listar_view("equipe");
Support.centralizar(jDesktopPane.add(peliv));
peliv.setVisible(true);
}//GEN-LAST:event_btnLocalizarActionPerformed
private void btnEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditarActionPerformed
if (tblServicos.getSelectedRow() != -1) {
List<QueryCriteria> criterias = new ArrayList<QueryCriteria>();
criterias.add(new QueryCriteria("equal", "codigo", String.valueOf(tblServicos.getValueAt(tblServicos.getSelectedRow(), 0))));
Servico srv = new Generico<Servico>(new Servico()).Visualizar(criterias);
Servico_view serv = new Servico_view(eq, srv);
Support.centralizar(JanelaPrincipal.jDesktopPane.add(serv));
serv.setVisible(true);
} else {
JOptionPane.showMessageDialog(null, "Uma linha da tabela deve estar selecionada para efetuar a ação!");
}
}//GEN-LAST:event_btnEditarActionPerformed
private void btnAdicionarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAdicionarActionPerformed
Servico_view serv = new Servico_view(eq);
Support.centralizar(JanelaPrincipal.jDesktopPane.add(serv));
serv.setVisible(true);
}//GEN-LAST:event_btnAdicionarActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
Equipe_listar_view serlisv = new Equipe_listar_view();
Support.centralizar(JanelaPrincipal.jDesktopPane.add(serlisv));
serlisv.setVisible(true);
dispose();
}//GEN-LAST:event_jButton3ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel background;
private javax.swing.JButton btnAdicionar;
private javax.swing.JButton btnEditar;
private javax.swing.JButton btnLocalizar;
private javax.swing.JButton btnSair;
private javax.swing.JButton btnSalvar;
public static javax.swing.JFormattedTextField ftfCpf;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTabbedPane jTabbedPane1;
public static javax.swing.JTable tblServicos;
private javax.swing.JTextField tfdCodigo;
public static javax.swing.JTextField tfdNome;
private javax.swing.JTextField tfdTitulo;
private javax.swing.JTextArea txaDescricao;
// End of variables declaration//GEN-END:variables
}
| UTF-8 | Java | 16,394 | java | Equipe_view.java | Java | []
| null | []
| package br.com.is.View;
import br.com.is.DAO.Generico;
import br.com.is.Entitys.Equipe;
import br.com.is.DAO.GenericoDAO;
import br.com.is.DAO.QueryCriteria;
import br.com.is.DAO.ServicoDAO;
import br.com.is.Entitys.Pessoa;
import br.com.is.Entitys.Servico;
import static br.com.is.View.JanelaPrincipal.jDesktopPane;
import br.com.is.utils.Formatacao;
import br.com.is.utils.Support;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
public class Equipe_view extends javax.swing.JInternalFrame {
Equipe eq = new Equipe();
public static Pessoa ps = new Pessoa();
public Equipe_view() {
initComponents();
resetField();
}
public Equipe_view(Pessoa ps) {
initComponents();
this.ps = ps;
ftfCpf.setText(ps.getCpf());
tfdNome.setText(ps.getNome());
}
public Equipe_view(Equipe equ) {
initComponents();
this.eq = equ;
Formatacao.reformatarCpf(ftfCpf);
tfdCodigo.setText(String.valueOf(this.eq.getCodigo()));
tfdTitulo.setText(this.eq.getTitulo());
txaDescricao.setText(this.eq.getDescricao());
ftfCpf.setText(this.eq.getResponsavel().getCpf());
tfdNome.setText(this.eq.getResponsavel().getNome());
new ServicoDAO(new Servico()).PopulaTabela(tblServicos, equ);
btnAdicionar.setEnabled(true);
btnEditar.setEnabled(true);
}
private void resetField() {
tfdCodigo.setText(String.valueOf(new GenericoDAO<Equipe>(eq).ProximoCodigo()));
tfdTitulo.setText("");
txaDescricao.setText("");
tfdNome.setText("");
ftfCpf.setText("");
Formatacao.reformatarCpf(ftfCpf);
btnAdicionar.setEnabled(false);
btnEditar.setEnabled(false);
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel2 = new javax.swing.JPanel();
background = new javax.swing.JPanel();
jTabbedPane1 = new javax.swing.JTabbedPane();
jPanel1 = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
tblServicos = new javax.swing.JTable();
btnAdicionar = new javax.swing.JButton();
btnEditar = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
tfdNome = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
tfdCodigo = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
tfdTitulo = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
txaDescricao = new javax.swing.JTextArea();
ftfCpf = new javax.swing.JFormattedTextField();
btnLocalizar = new javax.swing.JButton();
btnSalvar = new javax.swing.JButton();
btnSair = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
setTitle("Equipe");
tblServicos.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
}
));
jScrollPane2.setViewportView(tblServicos);
btnAdicionar.setText("Adicionar");
btnAdicionar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAdicionarActionPerformed(evt);
}
});
btnEditar.setText("Editar");
btnEditar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnEditarActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 455, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(btnAdicionar)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnEditar)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 172, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnAdicionar)
.addComponent(btnEditar))
.addContainerGap())
);
jTabbedPane1.addTab("Serviços", jPanel1);
jLabel4.setText("Responsável");
tfdNome.setOpaque(false);
jLabel2.setText("Código");
tfdCodigo.setEditable(false);
jLabel1.setText("Título *");
jLabel3.setText("Descrição");
txaDescricao.setColumns(20);
txaDescricao.setRows(5);
jScrollPane1.setViewportView(txaDescricao);
ftfCpf.setOpaque(false);
btnLocalizar.setText("Localizar");
btnLocalizar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLocalizarActionPerformed(evt);
}
});
btnSalvar.setText("Salvar");
btnSalvar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSalvarActionPerformed(evt);
}
});
btnSair.setText("Fechar");
btnSair.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSairActionPerformed(evt);
}
});
jButton3.setText("Listar");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
javax.swing.GroupLayout backgroundLayout = new javax.swing.GroupLayout(background);
background.setLayout(backgroundLayout);
backgroundLayout.setHorizontalGroup(
backgroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(backgroundLayout.createSequentialGroup()
.addContainerGap()
.addGroup(backgroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTabbedPane1, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane1)
.addComponent(tfdTitulo)
.addGroup(backgroundLayout.createSequentialGroup()
.addComponent(ftfCpf, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(tfdNome)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnLocalizar))
.addGroup(backgroundLayout.createSequentialGroup()
.addGroup(backgroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(tfdCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1)
.addComponent(jLabel3)
.addComponent(jLabel4)
.addGroup(backgroundLayout.createSequentialGroup()
.addComponent(btnSalvar)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnSair)))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
backgroundLayout.setVerticalGroup(
backgroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(backgroundLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tfdCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tfdTitulo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(backgroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(tfdNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(ftfCpf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnLocalizar))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jTabbedPane1)
.addGap(11, 11, 11)
.addGroup(backgroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnSair)
.addComponent(btnSalvar)
.addComponent(jButton3))
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(background, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(background, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSairActionPerformed
dispose();
}//GEN-LAST:event_btnSairActionPerformed
private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarActionPerformed
eq.setTitulo(tfdTitulo.getText());
eq.setDescricao(txaDescricao.getText());
eq.setResponsavel(this.ps);
btnAdicionar.setEnabled(true);
new Generico<Equipe>(eq).Gravar();
}//GEN-LAST:event_btnSalvarActionPerformed
private void btnLocalizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLocalizarActionPerformed
Pessoa_listar_view peliv = new Pessoa_listar_view("equipe");
Support.centralizar(jDesktopPane.add(peliv));
peliv.setVisible(true);
}//GEN-LAST:event_btnLocalizarActionPerformed
private void btnEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditarActionPerformed
if (tblServicos.getSelectedRow() != -1) {
List<QueryCriteria> criterias = new ArrayList<QueryCriteria>();
criterias.add(new QueryCriteria("equal", "codigo", String.valueOf(tblServicos.getValueAt(tblServicos.getSelectedRow(), 0))));
Servico srv = new Generico<Servico>(new Servico()).Visualizar(criterias);
Servico_view serv = new Servico_view(eq, srv);
Support.centralizar(JanelaPrincipal.jDesktopPane.add(serv));
serv.setVisible(true);
} else {
JOptionPane.showMessageDialog(null, "Uma linha da tabela deve estar selecionada para efetuar a ação!");
}
}//GEN-LAST:event_btnEditarActionPerformed
private void btnAdicionarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAdicionarActionPerformed
Servico_view serv = new Servico_view(eq);
Support.centralizar(JanelaPrincipal.jDesktopPane.add(serv));
serv.setVisible(true);
}//GEN-LAST:event_btnAdicionarActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
Equipe_listar_view serlisv = new Equipe_listar_view();
Support.centralizar(JanelaPrincipal.jDesktopPane.add(serlisv));
serlisv.setVisible(true);
dispose();
}//GEN-LAST:event_jButton3ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel background;
private javax.swing.JButton btnAdicionar;
private javax.swing.JButton btnEditar;
private javax.swing.JButton btnLocalizar;
private javax.swing.JButton btnSair;
private javax.swing.JButton btnSalvar;
public static javax.swing.JFormattedTextField ftfCpf;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTabbedPane jTabbedPane1;
public static javax.swing.JTable tblServicos;
private javax.swing.JTextField tfdCodigo;
public static javax.swing.JTextField tfdNome;
private javax.swing.JTextField tfdTitulo;
private javax.swing.JTextArea txaDescricao;
// End of variables declaration//GEN-END:variables
}
| 16,394 | 0.658306 | 0.651715 | 353 | 45.419262 | 33.946548 | 161 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.597734 | false | false | 15 |
1ee897df67ded74bb05092c0d1280fe975f367c1 | 8,297,876,817,390 | e6f4ca4d79ca54d3ff3e9b0355b8f5ced8bcd59b | /src/main/java/com/tei/view/menu/OptionsMenu.java | 4895a3de884b392576736ef9181297d476ec1441 | [
"MIT"
]
| permissive | DimMilios/sudoku | https://github.com/DimMilios/sudoku | 7ade68c0f4e3b403a896cdb0e3735a2c06a49948 | 49a23396431ed37497a4c1df1d1fa5e0b7907a38 | refs/heads/main | 2023-03-05T08:31:19.837000 | 2021-02-07T09:58:17 | 2021-02-07T09:58:17 | 329,284,286 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tei.view.menu;
import com.tei.model.SudokuConstants;
import com.tei.view.MainView;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class OptionsMenu extends JMenu {
private final MainView mainView;
private JMenu historySubMenu;
private JMenuItem showHistory;
private JMenuItem hideHistory;
public OptionsMenu(String name, MainView mainView) {
super(name);
this.mainView = mainView;
init();
}
private void init() {
historySubMenu = new JMenu("History");
showHistory = new JMenuItem("Show History");
showHistory.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
mainView.pushRoute(SudokuConstants.HISTORY_PANEL);
}
});
hideHistory = new JMenuItem("Hide History");
hideHistory.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
mainView.pushRoute(SudokuConstants.GAME_PANEL);
}
});
historySubMenu.add(showHistory);
historySubMenu.add(hideHistory);
this.add(historySubMenu);
}
}
| UTF-8 | Java | 1,100 | java | OptionsMenu.java | Java | []
| null | []
| package com.tei.view.menu;
import com.tei.model.SudokuConstants;
import com.tei.view.MainView;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class OptionsMenu extends JMenu {
private final MainView mainView;
private JMenu historySubMenu;
private JMenuItem showHistory;
private JMenuItem hideHistory;
public OptionsMenu(String name, MainView mainView) {
super(name);
this.mainView = mainView;
init();
}
private void init() {
historySubMenu = new JMenu("History");
showHistory = new JMenuItem("Show History");
showHistory.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
mainView.pushRoute(SudokuConstants.HISTORY_PANEL);
}
});
hideHistory = new JMenuItem("Hide History");
hideHistory.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
mainView.pushRoute(SudokuConstants.GAME_PANEL);
}
});
historySubMenu.add(showHistory);
historySubMenu.add(hideHistory);
this.add(historySubMenu);
}
}
| 1,100 | 0.750909 | 0.750909 | 45 | 23.444445 | 18.824989 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.866667 | false | false | 15 |
1499f9fa685cde26687a73d2e2bcd7ac79fcc2d2 | 14,800,457,302,714 | 0af8b92686a58eb0b64e319b22411432aca7a8f3 | /large-multiproject/project34/src/main/java/org/gradle/test/performance34_4/Production34_388.java | cfa73c122c8a906c1601eb27ee07062303ce94eb | []
| no_license | gradle/performance-comparisons | https://github.com/gradle/performance-comparisons | b0d38db37c326e0ce271abebdb3c91769b860799 | e53dc7182fafcf9fedf07920cbbea8b40ee4eef4 | refs/heads/master | 2023-08-14T19:24:39.164000 | 2022-11-24T05:18:33 | 2022-11-24T05:18:33 | 80,121,268 | 17 | 15 | null | false | 2022-09-30T08:04:35 | 2017-01-26T14:25:33 | 2022-09-09T14:38:38 | 2022-09-30T08:04:34 | 19,731 | 14 | 13 | 103 | null | false | false | package org.gradle.test.performance34_4;
public class Production34_388 extends org.gradle.test.performance13_4.Production13_388 {
private final String property;
public Production34_388() {
this.property = "foo";
}
public String getProperty() {
return property;
}
}
| UTF-8 | Java | 305 | java | Production34_388.java | Java | []
| null | []
| package org.gradle.test.performance34_4;
public class Production34_388 extends org.gradle.test.performance13_4.Production13_388 {
private final String property;
public Production34_388() {
this.property = "foo";
}
public String getProperty() {
return property;
}
}
| 305 | 0.681967 | 0.613115 | 14 | 20.785715 | 23.946901 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 15 |
ec951de56ceee3af0b88ecda6b791f4df5c6367f | 6,786,048,384,064 | b443ba8010bc0f7308ff6a7d8c6141f93cfd6f0e | /drp-web/src/main/java/com/yootk/drp/vo/CrItem.java | ebf4daf4f31144dfc9cc506250422fe3e0177b59 | []
| no_license | hanzhongao/drp | https://github.com/hanzhongao/drp | 86e3fba3da72635945f964c0a3752197a63004c0 | bf32f1ce571dd6e23aa364e9c3b258220a7b9fd3 | refs/heads/master | 2022-06-24T08:09:01.313000 | 2019-06-01T13:33:32 | 2019-06-01T13:33:32 | 189,684,640 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.yootk.drp.vo;
import java.io.Serializable;
public class CrItem implements Serializable {
private Long crrid;
private String title;
public CrItem(){}
public Long getCrrid() {
return crrid;
}
public void setCrrid(Long crrid) {
this.crrid = crrid;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public String toString() {
return "CrItem{" +
"crrid=" + crrid +
", title='" + title + '\'' +
'}';
}
}
| UTF-8 | Java | 626 | java | CrItem.java | Java | []
| null | []
| package com.yootk.drp.vo;
import java.io.Serializable;
public class CrItem implements Serializable {
private Long crrid;
private String title;
public CrItem(){}
public Long getCrrid() {
return crrid;
}
public void setCrrid(Long crrid) {
this.crrid = crrid;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public String toString() {
return "CrItem{" +
"crrid=" + crrid +
", title='" + title + '\'' +
'}';
}
}
| 626 | 0.531949 | 0.531949 | 34 | 17.411764 | 14.503788 | 45 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.294118 | false | false | 15 |
370da38f7740a74b3d14260cc7792be4dfc6482d | 33,474,975,117,522 | 3512c54189b762f54e95ff3b4e00d389b414ff45 | /src/main/java/ro/msg/learning/entity/Customer.java | b70e8c6ed8c85514f741acfd3358cf2364d3830f | []
| no_license | raduvd/shop | https://github.com/raduvd/shop | 11ddc94c1670c68d4156b6cd7bd73a43dc995bb3 | bff3cc10416371385e50544a1ebfa164ff8cb26d | refs/heads/master | 2020-04-24T03:07:28.846000 | 2019-03-28T14:24:19 | 2019-03-28T14:24:19 | 171,660,554 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ro.msg.learning.entity;
import lombok.Data;
import javax.persistence.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* Created by vancer at 2/12/2019
*/
@Data
@Entity(name = "CUSTOMER")
public class Customer implements Serializable {
@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "customer_sequence")
@SequenceGenerator(name = "customer_sequence", sequenceName = "customer_sequence", allocationSize = 1, initialValue = 1000)
private Long id;
@Column(name = "FIRST_NAME", nullable = false, length = 50)
private String firstName;
@Column(name = "LAST_NAME", nullable = false, length = 50)
private String lastName;
@Column(name = "USER_NAME", nullable = false, length = 50)
private String username;
@OneToMany(mappedBy = "customer")
private List<Order> orderList = new ArrayList<>();
}
| UTF-8 | Java | 935 | java | Customer.java | Java | [
{
"context": "rayList;\nimport java.util.List;\n\n/**\n * Created by vancer at 2/12/2019\n */\n@Data\n@Entity(name = \"CUSTOMER\")",
"end": 187,
"score": 0.9992614984512329,
"start": 181,
"tag": "USERNAME",
"value": "vancer"
}
]
| null | []
| package ro.msg.learning.entity;
import lombok.Data;
import javax.persistence.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* Created by vancer at 2/12/2019
*/
@Data
@Entity(name = "CUSTOMER")
public class Customer implements Serializable {
@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "customer_sequence")
@SequenceGenerator(name = "customer_sequence", sequenceName = "customer_sequence", allocationSize = 1, initialValue = 1000)
private Long id;
@Column(name = "FIRST_NAME", nullable = false, length = 50)
private String firstName;
@Column(name = "LAST_NAME", nullable = false, length = 50)
private String lastName;
@Column(name = "USER_NAME", nullable = false, length = 50)
private String username;
@OneToMany(mappedBy = "customer")
private List<Order> orderList = new ArrayList<>();
}
| 935 | 0.697326 | 0.678075 | 34 | 26.5 | 28.408005 | 127 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.617647 | false | false | 15 |
a3e18a91d9e383eb65c0c91c042e964752144357 | 10,299,331,630,635 | a8e043315e3a5879fbd480bdf17b7698f9f07618 | /boot/src/controller/lecture/LectureLikeController.java | 878d33d0f5fc7ba04e33f5dba95317bcefad1321 | []
| no_license | newapache/project_outsiderHelper | https://github.com/newapache/project_outsiderHelper | c18fcc5bd1f6f3f22f430b05c7f1704804f3b350 | fe372d0d47f957e8b71dff2b8bba0018170f4d52 | refs/heads/master | 2022-12-05T08:46:55.574000 | 2020-03-03T08:28:16 | 2020-03-03T08:28:16 | 225,832,741 | 1 | 0 | null | false | 2022-12-05T02:59:58 | 2019-12-04T09:48:11 | 2020-03-03T08:28:20 | 2022-12-05T02:59:58 | 32,189 | 0 | 0 | 29 | Java | false | false | package controller.lecture;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import controller.Controller;
import model.service.LectureManager;
import model.service.LikeManager;
public class LectureLikeController implements Controller{
private static final Logger log = LoggerFactory.getLogger(LectureDeleteController.class);
@Override
public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
// String userId = request.getParameter("userId");
String likeId = request.getParameter("likeId");
log.debug("like : {}", likeId);
LectureManager lecturemanager = LectureManager.getInstance();
LikeManager likeManager = LikeManager.getInstance();
String userId ="0";
int result = likeManager.like(userId, likeId); // 0이면 중복
int result2 = 1;
if(result != 0)
result2 = lecturemanager.like(likeId);
request.setAttribute("likeresult", result);
request.setAttribute("likeresult2", result2);
return "/lecture_board/list";
}
}
| UTF-8 | Java | 1,188 | java | LectureLikeController.java | Java | []
| null | []
| package controller.lecture;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import controller.Controller;
import model.service.LectureManager;
import model.service.LikeManager;
public class LectureLikeController implements Controller{
private static final Logger log = LoggerFactory.getLogger(LectureDeleteController.class);
@Override
public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
// String userId = request.getParameter("userId");
String likeId = request.getParameter("likeId");
log.debug("like : {}", likeId);
LectureManager lecturemanager = LectureManager.getInstance();
LikeManager likeManager = LikeManager.getInstance();
String userId ="0";
int result = likeManager.like(userId, likeId); // 0이면 중복
int result2 = 1;
if(result != 0)
result2 = lecturemanager.like(likeId);
request.setAttribute("likeresult", result);
request.setAttribute("likeresult2", result2);
return "/lecture_board/list";
}
}
| 1,188 | 0.720339 | 0.711864 | 40 | 28.5 | 26.28878 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.35 | false | false | 15 |
a8e3c714a612185f065f3225928f5e97e0b70490 | 8,426,725,901,013 | d232615f64a98ca944d9a8cd15aa100b1529a05a | /app/src/main/java/com/example/lenovo/myapplication/zhibochinafragments/Huangshan.java | 3b41c1aed7702702a20efb7859cf1baf1541db76 | []
| no_license | 328164246/xongmao | https://github.com/328164246/xongmao | 0cb148063d418fd7a8b1c6c94d265b2f332278f1 | 3a6e515b16e666de864760edf36ef415a1af7551 | refs/heads/master | 2021-05-07T01:14:14.246000 | 2017-11-27T05:26:48 | 2017-11-27T05:26:48 | 110,224,628 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.lenovo.myapplication.zhibochinafragments;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.example.lenovo.myapplication.R;
import com.example.lenovo.myapplication.adapters.fu_Adapter;
import com.example.lenovo.myapplication.beans.Hangshan;
import com.example.lenovo.myapplication.eventbus.Mes;
import com.example.lenovo.myapplication.utils.VolleyUtils;
import com.google.gson.Gson;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Lenovo on 2017/11/9.
*/
public class Huangshan extends Fragment {
private ListView lv_listview;
private List<Hangshan.LiveBean> list = new ArrayList<>();
private fu_Adapter fu_adapter;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View inflate = inflater.inflate(R.layout.listview, container, false);
lv_listview = inflate.findViewById(R.id.lv_listview);
EventBus.getDefault().register(this);
return inflate;
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void get(Mes s) {
String sy = s.getSy();
VolleyUtils.getInstance(getActivity()).get(sy, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
String s1 = response.toString();
Hangshan hangshan = new Gson().fromJson(s1, Hangshan.class);
List<Hangshan.LiveBean> live = hangshan.getLive();
fu_adapter = new fu_Adapter(live, getActivity());
lv_listview.setAdapter(fu_adapter);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("TAG", error.toString());
}
});
}
@Override
public void onPause() {
super.onPause();
EventBus.getDefault().unregister(this);
}
}
| UTF-8 | Java | 2,403 | java | Huangshan.java | Java | []
| null | []
| package com.example.lenovo.myapplication.zhibochinafragments;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.example.lenovo.myapplication.R;
import com.example.lenovo.myapplication.adapters.fu_Adapter;
import com.example.lenovo.myapplication.beans.Hangshan;
import com.example.lenovo.myapplication.eventbus.Mes;
import com.example.lenovo.myapplication.utils.VolleyUtils;
import com.google.gson.Gson;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Lenovo on 2017/11/9.
*/
public class Huangshan extends Fragment {
private ListView lv_listview;
private List<Hangshan.LiveBean> list = new ArrayList<>();
private fu_Adapter fu_adapter;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View inflate = inflater.inflate(R.layout.listview, container, false);
lv_listview = inflate.findViewById(R.id.lv_listview);
EventBus.getDefault().register(this);
return inflate;
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void get(Mes s) {
String sy = s.getSy();
VolleyUtils.getInstance(getActivity()).get(sy, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
String s1 = response.toString();
Hangshan hangshan = new Gson().fromJson(s1, Hangshan.class);
List<Hangshan.LiveBean> live = hangshan.getLive();
fu_adapter = new fu_Adapter(live, getActivity());
lv_listview.setAdapter(fu_adapter);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("TAG", error.toString());
}
});
}
@Override
public void onPause() {
super.onPause();
EventBus.getDefault().unregister(this);
}
}
| 2,403 | 0.688722 | 0.684561 | 80 | 29.012501 | 25.361139 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 15 |
a4f00ead526a65d2dcb8746a147dd308db8a781e | 36,009,005,811,754 | 0e2655ed40e4cb110532e960a5f030a28e46b510 | /src/main/java/VirtualPetApp.java | 9595dba9c72488e9148f78565d2355ae49a94b84 | []
| no_license | maulikmpatel/virtual-pet | https://github.com/maulikmpatel/virtual-pet | 17e9c35ea414abef6f54a349e37ea7024d950cf3 | 880deae44ad4af52d038c57a064aaab64804a58f | refs/heads/master | 2020-03-18T14:44:54.497000 | 2018-05-29T13:48:40 | 2018-05-29T13:48:40 | 134,864,810 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Scanner;
public class VirtualPetApp {
public static void main(String[] args) {
VirtualPet virtualPet = new VirtualPet(60,50,40,30);
Scanner input = new Scanner(System.in);
boolean gameOn = true;
System.out.println("Welcome to your new virtual pet.");
System.out.println("Please name your new pet.");
String petName = input.nextLine();
System.out.println("Hello, my name is "+ petName + ", the Top Dawg");
System.out.println("Currently I am at \n"+ virtualPet);
while(gameOn == true){
System.out.println("What would you like to do?");
System.out.println("press 1 to feed "+petName+". \npress 2 to water "+petName+". \npress 3 to play fetch with "+petName+". \npress 4 to put "+petName+" to bed.");
String userAction = input.nextLine();
if (userAction.equals("1")){
virtualPet.feedPet();
}if (userAction.equals("2")){
virtualPet.waterPet();
}if (userAction.equals("3")){
virtualPet.playPet();
}if (userAction.equals("4")){
virtualPet.petNapping();
}
virtualPet.tick();
System.out.println(petName + " is now at\n"+ virtualPet);
System.out.println("what would you like to do next?");
}
}
}
| UTF-8 | Java | 1,190 | java | VirtualPetApp.java | Java | []
| null | []
| import java.util.Scanner;
public class VirtualPetApp {
public static void main(String[] args) {
VirtualPet virtualPet = new VirtualPet(60,50,40,30);
Scanner input = new Scanner(System.in);
boolean gameOn = true;
System.out.println("Welcome to your new virtual pet.");
System.out.println("Please name your new pet.");
String petName = input.nextLine();
System.out.println("Hello, my name is "+ petName + ", the Top Dawg");
System.out.println("Currently I am at \n"+ virtualPet);
while(gameOn == true){
System.out.println("What would you like to do?");
System.out.println("press 1 to feed "+petName+". \npress 2 to water "+petName+". \npress 3 to play fetch with "+petName+". \npress 4 to put "+petName+" to bed.");
String userAction = input.nextLine();
if (userAction.equals("1")){
virtualPet.feedPet();
}if (userAction.equals("2")){
virtualPet.waterPet();
}if (userAction.equals("3")){
virtualPet.playPet();
}if (userAction.equals("4")){
virtualPet.petNapping();
}
virtualPet.tick();
System.out.println(petName + " is now at\n"+ virtualPet);
System.out.println("what would you like to do next?");
}
}
}
| 1,190 | 0.660504 | 0.647059 | 41 | 28.024391 | 29.879831 | 164 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.439024 | false | false | 15 |
b512d8aeabd229472bd8df0b2f2ce0682f490f88 | 18,665,927,906,053 | 6eb1d205fa3e6c13762bc74b68b178e0f3d40834 | /NAI/Android/src/dk/itu/nai/ui/authentication/BasicAuthenticationActivity.java | d2d261ded6815dde7ddac926ba553d1f5b9c3348 | []
| no_license | thomicdk/nai-framework | https://github.com/thomicdk/nai-framework | 510a8a1a1228b6dff0b9c8d5bd8ca65f59d6211d | fd42c3141d29e72fd28885e9faa083e931814f43 | refs/heads/master | 2016-09-07T18:32:47.352000 | 2011-07-21T09:06:17 | 2011-07-21T09:06:17 | 32,269,989 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dk.itu.nai.ui.authentication;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import dk.itu.nai.R;
public class BasicAuthenticationActivity extends Activity {
public static final int RESULT_FORCE_CLOSE = 9999;
public static final String INTENT_EXTRA_USER_ID = "user_id";
private static final String PREF_KEY_USER_ID = "pref_user_id";
private EditText ed;
private SharedPreferences sharedPref;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.basic_authentication_activity);
ed = (EditText) findViewById(R.id.etUserId);
sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
ed.setText(sharedPref.getString(PREF_KEY_USER_ID, ""));
}
/* button events **/
public void onSubmitAuthentication(View v)
{
String userId = ed.getText().toString().trim();
if (userId.length()<1){
Toast.makeText(this, "Please enter a user id.", Toast.LENGTH_SHORT).show();
return;
}
// Update preferences
Editor edit = sharedPref.edit();
edit.putString(PREF_KEY_USER_ID, userId);
edit.commit();
// Return from this activity
setResult(userId);
finish();
}
public void onExitApplication(View v)
{
setResult(RESULT_FORCE_CLOSE);
finish();
}
/* Helpers */
private void setResult(String userId)
{
Intent intent = getIntent();
intent.putExtra(INTENT_EXTRA_USER_ID, userId);
setResult(RESULT_OK, intent);
}
}
| UTF-8 | Java | 1,740 | java | BasicAuthenticationActivity.java | Java | []
| null | []
| package dk.itu.nai.ui.authentication;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import dk.itu.nai.R;
public class BasicAuthenticationActivity extends Activity {
public static final int RESULT_FORCE_CLOSE = 9999;
public static final String INTENT_EXTRA_USER_ID = "user_id";
private static final String PREF_KEY_USER_ID = "pref_user_id";
private EditText ed;
private SharedPreferences sharedPref;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.basic_authentication_activity);
ed = (EditText) findViewById(R.id.etUserId);
sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
ed.setText(sharedPref.getString(PREF_KEY_USER_ID, ""));
}
/* button events **/
public void onSubmitAuthentication(View v)
{
String userId = ed.getText().toString().trim();
if (userId.length()<1){
Toast.makeText(this, "Please enter a user id.", Toast.LENGTH_SHORT).show();
return;
}
// Update preferences
Editor edit = sharedPref.edit();
edit.putString(PREF_KEY_USER_ID, userId);
edit.commit();
// Return from this activity
setResult(userId);
finish();
}
public void onExitApplication(View v)
{
setResult(RESULT_FORCE_CLOSE);
finish();
}
/* Helpers */
private void setResult(String userId)
{
Intent intent = getIntent();
intent.putExtra(INTENT_EXTRA_USER_ID, userId);
setResult(RESULT_OK, intent);
}
}
| 1,740 | 0.733908 | 0.731034 | 68 | 24.588236 | 21.133493 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.911765 | false | false | 15 |
0faad177377c07f6bca461f6ffdcd73b1737dd59 | 5,257,040,020,301 | bacd347bfa18b7e404ffcbd7591748a783fbd3b9 | /src/com/app/auscope/PreferencesManager.java | 2eab0e27c60328c42d2b0bb4990c319ea987a885 | []
| no_license | oliver-appscore/AUScope | https://github.com/oliver-appscore/AUScope | c3ba1f6807e4aba1107897032802ccf6a9fe06d6 | c3bb76e611abab94ae0bd6ce0321cbd69cfdae93 | refs/heads/master | 2016-09-02T03:46:13.306000 | 2014-01-23T06:26:25 | 2014-01-23T06:26:25 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.app.auscope;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public class PreferencesManager
{
private static SharedPreferences mSharedPreferences;
private static Editor mPreferencesEditor;
@SuppressLint("CommitPrefEdits")
public static void init(Context ApplicationContext)
{
mSharedPreferences = android.preference.PreferenceManager.getDefaultSharedPreferences(ApplicationContext);
mPreferencesEditor = mSharedPreferences.edit();
}
public static void putBoolean(String KEY, boolean NewBoolean)
{
mPreferencesEditor.putBoolean(KEY, NewBoolean);
mPreferencesEditor.commit();
}
public static boolean getBoolean(String KEY)
{
return mSharedPreferences.getBoolean(KEY, false);
}
}
| UTF-8 | Java | 836 | java | PreferencesManager.java | Java | []
| null | []
| package com.app.auscope;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public class PreferencesManager
{
private static SharedPreferences mSharedPreferences;
private static Editor mPreferencesEditor;
@SuppressLint("CommitPrefEdits")
public static void init(Context ApplicationContext)
{
mSharedPreferences = android.preference.PreferenceManager.getDefaultSharedPreferences(ApplicationContext);
mPreferencesEditor = mSharedPreferences.edit();
}
public static void putBoolean(String KEY, boolean NewBoolean)
{
mPreferencesEditor.putBoolean(KEY, NewBoolean);
mPreferencesEditor.commit();
}
public static boolean getBoolean(String KEY)
{
return mSharedPreferences.getBoolean(KEY, false);
}
}
| 836 | 0.815789 | 0.815789 | 30 | 26.866667 | 26.231956 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.333333 | false | false | 15 |
5d5191dc530dae6a327e7ecc944d0f72a88ef161 | 34,205,119,546,932 | fc2b526fb24e71360cdf8a422cc3d7a0361019a4 | /Algorithm/src/SamsungExpertAcademy/SquareRootGame.java | 85a66bd03551a14dbe3c94061bef019141af61a7 | []
| no_license | KDJ0899/Java_Algorithm | https://github.com/KDJ0899/Java_Algorithm | 1c49c3af25288c77114e9d174efbbb3c2b350519 | 77400a0b94f153e15f822abe22471e5a4ded46d0 | refs/heads/master | 2021-11-18T11:36:11.466000 | 2021-09-06T12:57:23 | 2021-09-06T12:57:23 | 164,573,050 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package SamsungExpertAcademy;
import java.util.Scanner;
/**
*
* @FileName : SquareRootGame.java
* @Project : Algorithm
* @Date : 2019. 12. 15.
* @Author : Kim DongJin
* @Comment : Samsung Expert Academy 6782. D5 현주가 좋아하는 제곱근 놀이
*/
public class SquareRootGame {
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
int T = sc.nextInt();
long n,count,s,p;
for(int i=0; i<T; i++) {
n = sc.nextLong();
count = 0;
while(true) {
if(n==2)
break;
s =(long) Math.sqrt(n);
p = (long) Math.pow(s, 2);
if(p!=n) {
p = (long) Math.pow(s+1, 2);
count+=p-n+1;
n=(long) Math.sqrt(p);
}
else {
count++;
n=s;
}
}
System.out.println("#"+(i+1)+" "+count);
}
sc.close();
}
}
| UTF-8 | Java | 854 | java | SquareRootGame.java | Java | [
{
"context": "Algorithm\n * @Date : 2019. 12. 15. \n * @Author : Kim DongJin\n * @Comment : Samsung Expert Academy 6782. D5 현주",
"end": 179,
"score": 0.9998903274536133,
"start": 168,
"tag": "NAME",
"value": "Kim DongJin"
}
]
| null | []
| package SamsungExpertAcademy;
import java.util.Scanner;
/**
*
* @FileName : SquareRootGame.java
* @Project : Algorithm
* @Date : 2019. 12. 15.
* @Author : <NAME>
* @Comment : Samsung Expert Academy 6782. D5 현주가 좋아하는 제곱근 놀이
*/
public class SquareRootGame {
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
int T = sc.nextInt();
long n,count,s,p;
for(int i=0; i<T; i++) {
n = sc.nextLong();
count = 0;
while(true) {
if(n==2)
break;
s =(long) Math.sqrt(n);
p = (long) Math.pow(s, 2);
if(p!=n) {
p = (long) Math.pow(s+1, 2);
count+=p-n+1;
n=(long) Math.sqrt(p);
}
else {
count++;
n=s;
}
}
System.out.println("#"+(i+1)+" "+count);
}
sc.close();
}
}
| 849 | 0.513253 | 0.487952 | 54 | 14.37037 | 13.916811 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.685185 | false | false | 15 |
b93a816f19874893fd8b6cc8eded40c097863a7d | 20,151,986,594,655 | c3bda29746213cf0813e70d93deff4bc184a5be8 | /platform/jboss4/JBoss_4_0_5_GA_JBAS-4129/security/src/main/org/jboss/security/plugins/.svn/text-base/TmpFilePassword.java.svn-base | 23c50cba20bd556f4df4b36243f372682228c89a | []
| no_license | bellmit/esm-essa | https://github.com/bellmit/esm-essa | 2c1ce1e828ebc668f49c14806955059a5c1a9e66 | ec3c9188b03e8a6225f9860e5c686363012cb07d | refs/heads/master | 2022-01-14T15:44:51.485000 | 2016-11-23T21:48:24 | 2016-11-23T21:48:24 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* JBoss, Home of Professional Open Source.
* Copyright 2006, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.security.plugins;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.CharArrayWriter;
import java.io.RandomAccessFile;
import org.jboss.logging.Logger;
/** Read a password from a file specified via the ctor and then overwrite
the file contents with garbage, and then remove it. This may be used as a
password accessor in conjunction with the JaasSecurityDomain
{CLASS}org.jboss.security.plugins.TmpFilePassword:password-file
format of the KeyStorePass attribute.
This class waits until the file exists if it does not when toCharArray()
is called. It prints out to the console every 10 seconds the path to
the file it is waiting on until the file is created.
@author Scott.Stark@jboss.org
@version $Revison:$
*/
public class TmpFilePassword
{
private static Logger log = Logger.getLogger(TmpFilePassword.class);
private File passwordFile;
public TmpFilePassword(String file)
{
passwordFile = new File(file);
}
public char[] toCharArray()
throws IOException
{
while( passwordFile.exists() == false )
{
log.info("Waiting for password file: "+passwordFile.getAbsolutePath());
try
{
Thread.sleep(10*1000);
}
catch(InterruptedException e)
{
log.info("Exiting wait on InterruptedException");
break;
}
}
FileInputStream fis = new FileInputStream(passwordFile);
CharArrayWriter writer = new CharArrayWriter();
int b;
while( (b = fis.read()) >= 0 )
{
if( b == '\r' || b == '\n' )
continue;
writer.write(b);
}
fis.close();
char[] password = writer.toCharArray();
writer.reset();
for(int n = 0; n < password.length; n ++)
writer.write('\0');
// Overwrite the password file
try
{
RandomAccessFile raf = new RandomAccessFile(passwordFile, "rws");
for(int i = 0; i < 10; i ++)
{
raf.seek(0);
for(int j = 0; j < password.length; j ++)
raf.write(j);
}
raf.close();
if( passwordFile.delete() == false )
log.warn("Was not able to delete the password file");
}
catch(Exception e)
{
log.warn("Failed to zero the password file", e);
}
return password;
}
}
| UTF-8 | Java | 3,462 | TmpFilePassword.java.svn-base | Java | [
{
"context": "is waiting on until the file is created.\n\n @author Scott.Stark@jboss.org\n @version $Revison:$\n */\npublic class TmpFilePass",
"end": 1796,
"score": 0.9999167919158936,
"start": 1775,
"tag": "EMAIL",
"value": "Scott.Stark@jboss.org"
}
]
| null | []
| /*
* JBoss, Home of Professional Open Source.
* Copyright 2006, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.security.plugins;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.CharArrayWriter;
import java.io.RandomAccessFile;
import org.jboss.logging.Logger;
/** Read a password from a file specified via the ctor and then overwrite
the file contents with garbage, and then remove it. This may be used as a
password accessor in conjunction with the JaasSecurityDomain
{CLASS}org.jboss.security.plugins.TmpFilePassword:password-file
format of the KeyStorePass attribute.
This class waits until the file exists if it does not when toCharArray()
is called. It prints out to the console every 10 seconds the path to
the file it is waiting on until the file is created.
@author <EMAIL>
@version $Revison:$
*/
public class TmpFilePassword
{
private static Logger log = Logger.getLogger(TmpFilePassword.class);
private File passwordFile;
public TmpFilePassword(String file)
{
passwordFile = new File(file);
}
public char[] toCharArray()
throws IOException
{
while( passwordFile.exists() == false )
{
log.info("Waiting for password file: "+passwordFile.getAbsolutePath());
try
{
Thread.sleep(10*1000);
}
catch(InterruptedException e)
{
log.info("Exiting wait on InterruptedException");
break;
}
}
FileInputStream fis = new FileInputStream(passwordFile);
CharArrayWriter writer = new CharArrayWriter();
int b;
while( (b = fis.read()) >= 0 )
{
if( b == '\r' || b == '\n' )
continue;
writer.write(b);
}
fis.close();
char[] password = writer.toCharArray();
writer.reset();
for(int n = 0; n < password.length; n ++)
writer.write('\0');
// Overwrite the password file
try
{
RandomAccessFile raf = new RandomAccessFile(passwordFile, "rws");
for(int i = 0; i < 10; i ++)
{
raf.seek(0);
for(int j = 0; j < password.length; j ++)
raf.write(j);
}
raf.close();
if( passwordFile.delete() == false )
log.warn("Was not able to delete the password file");
}
catch(Exception e)
{
log.warn("Failed to zero the password file", e);
}
return password;
}
}
| 3,448 | 0.651935 | 0.642403 | 106 | 31.660378 | 24.687437 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.537736 | false | false | 15 |
|
80e7657b2652e8e12d337e298700762e0bf365dc | 1,932,735,308,534 | 73abc923d48885173864c412fd80c30aad8f3ab1 | /src/main/java/task01/App.java | 82f7b4b8e9fae8f82cc6bec1b26cf4ea5c2c9b0a | []
| no_license | GamidovRustam/Gojava4Core | https://github.com/GamidovRustam/Gojava4Core | a791c42d26951c339fb64d4d46ab09924065c255 | 1c9b16d5572a295de6c26a0c5e63daab31f0db22 | refs/heads/master | 2021-01-11T03:45:32.021000 | 2016-11-07T22:27:02 | 2016-11-07T22:27:02 | 71,294,227 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package task01;
import task01.mycollection.MyIntCollection;
/**
* Created by Rustam on 18.10.2016.
*/
class App {
public static void main(String[] args) {
int[] startValues = {10, 20, 30, 40, 50};
MyIntCollection myCollection = new MyIntCollection(startValues);
System.out.println("'MyCollection' filled with start values:");
System.out.println(myCollection + "\n");
myCollection.addToHead(5);
System.out.println("add value '5' to head: ");
System.out.println(myCollection + "\n");
myCollection.add(100);
System.out.println("add value '100' to tail: ");
System.out.println(myCollection + "\n");
myCollection.add(4, 1000);
System.out.println("add value '1000' to index position '4': ");
System.out.println(myCollection + "\n");
myCollection.remove(1000);
System.out.println("remove existing value '1000': ");
System.out.println(myCollection + "\n");
myCollection.removeByIndex(2);
System.out.println("remove value '125' by index '2': ");
System.out.println(myCollection + "\n");
}
}
| UTF-8 | Java | 1,155 | java | App.java | Java | [
{
"context": "1.mycollection.MyIntCollection;\n\n/**\n * Created by Rustam on 18.10.2016.\n */\nclass App {\n\n public static",
"end": 86,
"score": 0.999437689781189,
"start": 80,
"tag": "NAME",
"value": "Rustam"
}
]
| null | []
| package task01;
import task01.mycollection.MyIntCollection;
/**
* Created by Rustam on 18.10.2016.
*/
class App {
public static void main(String[] args) {
int[] startValues = {10, 20, 30, 40, 50};
MyIntCollection myCollection = new MyIntCollection(startValues);
System.out.println("'MyCollection' filled with start values:");
System.out.println(myCollection + "\n");
myCollection.addToHead(5);
System.out.println("add value '5' to head: ");
System.out.println(myCollection + "\n");
myCollection.add(100);
System.out.println("add value '100' to tail: ");
System.out.println(myCollection + "\n");
myCollection.add(4, 1000);
System.out.println("add value '1000' to index position '4': ");
System.out.println(myCollection + "\n");
myCollection.remove(1000);
System.out.println("remove existing value '1000': ");
System.out.println(myCollection + "\n");
myCollection.removeByIndex(2);
System.out.println("remove value '125' by index '2': ");
System.out.println(myCollection + "\n");
}
}
| 1,155 | 0.615584 | 0.569697 | 39 | 28.615385 | 25.134117 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 15 |
f8c41ac69e0b85232c09b619772a1624b4c2d082 | 19,997,367,776,532 | 2b42306cfbf79848c939098279c8ae7180bb20ea | /src/com/lc/bootcamp/array/RemoveElememt.java | b72dfb4a8835e6da609a7737b083c0dd0608c3eb | []
| no_license | tankyhsu/lc-bootcamp | https://github.com/tankyhsu/lc-bootcamp | 1b83f03e8250b686971edabec4d3a7fe1a0f48e9 | e082d18c5ceb4659e0b18df36dc69f6c77f36856 | refs/heads/master | 2022-11-07T10:53:19.789000 | 2020-06-24T03:29:54 | 2020-06-24T03:29:54 | 262,473,962 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lc.bootcamp.array;
/**
* @author tianqi.xu
* 2020/6/10
*/
public class RemoveElememt {
public int removeElement(int[] nums, int val) {
int len = nums.length;
int j = 0;
for (int i = 0; i < len; i++) {
if (nums[i] != val) {
nums[j] = nums[i];
j++;
}
}
return j+1;
}
}
| UTF-8 | Java | 388 | java | RemoveElememt.java | Java | [
{
"context": "package com.lc.bootcamp.array;\n\n/**\n * @author tianqi.xu\n * 2020/6/10\n */\npublic class RemoveElememt {\n ",
"end": 56,
"score": 0.9981471300125122,
"start": 47,
"tag": "NAME",
"value": "tianqi.xu"
}
]
| null | []
| package com.lc.bootcamp.array;
/**
* @author tianqi.xu
* 2020/6/10
*/
public class RemoveElememt {
public int removeElement(int[] nums, int val) {
int len = nums.length;
int j = 0;
for (int i = 0; i < len; i++) {
if (nums[i] != val) {
nums[j] = nums[i];
j++;
}
}
return j+1;
}
}
| 388 | 0.43299 | 0.407216 | 20 | 18.4 | 14.322709 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.45 | false | false | 15 |
70b4d512ae2fa52c5325a8a25eafd99f77108f31 | 11,948,599,038,145 | 2b5c17b855a1d8b0802dae0453f5da602f2abae5 | /src/main/java/napi/db/handler/BlockingHandler.java | 6f5a64e5b7095a3b179f942e8efef3b3b720a05e | []
| no_license | NanitApi/napi-db | https://github.com/NanitApi/napi-db | c6cad8b461722877b844cd14429c56d5ea38279b | d0ee39a6ab50a2c5078aa3460a8b6393918b98b8 | refs/heads/main | 2023-07-01T09:49:30.420000 | 2021-08-12T10:06:08 | 2021-08-12T10:06:08 | 394,561,266 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package napi.db.handler;
import napi.db.ConnectionProvider;
import napi.db.QueryHandler;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.function.Consumer;
public class BlockingHandler implements QueryHandler {
private final ConnectionProvider provider;
public BlockingHandler(ConnectionProvider provider) {
this.provider = provider;
}
@Override
public void query(Consumer<ResultSet> result, String sql, Object... args) {
withPreparedStatement(sql, statement -> {
try {
applyArgs(statement, args);
ResultSet res = statement.executeQuery();
result.accept(res);
res.close();
} catch (SQLException e) {
e.printStackTrace();
}
});
}
@Override
public void update(String sql, Object... args) {
withPreparedStatement(sql, statement -> {
try {
applyArgs(statement, args);
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
});
}
@Override
public void update(Consumer<ResultSet> result, String sql, Object... args) {
withPreparedStatement(sql, statement -> {
try {
applyArgs(statement, args);
statement.executeUpdate();
ResultSet keys = statement.getGeneratedKeys();
result.accept(keys);
keys.close();
} catch (SQLException e) {
e.printStackTrace();
}
}, PreparedStatement.RETURN_GENERATED_KEYS);
}
@Override
public void execute(String sql) {
withStatement(statement -> {
try {
statement.execute(sql);
} catch (SQLException ex) {
ex.printStackTrace();
}
});
}
private void applyArgs(PreparedStatement st, Object... args) throws SQLException {
for (int i = 1; i <= args.length; i++) {
st.setObject(i, args[i-1]);
}
}
private void withPreparedStatement(String sql, Consumer<PreparedStatement> st, int flag) {
provider.provide((conn) -> {
try (PreparedStatement statement = conn.prepareStatement(sql, flag)){
st.accept(statement);
} catch (SQLException ex) {
ex.printStackTrace();
}
});
}
private void withPreparedStatement(String sql, Consumer<PreparedStatement> st) {
withPreparedStatement(sql, st, PreparedStatement.NO_GENERATED_KEYS);
}
private void withStatement(Consumer<Statement> st) {
provider.provide((conn) -> {
try (Statement statement = conn.createStatement()) {
st.accept(statement);
} catch (SQLException ex) {
ex.printStackTrace();
}
});
}
}
| UTF-8 | Java | 3,041 | java | BlockingHandler.java | Java | []
| null | []
| package napi.db.handler;
import napi.db.ConnectionProvider;
import napi.db.QueryHandler;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.function.Consumer;
public class BlockingHandler implements QueryHandler {
private final ConnectionProvider provider;
public BlockingHandler(ConnectionProvider provider) {
this.provider = provider;
}
@Override
public void query(Consumer<ResultSet> result, String sql, Object... args) {
withPreparedStatement(sql, statement -> {
try {
applyArgs(statement, args);
ResultSet res = statement.executeQuery();
result.accept(res);
res.close();
} catch (SQLException e) {
e.printStackTrace();
}
});
}
@Override
public void update(String sql, Object... args) {
withPreparedStatement(sql, statement -> {
try {
applyArgs(statement, args);
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
});
}
@Override
public void update(Consumer<ResultSet> result, String sql, Object... args) {
withPreparedStatement(sql, statement -> {
try {
applyArgs(statement, args);
statement.executeUpdate();
ResultSet keys = statement.getGeneratedKeys();
result.accept(keys);
keys.close();
} catch (SQLException e) {
e.printStackTrace();
}
}, PreparedStatement.RETURN_GENERATED_KEYS);
}
@Override
public void execute(String sql) {
withStatement(statement -> {
try {
statement.execute(sql);
} catch (SQLException ex) {
ex.printStackTrace();
}
});
}
private void applyArgs(PreparedStatement st, Object... args) throws SQLException {
for (int i = 1; i <= args.length; i++) {
st.setObject(i, args[i-1]);
}
}
private void withPreparedStatement(String sql, Consumer<PreparedStatement> st, int flag) {
provider.provide((conn) -> {
try (PreparedStatement statement = conn.prepareStatement(sql, flag)){
st.accept(statement);
} catch (SQLException ex) {
ex.printStackTrace();
}
});
}
private void withPreparedStatement(String sql, Consumer<PreparedStatement> st) {
withPreparedStatement(sql, st, PreparedStatement.NO_GENERATED_KEYS);
}
private void withStatement(Consumer<Statement> st) {
provider.provide((conn) -> {
try (Statement statement = conn.createStatement()) {
st.accept(statement);
} catch (SQLException ex) {
ex.printStackTrace();
}
});
}
}
| 3,041 | 0.561657 | 0.561 | 101 | 29.108912 | 22.970451 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.594059 | false | false | 15 |
b70415b5eb2526958ed30990ce81a8efe38f3973 | 29,772,713,357,520 | 44a3ac342005c8ea828c0a3df2619d829f7e8954 | /microservice-backend-jpetstore/src/main/java/com/springcloud/mmy/jpetstore/repository/SequenceRepository.java | 6e6e50342a7b27df2e0bb74c0dbb056acbb6b0ea | []
| no_license | moumingyang/microservice-jpetstore | https://github.com/moumingyang/microservice-jpetstore | b4f1bd3f2fceb0eca36cd7abb83e204367938b18 | 8c5c045e983e600f7bec1e5700a86244b9d5151b | refs/heads/master | 2020-03-02T18:27:02.537000 | 2017-11-18T05:25:22 | 2017-11-18T05:25:22 | 102,806,544 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.springcloud.mmy.jpetstore.repository;
import com.springcloud.mmy.jpetstore.domain.Sequence;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface SequenceRepository extends JpaRepository<Sequence,String>{
}
| UTF-8 | Java | 308 | java | SequenceRepository.java | Java | []
| null | []
| package com.springcloud.mmy.jpetstore.repository;
import com.springcloud.mmy.jpetstore.domain.Sequence;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface SequenceRepository extends JpaRepository<Sequence,String>{
}
| 308 | 0.857143 | 0.857143 | 9 | 33.222221 | 28.17713 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false | 15 |
be5017a5d3501209983cb44e340c1a2e3200c25a | 2,619,930,054,008 | 65c88a97f3add98b97c35c43e0c11abdef416a15 | /src/View/Xanthane/BaseMapXanthane.java | 13578dfbc337881fc7b2a4873f0a0b141335ab83 | []
| no_license | peigne/project_java | https://github.com/peigne/project_java | 5e7c299d45dfe808a845a2dddef2a02283bc08ef | 2a5c8131be650d0b9f517e1dd630e156f6197090 | refs/heads/master | 2020-06-19T11:57:53.994000 | 2017-01-13T23:50:52 | 2017-01-13T23:50:52 | 74,905,310 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package View.Xanthane;
/**
*
* @author Flo
*/
import View.Xanthane.OutlineXanthane;
import View.Interfaces.IBaseMap;
import View.Interfaces.IZone;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="map")
@XmlAccessorType(value=XmlAccessType.FIELD)
public class BaseMapXanthane implements IBaseMap {
@XmlElement(name="outline")
ArrayList<OutlineXanthane> outlines;
@Override
public List<IZone> getZones() {
return new ArrayList<IZone>(this.outlines);
}
}
| UTF-8 | Java | 763 | java | BaseMapXanthane.java | Java | [
{
"context": "\r\npackage View.Xanthane;\r\n\r\n/**\r\n *\r\n * @author Flo\r\n */\r\nimport View.Xanthane.OutlineXanthane;\r\nimpo",
"end": 51,
"score": 0.9954665899276733,
"start": 48,
"tag": "USERNAME",
"value": "Flo"
}
]
| null | []
|
package View.Xanthane;
/**
*
* @author Flo
*/
import View.Xanthane.OutlineXanthane;
import View.Interfaces.IBaseMap;
import View.Interfaces.IZone;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="map")
@XmlAccessorType(value=XmlAccessType.FIELD)
public class BaseMapXanthane implements IBaseMap {
@XmlElement(name="outline")
ArrayList<OutlineXanthane> outlines;
@Override
public List<IZone> getZones() {
return new ArrayList<IZone>(this.outlines);
}
}
| 763 | 0.740498 | 0.740498 | 29 | 24.241379 | 18.005085 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.448276 | false | false | 15 |
a676c83de2c583b0f3ecbfc48aa6e1f5a8fb06bd | 36,155,034,706,706 | 374ad03287670140e4a716aa211cdaf60f50c944 | /ztr-weixin/ztr-member/ztravel-operator/src/main/java/com/ztravel/operator/electronicWallet/entity/CouponSearchCriteria.java | 834cbcf9e46458980d72e0e874e6a7e16b69460e | []
| no_license | xxxJppp/firstproj | https://github.com/xxxJppp/firstproj | ca541f8cbe004a557faff577698c0424f1bbd1aa | 00dcfbe731644eda62bd2d34d55144a3fb627181 | refs/heads/master | 2020-07-12T17:00:00.549000 | 2017-04-17T08:29:58 | 2017-04-17T08:29:58 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ztravel.operator.electronicWallet.entity;
import com.ztravel.common.entity.PaginationEntity;
public class CouponSearchCriteria extends PaginationEntity{
private String mobile;
private String mid;
private String useTimeFrom;
private String useTimeTo;
private String couponCode;
public String getUseTimeFrom() {
return useTimeFrom;
}
public void setUseTimeFrom(String useTimeFrom) {
this.useTimeFrom = useTimeFrom;
}
public String getUseTimeTo() {
return useTimeTo;
}
public void setUseTimeTo(String useTimeTo) {
this.useTimeTo = useTimeTo;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getCouponCode() {
return couponCode;
}
public void setCouponCode(String couponCode) {
this.couponCode = couponCode;
}
public String getMid() {
return mid;
}
public void setMid(String mid) {
this.mid = mid;
}
}
| UTF-8 | Java | 950 | java | CouponSearchCriteria.java | Java | []
| null | []
| package com.ztravel.operator.electronicWallet.entity;
import com.ztravel.common.entity.PaginationEntity;
public class CouponSearchCriteria extends PaginationEntity{
private String mobile;
private String mid;
private String useTimeFrom;
private String useTimeTo;
private String couponCode;
public String getUseTimeFrom() {
return useTimeFrom;
}
public void setUseTimeFrom(String useTimeFrom) {
this.useTimeFrom = useTimeFrom;
}
public String getUseTimeTo() {
return useTimeTo;
}
public void setUseTimeTo(String useTimeTo) {
this.useTimeTo = useTimeTo;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getCouponCode() {
return couponCode;
}
public void setCouponCode(String couponCode) {
this.couponCode = couponCode;
}
public String getMid() {
return mid;
}
public void setMid(String mid) {
this.mid = mid;
}
}
| 950 | 0.74 | 0.74 | 58 | 15.379311 | 17.268496 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.086207 | false | false | 15 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.