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
sequence | 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
sequence | 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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1cd716d9b63236551a1597087c9defbef1216b0e | 33,603,824,172,008 | 13fbedafa5bfb430ac1e6263f4de71c8b84e9c6a | /siveo-cloud-vmware/src/main/java/net/siveo/virtualization/vmware/virtualdevice/VirtualDisk.java | 9ee1d50237c84228fe62ac09ebfb2103dbaf98b7 | [] | no_license | eVA-Project/eVA | https://github.com/eVA-Project/eVA | 0e043ae971f4048571cac7ee8a3224a2864ab808 | 7c5be4544b5df7e1eb8399e30b9cce1189fb7ada | refs/heads/master | 2018-09-20T15:38:14.602000 | 2016-07-09T20:05:26 | 2016-07-09T20:05:26 | 59,123,196 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.siveo.virtualization.vmware.virtualdevice;
import com.vmware.vim25.ManagedObjectReference;
import com.vmware.vim25.VirtualDeviceBackingInfo;
import com.vmware.vim25.VirtualDeviceFileBackingInfo;
public class VirtualDisk{
private String virtualdiskID=null;
private long diskSize=0L;
private int key=0;
private int controllerKey=0;
private String label=null;
private String summary=null;
private int unitNumber=0;
private com.vmware.vim25.VirtualDisk virtualDisk=null;
private VirtualDeviceBackingInfo backing=null;
private VirtualDeviceOperation action=null;
private String deviceNode=null;
// VirtualDeviceFileBackingInfo
private String changeId=null;
private String compatibilityMode=null;
private String contentId=null;
private ManagedObjectReference datastore=null;
private String descriptorFileName=null;
private String deviceName=null;
private String diskMode=null;
private boolean eagerlyScrub=false;
private String fileName=null;
private String lunUuid=null;
private VirtualDeviceFileBackingInfo parent=null;
private int[] partition;
private long spaceUsedInKB=0L;
private boolean split=false;
private boolean thinProvisioned=false;
private boolean useAutoDetect=false;
private String uuid=null;
private boolean writeThrough=false;
public VirtualDisk()
{
}
public VirtualDisk(com.vmware.vim25.VirtualDisk vDisk)
{
this.virtualDisk=vDisk;
this.diskSize=vDisk.getCapacityInKB();
this.key=vDisk.getKey();
this.controllerKey=vDisk.getControllerKey();
this.label=vDisk.getDeviceInfo().getLabel();
this.summary=vDisk.getDeviceInfo().getSummary();
this.unitNumber=vDisk.getUnitNumber();
this.backing=vDisk.getBacking();
}
public String getVirtualdiskID()
{
return virtualdiskID;
}
public void setVirtualdiskID(String virtualdiskID)
{
this.virtualdiskID = virtualdiskID;
}
public long getDiskSize()
{
return diskSize;
}
public void setDiskSize(long diskSize)
{
this.diskSize = diskSize;
}
public int getKey() {
return key;
}
public void setKey(int key) {
this.key = key;
}
public int getControllerKey() {
return controllerKey;
}
public void setControllerKey(int controllerKey) {
this.controllerKey = controllerKey;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public int getUnitNumber() {
return unitNumber;
}
public void setUnitNumber(int unitNumber) {
this.unitNumber = unitNumber;
}
public com.vmware.vim25.VirtualDisk getVirtualDisk() {
return virtualDisk;
}
public void setVirtualDisk(com.vmware.vim25.VirtualDisk vmwareVirtualDisk) {
this.virtualDisk = vmwareVirtualDisk;
}
public VirtualDeviceBackingInfo getBacking() {
return backing;
}
public void setBacking(VirtualDeviceBackingInfo backing) {
this.backing = backing;
}
public VirtualDeviceOperation getAction() {
return action;
}
public void setAction(VirtualDeviceOperation action) {
this.action = action;
}
public String getDeviceNode() {
return deviceNode;
}
public void setDeviceNode(String deviceNode) {
this.deviceNode = deviceNode;
}
}
| UTF-8 | Java | 3,441 | java | VirtualDisk.java | Java | [] | null | [] | package net.siveo.virtualization.vmware.virtualdevice;
import com.vmware.vim25.ManagedObjectReference;
import com.vmware.vim25.VirtualDeviceBackingInfo;
import com.vmware.vim25.VirtualDeviceFileBackingInfo;
public class VirtualDisk{
private String virtualdiskID=null;
private long diskSize=0L;
private int key=0;
private int controllerKey=0;
private String label=null;
private String summary=null;
private int unitNumber=0;
private com.vmware.vim25.VirtualDisk virtualDisk=null;
private VirtualDeviceBackingInfo backing=null;
private VirtualDeviceOperation action=null;
private String deviceNode=null;
// VirtualDeviceFileBackingInfo
private String changeId=null;
private String compatibilityMode=null;
private String contentId=null;
private ManagedObjectReference datastore=null;
private String descriptorFileName=null;
private String deviceName=null;
private String diskMode=null;
private boolean eagerlyScrub=false;
private String fileName=null;
private String lunUuid=null;
private VirtualDeviceFileBackingInfo parent=null;
private int[] partition;
private long spaceUsedInKB=0L;
private boolean split=false;
private boolean thinProvisioned=false;
private boolean useAutoDetect=false;
private String uuid=null;
private boolean writeThrough=false;
public VirtualDisk()
{
}
public VirtualDisk(com.vmware.vim25.VirtualDisk vDisk)
{
this.virtualDisk=vDisk;
this.diskSize=vDisk.getCapacityInKB();
this.key=vDisk.getKey();
this.controllerKey=vDisk.getControllerKey();
this.label=vDisk.getDeviceInfo().getLabel();
this.summary=vDisk.getDeviceInfo().getSummary();
this.unitNumber=vDisk.getUnitNumber();
this.backing=vDisk.getBacking();
}
public String getVirtualdiskID()
{
return virtualdiskID;
}
public void setVirtualdiskID(String virtualdiskID)
{
this.virtualdiskID = virtualdiskID;
}
public long getDiskSize()
{
return diskSize;
}
public void setDiskSize(long diskSize)
{
this.diskSize = diskSize;
}
public int getKey() {
return key;
}
public void setKey(int key) {
this.key = key;
}
public int getControllerKey() {
return controllerKey;
}
public void setControllerKey(int controllerKey) {
this.controllerKey = controllerKey;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public int getUnitNumber() {
return unitNumber;
}
public void setUnitNumber(int unitNumber) {
this.unitNumber = unitNumber;
}
public com.vmware.vim25.VirtualDisk getVirtualDisk() {
return virtualDisk;
}
public void setVirtualDisk(com.vmware.vim25.VirtualDisk vmwareVirtualDisk) {
this.virtualDisk = vmwareVirtualDisk;
}
public VirtualDeviceBackingInfo getBacking() {
return backing;
}
public void setBacking(VirtualDeviceBackingInfo backing) {
this.backing = backing;
}
public VirtualDeviceOperation getAction() {
return action;
}
public void setAction(VirtualDeviceOperation action) {
this.action = action;
}
public String getDeviceNode() {
return deviceNode;
}
public void setDeviceNode(String deviceNode) {
this.deviceNode = deviceNode;
}
}
| 3,441 | 0.72973 | 0.724208 | 156 | 20.057692 | 18.830296 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.416667 | false | false | 3 |
471773361bfdbc2f4169dc1ef4704d157bb39e13 | 2,937,757,677,857 | 2cdc29a58151ad8e1a8c12922bfcf5666f04e7bd | /src/br/com/rsousa/transformers/DriverTransformer.java | db9403b70f544d0f4382495add9c0734829a2bd0 | [] | no_license | rdskill/race-results | https://github.com/rdskill/race-results | 1206f5d1650ead0484b598f91cb1857a4dc88860 | 0e04fc250544ae24e889b1f7bba1b00a4d9bb3ff | refs/heads/master | 2023-08-23T21:51:37.792000 | 2023-08-12T20:33:12 | 2023-08-12T20:34:17 | 236,380,766 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.rsousa.transformers;
import br.com.rsousa.pojo.Driver;
import br.com.rsousa.pojo.acc.LeaderBoardLine;
import br.com.rsousa.pojo.assetto.Result;
import br.com.rsousa.pojo.iracing.DriverSession;
import br.com.rsousa.utils.TimeUtils;
import java.util.List;
public class DriverTransformer {
public static Driver toDriver(br.com.rsousa.pojo.ams.Driver amsDriver, int position, String raceTimeFormatted, Double driverTotalTime, List<Driver> drivers) {
Driver driver = new Driver();
driver.setName(amsDriver.getName());
driver.setBestLap(amsDriver.getBestLapTime());
driver.setBestLapMilliseconds(TimeUtils.toMilliseconds(amsDriver.getBestLapTime()));
driver.setRaceTimeMilliseconds(TimeUtils.toMilliseconds(amsDriver.getFinishTime()));
driver.setLaps(amsDriver.getLaps());
driver.setPosition(position);
driver.setRaceTimeFormatted(raceTimeFormatted);
driver.setTeam(getTeamName(amsDriver.getName(), amsDriver.getTeamName(), drivers));
driver.setTeamStatistics(getTeamStatisticsName(amsDriver.getName(), amsDriver.getTeamName(), drivers));
driver.setDriverTotalTime(driverTotalTime);
return driver;
}
public static Driver toDriver(DriverSession iRacingDriver, int position, String raceTimeFormatted, List<Driver> drivers) {
Driver driver = new Driver();
driver.setName(getDriverName(iRacingDriver, drivers));
driver.setBestLap(iRacingDriver.getFastLap());
driver.setLaps(iRacingDriver.getCompletedLaps());
driver.setPosition(position);
driver.setRaceTimeFormatted(raceTimeFormatted);
driver.setBestLapMilliseconds(TimeUtils.toMilliseconds(iRacingDriver.getFastLap()));
driver.setTeam(getTeamName(iRacingDriver, drivers));
driver.setTeamStatistics(getTeamStatisticsName(iRacingDriver, drivers));
return driver;
}
public static Driver toDriver(Result assettoDriver, int position, int laps, String raceTimeFormatted, List<Driver> drivers) {
Driver driver = new Driver();
driver.setName(assettoDriver.getDriverName());
driver.setBestLapMilliseconds(assettoDriver.getBestLap());
driver.setRaceTimeMilliseconds(assettoDriver.getTotalTime());
driver.setLaps(laps);
driver.setPosition(position);
driver.setRaceTimeFormatted(raceTimeFormatted);
driver.setTeam(getTeamName(assettoDriver.getDriverName(), "Independente", drivers));
driver.setTeamStatistics(getTeamStatisticsName(assettoDriver.getDriverName(), "Independente", drivers));
return driver;
}
public static Driver toDriver(LeaderBoardLine assettoDriver, int position, int laps, String raceTimeFormatted, List<Driver> drivers) {
Driver driver = new Driver();
String driverName = assettoDriver.getCurrentDriver().getFirstName() + " " + assettoDriver.getCurrentDriver().getLastName();
driver.setName(driverName);
driver.setBestLapMilliseconds(assettoDriver.getTiming().getBestLap());
driver.setRaceTimeMilliseconds(assettoDriver.getTiming().getTotalTime());
driver.setLaps(laps);
driver.setPosition(position);
driver.setRaceTimeFormatted(raceTimeFormatted);
driver.setTeam(getTeamName(driverName, "Independente", drivers));
driver.setTeamStatistics(getTeamStatisticsName(driverName, "Independente", drivers));
return driver;
}
public static Driver toDriver(br.com.rsousa.pojo.ams2.Result result, int position, String raceTimeFormatted, List<Driver> drivers) {
Driver driver = new Driver();
driver.setName(result.getName());
driver.setBestLapMilliseconds(Long.valueOf(result.getAttributes().getFastestLapTime()));
driver.setRaceTimeMilliseconds(Long.valueOf(result.getAttributes().getTotalTime()));
driver.setLaps(result.getAttributes().getLap());
driver.setPosition(position);
driver.setRaceTimeFormatted(raceTimeFormatted);
driver.setTeam(getTeamName(result.getName(), "Independente", drivers));
driver.setTeamStatistics(getTeamStatisticsName(result.getName(), "Independente", drivers));
return driver;
}
private static String getTeamName(String driverName, String teamName, List<Driver> drivers) {
return drivers.stream().filter(d -> driverName.trim().equals(d.getName()))
.map(Driver::getTeam)
.findAny()
.orElse(teamName);
}
private static String getTeamStatisticsName(String driverName, String teamName, List<Driver> drivers) {
return drivers.stream().filter(d -> driverName.trim().equals(d.getName()))
.map(Driver::getTeamStatistics)
.findAny()
.orElse(teamName);
}
private static String getDriverName(DriverSession driver, List<Driver> drivers) {
return drivers.stream().filter(d -> driver.getId().equals(d.getId()))
.map(Driver::getName)
.findAny()
.orElse(driver.getName());
}
private static String getTeamName(DriverSession driver, List<Driver> drivers) {
return drivers.stream().filter(d -> driver.getId().equals(d.getId()))
.map(Driver::getTeam)
.findAny()
.orElse("Independente");
}
private static String getTeamStatisticsName(DriverSession driver, List<Driver> drivers) {
return drivers.stream().filter(d -> driver.getId().equals(d.getId()))
.map(Driver::getTeamStatistics)
.findAny()
.orElse("Independente");
}
}
| UTF-8 | Java | 5,686 | java | DriverTransformer.java | Java | [] | null | [] | package br.com.rsousa.transformers;
import br.com.rsousa.pojo.Driver;
import br.com.rsousa.pojo.acc.LeaderBoardLine;
import br.com.rsousa.pojo.assetto.Result;
import br.com.rsousa.pojo.iracing.DriverSession;
import br.com.rsousa.utils.TimeUtils;
import java.util.List;
public class DriverTransformer {
public static Driver toDriver(br.com.rsousa.pojo.ams.Driver amsDriver, int position, String raceTimeFormatted, Double driverTotalTime, List<Driver> drivers) {
Driver driver = new Driver();
driver.setName(amsDriver.getName());
driver.setBestLap(amsDriver.getBestLapTime());
driver.setBestLapMilliseconds(TimeUtils.toMilliseconds(amsDriver.getBestLapTime()));
driver.setRaceTimeMilliseconds(TimeUtils.toMilliseconds(amsDriver.getFinishTime()));
driver.setLaps(amsDriver.getLaps());
driver.setPosition(position);
driver.setRaceTimeFormatted(raceTimeFormatted);
driver.setTeam(getTeamName(amsDriver.getName(), amsDriver.getTeamName(), drivers));
driver.setTeamStatistics(getTeamStatisticsName(amsDriver.getName(), amsDriver.getTeamName(), drivers));
driver.setDriverTotalTime(driverTotalTime);
return driver;
}
public static Driver toDriver(DriverSession iRacingDriver, int position, String raceTimeFormatted, List<Driver> drivers) {
Driver driver = new Driver();
driver.setName(getDriverName(iRacingDriver, drivers));
driver.setBestLap(iRacingDriver.getFastLap());
driver.setLaps(iRacingDriver.getCompletedLaps());
driver.setPosition(position);
driver.setRaceTimeFormatted(raceTimeFormatted);
driver.setBestLapMilliseconds(TimeUtils.toMilliseconds(iRacingDriver.getFastLap()));
driver.setTeam(getTeamName(iRacingDriver, drivers));
driver.setTeamStatistics(getTeamStatisticsName(iRacingDriver, drivers));
return driver;
}
public static Driver toDriver(Result assettoDriver, int position, int laps, String raceTimeFormatted, List<Driver> drivers) {
Driver driver = new Driver();
driver.setName(assettoDriver.getDriverName());
driver.setBestLapMilliseconds(assettoDriver.getBestLap());
driver.setRaceTimeMilliseconds(assettoDriver.getTotalTime());
driver.setLaps(laps);
driver.setPosition(position);
driver.setRaceTimeFormatted(raceTimeFormatted);
driver.setTeam(getTeamName(assettoDriver.getDriverName(), "Independente", drivers));
driver.setTeamStatistics(getTeamStatisticsName(assettoDriver.getDriverName(), "Independente", drivers));
return driver;
}
public static Driver toDriver(LeaderBoardLine assettoDriver, int position, int laps, String raceTimeFormatted, List<Driver> drivers) {
Driver driver = new Driver();
String driverName = assettoDriver.getCurrentDriver().getFirstName() + " " + assettoDriver.getCurrentDriver().getLastName();
driver.setName(driverName);
driver.setBestLapMilliseconds(assettoDriver.getTiming().getBestLap());
driver.setRaceTimeMilliseconds(assettoDriver.getTiming().getTotalTime());
driver.setLaps(laps);
driver.setPosition(position);
driver.setRaceTimeFormatted(raceTimeFormatted);
driver.setTeam(getTeamName(driverName, "Independente", drivers));
driver.setTeamStatistics(getTeamStatisticsName(driverName, "Independente", drivers));
return driver;
}
public static Driver toDriver(br.com.rsousa.pojo.ams2.Result result, int position, String raceTimeFormatted, List<Driver> drivers) {
Driver driver = new Driver();
driver.setName(result.getName());
driver.setBestLapMilliseconds(Long.valueOf(result.getAttributes().getFastestLapTime()));
driver.setRaceTimeMilliseconds(Long.valueOf(result.getAttributes().getTotalTime()));
driver.setLaps(result.getAttributes().getLap());
driver.setPosition(position);
driver.setRaceTimeFormatted(raceTimeFormatted);
driver.setTeam(getTeamName(result.getName(), "Independente", drivers));
driver.setTeamStatistics(getTeamStatisticsName(result.getName(), "Independente", drivers));
return driver;
}
private static String getTeamName(String driverName, String teamName, List<Driver> drivers) {
return drivers.stream().filter(d -> driverName.trim().equals(d.getName()))
.map(Driver::getTeam)
.findAny()
.orElse(teamName);
}
private static String getTeamStatisticsName(String driverName, String teamName, List<Driver> drivers) {
return drivers.stream().filter(d -> driverName.trim().equals(d.getName()))
.map(Driver::getTeamStatistics)
.findAny()
.orElse(teamName);
}
private static String getDriverName(DriverSession driver, List<Driver> drivers) {
return drivers.stream().filter(d -> driver.getId().equals(d.getId()))
.map(Driver::getName)
.findAny()
.orElse(driver.getName());
}
private static String getTeamName(DriverSession driver, List<Driver> drivers) {
return drivers.stream().filter(d -> driver.getId().equals(d.getId()))
.map(Driver::getTeam)
.findAny()
.orElse("Independente");
}
private static String getTeamStatisticsName(DriverSession driver, List<Driver> drivers) {
return drivers.stream().filter(d -> driver.getId().equals(d.getId()))
.map(Driver::getTeamStatistics)
.findAny()
.orElse("Independente");
}
}
| 5,686 | 0.694865 | 0.694689 | 121 | 45.991737 | 37.574718 | 162 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.900826 | false | false | 3 |
584a1287d2803911623185c2fc1bb98bdf9eb94f | 20,942,260,578,466 | e5f295c641efa4b6fb105055ec2b497bea720909 | /Assignments/Assignment 1/Assignment1/src/main/java/service/user/UserManagementServiceMySQL.java | 782903eb0e7a8a1b41ceb1891b0b4bf7a2c35f6c | [] | no_license | UTCN-SoftwareDesignLab/assignment-1-octav96 | https://github.com/UTCN-SoftwareDesignLab/assignment-1-octav96 | 6e693ff19f94216b81a7847a052e4eb29c1134e5 | e920c46717aaa10171573ba3289b51f2cc68c854 | refs/heads/master | 2021-04-12T06:34:24.740000 | 2018-04-01T22:34:01 | 2018-04-01T22:34:01 | 125,886,175 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package service.user;
import model.Operation;
import model.Role;
import model.User;
import model.builder.OperationBuilder;
import model.builder.UserBuilder;
import model.validation.Notification;
import model.validation.UserValidator;
import repository.operation.OperationRepository;
import repository.security.RightsRolesRepository;
import repository.user.UserRepository;
import java.security.MessageDigest;
import java.util.Collections;
import java.util.List;
import static database.Constants.Roles.CUSTOMER;
public class UserManagementServiceMySQL implements UserManagementService{
private UserRepository userRepository;
private RightsRolesRepository rightsRolesRepository;
private OperationRepository operationRepository;
private Long userId;
public UserManagementServiceMySQL(UserRepository userRepository,
RightsRolesRepository rightsRolesRepository,
OperationRepository operationRepository ) {
this.userRepository = userRepository;
this.rightsRolesRepository = rightsRolesRepository;
this.operationRepository = operationRepository;
}
@Override
public Notification<User> deleteUser(User user) {
Notification<User> notification = new Notification<>();
UserValidator userValidator = new UserValidator(user);
List<User> users = userRepository.findAll();
Boolean verify = userValidator.validateExistence(users);
if(!verify){
userValidator.getErrors().forEach(notification::addError);
notification.setResult(null);
return notification;
}else{
userRepository.deleteUser(user.getId());
Operation operation = new OperationBuilder().setOperation("USER with id = " + userId +
" deleted " + "user with id = " + user.getId())
.setEmployeeId(userId).build();
operationRepository.addOperation(operation);
notification.setResult(user);
return notification;
}
}
@Override
public Notification<User> addUser(String username, String password, String role) {
Notification<Role> customerRole = rightsRolesRepository.findRoleByTitle(role);
User user = new UserBuilder()
.setUsername(username)
.setPassword(password)
.setRoles(Collections.singletonList(customerRole.getResult()))
.build();
UserValidator userValidator = new UserValidator(user);
boolean userValid = userValidator.validate();
Notification<User> userRegisterNotification = new Notification<>();
if (!userValid) {
userValidator.getErrors().forEach(userRegisterNotification::addError);
userRegisterNotification.setResult(user);
return userRegisterNotification;
} else {
user.setPassword(encodePassword(password));
userRepository.save(user);
Operation operation = new OperationBuilder().setOperation("USER with id = " + userId +
" added a new user.")
.setEmployeeId(userId).build();
operationRepository.addOperation(operation);
// rightsRolesRepository.addRolesToUser(user,Collections.singletonList(customerRole.getResult()));
userRegisterNotification.setResult(user);
return userRegisterNotification;
}
}
@Override
public Notification<User> findUser(Long id) {
Notification<User> notification = new Notification<>();
UserValidator userValidator = new UserValidator(new UserBuilder().setId(id).build());
List<User> clients = userRepository.findAll();
Boolean verify = userValidator.validateExistence(clients);
if(!verify){
userValidator.getErrors().forEach(notification::addError);
notification.setResult(null);
return notification;
}else{
notification.setResult(userRepository.findById(id));
return notification;
}
}
@Override
public Notification<Boolean> updateUser(User user1, User user2) {
Notification<Boolean> notification = new Notification<>();
UserValidator clientValidator1 = new UserValidator(user1);
//ClientValidator clientValidator2 = new ClientValidator(client2);
List<User> users = userRepository.findAll();
Boolean verify = clientValidator1.validateExistence(users);// && clientValidator2.validateUniqueness(clients);
if(!verify){
clientValidator1.getErrors().forEach(notification::addError);
// clientValidator2.getErrors().forEach(notification::addError);
notification.setResult(Boolean.FALSE);
return notification;
}else{
user2.setPassword(encodePassword(user2.getPassword()));
userRepository.updateUser(user1, user2);
Operation operation = new OperationBuilder().setOperation("USER with id = " + userId +
" updated " + "user with id = " + user1.getId())
.setEmployeeId(userId).build();
operationRepository.addOperation(operation);
notification.setResult(Boolean.TRUE);
return notification;
}
}
private String encodePassword(String password) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(password.getBytes("UTF-8"));
StringBuilder hexString = new StringBuilder();
for (int i = 0; i < hash.length; i++) {
String hex = Integer.toHexString(0xff & hash[i]);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public List<Operation> getReportForUser(Long id){
List<Operation> operations = operationRepository.findAllForUser(new UserBuilder().setId(id).build());
return operations;
}
public void setUserId(Long id){
this.userId = id;
}
}
| UTF-8 | Java | 6,274 | java | UserManagementServiceMySQL.java | Java | [
{
"context": " = new UserBuilder()\n .setUsername(username)\n .setPassword(password)\n ",
"end": 2351,
"score": 0.9899877905845642,
"start": 2343,
"tag": "USERNAME",
"value": "username"
},
{
"context": "etUsername(username)\n .setPassword(password)\n .setRoles(Collections.singletonL",
"end": 2390,
"score": 0.9989334940910339,
"start": 2382,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "on;\n } else {\n user.setPassword(encodePassword(password));\n userRepository.save(user)",
"end": 2960,
"score": 0.7508392930030823,
"start": 2946,
"tag": "PASSWORD",
"value": "encodePassword"
},
{
"context": "ion;\n }else{\n user2.setPassword(encodePassword(user2.getPassword()));\n userRepository",
"end": 4914,
"score": 0.8329575061798096,
"start": 4900,
"tag": "PASSWORD",
"value": "encodePassword"
},
{
"context": "lse{\n user2.setPassword(encodePassword(user2.getPassword()));\n userRepository.updateUser(user1,",
"end": 4932,
"score": 0.8769997358322144,
"start": 4915,
"tag": "PASSWORD",
"value": "user2.getPassword"
}
] | null | [] | package service.user;
import model.Operation;
import model.Role;
import model.User;
import model.builder.OperationBuilder;
import model.builder.UserBuilder;
import model.validation.Notification;
import model.validation.UserValidator;
import repository.operation.OperationRepository;
import repository.security.RightsRolesRepository;
import repository.user.UserRepository;
import java.security.MessageDigest;
import java.util.Collections;
import java.util.List;
import static database.Constants.Roles.CUSTOMER;
public class UserManagementServiceMySQL implements UserManagementService{
private UserRepository userRepository;
private RightsRolesRepository rightsRolesRepository;
private OperationRepository operationRepository;
private Long userId;
public UserManagementServiceMySQL(UserRepository userRepository,
RightsRolesRepository rightsRolesRepository,
OperationRepository operationRepository ) {
this.userRepository = userRepository;
this.rightsRolesRepository = rightsRolesRepository;
this.operationRepository = operationRepository;
}
@Override
public Notification<User> deleteUser(User user) {
Notification<User> notification = new Notification<>();
UserValidator userValidator = new UserValidator(user);
List<User> users = userRepository.findAll();
Boolean verify = userValidator.validateExistence(users);
if(!verify){
userValidator.getErrors().forEach(notification::addError);
notification.setResult(null);
return notification;
}else{
userRepository.deleteUser(user.getId());
Operation operation = new OperationBuilder().setOperation("USER with id = " + userId +
" deleted " + "user with id = " + user.getId())
.setEmployeeId(userId).build();
operationRepository.addOperation(operation);
notification.setResult(user);
return notification;
}
}
@Override
public Notification<User> addUser(String username, String password, String role) {
Notification<Role> customerRole = rightsRolesRepository.findRoleByTitle(role);
User user = new UserBuilder()
.setUsername(username)
.setPassword(<PASSWORD>)
.setRoles(Collections.singletonList(customerRole.getResult()))
.build();
UserValidator userValidator = new UserValidator(user);
boolean userValid = userValidator.validate();
Notification<User> userRegisterNotification = new Notification<>();
if (!userValid) {
userValidator.getErrors().forEach(userRegisterNotification::addError);
userRegisterNotification.setResult(user);
return userRegisterNotification;
} else {
user.setPassword(<PASSWORD>(password));
userRepository.save(user);
Operation operation = new OperationBuilder().setOperation("USER with id = " + userId +
" added a new user.")
.setEmployeeId(userId).build();
operationRepository.addOperation(operation);
// rightsRolesRepository.addRolesToUser(user,Collections.singletonList(customerRole.getResult()));
userRegisterNotification.setResult(user);
return userRegisterNotification;
}
}
@Override
public Notification<User> findUser(Long id) {
Notification<User> notification = new Notification<>();
UserValidator userValidator = new UserValidator(new UserBuilder().setId(id).build());
List<User> clients = userRepository.findAll();
Boolean verify = userValidator.validateExistence(clients);
if(!verify){
userValidator.getErrors().forEach(notification::addError);
notification.setResult(null);
return notification;
}else{
notification.setResult(userRepository.findById(id));
return notification;
}
}
@Override
public Notification<Boolean> updateUser(User user1, User user2) {
Notification<Boolean> notification = new Notification<>();
UserValidator clientValidator1 = new UserValidator(user1);
//ClientValidator clientValidator2 = new ClientValidator(client2);
List<User> users = userRepository.findAll();
Boolean verify = clientValidator1.validateExistence(users);// && clientValidator2.validateUniqueness(clients);
if(!verify){
clientValidator1.getErrors().forEach(notification::addError);
// clientValidator2.getErrors().forEach(notification::addError);
notification.setResult(Boolean.FALSE);
return notification;
}else{
user2.setPassword(<PASSWORD>(<PASSWORD>()));
userRepository.updateUser(user1, user2);
Operation operation = new OperationBuilder().setOperation("USER with id = " + userId +
" updated " + "user with id = " + user1.getId())
.setEmployeeId(userId).build();
operationRepository.addOperation(operation);
notification.setResult(Boolean.TRUE);
return notification;
}
}
private String encodePassword(String password) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(password.getBytes("UTF-8"));
StringBuilder hexString = new StringBuilder();
for (int i = 0; i < hash.length; i++) {
String hex = Integer.toHexString(0xff & hash[i]);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public List<Operation> getReportForUser(Long id){
List<Operation> operations = operationRepository.findAllForUser(new UserBuilder().setId(id).build());
return operations;
}
public void setUserId(Long id){
this.userId = id;
}
}
| 6,261 | 0.649187 | 0.645521 | 155 | 39.477421 | 28.34746 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.606452 | false | false | 3 |
7c91777c96d0942a81b8a9f6c35c463a255b88fc | 8,358,006,422,011 | 418064b46ca9837bf525b0a7b330e74791ffd986 | /jdroid-android-sample/src/main/java/com/jdroid/android/sample/firebase/analytics/FirebaseAppAnalyticsTracker.java | 2e1886d77b8ff37b32911bdccbd14b66439e0243 | [
"Apache-2.0"
] | permissive | vaginessa/jdroid | https://github.com/vaginessa/jdroid | 266c40687f82b8a26dc0de0ddb670150519b7e85 | 9841989dc0834c10d8df044f808b2d25d966aad0 | refs/heads/master | 2021-05-11T03:09:28.490000 | 2018-01-17T01:05:09 | 2018-01-17T01:05:09 | 117,907,641 | 0 | 0 | Apache-2.0 | true | 2019-01-18T10:12:45 | 2018-01-18T00:02:04 | 2018-01-18T00:02:07 | 2019-01-18T06:38:40 | 34,608 | 0 | 0 | 1 | Java | false | null | package com.jdroid.android.sample.firebase.analytics;
import android.os.Bundle;
import com.jdroid.android.firebase.analytics.AbstractFirebaseAnalyticsTracker;
import com.jdroid.android.sample.analytics.AppAnalyticsTracker;
public class FirebaseAppAnalyticsTracker extends AbstractFirebaseAnalyticsTracker implements AppAnalyticsTracker {
@Override
public void trackExampleEvent() {
Bundle bundle = new Bundle();
bundle.putString("exampleParam", "exampleValue");
getFirebaseAnalyticsHelper().sendEvent("ExampleAction", bundle);
}
@Override
public void trackExampleTransaction() {
// Do nothing
}
@Override
public void trackExampleTiming() {
// Do nothing
}
}
| UTF-8 | Java | 686 | java | FirebaseAppAnalyticsTracker.java | Java | [] | null | [] | package com.jdroid.android.sample.firebase.analytics;
import android.os.Bundle;
import com.jdroid.android.firebase.analytics.AbstractFirebaseAnalyticsTracker;
import com.jdroid.android.sample.analytics.AppAnalyticsTracker;
public class FirebaseAppAnalyticsTracker extends AbstractFirebaseAnalyticsTracker implements AppAnalyticsTracker {
@Override
public void trackExampleEvent() {
Bundle bundle = new Bundle();
bundle.putString("exampleParam", "exampleValue");
getFirebaseAnalyticsHelper().sendEvent("ExampleAction", bundle);
}
@Override
public void trackExampleTransaction() {
// Do nothing
}
@Override
public void trackExampleTiming() {
// Do nothing
}
}
| 686 | 0.793003 | 0.793003 | 27 | 24.407408 | 29.226141 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.111111 | false | false | 3 |
6232ea2a845fa65ad722c204c96ee8d7313d87ec | 27,908,697,540,442 | bad11b457c7ee7550e50fdf2e78a41e55c93c18f | /src/main/java/de/fau/screenshotter/Util.java | f742b97f863062ace0523d07221312325c35aa7f | [] | no_license | crzndx/ScreenShotter | https://github.com/crzndx/ScreenShotter | 1f453e75e2945120151621cf88bdd1e1a4382d16 | f93db5d6a24530ee03e9109638956b1b51de9952 | refs/heads/master | 2021-01-01T19:52:04.677000 | 2013-12-03T05:55:38 | 2013-12-03T05:55:38 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package de.fau.screenshotter;
import java.awt.*;
import java.net.URL;
public class Util {
/**
* @param pathAndFileName The resource name, relative to /src/main/resources/
* @return An image from the specified path
* @see <a href="http://stackoverflow.com/a/10465041/488265">http://stackoverflow.com/a/10465041/488265</a>
*/
public static Image getImage(final String pathAndFileName) {
final URL url = Thread.currentThread().getContextClassLoader().getResource(pathAndFileName);
if (null == url) {
return null;
}
return Toolkit.getDefaultToolkit().getImage(url);
}
}
| UTF-8 | Java | 644 | java | Util.java | Java | [] | null | [] | package de.fau.screenshotter;
import java.awt.*;
import java.net.URL;
public class Util {
/**
* @param pathAndFileName The resource name, relative to /src/main/resources/
* @return An image from the specified path
* @see <a href="http://stackoverflow.com/a/10465041/488265">http://stackoverflow.com/a/10465041/488265</a>
*/
public static Image getImage(final String pathAndFileName) {
final URL url = Thread.currentThread().getContextClassLoader().getResource(pathAndFileName);
if (null == url) {
return null;
}
return Toolkit.getDefaultToolkit().getImage(url);
}
}
| 644 | 0.667702 | 0.624224 | 19 | 32.894737 | 33.450504 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.368421 | false | false | 3 |
e5e8335b92157e8666c9f8d44eac9c4f4743be3c | 11,098,195,493,599 | 64d299ef26e2b18b2faab62ebadce8b63158b1ba | /src/algorithm/programmers/level2/Study7.java | 9cf6f5621e6014bfd3c8e99fb3448d3477b8849b | [] | no_license | NaKyouTae/algorithm | https://github.com/NaKyouTae/algorithm | 7cb530ce2161ac6be5ae4fd4c31fd88e422932c2 | eedb6a012782e58f504d79498d2b39ce140830e5 | refs/heads/master | 2023-08-29T16:15:02.066000 | 2021-11-01T02:21:56 | 2021-11-01T02:21:56 | 367,398,692 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package algorithm.programmers.level2;
/**
* 숫자의 표현
* */
public class Study7 {
public static void main(String[] args) {
int n = 15;
int cnt = 0;
for(int i = 1; i <= n; i++) {
int sum = 0;
for (int j = i; j <= n; j++) {
sum += j;
if(sum > n) break;
if(n == sum) {
cnt++;
break;
}
}
}
System.out.println(cnt);
}
}
| UTF-8 | Java | 514 | java | Study7.java | Java | [] | null | [] | package algorithm.programmers.level2;
/**
* 숫자의 표현
* */
public class Study7 {
public static void main(String[] args) {
int n = 15;
int cnt = 0;
for(int i = 1; i <= n; i++) {
int sum = 0;
for (int j = i; j <= n; j++) {
sum += j;
if(sum > n) break;
if(n == sum) {
cnt++;
break;
}
}
}
System.out.println(cnt);
}
}
| 514 | 0.347222 | 0.333333 | 25 | 19.16 | 13.820796 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.52 | false | false | 3 |
726caaf2042edd398d0b209204a1ee5465ff2339 | 9,397,388,502,742 | 28d45f096319f3eb4aff9bad1eff530a05b1cc41 | /quote_jdbc/com/ibm/dsw/quote/submittedquote/domain/jdbc/SpecialBidApprvr_jdbc.java | bae5944d8a2e4e4044a14e491736a5fbb52dedf5 | [] | no_license | zmmwl/dsw | https://github.com/zmmwl/dsw | 4a3f53413e63d8f5ed3caa0f3423f20aec8d67ba | 94fab0433a4e40425561a07f218361a0294aded5 | refs/heads/master | 2016-09-10T20:11:08.842000 | 2015-06-16T09:41:48 | 2015-06-16T09:41:48 | 35,540,090 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ibm.dsw.quote.submittedquote.domain.jdbc;
import java.sql.Connection;
import com.ibm.dsw.quote.common.domain.Domain;
import com.ibm.dsw.quote.submittedquote.domain.SpecialBidApprvr_Impl;
import com.ibm.ead4j.topaz.exception.TopazException;
import com.ibm.ead4j.topaz.persistence.jdbc.PersistentObject;
/**
* Copyright 2007 by IBM Corporation All rights reserved.
*
* This software is the confidential and proprietary information of IBM
* Corporation. ("Confidential Information").
*
* This <code>SpecialBidApprvr_jdbc<code> class.
*
* @author: wangtt@cn.ibm.com
*
* Creation date: May 15, 2007
*/
public class SpecialBidApprvr_jdbc extends SpecialBidApprvr_Impl implements PersistentObject {
transient SpecialBidApprvrPersister persister;
/**
*
*/
public SpecialBidApprvr_jdbc() {
super();
persister = new SpecialBidApprvrPersister(this);
}
/*
* (non-Javadoc)
*
* @see com.ibm.ead4j.topaz.persistence.jdbc.PersistentObject#hydrate(java.sql.Connection)
*/
public void hydrate(Connection connection) throws TopazException {
//do nothing
}
/*
* (non-Javadoc)
*
* @see com.ibm.ead4j.topaz.persistence.jdbc.PersistentObject#persist(java.sql.Connection)
*/
public void persist(Connection connection) throws TopazException {
persister.persist(connection);
}
/*
* (non-Javadoc)
*
* @see com.ibm.ead4j.topaz.persistence.jdbc.PersistentObjectState#isDeleted(boolean)
*/
public void isDeleted(boolean deleteState) throws TopazException {
//do nothing
}
/*
* (non-Javadoc)
*
* @see com.ibm.ead4j.topaz.persistence.jdbc.PersistentObjectState#isNew(boolean)
*/
public void isNew(boolean newState) throws TopazException {
persister.isNew(newState);
}
/*
* (non-Javadoc)
*
* @see com.ibm.dsw.quote.submittedquote.domain.SpecialBidApprvr#setWebQuoteNum(java.lang.String)
*/
public void setWebQuoteNum(String webQuoteNum) throws Exception {
super.setWebQuoteNum(webQuoteNum);
markAsModified();
}
/*
* (non-Javadoc)
*
* @see com.ibm.dsw.quote.submittedquote.domain.SpecialBidApprvr#setSpecialBidApprGrp(java.lang.String)
*/
public void setSpecialBidApprGrp(String specialBidApprGrp) throws Exception {
super.setSpecialBidApprGrp(specialBidApprGrp);
markAsModified();
}
/*
* (non-Javadoc)
*
* @see com.ibm.dsw.quote.submittedquote.domain.SpecialBidApprvr#setApprvrEmail(java.lang.String)
*/
public void setApprvrEmail(String apprvrEmail) throws Exception {
super.setApprvrEmail(apprvrEmail);
markAsModified();
}
/*
* (non-Javadoc)
*
* @see com.ibm.dsw.quote.submittedquote.domain.SpecialBidApprvr#setApprvrAction(java.lang.String)
*/
public void setApprvrAction(String apprvrAction) throws Exception {
super.setApprvrAction(apprvrAction);
markAsModified();
}
/*
* (non-Javadoc)
* @see com.ibm.dsw.quote.submittedquote.domain.SpecialBidApprvr#setSpecialBidApprLvl(int)
*/
public void setSpecialBidApprLvl(int specialBidApprLvl) throws Exception {
super.setSpecialBidApprLvl(specialBidApprLvl);
markAsModified();
}
public void markAsModified() throws Exception{
super.markAsModified();
if(getMode() == Domain.DOMAIN_MODE_PO){
persister.setDirty();
}
}
public void setMode(int mode) throws Exception{
super.setMode(mode);
if(mode == Domain.DOMAIN_MODE_PO && isModified()){
persister.setDirty();
}
}
public void setReturnReason(String returnReason) throws Exception {
// TODO Auto-generated method stub
super.setReturnReason(returnReason);
markAsModified();
}
}
| UTF-8 | Java | 4,077 | java | SpecialBidApprvr_jdbc.java | Java | [
{
"context": "alBidApprvr_jdbc<code> class.\r\n * \r\n * @author: wangtt@cn.ibm.com\r\n * \r\n * Creation date: May 15, 2007\r\n */\r\npublic",
"end": 607,
"score": 0.9999239444732666,
"start": 590,
"tag": "EMAIL",
"value": "wangtt@cn.ibm.com"
}
] | null | [] | package com.ibm.dsw.quote.submittedquote.domain.jdbc;
import java.sql.Connection;
import com.ibm.dsw.quote.common.domain.Domain;
import com.ibm.dsw.quote.submittedquote.domain.SpecialBidApprvr_Impl;
import com.ibm.ead4j.topaz.exception.TopazException;
import com.ibm.ead4j.topaz.persistence.jdbc.PersistentObject;
/**
* Copyright 2007 by IBM Corporation All rights reserved.
*
* This software is the confidential and proprietary information of IBM
* Corporation. ("Confidential Information").
*
* This <code>SpecialBidApprvr_jdbc<code> class.
*
* @author: <EMAIL>
*
* Creation date: May 15, 2007
*/
public class SpecialBidApprvr_jdbc extends SpecialBidApprvr_Impl implements PersistentObject {
transient SpecialBidApprvrPersister persister;
/**
*
*/
public SpecialBidApprvr_jdbc() {
super();
persister = new SpecialBidApprvrPersister(this);
}
/*
* (non-Javadoc)
*
* @see com.ibm.ead4j.topaz.persistence.jdbc.PersistentObject#hydrate(java.sql.Connection)
*/
public void hydrate(Connection connection) throws TopazException {
//do nothing
}
/*
* (non-Javadoc)
*
* @see com.ibm.ead4j.topaz.persistence.jdbc.PersistentObject#persist(java.sql.Connection)
*/
public void persist(Connection connection) throws TopazException {
persister.persist(connection);
}
/*
* (non-Javadoc)
*
* @see com.ibm.ead4j.topaz.persistence.jdbc.PersistentObjectState#isDeleted(boolean)
*/
public void isDeleted(boolean deleteState) throws TopazException {
//do nothing
}
/*
* (non-Javadoc)
*
* @see com.ibm.ead4j.topaz.persistence.jdbc.PersistentObjectState#isNew(boolean)
*/
public void isNew(boolean newState) throws TopazException {
persister.isNew(newState);
}
/*
* (non-Javadoc)
*
* @see com.ibm.dsw.quote.submittedquote.domain.SpecialBidApprvr#setWebQuoteNum(java.lang.String)
*/
public void setWebQuoteNum(String webQuoteNum) throws Exception {
super.setWebQuoteNum(webQuoteNum);
markAsModified();
}
/*
* (non-Javadoc)
*
* @see com.ibm.dsw.quote.submittedquote.domain.SpecialBidApprvr#setSpecialBidApprGrp(java.lang.String)
*/
public void setSpecialBidApprGrp(String specialBidApprGrp) throws Exception {
super.setSpecialBidApprGrp(specialBidApprGrp);
markAsModified();
}
/*
* (non-Javadoc)
*
* @see com.ibm.dsw.quote.submittedquote.domain.SpecialBidApprvr#setApprvrEmail(java.lang.String)
*/
public void setApprvrEmail(String apprvrEmail) throws Exception {
super.setApprvrEmail(apprvrEmail);
markAsModified();
}
/*
* (non-Javadoc)
*
* @see com.ibm.dsw.quote.submittedquote.domain.SpecialBidApprvr#setApprvrAction(java.lang.String)
*/
public void setApprvrAction(String apprvrAction) throws Exception {
super.setApprvrAction(apprvrAction);
markAsModified();
}
/*
* (non-Javadoc)
* @see com.ibm.dsw.quote.submittedquote.domain.SpecialBidApprvr#setSpecialBidApprLvl(int)
*/
public void setSpecialBidApprLvl(int specialBidApprLvl) throws Exception {
super.setSpecialBidApprLvl(specialBidApprLvl);
markAsModified();
}
public void markAsModified() throws Exception{
super.markAsModified();
if(getMode() == Domain.DOMAIN_MODE_PO){
persister.setDirty();
}
}
public void setMode(int mode) throws Exception{
super.setMode(mode);
if(mode == Domain.DOMAIN_MODE_PO && isModified()){
persister.setDirty();
}
}
public void setReturnReason(String returnReason) throws Exception {
// TODO Auto-generated method stub
super.setReturnReason(returnReason);
markAsModified();
}
}
| 4,067 | 0.647044 | 0.64312 | 139 | 27.330935 | 29.242569 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.258993 | false | false | 3 |
dd7ded0a27d683c567b8ff6ef68456f71ee30271 | 32,590,211,876,198 | ba122c5d3bf9327189c68ec6510fe9e12c1fa11c | /src/main/java/com/wl/school/admin/schoolIndexShow/service/impl/SchoolIndexShowService.java | 2e747428133cf8f8fa9d9fc0c3c3282e89444df8 | [] | no_license | wang6421453/SchoolWeb | https://github.com/wang6421453/SchoolWeb | 7caf0a2cf59706ea3877143cc697528cd9fdc2f3 | 081bb1a958442945d50bc4fa3333881fbd3fd87f | refs/heads/master | 2021-01-11T13:47:57.794000 | 2017-11-22T09:49:09 | 2017-11-22T09:49:09 | 86,526,698 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.wl.school.admin.schoolIndexShow.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.wl.school.admin.schoolIndexShow.dao.SchoolIndexShowDao;
import com.wl.school.admin.schoolIndexShow.model.SchoolIndexShowVo;
import com.wl.school.admin.schoolIndexShow.service.ISchoolIndexShowService;
@SuppressWarnings("restriction")
@Service
public class SchoolIndexShowService implements ISchoolIndexShowService{
@Resource
private SchoolIndexShowDao dao;
/**获取列表*/
public List<SchoolIndexShowVo> getSchoolIndexShowList(SchoolIndexShowVo schoolIndexShowVo){
String statement = "wl.mapping.school.schoolIndexShowMapper.getSchoolIndexShowList";
return dao.selectList(statement, schoolIndexShowVo);
}
/**根据id获取对象*/
public SchoolIndexShowVo getSchoolIndexShowById(String id){
String statement = "wl.mapping.school.schoolIndexShowMapper.getSchoolIndexShowById";
return dao.selectById(statement, id);
}
/**
* 获取数量
* @return 数量
*/
public int getSchoolIndexShowCount(SchoolIndexShowVo schoolIndexShowVo){
String statement = "wl.mapping.school.schoolIndexShowMapper.getSchoolIndexShowCount";
return dao.selectCount(statement, schoolIndexShowVo);
}
/**
* 新增
* @return 是否成功
*/
@Transactional
public int addSchoolIndexShow(SchoolIndexShowVo schoolIndexShowVo){
String statement = "wl.mapping.school.schoolIndexShowMapper.addSchoolIndexShow";
int result = dao.insert(statement, schoolIndexShowVo);
return result;
}
/**
* 删除
*/
@Transactional
public int deleteSchoolIndexShow(List<String> ids){
String statement = "wl.mapping.school.schoolIndexShowMapper.deleteSchoolIndexShow";
int result = dao.delete(statement, ids);
return result;
}
/**
* 发布
*/
@Transactional
public int commitSchoolIndexShow(List<String> ids){
String statement = "wl.mapping.school.schoolIndexShowMapper.commitSchoolIndexShow";
int result = dao.commitProject(statement, ids);
return result;
}
/**
* 更新
*/
@Transactional
public int updateSchoolIndexShow(SchoolIndexShowVo schoolIndexShowVo){
String statement = "wl.mapping.school.schoolIndexShowMapper.updateSchoolIndexShow";
int result = dao.update(statement, schoolIndexShowVo);
return result;
}
}
| UTF-8 | Java | 2,424 | java | SchoolIndexShowService.java | Java | [] | null | [] | package com.wl.school.admin.schoolIndexShow.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.wl.school.admin.schoolIndexShow.dao.SchoolIndexShowDao;
import com.wl.school.admin.schoolIndexShow.model.SchoolIndexShowVo;
import com.wl.school.admin.schoolIndexShow.service.ISchoolIndexShowService;
@SuppressWarnings("restriction")
@Service
public class SchoolIndexShowService implements ISchoolIndexShowService{
@Resource
private SchoolIndexShowDao dao;
/**获取列表*/
public List<SchoolIndexShowVo> getSchoolIndexShowList(SchoolIndexShowVo schoolIndexShowVo){
String statement = "wl.mapping.school.schoolIndexShowMapper.getSchoolIndexShowList";
return dao.selectList(statement, schoolIndexShowVo);
}
/**根据id获取对象*/
public SchoolIndexShowVo getSchoolIndexShowById(String id){
String statement = "wl.mapping.school.schoolIndexShowMapper.getSchoolIndexShowById";
return dao.selectById(statement, id);
}
/**
* 获取数量
* @return 数量
*/
public int getSchoolIndexShowCount(SchoolIndexShowVo schoolIndexShowVo){
String statement = "wl.mapping.school.schoolIndexShowMapper.getSchoolIndexShowCount";
return dao.selectCount(statement, schoolIndexShowVo);
}
/**
* 新增
* @return 是否成功
*/
@Transactional
public int addSchoolIndexShow(SchoolIndexShowVo schoolIndexShowVo){
String statement = "wl.mapping.school.schoolIndexShowMapper.addSchoolIndexShow";
int result = dao.insert(statement, schoolIndexShowVo);
return result;
}
/**
* 删除
*/
@Transactional
public int deleteSchoolIndexShow(List<String> ids){
String statement = "wl.mapping.school.schoolIndexShowMapper.deleteSchoolIndexShow";
int result = dao.delete(statement, ids);
return result;
}
/**
* 发布
*/
@Transactional
public int commitSchoolIndexShow(List<String> ids){
String statement = "wl.mapping.school.schoolIndexShowMapper.commitSchoolIndexShow";
int result = dao.commitProject(statement, ids);
return result;
}
/**
* 更新
*/
@Transactional
public int updateSchoolIndexShow(SchoolIndexShowVo schoolIndexShowVo){
String statement = "wl.mapping.school.schoolIndexShowMapper.updateSchoolIndexShow";
int result = dao.update(statement, schoolIndexShowVo);
return result;
}
}
| 2,424 | 0.781672 | 0.781672 | 83 | 27.530121 | 29.960752 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.361446 | false | false | 3 |
fd4141535b40716b01281b65958d88d5359c12a4 | 30,279,519,465,305 | ac6a62b1d4d73222d8816b71f351a9f507ed6b44 | /service-provider/src/main/java/org/sj/ws/rest/support/BloggingResourceV1.java | 42d464763a4939c0404a2d2ebef4aa8ad87a90b4 | [] | no_license | sangramjadhav/java-rest-quickstart | https://github.com/sangramjadhav/java-rest-quickstart | 83f6d1326e9bd4641eaa48a1693b68e6dfd78355 | ccbb7c5a4e7e00c02cbba48cfa1de7615419a0cb | refs/heads/master | 2021-01-01T04:11:01.952000 | 2016-04-21T15:51:55 | 2016-04-21T15:51:55 | 56,710,992 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.sj.ws.rest.support;
import org.dozer.Mapper;
import org.sj.ws.rest.model.BlogPost;
import org.sj.ws.rest.service.BloggingService;
import org.sj.ws.rest.v1.entity.Post;
import org.sj.ws.rest.v1.service.BloggingResource;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import java.util.ArrayList;
import java.util.List;
public class BloggingResourceV1 implements BloggingResource {
private BloggingService service;
private Mapper mapper;
public BloggingResourceV1(BloggingService service, Mapper mapper) {
this.service = service;
this.mapper = mapper;
}
@Override
public List<Post> getPosts() {
List<BlogPost> posts = service.getAllPosts();
List<Post> dtoPosts = new ArrayList<Post>(posts.size());
for (BlogPost blogPost : posts) {
dtoPosts.add(mapper.map(blogPost, Post.class));
}
return dtoPosts;
}
@Override
public Post getPost(int id) {
BlogPost post = service.getPost(id);
if (post == null) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
return mapper.map(post, Post.class);
}
@Override
public Response addPost(Post post) {
int id = service.addPost(mapper.map(post, BlogPost.class));
return Response.created(UriBuilder.fromPath(Integer.toString(id)).build()).build();
}
@Override
public Response updatePost(int id, Post post) {
boolean success = service.updatePost(id, mapper.map(post, BlogPost.class));
if (!success) {
throw new WebApplicationException(Response.Status.NOT_MODIFIED);
}
return Response.ok().build();
}
@Override
public Response deletePost(int id) {
boolean success = service.deletePost(id);
if (!success) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
return Response.ok().build();
}
} | UTF-8 | Java | 2,023 | java | BloggingResourceV1.java | Java | [] | null | [] | package org.sj.ws.rest.support;
import org.dozer.Mapper;
import org.sj.ws.rest.model.BlogPost;
import org.sj.ws.rest.service.BloggingService;
import org.sj.ws.rest.v1.entity.Post;
import org.sj.ws.rest.v1.service.BloggingResource;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import java.util.ArrayList;
import java.util.List;
public class BloggingResourceV1 implements BloggingResource {
private BloggingService service;
private Mapper mapper;
public BloggingResourceV1(BloggingService service, Mapper mapper) {
this.service = service;
this.mapper = mapper;
}
@Override
public List<Post> getPosts() {
List<BlogPost> posts = service.getAllPosts();
List<Post> dtoPosts = new ArrayList<Post>(posts.size());
for (BlogPost blogPost : posts) {
dtoPosts.add(mapper.map(blogPost, Post.class));
}
return dtoPosts;
}
@Override
public Post getPost(int id) {
BlogPost post = service.getPost(id);
if (post == null) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
return mapper.map(post, Post.class);
}
@Override
public Response addPost(Post post) {
int id = service.addPost(mapper.map(post, BlogPost.class));
return Response.created(UriBuilder.fromPath(Integer.toString(id)).build()).build();
}
@Override
public Response updatePost(int id, Post post) {
boolean success = service.updatePost(id, mapper.map(post, BlogPost.class));
if (!success) {
throw new WebApplicationException(Response.Status.NOT_MODIFIED);
}
return Response.ok().build();
}
@Override
public Response deletePost(int id) {
boolean success = service.deletePost(id);
if (!success) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
return Response.ok().build();
}
} | 2,023 | 0.660405 | 0.658428 | 67 | 29.208956 | 23.984159 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.552239 | false | false | 3 |
7862da55418f6f600a44b5e907764c84d93d81e6 | 24,455,543,805,077 | 8bd94b96f67d9be166e5f3412423acd8cac137ce | /src/main/java/com/algaworks/algafood/jpa/manterCozinha/InclusaoCozinha.java | f19d4da1e53ed539d3f4c98b1684841827bec380 | [] | no_license | janfernandes/algafood-spring-rest | https://github.com/janfernandes/algafood-spring-rest | f52e4baf4c1b2035b930ed62fd26b595a907ed6b | a23a2f430a5d9a9345a9a9988d20b16e1efd6f8f | refs/heads/master | 2023-06-28T01:42:38.526000 | 2021-08-01T19:19:51 | 2021-08-01T19:19:51 | 232,549,870 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.algaworks.algafood.jpa.manterCozinha;
import com.algaworks.algafood.AlgafoodApplication;
import com.algaworks.algafood.domain.model.Cozinha;
import com.algaworks.algafood.domain.repository.CozinhaRepository;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ApplicationContext;
public class InclusaoCozinha {
public static void main(String[] args) {
ApplicationContext applicationContext = new SpringApplicationBuilder(AlgafoodApplication.class)
.web(WebApplicationType.NONE)
.run(args);
CozinhaRepository cozinhaRepository = applicationContext.getBean(CozinhaRepository.class);
Cozinha cozinha1 = new Cozinha();
cozinha1.setNome("Brasileira");
Cozinha cozinha2 = new Cozinha();
cozinha2.setNome("Japonesa");
cozinhaRepository.save(cozinha1);
cozinhaRepository.save(cozinha2);
System.out.printf("%d - %s\n", cozinha1.getId(), cozinha1.getNome());
System.out.printf("%d - %s\n", cozinha2.getId(), cozinha2.getNome());
}
}
| UTF-8 | Java | 1,164 | java | InclusaoCozinha.java | Java | [] | null | [] | package com.algaworks.algafood.jpa.manterCozinha;
import com.algaworks.algafood.AlgafoodApplication;
import com.algaworks.algafood.domain.model.Cozinha;
import com.algaworks.algafood.domain.repository.CozinhaRepository;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ApplicationContext;
public class InclusaoCozinha {
public static void main(String[] args) {
ApplicationContext applicationContext = new SpringApplicationBuilder(AlgafoodApplication.class)
.web(WebApplicationType.NONE)
.run(args);
CozinhaRepository cozinhaRepository = applicationContext.getBean(CozinhaRepository.class);
Cozinha cozinha1 = new Cozinha();
cozinha1.setNome("Brasileira");
Cozinha cozinha2 = new Cozinha();
cozinha2.setNome("Japonesa");
cozinhaRepository.save(cozinha1);
cozinhaRepository.save(cozinha2);
System.out.printf("%d - %s\n", cozinha1.getId(), cozinha1.getNome());
System.out.printf("%d - %s\n", cozinha2.getId(), cozinha2.getNome());
}
}
| 1,164 | 0.729381 | 0.72079 | 31 | 36.548386 | 29.779663 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.677419 | false | false | 3 |
26e4020a6e976e048a88cc24fb3a1bbd938cc361 | 32,461,362,834,956 | b618ec68763b26161d3235c8296ef086e93d91ce | /Control Panel/src/server/tether/ServerTether.java | 391affe69d9387bbfe74a8da8642125617659288 | [] | no_license | owenvnek/ProjectA | https://github.com/owenvnek/ProjectA | 2d3ea7b31c5794385b7b71c2d253bd5b8059788a | 916d3e4f9ca7ce3ba6f91bd63681256226dd20f6 | refs/heads/master | 2021-09-02T03:57:51.982000 | 2017-12-30T05:31:23 | 2017-12-30T05:31:23 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package server.tether;
import lib.niodatatransmission.data.DataPacket;
public class ServerTether {
public ServerTether() {
}
public DataPacket receive() {
}
public void send(final DataPacket dataPacket) {
}
}
| UTF-8 | Java | 242 | java | ServerTether.java | Java | [] | null | [] | package server.tether;
import lib.niodatatransmission.data.DataPacket;
public class ServerTether {
public ServerTether() {
}
public DataPacket receive() {
}
public void send(final DataPacket dataPacket) {
}
}
| 242 | 0.677686 | 0.677686 | 19 | 11.736842 | 16.70122 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.105263 | false | false | 3 |
617d0518e91f26459025d03124cfb488caa7a6a5 | 29,661,044,185,281 | df34764057ba5455a894cedf94014393ae328f4e | /java_code/drivers/snowbros.java | 26ac0b771aea679289081c80efc57ffea62ca0b2 | [] | no_license | arcadeflex/arcadeflex037b5convertor | https://github.com/arcadeflex/arcadeflex037b5convertor | 00ae5cfce82482d570998a37ebdcfde133378cd3 | 76fea1187d6050d4e1451eec645fca0c25cd96ca | refs/heads/master | 2020-05-20T17:14:29.474000 | 2016-05-01T10:58:09 | 2016-05-01T10:58:09 | 84,493,226 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /***************************************************************************
Snow Brothers
driver by Mike Coates
***************************************************************************/
/*
* ported to v0.37b5
* using automatic conversion tool v0.01
*/
package drivers;
public class snowbros
{
static unsigned char *ram;
extern unsigned char *snowbros_spriteram;
public static InterruptPtr snowbros_interrupt = new InterruptPtr() { public int handler()
{
return cpu_getiloops() + 2; /* IRQs 4, 3, and 2 */
} };
public static ReadHandlerPtr snowbros_input_r = new ReadHandlerPtr() { public int handler(int offset)
{
int ans = 0xff;
switch (offset)
{
case 0:
ans = (input_port_0_r.handler (offset) << 8) + (input_port_3_r.handler (offset));
break;
case 2:
ans = (input_port_1_r.handler (offset) << 8) + (input_port_4_r.handler (offset));
break;
case 4:
ans = input_port_2_r.handler (offset) << 8;
break;
}
return ans;
} };
/* Sound Routines */
public static ReadHandlerPtr snowbros_68000_sound_r = new ReadHandlerPtr() { public int handler(int offset)
{
int ret;
/* If the sound CPU is running, read the YM3812 status, otherwise
just make it pass the test */
if (Machine.sample_rate != 0)
{
ret = soundlatch_r(offset);
}
else
{
ret = 3;
}
return ret;
} };
public static WriteHandlerPtr snowbros_68000_sound_w = new WriteHandlerPtr() {public void handler(int offset, int data)
{
soundlatch_w.handler(offset,data);
cpu_cause_interrupt(1,Z80_NMI_INT);
} };
static MemoryReadAddress readmem[] =
{
new MemoryReadAddress( 0x000000, 0x03ffff, MRA_ROM ),
new MemoryReadAddress( 0x100000, 0x103fff, MRA_BANK1 ),
new MemoryReadAddress( 0x300000, 0x300001, snowbros_68000_sound_r ),
new MemoryReadAddress( 0x500000, 0x500005, snowbros_input_r ),
new MemoryReadAddress( 0x600000, 0x6001ff, paletteram_word_r ),
new MemoryReadAddress( 0x700000, 0x701dff, snowbros_spriteram_r ),
new MemoryReadAddress( -1 ) /* end of table */
};
static MemoryWriteAddress writemem[] =
{
new MemoryWriteAddress( 0x000000, 0x03ffff, MWA_ROM ),
new MemoryWriteAddress( 0x100000, 0x103fff, MWA_BANK1, ram ),
new MemoryWriteAddress( 0x200000, 0x200001, watchdog_reset_w ),
new MemoryWriteAddress( 0x300000, 0x300001, snowbros_68000_sound_w ),
// new MemoryWriteAddress( 0x400000, 0x400001, snowbros_interrupt_enable_w ),
new MemoryWriteAddress( 0x600000, 0x6001ff, paletteram_xBBBBBGGGGGRRRRR_word_w, paletteram ),
new MemoryWriteAddress( 0x700000, 0x701dff, snowbros_spriteram_w, snowbros_spriteram, videoram_size ),
new MemoryWriteAddress( 0x800000, 0x800001, MWA_NOP ), /* IRQ 4 acknowledge? */
new MemoryWriteAddress( 0x900000, 0x900001, MWA_NOP ), /* IRQ 3 acknowledge? */
new MemoryWriteAddress( 0xa00000, 0xa00001, MWA_NOP ), /* IRQ 2 acknowledge? */
new MemoryWriteAddress( -1 ) /* end of table */
};
static MemoryReadAddress sound_readmem[] =
{
new MemoryReadAddress( 0x0000, 0x7fff, MRA_ROM ),
new MemoryReadAddress( 0x8000, 0x87ff, MRA_RAM ),
new MemoryReadAddress( -1 ) /* end of table */
};
static MemoryWriteAddress sound_writemem[] =
{
new MemoryWriteAddress( 0x0000, 0x7fff, MWA_ROM ),
new MemoryWriteAddress( 0x8000, 0x87ff, MWA_RAM ),
new MemoryWriteAddress( -1 ) /* end of table */
};
static IOReadPort sound_readport[] =
{
new IOReadPort( 0x02, 0x02, YM3812_status_port_0_r ),
new IOReadPort( 0x04, 0x04, soundlatch_r ),
new IOReadPort( -1 ) /* end of table */
};
static IOWritePort sound_writeport[] =
{
new IOWritePort( 0x02, 0x02, YM3812_control_port_0_w ),
new IOWritePort( 0x03, 0x03, YM3812_write_port_0_w ),
new IOWritePort( 0x04, 0x04, soundlatch_w ), /* goes back to the main CPU, checked during boot */
new IOWritePort( -1 ) /* end of table */
};
static InputPortPtr input_ports_snowbros = new InputPortPtr(){ public void handler() {
PORT_START(); /* 500001 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY );
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY );
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY );
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY );
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 );
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 );
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_BUTTON3 );
PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_UNKNOWN );/* Must be low or game stops! */
/* probably VBlank */
PORT_START(); /* 500003 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY | IPF_PLAYER2 );
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY | IPF_PLAYER2 );
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY | IPF_PLAYER2 );
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY | IPF_PLAYER2 );
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER2 );
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_PLAYER2 );
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_BUTTON3 | IPF_PLAYER2 );
PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_UNKNOWN );
PORT_START(); /* 500005 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_START1 );
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_START2 );
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_COIN1 );
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_COIN2 );
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNKNOWN );
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_TILT );
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_COIN3 );
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN );
PORT_START(); /* DSW 1 */
PORT_DIPNAME( 0x01, 0x01, "Country (Affects Coinage); )
PORT_DIPSETTING( 0x01, "America" );
PORT_DIPSETTING( 0x00, "Europe" );
PORT_DIPNAME( 0x02, 0x02, DEF_STR( "Flip_Screen") );
PORT_DIPSETTING( 0x02, DEF_STR( "Off") );
PORT_DIPSETTING( 0x00, DEF_STR( "On") );
PORT_SERVICE( 0x04, IP_ACTIVE_LOW );
PORT_DIPNAME( 0x08, 0x08, DEF_STR( "Demo_Sounds") );
PORT_DIPSETTING( 0x00, DEF_STR( "Off") );
PORT_DIPSETTING( 0x08, DEF_STR( "On") );
/* Better to implement a coin mode 1-2 stuff later */
PORT_DIPNAME( 0x30, 0x30, "Coin A America/Europe" );
PORT_DIPSETTING( 0x10, "2C/1C 3C/1C" );
PORT_DIPSETTING( 0x30, DEF_STR( "1C_1C") );
PORT_DIPSETTING( 0x00, "2C/3C 4C/1C" );
PORT_DIPSETTING( 0x20, "1C/2C 2C/1C" );
PORT_DIPNAME( 0xc0, 0xc0, "Coin B America/Europe" );
PORT_DIPSETTING( 0x40, "2C/1C 1C/4C" );
PORT_DIPSETTING( 0xc0, "1C/1C 1C/2C" );
PORT_DIPSETTING( 0x00, "2C/3C 1C/6C" );
PORT_DIPSETTING( 0x80, "1C/2C 1C/3C" );
PORT_START(); /* DSW 2 */
PORT_DIPNAME( 0x03, 0x03, DEF_STR( "Difficulty") );
PORT_DIPSETTING( 0x02, "Easy" );
PORT_DIPSETTING( 0x03, "Normal" );
PORT_DIPSETTING( 0x01, "Hard" );
PORT_DIPSETTING( 0x00, "Hardest" );
PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( "Bonus_Life") );
PORT_DIPSETTING( 0x04, "100k and every 200k " );
PORT_DIPSETTING( 0x0c, "100k Only" );
PORT_DIPSETTING( 0x08, "200k Only" );
PORT_DIPSETTING( 0x00, "None" );
PORT_DIPNAME( 0x30, 0x30, DEF_STR( "Lives") );
PORT_DIPSETTING( 0x20, "1" );
PORT_DIPSETTING( 0x00, "2" );
PORT_DIPSETTING( 0x30, "3" );
PORT_DIPSETTING( 0x10, "4" );
PORT_BITX( 0x40, 0x40, IPT_DIPSWITCH_NAME | IPF_CHEAT, "Invulnerability", IP_KEY_NONE, IP_JOY_NONE );
PORT_DIPSETTING( 0x40, DEF_STR( "Off") );
PORT_DIPSETTING( 0x00, DEF_STR( "On") );
PORT_DIPNAME( 0x80, 0x80, "Allow Continue" );
PORT_DIPSETTING( 0x00, DEF_STR( "No") );
PORT_DIPSETTING( 0x80, DEF_STR( "Yes") );
INPUT_PORTS_END(); }};
static GfxLayout tilelayout = new GfxLayout
(
16,16, /* 16*16 sprites */
4096, /* 4096 sprites */
4, /* 4 bits per pixel */
new int[] { 0, 1, 2, 3 },
new int[] {
0, 4, 8, 12, 16, 20, 24, 28,
8*32+0, 8*32+4, 8*32+8, 8*32+12, 8*32+16, 8*32+20, 8*32+24, 8*32+28,
},
new int[] {
0*32, 1*32, 2*32, 3*32, 4*32, 5*32, 6*32, 7*32,
16*32, 17*32, 18*32, 19*32, 20*32, 21*32, 22*32, 23*32
},
128*8
);
static GfxDecodeInfo gfxdecodeinfo[] =
{
new GfxDecodeInfo( REGION_GFX1, 0, tilelayout, 0, 16 ),
new GfxDecodeInfo( -1 ) /* end of array */
};
/* handler called by the 3812 emulator when the internal timers cause an IRQ */
static void irqhandler(int linestate)
{
cpu_set_irq_line(1,0,linestate);
}
static YM3812interface ym3812_interface = new YM3812interface
(
1, /* 1 chip */
3579545, /* 3.579545 MHz ? (hand tuned) */
new int[] { 100 }, /* volume */
new WriteYmHandlerPtr[] { irqhandler },
);
static MachineDriver machine_driver_snowbros = new MachineDriver
(
/* basic machine hardware */
new MachineCPU[] {
new MachineCPU(
CPU_M68000,
8000000, /* 8 Mhz ????? */
readmem,writemem,null,null,
snowbros_interrupt,3
),
new MachineCPU(
CPU_Z80 | CPU_AUDIO_CPU,
3600000, /* 3.6 Mhz ??? */
sound_readmem,sound_writemem,sound_readport,sound_writeport,
ignore_interrupt,0 /* IRQs are caused by the YM3812 */
)
},
60, DEFAULT_60HZ_VBLANK_DURATION, /* frames per second, vblank duration */
1, /* 1 CPU slice per frame - interleaving is forced when a sound command is written */
null,
/* video hardware */
32*8, 32*8, new rectangle( 0*8, 32*8-1, 2*8, 30*8-1 ),
gfxdecodeinfo,
256, 256,
null,
VIDEO_TYPE_RASTER | VIDEO_SUPPORTS_DIRTY | VIDEO_MODIFIES_PALETTE,
null,
generic_vh_start,
generic_vh_stop,
snowbros_vh_screenrefresh,
/* sound hardware */
0,0,0,0,
new MachineSound[] {
new MachineSound(
SOUND_YM3812,
ym3812_interface
),
}
);
/***************************************************************************
Game driver(s)
***************************************************************************/
static RomLoadPtr rom_snowbros = new RomLoadPtr(){ public void handler(){
ROM_REGION( 0x40000, REGION_CPU1 );/* 6*64k for 68000 code */
ROM_LOAD_EVEN( "sn6.bin", 0x00000, 0x20000, 0x4899ddcf );
ROM_LOAD_ODD ( "sn5.bin", 0x00000, 0x20000, 0xad310d3f );
ROM_REGION( 0x10000, REGION_CPU2 );/* 64k for z80 sound code */
ROM_LOAD( "snowbros.4", 0x0000, 0x8000, 0xe6eab4e4 );
ROM_REGION( 0x80000, REGION_GFX1 | REGIONFLAG_DISPOSE );
ROM_LOAD( "ch0", 0x00000, 0x20000, 0x36d84dfe );
ROM_LOAD( "ch1", 0x20000, 0x20000, 0x76347256 );
ROM_LOAD( "ch2", 0x40000, 0x20000, 0xfdaa634c );
ROM_LOAD( "ch3", 0x60000, 0x20000, 0x34024aef );
ROM_END(); }};
static RomLoadPtr rom_snowbroa = new RomLoadPtr(){ public void handler(){
ROM_REGION( 0x40000, REGION_CPU1 );/* 6*64k for 68000 code */
ROM_LOAD_EVEN( "snowbros.3a", 0x00000, 0x20000, 0x10cb37e1 );
ROM_LOAD_ODD ( "snowbros.2a", 0x00000, 0x20000, 0xab91cc1e );
ROM_REGION( 0x10000, REGION_CPU2 );/* 64k for z80 sound code */
ROM_LOAD( "snowbros.4", 0x0000, 0x8000, 0xe6eab4e4 );
ROM_REGION( 0x80000, REGION_GFX1 | REGIONFLAG_DISPOSE );
ROM_LOAD( "ch0", 0x00000, 0x20000, 0x36d84dfe );
ROM_LOAD( "ch1", 0x20000, 0x20000, 0x76347256 );
ROM_LOAD( "ch2", 0x40000, 0x20000, 0xfdaa634c );
ROM_LOAD( "ch3", 0x60000, 0x20000, 0x34024aef );
ROM_END(); }};
static RomLoadPtr rom_snowbrob = new RomLoadPtr(){ public void handler(){
ROM_REGION( 0x40000, REGION_CPU1 );/* 6*64k for 68000 code */
ROM_LOAD_EVEN( "sbros3-a", 0x00000, 0x20000, 0x301627d6 );
ROM_LOAD_ODD ( "sbros2-a", 0x00000, 0x20000, 0xf6689f41 );
ROM_REGION( 0x10000, REGION_CPU2 );/* 64k for z80 sound code */
ROM_LOAD( "snowbros.4", 0x0000, 0x8000, 0xe6eab4e4 );
ROM_REGION( 0x80000, REGION_GFX1 | REGIONFLAG_DISPOSE );
ROM_LOAD( "ch0", 0x00000, 0x20000, 0x36d84dfe );
ROM_LOAD( "ch1", 0x20000, 0x20000, 0x76347256 );
ROM_LOAD( "ch2", 0x40000, 0x20000, 0xfdaa634c );
ROM_LOAD( "ch3", 0x60000, 0x20000, 0x34024aef );
ROM_END(); }};
static RomLoadPtr rom_snowbroj = new RomLoadPtr(){ public void handler(){
ROM_REGION( 0x40000, REGION_CPU1 );/* 6*64k for 68000 code */
ROM_LOAD_EVEN( "snowbros.3", 0x00000, 0x20000, 0x3f504f9e );
ROM_LOAD_ODD ( "snowbros.2", 0x00000, 0x20000, 0x854b02bc );
ROM_REGION( 0x10000, REGION_CPU2 );/* 64k for z80 sound code */
ROM_LOAD( "snowbros.4", 0x0000, 0x8000, 0xe6eab4e4 );
ROM_REGION( 0x80000, REGION_GFX1 | REGIONFLAG_DISPOSE );
/* The gfx ROM (snowbros.1) was bad, I'm using the ones from the other sets. */
ROM_LOAD( "ch0", 0x00000, 0x20000, 0x36d84dfe );
ROM_LOAD( "ch1", 0x20000, 0x20000, 0x76347256 );
ROM_LOAD( "ch2", 0x40000, 0x20000, 0xfdaa634c );
ROM_LOAD( "ch3", 0x60000, 0x20000, 0x34024aef );
ROM_END(); }};
public static GameDriver driver_snowbros = new GameDriver("1990" ,"snowbros" ,"snowbros.java" ,rom_snowbros,null ,machine_driver_snowbros ,input_ports_snowbros ,null ,ROT0 , "Toaplan (Romstar license)", "Snow Bros. - Nick & Tom (set 1)" )
public static GameDriver driver_snowbroa = new GameDriver("1990" ,"snowbroa" ,"snowbros.java" ,rom_snowbroa,driver_snowbros ,machine_driver_snowbros ,input_ports_snowbros ,null ,ROT0 , "Toaplan (Romstar license)", "Snow Bros. - Nick & Tom (set 2)" )
public static GameDriver driver_snowbrob = new GameDriver("1990" ,"snowbrob" ,"snowbros.java" ,rom_snowbrob,driver_snowbros ,machine_driver_snowbros ,input_ports_snowbros ,null ,ROT0 , "Toaplan (Romstar license)", "Snow Bros. - Nick & Tom (set 3)" )
public static GameDriver driver_snowbroj = new GameDriver("1990" ,"snowbroj" ,"snowbros.java" ,rom_snowbroj,driver_snowbros ,machine_driver_snowbros ,input_ports_snowbros ,null ,ROT0 , "Toaplan (Romstar license)", "Snow Bros. - Nick & Tom (Japan)" )
}
| UTF-8 | Java | 13,792 | java | snowbros.java | Java | [
{
"context": "**********************\n\n Snow Brothers\n\n driver by Mike Coates\n\n************************************************",
"end": 116,
"score": 0.9998286962509155,
"start": 105,
"tag": "NAME",
"value": "Mike Coates"
},
{
"context": ",ROT0\t,\t\"Toaplan (Romstar license)\", \"Snow Bros. - Nick & Tom (set 1)\" )\n\tpublic static GameDriver driver",
"end": 13010,
"score": 0.9997811913490295,
"start": 13006,
"tag": "NAME",
"value": "Nick"
},
{
"context": "\t\"Toaplan (Romstar license)\", \"Snow Bros. - Nick & Tom (set 1)\" )\n\tpublic static GameDriver driver_snowb",
"end": 13016,
"score": 0.9993002414703369,
"start": 13013,
"tag": "NAME",
"value": "Tom"
},
{
"context": ",ROT0\t,\t\"Toaplan (Romstar license)\", \"Snow Bros. - Nick & Tom (set 2)\" )\n\tpublic static GameDriver driver",
"end": 13264,
"score": 0.9997892379760742,
"start": 13260,
"tag": "NAME",
"value": "Nick"
},
{
"context": "\t\"Toaplan (Romstar license)\", \"Snow Bros. - Nick & Tom (set 2)\" )\n\tpublic static GameDriver driver_snowb",
"end": 13270,
"score": 0.9992290735244751,
"start": 13267,
"tag": "NAME",
"value": "Tom"
},
{
"context": ",ROT0\t,\t\"Toaplan (Romstar license)\", \"Snow Bros. - Nick & Tom (set 3)\" )\n\tpublic static GameDriver driver",
"end": 13518,
"score": 0.9995934367179871,
"start": 13514,
"tag": "NAME",
"value": "Nick"
},
{
"context": "\t\"Toaplan (Romstar license)\", \"Snow Bros. - Nick & Tom (set 3)\" )\n\tpublic static GameDriver driver_snowb",
"end": 13524,
"score": 0.9949514865875244,
"start": 13521,
"tag": "NAME",
"value": "Tom"
},
{
"context": ",ROT0\t,\t\"Toaplan (Romstar license)\", \"Snow Bros. - Nick & Tom (Japan)\" )\n}\n",
"end": 13772,
"score": 0.9994342923164368,
"start": 13768,
"tag": "NAME",
"value": "Nick"
},
{
"context": "\t\"Toaplan (Romstar license)\", \"Snow Bros. - Nick & Tom (Japan)\" )\n}\n",
"end": 13778,
"score": 0.9867738485336304,
"start": 13775,
"tag": "NAME",
"value": "Tom"
}
] | null | [] | /***************************************************************************
Snow Brothers
driver by <NAME>
***************************************************************************/
/*
* ported to v0.37b5
* using automatic conversion tool v0.01
*/
package drivers;
public class snowbros
{
static unsigned char *ram;
extern unsigned char *snowbros_spriteram;
public static InterruptPtr snowbros_interrupt = new InterruptPtr() { public int handler()
{
return cpu_getiloops() + 2; /* IRQs 4, 3, and 2 */
} };
public static ReadHandlerPtr snowbros_input_r = new ReadHandlerPtr() { public int handler(int offset)
{
int ans = 0xff;
switch (offset)
{
case 0:
ans = (input_port_0_r.handler (offset) << 8) + (input_port_3_r.handler (offset));
break;
case 2:
ans = (input_port_1_r.handler (offset) << 8) + (input_port_4_r.handler (offset));
break;
case 4:
ans = input_port_2_r.handler (offset) << 8;
break;
}
return ans;
} };
/* Sound Routines */
public static ReadHandlerPtr snowbros_68000_sound_r = new ReadHandlerPtr() { public int handler(int offset)
{
int ret;
/* If the sound CPU is running, read the YM3812 status, otherwise
just make it pass the test */
if (Machine.sample_rate != 0)
{
ret = soundlatch_r(offset);
}
else
{
ret = 3;
}
return ret;
} };
public static WriteHandlerPtr snowbros_68000_sound_w = new WriteHandlerPtr() {public void handler(int offset, int data)
{
soundlatch_w.handler(offset,data);
cpu_cause_interrupt(1,Z80_NMI_INT);
} };
static MemoryReadAddress readmem[] =
{
new MemoryReadAddress( 0x000000, 0x03ffff, MRA_ROM ),
new MemoryReadAddress( 0x100000, 0x103fff, MRA_BANK1 ),
new MemoryReadAddress( 0x300000, 0x300001, snowbros_68000_sound_r ),
new MemoryReadAddress( 0x500000, 0x500005, snowbros_input_r ),
new MemoryReadAddress( 0x600000, 0x6001ff, paletteram_word_r ),
new MemoryReadAddress( 0x700000, 0x701dff, snowbros_spriteram_r ),
new MemoryReadAddress( -1 ) /* end of table */
};
static MemoryWriteAddress writemem[] =
{
new MemoryWriteAddress( 0x000000, 0x03ffff, MWA_ROM ),
new MemoryWriteAddress( 0x100000, 0x103fff, MWA_BANK1, ram ),
new MemoryWriteAddress( 0x200000, 0x200001, watchdog_reset_w ),
new MemoryWriteAddress( 0x300000, 0x300001, snowbros_68000_sound_w ),
// new MemoryWriteAddress( 0x400000, 0x400001, snowbros_interrupt_enable_w ),
new MemoryWriteAddress( 0x600000, 0x6001ff, paletteram_xBBBBBGGGGGRRRRR_word_w, paletteram ),
new MemoryWriteAddress( 0x700000, 0x701dff, snowbros_spriteram_w, snowbros_spriteram, videoram_size ),
new MemoryWriteAddress( 0x800000, 0x800001, MWA_NOP ), /* IRQ 4 acknowledge? */
new MemoryWriteAddress( 0x900000, 0x900001, MWA_NOP ), /* IRQ 3 acknowledge? */
new MemoryWriteAddress( 0xa00000, 0xa00001, MWA_NOP ), /* IRQ 2 acknowledge? */
new MemoryWriteAddress( -1 ) /* end of table */
};
static MemoryReadAddress sound_readmem[] =
{
new MemoryReadAddress( 0x0000, 0x7fff, MRA_ROM ),
new MemoryReadAddress( 0x8000, 0x87ff, MRA_RAM ),
new MemoryReadAddress( -1 ) /* end of table */
};
static MemoryWriteAddress sound_writemem[] =
{
new MemoryWriteAddress( 0x0000, 0x7fff, MWA_ROM ),
new MemoryWriteAddress( 0x8000, 0x87ff, MWA_RAM ),
new MemoryWriteAddress( -1 ) /* end of table */
};
static IOReadPort sound_readport[] =
{
new IOReadPort( 0x02, 0x02, YM3812_status_port_0_r ),
new IOReadPort( 0x04, 0x04, soundlatch_r ),
new IOReadPort( -1 ) /* end of table */
};
static IOWritePort sound_writeport[] =
{
new IOWritePort( 0x02, 0x02, YM3812_control_port_0_w ),
new IOWritePort( 0x03, 0x03, YM3812_write_port_0_w ),
new IOWritePort( 0x04, 0x04, soundlatch_w ), /* goes back to the main CPU, checked during boot */
new IOWritePort( -1 ) /* end of table */
};
static InputPortPtr input_ports_snowbros = new InputPortPtr(){ public void handler() {
PORT_START(); /* 500001 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY );
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY );
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY );
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY );
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 );
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 );
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_BUTTON3 );
PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_UNKNOWN );/* Must be low or game stops! */
/* probably VBlank */
PORT_START(); /* 500003 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY | IPF_PLAYER2 );
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY | IPF_PLAYER2 );
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY | IPF_PLAYER2 );
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY | IPF_PLAYER2 );
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER2 );
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_PLAYER2 );
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_BUTTON3 | IPF_PLAYER2 );
PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_UNKNOWN );
PORT_START(); /* 500005 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_START1 );
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_START2 );
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_COIN1 );
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_COIN2 );
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNKNOWN );
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_TILT );
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_COIN3 );
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN );
PORT_START(); /* DSW 1 */
PORT_DIPNAME( 0x01, 0x01, "Country (Affects Coinage); )
PORT_DIPSETTING( 0x01, "America" );
PORT_DIPSETTING( 0x00, "Europe" );
PORT_DIPNAME( 0x02, 0x02, DEF_STR( "Flip_Screen") );
PORT_DIPSETTING( 0x02, DEF_STR( "Off") );
PORT_DIPSETTING( 0x00, DEF_STR( "On") );
PORT_SERVICE( 0x04, IP_ACTIVE_LOW );
PORT_DIPNAME( 0x08, 0x08, DEF_STR( "Demo_Sounds") );
PORT_DIPSETTING( 0x00, DEF_STR( "Off") );
PORT_DIPSETTING( 0x08, DEF_STR( "On") );
/* Better to implement a coin mode 1-2 stuff later */
PORT_DIPNAME( 0x30, 0x30, "Coin A America/Europe" );
PORT_DIPSETTING( 0x10, "2C/1C 3C/1C" );
PORT_DIPSETTING( 0x30, DEF_STR( "1C_1C") );
PORT_DIPSETTING( 0x00, "2C/3C 4C/1C" );
PORT_DIPSETTING( 0x20, "1C/2C 2C/1C" );
PORT_DIPNAME( 0xc0, 0xc0, "Coin B America/Europe" );
PORT_DIPSETTING( 0x40, "2C/1C 1C/4C" );
PORT_DIPSETTING( 0xc0, "1C/1C 1C/2C" );
PORT_DIPSETTING( 0x00, "2C/3C 1C/6C" );
PORT_DIPSETTING( 0x80, "1C/2C 1C/3C" );
PORT_START(); /* DSW 2 */
PORT_DIPNAME( 0x03, 0x03, DEF_STR( "Difficulty") );
PORT_DIPSETTING( 0x02, "Easy" );
PORT_DIPSETTING( 0x03, "Normal" );
PORT_DIPSETTING( 0x01, "Hard" );
PORT_DIPSETTING( 0x00, "Hardest" );
PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( "Bonus_Life") );
PORT_DIPSETTING( 0x04, "100k and every 200k " );
PORT_DIPSETTING( 0x0c, "100k Only" );
PORT_DIPSETTING( 0x08, "200k Only" );
PORT_DIPSETTING( 0x00, "None" );
PORT_DIPNAME( 0x30, 0x30, DEF_STR( "Lives") );
PORT_DIPSETTING( 0x20, "1" );
PORT_DIPSETTING( 0x00, "2" );
PORT_DIPSETTING( 0x30, "3" );
PORT_DIPSETTING( 0x10, "4" );
PORT_BITX( 0x40, 0x40, IPT_DIPSWITCH_NAME | IPF_CHEAT, "Invulnerability", IP_KEY_NONE, IP_JOY_NONE );
PORT_DIPSETTING( 0x40, DEF_STR( "Off") );
PORT_DIPSETTING( 0x00, DEF_STR( "On") );
PORT_DIPNAME( 0x80, 0x80, "Allow Continue" );
PORT_DIPSETTING( 0x00, DEF_STR( "No") );
PORT_DIPSETTING( 0x80, DEF_STR( "Yes") );
INPUT_PORTS_END(); }};
static GfxLayout tilelayout = new GfxLayout
(
16,16, /* 16*16 sprites */
4096, /* 4096 sprites */
4, /* 4 bits per pixel */
new int[] { 0, 1, 2, 3 },
new int[] {
0, 4, 8, 12, 16, 20, 24, 28,
8*32+0, 8*32+4, 8*32+8, 8*32+12, 8*32+16, 8*32+20, 8*32+24, 8*32+28,
},
new int[] {
0*32, 1*32, 2*32, 3*32, 4*32, 5*32, 6*32, 7*32,
16*32, 17*32, 18*32, 19*32, 20*32, 21*32, 22*32, 23*32
},
128*8
);
static GfxDecodeInfo gfxdecodeinfo[] =
{
new GfxDecodeInfo( REGION_GFX1, 0, tilelayout, 0, 16 ),
new GfxDecodeInfo( -1 ) /* end of array */
};
/* handler called by the 3812 emulator when the internal timers cause an IRQ */
static void irqhandler(int linestate)
{
cpu_set_irq_line(1,0,linestate);
}
static YM3812interface ym3812_interface = new YM3812interface
(
1, /* 1 chip */
3579545, /* 3.579545 MHz ? (hand tuned) */
new int[] { 100 }, /* volume */
new WriteYmHandlerPtr[] { irqhandler },
);
static MachineDriver machine_driver_snowbros = new MachineDriver
(
/* basic machine hardware */
new MachineCPU[] {
new MachineCPU(
CPU_M68000,
8000000, /* 8 Mhz ????? */
readmem,writemem,null,null,
snowbros_interrupt,3
),
new MachineCPU(
CPU_Z80 | CPU_AUDIO_CPU,
3600000, /* 3.6 Mhz ??? */
sound_readmem,sound_writemem,sound_readport,sound_writeport,
ignore_interrupt,0 /* IRQs are caused by the YM3812 */
)
},
60, DEFAULT_60HZ_VBLANK_DURATION, /* frames per second, vblank duration */
1, /* 1 CPU slice per frame - interleaving is forced when a sound command is written */
null,
/* video hardware */
32*8, 32*8, new rectangle( 0*8, 32*8-1, 2*8, 30*8-1 ),
gfxdecodeinfo,
256, 256,
null,
VIDEO_TYPE_RASTER | VIDEO_SUPPORTS_DIRTY | VIDEO_MODIFIES_PALETTE,
null,
generic_vh_start,
generic_vh_stop,
snowbros_vh_screenrefresh,
/* sound hardware */
0,0,0,0,
new MachineSound[] {
new MachineSound(
SOUND_YM3812,
ym3812_interface
),
}
);
/***************************************************************************
Game driver(s)
***************************************************************************/
static RomLoadPtr rom_snowbros = new RomLoadPtr(){ public void handler(){
ROM_REGION( 0x40000, REGION_CPU1 );/* 6*64k for 68000 code */
ROM_LOAD_EVEN( "sn6.bin", 0x00000, 0x20000, 0x4899ddcf );
ROM_LOAD_ODD ( "sn5.bin", 0x00000, 0x20000, 0xad310d3f );
ROM_REGION( 0x10000, REGION_CPU2 );/* 64k for z80 sound code */
ROM_LOAD( "snowbros.4", 0x0000, 0x8000, 0xe6eab4e4 );
ROM_REGION( 0x80000, REGION_GFX1 | REGIONFLAG_DISPOSE );
ROM_LOAD( "ch0", 0x00000, 0x20000, 0x36d84dfe );
ROM_LOAD( "ch1", 0x20000, 0x20000, 0x76347256 );
ROM_LOAD( "ch2", 0x40000, 0x20000, 0xfdaa634c );
ROM_LOAD( "ch3", 0x60000, 0x20000, 0x34024aef );
ROM_END(); }};
static RomLoadPtr rom_snowbroa = new RomLoadPtr(){ public void handler(){
ROM_REGION( 0x40000, REGION_CPU1 );/* 6*64k for 68000 code */
ROM_LOAD_EVEN( "snowbros.3a", 0x00000, 0x20000, 0x10cb37e1 );
ROM_LOAD_ODD ( "snowbros.2a", 0x00000, 0x20000, 0xab91cc1e );
ROM_REGION( 0x10000, REGION_CPU2 );/* 64k for z80 sound code */
ROM_LOAD( "snowbros.4", 0x0000, 0x8000, 0xe6eab4e4 );
ROM_REGION( 0x80000, REGION_GFX1 | REGIONFLAG_DISPOSE );
ROM_LOAD( "ch0", 0x00000, 0x20000, 0x36d84dfe );
ROM_LOAD( "ch1", 0x20000, 0x20000, 0x76347256 );
ROM_LOAD( "ch2", 0x40000, 0x20000, 0xfdaa634c );
ROM_LOAD( "ch3", 0x60000, 0x20000, 0x34024aef );
ROM_END(); }};
static RomLoadPtr rom_snowbrob = new RomLoadPtr(){ public void handler(){
ROM_REGION( 0x40000, REGION_CPU1 );/* 6*64k for 68000 code */
ROM_LOAD_EVEN( "sbros3-a", 0x00000, 0x20000, 0x301627d6 );
ROM_LOAD_ODD ( "sbros2-a", 0x00000, 0x20000, 0xf6689f41 );
ROM_REGION( 0x10000, REGION_CPU2 );/* 64k for z80 sound code */
ROM_LOAD( "snowbros.4", 0x0000, 0x8000, 0xe6eab4e4 );
ROM_REGION( 0x80000, REGION_GFX1 | REGIONFLAG_DISPOSE );
ROM_LOAD( "ch0", 0x00000, 0x20000, 0x36d84dfe );
ROM_LOAD( "ch1", 0x20000, 0x20000, 0x76347256 );
ROM_LOAD( "ch2", 0x40000, 0x20000, 0xfdaa634c );
ROM_LOAD( "ch3", 0x60000, 0x20000, 0x34024aef );
ROM_END(); }};
static RomLoadPtr rom_snowbroj = new RomLoadPtr(){ public void handler(){
ROM_REGION( 0x40000, REGION_CPU1 );/* 6*64k for 68000 code */
ROM_LOAD_EVEN( "snowbros.3", 0x00000, 0x20000, 0x3f504f9e );
ROM_LOAD_ODD ( "snowbros.2", 0x00000, 0x20000, 0x854b02bc );
ROM_REGION( 0x10000, REGION_CPU2 );/* 64k for z80 sound code */
ROM_LOAD( "snowbros.4", 0x0000, 0x8000, 0xe6eab4e4 );
ROM_REGION( 0x80000, REGION_GFX1 | REGIONFLAG_DISPOSE );
/* The gfx ROM (snowbros.1) was bad, I'm using the ones from the other sets. */
ROM_LOAD( "ch0", 0x00000, 0x20000, 0x36d84dfe );
ROM_LOAD( "ch1", 0x20000, 0x20000, 0x76347256 );
ROM_LOAD( "ch2", 0x40000, 0x20000, 0xfdaa634c );
ROM_LOAD( "ch3", 0x60000, 0x20000, 0x34024aef );
ROM_END(); }};
public static GameDriver driver_snowbros = new GameDriver("1990" ,"snowbros" ,"snowbros.java" ,rom_snowbros,null ,machine_driver_snowbros ,input_ports_snowbros ,null ,ROT0 , "Toaplan (Romstar license)", "Snow Bros. - Nick & Tom (set 1)" )
public static GameDriver driver_snowbroa = new GameDriver("1990" ,"snowbroa" ,"snowbros.java" ,rom_snowbroa,driver_snowbros ,machine_driver_snowbros ,input_ports_snowbros ,null ,ROT0 , "Toaplan (Romstar license)", "Snow Bros. - Nick & Tom (set 2)" )
public static GameDriver driver_snowbrob = new GameDriver("1990" ,"snowbrob" ,"snowbros.java" ,rom_snowbrob,driver_snowbros ,machine_driver_snowbros ,input_ports_snowbros ,null ,ROT0 , "Toaplan (Romstar license)", "Snow Bros. - Nick & Tom (set 3)" )
public static GameDriver driver_snowbroj = new GameDriver("1990" ,"snowbroj" ,"snowbros.java" ,rom_snowbroj,driver_snowbros ,machine_driver_snowbros ,input_ports_snowbros ,null ,ROT0 , "Toaplan (Romstar license)", "Snow Bros. - Nick & Tom (Japan)" )
}
| 13,787 | 0.630655 | 0.517039 | 378 | 35.486771 | 35.720936 | 253 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.396825 | false | false | 3 |
b5159f8c6496322ab8d603324bf32bcfe86592b6 | 8,169,027,833,965 | 472613fce4eda98e2ca5c3664644295bb8a8b54d | /test/src/week4/lab2/Item.java | da095fcd340c31b09052a16ad996b4479b898344 | [] | no_license | SamCull/Java | https://github.com/SamCull/Java | 634af33f6eabdf44174c3a8411dfcaf7e5764fa2 | bba050740e605e079fe8f6f6582782b476b63648 | refs/heads/master | 2023-04-01T19:30:07.373000 | 2021-04-15T14:18:18 | 2021-04-15T14:18:18 | 305,205,450 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package week4.lab2;
public class Item {
//Variables
private int ItemID;
private static int nextItemID = 0; //"this should be a unique identifier"
private String name;
private String type;
private String date;
private char status;
private double price;
private static int noOfSalesItems=0;
//Constructors
public Item(String name, String type, String date, double price, char status) {
++nextItemID; //increments ItemID and puts it back as 1 extra
setItemID(nextItemID);
setName(name);
setType(type);
setManufactureDate(date);
setPrice(price);
setStatus(status); //"status field should be A for unavailable"
noOfSalesItems++; //increments by 1
}
//Getters & Setters
public int getItemID() {
return ItemID;
}
public void setItemID(int itemID) {
ItemID = itemID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDate() {
return date;
}
public void setManufactureDate(String date) {
this.date = date;
}
public char getStatus() {
return status;
}
public void setStatus(char status) {
this.status = status;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public static int getNoOfSalesItems() {
return noOfSalesItems;
}
//Misc Methods
//"create a class method SU which sets item for 'S' when sold"
public void statusUpdate() {
setStatus('S');
}
//toString
@Override
public String toString() {
if(status == 'A') {
return "Item [ItemID=" + ItemID + ", name=" + name + ", type=" + type + ", date=" + date
+ ", status=" + status + ", price=" + price + "]";
}
else { //if item is sold, don't print out price
return "Item [ItemID=" + ItemID + ", name=" + name + ", type=" + type + ", date=" + date
+ ", status=" + status + "]";
}
}
}
| UTF-8 | Java | 2,083 | java | Item.java | Java | [] | null | [] | package week4.lab2;
public class Item {
//Variables
private int ItemID;
private static int nextItemID = 0; //"this should be a unique identifier"
private String name;
private String type;
private String date;
private char status;
private double price;
private static int noOfSalesItems=0;
//Constructors
public Item(String name, String type, String date, double price, char status) {
++nextItemID; //increments ItemID and puts it back as 1 extra
setItemID(nextItemID);
setName(name);
setType(type);
setManufactureDate(date);
setPrice(price);
setStatus(status); //"status field should be A for unavailable"
noOfSalesItems++; //increments by 1
}
//Getters & Setters
public int getItemID() {
return ItemID;
}
public void setItemID(int itemID) {
ItemID = itemID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDate() {
return date;
}
public void setManufactureDate(String date) {
this.date = date;
}
public char getStatus() {
return status;
}
public void setStatus(char status) {
this.status = status;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public static int getNoOfSalesItems() {
return noOfSalesItems;
}
//Misc Methods
//"create a class method SU which sets item for 'S' when sold"
public void statusUpdate() {
setStatus('S');
}
//toString
@Override
public String toString() {
if(status == 'A') {
return "Item [ItemID=" + ItemID + ", name=" + name + ", type=" + type + ", date=" + date
+ ", status=" + status + ", price=" + price + "]";
}
else { //if item is sold, don't print out price
return "Item [ItemID=" + ItemID + ", name=" + name + ", type=" + type + ", date=" + date
+ ", status=" + status + "]";
}
}
}
| 2,083 | 0.621219 | 0.618339 | 96 | 19.697916 | 20.474638 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.854167 | false | false | 3 |
5bfd9b307ac6c4ccfc1ed81b53d6dc67c7b59a6f | 33,320,356,340,962 | 8fc6bedbb612b2ebdfbe4ce4ee2cbe0a98d3bcc8 | /httpake/src/org/hpake/HttPakeException.java | c1b2d6b38dec20a6a0d4234a542bcc4bce70167a | [] | no_license | wbibile/httpake | https://github.com/wbibile/httpake | efe06b42af33120dcb7edb1cf2e5a5debdf20659 | 8a81ef4c0d1546cf12f3b4120d20404b38441ecf | refs/heads/master | 2022-07-17T23:47:33.345000 | 2022-07-04T18:47:13 | 2022-07-04T18:47:13 | 163,769,211 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.hpake;
/**
* HttPake Exception
* @author Wiraj Bibile
*/
public class HttPakeException extends RuntimeException
{
private static final long serialVersionUID = 1L;
private boolean serverError;
public HttPakeException()
{
super();
}
/**
* @param cause The cause
*/
public HttPakeException(Throwable cause)
{
super(cause);
}
/**
* @param message The exception message
* @param cause the cause
*/
public HttPakeException(String message, Throwable cause)
{
super(message, cause);
}
/**
* @param message Exception message
*/
public HttPakeException(String message)
{
super(message);
}
/**
* Make this exception as being caused by a server error.
* @return this instance
*/
public HttPakeException setAsServerError()
{
this.serverError = true;
return this;
}
/**
* @return true if the error is a server error
*/
public boolean isServerError()
{
return serverError;
}
}
| UTF-8 | Java | 1,029 | java | HttPakeException.java | Java | [
{
"context": "rg.hpake;\r\n\r\n/**\r\n * HttPake Exception\r\n * @author Wiraj Bibile\r\n */\r\npublic class HttPakeException extends Runti",
"end": 72,
"score": 0.999775230884552,
"start": 60,
"tag": "NAME",
"value": "Wiraj Bibile"
}
] | null | [] | package org.hpake;
/**
* HttPake Exception
* @author <NAME>
*/
public class HttPakeException extends RuntimeException
{
private static final long serialVersionUID = 1L;
private boolean serverError;
public HttPakeException()
{
super();
}
/**
* @param cause The cause
*/
public HttPakeException(Throwable cause)
{
super(cause);
}
/**
* @param message The exception message
* @param cause the cause
*/
public HttPakeException(String message, Throwable cause)
{
super(message, cause);
}
/**
* @param message Exception message
*/
public HttPakeException(String message)
{
super(message);
}
/**
* Make this exception as being caused by a server error.
* @return this instance
*/
public HttPakeException setAsServerError()
{
this.serverError = true;
return this;
}
/**
* @return true if the error is a server error
*/
public boolean isServerError()
{
return serverError;
}
}
| 1,023 | 0.631681 | 0.630709 | 61 | 14.868853 | 17.193666 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 3 |
c5c75bbb737b361c91bf73f2ed8b58f3f5473974 | 17,721,035,090,647 | 1eb09737b853d983a18c1b5656a6ae59c3539999 | /src/main/java/com/study/kdtree/check/Point.java | 7c8ef02f1bec925d5d4d43ff6ab40391f50cbc09 | [] | no_license | chengchen901/KDTree | https://github.com/chengchen901/KDTree | 225ec5b5a9c5c62246950ce86173115f622b11e1 | 7b1414ef24986bc64ad4b869ebdab484ef1f1468 | refs/heads/master | 2023-02-28T19:24:57.531000 | 2021-02-07T03:28:42 | 2021-02-07T03:28:42 | 336,710,558 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.study.kdtree.check;
import java.util.Objects;
/**
* @author Hash
* @since 2021/2/1
*/
public class Point {
public static void main(String[] args) {
float f1 = Float.NaN;
float f2 = 9999;
System.out.println(f1 > f2);
System.out.println(f1 < f2);
System.out.println(f1 == f2);
}
private double lon;
private double lat;
private double distance;
public Point(double lon, double lat) {
this.lon = lon;
this.lat = lat;
}
public Point(double lon, double lat, double distance) {
this.lon = lon;
this.lat = lat;
this.distance = distance;
}
public double getLon() {
return lon;
}
public void setLon(double lon) {
this.lon = lon;
}
public double getLat() {
return lat;
}
public void setLat(double lat) {
this.lat = lat;
}
public double getDistance() {
return distance;
}
public void setDistance(double distance) {
this.distance = distance;
}
@Override
public String toString() {
return "Point{" +
"lon=" + lon +
", lat=" + lat +
", distance=" + distance +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Point point = (Point) o;
return Double.compare(point.lon, lon) == 0 &&
Double.compare(point.lat, lat) == 0 &&
Double.compare(point.distance, distance) == 0;
}
@Override
public int hashCode() {
return Objects.hash(lon, lat, distance);
}
}
| UTF-8 | Java | 1,743 | java | Point.java | Java | [
{
"context": ".check;\n\nimport java.util.Objects;\n\n/**\n * @author Hash\n * @since 2021/2/1\n */\npublic class Point {\n\n ",
"end": 79,
"score": 0.9919644594192505,
"start": 75,
"tag": "NAME",
"value": "Hash"
}
] | null | [] | package com.study.kdtree.check;
import java.util.Objects;
/**
* @author Hash
* @since 2021/2/1
*/
public class Point {
public static void main(String[] args) {
float f1 = Float.NaN;
float f2 = 9999;
System.out.println(f1 > f2);
System.out.println(f1 < f2);
System.out.println(f1 == f2);
}
private double lon;
private double lat;
private double distance;
public Point(double lon, double lat) {
this.lon = lon;
this.lat = lat;
}
public Point(double lon, double lat, double distance) {
this.lon = lon;
this.lat = lat;
this.distance = distance;
}
public double getLon() {
return lon;
}
public void setLon(double lon) {
this.lon = lon;
}
public double getLat() {
return lat;
}
public void setLat(double lat) {
this.lat = lat;
}
public double getDistance() {
return distance;
}
public void setDistance(double distance) {
this.distance = distance;
}
@Override
public String toString() {
return "Point{" +
"lon=" + lon +
", lat=" + lat +
", distance=" + distance +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Point point = (Point) o;
return Double.compare(point.lon, lon) == 0 &&
Double.compare(point.lat, lat) == 0 &&
Double.compare(point.distance, distance) == 0;
}
@Override
public int hashCode() {
return Objects.hash(lon, lat, distance);
}
}
| 1,743 | 0.526104 | 0.514056 | 81 | 20.518518 | 17.164499 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.481481 | false | false | 3 |
ecfe39708d91f4a60a07d9bc85de1fbdc8e716ea | 19,396,072,309,635 | 3a3502af3fc21dc020fed4bbbd04a3e0bd25e889 | /src/main/java/epsi/webservices/servlet/LoginServlet.java | 7fd69b74a595a0404ccfc09717271331e3aab08f | [] | no_license | KevinLarhant/WebServices | https://github.com/KevinLarhant/WebServices | a56c07cc9a9d74b77e435b9b6f91a282a96de53c | 12f460688ddccbd2a1b63508824cc3fc0b9783ce | refs/heads/master | 2020-05-18T10:49:00.131000 | 2015-04-06T23:17:28 | 2015-04-06T23:17:28 | 28,030,315 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package epsi.webservices.servlet;
import epsi.webservices.dao.DaoUser;
import org.apache.log4j.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(name = "LoginServlet", urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
private final static Logger log = Logger.getLogger(LoginServlet.class);
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher requestDispatcher;
if (request.getSession().getAttribute("login") != null) {
response.sendRedirect("index.jsp");
} else {
//TODO : changer la page
requestDispatcher = request.getRequestDispatcher("/login.jsp");
requestDispatcher.include(request, response);
}
}
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String login = request.getParameter("login");
String pwd = request.getParameter("pwd");
if (DaoUser.checkCredentials(login, pwd)) {
request.getSession().setAttribute("login", login);
}
response.sendRedirect("index.jsp");
}
}
| UTF-8 | Java | 1,381 | java | LoginServlet.java | Java | [] | null | [] | package epsi.webservices.servlet;
import epsi.webservices.dao.DaoUser;
import org.apache.log4j.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(name = "LoginServlet", urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
private final static Logger log = Logger.getLogger(LoginServlet.class);
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher requestDispatcher;
if (request.getSession().getAttribute("login") != null) {
response.sendRedirect("index.jsp");
} else {
//TODO : changer la page
requestDispatcher = request.getRequestDispatcher("/login.jsp");
requestDispatcher.include(request, response);
}
}
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String login = request.getParameter("login");
String pwd = request.getParameter("pwd");
if (DaoUser.checkCredentials(login, pwd)) {
request.getSession().setAttribute("login", login);
}
response.sendRedirect("index.jsp");
}
}
| 1,381 | 0.778421 | 0.777697 | 45 | 29.688889 | 23.520981 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.622222 | false | false | 3 |
27fab46faf5b7e15e145ec7e4ff2296b473c3358 | 6,236,292,513,833 | da1ee9da96311b31629ab0bbb28d162803cafe85 | /src/org/usfirst/frc/team5968/robot/AutonomousMode.java | 35674fa7eee25f45565bc51833c5e16b0da2adc2 | [] | no_license | PositiveFive/FRC2018 | https://github.com/PositiveFive/FRC2018 | 353254e3d48e2edd14e9b357ab917875f3d53506 | ece77f3e5d3377bbffa1ad149f081f6d20f9b50a | refs/heads/master | 2020-04-01T12:09:30.925000 | 2018-10-24T22:08:37 | 2018-10-24T22:08:37 | 120,139,075 | 0 | 0 | null | true | 2018-10-15T23:17:59 | 2018-02-03T23:30:38 | 2018-02-03T23:30:40 | 2018-02-03T23:35:07 | 26 | 0 | 0 | 1 | Java | false | null | package org.usfirst.frc.team5968.robot;
public class AutonomousMode implements IRobotMode {
private IFieldInformation fieldInformation;
private IDashboard dashboard;
private IDrive drive;
private IGrabber grabber;
private ILift lift;
private IRobotMode autonomousSubMode;
public AutonomousMode(IDrive drive, IGrabber grabber, ILift lift, IFieldInformation fieldInformation, IDashboard dashboard) {
this.drive = drive;
this.grabber = grabber;
this.lift = lift;
this.fieldInformation = fieldInformation;
this.dashboard = dashboard;
}
private AutoMode determineAutoMode() {
// If no field information is available, default to the LINE strategy
if (!fieldInformation.getIsDataValid()) {
return AutoMode.LINE;
}
// Determine the appropriate autonomous mode based on our position
FieldPosition ourSide = dashboard.getMatchStartingPoint();
boolean switchSameSide = fieldInformation.getNearSwitchPosition() == ourSide;
boolean scaleSameSide = fieldInformation.getScalePosition() == ourSide;
// We always want to use the LINE strategy when we're in the center lane
if (ourSide == FieldPosition.CENTER) {
return AutoMode.LINE;
}
// If the switch and scale are both on our side, we use the strategy chosen on the dashboard
if (switchSameSide && scaleSameSide) {
return dashboard.chooseModeforBoth();
} else if (switchSameSide) { // If the switch is on our side, we use the SWITCH strategy
return AutoMode.SWITCH;
} else if (scaleSameSide) { // If the scale is on our side, we use the SCALE strategy
return AutoMode.SCALE;
} else { // Otherwise, we fall back to the LINE strategy
return AutoMode.LINE;
}
}
/*
* Creates instance of correct autonomous mode
*/
private IRobotMode getAutoModeImplementation() {
AutoMode autoMode = determineAutoMode();
FieldPosition startingPoint = dashboard.getMatchStartingPoint();
switch (autoMode) {
case SWITCH:
return new SwitchAuto(startingPoint, drive, grabber, lift);
case SCALE:
return new ScaleAuto(startingPoint, drive, grabber, lift);
case LINE:
return new BaselineAuto(startingPoint, drive);
default:
throw new IllegalArgumentException("Tried to instantiate invalid autonomous mode.");
}
}
@Override
public void init() {
fieldInformation.refresh();
autonomousSubMode = getAutoModeImplementation();
Debug.log(autonomousSubMode.getClass().getName() + " mode is starting");
autonomousSubMode.init();
}
@Override
public void periodic() {
autonomousSubMode.periodic();
}
} | UTF-8 | Java | 2,923 | java | AutonomousMode.java | Java | [] | null | [] | package org.usfirst.frc.team5968.robot;
public class AutonomousMode implements IRobotMode {
private IFieldInformation fieldInformation;
private IDashboard dashboard;
private IDrive drive;
private IGrabber grabber;
private ILift lift;
private IRobotMode autonomousSubMode;
public AutonomousMode(IDrive drive, IGrabber grabber, ILift lift, IFieldInformation fieldInformation, IDashboard dashboard) {
this.drive = drive;
this.grabber = grabber;
this.lift = lift;
this.fieldInformation = fieldInformation;
this.dashboard = dashboard;
}
private AutoMode determineAutoMode() {
// If no field information is available, default to the LINE strategy
if (!fieldInformation.getIsDataValid()) {
return AutoMode.LINE;
}
// Determine the appropriate autonomous mode based on our position
FieldPosition ourSide = dashboard.getMatchStartingPoint();
boolean switchSameSide = fieldInformation.getNearSwitchPosition() == ourSide;
boolean scaleSameSide = fieldInformation.getScalePosition() == ourSide;
// We always want to use the LINE strategy when we're in the center lane
if (ourSide == FieldPosition.CENTER) {
return AutoMode.LINE;
}
// If the switch and scale are both on our side, we use the strategy chosen on the dashboard
if (switchSameSide && scaleSameSide) {
return dashboard.chooseModeforBoth();
} else if (switchSameSide) { // If the switch is on our side, we use the SWITCH strategy
return AutoMode.SWITCH;
} else if (scaleSameSide) { // If the scale is on our side, we use the SCALE strategy
return AutoMode.SCALE;
} else { // Otherwise, we fall back to the LINE strategy
return AutoMode.LINE;
}
}
/*
* Creates instance of correct autonomous mode
*/
private IRobotMode getAutoModeImplementation() {
AutoMode autoMode = determineAutoMode();
FieldPosition startingPoint = dashboard.getMatchStartingPoint();
switch (autoMode) {
case SWITCH:
return new SwitchAuto(startingPoint, drive, grabber, lift);
case SCALE:
return new ScaleAuto(startingPoint, drive, grabber, lift);
case LINE:
return new BaselineAuto(startingPoint, drive);
default:
throw new IllegalArgumentException("Tried to instantiate invalid autonomous mode.");
}
}
@Override
public void init() {
fieldInformation.refresh();
autonomousSubMode = getAutoModeImplementation();
Debug.log(autonomousSubMode.getClass().getName() + " mode is starting");
autonomousSubMode.init();
}
@Override
public void periodic() {
autonomousSubMode.periodic();
}
} | 2,923 | 0.649675 | 0.648307 | 79 | 36.012657 | 29.995567 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.607595 | false | false | 3 |
8f43c39bb0d5fb79a682c80dab3c90f9ef95d26b | 21,715,354,651,525 | 30ca0087cac86ca47b796b7b712fac6823e4aafc | /hobotun1/src/main/java/hobotun/news/NewsMain.java | 7397734bdc6dcb7a0bcc0952a58669d5e3155341 | [] | no_license | devis505/hobotun | https://github.com/devis505/hobotun | c755178ff3db4cdb1df36030a307411fb6f942d7 | 42d02380f8f5faa986410b3158d8ca81064627b2 | refs/heads/master | 2020-12-13T02:18:32.522000 | 2016-08-01T13:56:51 | 2016-08-01T13:56:51 | 49,434,542 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package hobotun.news;
import java.io.Serializable;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import hobotun.db.DBUtil;
import hobotun.db.news.NewsDao;
import hobotun.db.news.table.NewsTbl;
@ManagedBean(name = "newsMain")
@ViewScoped
public class NewsMain implements Serializable {
private static final long serialVersionUID = -518116625100690342L;
private List<NewsTbl> newses;
private Integer count_news;
public NewsMain() {
NewsDao newsDao = DBUtil.getInstance().getBean("newsDao", NewsDao.class);
newses = newsDao.selectFirst3News();
count_news = newsDao.countNews();
}
public List<NewsTbl> getNewses() {
return newses;
}
public void setNewses(List<NewsTbl> newses) {
this.newses = newses;
}
public Integer getCount_news() {
return count_news;
}
public void setCount_news(Integer count_news) {
this.count_news = count_news;
}
}
| UTF-8 | Java | 978 | java | NewsMain.java | Java | [] | null | [] | package hobotun.news;
import java.io.Serializable;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import hobotun.db.DBUtil;
import hobotun.db.news.NewsDao;
import hobotun.db.news.table.NewsTbl;
@ManagedBean(name = "newsMain")
@ViewScoped
public class NewsMain implements Serializable {
private static final long serialVersionUID = -518116625100690342L;
private List<NewsTbl> newses;
private Integer count_news;
public NewsMain() {
NewsDao newsDao = DBUtil.getInstance().getBean("newsDao", NewsDao.class);
newses = newsDao.selectFirst3News();
count_news = newsDao.countNews();
}
public List<NewsTbl> getNewses() {
return newses;
}
public void setNewses(List<NewsTbl> newses) {
this.newses = newses;
}
public Integer getCount_news() {
return count_news;
}
public void setCount_news(Integer count_news) {
this.count_news = count_news;
}
}
| 978 | 0.707566 | 0.688139 | 46 | 19.26087 | 19.330574 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.130435 | false | false | 3 |
80abc1f40c2d348a17a5a870f1a401620d996ee6 | 14,791,867,378,429 | d3ade16e6cd200407c60ee970caa4bae5bf4eed0 | /Procurement Management System for Construction Industry/application mobile/app/src/main/java/com/example/application_mobile/constant/OrderConstant.java | d5aede00d5075941f73e26689de6548dbb05f4d2 | [] | no_license | janith-ch/construction-management | https://github.com/janith-ch/construction-management | 6485fe48cd7eb230f7f462d66db07a82a99eb669 | 3d6ba2620eccac6fcfeb2d8f4fdc2251fb1895d5 | refs/heads/master | 2023-08-19T04:21:37.628000 | 2021-10-09T04:34:00 | 2021-10-09T04:34:00 | 413,749,847 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.application_mobile.constant;
import lombok.Data;
@Data
public class OrderConstant {
private String ID = "id";
private String MATERIAL_NAME = "materialName";
private String MATERIAL_ID = "materialId";
private String ORDER_DATE = "orderDate";
private String DELIVERY_DATE = "deliveryDate";
private String QUANTITY_TYPE = "quanitiyType";
private String QUANTITY__TYPE = "quantityType";
private String QUANTITY = "quantity";
private String IS_APPROVED = "isApprove";
private String SITE = "site";
private String LOCATION = "location";
private String NAME = "name";
private String SITE_MANAGER_ID = "siteManagerId";
private String ADDRESS = "address";
private String SITE_ID = "siteId";
private String[] descriptionData = {"Select Project", "Select Material", "Select Deadline"};
private String UNIT_TYPE = "unitType";
private String UNIT_COST = "unitCost";
private String SUPPLIER_ID = "supplierId";
private String FROM_DATE = "fromDate";
private String To_DATE = "toDate";
private String SITE_NAME = "siteName";
private String PUR_ID = "purId";
private String SITE_ADDRESS = "siteAddress";
private String SITE_MANAGER_NAME = "siteManagerName";
private String SITE_MANAGER_FIRST_NAME = "siteMangerFirstName";
}
| UTF-8 | Java | 1,336 | java | OrderConstant.java | Java | [] | null | [] | package com.example.application_mobile.constant;
import lombok.Data;
@Data
public class OrderConstant {
private String ID = "id";
private String MATERIAL_NAME = "materialName";
private String MATERIAL_ID = "materialId";
private String ORDER_DATE = "orderDate";
private String DELIVERY_DATE = "deliveryDate";
private String QUANTITY_TYPE = "quanitiyType";
private String QUANTITY__TYPE = "quantityType";
private String QUANTITY = "quantity";
private String IS_APPROVED = "isApprove";
private String SITE = "site";
private String LOCATION = "location";
private String NAME = "name";
private String SITE_MANAGER_ID = "siteManagerId";
private String ADDRESS = "address";
private String SITE_ID = "siteId";
private String[] descriptionData = {"Select Project", "Select Material", "Select Deadline"};
private String UNIT_TYPE = "unitType";
private String UNIT_COST = "unitCost";
private String SUPPLIER_ID = "supplierId";
private String FROM_DATE = "fromDate";
private String To_DATE = "toDate";
private String SITE_NAME = "siteName";
private String PUR_ID = "purId";
private String SITE_ADDRESS = "siteAddress";
private String SITE_MANAGER_NAME = "siteManagerName";
private String SITE_MANAGER_FIRST_NAME = "siteMangerFirstName";
}
| 1,336 | 0.699102 | 0.699102 | 36 | 36.111111 | 21.103947 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.833333 | false | false | 3 |
138da92a3e171de56e363f20bde4158ce88017e3 | 13,005,161,038,353 | e1072dbd9d5489baad943de10fd6af5e6d02a33a | /game/src/main/java/net/dungeonrealms/vn/data/PlayerRegistry.java | bc0f397bad6c50a2bfa8cd76d1be03caa1ac4eaf | [] | no_license | SubbyIO/DungeonIsles | https://github.com/SubbyIO/DungeonIsles | 3b5af5784346c84cfe00fc5b86ede0751bb5a209 | 33e3fee7910f88c86860659769f7f2a1aef88d20 | refs/heads/master | 2020-02-14T08:49:30.032000 | 2019-01-19T18:30:43 | 2019-01-19T18:30:43 | 87,451,207 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.dungeonrealms.vn.data;
import net.dungeonrealms.vn.game.api.registry.ObjectRegistry;
import net.dungeonrealms.vn.game.api.registry.Registry;
import net.dungeonrealms.vn.game.player.IslesPlayer;
/**
* Created by Giovanni on 5-4-2017.
*/
@Registry(simpleName = "PlayerRegistry")
public class PlayerRegistry extends ObjectRegistry<IslesPlayer> {
public PlayerRegistry() {
super();
}
}
| UTF-8 | Java | 415 | java | PlayerRegistry.java | Java | [
{
"context": "lms.vn.game.player.IslesPlayer;\n\n/**\n * Created by Giovanni on 5-4-2017.\n */\n@Registry(simpleName = \"PlayerRe",
"end": 234,
"score": 0.9991587996482849,
"start": 226,
"tag": "NAME",
"value": "Giovanni"
}
] | null | [] | package net.dungeonrealms.vn.data;
import net.dungeonrealms.vn.game.api.registry.ObjectRegistry;
import net.dungeonrealms.vn.game.api.registry.Registry;
import net.dungeonrealms.vn.game.player.IslesPlayer;
/**
* Created by Giovanni on 5-4-2017.
*/
@Registry(simpleName = "PlayerRegistry")
public class PlayerRegistry extends ObjectRegistry<IslesPlayer> {
public PlayerRegistry() {
super();
}
}
| 415 | 0.754217 | 0.739759 | 16 | 24.9375 | 23.51454 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3125 | false | false | 3 |
a46cb5742f68627b2aee2edfaf64641b3ca8c6ea | 27,943,057,229,304 | 630b6bf19d35e54beeb9aed9ee3e18db61146f2d | /hypermarket-core/src/main/java/ro/sda/hypermarket/core/service/ClientServiceImpl.java | 78c1bddd66093bef5c83587ae4038d5f6b60edbf | [] | no_license | SorinaBoz/hypermarket | https://github.com/SorinaBoz/hypermarket | 3808abb62384a3a6d27e0b83a03f41a0f459ff4e | cd7e2e64300b93743a0360c1d2025371c84f1f1d | refs/heads/master | 2020-04-26T13:22:16.474000 | 2019-03-27T20:29:47 | 2019-03-27T20:29:47 | 173,577,435 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ro.sda.hypermarket.core.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ro.sda.hypermarket.core.dao.ClientDAO;
import ro.sda.hypermarket.core.entity.Client;
import ro.sda.hypermarket.core.repository.ClientRepository;
import java.util.List;
@Service("clientService")
@Transactional(readOnly = true, rollbackFor = Exception.class)
public class ClientServiceImpl implements ClientService {
@Autowired
private ClientDAO clientDAO;
@Autowired
private ClientRepository clientRepository;
@Override
@Transactional
public Client create(Client client, boolean useHibernate) {
if(useHibernate) {
return clientDAO.createClient(client);
}
return clientRepository.save(client);
}
@Override
public Client update(Client client, boolean useHibernate) {
if(useHibernate) {
return clientDAO.updateClient(client);
}
return clientRepository.save(client);
}
@Override
public Client getClientById(Long id, boolean useHibernate) {
if(useHibernate) {
return clientDAO.getClientById(id);
}
return clientRepository.findById(id);
}
@Override
public Client getClientByName(String name, boolean useHibernate){
if(useHibernate) {
return clientDAO.getClientByName(name);
}
return clientRepository.findByName(name);
}
@Override
public List<Client> findAll(boolean useHibernate) {
if(useHibernate) {
return clientDAO.getAll();
}
return clientRepository.findAll();
}
@Override
public void delete(Client client, boolean useHibernate) {
if (useHibernate) {
clientDAO.deleteClient(client);
}
clientRepository.delete(client);
}
} | UTF-8 | Java | 1,961 | java | ClientServiceImpl.java | Java | [] | null | [] | package ro.sda.hypermarket.core.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ro.sda.hypermarket.core.dao.ClientDAO;
import ro.sda.hypermarket.core.entity.Client;
import ro.sda.hypermarket.core.repository.ClientRepository;
import java.util.List;
@Service("clientService")
@Transactional(readOnly = true, rollbackFor = Exception.class)
public class ClientServiceImpl implements ClientService {
@Autowired
private ClientDAO clientDAO;
@Autowired
private ClientRepository clientRepository;
@Override
@Transactional
public Client create(Client client, boolean useHibernate) {
if(useHibernate) {
return clientDAO.createClient(client);
}
return clientRepository.save(client);
}
@Override
public Client update(Client client, boolean useHibernate) {
if(useHibernate) {
return clientDAO.updateClient(client);
}
return clientRepository.save(client);
}
@Override
public Client getClientById(Long id, boolean useHibernate) {
if(useHibernate) {
return clientDAO.getClientById(id);
}
return clientRepository.findById(id);
}
@Override
public Client getClientByName(String name, boolean useHibernate){
if(useHibernate) {
return clientDAO.getClientByName(name);
}
return clientRepository.findByName(name);
}
@Override
public List<Client> findAll(boolean useHibernate) {
if(useHibernate) {
return clientDAO.getAll();
}
return clientRepository.findAll();
}
@Override
public void delete(Client client, boolean useHibernate) {
if (useHibernate) {
clientDAO.deleteClient(client);
}
clientRepository.delete(client);
}
} | 1,961 | 0.684345 | 0.684345 | 70 | 27.028572 | 22.181698 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 3 |
ead542f0cd80e98856adf5edfe3a7121c7570503 | 2,568,390,465,063 | c2934e0ac1ef8874261ce9b24b532359ca00cd57 | /src/Secante.java | f03bd1d16d92043228783f1a3ccd10b5f06d9fe8 | [] | no_license | HetairoiElite/Programas | https://github.com/HetairoiElite/Programas | 318d459a6b4072715586e5acb3e5dab5b65f09ad | 2409971322d5139ccb9932fc9cbe25ec6e1d37e5 | refs/heads/master | 2023-08-23T07:02:36.553000 | 2021-09-29T16:09:47 | 2021-09-29T16:09:47 | 409,728,905 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.util.Scanner;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.InputMismatchException;
public class Secante {
public static void main(String[] args) {
double x1 = 0;
double xu = 0;
double n1;
double f1;
double fu;
double fx;
double Ea;
double error = 0;
boolean continuar = true;
boolean bandera = true;
int contador = 0;
Scanner consola = new Scanner(System.in);
// paso 1
try {
FileWriter fw = new FileWriter("Salida-Newton.txt");
BufferedWriter bw = new BufferedWriter(fw);
do {
try {
System.out.println("inserte el valor de x1: ");
// double x = 1.420990;
x1 = consola.nextDouble();
continuar = false;
} catch (Exception e) {
System.out.println("Tipo de dato incorrecto: " + e.getMessage());
consola.nextLine();
}
} while (continuar);
continuar = true;
do {
try {
System.out.println("inserte el valor de xu: ");
// double x = 1.420990;
xu = consola.nextDouble();
continuar = false;
} catch (Exception e) {
System.out.println("Tipo de dato incorrecto: " + e.getMessage());
consola.nextLine();
}
} while (continuar);
continuar = true;
do {
try {
System.out.println("Inser el rango de error: ");
error = consola.nextDouble();
if (error < 0) {
throw new Exception("No se admiten valores negativos.");
}
continuar = false;
} catch (InputMismatchException e) {
System.out.println("Tipo de dato incorrecto: " + e.getMessage());
consola.nextLine();
} catch (Exception e) {
System.out.println(e.getMessage());
}
} while (continuar);
continuar = true;
double[] valores = Funcion.PedirFuncion();
do {
bw.write("\n" + "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx \n");
// f1= Math.pow(x1, 5)+Math.pow(x1, 3)+3;
// fu= Math.pow(xu, 5)+Math.pow(xu, 3)+3;
// f1 = Math.log(x1);
// fu = Math.log(xu);
f1 = Funcion.CicloFuncion(valores, x1);
fu = Funcion.CicloFuncion(valores, xu);
contador++;
System.out.println();
bw.write("\n" + "iteraciones = " + contador);
System.out.println("iteraciones = " + contador);
bw.write("\n" + " x1 = " + String.format("%.6f", x1));
System.out.println(" x1 = " + String.format("%.6f", x1));
bw.write("\n" + " xu = " + String.format("%.6f", xu));
System.out.println(" xu = " + String.format("%.6f", xu));
bw.write("\n" + " f1 = " + String.format("%.6f", f1));
System.out.println(" f1 = " + String.format("%.6f", f1));
bw.write("\n" + " fu = " + String.format("%.6f", fu));
System.out.println(" fu = " + String.format("%.6f", fu));
n1 = xu - ((xu - x1) / (fu - f1)) * fu;
// fx = Math.log(n1);
fx = Funcion.CicloFuncion(valores, n1);
// fx= Math.pow(n1, 5)+Math.pow(n1, 3)+3;
bw.write("\n" + " n1 = " + String.format("%.6f", n1));
System.out.println(" n1 = " + String.format("%.6f", n1));
bw.write("\n" + " fx = " + String.format("%.6f", fx));
System.out.println(" fx = " + String.format("%.6f", fx));
Ea = Math.abs((n1 - xu) / n1) * 100;
bw.write("\n" + "Ea = " + String.format("%.6f", Ea) + "%");
System.out.println("Ea = " + String.format("%.6f", Ea) + "%");
x1 = xu;
xu = n1;
bw.write("\n" + "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx \n");
System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx \n");
if (Ea < error) {
bandera = false;
}
} while (bandera);
consola.close();
bw.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
| UTF-8 | Java | 4,886 | java | Secante.java | Java | [] | null | [] |
import java.util.Scanner;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.InputMismatchException;
public class Secante {
public static void main(String[] args) {
double x1 = 0;
double xu = 0;
double n1;
double f1;
double fu;
double fx;
double Ea;
double error = 0;
boolean continuar = true;
boolean bandera = true;
int contador = 0;
Scanner consola = new Scanner(System.in);
// paso 1
try {
FileWriter fw = new FileWriter("Salida-Newton.txt");
BufferedWriter bw = new BufferedWriter(fw);
do {
try {
System.out.println("inserte el valor de x1: ");
// double x = 1.420990;
x1 = consola.nextDouble();
continuar = false;
} catch (Exception e) {
System.out.println("Tipo de dato incorrecto: " + e.getMessage());
consola.nextLine();
}
} while (continuar);
continuar = true;
do {
try {
System.out.println("inserte el valor de xu: ");
// double x = 1.420990;
xu = consola.nextDouble();
continuar = false;
} catch (Exception e) {
System.out.println("Tipo de dato incorrecto: " + e.getMessage());
consola.nextLine();
}
} while (continuar);
continuar = true;
do {
try {
System.out.println("Inser el rango de error: ");
error = consola.nextDouble();
if (error < 0) {
throw new Exception("No se admiten valores negativos.");
}
continuar = false;
} catch (InputMismatchException e) {
System.out.println("Tipo de dato incorrecto: " + e.getMessage());
consola.nextLine();
} catch (Exception e) {
System.out.println(e.getMessage());
}
} while (continuar);
continuar = true;
double[] valores = Funcion.PedirFuncion();
do {
bw.write("\n" + "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx \n");
// f1= Math.pow(x1, 5)+Math.pow(x1, 3)+3;
// fu= Math.pow(xu, 5)+Math.pow(xu, 3)+3;
// f1 = Math.log(x1);
// fu = Math.log(xu);
f1 = Funcion.CicloFuncion(valores, x1);
fu = Funcion.CicloFuncion(valores, xu);
contador++;
System.out.println();
bw.write("\n" + "iteraciones = " + contador);
System.out.println("iteraciones = " + contador);
bw.write("\n" + " x1 = " + String.format("%.6f", x1));
System.out.println(" x1 = " + String.format("%.6f", x1));
bw.write("\n" + " xu = " + String.format("%.6f", xu));
System.out.println(" xu = " + String.format("%.6f", xu));
bw.write("\n" + " f1 = " + String.format("%.6f", f1));
System.out.println(" f1 = " + String.format("%.6f", f1));
bw.write("\n" + " fu = " + String.format("%.6f", fu));
System.out.println(" fu = " + String.format("%.6f", fu));
n1 = xu - ((xu - x1) / (fu - f1)) * fu;
// fx = Math.log(n1);
fx = Funcion.CicloFuncion(valores, n1);
// fx= Math.pow(n1, 5)+Math.pow(n1, 3)+3;
bw.write("\n" + " n1 = " + String.format("%.6f", n1));
System.out.println(" n1 = " + String.format("%.6f", n1));
bw.write("\n" + " fx = " + String.format("%.6f", fx));
System.out.println(" fx = " + String.format("%.6f", fx));
Ea = Math.abs((n1 - xu) / n1) * 100;
bw.write("\n" + "Ea = " + String.format("%.6f", Ea) + "%");
System.out.println("Ea = " + String.format("%.6f", Ea) + "%");
x1 = xu;
xu = n1;
bw.write("\n" + "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx \n");
System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx \n");
if (Ea < error) {
bandera = false;
}
} while (bandera);
consola.close();
bw.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
| 4,886 | 0.445354 | 0.428776 | 124 | 38.395161 | 25.338615 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.862903 | false | false | 3 |
617c29933f4cd35cd0dce88123877f302db15a21 | 18,683,107,749,337 | 916dd059a35560bf2431994cfe05c22c73592065 | /src/main/java/se/miniwa/deater/cli/EmailCommand.java | 682504388573aae8dbb2756a6db88e695a89327e | [] | no_license | miniwa/deater | https://github.com/miniwa/deater | f9c4f193a9e71af9b13d9b09641f282aed25cf68 | 78506f0f723f633f45d331bf09b73419bd650ded | refs/heads/master | 2020-04-22T17:44:00.622000 | 2019-02-18T18:28:56 | 2019-02-18T18:28:56 | 170,552,093 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package se.miniwa.deater.cli;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
@Parameters(commandDescription = "Launches a game in email mode")
public class EmailCommand {
public static final String EMAIL_NAME = "email";
@Parameter(names = {"--subject", "-s"}, required = true,
description = "The subject of the invitation email")
private String subject;
@Parameter(names = {"--from-name", "-n"}, required = true,
description = "The name that will appear as sender in the invitation emails")
private String fromName;
@Parameter(names = {"--from-address", "-a"}, required = true,
description = "The address to send invitation emails from")
private String fromAddress;
@Parameter(names = {"--password", "-p"}, required = true,
description = "The password for the account that will send the invitation emails")
private String password;
public String getSubject() {
return subject;
}
public String getFromName() {
return fromName;
}
public String getFromAddress() {
return fromAddress;
}
public String getPassword() {
return password;
}
}
| UTF-8 | Java | 1,224 | java | EmailCommand.java | Java | [
{
"context": "\n\n public String getPassword() {\n return password;\n }\n}\n",
"end": 1214,
"score": 0.8368199467658997,
"start": 1206,
"tag": "PASSWORD",
"value": "password"
}
] | null | [] | package se.miniwa.deater.cli;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
@Parameters(commandDescription = "Launches a game in email mode")
public class EmailCommand {
public static final String EMAIL_NAME = "email";
@Parameter(names = {"--subject", "-s"}, required = true,
description = "The subject of the invitation email")
private String subject;
@Parameter(names = {"--from-name", "-n"}, required = true,
description = "The name that will appear as sender in the invitation emails")
private String fromName;
@Parameter(names = {"--from-address", "-a"}, required = true,
description = "The address to send invitation emails from")
private String fromAddress;
@Parameter(names = {"--password", "-p"}, required = true,
description = "The password for the account that will send the invitation emails")
private String password;
public String getSubject() {
return subject;
}
public String getFromName() {
return fromName;
}
public String getFromAddress() {
return fromAddress;
}
public String getPassword() {
return <PASSWORD>;
}
}
| 1,226 | 0.651961 | 0.651961 | 41 | 28.853659 | 26.540867 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.585366 | false | false | 3 |
9df0abefb9962be5f4285bbe8736895b0c40213d | 25,220,047,971,157 | b59e02ad56c26f94ca121e2ff43a4921031c7a62 | /src/main/java/com/server/interfaces/IParsesRequestLine.java | 0e7ce5962717e66d609e947658ddc54b37ac79fe | [] | no_license | Gslaughl/HttpServer | https://github.com/Gslaughl/HttpServer | 3deddbc34dd770301869e0730907076f3f612af8 | ed86bc4fbcb5c66fb8df6ec667b8061bd9943fbb | refs/heads/master | 2017-05-10T22:31:43.132000 | 2017-03-16T17:01:47 | 2017-03-16T17:01:47 | 82,597,384 | 0 | 0 | null | false | 2017-11-07T15:47:00 | 2017-02-20T20:03:02 | 2017-02-20T20:03:18 | 2017-11-07T15:47:00 | 15,276 | 0 | 0 | 0 | Java | false | null | package com.server.interfaces;
import java.io.BufferedReader;
import java.util.LinkedHashMap;
public interface IParsesRequestLine {
LinkedHashMap<String, String> parseRequestLine(BufferedReader reader);
}
| UTF-8 | Java | 211 | java | IParsesRequestLine.java | Java | [] | null | [] | package com.server.interfaces;
import java.io.BufferedReader;
import java.util.LinkedHashMap;
public interface IParsesRequestLine {
LinkedHashMap<String, String> parseRequestLine(BufferedReader reader);
}
| 211 | 0.819905 | 0.819905 | 8 | 25.375 | 23.600517 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.625 | false | false | 3 |
3b932642be6e0aaf1f2dc06264b1b4827d52c102 | 17,575,006,202,668 | b21f8c33f927ddfa290d71f8de89d9d8c40562a1 | /src/test/GameDataTest.java | 9b7ad151e9bff7e68fe040c0651128eb6589365e | [] | no_license | PIPProject/GameEditor | https://github.com/PIPProject/GameEditor | bedf65b952d9a99742020bc408146b65baf2ecdc | e0e9645e567fbc8862fa10e18381bc1218d43def | refs/heads/master | 2018-12-28T05:42:15.746000 | 2015-08-05T13:49:37 | 2015-08-05T13:49:37 | 39,922,371 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package test;
import com.pip.game.data.ProjectData;
public class GameDataTest extends ProjectData {
// public GameDataTest(ProjectConfig gameConfig) {
// super(gameConfig);
// }
// public static GameConfig gameConfig = new GameConfigTest();
public static void main(String[] args) {
System.out.println("dddd");
// Thread t = new Thread(new Runnable() {
// public void run() {
//// while(true) {
////
//// }
// System.out.println("ddddddd");
//
// }
//
// });
// t.start();
}
}
| UTF-8 | Java | 684 | java | GameDataTest.java | Java | [] | null | [] | package test;
import com.pip.game.data.ProjectData;
public class GameDataTest extends ProjectData {
// public GameDataTest(ProjectConfig gameConfig) {
// super(gameConfig);
// }
// public static GameConfig gameConfig = new GameConfigTest();
public static void main(String[] args) {
System.out.println("dddd");
// Thread t = new Thread(new Runnable() {
// public void run() {
//// while(true) {
////
//// }
// System.out.println("ddddddd");
//
// }
//
// });
// t.start();
}
}
| 684 | 0.461988 | 0.461988 | 27 | 23.333334 | 18.509256 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.296296 | false | false | 3 |
4ec84ce4dabba77fa7e6756811ee7320981e35a3 | 4,569,845,235,186 | 08434d1c3c7ccadfcd1ae83f29092bd8f8bf0084 | /common/src/main/java/com/vivek/wo/common/view/wheelpicker/widgets/WheelDayPicker.java | 64bbb0ea4b158f01aa5c49bb88947054c6aaa2a8 | [] | no_license | vivek-wo/ProjectMVVM | https://github.com/vivek-wo/ProjectMVVM | 0c27b5b2e8f3bc38a1c6abac6945d18044e1f5ea | aa42d07334b46797596ddda201a8a113361c8091 | refs/heads/master | 2021-06-12T03:51:09.754000 | 2021-04-09T02:07:19 | 2021-04-09T02:07:19 | 171,703,281 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.vivek.wo.common.view.wheelpicker.widgets;
import android.content.Context;
import android.util.AttributeSet;
import com.vivek.wo.common.view.wheelpicker.WheelPicker;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
/**
* 日期选择器
* <p>
* Picker for Day
*
* @author AigeStudio 2016-07-12
* @version 1
*/
public class WheelDayPicker extends WheelPicker {
private Calendar mCalendar;
private int mDayStart = 1, mDayEnd;
private int mYear, mMonth;
private int mSelectedDay;
public WheelDayPicker(Context context) {
this(context, null);
}
public WheelDayPicker(Context context, AttributeSet attrs) {
super(context, attrs);
mCalendar = Calendar.getInstance();
mYear = mCalendar.get(Calendar.YEAR);
mMonth = mCalendar.get(Calendar.MONTH);
updateDays();
}
private void updateDays() {
mCalendar.set(Calendar.YEAR, mYear);
mCalendar.set(Calendar.MONTH, mMonth);
int days = mCalendar.getActualMaximum(Calendar.DAY_OF_MONTH);
mDayEnd = days;
//开始日期大于结束日期为参数异常,正常时间下不会出现
if (mDayStart > mDayEnd) {
throw new IllegalArgumentException("Day Start parameter error in current Year and Month");
}
List<Integer> data = new ArrayList<>();
for (int i = mDayStart; i <= days; i++) {
data.add(i);
}
super.setData(data);
}
private void updateSelectedDay() {
setSelectedItemPosition(mSelectedDay - mDayStart);
}
@Override
public void setData(List data) {
throw new UnsupportedOperationException("You can not invoke setData in WheelDayPicker");
}
/**
* 获取设置的日期
*
* @return
*/
public int getSelectedDay() {
return mSelectedDay;
}
/**
* 设置日期
*
* @param day
*/
public void setSelectedDay(int day) {
mSelectedDay = day;
updateSelectedDay();
}
/**
* 获取当前的日期
*
* @return
*/
public int getCurrentDay() {
return Integer.valueOf(String.valueOf(getData().get(getCurrentItemPosition())));
}
/**
* 设置年月
*
* @param year
* @param month
*/
public void setYearAndMonth(int year, int month) {
setYearAndMonth(year, month, 1);
}
/**
* 设置年月和开始的日期
*
* @param year
* @param month
* @param dayStart
*/
public void setYearAndMonth(int year, int month, int dayStart) {
mYear = year;
mMonth = month - 1;
mDayStart = dayStart;
mSelectedDay = getCurrentDay();
//前一次选择的日期小于开始日期
if (mSelectedDay < mDayStart) {
mSelectedDay = mDayStart;
}
updateDays();
//前一次选择的日期大于结束日期
if (mSelectedDay > mDayEnd) {
mSelectedDay = mDayEnd;
}
updateSelectedDay();
}
/**
* 获取设置的年
*
* @return
*/
public int getYear() {
return mYear;
}
/**
* 设置年
*
* @param year
*/
public void setYear(int year) {
setYearAndMonth(year, mMonth + 1);
}
/**
* 获取设置的月
*
* @return
*/
public int getMonth() {
return mMonth;
}
/**
* 设置月
*
* @param month
*/
public void setMonth(int month) {
setYearAndMonth(mYear, month);
}
} | UTF-8 | Java | 3,636 | java | WheelDayPicker.java | Java | [
{
"context": "**\n * 日期选择器\n * <p>\n * Picker for Day\n *\n * @author AigeStudio 2016-07-12\n * @version 1\n */\npublic class WheelDa",
"end": 322,
"score": 0.9995549321174622,
"start": 312,
"tag": "USERNAME",
"value": "AigeStudio"
}
] | null | [] | package com.vivek.wo.common.view.wheelpicker.widgets;
import android.content.Context;
import android.util.AttributeSet;
import com.vivek.wo.common.view.wheelpicker.WheelPicker;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
/**
* 日期选择器
* <p>
* Picker for Day
*
* @author AigeStudio 2016-07-12
* @version 1
*/
public class WheelDayPicker extends WheelPicker {
private Calendar mCalendar;
private int mDayStart = 1, mDayEnd;
private int mYear, mMonth;
private int mSelectedDay;
public WheelDayPicker(Context context) {
this(context, null);
}
public WheelDayPicker(Context context, AttributeSet attrs) {
super(context, attrs);
mCalendar = Calendar.getInstance();
mYear = mCalendar.get(Calendar.YEAR);
mMonth = mCalendar.get(Calendar.MONTH);
updateDays();
}
private void updateDays() {
mCalendar.set(Calendar.YEAR, mYear);
mCalendar.set(Calendar.MONTH, mMonth);
int days = mCalendar.getActualMaximum(Calendar.DAY_OF_MONTH);
mDayEnd = days;
//开始日期大于结束日期为参数异常,正常时间下不会出现
if (mDayStart > mDayEnd) {
throw new IllegalArgumentException("Day Start parameter error in current Year and Month");
}
List<Integer> data = new ArrayList<>();
for (int i = mDayStart; i <= days; i++) {
data.add(i);
}
super.setData(data);
}
private void updateSelectedDay() {
setSelectedItemPosition(mSelectedDay - mDayStart);
}
@Override
public void setData(List data) {
throw new UnsupportedOperationException("You can not invoke setData in WheelDayPicker");
}
/**
* 获取设置的日期
*
* @return
*/
public int getSelectedDay() {
return mSelectedDay;
}
/**
* 设置日期
*
* @param day
*/
public void setSelectedDay(int day) {
mSelectedDay = day;
updateSelectedDay();
}
/**
* 获取当前的日期
*
* @return
*/
public int getCurrentDay() {
return Integer.valueOf(String.valueOf(getData().get(getCurrentItemPosition())));
}
/**
* 设置年月
*
* @param year
* @param month
*/
public void setYearAndMonth(int year, int month) {
setYearAndMonth(year, month, 1);
}
/**
* 设置年月和开始的日期
*
* @param year
* @param month
* @param dayStart
*/
public void setYearAndMonth(int year, int month, int dayStart) {
mYear = year;
mMonth = month - 1;
mDayStart = dayStart;
mSelectedDay = getCurrentDay();
//前一次选择的日期小于开始日期
if (mSelectedDay < mDayStart) {
mSelectedDay = mDayStart;
}
updateDays();
//前一次选择的日期大于结束日期
if (mSelectedDay > mDayEnd) {
mSelectedDay = mDayEnd;
}
updateSelectedDay();
}
/**
* 获取设置的年
*
* @return
*/
public int getYear() {
return mYear;
}
/**
* 设置年
*
* @param year
*/
public void setYear(int year) {
setYearAndMonth(year, mMonth + 1);
}
/**
* 获取设置的月
*
* @return
*/
public int getMonth() {
return mMonth;
}
/**
* 设置月
*
* @param month
*/
public void setMonth(int month) {
setYearAndMonth(mYear, month);
}
} | 3,636 | 0.568129 | 0.564327 | 162 | 20.117285 | 19.371414 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.37037 | false | false | 3 |
2322f44e49845de9375b6e68285d5872e03d375f | 32,143,535,254,307 | ed97d27a83cd034236ff65a2c6542367b4c83386 | /goldassist-job/src/main/java/com/sutian/goldassist/job/price/StandGoldRedPriceUSJob.java | 28096c52ada88297de8d7c948034363fd27efdb8 | [] | no_license | sijinzhang/goldassist-server | https://github.com/sijinzhang/goldassist-server | f63b70201cb7688ad85518991f08b8e99ee76895 | 421d711caf7b795d440d7714a05c94defa94c4ab | refs/heads/master | 2021-09-26T18:41:40.280000 | 2021-09-23T06:20:48 | 2021-09-23T06:20:48 | 119,222,292 | 3 | 4 | null | false | 2021-09-20T21:03:18 | 2018-01-28T02:55:47 | 2021-09-18T10:46:36 | 2021-09-20T21:03:15 | 11,685 | 1 | 0 | 10 | Java | false | false | package com.sutian.goldassist.job.price;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.sutian.goldassist.common.entity.GoldUs;
import com.sutian.goldassist.core.service.IGoldUsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author sutian
* @email sijin.zsj
* @create 2020/4/29 17:06
*/
@Service
@EnableScheduling
public class StandGoldRedPriceUSJob {
private static final Logger log = LoggerFactory.getLogger(StandGoldRedPriceUSJob.class);
@Autowired
private IGoldUsService goldUsService;
/**
* 标准模型价格监控
*
*/
//@Scheduled(cron = "0 52 12 ? * MON-SAT")
public void goldStandPriceWork() {
log.info("job.stand.gold.red.us.price start!");
doTask();
log.info("job.stand.gold.red.us.price end!");
}
public void doTask() {
EntityWrapper<GoldUs> ew = new EntityWrapper<GoldUs>();
ew.setSqlSelect("distinct code");
List<GoldUs> goldUses = goldUsService.selectList(ew);
for (GoldUs goldUs : goldUses) {
EntityWrapper<GoldUs> query = new EntityWrapper<>();
query.eq("code", goldUs.getCode());
query.orderBy("dateTime", false);
query.last(" limit 3");
List<GoldUs> resut = goldUsService.selectList(query);
}
}
}
| UTF-8 | Java | 1,547 | java | StandGoldRedPriceUSJob.java | Java | [
{
"context": "e.Service;\n\nimport java.util.List;\n\n/**\n * @author sutian\n * @email sijin.zsj\n * @create 2020/4/29 17:06\n *",
"end": 485,
"score": 0.9994992613792419,
"start": 479,
"tag": "USERNAME",
"value": "sutian"
},
{
"context": "t java.util.List;\n\n/**\n * @author sutian\n * @email sijin.zsj\n * @create 2020/4/29 17:06\n */\n@Service\n@EnableSc",
"end": 505,
"score": 0.9992473125457764,
"start": 496,
"tag": "USERNAME",
"value": "sijin.zsj"
}
] | null | [] | package com.sutian.goldassist.job.price;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.sutian.goldassist.common.entity.GoldUs;
import com.sutian.goldassist.core.service.IGoldUsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author sutian
* @email sijin.zsj
* @create 2020/4/29 17:06
*/
@Service
@EnableScheduling
public class StandGoldRedPriceUSJob {
private static final Logger log = LoggerFactory.getLogger(StandGoldRedPriceUSJob.class);
@Autowired
private IGoldUsService goldUsService;
/**
* 标准模型价格监控
*
*/
//@Scheduled(cron = "0 52 12 ? * MON-SAT")
public void goldStandPriceWork() {
log.info("job.stand.gold.red.us.price start!");
doTask();
log.info("job.stand.gold.red.us.price end!");
}
public void doTask() {
EntityWrapper<GoldUs> ew = new EntityWrapper<GoldUs>();
ew.setSqlSelect("distinct code");
List<GoldUs> goldUses = goldUsService.selectList(ew);
for (GoldUs goldUs : goldUses) {
EntityWrapper<GoldUs> query = new EntityWrapper<>();
query.eq("code", goldUs.getCode());
query.orderBy("dateTime", false);
query.last(" limit 3");
List<GoldUs> resut = goldUsService.selectList(query);
}
}
}
| 1,547 | 0.680601 | 0.668191 | 52 | 28.442308 | 23.792706 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.480769 | false | false | 3 |
9000b5bd111b63308b015e82145d5957225513f7 | 22,694,607,259,581 | 98fd79ad418d0f5b5764f8c8d8b76c9aed9b55ab | /thyme-data/thyme-data-client/src/main/java/org/yixi/data/client/UpsertRequest.java | fbdc4e4c03dd3301dd97cb6d50d8fcaca532945d | [] | no_license | leo3877/thyme | https://github.com/leo3877/thyme | 5d33f86d48117af8673b7a83b289522867dce1df | 6cfde48d576d79cf075fbe3f067c895aed70894c | refs/heads/main | 2023-07-02T09:40:57.885000 | 2021-08-06T08:28:17 | 2021-08-06T08:28:17 | 393,306,750 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.yixi.data.client;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* @author yixi
* @since 1.0.0
*/
@SuppressWarnings("all")
public class UpsertRequest<PK, Entity> implements Serializable {
private Map<String, Object> filter;
private Entity doc;
public Map<String, Object> getFilter() {
return filter;
}
public void setFilter(Map<String, Object> filter) {
this.filter = filter;
}
public Entity getDoc() {
return doc;
}
public void setDoc(Entity doc) {
this.doc = doc;
}
public static Builder builder() {
return new Builder();
}
/**
* @author yixi
* @since 1.0.0
*/
public static class Builder<PK, Entity> {
private final UpsertRequest<PK, Entity> upsertRequest = new UpsertRequest();
private final Map<String, Object> filter = new HashMap<>();
public static Builder builder() {
return new Builder();
}
public UpsertRequest<PK, Entity> build() {
upsertRequest.setFilter(filter);
return upsertRequest;
}
public Builder filter(Map<String, Object> filter) {
this.filter.putAll(filter);
return this;
}
public Builder filter(String key, Object value) {
this.filter.put(key, value);
return this;
}
public Builder doc(Entity doc) {
upsertRequest.setDoc(doc);
return this;
}
}
}
| UTF-8 | Java | 1,395 | java | UpsertRequest.java | Java | [
{
"context": "til.HashMap;\nimport java.util.Map;\n\n/**\n * @author yixi\n * @since 1.0.0\n */\n@SuppressWarnings(\"all\")\npubl",
"end": 128,
"score": 0.9966623783111572,
"start": 124,
"tag": "USERNAME",
"value": "yixi"
},
{
"context": "\n return new Builder();\n }\n\n /**\n * @author yixi\n * @since 1.0.0\n */\n public static class Bui",
"end": 651,
"score": 0.9905137419700623,
"start": 647,
"tag": "USERNAME",
"value": "yixi"
}
] | null | [] | package org.yixi.data.client;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* @author yixi
* @since 1.0.0
*/
@SuppressWarnings("all")
public class UpsertRequest<PK, Entity> implements Serializable {
private Map<String, Object> filter;
private Entity doc;
public Map<String, Object> getFilter() {
return filter;
}
public void setFilter(Map<String, Object> filter) {
this.filter = filter;
}
public Entity getDoc() {
return doc;
}
public void setDoc(Entity doc) {
this.doc = doc;
}
public static Builder builder() {
return new Builder();
}
/**
* @author yixi
* @since 1.0.0
*/
public static class Builder<PK, Entity> {
private final UpsertRequest<PK, Entity> upsertRequest = new UpsertRequest();
private final Map<String, Object> filter = new HashMap<>();
public static Builder builder() {
return new Builder();
}
public UpsertRequest<PK, Entity> build() {
upsertRequest.setFilter(filter);
return upsertRequest;
}
public Builder filter(Map<String, Object> filter) {
this.filter.putAll(filter);
return this;
}
public Builder filter(String key, Object value) {
this.filter.put(key, value);
return this;
}
public Builder doc(Entity doc) {
upsertRequest.setDoc(doc);
return this;
}
}
}
| 1,395 | 0.643728 | 0.639427 | 72 | 18.375 | 18.96813 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.458333 | false | false | 3 |
8c24c6cd22587723e2dc7e7529842ae655190358 | 893,353,229,897 | 47da275d6b10915cc60d6fc3238b5bc243d6c5c1 | /de.rcenvironment.core.start.validators/src/main/java/de/rcenvironment/core/validators/internal/InstanceDataDirectoryWritableValidator.java | 1c260f16e8b1f4bc03731fdfe00271081315f217 | [] | no_license | rcenvironment/rce-test | https://github.com/rcenvironment/rce-test | aa325877be8508ee0f08181304a50bd97fa9f96c | 392406e8ca968b5d8168a9dd3155d620b5631ab6 | HEAD | 2016-09-06T03:35:58.165000 | 2015-01-16T10:45:50 | 2015-01-16T10:45:50 | 29,299,206 | 1 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright (C) 2006-2014 DLR, Germany
*
* All rights reserved
*
* http://www.rcenvironment.de/
*/
package de.rcenvironment.core.validators.internal;
import java.io.File;
import java.util.Collection;
import java.util.LinkedList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import de.rcenvironment.core.configuration.ConfigurationService;
import de.rcenvironment.core.start.common.validation.PlatformMessage;
import de.rcenvironment.core.start.common.validation.PlatformValidator;
/**
* Validates RCE platform home directory. Check if it is writable.
*
* @author Christian Weiss
*
*/
public class InstanceDataDirectoryWritableValidator implements PlatformValidator {
private static ConfigurationService configurationService;
private static CountDownLatch configurationServiceLatch = new CountDownLatch(1);
@Deprecated
public InstanceDataDirectoryWritableValidator() {
// do nothing
}
protected void bindConfigurationService(final ConfigurationService newConfigurationService) {
InstanceDataDirectoryWritableValidator.configurationService = newConfigurationService;
configurationServiceLatch.countDown();
}
@Override
public Collection<PlatformMessage> validatePlatform() {
final Collection<PlatformMessage> result = new LinkedList<PlatformMessage>();
File profileDir = null;
final ConfigurationService boundConfigurationService = getConfigurationService();
if (boundConfigurationService != null) {
profileDir = boundConfigurationService.getProfileDirectory();
} else {
result.add(new PlatformMessage(PlatformMessage.Type.ERROR,
ValidatorsBundleActivator.bundleSymbolicName,
Messages.directoryNoConfigurationService));
}
if (profileDir == null) {
result.add(new PlatformMessage(PlatformMessage.Type.ERROR,
ValidatorsBundleActivator.bundleSymbolicName,
Messages.directoryCouldNotBeRetrieved));
} else {
if (!profileDir.exists() || !profileDir.isDirectory()) {
result.add(new PlatformMessage(PlatformMessage.Type.ERROR,
ValidatorsBundleActivator.bundleSymbolicName, Messages.directoryRceFolderDoesNotExist + profileDir));
} else if (!profileDir.canRead() || !profileDir.canWrite()) {
result.add(new PlatformMessage(PlatformMessage.Type.ERROR,
ValidatorsBundleActivator.bundleSymbolicName,
Messages.directoryRceFolderNotReadWriteAble + profileDir));
}
}
return result;
}
/*
* Please note: There is not unit test for this method, because too much OSGi API mocking would be needed for that little bit of code.
* It is tested well, because it runs every time RCE starts up.
*/
protected ConfigurationService getConfigurationService() {
try {
InstanceDataDirectoryWritableValidator.configurationServiceLatch.await(3, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return InstanceDataDirectoryWritableValidator.configurationService;
}
}
| UTF-8 | Java | 3,378 | java | InstanceDataDirectoryWritableValidator.java | Java | [
{
"context": "rectory. Check if it is writable.\r\n * \r\n * @author Christian Weiss\r\n * \r\n */\r\npublic class InstanceDataDirectoryWrit",
"end": 657,
"score": 0.9991152286529541,
"start": 642,
"tag": "NAME",
"value": "Christian Weiss"
}
] | null | [] | /*
* Copyright (C) 2006-2014 DLR, Germany
*
* All rights reserved
*
* http://www.rcenvironment.de/
*/
package de.rcenvironment.core.validators.internal;
import java.io.File;
import java.util.Collection;
import java.util.LinkedList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import de.rcenvironment.core.configuration.ConfigurationService;
import de.rcenvironment.core.start.common.validation.PlatformMessage;
import de.rcenvironment.core.start.common.validation.PlatformValidator;
/**
* Validates RCE platform home directory. Check if it is writable.
*
* @author <NAME>
*
*/
public class InstanceDataDirectoryWritableValidator implements PlatformValidator {
private static ConfigurationService configurationService;
private static CountDownLatch configurationServiceLatch = new CountDownLatch(1);
@Deprecated
public InstanceDataDirectoryWritableValidator() {
// do nothing
}
protected void bindConfigurationService(final ConfigurationService newConfigurationService) {
InstanceDataDirectoryWritableValidator.configurationService = newConfigurationService;
configurationServiceLatch.countDown();
}
@Override
public Collection<PlatformMessage> validatePlatform() {
final Collection<PlatformMessage> result = new LinkedList<PlatformMessage>();
File profileDir = null;
final ConfigurationService boundConfigurationService = getConfigurationService();
if (boundConfigurationService != null) {
profileDir = boundConfigurationService.getProfileDirectory();
} else {
result.add(new PlatformMessage(PlatformMessage.Type.ERROR,
ValidatorsBundleActivator.bundleSymbolicName,
Messages.directoryNoConfigurationService));
}
if (profileDir == null) {
result.add(new PlatformMessage(PlatformMessage.Type.ERROR,
ValidatorsBundleActivator.bundleSymbolicName,
Messages.directoryCouldNotBeRetrieved));
} else {
if (!profileDir.exists() || !profileDir.isDirectory()) {
result.add(new PlatformMessage(PlatformMessage.Type.ERROR,
ValidatorsBundleActivator.bundleSymbolicName, Messages.directoryRceFolderDoesNotExist + profileDir));
} else if (!profileDir.canRead() || !profileDir.canWrite()) {
result.add(new PlatformMessage(PlatformMessage.Type.ERROR,
ValidatorsBundleActivator.bundleSymbolicName,
Messages.directoryRceFolderNotReadWriteAble + profileDir));
}
}
return result;
}
/*
* Please note: There is not unit test for this method, because too much OSGi API mocking would be needed for that little bit of code.
* It is tested well, because it runs every time RCE starts up.
*/
protected ConfigurationService getConfigurationService() {
try {
InstanceDataDirectoryWritableValidator.configurationServiceLatch.await(3, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return InstanceDataDirectoryWritableValidator.configurationService;
}
}
| 3,369 | 0.690053 | 0.687093 | 85 | 37.741177 | 33.923149 | 138 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.482353 | false | false | 3 |
2b74de471403b185d1da0057d3ff782a96eac443 | 893,353,228,093 | a555c44e79a4c48134cfd271010383de6b0891fa | /time-tracking-service/src/main/java/com/leqcar/timetracking/resource/CannotCreateTimeSheetException.java | de584dac67b231b9b8de08a041e85a7ec5c14168 | [] | no_license | leqcar/time-tracking-demo | https://github.com/leqcar/time-tracking-demo | 6dc8b655bff7cd045ae10f84a85be36c2908e429 | 539f655f33d092758cc89e583a6b8f4fca206449 | refs/heads/master | 2020-06-13T03:10:33.416000 | 2017-01-01T11:07:38 | 2017-01-01T11:07:38 | 75,457,367 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.leqcar.timetracking.resource;
public class CannotCreateTimeSheetException extends RuntimeException {
private static final long serialVersionUID = -2880584909769984831L;
public CannotCreateTimeSheetException(String message) {
super(message);
}
}
| UTF-8 | Java | 268 | java | CannotCreateTimeSheetException.java | Java | [] | null | [] | package com.leqcar.timetracking.resource;
public class CannotCreateTimeSheetException extends RuntimeException {
private static final long serialVersionUID = -2880584909769984831L;
public CannotCreateTimeSheetException(String message) {
super(message);
}
}
| 268 | 0.817164 | 0.746269 | 11 | 23.363636 | 28.013868 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.909091 | false | false | 3 |
58154a279ea3bcbf137ec7eaeeb7266341eff68c | 893,353,228,865 | a08e0a744046cc2223472dc0cf31cb9bbf8276b4 | /src/main/java/com/ssm/utils/Test.java | 0de6a1fa4f5a2480cb36e586bb58eda708dc16c7 | [] | no_license | yyhansen/ssmjavaConfig | https://github.com/yyhansen/ssmjavaConfig | 2063d172e7183b31c84473db3669d85cf75a6ad9 | 6adf37696293f86f6ee2f82004dc6939097de375 | refs/heads/master | 2020-03-18T08:24:40.163000 | 2018-06-15T11:24:43 | 2018-06-15T11:24:43 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ssm.utils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
/**
* Created by chenhansen on 2018/5/21.
*/
@PropertySource("classpath:properties/jdbc.properties")
public class Test {
@Value("${maxActive}")
private static int maxActive;
@Value("${maxWait}")
private static int maxWait;
public static void main(String[] args){
System.out.println(maxWait);
}
}
| UTF-8 | Java | 476 | java | Test.java | Java | [
{
"context": "text.annotation.PropertySource;\n\n/**\n * Created by chenhansen on 2018/5/21.\n */\n@PropertySource(\"classpath:prop",
"end": 174,
"score": 0.9996005296707153,
"start": 164,
"tag": "USERNAME",
"value": "chenhansen"
}
] | null | [] | package com.ssm.utils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
/**
* Created by chenhansen on 2018/5/21.
*/
@PropertySource("classpath:properties/jdbc.properties")
public class Test {
@Value("${maxActive}")
private static int maxActive;
@Value("${maxWait}")
private static int maxWait;
public static void main(String[] args){
System.out.println(maxWait);
}
}
| 476 | 0.716387 | 0.701681 | 18 | 25.444445 | 20.050554 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 3 |
96a9b3e74746adeca66e875eb656b68dd6d89311 | 14,267,881,412,158 | 285ebb1cd970a4a5d393d390a7db26031a1b1416 | /workspace/java_study/src/day24/Ex01_8.java | 1370a2c40a602b2b8e8522a13cb650f97993c909 | [] | no_license | minji428/JAVA | https://github.com/minji428/JAVA | 722bf34b8429a1bb9af4453db6dd3644bc96cbdd | 20621af26d62321ec0b139bd21b0172482b5f50b | refs/heads/main | 2023-07-18T16:22:57.265000 | 2021-09-11T14:23:05 | 2021-09-11T14:23:05 | 382,685,583 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package day24;
import java.util.Scanner;
// # 학생 추가 삭제 컨트롤러
// => 컨트롤러를 완성해 아래 3개의 정보를 추가하시오.
// 김철수 : 과목3개 수학 50 국어50 영어 60
// 이만수 : 과목2개 수학 20 국어 30
// 이영희 : 과목1개 수학 100
class Subject{
String name;
int score;
}
class Student{
Subject[] subjects;
String name;
}
public class Ex01_8 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Student[] list = new Student[3];
int count = 0;
while(true) {
for(int i=0; i<count; i++) {
System.out.println("["+(i+1)+"]"+list[i].name+"학생>>>");
if(list[i].subjects!=null) {
for(int j=0; j<list[i].subjects.length; j++) {
System.out.println("["+(i+1)+"]"+list[i].subjects[j].name);
}
}
System.out.println();
}
System.out.println("[1]학생 추가하기"); // 이름 입력받아 추가
System.out.println("[2]과목 추가하기"); // 이름과 과목 입력받아 추가
System.out.println("[3]성적 추가하기"); // 이름과 과목 그리고 성적 입력받아 추가
int choice = scan.nextInt();
if(choice == 1) {
System.out.print("이름 입력 : ");
String name = scan.next();
list[count] = new Student();
list[count].name = name;
count += 1;
}
else if(choice == 2) {
for(int i=0; i<count; i++) {
System.out.println("["+(i+1)+"]"+list[i].name);
}
System.out.print("학생 선택 : ");
int select = scan.nextInt();
select = select-1;
System.out.print("과목 입력 : ");
String subject = scan.next();
if(list[select].subjects == null) {
list[select].subjects = new Subject[1];
list[select].subjects[0] = new Subject();
list[select].subjects[0].name = subject;
}else {
int size = list[select].subjects.length;
}
}
else if(choice == 3) {
}
}
}
}
| UHC | Java | 2,075 | java | Ex01_8.java | Java | [] | null | [] | package day24;
import java.util.Scanner;
// # 학생 추가 삭제 컨트롤러
// => 컨트롤러를 완성해 아래 3개의 정보를 추가하시오.
// 김철수 : 과목3개 수학 50 국어50 영어 60
// 이만수 : 과목2개 수학 20 국어 30
// 이영희 : 과목1개 수학 100
class Subject{
String name;
int score;
}
class Student{
Subject[] subjects;
String name;
}
public class Ex01_8 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Student[] list = new Student[3];
int count = 0;
while(true) {
for(int i=0; i<count; i++) {
System.out.println("["+(i+1)+"]"+list[i].name+"학생>>>");
if(list[i].subjects!=null) {
for(int j=0; j<list[i].subjects.length; j++) {
System.out.println("["+(i+1)+"]"+list[i].subjects[j].name);
}
}
System.out.println();
}
System.out.println("[1]학생 추가하기"); // 이름 입력받아 추가
System.out.println("[2]과목 추가하기"); // 이름과 과목 입력받아 추가
System.out.println("[3]성적 추가하기"); // 이름과 과목 그리고 성적 입력받아 추가
int choice = scan.nextInt();
if(choice == 1) {
System.out.print("이름 입력 : ");
String name = scan.next();
list[count] = new Student();
list[count].name = name;
count += 1;
}
else if(choice == 2) {
for(int i=0; i<count; i++) {
System.out.println("["+(i+1)+"]"+list[i].name);
}
System.out.print("학생 선택 : ");
int select = scan.nextInt();
select = select-1;
System.out.print("과목 입력 : ");
String subject = scan.next();
if(list[select].subjects == null) {
list[select].subjects = new Subject[1];
list[select].subjects[0] = new Subject();
list[select].subjects[0].name = subject;
}else {
int size = list[select].subjects.length;
}
}
else if(choice == 3) {
}
}
}
}
| 2,075 | 0.52279 | 0.500275 | 82 | 20.207317 | 17.522625 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.170732 | false | false | 3 |
5d967b595d756856fc1c4f926e465b3ff703541a | 22,084,721,837,942 | 8a5de81d7268ea026b00a1238aa6d1488de74f10 | /src/main/java/com/politecnica/workshops/springboottest/controller/OperationController.java | a95a2fb3dc4586afa17b9995287e556046d41984 | [] | no_license | KarinaCardenasP/springboot-test | https://github.com/KarinaCardenasP/springboot-test | 33e45cd5c524eb2b6e898724b25e482088fef77b | fa5a3a67c89bd89a93e2f71709c9e61d1a1cff9c | refs/heads/master | 2020-03-15T17:51:57.713000 | 2018-05-05T19:13:39 | 2018-05-05T19:13:39 | 132,271,196 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.politecnica.workshops.springboottest.controller;
import com.politecnica.workshops.Operation;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class OperationController {
@RequestMapping(value="/sum")
public int DoOperation(@RequestParam int a, @RequestParam int b){
return a;
}
@Bean
public Operation getOperation(){
return new Operation();
}
}
| UTF-8 | Java | 620 | java | OperationController.java | Java | [] | null | [] | package com.politecnica.workshops.springboottest.controller;
import com.politecnica.workshops.Operation;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class OperationController {
@RequestMapping(value="/sum")
public int DoOperation(@RequestParam int a, @RequestParam int b){
return a;
}
@Bean
public Operation getOperation(){
return new Operation();
}
}
| 620 | 0.764516 | 0.764516 | 25 | 23.799999 | 24.706274 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.36 | false | false | 3 |
dc6ecc8fed44850474fdfa08f8a557af8f15623b | 21,620,865,430,029 | 0db0f45dbc6b59cd85c1a7d14c35fdf4f0fb6225 | /vertx-gaia/vertx-up/src/main/java/io/vertx/up/kidd/outcome/ListObstain.java | ecabc4fce610f9dc479f8565a407f6708c7b5621 | [
"Apache-2.0"
] | permissive | StrangeDreamer/vertx-zero | https://github.com/StrangeDreamer/vertx-zero | 48950eebc2ebaa27363e8001de1b0e3d4c02263e | 00aeed8c3d5123f8115f3a99d4d1b3bf295e26a4 | refs/heads/master | 2020-04-08T06:57:13.165000 | 2018-11-20T04:19:41 | 2018-11-20T04:19:41 | 159,120,199 | 1 | 0 | Apache-2.0 | true | 2018-11-26T06:16:47 | 2018-11-26T06:16:43 | 2018-11-20T04:19:43 | 2018-11-25T08:23:08 | 19,038 | 0 | 0 | 0 | null | false | null | package io.vertx.up.kidd.outcome;
import io.vertx.core.AsyncResult;
import io.vertx.core.json.JsonArray;
import io.vertx.up.atom.Envelop;
import io.vertx.up.exception.WebException;
import io.vertx.up.exception._400DuplicatedRecordException;
import io.vertx.up.exception._404RecordNotFoundException;
import io.vertx.zero.eon.Values;
import io.zero.epic.Ut;
import io.zero.epic.fn.Fn;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
public class ListObstain<T> extends Obstain<List<T>> {
public ListObstain(final Class<?> clazz) {
super(clazz);
}
public static <T> ListObstain<T> startList(final Class<?> clazz) {
return new ListObstain<>(clazz);
}
@Override
public ListObstain<T> unique() {
final WebException error404 = Ut.instance(
_404RecordNotFoundException.class, this.clazz);
final WebException error400 = Ut.instance(
_400DuplicatedRecordException.class, this.clazz);
return this.unique(error404, error400);
}
public <E> ListObstain<T> result() {
/**
* Convert function for each item of JsonObject
* Fix issue: map, empty for List<JsonObject> type serialization
*/
final Function<List<T>, JsonArray> convert = (from) -> {
final JsonArray array = new JsonArray();
from.forEach(array::add);
return array;
};
if (this.isReady()) {
this.envelop = Fn.getSemi(this.handler.succeeded(), this.logger,
// 200. Handler executed successfully
() -> Fn.getSemi(null == this.handler.result(), this.logger,
// 200. Result
() -> Envelop.success(new ArrayList<>()),
// 200. Result
() -> Envelop.success(convert.apply(this.handler.result()))),
// 500. Internal Error
Failure.build500Flow(this.clazz, this.handler.cause()));
}
return this;
}
public ListObstain<T> unique(final WebException internal404,
final WebException duplicated) {
if (this.isReady()) {
this.envelop = Fn.getSemi(this.handler.succeeded(), this.logger,
// 200. Handler executed successfully
() -> Fn.getSemi(null == this.handler.result()
|| this.handler.result().isEmpty(), this.logger,
// 404 -> Response
() -> Fn.getSemi(null == internal404, this.logger,
// 200 with empty data
() -> Envelop.success(new ArrayList<>()),
// 404 Error returned
Failure.build(internal404)),
// 200 -> Response
() -> Fn.getSemi(Values.ONE == this.handler.result().size(), this.logger,
// 200 -> Successfully
() -> Envelop.success(this.handler.result()),
// 400 -> Duplicated
() -> Fn.getSemi(null == duplicated, this.logger,
// 200 -> Duplicated skipped
() -> Envelop.success(this.handler.result()),
// 400 -> Throw exception
Failure.build(duplicated)))),
// 500. Internal Error
Failure.build500Flow(this.clazz, this.handler.cause()));
}
return this;
}
@Override
/**
* Connect to message handler
*
* @param handler
* @return
*/
public ListObstain<T> connect(final AsyncResult<List<T>> handler) {
Fn.safeSemi(null == handler, this.logger,
() -> this.logger.error(Info.ERROR_HANDLER, handler, this.clazz));
this.handler = handler;
return this;
}
}
| UTF-8 | Java | 4,209 | java | ListObstain.java | Java | [] | null | [] | package io.vertx.up.kidd.outcome;
import io.vertx.core.AsyncResult;
import io.vertx.core.json.JsonArray;
import io.vertx.up.atom.Envelop;
import io.vertx.up.exception.WebException;
import io.vertx.up.exception._400DuplicatedRecordException;
import io.vertx.up.exception._404RecordNotFoundException;
import io.vertx.zero.eon.Values;
import io.zero.epic.Ut;
import io.zero.epic.fn.Fn;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
public class ListObstain<T> extends Obstain<List<T>> {
public ListObstain(final Class<?> clazz) {
super(clazz);
}
public static <T> ListObstain<T> startList(final Class<?> clazz) {
return new ListObstain<>(clazz);
}
@Override
public ListObstain<T> unique() {
final WebException error404 = Ut.instance(
_404RecordNotFoundException.class, this.clazz);
final WebException error400 = Ut.instance(
_400DuplicatedRecordException.class, this.clazz);
return this.unique(error404, error400);
}
public <E> ListObstain<T> result() {
/**
* Convert function for each item of JsonObject
* Fix issue: map, empty for List<JsonObject> type serialization
*/
final Function<List<T>, JsonArray> convert = (from) -> {
final JsonArray array = new JsonArray();
from.forEach(array::add);
return array;
};
if (this.isReady()) {
this.envelop = Fn.getSemi(this.handler.succeeded(), this.logger,
// 200. Handler executed successfully
() -> Fn.getSemi(null == this.handler.result(), this.logger,
// 200. Result
() -> Envelop.success(new ArrayList<>()),
// 200. Result
() -> Envelop.success(convert.apply(this.handler.result()))),
// 500. Internal Error
Failure.build500Flow(this.clazz, this.handler.cause()));
}
return this;
}
public ListObstain<T> unique(final WebException internal404,
final WebException duplicated) {
if (this.isReady()) {
this.envelop = Fn.getSemi(this.handler.succeeded(), this.logger,
// 200. Handler executed successfully
() -> Fn.getSemi(null == this.handler.result()
|| this.handler.result().isEmpty(), this.logger,
// 404 -> Response
() -> Fn.getSemi(null == internal404, this.logger,
// 200 with empty data
() -> Envelop.success(new ArrayList<>()),
// 404 Error returned
Failure.build(internal404)),
// 200 -> Response
() -> Fn.getSemi(Values.ONE == this.handler.result().size(), this.logger,
// 200 -> Successfully
() -> Envelop.success(this.handler.result()),
// 400 -> Duplicated
() -> Fn.getSemi(null == duplicated, this.logger,
// 200 -> Duplicated skipped
() -> Envelop.success(this.handler.result()),
// 400 -> Throw exception
Failure.build(duplicated)))),
// 500. Internal Error
Failure.build500Flow(this.clazz, this.handler.cause()));
}
return this;
}
@Override
/**
* Connect to message handler
*
* @param handler
* @return
*/
public ListObstain<T> connect(final AsyncResult<List<T>> handler) {
Fn.safeSemi(null == handler, this.logger,
() -> this.logger.error(Info.ERROR_HANDLER, handler, this.clazz));
this.handler = handler;
return this;
}
}
| 4,209 | 0.508909 | 0.489665 | 106 | 38.707546 | 27.997293 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.603774 | false | false | 3 |
433b10c445c882a793eb7528a48496fb289570bb | 24,197,845,812,548 | fb3ecc342d6e9b490d96085ce4b3cca68c95cffc | /src/test/java/com/jlisok/youtube_activity_manager/youtube/services/VideoServiceImplementationTest.java | dffebe45a2e990d2a0e5422046843fc0feb9929f | [] | no_license | jlisok/youtube_activity_manager | https://github.com/jlisok/youtube_activity_manager | f46d416f3088655fd9c5ceec7d287fcbca7601ab | 89eda9808872c29c547628d26a0ff9b707202606 | refs/heads/master | 2023-01-09T18:01:22.511000 | 2020-11-08T16:50:59 | 2020-11-08T16:50:59 | 289,956,491 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jlisok.youtube_activity_manager.youtube.services;
import com.jlisok.youtube_activity_manager.channels.models.Channel;
import com.jlisok.youtube_activity_manager.registration.exceptions.RegistrationException;
import com.jlisok.youtube_activity_manager.testutils.TestProfile;
import com.jlisok.youtube_activity_manager.testutils.UserTestUtils;
import com.jlisok.youtube_activity_manager.testutils.VideoUtils;
import com.jlisok.youtube_activity_manager.users.models.User;
import com.jlisok.youtube_activity_manager.videoCategories.models.VideoCategory;
import com.jlisok.youtube_activity_manager.videos.models.Video;
import com.jlisok.youtube_activity_manager.youtube.utils.EntityCreator;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import javax.persistence.EntityManager;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.jlisok.youtube_activity_manager.testutils.ChannelAndSubscriptionUtils.createRandomYouTubeChannelList;
import static com.jlisok.youtube_activity_manager.testutils.YouTubeEntityVerifier.assertListOfVideosEqual;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
@SpringBootTest
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class VideoServiceImplementationTest implements TestProfile {
@Autowired
private UserTestUtils userTestUtils;
@Autowired
private VideoService service;
@MockBean
private EntityManager entityManager;
private User user;
private List<Channel> channels;
private List<VideoCategory> videoCategories;
private List<com.google.api.services.youtube.model.Channel> youtubeChannels;
@BeforeAll
void prepareInitialConditions() throws RegistrationException {
youtubeChannels = createRandomYouTubeChannelList(1);
user = userTestUtils.createUser(userTestUtils.createRandomEmail(), userTestUtils.createRandomPassword());
channels = youtubeChannels
.stream()
.map(ytChannel -> EntityCreator
.createChannel(ytChannel.getId(),
ytChannel.getSnippet(),
ytChannel.getStatistics(),
ytChannel.getContentOwnerDetails(),
Collections.singleton(user)))
.collect(Collectors.toList());
videoCategories = VideoUtils.createRandomListOfVideoCategories(20);
}
@ParameterizedTest
@MethodSource("exampleYouTubeLists")
void insertVideos_whenNewVideos(List<com.google.api.services.youtube.model.Video> youTubeVideoList) {
//given
when(entityManager.getReference(eq(Channel.class), any(UUID.class)))
.thenReturn(channels.get(0));
// when
List<Video> actualList = service.createVideos(youTubeVideoList, channels, videoCategories);
//then
assertListOfVideosEqual(youTubeVideoList, actualList);
}
Stream<Arguments> exampleYouTubeLists() {
return Stream.of(
Arguments.arguments(VideoUtils.createYouTubeVideoListGivenChannelsAndVideoCategory(0, youtubeChannels, videoCategories)),
Arguments.arguments(VideoUtils.createYouTubeVideoListGivenChannelsAndVideoCategory(1, youtubeChannels, videoCategories)),
Arguments.arguments(VideoUtils.createYouTubeVideoListGivenChannelsAndVideoCategory(5, youtubeChannels, videoCategories)),
Arguments.arguments(VideoUtils.createYouTubeVideoListGivenChannelsAndVideoCategory(100, youtubeChannels, videoCategories))
);
}
} | UTF-8 | Java | 4,137 | java | VideoServiceImplementationTest.java | Java | [] | null | [] | package com.jlisok.youtube_activity_manager.youtube.services;
import com.jlisok.youtube_activity_manager.channels.models.Channel;
import com.jlisok.youtube_activity_manager.registration.exceptions.RegistrationException;
import com.jlisok.youtube_activity_manager.testutils.TestProfile;
import com.jlisok.youtube_activity_manager.testutils.UserTestUtils;
import com.jlisok.youtube_activity_manager.testutils.VideoUtils;
import com.jlisok.youtube_activity_manager.users.models.User;
import com.jlisok.youtube_activity_manager.videoCategories.models.VideoCategory;
import com.jlisok.youtube_activity_manager.videos.models.Video;
import com.jlisok.youtube_activity_manager.youtube.utils.EntityCreator;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import javax.persistence.EntityManager;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.jlisok.youtube_activity_manager.testutils.ChannelAndSubscriptionUtils.createRandomYouTubeChannelList;
import static com.jlisok.youtube_activity_manager.testutils.YouTubeEntityVerifier.assertListOfVideosEqual;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
@SpringBootTest
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class VideoServiceImplementationTest implements TestProfile {
@Autowired
private UserTestUtils userTestUtils;
@Autowired
private VideoService service;
@MockBean
private EntityManager entityManager;
private User user;
private List<Channel> channels;
private List<VideoCategory> videoCategories;
private List<com.google.api.services.youtube.model.Channel> youtubeChannels;
@BeforeAll
void prepareInitialConditions() throws RegistrationException {
youtubeChannels = createRandomYouTubeChannelList(1);
user = userTestUtils.createUser(userTestUtils.createRandomEmail(), userTestUtils.createRandomPassword());
channels = youtubeChannels
.stream()
.map(ytChannel -> EntityCreator
.createChannel(ytChannel.getId(),
ytChannel.getSnippet(),
ytChannel.getStatistics(),
ytChannel.getContentOwnerDetails(),
Collections.singleton(user)))
.collect(Collectors.toList());
videoCategories = VideoUtils.createRandomListOfVideoCategories(20);
}
@ParameterizedTest
@MethodSource("exampleYouTubeLists")
void insertVideos_whenNewVideos(List<com.google.api.services.youtube.model.Video> youTubeVideoList) {
//given
when(entityManager.getReference(eq(Channel.class), any(UUID.class)))
.thenReturn(channels.get(0));
// when
List<Video> actualList = service.createVideos(youTubeVideoList, channels, videoCategories);
//then
assertListOfVideosEqual(youTubeVideoList, actualList);
}
Stream<Arguments> exampleYouTubeLists() {
return Stream.of(
Arguments.arguments(VideoUtils.createYouTubeVideoListGivenChannelsAndVideoCategory(0, youtubeChannels, videoCategories)),
Arguments.arguments(VideoUtils.createYouTubeVideoListGivenChannelsAndVideoCategory(1, youtubeChannels, videoCategories)),
Arguments.arguments(VideoUtils.createYouTubeVideoListGivenChannelsAndVideoCategory(5, youtubeChannels, videoCategories)),
Arguments.arguments(VideoUtils.createYouTubeVideoListGivenChannelsAndVideoCategory(100, youtubeChannels, videoCategories))
);
}
} | 4,137 | 0.751752 | 0.749335 | 92 | 43.97826 | 35.811699 | 138 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.695652 | false | false | 3 |
d3b5b10613c886d69daf090e29cb7d11a695ad11 | 33,294,586,545,695 | 64631b4232c36aca7f38c4797dacdadd1be523be | /src/main/java/httpTest/PieGraph.java | 312c99d6c470d1782b7ca9b93784add5f3a1b0a8 | [] | no_license | AvelarJ/WorldGraphViewerG27 | https://github.com/AvelarJ/WorldGraphViewerG27 | e0ebacbd0ec24da2398492165d4359482570f7ce | d1a270b2e3963505e90f1908e0b640e369a86416 | refs/heads/main | 2023-05-03T13:31:30.686000 | 2021-05-22T04:14:42 | 2021-05-22T04:14:42 | 369,711,741 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package httpTest;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.JOptionPane;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.util.TableOrder;
import org.jfree.data.category.DefaultCategoryDataset;
/**
*
* @author Jordan Avelar
*
*/
public class PieGraph implements Viewer {
private ComputationServer subject;
/**
* LineGraph constructor
* @param subject
*/
public PieGraph(ComputationServer subject) {
subject.attach(this);
this.subject = subject;
initView();
}
/**
* Updates viewer with info in Result res
* @param changedSubject
* @param res
*/
public void update(ComputationServer changedSubject, Result res) {
if(changedSubject.equals(subject)) {
draw(res);
}
}
/**
* Initialize a blank viewer
*/
public void initView() {
JFreeChart chart = ChartFactory.createPieChart(null, null);
ChartPanel chartPanel = new ChartPanel(chart);
chartPanel.setPreferredSize(new Dimension(400, 300));
chartPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
chartPanel.setBackground(Color.white);
MainUI.draw(chartPanel);
}
/**
* Makes a new viewer with result data
* @param res
*/
public void draw(Result res) {
// anType array holds analysis info in each index
String[] anType = MainUI.decodeType(res);
if(anType.length == 2) { // length of 2 means its a 1 series dataset
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
for(int i=0;i<res.getYears().size();i++) { // Loop through all values in result
if(res.getValues().get(0).get(i) > 0) {
//Add normal value given then add remainder of pie chart (100-res....)
dataset.addValue(res.getValues().get(0).get(i), anType[1], res.getYears().get(i));
dataset.addValue(100-res.getValues().get(0).get(i), "", res.getYears().get(i));
}
}
JFreeChart pieChart = ChartFactory.createMultiplePieChart(anType[0], dataset,
TableOrder.BY_COLUMN, true, true, false);
ChartPanel chartPanel = new ChartPanel(pieChart);
chartPanel.setPreferredSize(new Dimension(400, 300));
chartPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
chartPanel.setBackground(Color.white);
MainUI.draw(chartPanel);
}
// Else can't make a pie chart
else {
JOptionPane.showMessageDialog(null,
"Cannot produce a pie chart with current analysis type",
"Error",
JOptionPane.WARNING_MESSAGE);
}
}
}
| UTF-8 | Java | 2,718 | java | PieGraph.java | Java | [
{
"context": "ry.DefaultCategoryDataset;\r\n\r\n/**\r\n * \r\n * @author Jordan Avelar\r\n *\r\n */\r\n\r\npublic class PieGraph implements View",
"end": 388,
"score": 0.9998363256454468,
"start": 375,
"tag": "NAME",
"value": "Jordan Avelar"
}
] | null | [] | package httpTest;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.JOptionPane;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.util.TableOrder;
import org.jfree.data.category.DefaultCategoryDataset;
/**
*
* @author <NAME>
*
*/
public class PieGraph implements Viewer {
private ComputationServer subject;
/**
* LineGraph constructor
* @param subject
*/
public PieGraph(ComputationServer subject) {
subject.attach(this);
this.subject = subject;
initView();
}
/**
* Updates viewer with info in Result res
* @param changedSubject
* @param res
*/
public void update(ComputationServer changedSubject, Result res) {
if(changedSubject.equals(subject)) {
draw(res);
}
}
/**
* Initialize a blank viewer
*/
public void initView() {
JFreeChart chart = ChartFactory.createPieChart(null, null);
ChartPanel chartPanel = new ChartPanel(chart);
chartPanel.setPreferredSize(new Dimension(400, 300));
chartPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
chartPanel.setBackground(Color.white);
MainUI.draw(chartPanel);
}
/**
* Makes a new viewer with result data
* @param res
*/
public void draw(Result res) {
// anType array holds analysis info in each index
String[] anType = MainUI.decodeType(res);
if(anType.length == 2) { // length of 2 means its a 1 series dataset
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
for(int i=0;i<res.getYears().size();i++) { // Loop through all values in result
if(res.getValues().get(0).get(i) > 0) {
//Add normal value given then add remainder of pie chart (100-res....)
dataset.addValue(res.getValues().get(0).get(i), anType[1], res.getYears().get(i));
dataset.addValue(100-res.getValues().get(0).get(i), "", res.getYears().get(i));
}
}
JFreeChart pieChart = ChartFactory.createMultiplePieChart(anType[0], dataset,
TableOrder.BY_COLUMN, true, true, false);
ChartPanel chartPanel = new ChartPanel(pieChart);
chartPanel.setPreferredSize(new Dimension(400, 300));
chartPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
chartPanel.setBackground(Color.white);
MainUI.draw(chartPanel);
}
// Else can't make a pie chart
else {
JOptionPane.showMessageDialog(null,
"Cannot produce a pie chart with current analysis type",
"Error",
JOptionPane.WARNING_MESSAGE);
}
}
}
| 2,711 | 0.662987 | 0.646799 | 99 | 25.454546 | 24.848743 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.090909 | false | false | 3 |
5dcb31455680e1b8b344988343b0eeb5f1528be0 | 16,286,516,000,675 | 6f36e847fbacb814f7ba041fe060dab32fa1be74 | /springboot-shiro/src/main/java/com/study/user/service/sys/SysUserService.java | 8fe244532ef72615d1b886f576ca0463bfb4cc73 | [] | no_license | wcl19860926/springboot-demo | https://github.com/wcl19860926/springboot-demo | b3d31f2a03bb3edc3097abad55d356f0505a2d28 | c71827acda26314ecd80dfd024e7858147f4c3b3 | refs/heads/main | 2023-03-09T15:31:28.805000 | 2021-02-28T11:34:05 | 2021-02-28T11:34:05 | 342,522,874 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.study.user.service.sys;
import com.study.user.entity.sys.SysUser;
import com.study.common.core.mybaties.service.BaseService;
/**
* 服务类
*
* @author
* @date Thu Jun 18 15:05:00 CST 2020
*/
public interface SysUserService extends BaseService<SysUser , String> {
SysUser findUserByUserCode(String userCode);
}
| UTF-8 | Java | 347 | java | SysUserService.java | Java | [] | null | [] | package com.study.user.service.sys;
import com.study.user.entity.sys.SysUser;
import com.study.common.core.mybaties.service.BaseService;
/**
* 服务类
*
* @author
* @date Thu Jun 18 15:05:00 CST 2020
*/
public interface SysUserService extends BaseService<SysUser , String> {
SysUser findUserByUserCode(String userCode);
}
| 347 | 0.721408 | 0.686217 | 18 | 17.888889 | 23.720335 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.277778 | false | false | 3 |
75a4afd6afa3503886d217d4badc7cd155a6b140 | 16,535,624,105,359 | f90139e8d8a90080394be57022cfefceb5bc4acc | /DsAlgoExamples/src/PreviousQuestions/StackInPlaceReversal.java | 4887541738cc52948b97c2b07f934965abebae4f | [] | no_license | NagarajuG/intprep | https://github.com/NagarajuG/intprep | 87c18733ef5ef0795a4899fbe1ea7fc395cb8889 | 8428bdd5c2e7cadb86439f854fc9d8a883e46fb2 | refs/heads/master | 2020-11-27T12:07:05.660000 | 2019-12-24T21:04:10 | 2019-12-24T21:04:10 | 229,431,905 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package PreviousQuestions;
import java.util.Stack;
public class StackInPlaceReversal {
public static void main(String[] args) {
Stack<Integer> st = new Stack<>();
st.push(1);
st.push(2);
st.push(3);
st.push(4);
st.push(5);
st.push(6);
// System.out.println(st);
reverse(st);
while (!st.isEmpty()) {
System.out.println(st.pop());
}
// System.out.println(st);
}
public static void reverse(Stack<Integer> st) {
if (st == null || st.isEmpty() == true)
return;
int element = st.pop();
reverse(st);
insertAtBottom(st, element);
}
public static void insertAtBottom(Stack<Integer> st, int element) {
if (st.isEmpty() == true) {
st.push(element);
return;
}
int element2 = st.pop();
insertAtBottom(st, element);
st.push(element2);
}
} | UTF-8 | Java | 795 | java | StackInPlaceReversal.java | Java | [] | null | [] | package PreviousQuestions;
import java.util.Stack;
public class StackInPlaceReversal {
public static void main(String[] args) {
Stack<Integer> st = new Stack<>();
st.push(1);
st.push(2);
st.push(3);
st.push(4);
st.push(5);
st.push(6);
// System.out.println(st);
reverse(st);
while (!st.isEmpty()) {
System.out.println(st.pop());
}
// System.out.println(st);
}
public static void reverse(Stack<Integer> st) {
if (st == null || st.isEmpty() == true)
return;
int element = st.pop();
reverse(st);
insertAtBottom(st, element);
}
public static void insertAtBottom(Stack<Integer> st, int element) {
if (st.isEmpty() == true) {
st.push(element);
return;
}
int element2 = st.pop();
insertAtBottom(st, element);
st.push(element2);
}
} | 795 | 0.628931 | 0.618868 | 46 | 16.304348 | 15.731261 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.891304 | false | false | 3 |
f7653e94bfb85503a26626fd318db2f38cbaaeea | 16,535,624,107,743 | 50ccae804ce221af3ffab60d798c0262f27bf5bd | /app/src/main/java/com/cang/zhenpin/zhenpincang/ui/search/SearchActivity.java | 058b188bfb4ae1304f879cce789472f3429540f3 | [] | no_license | mavsforlife/zhenpin | https://github.com/mavsforlife/zhenpin | 91738961937ff8acab641afb4d8c10bdbc017a6a | f5d063d29b6ac980e8e8d1944c5daf3ad695067a | refs/heads/master | 2018-10-10T09:51:46.287000 | 2018-06-24T06:57:44 | 2018-06-24T06:57:44 | 114,330,810 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cang.zhenpin.zhenpincang.ui.search;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.cang.zhenpin.zhenpincang.R;
import com.cang.zhenpin.zhenpincang.glide.GlideApp;
import com.cang.zhenpin.zhenpincang.model.Brand;
import com.cang.zhenpin.zhenpincang.model.UserInfo;
import com.cang.zhenpin.zhenpincang.pref.PreferencesFactory;
import com.cang.zhenpin.zhenpincang.ui.list.GoodsListAdapter;
import com.cang.zhenpin.zhenpincang.ui.register.RegisterActivity;
import com.cang.zhenpin.zhenpincang.util.DeviceUtil;
import com.cang.zhenpin.zhenpincang.util.DialogUtil;
import com.cang.zhenpin.zhenpincang.util.ShareUtil;
import com.cang.zhenpin.zhenpincang.util.ToastUtil;
import com.cang.zhenpin.zhenpincang.widget.TopDividerItemDecoration;
import com.victor.loadinglayout.LoadingLayout;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
public class SearchActivity extends AppCompatActivity implements SearchContract.View, GoodsListAdapter.ShareListener, View.OnClickListener {
private EditText mSearch;
private TextView mCancel;
private RecyclerView mRv;
private LinearLayoutManager mLayoutManager;
private GoodsListAdapter mAdapter;
private LoadingLayout mLoadingLayout;
private SearchPresenter mPresenter;
private LinearLayout mLlAll;
private ImageView mIv1, mIv2, mIv3, mIv4;
private TextView mTv1;
private LinearLayout mProgress;
private boolean mHasMoreData = true; //是否加载更多数据
private boolean mIsLoading; //是否在加载中
private Intent mShareIntent;
private int mScreenWidth;
private int mPos;
private String mKeyword;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
initView();
initShotView();
}
private void initView() {
mSearch = findViewById(R.id.et_keyword);
mSearch.setOnKeyListener(mOnKeyListener);
mCancel = findViewById(R.id.cancel);
mCancel.setOnClickListener(this);
mRv = findViewById(R.id.rv_goods);
mLoadingLayout = findViewById(R.id.loading_layout);
mLoadingLayout.setOnErrorClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mPresenter.onLoadData(mKeyword, true);
}
});
mLayoutManager = new LinearLayoutManager(this);
mRv.setLayoutManager(mLayoutManager);
mRv.addItemDecoration(new TopDividerItemDecoration(this,
LinearLayoutManager.VERTICAL, DeviceUtil.dip2px(this,
0.5f)));
mRv.addOnScrollListener(mOnScrollListener);
mAdapter = new GoodsListAdapter(this, this, false, false);
mRv.setAdapter(mAdapter);
mPresenter = new SearchPresenter(this, this);
mScreenWidth = DeviceUtil.getScreenWidthPixel(SearchActivity.this);
}
private void initShotView() {
mIv1 = findViewById(R.id.iv1);
mIv2 = findViewById(R.id.iv2);
mIv3 = findViewById(R.id.iv3);
mIv4 = findViewById(R.id.iv4);
mTv1 = findViewById(R.id.tv1);
mLlAll = findViewById(R.id.ll_all);
mProgress = findViewById(R.id.ll_progress);
}
private RecyclerView.OnScrollListener mOnScrollListener = new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int lastVisibleItem = mLayoutManager.findLastVisibleItemPosition();
int totalCount = mLayoutManager.getItemCount();
if (lastVisibleItem + 1 == totalCount && mHasMoreData && !mIsLoading) {
mPresenter.onLoadData(mKeyword, false);
}
}
};
private View.OnKeyListener mOnKeyListener = new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER) {
// 先隐藏键盘
((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
.hideSoftInputFromWindow(SearchActivity.this.getCurrentFocus()
.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
//进行搜索操作的方法,在该方法中可以加入mEditSearchUser的非空判断
mKeyword = mSearch.getText().toString();
mPresenter.onLoadData(mKeyword, true);
}
return false;
}
};
public static Intent createIntent(Context context) {
Intent intent = new Intent(context, SearchActivity.class);
return intent;
}
@Override
public void showTip(String tip) {
ToastUtil.showShort(this, tip);
}
@Override
public void showTip(int resId) {
ToastUtil.showShort(this, resId);
}
@Override
public void addBrandList(List<Brand> list, boolean isRefresh) {
if (null == list || list.size() == 0) {
return;
}
mLoadingLayout.showContent();
if (isRefresh) {
List<Object> newList = new ArrayList<>();
newList.addAll(list);
mAdapter.setData(newList);
} else {
mAdapter.addData(list);
}
}
@Override
public void showEmpty() {
mAdapter.clear();
mLoadingLayout.showEmpty();
}
@Override
public void onError() {
if (mAdapter.isEmpty()) {
mLoadingLayout.showError();
} else {
mAdapter.showFooterError();
}
}
@Override
public void hasMoreData(boolean bool) {
mHasMoreData = bool;
mAdapter.setHasMoreData(mHasMoreData);
}
@Override
public void setIsLoading(boolean isLoading) {
mIsLoading = isLoading;
}
@Override
public void showLoading() {
mLoadingLayout.showLoading();
}
@Override
public void shareTo(final List<File> list, final String desc) {
if (list == null || list.size() == 0) {
showTip(getString(R.string.no_pic));
return;
}
runOnUiThread(new Runnable() {
@Override
public void run() {
mShareIntent = ShareUtil.BuildShareIntent(SearchActivity.this, list, desc);
dismissProgressDialog();
startActivity(mShareIntent);
}
});
}
@Override
public void shareFail() {
runOnUiThread(new Runnable() {
@Override
public void run() {
dismissProgressDialog();
showTip(getString(R.string.save_pic_fail_please_retry));
}
});
}
@Override
public void showHideProgress(boolean isShow) {
if (isShow) {
showProgressDialog();
} else {
dismissProgressDialog();
}
}
private void showProgressDialog() {
mProgress.setVisibility(View.VISIBLE);
}
private void dismissProgressDialog() {
mProgress.setVisibility(View.GONE);
}
@Override
public void setUpShotView(final List<String> list, final List<Integer> params, final String desc, final String fileName) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (list == null || list.size() != 4) {
showTip("没有图片,分享失败");
return;
}
io.reactivex.Observable.just(mLlAll)
.map(new Function<LinearLayout, LinearLayout>() {
@Override
public LinearLayout apply(LinearLayout linearLayout) throws Exception {
ViewGroup.LayoutParams lp = mLlAll.getLayoutParams();
mScreenWidth = DeviceUtil.getScreenWidthPixel(SearchActivity.this);
int height = (int) (((float) params.get(1)) / ((float) params.get(0)) * mScreenWidth * 0.75f);
lp.width = mScreenWidth;
lp.height = height;
mLlAll.setLayoutParams(lp);
return mLlAll;
}
})
.subscribeOn(AndroidSchedulers.mainThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<LinearLayout>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(LinearLayout linearLayout) {
GlideApp.with(SearchActivity.this).load(list.get(0)).centerCrop().into(mIv1);
GlideApp.with(SearchActivity.this).load(list.get(1)).centerCrop().into(mIv2);
GlideApp.with(SearchActivity.this).load(list.get(2)).centerCrop().into(mIv3);
GlideApp.with(SearchActivity.this).load(list.get(3)).centerCrop().into(mIv4);
mTv1.setText(desc);
}
@Override
public void onError(Throwable e) {
shareFail();
}
@Override
public void onComplete() {
mLlAll.postDelayed(new Runnable() {
@Override
public void run() {
mPresenter.onShotToFile(mLlAll, desc, fileName);
}
}, 1000);
}
});
}
});
}
private void showShareDialog(final Brand brand) {
AlertDialog.Builder shareDialog = DialogUtil.showShareDialog(this);
shareDialog
.setNegativeButton(R.string.normal_share, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mPresenter.onShareNormal(brand);
dialog.dismiss();
}
})
.setPositiveButton(R.string.compose_share, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mPresenter.onShareCompose(brand);
dialog.dismiss();
}
})
.setNeutralButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.create()
.show();
}
@Override
public void onShare(Brand brand) {
if (!ShareUtil.isShareEnabled()) {
showShareTip();
return;
}
showShareDialog(brand);
// mPos = position;
}
private void showShareTip() {
new AlertDialog.Builder(this)
.setMessage("只有代理用户才能分享")
.setPositiveButton("申请代理", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if (!checkIsApplyed()) {
SearchActivity.this.startActivity(RegisterActivity.createIntent(SearchActivity.this));
}
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
}
private boolean checkIsApplyed() {
if (PreferencesFactory.getUserPref().getUserType() == UserInfo.TYPE_APPLY_ING_INT) {
ToastUtil.showShort(this, "您已经申请过代理,请等待后台处理");
mPresenter.refreshUserInfo();
return true;
}
return false;
}
@Override
public void onRetry() {
mPresenter.onLoadData(mKeyword, false);
}
@Override
public void onEmpty() {
mLoadingLayout.showEmpty();
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.cancel) {
onBackPressed();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
mPresenter.destroy();
}
}
| UTF-8 | Java | 14,124 | java | SearchActivity.java | Java | [] | null | [] | package com.cang.zhenpin.zhenpincang.ui.search;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.cang.zhenpin.zhenpincang.R;
import com.cang.zhenpin.zhenpincang.glide.GlideApp;
import com.cang.zhenpin.zhenpincang.model.Brand;
import com.cang.zhenpin.zhenpincang.model.UserInfo;
import com.cang.zhenpin.zhenpincang.pref.PreferencesFactory;
import com.cang.zhenpin.zhenpincang.ui.list.GoodsListAdapter;
import com.cang.zhenpin.zhenpincang.ui.register.RegisterActivity;
import com.cang.zhenpin.zhenpincang.util.DeviceUtil;
import com.cang.zhenpin.zhenpincang.util.DialogUtil;
import com.cang.zhenpin.zhenpincang.util.ShareUtil;
import com.cang.zhenpin.zhenpincang.util.ToastUtil;
import com.cang.zhenpin.zhenpincang.widget.TopDividerItemDecoration;
import com.victor.loadinglayout.LoadingLayout;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
public class SearchActivity extends AppCompatActivity implements SearchContract.View, GoodsListAdapter.ShareListener, View.OnClickListener {
private EditText mSearch;
private TextView mCancel;
private RecyclerView mRv;
private LinearLayoutManager mLayoutManager;
private GoodsListAdapter mAdapter;
private LoadingLayout mLoadingLayout;
private SearchPresenter mPresenter;
private LinearLayout mLlAll;
private ImageView mIv1, mIv2, mIv3, mIv4;
private TextView mTv1;
private LinearLayout mProgress;
private boolean mHasMoreData = true; //是否加载更多数据
private boolean mIsLoading; //是否在加载中
private Intent mShareIntent;
private int mScreenWidth;
private int mPos;
private String mKeyword;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
initView();
initShotView();
}
private void initView() {
mSearch = findViewById(R.id.et_keyword);
mSearch.setOnKeyListener(mOnKeyListener);
mCancel = findViewById(R.id.cancel);
mCancel.setOnClickListener(this);
mRv = findViewById(R.id.rv_goods);
mLoadingLayout = findViewById(R.id.loading_layout);
mLoadingLayout.setOnErrorClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mPresenter.onLoadData(mKeyword, true);
}
});
mLayoutManager = new LinearLayoutManager(this);
mRv.setLayoutManager(mLayoutManager);
mRv.addItemDecoration(new TopDividerItemDecoration(this,
LinearLayoutManager.VERTICAL, DeviceUtil.dip2px(this,
0.5f)));
mRv.addOnScrollListener(mOnScrollListener);
mAdapter = new GoodsListAdapter(this, this, false, false);
mRv.setAdapter(mAdapter);
mPresenter = new SearchPresenter(this, this);
mScreenWidth = DeviceUtil.getScreenWidthPixel(SearchActivity.this);
}
private void initShotView() {
mIv1 = findViewById(R.id.iv1);
mIv2 = findViewById(R.id.iv2);
mIv3 = findViewById(R.id.iv3);
mIv4 = findViewById(R.id.iv4);
mTv1 = findViewById(R.id.tv1);
mLlAll = findViewById(R.id.ll_all);
mProgress = findViewById(R.id.ll_progress);
}
private RecyclerView.OnScrollListener mOnScrollListener = new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int lastVisibleItem = mLayoutManager.findLastVisibleItemPosition();
int totalCount = mLayoutManager.getItemCount();
if (lastVisibleItem + 1 == totalCount && mHasMoreData && !mIsLoading) {
mPresenter.onLoadData(mKeyword, false);
}
}
};
private View.OnKeyListener mOnKeyListener = new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER) {
// 先隐藏键盘
((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
.hideSoftInputFromWindow(SearchActivity.this.getCurrentFocus()
.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
//进行搜索操作的方法,在该方法中可以加入mEditSearchUser的非空判断
mKeyword = mSearch.getText().toString();
mPresenter.onLoadData(mKeyword, true);
}
return false;
}
};
public static Intent createIntent(Context context) {
Intent intent = new Intent(context, SearchActivity.class);
return intent;
}
@Override
public void showTip(String tip) {
ToastUtil.showShort(this, tip);
}
@Override
public void showTip(int resId) {
ToastUtil.showShort(this, resId);
}
@Override
public void addBrandList(List<Brand> list, boolean isRefresh) {
if (null == list || list.size() == 0) {
return;
}
mLoadingLayout.showContent();
if (isRefresh) {
List<Object> newList = new ArrayList<>();
newList.addAll(list);
mAdapter.setData(newList);
} else {
mAdapter.addData(list);
}
}
@Override
public void showEmpty() {
mAdapter.clear();
mLoadingLayout.showEmpty();
}
@Override
public void onError() {
if (mAdapter.isEmpty()) {
mLoadingLayout.showError();
} else {
mAdapter.showFooterError();
}
}
@Override
public void hasMoreData(boolean bool) {
mHasMoreData = bool;
mAdapter.setHasMoreData(mHasMoreData);
}
@Override
public void setIsLoading(boolean isLoading) {
mIsLoading = isLoading;
}
@Override
public void showLoading() {
mLoadingLayout.showLoading();
}
@Override
public void shareTo(final List<File> list, final String desc) {
if (list == null || list.size() == 0) {
showTip(getString(R.string.no_pic));
return;
}
runOnUiThread(new Runnable() {
@Override
public void run() {
mShareIntent = ShareUtil.BuildShareIntent(SearchActivity.this, list, desc);
dismissProgressDialog();
startActivity(mShareIntent);
}
});
}
@Override
public void shareFail() {
runOnUiThread(new Runnable() {
@Override
public void run() {
dismissProgressDialog();
showTip(getString(R.string.save_pic_fail_please_retry));
}
});
}
@Override
public void showHideProgress(boolean isShow) {
if (isShow) {
showProgressDialog();
} else {
dismissProgressDialog();
}
}
private void showProgressDialog() {
mProgress.setVisibility(View.VISIBLE);
}
private void dismissProgressDialog() {
mProgress.setVisibility(View.GONE);
}
@Override
public void setUpShotView(final List<String> list, final List<Integer> params, final String desc, final String fileName) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (list == null || list.size() != 4) {
showTip("没有图片,分享失败");
return;
}
io.reactivex.Observable.just(mLlAll)
.map(new Function<LinearLayout, LinearLayout>() {
@Override
public LinearLayout apply(LinearLayout linearLayout) throws Exception {
ViewGroup.LayoutParams lp = mLlAll.getLayoutParams();
mScreenWidth = DeviceUtil.getScreenWidthPixel(SearchActivity.this);
int height = (int) (((float) params.get(1)) / ((float) params.get(0)) * mScreenWidth * 0.75f);
lp.width = mScreenWidth;
lp.height = height;
mLlAll.setLayoutParams(lp);
return mLlAll;
}
})
.subscribeOn(AndroidSchedulers.mainThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<LinearLayout>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(LinearLayout linearLayout) {
GlideApp.with(SearchActivity.this).load(list.get(0)).centerCrop().into(mIv1);
GlideApp.with(SearchActivity.this).load(list.get(1)).centerCrop().into(mIv2);
GlideApp.with(SearchActivity.this).load(list.get(2)).centerCrop().into(mIv3);
GlideApp.with(SearchActivity.this).load(list.get(3)).centerCrop().into(mIv4);
mTv1.setText(desc);
}
@Override
public void onError(Throwable e) {
shareFail();
}
@Override
public void onComplete() {
mLlAll.postDelayed(new Runnable() {
@Override
public void run() {
mPresenter.onShotToFile(mLlAll, desc, fileName);
}
}, 1000);
}
});
}
});
}
private void showShareDialog(final Brand brand) {
AlertDialog.Builder shareDialog = DialogUtil.showShareDialog(this);
shareDialog
.setNegativeButton(R.string.normal_share, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mPresenter.onShareNormal(brand);
dialog.dismiss();
}
})
.setPositiveButton(R.string.compose_share, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mPresenter.onShareCompose(brand);
dialog.dismiss();
}
})
.setNeutralButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.create()
.show();
}
@Override
public void onShare(Brand brand) {
if (!ShareUtil.isShareEnabled()) {
showShareTip();
return;
}
showShareDialog(brand);
// mPos = position;
}
private void showShareTip() {
new AlertDialog.Builder(this)
.setMessage("只有代理用户才能分享")
.setPositiveButton("申请代理", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if (!checkIsApplyed()) {
SearchActivity.this.startActivity(RegisterActivity.createIntent(SearchActivity.this));
}
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
}
private boolean checkIsApplyed() {
if (PreferencesFactory.getUserPref().getUserType() == UserInfo.TYPE_APPLY_ING_INT) {
ToastUtil.showShort(this, "您已经申请过代理,请等待后台处理");
mPresenter.refreshUserInfo();
return true;
}
return false;
}
@Override
public void onRetry() {
mPresenter.onLoadData(mKeyword, false);
}
@Override
public void onEmpty() {
mLoadingLayout.showEmpty();
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.cancel) {
onBackPressed();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
mPresenter.destroy();
}
}
| 14,124 | 0.569504 | 0.566351 | 395 | 34.331646 | 26.447443 | 140 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.562025 | false | false | 3 |
dc69f590ad6515ea39179f6b076694da0a491399 | 9,706,626,111,566 | 5e3235edf3de262f4d10b9e9e1fcc3bd13d6b8b1 | /Code Snippet Repository/Hibernate/Hibernate261.java | 6332dece1dd5ccdd4edb456b257b30b91a893e6f | [] | no_license | saber13812002/DeepCRM | https://github.com/saber13812002/DeepCRM | 3336a244d4852a364800af3181e03e868cf6f9f5 | be3e5e50e34a042d5ba7259ff5ff75c08ab32bb9 | refs/heads/master | 2023-03-16T00:08:06.473000 | 2018-04-18T05:29:50 | 2018-04-18T05:29:50 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | @Test
public void testDistinctProjection() {
doInJPA( this::entityManagerFactory, entityManager -> {
//tag::hql-distinct-projection-query-example[]
List<String> lastNames = entityManager.createQuery(
"select distinct p.lastName " +
"from Person p", String.class)
.getResultList();
//end::hql-distinct-projection-query-example[]
assertTrue(
lastNames.size() == 2 &&
lastNames.contains( "King" ) &&
lastNames.contains( "Mihalcea" )
);
});
}
| UTF-8 | Java | 501 | java | Hibernate261.java | Java | [
{
"context": "lastNames.size() == 2 &&\n\t\t\t\tlastNames.contains( \"King\" ) &&\n\t\t\t\tlastNames.contains( \"Mihalcea\" )\n\t\t\t);\n",
"end": 442,
"score": 0.9892337322235107,
"start": 438,
"tag": "NAME",
"value": "King"
},
{
"context": "es.contains( \"King\" ) &&\n\t\t\t\tlastNames.contains( \"Mihalcea\" )\n\t\t\t);\n\t\t});\n\t}\n",
"end": 482,
"score": 0.9991694688796997,
"start": 474,
"tag": "NAME",
"value": "Mihalcea"
}
] | null | [] | @Test
public void testDistinctProjection() {
doInJPA( this::entityManagerFactory, entityManager -> {
//tag::hql-distinct-projection-query-example[]
List<String> lastNames = entityManager.createQuery(
"select distinct p.lastName " +
"from Person p", String.class)
.getResultList();
//end::hql-distinct-projection-query-example[]
assertTrue(
lastNames.size() == 2 &&
lastNames.contains( "King" ) &&
lastNames.contains( "Mihalcea" )
);
});
}
| 501 | 0.644711 | 0.642715 | 18 | 26.777779 | 20.703074 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.444444 | false | false | 3 |
728393a1f6e43f75b3cf4022e640b0807cfb47e5 | 23,356,032,219,666 | ba98954353bb475114d48e6f9ddda07111f9091f | /edu/uncc/parsets/parsets/SelectionChangeEvent.java | 3e6e1ac98110b39b2a4663b25a3df1b5af891dcc | [
"BSD-3-Clause"
] | permissive | evelynmitchell/parsets | https://github.com/evelynmitchell/parsets | 846e325fc4d89c5b050d28dd4c1e1e6176c121f4 | 7cd8b2aff9befb825cc3bc5b9c86cd1de2942e56 | refs/heads/master | 2021-01-10T12:08:47.245000 | 2011-12-15T18:15:16 | 2011-12-15T18:15:16 | 48,853,304 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
*
*
*/
package edu.uncc.parsets.parsets;
import edu.uncc.parsets.data.CategoryHandle;
import edu.uncc.parsets.data.CategoryNode;
import java.util.List;
/**
*
* @author aacain
*/
public class SelectionChangeEvent {
public static final String SELECTION_CHANGE = "SELECTION_CHANGE";
public static final String CREATE_NEW_VIEW = "CREATE_NEW_VIEW";
private final String eventType;
private final CategoryNode selectedNode;
private final List<CategoryHandle> filteredCategories;
private final boolean isOnCategoryBar;
public SelectionChangeEvent(String eventType, CategoryNode selectedNode, List<CategoryHandle> filteredCategories, boolean isOnCategoryBar) {
this.eventType = eventType;
this.selectedNode = selectedNode;
this.filteredCategories = filteredCategories;
this.isOnCategoryBar = isOnCategoryBar;
}
public String getEventType() {
return eventType;
}
public List<CategoryHandle> getFilteredCategories() {
return filteredCategories;
}
public CategoryNode getSelectedCategory() {
return selectedNode;
}
public boolean isOnCategoryBar(){
return this.isOnCategoryBar;
}
}
| UTF-8 | Java | 1,226 | java | SelectionChangeEvent.java | Java | [
{
"context": "oryNode;\nimport java.util.List;\n\n/**\n *\n * @author aacain\n */\npublic class SelectionChangeEvent {\n publi",
"end": 187,
"score": 0.9993672966957092,
"start": 181,
"tag": "USERNAME",
"value": "aacain"
}
] | null | [] | /*
*
*
*/
package edu.uncc.parsets.parsets;
import edu.uncc.parsets.data.CategoryHandle;
import edu.uncc.parsets.data.CategoryNode;
import java.util.List;
/**
*
* @author aacain
*/
public class SelectionChangeEvent {
public static final String SELECTION_CHANGE = "SELECTION_CHANGE";
public static final String CREATE_NEW_VIEW = "CREATE_NEW_VIEW";
private final String eventType;
private final CategoryNode selectedNode;
private final List<CategoryHandle> filteredCategories;
private final boolean isOnCategoryBar;
public SelectionChangeEvent(String eventType, CategoryNode selectedNode, List<CategoryHandle> filteredCategories, boolean isOnCategoryBar) {
this.eventType = eventType;
this.selectedNode = selectedNode;
this.filteredCategories = filteredCategories;
this.isOnCategoryBar = isOnCategoryBar;
}
public String getEventType() {
return eventType;
}
public List<CategoryHandle> getFilteredCategories() {
return filteredCategories;
}
public CategoryNode getSelectedCategory() {
return selectedNode;
}
public boolean isOnCategoryBar(){
return this.isOnCategoryBar;
}
}
| 1,226 | 0.712072 | 0.712072 | 47 | 25.085106 | 27.469774 | 144 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.446809 | false | false | 3 |
5662a0add6a8cd6966a785d3621b99cbdc408949 | 2,181,843,435,115 | 4663170a25c299ba6abd2e614a78694a0aa78587 | /services/service-commons/src/test/java/net/thomas/portfolio/service_commons/network/urls/PortfolioUrlLibraryUnitTest.java | 6952fb057f45d3bc8fdcfb4bdace1b4deea2ab64 | [] | no_license | ViktorKob/portfolio | https://github.com/ViktorKob/portfolio | f71666b040a5970097ac69ac6c38393f0b527846 | 32223be163abcec412f8ed230944c554bdaec489 | refs/heads/master | 2022-06-24T11:01:56.795000 | 2020-01-05T08:57:00 | 2020-01-05T08:57:00 | 127,350,141 | 0 | 0 | null | false | 2022-06-20T22:43:17 | 2018-03-29T21:39:11 | 2020-01-05T08:57:16 | 2022-06-20T22:43:16 | 6,965 | 0 | 0 | 1 | Java | false | false | package net.thomas.portfolio.service_commons.network.urls;
import static java.util.Arrays.stream;
import static java.util.Collections.singleton;
import static java.util.stream.Collectors.joining;
import static net.thomas.portfolio.enums.HbaseIndexingServiceEndpoint.SCHEMA;
import static net.thomas.portfolio.globals.AnalyticsServiceGlobals.LOOKUP_KNOWLEDGE_PATH;
import static net.thomas.portfolio.globals.AnalyticsServiceGlobals.LOOKUP_KNOWLEDGE_ROOT_PATH;
import static net.thomas.portfolio.globals.HbaseIndexingServiceGlobals.DOCUMENTS_PATH;
import static net.thomas.portfolio.globals.HbaseIndexingServiceGlobals.ENTITIES_PATH;
import static net.thomas.portfolio.globals.HbaseIndexingServiceGlobals.FROM_SIMPLE_REP_PATH;
import static net.thomas.portfolio.globals.HbaseIndexingServiceGlobals.INVERTED_INDEX_PATH;
import static net.thomas.portfolio.globals.HbaseIndexingServiceGlobals.REFERENCES_PATH;
import static net.thomas.portfolio.globals.HbaseIndexingServiceGlobals.SAMPLES_PATH;
import static net.thomas.portfolio.globals.HbaseIndexingServiceGlobals.SELECTORS_PATH;
import static net.thomas.portfolio.globals.HbaseIndexingServiceGlobals.STATISTICS_PATH;
import static net.thomas.portfolio.globals.HbaseIndexingServiceGlobals.SUGGESTIONS_PATH;
import static net.thomas.portfolio.globals.LegalServiceGlobals.AUDIT_LOGGING_PATH;
import static net.thomas.portfolio.globals.LegalServiceGlobals.HISTORY_PATH;
import static net.thomas.portfolio.globals.LegalServiceGlobals.LEGAL_ROOT_PATH;
import static net.thomas.portfolio.globals.LegalServiceGlobals.LEGAL_RULES_PATH;
import static net.thomas.portfolio.globals.RenderServiceGlobals.AS_HTML_PATH;
import static net.thomas.portfolio.globals.RenderServiceGlobals.AS_SIMPLE_REPRESENTATION_PATH;
import static net.thomas.portfolio.globals.RenderServiceGlobals.AS_TEXT_PATH;
import static net.thomas.portfolio.globals.RenderServiceGlobals.RENDER_ENTITY_ROOT_PATH;
import static net.thomas.portfolio.globals.RenderServiceGlobals.RENDER_SELECTOR_ROOT_PATH;
import static net.thomas.portfolio.globals.UsageDataServiceGlobals.USAGE_ACTIVITIES_PATH;
import static net.thomas.portfolio.globals.UsageDataServiceGlobals.USAGE_ACTIVITIES_ROOT_PATH;
import static net.thomas.portfolio.services.Service.ANALYTICS_SERVICE;
import static net.thomas.portfolio.services.Service.HBASE_INDEXING_SERVICE;
import static net.thomas.portfolio.services.Service.LEGAL_SERVICE;
import static net.thomas.portfolio.services.Service.RENDER_SERVICE;
import static net.thomas.portfolio.services.Service.USAGE_DATA_SERVICE;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentMatcher;
import net.thomas.portfolio.common.services.parameters.Parameter;
import net.thomas.portfolio.common.services.parameters.ParameterGroup;
import net.thomas.portfolio.globals.LegalServiceGlobals;
import net.thomas.portfolio.services.ContextPathSection;
import net.thomas.portfolio.shared_objects.hbase_index.model.types.DataTypeId;
import net.thomas.portfolio.shared_objects.hbase_index.request.Bounds;
import net.thomas.portfolio.shared_objects.hbase_index.request.InvertedIndexLookupRequest;
import net.thomas.portfolio.shared_objects.legal.LegalInformation;
import net.thomas.portfolio.shared_objects.usage_data.UsageActivity;
public class PortfolioUrlLibraryUnitTest {
private static final Integer SOME_INTEGER = 10;
private static final String SOME_URL_STRING = "SOME_URL";
private static final String SOME_DATA_TYPE = "DataType";
private static final String SOME_SIMPLE_REPRESENTATION = "ABCD";
private static final String SOME_UID = "AA";
private static final DataTypeId SOME_DATA_TYPE_ID = new DataTypeId(SOME_DATA_TYPE, SOME_UID);
private static final ParameterGroup SOME_PARAMETER_GROUP = ParameterGroup.asGroup("name", singleton("value"));
private static final ParameterGroup[] SOME_PARAMETER_GROUPS = { SOME_PARAMETER_GROUP };
private UsageActivity someUsageActivity;
private LegalInformation someLegalInfo;
private Bounds someBounds;
private InvertedIndexLookupRequest someInvertedIndexLookupRequest;
private UrlFactory urlFactory;
private PortfolioUrlLibrary library;
@Before
public void setUpUrlGeneration() {
urlFactory = mock(UrlFactory.class);
library = new PortfolioUrlLibrary(urlFactory);
}
@Before
public void mockParameterGroups() {
someUsageActivity = mock(UsageActivity.class);
when(someUsageActivity.getParameters()).thenReturn(SOME_PARAMETER_GROUP.getParameters());
someLegalInfo = mock(LegalInformation.class);
when(someLegalInfo.getParameters()).thenReturn(SOME_PARAMETER_GROUP.getParameters());
someBounds = mock(Bounds.class);
when(someBounds.getParameters()).thenReturn(SOME_PARAMETER_GROUP.getParameters());
someInvertedIndexLookupRequest = mock(InvertedIndexLookupRequest.class);
when(someInvertedIndexLookupRequest.getSelectorId()).thenReturn(SOME_DATA_TYPE_ID);
when(someInvertedIndexLookupRequest.getGroups()).thenReturn(SOME_PARAMETER_GROUPS);
}
@Test
public void shouldHaveSchemaUrl() {
when(urlFactory.buildUrl(eq(HBASE_INDEXING_SERVICE), eq(SCHEMA))).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.schema());
}
@Test
public void shouldHaveEntitySamplesUrl() {
final ContextPathSection endpoint = asContextPath(ENTITIES_PATH, SOME_DATA_TYPE, SAMPLES_PATH);
when(urlFactory.buildUrl(eq(HBASE_INDEXING_SERVICE), argThat(matches(endpoint)), (ParameterGroup) any())).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.entities().samples(SOME_DATA_TYPE, SOME_INTEGER));
}
@Test
public void shouldHaveEntitySamplesParameterAmount() {
library.entities().samples(SOME_DATA_TYPE, SOME_INTEGER);
verify(urlFactory).buildUrl(any(), any(), argThat(matches(SOME_INTEGER)));
}
@Test
public void shouldHaveEntityLookupUrl() {
final ContextPathSection endpoint = asContextPath(ENTITIES_PATH, SOME_DATA_TYPE, SOME_UID);
when(urlFactory.buildUrl(eq(HBASE_INDEXING_SERVICE), argThat(matches(endpoint)))).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.entities().lookup(SOME_DATA_TYPE_ID));
}
@Test
public void shouldHaveEntityRenderAsTextUrl() {
final ContextPathSection endpoint = asContextPath(RENDER_ENTITY_ROOT_PATH, SOME_DATA_TYPE, SOME_UID, AS_TEXT_PATH);
when(urlFactory.buildUrl(eq(RENDER_SERVICE), argThat(matches(endpoint)))).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.entities().render().text(SOME_DATA_TYPE_ID));
}
@Test
public void shouldHaveEntityRenderAsHtmlUrl() {
final ContextPathSection endpoint = asContextPath(RENDER_ENTITY_ROOT_PATH, SOME_DATA_TYPE, SOME_UID, AS_HTML_PATH);
when(urlFactory.buildUrl(eq(RENDER_SERVICE), argThat(matches(endpoint)))).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.entities().render().html(SOME_DATA_TYPE_ID));
}
@Test
public void shouldHaveDocumentSamplesUrl() {
final ContextPathSection endpoint = asContextPath(DOCUMENTS_PATH, SOME_DATA_TYPE, SAMPLES_PATH);
when(urlFactory.buildUrl(eq(HBASE_INDEXING_SERVICE), argThat(matches(endpoint)), (ParameterGroup) any())).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.documents().samples(SOME_DATA_TYPE, SOME_INTEGER));
}
@Test
public void shouldHaveDocumentSamplesParameterAmount() {
library.documents().samples(SOME_DATA_TYPE, SOME_INTEGER);
verify(urlFactory).buildUrl(any(), any(), argThat(matches(SOME_INTEGER)));
}
@Test
public void shouldHaveDocumentLookupUrl() {
final ContextPathSection endpoint = asContextPath(DOCUMENTS_PATH, SOME_DATA_TYPE, SOME_UID);
when(urlFactory.buildUrl(eq(HBASE_INDEXING_SERVICE), argThat(matches(endpoint)))).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.documents().lookup(SOME_DATA_TYPE_ID));
}
@Test
public void shouldHaveDocumentReferencesUrl() {
final ContextPathSection endpoint = asContextPath(DOCUMENTS_PATH, SOME_DATA_TYPE, SOME_UID, REFERENCES_PATH);
when(urlFactory.buildUrl(eq(HBASE_INDEXING_SERVICE), argThat(matches(endpoint)))).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.documents().references(SOME_DATA_TYPE_ID));
}
@Test
public void shouldHaveDocumentGetUsageActivitiesUrl() {
final ContextPathSection endpoint = asContextPath(USAGE_ACTIVITIES_ROOT_PATH, SOME_DATA_TYPE, SOME_UID, USAGE_ACTIVITIES_PATH);
when(urlFactory.buildUrl(eq(USAGE_DATA_SERVICE), argThat(matches(endpoint)))).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.documents().usageActivities(SOME_DATA_TYPE_ID));
}
@Test
public void shouldHaveDocumentGetUsageActivitiesUrlWithBounds() {
final ContextPathSection endpoint = asContextPath(USAGE_ACTIVITIES_ROOT_PATH, SOME_DATA_TYPE, SOME_UID, USAGE_ACTIVITIES_PATH);
when(urlFactory.buildUrl(eq(USAGE_DATA_SERVICE), argThat(matches(endpoint)), (Bounds) any())).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.documents().usageActivities(SOME_DATA_TYPE_ID, someBounds));
}
@Test
public void shouldHaveDocumentPostUsageActivitiesUrl() {
final ContextPathSection endpoint = asContextPath(USAGE_ACTIVITIES_ROOT_PATH, SOME_DATA_TYPE, SOME_UID, USAGE_ACTIVITIES_PATH);
when(urlFactory.buildUrl(eq(USAGE_DATA_SERVICE), argThat(matches(endpoint)), (UsageActivity) any())).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.documents().usageActivities(SOME_DATA_TYPE_ID, someUsageActivity));
}
@Test
public void shouldHaveDocumentGetUsageActivitiesParameterBounds() {
library.documents().usageActivities(SOME_DATA_TYPE_ID, someBounds);
verify(urlFactory).buildUrl(any(), any(), argThat(matches(someBounds)));
}
@Test
public void shouldHaveDocumentPostUsageActivitiesParameterUsageActivity() {
library.documents().usageActivities(SOME_DATA_TYPE_ID, someUsageActivity);
verify(urlFactory).buildUrl(any(), any(), argThat(matches(someUsageActivity)));
}
@Test
public void shouldHaveDocumentRenderAsTextUrl() {
final ContextPathSection endpoint = asContextPath(RENDER_ENTITY_ROOT_PATH, SOME_DATA_TYPE, SOME_UID, AS_TEXT_PATH);
when(urlFactory.buildUrl(eq(RENDER_SERVICE), argThat(matches(endpoint)))).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.documents().render().text(SOME_DATA_TYPE_ID));
}
@Test
public void shouldHaveDocumentRenderAsHtmlUrl() {
final ContextPathSection endpoint = asContextPath(RENDER_ENTITY_ROOT_PATH, SOME_DATA_TYPE, SOME_UID, AS_HTML_PATH);
when(urlFactory.buildUrl(eq(RENDER_SERVICE), argThat(matches(endpoint)))).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.documents().render().html(SOME_DATA_TYPE_ID));
}
@Test
public void shouldHaveSelectorSamplesUrl() {
final ContextPathSection endpoint = asContextPath(SELECTORS_PATH, SOME_DATA_TYPE, SAMPLES_PATH);
when(urlFactory.buildUrl(eq(HBASE_INDEXING_SERVICE), argThat(matches(endpoint)), (ParameterGroup) any())).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.selectors().samples(SOME_DATA_TYPE, SOME_INTEGER));
}
@Test
public void shouldHaveSelectorSamplesParameterAmount() {
library.selectors().samples(SOME_DATA_TYPE, SOME_INTEGER);
verify(urlFactory).buildUrl(any(), any(), argThat(matches(SOME_INTEGER)));
}
@Test
public void shouldHaveSelectorSuggestionsUrl() {
final ContextPathSection endpoint = asContextPath(SELECTORS_PATH, SUGGESTIONS_PATH, SOME_SIMPLE_REPRESENTATION + "/");
when(urlFactory.buildUrl(eq(HBASE_INDEXING_SERVICE), argThat(matches(endpoint)))).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.selectors().suggestions(SOME_SIMPLE_REPRESENTATION));
}
@Test
public void shouldHaveSelectorLookupUrl() {
final ContextPathSection endpoint = asContextPath(SELECTORS_PATH, SOME_DATA_TYPE, SOME_UID);
when(urlFactory.buildUrl(eq(HBASE_INDEXING_SERVICE), argThat(matches(endpoint)))).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.selectors().lookup(SOME_DATA_TYPE_ID));
}
@Test
public void shouldHaveSelectorFromSimpleRepresentationUrl() {
final ContextPathSection endpoint = asContextPath(SELECTORS_PATH, SOME_DATA_TYPE, FROM_SIMPLE_REP_PATH, SOME_SIMPLE_REPRESENTATION + "/");
when(urlFactory.buildUrl(eq(HBASE_INDEXING_SERVICE), argThat(matches(endpoint)))).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.selectors().fromSimpleRepresentation(SOME_DATA_TYPE, SOME_SIMPLE_REPRESENTATION));
}
@Test
public void shouldHaveSelectorInvertedIndexLookupUrl() {
final ContextPathSection endpoint = asContextPath(SELECTORS_PATH, SOME_DATA_TYPE, SOME_UID, INVERTED_INDEX_PATH);
when(urlFactory.buildUrl(eq(HBASE_INDEXING_SERVICE), argThat(matches(endpoint)))).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.selectors().invertedIndex(SOME_DATA_TYPE_ID));
}
@Test
public void shouldHaveSelectorInvertedIndexLookupUrlWithParameter() {
final ContextPathSection endpoint = asContextPath(SELECTORS_PATH, SOME_DATA_TYPE, SOME_UID, INVERTED_INDEX_PATH);
when(urlFactory.buildUrl(eq(HBASE_INDEXING_SERVICE), argThat(matches(endpoint)), (ParameterGroup[]) any())).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.selectors().invertedIndex(someInvertedIndexLookupRequest));
}
@Test
public void shouldHaveSelectorInvertedIndexLookupUrlWithParameterInvertedIndexRequest() {
library.selectors().invertedIndex(someInvertedIndexLookupRequest);
verify(urlFactory).buildUrl(any(), any(), argThat(matches(SOME_PARAMETER_GROUP)));
}
@Test
public void shouldHaveSelectorKnowledgeUrl() {
final ContextPathSection endpoint = asContextPath(LOOKUP_KNOWLEDGE_ROOT_PATH, SOME_DATA_TYPE, SOME_UID, LOOKUP_KNOWLEDGE_PATH);
when(urlFactory.buildUrl(eq(ANALYTICS_SERVICE), argThat(matches(endpoint)))).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.selectors().knowledge(SOME_DATA_TYPE_ID));
}
@Test
public void shouldHaveSelectorStatisticsUrl() {
final ContextPathSection endpoint = asContextPath(SELECTORS_PATH, SOME_DATA_TYPE, SOME_UID, STATISTICS_PATH);
when(urlFactory.buildUrl(eq(HBASE_INDEXING_SERVICE), argThat(matches(endpoint)))).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.selectors().statistics(SOME_DATA_TYPE_ID));
}
@Test
public void shouldHaveSelectorRenderAsTextUrl() {
final ContextPathSection endpoint = asContextPath(RENDER_ENTITY_ROOT_PATH, SOME_DATA_TYPE, SOME_UID, AS_TEXT_PATH);
when(urlFactory.buildUrl(eq(RENDER_SERVICE), argThat(matches(endpoint)))).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.selectors().render().text(SOME_DATA_TYPE_ID));
}
@Test
public void shouldHaveSelectorRenderAsSimpleRepresentationUrl() {
final ContextPathSection endpoint = asContextPath(RENDER_SELECTOR_ROOT_PATH, SOME_DATA_TYPE, SOME_UID, AS_SIMPLE_REPRESENTATION_PATH);
when(urlFactory.buildUrl(eq(RENDER_SERVICE), argThat(matches(endpoint)))).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.selectors().render().simpleRepresentation(SOME_DATA_TYPE_ID));
}
@Test
public void shouldHaveSelectorRenderAsHtmlUrl() {
final ContextPathSection endpoint = asContextPath(RENDER_ENTITY_ROOT_PATH, SOME_DATA_TYPE, SOME_UID, AS_HTML_PATH);
when(urlFactory.buildUrl(eq(RENDER_SERVICE), argThat(matches(endpoint)))).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.selectors().render().html(SOME_DATA_TYPE_ID));
}
@Test
public void shouldHaveAuditCheckInvertedIndexUrl() {
final ContextPathSection endpoint = asContextPath(LEGAL_ROOT_PATH, SOME_DATA_TYPE, SOME_UID, LegalServiceGlobals.INVERTED_INDEX_PATH, LEGAL_RULES_PATH);
when(urlFactory.buildUrl(eq(LEGAL_SERVICE), argThat(matches(endpoint)), (LegalInformation) any())).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.selectors().audit().check().invertedIndex(SOME_DATA_TYPE_ID, someLegalInfo));
}
@Test
public void shouldHaveAuditCheckInvertedIndexUrlWithParameterLegalInfo() {
library.selectors().audit().check().invertedIndex(SOME_DATA_TYPE_ID, someLegalInfo);
verify(urlFactory).buildUrl(any(), any(), argThat(matches(SOME_PARAMETER_GROUP)));
}
@Test
public void shouldHaveAuditCheckStatisticsUrl() {
final ContextPathSection endpoint = asContextPath(LEGAL_ROOT_PATH, SOME_DATA_TYPE, SOME_UID, LegalServiceGlobals.STATISTICS_PATH, LEGAL_RULES_PATH);
when(urlFactory.buildUrl(eq(LEGAL_SERVICE), argThat(matches(endpoint)), (LegalInformation) any())).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.selectors().audit().check().statistics(SOME_DATA_TYPE_ID, someLegalInfo));
}
@Test
public void shouldHaveAuditCheckStatisticsUrlWithParameterLegalInfo() {
library.selectors().audit().check().statistics(SOME_DATA_TYPE_ID, someLegalInfo);
verify(urlFactory).buildUrl(any(), any(), argThat(matches(SOME_PARAMETER_GROUP)));
}
@Test
public void shouldHaveAuditLogInvertedIndexUrl() {
final ContextPathSection endpoint = asContextPath(LEGAL_ROOT_PATH, SOME_DATA_TYPE, SOME_UID, LegalServiceGlobals.INVERTED_INDEX_PATH,
AUDIT_LOGGING_PATH);
when(urlFactory.buildUrl(eq(LEGAL_SERVICE), argThat(matches(endpoint)), (LegalInformation) any())).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.selectors().audit().log().invertedIndex(SOME_DATA_TYPE_ID, someLegalInfo));
}
@Test
public void shouldHaveAuditLogInvertedIndexUrlWithParameterLegalInfo() {
library.selectors().audit().log().invertedIndex(SOME_DATA_TYPE_ID, someLegalInfo);
verify(urlFactory).buildUrl(any(), any(), argThat(matches(SOME_PARAMETER_GROUP)));
}
@Test
public void shouldHaveAuditLogStatisticsUrl() {
final ContextPathSection endpoint = asContextPath(LEGAL_ROOT_PATH, SOME_DATA_TYPE, SOME_UID, LegalServiceGlobals.STATISTICS_PATH, AUDIT_LOGGING_PATH);
when(urlFactory.buildUrl(eq(LEGAL_SERVICE), argThat(matches(endpoint)), (LegalInformation) any())).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.selectors().audit().log().statistics(SOME_DATA_TYPE_ID, someLegalInfo));
}
@Test
public void shouldHaveAuditLogStatisticsUrlWithParameterLegalInfo() {
library.selectors().audit().log().statistics(SOME_DATA_TYPE_ID, someLegalInfo);
verify(urlFactory).buildUrl(any(), any(), argThat(matches(SOME_PARAMETER_GROUP)));
}
@Test
public void shouldHaveLegalHistoryUrl() {
final ContextPathSection endpoint = asContextPath(LEGAL_ROOT_PATH, HISTORY_PATH);
when(urlFactory.buildUrl(eq(LEGAL_SERVICE), argThat(matches(endpoint)))).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.selectors().history().all());
}
@Test
public void shouldHaveLegalHistoryForItemUrl() {
final ContextPathSection endpoint = asContextPath(LEGAL_ROOT_PATH, HISTORY_PATH, "" + SOME_INTEGER + "/");
when(urlFactory.buildUrl(eq(LEGAL_SERVICE), argThat(matches(endpoint)))).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.selectors().history().item(SOME_INTEGER));
}
private ContextPathSection asContextPath(String... elements) {
return () -> ("/" + stream(elements).collect(joining("/"))).replaceAll("//", "/");
}
private ArgumentMatcher<ContextPathSection> matches(ContextPathSection endpoint) {
return actualEndpoint -> endpoint.getContextPath().equals(actualEndpoint.getContextPath());
}
private ArgumentMatcher<ParameterGroup> matches(Integer value) {
return group -> group.getParameters()[0].getValue().equals(value);
}
private ArgumentMatcher<ParameterGroup> matches(ParameterGroup value) {
return group -> {
final Parameter[] left = group.getParameters();
final Parameter[] right = value.getParameters();
if (left.length != right.length) {
return false;
}
for (int i = 0; i < left.length; i++) {
if (!(namesAreEqual(left[i], right[i]) && valuesAreEqual(left[i], right[i]))) {
return false;
}
}
return true;
};
}
private boolean namesAreEqual(Parameter currentLeft, Parameter currentRight) {
return currentLeft.getName().equals(currentRight.getName());
}
private boolean valuesAreEqual(Parameter currentLeft, Parameter currentRight) {
return currentLeft.getValue().equals(currentRight.getValue());
}
}
| UTF-8 | Java | 20,838 | java | PortfolioUrlLibraryUnitTest.java | Java | [] | null | [] | package net.thomas.portfolio.service_commons.network.urls;
import static java.util.Arrays.stream;
import static java.util.Collections.singleton;
import static java.util.stream.Collectors.joining;
import static net.thomas.portfolio.enums.HbaseIndexingServiceEndpoint.SCHEMA;
import static net.thomas.portfolio.globals.AnalyticsServiceGlobals.LOOKUP_KNOWLEDGE_PATH;
import static net.thomas.portfolio.globals.AnalyticsServiceGlobals.LOOKUP_KNOWLEDGE_ROOT_PATH;
import static net.thomas.portfolio.globals.HbaseIndexingServiceGlobals.DOCUMENTS_PATH;
import static net.thomas.portfolio.globals.HbaseIndexingServiceGlobals.ENTITIES_PATH;
import static net.thomas.portfolio.globals.HbaseIndexingServiceGlobals.FROM_SIMPLE_REP_PATH;
import static net.thomas.portfolio.globals.HbaseIndexingServiceGlobals.INVERTED_INDEX_PATH;
import static net.thomas.portfolio.globals.HbaseIndexingServiceGlobals.REFERENCES_PATH;
import static net.thomas.portfolio.globals.HbaseIndexingServiceGlobals.SAMPLES_PATH;
import static net.thomas.portfolio.globals.HbaseIndexingServiceGlobals.SELECTORS_PATH;
import static net.thomas.portfolio.globals.HbaseIndexingServiceGlobals.STATISTICS_PATH;
import static net.thomas.portfolio.globals.HbaseIndexingServiceGlobals.SUGGESTIONS_PATH;
import static net.thomas.portfolio.globals.LegalServiceGlobals.AUDIT_LOGGING_PATH;
import static net.thomas.portfolio.globals.LegalServiceGlobals.HISTORY_PATH;
import static net.thomas.portfolio.globals.LegalServiceGlobals.LEGAL_ROOT_PATH;
import static net.thomas.portfolio.globals.LegalServiceGlobals.LEGAL_RULES_PATH;
import static net.thomas.portfolio.globals.RenderServiceGlobals.AS_HTML_PATH;
import static net.thomas.portfolio.globals.RenderServiceGlobals.AS_SIMPLE_REPRESENTATION_PATH;
import static net.thomas.portfolio.globals.RenderServiceGlobals.AS_TEXT_PATH;
import static net.thomas.portfolio.globals.RenderServiceGlobals.RENDER_ENTITY_ROOT_PATH;
import static net.thomas.portfolio.globals.RenderServiceGlobals.RENDER_SELECTOR_ROOT_PATH;
import static net.thomas.portfolio.globals.UsageDataServiceGlobals.USAGE_ACTIVITIES_PATH;
import static net.thomas.portfolio.globals.UsageDataServiceGlobals.USAGE_ACTIVITIES_ROOT_PATH;
import static net.thomas.portfolio.services.Service.ANALYTICS_SERVICE;
import static net.thomas.portfolio.services.Service.HBASE_INDEXING_SERVICE;
import static net.thomas.portfolio.services.Service.LEGAL_SERVICE;
import static net.thomas.portfolio.services.Service.RENDER_SERVICE;
import static net.thomas.portfolio.services.Service.USAGE_DATA_SERVICE;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentMatcher;
import net.thomas.portfolio.common.services.parameters.Parameter;
import net.thomas.portfolio.common.services.parameters.ParameterGroup;
import net.thomas.portfolio.globals.LegalServiceGlobals;
import net.thomas.portfolio.services.ContextPathSection;
import net.thomas.portfolio.shared_objects.hbase_index.model.types.DataTypeId;
import net.thomas.portfolio.shared_objects.hbase_index.request.Bounds;
import net.thomas.portfolio.shared_objects.hbase_index.request.InvertedIndexLookupRequest;
import net.thomas.portfolio.shared_objects.legal.LegalInformation;
import net.thomas.portfolio.shared_objects.usage_data.UsageActivity;
public class PortfolioUrlLibraryUnitTest {
private static final Integer SOME_INTEGER = 10;
private static final String SOME_URL_STRING = "SOME_URL";
private static final String SOME_DATA_TYPE = "DataType";
private static final String SOME_SIMPLE_REPRESENTATION = "ABCD";
private static final String SOME_UID = "AA";
private static final DataTypeId SOME_DATA_TYPE_ID = new DataTypeId(SOME_DATA_TYPE, SOME_UID);
private static final ParameterGroup SOME_PARAMETER_GROUP = ParameterGroup.asGroup("name", singleton("value"));
private static final ParameterGroup[] SOME_PARAMETER_GROUPS = { SOME_PARAMETER_GROUP };
private UsageActivity someUsageActivity;
private LegalInformation someLegalInfo;
private Bounds someBounds;
private InvertedIndexLookupRequest someInvertedIndexLookupRequest;
private UrlFactory urlFactory;
private PortfolioUrlLibrary library;
@Before
public void setUpUrlGeneration() {
urlFactory = mock(UrlFactory.class);
library = new PortfolioUrlLibrary(urlFactory);
}
@Before
public void mockParameterGroups() {
someUsageActivity = mock(UsageActivity.class);
when(someUsageActivity.getParameters()).thenReturn(SOME_PARAMETER_GROUP.getParameters());
someLegalInfo = mock(LegalInformation.class);
when(someLegalInfo.getParameters()).thenReturn(SOME_PARAMETER_GROUP.getParameters());
someBounds = mock(Bounds.class);
when(someBounds.getParameters()).thenReturn(SOME_PARAMETER_GROUP.getParameters());
someInvertedIndexLookupRequest = mock(InvertedIndexLookupRequest.class);
when(someInvertedIndexLookupRequest.getSelectorId()).thenReturn(SOME_DATA_TYPE_ID);
when(someInvertedIndexLookupRequest.getGroups()).thenReturn(SOME_PARAMETER_GROUPS);
}
@Test
public void shouldHaveSchemaUrl() {
when(urlFactory.buildUrl(eq(HBASE_INDEXING_SERVICE), eq(SCHEMA))).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.schema());
}
@Test
public void shouldHaveEntitySamplesUrl() {
final ContextPathSection endpoint = asContextPath(ENTITIES_PATH, SOME_DATA_TYPE, SAMPLES_PATH);
when(urlFactory.buildUrl(eq(HBASE_INDEXING_SERVICE), argThat(matches(endpoint)), (ParameterGroup) any())).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.entities().samples(SOME_DATA_TYPE, SOME_INTEGER));
}
@Test
public void shouldHaveEntitySamplesParameterAmount() {
library.entities().samples(SOME_DATA_TYPE, SOME_INTEGER);
verify(urlFactory).buildUrl(any(), any(), argThat(matches(SOME_INTEGER)));
}
@Test
public void shouldHaveEntityLookupUrl() {
final ContextPathSection endpoint = asContextPath(ENTITIES_PATH, SOME_DATA_TYPE, SOME_UID);
when(urlFactory.buildUrl(eq(HBASE_INDEXING_SERVICE), argThat(matches(endpoint)))).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.entities().lookup(SOME_DATA_TYPE_ID));
}
@Test
public void shouldHaveEntityRenderAsTextUrl() {
final ContextPathSection endpoint = asContextPath(RENDER_ENTITY_ROOT_PATH, SOME_DATA_TYPE, SOME_UID, AS_TEXT_PATH);
when(urlFactory.buildUrl(eq(RENDER_SERVICE), argThat(matches(endpoint)))).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.entities().render().text(SOME_DATA_TYPE_ID));
}
@Test
public void shouldHaveEntityRenderAsHtmlUrl() {
final ContextPathSection endpoint = asContextPath(RENDER_ENTITY_ROOT_PATH, SOME_DATA_TYPE, SOME_UID, AS_HTML_PATH);
when(urlFactory.buildUrl(eq(RENDER_SERVICE), argThat(matches(endpoint)))).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.entities().render().html(SOME_DATA_TYPE_ID));
}
@Test
public void shouldHaveDocumentSamplesUrl() {
final ContextPathSection endpoint = asContextPath(DOCUMENTS_PATH, SOME_DATA_TYPE, SAMPLES_PATH);
when(urlFactory.buildUrl(eq(HBASE_INDEXING_SERVICE), argThat(matches(endpoint)), (ParameterGroup) any())).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.documents().samples(SOME_DATA_TYPE, SOME_INTEGER));
}
@Test
public void shouldHaveDocumentSamplesParameterAmount() {
library.documents().samples(SOME_DATA_TYPE, SOME_INTEGER);
verify(urlFactory).buildUrl(any(), any(), argThat(matches(SOME_INTEGER)));
}
@Test
public void shouldHaveDocumentLookupUrl() {
final ContextPathSection endpoint = asContextPath(DOCUMENTS_PATH, SOME_DATA_TYPE, SOME_UID);
when(urlFactory.buildUrl(eq(HBASE_INDEXING_SERVICE), argThat(matches(endpoint)))).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.documents().lookup(SOME_DATA_TYPE_ID));
}
@Test
public void shouldHaveDocumentReferencesUrl() {
final ContextPathSection endpoint = asContextPath(DOCUMENTS_PATH, SOME_DATA_TYPE, SOME_UID, REFERENCES_PATH);
when(urlFactory.buildUrl(eq(HBASE_INDEXING_SERVICE), argThat(matches(endpoint)))).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.documents().references(SOME_DATA_TYPE_ID));
}
@Test
public void shouldHaveDocumentGetUsageActivitiesUrl() {
final ContextPathSection endpoint = asContextPath(USAGE_ACTIVITIES_ROOT_PATH, SOME_DATA_TYPE, SOME_UID, USAGE_ACTIVITIES_PATH);
when(urlFactory.buildUrl(eq(USAGE_DATA_SERVICE), argThat(matches(endpoint)))).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.documents().usageActivities(SOME_DATA_TYPE_ID));
}
@Test
public void shouldHaveDocumentGetUsageActivitiesUrlWithBounds() {
final ContextPathSection endpoint = asContextPath(USAGE_ACTIVITIES_ROOT_PATH, SOME_DATA_TYPE, SOME_UID, USAGE_ACTIVITIES_PATH);
when(urlFactory.buildUrl(eq(USAGE_DATA_SERVICE), argThat(matches(endpoint)), (Bounds) any())).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.documents().usageActivities(SOME_DATA_TYPE_ID, someBounds));
}
@Test
public void shouldHaveDocumentPostUsageActivitiesUrl() {
final ContextPathSection endpoint = asContextPath(USAGE_ACTIVITIES_ROOT_PATH, SOME_DATA_TYPE, SOME_UID, USAGE_ACTIVITIES_PATH);
when(urlFactory.buildUrl(eq(USAGE_DATA_SERVICE), argThat(matches(endpoint)), (UsageActivity) any())).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.documents().usageActivities(SOME_DATA_TYPE_ID, someUsageActivity));
}
@Test
public void shouldHaveDocumentGetUsageActivitiesParameterBounds() {
library.documents().usageActivities(SOME_DATA_TYPE_ID, someBounds);
verify(urlFactory).buildUrl(any(), any(), argThat(matches(someBounds)));
}
@Test
public void shouldHaveDocumentPostUsageActivitiesParameterUsageActivity() {
library.documents().usageActivities(SOME_DATA_TYPE_ID, someUsageActivity);
verify(urlFactory).buildUrl(any(), any(), argThat(matches(someUsageActivity)));
}
@Test
public void shouldHaveDocumentRenderAsTextUrl() {
final ContextPathSection endpoint = asContextPath(RENDER_ENTITY_ROOT_PATH, SOME_DATA_TYPE, SOME_UID, AS_TEXT_PATH);
when(urlFactory.buildUrl(eq(RENDER_SERVICE), argThat(matches(endpoint)))).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.documents().render().text(SOME_DATA_TYPE_ID));
}
@Test
public void shouldHaveDocumentRenderAsHtmlUrl() {
final ContextPathSection endpoint = asContextPath(RENDER_ENTITY_ROOT_PATH, SOME_DATA_TYPE, SOME_UID, AS_HTML_PATH);
when(urlFactory.buildUrl(eq(RENDER_SERVICE), argThat(matches(endpoint)))).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.documents().render().html(SOME_DATA_TYPE_ID));
}
@Test
public void shouldHaveSelectorSamplesUrl() {
final ContextPathSection endpoint = asContextPath(SELECTORS_PATH, SOME_DATA_TYPE, SAMPLES_PATH);
when(urlFactory.buildUrl(eq(HBASE_INDEXING_SERVICE), argThat(matches(endpoint)), (ParameterGroup) any())).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.selectors().samples(SOME_DATA_TYPE, SOME_INTEGER));
}
@Test
public void shouldHaveSelectorSamplesParameterAmount() {
library.selectors().samples(SOME_DATA_TYPE, SOME_INTEGER);
verify(urlFactory).buildUrl(any(), any(), argThat(matches(SOME_INTEGER)));
}
@Test
public void shouldHaveSelectorSuggestionsUrl() {
final ContextPathSection endpoint = asContextPath(SELECTORS_PATH, SUGGESTIONS_PATH, SOME_SIMPLE_REPRESENTATION + "/");
when(urlFactory.buildUrl(eq(HBASE_INDEXING_SERVICE), argThat(matches(endpoint)))).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.selectors().suggestions(SOME_SIMPLE_REPRESENTATION));
}
@Test
public void shouldHaveSelectorLookupUrl() {
final ContextPathSection endpoint = asContextPath(SELECTORS_PATH, SOME_DATA_TYPE, SOME_UID);
when(urlFactory.buildUrl(eq(HBASE_INDEXING_SERVICE), argThat(matches(endpoint)))).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.selectors().lookup(SOME_DATA_TYPE_ID));
}
@Test
public void shouldHaveSelectorFromSimpleRepresentationUrl() {
final ContextPathSection endpoint = asContextPath(SELECTORS_PATH, SOME_DATA_TYPE, FROM_SIMPLE_REP_PATH, SOME_SIMPLE_REPRESENTATION + "/");
when(urlFactory.buildUrl(eq(HBASE_INDEXING_SERVICE), argThat(matches(endpoint)))).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.selectors().fromSimpleRepresentation(SOME_DATA_TYPE, SOME_SIMPLE_REPRESENTATION));
}
@Test
public void shouldHaveSelectorInvertedIndexLookupUrl() {
final ContextPathSection endpoint = asContextPath(SELECTORS_PATH, SOME_DATA_TYPE, SOME_UID, INVERTED_INDEX_PATH);
when(urlFactory.buildUrl(eq(HBASE_INDEXING_SERVICE), argThat(matches(endpoint)))).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.selectors().invertedIndex(SOME_DATA_TYPE_ID));
}
@Test
public void shouldHaveSelectorInvertedIndexLookupUrlWithParameter() {
final ContextPathSection endpoint = asContextPath(SELECTORS_PATH, SOME_DATA_TYPE, SOME_UID, INVERTED_INDEX_PATH);
when(urlFactory.buildUrl(eq(HBASE_INDEXING_SERVICE), argThat(matches(endpoint)), (ParameterGroup[]) any())).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.selectors().invertedIndex(someInvertedIndexLookupRequest));
}
@Test
public void shouldHaveSelectorInvertedIndexLookupUrlWithParameterInvertedIndexRequest() {
library.selectors().invertedIndex(someInvertedIndexLookupRequest);
verify(urlFactory).buildUrl(any(), any(), argThat(matches(SOME_PARAMETER_GROUP)));
}
@Test
public void shouldHaveSelectorKnowledgeUrl() {
final ContextPathSection endpoint = asContextPath(LOOKUP_KNOWLEDGE_ROOT_PATH, SOME_DATA_TYPE, SOME_UID, LOOKUP_KNOWLEDGE_PATH);
when(urlFactory.buildUrl(eq(ANALYTICS_SERVICE), argThat(matches(endpoint)))).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.selectors().knowledge(SOME_DATA_TYPE_ID));
}
@Test
public void shouldHaveSelectorStatisticsUrl() {
final ContextPathSection endpoint = asContextPath(SELECTORS_PATH, SOME_DATA_TYPE, SOME_UID, STATISTICS_PATH);
when(urlFactory.buildUrl(eq(HBASE_INDEXING_SERVICE), argThat(matches(endpoint)))).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.selectors().statistics(SOME_DATA_TYPE_ID));
}
@Test
public void shouldHaveSelectorRenderAsTextUrl() {
final ContextPathSection endpoint = asContextPath(RENDER_ENTITY_ROOT_PATH, SOME_DATA_TYPE, SOME_UID, AS_TEXT_PATH);
when(urlFactory.buildUrl(eq(RENDER_SERVICE), argThat(matches(endpoint)))).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.selectors().render().text(SOME_DATA_TYPE_ID));
}
@Test
public void shouldHaveSelectorRenderAsSimpleRepresentationUrl() {
final ContextPathSection endpoint = asContextPath(RENDER_SELECTOR_ROOT_PATH, SOME_DATA_TYPE, SOME_UID, AS_SIMPLE_REPRESENTATION_PATH);
when(urlFactory.buildUrl(eq(RENDER_SERVICE), argThat(matches(endpoint)))).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.selectors().render().simpleRepresentation(SOME_DATA_TYPE_ID));
}
@Test
public void shouldHaveSelectorRenderAsHtmlUrl() {
final ContextPathSection endpoint = asContextPath(RENDER_ENTITY_ROOT_PATH, SOME_DATA_TYPE, SOME_UID, AS_HTML_PATH);
when(urlFactory.buildUrl(eq(RENDER_SERVICE), argThat(matches(endpoint)))).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.selectors().render().html(SOME_DATA_TYPE_ID));
}
@Test
public void shouldHaveAuditCheckInvertedIndexUrl() {
final ContextPathSection endpoint = asContextPath(LEGAL_ROOT_PATH, SOME_DATA_TYPE, SOME_UID, LegalServiceGlobals.INVERTED_INDEX_PATH, LEGAL_RULES_PATH);
when(urlFactory.buildUrl(eq(LEGAL_SERVICE), argThat(matches(endpoint)), (LegalInformation) any())).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.selectors().audit().check().invertedIndex(SOME_DATA_TYPE_ID, someLegalInfo));
}
@Test
public void shouldHaveAuditCheckInvertedIndexUrlWithParameterLegalInfo() {
library.selectors().audit().check().invertedIndex(SOME_DATA_TYPE_ID, someLegalInfo);
verify(urlFactory).buildUrl(any(), any(), argThat(matches(SOME_PARAMETER_GROUP)));
}
@Test
public void shouldHaveAuditCheckStatisticsUrl() {
final ContextPathSection endpoint = asContextPath(LEGAL_ROOT_PATH, SOME_DATA_TYPE, SOME_UID, LegalServiceGlobals.STATISTICS_PATH, LEGAL_RULES_PATH);
when(urlFactory.buildUrl(eq(LEGAL_SERVICE), argThat(matches(endpoint)), (LegalInformation) any())).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.selectors().audit().check().statistics(SOME_DATA_TYPE_ID, someLegalInfo));
}
@Test
public void shouldHaveAuditCheckStatisticsUrlWithParameterLegalInfo() {
library.selectors().audit().check().statistics(SOME_DATA_TYPE_ID, someLegalInfo);
verify(urlFactory).buildUrl(any(), any(), argThat(matches(SOME_PARAMETER_GROUP)));
}
@Test
public void shouldHaveAuditLogInvertedIndexUrl() {
final ContextPathSection endpoint = asContextPath(LEGAL_ROOT_PATH, SOME_DATA_TYPE, SOME_UID, LegalServiceGlobals.INVERTED_INDEX_PATH,
AUDIT_LOGGING_PATH);
when(urlFactory.buildUrl(eq(LEGAL_SERVICE), argThat(matches(endpoint)), (LegalInformation) any())).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.selectors().audit().log().invertedIndex(SOME_DATA_TYPE_ID, someLegalInfo));
}
@Test
public void shouldHaveAuditLogInvertedIndexUrlWithParameterLegalInfo() {
library.selectors().audit().log().invertedIndex(SOME_DATA_TYPE_ID, someLegalInfo);
verify(urlFactory).buildUrl(any(), any(), argThat(matches(SOME_PARAMETER_GROUP)));
}
@Test
public void shouldHaveAuditLogStatisticsUrl() {
final ContextPathSection endpoint = asContextPath(LEGAL_ROOT_PATH, SOME_DATA_TYPE, SOME_UID, LegalServiceGlobals.STATISTICS_PATH, AUDIT_LOGGING_PATH);
when(urlFactory.buildUrl(eq(LEGAL_SERVICE), argThat(matches(endpoint)), (LegalInformation) any())).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.selectors().audit().log().statistics(SOME_DATA_TYPE_ID, someLegalInfo));
}
@Test
public void shouldHaveAuditLogStatisticsUrlWithParameterLegalInfo() {
library.selectors().audit().log().statistics(SOME_DATA_TYPE_ID, someLegalInfo);
verify(urlFactory).buildUrl(any(), any(), argThat(matches(SOME_PARAMETER_GROUP)));
}
@Test
public void shouldHaveLegalHistoryUrl() {
final ContextPathSection endpoint = asContextPath(LEGAL_ROOT_PATH, HISTORY_PATH);
when(urlFactory.buildUrl(eq(LEGAL_SERVICE), argThat(matches(endpoint)))).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.selectors().history().all());
}
@Test
public void shouldHaveLegalHistoryForItemUrl() {
final ContextPathSection endpoint = asContextPath(LEGAL_ROOT_PATH, HISTORY_PATH, "" + SOME_INTEGER + "/");
when(urlFactory.buildUrl(eq(LEGAL_SERVICE), argThat(matches(endpoint)))).thenReturn(SOME_URL_STRING);
assertEquals(SOME_URL_STRING, library.selectors().history().item(SOME_INTEGER));
}
private ContextPathSection asContextPath(String... elements) {
return () -> ("/" + stream(elements).collect(joining("/"))).replaceAll("//", "/");
}
private ArgumentMatcher<ContextPathSection> matches(ContextPathSection endpoint) {
return actualEndpoint -> endpoint.getContextPath().equals(actualEndpoint.getContextPath());
}
private ArgumentMatcher<ParameterGroup> matches(Integer value) {
return group -> group.getParameters()[0].getValue().equals(value);
}
private ArgumentMatcher<ParameterGroup> matches(ParameterGroup value) {
return group -> {
final Parameter[] left = group.getParameters();
final Parameter[] right = value.getParameters();
if (left.length != right.length) {
return false;
}
for (int i = 0; i < left.length; i++) {
if (!(namesAreEqual(left[i], right[i]) && valuesAreEqual(left[i], right[i]))) {
return false;
}
}
return true;
};
}
private boolean namesAreEqual(Parameter currentLeft, Parameter currentRight) {
return currentLeft.getName().equals(currentRight.getName());
}
private boolean valuesAreEqual(Parameter currentLeft, Parameter currentRight) {
return currentLeft.getValue().equals(currentRight.getValue());
}
}
| 20,838 | 0.775986 | 0.775794 | 397 | 50.488667 | 43.724728 | 154 | false | false | 0 | 0 | 0 | 0 | 73 | 0.003503 | 2.123426 | false | false | 3 |
e3671d94fc5c1014d660dc923685e049cac503c4 | 9,646,496,608,584 | 124df74bce796598d224c4380c60c8e95756f761 | /com.raytheon.uf.edex.decodertools/src/com/raytheon/uf/edex/decodertools/bufr/BUFRSearchContext.java | 1d73706a0dc89bdf450df5452ffad9695b2e84c2 | [] | no_license | Mapoet/AWIPS-Test | https://github.com/Mapoet/AWIPS-Test | 19059bbd401573950995c8cc442ddd45588e6c9f | 43c5a7cc360b3cbec2ae94cb58594fe247253621 | refs/heads/master | 2020-04-17T03:35:57.762000 | 2017-02-06T17:17:58 | 2017-02-06T17:17:58 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.edex.decodertools.bufr;
import java.util.List;
import com.raytheon.uf.edex.decodertools.bufr.descriptors.BUFRDescriptor;
import com.raytheon.uf.edex.decodertools.bufr.packets.IBUFRDataPacket;
/**
* TODO Add Description
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
*
*
* </pre>
*
* @author jkorman
* @version 1.0
*/
public class BUFRSearchContext {
private List<IBUFRDataPacket> targetDocument = null;
private int currPos = -1;
// private boolean isValid = false;
private IBUFRDataPacket currFindData = null;
private int descriptorTarget = -1;
public BUFRSearchContext(List<IBUFRDataPacket> document, int descriptor) {
if (document != null) {
targetDocument = document;
currPos = 0;
descriptorTarget = descriptor;
// isValid = true;
}
}
public BUFRSearchContext(List<IBUFRDataPacket> document, int f, int x, int y) {
this(document, BUFRDescriptor.createDescriptor(f, x, y));
}
/**
* Get the last found data packet.
*
* @return
*/
public IBUFRDataPacket get() {
return currFindData;
}
/**
* Searches the current packet list to find a packet that has a specified
* descriptor reference. The search begins at the current location.
*
* @return Was the find successful?
*/
public boolean find() {
boolean found = false;
// clear the last found data.
currFindData = null;
while (!found && (currPos < targetDocument.size())) {
IBUFRDataPacket packet = targetDocument.get(currPos);
if ((packet != null) && (packet.getReferencingDescriptor() != null)) {
if (packet.getReferencingDescriptor().getDescriptor() == descriptorTarget) {
currFindData = packet;
found = true;
}
}
if (!found) {
currPos++;
}
}
return found;
}
}
| UTF-8 | Java | 2,929 | java | BUFRSearchContext.java | Java | [
{
"context": "----------------\n * \t\n * \n * </pre>\n * \n * @author jkorman\n * @version 1.0\n */\n\npublic class BUFRSearchConte",
"end": 1220,
"score": 0.9994128346443176,
"start": 1213,
"tag": "USERNAME",
"value": "jkorman"
}
] | null | [] | /**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.edex.decodertools.bufr;
import java.util.List;
import com.raytheon.uf.edex.decodertools.bufr.descriptors.BUFRDescriptor;
import com.raytheon.uf.edex.decodertools.bufr.packets.IBUFRDataPacket;
/**
* TODO Add Description
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
*
*
* </pre>
*
* @author jkorman
* @version 1.0
*/
public class BUFRSearchContext {
private List<IBUFRDataPacket> targetDocument = null;
private int currPos = -1;
// private boolean isValid = false;
private IBUFRDataPacket currFindData = null;
private int descriptorTarget = -1;
public BUFRSearchContext(List<IBUFRDataPacket> document, int descriptor) {
if (document != null) {
targetDocument = document;
currPos = 0;
descriptorTarget = descriptor;
// isValid = true;
}
}
public BUFRSearchContext(List<IBUFRDataPacket> document, int f, int x, int y) {
this(document, BUFRDescriptor.createDescriptor(f, x, y));
}
/**
* Get the last found data packet.
*
* @return
*/
public IBUFRDataPacket get() {
return currFindData;
}
/**
* Searches the current packet list to find a packet that has a specified
* descriptor reference. The search begins at the current location.
*
* @return Was the find successful?
*/
public boolean find() {
boolean found = false;
// clear the last found data.
currFindData = null;
while (!found && (currPos < targetDocument.size())) {
IBUFRDataPacket packet = targetDocument.get(currPos);
if ((packet != null) && (packet.getReferencingDescriptor() != null)) {
if (packet.getReferencingDescriptor().getDescriptor() == descriptorTarget) {
currFindData = packet;
found = true;
}
}
if (!found) {
currPos++;
}
}
return found;
}
}
| 2,929 | 0.593035 | 0.580403 | 103 | 27.436893 | 25.560007 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.320388 | false | false | 3 |
673ae2c1bb0a6ab09fb9d4328c9a5aabf4f390e7 | 17,179,921,901 | 8a98577c5995449677ede2cbe1cc408c324efacc | /Big_Clone_Bench_files_used/bcb_reduced/3/selected/2478325.java | d8067c1c21d61fdfd31eb7fa161c13e46b126027 | [
"MIT"
] | permissive | pombredanne/lsh-for-source-code | https://github.com/pombredanne/lsh-for-source-code | 9363cc0c9a8ddf16550ae4764859fa60186351dd | fac9adfbd98a4d73122a8fc1a0e0cc4f45e9dcd4 | refs/heads/master | 2020-08-05T02:28:55.370000 | 2017-10-18T23:57:08 | 2017-10-18T23:57:08 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package be.fedict.eid.applet.service.signer.time;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.security.Security;
import java.security.cert.CertStore;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.security.auth.x500.X500Principal;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1OctetString;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.cmp.PKIFailureInfo;
import org.bouncycastle.asn1.x509.AuthorityKeyIdentifier;
import org.bouncycastle.asn1.x509.SubjectKeyIdentifier;
import org.bouncycastle.asn1.x509.X509Extensions;
import org.bouncycastle.cms.SignerId;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.tsp.TSPAlgorithms;
import org.bouncycastle.tsp.TimeStampRequest;
import org.bouncycastle.tsp.TimeStampRequestGenerator;
import org.bouncycastle.tsp.TimeStampResponse;
import org.bouncycastle.tsp.TimeStampToken;
import be.fedict.eid.applet.service.signer.facets.RevocationData;
/**
* A TSP time-stamp service implementation.
*
* @author Frank Cornelis
*
*/
public class TSPTimeStampService implements TimeStampService {
private static final Log LOG = LogFactory.getLog(TSPTimeStampService.class);
static {
if (null == Security.getProvider(BouncyCastleProvider.PROVIDER_NAME)) {
Security.addProvider(new BouncyCastleProvider());
}
}
public static final String DEFAULT_USER_AGENT = "eID Applet Service TSP Client";
private final String tspServiceUrl;
private String requestPolicy;
private final String userAgent;
private final TimeStampServiceValidator validator;
private String username;
private String password;
private String proxyHost;
private int proxyPort;
private String digestAlgo;
private String digestAlgoOid;
public TSPTimeStampService(String tspServiceUrl, TimeStampServiceValidator validator) {
this(tspServiceUrl, validator, null, null);
}
/**
* Main constructor.
*
* @param tspServiceUrl
* the URL of the TSP service.
* @param validator
* the trust validator used to validate incoming TSP response
* signatures.
* @param requestPolicy
* the optional TSP request policy.
* @param userAgent
* the optional User-Agent TSP request header value.
*/
public TSPTimeStampService(String tspServiceUrl, TimeStampServiceValidator validator, String requestPolicy, String userAgent) {
if (null == tspServiceUrl) {
throw new IllegalArgumentException("TSP service URL required");
}
this.tspServiceUrl = tspServiceUrl;
if (null == validator) {
throw new IllegalArgumentException("TSP validator required");
}
this.validator = validator;
this.requestPolicy = requestPolicy;
if (null != userAgent) {
this.userAgent = userAgent;
} else {
this.userAgent = DEFAULT_USER_AGENT;
}
this.digestAlgo = "SHA-1";
this.digestAlgoOid = TSPAlgorithms.SHA1;
}
/**
* Sets the request policy OID.
*
* @param policyOid
*/
public void setRequestPolicy(String policyOid) {
this.requestPolicy = policyOid;
}
/**
* Sets the credentials used in case the TSP service requires
* authentication.
*
* @param username
* @param password
*/
public void setAuthenticationCredentials(String username, String password) {
this.username = username;
this.password = password;
}
/**
* Resets the authentication credentials.
*/
public void resetAuthenticationCredentials() {
this.username = null;
this.password = null;
}
/**
* Sets the digest algorithm used for time-stamping data. Example value:
* "SHA-1".
*
* @param digestAlgo
*/
public void setDigestAlgo(String digestAlgo) {
if ("SHA-1".equals(digestAlgo)) {
this.digestAlgoOid = TSPAlgorithms.SHA1;
} else if ("SHA-256".equals(digestAlgo)) {
this.digestAlgoOid = TSPAlgorithms.SHA256;
} else if ("SHA-384".equals(digestAlgo)) {
this.digestAlgoOid = TSPAlgorithms.SHA384;
} else if ("SHA-512".equals(digestAlgo)) {
this.digestAlgoOid = TSPAlgorithms.SHA512;
} else {
throw new IllegalArgumentException("unsupported digest algo: " + digestAlgo);
}
this.digestAlgo = digestAlgo;
}
/**
* Configures the HTTP proxy settings to be used to connect to the TSP
* service.
*
* @param proxyHost
* @param proxyPort
*/
public void setProxy(String proxyHost, int proxyPort) {
this.proxyHost = proxyHost;
this.proxyPort = proxyPort;
}
/**
* Resets the HTTP proxy settings.
*/
public void resetProxy() {
this.proxyHost = null;
this.proxyPort = 0;
}
public byte[] timeStamp(byte[] data, RevocationData revocationData) throws Exception {
MessageDigest messageDigest = MessageDigest.getInstance(this.digestAlgo);
byte[] digest = messageDigest.digest(data);
BigInteger nonce = new BigInteger(128, new SecureRandom());
TimeStampRequestGenerator requestGenerator = new TimeStampRequestGenerator();
requestGenerator.setCertReq(true);
if (null != this.requestPolicy) {
requestGenerator.setReqPolicy(this.requestPolicy);
}
TimeStampRequest request = requestGenerator.generate(this.digestAlgoOid, digest, nonce);
byte[] encodedRequest = request.getEncoded();
HttpClient httpClient = new HttpClient();
if (null != this.username) {
Credentials credentials = new UsernamePasswordCredentials(this.username, this.password);
httpClient.getState().setCredentials(AuthScope.ANY, credentials);
}
if (null != this.proxyHost) {
httpClient.getHostConfiguration().setProxy(this.proxyHost, this.proxyPort);
}
PostMethod postMethod = new PostMethod(this.tspServiceUrl);
RequestEntity requestEntity = new ByteArrayRequestEntity(encodedRequest, "application/timestamp-query");
postMethod.addRequestHeader("User-Agent", this.userAgent);
postMethod.setRequestEntity(requestEntity);
int statusCode = httpClient.executeMethod(postMethod);
if (HttpStatus.SC_OK != statusCode) {
LOG.error("Error contacting TSP server " + this.tspServiceUrl);
throw new Exception("Error contacting TSP server " + this.tspServiceUrl);
}
Header responseContentTypeHeader = postMethod.getResponseHeader("Content-Type");
if (null == responseContentTypeHeader) {
throw new RuntimeException("missing Content-Type header");
}
String contentType = responseContentTypeHeader.getValue();
if (!contentType.startsWith("application/timestamp-reply")) {
LOG.debug("response content: " + postMethod.getResponseBodyAsString());
throw new RuntimeException("invalid Content-Type: " + contentType);
}
if (0 == postMethod.getResponseContentLength()) {
throw new RuntimeException("Content-Length is zero");
}
InputStream inputStream = postMethod.getResponseBodyAsStream();
TimeStampResponse timeStampResponse = new TimeStampResponse(inputStream);
timeStampResponse.validate(request);
if (0 != timeStampResponse.getStatus()) {
LOG.debug("status: " + timeStampResponse.getStatus());
LOG.debug("status string: " + timeStampResponse.getStatusString());
PKIFailureInfo failInfo = timeStampResponse.getFailInfo();
if (null != failInfo) {
LOG.debug("fail info int value: " + failInfo.intValue());
if (PKIFailureInfo.unacceptedPolicy == failInfo.intValue()) {
LOG.debug("unaccepted policy");
}
}
throw new RuntimeException("timestamp response status != 0: " + timeStampResponse.getStatus());
}
TimeStampToken timeStampToken = timeStampResponse.getTimeStampToken();
SignerId signerId = timeStampToken.getSID();
BigInteger signerCertSerialNumber = signerId.getSerialNumber();
X500Principal signerCertIssuer = signerId.getIssuer();
LOG.debug("signer cert serial number: " + signerCertSerialNumber);
LOG.debug("signer cert issuer: " + signerCertIssuer);
CertStore certStore = timeStampToken.getCertificatesAndCRLs("Collection", BouncyCastleProvider.PROVIDER_NAME);
Collection<? extends Certificate> certificates = certStore.getCertificates(null);
X509Certificate signerCert = null;
Map<String, X509Certificate> certificateMap = new HashMap<String, X509Certificate>();
for (Certificate certificate : certificates) {
X509Certificate x509Certificate = (X509Certificate) certificate;
if (signerCertIssuer.equals(x509Certificate.getIssuerX500Principal()) && signerCertSerialNumber.equals(x509Certificate.getSerialNumber())) {
signerCert = x509Certificate;
}
String ski = Hex.encodeHexString(getSubjectKeyId(x509Certificate));
certificateMap.put(ski, x509Certificate);
LOG.debug("embedded certificate: " + x509Certificate.getSubjectX500Principal() + "; SKI=" + ski);
}
if (null == signerCert) {
throw new RuntimeException("TSP response token has no signer certificate");
}
List<X509Certificate> tspCertificateChain = new LinkedList<X509Certificate>();
X509Certificate certificate = signerCert;
do {
LOG.debug("adding to certificate chain: " + certificate.getSubjectX500Principal());
tspCertificateChain.add(certificate);
if (certificate.getSubjectX500Principal().equals(certificate.getIssuerX500Principal())) {
break;
}
String aki = Hex.encodeHexString(getAuthorityKeyId(certificate));
certificate = certificateMap.get(aki);
} while (null != certificate);
timeStampToken.validate(tspCertificateChain.get(0), BouncyCastleProvider.PROVIDER_NAME);
this.validator.validate(tspCertificateChain, revocationData);
LOG.debug("time-stamp token time: " + timeStampToken.getTimeStampInfo().getGenTime());
byte[] timestamp = timeStampToken.getEncoded();
return timestamp;
}
private byte[] getSubjectKeyId(X509Certificate cert) throws IOException {
byte[] extvalue = cert.getExtensionValue(X509Extensions.SubjectKeyIdentifier.getId());
if (extvalue == null) {
return null;
}
ASN1OctetString str = ASN1OctetString.getInstance(new ASN1InputStream(new ByteArrayInputStream(extvalue)).readObject());
SubjectKeyIdentifier keyId = SubjectKeyIdentifier.getInstance(new ASN1InputStream(new ByteArrayInputStream(str.getOctets())).readObject());
return keyId.getKeyIdentifier();
}
private byte[] getAuthorityKeyId(X509Certificate cert) throws IOException {
byte[] extvalue = cert.getExtensionValue(X509Extensions.AuthorityKeyIdentifier.getId());
if (extvalue == null) {
return null;
}
DEROctetString oct = (DEROctetString) (new ASN1InputStream(new ByteArrayInputStream(extvalue)).readObject());
AuthorityKeyIdentifier keyId = new AuthorityKeyIdentifier((ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(oct.getOctets())).readObject());
return keyId.getKeyIdentifier();
}
}
| UTF-8 | Java | 12,708 | java | 2478325.java | Java | [
{
"context": " time-stamp service implementation.\n * \n * @author Frank Cornelis\n * \n */\npublic class TSPTimeStampService implemen",
"end": 2066,
"score": 0.9998533129692078,
"start": 2052,
"tag": "NAME",
"value": "Frank Cornelis"
},
{
"context": "ername, String password) {\n this.username = username;\n this.password = password;\n }\n\n /**",
"end": 4536,
"score": 0.9969775080680847,
"start": 4528,
"tag": "USERNAME",
"value": "username"
},
{
"context": " this.username = username;\n this.password = password;\n }\n\n /**\n\t * Resets the authentication cre",
"end": 4570,
"score": 0.9955995082855225,
"start": 4562,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "henticationCredentials() {\n this.username = null;\n this.password = null;\n }\n\n /**\n\t *",
"end": 4714,
"score": 0.9329684972763062,
"start": 4710,
"tag": "USERNAME",
"value": "null"
},
{
"context": " this.username = null;\n this.password = null;\n }\n\n /**\n\t * Sets the digest algorithm use",
"end": 4744,
"score": 0.9985461235046387,
"start": 4740,
"tag": "PASSWORD",
"value": "null"
}
] | null | [] | package be.fedict.eid.applet.service.signer.time;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.security.Security;
import java.security.cert.CertStore;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.security.auth.x500.X500Principal;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1OctetString;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.cmp.PKIFailureInfo;
import org.bouncycastle.asn1.x509.AuthorityKeyIdentifier;
import org.bouncycastle.asn1.x509.SubjectKeyIdentifier;
import org.bouncycastle.asn1.x509.X509Extensions;
import org.bouncycastle.cms.SignerId;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.tsp.TSPAlgorithms;
import org.bouncycastle.tsp.TimeStampRequest;
import org.bouncycastle.tsp.TimeStampRequestGenerator;
import org.bouncycastle.tsp.TimeStampResponse;
import org.bouncycastle.tsp.TimeStampToken;
import be.fedict.eid.applet.service.signer.facets.RevocationData;
/**
* A TSP time-stamp service implementation.
*
* @author <NAME>
*
*/
public class TSPTimeStampService implements TimeStampService {
private static final Log LOG = LogFactory.getLog(TSPTimeStampService.class);
static {
if (null == Security.getProvider(BouncyCastleProvider.PROVIDER_NAME)) {
Security.addProvider(new BouncyCastleProvider());
}
}
public static final String DEFAULT_USER_AGENT = "eID Applet Service TSP Client";
private final String tspServiceUrl;
private String requestPolicy;
private final String userAgent;
private final TimeStampServiceValidator validator;
private String username;
private String password;
private String proxyHost;
private int proxyPort;
private String digestAlgo;
private String digestAlgoOid;
public TSPTimeStampService(String tspServiceUrl, TimeStampServiceValidator validator) {
this(tspServiceUrl, validator, null, null);
}
/**
* Main constructor.
*
* @param tspServiceUrl
* the URL of the TSP service.
* @param validator
* the trust validator used to validate incoming TSP response
* signatures.
* @param requestPolicy
* the optional TSP request policy.
* @param userAgent
* the optional User-Agent TSP request header value.
*/
public TSPTimeStampService(String tspServiceUrl, TimeStampServiceValidator validator, String requestPolicy, String userAgent) {
if (null == tspServiceUrl) {
throw new IllegalArgumentException("TSP service URL required");
}
this.tspServiceUrl = tspServiceUrl;
if (null == validator) {
throw new IllegalArgumentException("TSP validator required");
}
this.validator = validator;
this.requestPolicy = requestPolicy;
if (null != userAgent) {
this.userAgent = userAgent;
} else {
this.userAgent = DEFAULT_USER_AGENT;
}
this.digestAlgo = "SHA-1";
this.digestAlgoOid = TSPAlgorithms.SHA1;
}
/**
* Sets the request policy OID.
*
* @param policyOid
*/
public void setRequestPolicy(String policyOid) {
this.requestPolicy = policyOid;
}
/**
* Sets the credentials used in case the TSP service requires
* authentication.
*
* @param username
* @param password
*/
public void setAuthenticationCredentials(String username, String password) {
this.username = username;
this.password = <PASSWORD>;
}
/**
* Resets the authentication credentials.
*/
public void resetAuthenticationCredentials() {
this.username = null;
this.password = <PASSWORD>;
}
/**
* Sets the digest algorithm used for time-stamping data. Example value:
* "SHA-1".
*
* @param digestAlgo
*/
public void setDigestAlgo(String digestAlgo) {
if ("SHA-1".equals(digestAlgo)) {
this.digestAlgoOid = TSPAlgorithms.SHA1;
} else if ("SHA-256".equals(digestAlgo)) {
this.digestAlgoOid = TSPAlgorithms.SHA256;
} else if ("SHA-384".equals(digestAlgo)) {
this.digestAlgoOid = TSPAlgorithms.SHA384;
} else if ("SHA-512".equals(digestAlgo)) {
this.digestAlgoOid = TSPAlgorithms.SHA512;
} else {
throw new IllegalArgumentException("unsupported digest algo: " + digestAlgo);
}
this.digestAlgo = digestAlgo;
}
/**
* Configures the HTTP proxy settings to be used to connect to the TSP
* service.
*
* @param proxyHost
* @param proxyPort
*/
public void setProxy(String proxyHost, int proxyPort) {
this.proxyHost = proxyHost;
this.proxyPort = proxyPort;
}
/**
* Resets the HTTP proxy settings.
*/
public void resetProxy() {
this.proxyHost = null;
this.proxyPort = 0;
}
public byte[] timeStamp(byte[] data, RevocationData revocationData) throws Exception {
MessageDigest messageDigest = MessageDigest.getInstance(this.digestAlgo);
byte[] digest = messageDigest.digest(data);
BigInteger nonce = new BigInteger(128, new SecureRandom());
TimeStampRequestGenerator requestGenerator = new TimeStampRequestGenerator();
requestGenerator.setCertReq(true);
if (null != this.requestPolicy) {
requestGenerator.setReqPolicy(this.requestPolicy);
}
TimeStampRequest request = requestGenerator.generate(this.digestAlgoOid, digest, nonce);
byte[] encodedRequest = request.getEncoded();
HttpClient httpClient = new HttpClient();
if (null != this.username) {
Credentials credentials = new UsernamePasswordCredentials(this.username, this.password);
httpClient.getState().setCredentials(AuthScope.ANY, credentials);
}
if (null != this.proxyHost) {
httpClient.getHostConfiguration().setProxy(this.proxyHost, this.proxyPort);
}
PostMethod postMethod = new PostMethod(this.tspServiceUrl);
RequestEntity requestEntity = new ByteArrayRequestEntity(encodedRequest, "application/timestamp-query");
postMethod.addRequestHeader("User-Agent", this.userAgent);
postMethod.setRequestEntity(requestEntity);
int statusCode = httpClient.executeMethod(postMethod);
if (HttpStatus.SC_OK != statusCode) {
LOG.error("Error contacting TSP server " + this.tspServiceUrl);
throw new Exception("Error contacting TSP server " + this.tspServiceUrl);
}
Header responseContentTypeHeader = postMethod.getResponseHeader("Content-Type");
if (null == responseContentTypeHeader) {
throw new RuntimeException("missing Content-Type header");
}
String contentType = responseContentTypeHeader.getValue();
if (!contentType.startsWith("application/timestamp-reply")) {
LOG.debug("response content: " + postMethod.getResponseBodyAsString());
throw new RuntimeException("invalid Content-Type: " + contentType);
}
if (0 == postMethod.getResponseContentLength()) {
throw new RuntimeException("Content-Length is zero");
}
InputStream inputStream = postMethod.getResponseBodyAsStream();
TimeStampResponse timeStampResponse = new TimeStampResponse(inputStream);
timeStampResponse.validate(request);
if (0 != timeStampResponse.getStatus()) {
LOG.debug("status: " + timeStampResponse.getStatus());
LOG.debug("status string: " + timeStampResponse.getStatusString());
PKIFailureInfo failInfo = timeStampResponse.getFailInfo();
if (null != failInfo) {
LOG.debug("fail info int value: " + failInfo.intValue());
if (PKIFailureInfo.unacceptedPolicy == failInfo.intValue()) {
LOG.debug("unaccepted policy");
}
}
throw new RuntimeException("timestamp response status != 0: " + timeStampResponse.getStatus());
}
TimeStampToken timeStampToken = timeStampResponse.getTimeStampToken();
SignerId signerId = timeStampToken.getSID();
BigInteger signerCertSerialNumber = signerId.getSerialNumber();
X500Principal signerCertIssuer = signerId.getIssuer();
LOG.debug("signer cert serial number: " + signerCertSerialNumber);
LOG.debug("signer cert issuer: " + signerCertIssuer);
CertStore certStore = timeStampToken.getCertificatesAndCRLs("Collection", BouncyCastleProvider.PROVIDER_NAME);
Collection<? extends Certificate> certificates = certStore.getCertificates(null);
X509Certificate signerCert = null;
Map<String, X509Certificate> certificateMap = new HashMap<String, X509Certificate>();
for (Certificate certificate : certificates) {
X509Certificate x509Certificate = (X509Certificate) certificate;
if (signerCertIssuer.equals(x509Certificate.getIssuerX500Principal()) && signerCertSerialNumber.equals(x509Certificate.getSerialNumber())) {
signerCert = x509Certificate;
}
String ski = Hex.encodeHexString(getSubjectKeyId(x509Certificate));
certificateMap.put(ski, x509Certificate);
LOG.debug("embedded certificate: " + x509Certificate.getSubjectX500Principal() + "; SKI=" + ski);
}
if (null == signerCert) {
throw new RuntimeException("TSP response token has no signer certificate");
}
List<X509Certificate> tspCertificateChain = new LinkedList<X509Certificate>();
X509Certificate certificate = signerCert;
do {
LOG.debug("adding to certificate chain: " + certificate.getSubjectX500Principal());
tspCertificateChain.add(certificate);
if (certificate.getSubjectX500Principal().equals(certificate.getIssuerX500Principal())) {
break;
}
String aki = Hex.encodeHexString(getAuthorityKeyId(certificate));
certificate = certificateMap.get(aki);
} while (null != certificate);
timeStampToken.validate(tspCertificateChain.get(0), BouncyCastleProvider.PROVIDER_NAME);
this.validator.validate(tspCertificateChain, revocationData);
LOG.debug("time-stamp token time: " + timeStampToken.getTimeStampInfo().getGenTime());
byte[] timestamp = timeStampToken.getEncoded();
return timestamp;
}
private byte[] getSubjectKeyId(X509Certificate cert) throws IOException {
byte[] extvalue = cert.getExtensionValue(X509Extensions.SubjectKeyIdentifier.getId());
if (extvalue == null) {
return null;
}
ASN1OctetString str = ASN1OctetString.getInstance(new ASN1InputStream(new ByteArrayInputStream(extvalue)).readObject());
SubjectKeyIdentifier keyId = SubjectKeyIdentifier.getInstance(new ASN1InputStream(new ByteArrayInputStream(str.getOctets())).readObject());
return keyId.getKeyIdentifier();
}
private byte[] getAuthorityKeyId(X509Certificate cert) throws IOException {
byte[] extvalue = cert.getExtensionValue(X509Extensions.AuthorityKeyIdentifier.getId());
if (extvalue == null) {
return null;
}
DEROctetString oct = (DEROctetString) (new ASN1InputStream(new ByteArrayInputStream(extvalue)).readObject());
AuthorityKeyIdentifier keyId = new AuthorityKeyIdentifier((ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(oct.getOctets())).readObject());
return keyId.getKeyIdentifier();
}
}
| 12,708 | 0.693579 | 0.682169 | 306 | 40.529411 | 31.764875 | 158 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.712418 | false | false | 3 |
136ca76baecf9e1498ce1d20e5d31a2ae77b5ec2 | 8,400,956,070,374 | 49b64d9aadb46a7df70571f5ce86afee26e88474 | /src/main/java/com/mods/kina/ExperiencePower/block/BlockSimpleExpInjector.java | c8d50e22fd85e4d8b1451f5108c0d25783fef394 | [] | no_license | CrafterKina/ExperiencePower | https://github.com/CrafterKina/ExperiencePower | 85c60ff7853287b4b23cbebea0d97656f5151875 | 159cdf4d50d44963e03cab8558c69c3b10e1c573 | refs/heads/master | 2021-01-19T09:09:21.731000 | 2015-04-19T01:18:50 | 2015-04-19T01:18:50 | 28,576,277 | 1 | 0 | null | false | 2015-02-16T12:40:45 | 2014-12-29T01:34:12 | 2015-02-05T01:04:37 | 2015-02-16T12:40:45 | 676 | 0 | 0 | 6 | Java | null | null | package com.mods.kina.ExperiencePower.block;
import com.mods.kina.ExperiencePower.base.BlockMachineBase;
import com.mods.kina.ExperiencePower.tileentity.TileEntitySimpleExpInjector;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.inventory.IInventory;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.util.Random;
public class BlockSimpleExpInjector extends BlockMachineBase{
public BlockSimpleExpInjector(){
super(Material.rock);
setUnlocalizedName("simple_exp_injector");
setLightLevel(0.1f);
}
/**
Returns a new instance of a block's tile entity class. Called on placing the block.
@param world
Worldのインスタンス
@param meta
設置されるBlockのメタデータ値。
*/
public TileEntity createNewTileEntity(World world, int meta){
return new TileEntitySimpleExpInjector();
}
public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumFacing side, float hitX, float hitY, float hitZ){
//TODO プレイヤーのアイテムを減らす
if(playerIn.getCurrentEquippedItem() != null){
if(((IInventory) worldIn.getTileEntity(pos)).getStackInSlot(0) != null)
Block.spawnAsEntity(worldIn, pos, ((IInventory) worldIn.getTileEntity(pos)).getStackInSlot(0));
((IInventory) worldIn.getTileEntity(pos)).setInventorySlotContents(0, playerIn.getCurrentEquippedItem());
}else if(((IInventory) worldIn.getTileEntity(pos)).getStackInSlot(0) != null){
Block.spawnAsEntity(worldIn, pos, ((IInventory) worldIn.getTileEntity(pos)).getStackInSlot(0));
((IInventory) worldIn.getTileEntity(pos)).setInventorySlotContents(0, null);
}
return true;
}
@SideOnly(Side.CLIENT)
public void randomDisplayTick(World worldIn, BlockPos pos, IBlockState state, Random rand){
if(((TileEntitySimpleExpInjector) worldIn.getTileEntity(pos)).progressTime > 0) for(int i = 0; i < 10; i++){
Blocks.enchanting_table.randomDisplayTick(worldIn, pos, state, rand);
}
}
}
| UTF-8 | Java | 2,524 | java | BlockSimpleExpInjector.java | Java | [] | null | [] | package com.mods.kina.ExperiencePower.block;
import com.mods.kina.ExperiencePower.base.BlockMachineBase;
import com.mods.kina.ExperiencePower.tileentity.TileEntitySimpleExpInjector;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.inventory.IInventory;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.util.Random;
public class BlockSimpleExpInjector extends BlockMachineBase{
public BlockSimpleExpInjector(){
super(Material.rock);
setUnlocalizedName("simple_exp_injector");
setLightLevel(0.1f);
}
/**
Returns a new instance of a block's tile entity class. Called on placing the block.
@param world
Worldのインスタンス
@param meta
設置されるBlockのメタデータ値。
*/
public TileEntity createNewTileEntity(World world, int meta){
return new TileEntitySimpleExpInjector();
}
public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumFacing side, float hitX, float hitY, float hitZ){
//TODO プレイヤーのアイテムを減らす
if(playerIn.getCurrentEquippedItem() != null){
if(((IInventory) worldIn.getTileEntity(pos)).getStackInSlot(0) != null)
Block.spawnAsEntity(worldIn, pos, ((IInventory) worldIn.getTileEntity(pos)).getStackInSlot(0));
((IInventory) worldIn.getTileEntity(pos)).setInventorySlotContents(0, playerIn.getCurrentEquippedItem());
}else if(((IInventory) worldIn.getTileEntity(pos)).getStackInSlot(0) != null){
Block.spawnAsEntity(worldIn, pos, ((IInventory) worldIn.getTileEntity(pos)).getStackInSlot(0));
((IInventory) worldIn.getTileEntity(pos)).setInventorySlotContents(0, null);
}
return true;
}
@SideOnly(Side.CLIENT)
public void randomDisplayTick(World worldIn, BlockPos pos, IBlockState state, Random rand){
if(((TileEntitySimpleExpInjector) worldIn.getTileEntity(pos)).progressTime > 0) for(int i = 0; i < 10; i++){
Blocks.enchanting_table.randomDisplayTick(worldIn, pos, state, rand);
}
}
}
| 2,524 | 0.730049 | 0.725163 | 58 | 41.344826 | 36.499199 | 160 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.827586 | false | false | 3 |
5057be40646ec14a081ce46dca8d65abc7b2add4 | 11,544,872,130,809 | fe289d4625cf928994abc6748b02a76b256abf67 | /src/day28_loops/FindUniqueChars.java | e6d448bd72718d33c3a1a0f9121da5ae9b70003c | [] | no_license | IrinaPK8/java-programming | https://github.com/IrinaPK8/java-programming | 495d8202b4bb9bb52457bf7e52f89cd023d48a60 | 12080e703c8f0585495ff8fbcaccb403c09ae13a | refs/heads/master | 2023-06-11T09:58:28.330000 | 2021-07-07T02:08:00 | 2021-07-07T02:08:00 | 382,659,178 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package day28_loops;
public class FindUniqueChars {
public static void main(String[] args) {
/**
* Find unique characters in String:
* String word = "java";
* 1) jac --> each character only one occurrence, remove duplicates
* 2) jv --> only the characters that are unique/non-duplicate in the String
* helloworld --> helowrd - remove duplicates
* helloworld --> hewrd - take only unique letters
*/
String word = "jaavva";
String unique = ""; // declare one additional variable, make it empty. USING IT AS STORAGE!!!
for (int i = 0; i < word.length(); i++) {
if (!unique.contains(word.charAt(i) + "")) { // + "" - makes it string // if word.charAt(i) does not contain - is unique
unique += word.charAt(i); // if word does not contain character, add this character to unique variable
}
}
System.out.println(unique);
}
}
| UTF-8 | Java | 1,008 | java | FindUniqueChars.java | Java | [
{
"context": "nique letters\n */\n\n String word = \"jaavva\";\n String unique = \"\"; // d",
"end": 500,
"score": 0.7502462267875671,
"start": 498,
"tag": "NAME",
"value": "ja"
},
{
"context": "que letters\n */\n\n String word = \"jaavva\";\n String unique = \"\"; // decla",
"end": 504,
"score": 0.27414757013320923,
"start": 500,
"tag": "KEY",
"value": "avva"
}
] | null | [] | package day28_loops;
public class FindUniqueChars {
public static void main(String[] args) {
/**
* Find unique characters in String:
* String word = "java";
* 1) jac --> each character only one occurrence, remove duplicates
* 2) jv --> only the characters that are unique/non-duplicate in the String
* helloworld --> helowrd - remove duplicates
* helloworld --> hewrd - take only unique letters
*/
String word = "jaavva";
String unique = ""; // declare one additional variable, make it empty. USING IT AS STORAGE!!!
for (int i = 0; i < word.length(); i++) {
if (!unique.contains(word.charAt(i) + "")) { // + "" - makes it string // if word.charAt(i) does not contain - is unique
unique += word.charAt(i); // if word does not contain character, add this character to unique variable
}
}
System.out.println(unique);
}
}
| 1,008 | 0.563492 | 0.558532 | 23 | 42.826088 | 39.798023 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.478261 | false | false | 3 |
88a47767bff62acfa215f7d822b08ff30e758e6b | 28,372,553,985,008 | 139e2c864c1c1cc20008c8a639d807f4bdc37ebd | /SparkGive/src/com/sparkgive/MainActivity.java | f8fa8488a2bda44bae9e1d5710fd91678a3260e2 | [] | no_license | sumitarora/sparkgive | https://github.com/sumitarora/sparkgive | 692b52c7baf73f0ea938d59c82f13a793a12f91d | 054f9d873afa0314d01f95cd34fce650e8ed5541 | refs/heads/master | 2021-01-10T19:20:23.147000 | 2015-03-14T14:13:50 | 2015-03-14T14:13:50 | 32,214,964 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sparkgive;
import java.util.ArrayList;
import java.util.List;
import android.app.ActionBar;
import android.app.Activity;
import android.app.SearchManager;
import android.app.SearchableInfo;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageView;
import android.widget.SearchView;
import android.widget.StackView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import com.sparkgive.components.Card;
import com.sparkgive.components.StackAdapter;
import com.sparkgive.components.StackItem;
import com.sparkgive.model.SparkGiveModel;
public class MainActivity extends Activity implements OnClickListener, SearchView.OnQueryTextListener,
SearchView.OnCloseListener {
private ImageView profileButton, mapsButton, publicCardsButton, settingsButton;
private TextView mStatusView;
private SearchView mSearchView;
// private Button mRedeemButton;
ArrayList<Card> mCardList;
ArrayList<StackItem> mStackItems;
@Override
protected void onCreate(Bundle savedInstanceState) {
SparkGiveModel.nearByPlaces.add("Place 1");
SparkGiveModel.nearByPlaces.add("Place 2");
SparkGiveModel.nearByPlaces.add("Place 3");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ActionBar actionBar = getActionBar();
Bitmap actionBarBackground = BitmapFactory.decodeResource(getResources(), R.drawable.footer_bar);
BitmapDrawable background = new BitmapDrawable(getResources(), actionBarBackground);
actionBar.setBackgroundDrawable(background);
actionBar.setHomeButtonEnabled(true);
profileButton = (ImageView) findViewById(R.id.profile);
mapsButton = (ImageView) findViewById(R.id.Maps_button);
publicCardsButton = (ImageView) findViewById(R.id.public_cards);
settingsButton = (ImageView) findViewById(R.id.list);
//mStatusView = (TextView) findViewById(R.id.status_text);
profileButton.setOnClickListener(this);
mapsButton.setOnClickListener(this);
publicCardsButton.setOnClickListener(this);
settingsButton.setOnClickListener(this);
mStackItems = new ArrayList<StackItem>();
mCardList = SparkGiveModel.cardList;
reloadCards();
for(int i=0; i<mCardList.size(); i++) {
mStackItems.add(new StackItem(this.getResources().getDrawable(mCardList.get(i).getResourceId())));
}
///Stackview
StackView stk = (StackView)this.findViewById(R.id.stackView1);
StackAdapter adapt = new StackAdapter(this, R.layout.item, mStackItems);
stk.setAdapter(adapt);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.layout.searchview_in_menu, menu);
mSearchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
setupSearchView();
return true;
}
@Override
protected void onResume() {
super.onResume();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.profile:
startActivity(new Intent(getApplicationContext(), CampaignsActivity.class));
break;
case R.id.Maps_button:
startActivity(new Intent(getApplicationContext(), MapsActivity.class));
break;
case R.id.public_cards:
startActivity(new Intent(getApplicationContext(), PublicCardsActivity.class));
break;
case R.id.list:
break;
}
}
private void setupSearchView() {
mSearchView.setIconifiedByDefault(true);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
if (searchManager != null) {
List<SearchableInfo> searchables = searchManager.getSearchablesInGlobalSearch();
// Try to use the "applications" global search provider
SearchableInfo info = searchManager.getSearchableInfo(getComponentName());
for (SearchableInfo inf : searchables) {
if (inf.getSuggestAuthority() != null
&& inf.getSuggestAuthority().startsWith("applications")) {
info = inf;
}
}
mSearchView.setSearchableInfo(info);
}
mSearchView.setOnQueryTextListener(this);
mSearchView.setOnCloseListener(this);
}
public boolean onQueryTextChange(String newText) {
return true;
}
public boolean onQueryTextSubmit(String query) {
startActivity(new Intent(getApplicationContext(), SearchableActivity.class));
return true;
}
private void reloadCards() {
SparkGiveModel.cardList.clear();
SparkGiveModel.cardList.add(new Card("Loblaws will donate food worth 5% of your purchase price, given a purchase of at least $50, to Food Bank Canada. SparkCard expires on March 31, 2013.", "food banks",R.drawable.final_loblaws_foodbank, R.drawable.back_loblaws));
SparkGiveModel.cardList.add(new Card("Shoppers Drug Mart will support SickKids Foundation by donating 3% of your purchase price, given a purchase of at least $40, to help sick kids ail faster. SparkCard expires on May 15, 2013.", "sick kids", R.drawable.final_sdm_sickkids, R.drawable.back_sickkids));
SparkGiveModel.cardList.add(new Card("Starbucks will donate 2% of your purchase price, given a purchase of $5 or more, to the Canadian Breast Cancer Research Foundation. SparkCard expires on June 1, 2013.", "breast cancer", R.drawable.final_star, R.drawable.back_starbucks));
SparkGiveModel.cardList.add(new Card("ToyRUs will donate 1% of your purchase cost, given a purchase of $50 or more, to Make A Wish Foundation to help grant a child a wish. SparkCard expires on September 21, 2013.", "wish",R.drawable.final_toysrus, R.drawable.back_toysrus));
SparkGiveModel.cardList.add(new Card("Walmart will donate 15% of your purchase price, on purchase worth $200 or more, to Global Women's Economic Empowerment. SparkCard valid on Women's Day (March 8, 2013).", "Red cross",R.drawable.final_walmartredcross, R.drawable.back_walmart));
}
public boolean onClose() {
return false;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.home:
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
| UTF-8 | Java | 7,335 | java | MainActivity.java | Java | [] | null | [] | package com.sparkgive;
import java.util.ArrayList;
import java.util.List;
import android.app.ActionBar;
import android.app.Activity;
import android.app.SearchManager;
import android.app.SearchableInfo;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageView;
import android.widget.SearchView;
import android.widget.StackView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import com.sparkgive.components.Card;
import com.sparkgive.components.StackAdapter;
import com.sparkgive.components.StackItem;
import com.sparkgive.model.SparkGiveModel;
public class MainActivity extends Activity implements OnClickListener, SearchView.OnQueryTextListener,
SearchView.OnCloseListener {
private ImageView profileButton, mapsButton, publicCardsButton, settingsButton;
private TextView mStatusView;
private SearchView mSearchView;
// private Button mRedeemButton;
ArrayList<Card> mCardList;
ArrayList<StackItem> mStackItems;
@Override
protected void onCreate(Bundle savedInstanceState) {
SparkGiveModel.nearByPlaces.add("Place 1");
SparkGiveModel.nearByPlaces.add("Place 2");
SparkGiveModel.nearByPlaces.add("Place 3");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ActionBar actionBar = getActionBar();
Bitmap actionBarBackground = BitmapFactory.decodeResource(getResources(), R.drawable.footer_bar);
BitmapDrawable background = new BitmapDrawable(getResources(), actionBarBackground);
actionBar.setBackgroundDrawable(background);
actionBar.setHomeButtonEnabled(true);
profileButton = (ImageView) findViewById(R.id.profile);
mapsButton = (ImageView) findViewById(R.id.Maps_button);
publicCardsButton = (ImageView) findViewById(R.id.public_cards);
settingsButton = (ImageView) findViewById(R.id.list);
//mStatusView = (TextView) findViewById(R.id.status_text);
profileButton.setOnClickListener(this);
mapsButton.setOnClickListener(this);
publicCardsButton.setOnClickListener(this);
settingsButton.setOnClickListener(this);
mStackItems = new ArrayList<StackItem>();
mCardList = SparkGiveModel.cardList;
reloadCards();
for(int i=0; i<mCardList.size(); i++) {
mStackItems.add(new StackItem(this.getResources().getDrawable(mCardList.get(i).getResourceId())));
}
///Stackview
StackView stk = (StackView)this.findViewById(R.id.stackView1);
StackAdapter adapt = new StackAdapter(this, R.layout.item, mStackItems);
stk.setAdapter(adapt);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.layout.searchview_in_menu, menu);
mSearchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
setupSearchView();
return true;
}
@Override
protected void onResume() {
super.onResume();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.profile:
startActivity(new Intent(getApplicationContext(), CampaignsActivity.class));
break;
case R.id.Maps_button:
startActivity(new Intent(getApplicationContext(), MapsActivity.class));
break;
case R.id.public_cards:
startActivity(new Intent(getApplicationContext(), PublicCardsActivity.class));
break;
case R.id.list:
break;
}
}
private void setupSearchView() {
mSearchView.setIconifiedByDefault(true);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
if (searchManager != null) {
List<SearchableInfo> searchables = searchManager.getSearchablesInGlobalSearch();
// Try to use the "applications" global search provider
SearchableInfo info = searchManager.getSearchableInfo(getComponentName());
for (SearchableInfo inf : searchables) {
if (inf.getSuggestAuthority() != null
&& inf.getSuggestAuthority().startsWith("applications")) {
info = inf;
}
}
mSearchView.setSearchableInfo(info);
}
mSearchView.setOnQueryTextListener(this);
mSearchView.setOnCloseListener(this);
}
public boolean onQueryTextChange(String newText) {
return true;
}
public boolean onQueryTextSubmit(String query) {
startActivity(new Intent(getApplicationContext(), SearchableActivity.class));
return true;
}
private void reloadCards() {
SparkGiveModel.cardList.clear();
SparkGiveModel.cardList.add(new Card("Loblaws will donate food worth 5% of your purchase price, given a purchase of at least $50, to Food Bank Canada. SparkCard expires on March 31, 2013.", "food banks",R.drawable.final_loblaws_foodbank, R.drawable.back_loblaws));
SparkGiveModel.cardList.add(new Card("Shoppers Drug Mart will support SickKids Foundation by donating 3% of your purchase price, given a purchase of at least $40, to help sick kids ail faster. SparkCard expires on May 15, 2013.", "sick kids", R.drawable.final_sdm_sickkids, R.drawable.back_sickkids));
SparkGiveModel.cardList.add(new Card("Starbucks will donate 2% of your purchase price, given a purchase of $5 or more, to the Canadian Breast Cancer Research Foundation. SparkCard expires on June 1, 2013.", "breast cancer", R.drawable.final_star, R.drawable.back_starbucks));
SparkGiveModel.cardList.add(new Card("ToyRUs will donate 1% of your purchase cost, given a purchase of $50 or more, to Make A Wish Foundation to help grant a child a wish. SparkCard expires on September 21, 2013.", "wish",R.drawable.final_toysrus, R.drawable.back_toysrus));
SparkGiveModel.cardList.add(new Card("Walmart will donate 15% of your purchase price, on purchase worth $200 or more, to Global Women's Economic Empowerment. SparkCard valid on Women's Day (March 8, 2013).", "Red cross",R.drawable.final_walmartredcross, R.drawable.back_walmart));
}
public boolean onClose() {
return false;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.home:
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
| 7,335 | 0.694479 | 0.687662 | 198 | 36.045456 | 47.510582 | 306 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.075758 | false | false | 3 |
e34651828205657fcbe8a9d02183f0ae06900603 | 37,340,445,704,781 | 20bf71dbd2acaf1477255e6b92498494e8010c40 | /src/main/java/volumes/Configuration.java | 799bf671145238e5defdf2508296fd292156c57d | [] | no_license | jwoschitz/volume-manager | https://github.com/jwoschitz/volume-manager | 6e3b091867f799987cb6c814192411a2109f235c | bccfdca0930a56a99ab33bfe7eb40a2886581b48 | refs/heads/master | 2021-01-09T03:07:38.879000 | 2019-01-18T15:42:50 | 2019-01-18T15:42:50 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package volumes;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
/**
* This class implements a simple and light-weight configuration utility. The
* class can read Hadoop-style XML configuration file without requiring a large
* set of additional libraries such as hadoop-common, guava, etc.
* <p>
* This class is not thread-safe.
*/
final class Configuration {
/**
* The log object used for debugging and reporting.
*/
private static final Log LOG = LogFactory.getLog(Configuration.class);
private final Map<String, String> keyValuePairs = new HashMap<String, String>();
void addResource(final File file) {
final DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
.newInstance();
// Ignore comments in the XML file
docBuilderFactory.setIgnoringComments(true);
docBuilderFactory.setNamespaceAware(true);
try {
final DocumentBuilder builder = docBuilderFactory
.newDocumentBuilder();
Document doc = null;
Element root = null;
doc = builder.parse(file);
if (doc == null) {
LOG.warn("Cannot load configuration: doc is null");
return;
}
root = doc.getDocumentElement();
if (root == null) {
LOG.warn("Cannot load configuration: root is null");
return;
}
if (!"configuration".equals(root.getNodeName())) {
LOG.warn("Cannot load configuration: unknown element "
+ root.getNodeName());
return;
}
final NodeList props = root.getChildNodes();
for (int i = 0; i < props.getLength(); i++) {
final Node propNode = props.item(i);
String name = null;
String value = null;
// Ignore text at this point
if (propNode instanceof Text) {
continue;
}
if (!(propNode instanceof Element)) {
LOG.warn("Error while reading configuration: "
+ propNode.getNodeName()
+ " is not of type element");
continue;
}
Element property = (Element) propNode;
if (!"property".equals(property.getNodeName())) {
LOG.warn("Error while reading configuration: unknown element "
+ property.getNodeName());
continue;
}
final NodeList propChildren = property.getChildNodes();
if (propChildren == null) {
LOG.warn("Error while reading configuration: property has no children, skipping...");
continue;
}
for (int j = 0; j < propChildren.getLength(); ++j) {
final Node propChild = propChildren.item(j);
if (propChild instanceof Element) {
if ("name".equals(propChild.getNodeName())
&& propChild.getChildNodes() != null
&& propChild.getChildNodes().getLength() == 1
&& propChild.getChildNodes().item(0) instanceof Text) {
final Text t = (Text) propChild.getChildNodes()
.item(0);
name = t.getTextContent();
}
if ("value".equals(propChild.getNodeName())
&& propChild.getChildNodes() != null
&& propChild.getChildNodes().getLength() == 1
&& propChild.getChildNodes().item(0) instanceof Text) {
final Text t = (Text) propChild.getChildNodes()
.item(0);
value = t.getTextContent();
}
}
}
if (name != null && value != null) {
if (LOG.isDebugEnabled()) {
LOG.debug("Added configuration property: " + name
+ ", " + value);
}
this.keyValuePairs.put(name, value);
}
}
} catch (Exception e) {
LOG.warn(e.getMessage());
}
}
String get(final String key, final String defaultValue) {
final String value = this.keyValuePairs.get(key);
if (value != null) {
return value;
}
return defaultValue;
}
int getInt(final String key, final int defaultValue) {
final String value = this.keyValuePairs.get(key);
if (value != null) {
try {
return Integer.parseInt(value);
} catch (NumberFormatException nfe) {
}
}
return defaultValue;
}
}
| UTF-8 | Java | 5,473 | java | Configuration.java | Java | [] | null | [] | package volumes;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
/**
* This class implements a simple and light-weight configuration utility. The
* class can read Hadoop-style XML configuration file without requiring a large
* set of additional libraries such as hadoop-common, guava, etc.
* <p>
* This class is not thread-safe.
*/
final class Configuration {
/**
* The log object used for debugging and reporting.
*/
private static final Log LOG = LogFactory.getLog(Configuration.class);
private final Map<String, String> keyValuePairs = new HashMap<String, String>();
void addResource(final File file) {
final DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
.newInstance();
// Ignore comments in the XML file
docBuilderFactory.setIgnoringComments(true);
docBuilderFactory.setNamespaceAware(true);
try {
final DocumentBuilder builder = docBuilderFactory
.newDocumentBuilder();
Document doc = null;
Element root = null;
doc = builder.parse(file);
if (doc == null) {
LOG.warn("Cannot load configuration: doc is null");
return;
}
root = doc.getDocumentElement();
if (root == null) {
LOG.warn("Cannot load configuration: root is null");
return;
}
if (!"configuration".equals(root.getNodeName())) {
LOG.warn("Cannot load configuration: unknown element "
+ root.getNodeName());
return;
}
final NodeList props = root.getChildNodes();
for (int i = 0; i < props.getLength(); i++) {
final Node propNode = props.item(i);
String name = null;
String value = null;
// Ignore text at this point
if (propNode instanceof Text) {
continue;
}
if (!(propNode instanceof Element)) {
LOG.warn("Error while reading configuration: "
+ propNode.getNodeName()
+ " is not of type element");
continue;
}
Element property = (Element) propNode;
if (!"property".equals(property.getNodeName())) {
LOG.warn("Error while reading configuration: unknown element "
+ property.getNodeName());
continue;
}
final NodeList propChildren = property.getChildNodes();
if (propChildren == null) {
LOG.warn("Error while reading configuration: property has no children, skipping...");
continue;
}
for (int j = 0; j < propChildren.getLength(); ++j) {
final Node propChild = propChildren.item(j);
if (propChild instanceof Element) {
if ("name".equals(propChild.getNodeName())
&& propChild.getChildNodes() != null
&& propChild.getChildNodes().getLength() == 1
&& propChild.getChildNodes().item(0) instanceof Text) {
final Text t = (Text) propChild.getChildNodes()
.item(0);
name = t.getTextContent();
}
if ("value".equals(propChild.getNodeName())
&& propChild.getChildNodes() != null
&& propChild.getChildNodes().getLength() == 1
&& propChild.getChildNodes().item(0) instanceof Text) {
final Text t = (Text) propChild.getChildNodes()
.item(0);
value = t.getTextContent();
}
}
}
if (name != null && value != null) {
if (LOG.isDebugEnabled()) {
LOG.debug("Added configuration property: " + name
+ ", " + value);
}
this.keyValuePairs.put(name, value);
}
}
} catch (Exception e) {
LOG.warn(e.getMessage());
}
}
String get(final String key, final String defaultValue) {
final String value = this.keyValuePairs.get(key);
if (value != null) {
return value;
}
return defaultValue;
}
int getInt(final String key, final int defaultValue) {
final String value = this.keyValuePairs.get(key);
if (value != null) {
try {
return Integer.parseInt(value);
} catch (NumberFormatException nfe) {
}
}
return defaultValue;
}
}
| 5,473 | 0.501005 | 0.49863 | 163 | 32.576687 | 26.451923 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.423313 | false | false | 11 |
b10997d817ec0e6b5f7d775eadda5c6ea8a1a32a | 36,876,589,240,150 | 9ac1cc511fd5b3dbf1bdfcce2333d9a8654e70ad | /Intro Programming/Java/PA05_TVs/src/pa05_tvs/PA05_TVs.java | 756ae2f2ae84622b1bca47e9d92d83d0f2828d0a | [] | no_license | DrewPick/2016-Java-Workspace | https://github.com/DrewPick/2016-Java-Workspace | dad7556c70b3bce71eeea340d048071ea8715617 | 733b33492622b3032c0a33a741b20827bb7229e8 | refs/heads/master | 2020-07-12T22:36:57.211000 | 2016-11-16T08:08:16 | 2016-11-16T08:08:16 | 73,897,745 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package pa05_tvs;
import java.util.*;
/** PA05.java
* This program shows you how class interaction is used. It shows how the
* program uses the Class Tv.java.
* Drew Pickett
* 10 - 12 - 2016
*/
public class PA05_TVs {
public static void main(String[] args) {
// Creates two TV Objects
Tv tv1 = new Tv(3, "Tv1");
Tv tv2 = new Tv(24, "Tv2");
// Prints out Tv Objects method .toString
System.out.println(tv1.toString());
System.out.println(tv2.toString());
System.out.println();
// Spacer
System.out.println("------------------------------------------");
System.out.println();
// Sets tv1 to channel 99 and tv2 to a random channel
tv1.setChannel(99);
tv2.getRandomChannel();
// Prints out Tv Objects method .toString
System.out.println(tv1.toString());
System.out.println(tv2.toString());
}
}
| UTF-8 | Java | 1,012 | java | PA05_TVs.java | Java | [
{
"context": "hows how the\n * program uses the Class Tv.java.\n * Drew Pickett\n * 10 - 12 - 2016\n */\npublic class PA05_TVs {\n\n\n ",
"end": 179,
"score": 0.9998793601989746,
"start": 167,
"tag": "NAME",
"value": "Drew Pickett"
}
] | null | [] |
package pa05_tvs;
import java.util.*;
/** PA05.java
* This program shows you how class interaction is used. It shows how the
* program uses the Class Tv.java.
* <NAME>
* 10 - 12 - 2016
*/
public class PA05_TVs {
public static void main(String[] args) {
// Creates two TV Objects
Tv tv1 = new Tv(3, "Tv1");
Tv tv2 = new Tv(24, "Tv2");
// Prints out Tv Objects method .toString
System.out.println(tv1.toString());
System.out.println(tv2.toString());
System.out.println();
// Spacer
System.out.println("------------------------------------------");
System.out.println();
// Sets tv1 to channel 99 and tv2 to a random channel
tv1.setChannel(99);
tv2.getRandomChannel();
// Prints out Tv Objects method .toString
System.out.println(tv1.toString());
System.out.println(tv2.toString());
}
}
| 1,006 | 0.52668 | 0.494071 | 41 | 23.658537 | 19.915197 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.365854 | false | false | 11 |
369f82dfcee5224181d444796895b9cc9c058d3d | 39,247,411,170,056 | 03e6e93490c54f78dcd6a824d078cd3c39d3bda6 | /src/puzzle9iua_Prueba/Puzzle9IUA_Prueba.java | 9b4f0d26342300e5ee10e61eb1d801747ce313f1 | [] | no_license | mangelino997/puzzleBusquedaHeuristica | https://github.com/mangelino997/puzzleBusquedaHeuristica | 3f981ce746bb7b7ebd3c96f74b770251a51e8e36 | 9263d468cb415d20b7077cc4a57786e7b9cb7a3c | refs/heads/master | 2022-12-04T18:39:20.396000 | 2020-08-09T05:12:41 | 2020-08-09T05:12:41 | 258,265,998 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package puzzle9iua_Prueba;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
//* @author Angelino Marcio, Pavon Rosenthal Joel
public class Puzzle9IUA_Prueba {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); //crear un objeto Scanner
int opcion=0;
int [][] ConfInicial= {{1,2,3},{0,5,6},{4,7,8}};//new int[3][3]; //creamos un array bidimensional (3x3), corresponde a la Conf Inicial
int [][] ConfFinal={{1,2,3},{4,5,6},{7,8,0}};//new int [3][3]; //creamos un array bidimensional, corresponde a la Conf Final
int [][] ConfInicialAnterior= {{1,2,3},{0,5,6},{4,7,8}}; //iniciamos el array con valores predefinidos
//luego de que se carguen valores en los anteriores, estos adquirirán dichos valores.
int [][] ConfFinalAnterior={{1,2,3},{4,5,6},{7,8,0}};
int fila=3, columna=3, profundidad=0, operacion=0, MAXProfundidad=0, MAXNodosExplorados=0 ;
double SinLimites=0;
Nodo solucion;
System.out.println("************************************************");
System.out.println(" PUZZLE IUA ");
System.out.println("************************************************");
System.out.println("La Matriz del Puzzle será la siguiente");
System.out.println(" [1er valor][2do valor][3er valor] ");
System.out.println(" [4to valor][5to valor][6to valor] ");
System.out.println(" [7mo valor][8vo valor][9no valor] ");
System.out.println("");
System.out.println("Caracterisitcas del Juego:");
System.out.println("-Solo se permite ingresar valores del 0-8");
System.out.println("-Al valor 0 se lo considera como Espacio/Comodín");
System.out.println("*************************************************");
System.out.println("------------------------MENU-----------------------");
System.out.println("1_ Ingresar valores al Juego, configuracion Inicial y Final(SOLUCION) ");
System.out.println("2_ Utilizar la ultima configuracion Inicial y Final usada ");
System.out.println("3_ Resolver con Primero en Anchura");
System.out.println("4_ Resolver con Primero en Profundidad ");
System.out.println("5_ Resolver con Primero el Mejor ");
System.out.println("6_ Resolver con A* ");
System.out.println("7_ Resolver con Escalada con Máxima Pendiente ");
System.out.println("Salir (0)");
opcion=sc.nextInt();
while(opcion!=0){
switch (opcion)
{
case 1:
//ANTES DE INGRESAR NUEVOS VALORES A LA MATRIZ, GUARDAMOS LA CONFIG ANTERIOR.
for (int i = 0; i < fila; i++) {
for (int j = 0; j < columna; j++) {
ConfInicialAnterior[i][j]=ConfInicial[i][j];
}
}
for (int i = 0; i < fila; i++) {
for (int j = 0; j < columna; j++) {
ConfFinalAnterior[i][j]=ConfFinal[i][j];
}
}
///////////////////////////////////////////////////////////////////////
System.out.println("Ingrese los valores de la Configuracion Inicial:");
for (int i = 0; i < fila; i++) { //recorremos por fila, i=fila.
System.out.println("Fila "+i);
for (int j = 0; j < columna; j++) {// recorremos por columna, j=columna.
System.out.print("valor: ");
ConfInicial [i][j]=sc.nextInt();//asignamos el valor ingresado a dicha fila y columna.
//primero carga todas las columnas de la primer fila y despues pasa a la siguiente fila
}
System.out.println("");
}
System.out.println("Ingrese los valores de la Configuracion Final:");
for (int i = 0; i < fila; i++) {
System.out.println("Fila "+i);
for (int j = 0; j < columna; j++) {
System.out.print("valor: ");
ConfFinal [i][j]=sc.nextInt();
}
System.out.println("");
}
System.out.println("Matriz Inicial sera:");
imprimirMatrices(ConfInicial);
System.out.println("Matriz Final/Solucion sera:");
imprimirMatrices(ConfFinal);
break;
case 2:
System.out.println("Los ultimos valores utilizados son:");
System.out.println("Matriz Inicial:");
for (int i = 0; i < fila; i++) {
for (int j = 0; j < columna; j++) {
System.out.print("["+ConfInicialAnterior[i][j]+"]");
ConfInicial[i][j]=ConfInicialAnterior[i][j];
}
System.out.println("");
}
System.out.println("Matriz Final/Solucion:");
for (int i = 0; i < fila; i++) {
for (int j = 0; j < columna; j++) {
System.out.print("["+ConfFinalAnterior[i][j]+"]");
ConfFinal[i][j]=ConfFinalAnterior[i][j];
}
System.out.println("");
}
break;
case 3:
//lo primero que necesitamos hacer para buscar la solucion es convertir el
//array ConfInicial en un nodo el cual sera el nodo origen (el primero)
Nodo inicial=new Nodo(ConfInicial);
System.out.println("Profundidad MAXIMA: ");
MAXProfundidad=sc.nextInt();
System.out.println("Cantidad MAXIMA de Nodos Explorar: ");
MAXNodosExplorados=sc.nextInt();
System.out.println("---------Paso Por Paso----------");
solucion=buscarSolucionAnchura(inicial, ConfFinal,MAXProfundidad,MAXNodosExplorados );
if(solucion==null)
System.out.println("NO SE ENCONTRO SOLUCION DENTRO DE LOS LIMITES ESTABLECIDOS");
else
{
System.out.println("--------EL CAMINO A LA SOLUCION ES------------ ");
while(solucion.padre!=null)
{
imprimirSolucion(solucion.getEstado());
solucion=solucion.padre;
}
System.out.println("Nodo inicial:");
for (int i = 0; i < fila; i++) {
for (int j = 0; j < columna; j++) {
System.out.print("["+ConfInicial[i][j]+"]");
}
System.out.println("");
}
}
break;
case 4:
Nodo inicial2=new Nodo(ConfInicial);
System.out.println("Profundidad MAXIMA: ");
MAXProfundidad=sc.nextInt();
System.out.println("Cantidad MAXIMA de Nodos a Explorar: ");
MAXNodosExplorados=sc.nextInt();
System.out.println("---------Paso Por Paso----------");
solucion=buscarSolucionProfundidad(inicial2, ConfFinal,MAXProfundidad,MAXNodosExplorados );
if(solucion==null)
System.out.println("NO SE ENCONTRO SOLUCION DENTRO DE LOS LIMITES ESTABLECIDOS");
else
{
System.out.println("--------EL CAMINO A LA SOLUCION ES------------ ");
while(solucion.padre!=null)
{
imprimirSolucion(solucion.getEstado());
solucion=solucion.padre;
}
System.out.println("Nodo inicial:");
for (int i = 0; i < fila; i++) {
for (int j = 0; j < columna; j++) {
System.out.print("["+ConfInicial[i][j]+"]");
}
System.out.println("");
}
}
break;
case 5:
Nodo inicial3=new Nodo(ConfInicial);
System.out.println("Profundidad MAXIMA: ");
MAXProfundidad=sc.nextInt();
System.out.println("Cantidad MAXIMA de Nodos a Explorar: ");
MAXNodosExplorados=sc.nextInt();
System.out.println("---------Paso Por Paso----------");
solucion=buscarSolucionPrimeroElMejor(inicial3, ConfFinal,MAXProfundidad,MAXNodosExplorados );
if(solucion==null)
System.out.println("NO SE ENCONTRO SOLUCION DENTRO DE LOS LIMITES ESTABLECIDOS");
else
{
System.out.println("--------EL CAMINO A LA SOLUCION ES------------ ");
while(solucion.padre!=null)
{
imprimirSolucion(solucion.getEstado());
solucion=solucion.padre;
}
System.out.println("Nodo inicial:");
for (int i = 0; i < fila; i++) {
for (int j = 0; j < columna; j++) {
System.out.print("["+ConfInicial[i][j]+"]");
}
System.out.println("");
}
}
break;
case 6:
Nodo inicial4=new Nodo(ConfInicial);
System.out.println("Profundidad MAXIMA: ");
MAXProfundidad=sc.nextInt();
System.out.println("Cantidad MAXIMA de Nodos a Explorar: ");
MAXNodosExplorados=sc.nextInt();
System.out.println("---------Paso Por Paso----------");
solucion=buscarSolucionAestrella(inicial4, ConfFinal,MAXProfundidad,MAXNodosExplorados );
if(solucion==null)
System.out.println("NO SE ENCONTRO SOLUCION DENTRO DE LOS LIMITES ESTABLECIDOS");
else
{
System.out.println("--------EL CAMINO A LA SOLUCION ES------------ ");
while(solucion.padre!=null)
{
imprimirSolucion(solucion.getEstado());
solucion=solucion.padre;
}
System.out.println("Nodo inicial:");
for (int i = 0; i < fila; i++) {
for (int j = 0; j < columna; j++) {
System.out.print("["+ConfInicial[i][j]+"]");
}
System.out.println("");
}
}
break;
case 7:
Nodo inicial5=new Nodo(ConfInicial);
System.out.println("Profundidad MAXIMA: ");
MAXProfundidad=sc.nextInt();
System.out.println("Cantidad MAXIMA de Nodos a Explorar: ");
MAXNodosExplorados=sc.nextInt();
System.out.println("---------Paso Por Paso----------");
solucion=buscarSolucionEscaladaMaxPendiente(inicial5, ConfFinal,MAXProfundidad,MAXNodosExplorados );
if(solucion==null)
{ System.out.println("NO SE ENCONTRO SOLUCION");
}
else
{
System.out.println("--------EL CAMINO A LA SOLUCION ES------------ ");
while(solucion.padre!=null)
{
imprimirSolucion(solucion.getEstado());
solucion=solucion.padre;
}
System.out.println("Nodo inicial:");
for (int i = 0; i < fila; i++) {
for (int j = 0; j < columna; j++) {
System.out.print("["+ConfInicial[i][j]+"]");
}
System.out.println("");
}
}
break;
default:
break;
}
System.out.println("------------------------MENU-----------------------");
System.out.println("1_ Ingresar valores al Juego, configuracion Inicial y Final(SOLUCION) ");
System.out.println("2_ Utilizar la ultima configuracion Inicial y Final usada ");
System.out.println("3_ Resolver con Primero en Anchura");
System.out.println("4_ Resolver con Primero en Profundidad ");
System.out.println("5_ Resolver con Primero el Mejor ");
System.out.println("6_ Resolver con A* ");
System.out.println("7_ Resolver con Escalada con Máxima Pendiente ");
System.out.println("Salir (0)");
opcion=sc.nextInt();
}
}
// es un metodo static porque nos permite instanciar SIN crear un objeto de la clase
public static Nodo buscarSolucionAnchura(Nodo inicial, int[][] ConfFinal,int MAXProfundidad, int MAXNodosExplorados){
// el metodo va a necesitar que le pasemos un Nodo inicial y un array bidirecc. con la solucion
ArrayList <Nodo> listaAbierta=new ArrayList<Nodo>();//guarda todos los nodos que se van a
//ir explorando/expandiendo, y el primer nodo que tiene que ser explorado es el Nodo inicial
ArrayList<Nodo> listaCerrada= new ArrayList<Nodo>();
int profundidad=0;//el nodo inicial se encuentra en la profundidad 0
inicial.setProfundidad(profundidad);
listaAbierta.add(inicial);
int cantidadDeNodosExplorados=0;
int prof=0;
Nodo revisar=listaAbierta.remove(0);//asigna el nodo inicial al nodo que vamos a revisar
double ramificacionMedio=0;
while(cantidadDeNodosExplorados<MAXNodosExplorados&&profundidad<=MAXProfundidad){
// Nodo revisar=nodosExplorados.remove(0);//lo que hacemos es ir sacando del ArrayList a cada nodo para despues poder compararlo con la ConfFinal
//el nodo que vamos a sacar es el que esta en la primera posicion, por ende se va a comportar como una COLA (FIFO)
cantidadDeNodosExplorados++;
imprimirEstadoNodoRevisado(revisar,revisar.getEstado(),cantidadDeNodosExplorados);//el .getEstado va a convertir el nodo en un array bidir [][]
int [] posicionDelCero=ubicarPosicionCero(revisar.getEstado());//posicion en el array[][] donde se ubica el cero
//asi a partir de ello sabremos cuantos movimientos puede hacer el juego si el cero esta en el centro del array[][] entonces puede hacer 4 movimientos
//arriba-abajo-derecha-izquierda, pero si esta en una punta solo dos movimientos
listaCerrada.add(revisar);
ArrayList<Nodo> hijos=new ArrayList<Nodo>();//creamos una lista de hijos que va a tener un nodo
if(Arrays.deepEquals(revisar.getEstado(), ConfFinal)){//condicion de parada si el nodo que estamos revisando es igual a la solucion parar
System.out.println("******* SOLUCION ENCONTRADA*********");
System.out.println("Informacion:");
System.out.println("> Cantidad de nodos Evaluados= "+listaCerrada.size());
profundidad=calcularProfundidad(revisar);
System.out.println("> Profundidad alcanzada: "+profundidad);
ramificacionMedio=(double)cantidadDeNodosExplorados/(double)calcularProfundidad(revisar);
System.out.println("> Ramificacion Medio= "+ramificacionMedio);
System.out.println("> Perfil de Ramificacion: ");
imprimirPerfilRamificacion(profundidad,listaCerrada );
return revisar;//retorna el ultimo nodo explorado
}
//A continuacion empezamos a crear los hijos del nodo
if(posicionDelCero[0]!=0) //si la posicion del cero en las filas (posicion[0] es fila, pos[1]columna)
//es diferente de cero va a poder crear un hijo con un movimiento hacia arriba o abajo(sube una fila o baja)
{
Nodo hijo=new Nodo(clonar(revisar.getEstado()));//le estamos pasando un nodo igual al de antes pero ahora lo modificamos com los movimientos
int arriba=hijo.getEstado()[posicionDelCero[0]-1][posicionDelCero[1]];//capturamos el valor que esta en la fila de arriba de esa columna en la variable arriba
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]]=arriba;//metemos en la posicion donde estaba el cero, el valor que estaba en la fila de arriba
hijo.getEstado()[posicionDelCero[0]-1][posicionDelCero[1]]=0;//metemos en la fila de arriba el cero
if(!nodoRevisado(listaCerrada,hijo))//el metodo verifica si el hijo que estamos por expandir ya fue creado por otro nodo, si es asi no lo expandimos porque ya fue creado(ahorramos movimientos, no repetimos nodos)
{
hijo.setPadre(revisar);//creamos punteros a “revisar” en todos sus sucesores, de forma que pueda conocerse en todos ellos la identidad de su antecesor
//si no le asignamos un padre a cada hijo no vamos a poder usar el metodo imprimirPerfilRamificacion
listaAbierta.add(hijo);//metemos en el array de nodos explorados este nuevo nodo hijo para que luego se evalue
prof=calcularProfundidad(hijo);
hijo.setProfundidad(prof);
}
hijos.add(hijo);//el hijo que creo lo guardo en la lista hijos
}
if(posicionDelCero[0]!=2)//como el puzzle es de 3x3 solo llega hasta la fila 2(0,1,2) entonces le decimos que si no es 2 que baje para crear el otro hijo
{
Nodo hijo=new Nodo(clonar(revisar.getEstado()));
int abajo=hijo.getEstado()[posicionDelCero[0]+1][posicionDelCero[1]];//capturamos el valor que esta en la fila de abajo del cero
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]]=abajo;
hijo.getEstado()[posicionDelCero[0]+1][posicionDelCero[1]]=0;
if(!nodoRevisado(listaCerrada,hijo))
{
hijo.setPadre(revisar);
listaAbierta.add(hijo);
prof=calcularProfundidad(hijo);
hijo.setProfundidad(prof);
}
hijos.add(hijo);
}
//Ahora cambiamos los valores en la misma fila donde esta ubicado el cero, osea movimiento a izq y derecha
if(posicionDelCero[1]!=0) //no pasarme por izquierda
{
Nodo hijo=new Nodo(clonar(revisar.getEstado()));//le estamos pasando un nodo igual al de antes pero ahora lo modificamos com los movimientos
int izquierda=hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]-1];//capturamos el valor que esta en la fila de arriba de esa columna en la variable arriba
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]]=izquierda;//metemos en la posicion donde estaba el cero, el valor que estaba en la fila de arriba
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]-1]=0;//metemos en la fila de arriba el cero
if(!nodoRevisado(listaCerrada,hijo))
{
hijo.setPadre(revisar);
listaAbierta.add(hijo);
prof=calcularProfundidad(hijo);
hijo.setProfundidad(prof);
}//metemos en el array de nodos explorados este nuevo nodo hijo para que luego se evalue
hijos.add(hijo);
}
if(posicionDelCero[1]!=2)//no pasarme por derecha
{
Nodo hijo=new Nodo(clonar(revisar.getEstado()));
int derecha=hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]+1];//capturamos el valor que esta en la fila de abajo del cero
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]]=derecha;
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]+1]=0;
if(!nodoRevisado(listaCerrada,hijo))
{
hijo.setPadre(revisar);
listaAbierta.add(hijo);
prof=calcularProfundidad(hijo);
hijo.setProfundidad(prof);
}
hijos.add(hijo);
}
revisar.setHijos(hijos);//le pasamos la lista de hijos a un nodo padre
//usamos el Nodo revisar porque es el Padre de esos nodos hijos
revisar=listaAbierta.remove(0);
profundidad=calcularProfundidad(revisar);
}
return null;
}
public static void imprimirEstadoNodoRevisado(Nodo revisar, int[][] revis, int cantNodosRev)
{
int prof=0;
while(revisar.padre!=null)
{
revisar=revisar.padre;
prof++;
}
System.out.println("Siguiente Movimiento en la profundidad= "+prof);//nodo revisado
System.out.println("Cantidad de nodos explorados= "+cantNodosRev);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print("["+revis[i][j]+"]");
}
System.out.println("");
}
}
public static int[] ubicarPosicionCero(int[][] estado) {
int[] posicionCero=new int[2];//array de tamaño 2, xq guarda la posicion "i","j"
for (int i = 0; i < estado.length; i++) {
for (int j = 0; j < estado.length; j++) {
if (estado[i][j]==0) {
posicionCero[0]=i;
posicionCero[1]=j;
}
}
}
return posicionCero;
}
public static int[][] clonar(int[][] estado) {
int[][] clon=new int[estado.length][estado.length];
for (int i = 0; i < estado.length; i++) {
for (int j = 0; j < estado.length; j++) {
clon[i][j]=estado[i][j];
}
}
return clon;
}
public static boolean nodoRevisado(ArrayList<Nodo> listaCerrada, Nodo hijo) {
for(Nodo revisado:listaCerrada){ //lo que hacemos es recorrer todo el arraylist "nodosYaRevisados" y comparamos con el siguinte if
if(Arrays.deepEquals(revisado.getEstado(), hijo.getEstado())) //si dentro de revisado existe algun nodo igual al nodo hijo que se esta comparando
{
return true;
}
}
return false;//por defecto retorna false (el nodo hijo no fue yarevisado anteriormente
}
public static Nodo buscarSolucionProfundidad(Nodo inicial2, int[][] ConfFinal,int MAXProfundidad,int MAXNodosExplorados) {
ArrayList <Nodo> listaAbierta=new ArrayList<Nodo>();
ArrayList<Nodo> listaCerrada= new ArrayList<Nodo>();
listaAbierta.add(inicial2);
int cantidadDeNodosExplorados=0;
int profundidad=0;
double ramificacionMedio=0;
Nodo revisar=listaAbierta.remove(listaAbierta.size()-1);//con esto hacemos de cuenta que el ArrayList es una Pila(LIFO)
while(cantidadDeNodosExplorados<MAXNodosExplorados&&profundidad<=MAXProfundidad)
{
cantidadDeNodosExplorados++;
imprimirEstadoNodoRevisado(revisar,revisar.getEstado(),cantidadDeNodosExplorados);
int [] posicionDelCero=ubicarPosicionCero(revisar.getEstado());
listaCerrada.add(revisar);
ArrayList<Nodo> hijos=new ArrayList<Nodo>();
if(Arrays.deepEquals(revisar.getEstado(), ConfFinal)){
System.out.println("******* SOLUCION ENCONTRADA*********");
System.out.println("Informacion:");
System.out.println("> Cantidad de nodos Evaluados= "+listaCerrada.size());
profundidad=calcularProfundidad(revisar);
System.out.println("> Profundidad alcanzada: "+profundidad);
ramificacionMedio=(double)cantidadDeNodosExplorados/(double)calcularProfundidad(revisar);
System.out.println("> Ramificacion Medio= "+ramificacionMedio);
System.out.println("> Perfil de Ramificacion: ");
imprimirPerfilRamificacion(profundidad,listaCerrada );
return revisar;
}
if(posicionDelCero[0]!=0)
{
Nodo hijo=new Nodo(clonar(revisar.getEstado()));
int arriba=hijo.getEstado()[posicionDelCero[0]-1][posicionDelCero[1]];
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]]=arriba;
hijo.getEstado()[posicionDelCero[0]-1][posicionDelCero[1]]=0;
if(!nodoRevisado(listaCerrada,hijo))
{
hijo.setPadre(revisar);
listaAbierta.add(hijo);
profundidad=calcularProfundidad(hijo);
hijo.setProfundidad(profundidad);
}
hijos.add(hijo);
}
if(posicionDelCero[1]!=0)
{
Nodo hijo=new Nodo(clonar(revisar.getEstado()));
int izquierda=hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]-1];
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]]=izquierda;
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]-1]=0;
if(!nodoRevisado(listaCerrada,hijo))
{
hijo.setPadre(revisar);
listaAbierta.add(hijo);
profundidad=calcularProfundidad(hijo);
hijo.setProfundidad(profundidad);
}
hijos.add(hijo);
}
if(posicionDelCero[1]!=2)
{
Nodo hijo=new Nodo(clonar(revisar.getEstado()));
int derecha=hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]+1];
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]]=derecha;
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]+1]=0;
if(!nodoRevisado(listaCerrada,hijo))
{
hijo.setPadre(revisar);
listaAbierta.add(hijo);
profundidad=calcularProfundidad(hijo);
hijo.setProfundidad(profundidad);
}
hijos.add(hijo);
}
if(posicionDelCero[0]!=2)
{
Nodo hijo=new Nodo(clonar(revisar.getEstado()));
int abajo=hijo.getEstado()[posicionDelCero[0]+1][posicionDelCero[1]];//capturamos el valor que esta en la fila de abajo del cero
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]]=abajo;
hijo.getEstado()[posicionDelCero[0]+1][posicionDelCero[1]]=0;
if(!nodoRevisado(listaCerrada,hijo))
{
hijo.setPadre(revisar);
listaAbierta.add(hijo);
profundidad=calcularProfundidad(hijo);
hijo.setProfundidad(profundidad);
}
hijos.add(hijo);
}
revisar.setHijos(hijos);
revisar=listaAbierta.remove(listaAbierta.size()-1);//sacamos el ultimo nodo de la lista, es decir la convertimos en una PILA(FIFO)
profundidad=calcularProfundidad(revisar);
}
return null;
}
public static Nodo buscarSolucionPrimeroElMejor(Nodo inicial3, int[][] ConfFinal,int MAXProfundidad,int MAXNodosExplorados) {
ArrayList <Nodo> listaAbierta=new ArrayList<Nodo>();
ArrayList<Nodo> listaCerrada= new ArrayList<Nodo>();
listaAbierta.add(inicial3);
int cantidadDeNodosExplorados=0;
int profundidad=0;
int costo=0;
int costoTotal=0;
double ramificacionMedio=0;
Nodo revisar=listaAbierta.remove(0);
costo=calcularCosto(revisar.getEstado(), ConfFinal);
revisar.setCostoTotal(costo);
while(cantidadDeNodosExplorados<MAXNodosExplorados&&profundidad<=MAXProfundidad)
{
cantidadDeNodosExplorados++;
imprimirEstadoNodoPMejorCostos(revisar.getEstado(),revisar.getCostoTotal(),revisar,cantidadDeNodosExplorados);
int [] posicionDelCero=ubicarPosicionCero(revisar.getEstado());
listaCerrada.add(revisar);
ArrayList<Nodo> hijos=new ArrayList<Nodo>();
if(Arrays.deepEquals(revisar.getEstado(), ConfFinal)){
System.out.println("******* SOLUCION ENCONTRADA*********");
System.out.println("Informacion:");
System.out.println("> Cantidad de nodos Evaluados= "+listaCerrada.size());
profundidad=calcularProfundidad(revisar);
System.out.println("> Profundidad alcanzada: "+profundidad);
ramificacionMedio=(double)cantidadDeNodosExplorados/(double)calcularProfundidad(revisar);
System.out.println("> Ramificacion Medio= "+ramificacionMedio);
System.out.println("> Perfil de Ramificacion: ");
imprimirPerfilRamificacion(profundidad,listaCerrada );
return revisar;
}
if(posicionDelCero[0]!=0)
{
Nodo hijo=new Nodo(clonar(revisar.getEstado()));
int arriba=hijo.getEstado()[posicionDelCero[0]-1][posicionDelCero[1]];
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]]=arriba;
hijo.getEstado()[posicionDelCero[0]-1][posicionDelCero[1]]=0;
hijo.setPadre(revisar);
profundidad=calcularProfundidad(hijo);
hijo.setProfundidad(profundidad);
costo=calcularCosto(hijo.getEstado(), ConfFinal);
costoTotal=costo;
hijo.setCostoTotal(costo);
listaAbierta.add(hijo);
hijos.add(hijo);
}
if(posicionDelCero[0]!=2)
{
Nodo hijo=new Nodo(clonar(revisar.getEstado()));
int abajo=hijo.getEstado()[posicionDelCero[0]+1][posicionDelCero[1]];//capturamos el valor que esta en la fila de abajo del cero
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]]=abajo;
hijo.getEstado()[posicionDelCero[0]+1][posicionDelCero[1]]=0;
hijo.setPadre(revisar);
profundidad=calcularProfundidad(hijo);
hijo.setProfundidad(profundidad);
costo=calcularCosto(hijo.getEstado(), ConfFinal);
costoTotal=costo;
hijo.setCostoTotal(costo);
listaAbierta.add(hijo);
hijos.add(hijo);
}
if(posicionDelCero[1]!=0)
{
Nodo hijo=new Nodo(clonar(revisar.getEstado()));//le estamos pasando un nodo igual al de antes pero ahora lo modificamos com los movimientos
int izquierda=hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]-1];//capturamos el valor que esta en la fila de arriba de esa columna en la variable arriba
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]]=izquierda;//metemos en la posicion donde estaba el cero, el valor que estaba en la fila de arriba
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]-1]=0;//metemos en la fila de arriba el cero
hijo.setPadre(revisar);
profundidad=calcularProfundidad(hijo);
hijo.setProfundidad(profundidad);
costo=calcularCosto(hijo.getEstado(), ConfFinal);
costoTotal=costo;
hijo.setCostoTotal(costo);
listaAbierta.add(hijo);
hijos.add(hijo);
}
if(posicionDelCero[1]!=2)
{
Nodo hijo=new Nodo(clonar(revisar.getEstado()));
int derecha=hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]+1];//capturamos el valor que esta en la fila de abajo del cero
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]]=derecha;
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]+1]=0;
hijo.setPadre(revisar);
profundidad=calcularProfundidad(hijo);
hijo.setProfundidad(profundidad);
costo=calcularCosto(hijo.getEstado(), ConfFinal);
costoTotal=costo;
hijo.setCostoTotal(costo);
listaAbierta.add(hijo);
hijos.add(hijo);
}
revisar.setHijos(hijos);
Collections.sort(listaAbierta);//Ordena el ArrayList de acuerdo al "COSTO", asi el nodo hijo con menor costo se ubica primero para salir
revisar=listaAbierta.remove(0);
profundidad=calcularProfundidad(revisar);
}
return null;
}
public static int calcularCosto(int[][] hijo, int[][] ConfFinal) {
int c=0;
for (int i = 0; i < ConfFinal.length; i++) {
for (int j = 0; j < ConfFinal.length; j++) {
if(hijo[i][j]!=ConfFinal[i][j])
c++;
}
}
return c;
}
public static void imprimirEstadoNodoPMejorCostos(int[][] estado, int costoTotal, Nodo rev, int cantidadExplorados) {
int prof=0;
while(rev.padre!=null)
{
rev=rev.padre;
prof++;
}
System.out.println("Siguiente Movimiento en la profundidad= "+prof+", costo= "+costoTotal);
System.out.println("Cantidad de nodos explorados= "+cantidadExplorados);
for (int i = 0; i < estado.length; i++) {
for (int j = 0; j < estado.length; j++) {
System.out.print("["+estado[i][j]+"]");
}
System.out.println("");
}
}
public static void imprimirSolucion(int [][] sol) {
System.out.println("Proximo ");
for (int i = 0; i < sol.length; i++) {
for (int j = 0; j<sol.length; j++) {
System.out.print("["+sol[i][j]+"]");
}
System.out.println("");
}
}
public static Nodo buscarSolucionAestrella(Nodo inicial4, int[][] ConfFinal,int MAXProfundidad,int MAXNodosExplorados) {
ArrayList <Nodo> listaAbierta=new ArrayList<Nodo>();
ArrayList<Nodo> listaCerrada= new ArrayList<Nodo>();
listaAbierta.add(inicial4);
int cantidadDeNodosExplorados=0;
int profundidad=0;
int profMax=0;
int costo=0;
int costoAestrella=0;
double ramificacionMedio=0;
Nodo revisar=listaAbierta.remove(0);
costo=calcularCosto(revisar.getEstado(), ConfFinal);
revisar.setCosto(costo);
revisar.setProfundidad(profundidad);
costoAestrella=costo+profundidad;
revisar.setCostoTotal(costoAestrella);
while(cantidadDeNodosExplorados<MAXNodosExplorados&&profMax<=MAXProfundidad)
{
cantidadDeNodosExplorados++;
imprimirEstadoNodoAestrellaCostos(revisar.getEstado(),revisar.getCosto(),revisar.getProfundidad(),revisar.getCostoTotal(),cantidadDeNodosExplorados);
int [] posicionDelCero=ubicarPosicionCero(revisar.getEstado());
listaCerrada.add(revisar);
ArrayList<Nodo> hijos=new ArrayList<Nodo>();
if(Arrays.deepEquals(revisar.getEstado(), ConfFinal)){
System.out.println("******* SOLUCION ENCONTRADA*********");
System.out.println("Informacion:");
System.out.println("> Cantidad de nodos Evaluados= "+listaCerrada.size());
profundidad=calcularProfundidad(revisar);
System.out.println("> Profundidad alcanzada: "+profundidad);
ramificacionMedio=(double)cantidadDeNodosExplorados/(double)calcularProfundidad(revisar);
System.out.println("> Ramificacion Medio= "+ramificacionMedio);
System.out.println("> Perfil de Ramificacion: ");
imprimirPerfilRamificacion(profundidad,listaCerrada );
return revisar;
}
if(posicionDelCero[0]!=0)
{
Nodo hijo=new Nodo(clonar(revisar.getEstado()));
int arriba=hijo.getEstado()[posicionDelCero[0]-1][posicionDelCero[1]];
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]]=arriba;
hijo.getEstado()[posicionDelCero[0]-1][posicionDelCero[1]]=0;
hijo.setPadre(revisar);
costo=calcularCosto(hijo.getEstado(), ConfFinal);
hijo.setCosto(costo);
profundidad=calcularProfundidad(hijo);
hijo.setProfundidad(profundidad);
costoAestrella=costo+profundidad;
hijo.setCostoTotal(costoAestrella);
listaAbierta.add(hijo);
hijos.add(hijo);
}
if(posicionDelCero[0]!=2)
{
Nodo hijo=new Nodo(clonar(revisar.getEstado()));
int abajo=hijo.getEstado()[posicionDelCero[0]+1][posicionDelCero[1]];//capturamos el valor que esta en la fila de abajo del cero
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]]=abajo;
hijo.getEstado()[posicionDelCero[0]+1][posicionDelCero[1]]=0;
hijo.setPadre(revisar);
costo=calcularCosto(hijo.getEstado(), ConfFinal);
hijo.setCosto(costo);
profundidad=calcularProfundidad(hijo);
hijo.setProfundidad(profundidad);
costoAestrella=costo+profundidad;
hijo.setCostoTotal(costoAestrella);
listaAbierta.add(hijo);
hijos.add(hijo);
}
if(posicionDelCero[1]!=0)
{
Nodo hijo=new Nodo(clonar(revisar.getEstado()));//le estamos pasando un nodo igual al de antes pero ahora lo modificamos com los movimientos
int izquierda=hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]-1];//capturamos el valor que esta en la fila de arriba de esa columna en la variable arriba
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]]=izquierda;//metemos en la posicion donde estaba el cero, el valor que estaba en la fila de arriba
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]-1]=0;//metemos en la fila de arriba el cero
hijo.setPadre(revisar);
costo=calcularCosto(hijo.getEstado(), ConfFinal);
hijo.setCosto(costo);
profundidad=calcularProfundidad(hijo);
hijo.setProfundidad(profundidad);
costoAestrella=costo+profundidad;
hijo.setCostoTotal(costoAestrella);
listaAbierta.add(hijo);
hijos.add(hijo);
}
if(posicionDelCero[1]!=2)
{
Nodo hijo=new Nodo(clonar(revisar.getEstado()));
int derecha=hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]+1];//capturamos el valor que esta en la fila de abajo del cero
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]]=derecha;
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]+1]=0;
hijo.setPadre(revisar);
costo=calcularCosto(hijo.getEstado(), ConfFinal);
hijo.setCosto(costo);
profundidad=calcularProfundidad(hijo);
hijo.setProfundidad(profundidad);
costoAestrella=costo+profundidad;
hijo.setCostoTotal(costoAestrella);
listaAbierta.add(hijo);
hijos.add(hijo);
}
revisar.setHijos(hijos);
Collections.sort(listaAbierta);//Ordena el ArrayList de acuerdo al "COSTO", asi el nodo hijo con menor costo se ubica primero para salir
revisar=listaAbierta.remove(0);
profMax=calcularProfundidad(revisar);
}
return null;
}
public static void imprimirEstadoNodoAestrellaCostos(int[][] estado, int costo, Integer prof, Integer costoTotal, int cantidadExplorados) {
System.out.println("Siguiente Movimiento");
System.out.println("Costo= "+costo+",Profundidad= "+prof+",Costo Total= "+costoTotal);
System.out.println("Cantidad nodos explorados= "+cantidadExplorados);
for (int i = 0; i < estado.length; i++) {
for (int j = 0; j < estado.length; j++) {
System.out.print("["+estado[i][j]+"]");
}
System.out.println("");
}
}
public static int calcularProfundidad(Nodo hijo) {
int prof=0;
while(hijo.padre!=null)
{
hijo=hijo.padre;
prof++;
}
return prof;
}
public static void imprimirMatrices(int[][] ConfActual) {
int valor=0;
for (int i = 0; i < ConfActual.length; i++) {
for (int j = 0; j < ConfActual.length; j++) {
valor=ConfActual [i][j];
System.out.print("["+valor+"]");
}
System.out.println("");
}
}
public static void imprimirPerfilRamificacion(int profundidad, ArrayList<Nodo> listaCerrada) {
int prof=0;
int cantNodosEnNivelDeProf;
for (int i = 0; i <=profundidad; i++)
{
cantNodosEnNivelDeProf=0;
if(listaCerrada!=null)
{
for(Nodo n:listaCerrada)
{
prof=n.getProfundidad();
if(prof==i)
cantNodosEnNivelDeProf++;
}
}
System.out.println(" Cantidad de nodos en el nivel: "+i+" es de: "+cantNodosEnNivelDeProf);
}
}
public static Nodo buscarSolucionEscaladaMaxPendiente(Nodo inicial5, int[][] ConfFinal, int MAXProfundidad, int MAXNodosExplorados) {
ArrayList <Nodo> listaAbierta=new ArrayList<Nodo>();
ArrayList<Nodo> listaCerrada= new ArrayList<Nodo>();
listaAbierta.add(inicial5);
int cantidadDeNodosExplorados=0;
int profundidad=0;
int cantidadElementosBien=0;// cantidad de piezas bien colocadas
double ramificacionMedio=0;
Nodo revisar=listaAbierta.remove(0);
cantidadElementosBien=calcularCantElemBien(revisar.getEstado(), ConfFinal);
revisar.setCostoTotal(cantidadElementosBien);
while(cantidadDeNodosExplorados<MAXNodosExplorados&&profundidad<=MAXProfundidad)
{
cantidadDeNodosExplorados++;
imprimirEstadoNodoEscMaxPend(revisar.getEstado(),revisar.getCostoTotal(),revisar,cantidadDeNodosExplorados);
int [] posicionDelCero=ubicarPosicionCero(revisar.getEstado());
listaCerrada.add(revisar);
ArrayList<Nodo> hijos=new ArrayList<Nodo>();
if(Arrays.deepEquals(revisar.getEstado(), ConfFinal)){
System.out.println("******* SOLUCION ENCONTRADA*********");
System.out.println("Informacion:");
System.out.println("> Cantidad de nodos Evaluados= "+listaCerrada.size());
profundidad=calcularProfundidad(revisar);
System.out.println("> Profundidad alcanzada: "+profundidad);
ramificacionMedio=(double)cantidadDeNodosExplorados/(double)calcularProfundidad(revisar);
System.out.println("> Ramificacion Medio= "+ramificacionMedio);
System.out.println("> Perfil de Ramificacion: ");
imprimirPerfilRamificacion(profundidad,listaCerrada );
return revisar;
}
if(posicionDelCero[0]!=0)
{
Nodo hijo=new Nodo(clonar(revisar.getEstado()));
int arriba=hijo.getEstado()[posicionDelCero[0]-1][posicionDelCero[1]];
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]]=arriba;
hijo.getEstado()[posicionDelCero[0]-1][posicionDelCero[1]]=0;
hijo.setPadre(revisar);
profundidad=calcularProfundidad(hijo);
hijo.setProfundidad(profundidad);
cantidadElementosBien=calcularCantElemBien(hijo.getEstado(), ConfFinal);
hijo.setCostoTotal(cantidadElementosBien);
listaAbierta.add(hijo);
hijos.add(hijo);
}
if(posicionDelCero[0]!=2)
{
Nodo hijo=new Nodo(clonar(revisar.getEstado()));
int abajo=hijo.getEstado()[posicionDelCero[0]+1][posicionDelCero[1]];//capturamos el valor que esta en la fila de abajo del cero
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]]=abajo;
hijo.getEstado()[posicionDelCero[0]+1][posicionDelCero[1]]=0;
hijo.setPadre(revisar);
profundidad=calcularProfundidad(hijo);
hijo.setProfundidad(profundidad);
cantidadElementosBien=calcularCantElemBien(hijo.getEstado(), ConfFinal);
hijo.setCostoTotal(cantidadElementosBien);
listaAbierta.add(hijo);
hijos.add(hijo);
}
if(posicionDelCero[1]!=0)
{
Nodo hijo=new Nodo(clonar(revisar.getEstado()));//le estamos pasando un nodo igual al de antes pero ahora lo modificamos com los movimientos
int izquierda=hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]-1];//capturamos el valor que esta en la fila de arriba de esa columna en la variable arriba
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]]=izquierda;//metemos en la posicion donde estaba el cero, el valor que estaba en la fila de arriba
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]-1]=0;//metemos en la fila de arriba el cero
hijo.setPadre(revisar);
profundidad=calcularProfundidad(hijo);
hijo.setProfundidad(profundidad);
cantidadElementosBien=calcularCantElemBien(hijo.getEstado(), ConfFinal);
hijo.setCostoTotal(cantidadElementosBien);
listaAbierta.add(hijo);
hijos.add(hijo);
}
if(posicionDelCero[1]!=2)
{
Nodo hijo=new Nodo(clonar(revisar.getEstado()));
int derecha=hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]+1];//capturamos el valor que esta en la fila de abajo del cero
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]]=derecha;
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]+1]=0;
hijo.setPadre(revisar);
profundidad=calcularProfundidad(hijo);
hijo.setProfundidad(profundidad);
cantidadElementosBien=calcularCantElemBien(hijo.getEstado(), ConfFinal);
hijo.setCostoTotal(cantidadElementosBien);
listaAbierta.add(hijo);
hijos.add(hijo);
}
revisar.setHijos(hijos);
Collections.sort(listaAbierta, Collections.reverseOrder());//Ordena el ArrayList de modo Ascendente
Nodo mejorHijo=listaAbierta.remove(0);
if (mejorHijo.getCostoTotal()<revisar.getCostoTotal()) {
System.out.println("No existe un nodo mejor que el actual");
break;
}
revisar=mejorHijo;
profundidad=calcularProfundidad(revisar);
listaAbierta.clear();//borro los hijos del nodo anterior
}
return null;
}
public static int calcularCantElemBien(int[][] estado, int[][] ConfFinal) {
int c=0;
for (int i = 0; i < ConfFinal.length; i++) {
for (int j = 0; j < ConfFinal.length; j++) {
if(estado[i][j]==ConfFinal[i][j])
c++;
}
}
return c;
}
public static void imprimirEstadoNodoEscMaxPend(int[][] estado, Integer costoTotal, Nodo revisar, int cantidadDeNodosExplorados) {
int prof=0;
while(revisar.padre!=null)
{
revisar=revisar.padre;
prof++;
}
System.out.println("Siguiente Movimiento en la profundidad= "+prof+", piezas bien colocadas= "+costoTotal);
System.out.println("Cantidad de nodos explorados= "+cantidadDeNodosExplorados);
for (int i = 0; i < estado.length; i++) {
for (int j = 0; j < estado.length; j++) {
System.out.print("["+estado[i][j]+"]");
}
System.out.println("");
}
}
}
| UTF-8 | Java | 54,167 | java | Puzzle9IUA_Prueba.java | Java | [
{
"context": "Arrays;\nimport java.util.Collections;\n\n//* @author Angelino Marcio, Pavon Rosenthal Joel\n \npublic class Puzzle9IUA_P",
"end": 165,
"score": 0.999875009059906,
"start": 150,
"tag": "NAME",
"value": "Angelino Marcio"
},
{
"context": "va.util.Collections;\n\n//* @author Angelino Marcio, Pavon Rosenthal Joel\n \npublic class Puzzle9IUA_Prueba {\n\n public st",
"end": 187,
"score": 0.9997327923774719,
"start": 167,
"tag": "NAME",
"value": "Pavon Rosenthal Joel"
}
] | null | [] |
package puzzle9iua_Prueba;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
//* @author <NAME>, <NAME>
public class Puzzle9IUA_Prueba {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); //crear un objeto Scanner
int opcion=0;
int [][] ConfInicial= {{1,2,3},{0,5,6},{4,7,8}};//new int[3][3]; //creamos un array bidimensional (3x3), corresponde a la Conf Inicial
int [][] ConfFinal={{1,2,3},{4,5,6},{7,8,0}};//new int [3][3]; //creamos un array bidimensional, corresponde a la Conf Final
int [][] ConfInicialAnterior= {{1,2,3},{0,5,6},{4,7,8}}; //iniciamos el array con valores predefinidos
//luego de que se carguen valores en los anteriores, estos adquirirán dichos valores.
int [][] ConfFinalAnterior={{1,2,3},{4,5,6},{7,8,0}};
int fila=3, columna=3, profundidad=0, operacion=0, MAXProfundidad=0, MAXNodosExplorados=0 ;
double SinLimites=0;
Nodo solucion;
System.out.println("************************************************");
System.out.println(" PUZZLE IUA ");
System.out.println("************************************************");
System.out.println("La Matriz del Puzzle será la siguiente");
System.out.println(" [1er valor][2do valor][3er valor] ");
System.out.println(" [4to valor][5to valor][6to valor] ");
System.out.println(" [7mo valor][8vo valor][9no valor] ");
System.out.println("");
System.out.println("Caracterisitcas del Juego:");
System.out.println("-Solo se permite ingresar valores del 0-8");
System.out.println("-Al valor 0 se lo considera como Espacio/Comodín");
System.out.println("*************************************************");
System.out.println("------------------------MENU-----------------------");
System.out.println("1_ Ingresar valores al Juego, configuracion Inicial y Final(SOLUCION) ");
System.out.println("2_ Utilizar la ultima configuracion Inicial y Final usada ");
System.out.println("3_ Resolver con Primero en Anchura");
System.out.println("4_ Resolver con Primero en Profundidad ");
System.out.println("5_ Resolver con Primero el Mejor ");
System.out.println("6_ Resolver con A* ");
System.out.println("7_ Resolver con Escalada con Máxima Pendiente ");
System.out.println("Salir (0)");
opcion=sc.nextInt();
while(opcion!=0){
switch (opcion)
{
case 1:
//ANTES DE INGRESAR NUEVOS VALORES A LA MATRIZ, GUARDAMOS LA CONFIG ANTERIOR.
for (int i = 0; i < fila; i++) {
for (int j = 0; j < columna; j++) {
ConfInicialAnterior[i][j]=ConfInicial[i][j];
}
}
for (int i = 0; i < fila; i++) {
for (int j = 0; j < columna; j++) {
ConfFinalAnterior[i][j]=ConfFinal[i][j];
}
}
///////////////////////////////////////////////////////////////////////
System.out.println("Ingrese los valores de la Configuracion Inicial:");
for (int i = 0; i < fila; i++) { //recorremos por fila, i=fila.
System.out.println("Fila "+i);
for (int j = 0; j < columna; j++) {// recorremos por columna, j=columna.
System.out.print("valor: ");
ConfInicial [i][j]=sc.nextInt();//asignamos el valor ingresado a dicha fila y columna.
//primero carga todas las columnas de la primer fila y despues pasa a la siguiente fila
}
System.out.println("");
}
System.out.println("Ingrese los valores de la Configuracion Final:");
for (int i = 0; i < fila; i++) {
System.out.println("Fila "+i);
for (int j = 0; j < columna; j++) {
System.out.print("valor: ");
ConfFinal [i][j]=sc.nextInt();
}
System.out.println("");
}
System.out.println("Matriz Inicial sera:");
imprimirMatrices(ConfInicial);
System.out.println("Matriz Final/Solucion sera:");
imprimirMatrices(ConfFinal);
break;
case 2:
System.out.println("Los ultimos valores utilizados son:");
System.out.println("Matriz Inicial:");
for (int i = 0; i < fila; i++) {
for (int j = 0; j < columna; j++) {
System.out.print("["+ConfInicialAnterior[i][j]+"]");
ConfInicial[i][j]=ConfInicialAnterior[i][j];
}
System.out.println("");
}
System.out.println("Matriz Final/Solucion:");
for (int i = 0; i < fila; i++) {
for (int j = 0; j < columna; j++) {
System.out.print("["+ConfFinalAnterior[i][j]+"]");
ConfFinal[i][j]=ConfFinalAnterior[i][j];
}
System.out.println("");
}
break;
case 3:
//lo primero que necesitamos hacer para buscar la solucion es convertir el
//array ConfInicial en un nodo el cual sera el nodo origen (el primero)
Nodo inicial=new Nodo(ConfInicial);
System.out.println("Profundidad MAXIMA: ");
MAXProfundidad=sc.nextInt();
System.out.println("Cantidad MAXIMA de Nodos Explorar: ");
MAXNodosExplorados=sc.nextInt();
System.out.println("---------Paso Por Paso----------");
solucion=buscarSolucionAnchura(inicial, ConfFinal,MAXProfundidad,MAXNodosExplorados );
if(solucion==null)
System.out.println("NO SE ENCONTRO SOLUCION DENTRO DE LOS LIMITES ESTABLECIDOS");
else
{
System.out.println("--------EL CAMINO A LA SOLUCION ES------------ ");
while(solucion.padre!=null)
{
imprimirSolucion(solucion.getEstado());
solucion=solucion.padre;
}
System.out.println("Nodo inicial:");
for (int i = 0; i < fila; i++) {
for (int j = 0; j < columna; j++) {
System.out.print("["+ConfInicial[i][j]+"]");
}
System.out.println("");
}
}
break;
case 4:
Nodo inicial2=new Nodo(ConfInicial);
System.out.println("Profundidad MAXIMA: ");
MAXProfundidad=sc.nextInt();
System.out.println("Cantidad MAXIMA de Nodos a Explorar: ");
MAXNodosExplorados=sc.nextInt();
System.out.println("---------Paso Por Paso----------");
solucion=buscarSolucionProfundidad(inicial2, ConfFinal,MAXProfundidad,MAXNodosExplorados );
if(solucion==null)
System.out.println("NO SE ENCONTRO SOLUCION DENTRO DE LOS LIMITES ESTABLECIDOS");
else
{
System.out.println("--------EL CAMINO A LA SOLUCION ES------------ ");
while(solucion.padre!=null)
{
imprimirSolucion(solucion.getEstado());
solucion=solucion.padre;
}
System.out.println("Nodo inicial:");
for (int i = 0; i < fila; i++) {
for (int j = 0; j < columna; j++) {
System.out.print("["+ConfInicial[i][j]+"]");
}
System.out.println("");
}
}
break;
case 5:
Nodo inicial3=new Nodo(ConfInicial);
System.out.println("Profundidad MAXIMA: ");
MAXProfundidad=sc.nextInt();
System.out.println("Cantidad MAXIMA de Nodos a Explorar: ");
MAXNodosExplorados=sc.nextInt();
System.out.println("---------Paso Por Paso----------");
solucion=buscarSolucionPrimeroElMejor(inicial3, ConfFinal,MAXProfundidad,MAXNodosExplorados );
if(solucion==null)
System.out.println("NO SE ENCONTRO SOLUCION DENTRO DE LOS LIMITES ESTABLECIDOS");
else
{
System.out.println("--------EL CAMINO A LA SOLUCION ES------------ ");
while(solucion.padre!=null)
{
imprimirSolucion(solucion.getEstado());
solucion=solucion.padre;
}
System.out.println("Nodo inicial:");
for (int i = 0; i < fila; i++) {
for (int j = 0; j < columna; j++) {
System.out.print("["+ConfInicial[i][j]+"]");
}
System.out.println("");
}
}
break;
case 6:
Nodo inicial4=new Nodo(ConfInicial);
System.out.println("Profundidad MAXIMA: ");
MAXProfundidad=sc.nextInt();
System.out.println("Cantidad MAXIMA de Nodos a Explorar: ");
MAXNodosExplorados=sc.nextInt();
System.out.println("---------Paso Por Paso----------");
solucion=buscarSolucionAestrella(inicial4, ConfFinal,MAXProfundidad,MAXNodosExplorados );
if(solucion==null)
System.out.println("NO SE ENCONTRO SOLUCION DENTRO DE LOS LIMITES ESTABLECIDOS");
else
{
System.out.println("--------EL CAMINO A LA SOLUCION ES------------ ");
while(solucion.padre!=null)
{
imprimirSolucion(solucion.getEstado());
solucion=solucion.padre;
}
System.out.println("Nodo inicial:");
for (int i = 0; i < fila; i++) {
for (int j = 0; j < columna; j++) {
System.out.print("["+ConfInicial[i][j]+"]");
}
System.out.println("");
}
}
break;
case 7:
Nodo inicial5=new Nodo(ConfInicial);
System.out.println("Profundidad MAXIMA: ");
MAXProfundidad=sc.nextInt();
System.out.println("Cantidad MAXIMA de Nodos a Explorar: ");
MAXNodosExplorados=sc.nextInt();
System.out.println("---------Paso Por Paso----------");
solucion=buscarSolucionEscaladaMaxPendiente(inicial5, ConfFinal,MAXProfundidad,MAXNodosExplorados );
if(solucion==null)
{ System.out.println("NO SE ENCONTRO SOLUCION");
}
else
{
System.out.println("--------EL CAMINO A LA SOLUCION ES------------ ");
while(solucion.padre!=null)
{
imprimirSolucion(solucion.getEstado());
solucion=solucion.padre;
}
System.out.println("Nodo inicial:");
for (int i = 0; i < fila; i++) {
for (int j = 0; j < columna; j++) {
System.out.print("["+ConfInicial[i][j]+"]");
}
System.out.println("");
}
}
break;
default:
break;
}
System.out.println("------------------------MENU-----------------------");
System.out.println("1_ Ingresar valores al Juego, configuracion Inicial y Final(SOLUCION) ");
System.out.println("2_ Utilizar la ultima configuracion Inicial y Final usada ");
System.out.println("3_ Resolver con Primero en Anchura");
System.out.println("4_ Resolver con Primero en Profundidad ");
System.out.println("5_ Resolver con Primero el Mejor ");
System.out.println("6_ Resolver con A* ");
System.out.println("7_ Resolver con Escalada con Máxima Pendiente ");
System.out.println("Salir (0)");
opcion=sc.nextInt();
}
}
// es un metodo static porque nos permite instanciar SIN crear un objeto de la clase
public static Nodo buscarSolucionAnchura(Nodo inicial, int[][] ConfFinal,int MAXProfundidad, int MAXNodosExplorados){
// el metodo va a necesitar que le pasemos un Nodo inicial y un array bidirecc. con la solucion
ArrayList <Nodo> listaAbierta=new ArrayList<Nodo>();//guarda todos los nodos que se van a
//ir explorando/expandiendo, y el primer nodo que tiene que ser explorado es el Nodo inicial
ArrayList<Nodo> listaCerrada= new ArrayList<Nodo>();
int profundidad=0;//el nodo inicial se encuentra en la profundidad 0
inicial.setProfundidad(profundidad);
listaAbierta.add(inicial);
int cantidadDeNodosExplorados=0;
int prof=0;
Nodo revisar=listaAbierta.remove(0);//asigna el nodo inicial al nodo que vamos a revisar
double ramificacionMedio=0;
while(cantidadDeNodosExplorados<MAXNodosExplorados&&profundidad<=MAXProfundidad){
// Nodo revisar=nodosExplorados.remove(0);//lo que hacemos es ir sacando del ArrayList a cada nodo para despues poder compararlo con la ConfFinal
//el nodo que vamos a sacar es el que esta en la primera posicion, por ende se va a comportar como una COLA (FIFO)
cantidadDeNodosExplorados++;
imprimirEstadoNodoRevisado(revisar,revisar.getEstado(),cantidadDeNodosExplorados);//el .getEstado va a convertir el nodo en un array bidir [][]
int [] posicionDelCero=ubicarPosicionCero(revisar.getEstado());//posicion en el array[][] donde se ubica el cero
//asi a partir de ello sabremos cuantos movimientos puede hacer el juego si el cero esta en el centro del array[][] entonces puede hacer 4 movimientos
//arriba-abajo-derecha-izquierda, pero si esta en una punta solo dos movimientos
listaCerrada.add(revisar);
ArrayList<Nodo> hijos=new ArrayList<Nodo>();//creamos una lista de hijos que va a tener un nodo
if(Arrays.deepEquals(revisar.getEstado(), ConfFinal)){//condicion de parada si el nodo que estamos revisando es igual a la solucion parar
System.out.println("******* SOLUCION ENCONTRADA*********");
System.out.println("Informacion:");
System.out.println("> Cantidad de nodos Evaluados= "+listaCerrada.size());
profundidad=calcularProfundidad(revisar);
System.out.println("> Profundidad alcanzada: "+profundidad);
ramificacionMedio=(double)cantidadDeNodosExplorados/(double)calcularProfundidad(revisar);
System.out.println("> Ramificacion Medio= "+ramificacionMedio);
System.out.println("> Perfil de Ramificacion: ");
imprimirPerfilRamificacion(profundidad,listaCerrada );
return revisar;//retorna el ultimo nodo explorado
}
//A continuacion empezamos a crear los hijos del nodo
if(posicionDelCero[0]!=0) //si la posicion del cero en las filas (posicion[0] es fila, pos[1]columna)
//es diferente de cero va a poder crear un hijo con un movimiento hacia arriba o abajo(sube una fila o baja)
{
Nodo hijo=new Nodo(clonar(revisar.getEstado()));//le estamos pasando un nodo igual al de antes pero ahora lo modificamos com los movimientos
int arriba=hijo.getEstado()[posicionDelCero[0]-1][posicionDelCero[1]];//capturamos el valor que esta en la fila de arriba de esa columna en la variable arriba
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]]=arriba;//metemos en la posicion donde estaba el cero, el valor que estaba en la fila de arriba
hijo.getEstado()[posicionDelCero[0]-1][posicionDelCero[1]]=0;//metemos en la fila de arriba el cero
if(!nodoRevisado(listaCerrada,hijo))//el metodo verifica si el hijo que estamos por expandir ya fue creado por otro nodo, si es asi no lo expandimos porque ya fue creado(ahorramos movimientos, no repetimos nodos)
{
hijo.setPadre(revisar);//creamos punteros a “revisar” en todos sus sucesores, de forma que pueda conocerse en todos ellos la identidad de su antecesor
//si no le asignamos un padre a cada hijo no vamos a poder usar el metodo imprimirPerfilRamificacion
listaAbierta.add(hijo);//metemos en el array de nodos explorados este nuevo nodo hijo para que luego se evalue
prof=calcularProfundidad(hijo);
hijo.setProfundidad(prof);
}
hijos.add(hijo);//el hijo que creo lo guardo en la lista hijos
}
if(posicionDelCero[0]!=2)//como el puzzle es de 3x3 solo llega hasta la fila 2(0,1,2) entonces le decimos que si no es 2 que baje para crear el otro hijo
{
Nodo hijo=new Nodo(clonar(revisar.getEstado()));
int abajo=hijo.getEstado()[posicionDelCero[0]+1][posicionDelCero[1]];//capturamos el valor que esta en la fila de abajo del cero
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]]=abajo;
hijo.getEstado()[posicionDelCero[0]+1][posicionDelCero[1]]=0;
if(!nodoRevisado(listaCerrada,hijo))
{
hijo.setPadre(revisar);
listaAbierta.add(hijo);
prof=calcularProfundidad(hijo);
hijo.setProfundidad(prof);
}
hijos.add(hijo);
}
//Ahora cambiamos los valores en la misma fila donde esta ubicado el cero, osea movimiento a izq y derecha
if(posicionDelCero[1]!=0) //no pasarme por izquierda
{
Nodo hijo=new Nodo(clonar(revisar.getEstado()));//le estamos pasando un nodo igual al de antes pero ahora lo modificamos com los movimientos
int izquierda=hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]-1];//capturamos el valor que esta en la fila de arriba de esa columna en la variable arriba
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]]=izquierda;//metemos en la posicion donde estaba el cero, el valor que estaba en la fila de arriba
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]-1]=0;//metemos en la fila de arriba el cero
if(!nodoRevisado(listaCerrada,hijo))
{
hijo.setPadre(revisar);
listaAbierta.add(hijo);
prof=calcularProfundidad(hijo);
hijo.setProfundidad(prof);
}//metemos en el array de nodos explorados este nuevo nodo hijo para que luego se evalue
hijos.add(hijo);
}
if(posicionDelCero[1]!=2)//no pasarme por derecha
{
Nodo hijo=new Nodo(clonar(revisar.getEstado()));
int derecha=hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]+1];//capturamos el valor que esta en la fila de abajo del cero
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]]=derecha;
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]+1]=0;
if(!nodoRevisado(listaCerrada,hijo))
{
hijo.setPadre(revisar);
listaAbierta.add(hijo);
prof=calcularProfundidad(hijo);
hijo.setProfundidad(prof);
}
hijos.add(hijo);
}
revisar.setHijos(hijos);//le pasamos la lista de hijos a un nodo padre
//usamos el Nodo revisar porque es el Padre de esos nodos hijos
revisar=listaAbierta.remove(0);
profundidad=calcularProfundidad(revisar);
}
return null;
}
public static void imprimirEstadoNodoRevisado(Nodo revisar, int[][] revis, int cantNodosRev)
{
int prof=0;
while(revisar.padre!=null)
{
revisar=revisar.padre;
prof++;
}
System.out.println("Siguiente Movimiento en la profundidad= "+prof);//nodo revisado
System.out.println("Cantidad de nodos explorados= "+cantNodosRev);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print("["+revis[i][j]+"]");
}
System.out.println("");
}
}
public static int[] ubicarPosicionCero(int[][] estado) {
int[] posicionCero=new int[2];//array de tamaño 2, xq guarda la posicion "i","j"
for (int i = 0; i < estado.length; i++) {
for (int j = 0; j < estado.length; j++) {
if (estado[i][j]==0) {
posicionCero[0]=i;
posicionCero[1]=j;
}
}
}
return posicionCero;
}
public static int[][] clonar(int[][] estado) {
int[][] clon=new int[estado.length][estado.length];
for (int i = 0; i < estado.length; i++) {
for (int j = 0; j < estado.length; j++) {
clon[i][j]=estado[i][j];
}
}
return clon;
}
public static boolean nodoRevisado(ArrayList<Nodo> listaCerrada, Nodo hijo) {
for(Nodo revisado:listaCerrada){ //lo que hacemos es recorrer todo el arraylist "nodosYaRevisados" y comparamos con el siguinte if
if(Arrays.deepEquals(revisado.getEstado(), hijo.getEstado())) //si dentro de revisado existe algun nodo igual al nodo hijo que se esta comparando
{
return true;
}
}
return false;//por defecto retorna false (el nodo hijo no fue yarevisado anteriormente
}
public static Nodo buscarSolucionProfundidad(Nodo inicial2, int[][] ConfFinal,int MAXProfundidad,int MAXNodosExplorados) {
ArrayList <Nodo> listaAbierta=new ArrayList<Nodo>();
ArrayList<Nodo> listaCerrada= new ArrayList<Nodo>();
listaAbierta.add(inicial2);
int cantidadDeNodosExplorados=0;
int profundidad=0;
double ramificacionMedio=0;
Nodo revisar=listaAbierta.remove(listaAbierta.size()-1);//con esto hacemos de cuenta que el ArrayList es una Pila(LIFO)
while(cantidadDeNodosExplorados<MAXNodosExplorados&&profundidad<=MAXProfundidad)
{
cantidadDeNodosExplorados++;
imprimirEstadoNodoRevisado(revisar,revisar.getEstado(),cantidadDeNodosExplorados);
int [] posicionDelCero=ubicarPosicionCero(revisar.getEstado());
listaCerrada.add(revisar);
ArrayList<Nodo> hijos=new ArrayList<Nodo>();
if(Arrays.deepEquals(revisar.getEstado(), ConfFinal)){
System.out.println("******* SOLUCION ENCONTRADA*********");
System.out.println("Informacion:");
System.out.println("> Cantidad de nodos Evaluados= "+listaCerrada.size());
profundidad=calcularProfundidad(revisar);
System.out.println("> Profundidad alcanzada: "+profundidad);
ramificacionMedio=(double)cantidadDeNodosExplorados/(double)calcularProfundidad(revisar);
System.out.println("> Ramificacion Medio= "+ramificacionMedio);
System.out.println("> Perfil de Ramificacion: ");
imprimirPerfilRamificacion(profundidad,listaCerrada );
return revisar;
}
if(posicionDelCero[0]!=0)
{
Nodo hijo=new Nodo(clonar(revisar.getEstado()));
int arriba=hijo.getEstado()[posicionDelCero[0]-1][posicionDelCero[1]];
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]]=arriba;
hijo.getEstado()[posicionDelCero[0]-1][posicionDelCero[1]]=0;
if(!nodoRevisado(listaCerrada,hijo))
{
hijo.setPadre(revisar);
listaAbierta.add(hijo);
profundidad=calcularProfundidad(hijo);
hijo.setProfundidad(profundidad);
}
hijos.add(hijo);
}
if(posicionDelCero[1]!=0)
{
Nodo hijo=new Nodo(clonar(revisar.getEstado()));
int izquierda=hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]-1];
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]]=izquierda;
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]-1]=0;
if(!nodoRevisado(listaCerrada,hijo))
{
hijo.setPadre(revisar);
listaAbierta.add(hijo);
profundidad=calcularProfundidad(hijo);
hijo.setProfundidad(profundidad);
}
hijos.add(hijo);
}
if(posicionDelCero[1]!=2)
{
Nodo hijo=new Nodo(clonar(revisar.getEstado()));
int derecha=hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]+1];
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]]=derecha;
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]+1]=0;
if(!nodoRevisado(listaCerrada,hijo))
{
hijo.setPadre(revisar);
listaAbierta.add(hijo);
profundidad=calcularProfundidad(hijo);
hijo.setProfundidad(profundidad);
}
hijos.add(hijo);
}
if(posicionDelCero[0]!=2)
{
Nodo hijo=new Nodo(clonar(revisar.getEstado()));
int abajo=hijo.getEstado()[posicionDelCero[0]+1][posicionDelCero[1]];//capturamos el valor que esta en la fila de abajo del cero
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]]=abajo;
hijo.getEstado()[posicionDelCero[0]+1][posicionDelCero[1]]=0;
if(!nodoRevisado(listaCerrada,hijo))
{
hijo.setPadre(revisar);
listaAbierta.add(hijo);
profundidad=calcularProfundidad(hijo);
hijo.setProfundidad(profundidad);
}
hijos.add(hijo);
}
revisar.setHijos(hijos);
revisar=listaAbierta.remove(listaAbierta.size()-1);//sacamos el ultimo nodo de la lista, es decir la convertimos en una PILA(FIFO)
profundidad=calcularProfundidad(revisar);
}
return null;
}
public static Nodo buscarSolucionPrimeroElMejor(Nodo inicial3, int[][] ConfFinal,int MAXProfundidad,int MAXNodosExplorados) {
ArrayList <Nodo> listaAbierta=new ArrayList<Nodo>();
ArrayList<Nodo> listaCerrada= new ArrayList<Nodo>();
listaAbierta.add(inicial3);
int cantidadDeNodosExplorados=0;
int profundidad=0;
int costo=0;
int costoTotal=0;
double ramificacionMedio=0;
Nodo revisar=listaAbierta.remove(0);
costo=calcularCosto(revisar.getEstado(), ConfFinal);
revisar.setCostoTotal(costo);
while(cantidadDeNodosExplorados<MAXNodosExplorados&&profundidad<=MAXProfundidad)
{
cantidadDeNodosExplorados++;
imprimirEstadoNodoPMejorCostos(revisar.getEstado(),revisar.getCostoTotal(),revisar,cantidadDeNodosExplorados);
int [] posicionDelCero=ubicarPosicionCero(revisar.getEstado());
listaCerrada.add(revisar);
ArrayList<Nodo> hijos=new ArrayList<Nodo>();
if(Arrays.deepEquals(revisar.getEstado(), ConfFinal)){
System.out.println("******* SOLUCION ENCONTRADA*********");
System.out.println("Informacion:");
System.out.println("> Cantidad de nodos Evaluados= "+listaCerrada.size());
profundidad=calcularProfundidad(revisar);
System.out.println("> Profundidad alcanzada: "+profundidad);
ramificacionMedio=(double)cantidadDeNodosExplorados/(double)calcularProfundidad(revisar);
System.out.println("> Ramificacion Medio= "+ramificacionMedio);
System.out.println("> Perfil de Ramificacion: ");
imprimirPerfilRamificacion(profundidad,listaCerrada );
return revisar;
}
if(posicionDelCero[0]!=0)
{
Nodo hijo=new Nodo(clonar(revisar.getEstado()));
int arriba=hijo.getEstado()[posicionDelCero[0]-1][posicionDelCero[1]];
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]]=arriba;
hijo.getEstado()[posicionDelCero[0]-1][posicionDelCero[1]]=0;
hijo.setPadre(revisar);
profundidad=calcularProfundidad(hijo);
hijo.setProfundidad(profundidad);
costo=calcularCosto(hijo.getEstado(), ConfFinal);
costoTotal=costo;
hijo.setCostoTotal(costo);
listaAbierta.add(hijo);
hijos.add(hijo);
}
if(posicionDelCero[0]!=2)
{
Nodo hijo=new Nodo(clonar(revisar.getEstado()));
int abajo=hijo.getEstado()[posicionDelCero[0]+1][posicionDelCero[1]];//capturamos el valor que esta en la fila de abajo del cero
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]]=abajo;
hijo.getEstado()[posicionDelCero[0]+1][posicionDelCero[1]]=0;
hijo.setPadre(revisar);
profundidad=calcularProfundidad(hijo);
hijo.setProfundidad(profundidad);
costo=calcularCosto(hijo.getEstado(), ConfFinal);
costoTotal=costo;
hijo.setCostoTotal(costo);
listaAbierta.add(hijo);
hijos.add(hijo);
}
if(posicionDelCero[1]!=0)
{
Nodo hijo=new Nodo(clonar(revisar.getEstado()));//le estamos pasando un nodo igual al de antes pero ahora lo modificamos com los movimientos
int izquierda=hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]-1];//capturamos el valor que esta en la fila de arriba de esa columna en la variable arriba
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]]=izquierda;//metemos en la posicion donde estaba el cero, el valor que estaba en la fila de arriba
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]-1]=0;//metemos en la fila de arriba el cero
hijo.setPadre(revisar);
profundidad=calcularProfundidad(hijo);
hijo.setProfundidad(profundidad);
costo=calcularCosto(hijo.getEstado(), ConfFinal);
costoTotal=costo;
hijo.setCostoTotal(costo);
listaAbierta.add(hijo);
hijos.add(hijo);
}
if(posicionDelCero[1]!=2)
{
Nodo hijo=new Nodo(clonar(revisar.getEstado()));
int derecha=hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]+1];//capturamos el valor que esta en la fila de abajo del cero
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]]=derecha;
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]+1]=0;
hijo.setPadre(revisar);
profundidad=calcularProfundidad(hijo);
hijo.setProfundidad(profundidad);
costo=calcularCosto(hijo.getEstado(), ConfFinal);
costoTotal=costo;
hijo.setCostoTotal(costo);
listaAbierta.add(hijo);
hijos.add(hijo);
}
revisar.setHijos(hijos);
Collections.sort(listaAbierta);//Ordena el ArrayList de acuerdo al "COSTO", asi el nodo hijo con menor costo se ubica primero para salir
revisar=listaAbierta.remove(0);
profundidad=calcularProfundidad(revisar);
}
return null;
}
public static int calcularCosto(int[][] hijo, int[][] ConfFinal) {
int c=0;
for (int i = 0; i < ConfFinal.length; i++) {
for (int j = 0; j < ConfFinal.length; j++) {
if(hijo[i][j]!=ConfFinal[i][j])
c++;
}
}
return c;
}
public static void imprimirEstadoNodoPMejorCostos(int[][] estado, int costoTotal, Nodo rev, int cantidadExplorados) {
int prof=0;
while(rev.padre!=null)
{
rev=rev.padre;
prof++;
}
System.out.println("Siguiente Movimiento en la profundidad= "+prof+", costo= "+costoTotal);
System.out.println("Cantidad de nodos explorados= "+cantidadExplorados);
for (int i = 0; i < estado.length; i++) {
for (int j = 0; j < estado.length; j++) {
System.out.print("["+estado[i][j]+"]");
}
System.out.println("");
}
}
public static void imprimirSolucion(int [][] sol) {
System.out.println("Proximo ");
for (int i = 0; i < sol.length; i++) {
for (int j = 0; j<sol.length; j++) {
System.out.print("["+sol[i][j]+"]");
}
System.out.println("");
}
}
public static Nodo buscarSolucionAestrella(Nodo inicial4, int[][] ConfFinal,int MAXProfundidad,int MAXNodosExplorados) {
ArrayList <Nodo> listaAbierta=new ArrayList<Nodo>();
ArrayList<Nodo> listaCerrada= new ArrayList<Nodo>();
listaAbierta.add(inicial4);
int cantidadDeNodosExplorados=0;
int profundidad=0;
int profMax=0;
int costo=0;
int costoAestrella=0;
double ramificacionMedio=0;
Nodo revisar=listaAbierta.remove(0);
costo=calcularCosto(revisar.getEstado(), ConfFinal);
revisar.setCosto(costo);
revisar.setProfundidad(profundidad);
costoAestrella=costo+profundidad;
revisar.setCostoTotal(costoAestrella);
while(cantidadDeNodosExplorados<MAXNodosExplorados&&profMax<=MAXProfundidad)
{
cantidadDeNodosExplorados++;
imprimirEstadoNodoAestrellaCostos(revisar.getEstado(),revisar.getCosto(),revisar.getProfundidad(),revisar.getCostoTotal(),cantidadDeNodosExplorados);
int [] posicionDelCero=ubicarPosicionCero(revisar.getEstado());
listaCerrada.add(revisar);
ArrayList<Nodo> hijos=new ArrayList<Nodo>();
if(Arrays.deepEquals(revisar.getEstado(), ConfFinal)){
System.out.println("******* SOLUCION ENCONTRADA*********");
System.out.println("Informacion:");
System.out.println("> Cantidad de nodos Evaluados= "+listaCerrada.size());
profundidad=calcularProfundidad(revisar);
System.out.println("> Profundidad alcanzada: "+profundidad);
ramificacionMedio=(double)cantidadDeNodosExplorados/(double)calcularProfundidad(revisar);
System.out.println("> Ramificacion Medio= "+ramificacionMedio);
System.out.println("> Perfil de Ramificacion: ");
imprimirPerfilRamificacion(profundidad,listaCerrada );
return revisar;
}
if(posicionDelCero[0]!=0)
{
Nodo hijo=new Nodo(clonar(revisar.getEstado()));
int arriba=hijo.getEstado()[posicionDelCero[0]-1][posicionDelCero[1]];
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]]=arriba;
hijo.getEstado()[posicionDelCero[0]-1][posicionDelCero[1]]=0;
hijo.setPadre(revisar);
costo=calcularCosto(hijo.getEstado(), ConfFinal);
hijo.setCosto(costo);
profundidad=calcularProfundidad(hijo);
hijo.setProfundidad(profundidad);
costoAestrella=costo+profundidad;
hijo.setCostoTotal(costoAestrella);
listaAbierta.add(hijo);
hijos.add(hijo);
}
if(posicionDelCero[0]!=2)
{
Nodo hijo=new Nodo(clonar(revisar.getEstado()));
int abajo=hijo.getEstado()[posicionDelCero[0]+1][posicionDelCero[1]];//capturamos el valor que esta en la fila de abajo del cero
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]]=abajo;
hijo.getEstado()[posicionDelCero[0]+1][posicionDelCero[1]]=0;
hijo.setPadre(revisar);
costo=calcularCosto(hijo.getEstado(), ConfFinal);
hijo.setCosto(costo);
profundidad=calcularProfundidad(hijo);
hijo.setProfundidad(profundidad);
costoAestrella=costo+profundidad;
hijo.setCostoTotal(costoAestrella);
listaAbierta.add(hijo);
hijos.add(hijo);
}
if(posicionDelCero[1]!=0)
{
Nodo hijo=new Nodo(clonar(revisar.getEstado()));//le estamos pasando un nodo igual al de antes pero ahora lo modificamos com los movimientos
int izquierda=hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]-1];//capturamos el valor que esta en la fila de arriba de esa columna en la variable arriba
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]]=izquierda;//metemos en la posicion donde estaba el cero, el valor que estaba en la fila de arriba
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]-1]=0;//metemos en la fila de arriba el cero
hijo.setPadre(revisar);
costo=calcularCosto(hijo.getEstado(), ConfFinal);
hijo.setCosto(costo);
profundidad=calcularProfundidad(hijo);
hijo.setProfundidad(profundidad);
costoAestrella=costo+profundidad;
hijo.setCostoTotal(costoAestrella);
listaAbierta.add(hijo);
hijos.add(hijo);
}
if(posicionDelCero[1]!=2)
{
Nodo hijo=new Nodo(clonar(revisar.getEstado()));
int derecha=hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]+1];//capturamos el valor que esta en la fila de abajo del cero
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]]=derecha;
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]+1]=0;
hijo.setPadre(revisar);
costo=calcularCosto(hijo.getEstado(), ConfFinal);
hijo.setCosto(costo);
profundidad=calcularProfundidad(hijo);
hijo.setProfundidad(profundidad);
costoAestrella=costo+profundidad;
hijo.setCostoTotal(costoAestrella);
listaAbierta.add(hijo);
hijos.add(hijo);
}
revisar.setHijos(hijos);
Collections.sort(listaAbierta);//Ordena el ArrayList de acuerdo al "COSTO", asi el nodo hijo con menor costo se ubica primero para salir
revisar=listaAbierta.remove(0);
profMax=calcularProfundidad(revisar);
}
return null;
}
public static void imprimirEstadoNodoAestrellaCostos(int[][] estado, int costo, Integer prof, Integer costoTotal, int cantidadExplorados) {
System.out.println("Siguiente Movimiento");
System.out.println("Costo= "+costo+",Profundidad= "+prof+",Costo Total= "+costoTotal);
System.out.println("Cantidad nodos explorados= "+cantidadExplorados);
for (int i = 0; i < estado.length; i++) {
for (int j = 0; j < estado.length; j++) {
System.out.print("["+estado[i][j]+"]");
}
System.out.println("");
}
}
public static int calcularProfundidad(Nodo hijo) {
int prof=0;
while(hijo.padre!=null)
{
hijo=hijo.padre;
prof++;
}
return prof;
}
public static void imprimirMatrices(int[][] ConfActual) {
int valor=0;
for (int i = 0; i < ConfActual.length; i++) {
for (int j = 0; j < ConfActual.length; j++) {
valor=ConfActual [i][j];
System.out.print("["+valor+"]");
}
System.out.println("");
}
}
public static void imprimirPerfilRamificacion(int profundidad, ArrayList<Nodo> listaCerrada) {
int prof=0;
int cantNodosEnNivelDeProf;
for (int i = 0; i <=profundidad; i++)
{
cantNodosEnNivelDeProf=0;
if(listaCerrada!=null)
{
for(Nodo n:listaCerrada)
{
prof=n.getProfundidad();
if(prof==i)
cantNodosEnNivelDeProf++;
}
}
System.out.println(" Cantidad de nodos en el nivel: "+i+" es de: "+cantNodosEnNivelDeProf);
}
}
public static Nodo buscarSolucionEscaladaMaxPendiente(Nodo inicial5, int[][] ConfFinal, int MAXProfundidad, int MAXNodosExplorados) {
ArrayList <Nodo> listaAbierta=new ArrayList<Nodo>();
ArrayList<Nodo> listaCerrada= new ArrayList<Nodo>();
listaAbierta.add(inicial5);
int cantidadDeNodosExplorados=0;
int profundidad=0;
int cantidadElementosBien=0;// cantidad de piezas bien colocadas
double ramificacionMedio=0;
Nodo revisar=listaAbierta.remove(0);
cantidadElementosBien=calcularCantElemBien(revisar.getEstado(), ConfFinal);
revisar.setCostoTotal(cantidadElementosBien);
while(cantidadDeNodosExplorados<MAXNodosExplorados&&profundidad<=MAXProfundidad)
{
cantidadDeNodosExplorados++;
imprimirEstadoNodoEscMaxPend(revisar.getEstado(),revisar.getCostoTotal(),revisar,cantidadDeNodosExplorados);
int [] posicionDelCero=ubicarPosicionCero(revisar.getEstado());
listaCerrada.add(revisar);
ArrayList<Nodo> hijos=new ArrayList<Nodo>();
if(Arrays.deepEquals(revisar.getEstado(), ConfFinal)){
System.out.println("******* SOLUCION ENCONTRADA*********");
System.out.println("Informacion:");
System.out.println("> Cantidad de nodos Evaluados= "+listaCerrada.size());
profundidad=calcularProfundidad(revisar);
System.out.println("> Profundidad alcanzada: "+profundidad);
ramificacionMedio=(double)cantidadDeNodosExplorados/(double)calcularProfundidad(revisar);
System.out.println("> Ramificacion Medio= "+ramificacionMedio);
System.out.println("> Perfil de Ramificacion: ");
imprimirPerfilRamificacion(profundidad,listaCerrada );
return revisar;
}
if(posicionDelCero[0]!=0)
{
Nodo hijo=new Nodo(clonar(revisar.getEstado()));
int arriba=hijo.getEstado()[posicionDelCero[0]-1][posicionDelCero[1]];
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]]=arriba;
hijo.getEstado()[posicionDelCero[0]-1][posicionDelCero[1]]=0;
hijo.setPadre(revisar);
profundidad=calcularProfundidad(hijo);
hijo.setProfundidad(profundidad);
cantidadElementosBien=calcularCantElemBien(hijo.getEstado(), ConfFinal);
hijo.setCostoTotal(cantidadElementosBien);
listaAbierta.add(hijo);
hijos.add(hijo);
}
if(posicionDelCero[0]!=2)
{
Nodo hijo=new Nodo(clonar(revisar.getEstado()));
int abajo=hijo.getEstado()[posicionDelCero[0]+1][posicionDelCero[1]];//capturamos el valor que esta en la fila de abajo del cero
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]]=abajo;
hijo.getEstado()[posicionDelCero[0]+1][posicionDelCero[1]]=0;
hijo.setPadre(revisar);
profundidad=calcularProfundidad(hijo);
hijo.setProfundidad(profundidad);
cantidadElementosBien=calcularCantElemBien(hijo.getEstado(), ConfFinal);
hijo.setCostoTotal(cantidadElementosBien);
listaAbierta.add(hijo);
hijos.add(hijo);
}
if(posicionDelCero[1]!=0)
{
Nodo hijo=new Nodo(clonar(revisar.getEstado()));//le estamos pasando un nodo igual al de antes pero ahora lo modificamos com los movimientos
int izquierda=hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]-1];//capturamos el valor que esta en la fila de arriba de esa columna en la variable arriba
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]]=izquierda;//metemos en la posicion donde estaba el cero, el valor que estaba en la fila de arriba
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]-1]=0;//metemos en la fila de arriba el cero
hijo.setPadre(revisar);
profundidad=calcularProfundidad(hijo);
hijo.setProfundidad(profundidad);
cantidadElementosBien=calcularCantElemBien(hijo.getEstado(), ConfFinal);
hijo.setCostoTotal(cantidadElementosBien);
listaAbierta.add(hijo);
hijos.add(hijo);
}
if(posicionDelCero[1]!=2)
{
Nodo hijo=new Nodo(clonar(revisar.getEstado()));
int derecha=hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]+1];//capturamos el valor que esta en la fila de abajo del cero
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]]=derecha;
hijo.getEstado()[posicionDelCero[0]][posicionDelCero[1]+1]=0;
hijo.setPadre(revisar);
profundidad=calcularProfundidad(hijo);
hijo.setProfundidad(profundidad);
cantidadElementosBien=calcularCantElemBien(hijo.getEstado(), ConfFinal);
hijo.setCostoTotal(cantidadElementosBien);
listaAbierta.add(hijo);
hijos.add(hijo);
}
revisar.setHijos(hijos);
Collections.sort(listaAbierta, Collections.reverseOrder());//Ordena el ArrayList de modo Ascendente
Nodo mejorHijo=listaAbierta.remove(0);
if (mejorHijo.getCostoTotal()<revisar.getCostoTotal()) {
System.out.println("No existe un nodo mejor que el actual");
break;
}
revisar=mejorHijo;
profundidad=calcularProfundidad(revisar);
listaAbierta.clear();//borro los hijos del nodo anterior
}
return null;
}
public static int calcularCantElemBien(int[][] estado, int[][] ConfFinal) {
int c=0;
for (int i = 0; i < ConfFinal.length; i++) {
for (int j = 0; j < ConfFinal.length; j++) {
if(estado[i][j]==ConfFinal[i][j])
c++;
}
}
return c;
}
public static void imprimirEstadoNodoEscMaxPend(int[][] estado, Integer costoTotal, Nodo revisar, int cantidadDeNodosExplorados) {
int prof=0;
while(revisar.padre!=null)
{
revisar=revisar.padre;
prof++;
}
System.out.println("Siguiente Movimiento en la profundidad= "+prof+", piezas bien colocadas= "+costoTotal);
System.out.println("Cantidad de nodos explorados= "+cantidadDeNodosExplorados);
for (int i = 0; i < estado.length; i++) {
for (int j = 0; j < estado.length; j++) {
System.out.print("["+estado[i][j]+"]");
}
System.out.println("");
}
}
}
| 54,144 | 0.507118 | 0.499234 | 1,038 | 51.173409 | 36.844841 | 228 | false | false | 0 | 0 | 0 | 0 | 72 | 0.001329 | 0.800578 | false | false | 11 |
76ad3ca14e6e8d4123e088b495040eb0bdc64bae | 39,247,411,171,245 | 4d151e78e1bec1a370b20226e9323fd4727992f0 | /webapp/src/main/java/com/henning/vacpla/business/request/dtos/RequestDto.java | 6ae5fb5163b274bb0457de5080a007edeb4b9f43 | [] | no_license | GittyGatto/vacpla | https://github.com/GittyGatto/vacpla | 9191bc8e2702b724bdacad7aa0a659fd44880feb | 3d8a2630ce2addf087c621a3b757bad917492172 | refs/heads/master | 2022-02-28T17:10:58.834000 | 2021-07-13T17:14:48 | 2021-07-13T17:14:48 | 152,750,647 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.henning.vacpla.business.request.dtos;
import lombok.Data;
import java.util.List;
@Data
public class RequestDto implements Comparable<RequestDto> {
private String uuid;
private String owner;
private String vacationRequestStatus;
private String requested;
private String approved;
private String approvedBy;
private String from;
private String to;
private String vacationCount;
private String category;
private List<CommentDto> comments;
@Override
public int compareTo(RequestDto o) {
return getRequested().compareTo(o.getRequested());
}
}
| UTF-8 | Java | 618 | java | RequestDto.java | Java | [] | null | [] | package com.henning.vacpla.business.request.dtos;
import lombok.Data;
import java.util.List;
@Data
public class RequestDto implements Comparable<RequestDto> {
private String uuid;
private String owner;
private String vacationRequestStatus;
private String requested;
private String approved;
private String approvedBy;
private String from;
private String to;
private String vacationCount;
private String category;
private List<CommentDto> comments;
@Override
public int compareTo(RequestDto o) {
return getRequested().compareTo(o.getRequested());
}
}
| 618 | 0.729773 | 0.729773 | 25 | 23.719999 | 17.468876 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 11 |
06b123e620325867671be3a285f764f441d4cb54 | 38,302,518,363,799 | c83a9b138047ec78c830169ea55c7c434858be59 | /app/src/main/java/ru/tulupov/alex/medalmanah/Model/api/ApiEvents.java | c97260832b355024d9893b6ae8ca882243b54372 | [] | no_license | Algresh/Medalmanah | https://github.com/Algresh/Medalmanah | 36b0324c3b96712abd7a1aeb0245f5b6aeea11cb | ceb370a9f4b6a2189d691d4f137ebda0db921630 | refs/heads/master | 2021-01-12T12:12:05.954000 | 2016-11-09T13:57:20 | 2016-11-09T13:57:20 | 72,353,390 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ru.tulupov.alex.medalmanah.model.api;
import retrofit.Callback;
import retrofit.http.GET;
import ru.tulupov.alex.medalmanah.model.dao.ListSpecialities;
public interface ApiEvents {
@GET("/api/specialty")
void getAllSpecialities(Callback<ListSpecialities> specialities);
}
| UTF-8 | Java | 292 | java | ApiEvents.java | Java | [] | null | [] | package ru.tulupov.alex.medalmanah.model.api;
import retrofit.Callback;
import retrofit.http.GET;
import ru.tulupov.alex.medalmanah.model.dao.ListSpecialities;
public interface ApiEvents {
@GET("/api/specialty")
void getAllSpecialities(Callback<ListSpecialities> specialities);
}
| 292 | 0.791096 | 0.791096 | 12 | 23.333334 | 23.602024 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.416667 | false | false | 11 |
bf1b6d09c0990792e61aa47cf34431aceab3b923 | 35,072,702,991,837 | 1b1aef4d4ebdbbb71837114771db4877e47f5f25 | /src/main/java/com/ydl/api/userManagementPlatform/DepartmentApi.java | d556b871b174faf7e5d87941f3cd6caf090c9a53 | [] | no_license | Ididntexpectthat/CountryData | https://github.com/Ididntexpectthat/CountryData | 4d7ecfcf5d29238ceaa87047f7a9d6669fbf8f9e | c31c8204e7f4b7b20bd851bbb5dc3961049a91d1 | refs/heads/master | 2022-10-10T09:12:09.412000 | 2020-01-16T10:07:52 | 2020-01-16T10:07:52 | 218,243,965 | 0 | 0 | null | false | 2022-09-08T01:03:56 | 2019-10-29T08:57:07 | 2020-01-16T10:08:16 | 2022-09-08T01:03:53 | 23,620 | 0 | 0 | 3 | Java | false | false | package com.ydl.api.userManagementPlatform;
import com.alibaba.fastjson.JSONObject;
import com.ydl.annotation.UserLoginToken;
import com.ydl.config.JsonXMLUtils;
import com.ydl.entity.Department;
import com.ydl.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("Department")
public class DepartmentApi {
@Autowired
DepartmentService departmentService;
/**
* 获取所有部门
*/
@PostMapping(value = "/getAllDepartment")
public Object getAllDepartment() {
return new ResponseEntity<List>(departmentService.getAllDepartment(), HttpStatus.OK);
}
/**
* 添加新科室
*
* @param models
* @return
*/
@UserLoginToken
@PostMapping(value = "/insert")
public Object insert(@RequestBody Map<String, Object> models) {
Department department = JsonXMLUtils.map2Department((Map<String, Object>) models.get("department"), Department.class);
JSONObject jsonObject = new JSONObject();
if (departmentService.findDeByname(department) == null) {
departmentService.insertDepartment(department);
jsonObject.put("message", "科室添加成功!");
return new ResponseEntity(jsonObject, HttpStatus.OK);
} else {
jsonObject.put("message", "添加失败,部门已经存在!");
return new ResponseEntity(jsonObject, HttpStatus.UNAUTHORIZED);
}
}
/**
* 根据科室删除科室,用户,权限
*
* @param models
* @return
*/
@UserLoginToken
@PostMapping(value = "/deleteDepartment")
public Object deleteDepartment(@RequestBody Map<String, Object> models) {
Department department = JsonXMLUtils.map2Department((Map<String, Object>) models.get("department"), Department.class);
JSONObject jsonObject = new JSONObject();
try {
departmentService.deleteDepartment(department);
jsonObject.put("message", "科室删除成功!");
return new ResponseEntity(jsonObject, HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity(e, HttpStatus.OK);
}
}
/**
* 修改科室的名称以及把科室下的用户的科室也修改
*
* @param models
* @return
*/
@UserLoginToken
@Transactional
@PostMapping(value = "/updateDepartment")
public Object test(@RequestBody Map<String, Object> models) {
JSONObject jsonObject = new JSONObject();
Department department1 = JsonXMLUtils.map2Department((Map<String, Object>) models.get("department1"), Department.class);
Department department2 = JsonXMLUtils.map2Department((Map<String, Object>) models.get("department2"), Department.class);
/**
* 先新增新的权限
*/
if (StringUtils.isEmpty(department1.getDepartment()) || StringUtils.isEmpty(department2.getDepartment())) {
jsonObject.put("message", "编辑失败,部门不能为空!");
return new ResponseEntity(jsonObject, HttpStatus.UNAUTHORIZED);
}
if (departmentService.findDeByname(department2) == null) {
departmentService.insertDepartment(department2);
/**
* 再进行修改和删除
*/
try {
departmentService.updateDepartment(department1, department2);
jsonObject.put("message", "编辑部门成功!");
return new ResponseEntity(jsonObject, HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity(e, HttpStatus.UNAUTHORIZED);
}
} else {
jsonObject.put("message", "编辑失败,部门已经存在");
return new ResponseEntity(jsonObject, HttpStatus.UNAUTHORIZED);
}
}
}
| UTF-8 | Java | 4,459 | java | DepartmentApi.java | Java | [] | null | [] | package com.ydl.api.userManagementPlatform;
import com.alibaba.fastjson.JSONObject;
import com.ydl.annotation.UserLoginToken;
import com.ydl.config.JsonXMLUtils;
import com.ydl.entity.Department;
import com.ydl.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("Department")
public class DepartmentApi {
@Autowired
DepartmentService departmentService;
/**
* 获取所有部门
*/
@PostMapping(value = "/getAllDepartment")
public Object getAllDepartment() {
return new ResponseEntity<List>(departmentService.getAllDepartment(), HttpStatus.OK);
}
/**
* 添加新科室
*
* @param models
* @return
*/
@UserLoginToken
@PostMapping(value = "/insert")
public Object insert(@RequestBody Map<String, Object> models) {
Department department = JsonXMLUtils.map2Department((Map<String, Object>) models.get("department"), Department.class);
JSONObject jsonObject = new JSONObject();
if (departmentService.findDeByname(department) == null) {
departmentService.insertDepartment(department);
jsonObject.put("message", "科室添加成功!");
return new ResponseEntity(jsonObject, HttpStatus.OK);
} else {
jsonObject.put("message", "添加失败,部门已经存在!");
return new ResponseEntity(jsonObject, HttpStatus.UNAUTHORIZED);
}
}
/**
* 根据科室删除科室,用户,权限
*
* @param models
* @return
*/
@UserLoginToken
@PostMapping(value = "/deleteDepartment")
public Object deleteDepartment(@RequestBody Map<String, Object> models) {
Department department = JsonXMLUtils.map2Department((Map<String, Object>) models.get("department"), Department.class);
JSONObject jsonObject = new JSONObject();
try {
departmentService.deleteDepartment(department);
jsonObject.put("message", "科室删除成功!");
return new ResponseEntity(jsonObject, HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity(e, HttpStatus.OK);
}
}
/**
* 修改科室的名称以及把科室下的用户的科室也修改
*
* @param models
* @return
*/
@UserLoginToken
@Transactional
@PostMapping(value = "/updateDepartment")
public Object test(@RequestBody Map<String, Object> models) {
JSONObject jsonObject = new JSONObject();
Department department1 = JsonXMLUtils.map2Department((Map<String, Object>) models.get("department1"), Department.class);
Department department2 = JsonXMLUtils.map2Department((Map<String, Object>) models.get("department2"), Department.class);
/**
* 先新增新的权限
*/
if (StringUtils.isEmpty(department1.getDepartment()) || StringUtils.isEmpty(department2.getDepartment())) {
jsonObject.put("message", "编辑失败,部门不能为空!");
return new ResponseEntity(jsonObject, HttpStatus.UNAUTHORIZED);
}
if (departmentService.findDeByname(department2) == null) {
departmentService.insertDepartment(department2);
/**
* 再进行修改和删除
*/
try {
departmentService.updateDepartment(department1, department2);
jsonObject.put("message", "编辑部门成功!");
return new ResponseEntity(jsonObject, HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity(e, HttpStatus.UNAUTHORIZED);
}
} else {
jsonObject.put("message", "编辑失败,部门已经存在");
return new ResponseEntity(jsonObject, HttpStatus.UNAUTHORIZED);
}
}
}
| 4,459 | 0.662018 | 0.65871 | 115 | 35.791306 | 30.104021 | 128 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.652174 | false | false | 11 |
b6786ed92d20b6c342febbeef5953a3ef3a3b10d | 34,797,825,079,011 | e1ac64ee96583ea789af0faf6d31cf6a15e3c34b | /app/src/main/java/com/example/vkeline/myapplication/data/PaiPanItem.java | af97972b303aae9f1d6637db514b20541bd803a4 | [] | no_license | liuxingraozhirou/MyApplicationyes | https://github.com/liuxingraozhirou/MyApplicationyes | ea7670d534ee3c86eb65b76d696ab162281498b7 | 7e405531afa8261cb5ed6cb73cc7a7303f2a6355 | refs/heads/master | 2022-04-07T01:03:54.532000 | 2020-02-26T09:00:20 | 2020-02-26T09:00:20 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.vkeline.myapplication.data;
/**
* Created by vkeline on 2018/3/2.
*/
public class PaiPanItem {
private int img;
private String text;
public PaiPanItem(int img, String text) {
this.img = img;
this.text = text;
}
public int getImg() {
return img;
}
public void setImg(int img) {
this.img = img;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
| UTF-8 | Java | 517 | java | PaiPanItem.java | Java | [
{
"context": "ple.vkeline.myapplication.data;\n\n/**\n * Created by vkeline on 2018/3/2.\n */\npublic class PaiPanItem {\n pr",
"end": 74,
"score": 0.9994672536849976,
"start": 67,
"tag": "USERNAME",
"value": "vkeline"
}
] | null | [] | package com.example.vkeline.myapplication.data;
/**
* Created by vkeline on 2018/3/2.
*/
public class PaiPanItem {
private int img;
private String text;
public PaiPanItem(int img, String text) {
this.img = img;
this.text = text;
}
public int getImg() {
return img;
}
public void setImg(int img) {
this.img = img;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
| 517 | 0.568665 | 0.55706 | 30 | 16.233334 | 14.488348 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 11 |
4cadda6a27951319bbcd173972d2bc9cb280217f | 26,594,437,548,571 | f3e716d9efc0edc9534fc4ec76378b058a18ad7c | /src/NewMain.java | 0215d6d2c811bb8e1687274dbddbb0a845ceea07 | [] | no_license | Progras/Progra1 | https://github.com/Progras/Progra1 | ca66dd5468495a028b2e7df28245def288673666 | a3e11027261234ef7b9a4cb93c7a6f5d8e173dae | refs/heads/master | 2020-04-10T16:34:47.485000 | 2014-09-05T05:55:39 | 2014-09-05T05:55:39 | 23,190,982 | 0 | 1 | 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.
*/
/**
*
* @author marco_197
*/
/**
* @author marco_197
*/
public class NewMain {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Library n = new Library();
n.InsertEnd("f", "", "", "", 0, "", "");
n.InsertEnd("w", "", "", "", 0, "", "");
n.InsertEnd("r", "", "", "", 0, "", "");
n.Delete("f");
//n.printconsole();
String ruta;
GetPath x = new GetPath();
//ruta = x.GetPath();
Main test =new Main(n);
test.setVisible(true);
}
} | UTF-8 | Java | 813 | java | NewMain.java | Java | [
{
"context": "the template in the editor.\n */\n\n/**\n *\n * @author marco_197\n */\n/**\n\n * @author marco_197\n */\n\npublic class N",
"end": 213,
"score": 0.9993665814399719,
"start": 204,
"tag": "USERNAME",
"value": "marco_197"
},
{
"context": "/\n\n/**\n *\n * @author marco_197\n */\n/**\n\n * @author marco_197\n */\n\npublic class NewMain {\n\n /**\n * @para",
"end": 243,
"score": 0.9994122982025146,
"start": 234,
"tag": "USERNAME",
"value": "marco_197"
}
] | 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.
*/
/**
*
* @author marco_197
*/
/**
* @author marco_197
*/
public class NewMain {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Library n = new Library();
n.InsertEnd("f", "", "", "", 0, "", "");
n.InsertEnd("w", "", "", "", 0, "", "");
n.InsertEnd("r", "", "", "", 0, "", "");
n.Delete("f");
//n.printconsole();
String ruta;
GetPath x = new GetPath();
//ruta = x.GetPath();
Main test =new Main(n);
test.setVisible(true);
}
} | 813 | 0.519065 | 0.507995 | 38 | 20.421053 | 20.049454 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.842105 | false | false | 11 |
dfaaa52fc57ce60dc0fec5d9f3feb2992cea7253 | 22,531,398,495,996 | 9b3a2eff5b73b8848ab93e6fc2cb3762929d743a | /scf-util/src/main/java/com/suning/scf/util/cfca/StampVerifyUtil.java | ae035eb66e86c1ac60b0a386ed9222f4fa37519e | [
"Apache-2.0"
] | permissive | 786228836/SCF | https://github.com/786228836/SCF | 878c2a9f5b6d3ae6cbecbadcdf8667d0ee9d5d29 | ba6d08f03db446faf3670584232e9ba88235d404 | refs/heads/master | 2015-07-14T23:41:23 | 2015-04-17T02:43:54 | 2015-04-17T02:43:54 | 34,092,496 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright (C), 2002-2012, 苏宁易购电子商务有限公司
* FileName: StampVerifyUtil.java
* Author: 12040247
* Date: 2012-6-12 上午10:51:36
* Description: cafa校验工具类
* History:
* <author> <time> <version> <desc>
*
*/
package com.suning.scf.util.cfca;
import com.cfca.esign.ESignKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* cafa校验工具类
*
* <pre>
* cafa校验工具类
* </pre>
*
* @author sunhaibo
* @see
* @since
*/
public class StampVerifyUtil {
/**
* 日志
*/
private static Logger logger = LoggerFactory.getLogger(StampVerifyUtil.class);
/**
*
* 功能描述:验证软签章
*
* <pre>
* 对页面电子签章内容进行合法性校验
* @param paramEntity
* @return
* @see
* @since 1.0.0
*/
public static boolean virifySignature(StampEntity paramEntity) {
String sealPath = paramEntity.getSealPath();
String signatreContent = paramEntity.getSignature();
String plainText = paramEntity.getPlainText();
String crlPath = paramEntity.getCrlPath();
boolean ret = Boolean.TRUE;
try {
// 初始化并读取印章文件并验证印章的有效性
ESignKit eSignKit = new ESignKit(sealPath, "11111111", 0, "");
eSignKit.CFCA_Key_LoadSeal(sealPath, "11111111", 0, "");
// 对电子签章进行验证
String checkStamp = eSignKit.CFCA_VerifyStamp(signatreContent, plainText, 0, "");
if (!"0".equals(checkStamp)) {
logger.error("验签失败," + eSignKit.getESignKitStatus() + ":" + eSignKit.getESignKitStatusDes());
return Boolean.FALSE;
}
// 获得签名公钥证书Base64编码
String userCert = eSignKit.CFCA_GetSignCert(0, "");
// 设置CFCA根证书
String rootCerts[] = new String[1];
rootCerts[0] = StampEntity.getRootcert();
// 校验证书有效性
String checkCert = eSignKit.CFCA_VerifyCert(userCert, rootCerts, 1, 1, 0, crlPath, 0, "");
if (!"0".equals(checkCert)) {
logger.error("证书不被信任,请确认证书合法性;" + eSignKit.getESignKitStatus() + ":" + eSignKit.getESignKitStatusDes());
return Boolean.FALSE;
}
} catch (Exception e) {
ret = Boolean.FALSE;
logger.error("对电子签章校验发生异常", e);
}
return ret;
}
}
| UTF-8 | Java | 2,597 | java | StampVerifyUtil.java | Java | [
{
"context": "公司\n * FileName: StampVerifyUtil.java\n * Author: 12040247\n * Date: 2012-6-12 上午10:51:36\n * Description:",
"end": 100,
"score": 0.9990602731704712,
"start": 92,
"tag": "USERNAME",
"value": "12040247"
},
{
"context": " * \n * <pre>\n * cafa校验工具类\n * </pre>\n * \n * @author sunhaibo\n * @see\n * @since\n */\npublic class StampVerifyUti",
"end": 433,
"score": 0.9996035695075989,
"start": 425,
"tag": "USERNAME",
"value": "sunhaibo"
},
{
"context": " eSignKit.CFCA_Key_LoadSeal(sealPath, \"11111111\", 0, \"\");\n\n // 对电子签章进行验证\n S",
"end": 1271,
"score": 0.9994999170303345,
"start": 1263,
"tag": "KEY",
"value": "11111111"
}
] | null | [] | /*
* Copyright (C), 2002-2012, 苏宁易购电子商务有限公司
* FileName: StampVerifyUtil.java
* Author: 12040247
* Date: 2012-6-12 上午10:51:36
* Description: cafa校验工具类
* History:
* <author> <time> <version> <desc>
*
*/
package com.suning.scf.util.cfca;
import com.cfca.esign.ESignKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* cafa校验工具类
*
* <pre>
* cafa校验工具类
* </pre>
*
* @author sunhaibo
* @see
* @since
*/
public class StampVerifyUtil {
/**
* 日志
*/
private static Logger logger = LoggerFactory.getLogger(StampVerifyUtil.class);
/**
*
* 功能描述:验证软签章
*
* <pre>
* 对页面电子签章内容进行合法性校验
* @param paramEntity
* @return
* @see
* @since 1.0.0
*/
public static boolean virifySignature(StampEntity paramEntity) {
String sealPath = paramEntity.getSealPath();
String signatreContent = paramEntity.getSignature();
String plainText = paramEntity.getPlainText();
String crlPath = paramEntity.getCrlPath();
boolean ret = Boolean.TRUE;
try {
// 初始化并读取印章文件并验证印章的有效性
ESignKit eSignKit = new ESignKit(sealPath, "11111111", 0, "");
eSignKit.CFCA_Key_LoadSeal(sealPath, "11111111", 0, "");
// 对电子签章进行验证
String checkStamp = eSignKit.CFCA_VerifyStamp(signatreContent, plainText, 0, "");
if (!"0".equals(checkStamp)) {
logger.error("验签失败," + eSignKit.getESignKitStatus() + ":" + eSignKit.getESignKitStatusDes());
return Boolean.FALSE;
}
// 获得签名公钥证书Base64编码
String userCert = eSignKit.CFCA_GetSignCert(0, "");
// 设置CFCA根证书
String rootCerts[] = new String[1];
rootCerts[0] = StampEntity.getRootcert();
// 校验证书有效性
String checkCert = eSignKit.CFCA_VerifyCert(userCert, rootCerts, 1, 1, 0, crlPath, 0, "");
if (!"0".equals(checkCert)) {
logger.error("证书不被信任,请确认证书合法性;" + eSignKit.getESignKitStatus() + ":" + eSignKit.getESignKitStatusDes());
return Boolean.FALSE;
}
} catch (Exception e) {
ret = Boolean.FALSE;
logger.error("对电子签章校验发生异常", e);
}
return ret;
}
}
| 2,597 | 0.569151 | 0.541577 | 84 | 26.630953 | 26.63813 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.52381 | false | false | 11 |
88c7119a5ca5d18b606db2ac9b23f783d242feab | 4,363,686,775,249 | 528395a0954da9a65ff3d7b4a2c6a26038b10bb0 | /alone/java/timer/TimerManager.java | 7077df84c044a98f61bcb1572287170c78e73ee0 | [] | no_license | jaronho/sdk | https://github.com/jaronho/sdk | 16ad88864b31e61d583a2fd782574e31da5e7759 | 179e8cebdbaa101d9a3782d9bc9148caf1fa14ad | refs/heads/master | 2023-08-10T23:30:50.485000 | 2023-08-04T01:44:46 | 2023-08-04T01:44:46 | 83,393,940 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jaronho.sdk.library.timer;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* Author: jaron.ho
* Date: 2017-02-08
* Brief: TimerManager
*/
public class TimerManager {
private class RunObject {
public Timer timer = null;
public Timer.RunHandler handler = null;
public RunObject(Timer.RunHandler handler) {
this.handler = handler;
}
}
private class OverObject {
public Timer timer = null;
public Timer.OverHandler handler = null;
public OverObject(Timer.OverHandler handler) {this.handler = handler;}
}
private static TimerManager mInstance = null;
private final ConcurrentHashMap<String, Timer> mTimerMap = new ConcurrentHashMap<>();
private final Handler mRunHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
RunObject runObj = (RunObject)msg.obj;
if (null != runObj && null != runObj.handler) {
int runCount = msg.arg1;
runObj.handler.onCallback(runObj.timer, runCount);
}
}
};
private final Handler mOverHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
OverObject overObj = (OverObject)msg.obj;
if (null != overObj && null != overObj.handler) {
overObj.handler.onCallback(overObj.timer);
}
}
};
private Thread mThread = new Thread(new Runnable() {
private void loopUpdate(long currentTime) {
Set<Entry<String, Timer>> entrySet = mTimerMap.entrySet();
for (Entry<String, Timer> entry : entrySet) {
Timer tm = entry.getValue();
if (null != tm) {
tm.update(currentTime);
}
}
}
@Override
public void run() {
while (!mThread.isInterrupted()) {
loopUpdate(SystemClock.elapsedRealtime());
}
}
});
private TimerManager() {
if (null != mThread) {
mThread.start();
}
}
@Override
protected void finalize() throws Throwable {
super.finalize();
mTimerMap.clear();
if (null != mThread) {
mThread.interrupt();
mThread = null;
}
}
public static TimerManager getInstance() {
if (null == mInstance) {
synchronized(TimerManager.class) {
if (null == mInstance) {
mInstance = new TimerManager();
}
}
}
return mInstance;
}
public void run(final String id, long interval, int count, Timer.RunHandler runHandler, Timer.OverHandler overHandler, Object param, boolean doStartCB) {
if (id.length() > 0 && interval > 0) {
final RunObject runObj = new RunObject(runHandler);
final OverObject overObj = new OverObject(overHandler);
Timer tm = new Timer(interval, count, new Timer.RunHandler() {
@Override
public void onCallback(Timer tm, int runCount, Object param) {
Message msg = mRunHandler.obtainMessage();
msg.obj = runObj;
msg.arg1 = runCount;
mRunHandler.sendMessage(msg);
}
}, new Timer.OverHandler() {
@Override
public void onCallback(Timer tm, Object param) {
if (mTimerMap.containsKey(id)) {
mTimerMap.remove(id);
}
Message msg = mOverHandler.obtainMessage();
msg.obj = overObj;
mOverHandler.sendMessage(msg);
}
}, id, param);
if (mTimerMap.containsKey(id)) {
mTimerMap.remove(id);
}
mTimerMap.put(id, tm);
runObj.timer = tm;
overObj.timer = tm;
tm.start(SystemClock.elapsedRealtime(), doStartCB);
}
}
public void run(final String id, long interval, int count, Timer.RunHandler runHandler, Timer.OverHandler overHandler, boolean doStartCB) {
run(id, interval, count, runHandler, overHandler, null, doStartCB);
}
public void run(final String id, long interval, int count, Timer.RunHandler runHandler, boolean doStartCB) {
run(id, interval, count, runHandler, null, null, doStartCB);
}
public void run(final String id, long interval, int count, Timer.OverHandler overHandler) {
run(id, interval, count, null, overHandler, null, false);
}
public String run(long interval, int count, Timer.RunHandler runHandler, Timer.OverHandler overHandler, Object param, boolean doStartCB) {
String id = UUID.randomUUID().toString();
run(id, interval, count, runHandler, overHandler, param, doStartCB);
return id;
}
public String run(long interval, int count, Timer.RunHandler runHandler, Timer.OverHandler overHandler, boolean doStartCB) {
String id = UUID.randomUUID().toString();
run(id, interval, count, runHandler, overHandler, null, doStartCB);
return id;
}
public String run(long interval, int count, Timer.RunHandler runHandler, boolean doStartCB) {
String id = UUID.randomUUID().toString();
run(id, interval, count, runHandler, null, null, doStartCB);
return id;
}
public String run(long interval, int count, Timer.OverHandler overHandler) {
String id = UUID.randomUUID().toString();
run(id, interval, count, null, overHandler, null, false);
return id;
}
public void stop(String id, boolean doStopCB) {
if (mTimerMap.containsKey(id)) {
Timer tm = mTimerMap.remove(id);
if (null != tm && doStopCB) {
tm.stop(true);
}
}
}
public void clear(boolean doStopCB) {
Set<Entry<String, Timer>> entrySet = mTimerMap.entrySet();
mTimerMap.clear();
if (doStopCB) {
for (Entry<String, Timer> entry : entrySet) {
Timer tm = entry.getValue();
if (null != tm) {
tm.stop(true);
}
}
}
}
}
| UTF-8 | Java | 6,537 | java | TimerManager.java | Java | [
{
"context": "til.concurrent.ConcurrentHashMap;\n\n/**\n * Author: jaron.ho\n * Date: 2017-02-08\n * Brief: TimerManager\n ",
"end": 271,
"score": 0.8982938528060913,
"start": 263,
"tag": "NAME",
"value": "jaron.ho"
}
] | null | [] | package com.jaronho.sdk.library.timer;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* Author: jaron.ho
* Date: 2017-02-08
* Brief: TimerManager
*/
public class TimerManager {
private class RunObject {
public Timer timer = null;
public Timer.RunHandler handler = null;
public RunObject(Timer.RunHandler handler) {
this.handler = handler;
}
}
private class OverObject {
public Timer timer = null;
public Timer.OverHandler handler = null;
public OverObject(Timer.OverHandler handler) {this.handler = handler;}
}
private static TimerManager mInstance = null;
private final ConcurrentHashMap<String, Timer> mTimerMap = new ConcurrentHashMap<>();
private final Handler mRunHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
RunObject runObj = (RunObject)msg.obj;
if (null != runObj && null != runObj.handler) {
int runCount = msg.arg1;
runObj.handler.onCallback(runObj.timer, runCount);
}
}
};
private final Handler mOverHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
OverObject overObj = (OverObject)msg.obj;
if (null != overObj && null != overObj.handler) {
overObj.handler.onCallback(overObj.timer);
}
}
};
private Thread mThread = new Thread(new Runnable() {
private void loopUpdate(long currentTime) {
Set<Entry<String, Timer>> entrySet = mTimerMap.entrySet();
for (Entry<String, Timer> entry : entrySet) {
Timer tm = entry.getValue();
if (null != tm) {
tm.update(currentTime);
}
}
}
@Override
public void run() {
while (!mThread.isInterrupted()) {
loopUpdate(SystemClock.elapsedRealtime());
}
}
});
private TimerManager() {
if (null != mThread) {
mThread.start();
}
}
@Override
protected void finalize() throws Throwable {
super.finalize();
mTimerMap.clear();
if (null != mThread) {
mThread.interrupt();
mThread = null;
}
}
public static TimerManager getInstance() {
if (null == mInstance) {
synchronized(TimerManager.class) {
if (null == mInstance) {
mInstance = new TimerManager();
}
}
}
return mInstance;
}
public void run(final String id, long interval, int count, Timer.RunHandler runHandler, Timer.OverHandler overHandler, Object param, boolean doStartCB) {
if (id.length() > 0 && interval > 0) {
final RunObject runObj = new RunObject(runHandler);
final OverObject overObj = new OverObject(overHandler);
Timer tm = new Timer(interval, count, new Timer.RunHandler() {
@Override
public void onCallback(Timer tm, int runCount, Object param) {
Message msg = mRunHandler.obtainMessage();
msg.obj = runObj;
msg.arg1 = runCount;
mRunHandler.sendMessage(msg);
}
}, new Timer.OverHandler() {
@Override
public void onCallback(Timer tm, Object param) {
if (mTimerMap.containsKey(id)) {
mTimerMap.remove(id);
}
Message msg = mOverHandler.obtainMessage();
msg.obj = overObj;
mOverHandler.sendMessage(msg);
}
}, id, param);
if (mTimerMap.containsKey(id)) {
mTimerMap.remove(id);
}
mTimerMap.put(id, tm);
runObj.timer = tm;
overObj.timer = tm;
tm.start(SystemClock.elapsedRealtime(), doStartCB);
}
}
public void run(final String id, long interval, int count, Timer.RunHandler runHandler, Timer.OverHandler overHandler, boolean doStartCB) {
run(id, interval, count, runHandler, overHandler, null, doStartCB);
}
public void run(final String id, long interval, int count, Timer.RunHandler runHandler, boolean doStartCB) {
run(id, interval, count, runHandler, null, null, doStartCB);
}
public void run(final String id, long interval, int count, Timer.OverHandler overHandler) {
run(id, interval, count, null, overHandler, null, false);
}
public String run(long interval, int count, Timer.RunHandler runHandler, Timer.OverHandler overHandler, Object param, boolean doStartCB) {
String id = UUID.randomUUID().toString();
run(id, interval, count, runHandler, overHandler, param, doStartCB);
return id;
}
public String run(long interval, int count, Timer.RunHandler runHandler, Timer.OverHandler overHandler, boolean doStartCB) {
String id = UUID.randomUUID().toString();
run(id, interval, count, runHandler, overHandler, null, doStartCB);
return id;
}
public String run(long interval, int count, Timer.RunHandler runHandler, boolean doStartCB) {
String id = UUID.randomUUID().toString();
run(id, interval, count, runHandler, null, null, doStartCB);
return id;
}
public String run(long interval, int count, Timer.OverHandler overHandler) {
String id = UUID.randomUUID().toString();
run(id, interval, count, null, overHandler, null, false);
return id;
}
public void stop(String id, boolean doStopCB) {
if (mTimerMap.containsKey(id)) {
Timer tm = mTimerMap.remove(id);
if (null != tm && doStopCB) {
tm.stop(true);
}
}
}
public void clear(boolean doStopCB) {
Set<Entry<String, Timer>> entrySet = mTimerMap.entrySet();
mTimerMap.clear();
if (doStopCB) {
for (Entry<String, Timer> entry : entrySet) {
Timer tm = entry.getValue();
if (null != tm) {
tm.stop(true);
}
}
}
}
}
| 6,537 | 0.567386 | 0.56555 | 189 | 33.587303 | 28.853012 | 157 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.862434 | false | false | 11 |
7f4ec22b0ef0108d30b1025fc43b6b90c081d1a1 | 5,514,738,047,140 | 6f672fb72caedccb841ee23f53e32aceeaf1895e | /Entertainment/crackle_source/src/com/sessionm/core/f$13.java | 3f791e9ffdbb32244f5a82804d2f726fcc718966 | [] | no_license | cha63506/CompSecurity | https://github.com/cha63506/CompSecurity | 5c69743f660b9899146ed3cf21eceabe3d5f4280 | eee7e74f4088b9c02dd711c061fc04fb1e4e2654 | refs/heads/master | 2018-03-23T04:15:18.480000 | 2015-12-19T01:29:58 | 2015-12-19T01:29:58 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | // Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.sessionm.core;
import android.util.Log;
import com.sessionm.api.ActivityListener;
import com.sessionm.api.SessionM;
// Referenced classes of package com.sessionm.core:
// f
class
implements Runnable
{
final f cM;
public void run()
{
SessionM sessionm = SessionM.getInstance();
ActivityListener activitylistener = sessionm.getActivityListener();
android.app.Activity activity;
if (activitylistener != null)
{
try
{
activitylistener.onDismissed(sessionm);
}
catch (Throwable throwable1)
{
if (Log.isLoggable("SessionM", 6))
{
Log.e("SessionM.Session", "Exception calling ActivityListener.onDismissed()", throwable1);
}
continue; /* Loop/switch isn't completed */
}
}
_L4:
activity = cM.J();
if (!(activity instanceof ActivityListener) || activity == activitylistener)
{
break MISSING_BLOCK_LABEL_50;
}
((ActivityListener)activity).onDismissed(sessionm);
_L2:
return;
Throwable throwable;
throwable;
if (!Log.isLoggable("SessionM", 6)) goto _L2; else goto _L1
_L1:
Log.e("SessionM.Session", "Exception calling ActivityListener.onDismissed()", throwable);
return;
if (true) goto _L4; else goto _L3
_L3:
}
tyListener(f f1)
{
cM = f1;
super();
}
}
| UTF-8 | Java | 1,723 | java | f$13.java | Java | [
{
"context": "// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.\n// Jad home page: http://www.geocities.com/kpdus",
"end": 61,
"score": 0.9996417164802551,
"start": 45,
"tag": "NAME",
"value": "Pavel Kouznetsov"
}
] | null | [] | // Decompiled by Jad v1.5.8e. Copyright 2001 <NAME>.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.sessionm.core;
import android.util.Log;
import com.sessionm.api.ActivityListener;
import com.sessionm.api.SessionM;
// Referenced classes of package com.sessionm.core:
// f
class
implements Runnable
{
final f cM;
public void run()
{
SessionM sessionm = SessionM.getInstance();
ActivityListener activitylistener = sessionm.getActivityListener();
android.app.Activity activity;
if (activitylistener != null)
{
try
{
activitylistener.onDismissed(sessionm);
}
catch (Throwable throwable1)
{
if (Log.isLoggable("SessionM", 6))
{
Log.e("SessionM.Session", "Exception calling ActivityListener.onDismissed()", throwable1);
}
continue; /* Loop/switch isn't completed */
}
}
_L4:
activity = cM.J();
if (!(activity instanceof ActivityListener) || activity == activitylistener)
{
break MISSING_BLOCK_LABEL_50;
}
((ActivityListener)activity).onDismissed(sessionm);
_L2:
return;
Throwable throwable;
throwable;
if (!Log.isLoggable("SessionM", 6)) goto _L2; else goto _L1
_L1:
Log.e("SessionM.Session", "Exception calling ActivityListener.onDismissed()", throwable);
return;
if (true) goto _L4; else goto _L3
_L3:
}
tyListener(f f1)
{
cM = f1;
super();
}
}
| 1,713 | 0.577481 | 0.564132 | 64 | 25.921875 | 25.473211 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.484375 | false | false | 11 |
519ffa82d63fad34a7483945173cc7f01b947c9e | 14,980,845,950,817 | 1ec8c203bd0665ea8fcf09b3cf99d5d40a31df29 | /src/CorbaDropbox/UserServicePOATie.java | 2be0ea402fdbe56739e4204010e2017584f3ba8b | [] | no_license | horand/CorbaDropbox | https://github.com/horand/CorbaDropbox | c8ab7ac0ae00e1f3fc9700aee3a921ea31f3518e | 4262187e9b21c1cf1564f73b1c753985730973e7 | refs/heads/master | 2016-09-05T15:50:14.147000 | 2013-04-09T18:45:53 | 2013-04-09T18:45:53 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package CorbaDropbox;
/**
* CorbaDropbox/UserServicePOATie.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from ../corbadropbox.idl
* 09 April 2013 15:56:25 o'clock IST
*/
public class UserServicePOATie extends UserServicePOA
{
// Constructors
public UserServicePOATie ( CorbaDropbox.UserServiceOperations delegate ) {
this._impl = delegate;
}
public UserServicePOATie ( CorbaDropbox.UserServiceOperations delegate , org.omg.PortableServer.POA poa ) {
this._impl = delegate;
this._poa = poa;
}
public CorbaDropbox.UserServiceOperations _delegate() {
return this._impl;
}
public void _delegate (CorbaDropbox.UserServiceOperations delegate ) {
this._impl = delegate;
}
public org.omg.PortableServer.POA _default_POA() {
if(_poa != null) {
return _poa;
}
else {
return super._default_POA();
}
}
public boolean register (String username, String password)
{
return _impl.register(username, password);
} // register
public CorbaDropbox.User login (String username, String password)
{
return _impl.login(username, password);
} // login
private CorbaDropbox.UserServiceOperations _impl;
private org.omg.PortableServer.POA _poa;
} // class UserServicePOATie
| UTF-8 | Java | 1,309 | java | UserServicePOATie.java | Java | [] | null | [] | package CorbaDropbox;
/**
* CorbaDropbox/UserServicePOATie.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from ../corbadropbox.idl
* 09 April 2013 15:56:25 o'clock IST
*/
public class UserServicePOATie extends UserServicePOA
{
// Constructors
public UserServicePOATie ( CorbaDropbox.UserServiceOperations delegate ) {
this._impl = delegate;
}
public UserServicePOATie ( CorbaDropbox.UserServiceOperations delegate , org.omg.PortableServer.POA poa ) {
this._impl = delegate;
this._poa = poa;
}
public CorbaDropbox.UserServiceOperations _delegate() {
return this._impl;
}
public void _delegate (CorbaDropbox.UserServiceOperations delegate ) {
this._impl = delegate;
}
public org.omg.PortableServer.POA _default_POA() {
if(_poa != null) {
return _poa;
}
else {
return super._default_POA();
}
}
public boolean register (String username, String password)
{
return _impl.register(username, password);
} // register
public CorbaDropbox.User login (String username, String password)
{
return _impl.login(username, password);
} // login
private CorbaDropbox.UserServiceOperations _impl;
private org.omg.PortableServer.POA _poa;
} // class UserServicePOATie
| 1,309 | 0.688312 | 0.677616 | 50 | 25.18 | 25.456387 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.36 | false | false | 11 |
ad796eea6b061d3f1a6013aea972ddeef217300f | 32,899,449,523,664 | 28c9befe6c39e79f842e5b383734b7a85601fc16 | /src/main/java/commons/BasePage.java | b9fd01a6f366569db8a8cf28be169c1fe8b2cff8 | [] | no_license | keshav-murthy/Dummy_Project | https://github.com/keshav-murthy/Dummy_Project | 296983024b11b89a8145a0db538dcccf1dae2efa | ffeb64bcac6a630641567071f507c88f5d824c31 | refs/heads/main | 2023-07-10T22:40:01.117000 | 2021-08-06T09:04:03 | 2021-08-06T09:04:03 | 393,315,068 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package commons;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.Select;
public abstract class BasePage {
protected WebDriver driver;
protected static ExplicitWait wait;
protected static Actions action;
protected static JavaScriptHelper js;
protected static Random random = new Random();
protected BasePage(WebDriver driver) {
this.driver = driver;
wait = new ExplicitWait(driver);
js = new JavaScriptHelper(driver);
PageFactory.initElements(driver, this);
}
public static void click(WebElement webElement) {
click(webElement, Timeouts.EXPLICIT);
}
public static void click(WebElement webElement, int timeOutInSeconds) {
wait.forElementToBeClickable(webElement, timeOutInSeconds, Timeouts.POLLING_INTERVAL);
js.clickElement(webElement);
}
public static void sendKeys(WebElement webElement, String value, int timeOutInSeconds) {
click(webElement, timeOutInSeconds);
webElement.clear();
webElement.sendKeys(value);
}
public static void sendKeys(WebElement webElement, String value) {
sendKeys(webElement, value, Timeouts.EXPLICIT);
}
public void executeJavascript(String string) {
js.executeScript(string);
}
public void executeJavascript(String string, WebElement element) {
js.executeScript(string, element);
}
public void dropDownMethod(WebElement element, String option, String value) {
Select s = new Select(element);
if (option.equalsIgnoreCase("Value")) {
s.selectByValue(value);
} else if (option.equalsIgnoreCase("VisibleText")) {
s.selectByVisibleText(value);
} else if (option.equalsIgnoreCase("Index")) {
int i = Integer.parseInt(value);
s.selectByIndex(i);
}
}
/* This method will validate partial text */
public static boolean getTextPartialValidate(WebElement element, String value) {
boolean flag = false;
System.out.println("Extracted text is:" + element.getText());
if (element.getText().contains(value)) {
System.out.println("Partial Text comparsion is successful");
flag = true;
} else {
System.out.println("Partial Text comparsion is unsuccessful");
}
return flag;
}
/* This is wrapper method to check the web element is displayed on the page */
public boolean isElementPresence(WebElement webElement) {
return webElement.isEnabled();
}
/* This method will clear the Text */
public void clearText(WebElement element) {
element.clear();
}
/* This method will scroll the web page till bottom of the page */
public static void scrollToBottom() {
js.executeScript("window.scrollTo(0, document.body.scrollHeight)");
}
/* This method will scroll the web page till top of the web page */
public static void scrollToTop() {
js.executeScript("window.scrollTo(0,0)");
}
public static void scrollToPixel(int px) {
js.executeScript("window.scrollTo(0," + px + ")");
}
/* This is wrapper method to check the web element is displayed on the page */
public boolean isElementDisplayed(WebElement webElement) {
return webElement.isDisplayed();
}
/* This method will scroll the web page Vertically till the element is found */
public static void scrollToElementView(WebElement element) {
js.executeScript("arguments[0].scrollIntoView();", element);
}
/* This method will enter value in the input textbox */
public static void javaScriptSendValue(WebElement element, String val) {
js.executeScript("arguments[0].value='" + val + "';", element);
}
/* This method will click on the web element using javascriptexecutor */
public static void javaScriptClick(WebElement element) {
js.executeScript("arguments[0].click();", element);
}
public static void actionsEnter() {
js.actionEnter();
}
public WebElement FindElement(String xpath) {
return driver.findElement(By.xpath(xpath));
}
public static void pause(Integer milliseconds) {
try {
TimeUnit.MILLISECONDS.sleep(milliseconds);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void sleep(long millisecond) {
try {
Thread.sleep(millisecond);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void windowHandling() {
Set<String> windowID = driver.getWindowHandles();
for (String i : windowID)
driver.switchTo().window(i);
}
public void defaultWindow() {
Set<String> windowID = driver.getWindowHandles();
List<String> window = new ArrayList<String>(windowID);
for (int i = 0; i < window.size(); i++)
driver.switchTo().window(window.get(0));
}
public void closeCurrentWindow() {
Set<String> windowID = driver.getWindowHandles();
List<String> window = new ArrayList<String>(windowID);
for (int i = 0; i < window.size(); i++)
driver.switchTo().window(window.get(1)).close();
;
}
public void clickOnOKAlert() {
Alert alert = driver.switchTo().alert();
alert.accept();
}
public String genRandomString() {
String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
StringBuilder salt = new StringBuilder();
Random rnd = new Random();
while (salt.length() < 15) { // length of the random string.
int index = (int) (rnd.nextFloat() * SALTCHARS.length());
salt.append(SALTCHARS.charAt(index));
}
String saltStr = salt.toString();
return saltStr;
}
public void moveToElement(WebElement element, WebElement element2) {
action = new Actions(driver);
action.moveToElement(element).perform();
}
public WebElement selectRandomElement(List<WebElement> element) {
int randomNumberIndex = random.nextInt(element.size());
wait.forElementToBeVisible(element.get(randomNumberIndex));
WebElement randomElement = element.get(randomNumberIndex);
System.out.println("The model selected is :------" + randomElement.getText());
return randomElement;
}
} | UTF-8 | Java | 6,074 | java | BasePage.java | Java | [] | null | [] | package commons;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.Select;
public abstract class BasePage {
protected WebDriver driver;
protected static ExplicitWait wait;
protected static Actions action;
protected static JavaScriptHelper js;
protected static Random random = new Random();
protected BasePage(WebDriver driver) {
this.driver = driver;
wait = new ExplicitWait(driver);
js = new JavaScriptHelper(driver);
PageFactory.initElements(driver, this);
}
public static void click(WebElement webElement) {
click(webElement, Timeouts.EXPLICIT);
}
public static void click(WebElement webElement, int timeOutInSeconds) {
wait.forElementToBeClickable(webElement, timeOutInSeconds, Timeouts.POLLING_INTERVAL);
js.clickElement(webElement);
}
public static void sendKeys(WebElement webElement, String value, int timeOutInSeconds) {
click(webElement, timeOutInSeconds);
webElement.clear();
webElement.sendKeys(value);
}
public static void sendKeys(WebElement webElement, String value) {
sendKeys(webElement, value, Timeouts.EXPLICIT);
}
public void executeJavascript(String string) {
js.executeScript(string);
}
public void executeJavascript(String string, WebElement element) {
js.executeScript(string, element);
}
public void dropDownMethod(WebElement element, String option, String value) {
Select s = new Select(element);
if (option.equalsIgnoreCase("Value")) {
s.selectByValue(value);
} else if (option.equalsIgnoreCase("VisibleText")) {
s.selectByVisibleText(value);
} else if (option.equalsIgnoreCase("Index")) {
int i = Integer.parseInt(value);
s.selectByIndex(i);
}
}
/* This method will validate partial text */
public static boolean getTextPartialValidate(WebElement element, String value) {
boolean flag = false;
System.out.println("Extracted text is:" + element.getText());
if (element.getText().contains(value)) {
System.out.println("Partial Text comparsion is successful");
flag = true;
} else {
System.out.println("Partial Text comparsion is unsuccessful");
}
return flag;
}
/* This is wrapper method to check the web element is displayed on the page */
public boolean isElementPresence(WebElement webElement) {
return webElement.isEnabled();
}
/* This method will clear the Text */
public void clearText(WebElement element) {
element.clear();
}
/* This method will scroll the web page till bottom of the page */
public static void scrollToBottom() {
js.executeScript("window.scrollTo(0, document.body.scrollHeight)");
}
/* This method will scroll the web page till top of the web page */
public static void scrollToTop() {
js.executeScript("window.scrollTo(0,0)");
}
public static void scrollToPixel(int px) {
js.executeScript("window.scrollTo(0," + px + ")");
}
/* This is wrapper method to check the web element is displayed on the page */
public boolean isElementDisplayed(WebElement webElement) {
return webElement.isDisplayed();
}
/* This method will scroll the web page Vertically till the element is found */
public static void scrollToElementView(WebElement element) {
js.executeScript("arguments[0].scrollIntoView();", element);
}
/* This method will enter value in the input textbox */
public static void javaScriptSendValue(WebElement element, String val) {
js.executeScript("arguments[0].value='" + val + "';", element);
}
/* This method will click on the web element using javascriptexecutor */
public static void javaScriptClick(WebElement element) {
js.executeScript("arguments[0].click();", element);
}
public static void actionsEnter() {
js.actionEnter();
}
public WebElement FindElement(String xpath) {
return driver.findElement(By.xpath(xpath));
}
public static void pause(Integer milliseconds) {
try {
TimeUnit.MILLISECONDS.sleep(milliseconds);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void sleep(long millisecond) {
try {
Thread.sleep(millisecond);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void windowHandling() {
Set<String> windowID = driver.getWindowHandles();
for (String i : windowID)
driver.switchTo().window(i);
}
public void defaultWindow() {
Set<String> windowID = driver.getWindowHandles();
List<String> window = new ArrayList<String>(windowID);
for (int i = 0; i < window.size(); i++)
driver.switchTo().window(window.get(0));
}
public void closeCurrentWindow() {
Set<String> windowID = driver.getWindowHandles();
List<String> window = new ArrayList<String>(windowID);
for (int i = 0; i < window.size(); i++)
driver.switchTo().window(window.get(1)).close();
;
}
public void clickOnOKAlert() {
Alert alert = driver.switchTo().alert();
alert.accept();
}
public String genRandomString() {
String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
StringBuilder salt = new StringBuilder();
Random rnd = new Random();
while (salt.length() < 15) { // length of the random string.
int index = (int) (rnd.nextFloat() * SALTCHARS.length());
salt.append(SALTCHARS.charAt(index));
}
String saltStr = salt.toString();
return saltStr;
}
public void moveToElement(WebElement element, WebElement element2) {
action = new Actions(driver);
action.moveToElement(element).perform();
}
public WebElement selectRandomElement(List<WebElement> element) {
int randomNumberIndex = random.nextInt(element.size());
wait.forElementToBeVisible(element.get(randomNumberIndex));
WebElement randomElement = element.get(randomNumberIndex);
System.out.println("The model selected is :------" + randomElement.getText());
return randomElement;
}
} | 6,074 | 0.732137 | 0.728186 | 219 | 26.739725 | 25.046274 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.666667 | false | false | 11 |
ec38e2311dc10f9479b9339694a66ede1f7664c5 | 10,342,281,301,724 | 56de9051c4929856df8ed7477fe144a4b36e9d01 | /plugin/indexer-discovery/src/test/com/ibm/watson/indexwriter/discovery/TestDiscoveryIndexWriter.java | 7913ae49f449840e65ff7388f05da5763c23061c | [] | no_license | IBM-Watson/nutch-indexer-discovery | https://github.com/IBM-Watson/nutch-indexer-discovery | 06de626cf1001bf40e5c4a28e64aa28faf723422 | 22a0a76389825dedae0f89ab25a102ce68e6f850 | refs/heads/master | 2020-12-03T04:03:03.909000 | 2018-10-08T14:08:09 | 2018-10-08T14:08:09 | 95,808,833 | 6 | 9 | null | false | 2018-10-08T14:08:10 | 2017-06-29T18:44:22 | 2018-10-05T19:56:55 | 2018-10-08T14:08:09 | 238 | 5 | 9 | 0 | Java | false | null | /*
* 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.ibm.watson.indexwriter.discovery;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.io.InputStream;
import org.apache.hadoop.conf.Configuration;
import org.apache.nutch.indexer.NutchDocument;
import org.apache.nutch.util.NutchConfiguration;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class TestDiscoveryIndexWriter {
private DiscoveryIndexWriter discoWriter;
private Configuration conf;
private NutchDocument doc;
private boolean documentCreated;
@Rule
public final ExpectedException exception = ExpectedException.none();
@Before
public void setup() {
documentCreated = false;
discoWriter = new DiscoveryIndexWriter() {
@Override
protected boolean createDocumentInDiscovery(String docId, InputStream documentStream) {
documentCreated = true;
return true;
}
};
conf = NutchConfiguration.create();
setDiscoProperties(conf);
doc = new NutchDocument();
doc.add("id", "www.example.com");
}
@Test
public void DiscoIndexWriterCanLoadConfig() {
discoWriter.setConf(conf);
Configuration indexWriterConfig = discoWriter.getConf();
assertEquals(conf, indexWriterConfig);
}
@Test
public void DiscoIndexWriterWillThrowRuntimeExceptionForIncompleteConfig() {
Configuration conf = NutchConfiguration.create();
exception.expect(RuntimeException.class);
discoWriter.setConf(conf);
}
@Test
public void canWriteDocumentToDiscovery() throws IOException {
discoWriter.setConf(conf);
discoWriter.open(conf);
discoWriter.write(doc);
assertTrue(documentCreated);
}
@Test
public void canUpdateDocumentToDiscovery() throws IOException {
discoWriter.setConf(conf);
discoWriter.open(conf);
discoWriter.update(doc);
assertTrue(documentCreated);
}
private void setDiscoProperties(Configuration conf) {
conf.set(DiscoveryConstants.USERNAME, "USERNAME");
conf.set(DiscoveryConstants.PASSWORD, "PASSWORD");
conf.set(DiscoveryConstants.ENVIRONMENT_ID, "ENVIRONMENT_ID");
conf.set(DiscoveryConstants.ENDPOINT, "ENDPOINT");
conf.set(DiscoveryConstants.CONFIGURATION_ID, "CONFIGURGATION_ID");
conf.set(DiscoveryConstants.COLLECTION_ID, "COLLECTION_ID");
conf.set(DiscoveryConstants.API_VERSION, "API_VERSION");
}
} | UTF-8 | Java | 3,190 | java | TestDiscoveryIndexWriter.java | Java | [
{
"context": " {\n conf.set(DiscoveryConstants.USERNAME, \"USERNAME\");\n conf.set(DiscoveryConstants.PASSWORD, ",
"end": 2779,
"score": 0.9994650483131409,
"start": 2771,
"tag": "USERNAME",
"value": "USERNAME"
},
{
"context": ");\n conf.set(DiscoveryConstants.PASSWORD, \"PASSWORD\");\n conf.set(DiscoveryConstants.ENVIRONMEN",
"end": 2838,
"score": 0.997186005115509,
"start": 2830,
"tag": "PASSWORD",
"value": "PASSWORD"
}
] | null | [] | /*
* 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.ibm.watson.indexwriter.discovery;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.io.InputStream;
import org.apache.hadoop.conf.Configuration;
import org.apache.nutch.indexer.NutchDocument;
import org.apache.nutch.util.NutchConfiguration;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class TestDiscoveryIndexWriter {
private DiscoveryIndexWriter discoWriter;
private Configuration conf;
private NutchDocument doc;
private boolean documentCreated;
@Rule
public final ExpectedException exception = ExpectedException.none();
@Before
public void setup() {
documentCreated = false;
discoWriter = new DiscoveryIndexWriter() {
@Override
protected boolean createDocumentInDiscovery(String docId, InputStream documentStream) {
documentCreated = true;
return true;
}
};
conf = NutchConfiguration.create();
setDiscoProperties(conf);
doc = new NutchDocument();
doc.add("id", "www.example.com");
}
@Test
public void DiscoIndexWriterCanLoadConfig() {
discoWriter.setConf(conf);
Configuration indexWriterConfig = discoWriter.getConf();
assertEquals(conf, indexWriterConfig);
}
@Test
public void DiscoIndexWriterWillThrowRuntimeExceptionForIncompleteConfig() {
Configuration conf = NutchConfiguration.create();
exception.expect(RuntimeException.class);
discoWriter.setConf(conf);
}
@Test
public void canWriteDocumentToDiscovery() throws IOException {
discoWriter.setConf(conf);
discoWriter.open(conf);
discoWriter.write(doc);
assertTrue(documentCreated);
}
@Test
public void canUpdateDocumentToDiscovery() throws IOException {
discoWriter.setConf(conf);
discoWriter.open(conf);
discoWriter.update(doc);
assertTrue(documentCreated);
}
private void setDiscoProperties(Configuration conf) {
conf.set(DiscoveryConstants.USERNAME, "USERNAME");
conf.set(DiscoveryConstants.PASSWORD, "<PASSWORD>");
conf.set(DiscoveryConstants.ENVIRONMENT_ID, "ENVIRONMENT_ID");
conf.set(DiscoveryConstants.ENDPOINT, "ENDPOINT");
conf.set(DiscoveryConstants.CONFIGURATION_ID, "CONFIGURGATION_ID");
conf.set(DiscoveryConstants.COLLECTION_ID, "COLLECTION_ID");
conf.set(DiscoveryConstants.API_VERSION, "API_VERSION");
}
} | 3,192 | 0.706583 | 0.705329 | 93 | 33.311829 | 28.326429 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.655914 | false | false | 11 |
801ce80dbdc010448604f47263d8c8cbe1b62303 | 2,233,383,029,910 | f86abb33b32a6275bf760b3175642171579bcac3 | /src/com/ych/web/model/CarouselModel.java | 81af0019e251615c43fcf3c26cb481d0b36fa87d | [] | no_license | net023/ych-wx | https://github.com/net023/ych-wx | 923c75cb94f974dd49f7224a574af07d6ff004d9 | 422464ad7aacd4fdc0d8fc59ef5e846f1dec81ae | refs/heads/master | 2016-08-09T16:52:41.126000 | 2015-06-29T02:05:33 | 2015-06-29T02:05:33 | 36,438,334 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ych.web.model;
import java.util.List;
import com.jfinal.plugin.activerecord.Model;
import com.ych.core.plugin.annotation.Table;
@Table(tableName = "carousel")
public class CarouselModel extends Model<CarouselModel> {
private static final long serialVersionUID = 2752235654049707967L;
public static final CarouselModel dao = new CarouselModel();
public List<CarouselModel> getTopThree() {
return this.find("select f_id, n_id from carousel where status = 0 order by `order`");
}
}
| UTF-8 | Java | 504 | java | CarouselModel.java | Java | [] | null | [] | package com.ych.web.model;
import java.util.List;
import com.jfinal.plugin.activerecord.Model;
import com.ych.core.plugin.annotation.Table;
@Table(tableName = "carousel")
public class CarouselModel extends Model<CarouselModel> {
private static final long serialVersionUID = 2752235654049707967L;
public static final CarouselModel dao = new CarouselModel();
public List<CarouselModel> getTopThree() {
return this.find("select f_id, n_id from carousel where status = 0 order by `order`");
}
}
| 504 | 0.769841 | 0.730159 | 18 | 27 | 27.756882 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.833333 | false | false | 11 |
cad01ffe58095422d1e260c2737cd57d03ed4b07 | 9,835,475,144,624 | 72345e586f19a28c02778be1131c505f396428cd | /code/src/com/bxg796/main/models/DecrypterModel.java | d3fc0128801df0cd972458653019084f9f8ada17 | [] | no_license | BrandonAGoodwin/decrypter | https://github.com/BrandonAGoodwin/decrypter | e3e90e62bd1a79c64a6bc7fd4332f797951acc89 | cdf1635b44906025d60d4876eb0c8fa7d96049d6 | refs/heads/master | 2020-04-25T21:53:19.955000 | 2019-02-28T10:48:43 | 2019-02-28T10:48:43 | 173,093,904 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bxg796.main.models;
import com.bxg796.files.*;
public class DecrypterModel extends AbstractModel{
// Default type of decryption
private static final Decrypter.DecryptionType DEFAULT_TYPE = Decrypter.DecryptionType.TYPE_1;
private static final String OUTPUT_FILE_NAME = "output.txt";
// Files
private FrequenciesFile frequenciesFile;
private CipherFile cipherFile;
private DecryptedFile decryptedFile;
private Decrypter decrypter;
// Stores the current decryption type
private Decrypter.DecryptionType type;
public DecrypterModel(){
super();
/*
frequenciesFile = new FrequenciesFile("frequencies.txt");
cipherFile = new CipherFile("cipher3.txt");
*/
//SUPER IMPORTANT MUST CHANGE
frequenciesFile = null;
cipherFile = null;
decryptedFile = null;
decrypter = null;
type = DEFAULT_TYPE;
}
// Load the frequencies file using its path
public void loadFrequenciesFile(String path){
frequenciesFile = new FrequenciesFile(path);
}
// Load the cipher file using its path
public void loadCipherFile(String path){
cipherFile = new CipherFile(path);
}
// Set the current decryption type to the specifed type
public void setDecryptionType(Decrypter.DecryptionType type){
this.type = type;
}
public void decrypt(){
// Create a decrypter that will decrypt using the two loaded files and the specified decryption type
decrypter = new Decrypter(frequenciesFile, cipherFile, OUTPUT_FILE_NAME, type);
// Create a decrypted file for the new decrypted file
decryptedFile = new DecryptedFile(OUTPUT_FILE_NAME);
}
// Check frequencies file and cipher file have been loaded and read
public boolean checkFilesLoaded(){
if(checkFrequenciesFileLoaded() && checkCipherFileLoaded()){
return true;
}
else{
return false;
}
}
// Check that the frequencies file has been loaded and read
public boolean checkFrequenciesFileLoaded(){
if(frequenciesFile != null && frequenciesFile.checkFileRead()){
return true;
}
else{
return false;
}
}
// check that the cipher file has been loaded and read
public boolean checkCipherFileLoaded(){
if(cipherFile != null && cipherFile.checkFileRead()){
return true;
}
else{
return false;
}
}
}
| UTF-8 | Java | 2,564 | java | DecrypterModel.java | Java | [] | null | [] | package com.bxg796.main.models;
import com.bxg796.files.*;
public class DecrypterModel extends AbstractModel{
// Default type of decryption
private static final Decrypter.DecryptionType DEFAULT_TYPE = Decrypter.DecryptionType.TYPE_1;
private static final String OUTPUT_FILE_NAME = "output.txt";
// Files
private FrequenciesFile frequenciesFile;
private CipherFile cipherFile;
private DecryptedFile decryptedFile;
private Decrypter decrypter;
// Stores the current decryption type
private Decrypter.DecryptionType type;
public DecrypterModel(){
super();
/*
frequenciesFile = new FrequenciesFile("frequencies.txt");
cipherFile = new CipherFile("cipher3.txt");
*/
//SUPER IMPORTANT MUST CHANGE
frequenciesFile = null;
cipherFile = null;
decryptedFile = null;
decrypter = null;
type = DEFAULT_TYPE;
}
// Load the frequencies file using its path
public void loadFrequenciesFile(String path){
frequenciesFile = new FrequenciesFile(path);
}
// Load the cipher file using its path
public void loadCipherFile(String path){
cipherFile = new CipherFile(path);
}
// Set the current decryption type to the specifed type
public void setDecryptionType(Decrypter.DecryptionType type){
this.type = type;
}
public void decrypt(){
// Create a decrypter that will decrypt using the two loaded files and the specified decryption type
decrypter = new Decrypter(frequenciesFile, cipherFile, OUTPUT_FILE_NAME, type);
// Create a decrypted file for the new decrypted file
decryptedFile = new DecryptedFile(OUTPUT_FILE_NAME);
}
// Check frequencies file and cipher file have been loaded and read
public boolean checkFilesLoaded(){
if(checkFrequenciesFileLoaded() && checkCipherFileLoaded()){
return true;
}
else{
return false;
}
}
// Check that the frequencies file has been loaded and read
public boolean checkFrequenciesFileLoaded(){
if(frequenciesFile != null && frequenciesFile.checkFileRead()){
return true;
}
else{
return false;
}
}
// check that the cipher file has been loaded and read
public boolean checkCipherFileLoaded(){
if(cipherFile != null && cipherFile.checkFileRead()){
return true;
}
else{
return false;
}
}
}
| 2,564 | 0.645086 | 0.641966 | 93 | 26.569893 | 25.441647 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 11 |
6ec0bb46865c64b2416f63085b620f599851229a | 32,152,125,224,792 | 1f27be32d4afb40f8474b03dea1f0183f5504e06 | /src/CodingInterviewGuide/demo/Chapter4/Getdp.java | dbac3f8579e2ecfd377eda4b7066a07b8bcf45c8 | [] | no_license | GitHubForDove/CodingInterViewGuide_20191112 | https://github.com/GitHubForDove/CodingInterViewGuide_20191112 | 4651c36f1440747f4e2f3736cee4ea1a377b6e71 | fa9f0e3462a3588f1e2104426e651f40eead07b2 | refs/heads/master | 2020-09-13T23:21:51.616000 | 2020-01-15T14:11:03 | 2020-01-15T14:11:03 | 222,936,608 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package CodingInterviewGuide.demo.Chapter4;
/**
* 最长递增 子序列
*
* 题目:
* 给定数组 arr, 返回 arr的最长递增子序列
*
* 举例:
*
* arr = [2,1,5,3,6,4,8,9,7],返回最长递增子序列为 [1,3,4,8,9]
*/
public class Getdp {
public int[] getdp1(int[] arr) {
int[] dp = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
dp[i] = 1;
for (int j = 0; j < i; j++) {
if (dp[i] > dp[j]) {
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
}
return dp;
}
}
| UTF-8 | Java | 628 | java | Getdp.java | Java | [] | null | [] | package CodingInterviewGuide.demo.Chapter4;
/**
* 最长递增 子序列
*
* 题目:
* 给定数组 arr, 返回 arr的最长递增子序列
*
* 举例:
*
* arr = [2,1,5,3,6,4,8,9,7],返回最长递增子序列为 [1,3,4,8,9]
*/
public class Getdp {
public int[] getdp1(int[] arr) {
int[] dp = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
dp[i] = 1;
for (int j = 0; j < i; j++) {
if (dp[i] > dp[j]) {
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
}
return dp;
}
}
| 628 | 0.404762 | 0.368132 | 29 | 17.827587 | 17.679268 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.689655 | false | false | 11 |
b75098c97ec999ce32bf9216dfee4247d19a3256 | 34,668,976,036,264 | 3337ff33ee303232550ccf167d479d05c010a0ce | /build/generated/source/apt/release/com/qizhi/qilaiqiqu/activity/Activity_NewConsultInformActivity$$ViewInjector.java | 29a07217e3a9be00ef32a33920ccb335fd1da7d4 | [] | no_license | 18984955240/Qilaiqiqu | https://github.com/18984955240/Qilaiqiqu | cb61a152fe73cff7cc4bde5efbbb2ec6efb99790 | bdb4773b3dafb04da6c5a9653085ca4dde28e928 | refs/heads/master | 2020-07-12T01:37:04.657000 | 2016-11-21T05:00:14 | 2016-11-21T05:00:14 | 73,987,369 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | // Generated code from Butter Knife. Do not modify!
package com.qizhi.qilaiqiqu.activity;
import android.view.View;
import butterknife.ButterKnife.Finder;
import butterknife.ButterKnife.Injector;
public class Activity_NewConsultInformActivity$$ViewInjector<T extends com.qizhi.qilaiqiqu.activity.Activity_NewConsultInformActivity> implements Injector<T> {
@Override public void inject(final Finder finder, final T target, Object source) {
View view;
view = finder.findRequiredView(source, 2131558513, "field 'layoutBack' and method 'onClick'");
target.layoutBack = finder.castView(view, 2131558513, "field 'layoutBack'");
view.setOnClickListener(
new butterknife.internal.DebouncingOnClickListener() {
@Override public void doClick(
android.view.View p0
) {
target.onClick(p0);
}
});
view = finder.findRequiredView(source, 2131558561, "field 'imgRidingCommentPhoto'");
target.imgRidingCommentPhoto = finder.castView(view, 2131558561, "field 'imgRidingCommentPhoto'");
view = finder.findRequiredView(source, 2131558562, "field 'textCommentmessageactivityMessage'");
target.textCommentmessageactivityMessage = finder.castView(view, 2131558562, "field 'textCommentmessageactivityMessage'");
view = finder.findRequiredView(source, 2131558563, "field 'txtContent'");
target.txtContent = finder.castView(view, 2131558563, "field 'txtContent'");
view = finder.findRequiredView(source, 2131558564, "field 'footerViewRidingPhoto'");
target.footerViewRidingPhoto = finder.castView(view, 2131558564, "field 'footerViewRidingPhoto'");
view = finder.findRequiredView(source, 2131558565, "field 'txtActivity'");
target.txtActivity = finder.castView(view, 2131558565, "field 'txtActivity'");
view = finder.findRequiredView(source, 2131558566, "field 'txtRidingTitle'");
target.txtRidingTitle = finder.castView(view, 2131558566, "field 'txtRidingTitle'");
view = finder.findRequiredView(source, 2131558567, "field 'txtFooterViewRidingTitle'");
target.txtFooterViewRidingTitle = finder.castView(view, 2131558567, "field 'txtFooterViewRidingTitle'");
view = finder.findRequiredView(source, 2131558568, "field 'imgFooterViewRidingScanNum'");
target.imgFooterViewRidingScanNum = finder.castView(view, 2131558568, "field 'imgFooterViewRidingScanNum'");
view = finder.findRequiredView(source, 2131558569, "field 'txtFooterViewRidingScanNum'");
target.txtFooterViewRidingScanNum = finder.castView(view, 2131558569, "field 'txtFooterViewRidingScanNum'");
view = finder.findRequiredView(source, 2131558570, "field 'imgFooterViewRidingLike'");
target.imgFooterViewRidingLike = finder.castView(view, 2131558570, "field 'imgFooterViewRidingLike'");
view = finder.findRequiredView(source, 2131558572, "field 'txtFooterViewRidingLike'");
target.txtFooterViewRidingLike = finder.castView(view, 2131558572, "field 'txtFooterViewRidingLike'");
view = finder.findRequiredView(source, 2131558571, "field 'txtFooterViewRidingComment'");
target.txtFooterViewRidingComment = finder.castView(view, 2131558571, "field 'txtFooterViewRidingComment'");
view = finder.findRequiredView(source, 2131558573, "field 'txtFooterViewCheckIt'");
target.txtFooterViewCheckIt = finder.castView(view, 2131558573, "field 'txtFooterViewCheckIt'");
view = finder.findRequiredView(source, 2131558574, "field 'txtReply'");
target.txtReply = finder.castView(view, 2131558574, "field 'txtReply'");
view = finder.findRequiredView(source, 2131558575, "field 'txtCheckAll' and method 'onClick'");
target.txtCheckAll = finder.castView(view, 2131558575, "field 'txtCheckAll'");
view.setOnClickListener(
new butterknife.internal.DebouncingOnClickListener() {
@Override public void doClick(
android.view.View p0
) {
target.onClick(p0);
}
});
view = finder.findRequiredView(source, 2131558577, "field 'edtContent'");
target.edtContent = finder.castView(view, 2131558577, "field 'edtContent'");
view = finder.findRequiredView(source, 2131558578, "field 'txtNcommit' and method 'onClick'");
target.txtNcommit = finder.castView(view, 2131558578, "field 'txtNcommit'");
view.setOnClickListener(
new butterknife.internal.DebouncingOnClickListener() {
@Override public void doClick(
android.view.View p0
) {
target.onClick(p0);
}
});
view = finder.findRequiredView(source, 2131558576, "field 'layoutReply'");
target.layoutReply = finder.castView(view, 2131558576, "field 'layoutReply'");
}
@Override public void reset(T target) {
target.layoutBack = null;
target.imgRidingCommentPhoto = null;
target.textCommentmessageactivityMessage = null;
target.txtContent = null;
target.footerViewRidingPhoto = null;
target.txtActivity = null;
target.txtRidingTitle = null;
target.txtFooterViewRidingTitle = null;
target.imgFooterViewRidingScanNum = null;
target.txtFooterViewRidingScanNum = null;
target.imgFooterViewRidingLike = null;
target.txtFooterViewRidingLike = null;
target.txtFooterViewRidingComment = null;
target.txtFooterViewCheckIt = null;
target.txtReply = null;
target.txtCheckAll = null;
target.edtContent = null;
target.txtNcommit = null;
target.layoutReply = null;
}
}
| UTF-8 | Java | 5,423 | java | Activity_NewConsultInformActivity$$ViewInjector.java | Java | [] | null | [] | // Generated code from Butter Knife. Do not modify!
package com.qizhi.qilaiqiqu.activity;
import android.view.View;
import butterknife.ButterKnife.Finder;
import butterknife.ButterKnife.Injector;
public class Activity_NewConsultInformActivity$$ViewInjector<T extends com.qizhi.qilaiqiqu.activity.Activity_NewConsultInformActivity> implements Injector<T> {
@Override public void inject(final Finder finder, final T target, Object source) {
View view;
view = finder.findRequiredView(source, 2131558513, "field 'layoutBack' and method 'onClick'");
target.layoutBack = finder.castView(view, 2131558513, "field 'layoutBack'");
view.setOnClickListener(
new butterknife.internal.DebouncingOnClickListener() {
@Override public void doClick(
android.view.View p0
) {
target.onClick(p0);
}
});
view = finder.findRequiredView(source, 2131558561, "field 'imgRidingCommentPhoto'");
target.imgRidingCommentPhoto = finder.castView(view, 2131558561, "field 'imgRidingCommentPhoto'");
view = finder.findRequiredView(source, 2131558562, "field 'textCommentmessageactivityMessage'");
target.textCommentmessageactivityMessage = finder.castView(view, 2131558562, "field 'textCommentmessageactivityMessage'");
view = finder.findRequiredView(source, 2131558563, "field 'txtContent'");
target.txtContent = finder.castView(view, 2131558563, "field 'txtContent'");
view = finder.findRequiredView(source, 2131558564, "field 'footerViewRidingPhoto'");
target.footerViewRidingPhoto = finder.castView(view, 2131558564, "field 'footerViewRidingPhoto'");
view = finder.findRequiredView(source, 2131558565, "field 'txtActivity'");
target.txtActivity = finder.castView(view, 2131558565, "field 'txtActivity'");
view = finder.findRequiredView(source, 2131558566, "field 'txtRidingTitle'");
target.txtRidingTitle = finder.castView(view, 2131558566, "field 'txtRidingTitle'");
view = finder.findRequiredView(source, 2131558567, "field 'txtFooterViewRidingTitle'");
target.txtFooterViewRidingTitle = finder.castView(view, 2131558567, "field 'txtFooterViewRidingTitle'");
view = finder.findRequiredView(source, 2131558568, "field 'imgFooterViewRidingScanNum'");
target.imgFooterViewRidingScanNum = finder.castView(view, 2131558568, "field 'imgFooterViewRidingScanNum'");
view = finder.findRequiredView(source, 2131558569, "field 'txtFooterViewRidingScanNum'");
target.txtFooterViewRidingScanNum = finder.castView(view, 2131558569, "field 'txtFooterViewRidingScanNum'");
view = finder.findRequiredView(source, 2131558570, "field 'imgFooterViewRidingLike'");
target.imgFooterViewRidingLike = finder.castView(view, 2131558570, "field 'imgFooterViewRidingLike'");
view = finder.findRequiredView(source, 2131558572, "field 'txtFooterViewRidingLike'");
target.txtFooterViewRidingLike = finder.castView(view, 2131558572, "field 'txtFooterViewRidingLike'");
view = finder.findRequiredView(source, 2131558571, "field 'txtFooterViewRidingComment'");
target.txtFooterViewRidingComment = finder.castView(view, 2131558571, "field 'txtFooterViewRidingComment'");
view = finder.findRequiredView(source, 2131558573, "field 'txtFooterViewCheckIt'");
target.txtFooterViewCheckIt = finder.castView(view, 2131558573, "field 'txtFooterViewCheckIt'");
view = finder.findRequiredView(source, 2131558574, "field 'txtReply'");
target.txtReply = finder.castView(view, 2131558574, "field 'txtReply'");
view = finder.findRequiredView(source, 2131558575, "field 'txtCheckAll' and method 'onClick'");
target.txtCheckAll = finder.castView(view, 2131558575, "field 'txtCheckAll'");
view.setOnClickListener(
new butterknife.internal.DebouncingOnClickListener() {
@Override public void doClick(
android.view.View p0
) {
target.onClick(p0);
}
});
view = finder.findRequiredView(source, 2131558577, "field 'edtContent'");
target.edtContent = finder.castView(view, 2131558577, "field 'edtContent'");
view = finder.findRequiredView(source, 2131558578, "field 'txtNcommit' and method 'onClick'");
target.txtNcommit = finder.castView(view, 2131558578, "field 'txtNcommit'");
view.setOnClickListener(
new butterknife.internal.DebouncingOnClickListener() {
@Override public void doClick(
android.view.View p0
) {
target.onClick(p0);
}
});
view = finder.findRequiredView(source, 2131558576, "field 'layoutReply'");
target.layoutReply = finder.castView(view, 2131558576, "field 'layoutReply'");
}
@Override public void reset(T target) {
target.layoutBack = null;
target.imgRidingCommentPhoto = null;
target.textCommentmessageactivityMessage = null;
target.txtContent = null;
target.footerViewRidingPhoto = null;
target.txtActivity = null;
target.txtRidingTitle = null;
target.txtFooterViewRidingTitle = null;
target.imgFooterViewRidingScanNum = null;
target.txtFooterViewRidingScanNum = null;
target.imgFooterViewRidingLike = null;
target.txtFooterViewRidingLike = null;
target.txtFooterViewRidingComment = null;
target.txtFooterViewCheckIt = null;
target.txtReply = null;
target.txtCheckAll = null;
target.edtContent = null;
target.txtNcommit = null;
target.layoutReply = null;
}
}
| 5,423 | 0.738706 | 0.667527 | 96 | 55.489582 | 35.800953 | 159 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.520833 | false | false | 11 |
a814b397f466e3970f17935d37b3021dcae2d66a | 34,668,976,035,964 | ac5f4b4eacf63bb55914efb8d33f314192732827 | /app/src/main/java/com/merodyadt/belotasistent/AboutActivity.java | 23126ceaf806a421de9bc6963a6c2ef503bbabfc | [
"MIT"
] | permissive | mlogic1/Belot-Asistent | https://github.com/mlogic1/Belot-Asistent | 671db284ec6b3b69f5044d9cecb05fede27171c8 | 4cd5ce3944d56bf7bbce5e7b94c6b668601b985f | refs/heads/master | 2023-03-02T23:38:08.286000 | 2020-05-09T17:48:51 | 2020-05-09T17:48:51 | 63,529,228 | 1 | 2 | MIT | false | 2021-01-01T16:35:58 | 2016-07-17T11:46:26 | 2020-07-18T19:18:24 | 2021-01-01T16:35:58 | 16,842 | 1 | 1 | 0 | Java | false | false | package com.merodyadt.belotasistent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
public class AboutActivity extends AppCompatActivity {
private Toolbar toolbar;
// Application settings
SharedPreferences preferences;
String appThemeColor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
LoadSettings();
SetupToolBar();
}
private void LoadSettings(){
preferences = PreferenceManager.getDefaultSharedPreferences(this);
appThemeColor = preferences.getString("themeColor", "");
}
private void SetupToolBar(){
toolbar = (Toolbar)findViewById(R.id.toolBarAbout);
toolbar.setTitle(R.string.ActivityAboutToolBarText);
toolbar.setTitleTextColor(Color.WHITE);
toolbar.setBackgroundColor(Color.parseColor(appThemeColor));
setSupportActionBar(toolbar);
}
public void OpenGitHubHyperlink(View view){
Uri uri = Uri.parse("https://github.com/mlogic1/Belot-asistent");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
public void OpenCC4LicenseHyperlink(View view){
Uri uri = Uri.parse("https://creativecommons.org/licenses/by/4.0/legalcode");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
}
| UTF-8 | Java | 1,707 | java | AboutActivity.java | Java | [
{
"context": "{\n Uri uri = Uri.parse(\"https://github.com/mlogic1/Belot-asistent\");\n Intent intent = new Int",
"end": 1351,
"score": 0.9996196627616882,
"start": 1344,
"tag": "USERNAME",
"value": "mlogic1"
}
] | null | [] | package com.merodyadt.belotasistent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
public class AboutActivity extends AppCompatActivity {
private Toolbar toolbar;
// Application settings
SharedPreferences preferences;
String appThemeColor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
LoadSettings();
SetupToolBar();
}
private void LoadSettings(){
preferences = PreferenceManager.getDefaultSharedPreferences(this);
appThemeColor = preferences.getString("themeColor", "");
}
private void SetupToolBar(){
toolbar = (Toolbar)findViewById(R.id.toolBarAbout);
toolbar.setTitle(R.string.ActivityAboutToolBarText);
toolbar.setTitleTextColor(Color.WHITE);
toolbar.setBackgroundColor(Color.parseColor(appThemeColor));
setSupportActionBar(toolbar);
}
public void OpenGitHubHyperlink(View view){
Uri uri = Uri.parse("https://github.com/mlogic1/Belot-asistent");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
public void OpenCC4LicenseHyperlink(View view){
Uri uri = Uri.parse("https://creativecommons.org/licenses/by/4.0/legalcode");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
}
| 1,707 | 0.718219 | 0.714704 | 55 | 30.036364 | 23.731808 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 11 |
d545c6f1a9cfa2a6cfdecd214a8bdc2cf948bc0e | 31,756,988,229,604 | 1bdb9ca1da787091843a29093f2a21dd94e4a916 | /src/main/java/atos/manolito/entity/UserDataExtended.java | d809e8a8a856131382023a4ab3cb58f023469201 | [] | no_license | JorgeMantinan/EmailPdfAndExceptions | https://github.com/JorgeMantinan/EmailPdfAndExceptions | ec3f10b14ad713165eedc0c7fc839e09f1055c87 | 36fe69699d223dbcdb83f8e5820b1f2fe7c300f8 | refs/heads/master | 2023-06-16T09:58:23.164000 | 2021-07-17T20:16:40 | 2021-07-17T20:16:40 | 387,029,718 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package atos.manolito.entity;
import java.io.Serializable;
import java.util.Date;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.MapsId;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.Pattern;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import atos.manolito.entity.UserData;
import atos.manolito.security.constraint.ValidIban;
import atos.manolito.security.constraint.ValidNif;
import atos.manolito.security.constraint.ValidNie;
import atos.manolito.security.constraint.ValidSSNumber;
/**
* Entidad que guarda la información adicional sobre el usuario.
* Su id es el mismo del usuario
*
* @author FGS
* @since 08/11/2019
*
*
*/
@Entity
@Table(name="USERDATA")
public class UserDataExtended implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@Column(name="userdataextended_id")
private int id;
// FGS 10/12/19 Cambios para almacenar de forma separada NIF, NIE y pasaporte
@Column(name="NIF",unique = true, columnDefinition = "VARCHAR(9) COMMENT 'Formato NIF: 8 dígitos y 1 letra.'")
@ValidNif(optional=true)
private String nif;
@Column(name="NIE",unique = true, columnDefinition = "VARCHAR(9) COMMENT 'Formato NIE: 1 letra (X,Y o Z), 7 dígitos y 1 letra.'")
@ValidNie(optional=true)
private String nie;
@Column(name="PASSPORT",unique = true, columnDefinition = "VARCHAR(9) COMMENT 'Formato pasaporte: 3 letras y 6 dígitos.'")
@Pattern(regexp="^[A-Z]{3}[0-9]{6}$", message="no tiene el formato apropiado (3 letras y 6 dígitos)")
private String passport;
// Número de la Seguridad Social del usuario.
@Column(name="SS_NUMBER",unique = true,columnDefinition = "VARCHAR(12) COMMENT 'Formato: 12 dígitos.'")
@ValidSSNumber(optional=true)
private String ssNumber;
@Column(name="IBAN_NUMBER",unique = true,columnDefinition = "VARCHAR(24) COMMENT 'Formato: ES seguido de 22 dígitos.'")
@ValidIban(optional=true)
private String ibanNumber;
@OneToMany(fetch = FetchType.LAZY)
@Cascade({CascadeType.ALL})
@JoinColumn(name="userdataextended_user_data_id")
@JsonIgnoreProperties(value = {"userdataextended"})
private Set<Address> addresses;
//FGS 08/11/19. Introducida la relación con los datos básicos del usuario.
@OneToOne(fetch = FetchType.LAZY)
@MapsId
@JsonIgnoreProperties(value = {"userDataExtended"})
private UserData userData;
private int salary;
private int payments;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="special_condition")
private Specialconditions specialCondition;
@Temporal(TemporalType.DATE)
private Date firedDate;
@Temporal(TemporalType.DATE)
private Date hiredDate;
public Set<Address> getAddresses() {
return addresses;
}
public void setAddresses(Set<Address> addresses) {
this.addresses = addresses;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNif() {
return nif;
}
public void setNif(String nif) {
this.nif = nif;
}
public String getNie() {
return nie;
}
public void setNie(String nie) {
this.nie = nie;
}
public String getPassport() {
return passport;
}
public void setPassport(String passport) {
this.passport = passport;
}
public String getSsNumber() {
return ssNumber;
}
public void setSsNumber(String ssNumber) {
this.ssNumber = ssNumber;
}
public String getIbanNumber() {
return ibanNumber;
}
public void setIbanNumber(String ibanNumber) {
this.ibanNumber = ibanNumber;
}
public UserData getUserData() {
return userData;
}
public void setUserData(UserData userData) {
this.userData = userData;
}
public int getPayments() {
return payments;
}
public Specialconditions getSpecialCondition() {
return specialCondition;
}
public Date getFiredDate() {
return firedDate;
}
public Date getHiredDate() {
return hiredDate;
}
public void setPayments(int payments) {
this.payments = payments;
}
public void setSpecialCondition(Specialconditions specialCondition) {
this.specialCondition = specialCondition;
}
public void setFiredDate(Date firedDate) {
this.firedDate = firedDate;
}
public void setHiredDate(Date hiredDate) {
this.hiredDate = hiredDate;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
@Override
public String toString() {
return "UserDataExtended [id=" + id + ", nif=" + nif + ", nie=" + nie + ", passport=" + passport + ", ssNumber="
+ ssNumber + ", ibanNumber=" + ibanNumber + ", salary=" + salary + ", payments=" + payments
+ ", specialCondition=" + specialCondition + ", firedDate=" + firedDate + ", hiredDate=" + hiredDate
+ "]";
}
}
| UTF-8 | Java | 5,146 | java | UserDataExtended.java | Java | [
{
"context": ". \n * Su id es el mismo del usuario\n * \n * @author FGS\n * @since 08/11/2019\n * \n * \n */\n@Entity\n@Table",
"end": 1088,
"score": 0.9425727725028992,
"start": 1085,
"tag": "USERNAME",
"value": "FGS"
}
] | null | [] | package atos.manolito.entity;
import java.io.Serializable;
import java.util.Date;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.MapsId;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.Pattern;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import atos.manolito.entity.UserData;
import atos.manolito.security.constraint.ValidIban;
import atos.manolito.security.constraint.ValidNif;
import atos.manolito.security.constraint.ValidNie;
import atos.manolito.security.constraint.ValidSSNumber;
/**
* Entidad que guarda la información adicional sobre el usuario.
* Su id es el mismo del usuario
*
* @author FGS
* @since 08/11/2019
*
*
*/
@Entity
@Table(name="USERDATA")
public class UserDataExtended implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@Column(name="userdataextended_id")
private int id;
// FGS 10/12/19 Cambios para almacenar de forma separada NIF, NIE y pasaporte
@Column(name="NIF",unique = true, columnDefinition = "VARCHAR(9) COMMENT 'Formato NIF: 8 dígitos y 1 letra.'")
@ValidNif(optional=true)
private String nif;
@Column(name="NIE",unique = true, columnDefinition = "VARCHAR(9) COMMENT 'Formato NIE: 1 letra (X,Y o Z), 7 dígitos y 1 letra.'")
@ValidNie(optional=true)
private String nie;
@Column(name="PASSPORT",unique = true, columnDefinition = "VARCHAR(9) COMMENT 'Formato pasaporte: 3 letras y 6 dígitos.'")
@Pattern(regexp="^[A-Z]{3}[0-9]{6}$", message="no tiene el formato apropiado (3 letras y 6 dígitos)")
private String passport;
// Número de la Seguridad Social del usuario.
@Column(name="SS_NUMBER",unique = true,columnDefinition = "VARCHAR(12) COMMENT 'Formato: 12 dígitos.'")
@ValidSSNumber(optional=true)
private String ssNumber;
@Column(name="IBAN_NUMBER",unique = true,columnDefinition = "VARCHAR(24) COMMENT 'Formato: ES seguido de 22 dígitos.'")
@ValidIban(optional=true)
private String ibanNumber;
@OneToMany(fetch = FetchType.LAZY)
@Cascade({CascadeType.ALL})
@JoinColumn(name="userdataextended_user_data_id")
@JsonIgnoreProperties(value = {"userdataextended"})
private Set<Address> addresses;
//FGS 08/11/19. Introducida la relación con los datos básicos del usuario.
@OneToOne(fetch = FetchType.LAZY)
@MapsId
@JsonIgnoreProperties(value = {"userDataExtended"})
private UserData userData;
private int salary;
private int payments;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="special_condition")
private Specialconditions specialCondition;
@Temporal(TemporalType.DATE)
private Date firedDate;
@Temporal(TemporalType.DATE)
private Date hiredDate;
public Set<Address> getAddresses() {
return addresses;
}
public void setAddresses(Set<Address> addresses) {
this.addresses = addresses;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNif() {
return nif;
}
public void setNif(String nif) {
this.nif = nif;
}
public String getNie() {
return nie;
}
public void setNie(String nie) {
this.nie = nie;
}
public String getPassport() {
return passport;
}
public void setPassport(String passport) {
this.passport = passport;
}
public String getSsNumber() {
return ssNumber;
}
public void setSsNumber(String ssNumber) {
this.ssNumber = ssNumber;
}
public String getIbanNumber() {
return ibanNumber;
}
public void setIbanNumber(String ibanNumber) {
this.ibanNumber = ibanNumber;
}
public UserData getUserData() {
return userData;
}
public void setUserData(UserData userData) {
this.userData = userData;
}
public int getPayments() {
return payments;
}
public Specialconditions getSpecialCondition() {
return specialCondition;
}
public Date getFiredDate() {
return firedDate;
}
public Date getHiredDate() {
return hiredDate;
}
public void setPayments(int payments) {
this.payments = payments;
}
public void setSpecialCondition(Specialconditions specialCondition) {
this.specialCondition = specialCondition;
}
public void setFiredDate(Date firedDate) {
this.firedDate = firedDate;
}
public void setHiredDate(Date hiredDate) {
this.hiredDate = hiredDate;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
@Override
public String toString() {
return "UserDataExtended [id=" + id + ", nif=" + nif + ", nie=" + nie + ", passport=" + passport + ", ssNumber="
+ ssNumber + ", ibanNumber=" + ibanNumber + ", salary=" + salary + ", payments=" + payments
+ ", specialCondition=" + specialCondition + ", firedDate=" + firedDate + ", hiredDate=" + hiredDate
+ "]";
}
}
| 5,146 | 0.731698 | 0.722936 | 213 | 23.112677 | 25.988739 | 131 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.253521 | false | false | 11 |
2a4d688fa6350aa3cea878df27a0462a0e693427 | 31,756,988,226,513 | 7fcc93bb172b4416bf5eea5b603f8af59a95e52a | /app/src/main/java/com/example/recyle/Admin/AdminList.java | 90b6b3870f714556afbab78d113d2a445a7c7495 | [] | no_license | deddy3212/zoologyca | https://github.com/deddy3212/zoologyca | 10bc231471e0026568662b7efb6e09e1a3d66c63 | e1481aa67070dae716c189dfe78271d6b859240c | refs/heads/master | 2023-01-01T13:47:30.781000 | 2020-10-24T10:37:55 | 2020-10-24T10:37:55 | 306,859,822 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.recyle.Admin;
import android.annotation.SuppressLint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.app.Activity;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.example.recyle.R;
import java.util.List;
public class AdminList extends ArrayAdapter<Admin> {
private Activity context;
private List<Admin> adminList;
AdminList(Activity context, List<Admin> adminList){
super(context, R.layout.list_view_admin, adminList);
this.context = context;
this.adminList = adminList;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
@SuppressLint({"ViewHolder", "InflateParams"}) View listViewItem = inflater.inflate(R.layout.list_view_admin, null, true);
TextView textViewNIM = listViewItem.findViewById(R.id.textViewNIM);
TextView textViewName = listViewItem.findViewById(R.id.textViewName);
Admin admins = adminList.get(position);
textViewNIM.setText(admins.getEmail());
textViewName.setText(admins.getName());
return listViewItem;
}
}
| UTF-8 | Java | 1,364 | java | AdminList.java | Java | [] | null | [] | package com.example.recyle.Admin;
import android.annotation.SuppressLint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.app.Activity;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.example.recyle.R;
import java.util.List;
public class AdminList extends ArrayAdapter<Admin> {
private Activity context;
private List<Admin> adminList;
AdminList(Activity context, List<Admin> adminList){
super(context, R.layout.list_view_admin, adminList);
this.context = context;
this.adminList = adminList;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
@SuppressLint({"ViewHolder", "InflateParams"}) View listViewItem = inflater.inflate(R.layout.list_view_admin, null, true);
TextView textViewNIM = listViewItem.findViewById(R.id.textViewNIM);
TextView textViewName = listViewItem.findViewById(R.id.textViewName);
Admin admins = adminList.get(position);
textViewNIM.setText(admins.getEmail());
textViewName.setText(admins.getName());
return listViewItem;
}
}
| 1,364 | 0.731672 | 0.731672 | 48 | 27.416666 | 28.306236 | 130 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6875 | false | false | 11 |
a99844d79ba1c946833521e8437f6cc82c4ace00 | 35,536,559,420,334 | ea2b76a2873beb19ce3f9d278a3ff0dbd97bd6a1 | /src/test/java/com/bdd/tests/integration/AppointmentProperties.java | d2a69c7e3e7ca946f1654f5d7b2f80dcd15d3c4b | [] | no_license | shalabi67/BddExample3 | https://github.com/shalabi67/BddExample3 | 02417d5adb13d6c325b34a78da44ce7775dbfc35 | 9315886079fa8c7fe38308e9c76cbb773cbc6d35 | refs/heads/master | 2020-05-16T18:00:17.534000 | 2019-04-27T18:39:53 | 2019-04-27T18:39:53 | 183,211,651 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bdd.tests.integration;
import com.bdd.appointments.queue.QueueProcessor;
import com.bdd.framework.Properties;
public class AppointmentProperties extends Properties {
private QueueProcessor queueProcessor;
public QueueProcessor getQueueProcessor() {
return queueProcessor;
}
public void setQueueProcessor(QueueProcessor queueProcessor) {
this.queueProcessor = queueProcessor;
}
}
| UTF-8 | Java | 431 | java | AppointmentProperties.java | Java | [] | null | [] | package com.bdd.tests.integration;
import com.bdd.appointments.queue.QueueProcessor;
import com.bdd.framework.Properties;
public class AppointmentProperties extends Properties {
private QueueProcessor queueProcessor;
public QueueProcessor getQueueProcessor() {
return queueProcessor;
}
public void setQueueProcessor(QueueProcessor queueProcessor) {
this.queueProcessor = queueProcessor;
}
}
| 431 | 0.767981 | 0.767981 | 16 | 25.9375 | 22.938692 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false | 11 |
024ef77725014bee540588d3fad66069f02afa59 | 17,884,243,867,261 | 7259ba7d098783148b8fe827fbe851bc45853035 | /test123/src/test/java/testScript/Test1.java | fe6d0f8d87376fd64f8ae71dc8634895a699f94c | [] | no_license | nilaykm12345/Test123 | https://github.com/nilaykm12345/Test123 | bb87adff4d9121368b97a3d88675e5bfc9673a2c | b233cb07cfa6720c549739c6df94d70e011ddba3 | refs/heads/master | 2020-03-19T04:50:49.707000 | 2018-06-03T05:35:41 | 2018-06-03T05:35:41 | 135,874,040 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package testScript;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.Reporter;
import org.testng.annotations.Test;
import pom.GoogleHomePO;
import pom.GoogleSearchPO;
//import pom.SearchPO;
import Library.BaseTest;
public class Test1 extends BaseTest
{
@Test
public void testFaceBookHkome() {
wait=new WebDriverWait(driver, 20);
driver.get("https://google.com");
GoogleHomePO googprPO=new GoogleHomePO(driver);
googprPO.searchTxtBx().sendKeys("facebook"+Keys.ENTER);
GoogleSearchPO searchpo=new GoogleSearchPO(driver);
searchpo.verifyElement(searchpo.facebooklink());
searchpo.facebooklink().click();
WebDriverWait wait = new WebDriverWait(driver, 10);
String eTitle= "Facebook – log in or sign up1";
wait.until(ExpectedConditions.titleContains(eTitle));
String aTitle = driver.getTitle();
Reporter.log("Tital displayed is"+aTitle,true);
Assert.assertEquals(aTitle,eTitle);
}
}
| WINDOWS-1252 | Java | 1,132 | java | Test1.java | Java | [] | null | [] | package testScript;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.Reporter;
import org.testng.annotations.Test;
import pom.GoogleHomePO;
import pom.GoogleSearchPO;
//import pom.SearchPO;
import Library.BaseTest;
public class Test1 extends BaseTest
{
@Test
public void testFaceBookHkome() {
wait=new WebDriverWait(driver, 20);
driver.get("https://google.com");
GoogleHomePO googprPO=new GoogleHomePO(driver);
googprPO.searchTxtBx().sendKeys("facebook"+Keys.ENTER);
GoogleSearchPO searchpo=new GoogleSearchPO(driver);
searchpo.verifyElement(searchpo.facebooklink());
searchpo.facebooklink().click();
WebDriverWait wait = new WebDriverWait(driver, 10);
String eTitle= "Facebook – log in or sign up1";
wait.until(ExpectedConditions.titleContains(eTitle));
String aTitle = driver.getTitle();
Reporter.log("Tital displayed is"+aTitle,true);
Assert.assertEquals(aTitle,eTitle);
}
}
| 1,132 | 0.752212 | 0.746903 | 36 | 29.388889 | 19.144592 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.777778 | false | false | 11 |
568c4dd03476f8c7eaf511c33541013aa96543c0 | 35,218,731,842,500 | 8b7bda36cf7689054659a718a44f7d6269c17745 | /app/src/main/java/com/example/food1/HomeActivity.java | 6bb2efd5ebf5d73ee35e3cdb0996d847f43fbb7b | [] | no_license | AdityaPrabhuCS/DevHack2.0 | https://github.com/AdityaPrabhuCS/DevHack2.0 | 44365a93c16f06b3a440441138d05b2331b982e4 | aa68068f5abe9529c147c3bb21272c1ffc79c1bf | refs/heads/master | 2021-01-05T01:27:29.980000 | 2020-05-22T16:13:59 | 2020-05-22T16:13:59 | 240,829,349 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.food1;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import com.google.firebase.auth.FirebaseAuth;
public class HomeActivity extends AppCompatActivity {
Button btnlogout;
Button scanqr;
Button generate;
Button data;
FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthStatelistner;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
scanqr=findViewById(R.id.scanqr);
data=findViewById(R.id.enterdata);
generate=findViewById(R.id.generate);
/*btnlogout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// FirebaseAuth.getInstance().signOut();
Intent intomain = new Intent(HomeActivity.this,first.class);
startActivity(intomain);
}
});*/
data.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent it =new Intent(HomeActivity.this,reader.class);
startActivity(it);
}
});
scanqr.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intscan = new Intent(HomeActivity.this,barcode.class);
startActivity(intscan);
}
});
generate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent inte = new Intent(HomeActivity.this,qr.class);
startActivity(inte);
}
});
}
}
| UTF-8 | Java | 1,890 | java | HomeActivity.java | Java | [] | null | [] | package com.example.food1;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import com.google.firebase.auth.FirebaseAuth;
public class HomeActivity extends AppCompatActivity {
Button btnlogout;
Button scanqr;
Button generate;
Button data;
FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthStatelistner;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
scanqr=findViewById(R.id.scanqr);
data=findViewById(R.id.enterdata);
generate=findViewById(R.id.generate);
/*btnlogout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// FirebaseAuth.getInstance().signOut();
Intent intomain = new Intent(HomeActivity.this,first.class);
startActivity(intomain);
}
});*/
data.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent it =new Intent(HomeActivity.this,reader.class);
startActivity(it);
}
});
scanqr.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intscan = new Intent(HomeActivity.this,barcode.class);
startActivity(intscan);
}
});
generate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent inte = new Intent(HomeActivity.this,qr.class);
startActivity(inte);
}
});
}
}
| 1,890 | 0.619577 | 0.619048 | 56 | 32.75 | 21.183088 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.625 | false | false | 11 |
675846cb85c42b8f1745518cad74afbc80f5e7ce | 28,381,143,929,522 | 598a3f8716d2f36a2a365928f9a1917829ae6d38 | /plugin/src/main/java/fr/mrmicky/worldeditselectionvisualizer/compat/SpigotActionBarAdapter.java | 04d89bf09cf464eb70f84a883d90157795886006 | [
"MIT"
] | permissive | MrMicky-FR/WorldEditSelectionVisualizer | https://github.com/MrMicky-FR/WorldEditSelectionVisualizer | a9d2644c7a8e671d252010c11f3a009f665047c8 | ea93ec2f6b8eca97afc17d93a5f9f56c0c055242 | refs/heads/master | 2023-06-22T06:08:55.010000 | 2023-06-08T17:05:55 | 2023-06-08T17:05:55 | 50,179,141 | 65 | 25 | MIT | false | 2023-04-01T16:48:51 | 2016-01-22T12:08:13 | 2023-03-26T07:03:12 | 2023-04-01T16:48:50 | 645 | 45 | 22 | 0 | Java | false | false | package fr.mrmicky.worldeditselectionvisualizer.compat;
import net.md_5.bungee.api.ChatMessageType;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.entity.Player;
final class SpigotActionBarAdapter {
private SpigotActionBarAdapter() {
throw new UnsupportedOperationException();
}
static void checkSupported() throws NoSuchMethodException {
Player.Spigot.class.getMethod("sendMessage", ChatMessageType.class, BaseComponent.class);
}
static void sendActionBar(Player player, String message) {
player.spigot().sendMessage(ChatMessageType.ACTION_BAR, new TextComponent(message));
}
}
| UTF-8 | Java | 697 | java | SpigotActionBarAdapter.java | Java | [
{
"context": "package fr.mrmicky.worldeditselectionvisualizer.compat;\n\nimport net.",
"end": 18,
"score": 0.8668322563171387,
"start": 11,
"tag": "USERNAME",
"value": "mrmicky"
}
] | null | [] | package fr.mrmicky.worldeditselectionvisualizer.compat;
import net.md_5.bungee.api.ChatMessageType;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.entity.Player;
final class SpigotActionBarAdapter {
private SpigotActionBarAdapter() {
throw new UnsupportedOperationException();
}
static void checkSupported() throws NoSuchMethodException {
Player.Spigot.class.getMethod("sendMessage", ChatMessageType.class, BaseComponent.class);
}
static void sendActionBar(Player player, String message) {
player.spigot().sendMessage(ChatMessageType.ACTION_BAR, new TextComponent(message));
}
}
| 697 | 0.761836 | 0.757532 | 21 | 32.190475 | 30.371696 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 11 |
f0342f411fda86aa11dd9cb704dcf573da81ae73 | 25,795,573,626,566 | d657d2a60c6c8b1490799eb694ad036ff05c2aa7 | /src/client/model/login/LoginModelHandler.java | e6bb496fc10165189ad77964ac07acd7e30763af | [] | no_license | IT-SEP2-A19-G6/SEP2 | https://github.com/IT-SEP2-A19-G6/SEP2 | d9ec87f12e4a509befaec5bd0d6906389930cf21 | 8af539e542cf8197d88d38f5fa08a5a5f7c79949 | refs/heads/Development | 2020-09-02T11:13:00.032000 | 2020-05-17T11:35:57 | 2020-05-17T11:35:57 | 219,207,962 | 0 | 0 | null | false | 2019-12-20T08:27:22 | 2019-11-02T20:10:15 | 2019-12-20T08:26:46 | 2019-12-20T08:27:21 | 1,323 | 0 | 0 | 0 | Java | false | false | package client.model.login;
import client.network.login.ILoginClient;
import client.util.ClientProperties;
import shared.Request;
import shared.Response;
import shared.clients.Client;
import shared.clients.User;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
public class LoginModelHandler implements ILoginModel {
private final PropertyChangeSupport support = new PropertyChangeSupport(this);
private final ILoginClient loginClient;
public LoginModelHandler(ILoginClient loginClient){
this.loginClient = loginClient;
addListeners();
}
private void addListeners() {
loginClient.addPropertyChangeListener(Request.TYPE.LOGIN_RESPONSE.name(), this::handleResponse);
}
@Override
public void validateLogin(String username, String password) {
Client client = new User(username, password);
loginClient.validateLogin(client);
}
private void handleResponse(PropertyChangeEvent propertyChangeEvent) {
Response loginResponse = (Response) propertyChangeEvent.getNewValue();
if (loginResponse.getReceiver() != null) {
ClientProperties.getInstance().setClient(loginResponse.getReceiver());
support.firePropertyChange(Request.TYPE.SET_STATE.name(), "", ClientProperties.getInstance().getClient().getType());
}
support.firePropertyChange(propertyChangeEvent.getPropertyName(), propertyChangeEvent.getOldValue(), propertyChangeEvent.getNewValue());
}
@Override
public void addPropertyChangeListener(String name, PropertyChangeListener listener) {
if (name == null){
support.addPropertyChangeListener(listener);
} else {
support.addPropertyChangeListener(name, listener);
}
}
}
| UTF-8 | Java | 1,847 | java | LoginModelHandler.java | Java | [] | null | [] | package client.model.login;
import client.network.login.ILoginClient;
import client.util.ClientProperties;
import shared.Request;
import shared.Response;
import shared.clients.Client;
import shared.clients.User;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
public class LoginModelHandler implements ILoginModel {
private final PropertyChangeSupport support = new PropertyChangeSupport(this);
private final ILoginClient loginClient;
public LoginModelHandler(ILoginClient loginClient){
this.loginClient = loginClient;
addListeners();
}
private void addListeners() {
loginClient.addPropertyChangeListener(Request.TYPE.LOGIN_RESPONSE.name(), this::handleResponse);
}
@Override
public void validateLogin(String username, String password) {
Client client = new User(username, password);
loginClient.validateLogin(client);
}
private void handleResponse(PropertyChangeEvent propertyChangeEvent) {
Response loginResponse = (Response) propertyChangeEvent.getNewValue();
if (loginResponse.getReceiver() != null) {
ClientProperties.getInstance().setClient(loginResponse.getReceiver());
support.firePropertyChange(Request.TYPE.SET_STATE.name(), "", ClientProperties.getInstance().getClient().getType());
}
support.firePropertyChange(propertyChangeEvent.getPropertyName(), propertyChangeEvent.getOldValue(), propertyChangeEvent.getNewValue());
}
@Override
public void addPropertyChangeListener(String name, PropertyChangeListener listener) {
if (name == null){
support.addPropertyChangeListener(listener);
} else {
support.addPropertyChangeListener(name, listener);
}
}
}
| 1,847 | 0.732539 | 0.732539 | 54 | 33.203705 | 34.215752 | 144 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.592593 | false | false | 11 |
4374ddba75574c59752ddf4b3e55a873eade4f3b | 28,063,316,379,100 | 84e6ff088d00d05dc22111e2d54456066bc41174 | /src/Payroll/AgileSD/DeleteEmployeeTransaction.java | fdb86dd7d73de244d58af9de396b9fa01ff5a3c7 | [] | no_license | ldb-github/AgileSD_BookCodes | https://github.com/ldb-github/AgileSD_BookCodes | 2a3e9196acb8ef9c3b2d1594b4dcd365528e530d | 34191e3e452bdce230add2894e870116c8802d5a | refs/heads/master | 2021-01-12T04:28:24.772000 | 2017-01-04T14:56:05 | 2017-01-04T14:56:05 | 77,617,345 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Payroll.AgileSD;
public class DeleteEmployeeTransaction implements Transaction {
private int empId;
public DeleteEmployeeTransaction(int empId) {
this.empId = empId;
}
@Override
public void execute() {
PayrollDatabase.deleteEmployee(empId);
}
}
| UTF-8 | Java | 285 | java | DeleteEmployeeTransaction.java | Java | [] | null | [] | package Payroll.AgileSD;
public class DeleteEmployeeTransaction implements Transaction {
private int empId;
public DeleteEmployeeTransaction(int empId) {
this.empId = empId;
}
@Override
public void execute() {
PayrollDatabase.deleteEmployee(empId);
}
}
| 285 | 0.719298 | 0.719298 | 16 | 15.8125 | 18.954613 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.9375 | false | false | 11 |
7ac0544fec7e0a6d165415b79453253fc7a2aa7e | 10,565,619,616,747 | fd031248e40e6a2bfc12f9461b5a9db0480b6642 | /HookahMix/app/src/main/java/com/hookah/roma/hookahmix/TabaksArrayList.java | 73818e75e9b604077d56caa512d9059a1ee287e5 | [] | no_license | romashka256/Hookah-Mix | https://github.com/romashka256/Hookah-Mix | 3b7f2c06a9ba6a7bf3c64d4e27ea863d0a748504 | 3e4c8c07a6887325e842794bf21b2f0e20b7727c | refs/heads/master | 2021-01-19T13:36:21.966000 | 2017-03-29T20:58:18 | 2017-03-29T20:58:18 | 82,399,722 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.hookah.roma.hookahmix;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class TabaksArrayList {
@SerializedName("name")
@Expose
private String name;
@SerializedName("description")
@Expose
private String description;
@SerializedName("second_name")
@Expose
private String second_name;
@SerializedName("rating")
@Expose
private String rating;
@SerializedName("favourite")
@Expose
private String favourite;
@SerializedName("family")
@Expose
private String family;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setSecond_name(String second_name) {this.second_name = second_name;}
public String getSecond_name() {return second_name;}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
public String getFavourite() {
return favourite;
}
public void setFavourite(String favourite) {
this.favourite = favourite;
}
public String getFamily() {
return family;
}
public void setFamily(String family) {
this.family = family;
}
}
| UTF-8 | Java | 1,494 | java | TabaksArrayList.java | Java | [] | null | [] |
package com.hookah.roma.hookahmix;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class TabaksArrayList {
@SerializedName("name")
@Expose
private String name;
@SerializedName("description")
@Expose
private String description;
@SerializedName("second_name")
@Expose
private String second_name;
@SerializedName("rating")
@Expose
private String rating;
@SerializedName("favourite")
@Expose
private String favourite;
@SerializedName("family")
@Expose
private String family;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setSecond_name(String second_name) {this.second_name = second_name;}
public String getSecond_name() {return second_name;}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
public String getFavourite() {
return favourite;
}
public void setFavourite(String favourite) {
this.favourite = favourite;
}
public String getFamily() {
return family;
}
public void setFamily(String family) {
this.family = family;
}
}
| 1,494 | 0.645917 | 0.645917 | 72 | 19.736111 | 17.815407 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.291667 | false | false | 11 |
f1b84831e4c5de194a139cd1f2181e7a59fdcae8 | 19,997,367,785,803 | 1dd9a9915e10f4255adbd54f65d59bc722658867 | /yhdg-web-server/src/main/java/cn/com/yusong/yhdg/webserver/service/hdg/FaultLogService.java | 163b2db339907cf66a45629a2b2e916953e2e5f2 | [] | no_license | Vampx/yhdg-parent | https://github.com/Vampx/yhdg-parent | fe28a02a86b80ba9caff78e769e15f25fb5bcedf | e981887e98264aa5c2c499ca9dd9575e2ac32bce | refs/heads/master | 2020-07-29T23:52:38.243000 | 2019-09-21T11:39:55 | 2019-09-21T11:39:55 | 210,007,134 | 0 | 2 | null | true | 2019-09-21T15:18:07 | 2019-09-21T15:18:06 | 2019-09-21T11:41:19 | 2019-09-21T11:40:48 | 25,646 | 0 | 0 | 0 | null | false | false | package cn.com.yusong.yhdg.webserver.service.hdg;
import cn.com.yusong.yhdg.common.domain.basic.DictCategory;
import cn.com.yusong.yhdg.common.domain.hdg.FaultLog;
import cn.com.yusong.yhdg.common.entity.json.ExtResult;
import cn.com.yusong.yhdg.common.entity.pagination.Page;
import cn.com.yusong.yhdg.webserver.persistence.basic.CustomerMapper;
import cn.com.yusong.yhdg.webserver.persistence.hdg.*;
import cn.com.yusong.yhdg.webserver.service.AbstractService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Service
public class FaultLogService extends AbstractService {
@Autowired
FaultLogMapper faultLogMapper;
@Autowired
CabinetMapper cabinetMapper;
@Autowired
CabinetBoxMapper cabinetBoxMapper;
@Autowired
BatteryOrderMapper batteryOrderMapper;
@Autowired
BatteryMapper batteryMapper;
@Autowired
CustomerMapper customerMapper;
public Page findPage(FaultLog search) {
Map<String, String> batteryBrandMap = findDictItemMap(DictCategory.CategoryType.BATTERY_BRAND.getValue());
Page page = search.buildPage();
page.setTotalItems(faultLogMapper.findPageCount(search));
search.setBeginIndex(page.getOffset());
List<FaultLog> faultLogs = faultLogMapper.findPageResult(search);
for (FaultLog faultLog : faultLogs) {
if (faultLog != null) {
if (faultLog.getBrand() != null) {
faultLog.setBrandName(batteryBrandMap.get(faultLog.getBrand()));
}
}
}
page.setResult(faultLogs);
return page;
}
public FaultLog find(Long id) {
return faultLogMapper.find(id);
}
public int findCount(Integer status) {
return faultLogMapper.findCount(status);
}
public ExtResult update(FaultLog entity) {
cleanFaultLog(entity.getFaultType(), entity.getId());
int total = faultLogMapper.handle(entity.getId(), FaultLog.HandleType.MANUAL.getValue(), entity.getHandleMemo(), entity.getHandleTime(), entity.getHandlerName(), FaultLog.Status.PROCESSED.getValue());
if (total == 0) {
return ExtResult.failResult("修改失败!");
}
return ExtResult.successResult();
}
public ExtResult updateStatus(Long[] faultLogIds, String username) {
Date now = new Date();
for (Long id : faultLogIds) {
FaultLog faultLog = faultLogMapper.find(id);
cleanFaultLog(faultLog.getFaultType(), id);
faultLogMapper.handle(id, FaultLog.HandleType.MANUAL.getValue(), "故障已处理", now, username, FaultLog.Status.PROCESSED.getValue());
}
return ExtResult.successResult();
}
private void cleanFaultLog(int faultType, long faultLogId) {
if (faultType == FaultLog.FaultType.CODE_1.getValue()) {
batteryMapper.updateFaultLog("monomerOvervoltageFaultLogId", faultLogId);
} else if (faultType == FaultLog.FaultType.CODE_2.getValue()) {
batteryMapper.updateFaultLog("monomerLowvoltageFaultLogId", faultLogId);
} else if (faultType == FaultLog.FaultType.CODE_3.getValue()) {
batteryMapper.updateFaultLog("wholeOvervoltageFaultLogId", faultLogId);
} else if (faultType == FaultLog.FaultType.CODE_4.getValue()) {
batteryMapper.updateFaultLog("wholeLowvoltageFaultLogId", faultLogId);
} else if (faultType == FaultLog.FaultType.CODE_5.getValue()) {
batteryMapper.updateFaultLog("chargeOvertempFaultLogId", faultLogId);
} else if (faultType == FaultLog.FaultType.CODE_6.getValue()) {
batteryMapper.updateFaultLog("chargeLowtempFaultLogId", faultLogId);
} else if (faultType == FaultLog.FaultType.CODE_7.getValue()) {
batteryMapper.updateFaultLog("dischargeOvertempFaultLogId", faultLogId);
} else if (faultType == FaultLog.FaultType.CODE_8.getValue()) {
batteryMapper.updateFaultLog("dischargeLowtempFaultLogId", faultLogId);
} else if (faultType == FaultLog.FaultType.CODE_9.getValue()) {
batteryMapper.updateFaultLog("chargeOvercurrentFaultLogId", faultLogId);
} else if (faultType == FaultLog.FaultType.CODE_10.getValue()) {
batteryMapper.updateFaultLog("dischargeOvercurrentFaultLogId", faultLogId);
} else if (faultType == FaultLog.FaultType.CODE_11.getValue()) {
batteryMapper.updateFaultLog("shortCircuitFaultLogId", faultLogId);
} else if (faultType == FaultLog.FaultType.CODE_12.getValue()) {
batteryMapper.updateFaultLog("testingIcFaultLogId", faultLogId);
} else if (faultType == FaultLog.FaultType.CODE_13.getValue()) {
batteryMapper.updateFaultLog("softwareLockingFaultLogId", faultLogId);
} else if (faultType == FaultLog.FaultType.CODE_14.getValue()) {
batteryMapper.updateFaultLog("dischargeLockingFaultLogId", faultLogId);
} else if (faultType == FaultLog.FaultType.CODE_15.getValue()) {
batteryMapper.updateFaultLog("chargeMosFaultLogId", faultLogId);
} else if (faultType == FaultLog.FaultType.CODE_16.getValue()) {
batteryMapper.updateFaultLog("dischargeMosFaultLogId", faultLogId);
} else if (faultType == FaultLog.FaultType.CODE_17.getValue()) {
batteryMapper.updateFaultLog("maxVolDiffLogId", faultLogId);
} else if (faultType == FaultLog.FaultType.CODE_20.getValue()) {
batteryMapper.updateFaultLog("signVolLowLogId", faultLogId);
} else if (faultType == FaultLog.FaultType.CODE_21.getValue()) {
cabinetBoxMapper.updateFaultLog("smokeFaultLogId", faultLogId);
}
}
}
| UTF-8 | Java | 5,838 | java | FaultLogService.java | Java | [] | null | [] | package cn.com.yusong.yhdg.webserver.service.hdg;
import cn.com.yusong.yhdg.common.domain.basic.DictCategory;
import cn.com.yusong.yhdg.common.domain.hdg.FaultLog;
import cn.com.yusong.yhdg.common.entity.json.ExtResult;
import cn.com.yusong.yhdg.common.entity.pagination.Page;
import cn.com.yusong.yhdg.webserver.persistence.basic.CustomerMapper;
import cn.com.yusong.yhdg.webserver.persistence.hdg.*;
import cn.com.yusong.yhdg.webserver.service.AbstractService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Service
public class FaultLogService extends AbstractService {
@Autowired
FaultLogMapper faultLogMapper;
@Autowired
CabinetMapper cabinetMapper;
@Autowired
CabinetBoxMapper cabinetBoxMapper;
@Autowired
BatteryOrderMapper batteryOrderMapper;
@Autowired
BatteryMapper batteryMapper;
@Autowired
CustomerMapper customerMapper;
public Page findPage(FaultLog search) {
Map<String, String> batteryBrandMap = findDictItemMap(DictCategory.CategoryType.BATTERY_BRAND.getValue());
Page page = search.buildPage();
page.setTotalItems(faultLogMapper.findPageCount(search));
search.setBeginIndex(page.getOffset());
List<FaultLog> faultLogs = faultLogMapper.findPageResult(search);
for (FaultLog faultLog : faultLogs) {
if (faultLog != null) {
if (faultLog.getBrand() != null) {
faultLog.setBrandName(batteryBrandMap.get(faultLog.getBrand()));
}
}
}
page.setResult(faultLogs);
return page;
}
public FaultLog find(Long id) {
return faultLogMapper.find(id);
}
public int findCount(Integer status) {
return faultLogMapper.findCount(status);
}
public ExtResult update(FaultLog entity) {
cleanFaultLog(entity.getFaultType(), entity.getId());
int total = faultLogMapper.handle(entity.getId(), FaultLog.HandleType.MANUAL.getValue(), entity.getHandleMemo(), entity.getHandleTime(), entity.getHandlerName(), FaultLog.Status.PROCESSED.getValue());
if (total == 0) {
return ExtResult.failResult("修改失败!");
}
return ExtResult.successResult();
}
public ExtResult updateStatus(Long[] faultLogIds, String username) {
Date now = new Date();
for (Long id : faultLogIds) {
FaultLog faultLog = faultLogMapper.find(id);
cleanFaultLog(faultLog.getFaultType(), id);
faultLogMapper.handle(id, FaultLog.HandleType.MANUAL.getValue(), "故障已处理", now, username, FaultLog.Status.PROCESSED.getValue());
}
return ExtResult.successResult();
}
private void cleanFaultLog(int faultType, long faultLogId) {
if (faultType == FaultLog.FaultType.CODE_1.getValue()) {
batteryMapper.updateFaultLog("monomerOvervoltageFaultLogId", faultLogId);
} else if (faultType == FaultLog.FaultType.CODE_2.getValue()) {
batteryMapper.updateFaultLog("monomerLowvoltageFaultLogId", faultLogId);
} else if (faultType == FaultLog.FaultType.CODE_3.getValue()) {
batteryMapper.updateFaultLog("wholeOvervoltageFaultLogId", faultLogId);
} else if (faultType == FaultLog.FaultType.CODE_4.getValue()) {
batteryMapper.updateFaultLog("wholeLowvoltageFaultLogId", faultLogId);
} else if (faultType == FaultLog.FaultType.CODE_5.getValue()) {
batteryMapper.updateFaultLog("chargeOvertempFaultLogId", faultLogId);
} else if (faultType == FaultLog.FaultType.CODE_6.getValue()) {
batteryMapper.updateFaultLog("chargeLowtempFaultLogId", faultLogId);
} else if (faultType == FaultLog.FaultType.CODE_7.getValue()) {
batteryMapper.updateFaultLog("dischargeOvertempFaultLogId", faultLogId);
} else if (faultType == FaultLog.FaultType.CODE_8.getValue()) {
batteryMapper.updateFaultLog("dischargeLowtempFaultLogId", faultLogId);
} else if (faultType == FaultLog.FaultType.CODE_9.getValue()) {
batteryMapper.updateFaultLog("chargeOvercurrentFaultLogId", faultLogId);
} else if (faultType == FaultLog.FaultType.CODE_10.getValue()) {
batteryMapper.updateFaultLog("dischargeOvercurrentFaultLogId", faultLogId);
} else if (faultType == FaultLog.FaultType.CODE_11.getValue()) {
batteryMapper.updateFaultLog("shortCircuitFaultLogId", faultLogId);
} else if (faultType == FaultLog.FaultType.CODE_12.getValue()) {
batteryMapper.updateFaultLog("testingIcFaultLogId", faultLogId);
} else if (faultType == FaultLog.FaultType.CODE_13.getValue()) {
batteryMapper.updateFaultLog("softwareLockingFaultLogId", faultLogId);
} else if (faultType == FaultLog.FaultType.CODE_14.getValue()) {
batteryMapper.updateFaultLog("dischargeLockingFaultLogId", faultLogId);
} else if (faultType == FaultLog.FaultType.CODE_15.getValue()) {
batteryMapper.updateFaultLog("chargeMosFaultLogId", faultLogId);
} else if (faultType == FaultLog.FaultType.CODE_16.getValue()) {
batteryMapper.updateFaultLog("dischargeMosFaultLogId", faultLogId);
} else if (faultType == FaultLog.FaultType.CODE_17.getValue()) {
batteryMapper.updateFaultLog("maxVolDiffLogId", faultLogId);
} else if (faultType == FaultLog.FaultType.CODE_20.getValue()) {
batteryMapper.updateFaultLog("signVolLowLogId", faultLogId);
} else if (faultType == FaultLog.FaultType.CODE_21.getValue()) {
cabinetBoxMapper.updateFaultLog("smokeFaultLogId", faultLogId);
}
}
}
| 5,838 | 0.6901 | 0.684943 | 119 | 47.890755 | 33.604168 | 208 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.764706 | false | false | 11 |
0d27327b59e6ebd6b1f0b714a3e50839013ddadd | 30,760,555,811,694 | e2e4b6b9e0cacf41911747dc7c4168259b04638f | /Java/src/GapInPrimes.java | e906bc1fcdec4711f9072db316789c8437c94745 | [] | no_license | Daniel-Benzion/HackerRank-challenges | https://github.com/Daniel-Benzion/HackerRank-challenges | 61280085f88306b16df7cb47907334903eacf466 | df30657b2f75ca4905955a52705b595f03a56d5b | refs/heads/main | 2023-06-12T17:38:17.663000 | 2021-07-07T23:48:14 | 2021-07-07T23:48:14 | 310,333,865 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class GapInPrimes {
static boolean isPrime(long number) {
for (long i = 2; i * i <= number; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
public static long[] gap(int g, long m, long n) {
long[] result = new long[2];
long current = m;
long first = current;
while (current <= n) {
if (isPrime(current)) {
first = current;
break;
} else {
current++;
}
}
while (true) {
long second = current + 1;
current = second;
while (current <= n) {
if (isPrime(current)) {
second = current;
break;
} else
current++;
}
if (isPrime(first) && isPrime(second) && second - first == g) {
result[0] = first;
result[1] = second;
return result;
} else if (!isPrime(second))
return null;
first = second;
current = first;
}
}
}
| UTF-8 | Java | 1,208 | java | GapInPrimes.java | Java | [] | null | [] | public class GapInPrimes {
static boolean isPrime(long number) {
for (long i = 2; i * i <= number; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
public static long[] gap(int g, long m, long n) {
long[] result = new long[2];
long current = m;
long first = current;
while (current <= n) {
if (isPrime(current)) {
first = current;
break;
} else {
current++;
}
}
while (true) {
long second = current + 1;
current = second;
while (current <= n) {
if (isPrime(current)) {
second = current;
break;
} else
current++;
}
if (isPrime(first) && isPrime(second) && second - first == g) {
result[0] = first;
result[1] = second;
return result;
} else if (!isPrime(second))
return null;
first = second;
current = first;
}
}
}
| 1,208 | 0.383278 | 0.378311 | 51 | 22.686274 | 16.311298 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.45098 | false | false | 11 |
8cbea9880acbc05aefb459b470b9bd4e85334544 | 32,006,096,302,028 | e0b40802781040919850152aae33665337b089dd | /AndroidJUnitTest/src/com/example/android/junittest/AndroidJUnitTest.java | bb7adde65aad5be1f7b03e5802960c62286ba137 | [] | no_license | kusium/android-develop-toolkit | https://github.com/kusium/android-develop-toolkit | d69df21eff459ad90c41c8f7472206f508c0574e | 58d232c54d20bd04441dacb46588345ed8963a95 | refs/heads/master | 2021-01-14T11:20:04.803000 | 2014-12-20T17:56:44 | 2014-12-20T17:56:44 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.android.junittest;
import android.content.Context;
import android.widget.Toast;
public class AndroidJUnitTest {
private static final String TAG = "AndroidJUnitTest";
public static void testStaticPrintln(String message) {
android.util.Log.d(TAG, message);
}
public void testPrintln(String message) {
android.util.Log.d(TAG, message);
}
public void testToast(Context context, String message) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
}
| UTF-8 | Java | 518 | java | AndroidJUnitTest.java | Java | [] | null | [] | package com.example.android.junittest;
import android.content.Context;
import android.widget.Toast;
public class AndroidJUnitTest {
private static final String TAG = "AndroidJUnitTest";
public static void testStaticPrintln(String message) {
android.util.Log.d(TAG, message);
}
public void testPrintln(String message) {
android.util.Log.d(TAG, message);
}
public void testToast(Context context, String message) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
}
| 518 | 0.725869 | 0.725869 | 22 | 21.545454 | 22.437241 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.136364 | false | false | 11 |
b49d9b49eaddb523279bf36def8fc61fa1fed441 | 21,698,174,780,354 | 2198dfe33f375e85201fc0d2fc1e6514cfc257f1 | /eenass/QLanguage/src/ast/expr/binExpr/Sub.java | ea44ed61005025febad91eb7dc8d30efbee9091b | [
"Apache-2.0"
] | permissive | software-engineering-amsterdam/poly-ql | https://github.com/software-engineering-amsterdam/poly-ql | c073e19da80ab66ae540f7438d6637fb55286c07 | acde6f943265e8aca08e1fe1ce213bcb1b5f9421 | refs/heads/master | 2022-05-01T10:05:32.627000 | 2022-04-19T12:05:26 | 2022-04-19T12:05:26 | 16,277,142 | 1 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ast.expr.binExpr;
import typecheck.SymbolTable;
import ast.expr.Expr;
import ast.types.IntType;
import ast.types.Type;
import ast.visitors.ExprVisitor;
public class Sub extends BinExpr{
public Sub(Expr lhs, Expr rhs) {
super(lhs, rhs);
}
@Override
public <T> T accept(ExprVisitor<T> visitor) {
return visitor.visit(this);
}
@Override
public Type typeof(SymbolTable symbolTable) {
return new IntType();
}
}
| UTF-8 | Java | 434 | java | Sub.java | Java | [] | null | [] | package ast.expr.binExpr;
import typecheck.SymbolTable;
import ast.expr.Expr;
import ast.types.IntType;
import ast.types.Type;
import ast.visitors.ExprVisitor;
public class Sub extends BinExpr{
public Sub(Expr lhs, Expr rhs) {
super(lhs, rhs);
}
@Override
public <T> T accept(ExprVisitor<T> visitor) {
return visitor.visit(this);
}
@Override
public Type typeof(SymbolTable symbolTable) {
return new IntType();
}
}
| 434 | 0.732719 | 0.732719 | 24 | 17.083334 | 14.935742 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.083333 | false | false | 11 |
e120be267596789ccb6eeadbecb3c4790d6b360b | 11,897,059,456,235 | b2da0f8c1e6b003c32ddad6ac77a2e0a0376e9df | /web/src/main/java/com/nrusev/web/ui/edit/EditView.java | 980a297e49fabb4b2facee0c48ebb1d690fc4e6d | [
"MIT"
] | permissive | nickolayrusev/trackteam | https://github.com/nickolayrusev/trackteam | bec1aac366f5ed80ec3e1614e494ae20c4185803 | 7ae5d17ecfdea76f3db6c8c0de06fe292baf82e0 | refs/heads/master | 2021-01-10T07:07:19.846000 | 2017-03-21T16:14:12 | 2017-03-21T16:14:12 | 55,540,974 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.nrusev.web.ui.edit;
import com.nrusev.web.ui.mvp.MvpView;
public interface EditView extends MvpView {
}
| UTF-8 | Java | 120 | java | EditView.java | Java | [] | null | [] | package com.nrusev.web.ui.edit;
import com.nrusev.web.ui.mvp.MvpView;
public interface EditView extends MvpView {
}
| 120 | 0.766667 | 0.766667 | 8 | 14 | 18.069311 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 11 |
1b9ef7a712217ce4333b236774470728f1d10ca3 | 32,469,952,758,278 | 79cd803b89bd9ef21976badb3aa8664ccf6927a4 | /collage/src/collage/InputController.java | 58f9044b142ba6faef2c8eb29d179127ed72f074 | [] | no_license | mnpenner/mfcollage | https://github.com/mnpenner/mfcollage | 5b4fd90111f261d7b16c0810569fe2270b94d5f6 | bd41403642601f6f39affb0d0119677bd4321bed | refs/heads/master | 2020-06-02T15:26:52.594000 | 2008-12-02T07:11:09 | 2008-12-02T07:11:09 | 32,114,892 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package collage;
import java.awt.*;
import java.awt.event.ContainerEvent;
import java.awt.event.ContainerListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
/**
*
* @author Mark
*/
public class InputController implements MouseListener, MouseMotionListener,
KeyListener, MouseWheelListener {
JPanel mp = null;
CollageView cv = null;
Point mouseStart = null;
boolean resizing = false;
Toolkit toolkit = Toolkit.getDefaultToolkit();
Image image = toolkit.getImage("src/collage/resources/rotate.gif");
Point hotSpot = new Point(15, 15);
Cursor customCursor = toolkit.createCustomCursor(image, hotSpot, "Rotate");
private JPopupMenu contextMenu;
InputController(JPanel mp, CollageView cv, JPopupMenu contextMenu) {
this.mp = mp;
this.cv = cv;
this.contextMenu = contextMenu;
}
public void mouseClicked(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
if (mp.getCursor().getType() == Cursor.DEFAULT_CURSOR) {
if (!e.isShiftDown()) {
for (Component c1 : mp.getComponents()) {
if (c1 instanceof ImagePanel) {
((ImagePanel) c1).selected = false;
}
}
}
Component c2 = mp.getComponentAt(e.getPoint());
if (c2 instanceof ImagePanel) {
((ImagePanel) c2).selected = true;
}
mp.repaint();
}
mouseStart = e.getPoint();
}
public void mouseReleased(MouseEvent e) {
for (Component c : mp.getComponents()) {
if (c instanceof ImagePanel) {
ImagePanel ip = ((ImagePanel) c);
if (ip.selected) {
if (resizing) {
ip.updateImage();
resizing = false;
mp.repaint();
} else if (e.isPopupTrigger() && !e.isShiftDown()) {
//TODO: this should have been an ImagePlane mouse listener; not here
ip.selected = true;
contextMenu.show(e.getComponent(), e.getX(), e.getY());
}
}
}
}
}
public void mouseDragged(MouseEvent e) {
Point mouseEnd = e.getPoint();
for (Component c : mp.getComponents()) {
if (c instanceof ImagePanel) {
ImagePanel ip = ((ImagePanel) c);
if (ip.selected) {
Point ipLoc = ip.getLocation();
int dx = mouseEnd.x - mouseStart.x;
int dy = mouseEnd.y - mouseStart.y;
if (mp.getCursor().getType() == Cursor.DEFAULT_CURSOR) {
ip.setLocation(dx + ipLoc.x, dy + ipLoc.y);
} else {
if (mp.getCursor().getType() == Cursor.NW_RESIZE_CURSOR) {
ip.setBounds(ipLoc.x + dx, ipLoc.y + dy,
ip.getWidth() - dx, ip.getHeight() - dy);
} else if (mp.getCursor().getType() == Cursor.NE_RESIZE_CURSOR) {
ip.setBounds(ipLoc.x, ipLoc.y + dy,
ip.getWidth() + dx, ip.getHeight() - dy);
} else if (mp.getCursor().getType() == Cursor.SW_RESIZE_CURSOR) {
ip.setBounds(ipLoc.x + dx, ipLoc.y,
ip.getWidth() - dx, ip.getHeight() + dy);
} else if (mp.getCursor().getType() == Cursor.SE_RESIZE_CURSOR) {
ip.setBounds(ipLoc.x, ipLoc.y,
ip.getWidth() + dx, ip.getHeight() + dy);
}
ip.quickUpdate();
resizing = true;
mp.repaint();
}
}
}
}
mouseStart = e.getPoint();
}
public void mouseMoved(MouseEvent e) {
Point p = e.getPoint();
double maxDist = 7.5;
double maxRotationDist = 25.0;
boolean change = false;
for (Component c : mp.getComponents()) {
if (c instanceof ImagePanel) {
ImagePanel ip = ((ImagePanel) c);
if (ip.selected) {
if (dist(p, ip.getLocation()) < maxDist) {
mp.setCursor(new Cursor(Cursor.NW_RESIZE_CURSOR));
change = true;
} else if (dist2(p, new Point(ip.getX() + ip.getWidth(), ip.getY())) < maxDist) {
mp.setCursor(new Cursor(Cursor.NE_RESIZE_CURSOR));
change = true;
} else if (dist(p, new Point(ip.getX(), ip.getY() + ip.getHeight())) < maxDist) {
mp.setCursor(new Cursor(Cursor.SW_RESIZE_CURSOR));
change = true;
} else if (dist(p, new Point(ip.getX() + ip.getWidth(), ip.getY() + ip.getHeight())) < maxDist) {
mp.setCursor(new Cursor(Cursor.SE_RESIZE_CURSOR));
change = true;
} else if (dist(p, ip.getLocation()) >= maxDist && dist(p, ip.getLocation()) < maxRotationDist) {
mp.setCursor(customCursor);
change = true;
} else if (dist2(p, new Point(ip.getX() + ip.getWidth(), ip.getY())) >= maxDist && dist2(p, new Point(ip.getX() + ip.getWidth(), ip.getY())) < maxRotationDist) {
mp.setCursor(customCursor);
change = true;
} else if (dist3(p, new Point(ip.getX(), ip.getY() + ip.getHeight())) >= maxDist && dist3(p, new Point(ip.getX(), ip.getY() + ip.getHeight())) < maxRotationDist) {
mp.setCursor(customCursor);
change = true;
} else if (dist4(p, new Point(ip.getX() + ip.getWidth(), ip.getY() + ip.getHeight())) >= maxDist && dist4(p, new Point(ip.getX() + ip.getWidth(), ip.getY() + ip.getHeight())) < maxRotationDist) {
mp.setCursor(customCursor);
change = true;
}
}
}
}
if (!change) {
mp.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
}
private double dist(Point p1, Point p2) {
int dx = p2.x - p1.x;
int dy = p2.y - p1.y;
if (dx < 0 && dy < 0) {
return 100;
} else {
return Math.sqrt(dx * dx + dy * dy);
}
}
private double dist2(Point p1, Point p2) {
int dx = p2.x - p1.x;
int dy = p2.y - p1.y;
if (dx > 0 && dy < 0) {
return 100;
} else {
return Math.sqrt(dx * dx + dy * dy);
}
}
private double dist3(Point p1, Point p2) {
int dx = p2.x - p1.x;
int dy = p2.y - p1.y;
if (dx < 0 && dy > 0) {
return 100;
} else {
return Math.sqrt(dx * dx + dy * dy);
}
}
private double dist4(Point p1, Point p2) {
int dx = p2.x - p1.x;
int dy = p2.y - p1.y;
if (dx > 0 && dy > 0) {
return 100;
} else {
return Math.sqrt(dx * dx + dy * dy);
}
}
public void mouseWheelMoved(MouseWheelEvent e) {
int minZ = 1000, maxZ = -1000;
int notches = e.getWheelRotation();
for (Component c : mp.getComponents()) {
if (c instanceof ImagePanel) {
ImagePanel ip = ((ImagePanel) c);
int z = mp.getComponentZOrder(ip);
if (z < minZ) {
minZ = z;
}
if (z > maxZ) {
maxZ = z;
}
}
}
for (Component c : mp.getComponents()) {
if (c instanceof ImagePanel) {
ImagePanel ip = ((ImagePanel) c);
if (ip.selected) {
int z = mp.getComponentZOrder(ip);
z -= notches;
if (z > maxZ) {
z = maxZ;
}
if (z < minZ) {
z = minZ;
}
mp.setComponentZOrder(ip, z);
}
}
}
mp.repaint();
}
public void keyPressed(KeyEvent e) {
int kc = e.getKeyCode();
if (kc == KeyEvent.VK_DELETE || kc == KeyEvent.VK_BACK_SPACE) {
cv.removeImages();
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
public void alert(String msg) {
JOptionPane.showMessageDialog(null, msg);
}
}
| UTF-8 | Java | 9,346 | java | InputController.java | Java | [
{
"context": "\nimport javax.swing.JPopupMenu;\n\n/**\n *\n * @author Mark\n */\npublic class InputController implements Mouse",
"end": 491,
"score": 0.9986352324485779,
"start": 487,
"tag": "NAME",
"value": "Mark"
}
] | null | [] | package collage;
import java.awt.*;
import java.awt.event.ContainerEvent;
import java.awt.event.ContainerListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
/**
*
* @author Mark
*/
public class InputController implements MouseListener, MouseMotionListener,
KeyListener, MouseWheelListener {
JPanel mp = null;
CollageView cv = null;
Point mouseStart = null;
boolean resizing = false;
Toolkit toolkit = Toolkit.getDefaultToolkit();
Image image = toolkit.getImage("src/collage/resources/rotate.gif");
Point hotSpot = new Point(15, 15);
Cursor customCursor = toolkit.createCustomCursor(image, hotSpot, "Rotate");
private JPopupMenu contextMenu;
InputController(JPanel mp, CollageView cv, JPopupMenu contextMenu) {
this.mp = mp;
this.cv = cv;
this.contextMenu = contextMenu;
}
public void mouseClicked(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
if (mp.getCursor().getType() == Cursor.DEFAULT_CURSOR) {
if (!e.isShiftDown()) {
for (Component c1 : mp.getComponents()) {
if (c1 instanceof ImagePanel) {
((ImagePanel) c1).selected = false;
}
}
}
Component c2 = mp.getComponentAt(e.getPoint());
if (c2 instanceof ImagePanel) {
((ImagePanel) c2).selected = true;
}
mp.repaint();
}
mouseStart = e.getPoint();
}
public void mouseReleased(MouseEvent e) {
for (Component c : mp.getComponents()) {
if (c instanceof ImagePanel) {
ImagePanel ip = ((ImagePanel) c);
if (ip.selected) {
if (resizing) {
ip.updateImage();
resizing = false;
mp.repaint();
} else if (e.isPopupTrigger() && !e.isShiftDown()) {
//TODO: this should have been an ImagePlane mouse listener; not here
ip.selected = true;
contextMenu.show(e.getComponent(), e.getX(), e.getY());
}
}
}
}
}
public void mouseDragged(MouseEvent e) {
Point mouseEnd = e.getPoint();
for (Component c : mp.getComponents()) {
if (c instanceof ImagePanel) {
ImagePanel ip = ((ImagePanel) c);
if (ip.selected) {
Point ipLoc = ip.getLocation();
int dx = mouseEnd.x - mouseStart.x;
int dy = mouseEnd.y - mouseStart.y;
if (mp.getCursor().getType() == Cursor.DEFAULT_CURSOR) {
ip.setLocation(dx + ipLoc.x, dy + ipLoc.y);
} else {
if (mp.getCursor().getType() == Cursor.NW_RESIZE_CURSOR) {
ip.setBounds(ipLoc.x + dx, ipLoc.y + dy,
ip.getWidth() - dx, ip.getHeight() - dy);
} else if (mp.getCursor().getType() == Cursor.NE_RESIZE_CURSOR) {
ip.setBounds(ipLoc.x, ipLoc.y + dy,
ip.getWidth() + dx, ip.getHeight() - dy);
} else if (mp.getCursor().getType() == Cursor.SW_RESIZE_CURSOR) {
ip.setBounds(ipLoc.x + dx, ipLoc.y,
ip.getWidth() - dx, ip.getHeight() + dy);
} else if (mp.getCursor().getType() == Cursor.SE_RESIZE_CURSOR) {
ip.setBounds(ipLoc.x, ipLoc.y,
ip.getWidth() + dx, ip.getHeight() + dy);
}
ip.quickUpdate();
resizing = true;
mp.repaint();
}
}
}
}
mouseStart = e.getPoint();
}
public void mouseMoved(MouseEvent e) {
Point p = e.getPoint();
double maxDist = 7.5;
double maxRotationDist = 25.0;
boolean change = false;
for (Component c : mp.getComponents()) {
if (c instanceof ImagePanel) {
ImagePanel ip = ((ImagePanel) c);
if (ip.selected) {
if (dist(p, ip.getLocation()) < maxDist) {
mp.setCursor(new Cursor(Cursor.NW_RESIZE_CURSOR));
change = true;
} else if (dist2(p, new Point(ip.getX() + ip.getWidth(), ip.getY())) < maxDist) {
mp.setCursor(new Cursor(Cursor.NE_RESIZE_CURSOR));
change = true;
} else if (dist(p, new Point(ip.getX(), ip.getY() + ip.getHeight())) < maxDist) {
mp.setCursor(new Cursor(Cursor.SW_RESIZE_CURSOR));
change = true;
} else if (dist(p, new Point(ip.getX() + ip.getWidth(), ip.getY() + ip.getHeight())) < maxDist) {
mp.setCursor(new Cursor(Cursor.SE_RESIZE_CURSOR));
change = true;
} else if (dist(p, ip.getLocation()) >= maxDist && dist(p, ip.getLocation()) < maxRotationDist) {
mp.setCursor(customCursor);
change = true;
} else if (dist2(p, new Point(ip.getX() + ip.getWidth(), ip.getY())) >= maxDist && dist2(p, new Point(ip.getX() + ip.getWidth(), ip.getY())) < maxRotationDist) {
mp.setCursor(customCursor);
change = true;
} else if (dist3(p, new Point(ip.getX(), ip.getY() + ip.getHeight())) >= maxDist && dist3(p, new Point(ip.getX(), ip.getY() + ip.getHeight())) < maxRotationDist) {
mp.setCursor(customCursor);
change = true;
} else if (dist4(p, new Point(ip.getX() + ip.getWidth(), ip.getY() + ip.getHeight())) >= maxDist && dist4(p, new Point(ip.getX() + ip.getWidth(), ip.getY() + ip.getHeight())) < maxRotationDist) {
mp.setCursor(customCursor);
change = true;
}
}
}
}
if (!change) {
mp.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
}
private double dist(Point p1, Point p2) {
int dx = p2.x - p1.x;
int dy = p2.y - p1.y;
if (dx < 0 && dy < 0) {
return 100;
} else {
return Math.sqrt(dx * dx + dy * dy);
}
}
private double dist2(Point p1, Point p2) {
int dx = p2.x - p1.x;
int dy = p2.y - p1.y;
if (dx > 0 && dy < 0) {
return 100;
} else {
return Math.sqrt(dx * dx + dy * dy);
}
}
private double dist3(Point p1, Point p2) {
int dx = p2.x - p1.x;
int dy = p2.y - p1.y;
if (dx < 0 && dy > 0) {
return 100;
} else {
return Math.sqrt(dx * dx + dy * dy);
}
}
private double dist4(Point p1, Point p2) {
int dx = p2.x - p1.x;
int dy = p2.y - p1.y;
if (dx > 0 && dy > 0) {
return 100;
} else {
return Math.sqrt(dx * dx + dy * dy);
}
}
public void mouseWheelMoved(MouseWheelEvent e) {
int minZ = 1000, maxZ = -1000;
int notches = e.getWheelRotation();
for (Component c : mp.getComponents()) {
if (c instanceof ImagePanel) {
ImagePanel ip = ((ImagePanel) c);
int z = mp.getComponentZOrder(ip);
if (z < minZ) {
minZ = z;
}
if (z > maxZ) {
maxZ = z;
}
}
}
for (Component c : mp.getComponents()) {
if (c instanceof ImagePanel) {
ImagePanel ip = ((ImagePanel) c);
if (ip.selected) {
int z = mp.getComponentZOrder(ip);
z -= notches;
if (z > maxZ) {
z = maxZ;
}
if (z < minZ) {
z = minZ;
}
mp.setComponentZOrder(ip, z);
}
}
}
mp.repaint();
}
public void keyPressed(KeyEvent e) {
int kc = e.getKeyCode();
if (kc == KeyEvent.VK_DELETE || kc == KeyEvent.VK_BACK_SPACE) {
cv.removeImages();
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
public void alert(String msg) {
JOptionPane.showMessageDialog(null, msg);
}
}
| 9,346 | 0.469292 | 0.461053 | 259 | 35.084942 | 29.540766 | 215 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6139 | false | false | 11 |
2e42e75f64ea12bd2105e64ac82d2de4e57cf466 | 6,803,228,249,591 | 7e181aa838f3979c693dc87069da44442aed673c | /namescorer/src/org/peb/scorer/Scorer.java | a5494dc67667c7e0836a5e9a70e0a9484eacd6da | [] | no_license | pblack67/occ | https://github.com/pblack67/occ | d9b5dee77144fea6d2671a69cb4cc79dd421a082 | 295add7dc065c9500fcaee5f9c0b9f88f64e33e1 | refs/heads/master | 2020-09-11T06:10:30.440000 | 2019-11-17T22:46:27 | 2019-11-17T22:46:27 | 221,966,644 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.peb.scorer;
public interface Scorer {
/**
* This function scores an individual name
*
* @param name The name to be scored
* @return The name's score
*/
int scoreName(String name);
/**
* This function completely scores the entire array of names
*
* @param names The array of names to be scored
* @return The list's total score
*/
int score(String[] names);
}
| UTF-8 | Java | 403 | java | Scorer.java | Java | [] | null | [] | package org.peb.scorer;
public interface Scorer {
/**
* This function scores an individual name
*
* @param name The name to be scored
* @return The name's score
*/
int scoreName(String name);
/**
* This function completely scores the entire array of names
*
* @param names The array of names to be scored
* @return The list's total score
*/
int score(String[] names);
}
| 403 | 0.665012 | 0.665012 | 21 | 18.190475 | 18.355274 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.904762 | false | false | 11 |
89dee6046ddab18957a95039a3e0595a17927aca | 532,575,948,515 | a28473366a8335635e5c43e3b67153c713a5d27c | /event-sourcing/axon/finance-axon-query/src/main/java/com/trivadis/sample/axon/account/event/AccountCreatedEvent.java | cacf0e381cc2d7253cd7a79ff3b41b12b075ccbd | [] | no_license | rodrigo-mendes/various-demos | https://github.com/rodrigo-mendes/various-demos | a71304c58eb7b668c78016edbebbe3267126ac41 | 2e8833d127388371560a951052f59f8586744f2f | refs/heads/master | 2023-03-11T08:20:46.262000 | 2021-03-01T13:52:21 | 2021-03-01T13:52:21 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.trivadis.sample.axon.account.event;
import java.math.BigDecimal;
/**
* @author saikatkar1
*
*/
public class AccountCreatedEvent extends BaseEvent<String> {
private String forCustomerId;
private String accountType;
private BigDecimal balance;
public AccountCreatedEvent(String __eventId, String id,String forCustomerId,String accountType,BigDecimal balance) {
super(__eventId, id);
this.setForCustomerId(forCustomerId);
this.setBalance(balance);
this.setAccountType(accountType);
}
public AccountCreatedEvent() {}
public String getForCustomerId() {
return forCustomerId;
}
public void setForCustomerId(String forCustomerId) {
this.forCustomerId = forCustomerId;
}
public String getAccountType() {
return accountType;
}
public void setAccountType(String accountType) {
this.accountType = accountType;
}
public BigDecimal getBalance() {
return balance;
}
public void setBalance(BigDecimal balance) {
this.balance = balance;
}
}
| UTF-8 | Java | 990 | java | AccountCreatedEvent.java | Java | [
{
"context": "ent;\n\nimport java.math.BigDecimal;\n\n/**\n * @author saikatkar1\n *\n */\npublic class AccountCreatedEvent extends B",
"end": 104,
"score": 0.9996523857116699,
"start": 94,
"tag": "USERNAME",
"value": "saikatkar1"
}
] | null | [] | package com.trivadis.sample.axon.account.event;
import java.math.BigDecimal;
/**
* @author saikatkar1
*
*/
public class AccountCreatedEvent extends BaseEvent<String> {
private String forCustomerId;
private String accountType;
private BigDecimal balance;
public AccountCreatedEvent(String __eventId, String id,String forCustomerId,String accountType,BigDecimal balance) {
super(__eventId, id);
this.setForCustomerId(forCustomerId);
this.setBalance(balance);
this.setAccountType(accountType);
}
public AccountCreatedEvent() {}
public String getForCustomerId() {
return forCustomerId;
}
public void setForCustomerId(String forCustomerId) {
this.forCustomerId = forCustomerId;
}
public String getAccountType() {
return accountType;
}
public void setAccountType(String accountType) {
this.accountType = accountType;
}
public BigDecimal getBalance() {
return balance;
}
public void setBalance(BigDecimal balance) {
this.balance = balance;
}
}
| 990 | 0.760606 | 0.759596 | 47 | 20.063829 | 22.752512 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.255319 | false | false | 11 |
bf2a0c07d2869741e54402bcd41805b78b376a22 | 17,549,236,431,854 | 657465724a4ceb3120040f72ccd6207507cb1151 | /src/main/java/task_13.java | 9b78737b184dcd181b74acdeba3c8d70265c7067 | [] | no_license | skynetls/test_5 | https://github.com/skynetls/test_5 | 9cdbfe89da75b1b38b5ec92fde11af835c3901d7 | 38e49b270c29adbafb1672c6ea0ffbd7148deb9b | refs/heads/master | 2020-04-05T16:46:36.918000 | 2018-11-17T23:31:59 | 2018-11-17T23:31:59 | 157,028,008 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Scanner;
public class task_13 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Введите число: ");
String S = scanner.next();
int X = Integer.parseInt(S);
double Y = (double) X;
System.out.println(S);
System.out.println(X);
System.out.println(Y);
scanner.close();
}
}
| UTF-8 | Java | 456 | java | task_13.java | Java | [] | null | [] | import java.util.Scanner;
public class task_13 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Введите число: ");
String S = scanner.next();
int X = Integer.parseInt(S);
double Y = (double) X;
System.out.println(S);
System.out.println(X);
System.out.println(Y);
scanner.close();
}
}
| 456 | 0.547297 | 0.542793 | 19 | 21.368422 | 17.076332 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.526316 | false | false | 11 |
3a55d0d2055129cb666ad34aa1a4d2cf88ff2c16 | 12,472,585,080,695 | e31980f1aa66a1f391d375746028e813113ab562 | /src/asyn/Semantic/Asignacion.java | c7b4319dec6b8b7d9eac7b29e5b2726dc130bfec | [] | no_license | matiaschap/miniJava | https://github.com/matiaschap/miniJava | 55dc2cca9abcd36847786b33a8f23285d920962c | ead0b556cbbd81eda9a6c6fea9eae0e5363a6891 | refs/heads/master | 2021-08-31T13:14:48.208000 | 2017-12-21T12:14:57 | 2017-12-21T12:14:57 | 115,000,446 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package asyn.Semantic;
import asyn.Token;
public class Asignacion extends Sentencia{
private Expresion exp;
private Primario li;
public Asignacion(Expresion exp, Primario li, Token t) {
this.exp = exp;
this.li = li;
linea = t.getnLinea();
}
public void check() throws Exception {
li.setEsLadoIzq(true);
TipoMetodo tipoExp = exp.check();
TipoMetodo tipoLi = li.check();
if(tipoExp.esVoid())
throw new Exception("Error en la linea "+linea+". La expresion debe devolver un tipo valido. El metodo llamado es void");
if (li.terminaEnLlamada())
throw new Exception("Error en la linea "+linea+". El lado izquierdo no puede terminar en una llamada.");
if(!tipoExp.esCompatible(tipoLi)) {
throw new Exception("Tipos no compatibles en la asignacion en linea "+linea);
}
}
} | UTF-8 | Java | 845 | java | Asignacion.java | Java | [] | null | [] | package asyn.Semantic;
import asyn.Token;
public class Asignacion extends Sentencia{
private Expresion exp;
private Primario li;
public Asignacion(Expresion exp, Primario li, Token t) {
this.exp = exp;
this.li = li;
linea = t.getnLinea();
}
public void check() throws Exception {
li.setEsLadoIzq(true);
TipoMetodo tipoExp = exp.check();
TipoMetodo tipoLi = li.check();
if(tipoExp.esVoid())
throw new Exception("Error en la linea "+linea+". La expresion debe devolver un tipo valido. El metodo llamado es void");
if (li.terminaEnLlamada())
throw new Exception("Error en la linea "+linea+". El lado izquierdo no puede terminar en una llamada.");
if(!tipoExp.esCompatible(tipoLi)) {
throw new Exception("Tipos no compatibles en la asignacion en linea "+linea);
}
}
} | 845 | 0.678106 | 0.678106 | 34 | 22.911764 | 29.888388 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.529412 | false | false | 11 |
5f435c66f40cb83b9027185eda71c7cf29085045 | 25,288,767,492,684 | 6f438817c18c30beaa230df2ea9e884e6560c4c2 | /kafka-practice/src/main/java/com/paner/kafka/KafkaProtocol.java | bb7b6ae2fc241a480d9c79d70fe9de5c234adfef | [] | no_license | caidao/stream-process-practice | https://github.com/caidao/stream-process-practice | 9115793b95a7938122e56aea22b4287ad9695599 | 2120ac26f5b13ad8e5b791952bf5eaa98c555813 | refs/heads/master | 2021-01-20T13:56:17.125000 | 2018-03-01T07:05:26 | 2018-03-01T07:05:26 | 90,540,184 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.paner.kafka;
import kafka.api.*;
import kafka.api.FetchRequest;
import kafka.api.FetchResponse;
import kafka.api.GroupCoordinatorResponse;
import kafka.api.OffsetCommitResponse;
import kafka.api.OffsetFetchRequest;
import kafka.api.TopicMetadataResponse;
import kafka.common.OffsetAndMetadata;
import kafka.common.OffsetMetadata;
import kafka.common.TopicAndPartition;
import kafka.javaapi.*;
import kafka.javaapi.OffsetCommitRequest;
import kafka.javaapi.OffsetFetchResponse;
import kafka.javaapi.OffsetRequest;
import kafka.javaapi.TopicMetadataRequest;
import kafka.message.ByteBufferMessageSet;
import kafka.message.Message;
import kafka.network.BlockingChannel;
import org.apache.kafka.common.requests.ListGroupsRequest;
import org.apache.kafka.common.requests.ListOffsetRequest;
import org.junit.Before;
import org.junit.Test;
import scala.Predef;
import scala.Tuple2;
import scala.collection.JavaConverters;
import scala.collection.JavaConverters$;
import java.util.*;
/**
* Created by paner on 17/5/15.
*/
public class KafkaProtocol {
private BlockingChannel channel;
final String MY_CLIENTID = "demoClientId";
int correlationId = 0;
@Before
public void before(){
}
//topic元数据接口
@Test
public void topicMetadata(){
BlockingChannel channel =null;
try {
channel = new BlockingChannel("localhost", 9092,
BlockingChannel.UseDefaultBufferSize(),
BlockingChannel.UseDefaultBufferSize(),
5000 /* read timeout in millis */);
channel.connect();
TopicMetadataRequest request = new TopicMetadataRequest(Arrays.asList("streams-file-input"));
channel.send(request);
TopicMetadataResponse response = TopicMetadataResponse.readFrom(channel.receive().payload());
System.out.println("TopicMetadataResponse:"+convertSeq(convertSeq(response.topicsMetadata()).get(0).partitionsMetadata()));
}catch (Exception ex){
}finally {
channel.disconnect();
}
}
//发送produce请求
@Test
public void produceAPi(){
BlockingChannel channel =null;
try {
channel = new BlockingChannel("localhost", 9092,
BlockingChannel.UseDefaultBufferSize(),
BlockingChannel.UseDefaultBufferSize(),
5000 /* read timeout in millis */);
channel.connect();
// TopicMetadataRequest request = new TopicMetadataRequest(Arrays.asList("topic_0511_2"));
final TopicAndPartition testPartition0 = new TopicAndPartition("topic_0511_2", 1);
Message msgBuf =new Message("values".getBytes());
final ByteBufferMessageSet message = new ByteBufferMessageSet(convertList(Arrays.asList(msgBuf)));
Map<TopicAndPartition,ByteBufferMessageSet> map = new HashMap<TopicAndPartition, ByteBufferMessageSet>(){{
put(testPartition0,message);
}};
ProducerRequest request = new ProducerRequest((short)1,correlationId,MY_CLIENTID,(short)1,300,convertMap(map));
channel.send(request);
ProducerResponse response = ProducerResponse.readFrom(channel.receive().payload());
System.out.println("TopicMetadataResponse:"+response.describe(true));
}catch (Exception ex){
ex.printStackTrace();
}finally {
channel.disconnect();
}
}
//获取消息接口
@Test
public void fetchRequest(){
BlockingChannel channel =null;
try {
channel = new BlockingChannel("localhost", 9092,
BlockingChannel.UseDefaultBufferSize(),
BlockingChannel.UseDefaultBufferSize(),
5000 /* read timeout in millis */);
channel.connect();
final TopicAndPartition testPartition0 = new TopicAndPartition("topic_0511_2", 1);
final PartitionFetchInfo partitionFetchInfo0 = new PartitionFetchInfo(0,100);
Map<TopicAndPartition, PartitionFetchInfo> requestInfo =new HashMap<TopicAndPartition,PartitionFetchInfo>();
requestInfo.put(testPartition0, partitionFetchInfo0);
//这里的map是kafak封装的,而非java.util中提供的
FetchRequest request = new FetchRequest(++correlationId,MY_CLIENTID,10,10,
convert(requestInfo));
channel.send(request);
FetchResponse response = FetchResponse.readFrom(channel.receive().payload(), 100);
System.out.println(response.describe(true));
}catch (Exception ex){
ex.printStackTrace();
}finally {
channel.disconnect();
}
}
@Test
public void listOffset(){
BlockingChannel channel =null;
try {
channel = new BlockingChannel("localhost", 9092,
BlockingChannel.UseDefaultBufferSize(),
BlockingChannel.UseDefaultBufferSize(),
5000 /* read timeout in millis */);
channel.connect();
String groupId = "test";
long now = System.currentTimeMillis();
final TopicAndPartition testPartition0 = new TopicAndPartition("topic_0511_2", 1);
final OffsetAndMetadata partitionFetchInfo0 = new OffsetAndMetadata(new OffsetMetadata(0,null),now,now);
Map<TopicAndPartition, OffsetAndMetadata> requestInfo =new HashMap<TopicAndPartition,OffsetAndMetadata>();
requestInfo.put(testPartition0, partitionFetchInfo0);
//ListOffsetRequest request = new ListOffsetRequest(null);
//channel.send(request.);
TopicMetadataResponse response = TopicMetadataResponse.readFrom(channel.receive().payload());
System.out.println("TopicMetadataResponse:"+convertSeq(response.topicsMetadata()));
}catch (Exception ex){
}finally {
channel.disconnect();
}
}
//提交offset的方式
@Test
public void offsetCommitApi(){
BlockingChannel channel =null;
try {
channel = new BlockingChannel("localhost", 9092,
BlockingChannel.UseDefaultBufferSize(),
BlockingChannel.UseDefaultBufferSize(),
5000 /* read timeout in millis */);
channel.connect();
String groupId = "test";
long now = System.currentTimeMillis();
final TopicAndPartition testPartition0 = new TopicAndPartition("topic_0511_2", 1);
final OffsetAndMetadata partitionFetchInfo0 = new OffsetAndMetadata(new OffsetMetadata(100,"more metadata"),now,now);
Map<TopicAndPartition, OffsetAndMetadata> requestInfo =new HashMap<TopicAndPartition,OffsetAndMetadata>();
requestInfo.put(testPartition0, partitionFetchInfo0);
OffsetCommitRequest request = new OffsetCommitRequest(groupId,requestInfo,1,MY_CLIENTID);
channel.send(request.underlying());
OffsetCommitResponse response = OffsetCommitResponse.readFrom(channel.receive().payload());
System.out.println("OffsetCommitRequest:"+response.describe(true));
}catch (Exception ex){
}finally {
channel.disconnect();
}
}
//获取offset的方式
@Test
public void fetchOffsetApi(){
BlockingChannel channel =null;
try {
channel = new BlockingChannel("localhost", 9092,
BlockingChannel.UseDefaultBufferSize(),
BlockingChannel.UseDefaultBufferSize(),
5000 /* read timeout in millis */);
channel.connect();
String groupId = "streams-consumer";
final TopicAndPartition testPartition0 = new TopicAndPartition("streams-file-input", 1);
List<TopicAndPartition> partitions = new ArrayList<TopicAndPartition>();
partitions.add(testPartition0);
partitions.add(new TopicAndPartition("streams-file-input", 0));
partitions.add(new TopicAndPartition("streams-file-input", 2));
OffsetFetchRequest request = new OffsetFetchRequest(groupId,convertList(partitions),(short)1,correlationId,MY_CLIENTID);
channel.send(request);
OffsetFetchResponse response = kafka.javaapi.OffsetFetchResponse.readFrom(channel.receive().payload());
System.out.println("OffsetCommitRequest:"+response.offsets());
}catch (Exception ex){
}finally {
channel.disconnect();
}
}
@Test
public void groupCoordinator(){
BlockingChannel channel =null;
try {
channel = new BlockingChannel("localhost", 9092,
BlockingChannel.UseDefaultBufferSize(),
BlockingChannel.UseDefaultBufferSize(),
5000 /* read timeout in millis */);
channel.connect();
GroupCoordinatorRequest request = new GroupCoordinatorRequest("group_paner",(short)1,correlationId,MY_CLIENTID);
channel.send(request);
GroupCoordinatorResponse response = GroupCoordinatorResponse.readFrom(channel.receive().payload());
System.out.println("TopicMetadataResponse:"+response.describe(true));
}catch (Exception ex){
}finally {
channel.disconnect();
}
}
public <K, V> scala.collection.immutable.Map<K, V> convert(Map<K, V> m) {
return JavaConverters$.MODULE$.mapAsScalaMapConverter(m).asScala().toMap(
scala.Predef$.MODULE$.<scala.Tuple2<K, V>>conforms()
);
}
public <K, V> scala.collection.mutable.Map<K, V> convertMap(Map<K, V> m) {
return JavaConverters$.MODULE$.mapAsScalaMapConverter(m).asScala().seq();
}
public <K> scala.collection.Seq<K> convertList(List<K> m) {
return JavaConverters$.MODULE$.asScalaBufferConverter(m).asScala().toSeq().seq();
}
public <K> List<K> convertSeq(scala.collection.Seq<K> m){
return JavaConverters$.MODULE$.seqAsJavaListConverter(m).asJava();
}
}
| UTF-8 | Java | 10,210 | java | KafkaProtocol.java | Java | [
{
"context": "verters$;\n\n\nimport java.util.*;\n\n/**\n * Created by paner on 17/5/15.\n */\npublic class KafkaProtocol {\n\n ",
"end": 1015,
"score": 0.9722688794136047,
"start": 1010,
"tag": "USERNAME",
"value": "paner"
},
{
"context": "gChannel channel;\n final String MY_CLIENTID = \"demoClientId\";\n int correlationId = 0;\n\n @Before\n pub",
"end": 1143,
"score": 0.9172291159629822,
"start": 1131,
"tag": "USERNAME",
"value": "demoClientId"
},
{
"context": " channel.connect();\n String groupId = \"test\";\n long now = System.currentTimeMillis",
"end": 5129,
"score": 0.9950621724128723,
"start": 5125,
"tag": "USERNAME",
"value": "test"
},
{
"context": " channel.connect();\n String groupId = \"test\";\n long now = System.currentTimeMillis",
"end": 6411,
"score": 0.9954839944839478,
"start": 6407,
"tag": "USERNAME",
"value": "test"
}
] | null | [] | package com.paner.kafka;
import kafka.api.*;
import kafka.api.FetchRequest;
import kafka.api.FetchResponse;
import kafka.api.GroupCoordinatorResponse;
import kafka.api.OffsetCommitResponse;
import kafka.api.OffsetFetchRequest;
import kafka.api.TopicMetadataResponse;
import kafka.common.OffsetAndMetadata;
import kafka.common.OffsetMetadata;
import kafka.common.TopicAndPartition;
import kafka.javaapi.*;
import kafka.javaapi.OffsetCommitRequest;
import kafka.javaapi.OffsetFetchResponse;
import kafka.javaapi.OffsetRequest;
import kafka.javaapi.TopicMetadataRequest;
import kafka.message.ByteBufferMessageSet;
import kafka.message.Message;
import kafka.network.BlockingChannel;
import org.apache.kafka.common.requests.ListGroupsRequest;
import org.apache.kafka.common.requests.ListOffsetRequest;
import org.junit.Before;
import org.junit.Test;
import scala.Predef;
import scala.Tuple2;
import scala.collection.JavaConverters;
import scala.collection.JavaConverters$;
import java.util.*;
/**
* Created by paner on 17/5/15.
*/
public class KafkaProtocol {
private BlockingChannel channel;
final String MY_CLIENTID = "demoClientId";
int correlationId = 0;
@Before
public void before(){
}
//topic元数据接口
@Test
public void topicMetadata(){
BlockingChannel channel =null;
try {
channel = new BlockingChannel("localhost", 9092,
BlockingChannel.UseDefaultBufferSize(),
BlockingChannel.UseDefaultBufferSize(),
5000 /* read timeout in millis */);
channel.connect();
TopicMetadataRequest request = new TopicMetadataRequest(Arrays.asList("streams-file-input"));
channel.send(request);
TopicMetadataResponse response = TopicMetadataResponse.readFrom(channel.receive().payload());
System.out.println("TopicMetadataResponse:"+convertSeq(convertSeq(response.topicsMetadata()).get(0).partitionsMetadata()));
}catch (Exception ex){
}finally {
channel.disconnect();
}
}
//发送produce请求
@Test
public void produceAPi(){
BlockingChannel channel =null;
try {
channel = new BlockingChannel("localhost", 9092,
BlockingChannel.UseDefaultBufferSize(),
BlockingChannel.UseDefaultBufferSize(),
5000 /* read timeout in millis */);
channel.connect();
// TopicMetadataRequest request = new TopicMetadataRequest(Arrays.asList("topic_0511_2"));
final TopicAndPartition testPartition0 = new TopicAndPartition("topic_0511_2", 1);
Message msgBuf =new Message("values".getBytes());
final ByteBufferMessageSet message = new ByteBufferMessageSet(convertList(Arrays.asList(msgBuf)));
Map<TopicAndPartition,ByteBufferMessageSet> map = new HashMap<TopicAndPartition, ByteBufferMessageSet>(){{
put(testPartition0,message);
}};
ProducerRequest request = new ProducerRequest((short)1,correlationId,MY_CLIENTID,(short)1,300,convertMap(map));
channel.send(request);
ProducerResponse response = ProducerResponse.readFrom(channel.receive().payload());
System.out.println("TopicMetadataResponse:"+response.describe(true));
}catch (Exception ex){
ex.printStackTrace();
}finally {
channel.disconnect();
}
}
//获取消息接口
@Test
public void fetchRequest(){
BlockingChannel channel =null;
try {
channel = new BlockingChannel("localhost", 9092,
BlockingChannel.UseDefaultBufferSize(),
BlockingChannel.UseDefaultBufferSize(),
5000 /* read timeout in millis */);
channel.connect();
final TopicAndPartition testPartition0 = new TopicAndPartition("topic_0511_2", 1);
final PartitionFetchInfo partitionFetchInfo0 = new PartitionFetchInfo(0,100);
Map<TopicAndPartition, PartitionFetchInfo> requestInfo =new HashMap<TopicAndPartition,PartitionFetchInfo>();
requestInfo.put(testPartition0, partitionFetchInfo0);
//这里的map是kafak封装的,而非java.util中提供的
FetchRequest request = new FetchRequest(++correlationId,MY_CLIENTID,10,10,
convert(requestInfo));
channel.send(request);
FetchResponse response = FetchResponse.readFrom(channel.receive().payload(), 100);
System.out.println(response.describe(true));
}catch (Exception ex){
ex.printStackTrace();
}finally {
channel.disconnect();
}
}
@Test
public void listOffset(){
BlockingChannel channel =null;
try {
channel = new BlockingChannel("localhost", 9092,
BlockingChannel.UseDefaultBufferSize(),
BlockingChannel.UseDefaultBufferSize(),
5000 /* read timeout in millis */);
channel.connect();
String groupId = "test";
long now = System.currentTimeMillis();
final TopicAndPartition testPartition0 = new TopicAndPartition("topic_0511_2", 1);
final OffsetAndMetadata partitionFetchInfo0 = new OffsetAndMetadata(new OffsetMetadata(0,null),now,now);
Map<TopicAndPartition, OffsetAndMetadata> requestInfo =new HashMap<TopicAndPartition,OffsetAndMetadata>();
requestInfo.put(testPartition0, partitionFetchInfo0);
//ListOffsetRequest request = new ListOffsetRequest(null);
//channel.send(request.);
TopicMetadataResponse response = TopicMetadataResponse.readFrom(channel.receive().payload());
System.out.println("TopicMetadataResponse:"+convertSeq(response.topicsMetadata()));
}catch (Exception ex){
}finally {
channel.disconnect();
}
}
//提交offset的方式
@Test
public void offsetCommitApi(){
BlockingChannel channel =null;
try {
channel = new BlockingChannel("localhost", 9092,
BlockingChannel.UseDefaultBufferSize(),
BlockingChannel.UseDefaultBufferSize(),
5000 /* read timeout in millis */);
channel.connect();
String groupId = "test";
long now = System.currentTimeMillis();
final TopicAndPartition testPartition0 = new TopicAndPartition("topic_0511_2", 1);
final OffsetAndMetadata partitionFetchInfo0 = new OffsetAndMetadata(new OffsetMetadata(100,"more metadata"),now,now);
Map<TopicAndPartition, OffsetAndMetadata> requestInfo =new HashMap<TopicAndPartition,OffsetAndMetadata>();
requestInfo.put(testPartition0, partitionFetchInfo0);
OffsetCommitRequest request = new OffsetCommitRequest(groupId,requestInfo,1,MY_CLIENTID);
channel.send(request.underlying());
OffsetCommitResponse response = OffsetCommitResponse.readFrom(channel.receive().payload());
System.out.println("OffsetCommitRequest:"+response.describe(true));
}catch (Exception ex){
}finally {
channel.disconnect();
}
}
//获取offset的方式
@Test
public void fetchOffsetApi(){
BlockingChannel channel =null;
try {
channel = new BlockingChannel("localhost", 9092,
BlockingChannel.UseDefaultBufferSize(),
BlockingChannel.UseDefaultBufferSize(),
5000 /* read timeout in millis */);
channel.connect();
String groupId = "streams-consumer";
final TopicAndPartition testPartition0 = new TopicAndPartition("streams-file-input", 1);
List<TopicAndPartition> partitions = new ArrayList<TopicAndPartition>();
partitions.add(testPartition0);
partitions.add(new TopicAndPartition("streams-file-input", 0));
partitions.add(new TopicAndPartition("streams-file-input", 2));
OffsetFetchRequest request = new OffsetFetchRequest(groupId,convertList(partitions),(short)1,correlationId,MY_CLIENTID);
channel.send(request);
OffsetFetchResponse response = kafka.javaapi.OffsetFetchResponse.readFrom(channel.receive().payload());
System.out.println("OffsetCommitRequest:"+response.offsets());
}catch (Exception ex){
}finally {
channel.disconnect();
}
}
@Test
public void groupCoordinator(){
BlockingChannel channel =null;
try {
channel = new BlockingChannel("localhost", 9092,
BlockingChannel.UseDefaultBufferSize(),
BlockingChannel.UseDefaultBufferSize(),
5000 /* read timeout in millis */);
channel.connect();
GroupCoordinatorRequest request = new GroupCoordinatorRequest("group_paner",(short)1,correlationId,MY_CLIENTID);
channel.send(request);
GroupCoordinatorResponse response = GroupCoordinatorResponse.readFrom(channel.receive().payload());
System.out.println("TopicMetadataResponse:"+response.describe(true));
}catch (Exception ex){
}finally {
channel.disconnect();
}
}
public <K, V> scala.collection.immutable.Map<K, V> convert(Map<K, V> m) {
return JavaConverters$.MODULE$.mapAsScalaMapConverter(m).asScala().toMap(
scala.Predef$.MODULE$.<scala.Tuple2<K, V>>conforms()
);
}
public <K, V> scala.collection.mutable.Map<K, V> convertMap(Map<K, V> m) {
return JavaConverters$.MODULE$.mapAsScalaMapConverter(m).asScala().seq();
}
public <K> scala.collection.Seq<K> convertList(List<K> m) {
return JavaConverters$.MODULE$.asScalaBufferConverter(m).asScala().toSeq().seq();
}
public <K> List<K> convertSeq(scala.collection.Seq<K> m){
return JavaConverters$.MODULE$.seqAsJavaListConverter(m).asJava();
}
}
| 10,210 | 0.646664 | 0.633241 | 243 | 40.695473 | 33.222374 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.831276 | false | false | 11 |
de8dca6b9ba48159ae7a4ab82908eb892a63f1db | 30,769,145,764,584 | 0fe17a07d0f72ca39f852bafdf8ccdb7bd9207ee | /ComInLanDroid/cominlan/src/main/java/com/onballgroup/cominlan/model/packet/IClientPacket.java | 88ebcccf56a525887f5d5beb3779838aead2de08 | [] | no_license | lhphong09t2/ComInLan | https://github.com/lhphong09t2/ComInLan | 5009bb56761f0218031c80a96e106881c71a6724 | ee25aa90ee464f38342fb226c1fb3b8931dcdafa | refs/heads/master | 2020-02-26T13:46:17.926000 | 2016-04-28T02:59:50 | 2016-04-28T02:59:50 | 63,703,558 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.onballgroup.cominlan.model.packet;
import com.onballgroup.cominlan.model.Base.IJson;
/**
* Created by Phong Le on 4/18/2016.
*/
public interface IClientPacket extends IJson {
String getId();
String getName();
ClientPacketType getType();
}
| UTF-8 | Java | 267 | java | IClientPacket.java | Java | [
{
"context": "roup.cominlan.model.Base.IJson;\n\n/**\n * Created by Phong Le on 4/18/2016.\n */\npublic interface IClientPacket ",
"end": 125,
"score": 0.9997532963752747,
"start": 117,
"tag": "NAME",
"value": "Phong Le"
}
] | null | [] | package com.onballgroup.cominlan.model.packet;
import com.onballgroup.cominlan.model.Base.IJson;
/**
* Created by <NAME> on 4/18/2016.
*/
public interface IClientPacket extends IJson {
String getId();
String getName();
ClientPacketType getType();
}
| 265 | 0.726592 | 0.700375 | 12 | 21.25 | 18.912628 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.416667 | false | false | 11 |
fdd1938dcaa715f7f56e59951ea2adf511d79a0e | 17,102,559,817,686 | c77bad14169c9ebeebc5fda8f6fbfd43215bccda | /app/src/main/java/com/tencent/ilivedemo/demos/DemoGuest.java | dee8b23dac0d792389aa9d1f1292d9bd95f3d3c6 | [] | no_license | huobaohai/LiveApp_ILiveSDK | https://github.com/huobaohai/LiveApp_ILiveSDK | 2e59deb5ba5600a01d9ced8a60b38ba029bb7208 | 9a8290ba3a76e9e07502acf78d83fca103e02e64 | refs/heads/master | 2020-05-16T03:05:39.952000 | 2019-04-22T12:28:42 | 2019-04-22T12:28:42 | 182,651,519 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tencent.ilivedemo.demos;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import com.tencent.av.sdk.AVContext;
import com.tencent.ilivedemo.R;
import com.tencent.ilivedemo.model.Constants;
import com.tencent.ilivedemo.model.MessageObservable;
import com.tencent.ilivedemo.model.StatusObservable;
import com.tencent.ilivedemo.model.UserInfo;
import com.tencent.ilivedemo.uiutils.DemoFunc;
import com.tencent.ilivedemo.uiutils.DlgMgr;
import com.tencent.ilivesdk.ILiveCallBack;
import com.tencent.ilivesdk.ILiveConstants;
import com.tencent.ilivesdk.ILiveSDK;
import com.tencent.ilivesdk.core.ILiveLoginManager;
import com.tencent.ilivesdk.core.ILiveRoomManager;
import com.tencent.ilivesdk.core.ILiveRoomOption;
import com.tencent.ilivesdk.data.ILiveMessage;
import com.tencent.ilivesdk.data.msg.ILiveTextMessage;
import com.tencent.ilivesdk.listener.ILiveEventHandler;
import com.tencent.ilivesdk.listener.ILiveMessageListener;
import com.tencent.ilivesdk.tools.quality.ILiveQualityData;
import com.tencent.ilivesdk.tools.quality.LiveInfo;
import com.tencent.ilivesdk.view.AVRootView;
import java.util.Map;
import master.flame.danmaku.controller.DrawHandler;
import master.flame.danmaku.danmaku.model.BaseDanmaku;
import master.flame.danmaku.danmaku.model.DanmakuTimer;
import master.flame.danmaku.danmaku.model.IDanmakus;
import master.flame.danmaku.danmaku.model.android.DanmakuContext;
import master.flame.danmaku.danmaku.model.android.Danmakus;
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser;
import master.flame.danmaku.ui.widget.DanmakuView;
import static com.tencent.ilivesdk.data.ILiveMessage.ILIVE_MSG_TYPE_TEXT;
public class DemoGuest extends Activity implements View.OnClickListener, ILiveMessageListener, ILiveLoginManager.TILVBStatusListener {
private final String TAG = "DemoGuest";
private EditText etMsg;
private AVRootView arvRoot;
private TextView tvMsg;
private ScrollView svScroll;
private TextView hostName;
private TextView hostTitle;
private boolean isInfoOn = true;
private boolean isDanmu = true;
private Handler mainHandler = new Handler(Looper.getMainLooper());
private String strMsg = "";
private DanmakuView danmakuView;
private DanmakuContext danmakuContext;
private BaseDanmakuParser parser = new BaseDanmakuParser() {
@Override
protected IDanmakus parse() {
return new Danmakus();
}
};
private Runnable infoRun = new Runnable() {
@Override
public void run() {
ILiveQualityData qualityData = ILiveRoomManager.getInstance().getQualityData();
if (null != qualityData) {
String info = "AVSDK 版本: \t" + AVContext.sdkVersion + "\n\n"
+ "上行速率:\t" + qualityData.getSendKbps() + "kbps\t"
+ "上行丢包率:\t" + qualityData.getSendLossRate() / 100 + "%\n\n"
+ "下行速率:\t" + qualityData.getRecvKbps() + "kbps\t"
+ "下行丢包率:\t" + qualityData.getRecvLossRate() / 100 + "%\n\n"
+ "应用CPU:\t" + qualityData.getAppCPURate() + "\t"
+ "系统CPU:\t" + qualityData.getSysCPURate() + "\n\n";
for (Map.Entry<String, LiveInfo> entry : qualityData.getLives().entrySet()) {
info += "\t" + entry.getKey() + "-" + entry.getValue().getWidth() + "*" + entry.getValue().getHeight() + "\n\n";
}
((TextView) findViewById(R.id.tv_status)).setText(info);
}
if (ILiveRoomManager.getInstance().isEnterRoom()) {
mainHandler.postDelayed(infoRun, 2000);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo_guest);
String room_id = getIntent().getStringExtra("room_ID");
UserInfo.getInstance().getCache(getApplicationContext());
arvRoot = (AVRootView) findViewById(R.id.arv_root);
hostName = (TextView) findViewById(R.id.live_host_name);
hostName.setText(room_id);
hostTitle = (TextView) findViewById(R.id.live_host_title);
etMsg = (EditText) findViewById(R.id.guest_say_something);
tvMsg = (TextView) findViewById(R.id.tv_msg);
svScroll = (ScrollView) findViewById(R.id.sv_scroll);
danmakuView = (DanmakuView) findViewById(R.id.danmu_ku);
ILiveRoomManager.getInstance().initAvRootView(arvRoot);
MessageObservable.getInstance().addObserver(this);
StatusObservable.getInstance().addObserver(this);
joinRoom(room_id);
// 管理弹幕
setDanmuku();
ILiveSDK.getInstance().addEventHandler(new ILiveEventHandler(){
@Override
public void onGroupDisband(int roomId, String groupId) {
if (groupId.equals(ILiveRoomManager.getInstance().getIMGroupId())) {
DlgMgr.showMsg(getContenxt(), getString(R.string.str_tips_discuss)).setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialogInterface) {
finish();
}
});
}
}
});
}
@Override
protected void onPause() {
super.onPause();
ILiveRoomManager.getInstance().onPause();
}
@Override
protected void onResume() {
super.onResume();
ILiveRoomManager.getInstance().onResume();
}
private Context getContenxt(){
return this;
}
@Override
protected void onDestroy() {
super.onDestroy();
MessageObservable.getInstance().deleteObserver(this);
StatusObservable.getInstance().deleteObserver(this);
ILiveRoomManager.getInstance().onDestory();
isDanmu = false;
if (danmakuView != null) {
danmakuView.release();
danmakuView = null;
}
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.guest_send_msg:
sendMsg();
break;
case R.id.close_live:
finish();
break;
case R.id.iv_info:
isInfoOn = !isInfoOn;
((ImageView) findViewById(R.id.iv_info)).setImageResource(isInfoOn ? R.mipmap.ic_info_on : R.mipmap.ic_info_off);
findViewById(R.id.tv_status).setVisibility(isInfoOn ? View.VISIBLE : View.INVISIBLE);
break;
case R.id.iv_danmu:
// 开启弹幕
isDanmu = !isDanmu;
((ImageView) findViewById(R.id.iv_danmu)).setImageResource(isDanmu ? R.mipmap.icon_message_pressed : R.mipmap.icon_message_png);
if (isDanmu) {
danmakuView.show();
} else {
danmakuView.hide();
}
break;
}
}
@Override
public void onNewMessage(ILiveMessage message) {
switch (message.getMsgType()) {
case ILIVE_MSG_TYPE_TEXT:
ILiveTextMessage textMessage = (ILiveTextMessage) message;
addMessage(textMessage.getSender(), DemoFunc.getLimitString(textMessage.getText(), Constants.MAX_SIZE), false);
break;
}
}
@Override
public void onForceOffline(int error, String message) {
finish();
}
private Context getContext() {
return this;
}
// 添加消息
private void addMessage(String sender, String msg, boolean self) {
String[] msgs = msg.split("@");
String trueMsg = "";
if (msgs.length>1){
trueMsg = msgs[1];
}else {
trueMsg = msg;
}
if (msgs.length > 1 && msgs[0].equals("host") && !TextUtils.isEmpty(msgs[1])) {
strMsg += "主播 [" + sender + "] : " + msgs[1] + "\n";
addDanmaku(trueMsg, false);
} else if (self) {
strMsg += "[我] : " + msg + "\n";
addDanmaku(trueMsg, true);
} else {
strMsg += "[" + sender + "] : " + msg + "\n";
addDanmaku(trueMsg, false);
}
tvMsg.setText(strMsg);
svScroll.fullScroll(View.FOCUS_DOWN);
}
// 加入房间
private void joinRoom(String room_id) {
int roomId = DemoFunc.getIntValue(room_id, -1);
if (-1 == roomId) {
DlgMgr.showMsg(getContext(), getString(R.string.str_tip_num_error));
return;
}
ILiveRoomOption option = new ILiveRoomOption("")
.controlRole(Constants.ROLE_GUEST)
.videoMode(ILiveConstants.VIDEOMODE_NORMAL)
.autoCamera(false)
.autoMic(false);
ILiveRoomManager.getInstance().joinRoom(roomId,
option, new ILiveCallBack() {
@Override
public void onSuccess(Object data) {
afterJoin();
}
@Override
public void onError(String module, int errCode, String errMsg) {
DlgMgr.showMsg(getContext(), "create failed:" + module + "|" + errCode + "|" + errMsg);
}
});
}
private void afterJoin() {
UserInfo.getInstance().setRoom(ILiveRoomManager.getInstance().getRoomId());
UserInfo.getInstance().writeToCache(this);
findViewById(R.id.iv_danmu).setVisibility(View.VISIBLE);
findViewById(R.id.iv_info).setVisibility(View.VISIBLE);
mainHandler.postDelayed(infoRun, 500);
}
// 发送消息
private void sendMsg() {
final String strMsg = etMsg.getText().toString();
if (TextUtils.isEmpty(strMsg)) {
DlgMgr.showMsg(this, getString(R.string.msg_send_empty));
return;
} else if (strMsg.length() > Constants.MAX_SIZE) {
DlgMgr.showMsg(this, getString(R.string.str_send_limit));
return;
}
ILiveTextMessage textMessage = new ILiveTextMessage(strMsg);
ILiveRoomManager.getInstance().sendGroupMessage(textMessage, new ILiveCallBack() {
@Override
public void onSuccess(Object data) {
addMessage(ILiveLoginManager.getInstance().getMyUserId(), strMsg, true);
etMsg.setText("");
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(etMsg.getWindowToken(), 0);
}
@Override
public void onError(String module, int errCode, String errMsg) {
DlgMgr.showMsg(getContext(), "sendText failed:" + module + "|" + errCode + "|" + errMsg);
}
});
}
private void setDanmuku() {
danmakuView.enableDanmakuDrawingCache(true);
danmakuView.setCallback(new DrawHandler.Callback() {
@Override
public void prepared() {
if (isDanmu) {
danmakuView.start();
}
}
@Override
public void updateTimer(DanmakuTimer timer) {
}
@Override
public void danmakuShown(BaseDanmaku danmaku) {
}
@Override
public void drawingFinished() {
}
});
danmakuContext = DanmakuContext.create();
danmakuView.prepare(parser, danmakuContext);
}
// 转换单位
public int sp2px(float spValue) {
final float fontScale = getResources().getDisplayMetrics().scaledDensity;
return (int) (spValue * fontScale + 0.5f);
}
private void addDanmaku(String content, boolean b) {
BaseDanmaku danmaku = danmakuContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL);
danmaku.text = content;
danmaku.padding = 10;
danmaku.textColor = Color.WHITE;
danmaku.textSize = sp2px(20);
danmaku.setTime(danmakuView.getCurrentTime());
if (b) {
danmaku.borderColor = Color.RED;
}
danmakuView.addDanmaku(danmaku);
}
}
| UTF-8 | Java | 12,884 | java | DemoGuest.java | Java | [] | null | [] | package com.tencent.ilivedemo.demos;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import com.tencent.av.sdk.AVContext;
import com.tencent.ilivedemo.R;
import com.tencent.ilivedemo.model.Constants;
import com.tencent.ilivedemo.model.MessageObservable;
import com.tencent.ilivedemo.model.StatusObservable;
import com.tencent.ilivedemo.model.UserInfo;
import com.tencent.ilivedemo.uiutils.DemoFunc;
import com.tencent.ilivedemo.uiutils.DlgMgr;
import com.tencent.ilivesdk.ILiveCallBack;
import com.tencent.ilivesdk.ILiveConstants;
import com.tencent.ilivesdk.ILiveSDK;
import com.tencent.ilivesdk.core.ILiveLoginManager;
import com.tencent.ilivesdk.core.ILiveRoomManager;
import com.tencent.ilivesdk.core.ILiveRoomOption;
import com.tencent.ilivesdk.data.ILiveMessage;
import com.tencent.ilivesdk.data.msg.ILiveTextMessage;
import com.tencent.ilivesdk.listener.ILiveEventHandler;
import com.tencent.ilivesdk.listener.ILiveMessageListener;
import com.tencent.ilivesdk.tools.quality.ILiveQualityData;
import com.tencent.ilivesdk.tools.quality.LiveInfo;
import com.tencent.ilivesdk.view.AVRootView;
import java.util.Map;
import master.flame.danmaku.controller.DrawHandler;
import master.flame.danmaku.danmaku.model.BaseDanmaku;
import master.flame.danmaku.danmaku.model.DanmakuTimer;
import master.flame.danmaku.danmaku.model.IDanmakus;
import master.flame.danmaku.danmaku.model.android.DanmakuContext;
import master.flame.danmaku.danmaku.model.android.Danmakus;
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser;
import master.flame.danmaku.ui.widget.DanmakuView;
import static com.tencent.ilivesdk.data.ILiveMessage.ILIVE_MSG_TYPE_TEXT;
public class DemoGuest extends Activity implements View.OnClickListener, ILiveMessageListener, ILiveLoginManager.TILVBStatusListener {
private final String TAG = "DemoGuest";
private EditText etMsg;
private AVRootView arvRoot;
private TextView tvMsg;
private ScrollView svScroll;
private TextView hostName;
private TextView hostTitle;
private boolean isInfoOn = true;
private boolean isDanmu = true;
private Handler mainHandler = new Handler(Looper.getMainLooper());
private String strMsg = "";
private DanmakuView danmakuView;
private DanmakuContext danmakuContext;
private BaseDanmakuParser parser = new BaseDanmakuParser() {
@Override
protected IDanmakus parse() {
return new Danmakus();
}
};
private Runnable infoRun = new Runnable() {
@Override
public void run() {
ILiveQualityData qualityData = ILiveRoomManager.getInstance().getQualityData();
if (null != qualityData) {
String info = "AVSDK 版本: \t" + AVContext.sdkVersion + "\n\n"
+ "上行速率:\t" + qualityData.getSendKbps() + "kbps\t"
+ "上行丢包率:\t" + qualityData.getSendLossRate() / 100 + "%\n\n"
+ "下行速率:\t" + qualityData.getRecvKbps() + "kbps\t"
+ "下行丢包率:\t" + qualityData.getRecvLossRate() / 100 + "%\n\n"
+ "应用CPU:\t" + qualityData.getAppCPURate() + "\t"
+ "系统CPU:\t" + qualityData.getSysCPURate() + "\n\n";
for (Map.Entry<String, LiveInfo> entry : qualityData.getLives().entrySet()) {
info += "\t" + entry.getKey() + "-" + entry.getValue().getWidth() + "*" + entry.getValue().getHeight() + "\n\n";
}
((TextView) findViewById(R.id.tv_status)).setText(info);
}
if (ILiveRoomManager.getInstance().isEnterRoom()) {
mainHandler.postDelayed(infoRun, 2000);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo_guest);
String room_id = getIntent().getStringExtra("room_ID");
UserInfo.getInstance().getCache(getApplicationContext());
arvRoot = (AVRootView) findViewById(R.id.arv_root);
hostName = (TextView) findViewById(R.id.live_host_name);
hostName.setText(room_id);
hostTitle = (TextView) findViewById(R.id.live_host_title);
etMsg = (EditText) findViewById(R.id.guest_say_something);
tvMsg = (TextView) findViewById(R.id.tv_msg);
svScroll = (ScrollView) findViewById(R.id.sv_scroll);
danmakuView = (DanmakuView) findViewById(R.id.danmu_ku);
ILiveRoomManager.getInstance().initAvRootView(arvRoot);
MessageObservable.getInstance().addObserver(this);
StatusObservable.getInstance().addObserver(this);
joinRoom(room_id);
// 管理弹幕
setDanmuku();
ILiveSDK.getInstance().addEventHandler(new ILiveEventHandler(){
@Override
public void onGroupDisband(int roomId, String groupId) {
if (groupId.equals(ILiveRoomManager.getInstance().getIMGroupId())) {
DlgMgr.showMsg(getContenxt(), getString(R.string.str_tips_discuss)).setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialogInterface) {
finish();
}
});
}
}
});
}
@Override
protected void onPause() {
super.onPause();
ILiveRoomManager.getInstance().onPause();
}
@Override
protected void onResume() {
super.onResume();
ILiveRoomManager.getInstance().onResume();
}
private Context getContenxt(){
return this;
}
@Override
protected void onDestroy() {
super.onDestroy();
MessageObservable.getInstance().deleteObserver(this);
StatusObservable.getInstance().deleteObserver(this);
ILiveRoomManager.getInstance().onDestory();
isDanmu = false;
if (danmakuView != null) {
danmakuView.release();
danmakuView = null;
}
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.guest_send_msg:
sendMsg();
break;
case R.id.close_live:
finish();
break;
case R.id.iv_info:
isInfoOn = !isInfoOn;
((ImageView) findViewById(R.id.iv_info)).setImageResource(isInfoOn ? R.mipmap.ic_info_on : R.mipmap.ic_info_off);
findViewById(R.id.tv_status).setVisibility(isInfoOn ? View.VISIBLE : View.INVISIBLE);
break;
case R.id.iv_danmu:
// 开启弹幕
isDanmu = !isDanmu;
((ImageView) findViewById(R.id.iv_danmu)).setImageResource(isDanmu ? R.mipmap.icon_message_pressed : R.mipmap.icon_message_png);
if (isDanmu) {
danmakuView.show();
} else {
danmakuView.hide();
}
break;
}
}
@Override
public void onNewMessage(ILiveMessage message) {
switch (message.getMsgType()) {
case ILIVE_MSG_TYPE_TEXT:
ILiveTextMessage textMessage = (ILiveTextMessage) message;
addMessage(textMessage.getSender(), DemoFunc.getLimitString(textMessage.getText(), Constants.MAX_SIZE), false);
break;
}
}
@Override
public void onForceOffline(int error, String message) {
finish();
}
private Context getContext() {
return this;
}
// 添加消息
private void addMessage(String sender, String msg, boolean self) {
String[] msgs = msg.split("@");
String trueMsg = "";
if (msgs.length>1){
trueMsg = msgs[1];
}else {
trueMsg = msg;
}
if (msgs.length > 1 && msgs[0].equals("host") && !TextUtils.isEmpty(msgs[1])) {
strMsg += "主播 [" + sender + "] : " + msgs[1] + "\n";
addDanmaku(trueMsg, false);
} else if (self) {
strMsg += "[我] : " + msg + "\n";
addDanmaku(trueMsg, true);
} else {
strMsg += "[" + sender + "] : " + msg + "\n";
addDanmaku(trueMsg, false);
}
tvMsg.setText(strMsg);
svScroll.fullScroll(View.FOCUS_DOWN);
}
// 加入房间
private void joinRoom(String room_id) {
int roomId = DemoFunc.getIntValue(room_id, -1);
if (-1 == roomId) {
DlgMgr.showMsg(getContext(), getString(R.string.str_tip_num_error));
return;
}
ILiveRoomOption option = new ILiveRoomOption("")
.controlRole(Constants.ROLE_GUEST)
.videoMode(ILiveConstants.VIDEOMODE_NORMAL)
.autoCamera(false)
.autoMic(false);
ILiveRoomManager.getInstance().joinRoom(roomId,
option, new ILiveCallBack() {
@Override
public void onSuccess(Object data) {
afterJoin();
}
@Override
public void onError(String module, int errCode, String errMsg) {
DlgMgr.showMsg(getContext(), "create failed:" + module + "|" + errCode + "|" + errMsg);
}
});
}
private void afterJoin() {
UserInfo.getInstance().setRoom(ILiveRoomManager.getInstance().getRoomId());
UserInfo.getInstance().writeToCache(this);
findViewById(R.id.iv_danmu).setVisibility(View.VISIBLE);
findViewById(R.id.iv_info).setVisibility(View.VISIBLE);
mainHandler.postDelayed(infoRun, 500);
}
// 发送消息
private void sendMsg() {
final String strMsg = etMsg.getText().toString();
if (TextUtils.isEmpty(strMsg)) {
DlgMgr.showMsg(this, getString(R.string.msg_send_empty));
return;
} else if (strMsg.length() > Constants.MAX_SIZE) {
DlgMgr.showMsg(this, getString(R.string.str_send_limit));
return;
}
ILiveTextMessage textMessage = new ILiveTextMessage(strMsg);
ILiveRoomManager.getInstance().sendGroupMessage(textMessage, new ILiveCallBack() {
@Override
public void onSuccess(Object data) {
addMessage(ILiveLoginManager.getInstance().getMyUserId(), strMsg, true);
etMsg.setText("");
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(etMsg.getWindowToken(), 0);
}
@Override
public void onError(String module, int errCode, String errMsg) {
DlgMgr.showMsg(getContext(), "sendText failed:" + module + "|" + errCode + "|" + errMsg);
}
});
}
private void setDanmuku() {
danmakuView.enableDanmakuDrawingCache(true);
danmakuView.setCallback(new DrawHandler.Callback() {
@Override
public void prepared() {
if (isDanmu) {
danmakuView.start();
}
}
@Override
public void updateTimer(DanmakuTimer timer) {
}
@Override
public void danmakuShown(BaseDanmaku danmaku) {
}
@Override
public void drawingFinished() {
}
});
danmakuContext = DanmakuContext.create();
danmakuView.prepare(parser, danmakuContext);
}
// 转换单位
public int sp2px(float spValue) {
final float fontScale = getResources().getDisplayMetrics().scaledDensity;
return (int) (spValue * fontScale + 0.5f);
}
private void addDanmaku(String content, boolean b) {
BaseDanmaku danmaku = danmakuContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL);
danmaku.text = content;
danmaku.padding = 10;
danmaku.textColor = Color.WHITE;
danmaku.textSize = sp2px(20);
danmaku.setTime(danmakuView.getCurrentTime());
if (b) {
danmaku.borderColor = Color.RED;
}
danmakuView.addDanmaku(danmaku);
}
}
| 12,884 | 0.604991 | 0.602644 | 360 | 34.505554 | 28.227251 | 148 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.575 | false | false | 11 |
e697452b4d1a9b243a183031d4b7c5e746d737d2 | 35,003,983,478,404 | 5d0d07ebce549d3aec05f1fd455f5532a14f862e | /commercetools/importer/commercetools-api-generated/src/main/java/com/commercetools/api/generated/models/order_edit/StagedOrderAddLineItemActionBuilder.java | d3a8051f5614004b7a33bd2b8042e88512b18091 | [] | no_license | commercetools/commercetools-java-sdks | https://github.com/commercetools/commercetools-java-sdks | ef630c320078debd15d248492ab6aedd5d279069 | baac9ab4f9591b57fbd49ed966a864b8227947a1 | refs/heads/master | 2020-07-20T04:10:29.614000 | 2020-07-14T15:01:37 | 2020-07-14T15:01:37 | 206,558,937 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.commercetools.api.generated.models.order_edit;
import com.commercetools.api.generated.models.cart.ExternalLineItemTotalPrice;
import com.commercetools.api.generated.models.cart.ExternalTaxRateDraft;
import com.commercetools.api.generated.models.cart.ItemShippingDetailsDraft;
import com.commercetools.api.generated.models.channel.ChannelResourceIdentifier;
import com.commercetools.api.generated.models.common.Money;
import com.commercetools.api.generated.models.order.StagedOrderUpdateAction;
import com.commercetools.api.generated.models.type.CustomFieldsDraft;
import com.commercetools.api.generated.models.order_edit.StagedOrderAddLineItemAction;
import javax.annotation.Nullable;
import java.util.List;
import java.util.Map;
import java.time.ZonedDateTime;
import io.vrap.rmf.base.client.utils.Generated;
@Generated(
value = "io.vrap.rmf.codegen.rendring.CoreCodeGenerator",
comments = "https://github.com/vrapio/rmf-codegen"
)
public final class StagedOrderAddLineItemActionBuilder {
@Nullable
private Integer quantity;
@Nullable
private com.commercetools.api.generated.models.cart.ExternalTaxRateDraft externalTaxRate;
@Nullable
private com.commercetools.api.generated.models.cart.ItemShippingDetailsDraft shippingDetails;
@Nullable
private String productId;
@Nullable
private com.commercetools.api.generated.models.cart.ExternalLineItemTotalPrice externalTotalPrice;
@Nullable
private com.commercetools.api.generated.models.type.CustomFieldsDraft custom;
@Nullable
private com.commercetools.api.generated.models.channel.ChannelResourceIdentifier supplyChannel;
@Nullable
private Long variantId;
@Nullable
private String sku;
@Nullable
private com.commercetools.api.generated.models.channel.ChannelResourceIdentifier distributionChannel;
@Nullable
private com.commercetools.api.generated.models.common.Money externalPrice;
public StagedOrderAddLineItemActionBuilder quantity(@Nullable final Integer quantity) {
this.quantity = quantity;
return this;
}
public StagedOrderAddLineItemActionBuilder externalTaxRate(@Nullable final com.commercetools.api.generated.models.cart.ExternalTaxRateDraft externalTaxRate) {
this.externalTaxRate = externalTaxRate;
return this;
}
public StagedOrderAddLineItemActionBuilder shippingDetails(@Nullable final com.commercetools.api.generated.models.cart.ItemShippingDetailsDraft shippingDetails) {
this.shippingDetails = shippingDetails;
return this;
}
public StagedOrderAddLineItemActionBuilder productId(@Nullable final String productId) {
this.productId = productId;
return this;
}
public StagedOrderAddLineItemActionBuilder externalTotalPrice(@Nullable final com.commercetools.api.generated.models.cart.ExternalLineItemTotalPrice externalTotalPrice) {
this.externalTotalPrice = externalTotalPrice;
return this;
}
public StagedOrderAddLineItemActionBuilder custom(@Nullable final com.commercetools.api.generated.models.type.CustomFieldsDraft custom) {
this.custom = custom;
return this;
}
public StagedOrderAddLineItemActionBuilder supplyChannel(@Nullable final com.commercetools.api.generated.models.channel.ChannelResourceIdentifier supplyChannel) {
this.supplyChannel = supplyChannel;
return this;
}
public StagedOrderAddLineItemActionBuilder variantId(@Nullable final Long variantId) {
this.variantId = variantId;
return this;
}
public StagedOrderAddLineItemActionBuilder sku(@Nullable final String sku) {
this.sku = sku;
return this;
}
public StagedOrderAddLineItemActionBuilder distributionChannel(@Nullable final com.commercetools.api.generated.models.channel.ChannelResourceIdentifier distributionChannel) {
this.distributionChannel = distributionChannel;
return this;
}
public StagedOrderAddLineItemActionBuilder externalPrice(@Nullable final com.commercetools.api.generated.models.common.Money externalPrice) {
this.externalPrice = externalPrice;
return this;
}
@Nullable
public Integer getQuantity(){
return this.quantity;
}
@Nullable
public com.commercetools.api.generated.models.cart.ExternalTaxRateDraft getExternalTaxRate(){
return this.externalTaxRate;
}
@Nullable
public com.commercetools.api.generated.models.cart.ItemShippingDetailsDraft getShippingDetails(){
return this.shippingDetails;
}
@Nullable
public String getProductId(){
return this.productId;
}
@Nullable
public com.commercetools.api.generated.models.cart.ExternalLineItemTotalPrice getExternalTotalPrice(){
return this.externalTotalPrice;
}
@Nullable
public com.commercetools.api.generated.models.type.CustomFieldsDraft getCustom(){
return this.custom;
}
@Nullable
public com.commercetools.api.generated.models.channel.ChannelResourceIdentifier getSupplyChannel(){
return this.supplyChannel;
}
@Nullable
public Long getVariantId(){
return this.variantId;
}
@Nullable
public String getSku(){
return this.sku;
}
@Nullable
public com.commercetools.api.generated.models.channel.ChannelResourceIdentifier getDistributionChannel(){
return this.distributionChannel;
}
@Nullable
public com.commercetools.api.generated.models.common.Money getExternalPrice(){
return this.externalPrice;
}
public StagedOrderAddLineItemAction build() {
return new StagedOrderAddLineItemActionImpl(quantity, externalTaxRate, shippingDetails, productId, externalTotalPrice, custom, supplyChannel, variantId, sku, distributionChannel, externalPrice);
}
public static StagedOrderAddLineItemActionBuilder of() {
return new StagedOrderAddLineItemActionBuilder();
}
public static StagedOrderAddLineItemActionBuilder of(final StagedOrderAddLineItemAction template) {
StagedOrderAddLineItemActionBuilder builder = new StagedOrderAddLineItemActionBuilder();
builder.quantity = template.getQuantity();
builder.externalTaxRate = template.getExternalTaxRate();
builder.shippingDetails = template.getShippingDetails();
builder.productId = template.getProductId();
builder.externalTotalPrice = template.getExternalTotalPrice();
builder.custom = template.getCustom();
builder.supplyChannel = template.getSupplyChannel();
builder.variantId = template.getVariantId();
builder.sku = template.getSku();
builder.distributionChannel = template.getDistributionChannel();
builder.externalPrice = template.getExternalPrice();
return builder;
}
} | UTF-8 | Java | 6,819 | java | StagedOrderAddLineItemActionBuilder.java | Java | [
{
"context": "odeGenerator\",\n comments = \"https://github.com/vrapio/rmf-codegen\"\n)\npublic final class StagedOrderAddL",
"end": 939,
"score": 0.9992720484733582,
"start": 933,
"tag": "USERNAME",
"value": "vrapio"
}
] | null | [] | package com.commercetools.api.generated.models.order_edit;
import com.commercetools.api.generated.models.cart.ExternalLineItemTotalPrice;
import com.commercetools.api.generated.models.cart.ExternalTaxRateDraft;
import com.commercetools.api.generated.models.cart.ItemShippingDetailsDraft;
import com.commercetools.api.generated.models.channel.ChannelResourceIdentifier;
import com.commercetools.api.generated.models.common.Money;
import com.commercetools.api.generated.models.order.StagedOrderUpdateAction;
import com.commercetools.api.generated.models.type.CustomFieldsDraft;
import com.commercetools.api.generated.models.order_edit.StagedOrderAddLineItemAction;
import javax.annotation.Nullable;
import java.util.List;
import java.util.Map;
import java.time.ZonedDateTime;
import io.vrap.rmf.base.client.utils.Generated;
@Generated(
value = "io.vrap.rmf.codegen.rendring.CoreCodeGenerator",
comments = "https://github.com/vrapio/rmf-codegen"
)
public final class StagedOrderAddLineItemActionBuilder {
@Nullable
private Integer quantity;
@Nullable
private com.commercetools.api.generated.models.cart.ExternalTaxRateDraft externalTaxRate;
@Nullable
private com.commercetools.api.generated.models.cart.ItemShippingDetailsDraft shippingDetails;
@Nullable
private String productId;
@Nullable
private com.commercetools.api.generated.models.cart.ExternalLineItemTotalPrice externalTotalPrice;
@Nullable
private com.commercetools.api.generated.models.type.CustomFieldsDraft custom;
@Nullable
private com.commercetools.api.generated.models.channel.ChannelResourceIdentifier supplyChannel;
@Nullable
private Long variantId;
@Nullable
private String sku;
@Nullable
private com.commercetools.api.generated.models.channel.ChannelResourceIdentifier distributionChannel;
@Nullable
private com.commercetools.api.generated.models.common.Money externalPrice;
public StagedOrderAddLineItemActionBuilder quantity(@Nullable final Integer quantity) {
this.quantity = quantity;
return this;
}
public StagedOrderAddLineItemActionBuilder externalTaxRate(@Nullable final com.commercetools.api.generated.models.cart.ExternalTaxRateDraft externalTaxRate) {
this.externalTaxRate = externalTaxRate;
return this;
}
public StagedOrderAddLineItemActionBuilder shippingDetails(@Nullable final com.commercetools.api.generated.models.cart.ItemShippingDetailsDraft shippingDetails) {
this.shippingDetails = shippingDetails;
return this;
}
public StagedOrderAddLineItemActionBuilder productId(@Nullable final String productId) {
this.productId = productId;
return this;
}
public StagedOrderAddLineItemActionBuilder externalTotalPrice(@Nullable final com.commercetools.api.generated.models.cart.ExternalLineItemTotalPrice externalTotalPrice) {
this.externalTotalPrice = externalTotalPrice;
return this;
}
public StagedOrderAddLineItemActionBuilder custom(@Nullable final com.commercetools.api.generated.models.type.CustomFieldsDraft custom) {
this.custom = custom;
return this;
}
public StagedOrderAddLineItemActionBuilder supplyChannel(@Nullable final com.commercetools.api.generated.models.channel.ChannelResourceIdentifier supplyChannel) {
this.supplyChannel = supplyChannel;
return this;
}
public StagedOrderAddLineItemActionBuilder variantId(@Nullable final Long variantId) {
this.variantId = variantId;
return this;
}
public StagedOrderAddLineItemActionBuilder sku(@Nullable final String sku) {
this.sku = sku;
return this;
}
public StagedOrderAddLineItemActionBuilder distributionChannel(@Nullable final com.commercetools.api.generated.models.channel.ChannelResourceIdentifier distributionChannel) {
this.distributionChannel = distributionChannel;
return this;
}
public StagedOrderAddLineItemActionBuilder externalPrice(@Nullable final com.commercetools.api.generated.models.common.Money externalPrice) {
this.externalPrice = externalPrice;
return this;
}
@Nullable
public Integer getQuantity(){
return this.quantity;
}
@Nullable
public com.commercetools.api.generated.models.cart.ExternalTaxRateDraft getExternalTaxRate(){
return this.externalTaxRate;
}
@Nullable
public com.commercetools.api.generated.models.cart.ItemShippingDetailsDraft getShippingDetails(){
return this.shippingDetails;
}
@Nullable
public String getProductId(){
return this.productId;
}
@Nullable
public com.commercetools.api.generated.models.cart.ExternalLineItemTotalPrice getExternalTotalPrice(){
return this.externalTotalPrice;
}
@Nullable
public com.commercetools.api.generated.models.type.CustomFieldsDraft getCustom(){
return this.custom;
}
@Nullable
public com.commercetools.api.generated.models.channel.ChannelResourceIdentifier getSupplyChannel(){
return this.supplyChannel;
}
@Nullable
public Long getVariantId(){
return this.variantId;
}
@Nullable
public String getSku(){
return this.sku;
}
@Nullable
public com.commercetools.api.generated.models.channel.ChannelResourceIdentifier getDistributionChannel(){
return this.distributionChannel;
}
@Nullable
public com.commercetools.api.generated.models.common.Money getExternalPrice(){
return this.externalPrice;
}
public StagedOrderAddLineItemAction build() {
return new StagedOrderAddLineItemActionImpl(quantity, externalTaxRate, shippingDetails, productId, externalTotalPrice, custom, supplyChannel, variantId, sku, distributionChannel, externalPrice);
}
public static StagedOrderAddLineItemActionBuilder of() {
return new StagedOrderAddLineItemActionBuilder();
}
public static StagedOrderAddLineItemActionBuilder of(final StagedOrderAddLineItemAction template) {
StagedOrderAddLineItemActionBuilder builder = new StagedOrderAddLineItemActionBuilder();
builder.quantity = template.getQuantity();
builder.externalTaxRate = template.getExternalTaxRate();
builder.shippingDetails = template.getShippingDetails();
builder.productId = template.getProductId();
builder.externalTotalPrice = template.getExternalTotalPrice();
builder.custom = template.getCustom();
builder.supplyChannel = template.getSupplyChannel();
builder.variantId = template.getVariantId();
builder.sku = template.getSku();
builder.distributionChannel = template.getDistributionChannel();
builder.externalPrice = template.getExternalPrice();
return builder;
}
} | 6,819 | 0.764922 | 0.764922 | 190 | 34.894737 | 40.784924 | 201 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.442105 | false | false | 11 |
d80822939801592355bb88d43dfec534b003614c | 34,213,709,494,801 | b45f73ba09b95c791c71d2b1659de39ef2072bbc | /src/main/java/by/epam/halavin/maintask/util/builder/user/DriverBuilder.java | 840266fd8681a16a977ab1a9b5bef711e47290b2 | [] | no_license | Epimedo/WebApplication | https://github.com/Epimedo/WebApplication | f0db939790a410a7ff4dc6b2460c256554ed7654 | d39b4db9be1cdce148e31389c5ab3350d604182c | refs/heads/master | 2020-04-25T10:23:26.135000 | 2019-03-24T12:05:47 | 2019-03-24T12:05:47 | 172,707,716 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package by.epam.halavin.maintask.util.builder.user;
import by.epam.halavin.maintask.bean.Car;
import by.epam.halavin.maintask.bean.user.Driver;
import by.epam.halavin.maintask.bean.user.User;
public class DriverBuilder implements UserBuilder {
private Driver driver;
{
driver = new Driver();
}
public DriverBuilder setId(int id) {
driver.setId(id);
return this;
}
public DriverBuilder setCar(Car car) {
driver.setCar(car);
return this;
}
public DriverBuilder setName(String name) {
driver.setName(name);
return this;
}
public DriverBuilder setSurname(String surname) {
driver.setSurname(surname);
return this;
}
public DriverBuilder setEmail(String email) {
driver.setEmail(email);
return this;
}
public DriverBuilder setTel(String tel) {
driver.setTel(tel);
return this;
}
public DriverBuilder setPassword(String password) {
driver.setPassword(password);
return this;
}
public DriverBuilder setStatus(String status) {
driver.setStatus(status);
return this;
}
public DriverBuilder setCarName(String carName) {
driver.setCarName(carName);
return this;
}
public DriverBuilder setCarNumber(String carNumber) {
driver.setCarNumber(carNumber);
return this;
}
@Override
public User getObject() {
return driver;
}
@Override
public void reset() {
driver = new Driver();
}
}
| UTF-8 | Java | 1,581 | java | DriverBuilder.java | Java | [] | null | [] | package by.epam.halavin.maintask.util.builder.user;
import by.epam.halavin.maintask.bean.Car;
import by.epam.halavin.maintask.bean.user.Driver;
import by.epam.halavin.maintask.bean.user.User;
public class DriverBuilder implements UserBuilder {
private Driver driver;
{
driver = new Driver();
}
public DriverBuilder setId(int id) {
driver.setId(id);
return this;
}
public DriverBuilder setCar(Car car) {
driver.setCar(car);
return this;
}
public DriverBuilder setName(String name) {
driver.setName(name);
return this;
}
public DriverBuilder setSurname(String surname) {
driver.setSurname(surname);
return this;
}
public DriverBuilder setEmail(String email) {
driver.setEmail(email);
return this;
}
public DriverBuilder setTel(String tel) {
driver.setTel(tel);
return this;
}
public DriverBuilder setPassword(String password) {
driver.setPassword(password);
return this;
}
public DriverBuilder setStatus(String status) {
driver.setStatus(status);
return this;
}
public DriverBuilder setCarName(String carName) {
driver.setCarName(carName);
return this;
}
public DriverBuilder setCarNumber(String carNumber) {
driver.setCarNumber(carNumber);
return this;
}
@Override
public User getObject() {
return driver;
}
@Override
public void reset() {
driver = new Driver();
}
}
| 1,581 | 0.628083 | 0.628083 | 73 | 20.657534 | 18.230803 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.383562 | false | false | 11 |
a0aab573950225d5a58c23cfa332e5870024c1db | 16,295,105,954,967 | de26b72b8a3f7b9c913438b072762448615dc68e | /funtip-tournaments/src/main/java/net/funtip/tournaments/bl/TeamNameBlImpl.java | 4d22aaac96d153a809c58525b1fd83c0f338e8ad | [] | no_license | perryp/funtip-tournaments | https://github.com/perryp/funtip-tournaments | b883c4e1c23e0fd90248c3df80978db817fe7d36 | 2cad8056c125822c365367d0baa4263595a13a61 | refs/heads/master | 2019-01-01T15:48:33.838000 | 2012-07-16T21:21:45 | 2012-07-16T21:21:45 | 33,376,317 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.funtip.tournaments.bl;
import java.util.List;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.inject.Named;
import net.funtip.tournaments.dao.CacheDao;
import net.funtip.tournaments.dao.TeamNameDao;
import net.funtip.tournaments.entity.Team;
import net.funtip.tournaments.entity.TeamName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Named
@ApplicationScoped
public class TeamNameBlImpl implements TeamNameBl {
@SuppressWarnings("unused")
private Logger log = LoggerFactory.getLogger(this.getClass());
@Inject private CacheDao cacheBl;
@Inject private TeamNameDao teamNameDao;
@Inject private TeamBl teamBl;
@Override
public TeamName getTeamName(Team team, String type) {
if (team == null || type == null) return null;
TeamName tn = cacheBl.getTeamName(team, type);
if (tn != null) return tn;
tn = teamNameDao.findByTeamIdType(team.getId(), type);
if (tn != null) {
cacheBl.putTeamName(tn);
}
return tn;
}
@Override
public void store(TeamName tn) {
teamNameDao.store(tn);
cacheBl.putTeamName(tn);
}
@Override
public TeamName getTeamName(Team team) {
return getTeamName(team, TeamNameBl.TYPE_STANDARD);
}
@Override
public List<TeamName> getAllStandardTeamNames() {
List<TeamName> l = cacheBl.getStandardTeamNames();
if (l == null) {
l = teamNameDao.findByType(TeamNameBl.TYPE_STANDARD);
cacheBl.putStandardTeamNames(l);
}
return l;
}
@Override
public void update(TeamName tn) {
Team team = teamBl.getById(tn.getTeamId());
TeamName dbTn = getTeamName(team, tn.getType());
if (dbTn == null || !dbTn.equals(tn)) {
if (dbTn != null) {
tn.setId(dbTn.getId());
}
store(tn);
}
}
}
| UTF-8 | Java | 1,737 | java | TeamNameBlImpl.java | Java | [] | null | [] | package net.funtip.tournaments.bl;
import java.util.List;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.inject.Named;
import net.funtip.tournaments.dao.CacheDao;
import net.funtip.tournaments.dao.TeamNameDao;
import net.funtip.tournaments.entity.Team;
import net.funtip.tournaments.entity.TeamName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Named
@ApplicationScoped
public class TeamNameBlImpl implements TeamNameBl {
@SuppressWarnings("unused")
private Logger log = LoggerFactory.getLogger(this.getClass());
@Inject private CacheDao cacheBl;
@Inject private TeamNameDao teamNameDao;
@Inject private TeamBl teamBl;
@Override
public TeamName getTeamName(Team team, String type) {
if (team == null || type == null) return null;
TeamName tn = cacheBl.getTeamName(team, type);
if (tn != null) return tn;
tn = teamNameDao.findByTeamIdType(team.getId(), type);
if (tn != null) {
cacheBl.putTeamName(tn);
}
return tn;
}
@Override
public void store(TeamName tn) {
teamNameDao.store(tn);
cacheBl.putTeamName(tn);
}
@Override
public TeamName getTeamName(Team team) {
return getTeamName(team, TeamNameBl.TYPE_STANDARD);
}
@Override
public List<TeamName> getAllStandardTeamNames() {
List<TeamName> l = cacheBl.getStandardTeamNames();
if (l == null) {
l = teamNameDao.findByType(TeamNameBl.TYPE_STANDARD);
cacheBl.putStandardTeamNames(l);
}
return l;
}
@Override
public void update(TeamName tn) {
Team team = teamBl.getById(tn.getTeamId());
TeamName dbTn = getTeamName(team, tn.getType());
if (dbTn == null || !dbTn.equals(tn)) {
if (dbTn != null) {
tn.setId(dbTn.getId());
}
store(tn);
}
}
}
| 1,737 | 0.725389 | 0.724237 | 73 | 22.794521 | 19.384331 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.671233 | false | false | 11 |
035873164a91a57a6c8b26dff928410804a49c8e | 27,530,740,394,993 | a92a39d3b7011789539cedb936de4f82a7033008 | /user/src/main/java/com/gracelogic/platform/user/service/UserService.java | c55f6f7e8cb2abab9dccb3601da35d457af56c51 | [
"Apache-2.0"
] | permissive | gracelogic/platform | https://github.com/gracelogic/platform | 7e839a54c45c70e2cc845ed165e1a8d3937b91d0 | caa1521ae192d02859878d16c5f15fb4997339d8 | refs/heads/master | 2023-03-11T03:30:36.937000 | 2023-01-19T14:34:49 | 2023-01-19T14:34:49 | 118,780,261 | 1 | 1 | Apache-2.0 | false | 2023-02-22T08:10:27 | 2018-01-24T14:59:51 | 2022-02-11T06:41:39 | 2023-02-22T08:10:26 | 2,685 | 0 | 0 | 11 | JavaScript | false | false | package com.gracelogic.platform.user.service;
import com.gracelogic.platform.db.dto.EntityListResponse;
import com.gracelogic.platform.db.exception.ObjectNotFoundException;
import com.gracelogic.platform.user.dto.*;
import com.gracelogic.platform.user.exception.*;
import com.gracelogic.platform.user.model.*;
import com.gracelogic.platform.user.security.SessionBasedAuthentication;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;
public interface UserService {
void changeUserPassword(UUID userId, String newPassword);
UserSession updateSessionInfo(HttpSession session, SessionBasedAuthentication sessionBasedAuthentication, String userAgent, boolean isDestroying);
void changePasswordViaVerificationCode(UUID identifierTypeId, String identifierValue, String verificationCode, String newPassword) throws ObjectNotFoundException, InvalidPassphraseException;
UserSetting getUserSetting(UUID userId, String key);
void updateUserSetting(UUID userId, String key, String value);
void deleteUser(User user);
void addRoleToUser(User user, Collection<UUID> roleIds);
User saveUser(UserDTO user, boolean mergeRoles, boolean mergeIdentifiers, AuthorizedUser executor) throws ObjectNotFoundException, InvalidIdentifierException, InvalidPassphraseException;
List<UserRole> getUserRoles(UUID userId);
void mergeUserRoles(UUID userId, Collection<UUID> activeRoles);
void mergeUserIdentifiers(User user, boolean isNewUser, Collection<IdentifierDTO> identifierDTOList, boolean throwExceptionIfAlreadyAttached);
EntityListResponse<UserDTO> getUsersPaged(String identifierValue, Boolean approved, Boolean blocked, Map<String, String> fields, boolean fetchRoles, boolean calculate, Integer count, Integer page, Integer start, String sortField, String sortDir);
UserDTO getUser(UUID userId, boolean fetchRoles) throws ObjectNotFoundException;
EntityListResponse<RoleDTO> getRolesPaged(String code, String name, boolean fetchGrants, boolean calculate, Integer count, Integer page, Integer start, String sortField, String sortDir);
Role saveRole(RoleDTO dto) throws ObjectNotFoundException;
RoleDTO getRole(UUID roleId, boolean fetchGrants) throws ObjectNotFoundException;
void deleteRole(UUID roleId);
EntityListResponse<UserSessionDTO> getSessionsPaged(UUID userId, String authIp, Date startDate, Date endDate, boolean enrich, boolean calculate, Integer count, Integer page, Integer start, String sortField, String sortDir);
String translateUserSortFieldToNative(String sortFieldInJPAFormat);
void changeLocale(AuthorizedUser authorizedUser, String locale) throws IllegalArgumentException;
boolean isIdentifierValid(UUID identifierTypeId, String identifierValue, boolean checkAvailable);
Date getUserPasswordExpirationDate(UUID userId) throws ObjectNotFoundException;
UUID resolveIdentifierTypeId(String identifierValue) throws InvalidIdentifierException;
boolean isPassphraseValueValid(Passphrase passphrase, String value);
Passphrase getActualPassphrase(UUID userId, UUID passphraseTypeId, UUID referenceObjectId, boolean archiveExpiredPassphrase);
Identifier findIdentifier(UUID identifierTypeId, String value, boolean enrich);
void archiveActualPassphrases(UUID userId, UUID passphraseTypeId, UUID referenceObjectId);
Passphrase updatePassphrase(User user, String value, UUID passphraseTypeId, UUID referenceObjectId, boolean archiveOtherPassphrases) throws InvalidPassphraseException;
Identifier processSignIn(UUID identifierTypeId, String identifierValue, String password, String remoteAddress, boolean trust) throws UserBlockedException, TooManyAttemptsException, NotAllowedIPException, UserNotApprovedException, InvalidIdentifierException;
void sendIdentifierVerificationCode(UUID identifierId, Map<String, String> templateParams);
Passphrase getActualVerificationCode(User user, UUID referenceObjectId, UUID passphraseTypeId, boolean createNewIfNotExist);
User processSignUp(SignUpDTO signUpDTO) throws InvalidIdentifierException, InvalidPassphraseException;
void sendVerificationCodeForPasswordChanging(UUID identifierTypeId, String identifierValue, Map<String, String> templateParams) throws ObjectNotFoundException, TooFastOperationException;
boolean processIdentifierVerificationViaVerificationCode(UUID identifierTypeId, String identifierValue, String verificationCode);
void verifyIdentifierViaVerificationCode(UUID identifierTypeId, String identifierValue, String verificationCode) throws ObjectNotFoundException, InvalidPassphraseException;
void updateTokenLastRequestDate(Token newToken);
Token establishToken(AuthRequestDTO authRequestDTO, String remoteAddress, boolean trust) throws UserBlockedException, TooManyAttemptsException, NotAllowedIPException, UserNotApprovedException, InvalidIdentifierException;
void deactivateToken(TokenDTO tokenDTO);
void blockExpiredUsers();
void archivePassphrase(Passphrase passphrase);
EntityListResponse<PassphraseTypeDTO> getPassphraseTypePaged(String name, boolean enrich, boolean calculate, Integer count, Integer page, Integer start, String sortField, String sortDir);
PassphraseTypeDTO getPassphraseType(UUID id) throws ObjectNotFoundException;
PassphraseType savePassphraseType(PassphraseTypeDTO passphraseTypeDTO) throws ObjectNotFoundException;
void deletePassphraseType(UUID id);
}
| UTF-8 | Java | 5,507 | java | UserService.java | Java | [] | null | [] | package com.gracelogic.platform.user.service;
import com.gracelogic.platform.db.dto.EntityListResponse;
import com.gracelogic.platform.db.exception.ObjectNotFoundException;
import com.gracelogic.platform.user.dto.*;
import com.gracelogic.platform.user.exception.*;
import com.gracelogic.platform.user.model.*;
import com.gracelogic.platform.user.security.SessionBasedAuthentication;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;
public interface UserService {
void changeUserPassword(UUID userId, String newPassword);
UserSession updateSessionInfo(HttpSession session, SessionBasedAuthentication sessionBasedAuthentication, String userAgent, boolean isDestroying);
void changePasswordViaVerificationCode(UUID identifierTypeId, String identifierValue, String verificationCode, String newPassword) throws ObjectNotFoundException, InvalidPassphraseException;
UserSetting getUserSetting(UUID userId, String key);
void updateUserSetting(UUID userId, String key, String value);
void deleteUser(User user);
void addRoleToUser(User user, Collection<UUID> roleIds);
User saveUser(UserDTO user, boolean mergeRoles, boolean mergeIdentifiers, AuthorizedUser executor) throws ObjectNotFoundException, InvalidIdentifierException, InvalidPassphraseException;
List<UserRole> getUserRoles(UUID userId);
void mergeUserRoles(UUID userId, Collection<UUID> activeRoles);
void mergeUserIdentifiers(User user, boolean isNewUser, Collection<IdentifierDTO> identifierDTOList, boolean throwExceptionIfAlreadyAttached);
EntityListResponse<UserDTO> getUsersPaged(String identifierValue, Boolean approved, Boolean blocked, Map<String, String> fields, boolean fetchRoles, boolean calculate, Integer count, Integer page, Integer start, String sortField, String sortDir);
UserDTO getUser(UUID userId, boolean fetchRoles) throws ObjectNotFoundException;
EntityListResponse<RoleDTO> getRolesPaged(String code, String name, boolean fetchGrants, boolean calculate, Integer count, Integer page, Integer start, String sortField, String sortDir);
Role saveRole(RoleDTO dto) throws ObjectNotFoundException;
RoleDTO getRole(UUID roleId, boolean fetchGrants) throws ObjectNotFoundException;
void deleteRole(UUID roleId);
EntityListResponse<UserSessionDTO> getSessionsPaged(UUID userId, String authIp, Date startDate, Date endDate, boolean enrich, boolean calculate, Integer count, Integer page, Integer start, String sortField, String sortDir);
String translateUserSortFieldToNative(String sortFieldInJPAFormat);
void changeLocale(AuthorizedUser authorizedUser, String locale) throws IllegalArgumentException;
boolean isIdentifierValid(UUID identifierTypeId, String identifierValue, boolean checkAvailable);
Date getUserPasswordExpirationDate(UUID userId) throws ObjectNotFoundException;
UUID resolveIdentifierTypeId(String identifierValue) throws InvalidIdentifierException;
boolean isPassphraseValueValid(Passphrase passphrase, String value);
Passphrase getActualPassphrase(UUID userId, UUID passphraseTypeId, UUID referenceObjectId, boolean archiveExpiredPassphrase);
Identifier findIdentifier(UUID identifierTypeId, String value, boolean enrich);
void archiveActualPassphrases(UUID userId, UUID passphraseTypeId, UUID referenceObjectId);
Passphrase updatePassphrase(User user, String value, UUID passphraseTypeId, UUID referenceObjectId, boolean archiveOtherPassphrases) throws InvalidPassphraseException;
Identifier processSignIn(UUID identifierTypeId, String identifierValue, String password, String remoteAddress, boolean trust) throws UserBlockedException, TooManyAttemptsException, NotAllowedIPException, UserNotApprovedException, InvalidIdentifierException;
void sendIdentifierVerificationCode(UUID identifierId, Map<String, String> templateParams);
Passphrase getActualVerificationCode(User user, UUID referenceObjectId, UUID passphraseTypeId, boolean createNewIfNotExist);
User processSignUp(SignUpDTO signUpDTO) throws InvalidIdentifierException, InvalidPassphraseException;
void sendVerificationCodeForPasswordChanging(UUID identifierTypeId, String identifierValue, Map<String, String> templateParams) throws ObjectNotFoundException, TooFastOperationException;
boolean processIdentifierVerificationViaVerificationCode(UUID identifierTypeId, String identifierValue, String verificationCode);
void verifyIdentifierViaVerificationCode(UUID identifierTypeId, String identifierValue, String verificationCode) throws ObjectNotFoundException, InvalidPassphraseException;
void updateTokenLastRequestDate(Token newToken);
Token establishToken(AuthRequestDTO authRequestDTO, String remoteAddress, boolean trust) throws UserBlockedException, TooManyAttemptsException, NotAllowedIPException, UserNotApprovedException, InvalidIdentifierException;
void deactivateToken(TokenDTO tokenDTO);
void blockExpiredUsers();
void archivePassphrase(Passphrase passphrase);
EntityListResponse<PassphraseTypeDTO> getPassphraseTypePaged(String name, boolean enrich, boolean calculate, Integer count, Integer page, Integer start, String sortField, String sortDir);
PassphraseTypeDTO getPassphraseType(UUID id) throws ObjectNotFoundException;
PassphraseType savePassphraseType(PassphraseTypeDTO passphraseTypeDTO) throws ObjectNotFoundException;
void deletePassphraseType(UUID id);
}
| 5,507 | 0.834029 | 0.834029 | 102 | 52.990196 | 67.090591 | 261 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.539216 | false | false | 11 |
bfd2ce0549615dfe611d0e61c5daa6c3cba23c19 | 19,507,741,509,790 | 56aa536aab60312295bf3d99121f4bbd88f56563 | /app/src/main/java/com/example/vsvll/volley/pojoClass.java | 4315b72ecffef763b06340a6fdca6ebcc79704f7 | [] | no_license | vsvllbh/Volley | https://github.com/vsvllbh/Volley | 9a93aa40b8f3e52770c8ebdcde4917b8c15e70f6 | 9b14512dacc4de059d4a47a34d3beeeee5aa2f8e | refs/heads/master | 2020-04-09T23:05:45.801000 | 2018-12-06T08:54:49 | 2018-12-06T08:54:49 | 160,646,584 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.vsvll.volley;
public class pojoClass {
private String Name;
private String Address1;
private String Zip;
private String City;
private String Phone;
private String Lat;
private String Lon;
private String Link;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getAddress1() {
return Address1;
}
public void setAddress1(String address1) {
Address1 = address1;
}
public String getZip() {
return Zip;
}
public void setZip(String zip) {
Zip = zip;
}
public String getCity() {
return City;
}
public void setCity(String city) {
City = city;
}
public String getPhone() {
return Phone;
}
public void setPhone(String phone) {
Phone = phone;
}
public String getLat() {
return Lat;
}
public void setLat(String lat) {
Lat = lat;
}
public String getLon() {
return Lon;
}
public void setLon(String lon) {
Lon = lon;
}
public String getLink() {
return Link;
}
public void setLink(String link) {
Link = link;
}
}
| UTF-8 | Java | 1,326 | java | pojoClass.java | Java | [] | null | [] | package com.example.vsvll.volley;
public class pojoClass {
private String Name;
private String Address1;
private String Zip;
private String City;
private String Phone;
private String Lat;
private String Lon;
private String Link;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getAddress1() {
return Address1;
}
public void setAddress1(String address1) {
Address1 = address1;
}
public String getZip() {
return Zip;
}
public void setZip(String zip) {
Zip = zip;
}
public String getCity() {
return City;
}
public void setCity(String city) {
City = city;
}
public String getPhone() {
return Phone;
}
public void setPhone(String phone) {
Phone = phone;
}
public String getLat() {
return Lat;
}
public void setLat(String lat) {
Lat = lat;
}
public String getLon() {
return Lon;
}
public void setLon(String lon) {
Lon = lon;
}
public String getLink() {
return Link;
}
public void setLink(String link) {
Link = link;
}
}
| 1,326 | 0.535445 | 0.530166 | 78 | 16 | 13.857331 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.320513 | false | false | 11 |
23d37e220ae6a58c1ff1f85b6d6b8eef19ba5f06 | 22,883,585,791,782 | 638b55b55ddac03c8d65499f6d19862b56964a0a | /Ch 04. Trees and Graphs/Q4_11_Random_Node/BSTNode.java | 014fade9d91689cfa0160ce057e4f0e0d6cf12f5 | [] | no_license | buptxz/crackTheCodeInterview | https://github.com/buptxz/crackTheCodeInterview | 7129dfdedb4a8c0ca09c116c78d847b04674f718 | 743d54df24a8c53001d1f975a9a35dff7734408d | refs/heads/master | 2020-02-26T15:20:30.129000 | 2017-02-07T22:48:24 | 2017-02-07T22:49:22 | 70,214,636 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Created by xiong on 11/7/2016.
*/
package Q4_11_Random_Node;
import java.util.Random;
public class BSTNode {
public int data;
public BSTNode left;
public BSTNode right;
public int size;
public BSTNode(int data) {
this.data = data;
this.size = 1;
}
public void insert(int val) {
if (val <= this.data) {
if (this.left == null) {
this.left = new BSTNode(val);
} else {
this.left.insert(val);
}
} else {
if (this.right == null) {
this.right = new BSTNode(val);
} else {
this.right.insert(val);
}
}
this.size++;
}
public BSTNode find(int val) {
if (val == this.data) {
return this;
} else if (val < this.data) {
if (this.left == null) return null;
return this.left.find(val);
} else {
if (this.right == null) return null;
return this.right.find(val);
}
}
public int size() {
return this.size;
}
public BSTNode getRandomNode() {
Random rnd = new Random();
int randomNum = rnd.nextInt(this.size);
if (randomNum == 0) {
return this;
} else if (this.left != null && randomNum > 0 && randomNum <= this.left.size) {
return this.left.getRandomNode();
} else if (this.right != null) {
return this.right.getRandomNode();
} else {
return null;
}
}
}
| UTF-8 | Java | 1,598 | java | BSTNode.java | Java | [
{
"context": "/**\n * Created by xiong on 11/7/2016.\n */\npackage Q4_11_Random_Node;\n\nimp",
"end": 23,
"score": 0.9992814064025879,
"start": 18,
"tag": "USERNAME",
"value": "xiong"
}
] | null | [] | /**
* Created by xiong on 11/7/2016.
*/
package Q4_11_Random_Node;
import java.util.Random;
public class BSTNode {
public int data;
public BSTNode left;
public BSTNode right;
public int size;
public BSTNode(int data) {
this.data = data;
this.size = 1;
}
public void insert(int val) {
if (val <= this.data) {
if (this.left == null) {
this.left = new BSTNode(val);
} else {
this.left.insert(val);
}
} else {
if (this.right == null) {
this.right = new BSTNode(val);
} else {
this.right.insert(val);
}
}
this.size++;
}
public BSTNode find(int val) {
if (val == this.data) {
return this;
} else if (val < this.data) {
if (this.left == null) return null;
return this.left.find(val);
} else {
if (this.right == null) return null;
return this.right.find(val);
}
}
public int size() {
return this.size;
}
public BSTNode getRandomNode() {
Random rnd = new Random();
int randomNum = rnd.nextInt(this.size);
if (randomNum == 0) {
return this;
} else if (this.left != null && randomNum > 0 && randomNum <= this.left.size) {
return this.left.getRandomNode();
} else if (this.right != null) {
return this.right.getRandomNode();
} else {
return null;
}
}
}
| 1,598 | 0.478723 | 0.470588 | 65 | 23.584616 | 16.651997 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.384615 | false | false | 11 |
3db812a541aae5092bf37bbb077b6cd85d46349f | 11,948,599,041,859 | 96d1336c0086a2acc53ed41eca5604d66962d13a | /src/com/interview/codechef/ccdsap_2/leetcode/linkedlist/easy/PalindromeLinkedList.java | 963c8814a0394a8ff213561f1a873a944964b7cd | [
"Apache-2.0"
] | permissive | prdp89/interview | https://github.com/prdp89/interview | 990e052d6bba5d2555a7b549d5bb5a12a92121ef | 04424ec1f13b0d1555382090d35c394b99a3a24b | refs/heads/master | 2022-12-27T16:44:41.690000 | 2020-09-30T13:21:44 | 2020-09-30T13:21:44 | 109,804,931 | 1 | 1 | null | true | 2017-11-07T08:05:26 | 2017-11-07T08:05:25 | 2017-11-07T06:18:28 | 2017-11-04T12:29:55 | 1,190 | 0 | 0 | 0 | null | false | null | package com.interview.codechef.ccdsap_2.leetcode.linkedlist.easy;
import com.interview.codechef.ccdsap_2.leetcode.linkedlist.medium.PartitionLinkedList;
public class PalindromeLinkedList {
//https://leetcode.com/problems/palindrome-linked-list/
public static void main( String[] args ) {
PartitionLinkedList.ListNode head = null;
PalindromeLinkedList ll = new PalindromeLinkedList();
head = ll.addNode(1, head);
head = ll.addNode(2, head);
head = ll.addNode(2, head);
head = ll.addNode(3, head);
//System.out.println(ll.isPalindrome(head));
System.out.println(ll.isPalindromeOptimal(head));
}
//passed 22/26 test cases
public boolean isPalindrome( PartitionLinkedList.ListNode head ) {
if (head == null)
return true;
int mult = head.val;
head = head.next;
while (head != null) {
mult = mult * 10 + head.val;
head = head.next;
}
int num = mult, reversed = 0;
while (num != 0) {
int digit = num % 10;
reversed = reversed * 10 + digit;
num /= 10;
}
return reversed == mult;
}
//ref : https://leetcode.com/problems/palindrome-linked-list/discuss/64501/Java-easy-to-understand
private boolean isPalindromeOptimal( PartitionLinkedList.ListNode head ) {
PartitionLinkedList.ListNode fast = head, slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
if (fast != null) { // odd nodes: let right half smaller
slow = slow.next;
}
//reverse the slow part
slow = reverse(slow);
//start the head from start
fast = head;
//if any value doesn't match return false.
while (fast != null && slow != null) {
if (fast.val != slow.val) {
return false;
}
fast = fast.next;
slow = slow.next;
}
return true;
}
public PartitionLinkedList.ListNode reverse( PartitionLinkedList.ListNode head ) {
PartitionLinkedList.ListNode prev = null;
while (head != null) {
PartitionLinkedList.ListNode next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}
public PartitionLinkedList.ListNode addNode( int data, PartitionLinkedList.ListNode head, Object... obj ) {
PartitionLinkedList.ListNode temp = head;
PartitionLinkedList.ListNode n;
if (obj.length > 0) {
n = PartitionLinkedList.ListNode.newNode(data, obj[0]);
} else {
n = PartitionLinkedList.ListNode.newNode(data);
}
if (head == null) {
return n;
}
while (head.next != null) {
head = head.next;
}
head.next = n;
return temp;
}
}
| UTF-8 | Java | 3,025 | java | PalindromeLinkedList.java | Java | [] | null | [] | package com.interview.codechef.ccdsap_2.leetcode.linkedlist.easy;
import com.interview.codechef.ccdsap_2.leetcode.linkedlist.medium.PartitionLinkedList;
public class PalindromeLinkedList {
//https://leetcode.com/problems/palindrome-linked-list/
public static void main( String[] args ) {
PartitionLinkedList.ListNode head = null;
PalindromeLinkedList ll = new PalindromeLinkedList();
head = ll.addNode(1, head);
head = ll.addNode(2, head);
head = ll.addNode(2, head);
head = ll.addNode(3, head);
//System.out.println(ll.isPalindrome(head));
System.out.println(ll.isPalindromeOptimal(head));
}
//passed 22/26 test cases
public boolean isPalindrome( PartitionLinkedList.ListNode head ) {
if (head == null)
return true;
int mult = head.val;
head = head.next;
while (head != null) {
mult = mult * 10 + head.val;
head = head.next;
}
int num = mult, reversed = 0;
while (num != 0) {
int digit = num % 10;
reversed = reversed * 10 + digit;
num /= 10;
}
return reversed == mult;
}
//ref : https://leetcode.com/problems/palindrome-linked-list/discuss/64501/Java-easy-to-understand
private boolean isPalindromeOptimal( PartitionLinkedList.ListNode head ) {
PartitionLinkedList.ListNode fast = head, slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
if (fast != null) { // odd nodes: let right half smaller
slow = slow.next;
}
//reverse the slow part
slow = reverse(slow);
//start the head from start
fast = head;
//if any value doesn't match return false.
while (fast != null && slow != null) {
if (fast.val != slow.val) {
return false;
}
fast = fast.next;
slow = slow.next;
}
return true;
}
public PartitionLinkedList.ListNode reverse( PartitionLinkedList.ListNode head ) {
PartitionLinkedList.ListNode prev = null;
while (head != null) {
PartitionLinkedList.ListNode next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}
public PartitionLinkedList.ListNode addNode( int data, PartitionLinkedList.ListNode head, Object... obj ) {
PartitionLinkedList.ListNode temp = head;
PartitionLinkedList.ListNode n;
if (obj.length > 0) {
n = PartitionLinkedList.ListNode.newNode(data, obj[0]);
} else {
n = PartitionLinkedList.ListNode.newNode(data);
}
if (head == null) {
return n;
}
while (head.next != null) {
head = head.next;
}
head.next = n;
return temp;
}
}
| 3,025 | 0.557686 | 0.54876 | 110 | 26.5 | 24.456177 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.481818 | false | false | 11 |
655d974f7510fa20254c8b33398d46d1d9c1f789 | 592,705,528,192 | 81a4bced74e36a0625330a4fe3d250749a0830b3 | /src/io/github/bunnyking123/unojava/console/UnoConsoleCard.java | 19a8cfcefb074b691066f9f6ead507cf656f574b | [] | no_license | Dolphcode/UNO_Java | https://github.com/Dolphcode/UNO_Java | 8c7dc754720a18ebf345ce960b0616ffbc90c824 | 62c8b81351a785599fce9e05895a265146a59e9c | refs/heads/master | 2022-11-14T15:31:31.756000 | 2020-07-04T14:30:40 | 2020-07-04T14:30:40 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package io.github.bunnyking123.unojava.console;
import io.github.bunnyking123.unojava.constants.*;
public class UnoConsoleCard {
private UnoColorConstants color; // Represents color of the card
private UnoNumberConstants number; // Represents number/type of card
/**
* Uno Console Card class is used to represent an Uno Card
*
* @param color - Represents the color of the card, must be an UnoColorConstant
* @param number - Represents the number of the card, must be an UnoNumberConstant
*/
public UnoConsoleCard (UnoColorConstants color, UnoNumberConstants number) {
this.color = color;
this.number = number;
}
// Encapsulation stuff
/**
* Returns the Uno Color Constant of the card
*
* @return UnoColorConstant
*/
public UnoColorConstants getColor() { return color; }
public void setColor(UnoColorConstants color) {
this.color = color;
}
/**
* Returns the Uno Number Constant of the card
*
* @return UnoNumberConstant
*/
public UnoNumberConstants getNumber() { return number; }
@Override
public String toString() {
String cardColor = "DEFAULT";
String cardNum = "DEFAULT";
/*
if (color == UnoColorConstants.RED) {
cardColor = "Red";
} else if (color == UnoColorConstants.BLUE) {
cardColor = "Blue";
} else if (color == UnoColorConstants.GREEN) {
cardColor = "Green";
} else if (color == UnoColorConstants.YELLOW) {
cardColor = "Yellow";
} else {
cardColor = "Uncolored";
}
*/
return color + " " + number;
}
}
| UTF-8 | Java | 1,516 | java | UnoConsoleCard.java | Java | [
{
"context": "package io.github.bunnyking123.unojava.console;\n\nimport io.github.bunnyking123.u",
"end": 30,
"score": 0.9996139407157898,
"start": 18,
"tag": "USERNAME",
"value": "bunnyking123"
},
{
"context": "b.bunnyking123.unojava.console;\n\nimport io.github.bunnyking123.unojava.constants.*;\n\npublic class UnoConsoleCard",
"end": 78,
"score": 0.9996177554130554,
"start": 66,
"tag": "USERNAME",
"value": "bunnyking123"
}
] | null | [] | package io.github.bunnyking123.unojava.console;
import io.github.bunnyking123.unojava.constants.*;
public class UnoConsoleCard {
private UnoColorConstants color; // Represents color of the card
private UnoNumberConstants number; // Represents number/type of card
/**
* Uno Console Card class is used to represent an Uno Card
*
* @param color - Represents the color of the card, must be an UnoColorConstant
* @param number - Represents the number of the card, must be an UnoNumberConstant
*/
public UnoConsoleCard (UnoColorConstants color, UnoNumberConstants number) {
this.color = color;
this.number = number;
}
// Encapsulation stuff
/**
* Returns the Uno Color Constant of the card
*
* @return UnoColorConstant
*/
public UnoColorConstants getColor() { return color; }
public void setColor(UnoColorConstants color) {
this.color = color;
}
/**
* Returns the Uno Number Constant of the card
*
* @return UnoNumberConstant
*/
public UnoNumberConstants getNumber() { return number; }
@Override
public String toString() {
String cardColor = "DEFAULT";
String cardNum = "DEFAULT";
/*
if (color == UnoColorConstants.RED) {
cardColor = "Red";
} else if (color == UnoColorConstants.BLUE) {
cardColor = "Blue";
} else if (color == UnoColorConstants.GREEN) {
cardColor = "Green";
} else if (color == UnoColorConstants.YELLOW) {
cardColor = "Yellow";
} else {
cardColor = "Uncolored";
}
*/
return color + " " + number;
}
}
| 1,516 | 0.691293 | 0.687335 | 65 | 22.323076 | 23.604502 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.507692 | false | false | 11 |
3f0b7294683e58c2a49ae2d9e87924cfdf8e3fb5 | 1,571,958,078,342 | 33e812239e37a8c7afd4812d6f9978c0e6691f0a | /src/test/java/uk/gov/hmcts/reform/juddata/camel/binder/JudicialOfficeAppointmentTest.java | 42150dbf6d123bd908cb1c67b280b56f20858cbe | [
"MIT"
] | permissive | SouravB01/rd-judicial-data-load | https://github.com/SouravB01/rd-judicial-data-load | 045bd4bfca47ed277478d8cc4fba6a9e58fc68f8 | 6aefe900fa4d6b44bd4d1ea4e77e18587e9d507f | refs/heads/master | 2022-11-18T23:07:53.856000 | 2020-06-19T12:06:59 | 2020-06-19T12:06:59 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package uk.gov.hmcts.reform.juddata.camel.binder;
import static org.junit.Assert.assertEquals;
import static uk.gov.hmcts.reform.juddata.camel.helper.JrdTestSupport.createJudicialOfficeAppointmentMockMock;
import static uk.gov.hmcts.reform.juddata.camel.helper.JrdTestSupport.getDateTimeWithFormat;
import static uk.gov.hmcts.reform.juddata.camel.helper.JrdTestSupport.getDateWithFormat;
import static uk.gov.hmcts.reform.juddata.camel.util.MappingConstants.DATE_FORMAT;
import java.time.LocalDateTime;
import java.util.Date;
import org.junit.Test;
public class JudicialOfficeAppointmentTest {
@Test
public void test_objects_JudicialOfficeAppointment_correctly() {
Date currentDate = new Date();
LocalDateTime dateTime = LocalDateTime.now();
JudicialOfficeAppointment judicialOfficeAppointment = createJudicialOfficeAppointmentMockMock(currentDate,
dateTime);
assertEquals("elinksid_1", judicialOfficeAppointment.getElinksId());
assertEquals("roleId_1", judicialOfficeAppointment.getRoleId());
assertEquals("contractTypeId_1", judicialOfficeAppointment.getContractType());
assertEquals("baseLocationId_1", judicialOfficeAppointment.getBaseLocationId());
assertEquals("regionId_1", judicialOfficeAppointment.getRegionId());
assertEquals(true, judicialOfficeAppointment.getIsPrincipalAppointment());
assertEquals(getDateWithFormat(currentDate, DATE_FORMAT), judicialOfficeAppointment.getStartDate());
assertEquals(getDateWithFormat(currentDate, DATE_FORMAT), judicialOfficeAppointment.getEndDate());
assertEquals(true, judicialOfficeAppointment.isActiveFlag());
assertEquals(getDateTimeWithFormat(dateTime), judicialOfficeAppointment.getExtractedDate());
}
}
| UTF-8 | Java | 1,794 | java | JudicialOfficeAppointmentTest.java | Java | [] | null | [] | package uk.gov.hmcts.reform.juddata.camel.binder;
import static org.junit.Assert.assertEquals;
import static uk.gov.hmcts.reform.juddata.camel.helper.JrdTestSupport.createJudicialOfficeAppointmentMockMock;
import static uk.gov.hmcts.reform.juddata.camel.helper.JrdTestSupport.getDateTimeWithFormat;
import static uk.gov.hmcts.reform.juddata.camel.helper.JrdTestSupport.getDateWithFormat;
import static uk.gov.hmcts.reform.juddata.camel.util.MappingConstants.DATE_FORMAT;
import java.time.LocalDateTime;
import java.util.Date;
import org.junit.Test;
public class JudicialOfficeAppointmentTest {
@Test
public void test_objects_JudicialOfficeAppointment_correctly() {
Date currentDate = new Date();
LocalDateTime dateTime = LocalDateTime.now();
JudicialOfficeAppointment judicialOfficeAppointment = createJudicialOfficeAppointmentMockMock(currentDate,
dateTime);
assertEquals("elinksid_1", judicialOfficeAppointment.getElinksId());
assertEquals("roleId_1", judicialOfficeAppointment.getRoleId());
assertEquals("contractTypeId_1", judicialOfficeAppointment.getContractType());
assertEquals("baseLocationId_1", judicialOfficeAppointment.getBaseLocationId());
assertEquals("regionId_1", judicialOfficeAppointment.getRegionId());
assertEquals(true, judicialOfficeAppointment.getIsPrincipalAppointment());
assertEquals(getDateWithFormat(currentDate, DATE_FORMAT), judicialOfficeAppointment.getStartDate());
assertEquals(getDateWithFormat(currentDate, DATE_FORMAT), judicialOfficeAppointment.getEndDate());
assertEquals(true, judicialOfficeAppointment.isActiveFlag());
assertEquals(getDateTimeWithFormat(dateTime), judicialOfficeAppointment.getExtractedDate());
}
}
| 1,794 | 0.786511 | 0.783724 | 33 | 53.363636 | 38.209007 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.060606 | false | false | 11 |
4787e4b4bee38c848c2918eb7c691fa763d24fe5 | 35,175,782,172,579 | 429027cf315de691ae85db919a906b68f25d4ffb | /src/main/java/com/chaos/eurekaproducer/domain/User.java | c641d14cf3bdc59b8ab8ff9100bf38fa4602ea2a | [] | no_license | chaos3583/eureka-producer | https://github.com/chaos3583/eureka-producer | 3e665c1b3d9a75f97281269adadc41d815c611f1 | 471eb234d530d59e894250ad926f4acb4827d8b5 | refs/heads/master | 2023-04-22T08:54:39.286000 | 2021-05-18T09:56:26 | 2021-05-18T09:56:26 | 299,003,182 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.chaos.eurekaproducer.domain;
import java.io.Serializable;
/**
* @author liaopeng
* @title: User
* @projectName eureka-producer
* @description: TODO
* @date 2021/5/11上午10:31
*/
public class User{
private Long id;
private String name;
private Integer age;
private Address address;
public User(){
}
public User(String name, Address address) {
this.name = name;
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
| UTF-8 | Java | 983 | java | User.java | Java | [
{
"context": "ain;\n\nimport java.io.Serializable;\n\n/**\n * @author liaopeng\n * @title: User\n * @projectName eureka-producer\n ",
"end": 95,
"score": 0.996766984462738,
"start": 87,
"tag": "USERNAME",
"value": "liaopeng"
}
] | null | [] | package com.chaos.eurekaproducer.domain;
import java.io.Serializable;
/**
* @author liaopeng
* @title: User
* @projectName eureka-producer
* @description: TODO
* @date 2021/5/11上午10:31
*/
public class User{
private Long id;
private String name;
private Integer age;
private Address address;
public User(){
}
public User(String name, Address address) {
this.name = name;
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
| 983 | 0.580184 | 0.568948 | 60 | 15.316667 | 13.782225 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.283333 | false | false | 11 |
a2674d1548684e32394389d6e71fec48c1b28915 | 16,114,717,298,219 | 2a43338330720b41aa6e360abd7605a68e7ea4ec | /src/main/java/com/sofka/implementacionDDD/Tienda/Usuario/entity/Cuenta.java | fb65a9bf8c21120ae27e99d71cb0c72a6065df72 | [] | no_license | Danvar03/implementacionDDD | https://github.com/Danvar03/implementacionDDD | c2969e0c31b00132cf1199c391a9466782a6c986 | f4370e05e1ff3de40e4867294f1b3d19f2cc487d | refs/heads/master | 2023-08-02T23:28:26.154000 | 2021-09-28T20:49:51 | 2021-09-28T20:49:51 | 411,003,628 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sofka.implementacionDDD.Tienda.Usuario.entity;
import co.com.sofka.domain.generic.AggregateEvent;
import com.sofka.implementacionDDD.Tienda.Compra.values.Correo;
import com.sofka.implementacionDDD.Tienda.Usuario.values.Clave;
import com.sofka.implementacionDDD.Tienda.Usuario.values.IdCuenta;
import com.sofka.implementacionDDD.Tienda.genericvalues.Nombre;
import java.util.Objects;
public class Cuenta extends AggregateEvent<IdCuenta> {
protected Clave clave;
protected Correo correo;
protected Nombre nombre;
public Cuenta(IdCuenta entityId, Clave clave, Correo correo, Nombre nombre) {
super(entityId);
this.clave = clave;
this.correo = correo;
this.nombre = nombre;
}
public void cambiarClaveUsuario(Clave clave){
this.clave = Objects.requireNonNull(clave);
}
public void cambiarCorreoUsuario(Correo correo){
this.correo = Objects.requireNonNull(correo);
}
public void cambiarNombreUsuario(Nombre nombre){
this.nombre = Objects.requireNonNull(nombre);
}
public Clave clave(){
return clave;
}
public Correo correo(){
return correo;
}
public Nombre nombre(){
return nombre;
}
} | UTF-8 | Java | 1,249 | java | Cuenta.java | Java | [] | null | [] | package com.sofka.implementacionDDD.Tienda.Usuario.entity;
import co.com.sofka.domain.generic.AggregateEvent;
import com.sofka.implementacionDDD.Tienda.Compra.values.Correo;
import com.sofka.implementacionDDD.Tienda.Usuario.values.Clave;
import com.sofka.implementacionDDD.Tienda.Usuario.values.IdCuenta;
import com.sofka.implementacionDDD.Tienda.genericvalues.Nombre;
import java.util.Objects;
public class Cuenta extends AggregateEvent<IdCuenta> {
protected Clave clave;
protected Correo correo;
protected Nombre nombre;
public Cuenta(IdCuenta entityId, Clave clave, Correo correo, Nombre nombre) {
super(entityId);
this.clave = clave;
this.correo = correo;
this.nombre = nombre;
}
public void cambiarClaveUsuario(Clave clave){
this.clave = Objects.requireNonNull(clave);
}
public void cambiarCorreoUsuario(Correo correo){
this.correo = Objects.requireNonNull(correo);
}
public void cambiarNombreUsuario(Nombre nombre){
this.nombre = Objects.requireNonNull(nombre);
}
public Clave clave(){
return clave;
}
public Correo correo(){
return correo;
}
public Nombre nombre(){
return nombre;
}
} | 1,249 | 0.709368 | 0.709368 | 46 | 26.173914 | 23.610336 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 11 |
94c9fe95a25dd37a2d19d6e242ef602ce48692bd | 10,642,929,027,824 | 3c2f68a3c7bc2e01a8cd54fa32ac8e53b394beec | /piano-app2/app/src/main/java/com/vtd/pianoapp/practice/Cell.java | d7c689a4a417dd317364e50c897d0209d38f3e3f | [] | no_license | vytiendung/pianoApp2 | https://github.com/vytiendung/pianoApp2 | 7e80babf2842f8e5b661760c639cc7b9d24a01d7 | a9c488641de0f9cffdfcc200f1a92a41e04bf551 | refs/heads/master | 2020-04-09T16:12:13.239000 | 2018-12-05T02:19:08 | 2018-12-05T02:19:08 | 160,446,353 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.vtd.pianoapp.practice;
import com.vtd.pianoapp.common.Constant;
import com.vtd.pianoapp.common.UserConfig;
import com.vtd.pianoapp.songobject.GamePlayNote;
import com.vtd.pianoapp.common.Config;
import com.vtd.pianoapp.util.NoteUtils;
import org.cocos2d.nodes.CCNode;
import org.cocos2d.nodes.CCSprite;
import org.cocos2d.nodes.CCSpriteFrame;
import org.cocos2d.nodes.CCSpriteFrameCache;
public class Cell extends CCNode {
private static final String NOTE_FRAME_NAME_TINY = "guide_note_tiny.png";
private static final String NOTE_FRAME_NAME_SMALL = "guide_note_small.png";
private static final String NOTE_FRAME_NAME_DEFAULT = "guide_note.png";
private static final String NEW_STATE = "NEW";
private static final String GLOW_STATE = "GLOW";
private static final String RELEASE_STATE = "RELEASE";
private int border;
private float mWidth, mHeight; // width & height without border
private CCSprite sprite;
private GamePlayNote gamePlayNote;
private String state;
public static Cell make(GamePlayNote gamePlayNote) {
float width = NoteUtils.isSharpNote(gamePlayNote) ? Config.getInstance().keyWidthBlack : Config.getInstance().keyWidthWhite;
float height = CellDirector.getHeightByDuration(gamePlayNote.duration);
return new Cell(gamePlayNote, width, height);
}
public static Cell make(GamePlayNote gamePlayNote, float width, float height) {
return new Cell(gamePlayNote, width, height);
}
private Cell(GamePlayNote gamePlayNote, float width, float height) {
super();
this.gamePlayNote = gamePlayNote;
this.mWidth = width;
this.mHeight = height;
draw();
}
private void draw() {
state = NEW_STATE;
String frameName = frameNameByDuration(gamePlayNote.duration);
border = 0;
sprite = createSprite(frameName);
setWidth(mWidth);
setHeight(mHeight);
sprite.setPosition(0f, 0f);
if (NoteUtils.isSharpNote(gamePlayNote)) {
sprite.setColor(UserConfig.getInstance().getBlackNoteGuideColor());
} else {
sprite.setColor(UserConfig.getInstance().getWhiteNoteGuideColor());
}
addChild(sprite);
}
private static String frameNameByDuration(float duration) {
String frameName;
if (duration < 200) {
frameName = NOTE_FRAME_NAME_TINY;
} else if (duration < 700) {
frameName = NOTE_FRAME_NAME_SMALL;
} else {
frameName = NOTE_FRAME_NAME_DEFAULT;
}
return frameName;
}
private static CCSprite createSprite(String frameName) {
CCSpriteFrame sf = CCSpriteFrameCache.sharedSpriteFrameCache().spriteFrameByName(frameName);
CCSprite sprite = CCSprite.sprite(sf);
sprite.setAnchorPoint(0f, 0f);
return sprite;
}
public void setWidth(float width) {
mWidth = width;
sprite.setScaleX(width / (sprite.getContentSizeRef().width - border));
sprite.setPosition(-sprite.getScaleX() * border / 2, sprite.getPositionRef().y);
}
public void setHeight(float height) {
mHeight = height;
sprite.setScaleY(height / (sprite.getContentSizeRef().height - border));
sprite.setPosition(sprite.getPositionRef().x, -sprite.getScaleY() * border / 2);
}
public void glow() {
if (GLOW_STATE.equals(state)) return;
removeAllChildren(true);
state = GLOW_STATE;
String frameName = frameNameByDuration(gamePlayNote.duration);
border = (Config.getInstance().deviceType == Constant.SMALL ? 15 : 22) * 2;
sprite = createSprite(buildGlowingFrameName(frameName));
setWidth(mWidth);
setHeight(mHeight);
if (NoteUtils.isSharpNote(gamePlayNote)) {
sprite.setColor(UserConfig.getInstance().getBlackNoteGuideColor());
} else {
sprite.setColor(UserConfig.getInstance().getWhiteNoteGuideColor());
}
addChild(sprite);
}
private static String buildGlowingFrameName(String frameName) {
return frameName.replace(".png", "_glow.png");
}
public void release() {
if (RELEASE_STATE.equals(state)) return;
removeAllChildren(true);
state = RELEASE_STATE;
String frameName = frameNameByDuration(gamePlayNote.duration);
border = 0;
sprite = createSprite(frameName);
setWidth(mWidth);
setHeight(mHeight);
sprite.setPosition(0f, 0f);
addChild(sprite);
}
public float getWidth() {
return mWidth;
}
public float getHeight() {
return mHeight;
}
public void recreate() {
if (NEW_STATE.equals(state)) return;
removeAllChildren(true);
draw();
}
public GamePlayNote getNote() {
return gamePlayNote;
}
}
| UTF-8 | Java | 4,335 | java | Cell.java | Java | [] | null | [] | package com.vtd.pianoapp.practice;
import com.vtd.pianoapp.common.Constant;
import com.vtd.pianoapp.common.UserConfig;
import com.vtd.pianoapp.songobject.GamePlayNote;
import com.vtd.pianoapp.common.Config;
import com.vtd.pianoapp.util.NoteUtils;
import org.cocos2d.nodes.CCNode;
import org.cocos2d.nodes.CCSprite;
import org.cocos2d.nodes.CCSpriteFrame;
import org.cocos2d.nodes.CCSpriteFrameCache;
public class Cell extends CCNode {
private static final String NOTE_FRAME_NAME_TINY = "guide_note_tiny.png";
private static final String NOTE_FRAME_NAME_SMALL = "guide_note_small.png";
private static final String NOTE_FRAME_NAME_DEFAULT = "guide_note.png";
private static final String NEW_STATE = "NEW";
private static final String GLOW_STATE = "GLOW";
private static final String RELEASE_STATE = "RELEASE";
private int border;
private float mWidth, mHeight; // width & height without border
private CCSprite sprite;
private GamePlayNote gamePlayNote;
private String state;
public static Cell make(GamePlayNote gamePlayNote) {
float width = NoteUtils.isSharpNote(gamePlayNote) ? Config.getInstance().keyWidthBlack : Config.getInstance().keyWidthWhite;
float height = CellDirector.getHeightByDuration(gamePlayNote.duration);
return new Cell(gamePlayNote, width, height);
}
public static Cell make(GamePlayNote gamePlayNote, float width, float height) {
return new Cell(gamePlayNote, width, height);
}
private Cell(GamePlayNote gamePlayNote, float width, float height) {
super();
this.gamePlayNote = gamePlayNote;
this.mWidth = width;
this.mHeight = height;
draw();
}
private void draw() {
state = NEW_STATE;
String frameName = frameNameByDuration(gamePlayNote.duration);
border = 0;
sprite = createSprite(frameName);
setWidth(mWidth);
setHeight(mHeight);
sprite.setPosition(0f, 0f);
if (NoteUtils.isSharpNote(gamePlayNote)) {
sprite.setColor(UserConfig.getInstance().getBlackNoteGuideColor());
} else {
sprite.setColor(UserConfig.getInstance().getWhiteNoteGuideColor());
}
addChild(sprite);
}
private static String frameNameByDuration(float duration) {
String frameName;
if (duration < 200) {
frameName = NOTE_FRAME_NAME_TINY;
} else if (duration < 700) {
frameName = NOTE_FRAME_NAME_SMALL;
} else {
frameName = NOTE_FRAME_NAME_DEFAULT;
}
return frameName;
}
private static CCSprite createSprite(String frameName) {
CCSpriteFrame sf = CCSpriteFrameCache.sharedSpriteFrameCache().spriteFrameByName(frameName);
CCSprite sprite = CCSprite.sprite(sf);
sprite.setAnchorPoint(0f, 0f);
return sprite;
}
public void setWidth(float width) {
mWidth = width;
sprite.setScaleX(width / (sprite.getContentSizeRef().width - border));
sprite.setPosition(-sprite.getScaleX() * border / 2, sprite.getPositionRef().y);
}
public void setHeight(float height) {
mHeight = height;
sprite.setScaleY(height / (sprite.getContentSizeRef().height - border));
sprite.setPosition(sprite.getPositionRef().x, -sprite.getScaleY() * border / 2);
}
public void glow() {
if (GLOW_STATE.equals(state)) return;
removeAllChildren(true);
state = GLOW_STATE;
String frameName = frameNameByDuration(gamePlayNote.duration);
border = (Config.getInstance().deviceType == Constant.SMALL ? 15 : 22) * 2;
sprite = createSprite(buildGlowingFrameName(frameName));
setWidth(mWidth);
setHeight(mHeight);
if (NoteUtils.isSharpNote(gamePlayNote)) {
sprite.setColor(UserConfig.getInstance().getBlackNoteGuideColor());
} else {
sprite.setColor(UserConfig.getInstance().getWhiteNoteGuideColor());
}
addChild(sprite);
}
private static String buildGlowingFrameName(String frameName) {
return frameName.replace(".png", "_glow.png");
}
public void release() {
if (RELEASE_STATE.equals(state)) return;
removeAllChildren(true);
state = RELEASE_STATE;
String frameName = frameNameByDuration(gamePlayNote.duration);
border = 0;
sprite = createSprite(frameName);
setWidth(mWidth);
setHeight(mHeight);
sprite.setPosition(0f, 0f);
addChild(sprite);
}
public float getWidth() {
return mWidth;
}
public float getHeight() {
return mHeight;
}
public void recreate() {
if (NEW_STATE.equals(state)) return;
removeAllChildren(true);
draw();
}
public GamePlayNote getNote() {
return gamePlayNote;
}
}
| 4,335 | 0.743022 | 0.737255 | 144 | 29.104166 | 25.495838 | 126 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.013889 | false | false | 11 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.