blob_id
stringlengths 40
40
| __id__
int64 225
39,780B
| directory_id
stringlengths 40
40
| path
stringlengths 6
313
| content_id
stringlengths 40
40
| detected_licenses
list | license_type
stringclasses 2
values | repo_name
stringlengths 6
132
| repo_url
stringlengths 25
151
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
70
| visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 7.28k
689M
⌀ | star_events_count
int64 0
131k
| fork_events_count
int64 0
48k
| gha_license_id
stringclasses 23
values | gha_fork
bool 2
classes | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_updated_at
timestamp[ns] | gha_pushed_at
timestamp[ns] | gha_size
int64 0
40.4M
⌀ | gha_stargazers_count
int32 0
112k
⌀ | gha_forks_count
int32 0
39.4k
⌀ | gha_open_issues_count
int32 0
11k
⌀ | gha_language
stringlengths 1
21
⌀ | gha_archived
bool 2
classes | gha_disabled
bool 1
class | content
stringlengths 7
4.37M
| src_encoding
stringlengths 3
16
| language
stringclasses 1
value | length_bytes
int64 7
4.37M
| extension
stringclasses 24
values | filename
stringlengths 4
174
| language_id
stringclasses 1
value | entities
list | contaminating_dataset
stringclasses 0
values | malware_signatures
list | redacted_content
stringlengths 7
4.37M
| redacted_length_bytes
int64 7
4.37M
| alphanum_fraction
float32 0.25
0.94
| alpha_fraction
float32 0.25
0.94
| num_lines
int32 1
84k
| avg_line_length
float32 0.76
99.9
| std_line_length
float32 0
220
| max_line_length
int32 5
998
| is_vendor
bool 2
classes | is_generated
bool 1
class | max_hex_length
int32 0
319
| hex_fraction
float32 0
0.38
| max_unicode_length
int32 0
408
| unicode_fraction
float32 0
0.36
| max_base64_length
int32 0
506
| base64_fraction
float32 0
0.5
| avg_csv_sep_count
float32 0
4
| is_autogen_header
bool 1
class | is_empty_html
bool 1
class | shard
stringclasses 16
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8fddf0753c0e2bea5c0dc38fcf4c31a8f8c98158
| 7,584,912,267,953 |
6812146ee238d684eec345189e8d03bb103c2fca
|
/src/com/class14/StringMethodsRecap.java
|
694025bec39cad56a24a3c65d30c78d536cffb85
|
[] |
no_license
|
jasraj10/JavaClassesV
|
https://github.com/jasraj10/JavaClassesV
|
e838d69d7a0ba9f10f58bb6ecd59e677dbe9f499
|
b7e6cd8a573dd875d53359680314f40f7a2a58d6
|
refs/heads/master
| 2020-09-28T05:10:09.905000 | 2019-12-19T22:44:30 | 2019-12-19T22:44:30 | 226,695,893 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.class14;
public class StringMethodsRecap {
public static void main(String[] args) {
//.replace
String str="my Syntax Technologies";
System.out.println(str.replace('y', 'i'));
System.out.println("**************");
System.out.println(str.replace("your", "my"));
//.replaceAll
String str2="";
}
}
|
UTF-8
|
Java
| 316 |
java
|
StringMethodsRecap.java
|
Java
|
[] | null |
[] |
package com.class14;
public class StringMethodsRecap {
public static void main(String[] args) {
//.replace
String str="my Syntax Technologies";
System.out.println(str.replace('y', 'i'));
System.out.println("**************");
System.out.println(str.replace("your", "my"));
//.replaceAll
String str2="";
}
}
| 316 | 0.658228 | 0.648734 | 14 | 21.571428 | 16.948301 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.142857 | false | false |
14
|
40117d7f080b8bce803265cf4c133c697d344dfb
| 12,086,037,991,262 |
754b9ad56972481bf912aa096e43fa32e131db0b
|
/src/main/java/hello/config/MongodbConfig.java
|
9a411994a93cfa9bbb354039b742d21b728fb4bd
|
[] |
no_license
|
houyewei/spark
|
https://github.com/houyewei/spark
|
b87d529fa262f57148c4ccddd8d503fa2ee75a40
|
9336040a827cdc3e11aa8ea22d53944893b3902e
|
refs/heads/master
| 2020-06-29T03:36:52.400000 | 2016-12-15T02:02:39 | 2016-12-15T02:02:39 | 74,450,283 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package hello.config;
import hello.repo.PersonRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.authentication.UserCredentials;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.core.MongoClientFactoryBean;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;
import com.mongodb.DBAddress;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.WriteConcern;
@Configuration
@EnableMongoRepositories(basePackages = "hello.repo")
public class MongodbConfig extends AbstractMongoConfiguration {
//1.2.3.4
@Value("${mongodb.url}")
private String mongodbUrl;
//hello
@Value("${mongodb.db}")
private String defaultDb;
@Value("${mongodb.username}")
private String userName;
@Value("${mongodb.password}")
private String password;
@Override
protected String getDatabaseName() {
return defaultDb;
}
@Override
public Mongo mongo() throws Exception {
MongoClientURI uri = new MongoClientURI("mongodb://"+ userName + ":" + password + "@" + mongodbUrl + "/?authSource=" + defaultDb);
return new MongoClient(uri);
}
@Override
protected String getMappingBasePackage() {
return "com.oreilly.springdata.mongodb";
}
}
|
UTF-8
|
Java
| 2,001 |
java
|
MongodbConfig.java
|
Java
|
[] | null |
[] |
package hello.config;
import hello.repo.PersonRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.authentication.UserCredentials;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.core.MongoClientFactoryBean;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;
import com.mongodb.DBAddress;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.WriteConcern;
@Configuration
@EnableMongoRepositories(basePackages = "hello.repo")
public class MongodbConfig extends AbstractMongoConfiguration {
//1.2.3.4
@Value("${mongodb.url}")
private String mongodbUrl;
//hello
@Value("${mongodb.db}")
private String defaultDb;
@Value("${mongodb.username}")
private String userName;
@Value("${mongodb.password}")
private String password;
@Override
protected String getDatabaseName() {
return defaultDb;
}
@Override
public Mongo mongo() throws Exception {
MongoClientURI uri = new MongoClientURI("mongodb://"+ userName + ":" + password + "@" + mongodbUrl + "/?authSource=" + defaultDb);
return new MongoClient(uri);
}
@Override
protected String getMappingBasePackage() {
return "com.oreilly.springdata.mongodb";
}
}
| 2,001 | 0.788606 | 0.785607 | 64 | 30.28125 | 27.258295 | 134 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.109375 | false | false |
14
|
fda445e7d3d17a573b2c4dfb2e8398447f9ff2bb
| 17,291,538,393,765 |
289da898927671b784d72136afe4e2ca4cc7aaea
|
/src/main/java/mqtt/controller/ServicActivator.java
|
e5666fc0fdb64e834fbbc125c6314ae1930cc731
|
[] |
no_license
|
bayaabid/mqtt1
|
https://github.com/bayaabid/mqtt1
|
c7dde54a045fb3a41cb04b72b12d7f74ee926c28
|
ee26e76dae66d395d0154bb5f2839bd87a431d18
|
refs/heads/master
| 2021-01-13T12:34:19.776000 | 2016-11-01T14:25:27 | 2016-11-01T14:25:27 | 72,543,511 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package mqtt.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.annotation.MessageEndpoint;
import org.springframework.integration.annotation.MessagingGateway;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Component;
@Component
//@MessageEndpoint
public class ServicActivator{
DefaultMqttPahoClientFactory factory;
/*@Autowired
MyGateway gateway;*/
public ServicActivator() {
// TODO Auto-generated constructor stub
factory = new DefaultMqttPahoClientFactory();
factory.setServerURIs("tcp://localhost:1883");
}
/*@ServiceActivator(inputChannel = "mqttOutboundChannel")
public void send(){
System.out.println("HHHHHHHHHHHHHHHHH");
//gateway.sendToMqtt("baya");
}*/
@ServiceActivator(inputChannel = "mqttOutboundChannel",outputChannel="out")
public String mqttOutbound(Message<String> message) {
/*Message<String> message1 = new Message<String>() {
@Override
public String getPayload() {
// TODO Auto-generated method stub
return "kais";
}
@Override
public MessageHeaders getHeaders() {
// TODO Auto-generated method stub
return null;
}
};*/
System.out.println("message"+message.getPayload());
/* MqttPahoMessageHandler messageHandler =
new MqttPahoMessageHandler("java", factory);
messageHandler.setAsync(true);
messageHandler.setDefaultTopic("test1");
messageHandler.setDefaultQos(2);*/
//messageHandler.handleMessage(message);
//return messageHandler;
return "kaisssssssssssssssss";
}
}
|
UTF-8
|
Java
| 2,285 |
java
|
ServicActivator.java
|
Java
|
[
{
"context": "ync(true);\r\n messageHandler.setDefaultTopic(\"test1\");\r\n messageHandler.setDefaultQos(2);*/\r\n ",
"end": 2102,
"score": 0.9335829615592957,
"start": 2097,
"tag": "USERNAME",
"value": "test1"
}
] | null |
[] |
package mqtt.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.annotation.MessageEndpoint;
import org.springframework.integration.annotation.MessagingGateway;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Component;
@Component
//@MessageEndpoint
public class ServicActivator{
DefaultMqttPahoClientFactory factory;
/*@Autowired
MyGateway gateway;*/
public ServicActivator() {
// TODO Auto-generated constructor stub
factory = new DefaultMqttPahoClientFactory();
factory.setServerURIs("tcp://localhost:1883");
}
/*@ServiceActivator(inputChannel = "mqttOutboundChannel")
public void send(){
System.out.println("HHHHHHHHHHHHHHHHH");
//gateway.sendToMqtt("baya");
}*/
@ServiceActivator(inputChannel = "mqttOutboundChannel",outputChannel="out")
public String mqttOutbound(Message<String> message) {
/*Message<String> message1 = new Message<String>() {
@Override
public String getPayload() {
// TODO Auto-generated method stub
return "kais";
}
@Override
public MessageHeaders getHeaders() {
// TODO Auto-generated method stub
return null;
}
};*/
System.out.println("message"+message.getPayload());
/* MqttPahoMessageHandler messageHandler =
new MqttPahoMessageHandler("java", factory);
messageHandler.setAsync(true);
messageHandler.setDefaultTopic("test1");
messageHandler.setDefaultQos(2);*/
//messageHandler.handleMessage(message);
//return messageHandler;
return "kaisssssssssssssssss";
}
}
| 2,285 | 0.748359 | 0.745295 | 66 | 32.621212 | 23.701914 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.545455 | false | false |
14
|
e1003a2a7a15e5b1ea1c63c7390189cfa2bc41a5
| 30,382,598,678,185 |
f4401ccca2718950d9f0b1fbdd29812d4511676b
|
/eagle-security/eagle-security-hive-web/src/main/java/org/apache/eagle/service/security/hive/dao/HiveSensitivityMetadataDAOImpl.java
|
90ee845ea26ec3d65118abfdbbd2bfaffd6e37fe
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
fisher2017/incubator-eagle
|
https://github.com/fisher2017/incubator-eagle
|
75799e4019a6b68168d031bd29a7822b27764641
|
982a6b7430d349199091add264c9bef1bdc8ae35
|
refs/heads/master
| 2021-01-21T01:39:37.279000 | 2016-06-02T10:45:52 | 2016-06-02T10:45:52 | 62,016,034 | 2 | 0 | null | true | 2016-12-06T14:52:18 | 2016-06-27T01:10:53 | 2016-06-27T01:10:59 | 2016-12-06T14:52:18 | 24,166 | 0 | 0 | 1 |
Java
| null | null |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.eagle.service.security.hive.dao;
import org.apache.eagle.log.entity.GenericServiceAPIResponseEntity;
import org.apache.eagle.log.entity.ListQueryAPIResponseEntity;
import org.apache.eagle.service.generic.GenericEntityServiceResource;
import org.apache.eagle.service.generic.ListQueryResource;
import org.apache.eagle.security.entity.HiveResourceSensitivityAPIEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HiveSensitivityMetadataDAOImpl implements HiveSensitivityMetadataDAO{
private static Logger LOG = LoggerFactory.getLogger(HiveSensitivityMetadataDAOImpl.class);
@Override
public Map<String, Map<String, String>> getAllHiveSensitivityMap(){
GenericEntityServiceResource resource = new GenericEntityServiceResource();
/* parameters are: query, startTime, endTime, pageSzie, startRowkey, treeAgg, timeSeries, intervalmin, top, filterIfMissing,
* parallel, metricName*/
GenericServiceAPIResponseEntity ret = resource.search("HiveResourceSensitivityService[]{*}", null, null, Integer.MAX_VALUE, null, false, false, 0L, 0, false,
0, null, false);
List<HiveResourceSensitivityAPIEntity> list = (List<HiveResourceSensitivityAPIEntity>) ret.getObj();
if( list == null )
return Collections.emptyMap();
Map<String, Map<String, String>> res = new HashMap<String, Map<String, String>>();
for(HiveResourceSensitivityAPIEntity entity : list){
String site = entity.getTags().get("site");
if(entity.getTags().containsKey("hiveResource")) {
if(res.get(site) == null){
res.put(site, new HashMap<String, String>());
}
Map<String, String> resSensitivityMap = res.get(site);
resSensitivityMap.put(entity.getTags().get("hiveResource"), entity.getSensitivityType());
}
else {
if(LOG.isDebugEnabled()) {
LOG.debug("An invalid sensitivity entity is detected" + entity);
}
}
}
return res;
}
@Override
public Map<String, String> getHiveSensitivityMap(String site){
GenericEntityServiceResource resource = new GenericEntityServiceResource();
String queryFormat = "HiveResourceSensitivityService[@site=\"%s\"]{*}";
GenericServiceAPIResponseEntity ret = resource.search(String.format(queryFormat, site), null, null, Integer.MAX_VALUE, null, false, false, 0L, 0, false,
0, null, false);
List<HiveResourceSensitivityAPIEntity> list = (List<HiveResourceSensitivityAPIEntity>) ret.getObj();
if( list == null )
return Collections.emptyMap();
Map<String, String> resSensitivityMap = new HashMap<String, String>();
for(HiveResourceSensitivityAPIEntity entity : list){
if(entity.getTags().containsKey("hiveResource")) {
resSensitivityMap.put(entity.getTags().get("hiveResource"), entity.getSensitivityType());
}
}
return resSensitivityMap;
}
}
|
UTF-8
|
Java
| 4,047 |
java
|
HiveSensitivityMetadataDAOImpl.java
|
Java
|
[] | null |
[] |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.eagle.service.security.hive.dao;
import org.apache.eagle.log.entity.GenericServiceAPIResponseEntity;
import org.apache.eagle.log.entity.ListQueryAPIResponseEntity;
import org.apache.eagle.service.generic.GenericEntityServiceResource;
import org.apache.eagle.service.generic.ListQueryResource;
import org.apache.eagle.security.entity.HiveResourceSensitivityAPIEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HiveSensitivityMetadataDAOImpl implements HiveSensitivityMetadataDAO{
private static Logger LOG = LoggerFactory.getLogger(HiveSensitivityMetadataDAOImpl.class);
@Override
public Map<String, Map<String, String>> getAllHiveSensitivityMap(){
GenericEntityServiceResource resource = new GenericEntityServiceResource();
/* parameters are: query, startTime, endTime, pageSzie, startRowkey, treeAgg, timeSeries, intervalmin, top, filterIfMissing,
* parallel, metricName*/
GenericServiceAPIResponseEntity ret = resource.search("HiveResourceSensitivityService[]{*}", null, null, Integer.MAX_VALUE, null, false, false, 0L, 0, false,
0, null, false);
List<HiveResourceSensitivityAPIEntity> list = (List<HiveResourceSensitivityAPIEntity>) ret.getObj();
if( list == null )
return Collections.emptyMap();
Map<String, Map<String, String>> res = new HashMap<String, Map<String, String>>();
for(HiveResourceSensitivityAPIEntity entity : list){
String site = entity.getTags().get("site");
if(entity.getTags().containsKey("hiveResource")) {
if(res.get(site) == null){
res.put(site, new HashMap<String, String>());
}
Map<String, String> resSensitivityMap = res.get(site);
resSensitivityMap.put(entity.getTags().get("hiveResource"), entity.getSensitivityType());
}
else {
if(LOG.isDebugEnabled()) {
LOG.debug("An invalid sensitivity entity is detected" + entity);
}
}
}
return res;
}
@Override
public Map<String, String> getHiveSensitivityMap(String site){
GenericEntityServiceResource resource = new GenericEntityServiceResource();
String queryFormat = "HiveResourceSensitivityService[@site=\"%s\"]{*}";
GenericServiceAPIResponseEntity ret = resource.search(String.format(queryFormat, site), null, null, Integer.MAX_VALUE, null, false, false, 0L, 0, false,
0, null, false);
List<HiveResourceSensitivityAPIEntity> list = (List<HiveResourceSensitivityAPIEntity>) ret.getObj();
if( list == null )
return Collections.emptyMap();
Map<String, String> resSensitivityMap = new HashMap<String, String>();
for(HiveResourceSensitivityAPIEntity entity : list){
if(entity.getTags().containsKey("hiveResource")) {
resSensitivityMap.put(entity.getTags().get("hiveResource"), entity.getSensitivityType());
}
}
return resSensitivityMap;
}
}
| 4,047 | 0.692612 | 0.689647 | 83 | 47.759037 | 37.113499 | 165 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.072289 | false | false |
14
|
730241e374d808cb763cd7660d7951161ff3cc2c
| 12,841,952,276,136 |
914ca1969a1a6314be8b956d81662e5456265e56
|
/src/view/DO/RoomViewFloor2.java
|
d4f095492c12fbdcf7b6346a4328920cce3859ff
|
[] |
no_license
|
dungnhm1998/hotel_management
|
https://github.com/dungnhm1998/hotel_management
|
849fb4e66724c5580841b1a20c36634d2de9997a
|
f8fe5540fa4026f1de75f4e7dd53caf51e27f15a
|
refs/heads/master
| 2022-12-06T16:10:52.185000 | 2020-08-17T12:53:33 | 2020-08-17T12:53:33 | 288,171,720 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package view.DO;
import controllerl.Util.impl.BookRoomDAO;
import controllerl.Util.impl.PayBillDAO;
import controllerl.Util.impl.RoomDAO;
import daoop_qlks_ver1.DatabaseConnector;
import java.awt.Color;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import model.dto.BookRoom;
import model.dto.PayBill;
import model.dto.Room;
import view.HomePage;
/**
*
* @author Admin
*/
public class RoomViewFloor2 extends javax.swing.JFrame {
/**
* Creates new form RoomViewFloor2
*/
ArrayList<Room> listRoom;
ArrayList<PayBill> listPayBill;
ArrayList<BookRoom> listBookRoom;
static int price2 = 0;
static int roomID2 = 0;
public RoomViewFloor2() {
initComponents();
this.setLocationRelativeTo(null);
listRoom = new RoomDAO().getListRoom();
listPayBill = new PayBillDAO().getLisPaytBill();
listBookRoom = new BookRoomDAO().getListBookRoom();
int roomID = 0;
for (Room room : listRoom) {
if (room.getIsBooked() == true) {
roomID = room.getRoomID();
if (roomID == 4) {
btn1.setBackground(Color.red);
}
if (roomID == 5) {
btn2.setBackground(Color.red);
}
if (roomID == 6) {
btn3.setBackground(Color.red);
}
//break;
}
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
btn1 = new javax.swing.JButton();
btn3 = new javax.swing.JButton();
btn5 = new javax.swing.JButton();
btn7 = new javax.swing.JButton();
btn8 = new javax.swing.JButton();
btn6 = new javax.swing.JButton();
btn4 = new javax.swing.JButton();
btn2 = new javax.swing.JButton();
a = new javax.swing.JLabel();
b = new javax.swing.JLabel();
c = new javax.swing.JLabel();
d = new javax.swing.JLabel();
e = new javax.swing.JLabel();
txtRoomID = new javax.swing.JTextField();
txtRoomName = new javax.swing.JTextField();
txtFloor = new javax.swing.JTextField();
txtBedNumber = new javax.swing.JTextField();
txtPrice = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
btnBook = new javax.swing.JButton();
btnUse = new javax.swing.JButton();
btnBack = new javax.swing.JButton();
btnNext = new javax.swing.JButton();
txtHome = new javax.swing.JButton();
btnOut = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("RoomViewFloor2");
btn1.setText("Phòng 201");
btn1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn1ActionPerformed(evt);
}
});
btn3.setText("Phòng 203");
btn3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn3ActionPerformed(evt);
}
});
btn5.setText("Phòng 205");
btn7.setText("Phòng 207");
btn8.setText("Phòng 208");
btn6.setText("Phòng 206");
btn4.setText("Phòng 204");
btn2.setText("Phòng 202");
btn2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn2ActionPerformed(evt);
}
});
a.setText("RoomID");
b.setText("RoomName");
c.setText("Floor");
d.setText("Bed");
e.setText("Price");
txtRoomName.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtRoomNameActionPerformed(evt);
}
});
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
btnBook.setText("Book");
btnBook.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnBookActionPerformed(evt);
}
});
btnUse.setText("Use");
btnUse.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnUseActionPerformed(evt);
}
});
btnBack.setText("back");
btnBack.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnBackActionPerformed(evt);
}
});
btnNext.setText("next");
btnNext.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnNextActionPerformed(evt);
}
});
txtHome.setText("homePage");
txtHome.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtHomeActionPerformed(evt);
}
});
btnOut.setText("Out");
btnOut.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnOutActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(26, 26, 26)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btn3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btn5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btn7, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(btn1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(txtHome, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(116, 116, 116)
.addComponent(btn2))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btn4, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(btn6, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(btn8, javax.swing.GroupLayout.Alignment.TRAILING))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 133, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(e)
.addComponent(d)
.addComponent(c)
.addComponent(b))
.addGap(21, 21, 21)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(txtFloor)
.addComponent(txtBedNumber)
.addComponent(txtRoomName)
.addComponent(txtPrice, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addComponent(a)
.addGap(37, 37, 37)
.addComponent(txtRoomID, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(109, 109, 109)
.addComponent(btnBack)
.addGap(18, 18, 18)
.addComponent(btnNext))
.addGroup(layout.createSequentialGroup()
.addGap(73, 73, 73)
.addComponent(btnBook)
.addGap(18, 18, 18)
.addComponent(btnUse)
.addGap(18, 18, 18)
.addComponent(btnOut)))
.addGap(18, 18, 18))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 201, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())))
);
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8});
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(txtHome)
.addGap(20, 20, 20)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnBook)
.addComponent(btnUse)
.addComponent(btnOut)
.addComponent(txtBedNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(d))
.addGap(27, 27, 27)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnBack)
.addComponent(btnNext))
.addGap(29, 29, 29))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btn1, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btn2, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btn4, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btn3, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 32, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btn5, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btn6, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btn7, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btn8, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(e)
.addComponent(txtPrice, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(b)
.addComponent(txtRoomName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(a)
.addComponent(txtRoomID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(28, 28, 28)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(c)
.addComponent(txtFloor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(134, 134, 134))))
);
layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8});
pack();
}// </editor-fold>//GEN-END:initComponents
private void txtRoomNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtRoomNameActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtRoomNameActionPerformed
private void btn1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn1ActionPerformed
// TODO add your handling code here:
txtRoomID.setText("4");
txtRoomName.setText("201");
txtFloor.setText("2");
txtBedNumber.setText("1");
txtPrice.setText("60000");
for (Room r : listRoom) {
if (r.getRoomID() == 4) {
if (r.getIsBooked() == true) {
btnBook.setText("Booked");
} else {
btnBook.setText("Book");
}
}
if (r.getRoomID() == 4) {
if (r.getIsUsed() == true) {
btnUse.setText("Used");
} else {
btnUse.setText("Use");
}
}
}
}//GEN-LAST:event_btn1ActionPerformed
private void btn2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn2ActionPerformed
// TODO add your handling code here:
txtRoomID.setText("5");
txtRoomName.setText("202");
txtFloor.setText("2");
txtBedNumber.setText("1");
txtPrice.setText("60000");
for (Room r : listRoom) {
if (r.getRoomID() == 5) {
if (r.getIsBooked() == true) {
btnBook.setText("Booked");
} else {
btnBook.setText("Book");
}
}
if (r.getRoomID() == 5) {
if (r.getIsUsed() == true) {
btnUse.setText("Used");
} else {
btnUse.setText("Use");
}
}
}
}//GEN-LAST:event_btn2ActionPerformed
private void btn3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn3ActionPerformed
// TODO add your handling code here:
txtRoomID.setText("6");
txtRoomName.setText("203");
txtFloor.setText("2");
txtBedNumber.setText("2");
txtPrice.setText("150000");
for (Room r : listRoom) {
if (r.getRoomID() == 6) {
if (r.getIsBooked() == true) {
btnBook.setText("Booked");
} else {
btnBook.setText("Book");
}
}
if (r.getRoomID() == 6) {
if (r.getIsUsed() == true) {
btnUse.setText("Used");
} else {
btnUse.setText("Use");
}
}
}
}//GEN-LAST:event_btn3ActionPerformed
private void btnUseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUseActionPerformed
// TODO add your handling code here:
if (btnUse.getText().equals("Use")) {
for (Room r : listRoom) {
if (r.getRoomID() == Integer.parseInt(txtRoomID.getText())) {
try {
r.setIsBooked(true);
String sql = "UPDATE tblRoom SET isUsed = 1, isBooked = 1 WHERE roomID = ?";
Connection conn = DatabaseConnector.getSQLServerConnection();
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1, r.getRoomID());
stmt.execute();
JOptionPane.showMessageDialog(rootPane, "Used done");
CustomerView cv = new CustomerView();
cv.pack();
cv.setLocationRelativeTo(null);
cv.setVisible(true);
dispose();
break;
} catch (SQLException | ClassNotFoundException ex) {
Logger.getLogger(RoomViewFloor1.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
} else {
JOptionPane.showMessageDialog(rootPane, "Phong dang duoc su dung");
}
}//GEN-LAST:event_btnUseActionPerformed
private void btnBookActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBookActionPerformed
// TODO add your handling code here:
if (btnBook.getText().equals("Book")) {
for (Room r : listRoom) {
if (r.getRoomID() == Integer.parseInt(txtRoomID.getText())) {
try {
r.setIsBooked(true);
String sql = "UPDATE tblRoom SET isBooked = 1 WHERE roomID = ?";
Connection conn = DatabaseConnector.getSQLServerConnection();
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1, r.getRoomID());
stmt.execute();
JOptionPane.showMessageDialog(rootPane, "Booked done");
CustomerView cv = new CustomerView();
cv.pack();
cv.setLocationRelativeTo(null);
cv.setVisible(true);
dispose();
break;
} catch (SQLException | ClassNotFoundException ex) {
Logger.getLogger(RoomViewFloor1.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
} else {
JOptionPane.showMessageDialog(rootPane, "Phong da duoc dat tu truoc");
}
}//GEN-LAST:event_btnBookActionPerformed
private void btnBackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBackActionPerformed
// TODO add your handling code here:
dispose();
RoomViewFloor1 roomview1 = new RoomViewFloor1();
roomview1.pack();
roomview1.setLocationRelativeTo(null);
roomview1.setVisible(true);
}//GEN-LAST:event_btnBackActionPerformed
private void btnNextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNextActionPerformed
// TODO add your handling code here:
dispose();
RoomViewFloor3 roomview3 = new RoomViewFloor3();
roomview3.pack();
roomview3.setLocationRelativeTo(null);
roomview3.setVisible(true);
}//GEN-LAST:event_btnNextActionPerformed
private void txtHomeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtHomeActionPerformed
// TODO add your handling code here:
dispose();
HomePage homePage = new HomePage();
homePage.pack();
homePage.setLocationRelativeTo(null);
homePage.setVisible(true);
}//GEN-LAST:event_txtHomeActionPerformed
private void btnOutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOutActionPerformed
// TODO add your handling code here:
roomID2 = Integer.parseInt(txtRoomID.getText());
Date date3;
Date date4;
for (BookRoom br : listBookRoom) {
if (br.getRoomID() == roomID2) {
int x = 0;
try {
date3 = new SimpleDateFormat("yyyy-MM-dd").parse(br.getDateFrom());
date4 = new SimpleDateFormat("yyyy-MM-dd").parse(br.getDateTo());
long diff = date4.getTime() - date3.getTime();
x = (int) TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
for (Room r : listRoom) {
if (r.getRoomID() == br.getRoomID()) {
price2 = (x + 1) * r.getPrice();
break;
}
}
System.out.println(x + " " + price2);
} catch (ParseException ex) {
Logger.getLogger(RoomViewFloor1.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
for (Room r : listRoom) {
if (r.getRoomID() == Integer.parseInt(txtRoomID.getText())) {
String sql = "UPDATE tblRoom SET isUsed = 0, isBooked= 0 WHERE roomID = ?";
Connection conn;
try {
conn = DatabaseConnector.getSQLServerConnection();
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1, r.getRoomID());
stmt.execute();
} catch (SQLException | ClassNotFoundException ex) {
Logger.getLogger(RoomViewFloor1.class.getName()).log(Level.SEVERE, null, ex);
}
JOptionPane.showMessageDialog(rootPane, "Out done");
}
}
dispose();
BillView bv = new BillView();
bv.pack();
bv.setLocationRelativeTo(null);
bv.setVisible(true);
}//GEN-LAST:event_btnOutActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(RoomViewFloor2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(RoomViewFloor2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(RoomViewFloor2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(RoomViewFloor2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new RoomViewFloor2().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel a;
private javax.swing.JLabel b;
private javax.swing.JButton btn1;
private javax.swing.JButton btn2;
private javax.swing.JButton btn3;
private javax.swing.JButton btn4;
private javax.swing.JButton btn5;
private javax.swing.JButton btn6;
private javax.swing.JButton btn7;
private javax.swing.JButton btn8;
private javax.swing.JButton btnBack;
private javax.swing.JButton btnBook;
private javax.swing.JButton btnNext;
private javax.swing.JButton btnOut;
private javax.swing.JButton btnUse;
private javax.swing.JLabel c;
private javax.swing.JLabel d;
private javax.swing.JLabel e;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextField txtBedNumber;
private javax.swing.JTextField txtFloor;
private javax.swing.JButton txtHome;
private javax.swing.JTextField txtPrice;
private javax.swing.JTextField txtRoomID;
private javax.swing.JTextField txtRoomName;
// End of variables declaration//GEN-END:variables
}
|
UTF-8
|
Java
| 28,359 |
java
|
RoomViewFloor2.java
|
Java
|
[
{
"context": "dto.Room;\nimport view.HomePage;\n\n/**\n *\n * @author Admin\n */\npublic class RoomViewFloor2 extends javax.swi",
"end": 858,
"score": 0.7073879837989807,
"start": 853,
"tag": "USERNAME",
"value": "Admin"
}
] | null |
[] |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package view.DO;
import controllerl.Util.impl.BookRoomDAO;
import controllerl.Util.impl.PayBillDAO;
import controllerl.Util.impl.RoomDAO;
import daoop_qlks_ver1.DatabaseConnector;
import java.awt.Color;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import model.dto.BookRoom;
import model.dto.PayBill;
import model.dto.Room;
import view.HomePage;
/**
*
* @author Admin
*/
public class RoomViewFloor2 extends javax.swing.JFrame {
/**
* Creates new form RoomViewFloor2
*/
ArrayList<Room> listRoom;
ArrayList<PayBill> listPayBill;
ArrayList<BookRoom> listBookRoom;
static int price2 = 0;
static int roomID2 = 0;
public RoomViewFloor2() {
initComponents();
this.setLocationRelativeTo(null);
listRoom = new RoomDAO().getListRoom();
listPayBill = new PayBillDAO().getLisPaytBill();
listBookRoom = new BookRoomDAO().getListBookRoom();
int roomID = 0;
for (Room room : listRoom) {
if (room.getIsBooked() == true) {
roomID = room.getRoomID();
if (roomID == 4) {
btn1.setBackground(Color.red);
}
if (roomID == 5) {
btn2.setBackground(Color.red);
}
if (roomID == 6) {
btn3.setBackground(Color.red);
}
//break;
}
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
btn1 = new javax.swing.JButton();
btn3 = new javax.swing.JButton();
btn5 = new javax.swing.JButton();
btn7 = new javax.swing.JButton();
btn8 = new javax.swing.JButton();
btn6 = new javax.swing.JButton();
btn4 = new javax.swing.JButton();
btn2 = new javax.swing.JButton();
a = new javax.swing.JLabel();
b = new javax.swing.JLabel();
c = new javax.swing.JLabel();
d = new javax.swing.JLabel();
e = new javax.swing.JLabel();
txtRoomID = new javax.swing.JTextField();
txtRoomName = new javax.swing.JTextField();
txtFloor = new javax.swing.JTextField();
txtBedNumber = new javax.swing.JTextField();
txtPrice = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
btnBook = new javax.swing.JButton();
btnUse = new javax.swing.JButton();
btnBack = new javax.swing.JButton();
btnNext = new javax.swing.JButton();
txtHome = new javax.swing.JButton();
btnOut = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("RoomViewFloor2");
btn1.setText("Phòng 201");
btn1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn1ActionPerformed(evt);
}
});
btn3.setText("Phòng 203");
btn3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn3ActionPerformed(evt);
}
});
btn5.setText("Phòng 205");
btn7.setText("Phòng 207");
btn8.setText("Phòng 208");
btn6.setText("Phòng 206");
btn4.setText("Phòng 204");
btn2.setText("Phòng 202");
btn2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn2ActionPerformed(evt);
}
});
a.setText("RoomID");
b.setText("RoomName");
c.setText("Floor");
d.setText("Bed");
e.setText("Price");
txtRoomName.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtRoomNameActionPerformed(evt);
}
});
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
btnBook.setText("Book");
btnBook.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnBookActionPerformed(evt);
}
});
btnUse.setText("Use");
btnUse.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnUseActionPerformed(evt);
}
});
btnBack.setText("back");
btnBack.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnBackActionPerformed(evt);
}
});
btnNext.setText("next");
btnNext.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnNextActionPerformed(evt);
}
});
txtHome.setText("homePage");
txtHome.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtHomeActionPerformed(evt);
}
});
btnOut.setText("Out");
btnOut.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnOutActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(26, 26, 26)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btn3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btn5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btn7, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(btn1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(txtHome, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(116, 116, 116)
.addComponent(btn2))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btn4, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(btn6, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(btn8, javax.swing.GroupLayout.Alignment.TRAILING))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 133, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(e)
.addComponent(d)
.addComponent(c)
.addComponent(b))
.addGap(21, 21, 21)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(txtFloor)
.addComponent(txtBedNumber)
.addComponent(txtRoomName)
.addComponent(txtPrice, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addComponent(a)
.addGap(37, 37, 37)
.addComponent(txtRoomID, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(109, 109, 109)
.addComponent(btnBack)
.addGap(18, 18, 18)
.addComponent(btnNext))
.addGroup(layout.createSequentialGroup()
.addGap(73, 73, 73)
.addComponent(btnBook)
.addGap(18, 18, 18)
.addComponent(btnUse)
.addGap(18, 18, 18)
.addComponent(btnOut)))
.addGap(18, 18, 18))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 201, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())))
);
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8});
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(txtHome)
.addGap(20, 20, 20)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnBook)
.addComponent(btnUse)
.addComponent(btnOut)
.addComponent(txtBedNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(d))
.addGap(27, 27, 27)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnBack)
.addComponent(btnNext))
.addGap(29, 29, 29))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btn1, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btn2, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btn4, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btn3, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 32, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btn5, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btn6, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btn7, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btn8, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(e)
.addComponent(txtPrice, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(b)
.addComponent(txtRoomName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(a)
.addComponent(txtRoomID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(28, 28, 28)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(c)
.addComponent(txtFloor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(134, 134, 134))))
);
layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8});
pack();
}// </editor-fold>//GEN-END:initComponents
private void txtRoomNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtRoomNameActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtRoomNameActionPerformed
private void btn1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn1ActionPerformed
// TODO add your handling code here:
txtRoomID.setText("4");
txtRoomName.setText("201");
txtFloor.setText("2");
txtBedNumber.setText("1");
txtPrice.setText("60000");
for (Room r : listRoom) {
if (r.getRoomID() == 4) {
if (r.getIsBooked() == true) {
btnBook.setText("Booked");
} else {
btnBook.setText("Book");
}
}
if (r.getRoomID() == 4) {
if (r.getIsUsed() == true) {
btnUse.setText("Used");
} else {
btnUse.setText("Use");
}
}
}
}//GEN-LAST:event_btn1ActionPerformed
private void btn2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn2ActionPerformed
// TODO add your handling code here:
txtRoomID.setText("5");
txtRoomName.setText("202");
txtFloor.setText("2");
txtBedNumber.setText("1");
txtPrice.setText("60000");
for (Room r : listRoom) {
if (r.getRoomID() == 5) {
if (r.getIsBooked() == true) {
btnBook.setText("Booked");
} else {
btnBook.setText("Book");
}
}
if (r.getRoomID() == 5) {
if (r.getIsUsed() == true) {
btnUse.setText("Used");
} else {
btnUse.setText("Use");
}
}
}
}//GEN-LAST:event_btn2ActionPerformed
private void btn3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn3ActionPerformed
// TODO add your handling code here:
txtRoomID.setText("6");
txtRoomName.setText("203");
txtFloor.setText("2");
txtBedNumber.setText("2");
txtPrice.setText("150000");
for (Room r : listRoom) {
if (r.getRoomID() == 6) {
if (r.getIsBooked() == true) {
btnBook.setText("Booked");
} else {
btnBook.setText("Book");
}
}
if (r.getRoomID() == 6) {
if (r.getIsUsed() == true) {
btnUse.setText("Used");
} else {
btnUse.setText("Use");
}
}
}
}//GEN-LAST:event_btn3ActionPerformed
private void btnUseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUseActionPerformed
// TODO add your handling code here:
if (btnUse.getText().equals("Use")) {
for (Room r : listRoom) {
if (r.getRoomID() == Integer.parseInt(txtRoomID.getText())) {
try {
r.setIsBooked(true);
String sql = "UPDATE tblRoom SET isUsed = 1, isBooked = 1 WHERE roomID = ?";
Connection conn = DatabaseConnector.getSQLServerConnection();
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1, r.getRoomID());
stmt.execute();
JOptionPane.showMessageDialog(rootPane, "Used done");
CustomerView cv = new CustomerView();
cv.pack();
cv.setLocationRelativeTo(null);
cv.setVisible(true);
dispose();
break;
} catch (SQLException | ClassNotFoundException ex) {
Logger.getLogger(RoomViewFloor1.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
} else {
JOptionPane.showMessageDialog(rootPane, "Phong dang duoc su dung");
}
}//GEN-LAST:event_btnUseActionPerformed
private void btnBookActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBookActionPerformed
// TODO add your handling code here:
if (btnBook.getText().equals("Book")) {
for (Room r : listRoom) {
if (r.getRoomID() == Integer.parseInt(txtRoomID.getText())) {
try {
r.setIsBooked(true);
String sql = "UPDATE tblRoom SET isBooked = 1 WHERE roomID = ?";
Connection conn = DatabaseConnector.getSQLServerConnection();
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1, r.getRoomID());
stmt.execute();
JOptionPane.showMessageDialog(rootPane, "Booked done");
CustomerView cv = new CustomerView();
cv.pack();
cv.setLocationRelativeTo(null);
cv.setVisible(true);
dispose();
break;
} catch (SQLException | ClassNotFoundException ex) {
Logger.getLogger(RoomViewFloor1.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
} else {
JOptionPane.showMessageDialog(rootPane, "Phong da duoc dat tu truoc");
}
}//GEN-LAST:event_btnBookActionPerformed
private void btnBackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBackActionPerformed
// TODO add your handling code here:
dispose();
RoomViewFloor1 roomview1 = new RoomViewFloor1();
roomview1.pack();
roomview1.setLocationRelativeTo(null);
roomview1.setVisible(true);
}//GEN-LAST:event_btnBackActionPerformed
private void btnNextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNextActionPerformed
// TODO add your handling code here:
dispose();
RoomViewFloor3 roomview3 = new RoomViewFloor3();
roomview3.pack();
roomview3.setLocationRelativeTo(null);
roomview3.setVisible(true);
}//GEN-LAST:event_btnNextActionPerformed
private void txtHomeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtHomeActionPerformed
// TODO add your handling code here:
dispose();
HomePage homePage = new HomePage();
homePage.pack();
homePage.setLocationRelativeTo(null);
homePage.setVisible(true);
}//GEN-LAST:event_txtHomeActionPerformed
private void btnOutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOutActionPerformed
// TODO add your handling code here:
roomID2 = Integer.parseInt(txtRoomID.getText());
Date date3;
Date date4;
for (BookRoom br : listBookRoom) {
if (br.getRoomID() == roomID2) {
int x = 0;
try {
date3 = new SimpleDateFormat("yyyy-MM-dd").parse(br.getDateFrom());
date4 = new SimpleDateFormat("yyyy-MM-dd").parse(br.getDateTo());
long diff = date4.getTime() - date3.getTime();
x = (int) TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
for (Room r : listRoom) {
if (r.getRoomID() == br.getRoomID()) {
price2 = (x + 1) * r.getPrice();
break;
}
}
System.out.println(x + " " + price2);
} catch (ParseException ex) {
Logger.getLogger(RoomViewFloor1.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
for (Room r : listRoom) {
if (r.getRoomID() == Integer.parseInt(txtRoomID.getText())) {
String sql = "UPDATE tblRoom SET isUsed = 0, isBooked= 0 WHERE roomID = ?";
Connection conn;
try {
conn = DatabaseConnector.getSQLServerConnection();
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1, r.getRoomID());
stmt.execute();
} catch (SQLException | ClassNotFoundException ex) {
Logger.getLogger(RoomViewFloor1.class.getName()).log(Level.SEVERE, null, ex);
}
JOptionPane.showMessageDialog(rootPane, "Out done");
}
}
dispose();
BillView bv = new BillView();
bv.pack();
bv.setLocationRelativeTo(null);
bv.setVisible(true);
}//GEN-LAST:event_btnOutActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(RoomViewFloor2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(RoomViewFloor2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(RoomViewFloor2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(RoomViewFloor2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new RoomViewFloor2().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel a;
private javax.swing.JLabel b;
private javax.swing.JButton btn1;
private javax.swing.JButton btn2;
private javax.swing.JButton btn3;
private javax.swing.JButton btn4;
private javax.swing.JButton btn5;
private javax.swing.JButton btn6;
private javax.swing.JButton btn7;
private javax.swing.JButton btn8;
private javax.swing.JButton btnBack;
private javax.swing.JButton btnBook;
private javax.swing.JButton btnNext;
private javax.swing.JButton btnOut;
private javax.swing.JButton btnUse;
private javax.swing.JLabel c;
private javax.swing.JLabel d;
private javax.swing.JLabel e;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextField txtBedNumber;
private javax.swing.JTextField txtFloor;
private javax.swing.JButton txtHome;
private javax.swing.JTextField txtPrice;
private javax.swing.JTextField txtRoomID;
private javax.swing.JTextField txtRoomName;
// End of variables declaration//GEN-END:variables
}
| 28,359 | 0.580332 | 0.567987 | 602 | 46.094685 | 35.098572 | 184 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.684385 | false | false |
14
|
2c5f6dbff185be2776f0d5878bcb12f837a6e203
| 18,485,539,266,007 |
0f4983a35ec136179bafb84012c5477225d1240e
|
/src/main/java/com/deo/stark/base/vo/PageVO.java
|
680acde0335a2914b2912f15a5f38714c73a29f1
|
[
"MIT"
] |
permissive
|
deo-prime/stark
|
https://github.com/deo-prime/stark
|
3e83643fb2653fd949bdf5a7f4543c4437030d5d
|
88c1f74625f17c2b0f53c9b4b14001a7ebd0cb83
|
refs/heads/master
| 2022-12-22T13:15:58.235000 | 2020-04-01T01:23:54 | 2020-04-01T01:23:54 | 228,861,507 | 0 | 0 |
MIT
| false | 2022-12-16T09:44:41 | 2019-12-18T14:50:13 | 2020-04-01T01:24:01 | 2022-12-16T09:44:38 | 12,483 | 0 | 0 | 8 |
JavaScript
| false | false |
package com.deo.stark.base.vo;
import java.io.Serializable;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class PageVO<T> implements Serializable {
/**
*
*/
private static final long serialVersionUID = -1767789312937770931L;
private List<T> data;
private Long total;
private Long index;
private Integer pageSize;
private Integer pageNo;
}
|
UTF-8
|
Java
| 531 |
java
|
PageVO.java
|
Java
|
[] | null |
[] |
package com.deo.stark.base.vo;
import java.io.Serializable;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class PageVO<T> implements Serializable {
/**
*
*/
private static final long serialVersionUID = -1767789312937770931L;
private List<T> data;
private Long total;
private Long index;
private Integer pageSize;
private Integer pageNo;
}
| 531 | 0.741996 | 0.706215 | 27 | 17.666666 | 16.085421 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.814815 | false | false |
14
|
479cd19ff48592c7715efc00f6081742682723e9
| 33,827,162,435,766 |
ac4ae5e7c04b6e9c52ec563a4ebe2d8391df4ae9
|
/Part-4 Spring Boot REST API/SpringJerseyJPA/src/main/java/spring/database/controller/JobResource.java
|
06a5f4bd961fda7c92330baf3d0355151ed5d2a5
|
[] |
no_license
|
Hamdambek/Spring-Boot-Projects
|
https://github.com/Hamdambek/Spring-Boot-Projects
|
e8db33946f4bd462184052f48bbee4f274dace49
|
a060f8189e86d8655b662f6b69e06afe1a402f07
|
refs/heads/master
| 2021-01-04T19:15:09.047000 | 2021-01-04T09:01:22 | 2021-01-04T09:01:22 | 240,722,764 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package spring.database.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import spring.database.exception.ResourceNotFoundException;
import spring.database.model.Job;
import spring.database.repository.JobRepository;
import javax.validation.Valid;
import javax.ws.rs.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @Author: apple
* @created on 01/04/2020
* @Project is SpringJerseyJPA
*/
@Component
@Path("/api/")
public class JobResource {
//
@Autowired
private JobRepository jobRepository;
@GET
@Produces("application/json")
@Path("/jobs")
public List<Job> getAllJobs(){
return jobRepository.findAll();
}
@GET
@Produces("application/json")
@Path("/jobs")
public ResponseEntity<Job> getJobById(@PathVariable(value = "id") Long jobId) throws ResourceNotFoundException{
Job job = jobRepository.findById(jobId)
.orElseThrow(()-> new ResourceNotFoundException("Job not found ::" + jobId));
return ResponseEntity.ok().body(job);
}
@POST
@Produces("appliction/json")
@Consumes("application/json")
@Path("/jobs")
@PostMapping("/jobs")
public Job createJob(Job job){
return jobRepository.save(job);
}
@PUT
@Consumes("application/json")
@Path("/jobs/{id}")
public ResponseEntity<Job> updateJob(@PathParam(value = "id") Long jobId, @Valid @RequestBody Job jobDetails) throws ResourceNotFoundException {
Job job = jobRepository.findById(jobId)
.orElseThrow(()->new ResourceNotFoundException("Job not found::" + jobId));
job.setEmailId(jobDetails.getEmailId());
job.setLastName(jobDetails.getLastName());
job.setFirstName(jobDetails.getFirstName());
final Job updateJob = jobRepository.save(job);
return ResponseEntity.ok(updateJob);
}
@DELETE
@Path("/jobs/{id}")
public Map<String, Boolean> deleteJob (@PathParam(value = "id") Long jobId) throws ResourceNotFoundException{
Job job = jobRepository.findById(jobId)
.orElseThrow(()-> new ResourceNotFoundException("User not found::" + jobId));
jobRepository.delete(job);
Map<String, Boolean> response = new HashMap<>();
response.put("deleted", Boolean.FALSE);
return response;
}
}
|
UTF-8
|
Java
| 2,651 |
java
|
JobResource.java
|
Java
|
[
{
"context": ".util.List;\nimport java.util.Map;\n\n/**\n * @Author: apple\n * @created on 01/04/2020\n * @Project is SpringJe",
"end": 668,
"score": 0.9958613514900208,
"start": 663,
"tag": "USERNAME",
"value": "apple"
}
] | null |
[] |
package spring.database.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import spring.database.exception.ResourceNotFoundException;
import spring.database.model.Job;
import spring.database.repository.JobRepository;
import javax.validation.Valid;
import javax.ws.rs.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @Author: apple
* @created on 01/04/2020
* @Project is SpringJerseyJPA
*/
@Component
@Path("/api/")
public class JobResource {
//
@Autowired
private JobRepository jobRepository;
@GET
@Produces("application/json")
@Path("/jobs")
public List<Job> getAllJobs(){
return jobRepository.findAll();
}
@GET
@Produces("application/json")
@Path("/jobs")
public ResponseEntity<Job> getJobById(@PathVariable(value = "id") Long jobId) throws ResourceNotFoundException{
Job job = jobRepository.findById(jobId)
.orElseThrow(()-> new ResourceNotFoundException("Job not found ::" + jobId));
return ResponseEntity.ok().body(job);
}
@POST
@Produces("appliction/json")
@Consumes("application/json")
@Path("/jobs")
@PostMapping("/jobs")
public Job createJob(Job job){
return jobRepository.save(job);
}
@PUT
@Consumes("application/json")
@Path("/jobs/{id}")
public ResponseEntity<Job> updateJob(@PathParam(value = "id") Long jobId, @Valid @RequestBody Job jobDetails) throws ResourceNotFoundException {
Job job = jobRepository.findById(jobId)
.orElseThrow(()->new ResourceNotFoundException("Job not found::" + jobId));
job.setEmailId(jobDetails.getEmailId());
job.setLastName(jobDetails.getLastName());
job.setFirstName(jobDetails.getFirstName());
final Job updateJob = jobRepository.save(job);
return ResponseEntity.ok(updateJob);
}
@DELETE
@Path("/jobs/{id}")
public Map<String, Boolean> deleteJob (@PathParam(value = "id") Long jobId) throws ResourceNotFoundException{
Job job = jobRepository.findById(jobId)
.orElseThrow(()-> new ResourceNotFoundException("User not found::" + jobId));
jobRepository.delete(job);
Map<String, Boolean> response = new HashMap<>();
response.put("deleted", Boolean.FALSE);
return response;
}
}
| 2,651 | 0.691437 | 0.688419 | 81 | 31.728395 | 29.075895 | 148 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.432099 | false | false |
14
|
1e68ff2b99e03e74f5597404a0fde8d3e6ca9625
| 936,302,929,029 |
74cc798bdc0d5ae4cba31aa29ee17a7ca40545ca
|
/unit_test/unit_test_demo/src/test/java/ccc/jmockit/Mocking/E_3_5_Recording_results_for_an_expectation.java
|
047ad243cd8128545f5db85e29ba9100de011f2f
|
[] |
no_license
|
chen2526264/A_GitRepository
|
https://github.com/chen2526264/A_GitRepository
|
2cfd5bc9c6fc4def55a0acbdc9d6a5d733b460bb
|
f61cc202a75b10f323d21e354abe0ce039c27b29
|
refs/heads/master
| 2018-12-21T07:21:45.274000 | 2018-12-17T00:59:23 | 2018-12-17T00:59:23 | 50,508,416 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ccc.jmockit.Mocking;
import ccc.jmockit.ClassUnderTest;
import ccc.jmockit.DependencyAbc;
import ccc.jmockit.SomeCheckedException;
import mockit.Expectations;
import mockit.Mocked;
import mockit.Tested;
import org.junit.Test;
/**
* 通过在Expectations块中为result属性赋值,可以录制需要返回的值。
* 如果需要mock的方法需要抛出异常,只需要为result赋值一个异常即可,这种方法同样适用于构造函数。
*
* 可以使用 returns(v1, v2, ...) 为一个方法指定多个返回值,这些返回值会在该方法被依次调用的时候返回。
* 比如下面的例子,abc.stringReturningMethod()方法被第一、二、三次调用的时候,分别会返回"str1", "str2"和
* 抛出SomeCheckedException异常。
*
* 还要注意一点:本例中方法参数"DependencyAbc abc"是使用 @Mocked 进行mock的,那么它并不会被注入到任何 @Tested 的实例中。
* 但是在 ClassUnderTest 类的内部,是直接使用 new 关键字创建的 DependencyAbc 实例,由于 @Mocked 注解会把标记的类的所有已经
* 存在的实例,或者将来创建的实例进行mock,所以该例中 ClassUnderTest 类中就可以正确的拿到 DependencyAbc 的实例。
*/
public class E_3_5_Recording_results_for_an_expectation {
@Tested
ClassUnderTest classUnderTest;
@Test
public void doSomethingHandlesSomeCheckedException(@Mocked DependencyAbc abc) throws Exception {
new Expectations() {{
abc.intReturningMethod();
result = 3;
abc.stringReturningMethod();
returns("str1", "str2");
result = new SomeCheckedException();
}};
classUnderTest.doSomething();
}
}
|
UTF-8
|
Java
| 1,754 |
java
|
E_3_5_Recording_results_for_an_expectation.java
|
Java
|
[] | null |
[] |
package ccc.jmockit.Mocking;
import ccc.jmockit.ClassUnderTest;
import ccc.jmockit.DependencyAbc;
import ccc.jmockit.SomeCheckedException;
import mockit.Expectations;
import mockit.Mocked;
import mockit.Tested;
import org.junit.Test;
/**
* 通过在Expectations块中为result属性赋值,可以录制需要返回的值。
* 如果需要mock的方法需要抛出异常,只需要为result赋值一个异常即可,这种方法同样适用于构造函数。
*
* 可以使用 returns(v1, v2, ...) 为一个方法指定多个返回值,这些返回值会在该方法被依次调用的时候返回。
* 比如下面的例子,abc.stringReturningMethod()方法被第一、二、三次调用的时候,分别会返回"str1", "str2"和
* 抛出SomeCheckedException异常。
*
* 还要注意一点:本例中方法参数"DependencyAbc abc"是使用 @Mocked 进行mock的,那么它并不会被注入到任何 @Tested 的实例中。
* 但是在 ClassUnderTest 类的内部,是直接使用 new 关键字创建的 DependencyAbc 实例,由于 @Mocked 注解会把标记的类的所有已经
* 存在的实例,或者将来创建的实例进行mock,所以该例中 ClassUnderTest 类中就可以正确的拿到 DependencyAbc 的实例。
*/
public class E_3_5_Recording_results_for_an_expectation {
@Tested
ClassUnderTest classUnderTest;
@Test
public void doSomethingHandlesSomeCheckedException(@Mocked DependencyAbc abc) throws Exception {
new Expectations() {{
abc.intReturningMethod();
result = 3;
abc.stringReturningMethod();
returns("str1", "str2");
result = new SomeCheckedException();
}};
classUnderTest.doSomething();
}
}
| 1,754 | 0.73132 | 0.724165 | 40 | 30.450001 | 26.595066 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
14
|
6d75a45696d051fa0ad5b3a0b4aa756e40820d7d
| 18,227,841,260,599 |
206deb561f9fb893fb22241f9af44ce5b797b549
|
/EMailMessage.java
|
911c45c04f87811d2080bce241ffe45f0f32fd7c
|
[] |
no_license
|
IvanGospodinov97/Java
|
https://github.com/IvanGospodinov97/Java
|
d683dac6cb8f5a328037c3198658e8d6374fcb12
|
ad7016190a3e1dc4e2eac016bc7cf4a29dc1173f
|
refs/heads/master
| 2020-05-02T09:00:59.140000 | 2019-03-26T19:54:39 | 2019-03-26T19:54:39 | 177,858,231 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package bg.tyvarna.java;
public abstract class EMailMessage {
protected String strEMailMessage;
public EMailMessage() {
this.strEMailMessage = "Unknown";
}
public EMailMessage(String strEMailMessage) {
this.strEMailMessage = strEMailMessage;
}
public abstract void setEMailMessage(String mess);
public abstract String getEMailMessage();
}
|
UTF-8
|
Java
| 409 |
java
|
EMailMessage.java
|
Java
|
[] | null |
[] |
package bg.tyvarna.java;
public abstract class EMailMessage {
protected String strEMailMessage;
public EMailMessage() {
this.strEMailMessage = "Unknown";
}
public EMailMessage(String strEMailMessage) {
this.strEMailMessage = strEMailMessage;
}
public abstract void setEMailMessage(String mess);
public abstract String getEMailMessage();
}
| 409 | 0.674817 | 0.674817 | 19 | 19.526316 | 20.530769 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.315789 | false | false |
14
|
f7925ced0be6b03f79d1a64e939b9c2b786c7406
| 12,902,081,824,088 |
4f4fa2183ed1b5ad80403d289f42295ac640e505
|
/src/lhvote/controller/qnaBoard/QnaBoardListController.java
|
ed1e0d4bdad5f979dc95147131a177bc2980af3e
|
[] |
no_license
|
cheolhyeonpark/lhvote
|
https://github.com/cheolhyeonpark/lhvote
|
079e4a807c42daa864cd077efac81e0b1322c041
|
b05d633b1b5d84c3cc06f13467f83e03a85e3e06
|
refs/heads/master
| 2020-05-07T22:48:58.752000 | 2019-04-12T08:43:46 | 2019-04-12T08:43:46 | 180,961,741 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package lhvote.controller.qnaBoard;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lhvote.controller.Controller;
import lhvote.impl.DefaultQnaBoardService;
import lhvote.model.QnaBoard;
import lhvote.service.QnaBoardService;
public class QnaBoardListController implements Controller {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response, Connection connection)
throws ServletException, IOException {
int page = 1;
if (request.getParameter("page") != null) {
page = Integer.parseInt(request.getParameter("page"));
}
QnaBoardService qnaBoardService = new DefaultQnaBoardService(connection);
List<QnaBoard> list = qnaBoardService.selectList(page);
PrintWriter out = response.getWriter();
out.write(convertListToJson(list));
}
private String convertListToJson(List<QnaBoard> list) {
String json = "{\"list\":[";
for (QnaBoard qnaBoard : list) {
json += "{" + "\"qnaIsAnswered" + "\" : \"" + qnaBoard.isAnswerdQna() + "\"," + "\"qnaNo" + "\" : \""
+ qnaBoard.getQnaNo() + "\"," + "\"qnaTitle" + "\" : \"" + qnaBoard.getQnaTitle() + "\","
+ "\"qnaDate" + "\" : \"" + qnaBoard.getQnaDate() + "\"," + "\"qnaIsOpened" + "\" : \""
+ qnaBoard.isOpenedQna() + "\"," + "\"qnaPassword" + "\" : \"" + qnaBoard.getQnaPassword() + "\","
+ "\"qnaQuestion" + "\" : \"" + qnaBoard.getQnaQuestion().replaceAll("\n", "") + "\"," + "\"qnaAnswer" + "\" : \""
+ qnaBoard.getQnaAnswer() + "\"},";
}
return json.substring(0,json.length()-1) + "]}";
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response, Connection connection)
throws ServletException, IOException {
}
}
|
UTF-8
|
Java
| 1,884 |
java
|
QnaBoardListController.java
|
Java
|
[] | null |
[] |
package lhvote.controller.qnaBoard;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lhvote.controller.Controller;
import lhvote.impl.DefaultQnaBoardService;
import lhvote.model.QnaBoard;
import lhvote.service.QnaBoardService;
public class QnaBoardListController implements Controller {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response, Connection connection)
throws ServletException, IOException {
int page = 1;
if (request.getParameter("page") != null) {
page = Integer.parseInt(request.getParameter("page"));
}
QnaBoardService qnaBoardService = new DefaultQnaBoardService(connection);
List<QnaBoard> list = qnaBoardService.selectList(page);
PrintWriter out = response.getWriter();
out.write(convertListToJson(list));
}
private String convertListToJson(List<QnaBoard> list) {
String json = "{\"list\":[";
for (QnaBoard qnaBoard : list) {
json += "{" + "\"qnaIsAnswered" + "\" : \"" + qnaBoard.isAnswerdQna() + "\"," + "\"qnaNo" + "\" : \""
+ qnaBoard.getQnaNo() + "\"," + "\"qnaTitle" + "\" : \"" + qnaBoard.getQnaTitle() + "\","
+ "\"qnaDate" + "\" : \"" + qnaBoard.getQnaDate() + "\"," + "\"qnaIsOpened" + "\" : \""
+ qnaBoard.isOpenedQna() + "\"," + "\"qnaPassword" + "\" : \"" + qnaBoard.getQnaPassword() + "\","
+ "\"qnaQuestion" + "\" : \"" + qnaBoard.getQnaQuestion().replaceAll("\n", "") + "\"," + "\"qnaAnswer" + "\" : \""
+ qnaBoard.getQnaAnswer() + "\"},";
}
return json.substring(0,json.length()-1) + "]}";
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response, Connection connection)
throws ServletException, IOException {
}
}
| 1,884 | 0.679936 | 0.678344 | 50 | 36.68 | 32.872749 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.08 | false | false |
14
|
9a29174f28ad4178f09bf4f729b5ff18bfed600d
| 558,345,786,623 |
164da08476a37dcdc961cdda0c9ef179b1a2c3f7
|
/translation/src/com/gdxz/zhongbao/client/utils/SpUtils.java
|
6dfc3d0eb96d4ed1b40c8add293bd16d04d5ea80
|
[
"Apache-2.0"
] |
permissive
|
jiandaima/Translation
|
https://github.com/jiandaima/Translation
|
56081573837a6fbde4830d49d8a4e9de71c56f68
|
bfe36427c586c6caca9b6079a0b975f68366acd9
|
refs/heads/master
| 2021-01-22T13:13:16.969000 | 2016-02-16T08:25:35 | 2016-02-16T08:25:35 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.gdxz.zhongbao.client.utils;
import android.content.Context;
import android.content.SharedPreferences;
import java.util.HashSet;
import java.util.Set;
/**
* Created by chenantao on 2015/6/29.
*/
public class SpUtils
{
//存储当前登录用户的id的文件名
public static final String DEFAULT_FILE_NAME = "currentUser";
/**
* 设置属性根据指定的文件名
*
* @param context
* @param key
* @param value
* @param fileName
*/
public static void setStringProperty(Context context, String key, String value, String fileName)
{
SharedPreferences.Editor editor = context.getSharedPreferences(fileName, context.MODE_PRIVATE).edit();
editor.putString(key, value);
editor.commit();
}
/**
* 设置字符串属性根据默认的文件名
*
* @param context
* @param key
* @param value
*/
public static void setStringProperty(Context context, String key, String value)
{
SharedPreferences.Editor editor = context.getSharedPreferences(DEFAULT_FILE_NAME, context.MODE_PRIVATE).edit();
editor.putString(key, value);
editor.commit();
}
/**
* 设置字符串的set集合根据默认的文件名
*
* @param context
* @param key
* @param set
*/
public static void setStringSetProperty(Context context, String key, Set<String> set)
{
SharedPreferences.Editor editor = context.getSharedPreferences(DEFAULT_FILE_NAME, context.MODE_PRIVATE).edit();
editor.putStringSet(key, set);
editor.commit();
}
/**
* 设置字符串的set集合根据指定的文件名
*
* @param context
* @param key
* @param set
*/
public static void setStringSetProperty(Context context,String key, Set<String> set, String fileName)
{
SharedPreferences.Editor editor = context.getSharedPreferences(fileName, context.MODE_PRIVATE).edit();
editor.putStringSet(key, set);
editor.commit();
}
/**
* 根据key从指定的文件中获取字符串值
*
* @param context
* @param key
* @param fileName
* @return
*/
public static String getStringProperty(Context context, String key, String fileName)
{
SharedPreferences sp = context.getSharedPreferences(fileName, context.MODE_PRIVATE);
return sp.getString(key, "");
}
/**
* 根据key从默认的文件中获取字符串值
*
* @param context
* @param key
* @return
*/
public static String getStringProperty(Context context, String key)
{
SharedPreferences sp = context.getSharedPreferences(DEFAULT_FILE_NAME, context.MODE_PRIVATE);
return sp.getString(key, "");
}
/**
* 根据key从默认的文件中获取字符串集合
*
* @param context
* @param key
* @return
*/
public static Set<String> getStringSetProperty(Context context, String key)
{
SharedPreferences sp = context.getSharedPreferences(DEFAULT_FILE_NAME, context.MODE_PRIVATE);
return sp.getStringSet(key, null);
}
/**
* 根据key从指定的文件中获取字符串集合
*
* @param context
* @param key
* @return
*/
public static Set<String> getStringSetProperty(Context context, String key, String fileName)
{
SharedPreferences sp = context.getSharedPreferences(fileName, context.MODE_PRIVATE);
return sp.getStringSet(key, new HashSet<String>());
}
}
|
UTF-8
|
Java
| 3,219 |
java
|
SpUtils.java
|
Java
|
[
{
"context": ".HashSet;\nimport java.util.Set;\n\n/**\n * Created by chenantao on 2015/6/29.\n */\npublic class SpUtils\n{\n\t//存储当前登",
"end": 192,
"score": 0.9994714856147766,
"start": 183,
"tag": "USERNAME",
"value": "chenantao"
}
] | null |
[] |
package com.gdxz.zhongbao.client.utils;
import android.content.Context;
import android.content.SharedPreferences;
import java.util.HashSet;
import java.util.Set;
/**
* Created by chenantao on 2015/6/29.
*/
public class SpUtils
{
//存储当前登录用户的id的文件名
public static final String DEFAULT_FILE_NAME = "currentUser";
/**
* 设置属性根据指定的文件名
*
* @param context
* @param key
* @param value
* @param fileName
*/
public static void setStringProperty(Context context, String key, String value, String fileName)
{
SharedPreferences.Editor editor = context.getSharedPreferences(fileName, context.MODE_PRIVATE).edit();
editor.putString(key, value);
editor.commit();
}
/**
* 设置字符串属性根据默认的文件名
*
* @param context
* @param key
* @param value
*/
public static void setStringProperty(Context context, String key, String value)
{
SharedPreferences.Editor editor = context.getSharedPreferences(DEFAULT_FILE_NAME, context.MODE_PRIVATE).edit();
editor.putString(key, value);
editor.commit();
}
/**
* 设置字符串的set集合根据默认的文件名
*
* @param context
* @param key
* @param set
*/
public static void setStringSetProperty(Context context, String key, Set<String> set)
{
SharedPreferences.Editor editor = context.getSharedPreferences(DEFAULT_FILE_NAME, context.MODE_PRIVATE).edit();
editor.putStringSet(key, set);
editor.commit();
}
/**
* 设置字符串的set集合根据指定的文件名
*
* @param context
* @param key
* @param set
*/
public static void setStringSetProperty(Context context,String key, Set<String> set, String fileName)
{
SharedPreferences.Editor editor = context.getSharedPreferences(fileName, context.MODE_PRIVATE).edit();
editor.putStringSet(key, set);
editor.commit();
}
/**
* 根据key从指定的文件中获取字符串值
*
* @param context
* @param key
* @param fileName
* @return
*/
public static String getStringProperty(Context context, String key, String fileName)
{
SharedPreferences sp = context.getSharedPreferences(fileName, context.MODE_PRIVATE);
return sp.getString(key, "");
}
/**
* 根据key从默认的文件中获取字符串值
*
* @param context
* @param key
* @return
*/
public static String getStringProperty(Context context, String key)
{
SharedPreferences sp = context.getSharedPreferences(DEFAULT_FILE_NAME, context.MODE_PRIVATE);
return sp.getString(key, "");
}
/**
* 根据key从默认的文件中获取字符串集合
*
* @param context
* @param key
* @return
*/
public static Set<String> getStringSetProperty(Context context, String key)
{
SharedPreferences sp = context.getSharedPreferences(DEFAULT_FILE_NAME, context.MODE_PRIVATE);
return sp.getStringSet(key, null);
}
/**
* 根据key从指定的文件中获取字符串集合
*
* @param context
* @param key
* @return
*/
public static Set<String> getStringSetProperty(Context context, String key, String fileName)
{
SharedPreferences sp = context.getSharedPreferences(fileName, context.MODE_PRIVATE);
return sp.getStringSet(key, new HashSet<String>());
}
}
| 3,219 | 0.716028 | 0.713656 | 128 | 22.054688 | 29.37854 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.421875 | false | false |
14
|
cbeac83005cedc3c2132542dacb0e3aa73c0ef69
| 10,505,490,034,544 |
6cc2f47d8e0f3eb482e5566045a6135d6d3289e5
|
/gs-rest-service/src/main/java/spring/guides/hello/GreetingApplication.java
|
654f97092a28aa5022ada9dcac9b538d0ae315d5
|
[] |
no_license
|
EdwardLee03/spring-guides
|
https://github.com/EdwardLee03/spring-guides
|
86f5eca007b800df195adf3273b2475b8e133865
|
7cd726afd33544e20862163725e6038db5f1baf7
|
refs/heads/master
| 2021-05-04T10:00:37.325000 | 2021-04-17T19:10:09 | 2021-04-17T19:10:09 | 79,807,895 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package spring.guides.hello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* 问候应用入口点。
*
* <p>Make the application executable.
*
* @author dannong
* @since 2017年01月30日 09:47
*/
@SpringBootApplication // = @SpringBootConfiguration/@Configuration + @EnableAutoConfiguration + @ComponentScan
@SuppressWarnings("startup-enter-point")
public class GreetingApplication {
public static void main(String[] args) {
SpringApplication.run(GreetingApplication.class, args);
}
}
|
UTF-8
|
Java
| 592 |
java
|
GreetingApplication.java
|
Java
|
[
{
"context": " <p>Make the application executable.\n *\n * @author dannong\n * @since 2017年01月30日 09:47\n */\n@SpringBootApplic",
"end": 230,
"score": 0.9994840621948242,
"start": 223,
"tag": "USERNAME",
"value": "dannong"
}
] | null |
[] |
package spring.guides.hello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* 问候应用入口点。
*
* <p>Make the application executable.
*
* @author dannong
* @since 2017年01月30日 09:47
*/
@SpringBootApplication // = @SpringBootConfiguration/@Configuration + @EnableAutoConfiguration + @ComponentScan
@SuppressWarnings("startup-enter-point")
public class GreetingApplication {
public static void main(String[] args) {
SpringApplication.run(GreetingApplication.class, args);
}
}
| 592 | 0.761404 | 0.740351 | 22 | 24.90909 | 28.532133 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.227273 | false | false |
14
|
2201b211a22a039756dca966d806bb3632fcd61d
| 13,821,204,821,048 |
6183176c32678d9aa4512dfe1f42d011ca8d6889
|
/src/main/java/br/com/mgdev/jwt/controller/AuthController.java
|
b88308b0d30cc233f56a973a40cbb3caced22321
|
[] |
no_license
|
devmgsouza/SegurancaComJWT
|
https://github.com/devmgsouza/SegurancaComJWT
|
d0f38bfee39861f1581bad6230f578c4b1cf8be9
|
60870d4d58e230e51930314198b4ea4a127176c1
|
refs/heads/master
| 2020-12-26T13:44:53.920000 | 2020-03-25T12:02:30 | 2020-03-25T12:02:30 | 237,528,658 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package br.com.mgdev.jwt.controller;
import java.util.Collections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
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 br.com.mgdev.jwt.security.entity.UserAuthentication;
import br.com.mgdev.jwt.security.jwt.JwtCustomAuthenticationProvider;
import br.com.mgdev.jwt.security.jwt.JwtTokenUtil;
@RestController
@RequestMapping("/api/auth")
public class AuthController {
@Autowired
private JwtCustomAuthenticationProvider jwtCustomAuthenticationProvider;
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private JwtTokenUtil jwtTokenUtil;
/*
*
* Metodo Responsável por receber o usuário e senha
* e fazer as chamadas para gerar o token de authenticação
*
*/
@PostMapping
public String getToken(@RequestBody UserAuthentication userAuthentication) {
final Authentication authentication = jwtCustomAuthenticationProvider.authenticate(
new UsernamePasswordAuthenticationToken(
userAuthentication.getUsername(),
userAuthentication.getPassword(),
Collections.emptyList()
)
);
SecurityContextHolder.getContext().setAuthentication(authentication);
final UserDetails userDetails = userDetailsService.loadUserByUsername(userAuthentication.getUsername());
final String token = jwtTokenUtil.generateToken(userDetails);
return token;
}
}
|
UTF-8
|
Java
| 1,977 |
java
|
AuthController.java
|
Java
|
[] | null |
[] |
package br.com.mgdev.jwt.controller;
import java.util.Collections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
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 br.com.mgdev.jwt.security.entity.UserAuthentication;
import br.com.mgdev.jwt.security.jwt.JwtCustomAuthenticationProvider;
import br.com.mgdev.jwt.security.jwt.JwtTokenUtil;
@RestController
@RequestMapping("/api/auth")
public class AuthController {
@Autowired
private JwtCustomAuthenticationProvider jwtCustomAuthenticationProvider;
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private JwtTokenUtil jwtTokenUtil;
/*
*
* Metodo Responsável por receber o usuário e senha
* e fazer as chamadas para gerar o token de authenticação
*
*/
@PostMapping
public String getToken(@RequestBody UserAuthentication userAuthentication) {
final Authentication authentication = jwtCustomAuthenticationProvider.authenticate(
new UsernamePasswordAuthenticationToken(
userAuthentication.getUsername(),
userAuthentication.getPassword(),
Collections.emptyList()
)
);
SecurityContextHolder.getContext().setAuthentication(authentication);
final UserDetails userDetails = userDetailsService.loadUserByUsername(userAuthentication.getUsername());
final String token = jwtTokenUtil.generateToken(userDetails);
return token;
}
}
| 1,977 | 0.810948 | 0.810948 | 63 | 30.301588 | 29.969633 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.714286 | false | false |
14
|
a9985cc231143d4b7e4cf96f8b0aeb1d48c5233a
| 23,347,442,277,007 |
2ef9ac68bb2e252ed1478e7c6f428e638b18484c
|
/src/main/java/com/murali/me/model/dto/OrderType.java
|
334c098928498470c5841192fdb09998f75bfb3f
|
[] |
no_license
|
muraliweb9/silver-bars
|
https://github.com/muraliweb9/silver-bars
|
2bdae337642c099d9639470b6891263a5c7ee1dc
|
933872ccc090743d7b41723f73db65aa63f247a4
|
refs/heads/master
| 2020-07-17T20:03:33.111000 | 2019-09-12T15:25:13 | 2019-09-12T15:25:13 | 206,088,798 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.murali.me.model.dto;
/**
* Defines the types of orders handled by the system
*
* @author murali
*
*/
public enum OrderType {
BUY,
SELL;
}
|
UTF-8
|
Java
| 159 |
java
|
OrderType.java
|
Java
|
[
{
"context": "pes of orders handled by the system\n * \n * @author murali\n *\n */\npublic enum OrderType {\n\tBUY,\n\tSELL;\n}\n",
"end": 112,
"score": 0.965338408946991,
"start": 106,
"tag": "USERNAME",
"value": "murali"
}
] | null |
[] |
package com.murali.me.model.dto;
/**
* Defines the types of orders handled by the system
*
* @author murali
*
*/
public enum OrderType {
BUY,
SELL;
}
| 159 | 0.660377 | 0.660377 | 12 | 12.25 | 15.379233 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.416667 | false | false |
14
|
05d5aff780cfbc3418b24c25c136ef59aa05863e
| 1,735,166,835,258 |
5b676944ca7320d7bc50be47017abf1f83b2ccd6
|
/src/pl/ceski23/Main.java
|
5b2d2cf590b9b38e94bb6786da21a1e059150aa2
|
[] |
no_license
|
ceski23/SchoolBreaker
|
https://github.com/ceski23/SchoolBreaker
|
95de9b3b636c6375b96c75640811dabddc6d8b44
|
7ed2e1b156150548dbae2bc11d44bcdb465e85be
|
refs/heads/master
| 2020-06-12T18:43:38.317000 | 2017-10-15T09:02:22 | 2017-10-15T09:02:22 | 75,773,126 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package pl.ceski23;
import org.apache.commons.lang3.math.NumberUtils;
import pl.ceski23.listeners.InputValidationListener;
import pl.ceski23.models.EventOption;
import pl.ceski23.models.OptionCondition;
import java.util.List;
import java.util.Scanner;
public class Main {
static int TURNS_LEFT = 10;
static String NEXT_EVENT_ID = null;
static boolean GAME_OVER = false;
static int PRINT_DELAY = 20;
public static void main(String[] args) {
if (args.length > 0 && args[0].equals("-godmode")) {
Stats.FLAIR.setValue(999);
Stats.HP.setValue(999);
Stats.SATISFACTION.setValue(999);
Stats.INTELLIGENCE.setValue(999);
Stats.MONEY.setValue(999);
}
if (args.length > 0 && args[0].equals("-speed")) {
PRINT_DELAY = Integer.parseInt(args[1]);
}
Scanner scanner = new Scanner(System.in);
UIUtils.showStartupMenu();
UIUtils.showIntroduction();
EventsManager.loadEvents(() -> {
while (TURNS_LEFT > 0 && !GAME_OVER) {
if (NEXT_EVENT_ID == null) {
EventsManager.startRandomEvent();
} else {
EventsManager.startEvent(NEXT_EVENT_ID, true);
NEXT_EVENT_ID = null;
}
String input = scanner.next();
while (!isInputValid(input, System.out::println) && !GAME_OVER) {
System.out.print(" => Wybieram: ");
input = scanner.next();
}
if (!GAME_OVER) EventsManager.endEvent(Integer.valueOf(input) - 1);
}
if (Stats.HP.getValue() <= 0) {
UIUtils.showDeathMessage();
}
if (GAME_OVER) {
UIUtils.showStatistics();
UIUtils.showEndMessage();
}
if (TURNS_LEFT == 0) {
System.out.println();
UIUtils.showStatistics();
System.out.println("\n ────────────────────────────────[ MATURA ]────────────────────────────────\n");
UIUtils.printText("Nadszedł ten ważny dzień egzaminu. Wstajesz o poranku i już czujesz narastający stres. No, ale niestety trzeba iść. Po drodze do szkoły zastanawiasz się, czy aby na pewno wszystko powtórzyłaś. Masz wrażenie jakby w jednym momencie wszystkie twoje wiadomości zniknęły, ale nie panikuj to tylko stres. Uspokajasz się, gdy docierasz do szkoły. Wchodzisz do sali. Teraz wszystko zależy od tego jakie decyzje podejmowałaś. Zobaczmy, co się stanie...\n\n");
if (Stats.INTELLIGENCE.getValue() >= 15) {
UIUtils.printText("Widzisz przed sobą test. Pytania wydają ci się banalne. Robisz jedno za drugim jak w transie. Ale nie tak szybko, jednak pojawia się jeden mały problem. Nie jesteś pewna jednej odpowiedzi. Co robisz?\n\n");
System.out.println(" [1] Zdajesz się na swoją intuicję");
System.out.println(" [2] Postanawiasz odpisać odpowiedź od kolegi");
System.out.println(" [3] Poświęcasz bardzo dużo czasu na ponowne rozwiązanie tego zadania");
System.out.print("\n => Wybieram: ");
String input = scanner.next();
while (true) {
if (NumberUtils.isCreatable(input)) {
int number = Integer.parseInt(input);
if (number > 0 && number < 4) break;
}
System.out.print(" => Wybieram: ");
input = scanner.next();
}
switch (input) {
case "1":
UIUtils.printText("\nPrzecież jesteś kobietą, a kobieca intuicja nigdy cię nie zawiodła.\n");
if (Stats.SATISFACTION.getValue() >= 6) {
UIUtils.printText("Udało ci się! Możesz spokojnie oddać kartkę, ale na wyniki niestety i tak trzeba będzie poczekać.");
}
else {
UIUtils.printText("Niestety, po oddaniu kartki czujesz, że twoja intuicja cię zawiodła. Niestety nie miałaś innego pomysłu. Teraz pozostaje tylko czekać.");
}
break;
case "2":
UIUtils.printText("\n");
if (Stats.FLAIR.getValue() >= 10) {
UIUtils.printText("Uff... Udało ci się odpisać i nikt się nie zorientował, jak to dobrze! Oddajesz kartkę z ulgą na twarzy i wiesz, że będzie dobrze.");
}
else {
UIUtils.printText("Niestety nie udało się. Nie dałaś rady zauważyć odpowiedzi kolegi, więc musisz strzelać. Zobaczymy czy ci się udało.");
}
break;
case "3":
UIUtils.printText("\nMyślisz i głowisz się jeszcze raz nad tym zadaniem, ale nie możesz nic wymyśleć. Tracisz bardzo dużo czasu, przez co strzelasz i przechodzisz do następnych zadań, bo możesz się nie wyrobić. Na szczęście udało ci się ukończyć egzamin na czas.");
break;
}
}
else {
UIUtils.printText("Widzisz przed sobą test i już wiesz, że to będą ciężkie 2 h. Niestety niewiele pamiętasz. Próbujesz robić zadania. Jedne ci wychodzą, inne nie. Niestety zdecydowana większość jest tych, które nie wychodzą. Zaczynasz się denerwować. No, ale dobrze coś trzeba napisać. Co robisz?\n\n");
System.out.println(" [1] Zdajesz się na swoją intuicję");
System.out.println(" [2] Postanawiasz odpisać odpowiedź od kolegi");
System.out.println(" [3] Próbujesz coś jeszcze wymyślić");
System.out.print("\n => Wybieram: ");
String input = scanner.next();
while (true) {
if (NumberUtils.isCreatable(input)) {
int number = Integer.parseInt(input);
if (number > 0 && number < 4) break;
}
System.out.print(" => Wybieram: ");
input = scanner.next();
}
switch (input) {
case "1":
UIUtils.printText("\nPrzecież jesteś kobietą, a kobieca intuicja nigdy cię nie zawiodła.\n");
if (Stats.SATISFACTION.getValue() >= 6) {
UIUtils.printText("Udało ci się w większości zadań. Możesz oddać kartkę, ale na wyniki niestety i tak trzeba będzie poczekać");
}
else {
UIUtils.printText("Niestety, po oddaniu kartki czujesz, że twoja intuicja cię zawiodła. Niestety nie miałaś innego pomysłu. Teraz pozostaje tylko czekać.");
}
break;
case "2":
UIUtils.printText("\n");
if (Stats.FLAIR.getValue() >= 10) {
UIUtils.printText("Uff... Udało ci się odpisać i nikt się nie zorientował, jak to dobrze! Oddajesz kartkę z ulgą na twarzy i masz nadzieję, że odpisałaś od odpowiedniej osoby.");
}
else {
UIUtils.printText("Niestety nie udało się. Nie dałaś rady zauważyć odpowiedzi kolegi, a w dodatku komisja zauważyła, że coś kombinujesz i wyprosiła cię z sali. Najprawdopodobniej to co napisałaś nie wystarczy, aby zdać .. Jesteś załamana, ale pozostaje ci nadzieja. Może jednak będzie inaczej. Musisz zaczekać na wyniki.");
}
break;
case "3":
UIUtils.printText("\nNiestety nie idzie ci to zbyt dobrze, w końcu poddajesz się i oddajesz kartkę, z tym co napisałaś. Masz nadzieję, że zdasz choć kto to wie.. Na wyniki jeszcze trochę poczekasz...");
break;
}
}
UIUtils.printText("\n\nCiąg dalszy nastąpi");
UIUtils.printText(".....", 1000);
GAME_OVER = true;
UIUtils.showEndMessage();
}
});
}
private static boolean isInputValid(String input, InputValidationListener listener) {
input = input.toLowerCase();
if (input.equals("s")) {
UIUtils.showStatistics();
return false;
}
if (input.equals("x")) {
GAME_OVER = true;
Stats.HP.setValue(0);
return false;
}
if (NumberUtils.isCreatable(input)) {
List<EventOption> options = EventsManager.RECENT_EVENT.getOptions();
int option = Integer.valueOf(input) - 1;
if (option >= 0 && option < options.size()) {
List<OptionCondition> conditions = options.get(option).getConditions();
if (conditions == null) {
return true;
} else {
for (OptionCondition condition : conditions) {
if (condition.getStatistic().getValue() < condition.getMinValue()) {
listener.invalidInput(" [ Nie spełniasz wymagań! Wybierz inną opcję... ]\n");
return false;
}
}
return true;
}
}
}
listener.invalidInput(" [ Wybierz poprawną opcję! ]\n");
return false;
}
}
|
UTF-8
|
Java
| 10,384 |
java
|
Main.java
|
Java
|
[] | null |
[] |
package pl.ceski23;
import org.apache.commons.lang3.math.NumberUtils;
import pl.ceski23.listeners.InputValidationListener;
import pl.ceski23.models.EventOption;
import pl.ceski23.models.OptionCondition;
import java.util.List;
import java.util.Scanner;
public class Main {
static int TURNS_LEFT = 10;
static String NEXT_EVENT_ID = null;
static boolean GAME_OVER = false;
static int PRINT_DELAY = 20;
public static void main(String[] args) {
if (args.length > 0 && args[0].equals("-godmode")) {
Stats.FLAIR.setValue(999);
Stats.HP.setValue(999);
Stats.SATISFACTION.setValue(999);
Stats.INTELLIGENCE.setValue(999);
Stats.MONEY.setValue(999);
}
if (args.length > 0 && args[0].equals("-speed")) {
PRINT_DELAY = Integer.parseInt(args[1]);
}
Scanner scanner = new Scanner(System.in);
UIUtils.showStartupMenu();
UIUtils.showIntroduction();
EventsManager.loadEvents(() -> {
while (TURNS_LEFT > 0 && !GAME_OVER) {
if (NEXT_EVENT_ID == null) {
EventsManager.startRandomEvent();
} else {
EventsManager.startEvent(NEXT_EVENT_ID, true);
NEXT_EVENT_ID = null;
}
String input = scanner.next();
while (!isInputValid(input, System.out::println) && !GAME_OVER) {
System.out.print(" => Wybieram: ");
input = scanner.next();
}
if (!GAME_OVER) EventsManager.endEvent(Integer.valueOf(input) - 1);
}
if (Stats.HP.getValue() <= 0) {
UIUtils.showDeathMessage();
}
if (GAME_OVER) {
UIUtils.showStatistics();
UIUtils.showEndMessage();
}
if (TURNS_LEFT == 0) {
System.out.println();
UIUtils.showStatistics();
System.out.println("\n ────────────────────────────────[ MATURA ]────────────────────────────────\n");
UIUtils.printText("Nadszedł ten ważny dzień egzaminu. Wstajesz o poranku i już czujesz narastający stres. No, ale niestety trzeba iść. Po drodze do szkoły zastanawiasz się, czy aby na pewno wszystko powtórzyłaś. Masz wrażenie jakby w jednym momencie wszystkie twoje wiadomości zniknęły, ale nie panikuj to tylko stres. Uspokajasz się, gdy docierasz do szkoły. Wchodzisz do sali. Teraz wszystko zależy od tego jakie decyzje podejmowałaś. Zobaczmy, co się stanie...\n\n");
if (Stats.INTELLIGENCE.getValue() >= 15) {
UIUtils.printText("Widzisz przed sobą test. Pytania wydają ci się banalne. Robisz jedno za drugim jak w transie. Ale nie tak szybko, jednak pojawia się jeden mały problem. Nie jesteś pewna jednej odpowiedzi. Co robisz?\n\n");
System.out.println(" [1] Zdajesz się na swoją intuicję");
System.out.println(" [2] Postanawiasz odpisać odpowiedź od kolegi");
System.out.println(" [3] Poświęcasz bardzo dużo czasu na ponowne rozwiązanie tego zadania");
System.out.print("\n => Wybieram: ");
String input = scanner.next();
while (true) {
if (NumberUtils.isCreatable(input)) {
int number = Integer.parseInt(input);
if (number > 0 && number < 4) break;
}
System.out.print(" => Wybieram: ");
input = scanner.next();
}
switch (input) {
case "1":
UIUtils.printText("\nPrzecież jesteś kobietą, a kobieca intuicja nigdy cię nie zawiodła.\n");
if (Stats.SATISFACTION.getValue() >= 6) {
UIUtils.printText("Udało ci się! Możesz spokojnie oddać kartkę, ale na wyniki niestety i tak trzeba będzie poczekać.");
}
else {
UIUtils.printText("Niestety, po oddaniu kartki czujesz, że twoja intuicja cię zawiodła. Niestety nie miałaś innego pomysłu. Teraz pozostaje tylko czekać.");
}
break;
case "2":
UIUtils.printText("\n");
if (Stats.FLAIR.getValue() >= 10) {
UIUtils.printText("Uff... Udało ci się odpisać i nikt się nie zorientował, jak to dobrze! Oddajesz kartkę z ulgą na twarzy i wiesz, że będzie dobrze.");
}
else {
UIUtils.printText("Niestety nie udało się. Nie dałaś rady zauważyć odpowiedzi kolegi, więc musisz strzelać. Zobaczymy czy ci się udało.");
}
break;
case "3":
UIUtils.printText("\nMyślisz i głowisz się jeszcze raz nad tym zadaniem, ale nie możesz nic wymyśleć. Tracisz bardzo dużo czasu, przez co strzelasz i przechodzisz do następnych zadań, bo możesz się nie wyrobić. Na szczęście udało ci się ukończyć egzamin na czas.");
break;
}
}
else {
UIUtils.printText("Widzisz przed sobą test i już wiesz, że to będą ciężkie 2 h. Niestety niewiele pamiętasz. Próbujesz robić zadania. Jedne ci wychodzą, inne nie. Niestety zdecydowana większość jest tych, które nie wychodzą. Zaczynasz się denerwować. No, ale dobrze coś trzeba napisać. Co robisz?\n\n");
System.out.println(" [1] Zdajesz się na swoją intuicję");
System.out.println(" [2] Postanawiasz odpisać odpowiedź od kolegi");
System.out.println(" [3] Próbujesz coś jeszcze wymyślić");
System.out.print("\n => Wybieram: ");
String input = scanner.next();
while (true) {
if (NumberUtils.isCreatable(input)) {
int number = Integer.parseInt(input);
if (number > 0 && number < 4) break;
}
System.out.print(" => Wybieram: ");
input = scanner.next();
}
switch (input) {
case "1":
UIUtils.printText("\nPrzecież jesteś kobietą, a kobieca intuicja nigdy cię nie zawiodła.\n");
if (Stats.SATISFACTION.getValue() >= 6) {
UIUtils.printText("Udało ci się w większości zadań. Możesz oddać kartkę, ale na wyniki niestety i tak trzeba będzie poczekać");
}
else {
UIUtils.printText("Niestety, po oddaniu kartki czujesz, że twoja intuicja cię zawiodła. Niestety nie miałaś innego pomysłu. Teraz pozostaje tylko czekać.");
}
break;
case "2":
UIUtils.printText("\n");
if (Stats.FLAIR.getValue() >= 10) {
UIUtils.printText("Uff... Udało ci się odpisać i nikt się nie zorientował, jak to dobrze! Oddajesz kartkę z ulgą na twarzy i masz nadzieję, że odpisałaś od odpowiedniej osoby.");
}
else {
UIUtils.printText("Niestety nie udało się. Nie dałaś rady zauważyć odpowiedzi kolegi, a w dodatku komisja zauważyła, że coś kombinujesz i wyprosiła cię z sali. Najprawdopodobniej to co napisałaś nie wystarczy, aby zdać .. Jesteś załamana, ale pozostaje ci nadzieja. Może jednak będzie inaczej. Musisz zaczekać na wyniki.");
}
break;
case "3":
UIUtils.printText("\nNiestety nie idzie ci to zbyt dobrze, w końcu poddajesz się i oddajesz kartkę, z tym co napisałaś. Masz nadzieję, że zdasz choć kto to wie.. Na wyniki jeszcze trochę poczekasz...");
break;
}
}
UIUtils.printText("\n\nCiąg dalszy nastąpi");
UIUtils.printText(".....", 1000);
GAME_OVER = true;
UIUtils.showEndMessage();
}
});
}
private static boolean isInputValid(String input, InputValidationListener listener) {
input = input.toLowerCase();
if (input.equals("s")) {
UIUtils.showStatistics();
return false;
}
if (input.equals("x")) {
GAME_OVER = true;
Stats.HP.setValue(0);
return false;
}
if (NumberUtils.isCreatable(input)) {
List<EventOption> options = EventsManager.RECENT_EVENT.getOptions();
int option = Integer.valueOf(input) - 1;
if (option >= 0 && option < options.size()) {
List<OptionCondition> conditions = options.get(option).getConditions();
if (conditions == null) {
return true;
} else {
for (OptionCondition condition : conditions) {
if (condition.getStatistic().getValue() < condition.getMinValue()) {
listener.invalidInput(" [ Nie spełniasz wymagań! Wybierz inną opcję... ]\n");
return false;
}
}
return true;
}
}
}
listener.invalidInput(" [ Wybierz poprawną opcję! ]\n");
return false;
}
}
| 10,384 | 0.510831 | 0.503975 | 210 | 46.923809 | 61.585125 | 486 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.62381 | false | false |
14
|
7d30164019e9a986fab0e8e4f3b6b6a1e1d69fcd
| 5,059,471,510,122 |
208ba847cec642cdf7b77cff26bdc4f30a97e795
|
/x/src/main/java/org.wp.x/models/FilterCriteria.java
|
0a806c42f037f3622fe2914adad77c47b9fa3252
|
[] |
no_license
|
kageiit/perf-android-large
|
https://github.com/kageiit/perf-android-large
|
ec7c291de9cde2f813ed6573f706a8593be7ac88
|
2cbd6e74837a14ae87c1c4d1d62ac3c35df9e6f8
|
refs/heads/master
| 2021-01-12T14:00:19.468000 | 2016-09-27T13:10:42 | 2016-09-27T13:10:42 | 69,685,305 | 0 | 0 | null | true | 2016-09-30T16:59:49 | 2016-09-30T16:59:48 | 2016-09-27T07:32:53 | 2016-09-27T13:14:58 | 7,680 | 0 | 0 | 0 | null | null | null |
package org.wp.x.models;
public interface FilterCriteria {
String getLabel();
}
|
UTF-8
|
Java
| 85 |
java
|
FilterCriteria.java
|
Java
|
[] | null |
[] |
package org.wp.x.models;
public interface FilterCriteria {
String getLabel();
}
| 85 | 0.729412 | 0.729412 | 5 | 16 | 13.190906 | 33 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false |
14
|
13bbeee64df4f050d0d18f7781911a48a4897b38
| 28,827,820,519,205 |
dfa82765f34c421b594301fe919af54444ba5e03
|
/src/cr/ac/ucenfotec/proyectofinal/bl/dao/ListaReproduccionDAO.java
|
1b6c2b7a7a479a6a1284b7b9f6e9aae8d87a5f02
|
[] |
no_license
|
DanielGit28/PFinalConJFX
|
https://github.com/DanielGit28/PFinalConJFX
|
d1f21d728570ae6c5e3469872b306bfde8fec9e0
|
0456f3d5cd39c52405d18b0172acf1cf1f474e06
|
refs/heads/main
| 2023-02-03T05:12:06.497000 | 2020-12-21T03:51:27 | 2020-12-21T03:51:27 | 312,950,935 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package cr.ac.ucenfotec.proyectofinal.bl.dao;
import cr.ac.ucenfotec.proyectofinal.bl.entidades.Admin;
import cr.ac.ucenfotec.proyectofinal.bl.entidades.Cancion;
import cr.ac.ucenfotec.proyectofinal.bl.entidades.ListaReproduccion;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
* @author Daniel
* @version 1.0
*/
public class ListaReproduccionDAO {
Connection cnx;
private PreparedStatement cmdInsertar;
private PreparedStatement queryListaReproduccion;
private final String TEMPLATE_CMD_INSERTAR = "insert into lista_reproduccion_usuario (nombreLista,fechaCreacion,calificacion,idUsuarioLista)" +
" values (?,?,?,?)";
private final String TEMPLATE_QRY_LISTASREPRODUCCION = "select * from lista_reproduccion_usuario";
/**
*
* @param conexion conexión de la clase con la base de datos
*/
public ListaReproduccionDAO(Connection conexion){
this.cnx = conexion;
try {
this.cmdInsertar = cnx.prepareStatement(TEMPLATE_CMD_INSERTAR);
this.queryListaReproduccion = cnx.prepareStatement(TEMPLATE_QRY_LISTASREPRODUCCION);
}
catch (SQLException throwables) {
throwables.printStackTrace();
}
}
public Admin encontrarPorId(String cedula){
return null;
}
public List<Admin> obtenerTodosLosClientes() throws SQLException {
Statement query = cnx.createStatement();
ResultSet resultado = query.executeQuery("select * from tcliente");
ArrayList<Admin> listaClientes = new ArrayList<>();
while (resultado.next()){
Admin leido = new Admin();
leido.setAvatarUsuario(resultado.getString("avatar"));
leido.setNombre(resultado.getString("nombre"));
//leido.setPuntos(resultado.getInt("puntos"));
listaClientes.add(leido);
}
return listaClientes;
}
/**
*
*
* @param nuevo objeto ListaReproduccion que se va a guardar en la base de datos
* @throws SQLException
*/
public void guardarListaReproduccion(ListaReproduccion nuevo) throws SQLException{
if(this.cmdInsertar != null) {
this.cmdInsertar.setString(1,nuevo.getNombreListaReproduccion());
this.cmdInsertar.setDate(2, Date.valueOf(nuevo.getFechaCreacionListaReproduccion()));
this.cmdInsertar.setInt(3,nuevo.getCalificacionReproduccion());
this.cmdInsertar.setInt(4,nuevo.getAutorLista().getId());
this.cmdInsertar.execute();
Statement queryLista = cnx.createStatement();
ResultSet resultadoLista = queryLista.executeQuery("select * from lista_reproduccion_usuario where idUsuarioLista = "+nuevo.getAutorLista().getId()+" and nombreLista = '"+nuevo.getNombreListaReproduccion()+"'");
if(resultadoLista.next()) {
for (Cancion cancion: nuevo.getCancionesListaReproduccion()) {
Statement queryBiblioteca = cnx.createStatement();
queryBiblioteca.execute("insert into biblioteca_lista_reproduccion (idListaReproduccionUsuario,idCancionBibliotecaLista) values("+resultadoLista.getInt("idListaUsuario")+", "+cancion.getId()+")");
}
} else {
System.out.println("No se encontró la lista recién creada");
}
} else {
System.out.println("No se pudo guardar la lista de reproducción");
}
}
}
|
UTF-8
|
Java
| 3,503 |
java
|
ListaReproduccionDAO.java
|
Java
|
[
{
"context": ".ArrayList;\nimport java.util.List;\n\n/**\n * @author Daniel\n * @version 1.0\n */\n\npublic class ListaReproducci",
"end": 325,
"score": 0.9984248280525208,
"start": 319,
"tag": "NAME",
"value": "Daniel"
}
] | null |
[] |
package cr.ac.ucenfotec.proyectofinal.bl.dao;
import cr.ac.ucenfotec.proyectofinal.bl.entidades.Admin;
import cr.ac.ucenfotec.proyectofinal.bl.entidades.Cancion;
import cr.ac.ucenfotec.proyectofinal.bl.entidades.ListaReproduccion;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
* @author Daniel
* @version 1.0
*/
public class ListaReproduccionDAO {
Connection cnx;
private PreparedStatement cmdInsertar;
private PreparedStatement queryListaReproduccion;
private final String TEMPLATE_CMD_INSERTAR = "insert into lista_reproduccion_usuario (nombreLista,fechaCreacion,calificacion,idUsuarioLista)" +
" values (?,?,?,?)";
private final String TEMPLATE_QRY_LISTASREPRODUCCION = "select * from lista_reproduccion_usuario";
/**
*
* @param conexion conexión de la clase con la base de datos
*/
public ListaReproduccionDAO(Connection conexion){
this.cnx = conexion;
try {
this.cmdInsertar = cnx.prepareStatement(TEMPLATE_CMD_INSERTAR);
this.queryListaReproduccion = cnx.prepareStatement(TEMPLATE_QRY_LISTASREPRODUCCION);
}
catch (SQLException throwables) {
throwables.printStackTrace();
}
}
public Admin encontrarPorId(String cedula){
return null;
}
public List<Admin> obtenerTodosLosClientes() throws SQLException {
Statement query = cnx.createStatement();
ResultSet resultado = query.executeQuery("select * from tcliente");
ArrayList<Admin> listaClientes = new ArrayList<>();
while (resultado.next()){
Admin leido = new Admin();
leido.setAvatarUsuario(resultado.getString("avatar"));
leido.setNombre(resultado.getString("nombre"));
//leido.setPuntos(resultado.getInt("puntos"));
listaClientes.add(leido);
}
return listaClientes;
}
/**
*
*
* @param nuevo objeto ListaReproduccion que se va a guardar en la base de datos
* @throws SQLException
*/
public void guardarListaReproduccion(ListaReproduccion nuevo) throws SQLException{
if(this.cmdInsertar != null) {
this.cmdInsertar.setString(1,nuevo.getNombreListaReproduccion());
this.cmdInsertar.setDate(2, Date.valueOf(nuevo.getFechaCreacionListaReproduccion()));
this.cmdInsertar.setInt(3,nuevo.getCalificacionReproduccion());
this.cmdInsertar.setInt(4,nuevo.getAutorLista().getId());
this.cmdInsertar.execute();
Statement queryLista = cnx.createStatement();
ResultSet resultadoLista = queryLista.executeQuery("select * from lista_reproduccion_usuario where idUsuarioLista = "+nuevo.getAutorLista().getId()+" and nombreLista = '"+nuevo.getNombreListaReproduccion()+"'");
if(resultadoLista.next()) {
for (Cancion cancion: nuevo.getCancionesListaReproduccion()) {
Statement queryBiblioteca = cnx.createStatement();
queryBiblioteca.execute("insert into biblioteca_lista_reproduccion (idListaReproduccionUsuario,idCancionBibliotecaLista) values("+resultadoLista.getInt("idListaUsuario")+", "+cancion.getId()+")");
}
} else {
System.out.println("No se encontró la lista recién creada");
}
} else {
System.out.println("No se pudo guardar la lista de reproducción");
}
}
}
| 3,503 | 0.663332 | 0.661618 | 89 | 38.314606 | 41.650928 | 223 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.550562 | false | false |
14
|
2e0fa253ca0e904f43e571abd35a2649989d8e49
| 2,345,052,202,211 |
67c6700f868f61634dededecc416845f6c5f081a
|
/test/upeu/holamundo/matricula/data/mycontexts/AlumnoDataTest.java
|
d6b9bfd4ba374356de2eadfa9462be0e805cfec6
|
[] |
no_license
|
CarlosAvilesArredondo/HolaMundo2
|
https://github.com/CarlosAvilesArredondo/HolaMundo2
|
c0e792bd57bbc24d2b28412a28a728e8706acdd1
|
9614c8539044870824fb4612af89bf3d0414aaa1
|
refs/heads/master
| 2021-01-02T08:38:44.037000 | 2017-08-01T20:27:59 | 2017-08-01T20:27:59 | 99,040,449 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package upeu.holamundo.matricula.data.mycontexts;
import java.util.List;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import upeu.holamundo.matricula.data.contracts.DataFactory;
import upeu.holamundo.matricula.data.contracts.IAlumnoData;
import upeu.holamundo.matricula.data.entities.Alumno;
/**
*
* @author Asullom
*/
public class AlumnoDataTest {
IAlumnoData instance ;
@Before
public void setUp() {
DataFactory.setInitializeFactory(DataFactory.PG);
instance = DataFactory.getAlumnoData();
}
@After
public void tearDown() {
}
/**
* Test of create method, of class AlumnoData.
*/
@Test
public void testCreate() { //Hecho/Done
System.out.println("create");
Alumno alumno = new Alumno();
alumno.setCodigo("A001");
Alumno result = instance.create(alumno);
Alumno x = result;
assertTrue(result.getId()>0);
}
/**
* Test of edit method, of class AlumnoData.
*/
@Test
public void testEdit() {
System.out.println("edit");
Alumno alumno = null;
Alumno expResult = null;
Alumno result = instance.edit(alumno);
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of delete method, of class AlumnoData.
*/
@Test
public void testDelete() {
System.out.println("delete");
int id = 0;
instance.delete(id);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of getById method, of class AlumnoData.
*/
@Test
public void testGetById() {
System.out.println("getById");
int id = 0;
Alumno expResult = null;
Alumno result = instance.getById(id);
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of getListAll method, of class AlumnoData.
*/
@Test
public void testGetListAll() {
System.out.println("getListAll");
List<Alumno> expResult = null;
List<Alumno> result = instance.getListAll();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of getListByFilter method, of class AlumnoData.
*/
@Test
public void testGetListByFilter() {
System.out.println("getListByFilter");
String filter = "";
List<Alumno> expResult = null;
List<Alumno> result = instance.getListByFilter(filter);
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
}
|
UTF-8
|
Java
| 3,415 |
java
|
AlumnoDataTest.java
|
Java
|
[
{
"context": "matricula.data.entities.Alumno;\n\n/**\n *\n * @author Asullom\n */\npublic class AlumnoDataTest {\n \n IAlumn",
"end": 625,
"score": 0.9675844311714172,
"start": 618,
"tag": "NAME",
"value": "Asullom"
}
] | null |
[] |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package upeu.holamundo.matricula.data.mycontexts;
import java.util.List;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import upeu.holamundo.matricula.data.contracts.DataFactory;
import upeu.holamundo.matricula.data.contracts.IAlumnoData;
import upeu.holamundo.matricula.data.entities.Alumno;
/**
*
* @author Asullom
*/
public class AlumnoDataTest {
IAlumnoData instance ;
@Before
public void setUp() {
DataFactory.setInitializeFactory(DataFactory.PG);
instance = DataFactory.getAlumnoData();
}
@After
public void tearDown() {
}
/**
* Test of create method, of class AlumnoData.
*/
@Test
public void testCreate() { //Hecho/Done
System.out.println("create");
Alumno alumno = new Alumno();
alumno.setCodigo("A001");
Alumno result = instance.create(alumno);
Alumno x = result;
assertTrue(result.getId()>0);
}
/**
* Test of edit method, of class AlumnoData.
*/
@Test
public void testEdit() {
System.out.println("edit");
Alumno alumno = null;
Alumno expResult = null;
Alumno result = instance.edit(alumno);
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of delete method, of class AlumnoData.
*/
@Test
public void testDelete() {
System.out.println("delete");
int id = 0;
instance.delete(id);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of getById method, of class AlumnoData.
*/
@Test
public void testGetById() {
System.out.println("getById");
int id = 0;
Alumno expResult = null;
Alumno result = instance.getById(id);
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of getListAll method, of class AlumnoData.
*/
@Test
public void testGetListAll() {
System.out.println("getListAll");
List<Alumno> expResult = null;
List<Alumno> result = instance.getListAll();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of getListByFilter method, of class AlumnoData.
*/
@Test
public void testGetListByFilter() {
System.out.println("getListByFilter");
String filter = "";
List<Alumno> expResult = null;
List<Alumno> result = instance.getListByFilter(filter);
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
}
| 3,415 | 0.618155 | 0.616398 | 125 | 26.304001 | 22.253889 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.48 | false | false |
14
|
d92ecec3f33899dc85f1e25badbaa0374f1bed5d
| 27,401,891,361,157 |
ec2c242f825aad18f587ef9ca201e317dfcba47b
|
/src/com/est/views/viewEntrada.java
|
7d3640510be27fd4083596a22978febf7c49b1d3
|
[] |
no_license
|
migangel9/parking
|
https://github.com/migangel9/parking
|
ceaf21453a836f608d7308e4a4a13cc1394ff37a
|
d33292fc6c8f8f6b23307fb756074d77c8f01dd1
|
refs/heads/master
| 2021-01-20T09:32:32.082000 | 2015-03-04T08:58:59 | 2015-03-04T08:58:59 | 31,644,535 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.est.views;
import com.est.ctrl.registroD;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.Authenticator;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.imageio.ImageIO;
import javax.swing.JOptionPane;
/**
*
* @author m
*/
public class viewEntrada extends javax.swing.JDialog {
int opcion;
registroD registro = new registroD();
private final String IP;
private final String pathFotos = "data\\";
private final String usuario = "admin";
private final String contra = "admin";
private final String rutaF;
private final String hrEntrada;
boolean hayConexion;
/**
* Creates new form viewAgregarPensionado
*/
private String getFechaActual() {
Date ahora = new Date();
SimpleDateFormat formateador = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return formateador.format(ahora);
}
public viewEntrada(javax.swing.JFrame parent, boolean modal, String IP, boolean hayConexion) {
super(parent, modal);
this.IP = IP;
initComponents();
this.hrEntrada = getFechaActual();
this.rutaF = "E"+hrEntrada.replace(" ","").replace(":","_").replace("-","");
System.out.println("**************************"+rutaF);
if(hayConexion){
guardarFoto(rutaF, this.IP);
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
btnCamioneta = new javax.swing.JButton();
btnAuto = new javax.swing.JButton();
btnHotel1 = new javax.swing.JButton();
btnHotel2 = new javax.swing.JButton();
btnPensionado = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
btnCancelar = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
setAlwaysOnTop(true);
setBounds(new java.awt.Rectangle(250, 200, 0, 0));
setResizable(false);
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel1.setText("Entrada de Automovil");
jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/signin_-32.png"))); // NOI18N
btnCamioneta.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/SUV-128.png"))); // NOI18N
btnCamioneta.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
btnCamioneta.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCamionetaActionPerformed(evt);
}
});
btnAuto.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/sedan-128.png"))); // NOI18N
btnAuto.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
btnAuto.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAutoActionPerformed(evt);
}
});
btnHotel1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
btnHotel1.setText("La Alhondiga");
btnHotel1.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
btnHotel1.setMaximumSize(new java.awt.Dimension(161, 85));
btnHotel1.setMinimumSize(new java.awt.Dimension(161, 85));
btnHotel1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnHotel1ActionPerformed(evt);
}
});
btnHotel2.setText("Puebla de Antaño");
btnHotel2.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
btnHotel2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnHotel2ActionPerformed(evt);
}
});
btnPensionado.setText("PENSIONADO");
btnPensionado.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
btnPensionado.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnPensionadoActionPerformed(evt);
}
});
jLabel3.setText("Auto");
jLabel4.setText("Camioneta");
jLabel5.setText("Hotel 1");
jLabel6.setText("Hotel 2");
jLabel7.setText("Pensionado");
btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/error-32.png"))); // NOI18N
btnCancelar.setText("Cancelar");
btnCancelar.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
btnCancelar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCancelarActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator1)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(55, 55, 55)
.addComponent(jLabel3)
.addGap(97, 97, 97)
.addComponent(jLabel4)
.addGap(95, 95, 95)
.addComponent(jLabel5)
.addGap(101, 101, 101)
.addComponent(jLabel6)
.addGap(92, 92, 92)
.addComponent(jLabel7))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(16, 16, 16)
.addComponent(btnAuto, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnCamioneta, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnHotel1, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnHotel2, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnPensionado, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(23, 23, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(4, 4, 4)
.addComponent(jLabel1))
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(47, 47, 47)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnCamioneta, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnHotel1, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnPensionado, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnHotel2, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(btnAuto, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(13, 13, 13)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(jLabel5))
.addComponent(jLabel6)
.addComponent(jLabel7))
.addContainerGap(50, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnAutoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAutoActionPerformed
// TODO add your handling code here:
String folio = registro.getFolio();
registro.setEntrada(folio,"Automovil", true, false,1,this.hrEntrada);
this.opcion = 1;
this.setVisible(false);
}//GEN-LAST:event_btnAutoActionPerformed
private void guardarFoto(String nombreArchivo, String direccionIP ){
URL nurl = null;
BufferedImage imagen = null;
try {
nurl = new URL(direccionIP);
} catch (MalformedURLException e) {
e.printStackTrace();
}
Authenticator au = new Authenticator() {@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication (usuario, contra.toCharArray());
}};
Authenticator.setDefault(au);
try {
imagen = ImageIO.read(nurl);
} catch (IOException ex) {
//Logger.getLogger(PanelVideoCam.class.getName()).log(Level.SEVERE, null, ex);
//ex.printStackTrace();
JOptionPane.showMessageDialog(null, "Verifique la conexión a la cámara ", "Error al leer la imagen", JOptionPane.ERROR_MESSAGE);
}
if (imagen != null) {
try {
ImageIO.write(imagen, "png", new File(pathFotos+nombreArchivo+".ppj"));
System.out.println(pathFotos+nombreArchivo+".ppj");
} catch (IOException e) {
//e.printStackTrace();
JOptionPane.showMessageDialog(null, "No se puede guardar la captura", "Error al guardar la captura", JOptionPane.ERROR_MESSAGE);
}
}
else{
JOptionPane.showMessageDialog(null, "Verifique la conexión a la cámara ", "Error al accesar a la cámara", JOptionPane.ERROR_MESSAGE);
}
}
private void btnCamionetaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCamionetaActionPerformed
// TODO add your handling code here:
String folio = registro.getFolio();
registro.setEntrada(folio,"Camioneta", true, false,2,this.hrEntrada);
/*String hr = registro.getHrEntrada();
System.out.println("**************************"+hr);
guardarFoto("E"+hr.replace(" ","").replace(":","_").replace("-",""), this.FRENTE );*/
this.opcion = 2;
this.setVisible(false);
}//GEN-LAST:event_btnCamionetaActionPerformed
private void btnHotel1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnHotel1ActionPerformed
// TODO add your handling code here:
String folio = registro.getFolio();
registro.setEntrada(folio,"La.Alhondiga", true, false,3,this.hrEntrada);
/*String hr = registro.getHrEntrada();
System.out.println("**************************"+hr);
guardarFoto("E"+hr.replace(" ","").replace(":","_").replace("-",""), this.FRENTE );*/
this.opcion = 3;
this.setVisible(false);
}//GEN-LAST:event_btnHotel1ActionPerformed
private void btnHotel2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnHotel2ActionPerformed
// TODO add your handling code here:
String folio = registro.getFolio();
registro.setEntrada(folio,"Puebla.de.Antano", true, false,4,this.hrEntrada);
/*String hr = registro.getHrEntrada();
System.out.println("**************************"+hr);
guardarFoto("E"+hr.replace(" ","").replace(":","_").replace("-",""), this.FRENTE );*/
this.opcion = 4;
this.setVisible(false);
}//GEN-LAST:event_btnHotel2ActionPerformed
private void btnPensionadoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPensionadoActionPerformed
// TODO add your handling code here:
String folio = registro.getFolio();
registro.setEntrada(folio,"Pensionado", true, false,5,this.hrEntrada);
/*String hr = registro.getHrEntrada();
System.out.println("**************************"+hr);
guardarFoto("E"+hr.replace(" ","").replace(":","_").replace("-",""), this.FRENTE );*/
this.opcion = 5;
this.setVisible(false);
}//GEN-LAST:event_btnPensionadoActionPerformed
private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
// TODO add your handling code here:
String folio = registro.getFolio();
registro.setCancelado("C"+folio,"Cancelado", true, true, 9,this.hrEntrada);
/*String hr = registro.getHrEntrada();
System.out.println("**************************"+hr);
guardarFoto("E"+hr.replace(" ","").replace(":","_").replace("-",""), this.FRENTE );*/
this.opcion = 0;
this.setVisible(false);
}//GEN-LAST:event_btnCancelarActionPerformed
public int getRespuesta(){
return this.opcion;
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(viewEntrada.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(viewEntrada.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(viewEntrada.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(viewEntrada.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
viewEntrada dialog = new viewEntrada(new javax.swing.JFrame(), true,"",true);
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnAuto;
private javax.swing.JButton btnCamioneta;
private javax.swing.JButton btnCancelar;
private javax.swing.JButton btnHotel1;
private javax.swing.JButton btnHotel2;
private javax.swing.JButton btnPensionado;
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JPanel jPanel1;
private javax.swing.JSeparator jSeparator1;
// End of variables declaration//GEN-END:variables
}
|
UTF-8
|
Java
| 19,654 |
java
|
viewEntrada.java
|
Java
|
[
{
"context": "import javax.swing.JOptionPane;\n\n/**\n *\n * @author m\n */\npublic class viewEntrada extends javax.swing.",
"end": 597,
"score": 0.9945354461669922,
"start": 596,
"tag": "USERNAME",
"value": "m"
},
{
"context": "\"data\\\\\";\n private final String usuario = \"admin\";\n private final String contra = \"admin\";\n",
"end": 860,
"score": 0.9993607401847839,
"start": 855,
"tag": "USERNAME",
"value": "admin"
},
{
"context": "Label3.setText(\"Auto\");\n\n jLabel4.setText(\"Camioneta\");\n\n jLabel5.setText(\"Hotel 1\");\n\n ",
"end": 5536,
"score": 0.9984068870544434,
"start": 5527,
"tag": "NAME",
"value": "Camioneta"
}
] | null |
[] |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.est.views;
import com.est.ctrl.registroD;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.Authenticator;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.imageio.ImageIO;
import javax.swing.JOptionPane;
/**
*
* @author m
*/
public class viewEntrada extends javax.swing.JDialog {
int opcion;
registroD registro = new registroD();
private final String IP;
private final String pathFotos = "data\\";
private final String usuario = "admin";
private final String contra = "admin";
private final String rutaF;
private final String hrEntrada;
boolean hayConexion;
/**
* Creates new form viewAgregarPensionado
*/
private String getFechaActual() {
Date ahora = new Date();
SimpleDateFormat formateador = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return formateador.format(ahora);
}
public viewEntrada(javax.swing.JFrame parent, boolean modal, String IP, boolean hayConexion) {
super(parent, modal);
this.IP = IP;
initComponents();
this.hrEntrada = getFechaActual();
this.rutaF = "E"+hrEntrada.replace(" ","").replace(":","_").replace("-","");
System.out.println("**************************"+rutaF);
if(hayConexion){
guardarFoto(rutaF, this.IP);
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
btnCamioneta = new javax.swing.JButton();
btnAuto = new javax.swing.JButton();
btnHotel1 = new javax.swing.JButton();
btnHotel2 = new javax.swing.JButton();
btnPensionado = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
btnCancelar = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
setAlwaysOnTop(true);
setBounds(new java.awt.Rectangle(250, 200, 0, 0));
setResizable(false);
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel1.setText("Entrada de Automovil");
jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/signin_-32.png"))); // NOI18N
btnCamioneta.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/SUV-128.png"))); // NOI18N
btnCamioneta.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
btnCamioneta.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCamionetaActionPerformed(evt);
}
});
btnAuto.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/sedan-128.png"))); // NOI18N
btnAuto.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
btnAuto.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAutoActionPerformed(evt);
}
});
btnHotel1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
btnHotel1.setText("La Alhondiga");
btnHotel1.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
btnHotel1.setMaximumSize(new java.awt.Dimension(161, 85));
btnHotel1.setMinimumSize(new java.awt.Dimension(161, 85));
btnHotel1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnHotel1ActionPerformed(evt);
}
});
btnHotel2.setText("Puebla de Antaño");
btnHotel2.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
btnHotel2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnHotel2ActionPerformed(evt);
}
});
btnPensionado.setText("PENSIONADO");
btnPensionado.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
btnPensionado.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnPensionadoActionPerformed(evt);
}
});
jLabel3.setText("Auto");
jLabel4.setText("Camioneta");
jLabel5.setText("Hotel 1");
jLabel6.setText("Hotel 2");
jLabel7.setText("Pensionado");
btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/error-32.png"))); // NOI18N
btnCancelar.setText("Cancelar");
btnCancelar.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
btnCancelar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCancelarActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator1)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(55, 55, 55)
.addComponent(jLabel3)
.addGap(97, 97, 97)
.addComponent(jLabel4)
.addGap(95, 95, 95)
.addComponent(jLabel5)
.addGap(101, 101, 101)
.addComponent(jLabel6)
.addGap(92, 92, 92)
.addComponent(jLabel7))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(16, 16, 16)
.addComponent(btnAuto, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnCamioneta, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnHotel1, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnHotel2, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnPensionado, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(23, 23, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(4, 4, 4)
.addComponent(jLabel1))
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(47, 47, 47)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnCamioneta, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnHotel1, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnPensionado, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnHotel2, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(btnAuto, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(13, 13, 13)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(jLabel5))
.addComponent(jLabel6)
.addComponent(jLabel7))
.addContainerGap(50, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnAutoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAutoActionPerformed
// TODO add your handling code here:
String folio = registro.getFolio();
registro.setEntrada(folio,"Automovil", true, false,1,this.hrEntrada);
this.opcion = 1;
this.setVisible(false);
}//GEN-LAST:event_btnAutoActionPerformed
private void guardarFoto(String nombreArchivo, String direccionIP ){
URL nurl = null;
BufferedImage imagen = null;
try {
nurl = new URL(direccionIP);
} catch (MalformedURLException e) {
e.printStackTrace();
}
Authenticator au = new Authenticator() {@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication (usuario, contra.toCharArray());
}};
Authenticator.setDefault(au);
try {
imagen = ImageIO.read(nurl);
} catch (IOException ex) {
//Logger.getLogger(PanelVideoCam.class.getName()).log(Level.SEVERE, null, ex);
//ex.printStackTrace();
JOptionPane.showMessageDialog(null, "Verifique la conexión a la cámara ", "Error al leer la imagen", JOptionPane.ERROR_MESSAGE);
}
if (imagen != null) {
try {
ImageIO.write(imagen, "png", new File(pathFotos+nombreArchivo+".ppj"));
System.out.println(pathFotos+nombreArchivo+".ppj");
} catch (IOException e) {
//e.printStackTrace();
JOptionPane.showMessageDialog(null, "No se puede guardar la captura", "Error al guardar la captura", JOptionPane.ERROR_MESSAGE);
}
}
else{
JOptionPane.showMessageDialog(null, "Verifique la conexión a la cámara ", "Error al accesar a la cámara", JOptionPane.ERROR_MESSAGE);
}
}
private void btnCamionetaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCamionetaActionPerformed
// TODO add your handling code here:
String folio = registro.getFolio();
registro.setEntrada(folio,"Camioneta", true, false,2,this.hrEntrada);
/*String hr = registro.getHrEntrada();
System.out.println("**************************"+hr);
guardarFoto("E"+hr.replace(" ","").replace(":","_").replace("-",""), this.FRENTE );*/
this.opcion = 2;
this.setVisible(false);
}//GEN-LAST:event_btnCamionetaActionPerformed
private void btnHotel1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnHotel1ActionPerformed
// TODO add your handling code here:
String folio = registro.getFolio();
registro.setEntrada(folio,"La.Alhondiga", true, false,3,this.hrEntrada);
/*String hr = registro.getHrEntrada();
System.out.println("**************************"+hr);
guardarFoto("E"+hr.replace(" ","").replace(":","_").replace("-",""), this.FRENTE );*/
this.opcion = 3;
this.setVisible(false);
}//GEN-LAST:event_btnHotel1ActionPerformed
private void btnHotel2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnHotel2ActionPerformed
// TODO add your handling code here:
String folio = registro.getFolio();
registro.setEntrada(folio,"Puebla.de.Antano", true, false,4,this.hrEntrada);
/*String hr = registro.getHrEntrada();
System.out.println("**************************"+hr);
guardarFoto("E"+hr.replace(" ","").replace(":","_").replace("-",""), this.FRENTE );*/
this.opcion = 4;
this.setVisible(false);
}//GEN-LAST:event_btnHotel2ActionPerformed
private void btnPensionadoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPensionadoActionPerformed
// TODO add your handling code here:
String folio = registro.getFolio();
registro.setEntrada(folio,"Pensionado", true, false,5,this.hrEntrada);
/*String hr = registro.getHrEntrada();
System.out.println("**************************"+hr);
guardarFoto("E"+hr.replace(" ","").replace(":","_").replace("-",""), this.FRENTE );*/
this.opcion = 5;
this.setVisible(false);
}//GEN-LAST:event_btnPensionadoActionPerformed
private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
// TODO add your handling code here:
String folio = registro.getFolio();
registro.setCancelado("C"+folio,"Cancelado", true, true, 9,this.hrEntrada);
/*String hr = registro.getHrEntrada();
System.out.println("**************************"+hr);
guardarFoto("E"+hr.replace(" ","").replace(":","_").replace("-",""), this.FRENTE );*/
this.opcion = 0;
this.setVisible(false);
}//GEN-LAST:event_btnCancelarActionPerformed
public int getRespuesta(){
return this.opcion;
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(viewEntrada.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(viewEntrada.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(viewEntrada.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(viewEntrada.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
viewEntrada dialog = new viewEntrada(new javax.swing.JFrame(), true,"",true);
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnAuto;
private javax.swing.JButton btnCamioneta;
private javax.swing.JButton btnCancelar;
private javax.swing.JButton btnHotel1;
private javax.swing.JButton btnHotel2;
private javax.swing.JButton btnPensionado;
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JPanel jPanel1;
private javax.swing.JSeparator jSeparator1;
// End of variables declaration//GEN-END:variables
}
| 19,654 | 0.631769 | 0.618536 | 394 | 48.868019 | 35.714718 | 152 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.873096 | false | false |
14
|
8cc7a086eac4ee1b1455ce48d2ffb5f6b4491388
| 317,827,639,205 |
2a21dd6e47459dd2b9d2d81608272cc9be25fe6b
|
/src/main/java/com/foi/entities/anomaly/features/compa/TimeDistribution.java
|
d9363a2197f617817dae37b24da59236bb3930c2
|
[] |
no_license
|
chte/tweecious
|
https://github.com/chte/tweecious
|
7fa262a18dffba7aa0eaa204f7f3a9617e06ad8f
|
bea2fa0b96814f374011db7979cdb05f37b25a6e
|
refs/heads/master
| 2016-05-23T17:33:08.848000 | 2015-06-28T09:40:37 | 2015-06-28T09:40:37 | 31,007,505 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.foi.entities.anomaly.features.compa;
import com.foi.entities.anomaly.AnomalyFeature;
import com.foi.entities.Tweet;
import com.foi.entities.containers.TimeContainer;
import weka.core.Attribute;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* Created by david on 2015-02-23.
*/
public class TimeDistribution extends AnomalyFeature {
private int boxWidthInSeconds;
private int numBoxes;
private TimeContainer tc;
private String featureKeyword;
public static SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM d HH:mm:ss Z yyyy");
public TimeDistribution(String name, TimeContainer tc, int boxWidthInSeconds, int numBoxes, String featureKeyword, double scoreWeight) {
this.name = name;
this.boxWidthInSeconds = boxWidthInSeconds;
this.numBoxes = numBoxes;
this.tc = tc;
this.numTweetsAnalyzed = mapSum(tc.getTimeslots());
this.featureKeyword = featureKeyword;
this.scoreWeight = scoreWeight;
}
public TimeDistribution(String name, TimeContainer tc, int boxWidthInSeconds, int numBoxes, String featureKeyword) {
this.name = name;
this.boxWidthInSeconds = boxWidthInSeconds;
this.numBoxes = numBoxes;
this.tc = tc;
this.numTweetsAnalyzed = mapSum(tc.getTimeslots());
this.featureKeyword = featureKeyword;
}
public TimeDistribution(String name, TimeContainer tc, int boxWidthInSeconds, int numBoxes) {
this.name = name;
this.boxWidthInSeconds = boxWidthInSeconds;
this.numBoxes = numBoxes;
this.tc = tc;
this.numTweetsAnalyzed = mapSum(tc.getTimeslots());
}
public TimeDistribution(String name, int boxWidthInSeconds, int numBoxes) {
this.name = name;
this.boxWidthInSeconds = boxWidthInSeconds;
this.numBoxes = numBoxes;
//this.normalizedDistribution = new double[numBoxes];
}
public double calculateAnomalyScore(int timeSlot) {
/* If the value is unseen before, it's anomaly */
if (!tc.getTimeslots().containsKey(timeSlot)) {
return 1;
}
int N = tc.getTimeslots().size();
long valuesSeen = mapSum(tc.getTimeslots());
double refRatio = (double)valuesSeen/N;
long c = tc.getTimeslots().get(timeSlot);
if (c >= refRatio) {
return 0;
} else {
return 1 - (double)c/N;
}
}
@Override
public void addTweetToModel(Tweet newTweet) {
DateFormat sdf = new SimpleDateFormat("EEE MMM d HH:mm:ss Z YYYY");
Date date;
try {
date = sdf.parse((String) newTweet.getProps().get("created_at"));
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
date = new Date(); // just for compiler reason..
}
int bucket = unixtimeToBucket(date.getTime());
tc.addTimeSlot(bucket);
numTweetsAnalyzed++;
}
@Override
public double calculateAnomalyScore(Tweet tweet) {
DateFormat sdf = new SimpleDateFormat("EEE MMM d HH:mm:ss Z YYYY");
Date date;
try {
date = sdf.parse((String) tweet.getProps().get("created_at"));
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
date = new Date(); // just for compiler reason..
}
int bucket = unixtimeToBucket(date.getTime());
int numBoxesUsed = tc.numNonEmptyTimeslots();
double refRatio = (double)numTweetsAnalyzed/numBoxesUsed; // I assume all time slots should be in here
long c = tc.getTimeslots().get(bucket) != null ? tc.getTimeslots().get(bucket) : 0L;
if (c >= refRatio) {
return 0;
} else {
return 1 - (double)c/numBoxesUsed;
}
}
private int unixtimeToBucket(long unixtimeInSec) {
// Change origin to monday 5 jan 1970
unixtimeInSec -= 4*24*3600;
// now, %7 gives weekday where 0 ~ monday
// day of month is not possible here
return (int)((unixtimeInSec/(long)boxWidthInSeconds)%(long)numBoxes);
}
public String visualizeDistribution() {
String output = "\n" + this.name + ":\n";
if (tc.getTimeslots().isEmpty()) {
output += "Empty\n";
return output;
}
double normalizedDistribution[] = computeNormalizedDistribution(tc.getTimeslots(), this.numBoxes);
output += visualizeNormalizedDistribution(normalizedDistribution, 1);
output += "\nCOMPA distribution: \n";
double normalizedCOMPADistribution[] = computeNormalizedDistribution(computeCOMPADistribution(tc.getTimeslots(), this.numBoxes), this.numBoxes);
output += visualizeNormalizedDistribution(normalizedCOMPADistribution, 1);
return output;
}
@Override
public String compute() { return null; }
public Attribute getAttribute(){
return null;
}
public static String visualizeNormalizedDistribution(double normalizedDistribution[], int percentBox) {
String output = "";
double max = vecMax(normalizedDistribution) * 100;
if (max==0) {
output += "No data to visualize\n";
return output;
}
int start = (int)(max/percentBox)*percentBox;
int numElm = normalizedDistribution.length;
output += " % ^\n";
for (int i = start; i > 0; i-=percentBox) {
output += String.format("%3d",i) + " - |";
for (int j = 0; j < numElm; j++) {
if (normalizedDistribution[j] >= i/100.0) {
output += " X ";
} else {
output += " ";
}
}
output += "\n";
}
String footer = " Slot ";
output += " 0 - ";
for (int i = 0; i < numElm; i++) {
output += "---";
footer += String.format("%3d",i);
}
output += "->\n";
output = output + footer;
return output;
}
private static double[] normalizeDoubleArray(double[] arr) {
double[] normalizedDist = arr;
double sum = 0;
for (int i = 0; i < normalizedDist.length; i++) {
sum += normalizedDist[i];
}
for (int i = 0; i < normalizedDist.length; i++) {
normalizedDist[i] = normalizedDist[i]/sum;
}
return normalizedDist;
}
private static <T extends Number> double[] computeNormalizedDistribution(Map<Integer, T> map, int numBoxes) {
double sum = 0;
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
sum += ((Number)(((Map.Entry)it.next()).getValue())).doubleValue();
}
double normalized[] = new double[numBoxes];
try {
for (int key : map.keySet()) {
T val = map.get(key);
normalized[key] = val.doubleValue() / sum;
}
} catch (Exception e) {
e.printStackTrace();
}
return normalized;
}
private static double vecMax(double[] arr) {
double max = 0;
for (double elm : arr) {
max = elm > max ? elm : max;
}
return max;
}
public static Map<Integer, Double> computeCOMPADistribution(Map<Integer, Long> distribution, int numBoxes) {
HashMap<Integer, Double> compaDistribution = new HashMap<Integer, Double>();
compaDistribution.put(0, (
(distribution.containsKey(numBoxes-1) ? distribution.get(numBoxes-1) : 0) +
(distribution.containsKey(0) ? distribution.get(0) : 0) +
(distribution.containsKey(1) ? distribution.get(1) : 0)
)/3.0);
for (int key = 1; key < numBoxes - 1; key++) {
compaDistribution.put(key, (
(distribution.containsKey(key-1) ? distribution.get(key-1) : 0) +
(distribution.containsKey(key) ? distribution.get(key) : 0) +
(distribution.containsKey(key+1) ? distribution.get(key+1) : 0)
)/3.0);
}
compaDistribution.put(numBoxes-1, (
(distribution.containsKey(numBoxes-2) ? distribution.get(numBoxes-2) : 0) +
(distribution.containsKey(numBoxes-1) ? distribution.get(numBoxes-1) : 0) +
(distribution.containsKey(0) ? distribution.get(0) : 0)
)/3.0);
return compaDistribution;
}
public static long mapSum (Map<?, Long> map) {
long sum = 0;
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
sum += (Long)((Map.Entry)it.next()).getValue();
}
return sum;
}
}
|
UTF-8
|
Java
| 9,175 |
java
|
TimeDistribution.java
|
Java
|
[
{
"context": "Format;\r\nimport java.util.*;\r\n\r\n/**\r\n * Created by david on 2015-02-23.\r\n */\r\npublic class TimeDistributio",
"end": 328,
"score": 0.9978663921356201,
"start": 323,
"tag": "USERNAME",
"value": "david"
}
] | null |
[] |
package com.foi.entities.anomaly.features.compa;
import com.foi.entities.anomaly.AnomalyFeature;
import com.foi.entities.Tweet;
import com.foi.entities.containers.TimeContainer;
import weka.core.Attribute;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* Created by david on 2015-02-23.
*/
public class TimeDistribution extends AnomalyFeature {
private int boxWidthInSeconds;
private int numBoxes;
private TimeContainer tc;
private String featureKeyword;
public static SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM d HH:mm:ss Z yyyy");
public TimeDistribution(String name, TimeContainer tc, int boxWidthInSeconds, int numBoxes, String featureKeyword, double scoreWeight) {
this.name = name;
this.boxWidthInSeconds = boxWidthInSeconds;
this.numBoxes = numBoxes;
this.tc = tc;
this.numTweetsAnalyzed = mapSum(tc.getTimeslots());
this.featureKeyword = featureKeyword;
this.scoreWeight = scoreWeight;
}
public TimeDistribution(String name, TimeContainer tc, int boxWidthInSeconds, int numBoxes, String featureKeyword) {
this.name = name;
this.boxWidthInSeconds = boxWidthInSeconds;
this.numBoxes = numBoxes;
this.tc = tc;
this.numTweetsAnalyzed = mapSum(tc.getTimeslots());
this.featureKeyword = featureKeyword;
}
public TimeDistribution(String name, TimeContainer tc, int boxWidthInSeconds, int numBoxes) {
this.name = name;
this.boxWidthInSeconds = boxWidthInSeconds;
this.numBoxes = numBoxes;
this.tc = tc;
this.numTweetsAnalyzed = mapSum(tc.getTimeslots());
}
public TimeDistribution(String name, int boxWidthInSeconds, int numBoxes) {
this.name = name;
this.boxWidthInSeconds = boxWidthInSeconds;
this.numBoxes = numBoxes;
//this.normalizedDistribution = new double[numBoxes];
}
public double calculateAnomalyScore(int timeSlot) {
/* If the value is unseen before, it's anomaly */
if (!tc.getTimeslots().containsKey(timeSlot)) {
return 1;
}
int N = tc.getTimeslots().size();
long valuesSeen = mapSum(tc.getTimeslots());
double refRatio = (double)valuesSeen/N;
long c = tc.getTimeslots().get(timeSlot);
if (c >= refRatio) {
return 0;
} else {
return 1 - (double)c/N;
}
}
@Override
public void addTweetToModel(Tweet newTweet) {
DateFormat sdf = new SimpleDateFormat("EEE MMM d HH:mm:ss Z YYYY");
Date date;
try {
date = sdf.parse((String) newTweet.getProps().get("created_at"));
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
date = new Date(); // just for compiler reason..
}
int bucket = unixtimeToBucket(date.getTime());
tc.addTimeSlot(bucket);
numTweetsAnalyzed++;
}
@Override
public double calculateAnomalyScore(Tweet tweet) {
DateFormat sdf = new SimpleDateFormat("EEE MMM d HH:mm:ss Z YYYY");
Date date;
try {
date = sdf.parse((String) tweet.getProps().get("created_at"));
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
date = new Date(); // just for compiler reason..
}
int bucket = unixtimeToBucket(date.getTime());
int numBoxesUsed = tc.numNonEmptyTimeslots();
double refRatio = (double)numTweetsAnalyzed/numBoxesUsed; // I assume all time slots should be in here
long c = tc.getTimeslots().get(bucket) != null ? tc.getTimeslots().get(bucket) : 0L;
if (c >= refRatio) {
return 0;
} else {
return 1 - (double)c/numBoxesUsed;
}
}
private int unixtimeToBucket(long unixtimeInSec) {
// Change origin to monday 5 jan 1970
unixtimeInSec -= 4*24*3600;
// now, %7 gives weekday where 0 ~ monday
// day of month is not possible here
return (int)((unixtimeInSec/(long)boxWidthInSeconds)%(long)numBoxes);
}
public String visualizeDistribution() {
String output = "\n" + this.name + ":\n";
if (tc.getTimeslots().isEmpty()) {
output += "Empty\n";
return output;
}
double normalizedDistribution[] = computeNormalizedDistribution(tc.getTimeslots(), this.numBoxes);
output += visualizeNormalizedDistribution(normalizedDistribution, 1);
output += "\nCOMPA distribution: \n";
double normalizedCOMPADistribution[] = computeNormalizedDistribution(computeCOMPADistribution(tc.getTimeslots(), this.numBoxes), this.numBoxes);
output += visualizeNormalizedDistribution(normalizedCOMPADistribution, 1);
return output;
}
@Override
public String compute() { return null; }
public Attribute getAttribute(){
return null;
}
public static String visualizeNormalizedDistribution(double normalizedDistribution[], int percentBox) {
String output = "";
double max = vecMax(normalizedDistribution) * 100;
if (max==0) {
output += "No data to visualize\n";
return output;
}
int start = (int)(max/percentBox)*percentBox;
int numElm = normalizedDistribution.length;
output += " % ^\n";
for (int i = start; i > 0; i-=percentBox) {
output += String.format("%3d",i) + " - |";
for (int j = 0; j < numElm; j++) {
if (normalizedDistribution[j] >= i/100.0) {
output += " X ";
} else {
output += " ";
}
}
output += "\n";
}
String footer = " Slot ";
output += " 0 - ";
for (int i = 0; i < numElm; i++) {
output += "---";
footer += String.format("%3d",i);
}
output += "->\n";
output = output + footer;
return output;
}
private static double[] normalizeDoubleArray(double[] arr) {
double[] normalizedDist = arr;
double sum = 0;
for (int i = 0; i < normalizedDist.length; i++) {
sum += normalizedDist[i];
}
for (int i = 0; i < normalizedDist.length; i++) {
normalizedDist[i] = normalizedDist[i]/sum;
}
return normalizedDist;
}
private static <T extends Number> double[] computeNormalizedDistribution(Map<Integer, T> map, int numBoxes) {
double sum = 0;
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
sum += ((Number)(((Map.Entry)it.next()).getValue())).doubleValue();
}
double normalized[] = new double[numBoxes];
try {
for (int key : map.keySet()) {
T val = map.get(key);
normalized[key] = val.doubleValue() / sum;
}
} catch (Exception e) {
e.printStackTrace();
}
return normalized;
}
private static double vecMax(double[] arr) {
double max = 0;
for (double elm : arr) {
max = elm > max ? elm : max;
}
return max;
}
public static Map<Integer, Double> computeCOMPADistribution(Map<Integer, Long> distribution, int numBoxes) {
HashMap<Integer, Double> compaDistribution = new HashMap<Integer, Double>();
compaDistribution.put(0, (
(distribution.containsKey(numBoxes-1) ? distribution.get(numBoxes-1) : 0) +
(distribution.containsKey(0) ? distribution.get(0) : 0) +
(distribution.containsKey(1) ? distribution.get(1) : 0)
)/3.0);
for (int key = 1; key < numBoxes - 1; key++) {
compaDistribution.put(key, (
(distribution.containsKey(key-1) ? distribution.get(key-1) : 0) +
(distribution.containsKey(key) ? distribution.get(key) : 0) +
(distribution.containsKey(key+1) ? distribution.get(key+1) : 0)
)/3.0);
}
compaDistribution.put(numBoxes-1, (
(distribution.containsKey(numBoxes-2) ? distribution.get(numBoxes-2) : 0) +
(distribution.containsKey(numBoxes-1) ? distribution.get(numBoxes-1) : 0) +
(distribution.containsKey(0) ? distribution.get(0) : 0)
)/3.0);
return compaDistribution;
}
public static long mapSum (Map<?, Long> map) {
long sum = 0;
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
sum += (Long)((Map.Entry)it.next()).getValue();
}
return sum;
}
}
| 9,175 | 0.559782 | 0.5503 | 272 | 31.731617 | 29.331736 | 152 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.613971 | false | false |
14
|
563c790f0dbf8cf9fb87c9387291ece95d4f78e8
| 11,776,800,351,413 |
35bd568425d3bcd9c5298f3fa574bb349e65e990
|
/src/main/java/com/barath/app/model/InventoryDTO.java
|
80cf01e47f013574706c65e9402d2218246a152f
|
[] |
no_license
|
BarathArivazhagan/api-ai-chat-bot
|
https://github.com/BarathArivazhagan/api-ai-chat-bot
|
0ddc45014bd2371ab817c7454f0444704908a33c
|
5a5b5b9413888486aa1a61f5afe5cc840887f262
|
refs/heads/master
| 2021-01-23T10:03:59.122000 | 2017-09-07T12:24:27 | 2017-09-07T12:24:27 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.barath.app.model;
/**
* Created by barath.arivazhagan on 9/7/2017.
*/
public class InventoryDTO {
private String productName;
private String locationName;
private int quantity;
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getLocationName() {
return locationName;
}
public void setLocationName(String locationName) {
this.locationName = locationName;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
|
UTF-8
|
Java
| 707 |
java
|
InventoryDTO.java
|
Java
|
[
{
"context": "package com.barath.app.model;\n\n/**\n * Created by barath.arivazhagan on 9/7/2017.\n */\npublic class InventoryDTO {\n\n ",
"end": 67,
"score": 0.9979367852210999,
"start": 49,
"tag": "NAME",
"value": "barath.arivazhagan"
}
] | null |
[] |
package com.barath.app.model;
/**
* Created by barath.arivazhagan on 9/7/2017.
*/
public class InventoryDTO {
private String productName;
private String locationName;
private int quantity;
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getLocationName() {
return locationName;
}
public void setLocationName(String locationName) {
this.locationName = locationName;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
| 707 | 0.650636 | 0.64215 | 37 | 18.108109 | 17.748671 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.27027 | false | false |
14
|
b83bcc9e8b52f5a7c654e201afeed05a70b06903
| 11,519,102,355,943 |
29d77c675220b0aaabacccab54db4837b7fdda02
|
/dev/client/src/ilrp/net/IlrpClient.java
|
f5a48efc5c41a0e0fdd723ac1a9b6176aebdaab4
|
[] |
no_license
|
haibara-ai/i-love-red-packet
|
https://github.com/haibara-ai/i-love-red-packet
|
dabee63762aeae012ed16a57d0589480e2c8d728
|
2cdd01dd80329261f8e4c396f95b3b1afda414c8
|
refs/heads/master
| 2020-12-31T01:48:07.576000 | 2015-08-15T13:36:06 | 2015-08-15T13:36:06 | 39,515,025 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ilrp.net;
import ilrp.protocol.common.Callback;
import ilrp.protocol.common.Request;
import ilrp.protocol.common.Response;
import ilrp.protocol.packet.AuthResponse;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.LinkedList;
import java.util.Queue;
public class IlrpClient {
private static class Pair<F, S> {
public Pair(F f, S s) {
this.first = f;
this.second = s;
}
public F first;
public S second;
}
private Socket socket;
private ObjectInputStream is;
private ObjectOutputStream os;
private ClientStatus status;
private Queue<Pair<Request, Callback>> pending = new LinkedList<>();
public static enum ClientStatus {
DISCONNECTED, // not connected
UNAUTHORIZED, // connected but not authorized
AUTHORIZED, // authorized
CLOSED, // closed
}
private static class ResponseWaiter extends Thread {
public IlrpClient client;
public ResponseWaiter(IlrpClient client) {
this.client = client;
}
public void run() {
while (client.status != ClientStatus.CLOSED) {
Pair<Request, Callback> pair = null;
synchronized (client.pending) {
if (client.pending.size() > 0)
pair = client.pending.poll();
}
if (pair != null) {
try {
Request req = pair.first;
Response res = client.sendMessage(req);
pair.second.invoke(Callback.SUCCESS, req, res);
} catch (ClassNotFoundException | IOException e) {
pair.second.invoke(Callback.ERROR, pair.first, null);
e.printStackTrace();
}
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public IlrpClient() {
status = ClientStatus.DISCONNECTED;
}
public void openConnection(String host, int port) throws UnknownHostException, IOException {
socket = new Socket(host, port);
socket.setSoTimeout(20000); // wait 20s for response
status = ClientStatus.UNAUTHORIZED;
os = new ObjectOutputStream(socket.getOutputStream());
is = new ObjectInputStream(socket.getInputStream());
// start the daemon
new ResponseWaiter(this).start();
}
public void closeConnection() throws IOException {
// close directly
status = ClientStatus.CLOSED;
if (!socket.isClosed()) {
try {
socket.close();
} catch (IOException e) {
}
}
synchronized (pending) {
pending.clear();
}
}
/**
* send authorization request
* @param request
* @return
* @throws ClassNotFoundException
* @throws IOException
*/
public Response authorize(Request request) throws ClassNotFoundException, IOException {
if (status == ClientStatus.UNAUTHORIZED) {
Response res = sendMessage(request);
if (res instanceof AuthResponse) {
AuthResponse ar = (AuthResponse) res;
if (ar.status == AuthResponse.LICENSE_OK) {
status = ClientStatus.AUTHORIZED;
}
}
return res;
} else {
throw new IllegalStateException("can not authorize in " + status + " status.");
}
}
/**
* Send a message and wait for response
* @param msg
* @return
* @throws IOException
* @throws ClassNotFoundException
*/
private Response sendMessage(Request request) throws IOException, ClassNotFoundException {
os.writeObject(request);
os.flush();
return (Response) is.readObject();
}
/**
* Send a message and return
* Once there is a response, the callback will be called
* @param msg
* @param callback
*/
public void sendMessage(Request request, Callback callback) {
if (status == ClientStatus.AUTHORIZED) {
synchronized (pending) {
pending.add(new Pair<Request, Callback>(request, callback));
}
} else {
throw new IllegalStateException("can not send request in " + status + " status.");
}
}
}
|
UTF-8
|
Java
| 3,853 |
java
|
IlrpClient.java
|
Java
|
[] | null |
[] |
package ilrp.net;
import ilrp.protocol.common.Callback;
import ilrp.protocol.common.Request;
import ilrp.protocol.common.Response;
import ilrp.protocol.packet.AuthResponse;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.LinkedList;
import java.util.Queue;
public class IlrpClient {
private static class Pair<F, S> {
public Pair(F f, S s) {
this.first = f;
this.second = s;
}
public F first;
public S second;
}
private Socket socket;
private ObjectInputStream is;
private ObjectOutputStream os;
private ClientStatus status;
private Queue<Pair<Request, Callback>> pending = new LinkedList<>();
public static enum ClientStatus {
DISCONNECTED, // not connected
UNAUTHORIZED, // connected but not authorized
AUTHORIZED, // authorized
CLOSED, // closed
}
private static class ResponseWaiter extends Thread {
public IlrpClient client;
public ResponseWaiter(IlrpClient client) {
this.client = client;
}
public void run() {
while (client.status != ClientStatus.CLOSED) {
Pair<Request, Callback> pair = null;
synchronized (client.pending) {
if (client.pending.size() > 0)
pair = client.pending.poll();
}
if (pair != null) {
try {
Request req = pair.first;
Response res = client.sendMessage(req);
pair.second.invoke(Callback.SUCCESS, req, res);
} catch (ClassNotFoundException | IOException e) {
pair.second.invoke(Callback.ERROR, pair.first, null);
e.printStackTrace();
}
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public IlrpClient() {
status = ClientStatus.DISCONNECTED;
}
public void openConnection(String host, int port) throws UnknownHostException, IOException {
socket = new Socket(host, port);
socket.setSoTimeout(20000); // wait 20s for response
status = ClientStatus.UNAUTHORIZED;
os = new ObjectOutputStream(socket.getOutputStream());
is = new ObjectInputStream(socket.getInputStream());
// start the daemon
new ResponseWaiter(this).start();
}
public void closeConnection() throws IOException {
// close directly
status = ClientStatus.CLOSED;
if (!socket.isClosed()) {
try {
socket.close();
} catch (IOException e) {
}
}
synchronized (pending) {
pending.clear();
}
}
/**
* send authorization request
* @param request
* @return
* @throws ClassNotFoundException
* @throws IOException
*/
public Response authorize(Request request) throws ClassNotFoundException, IOException {
if (status == ClientStatus.UNAUTHORIZED) {
Response res = sendMessage(request);
if (res instanceof AuthResponse) {
AuthResponse ar = (AuthResponse) res;
if (ar.status == AuthResponse.LICENSE_OK) {
status = ClientStatus.AUTHORIZED;
}
}
return res;
} else {
throw new IllegalStateException("can not authorize in " + status + " status.");
}
}
/**
* Send a message and wait for response
* @param msg
* @return
* @throws IOException
* @throws ClassNotFoundException
*/
private Response sendMessage(Request request) throws IOException, ClassNotFoundException {
os.writeObject(request);
os.flush();
return (Response) is.readObject();
}
/**
* Send a message and return
* Once there is a response, the callback will be called
* @param msg
* @param callback
*/
public void sendMessage(Request request, Callback callback) {
if (status == ClientStatus.AUTHORIZED) {
synchronized (pending) {
pending.add(new Pair<Request, Callback>(request, callback));
}
} else {
throw new IllegalStateException("can not send request in " + status + " status.");
}
}
}
| 3,853 | 0.68518 | 0.682325 | 151 | 24.516556 | 21.022175 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.483444 | false | false |
14
|
896bf68337718cd73383d4809498283b2e9cd3c5
| 32,839,319,964,223 |
80aa733ce090ff3098899bd0a74a5a4c8b3e8d20
|
/src/service/smart-contract-server/src/main/java/service/ContractService.java
|
96562b24b1c92a3d439bf3c8f8741c52d3971c55
|
[] |
no_license
|
juaneulate/smartcontrat
|
https://github.com/juaneulate/smartcontrat
|
3975782f0f4d2a0ecf248e1e919b8187772d616f
|
ddde1d85334ad6d0cee48e02acd46770ffb39fc1
|
refs/heads/master
| 2023-01-08T09:24:33.562000 | 2019-06-25T01:00:05 | 2019-06-25T01:00:05 | 192,136,745 | 0 | 0 | null | false | 2023-01-07T06:26:11 | 2019-06-16T00:58:02 | 2019-06-25T01:01:25 | 2023-01-07T06:26:10 | 29,198 | 0 | 0 | 28 |
TypeScript
| false | false |
package service;
import dao.ContractDao;
import entity.ContractEntity;
import javax.inject.Inject;
import javax.inject.Named;
import javax.transaction.Transactional;
import java.io.Serializable;
import java.util.List;
import java.util.Optional;
@Named
public class ContractService implements Serializable {
@Inject
private ContractDao contractDao;
public List<ContractEntity> findAll() {
return contractDao.findAll();
}
@Transactional
public ContractEntity save(ContractEntity contract) {
return contractDao.merge(contract);
}
@Transactional
public void remove(ContractEntity contract) {
contractDao.remove(contract);
}
@Transactional
public void deleteAll(List<ContractEntity> listToDelete) {
for (ContractEntity contract : listToDelete) {
remove(contract);
}
}
public Optional<ContractEntity> getById(long id) {
return contractDao.getById(id);
}
public List<ContractEntity> findAllByPersonId(long personId) {
return contractDao.findAllByPersonId(personId);
}
}
|
UTF-8
|
Java
| 1,158 |
java
|
ContractService.java
|
Java
|
[] | null |
[] |
package service;
import dao.ContractDao;
import entity.ContractEntity;
import javax.inject.Inject;
import javax.inject.Named;
import javax.transaction.Transactional;
import java.io.Serializable;
import java.util.List;
import java.util.Optional;
@Named
public class ContractService implements Serializable {
@Inject
private ContractDao contractDao;
public List<ContractEntity> findAll() {
return contractDao.findAll();
}
@Transactional
public ContractEntity save(ContractEntity contract) {
return contractDao.merge(contract);
}
@Transactional
public void remove(ContractEntity contract) {
contractDao.remove(contract);
}
@Transactional
public void deleteAll(List<ContractEntity> listToDelete) {
for (ContractEntity contract : listToDelete) {
remove(contract);
}
}
public Optional<ContractEntity> getById(long id) {
return contractDao.getById(id);
}
public List<ContractEntity> findAllByPersonId(long personId) {
return contractDao.findAllByPersonId(personId);
}
}
| 1,158 | 0.67962 | 0.67962 | 48 | 22.125 | 20.451797 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false |
14
|
2a87a1456afb034443a15613142efc3741de0b5b
| 34,583,076,673,200 |
8ba87d8e4b630ee5e189c4678e3f314e7f186b79
|
/android/src/com/mygdx/game/psg/AndroidLauncher.java
|
daf445376977a64969e8e468ea3c8ac7ff187bb1
|
[] |
no_license
|
FeMinorelli/testpsg
|
https://github.com/FeMinorelli/testpsg
|
a9eb021f61a852eea85b6efff7ac1276f20e8646
|
01da5eebd28eea2f7bbb9b31f3b013a593efd0ea
|
refs/heads/master
| 2020-03-28T20:21:37.541000 | 2019-02-15T18:03:23 | 2019-02-15T18:03:23 | 149,062,543 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.mygdx.game.psg;
import android.os.Bundle;
import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
import java.io.IOException;
public class AndroidLauncher extends AndroidApplication {
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
try {
initialize(new MainGame(), config);
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
UTF-8
|
Java
| 574 |
java
|
AndroidLauncher.java
|
Java
|
[] | null |
[] |
package com.mygdx.game.psg;
import android.os.Bundle;
import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
import java.io.IOException;
public class AndroidLauncher extends AndroidApplication {
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
try {
initialize(new MainGame(), config);
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 574 | 0.790941 | 0.790941 | 22 | 25.09091 | 25.335762 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.318182 | false | false |
14
|
e2792da47f74194c48e0fcb9a368f0e8447ba2c3
| 34,746,285,433,049 |
519b3056c885bcbbc1306c8d6e56c4132fbc866c
|
/app/src/main/java/com/multi/schooldiary/notification/ExampleJobService.java
|
addf1b3013a2fdaa85d7e1e01c3cc5270e9d81b9
|
[] |
no_license
|
mdmuneerhasan/schoolDiary
|
https://github.com/mdmuneerhasan/schoolDiary
|
f28f7a6b7cff18aecaee737a891e0cf316cf7b45
|
9e0fc413d4e21338dc14b8c11008314c823c4c95
|
refs/heads/master
| 2020-06-10T20:53:50.034000 | 2019-08-09T20:41:56 | 2019-08-09T20:41:56 | 193,743,721 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.multi.schooldiary.notification;
import android.app.job.JobParameters;
import android.app.job.JobService;
import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.util.Log;
public class ExampleJobService extends JobService {
private static final String TAG = "ExampleJobService";
private boolean jobCancelled = false;
@Override
public boolean onStartJob(JobParameters params) {
Log.d(TAG, "Job started");
doBackgroundWork(params);
return true;
}
private void doBackgroundWork(final JobParameters params) {
new Thread(new Runnable() {
@Override
public void run() {
Intent serviceIntent = new Intent(getBaseContext(), MyService.class);
serviceIntent.putExtra("inputExtra", "hello Services");
ContextCompat.startForegroundService(getBaseContext(), serviceIntent);
Log.d(TAG, "Job finished");
jobFinished(params, false);
}
}).start();
}
@Override
public boolean onStopJob(JobParameters params) {
Log.d(TAG, "Job cancelled before completion");
jobCancelled = true;
return true;
}
}
|
UTF-8
|
Java
| 1,250 |
java
|
ExampleJobService.java
|
Java
|
[] | null |
[] |
package com.multi.schooldiary.notification;
import android.app.job.JobParameters;
import android.app.job.JobService;
import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.util.Log;
public class ExampleJobService extends JobService {
private static final String TAG = "ExampleJobService";
private boolean jobCancelled = false;
@Override
public boolean onStartJob(JobParameters params) {
Log.d(TAG, "Job started");
doBackgroundWork(params);
return true;
}
private void doBackgroundWork(final JobParameters params) {
new Thread(new Runnable() {
@Override
public void run() {
Intent serviceIntent = new Intent(getBaseContext(), MyService.class);
serviceIntent.putExtra("inputExtra", "hello Services");
ContextCompat.startForegroundService(getBaseContext(), serviceIntent);
Log.d(TAG, "Job finished");
jobFinished(params, false);
}
}).start();
}
@Override
public boolean onStopJob(JobParameters params) {
Log.d(TAG, "Job cancelled before completion");
jobCancelled = true;
return true;
}
}
| 1,250 | 0.652 | 0.6512 | 39 | 31.076923 | 23.365967 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.692308 | false | false |
14
|
048999ca47ae0f7d80b66b2d5c965733a777cedb
| 14,680,198,261,366 |
7653e008384de73b57411b7748dab52b561d51e6
|
/SrcGame/dwo/gameserver/handler/transformations/GuardsoftheDawn.java
|
2993fa32ca99f0c0ad861fb8a6cd64e3d723d4a8
|
[] |
no_license
|
BloodyDawn/Ertheia
|
https://github.com/BloodyDawn/Ertheia
|
14520ecd79c38acf079de05c316766280ae6c0e8
|
d90d7f079aa370b57999d483c8309ce833ff8af0
|
refs/heads/master
| 2021-01-11T22:10:19.455000 | 2017-01-14T12:15:56 | 2017-01-14T12:15:56 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package dwo.gameserver.handler.transformations;
import dwo.gameserver.model.skills.L2Transformation;
import dwo.gameserver.model.skills.SkillTable;
public class GuardsoftheDawn extends L2Transformation
{
private static final int[] Skills = {963, 5491};
public GuardsoftheDawn()
{
// id, colRadius, colHeight
super(113, 8, 23.5);
}
@Override
public void transformedSkills()
{
getPlayer().getInventory().blockAllItems();
getPlayer().addSkill(SkillTable.getInstance().getInfo(963, 1), false);
// Decrease Bow/Crossbow Attack Speed
getPlayer().addSkill(SkillTable.getInstance().getInfo(5491, 1), false);
getPlayer().setTransformAllowedSkills(Skills);
}
@Override
public void removeSkills()
{
getPlayer().getInventory().unblock();
getPlayer().removeSkill(SkillTable.getInstance().getInfo(963, 1), false);
// Decrease Bow/Crossbow Attack Speed
getPlayer().removeSkill(SkillTable.getInstance().getInfo(5491, 1), false);
getPlayer().setTransformAllowedSkills(EMPTY_ARRAY);
}
@Override
public boolean canDoMeleeAttack()
{
return false;
}
}
|
UTF-8
|
Java
| 1,078 |
java
|
GuardsoftheDawn.java
|
Java
|
[] | null |
[] |
package dwo.gameserver.handler.transformations;
import dwo.gameserver.model.skills.L2Transformation;
import dwo.gameserver.model.skills.SkillTable;
public class GuardsoftheDawn extends L2Transformation
{
private static final int[] Skills = {963, 5491};
public GuardsoftheDawn()
{
// id, colRadius, colHeight
super(113, 8, 23.5);
}
@Override
public void transformedSkills()
{
getPlayer().getInventory().blockAllItems();
getPlayer().addSkill(SkillTable.getInstance().getInfo(963, 1), false);
// Decrease Bow/Crossbow Attack Speed
getPlayer().addSkill(SkillTable.getInstance().getInfo(5491, 1), false);
getPlayer().setTransformAllowedSkills(Skills);
}
@Override
public void removeSkills()
{
getPlayer().getInventory().unblock();
getPlayer().removeSkill(SkillTable.getInstance().getInfo(963, 1), false);
// Decrease Bow/Crossbow Attack Speed
getPlayer().removeSkill(SkillTable.getInstance().getInfo(5491, 1), false);
getPlayer().setTransformAllowedSkills(EMPTY_ARRAY);
}
@Override
public boolean canDoMeleeAttack()
{
return false;
}
}
| 1,078 | 0.748609 | 0.717069 | 41 | 25.317074 | 24.689722 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.682927 | false | false |
14
|
979a52006a4dce042e79c9ba9a7710f7a5828f57
| 9,285,719,328,805 |
2e8b70e0fc5f8381319d74ddd062848056a9fc45
|
/TP2/java/src/main/java/CAP8/E5_Time2Mod.java
|
1ba28ddfc8e34d997fac1f77b2fe280dd80d7479
|
[] |
no_license
|
LucianoAlbanes/ParadigmasProgramacion
|
https://github.com/LucianoAlbanes/ParadigmasProgramacion
|
ca30cde8e617559a49cb5c9208b7d386d9d65b3a
|
faab62a4903d8de5eb64bec21de6b409a8bf6b88
|
refs/heads/main
| 2023-08-24T04:36:00.534000 | 2021-11-02T18:49:23 | 2021-11-02T18:49:23 | 401,691,786 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package CAP8;
/*
(Modifying the Internal Data Representation of a Class) It would be perfectly reasonable
for the Time2 class of Fig. 8.5 to represent the time internally as the number of seconds since mid-
night rather than the three integer values hour, minute and second. Clients could use the same pub-
lic methods and get the same results. Modify the Time2 class of Fig. 8.5 to implement the time as
the number of seconds since midnight and show that no change is visible to the clients of the class.
*/
public class E5_Time2Mod {
public static void main(String[] args) {
Time2 time = new Time2(18,15,55);
System.out.println(time.toUniversalString());
time.setMinute(33);
System.out.println(time.toUniversalString());
}
}
class Time2 {
private int seconds; // Seconds since midnight
// Time2 no-argument constructor:
// initializes each instance variable to zero
public Time2() {
this(0, 0, 0); // invoke constructor with three arguments
}
// Time2 constructor: hour supplied, minute and second defaulted to 0
public Time2(int hour) {
this(hour, 0, 0); // invoke constructor with three arguments
}
// Time2 constructor: hour and minute supplied, second defaulted to 0
public Time2(int hour, int minute) {
this(hour, minute, 0); // invoke constructor with three arguments
}
// Time2 constructor: hour, minute and second supplied
public Time2(int hour, int minute, int second) {
if (hour < 0 || hour >= 24) {
throw new IllegalArgumentException("hour must be 0-23");
}
if (minute < 0 || minute >= 60) {
throw new IllegalArgumentException("minute must be 0-59");
}
if (second < 0 || second >= 60) {
throw new IllegalArgumentException("second must be 0-59");
}
seconds = toSeconds(hour, minute, second);
}
// Time2 constructor: another Time2 object supplied
public Time2(Time2 time) {
// Gets the seconds from time and copy to the new Time2 object.
seconds = time.seconds;
}
// Set Methods
// set a new time value using universal time;
// validate the data
public void setTime(int hour, int minute, int second) {
if (hour < 0 || hour >= 24) {
throw new IllegalArgumentException("hour must be 0-23");
}
if (minute < 0 || minute >= 60) {
throw new IllegalArgumentException("minute must be 0-59");
}
if (second < 0 || second >= 60) {
throw new IllegalArgumentException("second must be 0-59");
}
seconds = toSeconds(hour, minute, second);
}
// validate and set hour
public void setHour(int hour) {
if (hour < 0 || hour >= 24) {
throw new IllegalArgumentException("hour must be 0-23");
}
seconds -= toSeconds(getHour(),0,0);
seconds += toSeconds(hour,0,0);
}
// validate and set minute
public void setMinute(int minute) {
if (minute < 0 || minute >= 60) {
throw new IllegalArgumentException("minute must be 0-59");
}
seconds -= toSeconds(0,getMinute(),0);
seconds += toSeconds(0,minute,0);
}
// validate and set second
public void setSecond(int second) {
if (second < 0 || second >= 60) {
throw new IllegalArgumentException("second must be 0-59");
}
seconds -= toSeconds(0,0,getSecond());
seconds += toSeconds(0,0,second);
}
// Get Methods
// get hour value
public int getHour() {
return seconds/3600;
}
// get minute value
public int getMinute() {
return (seconds%3600)/60;
}
// get second value
public int getSecond() {
return (seconds%3600)%60;
}
// convert to String in universal-time format (HH:MM:SS)
public String toUniversalString() {
return String.format("%02d:%02d:%02d", getHour(), getMinute(), getSecond());
}
// convert to String in standard-time format (H:MM:SS AM or PM)
public String toString() {
return String.format("%d:%02d:%02d %s",
((getHour() == 0 || getHour() == 12) ? 12 : getHour() % 12),
getMinute(), getSecond(), (getHour() < 12 ? "AM" : "PM"));
}
// calculate the amount of seconds since midnight from a given time in format (HH:MM:SS)
private static int toSeconds(int hour, int minute, int second) {
return hour * 3600 + minute * 60 + second;
}
}
|
UTF-8
|
Java
| 4,565 |
java
|
E5_Time2Mod.java
|
Java
|
[] | null |
[] |
package CAP8;
/*
(Modifying the Internal Data Representation of a Class) It would be perfectly reasonable
for the Time2 class of Fig. 8.5 to represent the time internally as the number of seconds since mid-
night rather than the three integer values hour, minute and second. Clients could use the same pub-
lic methods and get the same results. Modify the Time2 class of Fig. 8.5 to implement the time as
the number of seconds since midnight and show that no change is visible to the clients of the class.
*/
public class E5_Time2Mod {
public static void main(String[] args) {
Time2 time = new Time2(18,15,55);
System.out.println(time.toUniversalString());
time.setMinute(33);
System.out.println(time.toUniversalString());
}
}
class Time2 {
private int seconds; // Seconds since midnight
// Time2 no-argument constructor:
// initializes each instance variable to zero
public Time2() {
this(0, 0, 0); // invoke constructor with three arguments
}
// Time2 constructor: hour supplied, minute and second defaulted to 0
public Time2(int hour) {
this(hour, 0, 0); // invoke constructor with three arguments
}
// Time2 constructor: hour and minute supplied, second defaulted to 0
public Time2(int hour, int minute) {
this(hour, minute, 0); // invoke constructor with three arguments
}
// Time2 constructor: hour, minute and second supplied
public Time2(int hour, int minute, int second) {
if (hour < 0 || hour >= 24) {
throw new IllegalArgumentException("hour must be 0-23");
}
if (minute < 0 || minute >= 60) {
throw new IllegalArgumentException("minute must be 0-59");
}
if (second < 0 || second >= 60) {
throw new IllegalArgumentException("second must be 0-59");
}
seconds = toSeconds(hour, minute, second);
}
// Time2 constructor: another Time2 object supplied
public Time2(Time2 time) {
// Gets the seconds from time and copy to the new Time2 object.
seconds = time.seconds;
}
// Set Methods
// set a new time value using universal time;
// validate the data
public void setTime(int hour, int minute, int second) {
if (hour < 0 || hour >= 24) {
throw new IllegalArgumentException("hour must be 0-23");
}
if (minute < 0 || minute >= 60) {
throw new IllegalArgumentException("minute must be 0-59");
}
if (second < 0 || second >= 60) {
throw new IllegalArgumentException("second must be 0-59");
}
seconds = toSeconds(hour, minute, second);
}
// validate and set hour
public void setHour(int hour) {
if (hour < 0 || hour >= 24) {
throw new IllegalArgumentException("hour must be 0-23");
}
seconds -= toSeconds(getHour(),0,0);
seconds += toSeconds(hour,0,0);
}
// validate and set minute
public void setMinute(int minute) {
if (minute < 0 || minute >= 60) {
throw new IllegalArgumentException("minute must be 0-59");
}
seconds -= toSeconds(0,getMinute(),0);
seconds += toSeconds(0,minute,0);
}
// validate and set second
public void setSecond(int second) {
if (second < 0 || second >= 60) {
throw new IllegalArgumentException("second must be 0-59");
}
seconds -= toSeconds(0,0,getSecond());
seconds += toSeconds(0,0,second);
}
// Get Methods
// get hour value
public int getHour() {
return seconds/3600;
}
// get minute value
public int getMinute() {
return (seconds%3600)/60;
}
// get second value
public int getSecond() {
return (seconds%3600)%60;
}
// convert to String in universal-time format (HH:MM:SS)
public String toUniversalString() {
return String.format("%02d:%02d:%02d", getHour(), getMinute(), getSecond());
}
// convert to String in standard-time format (H:MM:SS AM or PM)
public String toString() {
return String.format("%d:%02d:%02d %s",
((getHour() == 0 || getHour() == 12) ? 12 : getHour() % 12),
getMinute(), getSecond(), (getHour() < 12 ? "AM" : "PM"));
}
// calculate the amount of seconds since midnight from a given time in format (HH:MM:SS)
private static int toSeconds(int hour, int minute, int second) {
return hour * 3600 + minute * 60 + second;
}
}
| 4,565 | 0.60701 | 0.574589 | 134 | 33.067165 | 27.755381 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.716418 | false | false |
14
|
0a6dd3984749d71fcf243f9c4896206744ae96bb
| 13,718,125,587,247 |
c256472f919ea8978f59ce0117d26bcc313f108d
|
/src/main/java/commands/ShopCommand.java
|
39b9d27548463f679f40afaff019788aaedbfbd5
|
[] |
no_license
|
vladyour/PMPUGame
|
https://github.com/vladyour/PMPUGame
|
f5751270c91a4daae39d0546660e76e9999a1b08
|
984e4593570c06762f6f51d0a6a7416e2ba5c33a
|
refs/heads/master
| 2019-01-14T05:09:49.729000 | 2017-06-25T21:00:45 | 2017-06-25T21:00:45 | 95,385,570 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package commands;
import botExceptions.BotException;
import model.Team;
import org.telegram.telegrambots.api.methods.send.SendMessage;
import org.telegram.telegrambots.api.objects.Message;
import static dao.TeamDaoImpl.getTeamByTelegramId;
import static model.Logger.log;
/**
* Created by vlad.your on 26.09.2016.
*/
public class ShopCommand implements Command {
@Override
public SendMessage getMessage(Message message) throws BotException {
SendMessage sendMessageRequest = new SendMessage().enableHtml(true);
sendMessageRequest.setChatId(message.getChatId().toString());
Team team = getTeamByTelegramId(message.getChatId().toString());
if (team == null) {
log("Кто-то попытался войти в магазин");
throw new BotException("Вам недоступна эта команда");
}
log("Группа " + team.getNumber() + " вошла в магазин");
sendMessageRequest.setText("<b>Добро пожаловать в магазин!</b> Нажмите:\n" +
"/outOfTurn <i>номер_станции</i>, чтобы пройти без очереди (цена: 200 ПMoney).\n" +
"/getCourse, чтобы получить 1000 едениц опыта (цена: 400 ПMoney, не более 2х раз).");
return sendMessageRequest;
}
}
|
UTF-8
|
Java
| 1,437 |
java
|
ShopCommand.java
|
Java
|
[
{
"context": "ort static model.Logger.log;\r\n\r\n/**\r\n * Created by vlad.your on 26.09.2016.\r\n */\r\npublic class ShopCommand imp",
"end": 313,
"score": 0.9993629455566406,
"start": 304,
"tag": "USERNAME",
"value": "vlad.your"
}
] | null |
[] |
package commands;
import botExceptions.BotException;
import model.Team;
import org.telegram.telegrambots.api.methods.send.SendMessage;
import org.telegram.telegrambots.api.objects.Message;
import static dao.TeamDaoImpl.getTeamByTelegramId;
import static model.Logger.log;
/**
* Created by vlad.your on 26.09.2016.
*/
public class ShopCommand implements Command {
@Override
public SendMessage getMessage(Message message) throws BotException {
SendMessage sendMessageRequest = new SendMessage().enableHtml(true);
sendMessageRequest.setChatId(message.getChatId().toString());
Team team = getTeamByTelegramId(message.getChatId().toString());
if (team == null) {
log("Кто-то попытался войти в магазин");
throw new BotException("Вам недоступна эта команда");
}
log("Группа " + team.getNumber() + " вошла в магазин");
sendMessageRequest.setText("<b>Добро пожаловать в магазин!</b> Нажмите:\n" +
"/outOfTurn <i>номер_станции</i>, чтобы пройти без очереди (цена: 200 ПMoney).\n" +
"/getCourse, чтобы получить 1000 едениц опыта (цена: 400 ПMoney, не более 2х раз).");
return sendMessageRequest;
}
}
| 1,437 | 0.669841 | 0.654762 | 33 | 36.242424 | 31.644838 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.545455 | false | false |
14
|
a891c0f58a6e6dc16d7dad961a5aafa11a32ee8e
| 867,583,409,492 |
5e43729e866787b8728094e709b050d0534831be
|
/NewProject/SpringStudy/src/main/java/com/xuzhi/service/AfterReturnningService.java
|
b6fa0cb55054ca7865b934efd4558eda15ded2c9
|
[] |
no_license
|
xuzhi7162/SSM-study
|
https://github.com/xuzhi7162/SSM-study
|
c428510c4b6a7be7c8733207120245c404dc4967
|
5c725d9a4d53875e00341d04363e081d16a24dd1
|
refs/heads/master
| 2020-04-14T16:55:40.137000 | 2019-03-14T12:51:46 | 2019-03-14T12:51:46 | 163,964,973 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.xuzhi.service;
public class AfterReturnningService {
public String afterReturnService(){
System.out.println("我是正在执行的方法");
return "我是为了测试返回值切面";
}
}
|
UTF-8
|
Java
| 225 |
java
|
AfterReturnningService.java
|
Java
|
[] | null |
[] |
package com.xuzhi.service;
public class AfterReturnningService {
public String afterReturnService(){
System.out.println("我是正在执行的方法");
return "我是为了测试返回值切面";
}
}
| 225 | 0.686486 | 0.686486 | 8 | 22.125 | 16.266819 | 40 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false |
14
|
07f287efe0a9666e8c0e0892423009af06f2efde
| 13,958,643,746,544 |
8069e38aeccef425723629608d0ba03683664735
|
/app/src/main/java/com/crazy/taolove/activity/GiveVipActivity.java
|
d1136324a99c1273a2d7ccfa8bb41226b1452497
|
[] |
no_license
|
wybilold1999/TaoPrj
|
https://github.com/wybilold1999/TaoPrj
|
7b7b7c8e8d1dbe8f422f428743e42b5c088cfba3
|
cb6faa27d0cb719f728361381cd8480c30cedb5b
|
refs/heads/master
| 2020-03-25T07:41:04.556000 | 2018-09-21T02:58:42 | 2018-09-21T02:58:42 | 143,575,750 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.crazy.taolove.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import com.crazy.taolove.R;
import com.crazy.taolove.activity.base.BaseActivity;
import com.crazy.taolove.config.AppConstants;
import com.crazy.taolove.config.ValueKey;
import com.crazy.taolove.manager.AppManager;
import com.crazy.taolove.net.request.OSSImagUploadRequest;
import com.crazy.taolove.net.request.UploadCommentImgRequest;
import com.crazy.taolove.utils.CheckUtil;
import com.crazy.taolove.utils.PreferencesUtils;
import com.crazy.taolove.utils.ProgressDialogUtils;
import com.crazy.taolove.utils.ToastUtil;
import com.umeng.analytics.MobclickAgent;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import mehdi.sakout.fancybuttons.FancyButton;
/**
* @author wangyb
* @Description:赠送vip
* @Date:2015年7月13日下午2:21:46
*/
public class GiveVipActivity extends BaseActivity {
public static final int CHOOSE_IMG_RESULT = 0;
@BindView(R.id.skip_market)
FancyButton mSkipMarket;
@BindView(R.id.upload_img)
FancyButton mUploadImg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_give_vip);
ButterKnife.bind(this);
Toolbar toolbar = getActionBarToolbar();
if (toolbar != null) {
toolbar.setNavigationIcon(R.mipmap.ic_up);
}
setupViews();
setupEvent();
setupData();
}
/**
* 设置视图
*/
private void setupViews() {
}
/**
* 设置事件
*/
private void setupEvent() {
}
/**
* 设置数据
*/
private void setupData() {
if (PreferencesUtils.getIsUploadCommentImg(this)) {
mUploadImg.setEnabled(false);
mUploadImg.setFocusBackgroundColor(getResources().getColor(R.color.gray_text));
mUploadImg.setBackgroundColor(getResources().getColor(R.color.gray_text));
}
}
@Override
protected void onResume() {
super.onResume();
MobclickAgent.onPageStart(this.getClass().getName());
MobclickAgent.onResume(this);
}
@Override
protected void onPause() {
super.onPause();
MobclickAgent.onPageEnd(this.getClass().getName());
MobclickAgent.onPause(this);
}
@OnClick({R.id.skip_market, R.id.upload_img})
public void onViewClicked(View view) {
Intent intent = new Intent();
switch (view.getId()) {
case R.id.skip_market:
AppManager.goToMarket(this, CheckUtil.getAppMetaData(this, "UMENG_CHANNEL"));
break;
case R.id.upload_img:
intent.setClass(this, PhotoChoserActivity.class);
intent.putExtra(ValueKey.DATA, 1);
startActivityForResult(intent, CHOOSE_IMG_RESULT);
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == CHOOSE_IMG_RESULT) {
List<String> imgUrls = data.getStringArrayListExtra(ValueKey.IMAGE_URL);
if (null != imgUrls && imgUrls.size() > 0) {
ProgressDialogUtils.getInstance(this).show(R.string.dialog_request_uploda);
new OSSUploadImgTask().request(AppManager.getFederationToken().bucketName,
AppManager.getOSSFacePath(), imgUrls.get(0));
}
}
}
class OSSUploadImgTask extends OSSImagUploadRequest {
@Override
public void onPostExecute(String s) {
String url = AppConstants.OSS_IMG_ENDPOINT + s;
new UploadCImgTask().request(url);
}
@Override
public void onErrorExecute(String error) {
ProgressDialogUtils.getInstance(GiveVipActivity.this).dismiss();
}
}
class UploadCImgTask extends UploadCommentImgRequest {
@Override
public void onPostExecute(String s) {
ProgressDialogUtils.getInstance(GiveVipActivity.this).dismiss();
ToastUtil.showMessage(s);
PreferencesUtils.setIsUploadCommentImg(GiveVipActivity.this, true);
mUploadImg.setEnabled(false);
mUploadImg.setFocusBackgroundColor(getResources().getColor(R.color.gray_text));
mUploadImg.setBackgroundColor(getResources().getColor(R.color.gray_text));
}
@Override
public void onErrorExecute(String error) {
ProgressDialogUtils.getInstance(GiveVipActivity.this).dismiss();
ToastUtil.showMessage(error);
}
}
}
|
UTF-8
|
Java
| 4,881 |
java
|
GiveVipActivity.java
|
Java
|
[
{
"context": "i.sakout.fancybuttons.FancyButton;\n\n/**\n * @author wangyb\n * @Description:赠送vip\n * @Date:2015年7月13日下午2:21:4",
"end": 907,
"score": 0.9991828799247742,
"start": 901,
"tag": "USERNAME",
"value": "wangyb"
}
] | null |
[] |
package com.crazy.taolove.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import com.crazy.taolove.R;
import com.crazy.taolove.activity.base.BaseActivity;
import com.crazy.taolove.config.AppConstants;
import com.crazy.taolove.config.ValueKey;
import com.crazy.taolove.manager.AppManager;
import com.crazy.taolove.net.request.OSSImagUploadRequest;
import com.crazy.taolove.net.request.UploadCommentImgRequest;
import com.crazy.taolove.utils.CheckUtil;
import com.crazy.taolove.utils.PreferencesUtils;
import com.crazy.taolove.utils.ProgressDialogUtils;
import com.crazy.taolove.utils.ToastUtil;
import com.umeng.analytics.MobclickAgent;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import mehdi.sakout.fancybuttons.FancyButton;
/**
* @author wangyb
* @Description:赠送vip
* @Date:2015年7月13日下午2:21:46
*/
public class GiveVipActivity extends BaseActivity {
public static final int CHOOSE_IMG_RESULT = 0;
@BindView(R.id.skip_market)
FancyButton mSkipMarket;
@BindView(R.id.upload_img)
FancyButton mUploadImg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_give_vip);
ButterKnife.bind(this);
Toolbar toolbar = getActionBarToolbar();
if (toolbar != null) {
toolbar.setNavigationIcon(R.mipmap.ic_up);
}
setupViews();
setupEvent();
setupData();
}
/**
* 设置视图
*/
private void setupViews() {
}
/**
* 设置事件
*/
private void setupEvent() {
}
/**
* 设置数据
*/
private void setupData() {
if (PreferencesUtils.getIsUploadCommentImg(this)) {
mUploadImg.setEnabled(false);
mUploadImg.setFocusBackgroundColor(getResources().getColor(R.color.gray_text));
mUploadImg.setBackgroundColor(getResources().getColor(R.color.gray_text));
}
}
@Override
protected void onResume() {
super.onResume();
MobclickAgent.onPageStart(this.getClass().getName());
MobclickAgent.onResume(this);
}
@Override
protected void onPause() {
super.onPause();
MobclickAgent.onPageEnd(this.getClass().getName());
MobclickAgent.onPause(this);
}
@OnClick({R.id.skip_market, R.id.upload_img})
public void onViewClicked(View view) {
Intent intent = new Intent();
switch (view.getId()) {
case R.id.skip_market:
AppManager.goToMarket(this, CheckUtil.getAppMetaData(this, "UMENG_CHANNEL"));
break;
case R.id.upload_img:
intent.setClass(this, PhotoChoserActivity.class);
intent.putExtra(ValueKey.DATA, 1);
startActivityForResult(intent, CHOOSE_IMG_RESULT);
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == CHOOSE_IMG_RESULT) {
List<String> imgUrls = data.getStringArrayListExtra(ValueKey.IMAGE_URL);
if (null != imgUrls && imgUrls.size() > 0) {
ProgressDialogUtils.getInstance(this).show(R.string.dialog_request_uploda);
new OSSUploadImgTask().request(AppManager.getFederationToken().bucketName,
AppManager.getOSSFacePath(), imgUrls.get(0));
}
}
}
class OSSUploadImgTask extends OSSImagUploadRequest {
@Override
public void onPostExecute(String s) {
String url = AppConstants.OSS_IMG_ENDPOINT + s;
new UploadCImgTask().request(url);
}
@Override
public void onErrorExecute(String error) {
ProgressDialogUtils.getInstance(GiveVipActivity.this).dismiss();
}
}
class UploadCImgTask extends UploadCommentImgRequest {
@Override
public void onPostExecute(String s) {
ProgressDialogUtils.getInstance(GiveVipActivity.this).dismiss();
ToastUtil.showMessage(s);
PreferencesUtils.setIsUploadCommentImg(GiveVipActivity.this, true);
mUploadImg.setEnabled(false);
mUploadImg.setFocusBackgroundColor(getResources().getColor(R.color.gray_text));
mUploadImg.setBackgroundColor(getResources().getColor(R.color.gray_text));
}
@Override
public void onErrorExecute(String error) {
ProgressDialogUtils.getInstance(GiveVipActivity.this).dismiss();
ToastUtil.showMessage(error);
}
}
}
| 4,881 | 0.655585 | 0.652075 | 151 | 31.072847 | 25.563089 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.509934 | false | false |
14
|
5418c7e32bd280f4c44d126704558f5cabf326d2
| 34,179,349,749,081 |
d6e557ab197d14a503ddc6a5a264ba0329b8923c
|
/src/main/java/uk/ac/liverpool/spreadsheet/ExcelFeatureAnalysis.java
|
df2c236460d51fa7e7fb213941f3fbe190d3037e
|
[] |
no_license
|
corubolo/scone-fu
|
https://github.com/corubolo/scone-fu
|
93838637248395dc9918f7a3d1300c7cfb5a6ef6
|
5af9949613bb851bee6753098713933ec8d3ca33
|
refs/heads/master
| 2021-06-30T21:32:28.587000 | 2016-11-01T11:13:44 | 2016-11-01T11:13:44 | 32,316,422 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
/**
* This class will analyze and report the specific features used in an Excel document.
* This is intended as an exemplar for the feature based preservation analysis, described in the SHAMAN deliverable 9.3
* and Deliverable 4.4
*
* @author Fabio Corubolo
*/
package uk.ac.liverpool.spreadsheet;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.POIXMLProperties;
import org.apache.poi.hpsf.DocumentSummaryInformation;
import org.apache.poi.hssf.usermodel.HSSFObjectData;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.PaneInformation;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.poi.ss.formula.eval.NotImplementedException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Footer;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Header;
import org.apache.poi.ss.usermodel.PictureData;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.Namespace;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
/**
* Excel feature analysis. This class allows analysing the main features present
* in an Excel (both binary and XML based) file. This will help classifying the
* file and planning an appropriate preservation and long term access strategy.
*
*
* @author Fabio Corubolo
*
*/
public class ExcelFeatureAnalysis {
public static final String VERSION = "0.3";
public static final String SW_ID = ExcelFeatureAnalysis.class
.getCanonicalName();
private static final String MIME = "application/vnd.ms-excel";
// The feature analysis namespace
public static final Namespace fa = Namespace
.getNamespace("http://shaman.disi.unitn.it/FeatureAnalysis");
// Dublin core
public static final Namespace dc = Namespace.getNamespace("dc",
"http://purl.org/dc/elements/1.1/");
// The data format specific part (in this case, spreadsheets)
public static final Namespace sn = Namespace.getNamespace("ss",
"http://shaman.disi.unitn.it/Spreadsheet");
Workbook wb;
HSSFWorkbook hswb;
XSSFWorkbook xswb;
File f;
/**
*
* @param w
* @param f
*/
private ExcelFeatureAnalysis(Workbook w, File f) {
wb = w;
if (wb instanceof HSSFWorkbook) {
hswb = (HSSFWorkbook) wb;
} else if (wb instanceof XSSFWorkbook) {
xswb = (XSSFWorkbook) wb;
}
this.f = f;
}
/**
*
* This method will instantiate the workbook and return the feature analysis
* object.
*
* @param in
* @return
* @throws IOException
* @throws InvalidFormatException
*/
public static ExcelFeatureAnalysis create(File in) throws IOException,
InvalidFormatException, EncryptedDocumentException {
Workbook wb = WorkbookFactory.create(new FileInputStream(in));
return new ExcelFeatureAnalysis(wb, in);
}
public static void main(String[] args) throws Exception {
if (args.length < 1) {
System.err.println("usage: ToHtml inputWorkbook");
return;
}
if (args.length > 2 && args[2].equals("-something"))
;
String s = analyse(new File(args[0]));
System.out.println(s);
}
/**
*
* The main analysis method. The returned string will be a properly formed
* XML enlisting the file features.
*
* @return XML string listing the features used in the file.
* @throws IOException
* @throws InvalidFormatException
*/
public static String analyse(File in) throws InvalidFormatException,
IOException {
ExcelFeatureAnalysis efa;
try {
efa = create(in);
}
catch (EncryptedDocumentException e) {
Element r = new Element("featureanalysis", fa);
SimpleDateFormat sdt = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSSZ");
r.addContent(new Element("processing_date", fa).addContent(sdt
.format(new Date())));
r.addContent(new Element("processingSoftware", fa).setAttribute("name",
SW_ID).setAttribute("version", VERSION));
Element da = new Element("object", fa);
r.addContent(da);
da.setAttribute("filename", in.getName());
da.setAttribute("lastModified", sdt.format(new Date(in.lastModified())));
da.setAttribute("mimeType", MIME);
da.addContent(new Element("encrypted", fa));
Document d = new Document();
d.setRootElement(r);
XMLOutputter o = new XMLOutputter(Format.getPrettyFormat());
String res = o.outputString(d);
return res;
}
Element r = new Element("featureanalysis", fa);
SimpleDateFormat sdt = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSSZ");
r.addContent(new Element("processing_date", fa).addContent(sdt
.format(new Date())));
r.addContent(new Element("processingSoftware", fa).setAttribute("name",
SW_ID).setAttribute("version", VERSION));
Element da = new Element("object", fa);
r.addContent(da);
da.setAttribute("filename", in.getName());
da.setAttribute("lastModified", sdt.format(new Date(in.lastModified())));
da.setAttribute("mimeType", MIME);
// end of the generic part, beginning of the file specific
analyseSpreadsheet(da, efa);
// finishing up, formatting and return string
Document d = new Document();
d.setRootElement(r);
XMLOutputter o = new XMLOutputter(Format.getPrettyFormat());
String res = o.outputString(d);
return res;
}
// Analysis at the file level
private static void analyseSpreadsheet(Element da, ExcelFeatureAnalysis efa) {
Element s = new Element("spreadsheets", sn);
da.addContent(s);
s.setAttribute("numberOfSheets", "" + efa.wb.getNumberOfSheets());
// workbook wide features
List<? extends PictureData> allPictures = efa.wb.getAllPictures();
if (allPictures != null && allPictures.size() > 0) {
Element oo = new Element("Pictures", sn);
s.addContent(oo);
for (PictureData pd : allPictures) {
Element ob = new Element("Picture", sn);
ob.setAttribute("mimeType", pd.getMimeType());
oo.addContent(ob);
}
}
int numfonts = efa.wb.getNumberOfFonts();
if (numfonts > 0) {
Element oo = new Element("Fonts", sn);
s.addContent(oo);
for (int i = 0; i < numfonts; i++) {
Font cs = efa.wb.getFontAt((short) i);
Element ob = new Element("Font", sn);
ob.setAttribute("Name", cs.getFontName());
ob.setAttribute("Charset", "" + cs.getCharSet());
oo.addContent(ob);
}
}
if (efa.hswb != null) {
DocumentSummaryInformation dsi = efa.hswb
.getDocumentSummaryInformation();
if (dsi != null)
s.setAttribute("OSVersion", "" + dsi.getOSVersion());
// Property[] properties = dsi.getProperties();
// CustomProperties customProperties = dsi.getCustomProperties();
List<HSSFObjectData> eo = efa.hswb.getAllEmbeddedObjects();
if (eo != null && eo.size() > 0) {
Element oo = new Element("EmbeddedObjects", sn);
s.addContent(oo);
for (HSSFObjectData o : eo) {
Element ob = new Element("EmbeddedObject", sn);
ob.setAttribute("name", o.getOLE2ClassName());
oo.addContent(ob);
}
}
} else if (efa.xswb != null) {
try {
POIXMLProperties properties = efa.xswb.getProperties();
List<PackagePart> allEmbedds = efa.xswb.getAllEmbedds();
if (allEmbedds != null && allEmbedds.size() > 0) {
Element oo = new Element("EmbeddedObjects", sn);
s.addContent(oo);
for (PackagePart p : allEmbedds) {
Element ob = new Element("EmbeddedObject", sn);
ob.setAttribute("mimeType", p.getContentType());
ob.setAttribute("name", p.getPartName().getName());
oo.addContent(ob);
}
}
} catch (OpenXML4JException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
int nn = efa.wb.getNumberOfNames();
if (nn > 0) {
Element oo = new Element("NamedCells", sn);
s.addContent(oo);
}
// sheet specific features
int total = efa.wb.getNumberOfSheets();
for (int c = 0; c < total; c++) {
Sheet sheet = efa.wb.getSheetAt(c);
Element single = new Element("sheet", sn);
s.addContent(single);
analyseSheet(sheet, single, sn, efa);
}
}
// Analysis at the sheet level
private static void analyseSheet(Sheet ss, Element s, Namespace n,
ExcelFeatureAnalysis efa) {
// generic part
boolean costumFormatting = false;
boolean formulae = false;
boolean UDF = false;
boolean hasComments = false;
Set<String> udfs = new HashSet<String>();
FormulaEvaluator evaluator = ss.getWorkbook().getCreationHelper()
.createFormulaEvaluator();
s.setAttribute("name", ss.getSheetName());
s.setAttribute("firstRow", "" + ss.getFirstRowNum());
s.setAttribute("lastRow", "" + ss.getLastRowNum());
try {
s.setAttribute("forceFormulaRecalc",
"" + ss.getForceFormulaRecalculation());
} catch (Throwable x) {
//x.printStackTrace();
}
// shapes in detail?
Footer footer = ss.getFooter();
if (footer != null) {
s.setAttribute("footer", "true");
}
Header header = ss.getHeader();
if (header != null) {
s.setAttribute("header", "true");
}
PaneInformation paneInformation = ss.getPaneInformation();
if (paneInformation != null) {
s.setAttribute("panels", "true");
}
HSSFSheet hs = null;
XSSFSheet xs = null;
if (ss instanceof HSSFSheet) {
hs = (HSSFSheet) ss;
try {
if (hs.getDrawingPatriarch() != null) {
if (hs.getDrawingPatriarch().containsChart())
s.addContent(new Element("charts",sn));
if (hs.getDrawingPatriarch().countOfAllChildren() > 0)
s.addContent(new Element("shapes",sn));
}
} catch (Exception x) {
x.printStackTrace();
}
if (hs.getSheetConditionalFormatting()
.getNumConditionalFormattings() > 0) {
s.setAttribute("conditionalFormatting", "true");
}
}
if (ss instanceof XSSFSheet) {
xs = (XSSFSheet) ss;
}
Iterator<Row> rows = ss.rowIterator();
int firstColumn = (rows.hasNext() ? Integer.MAX_VALUE : 0);
int endColumn = 0;
while (rows.hasNext()) {
Row row = rows.next();
short firstCell = row.getFirstCellNum();
if (firstCell >= 0) {
firstColumn = Math.min(firstColumn, firstCell);
endColumn = Math.max(endColumn, row.getLastCellNum());
}
}
s.setAttribute("firstColumn", "" + firstColumn);
s.setAttribute("lastColumn", "" + endColumn);
rows = ss.rowIterator();
while (rows.hasNext()) {
Row row = rows.next();
for (Cell cell : row)
if (cell != null) {
try {
if (!cell.getCellStyle().getDataFormatString()
.equals("GENERAL"))
costumFormatting = true;
} catch (Throwable t) {}
if (cell.getCellComment()!=null)
hasComments = true;
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
// System.out.println(cell.getRichStringCellValue().getString());
break;
case Cell.CELL_TYPE_NUMERIC:
// if (DateUtil.isCellDateFormatted(cell)) {
// // System.out.println(cell.getDateCellValue());
// } else {
// // System.out.println(cell.getNumericCellValue());
// }
break;
case Cell.CELL_TYPE_BOOLEAN:
// System.out.println(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_FORMULA:
// System.out.println(cell.getCellFormula());
formulae = true;
if (!UDF)
try {
evaluator.evaluate(cell);
} catch (Exception x) {
if (x instanceof NotImplementedException) {
Throwable e = x;
//e.printStackTrace();
while (e!=null) {
for (StackTraceElement c : e.getStackTrace()) {
if (c.getClassName().contains(
"UserDefinedFunction")) {
UDF = true;
System.out.println("UDF " + e.getMessage());
udfs.add(e.getMessage());
}
}
e = e.getCause();
}
}
}
break;
default:
}
}
}
if (costumFormatting) {
Element cf = new Element("customisedFormatting", sn);
s.addContent(cf);
}
if (formulae) {
Element cf = new Element("formulae", sn);
s.addContent(cf);
}
if (UDF) {
Element cf = new Element("userDefinedFunctions", sn);
for (String sss: udfs)
cf.addContent(new Element("userDefinedFunction",sn).setAttribute("functionName",sss));
s.addContent(cf);
}
if (hasComments) {
Element cf = new Element("cellComments", sn);
s.addContent(cf);
}
}
}
|
UTF-8
|
Java
| 17,164 |
java
|
ExcelFeatureAnalysis.java
|
Java
|
[
{
"context": "iverable 9.3\n * and Deliverable 4.4\n * \n * @author Fabio Corubolo\n */\n\npackage uk.ac.liverpool.spreadsheet;\n\nimport",
"end": 1199,
"score": 0.9998765587806702,
"start": 1185,
"tag": "NAME",
"value": "Fabio Corubolo"
},
{
"context": " and long term access strategy.\n * \n * \n * @author Fabio Corubolo\n * \n */\n\npublic class ExcelFeatureAnalysis {\n\n ",
"end": 3041,
"score": 0.9998744130134583,
"start": 3027,
"tag": "NAME",
"value": "Fabio Corubolo"
}
] | null |
[] |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
/**
* This class will analyze and report the specific features used in an Excel document.
* This is intended as an exemplar for the feature based preservation analysis, described in the SHAMAN deliverable 9.3
* and Deliverable 4.4
*
* @author <NAME>
*/
package uk.ac.liverpool.spreadsheet;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.POIXMLProperties;
import org.apache.poi.hpsf.DocumentSummaryInformation;
import org.apache.poi.hssf.usermodel.HSSFObjectData;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.PaneInformation;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.poi.ss.formula.eval.NotImplementedException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Footer;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Header;
import org.apache.poi.ss.usermodel.PictureData;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.Namespace;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
/**
* Excel feature analysis. This class allows analysing the main features present
* in an Excel (both binary and XML based) file. This will help classifying the
* file and planning an appropriate preservation and long term access strategy.
*
*
* @author <NAME>
*
*/
public class ExcelFeatureAnalysis {
public static final String VERSION = "0.3";
public static final String SW_ID = ExcelFeatureAnalysis.class
.getCanonicalName();
private static final String MIME = "application/vnd.ms-excel";
// The feature analysis namespace
public static final Namespace fa = Namespace
.getNamespace("http://shaman.disi.unitn.it/FeatureAnalysis");
// Dublin core
public static final Namespace dc = Namespace.getNamespace("dc",
"http://purl.org/dc/elements/1.1/");
// The data format specific part (in this case, spreadsheets)
public static final Namespace sn = Namespace.getNamespace("ss",
"http://shaman.disi.unitn.it/Spreadsheet");
Workbook wb;
HSSFWorkbook hswb;
XSSFWorkbook xswb;
File f;
/**
*
* @param w
* @param f
*/
private ExcelFeatureAnalysis(Workbook w, File f) {
wb = w;
if (wb instanceof HSSFWorkbook) {
hswb = (HSSFWorkbook) wb;
} else if (wb instanceof XSSFWorkbook) {
xswb = (XSSFWorkbook) wb;
}
this.f = f;
}
/**
*
* This method will instantiate the workbook and return the feature analysis
* object.
*
* @param in
* @return
* @throws IOException
* @throws InvalidFormatException
*/
public static ExcelFeatureAnalysis create(File in) throws IOException,
InvalidFormatException, EncryptedDocumentException {
Workbook wb = WorkbookFactory.create(new FileInputStream(in));
return new ExcelFeatureAnalysis(wb, in);
}
public static void main(String[] args) throws Exception {
if (args.length < 1) {
System.err.println("usage: ToHtml inputWorkbook");
return;
}
if (args.length > 2 && args[2].equals("-something"))
;
String s = analyse(new File(args[0]));
System.out.println(s);
}
/**
*
* The main analysis method. The returned string will be a properly formed
* XML enlisting the file features.
*
* @return XML string listing the features used in the file.
* @throws IOException
* @throws InvalidFormatException
*/
public static String analyse(File in) throws InvalidFormatException,
IOException {
ExcelFeatureAnalysis efa;
try {
efa = create(in);
}
catch (EncryptedDocumentException e) {
Element r = new Element("featureanalysis", fa);
SimpleDateFormat sdt = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSSZ");
r.addContent(new Element("processing_date", fa).addContent(sdt
.format(new Date())));
r.addContent(new Element("processingSoftware", fa).setAttribute("name",
SW_ID).setAttribute("version", VERSION));
Element da = new Element("object", fa);
r.addContent(da);
da.setAttribute("filename", in.getName());
da.setAttribute("lastModified", sdt.format(new Date(in.lastModified())));
da.setAttribute("mimeType", MIME);
da.addContent(new Element("encrypted", fa));
Document d = new Document();
d.setRootElement(r);
XMLOutputter o = new XMLOutputter(Format.getPrettyFormat());
String res = o.outputString(d);
return res;
}
Element r = new Element("featureanalysis", fa);
SimpleDateFormat sdt = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSSZ");
r.addContent(new Element("processing_date", fa).addContent(sdt
.format(new Date())));
r.addContent(new Element("processingSoftware", fa).setAttribute("name",
SW_ID).setAttribute("version", VERSION));
Element da = new Element("object", fa);
r.addContent(da);
da.setAttribute("filename", in.getName());
da.setAttribute("lastModified", sdt.format(new Date(in.lastModified())));
da.setAttribute("mimeType", MIME);
// end of the generic part, beginning of the file specific
analyseSpreadsheet(da, efa);
// finishing up, formatting and return string
Document d = new Document();
d.setRootElement(r);
XMLOutputter o = new XMLOutputter(Format.getPrettyFormat());
String res = o.outputString(d);
return res;
}
// Analysis at the file level
private static void analyseSpreadsheet(Element da, ExcelFeatureAnalysis efa) {
Element s = new Element("spreadsheets", sn);
da.addContent(s);
s.setAttribute("numberOfSheets", "" + efa.wb.getNumberOfSheets());
// workbook wide features
List<? extends PictureData> allPictures = efa.wb.getAllPictures();
if (allPictures != null && allPictures.size() > 0) {
Element oo = new Element("Pictures", sn);
s.addContent(oo);
for (PictureData pd : allPictures) {
Element ob = new Element("Picture", sn);
ob.setAttribute("mimeType", pd.getMimeType());
oo.addContent(ob);
}
}
int numfonts = efa.wb.getNumberOfFonts();
if (numfonts > 0) {
Element oo = new Element("Fonts", sn);
s.addContent(oo);
for (int i = 0; i < numfonts; i++) {
Font cs = efa.wb.getFontAt((short) i);
Element ob = new Element("Font", sn);
ob.setAttribute("Name", cs.getFontName());
ob.setAttribute("Charset", "" + cs.getCharSet());
oo.addContent(ob);
}
}
if (efa.hswb != null) {
DocumentSummaryInformation dsi = efa.hswb
.getDocumentSummaryInformation();
if (dsi != null)
s.setAttribute("OSVersion", "" + dsi.getOSVersion());
// Property[] properties = dsi.getProperties();
// CustomProperties customProperties = dsi.getCustomProperties();
List<HSSFObjectData> eo = efa.hswb.getAllEmbeddedObjects();
if (eo != null && eo.size() > 0) {
Element oo = new Element("EmbeddedObjects", sn);
s.addContent(oo);
for (HSSFObjectData o : eo) {
Element ob = new Element("EmbeddedObject", sn);
ob.setAttribute("name", o.getOLE2ClassName());
oo.addContent(ob);
}
}
} else if (efa.xswb != null) {
try {
POIXMLProperties properties = efa.xswb.getProperties();
List<PackagePart> allEmbedds = efa.xswb.getAllEmbedds();
if (allEmbedds != null && allEmbedds.size() > 0) {
Element oo = new Element("EmbeddedObjects", sn);
s.addContent(oo);
for (PackagePart p : allEmbedds) {
Element ob = new Element("EmbeddedObject", sn);
ob.setAttribute("mimeType", p.getContentType());
ob.setAttribute("name", p.getPartName().getName());
oo.addContent(ob);
}
}
} catch (OpenXML4JException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
int nn = efa.wb.getNumberOfNames();
if (nn > 0) {
Element oo = new Element("NamedCells", sn);
s.addContent(oo);
}
// sheet specific features
int total = efa.wb.getNumberOfSheets();
for (int c = 0; c < total; c++) {
Sheet sheet = efa.wb.getSheetAt(c);
Element single = new Element("sheet", sn);
s.addContent(single);
analyseSheet(sheet, single, sn, efa);
}
}
// Analysis at the sheet level
private static void analyseSheet(Sheet ss, Element s, Namespace n,
ExcelFeatureAnalysis efa) {
// generic part
boolean costumFormatting = false;
boolean formulae = false;
boolean UDF = false;
boolean hasComments = false;
Set<String> udfs = new HashSet<String>();
FormulaEvaluator evaluator = ss.getWorkbook().getCreationHelper()
.createFormulaEvaluator();
s.setAttribute("name", ss.getSheetName());
s.setAttribute("firstRow", "" + ss.getFirstRowNum());
s.setAttribute("lastRow", "" + ss.getLastRowNum());
try {
s.setAttribute("forceFormulaRecalc",
"" + ss.getForceFormulaRecalculation());
} catch (Throwable x) {
//x.printStackTrace();
}
// shapes in detail?
Footer footer = ss.getFooter();
if (footer != null) {
s.setAttribute("footer", "true");
}
Header header = ss.getHeader();
if (header != null) {
s.setAttribute("header", "true");
}
PaneInformation paneInformation = ss.getPaneInformation();
if (paneInformation != null) {
s.setAttribute("panels", "true");
}
HSSFSheet hs = null;
XSSFSheet xs = null;
if (ss instanceof HSSFSheet) {
hs = (HSSFSheet) ss;
try {
if (hs.getDrawingPatriarch() != null) {
if (hs.getDrawingPatriarch().containsChart())
s.addContent(new Element("charts",sn));
if (hs.getDrawingPatriarch().countOfAllChildren() > 0)
s.addContent(new Element("shapes",sn));
}
} catch (Exception x) {
x.printStackTrace();
}
if (hs.getSheetConditionalFormatting()
.getNumConditionalFormattings() > 0) {
s.setAttribute("conditionalFormatting", "true");
}
}
if (ss instanceof XSSFSheet) {
xs = (XSSFSheet) ss;
}
Iterator<Row> rows = ss.rowIterator();
int firstColumn = (rows.hasNext() ? Integer.MAX_VALUE : 0);
int endColumn = 0;
while (rows.hasNext()) {
Row row = rows.next();
short firstCell = row.getFirstCellNum();
if (firstCell >= 0) {
firstColumn = Math.min(firstColumn, firstCell);
endColumn = Math.max(endColumn, row.getLastCellNum());
}
}
s.setAttribute("firstColumn", "" + firstColumn);
s.setAttribute("lastColumn", "" + endColumn);
rows = ss.rowIterator();
while (rows.hasNext()) {
Row row = rows.next();
for (Cell cell : row)
if (cell != null) {
try {
if (!cell.getCellStyle().getDataFormatString()
.equals("GENERAL"))
costumFormatting = true;
} catch (Throwable t) {}
if (cell.getCellComment()!=null)
hasComments = true;
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
// System.out.println(cell.getRichStringCellValue().getString());
break;
case Cell.CELL_TYPE_NUMERIC:
// if (DateUtil.isCellDateFormatted(cell)) {
// // System.out.println(cell.getDateCellValue());
// } else {
// // System.out.println(cell.getNumericCellValue());
// }
break;
case Cell.CELL_TYPE_BOOLEAN:
// System.out.println(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_FORMULA:
// System.out.println(cell.getCellFormula());
formulae = true;
if (!UDF)
try {
evaluator.evaluate(cell);
} catch (Exception x) {
if (x instanceof NotImplementedException) {
Throwable e = x;
//e.printStackTrace();
while (e!=null) {
for (StackTraceElement c : e.getStackTrace()) {
if (c.getClassName().contains(
"UserDefinedFunction")) {
UDF = true;
System.out.println("UDF " + e.getMessage());
udfs.add(e.getMessage());
}
}
e = e.getCause();
}
}
}
break;
default:
}
}
}
if (costumFormatting) {
Element cf = new Element("customisedFormatting", sn);
s.addContent(cf);
}
if (formulae) {
Element cf = new Element("formulae", sn);
s.addContent(cf);
}
if (UDF) {
Element cf = new Element("userDefinedFunctions", sn);
for (String sss: udfs)
cf.addContent(new Element("userDefinedFunction",sn).setAttribute("functionName",sss));
s.addContent(cf);
}
if (hasComments) {
Element cf = new Element("cellComments", sn);
s.addContent(cf);
}
}
}
| 17,148 | 0.543987 | 0.542007 | 452 | 36.97345 | 24.822809 | 119 | false | false | 0 | 0 | 0 | 0 | 69 | 0.00804 | 0.630531 | false | false |
14
|
bed2360a59ac23cfc99246b3af0590c555161ed1
| 5,987,184,458,117 |
d0e077174e34ab89d6f50d9c3d0b78d1fbabb5b5
|
/app/src/main/java/com/andry/andrey_kalyuzhnyy_homework3/AppsManager.java
|
cd7e69b41f1c270b21328c7acbc7e38e10e5df22
|
[] |
no_license
|
andrydonalts/Andrey_Kalyuzhnyy_CustomLauncher
|
https://github.com/andrydonalts/Andrey_Kalyuzhnyy_CustomLauncher
|
fd53b0173e4081cb319e2a466ebc87207b924d55
|
02651c9f1ba5a48c94b330d229916b25deca3b28
|
refs/heads/master
| 2021-01-01T04:56:12.791000 | 2016-05-13T09:07:26 | 2016-05-13T09:07:26 | 56,447,786 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.andry.andrey_kalyuzhnyy_homework3;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
/**
* Created by andry on 26.04.2016.
*/
public class AppsManager{
private Context context;
private ArrayList<AppsDetail> apps;
private ArrayList<AppsDetail> mainScreenApps;
protected PackageManager manager;
public AppsManager(PackageManager packageManager){
manager = packageManager;
apps = new ArrayList<>();
mainScreenApps = new ArrayList<>();
}
public AppsManager(Context context) {
this.context = context;
manager = context.getPackageManager();
apps = new ArrayList<>();
mainScreenApps = new ArrayList<>();
}
public void loadApps(){
Log.d("AppsAdapter", "In loadApps method");
if (apps == null || apps.isEmpty()) {
Log.d("AppsAdapter", "Loading apps");
AppsDetail appsDetail;
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> availableActives = manager.queryIntentActivities(intent, 0);
for (int i = 0; i < availableActives.size(); i++) {
ResolveInfo resolveInfo = availableActives.get(i);
appsDetail = new AppsDetail();
String label = resolveInfo.loadLabel(manager).toString();
Drawable icon = resolveInfo.loadIcon(manager);
String name = resolveInfo.activityInfo.packageName;
appsDetail.setLabel(label);
appsDetail.setName(name);
appsDetail.setIcon(icon);
apps.add(appsDetail);
}
}
}
public void loadMainScreenApps(){
if (apps == null || apps.isEmpty()){
Log.d("AppsManager", "apps == null or are empty");
loadApps();
}
for (int i = 0; i < 15; i++){
AppsDetail mainScreenApp = apps.get(i);
mainScreenApp.setIsVisibleOnMainScreen(true);
mainScreenApps.add(mainScreenApp);
}
}
public ArrayList<AppsDetail> getAppsList(){
return this.apps;
}
public void setAppsList(ArrayList<AppsDetail> apps){
this.apps = apps;
}
public ArrayList<AppsDetail> getMainScreenApps(){
return this.mainScreenApps;
}
public void setMainScreenApps(ArrayList<AppsDetail> mainScreenApps){
this.mainScreenApps = mainScreenApps;
}
public void startApp(AppsDetail appsDetail) {
Intent intent = manager.getLaunchIntentForPackage(appsDetail.getName());
context.startActivity(intent);
}
}
|
UTF-8
|
Java
| 2,904 |
java
|
AppsManager.java
|
Java
|
[
{
"context": "package com.andry.andrey_kalyuzhnyy_homework3;\n\nimport android.cont",
"end": 17,
"score": 0.5748819708824158,
"start": 15,
"tag": "USERNAME",
"value": "ry"
},
{
"context": "rayList;\nimport java.util.List;\n\n/**\n * Created by andry on 26.04.2016.\n */\npublic class AppsManager{\n\n ",
"end": 336,
"score": 0.9977113008499146,
"start": 331,
"tag": "USERNAME",
"value": "andry"
}
] | null |
[] |
package com.andry.andrey_kalyuzhnyy_homework3;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
/**
* Created by andry on 26.04.2016.
*/
public class AppsManager{
private Context context;
private ArrayList<AppsDetail> apps;
private ArrayList<AppsDetail> mainScreenApps;
protected PackageManager manager;
public AppsManager(PackageManager packageManager){
manager = packageManager;
apps = new ArrayList<>();
mainScreenApps = new ArrayList<>();
}
public AppsManager(Context context) {
this.context = context;
manager = context.getPackageManager();
apps = new ArrayList<>();
mainScreenApps = new ArrayList<>();
}
public void loadApps(){
Log.d("AppsAdapter", "In loadApps method");
if (apps == null || apps.isEmpty()) {
Log.d("AppsAdapter", "Loading apps");
AppsDetail appsDetail;
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> availableActives = manager.queryIntentActivities(intent, 0);
for (int i = 0; i < availableActives.size(); i++) {
ResolveInfo resolveInfo = availableActives.get(i);
appsDetail = new AppsDetail();
String label = resolveInfo.loadLabel(manager).toString();
Drawable icon = resolveInfo.loadIcon(manager);
String name = resolveInfo.activityInfo.packageName;
appsDetail.setLabel(label);
appsDetail.setName(name);
appsDetail.setIcon(icon);
apps.add(appsDetail);
}
}
}
public void loadMainScreenApps(){
if (apps == null || apps.isEmpty()){
Log.d("AppsManager", "apps == null or are empty");
loadApps();
}
for (int i = 0; i < 15; i++){
AppsDetail mainScreenApp = apps.get(i);
mainScreenApp.setIsVisibleOnMainScreen(true);
mainScreenApps.add(mainScreenApp);
}
}
public ArrayList<AppsDetail> getAppsList(){
return this.apps;
}
public void setAppsList(ArrayList<AppsDetail> apps){
this.apps = apps;
}
public ArrayList<AppsDetail> getMainScreenApps(){
return this.mainScreenApps;
}
public void setMainScreenApps(ArrayList<AppsDetail> mainScreenApps){
this.mainScreenApps = mainScreenApps;
}
public void startApp(AppsDetail appsDetail) {
Intent intent = manager.getLaunchIntentForPackage(appsDetail.getName());
context.startActivity(intent);
}
}
| 2,904 | 0.625689 | 0.620868 | 103 | 27.194174 | 23.709429 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.572816 | false | false |
14
|
ff762ed58a86d1767cb9475ba770899801364b00
| 21,638,045,272,952 |
2ae2d27fbb5d16b7985af1ef4183d592db4b6798
|
/springboot/db다중연결conf/ElasticSearchConfig.java
|
8bd927a2713c3468ec34902bec517b10c49a4d74
|
[] |
no_license
|
julysky123/anything
|
https://github.com/julysky123/anything
|
8b4d1c684df48ae6a3228ac99df99367c172c441
|
bc97b07abec020c3a1a772da19c03d0e33ec28b4
|
refs/heads/master
| 2022-11-09T15:24:21.718000 | 2022-11-01T22:12:06 | 2022-11-01T22:12:06 | 232,242,925 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package //;
import com.example.test.elastic.dto.entity.ElasticsearchProperties;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.RestClients;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
@Configuration
@EnableElasticsearchRepositories(basePackages = "com.example.test.elastic.dto.repository")
@ComponentScan(basePackages = { "com.example.test.elastic" })
public class ElasticSearchConfig {
@Bean
public RestHighLevelClient client(ElasticsearchProperties properties) {
ClientConfiguration clientConfiguration = ClientConfiguration.builder()
.connectedTo(properties.getHost())
.withBasicAuth(properties.getUsername(), properties.getPassword())
.build();
return RestClients.create(clientConfiguration).rest();
}
}
|
UTF-8
|
Java
| 1,148 |
java
|
ElasticSearchConfig.java
|
Java
|
[] | null |
[] |
package //;
import com.example.test.elastic.dto.entity.ElasticsearchProperties;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.RestClients;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
@Configuration
@EnableElasticsearchRepositories(basePackages = "com.example.test.elastic.dto.repository")
@ComponentScan(basePackages = { "com.example.test.elastic" })
public class ElasticSearchConfig {
@Bean
public RestHighLevelClient client(ElasticsearchProperties properties) {
ClientConfiguration clientConfiguration = ClientConfiguration.builder()
.connectedTo(properties.getHost())
.withBasicAuth(properties.getUsername(), properties.getPassword())
.build();
return RestClients.create(clientConfiguration).rest();
}
}
| 1,148 | 0.792683 | 0.792683 | 26 | 43.153847 | 31.807947 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.461538 | false | false |
14
|
a34645594edc3811a8f5fe90a4ad3b630c64614f
| 111,669,184,127 |
61cd7c1169236d4d8c82d82ada887b8fb02aa200
|
/house-model/src/main/java/com/xuetang9/house/domain/LeaseType.java
|
c63b1c319144b5d76419bbdc465be87e2e89b3de
|
[
"LicenseRef-scancode-mulanpsl-2.0-en",
"MulanPSL-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
xiaobingbinga/real_estate_management
|
https://github.com/xiaobingbinga/real_estate_management
|
5f49cf46c041040b8f6f211dded774d428d37d20
|
b0ca5af95a50c46d32b69393af3b3e86c1e5422d
|
refs/heads/master
| 2023-03-06T14:39:42.137000 | 2020-08-31T10:36:47 | 2020-08-31T10:36:47 | 340,077,965 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.xuetang9.house.domain;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import javax.persistence.*;
@ApiModel("租期类型实体类")
@Table(name = "lease_type")
public class LeaseType implements Serializable {
@Id
@ApiModelProperty(value = "租期类型唯一标识",example = "1",required = true)
private Integer id;
/**
* 租期类型名称
*/
@Column(name = "type_name")
@ApiModelProperty(value = "租期类型名称",example = "按天计",required = true)
private String typeName;
private static final long serialVersionUID = 1L;
/**
* @return id
*/
public Integer getId() {
return id;
}
/**
* @param id
*/
public void setId(Integer id) {
this.id = id;
}
/**
* 获取租期类型名称
*
* @return type_name - 租期类型名称
*/
public String getTypeName() {
return typeName;
}
/**
* 设置租期类型名称
*
* @param typeName 租期类型名称
*/
public void setTypeName(String typeName) {
this.typeName = typeName;
}
@Override
public String toString() {
return "LeaseType{" +
"id=" + id +
", typeName='" + typeName + '\'' +
'}';
}
}
|
UTF-8
|
Java
| 1,386 |
java
|
LeaseType.java
|
Java
|
[] | null |
[] |
package com.xuetang9.house.domain;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import javax.persistence.*;
@ApiModel("租期类型实体类")
@Table(name = "lease_type")
public class LeaseType implements Serializable {
@Id
@ApiModelProperty(value = "租期类型唯一标识",example = "1",required = true)
private Integer id;
/**
* 租期类型名称
*/
@Column(name = "type_name")
@ApiModelProperty(value = "租期类型名称",example = "按天计",required = true)
private String typeName;
private static final long serialVersionUID = 1L;
/**
* @return id
*/
public Integer getId() {
return id;
}
/**
* @param id
*/
public void setId(Integer id) {
this.id = id;
}
/**
* 获取租期类型名称
*
* @return type_name - 租期类型名称
*/
public String getTypeName() {
return typeName;
}
/**
* 设置租期类型名称
*
* @param typeName 租期类型名称
*/
public void setTypeName(String typeName) {
this.typeName = typeName;
}
@Override
public String toString() {
return "LeaseType{" +
"id=" + id +
", typeName='" + typeName + '\'' +
'}';
}
}
| 1,386 | 0.559055 | 0.556693 | 64 | 18.859375 | 17.319487 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.28125 | false | false |
14
|
dd5a3de9ce90531ca2759add2cb798abe39ae8b9
| 20,409,684,633,484 |
5479ada6004d5954e05bc6eefd690431a1765fdd
|
/szcg-bxp/src/main/java/tx/bxp/mapper/LikeMapper.java
|
24f472e6f287a87633f8eb3ddc8e9f125ff2124a
|
[] |
no_license
|
15258334873/szcg-project
|
https://github.com/15258334873/szcg-project
|
c60be045a4b00512bd386429bd68bfb0879f66fd
|
73f18073553c954d01eb29826946fe0e560e4897
|
refs/heads/master
| 2020-04-08T21:34:07.746000 | 2018-11-30T01:15:16 | 2018-11-30T01:15:16 | 159,749,447 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package tx.bxp.mapper;
import org.apache.ibatis.annotations.Mapper;
import tx.bxp.entity.Like;
/**
* 点赞功能
* @program: tx.framework
* @description:
* @author:pck
* @create: 2018-06-07 16:27
**/
@Mapper
public interface LikeMapper {
/**
* 用户点赞
* @author chenmc
* @date 2018/8/17 10:39
* @param
* @return
*/
void InsertLike(Like like);
/**
* 取消点赞
* @author chenmc
* @date 2018/8/17 10:39
* @param
* @return
*/
void DeleteLike(Like like);
public Integer selectLike( Like like);
}
|
UTF-8
|
Java
| 592 |
java
|
LikeMapper.java
|
Java
|
[
{
"context": "program: tx.framework\n * @description:\n * @author:pck\n * @create: 2018-06-07 16:27\n **/\n@Mapper\npublic ",
"end": 165,
"score": 0.9995695352554321,
"start": 162,
"tag": "USERNAME",
"value": "pck"
},
{
"context": "e LikeMapper {\n\n /**\n * 用户点赞\n * @author chenmc\n * @date 2018/8/17 10:39\n * @param\n *",
"end": 280,
"score": 0.9996547698974609,
"start": 274,
"tag": "USERNAME",
"value": "chenmc"
},
{
"context": "ke(Like like);\n\n /**\n * 取消点赞\n * @author chenmc\n * @date 2018/8/17 10:39\n * @param\n *",
"end": 421,
"score": 0.9996679425239563,
"start": 415,
"tag": "USERNAME",
"value": "chenmc"
}
] | null |
[] |
package tx.bxp.mapper;
import org.apache.ibatis.annotations.Mapper;
import tx.bxp.entity.Like;
/**
* 点赞功能
* @program: tx.framework
* @description:
* @author:pck
* @create: 2018-06-07 16:27
**/
@Mapper
public interface LikeMapper {
/**
* 用户点赞
* @author chenmc
* @date 2018/8/17 10:39
* @param
* @return
*/
void InsertLike(Like like);
/**
* 取消点赞
* @author chenmc
* @date 2018/8/17 10:39
* @param
* @return
*/
void DeleteLike(Like like);
public Integer selectLike( Like like);
}
| 592 | 0.575704 | 0.515845 | 36 | 14.777778 | 12.206808 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.166667 | false | false |
14
|
90eb66279704e9b8516498ce79f9935f028549c1
| 7,842,610,351,766 |
ec07d2764d41b667f6cc65b4a7a86f4c111e60b3
|
/cmfz_wy/src/main/java/com/baizhi/dao/LogMapper.java
|
d11c5b9a4c8b20718533cea85553ccbf3574a5e0
|
[] |
no_license
|
wangfires/dd_wy
|
https://github.com/wangfires/dd_wy
|
be3ad7a637695c905c6ff961f35da989a4aff0ce
|
5b5a0b9e5960a0c743cc91c9328e6a0f0fd73139
|
refs/heads/master
| 2020-05-22T11:18:36.172000 | 2019-05-14T11:03:42 | 2019-05-14T11:03:42 | 186,320,702 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.baizhi.dao;
import com.baizhi.entity.Log;
import tk.mybatis.mapper.common.Mapper;
public interface LogMapper extends Mapper<Log> {
}
|
UTF-8
|
Java
| 147 |
java
|
LogMapper.java
|
Java
|
[] | null |
[] |
package com.baizhi.dao;
import com.baizhi.entity.Log;
import tk.mybatis.mapper.common.Mapper;
public interface LogMapper extends Mapper<Log> {
}
| 147 | 0.789116 | 0.789116 | 7 | 20 | 18.500965 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false |
14
|
86f79ad40aff55b6bc42830f66f165c9525ee756
| 3,856,880,696,423 |
df3ddeecd9450465ff55bf676c2ac4cd00453d4e
|
/app/src/main/java/com/darayuth/room/UserDatabase.java
|
de56e72eade3e26ef69a46160160f8bfe625b4c6
|
[] |
no_license
|
darayuthhang/Room_Persistence_Android
|
https://github.com/darayuthhang/Room_Persistence_Android
|
2fa03de1bdada520d0b126c086fb11db80797d10
|
fa83611c8cad49534befe1eb01c77981695cf7cc
|
refs/heads/master
| 2020-12-15T02:01:26.091000 | 2020-01-19T19:44:50 | 2020-01-19T19:44:50 | 234,954,980 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.darayuth.room;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.DatabaseConfiguration;
import androidx.room.InvalidationTracker;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.sqlite.db.SupportSQLiteOpenHelper;
@Database(entities = User.class, exportSchema = false, version = 1)
public abstract class UserDatabase extends RoomDatabase {
private static final String DB_NAME = "user_db";
public static UserDatabase instance;
//create singleton for database;
public static synchronized UserDatabase getInstance(Context context){
if(instance == null){
instance = Room.databaseBuilder(context.getApplicationContext(), UserDatabase.class,
DB_NAME).fallbackToDestructiveMigration().build();
}
return instance;
}
public abstract UserDao userDao();
}
|
UTF-8
|
Java
| 940 |
java
|
UserDatabase.java
|
Java
|
[] | null |
[] |
package com.darayuth.room;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.DatabaseConfiguration;
import androidx.room.InvalidationTracker;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.sqlite.db.SupportSQLiteOpenHelper;
@Database(entities = User.class, exportSchema = false, version = 1)
public abstract class UserDatabase extends RoomDatabase {
private static final String DB_NAME = "user_db";
public static UserDatabase instance;
//create singleton for database;
public static synchronized UserDatabase getInstance(Context context){
if(instance == null){
instance = Room.databaseBuilder(context.getApplicationContext(), UserDatabase.class,
DB_NAME).fallbackToDestructiveMigration().build();
}
return instance;
}
public abstract UserDao userDao();
}
| 940 | 0.747872 | 0.746809 | 27 | 33.814816 | 24.722216 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.703704 | false | false |
14
|
f65ce89dc175f393f8ed09e744cd9aff62646466
| 7,602,092,179,392 |
f1604a04dba0fd2c81dab7466dcb275206bd45da
|
/RepairRecipe/src/main/java/de/funkyclan/mc/RepairRecipe/RepairRecipe.java
|
22add53368f6942b3881253fc98523d1f149af30
|
[] |
no_license
|
pulsar256/RepairRecipe
|
https://github.com/pulsar256/RepairRecipe
|
c2c5be5b2b303e8ed44155642e4204098f21e834
|
b6894db79aad0ff0229c48c3cd7d87b54f5a3666
|
refs/heads/master
| 2021-01-18T06:57:40.802000 | 2014-07-29T22:46:21 | 2014-07-29T22:46:21 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package de.funkyclan.mc.RepairRecipe;
import de.funkyclan.mc.RepairRecipe.Listener.CraftingListener;
import de.funkyclan.mc.RepairRecipe.Recipe.ShapelessRepairRecipe;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Logger;
public class RepairRecipe extends JavaPlugin {
public static final Logger logger = Logger.getLogger("Minecraft");
private Set<ShapelessRepairRecipe> repairRecipes = new HashSet<ShapelessRepairRecipe>();
private RepairRecipeConfig config;
public void onEnable() {
getServer().getPluginManager().registerEvents(new CraftingListener(this), this);
getCommand("repairrecipe").setExecutor(new RepairRecipeCommand(this));
config = new RepairRecipeConfig(this);
addRecipes();
if (repairRecipes.size() == 0) {
logger.info("[RepairRecipe] no recipes found, disabling plugin.");
getServer().getPluginManager().disablePlugin(this);
return;
}
try {
MetricsLite metrics = new MetricsLite(this);
metrics.start();
} catch (IOException e) {
// Failed to submit the stats :-(
}
logger.info("[RepairRecipe] added " + repairRecipes.size() + " Recipes for repair.");
logger.info("[RepairRecipe] successfully loaded.");
}
public ShapelessRepairRecipe getRepairRecipeFor(ItemStack itemStack) {
return getRepairRecipeFor(itemStack.getType());
}
public ShapelessRepairRecipe getRepairRecipeFor(Material item) {
for (ShapelessRepairRecipe recipe : repairRecipes) {
if (recipe.getResult().getType().equals(item)) {
return recipe;
}
}
return null;
}
public RepairRecipeConfig getConfigurator() {
return config;
}
public void updateSlotInventory(HumanEntity player, ItemStack item, int index) {
if (player instanceof Player) {
final Player craftPlayer = (Player) player;
this.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
@SuppressWarnings("deprecation")
@Override
public void run() {
craftPlayer.updateInventory();
}
});
}
}
private void addRecipes() {
for (String key : config.getItemConfig().getKeys(false)) {
Material item = Material.matchMaterial(key);
if (item == null) {
logger.info("[RepairRecipe] unknown item " + key);
continue;
}
ConfigurationSection section = config.getItemConfig().getConfigurationSection(key);
Material baseItem = Material.matchMaterial(section.getString("base_item"));
if (baseItem == null) {
logger.info("[RepairRecipe] unknown base item " + section.getString("base_item"));
continue;
}
int baseAmount = section.getInt("base_amount");
if (baseAmount == 0) {
logger.info("[RepairRecipe] No base_amount to repair " + item.name() + " with " + baseItem.name() + ". Repairing is for free!");
}
ShapelessRepairRecipe recipe = new ShapelessRepairRecipe(item, baseItem, baseAmount, this);
recipe.setConfig("keep_enchantments_chance", section.getString("keep_enchantments_chance", null));
recipe.setConfig("enchant_multiplier", section.getString("enchant_multiplier", null));
recipe.setConfig("allow_over_repair", section.getString("allow_over_repair", null));
recipe.setConfig("use_highest_enchant", section.getString("use_highest_enchant", null));
repairRecipes.add(recipe);
getServer().addRecipe(recipe);
if (RepairRecipeConfig.DEBUG)
RepairRecipe.logger.info("Added " + item + " with " + baseAmount + "x" + baseItem);
}
}
}
|
UTF-8
|
Java
| 4,335 |
java
|
RepairRecipe.java
|
Java
|
[] | null |
[] |
package de.funkyclan.mc.RepairRecipe;
import de.funkyclan.mc.RepairRecipe.Listener.CraftingListener;
import de.funkyclan.mc.RepairRecipe.Recipe.ShapelessRepairRecipe;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Logger;
public class RepairRecipe extends JavaPlugin {
public static final Logger logger = Logger.getLogger("Minecraft");
private Set<ShapelessRepairRecipe> repairRecipes = new HashSet<ShapelessRepairRecipe>();
private RepairRecipeConfig config;
public void onEnable() {
getServer().getPluginManager().registerEvents(new CraftingListener(this), this);
getCommand("repairrecipe").setExecutor(new RepairRecipeCommand(this));
config = new RepairRecipeConfig(this);
addRecipes();
if (repairRecipes.size() == 0) {
logger.info("[RepairRecipe] no recipes found, disabling plugin.");
getServer().getPluginManager().disablePlugin(this);
return;
}
try {
MetricsLite metrics = new MetricsLite(this);
metrics.start();
} catch (IOException e) {
// Failed to submit the stats :-(
}
logger.info("[RepairRecipe] added " + repairRecipes.size() + " Recipes for repair.");
logger.info("[RepairRecipe] successfully loaded.");
}
public ShapelessRepairRecipe getRepairRecipeFor(ItemStack itemStack) {
return getRepairRecipeFor(itemStack.getType());
}
public ShapelessRepairRecipe getRepairRecipeFor(Material item) {
for (ShapelessRepairRecipe recipe : repairRecipes) {
if (recipe.getResult().getType().equals(item)) {
return recipe;
}
}
return null;
}
public RepairRecipeConfig getConfigurator() {
return config;
}
public void updateSlotInventory(HumanEntity player, ItemStack item, int index) {
if (player instanceof Player) {
final Player craftPlayer = (Player) player;
this.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
@SuppressWarnings("deprecation")
@Override
public void run() {
craftPlayer.updateInventory();
}
});
}
}
private void addRecipes() {
for (String key : config.getItemConfig().getKeys(false)) {
Material item = Material.matchMaterial(key);
if (item == null) {
logger.info("[RepairRecipe] unknown item " + key);
continue;
}
ConfigurationSection section = config.getItemConfig().getConfigurationSection(key);
Material baseItem = Material.matchMaterial(section.getString("base_item"));
if (baseItem == null) {
logger.info("[RepairRecipe] unknown base item " + section.getString("base_item"));
continue;
}
int baseAmount = section.getInt("base_amount");
if (baseAmount == 0) {
logger.info("[RepairRecipe] No base_amount to repair " + item.name() + " with " + baseItem.name() + ". Repairing is for free!");
}
ShapelessRepairRecipe recipe = new ShapelessRepairRecipe(item, baseItem, baseAmount, this);
recipe.setConfig("keep_enchantments_chance", section.getString("keep_enchantments_chance", null));
recipe.setConfig("enchant_multiplier", section.getString("enchant_multiplier", null));
recipe.setConfig("allow_over_repair", section.getString("allow_over_repair", null));
recipe.setConfig("use_highest_enchant", section.getString("use_highest_enchant", null));
repairRecipes.add(recipe);
getServer().addRecipe(recipe);
if (RepairRecipeConfig.DEBUG)
RepairRecipe.logger.info("Added " + item + " with " + baseAmount + "x" + baseItem);
}
}
}
| 4,335 | 0.618685 | 0.618224 | 121 | 33.826447 | 33.045094 | 144 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.710744 | false | false |
14
|
c969e72560420536c66b7493c1e1782a12fdb146
| 16,037,407,900,469 |
4a3fe668899b098c7e77cc1f7f6b1c2b1dc2bfb2
|
/Individual.java
|
681936eb38275150c962bd973eda4610465412a2
|
[
"Apache-2.0"
] |
permissive
|
Hellboy7abduzcan/Proyecto2.0
|
https://github.com/Hellboy7abduzcan/Proyecto2.0
|
83805fd43559b2dd88b497af7a605da5aca29389
|
24efdef63d27d568d362b1d7dbb5272275ca7ad2
|
refs/heads/main
| 2022-12-27T23:31:10.281000 | 2020-10-07T00:51:50 | 2020-10-07T00:51:50 | 301,890,724 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Proyecto2;
public class Individual extends Cliente {
public String Dpi;
public String contacto;
public String getDpi() {
return Dpi;
}
public void setDpi(String dpi) {
Dpi = dpi;
}
public String getContacto() {
return contacto;
}
public void setContacto(String contacto) {
this.contacto = contacto;
}
}
|
UTF-8
|
Java
| 410 |
java
|
Individual.java
|
Java
|
[] | null |
[] |
package Proyecto2;
public class Individual extends Cliente {
public String Dpi;
public String contacto;
public String getDpi() {
return Dpi;
}
public void setDpi(String dpi) {
Dpi = dpi;
}
public String getContacto() {
return contacto;
}
public void setContacto(String contacto) {
this.contacto = contacto;
}
}
| 410 | 0.57561 | 0.573171 | 22 | 16.636364 | 14.870793 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.318182 | false | false |
14
|
a055f832a45097618273a9113ef70d89a3eadcbb
| 29,248,727,321,394 |
5e9e183fc69a7f869a43d457ca0485491b112e44
|
/uiadapter17-egov-sample1/src/main/java/com/nexacro/sample/service/impl/mybatis/UiAdapterLargeDataMybatisMapper.java
|
9b6faa5570905fd8123972926ed01bbdb5a0c086
|
[] |
no_license
|
juyoung1222/juyoungWeb
|
https://github.com/juyoung1222/juyoungWeb
|
6011cd500bd5ff574fdf6ed6b15bd9a13b1b0029
|
b1570f1f73f0ff804322c754407b6d3709e8cbe5
|
refs/heads/master
| 2023-05-23T08:15:37.276000 | 2021-06-10T04:14:46 | 2021-06-10T04:14:46 | 307,261,714 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.nexacro.sample.service.impl.mybatis;
import org.apache.ibatis.session.ResultHandler;
import egovframework.rte.psl.dataaccess.mapper.Mapper;
/**
* <pre>
* @title
* @desc 제공 예제는 샘플용으로 작성된 코드로 참고용으로만
* 사용하시기 바랍니다.
* - Mapper Class
* @package nexacro.sample.service.impl.mybatis
* <pre>
* @author TOBESOFT
* @since 2017. 11. 8.
* @version 1.0
* @see
* =================== 변경 내역 ==================
* 날짜 변경자 내용
* ------------------------------------------------
* 2017. 11. 8. TOBESOFT 최초작성
*/
@Mapper("largeDataMybatisMapper")
public interface UiAdapterLargeDataMybatisMapper {
public void selectLargeData(ResultHandler resultHandler);
}
|
UTF-8
|
Java
| 786 |
java
|
UiAdapterLargeDataMybatisMapper.java
|
Java
|
[
{
"context": "o.sample.service.impl.mybatis\n * <pre>\n * @author TOBESOFT\n * @since 2017. 11. 8.\n * @version 1.0\n * @see\n",
"end": 347,
"score": 0.9995898008346558,
"start": 339,
"tag": "USERNAME",
"value": "TOBESOFT"
}
] | null |
[] |
package com.nexacro.sample.service.impl.mybatis;
import org.apache.ibatis.session.ResultHandler;
import egovframework.rte.psl.dataaccess.mapper.Mapper;
/**
* <pre>
* @title
* @desc 제공 예제는 샘플용으로 작성된 코드로 참고용으로만
* 사용하시기 바랍니다.
* - Mapper Class
* @package nexacro.sample.service.impl.mybatis
* <pre>
* @author TOBESOFT
* @since 2017. 11. 8.
* @version 1.0
* @see
* =================== 변경 내역 ==================
* 날짜 변경자 내용
* ------------------------------------------------
* 2017. 11. 8. TOBESOFT 최초작성
*/
@Mapper("largeDataMybatisMapper")
public interface UiAdapterLargeDataMybatisMapper {
public void selectLargeData(ResultHandler resultHandler);
}
| 786 | 0.600865 | 0.57781 | 27 | 24.703703 | 19.451391 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.481481 | false | false |
14
|
30b202f2b9e94e09d5dc8bbb7b49535b975e5414
| 29,248,727,319,394 |
5db9c2a1bb5fbfa7ef6440921e93bc5f4e742e82
|
/Android/assignment5/task1/app/src/main/java/com/example/task1/StatusRecyclerViewAdapter.java
|
0bfbee8f13dbf165578e2218e1b00caa1864eea5
|
[] |
no_license
|
diggledoot/projects
|
https://github.com/diggledoot/projects
|
3207ee81b2524a891ab57e5f8b200371085aec16
|
4bf380c202233319c5f425afd179267b1b04d03f
|
refs/heads/master
| 2023-04-29T04:16:42.504000 | 2023-02-04T10:26:05 | 2023-02-04T10:26:05 | 234,905,608 | 0 | 0 | null | false | 2023-04-19T21:30:15 | 2020-01-19T13:33:23 | 2022-11-16T02:57:38 | 2023-04-19T21:30:14 | 173,037 | 0 | 0 | 49 |
JavaScript
| false | false |
package com.example.task1;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Switch;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
public class StatusRecyclerViewAdapter extends RecyclerView.Adapter<StatusRecyclerViewAdapter.ViewHolder>{
//Required variables
ArrayList<Task> taskArrayList;
Context context;
//Date
Date selectedDate;
public StatusRecyclerViewAdapter(ArrayList<Task> taskArrayList, Context context) {
this.taskArrayList = taskArrayList;
this.context = context;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.completed_task_layout,parent,false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
final Task task = taskArrayList.get(position);
holder.title.setText(task.getTitle());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
SimpleDateFormat sdf_format=new SimpleDateFormat("d-MMM-yy");
try {
String temp = task.getDue_date();
selectedDate = sdf.parse(temp);
Date currentDate = Calendar.getInstance().getTime();
long curdate=currentDate.getTime();
long seldate=selectedDate.getTime();
float result = (float)(seldate-curdate)/(24*60*60*1000)+1;
holder.date.setText(sdf_format.format(selectedDate));
if(result<0){
holder.aSwitch.setText("Not Completed");
}
} catch (ParseException e) {
e.printStackTrace();
}
if(task.getCompleted().equals("0")){
holder.aSwitch.setChecked(true);
}
}
@Override
public int getItemCount() {
return taskArrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView title,date;
private Switch aSwitch;
public ViewHolder(@NonNull View itemView) {
super(itemView);
title=itemView.findViewById(R.id.title_completed);
date = itemView.findViewById(R.id.datetitle_completed);
aSwitch=itemView.findViewById(R.id.switch_completed);
}
}
}
|
UTF-8
|
Java
| 2,725 |
java
|
StatusRecyclerViewAdapter.java
|
Java
|
[] | null |
[] |
package com.example.task1;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Switch;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
public class StatusRecyclerViewAdapter extends RecyclerView.Adapter<StatusRecyclerViewAdapter.ViewHolder>{
//Required variables
ArrayList<Task> taskArrayList;
Context context;
//Date
Date selectedDate;
public StatusRecyclerViewAdapter(ArrayList<Task> taskArrayList, Context context) {
this.taskArrayList = taskArrayList;
this.context = context;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.completed_task_layout,parent,false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
final Task task = taskArrayList.get(position);
holder.title.setText(task.getTitle());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
SimpleDateFormat sdf_format=new SimpleDateFormat("d-MMM-yy");
try {
String temp = task.getDue_date();
selectedDate = sdf.parse(temp);
Date currentDate = Calendar.getInstance().getTime();
long curdate=currentDate.getTime();
long seldate=selectedDate.getTime();
float result = (float)(seldate-curdate)/(24*60*60*1000)+1;
holder.date.setText(sdf_format.format(selectedDate));
if(result<0){
holder.aSwitch.setText("Not Completed");
}
} catch (ParseException e) {
e.printStackTrace();
}
if(task.getCompleted().equals("0")){
holder.aSwitch.setChecked(true);
}
}
@Override
public int getItemCount() {
return taskArrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView title,date;
private Switch aSwitch;
public ViewHolder(@NonNull View itemView) {
super(itemView);
title=itemView.findViewById(R.id.title_completed);
date = itemView.findViewById(R.id.datetitle_completed);
aSwitch=itemView.findViewById(R.id.switch_completed);
}
}
}
| 2,725 | 0.671927 | 0.666789 | 81 | 32.641975 | 24.729803 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.604938 | false | false |
14
|
d3594e6c0fe384622887423267cbd79677914949
| 29,248,727,322,353 |
e33e0e8456595479fb54995774591afacbff55eb
|
/src/com/ttms/model/student.java
|
90d56fcffe76a3966f306db0ea9dd9b88a1c7ed8
|
[] |
no_license
|
justiceForEveryone/ttms_uh
|
https://github.com/justiceForEveryone/ttms_uh
|
953bcb104ac049363a8bd3f4326d8d5ec4c20a65
|
2c2d08b201aec7d48c4e8ad141d923cf70dd9d96
|
refs/heads/master
| 2023-02-16T09:56:02.075000 | 2021-01-11T16:56:31 | 2021-01-11T16:56:31 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.ttms.model;
/**
*
* @author Nethmi Dasanayaka
*/
public class student {
public static int ACTIVE_STUDENT = 1;
public static int INACTIVE_STUDENT = 0;
private int id;
private String name;
private String email1;
private String email2;
private String regNo;
private String contactNo;
private String detail;
private int status;
private int batchId;
private int groupId;
private int specialId;
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the email1
*/
public String getEmail1() {
return email1;
}
/**
* @param email1 the email1 to set
*/
public void setEmail1(String email1) {
this.email1 = email1;
}
/**
* @return the email2
*/
public String getEmail2() {
return email2;
}
/**
* @param email2 the email2 to set
*/
public void setEmail2(String email2) {
this.email2 = email2;
}
/**
* @return the regNo
*/
public String getRegNo() {
return regNo;
}
/**
* @param regNo the regNo to set
*/
public void setRegNo(String regNo) {
this.regNo = regNo;
}
/**
* @return the contactNo
*/
public String getContactNo() {
return contactNo;
}
/**
* @param contactNo the contactNo to set
*/
public void setContactNo(String contactNo) {
this.contactNo = contactNo;
}
/**
* @return the detail
*/
public String getDetail() {
return detail;
}
/**
* @param detail the detail to set
*/
public void setDetail(String detail) {
this.detail = detail;
}
/**
* @return the status
*/
public int getStatus() {
return status;
}
/**
* @param status the status to set
*/
public void setStatus(int status) {
this.status = status;
}
/**
* @return the batchId
*/
public int getBatchId() {
return batchId;
}
/**
* @param batchId the batchId to set
*/
public void setBatchId(int batchId) {
this.batchId = batchId;
}
/**
* @return the groupId
*/
public int getGroupId() {
return groupId;
}
/**
* @param groupId the groupId to set
*/
public void setGroupId(int groupId) {
this.groupId = groupId;
}
/**
* @return the specialId
*/
public int getSpecialId() {
return specialId;
}
/**
* @param specialId the specialId to set
*/
public void setSpecialId(int specialId) {
this.specialId = specialId;
}
}
|
UTF-8
|
Java
| 3,255 |
java
|
student.java
|
Java
|
[
{
"context": "or.\n */\npackage com.ttms.model;\n\n/**\n *\n * @author Nethmi Dasanayaka\n */\npublic class student {\n\n public static int",
"end": 245,
"score": 0.9998068809509277,
"start": 228,
"tag": "NAME",
"value": "Nethmi Dasanayaka"
}
] | null |
[] |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.ttms.model;
/**
*
* @author <NAME>
*/
public class student {
public static int ACTIVE_STUDENT = 1;
public static int INACTIVE_STUDENT = 0;
private int id;
private String name;
private String email1;
private String email2;
private String regNo;
private String contactNo;
private String detail;
private int status;
private int batchId;
private int groupId;
private int specialId;
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the email1
*/
public String getEmail1() {
return email1;
}
/**
* @param email1 the email1 to set
*/
public void setEmail1(String email1) {
this.email1 = email1;
}
/**
* @return the email2
*/
public String getEmail2() {
return email2;
}
/**
* @param email2 the email2 to set
*/
public void setEmail2(String email2) {
this.email2 = email2;
}
/**
* @return the regNo
*/
public String getRegNo() {
return regNo;
}
/**
* @param regNo the regNo to set
*/
public void setRegNo(String regNo) {
this.regNo = regNo;
}
/**
* @return the contactNo
*/
public String getContactNo() {
return contactNo;
}
/**
* @param contactNo the contactNo to set
*/
public void setContactNo(String contactNo) {
this.contactNo = contactNo;
}
/**
* @return the detail
*/
public String getDetail() {
return detail;
}
/**
* @param detail the detail to set
*/
public void setDetail(String detail) {
this.detail = detail;
}
/**
* @return the status
*/
public int getStatus() {
return status;
}
/**
* @param status the status to set
*/
public void setStatus(int status) {
this.status = status;
}
/**
* @return the batchId
*/
public int getBatchId() {
return batchId;
}
/**
* @param batchId the batchId to set
*/
public void setBatchId(int batchId) {
this.batchId = batchId;
}
/**
* @return the groupId
*/
public int getGroupId() {
return groupId;
}
/**
* @param groupId the groupId to set
*/
public void setGroupId(int groupId) {
this.groupId = groupId;
}
/**
* @return the specialId
*/
public int getSpecialId() {
return specialId;
}
/**
* @param specialId the specialId to set
*/
public void setSpecialId(int specialId) {
this.specialId = specialId;
}
}
| 3,244 | 0.537634 | 0.530876 | 183 | 16.786884 | 14.912621 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.213115 | false | false |
14
|
692e781d88285f5ca94038d7698e08777b97a359
| 10,642,928,970,335 |
10f842f214c3f7610b7d65acb30dcb1d3dd6c7f1
|
/src/main/java/org/nuradinnur/eyeoftheherald/component/exception/CrawlerResponseErrorHandler.java
|
492550d4f4cf5cedb5cfd49d6d87f4572f83347b
|
[
"Unlicense"
] |
permissive
|
Nuradinnur/eyeoftheherald
|
https://github.com/Nuradinnur/eyeoftheherald
|
38d17a3d9d4dcd85b8350f4c174131b37442c653
|
42891b960d0d01c27102d3248d1d1a505c6ea4e4
|
refs/heads/master
| 2020-04-08T21:58:30.835000 | 2018-12-05T05:27:02 | 2018-12-05T05:27:02 | 159,765,758 | 1 | 0 |
Unlicense
| false | 2018-12-08T04:22:02 | 2018-11-30T03:52:58 | 2018-12-05T05:28:31 | 2018-12-08T04:17:09 | 148 | 0 | 0 | 0 |
Java
| false | null |
package org.nuradinnur.eyeoftheherald.component.exception;
import org.nuradinnur.eyeoftheherald.component.ShutdownHook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.client.ResponseErrorHandler;
import java.io.IOException;
@Component
public class CrawlerResponseErrorHandler implements ResponseErrorHandler {
private final Logger logger;
private final ShutdownHook shutdownHook;
public CrawlerResponseErrorHandler(ShutdownHook shutdownHook) {
this.shutdownHook = shutdownHook;
logger = LoggerFactory.getLogger(this.getClass());
}
@Override
public boolean hasError(ClientHttpResponse clientHttpResponse) throws IOException {
return clientHttpResponse.getStatusCode().is4xxClientError()
|| clientHttpResponse.getStatusCode().is5xxServerError();
}
@Override
public void handleError(ClientHttpResponse clientHttpResponse) throws IOException {
switch (clientHttpResponse.getStatusCode()) {
case UNAUTHORIZED:
case FORBIDDEN:
case UNSUPPORTED_MEDIA_TYPE:
logger.error("FATAL error with response code: {} ({})",
clientHttpResponse.getStatusCode().value(),
clientHttpResponse.getStatusText().toUpperCase());
shutdownHook.shutdownGracefully();
case BAD_REQUEST:
case NOT_FOUND:
logger.debug("Response code: {} ({})",
clientHttpResponse.getStatusCode().value(),
clientHttpResponse.getStatusText().toUpperCase());
break;
case TOO_MANY_REQUESTS:
logger.warn("Exceptional response code: {} ({})",
clientHttpResponse.getStatusCode().value(),
clientHttpResponse.getStatusText().toUpperCase());
break;
case INTERNAL_SERVER_ERROR:
case SERVICE_UNAVAILABLE:
logger.warn("Game data servers returned error code: {} ({})",
clientHttpResponse.getStatusCode().value(),
clientHttpResponse.getStatusText().toUpperCase());
break;
default:
logger.error("Unexpected response code: {} ({})",
clientHttpResponse.getStatusCode().value(),
clientHttpResponse.getStatusText().toUpperCase());
shutdownHook.shutdownGracefully();
}
}
}
|
UTF-8
|
Java
| 2,664 |
java
|
CrawlerResponseErrorHandler.java
|
Java
|
[] | null |
[] |
package org.nuradinnur.eyeoftheherald.component.exception;
import org.nuradinnur.eyeoftheherald.component.ShutdownHook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.client.ResponseErrorHandler;
import java.io.IOException;
@Component
public class CrawlerResponseErrorHandler implements ResponseErrorHandler {
private final Logger logger;
private final ShutdownHook shutdownHook;
public CrawlerResponseErrorHandler(ShutdownHook shutdownHook) {
this.shutdownHook = shutdownHook;
logger = LoggerFactory.getLogger(this.getClass());
}
@Override
public boolean hasError(ClientHttpResponse clientHttpResponse) throws IOException {
return clientHttpResponse.getStatusCode().is4xxClientError()
|| clientHttpResponse.getStatusCode().is5xxServerError();
}
@Override
public void handleError(ClientHttpResponse clientHttpResponse) throws IOException {
switch (clientHttpResponse.getStatusCode()) {
case UNAUTHORIZED:
case FORBIDDEN:
case UNSUPPORTED_MEDIA_TYPE:
logger.error("FATAL error with response code: {} ({})",
clientHttpResponse.getStatusCode().value(),
clientHttpResponse.getStatusText().toUpperCase());
shutdownHook.shutdownGracefully();
case BAD_REQUEST:
case NOT_FOUND:
logger.debug("Response code: {} ({})",
clientHttpResponse.getStatusCode().value(),
clientHttpResponse.getStatusText().toUpperCase());
break;
case TOO_MANY_REQUESTS:
logger.warn("Exceptional response code: {} ({})",
clientHttpResponse.getStatusCode().value(),
clientHttpResponse.getStatusText().toUpperCase());
break;
case INTERNAL_SERVER_ERROR:
case SERVICE_UNAVAILABLE:
logger.warn("Game data servers returned error code: {} ({})",
clientHttpResponse.getStatusCode().value(),
clientHttpResponse.getStatusText().toUpperCase());
break;
default:
logger.error("Unexpected response code: {} ({})",
clientHttpResponse.getStatusCode().value(),
clientHttpResponse.getStatusText().toUpperCase());
shutdownHook.shutdownGracefully();
}
}
}
| 2,664 | 0.626877 | 0.625375 | 63 | 41.285713 | 26.928141 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false |
14
|
d8fc2e39ce7744a6d6c6b66d1a6e58b8a948f36e
| 32,865,089,761,995 |
02ed1309bd166742469a417dfec2af43fd237a0a
|
/geoforce-base/src/main/java/com/supermap/egispservice/base/pojo/BaseAccessInfo.java
|
898988954182940d135beff82a2735f8251bab73
|
[] |
no_license
|
beiyu005/geoforce
|
https://github.com/beiyu005/geoforce
|
92865c2cc2e590050f42cfec0d6dc3cfee9f5ace
|
e19eb8e9221370e0a590bc3224e8b9ac4260d88b
|
refs/heads/master
| 2022-04-08T16:42:20.166000 | 2018-03-31T08:29:05 | 2018-03-31T08:29:05 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.supermap.egispservice.base.pojo;
import java.io.Serializable;
public class BaseAccessInfo implements Serializable {
private static final long serialVersionUID = 7173997010886220440L;
private String userId;
private String realName;
private String companyName;
private String companyId;
private String source;
private String status;
private String email;
private String username;
private String tel;
private int iid;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getCompanyId() {
return companyId;
}
public void setCompanyId(String companyId) {
this.companyId = companyId;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public int getIid() {
return iid;
}
public void setIid(int iid) {
this.iid = iid;
}
}
|
UTF-8
|
Java
| 1,720 |
java
|
BaseAccessInfo.java
|
Java
|
[
{
"context": "ail;\r\n\t}\r\n\tpublic String getUsername() {\r\n\t\treturn username;\r\n\t}\r\n\tpublic void setUsername(String username) {",
"end": 1416,
"score": 0.8501331210136414,
"start": 1408,
"tag": "USERNAME",
"value": "username"
},
{
"context": " setUsername(String username) {\r\n\t\tthis.username = username;\r\n\t}\r\n\tpublic String getTel() {\r\n\t\treturn tel;\r\n\t",
"end": 1494,
"score": 0.9509595036506653,
"start": 1486,
"tag": "USERNAME",
"value": "username"
}
] | null |
[] |
package com.supermap.egispservice.base.pojo;
import java.io.Serializable;
public class BaseAccessInfo implements Serializable {
private static final long serialVersionUID = 7173997010886220440L;
private String userId;
private String realName;
private String companyName;
private String companyId;
private String source;
private String status;
private String email;
private String username;
private String tel;
private int iid;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getCompanyId() {
return companyId;
}
public void setCompanyId(String companyId) {
this.companyId = companyId;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public int getIid() {
return iid;
}
public void setIid(int iid) {
this.iid = iid;
}
}
| 1,720 | 0.687791 | 0.676744 | 83 | 18.722891 | 15.26419 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.554217 | false | false |
14
|
17d7c521e66a899e6365bc77a43f6fb8012a176f
| 10,892,037,128,940 |
10a00770b56d2c416756da1d9f6e438b05da371c
|
/productorderexercise/src/main/java/com/stackroute/oops/ProductService.java
|
4a2cc7c47f63cdd77cacec637445691932b6a5c1
|
[] |
no_license
|
Raja369/JavaRepo
|
https://github.com/Raja369/JavaRepo
|
47bd3bdd23123d03bdda46f9e4aa303bd54d2bde
|
668d38bd9d8bcb0e9d14de58b6f8893e8dd32319
|
refs/heads/master
| 2023-04-21T11:31:36.942000 | 2021-05-22T12:17:49 | 2021-05-22T12:17:49 | 369,799,716 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.stackroute.oops;
/*
Class for Analyzing the products present in ProductRepository
*/
public class ProductService {
Product[] productDetails = ProductRepository.getProducts();
/*
* Returns the name of the product given the productCode
*/
public String findProductNameByCode(int productCode) {
if (productCode > 100 && productCode < 109) {
int index = productCode % 100;
index = index - 1;
return productDetails[index].getName();
}
return null;
}
/*
* Returns the Product with maximum price in a given category
*/
public Product findMaxPriceProductInCategory(String category) {
if (category.equals("computers")) {
return productDetails[2];
}
if (category.equals("clothing")) {
return productDetails[4];
}
if (category.equals("toys")) {
return productDetails[7];
}
return null;
}
/*
* Returns a array of products for a given category
*/
public Product[] getProductsByCategory(String category) {
if (category.equals("computers")) {
return new Product[] { productDetails[0], productDetails[1], productDetails[2] };
}
if (category.equals("clothing")) {
return new Product[] { productDetails[3], productDetails[4], productDetails[5] };
}
if (category.equals("toys")) {
return new Product[] { productDetails[6], productDetails[7] };
}
return null;
}
}
|
UTF-8
|
Java
| 1,346 |
java
|
ProductService.java
|
Java
|
[] | null |
[] |
package com.stackroute.oops;
/*
Class for Analyzing the products present in ProductRepository
*/
public class ProductService {
Product[] productDetails = ProductRepository.getProducts();
/*
* Returns the name of the product given the productCode
*/
public String findProductNameByCode(int productCode) {
if (productCode > 100 && productCode < 109) {
int index = productCode % 100;
index = index - 1;
return productDetails[index].getName();
}
return null;
}
/*
* Returns the Product with maximum price in a given category
*/
public Product findMaxPriceProductInCategory(String category) {
if (category.equals("computers")) {
return productDetails[2];
}
if (category.equals("clothing")) {
return productDetails[4];
}
if (category.equals("toys")) {
return productDetails[7];
}
return null;
}
/*
* Returns a array of products for a given category
*/
public Product[] getProductsByCategory(String category) {
if (category.equals("computers")) {
return new Product[] { productDetails[0], productDetails[1], productDetails[2] };
}
if (category.equals("clothing")) {
return new Product[] { productDetails[3], productDetails[4], productDetails[5] };
}
if (category.equals("toys")) {
return new Product[] { productDetails[6], productDetails[7] };
}
return null;
}
}
| 1,346 | 0.691679 | 0.676077 | 49 | 26.489796 | 24.608877 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2 | false | false |
14
|
afd3b4227e1e4b2a28f4f8d308d353a6dc35a3b3
| 7,378,753,854,019 |
e7c42c0cf37cbd12da99b21b6599f0eaa02f0bdc
|
/src/com/deliverik/infogovernor/cic/model/dao/CompareobjectHistoryDAO.java
|
dcb347707b3f80250ca5c8f2f8e6f342c8bf7229
|
[] |
no_license
|
SuPerCat323/IGCRCB
|
https://github.com/SuPerCat323/IGCRCB
|
b6c577705a0983c658301f418d05925557d2ec56
|
4fbe4a786e1621f6a76b716dfd73b8206f0b2e0b
|
refs/heads/master
| 2020-09-28T02:45:33.354000 | 2017-10-17T00:16:49 | 2017-10-17T00:16:49 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* 北京递蓝科软件技术有限公司版权所有,保留所有权利。
*/
package com.deliverik.infogovernor.cic.model.dao;
import java.io.Serializable;
import java.util.List;
import com.deliverik.framework.dao.hibernate.BaseHibernateDAO;
import com.deliverik.infogovernor.cic.model.CompareobjectHistoryInfo;
import com.deliverik.infogovernor.cic.model.condition.CompareobjectHistorySearchCond;
/**
* 概述: 对比对象历史表DAO接口
* 功能描述: 对比对象历史表DAO接口
* 创建记录: 2014/04/24
* 修改记录:
*/
public interface CompareobjectHistoryDAO extends BaseHibernateDAO<CompareobjectHistoryInfo> {
/**
* 全件检索
*
* @return 检索结果集
*/
public List<CompareobjectHistoryInfo> findAll();
/**
* 主键检索处理
*
* @param pk 主键
* @return 检索结果
*/
public CompareobjectHistoryInfo findByPK(Serializable pk);
/**
* 条件检索结果件数取得
*
* @param cond 检索条件
* @return 检索结果件数
*/
public int getSearchCount(final CompareobjectHistorySearchCond cond);
/**
* 条件检索处理
*
* @param cond 检索条件
* @param start 检索记录起始行号
* @param count 检索记录件数
* @return 检索结果列表
*/
public List<CompareobjectHistoryInfo> findByCond(
final CompareobjectHistorySearchCond cond, final int start,
final int count);
}
|
GB18030
|
Java
| 1,402 |
java
|
CompareobjectHistoryDAO.java
|
Java
|
[] | null |
[] |
/*
* 北京递蓝科软件技术有限公司版权所有,保留所有权利。
*/
package com.deliverik.infogovernor.cic.model.dao;
import java.io.Serializable;
import java.util.List;
import com.deliverik.framework.dao.hibernate.BaseHibernateDAO;
import com.deliverik.infogovernor.cic.model.CompareobjectHistoryInfo;
import com.deliverik.infogovernor.cic.model.condition.CompareobjectHistorySearchCond;
/**
* 概述: 对比对象历史表DAO接口
* 功能描述: 对比对象历史表DAO接口
* 创建记录: 2014/04/24
* 修改记录:
*/
public interface CompareobjectHistoryDAO extends BaseHibernateDAO<CompareobjectHistoryInfo> {
/**
* 全件检索
*
* @return 检索结果集
*/
public List<CompareobjectHistoryInfo> findAll();
/**
* 主键检索处理
*
* @param pk 主键
* @return 检索结果
*/
public CompareobjectHistoryInfo findByPK(Serializable pk);
/**
* 条件检索结果件数取得
*
* @param cond 检索条件
* @return 检索结果件数
*/
public int getSearchCount(final CompareobjectHistorySearchCond cond);
/**
* 条件检索处理
*
* @param cond 检索条件
* @param start 检索记录起始行号
* @param count 检索记录件数
* @return 检索结果列表
*/
public List<CompareobjectHistoryInfo> findByCond(
final CompareobjectHistorySearchCond cond, final int start,
final int count);
}
| 1,402 | 0.729494 | 0.722513 | 57 | 19.122807 | 23.344912 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.824561 | false | false |
14
|
6b4a00f779e33e37a39696c88a28fddfca0c64a4
| 24,678,882,112,209 |
80d26952b61a59fd2b5d8d7ca8909a886bf52fe9
|
/src/NaoExisteTaxiException.java
|
6cbfd9e5a43e3e7f1fb87620ed1d44bae2fa5aa0
|
[] |
no_license
|
Barca88/POO-UMer
|
https://github.com/Barca88/POO-UMer
|
a4741c550c73c10a1ba49c0b42d8c2bf5c56ffb5
|
857d8d1758d2bdf4640ad560231ef327e010fbdb
|
refs/heads/master
| 2021-03-24T13:46:18.694000 | 2017-07-06T20:25:38 | 2017-07-06T20:25:38 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class NaoExisteTaxiException extends Exception {
public NaoExisteTaxiException (String msg){
super(msg);
}
}
|
UTF-8
|
Java
| 129 |
java
|
NaoExisteTaxiException.java
|
Java
|
[] | null |
[] |
public class NaoExisteTaxiException extends Exception {
public NaoExisteTaxiException (String msg){
super(msg);
}
}
| 129 | 0.728682 | 0.728682 | 6 | 20.666666 | 21.390549 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.166667 | false | false |
14
|
d61d768a4e2ceada8f010ebf563f988d47c9d063
| 12,300,786,379,084 |
60274bb846c0ed0863a3d2c6c45e9d9db1d9e04b
|
/app/src/main/java/kr/co/tjeit/calendar/adapter/GridViewAdapter.java
|
cf1f303d4319c141f3ef6d077785870b9fbe1526
|
[] |
no_license
|
hyuni106/Calendar
|
https://github.com/hyuni106/Calendar
|
722929066e7a9bbf8b427e89c37fc13bbfd8ce66
|
56ede6f3fb2eb733876a2ff22ce8b38e4ef12dbf
|
refs/heads/master
| 2021-05-07T06:58:09.611000 | 2017-12-12T01:56:31 | 2017-12-12T01:56:31 | 111,782,654 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package kr.co.tjeit.calendar.adapter;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
import kr.co.tjeit.calendar.R;
import kr.co.tjeit.calendar.data.Group;
import kr.co.tjeit.calendar.data.Schedule;
/**
* Created by the on 2017-11-27.
*/
public class GridViewAdapter extends ArrayAdapter<Group> {
Context mContext;
List<Group> mList;
LayoutInflater inf;
public GridViewAdapter(Context context, List<Group> list) {
super(context, R.layout.gridview_item, list);
mContext = context;
mList = list;
inf = LayoutInflater.from(mContext);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View row = convertView;
if ( row == null) {
row = inf.inflate(R.layout.gridview_item, null);
}
Group data = mList.get(position);
TextView calNameTxt = (TextView) row.findViewById(R.id.calNameTxt);
TextView calInfoTxt = (TextView) row.findViewById(R.id.calInfoTxt);
calNameTxt.setText(data.getName());
calInfoTxt.setText(data.getComment());
return row;
}
}
|
UTF-8
|
Java
| 1,421 |
java
|
GridViewAdapter.java
|
Java
|
[
{
"context": "o.tjeit.calendar.data.Schedule;\n\n/**\n * Created by the on 2017-11-27.\n */\n\npublic class GridViewAdapter ",
"end": 480,
"score": 0.6902470588684082,
"start": 477,
"tag": "USERNAME",
"value": "the"
}
] | null |
[] |
package kr.co.tjeit.calendar.adapter;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
import kr.co.tjeit.calendar.R;
import kr.co.tjeit.calendar.data.Group;
import kr.co.tjeit.calendar.data.Schedule;
/**
* Created by the on 2017-11-27.
*/
public class GridViewAdapter extends ArrayAdapter<Group> {
Context mContext;
List<Group> mList;
LayoutInflater inf;
public GridViewAdapter(Context context, List<Group> list) {
super(context, R.layout.gridview_item, list);
mContext = context;
mList = list;
inf = LayoutInflater.from(mContext);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View row = convertView;
if ( row == null) {
row = inf.inflate(R.layout.gridview_item, null);
}
Group data = mList.get(position);
TextView calNameTxt = (TextView) row.findViewById(R.id.calNameTxt);
TextView calInfoTxt = (TextView) row.findViewById(R.id.calInfoTxt);
calNameTxt.setText(data.getName());
calInfoTxt.setText(data.getComment());
return row;
}
}
| 1,421 | 0.69247 | 0.68684 | 53 | 25.811321 | 22.906748 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.641509 | false | false |
14
|
16109cc693b8c36a6f862856f1570d646ffa1ff7
| 23,510,651,022,195 |
60e1a7df2076c835a47959979cc2a277a9ba7546
|
/vapor-zeroconf/src/main/java/evymind/vapor/zeroconf/BonjourBrowserStrategy.java
|
541eb10e446ca60717d1d235f0330d98a9a09eed
|
[] |
no_license
|
torworx/Vapor
|
https://github.com/torworx/Vapor
|
09243f4c871d6711df5f0eba3e6b7cf12359c0e6
|
4dc7156e50a2b72095f37e539ea0388b518f18ed
|
refs/heads/master
| 2021-01-25T04:02:38.658000 | 2013-03-18T12:54:06 | 2013-03-18T12:54:06 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package evymind.vapor.zeroconf;
import evymind.vapor.zeroconf.utils.DNSUtils;
import javax.jmdns.JmDNS;
import javax.jmdns.ServiceEvent;
import javax.jmdns.ServiceInfo;
import javax.jmdns.ServiceListener;
import java.io.IOException;
/**
* Copyright 2012 EvyMind.
*/
public class BonjourBrowserStrategy extends AbstractZeroConfBrowserStrategy {
private final ZeroConfBrowser browser;
private JmDNS mdns;
public BonjourBrowserStrategy(ZeroConfBrowser browser) {
this.browser = browser;
}
@Override
public ZeroConfStrategy getCurrentStrategyType() {
return ZeroConfStrategy.BONJOUR;
}
@Override
public void start(String domain, String type) {
stop();
try {
mdns = JmDNS.create();
String qualifiedType = DNSUtils.qualify(type, domain);
ServiceListener listener = new BonjourServiceListener(domain, type);
mdns.addServiceListener(qualifiedType, listener);
} catch (IOException e) {
throw new ZeroConfException(e);
}
}
@Override
public void stop() {
if (mdns != null) {
try {
mdns.close();
} catch (IOException e) {
throw new ZeroConfException(e);
}
}
}
class BonjourServiceListener implements ServiceListener {
private final String domain;
private final String type;
BonjourServiceListener(String domain, String type) {
this.domain = domain;
this.type = type;
}
@Override
public void serviceAdded(ServiceEvent event) {
BonjourBrowserStrategy.this.mdns.requestServiceInfo(event.getType(), event.getName(), 1);
}
@Override
public void serviceRemoved(ServiceEvent event) {
synchronized (this) {
BonjourBrowserStrategy.this.browser.fireServiceRemoved(new ZeroConfService(BonjourBrowserStrategy.this.browser,
BonjourResolver.getInstance(), event.getInfo().getDomain(), event.getName(), event.getType()));
}
}
@Override
public void serviceResolved(ServiceEvent event) {
synchronized (this) {
ServiceInfo info = event.getInfo();
ZeroConfService service = new ZeroConfService(BonjourBrowserStrategy.this.browser,
BonjourResolver.getInstance(), info.getDomain(), info.getName(), info.getType());
BonjourResolver.resolveService(service, info);
BonjourBrowserStrategy.this.browser.fireServiceAdded(service);
}
}
}
}
|
UTF-8
|
Java
| 2,685 |
java
|
BonjourBrowserStrategy.java
|
Java
|
[
{
"context": "import java.io.IOException;\n\n/**\n * Copyright 2012 EvyMind.\n */\npublic class BonjourBrowserStrategy extends ",
"end": 265,
"score": 0.9654250144958496,
"start": 258,
"tag": "USERNAME",
"value": "EvyMind"
}
] | null |
[] |
package evymind.vapor.zeroconf;
import evymind.vapor.zeroconf.utils.DNSUtils;
import javax.jmdns.JmDNS;
import javax.jmdns.ServiceEvent;
import javax.jmdns.ServiceInfo;
import javax.jmdns.ServiceListener;
import java.io.IOException;
/**
* Copyright 2012 EvyMind.
*/
public class BonjourBrowserStrategy extends AbstractZeroConfBrowserStrategy {
private final ZeroConfBrowser browser;
private JmDNS mdns;
public BonjourBrowserStrategy(ZeroConfBrowser browser) {
this.browser = browser;
}
@Override
public ZeroConfStrategy getCurrentStrategyType() {
return ZeroConfStrategy.BONJOUR;
}
@Override
public void start(String domain, String type) {
stop();
try {
mdns = JmDNS.create();
String qualifiedType = DNSUtils.qualify(type, domain);
ServiceListener listener = new BonjourServiceListener(domain, type);
mdns.addServiceListener(qualifiedType, listener);
} catch (IOException e) {
throw new ZeroConfException(e);
}
}
@Override
public void stop() {
if (mdns != null) {
try {
mdns.close();
} catch (IOException e) {
throw new ZeroConfException(e);
}
}
}
class BonjourServiceListener implements ServiceListener {
private final String domain;
private final String type;
BonjourServiceListener(String domain, String type) {
this.domain = domain;
this.type = type;
}
@Override
public void serviceAdded(ServiceEvent event) {
BonjourBrowserStrategy.this.mdns.requestServiceInfo(event.getType(), event.getName(), 1);
}
@Override
public void serviceRemoved(ServiceEvent event) {
synchronized (this) {
BonjourBrowserStrategy.this.browser.fireServiceRemoved(new ZeroConfService(BonjourBrowserStrategy.this.browser,
BonjourResolver.getInstance(), event.getInfo().getDomain(), event.getName(), event.getType()));
}
}
@Override
public void serviceResolved(ServiceEvent event) {
synchronized (this) {
ServiceInfo info = event.getInfo();
ZeroConfService service = new ZeroConfService(BonjourBrowserStrategy.this.browser,
BonjourResolver.getInstance(), info.getDomain(), info.getName(), info.getType());
BonjourResolver.resolveService(service, info);
BonjourBrowserStrategy.this.browser.fireServiceAdded(service);
}
}
}
}
| 2,685 | 0.625326 | 0.623464 | 87 | 29.862068 | 29.334446 | 127 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.517241 | false | false |
14
|
64159797f4f87cee524f4f637975e1832a305f06
| 31,018,253,836,569 |
2c669ccff008612f6e12054d9162597f2088442c
|
/MEVO_apkpure.com_source_from_JADX/sources/com/google/android/gms/internal/measurement/zzia.java
|
7457bcbd842bd39a2bf7e450b4b5ec1fd9ba1bd6
|
[] |
no_license
|
PythonicNinja/mevo
|
https://github.com/PythonicNinja/mevo
|
e97fb27f302cb3554a69b27022dada2134ff99c0
|
cab7cea9376085caead1302b93e62e0d34a75470
|
refs/heads/master
| 2020-05-02T22:32:46.764000 | 2019-03-28T23:37:51 | 2019-03-28T23:37:51 | 178,254,526 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.google.android.gms.internal.measurement;
import java.util.concurrent.atomic.AtomicReference;
final class zzia implements Runnable {
private final /* synthetic */ AtomicReference zzapr;
private final /* synthetic */ zzhm zzaps;
zzia(zzhm zzhm, AtomicReference atomicReference) {
this.zzaps = zzhm;
this.zzapr = atomicReference;
}
public final void run() {
synchronized (this.zzapr) {
try {
this.zzapr.set(Double.valueOf(this.zzaps.zzgk().zzc(this.zzaps.zzfz().zzah(), zzez.zzajp)));
this.zzapr.notify();
} catch (Throwable th) {
this.zzapr.notify();
}
}
}
}
|
UTF-8
|
Java
| 713 |
java
|
zzia.java
|
Java
|
[] | null |
[] |
package com.google.android.gms.internal.measurement;
import java.util.concurrent.atomic.AtomicReference;
final class zzia implements Runnable {
private final /* synthetic */ AtomicReference zzapr;
private final /* synthetic */ zzhm zzaps;
zzia(zzhm zzhm, AtomicReference atomicReference) {
this.zzaps = zzhm;
this.zzapr = atomicReference;
}
public final void run() {
synchronized (this.zzapr) {
try {
this.zzapr.set(Double.valueOf(this.zzaps.zzgk().zzc(this.zzaps.zzfz().zzah(), zzez.zzajp)));
this.zzapr.notify();
} catch (Throwable th) {
this.zzapr.notify();
}
}
}
}
| 713 | 0.598878 | 0.598878 | 24 | 28.708334 | 25.247902 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.458333 | false | false |
14
|
f3222d614a0a249bbe8d22d127c37b3804a90fdd
| 85,899,381,487 |
89afcfd9822ecfef1f696fd62c27218e0f874744
|
/app/src/main/java/com/whatmedia/ttia/page/main/useful/language/TravelLanguagePresenter.java
|
532c61b2b8350a54c553620f21a57a515f2e5afe
|
[] |
no_license
|
ilikekobe0502/Airport
|
https://github.com/ilikekobe0502/Airport
|
d99647a98abfda4ef42ed10613cdc07b380b943e
|
a346d59e411377045503d4bd8e48f12aa1461b64
|
refs/heads/master
| 2021-01-15T14:28:36.573000 | 2017-09-29T12:34:44 | 2017-09-29T12:34:44 | 99,692,168 | 0 | 1 | null | false | 2018-02-12T05:17:56 | 2017-08-08T12:49:42 | 2017-08-08T12:55:33 | 2018-02-12T05:17:56 | 45,184 | 0 | 1 | 0 |
Java
| false | null |
package com.whatmedia.ttia.page.main.useful.language;
import android.content.Context;
import com.whatmedia.ttia.connect.ApiConnect;
public class TravelLanguagePresenter implements TravelLanguageContract.Presenter{
private final static String TAG = TravelLanguagePresenter.class.getSimpleName();
private static TravelLanguagePresenter mTravelLanguagePresenter;
private static ApiConnect mApiConnect;
private static TravelLanguageContract.View mView;
public static TravelLanguagePresenter getInstance(Context context, TravelLanguageContract.View view) {
mTravelLanguagePresenter = new TravelLanguagePresenter();
mApiConnect = ApiConnect.getInstance(context);
mView = view;
return mTravelLanguagePresenter;
}
}
|
UTF-8
|
Java
| 771 |
java
|
TravelLanguagePresenter.java
|
Java
|
[] | null |
[] |
package com.whatmedia.ttia.page.main.useful.language;
import android.content.Context;
import com.whatmedia.ttia.connect.ApiConnect;
public class TravelLanguagePresenter implements TravelLanguageContract.Presenter{
private final static String TAG = TravelLanguagePresenter.class.getSimpleName();
private static TravelLanguagePresenter mTravelLanguagePresenter;
private static ApiConnect mApiConnect;
private static TravelLanguageContract.View mView;
public static TravelLanguagePresenter getInstance(Context context, TravelLanguageContract.View view) {
mTravelLanguagePresenter = new TravelLanguagePresenter();
mApiConnect = ApiConnect.getInstance(context);
mView = view;
return mTravelLanguagePresenter;
}
}
| 771 | 0.79118 | 0.79118 | 22 | 34.045456 | 32.719852 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.545455 | false | false |
14
|
6c0829459a6c51c24195935183279b3afa54a619
| 9,826,885,222,436 |
9731931c3c2eb8c63cb07a95de079d89d9797723
|
/src/DataStructure/Stack/ValidParentheses.java
|
474b11eb59a8e93f4e240374d9433bf175cb46dc
|
[] |
no_license
|
njuxiaoqian/NineChaptersAlgorithm
|
https://github.com/njuxiaoqian/NineChaptersAlgorithm
|
438cd65ed7086807f5c9bc370cb88af2076482fe
|
3d26588afa0fa23c106b05690223038cc88d0068
|
refs/heads/master
| 2021-01-19T20:22:46.093000 | 2016-01-01T07:55:21 | 2016-01-01T07:55:21 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package DataStructure.Stack;
import java.util.Stack;
/**
* Created by hao on 15-10-20.
*/
public class ValidParentheses {
/**
* @param s A string
* @return whether the string is a valid parentheses
*/
public boolean isValidParentheses(String s) {
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
char cur = s.charAt(i);
switch (cur) {
case ')': if (!isValid(stack, cur)) {
return false;
}
break;
case ']': if (!isValid(stack, cur)) {
return false;
}
break;
case '}': if (!isValid(stack, cur)) {
return false;
}
break;
default: stack.push(cur);
}
}
return stack.isEmpty();
}
private boolean isValid(Stack<Character> stack, char b) {
if (stack.isEmpty()) {
return false;
}
char a = stack.pop();
return a == b - 1 || a == b - 2;
}
public static void main(String[] args) {
ValidParentheses vp = new ValidParentheses();
System.out.print(vp.isValidParentheses("[]()"));
}
}
|
UTF-8
|
Java
| 1,318 |
java
|
ValidParentheses.java
|
Java
|
[
{
"context": "Stack;\n\nimport java.util.Stack;\n\n/**\n * Created by hao on 15-10-20.\n */\npublic class ValidParentheses {\n",
"end": 76,
"score": 0.993817925453186,
"start": 73,
"tag": "USERNAME",
"value": "hao"
}
] | null |
[] |
package DataStructure.Stack;
import java.util.Stack;
/**
* Created by hao on 15-10-20.
*/
public class ValidParentheses {
/**
* @param s A string
* @return whether the string is a valid parentheses
*/
public boolean isValidParentheses(String s) {
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
char cur = s.charAt(i);
switch (cur) {
case ')': if (!isValid(stack, cur)) {
return false;
}
break;
case ']': if (!isValid(stack, cur)) {
return false;
}
break;
case '}': if (!isValid(stack, cur)) {
return false;
}
break;
default: stack.push(cur);
}
}
return stack.isEmpty();
}
private boolean isValid(Stack<Character> stack, char b) {
if (stack.isEmpty()) {
return false;
}
char a = stack.pop();
return a == b - 1 || a == b - 2;
}
public static void main(String[] args) {
ValidParentheses vp = new ValidParentheses();
System.out.print(vp.isValidParentheses("[]()"));
}
}
| 1,318 | 0.45827 | 0.451442 | 50 | 25.360001 | 18.764605 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
14
|
be483c03a4152b385bff41cd0fa3bfb3ef42ca8d
| 9,826,885,223,920 |
ed589ea2c8dededa36d3b6d24fc86472a22322b6
|
/trunk/GoJava1/sergey.poznyak/MyProject/FoodCalculations/trunk/src/ua/com/goit/gojava/poznyak/ListServiceHardcodedDataTest.java
|
a6d580b6c00c717e9ffcdfebf48bb0d3924632c8
|
[] |
no_license
|
baygoit/GoJava
|
https://github.com/baygoit/GoJava
|
dcf884d271a4612051036e4fdc2c882c343ec870
|
a0a07165092bcc60e109c84227b0024f4bca38ed
|
refs/heads/master
| 2020-04-16T01:46:09.808000 | 2016-08-06T06:28:13 | 2016-08-06T06:28:13 | 42,005,479 | 8 | 27 | null | false | 2016-03-09T11:26:20 | 2015-09-06T14:28:53 | 2016-01-11T14:00:31 | 2016-03-09T11:26:19 | 246,886 | 6 | 19 | 1 |
Java
| null | null |
package ua.com.goit.gojava.poznyak;
import static org.junit.Assert.*;
import java.util.List;
import org.junit.Test;
/**
* This class tests ListServiceHardcodedData class.
*
* @version 0.1 11 Feb 2015
* @author Sergey Poznyak
*/
public class ListServiceHardcodedDataTest {
@Test
public void testGetDishList() {
List<Dish> dishList = ListServiceHardcodedData.getDishList();
assertNotNull(dishList);
assertEquals(5, dishList.size());
assertEquals("1. Borshch", dishList.get(0).toString());
}
@Test
public void testGetFoodstuffList() {
List<Foodstuff> foodstuffList = ListServiceHardcodedData.getFoodstuffList();
assertNotNull(foodstuffList);
assertEquals("buckwheat", foodstuffList.get(0).toString());
}
}
|
UTF-8
|
Java
| 764 |
java
|
ListServiceHardcodedDataTest.java
|
Java
|
[
{
"context": "ass.\r\n * \r\n * @version 0.1 11 Feb 2015\r\n * @author Sergey Poznyak\r\n */\r\npublic class ListServiceHardcodedDataTest {",
"end": 241,
"score": 0.999834418296814,
"start": 227,
"tag": "NAME",
"value": "Sergey Poznyak"
}
] | null |
[] |
package ua.com.goit.gojava.poznyak;
import static org.junit.Assert.*;
import java.util.List;
import org.junit.Test;
/**
* This class tests ListServiceHardcodedData class.
*
* @version 0.1 11 Feb 2015
* @author <NAME>
*/
public class ListServiceHardcodedDataTest {
@Test
public void testGetDishList() {
List<Dish> dishList = ListServiceHardcodedData.getDishList();
assertNotNull(dishList);
assertEquals(5, dishList.size());
assertEquals("1. Borshch", dishList.get(0).toString());
}
@Test
public void testGetFoodstuffList() {
List<Foodstuff> foodstuffList = ListServiceHardcodedData.getFoodstuffList();
assertNotNull(foodstuffList);
assertEquals("buckwheat", foodstuffList.get(0).toString());
}
}
| 756 | 0.717277 | 0.701571 | 30 | 23.466667 | 22.324476 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.133333 | false | false |
14
|
09a9b7821fa27ad797c3dc1121250b8ca47afe57
| 37,718,402,816,565 |
894ab9c137982ed374c9f19a28020d136a80a31c
|
/puzzle/Display.java
|
2f2de2e60ee76f121b5fb881ad098862e0b92950
|
[] |
no_license
|
yasynn/PegPuzzle
|
https://github.com/yasynn/PegPuzzle
|
83bd02d8471e22f280db978e6d1b52b3637a61ae
|
fb469f3b126c5c756710f0b93a17a10d63bf3dbc
|
refs/heads/master
| 2022-06-01T14:50:20.989000 | 2020-05-04T02:56:07 | 2020-05-04T02:56:07 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package puzzle;
/**
*
* @author Andrew Clark, Justin Greco, Mohammed Yaseen
*/
public class Display {
public void Display()
{
System.out.println("Display Created!");
}
final public static int SIZE = 5;
public void print(int mask) {
for (int i=0; i<SIZE; i++) {
for (int j=0; j<SIZE-1-i; j++) System.out.print(" ");
for (int j=0; j<=i; j++) {
if (on(mask, SIZE*i+j)) System.out.print("X ");
else System.out.print(". ");
}
System.out.println();
}
System.out.println();
}
public static boolean on(int mask, int bit) {
return (mask & (1<<bit)) != 0;
}
}
|
UTF-8
|
Java
| 947 |
java
|
Display.java
|
Java
|
[
{
"context": "itor.\r\n */\r\npackage puzzle;\r\n\r\n/**\r\n *\r\n * @author Andrew Clark, Justin Greco, Mohammed Yaseen\r\n */\r\npublic class",
"end": 241,
"score": 0.9998683333396912,
"start": 229,
"tag": "NAME",
"value": "Andrew Clark"
},
{
"context": "ckage puzzle;\r\n\r\n/**\r\n *\r\n * @author Andrew Clark, Justin Greco, Mohammed Yaseen\r\n */\r\npublic class Display {\r\n ",
"end": 255,
"score": 0.9998798370361328,
"start": 243,
"tag": "NAME",
"value": "Justin Greco"
},
{
"context": "\n\r\n/**\r\n *\r\n * @author Andrew Clark, Justin Greco, Mohammed Yaseen\r\n */\r\npublic class Display {\r\n public void Dis",
"end": 272,
"score": 0.9998895525932312,
"start": 257,
"tag": "NAME",
"value": "Mohammed Yaseen"
}
] | null |
[] |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package puzzle;
/**
*
* @author <NAME>, <NAME>, <NAME>
*/
public class Display {
public void Display()
{
System.out.println("Display Created!");
}
final public static int SIZE = 5;
public void print(int mask) {
for (int i=0; i<SIZE; i++) {
for (int j=0; j<SIZE-1-i; j++) System.out.print(" ");
for (int j=0; j<=i; j++) {
if (on(mask, SIZE*i+j)) System.out.print("X ");
else System.out.print(". ");
}
System.out.println();
}
System.out.println();
}
public static boolean on(int mask, int bit) {
return (mask & (1<<bit)) != 0;
}
}
| 926 | 0.514256 | 0.506864 | 40 | 21.674999 | 22.666481 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.675 | false | false |
14
|
0f0dabacd1b40c3ce2523a97992ce5a5c5bc36f3
| 13,219,909,404,636 |
4ce0e81616d5b319089a07b6a844fb3823d0c2ff
|
/coe11-master/hougong/src/main/java/com/zhuye/hougong/view/RegeistActivity.java
|
48eb4ec8601115dbfb6f2b22b9303389a74463d8
|
[] |
no_license
|
hsdzqs1992/hougong
|
https://github.com/hsdzqs1992/hougong
|
ebaff9cbdef0a992478d8bb0780d51601f899c3d
|
5b2331fa78a9d9cdf2dc8c3b208c23b4d644c0db
|
refs/heads/master
| 2021-08-26T08:35:47.976000 | 2017-11-22T15:08:39 | 2017-11-22T15:08:39 | 111,694,815 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.zhuye.hougong.view;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.zhuye.hougong.R;
import com.zhuye.hougong.bean.Code;
import com.zhuye.hougong.contants.Contants;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class RegeistActivity extends AppCompatActivity {
@BindView(R.id.regeist_username_tv)
TextView regeistUsernameTv;
@BindView(R.id.regeist_username)
EditText regeistUsername;
@BindView(R.id.regeist_yanzhengma)
EditText regeistYanzhengma;
@BindView(R.id.login_sendcode)
Button loginSendcode;
@BindView(R.id.regeist_pass)
EditText regeistPass;
@BindView(R.id.regeist_repass)
EditText regeistRepass;
@BindView(R.id.login_login)
Button loginLogin;
@BindView(R.id.activity_regeist)
LinearLayout activityRegeist;
String phone;
String pass;
String repassword;
String regeistYanzhengma1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_regeist);
ButterKnife.bind(this);
}
@OnClick({R.id.login_sendcode, R.id.login_login})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.login_sendcode:
phone=regeistUsername.getText().toString().trim();
if(TextUtils.isEmpty(phone)){
Toast.makeText(RegeistActivity.this,"手机号不能为空",Toast.LENGTH_SHORT).show();
return;
}
OkGo.<String>post(Contants.GET_REGEIST_URL)
.params("mobile",phone).execute(new StringCallback() {
@Override
public void onSuccess(Response<String> response) {
Gson gson = new Gson();
Code code = gson.fromJson(response.body(), Code.class);
if(code.getCode()==200){
Toast.makeText(RegeistActivity.this,"获取验证码成功,为"+code.getData(),Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(RegeistActivity.this,"获取验证码失败",Toast.LENGTH_SHORT).show();
}
}
@Override
public void onError(Response<String> response) {
super.onError(response);
Toast.makeText(RegeistActivity.this,"获取验证码失败",Toast.LENGTH_SHORT).show();
}
});
break;
case R.id.login_login:
phone=regeistUsername.getText().toString().trim();
regeistYanzhengma1=regeistYanzhengma.getText().toString().trim();
pass=regeistPass.getText().toString().trim();
repassword=regeistRepass.getText().toString().trim();
if(TextUtils.isEmpty(phone)){
Toast.makeText(RegeistActivity.this,"手机号不能为空",Toast.LENGTH_SHORT).show();
return;
}
if(!pass.equals(repassword)){
Toast.makeText(RegeistActivity.this,"密码不一致",Toast.LENGTH_SHORT).show();
return;
}
OkGo.<String>post(Contants.REGEIST_URL).params("mobile",phone)
.params("password",pass)
.params("code",regeistYanzhengma1)
.execute(new StringCallback() {
@Override
public void onSuccess(Response<String> response) {
//JsonObject jsonObject = new JsonObject();
//JsonObject s = jsonObject.getAsJsonObject(response.body());
//s.get("Code");
Toast.makeText(RegeistActivity.this,"注册成功",Toast.LENGTH_SHORT).show();
startActivity(new Intent(RegeistActivity.this,LoginActivity.class));
// Gson gson = new Gson();
// Code code = gson.fromJson(response.body(), Code.class);
// if(code.getCode()==200){
// Toast.makeText(RegeistActivity.this,"注册成功",Toast.LENGTH_SHORT).show();
// startActivity(new Intent(RegeistActivity.this,LoginActivity.class));
// finish();
// }else {
// Toast.makeText(RegeistActivity.this,"获取验证码失败",Toast.LENGTH_SHORT).show();
// }
}
@Override
public void onError(Response<String> response) {
super.onError(response);
}
});
break;
}
}
}
|
UTF-8
|
Java
| 5,576 |
java
|
RegeistActivity.java
|
Java
|
[
{
"context": "phone)\n .params(\"password\",pass)\n .params(\"code\",regeistYa",
"end": 3840,
"score": 0.9741373062133789,
"start": 3836,
"tag": "PASSWORD",
"value": "pass"
}
] | null |
[] |
package com.zhuye.hougong.view;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.zhuye.hougong.R;
import com.zhuye.hougong.bean.Code;
import com.zhuye.hougong.contants.Contants;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class RegeistActivity extends AppCompatActivity {
@BindView(R.id.regeist_username_tv)
TextView regeistUsernameTv;
@BindView(R.id.regeist_username)
EditText regeistUsername;
@BindView(R.id.regeist_yanzhengma)
EditText regeistYanzhengma;
@BindView(R.id.login_sendcode)
Button loginSendcode;
@BindView(R.id.regeist_pass)
EditText regeistPass;
@BindView(R.id.regeist_repass)
EditText regeistRepass;
@BindView(R.id.login_login)
Button loginLogin;
@BindView(R.id.activity_regeist)
LinearLayout activityRegeist;
String phone;
String pass;
String repassword;
String regeistYanzhengma1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_regeist);
ButterKnife.bind(this);
}
@OnClick({R.id.login_sendcode, R.id.login_login})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.login_sendcode:
phone=regeistUsername.getText().toString().trim();
if(TextUtils.isEmpty(phone)){
Toast.makeText(RegeistActivity.this,"手机号不能为空",Toast.LENGTH_SHORT).show();
return;
}
OkGo.<String>post(Contants.GET_REGEIST_URL)
.params("mobile",phone).execute(new StringCallback() {
@Override
public void onSuccess(Response<String> response) {
Gson gson = new Gson();
Code code = gson.fromJson(response.body(), Code.class);
if(code.getCode()==200){
Toast.makeText(RegeistActivity.this,"获取验证码成功,为"+code.getData(),Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(RegeistActivity.this,"获取验证码失败",Toast.LENGTH_SHORT).show();
}
}
@Override
public void onError(Response<String> response) {
super.onError(response);
Toast.makeText(RegeistActivity.this,"获取验证码失败",Toast.LENGTH_SHORT).show();
}
});
break;
case R.id.login_login:
phone=regeistUsername.getText().toString().trim();
regeistYanzhengma1=regeistYanzhengma.getText().toString().trim();
pass=regeistPass.getText().toString().trim();
repassword=regeistRepass.getText().toString().trim();
if(TextUtils.isEmpty(phone)){
Toast.makeText(RegeistActivity.this,"手机号不能为空",Toast.LENGTH_SHORT).show();
return;
}
if(!pass.equals(repassword)){
Toast.makeText(RegeistActivity.this,"密码不一致",Toast.LENGTH_SHORT).show();
return;
}
OkGo.<String>post(Contants.REGEIST_URL).params("mobile",phone)
.params("password",<PASSWORD>)
.params("code",regeistYanzhengma1)
.execute(new StringCallback() {
@Override
public void onSuccess(Response<String> response) {
//JsonObject jsonObject = new JsonObject();
//JsonObject s = jsonObject.getAsJsonObject(response.body());
//s.get("Code");
Toast.makeText(RegeistActivity.this,"注册成功",Toast.LENGTH_SHORT).show();
startActivity(new Intent(RegeistActivity.this,LoginActivity.class));
// Gson gson = new Gson();
// Code code = gson.fromJson(response.body(), Code.class);
// if(code.getCode()==200){
// Toast.makeText(RegeistActivity.this,"注册成功",Toast.LENGTH_SHORT).show();
// startActivity(new Intent(RegeistActivity.this,LoginActivity.class));
// finish();
// }else {
// Toast.makeText(RegeistActivity.this,"获取验证码失败",Toast.LENGTH_SHORT).show();
// }
}
@Override
public void onError(Response<String> response) {
super.onError(response);
}
});
break;
}
}
}
| 5,582 | 0.53918 | 0.537349 | 145 | 36.668964 | 28.935375 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.662069 | false | false |
14
|
dba97c7ae812b9d4fe084bf965740a56741676c3
| 34,565,896,854,678 |
a8a602e72a3bbd4ab5801a1818ab1a664bfc8486
|
/app/src/main/java/com/example/delivery/activities/LoginActivity.java
|
1cffa6bd960678127f0f1da86bad679f48ee2186
|
[] |
no_license
|
realwhizzylong/Delivery
|
https://github.com/realwhizzylong/Delivery
|
0a78c8d9994f6e04cc36b59fe5f69950d2b7aea7
|
758337f6f109c5947dc389bcb3d0e85ee32e0e7c
|
refs/heads/master
| 2023-04-25T15:05:42.197000 | 2021-05-14T11:00:09 | 2021-05-14T11:00:09 | 361,509,415 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.delivery.activities;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.example.delivery.R;
import com.example.delivery.helpers.RealmHelper;
import com.example.delivery.helpers.UserHelper;
import com.example.delivery.models.UserModel;
import com.example.delivery.utils.UserInforSPUtils;
import com.example.delivery.utils.UserUtil;
import com.example.delivery.views.InputView;
public class LoginActivity extends BaseActivity {
private InputView inputEmail, inputPassword;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
initView();
}
private void initView() {
initNavBar(false, "Log In", false);
inputEmail = fd(R.id.login_email);
inputPassword = fd(R.id.login_password);
}
public void onLoginClick(View view) {
String email = inputEmail.getInputString();
String password = inputPassword.getInputString();
if (!UserUtil.login(this, email, password)) {
return;
}
RealmHelper realmHelper2 = new RealmHelper();
UserModel userModel = realmHelper2.getUserByEmail(email);
UserInforSPUtils.saveEmail(userModel.getEmail());
UserInforSPUtils.saveName(userModel.getUserName());
UserInforSPUtils.savePhone(userModel.getPhone());
UserInforSPUtils.savePic(userModel.getProfilePicture());
realmHelper2.close();
if (UserUtil.isManager(email)) {
Intent intent1 = new Intent(this, ManagerActivity.class);
startActivity(intent1);
} else if(UserUtil.isAdmin(email)){
Intent intent2 = new Intent(this, AdminActivity.class);
startActivity(intent2);
}else {
Intent intent3 = new Intent(this, MainActivity.class);
startActivity(intent3);
}
finish();
}
public void onRegisterManagerClick(View view) {
startActivity(new Intent(this, RegisterManagerActivity.class));
}
}
|
UTF-8
|
Java
| 2,206 |
java
|
LoginActivity.java
|
Java
|
[] | null |
[] |
package com.example.delivery.activities;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.example.delivery.R;
import com.example.delivery.helpers.RealmHelper;
import com.example.delivery.helpers.UserHelper;
import com.example.delivery.models.UserModel;
import com.example.delivery.utils.UserInforSPUtils;
import com.example.delivery.utils.UserUtil;
import com.example.delivery.views.InputView;
public class LoginActivity extends BaseActivity {
private InputView inputEmail, inputPassword;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
initView();
}
private void initView() {
initNavBar(false, "Log In", false);
inputEmail = fd(R.id.login_email);
inputPassword = fd(R.id.login_password);
}
public void onLoginClick(View view) {
String email = inputEmail.getInputString();
String password = inputPassword.getInputString();
if (!UserUtil.login(this, email, password)) {
return;
}
RealmHelper realmHelper2 = new RealmHelper();
UserModel userModel = realmHelper2.getUserByEmail(email);
UserInforSPUtils.saveEmail(userModel.getEmail());
UserInforSPUtils.saveName(userModel.getUserName());
UserInforSPUtils.savePhone(userModel.getPhone());
UserInforSPUtils.savePic(userModel.getProfilePicture());
realmHelper2.close();
if (UserUtil.isManager(email)) {
Intent intent1 = new Intent(this, ManagerActivity.class);
startActivity(intent1);
} else if(UserUtil.isAdmin(email)){
Intent intent2 = new Intent(this, AdminActivity.class);
startActivity(intent2);
}else {
Intent intent3 = new Intent(this, MainActivity.class);
startActivity(intent3);
}
finish();
}
public void onRegisterManagerClick(View view) {
startActivity(new Intent(this, RegisterManagerActivity.class));
}
}
| 2,206 | 0.68903 | 0.68495 | 70 | 30.528572 | 22.947594 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.671429 | false | false |
14
|
281b48095fa1375eb82baa95fd78ee37b4ca0fa9
| 8,512,625,190,812 |
e8626f9f64a8bb90008015b06856d3da16eeecad
|
/server/src/test/java/org/apache/druid/server/coordinator/simulate/CoordinatorSimulationBuilder.java
|
4556e203156a303093d9ef05766237cd55938096
|
[
"EPL-1.0",
"Classpath-exception-2.0",
"ISC",
"GPL-2.0-only",
"BSD-3-Clause",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-generic-cla",
"0BSD",
"LicenseRef-scancode-sun-no-high-risk-activities",
"LicenseRef-scancode-free-unknown",
"JSON",
"LicenseRef-scancode-unicode",
"CC-BY-SA-3.0",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-westhawk",
"CDDL-1.1",
"BSD-2-Clause",
"EPL-2.0",
"CDDL-1.0",
"GCC-exception-3.1",
"MPL-2.0",
"CC-PDDC",
"MIT",
"LicenseRef-scancode-unicode-icu-58",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
apache/druid
|
https://github.com/apache/druid
|
bb1b20be5104882e4eeb045d109b559f396086c0
|
d4e972e1e4b798d7e057e910deea4d192fe57952
|
refs/heads/master
| 2023-09-05T02:41:03.009000 | 2023-09-04T07:48:55 | 2023-09-04T07:48:55 | 6,358,188 | 4,364 | 1,629 |
Apache-2.0
| false | 2023-09-14T21:04:46 | 2012-10-23T19:08:07 | 2023-09-14T21:04:40 | 2023-09-14T21:04:46 | 324,885 | 12,839 | 3,591 | 1,383 |
Java
| false | false |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.druid.server.coordinator.simulate;
import com.fasterxml.jackson.databind.InjectableValues;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Preconditions;
import org.apache.druid.audit.AuditInfo;
import org.apache.druid.client.DruidServer;
import org.apache.druid.common.config.JacksonConfigManager;
import org.apache.druid.curator.discovery.ServiceAnnouncer;
import org.apache.druid.jackson.DefaultObjectMapper;
import org.apache.druid.java.util.common.IAE;
import org.apache.druid.java.util.common.ISE;
import org.apache.druid.java.util.common.concurrent.DirectExecutorService;
import org.apache.druid.java.util.common.concurrent.ScheduledExecutorFactory;
import org.apache.druid.java.util.common.lifecycle.Lifecycle;
import org.apache.druid.java.util.emitter.EmittingLogger;
import org.apache.druid.java.util.http.client.HttpClient;
import org.apache.druid.java.util.metrics.MetricsVerifier;
import org.apache.druid.java.util.metrics.StubServiceEmitter;
import org.apache.druid.server.coordinator.CoordinatorCompactionConfig;
import org.apache.druid.server.coordinator.CoordinatorDynamicConfig;
import org.apache.druid.server.coordinator.DruidCoordinator;
import org.apache.druid.server.coordinator.DruidCoordinatorConfig;
import org.apache.druid.server.coordinator.TestDruidCoordinatorConfig;
import org.apache.druid.server.coordinator.balancer.BalancerStrategyFactory;
import org.apache.druid.server.coordinator.balancer.CachingCostBalancerStrategyConfig;
import org.apache.druid.server.coordinator.balancer.CachingCostBalancerStrategyFactory;
import org.apache.druid.server.coordinator.balancer.CostBalancerStrategyFactory;
import org.apache.druid.server.coordinator.balancer.DiskNormalizedCostBalancerStrategyFactory;
import org.apache.druid.server.coordinator.balancer.RandomBalancerStrategyFactory;
import org.apache.druid.server.coordinator.compact.CompactionSegmentSearchPolicy;
import org.apache.druid.server.coordinator.compact.NewestSegmentFirstPolicy;
import org.apache.druid.server.coordinator.duty.CoordinatorCustomDutyGroups;
import org.apache.druid.server.coordinator.loading.LoadQueueTaskMaster;
import org.apache.druid.server.coordinator.loading.SegmentLoadQueueManager;
import org.apache.druid.server.coordinator.rules.Rule;
import org.apache.druid.server.lookup.cache.LookupCoordinatorManager;
import org.apache.druid.timeline.DataSegment;
import org.easymock.EasyMock;
import org.joda.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
/**
* Builder for {@link CoordinatorSimulation}.
*/
public class CoordinatorSimulationBuilder
{
private static final ObjectMapper OBJECT_MAPPER = new DefaultObjectMapper()
.setInjectableValues(
new InjectableValues.Std().addValue(
DataSegment.PruneSpecsHolder.class,
DataSegment.PruneSpecsHolder.DEFAULT
)
);
private static final CompactionSegmentSearchPolicy COMPACTION_SEGMENT_SEARCH_POLICY =
new NewestSegmentFirstPolicy(OBJECT_MAPPER);
private String balancerStrategy;
private CoordinatorDynamicConfig dynamicConfig = CoordinatorDynamicConfig.builder().build();
private List<DruidServer> servers;
private List<DataSegment> segments;
private final Map<String, List<Rule>> datasourceRules = new HashMap<>();
private boolean loadImmediately = false;
private boolean autoSyncInventory = true;
/**
* Specifies the balancer strategy to be used.
* <p>
* Default: "cost" ({@link CostBalancerStrategyFactory})
*/
public CoordinatorSimulationBuilder withBalancer(String balancerStrategy)
{
this.balancerStrategy = balancerStrategy;
return this;
}
public CoordinatorSimulationBuilder withServers(List<DruidServer> servers)
{
this.servers = servers;
return this;
}
public CoordinatorSimulationBuilder withServers(DruidServer... servers)
{
return withServers(Arrays.asList(servers));
}
public CoordinatorSimulationBuilder withSegments(List<DataSegment> segments)
{
this.segments = segments;
return this;
}
public CoordinatorSimulationBuilder withRules(String datasource, Rule... rules)
{
this.datasourceRules.put(datasource, Arrays.asList(rules));
return this;
}
/**
* Specifies whether segments should be loaded as soon as they are queued.
* <p>
* Default: false
*/
public CoordinatorSimulationBuilder withImmediateSegmentLoading(boolean loadImmediately)
{
this.loadImmediately = loadImmediately;
return this;
}
/**
* Specifies whether the inventory view maintained by the coordinator
* should be auto-synced as soon as any change is made to the cluster.
* <p>
* Default: true
*/
public CoordinatorSimulationBuilder withAutoInventorySync(boolean autoSync)
{
this.autoSyncInventory = autoSync;
return this;
}
/**
* Specifies the CoordinatorDynamicConfig to be used in the simulation.
* <p>
* Default values: as specified in {@link CoordinatorDynamicConfig.Builder}.
* <p>
* Tests that verify balancing behaviour use batched segment sampling.
* Otherwise, the segment sampling is random and can produce repeated values
* leading to flakiness in the tests. The simulation sets this field to true by
* default.
*/
public CoordinatorSimulationBuilder withDynamicConfig(CoordinatorDynamicConfig dynamicConfig)
{
this.dynamicConfig = dynamicConfig;
return this;
}
public CoordinatorSimulation build()
{
Preconditions.checkArgument(
servers != null && !servers.isEmpty(),
"Cannot run simulation for an empty cluster"
);
// Prepare the environment
final TestServerInventoryView serverInventoryView = new TestServerInventoryView();
servers.forEach(serverInventoryView::addServer);
final Environment env = new Environment(
serverInventoryView,
dynamicConfig,
loadImmediately,
autoSyncInventory
);
if (segments != null) {
segments.forEach(env.segmentManager::addSegment);
}
datasourceRules.forEach(
(datasource, rules) ->
env.ruleManager.overrideRule(datasource, rules, null)
);
// Build the coordinator
final DruidCoordinator coordinator = new DruidCoordinator(
env.coordinatorConfig,
env.jacksonConfigManager,
env.segmentManager,
env.coordinatorInventoryView,
env.ruleManager,
env.serviceEmitter,
env.executorFactory,
null,
env.loadQueueTaskMaster,
env.loadQueueManager,
new ServiceAnnouncer.Noop(),
null,
Collections.emptySet(),
null,
new CoordinatorCustomDutyGroups(Collections.emptySet()),
createBalancerStrategy(env),
env.lookupCoordinatorManager,
env.leaderSelector,
COMPACTION_SEGMENT_SEARCH_POLICY
);
return new SimulationImpl(coordinator, env);
}
private BalancerStrategyFactory createBalancerStrategy(Environment env)
{
if (balancerStrategy == null) {
return new CostBalancerStrategyFactory();
}
switch (balancerStrategy) {
case "cost":
return new CostBalancerStrategyFactory();
case "cachingCost":
return buildCachingCostBalancerStrategy(env);
case "diskNormalized":
return new DiskNormalizedCostBalancerStrategyFactory();
case "random":
return new RandomBalancerStrategyFactory();
default:
throw new IAE("Unknown balancer stratgy: " + balancerStrategy);
}
}
private BalancerStrategyFactory buildCachingCostBalancerStrategy(Environment env)
{
try {
return new CachingCostBalancerStrategyFactory(
env.coordinatorInventoryView,
env.lifecycle,
new CachingCostBalancerStrategyConfig()
);
}
catch (Exception e) {
throw new ISE(e, "Error building balancer strategy");
}
}
/**
* Implementation of {@link CoordinatorSimulation}.
*/
private static class SimulationImpl implements CoordinatorSimulation,
CoordinatorSimulation.CoordinatorState, CoordinatorSimulation.ClusterState
{
private final AtomicBoolean running = new AtomicBoolean(false);
private final Environment env;
private final DruidCoordinator coordinator;
private SimulationImpl(DruidCoordinator coordinator, Environment env)
{
this.env = env;
this.coordinator = coordinator;
}
@Override
public void start()
{
if (!running.compareAndSet(false, true)) {
throw new ISE("Simulation is already running");
}
try {
env.setUp();
coordinator.start();
env.executorFactory.findExecutors();
}
catch (Exception e) {
throw new ISE(e, "Exception while running simulation");
}
}
@Override
public void stop()
{
coordinator.stop();
env.leaderSelector.stopBeingLeader();
env.tearDown();
}
@Override
public CoordinatorState coordinator()
{
return this;
}
@Override
public ClusterState cluster()
{
return this;
}
@Override
public void runCoordinatorCycle()
{
verifySimulationRunning();
env.serviceEmitter.flush();
// Invoke historical duties
env.executorFactory.historicalDutiesRunner.finishNextPendingTasks(1);
}
@Override
public void syncInventoryView()
{
verifySimulationRunning();
Preconditions.checkState(
!env.autoSyncInventory,
"Cannot invoke syncInventoryView as simulation is running in auto-sync mode."
);
env.coordinatorInventoryView.sync(env.inventory);
}
@Override
public void setDynamicConfig(CoordinatorDynamicConfig dynamicConfig)
{
env.setDynamicConfig(dynamicConfig);
}
@Override
public void setRetentionRules(String datasource, Rule... rules)
{
env.ruleManager.overrideRule(
datasource,
Arrays.asList(rules),
new AuditInfo("sim", "sim", "localhost")
);
}
@Override
public DruidServer getInventoryView(String serverName)
{
return env.coordinatorInventoryView.getInventoryValue(serverName);
}
@Override
public void loadQueuedSegments()
{
verifySimulationRunning();
Preconditions.checkState(
!env.loadImmediately,
"Cannot invoke loadQueuedSegments as simulation is running in immediate loading mode."
);
final BlockingExecutorService loadQueueExecutor = env.executorFactory.loadQueueExecutor;
while (loadQueueExecutor.hasPendingTasks()) {
// Drain all the items from the load queue executor
// This sends at most 1 load/drop request to each server
loadQueueExecutor.finishAllPendingTasks();
// Load all the queued segments, handle their responses and execute callbacks
int loadedSegments = env.executorFactory.historicalLoader.finishAllPendingTasks();
loadQueueExecutor.finishNextPendingTasks(loadedSegments);
env.executorFactory.loadCallbackExecutor.finishAllPendingTasks();
}
}
@Override
public void removeServer(DruidServer server)
{
env.inventory.removeServer(server);
}
@Override
public void addServer(DruidServer server)
{
env.inventory.addServer(server);
}
@Override
public void addSegments(List<DataSegment> segments)
{
if (segments != null) {
segments.forEach(env.segmentManager::addSegment);
}
}
private void verifySimulationRunning()
{
if (!running.get()) {
throw new ISE("Simulation hasn't been started yet.");
}
}
@Override
public double getLoadPercentage(String datasource)
{
return coordinator.getDatasourceToLoadStatus().get(datasource);
}
@Override
public MetricsVerifier getMetricsVerifier()
{
return env.serviceEmitter;
}
}
/**
* Environment for a coordinator simulation.
*/
private static class Environment
{
private final Lifecycle lifecycle = new Lifecycle("coord-sim");
private final StubServiceEmitter serviceEmitter
= new StubServiceEmitter("coordinator", "coordinator");
private final AtomicReference<CoordinatorDynamicConfig> dynamicConfig
= new AtomicReference<>();
private final TestDruidLeaderSelector leaderSelector
= new TestDruidLeaderSelector();
private final ExecutorFactory executorFactory;
private final TestSegmentsMetadataManager segmentManager = new TestSegmentsMetadataManager();
private final TestMetadataRuleManager ruleManager = new TestMetadataRuleManager();
private final LoadQueueTaskMaster loadQueueTaskMaster;
private final SegmentLoadQueueManager loadQueueManager;
/**
* Represents the current inventory of all servers (typically historicals)
* actually present in the cluster.
*/
private final TestServerInventoryView inventory;
/**
* Represents the view of the cluster inventory as seen by the coordinator.
* When {@code autoSyncInventory=true}, this is the same as {@link #inventory}.
*/
private final TestServerInventoryView coordinatorInventoryView;
private final JacksonConfigManager jacksonConfigManager;
private final LookupCoordinatorManager lookupCoordinatorManager;
private final DruidCoordinatorConfig coordinatorConfig;
private final boolean loadImmediately;
private final boolean autoSyncInventory;
private final List<Object> mocks = new ArrayList<>();
private Environment(
TestServerInventoryView clusterInventory,
CoordinatorDynamicConfig dynamicConfig,
boolean loadImmediately,
boolean autoSyncInventory
)
{
this.inventory = clusterInventory;
this.loadImmediately = loadImmediately;
this.autoSyncInventory = autoSyncInventory;
this.coordinatorConfig = new TestDruidCoordinatorConfig.Builder()
.withCoordinatorStartDelay(new Duration(1L))
.withCoordinatorPeriod(Duration.standardMinutes(1))
.withCoordinatorKillPeriod(Duration.millis(100))
.withLoadQueuePeonType("http")
.withCoordinatorKillIgnoreDurationToRetain(false)
.build();
this.executorFactory = new ExecutorFactory(loadImmediately);
this.coordinatorInventoryView = autoSyncInventory
? clusterInventory
: new TestServerInventoryView();
HttpClient httpClient = new TestSegmentLoadingHttpClient(
OBJECT_MAPPER,
clusterInventory::getChangeHandlerForHost,
executorFactory.create(1, ExecutorFactory.HISTORICAL_LOADER)
);
this.loadQueueTaskMaster = new LoadQueueTaskMaster(
null,
OBJECT_MAPPER,
executorFactory.create(1, ExecutorFactory.LOAD_QUEUE_EXECUTOR),
executorFactory.create(1, ExecutorFactory.LOAD_CALLBACK_EXECUTOR),
coordinatorConfig,
httpClient,
null
);
this.loadQueueManager =
new SegmentLoadQueueManager(coordinatorInventoryView, loadQueueTaskMaster);
this.jacksonConfigManager = mockConfigManager();
setDynamicConfig(dynamicConfig);
this.lookupCoordinatorManager = EasyMock.createNiceMock(LookupCoordinatorManager.class);
mocks.add(jacksonConfigManager);
mocks.add(lookupCoordinatorManager);
}
private void setUp() throws Exception
{
EmittingLogger.registerEmitter(serviceEmitter);
inventory.setUp();
coordinatorInventoryView.setUp();
lifecycle.start();
leaderSelector.becomeLeader();
EasyMock.replay(mocks.toArray());
}
private void tearDown()
{
EasyMock.verify(mocks.toArray());
executorFactory.tearDown();
lifecycle.stop();
}
private void setDynamicConfig(CoordinatorDynamicConfig dynamicConfig)
{
this.dynamicConfig.set(dynamicConfig);
}
private JacksonConfigManager mockConfigManager()
{
final JacksonConfigManager jacksonConfigManager
= EasyMock.createMock(JacksonConfigManager.class);
EasyMock.expect(
jacksonConfigManager.watch(
EasyMock.eq(CoordinatorDynamicConfig.CONFIG_KEY),
EasyMock.eq(CoordinatorDynamicConfig.class),
EasyMock.anyObject()
)
).andReturn(dynamicConfig).anyTimes();
EasyMock.expect(
jacksonConfigManager.watch(
EasyMock.eq(CoordinatorCompactionConfig.CONFIG_KEY),
EasyMock.eq(CoordinatorCompactionConfig.class),
EasyMock.anyObject()
)
).andReturn(new AtomicReference<>(CoordinatorCompactionConfig.empty())).anyTimes();
return jacksonConfigManager;
}
}
/**
* Implementation of {@link ScheduledExecutorFactory} used to create and keep
* a handle on the various executors used inside the coordinator.
*/
private static class ExecutorFactory implements ScheduledExecutorFactory
{
static final String HISTORICAL_LOADER = "historical-loader-%d";
static final String LOAD_QUEUE_EXECUTOR = "load-queue-%d";
static final String LOAD_CALLBACK_EXECUTOR = "load-callback-%d";
static final String COORDINATOR_RUNNER = "Coordinator-Exec-HistoricalManagementDuties-%d";
private final Map<String, BlockingExecutorService> blockingExecutors = new HashMap<>();
private final boolean directExecution;
private BlockingExecutorService historicalLoader;
private BlockingExecutorService loadQueueExecutor;
private BlockingExecutorService loadCallbackExecutor;
private BlockingExecutorService historicalDutiesRunner;
private ExecutorFactory(boolean directExecution)
{
this.directExecution = directExecution;
}
@Override
public ScheduledExecutorService create(int corePoolSize, String nameFormat)
{
boolean isCoordinatorRunner = COORDINATOR_RUNNER.equals(nameFormat);
// Coordinator running executor must always be blocked
final ExecutorService executorService =
(directExecution && !isCoordinatorRunner)
? new DirectExecutorService()
: blockingExecutors.computeIfAbsent(nameFormat, BlockingExecutorService::new);
return new WrappingScheduledExecutorService(nameFormat, executorService, !isCoordinatorRunner);
}
private BlockingExecutorService findExecutor(String nameFormat)
{
return blockingExecutors.get(nameFormat);
}
private void findExecutors()
{
historicalDutiesRunner = findExecutor(COORDINATOR_RUNNER);
historicalLoader = findExecutor(HISTORICAL_LOADER);
loadQueueExecutor = findExecutor(LOAD_QUEUE_EXECUTOR);
loadCallbackExecutor = findExecutor(LOAD_CALLBACK_EXECUTOR);
}
private void tearDown()
{
blockingExecutors.values().forEach(BlockingExecutorService::shutdown);
}
}
}
|
UTF-8
|
Java
| 20,145 |
java
|
CoordinatorSimulationBuilder.java
|
Java
|
[] | null |
[] |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.druid.server.coordinator.simulate;
import com.fasterxml.jackson.databind.InjectableValues;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Preconditions;
import org.apache.druid.audit.AuditInfo;
import org.apache.druid.client.DruidServer;
import org.apache.druid.common.config.JacksonConfigManager;
import org.apache.druid.curator.discovery.ServiceAnnouncer;
import org.apache.druid.jackson.DefaultObjectMapper;
import org.apache.druid.java.util.common.IAE;
import org.apache.druid.java.util.common.ISE;
import org.apache.druid.java.util.common.concurrent.DirectExecutorService;
import org.apache.druid.java.util.common.concurrent.ScheduledExecutorFactory;
import org.apache.druid.java.util.common.lifecycle.Lifecycle;
import org.apache.druid.java.util.emitter.EmittingLogger;
import org.apache.druid.java.util.http.client.HttpClient;
import org.apache.druid.java.util.metrics.MetricsVerifier;
import org.apache.druid.java.util.metrics.StubServiceEmitter;
import org.apache.druid.server.coordinator.CoordinatorCompactionConfig;
import org.apache.druid.server.coordinator.CoordinatorDynamicConfig;
import org.apache.druid.server.coordinator.DruidCoordinator;
import org.apache.druid.server.coordinator.DruidCoordinatorConfig;
import org.apache.druid.server.coordinator.TestDruidCoordinatorConfig;
import org.apache.druid.server.coordinator.balancer.BalancerStrategyFactory;
import org.apache.druid.server.coordinator.balancer.CachingCostBalancerStrategyConfig;
import org.apache.druid.server.coordinator.balancer.CachingCostBalancerStrategyFactory;
import org.apache.druid.server.coordinator.balancer.CostBalancerStrategyFactory;
import org.apache.druid.server.coordinator.balancer.DiskNormalizedCostBalancerStrategyFactory;
import org.apache.druid.server.coordinator.balancer.RandomBalancerStrategyFactory;
import org.apache.druid.server.coordinator.compact.CompactionSegmentSearchPolicy;
import org.apache.druid.server.coordinator.compact.NewestSegmentFirstPolicy;
import org.apache.druid.server.coordinator.duty.CoordinatorCustomDutyGroups;
import org.apache.druid.server.coordinator.loading.LoadQueueTaskMaster;
import org.apache.druid.server.coordinator.loading.SegmentLoadQueueManager;
import org.apache.druid.server.coordinator.rules.Rule;
import org.apache.druid.server.lookup.cache.LookupCoordinatorManager;
import org.apache.druid.timeline.DataSegment;
import org.easymock.EasyMock;
import org.joda.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
/**
* Builder for {@link CoordinatorSimulation}.
*/
public class CoordinatorSimulationBuilder
{
private static final ObjectMapper OBJECT_MAPPER = new DefaultObjectMapper()
.setInjectableValues(
new InjectableValues.Std().addValue(
DataSegment.PruneSpecsHolder.class,
DataSegment.PruneSpecsHolder.DEFAULT
)
);
private static final CompactionSegmentSearchPolicy COMPACTION_SEGMENT_SEARCH_POLICY =
new NewestSegmentFirstPolicy(OBJECT_MAPPER);
private String balancerStrategy;
private CoordinatorDynamicConfig dynamicConfig = CoordinatorDynamicConfig.builder().build();
private List<DruidServer> servers;
private List<DataSegment> segments;
private final Map<String, List<Rule>> datasourceRules = new HashMap<>();
private boolean loadImmediately = false;
private boolean autoSyncInventory = true;
/**
* Specifies the balancer strategy to be used.
* <p>
* Default: "cost" ({@link CostBalancerStrategyFactory})
*/
public CoordinatorSimulationBuilder withBalancer(String balancerStrategy)
{
this.balancerStrategy = balancerStrategy;
return this;
}
public CoordinatorSimulationBuilder withServers(List<DruidServer> servers)
{
this.servers = servers;
return this;
}
public CoordinatorSimulationBuilder withServers(DruidServer... servers)
{
return withServers(Arrays.asList(servers));
}
public CoordinatorSimulationBuilder withSegments(List<DataSegment> segments)
{
this.segments = segments;
return this;
}
public CoordinatorSimulationBuilder withRules(String datasource, Rule... rules)
{
this.datasourceRules.put(datasource, Arrays.asList(rules));
return this;
}
/**
* Specifies whether segments should be loaded as soon as they are queued.
* <p>
* Default: false
*/
public CoordinatorSimulationBuilder withImmediateSegmentLoading(boolean loadImmediately)
{
this.loadImmediately = loadImmediately;
return this;
}
/**
* Specifies whether the inventory view maintained by the coordinator
* should be auto-synced as soon as any change is made to the cluster.
* <p>
* Default: true
*/
public CoordinatorSimulationBuilder withAutoInventorySync(boolean autoSync)
{
this.autoSyncInventory = autoSync;
return this;
}
/**
* Specifies the CoordinatorDynamicConfig to be used in the simulation.
* <p>
* Default values: as specified in {@link CoordinatorDynamicConfig.Builder}.
* <p>
* Tests that verify balancing behaviour use batched segment sampling.
* Otherwise, the segment sampling is random and can produce repeated values
* leading to flakiness in the tests. The simulation sets this field to true by
* default.
*/
public CoordinatorSimulationBuilder withDynamicConfig(CoordinatorDynamicConfig dynamicConfig)
{
this.dynamicConfig = dynamicConfig;
return this;
}
public CoordinatorSimulation build()
{
Preconditions.checkArgument(
servers != null && !servers.isEmpty(),
"Cannot run simulation for an empty cluster"
);
// Prepare the environment
final TestServerInventoryView serverInventoryView = new TestServerInventoryView();
servers.forEach(serverInventoryView::addServer);
final Environment env = new Environment(
serverInventoryView,
dynamicConfig,
loadImmediately,
autoSyncInventory
);
if (segments != null) {
segments.forEach(env.segmentManager::addSegment);
}
datasourceRules.forEach(
(datasource, rules) ->
env.ruleManager.overrideRule(datasource, rules, null)
);
// Build the coordinator
final DruidCoordinator coordinator = new DruidCoordinator(
env.coordinatorConfig,
env.jacksonConfigManager,
env.segmentManager,
env.coordinatorInventoryView,
env.ruleManager,
env.serviceEmitter,
env.executorFactory,
null,
env.loadQueueTaskMaster,
env.loadQueueManager,
new ServiceAnnouncer.Noop(),
null,
Collections.emptySet(),
null,
new CoordinatorCustomDutyGroups(Collections.emptySet()),
createBalancerStrategy(env),
env.lookupCoordinatorManager,
env.leaderSelector,
COMPACTION_SEGMENT_SEARCH_POLICY
);
return new SimulationImpl(coordinator, env);
}
private BalancerStrategyFactory createBalancerStrategy(Environment env)
{
if (balancerStrategy == null) {
return new CostBalancerStrategyFactory();
}
switch (balancerStrategy) {
case "cost":
return new CostBalancerStrategyFactory();
case "cachingCost":
return buildCachingCostBalancerStrategy(env);
case "diskNormalized":
return new DiskNormalizedCostBalancerStrategyFactory();
case "random":
return new RandomBalancerStrategyFactory();
default:
throw new IAE("Unknown balancer stratgy: " + balancerStrategy);
}
}
private BalancerStrategyFactory buildCachingCostBalancerStrategy(Environment env)
{
try {
return new CachingCostBalancerStrategyFactory(
env.coordinatorInventoryView,
env.lifecycle,
new CachingCostBalancerStrategyConfig()
);
}
catch (Exception e) {
throw new ISE(e, "Error building balancer strategy");
}
}
/**
* Implementation of {@link CoordinatorSimulation}.
*/
private static class SimulationImpl implements CoordinatorSimulation,
CoordinatorSimulation.CoordinatorState, CoordinatorSimulation.ClusterState
{
private final AtomicBoolean running = new AtomicBoolean(false);
private final Environment env;
private final DruidCoordinator coordinator;
private SimulationImpl(DruidCoordinator coordinator, Environment env)
{
this.env = env;
this.coordinator = coordinator;
}
@Override
public void start()
{
if (!running.compareAndSet(false, true)) {
throw new ISE("Simulation is already running");
}
try {
env.setUp();
coordinator.start();
env.executorFactory.findExecutors();
}
catch (Exception e) {
throw new ISE(e, "Exception while running simulation");
}
}
@Override
public void stop()
{
coordinator.stop();
env.leaderSelector.stopBeingLeader();
env.tearDown();
}
@Override
public CoordinatorState coordinator()
{
return this;
}
@Override
public ClusterState cluster()
{
return this;
}
@Override
public void runCoordinatorCycle()
{
verifySimulationRunning();
env.serviceEmitter.flush();
// Invoke historical duties
env.executorFactory.historicalDutiesRunner.finishNextPendingTasks(1);
}
@Override
public void syncInventoryView()
{
verifySimulationRunning();
Preconditions.checkState(
!env.autoSyncInventory,
"Cannot invoke syncInventoryView as simulation is running in auto-sync mode."
);
env.coordinatorInventoryView.sync(env.inventory);
}
@Override
public void setDynamicConfig(CoordinatorDynamicConfig dynamicConfig)
{
env.setDynamicConfig(dynamicConfig);
}
@Override
public void setRetentionRules(String datasource, Rule... rules)
{
env.ruleManager.overrideRule(
datasource,
Arrays.asList(rules),
new AuditInfo("sim", "sim", "localhost")
);
}
@Override
public DruidServer getInventoryView(String serverName)
{
return env.coordinatorInventoryView.getInventoryValue(serverName);
}
@Override
public void loadQueuedSegments()
{
verifySimulationRunning();
Preconditions.checkState(
!env.loadImmediately,
"Cannot invoke loadQueuedSegments as simulation is running in immediate loading mode."
);
final BlockingExecutorService loadQueueExecutor = env.executorFactory.loadQueueExecutor;
while (loadQueueExecutor.hasPendingTasks()) {
// Drain all the items from the load queue executor
// This sends at most 1 load/drop request to each server
loadQueueExecutor.finishAllPendingTasks();
// Load all the queued segments, handle their responses and execute callbacks
int loadedSegments = env.executorFactory.historicalLoader.finishAllPendingTasks();
loadQueueExecutor.finishNextPendingTasks(loadedSegments);
env.executorFactory.loadCallbackExecutor.finishAllPendingTasks();
}
}
@Override
public void removeServer(DruidServer server)
{
env.inventory.removeServer(server);
}
@Override
public void addServer(DruidServer server)
{
env.inventory.addServer(server);
}
@Override
public void addSegments(List<DataSegment> segments)
{
if (segments != null) {
segments.forEach(env.segmentManager::addSegment);
}
}
private void verifySimulationRunning()
{
if (!running.get()) {
throw new ISE("Simulation hasn't been started yet.");
}
}
@Override
public double getLoadPercentage(String datasource)
{
return coordinator.getDatasourceToLoadStatus().get(datasource);
}
@Override
public MetricsVerifier getMetricsVerifier()
{
return env.serviceEmitter;
}
}
/**
* Environment for a coordinator simulation.
*/
private static class Environment
{
private final Lifecycle lifecycle = new Lifecycle("coord-sim");
private final StubServiceEmitter serviceEmitter
= new StubServiceEmitter("coordinator", "coordinator");
private final AtomicReference<CoordinatorDynamicConfig> dynamicConfig
= new AtomicReference<>();
private final TestDruidLeaderSelector leaderSelector
= new TestDruidLeaderSelector();
private final ExecutorFactory executorFactory;
private final TestSegmentsMetadataManager segmentManager = new TestSegmentsMetadataManager();
private final TestMetadataRuleManager ruleManager = new TestMetadataRuleManager();
private final LoadQueueTaskMaster loadQueueTaskMaster;
private final SegmentLoadQueueManager loadQueueManager;
/**
* Represents the current inventory of all servers (typically historicals)
* actually present in the cluster.
*/
private final TestServerInventoryView inventory;
/**
* Represents the view of the cluster inventory as seen by the coordinator.
* When {@code autoSyncInventory=true}, this is the same as {@link #inventory}.
*/
private final TestServerInventoryView coordinatorInventoryView;
private final JacksonConfigManager jacksonConfigManager;
private final LookupCoordinatorManager lookupCoordinatorManager;
private final DruidCoordinatorConfig coordinatorConfig;
private final boolean loadImmediately;
private final boolean autoSyncInventory;
private final List<Object> mocks = new ArrayList<>();
private Environment(
TestServerInventoryView clusterInventory,
CoordinatorDynamicConfig dynamicConfig,
boolean loadImmediately,
boolean autoSyncInventory
)
{
this.inventory = clusterInventory;
this.loadImmediately = loadImmediately;
this.autoSyncInventory = autoSyncInventory;
this.coordinatorConfig = new TestDruidCoordinatorConfig.Builder()
.withCoordinatorStartDelay(new Duration(1L))
.withCoordinatorPeriod(Duration.standardMinutes(1))
.withCoordinatorKillPeriod(Duration.millis(100))
.withLoadQueuePeonType("http")
.withCoordinatorKillIgnoreDurationToRetain(false)
.build();
this.executorFactory = new ExecutorFactory(loadImmediately);
this.coordinatorInventoryView = autoSyncInventory
? clusterInventory
: new TestServerInventoryView();
HttpClient httpClient = new TestSegmentLoadingHttpClient(
OBJECT_MAPPER,
clusterInventory::getChangeHandlerForHost,
executorFactory.create(1, ExecutorFactory.HISTORICAL_LOADER)
);
this.loadQueueTaskMaster = new LoadQueueTaskMaster(
null,
OBJECT_MAPPER,
executorFactory.create(1, ExecutorFactory.LOAD_QUEUE_EXECUTOR),
executorFactory.create(1, ExecutorFactory.LOAD_CALLBACK_EXECUTOR),
coordinatorConfig,
httpClient,
null
);
this.loadQueueManager =
new SegmentLoadQueueManager(coordinatorInventoryView, loadQueueTaskMaster);
this.jacksonConfigManager = mockConfigManager();
setDynamicConfig(dynamicConfig);
this.lookupCoordinatorManager = EasyMock.createNiceMock(LookupCoordinatorManager.class);
mocks.add(jacksonConfigManager);
mocks.add(lookupCoordinatorManager);
}
private void setUp() throws Exception
{
EmittingLogger.registerEmitter(serviceEmitter);
inventory.setUp();
coordinatorInventoryView.setUp();
lifecycle.start();
leaderSelector.becomeLeader();
EasyMock.replay(mocks.toArray());
}
private void tearDown()
{
EasyMock.verify(mocks.toArray());
executorFactory.tearDown();
lifecycle.stop();
}
private void setDynamicConfig(CoordinatorDynamicConfig dynamicConfig)
{
this.dynamicConfig.set(dynamicConfig);
}
private JacksonConfigManager mockConfigManager()
{
final JacksonConfigManager jacksonConfigManager
= EasyMock.createMock(JacksonConfigManager.class);
EasyMock.expect(
jacksonConfigManager.watch(
EasyMock.eq(CoordinatorDynamicConfig.CONFIG_KEY),
EasyMock.eq(CoordinatorDynamicConfig.class),
EasyMock.anyObject()
)
).andReturn(dynamicConfig).anyTimes();
EasyMock.expect(
jacksonConfigManager.watch(
EasyMock.eq(CoordinatorCompactionConfig.CONFIG_KEY),
EasyMock.eq(CoordinatorCompactionConfig.class),
EasyMock.anyObject()
)
).andReturn(new AtomicReference<>(CoordinatorCompactionConfig.empty())).anyTimes();
return jacksonConfigManager;
}
}
/**
* Implementation of {@link ScheduledExecutorFactory} used to create and keep
* a handle on the various executors used inside the coordinator.
*/
private static class ExecutorFactory implements ScheduledExecutorFactory
{
static final String HISTORICAL_LOADER = "historical-loader-%d";
static final String LOAD_QUEUE_EXECUTOR = "load-queue-%d";
static final String LOAD_CALLBACK_EXECUTOR = "load-callback-%d";
static final String COORDINATOR_RUNNER = "Coordinator-Exec-HistoricalManagementDuties-%d";
private final Map<String, BlockingExecutorService> blockingExecutors = new HashMap<>();
private final boolean directExecution;
private BlockingExecutorService historicalLoader;
private BlockingExecutorService loadQueueExecutor;
private BlockingExecutorService loadCallbackExecutor;
private BlockingExecutorService historicalDutiesRunner;
private ExecutorFactory(boolean directExecution)
{
this.directExecution = directExecution;
}
@Override
public ScheduledExecutorService create(int corePoolSize, String nameFormat)
{
boolean isCoordinatorRunner = COORDINATOR_RUNNER.equals(nameFormat);
// Coordinator running executor must always be blocked
final ExecutorService executorService =
(directExecution && !isCoordinatorRunner)
? new DirectExecutorService()
: blockingExecutors.computeIfAbsent(nameFormat, BlockingExecutorService::new);
return new WrappingScheduledExecutorService(nameFormat, executorService, !isCoordinatorRunner);
}
private BlockingExecutorService findExecutor(String nameFormat)
{
return blockingExecutors.get(nameFormat);
}
private void findExecutors()
{
historicalDutiesRunner = findExecutor(COORDINATOR_RUNNER);
historicalLoader = findExecutor(HISTORICAL_LOADER);
loadQueueExecutor = findExecutor(LOAD_QUEUE_EXECUTOR);
loadCallbackExecutor = findExecutor(LOAD_CALLBACK_EXECUTOR);
}
private void tearDown()
{
blockingExecutors.values().forEach(BlockingExecutorService::shutdown);
}
}
}
| 20,145 | 0.722413 | 0.721718 | 605 | 32.29752 | 27.604481 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444628 | false | false |
14
|
d0bf4fc95ce7924344ffc6a621295c435672cb9c
| 30,021,821,417,181 |
6d9ed7a4f7330ca0f8754b6127a6430df26ee645
|
/morfologik-fsa-builders/src/test/java/morfologik/fsa/builders/FSA5Test.java
|
765e3235df25a66103e6294f8446b855411cd938
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
morfologik/morfologik-stemming
|
https://github.com/morfologik/morfologik-stemming
|
d154025ade1041906a0f4744306f83ced47b1acb
|
d7f1c571829562eaa4a16382860c1db42a63fe85
|
refs/heads/master
| 2023-08-08T15:17:50.038000 | 2022-04-26T11:47:14 | 2022-04-26T11:47:14 | 8,672,234 | 178 | 47 |
BSD-3-Clause
| false | 2023-07-25T17:24:02 | 2013-03-09T16:18:38 | 2023-06-23T19:19:48 | 2023-07-25T17:24:01 | 31,537 | 176 | 44 | 4 |
Java
| false | false |
package morfologik.fsa.builders;
import static morfologik.fsa.FSAFlags.*;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import morfologik.fsa.FSA;
import morfologik.fsa.FSA5;
import morfologik.fsa.FSAFlags;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Additional tests for {@link FSA5}.
*/
public final class FSA5Test extends TestBase {
public List<String> expected = Arrays.asList("a", "aba", "ac", "b", "ba", "c");
@Test
public void testVersion5() throws IOException {
final FSA fsa = FSA.read(this.getClass().getResourceAsStream("abc.fsa"));
assertFalse(fsa.getFlags().contains(FSAFlags.NUMBERS));
verifyContent(expected, fsa);
}
@Test
public void testVersion5WithNumbers() throws IOException {
final FSA fsa = FSA.read(this.getClass().getResourceAsStream("abc-numbers.fsa"));
verifyContent(expected, fsa);
assertTrue(fsa.getFlags().contains(FSAFlags.NUMBERS));
}
@Test
public void testArcsAndNodes() throws IOException {
final FSA fsa1 = FSA.read(this.getClass().getResourceAsStream("abc.fsa"));
final FSA fsa2 = FSA.read(this.getClass().getResourceAsStream("abc-numbers.fsa"));
FSAInfo info1 = new FSAInfo(fsa1);
FSAInfo info2 = new FSAInfo(fsa2);
assertEquals(info1.arcsCount, info2.arcsCount);
assertEquals(info1.nodeCount, info2.nodeCount);
assertEquals(4, info2.nodeCount);
assertEquals(7, info2.arcsCount);
}
@Test
public void testNumbers() throws IOException {
final FSA fsa = FSA.read(this.getClass().getResourceAsStream("abc-numbers.fsa"));
assertTrue(fsa.getFlags().contains(NEXTBIT));
// Get all numbers for nodes.
byte[] buffer = new byte[128];
final ArrayList<String> result = new ArrayList<String>();
walkNode(buffer, 0, fsa, fsa.getRootNode(), 0, result);
Collections.sort(result);
assertEquals(Arrays.asList("0 c", "1 b", "2 ba", "3 a", "4 ac", "5 aba"), result);
}
public static void walkNode(byte[] buffer, int depth, FSA fsa, int node, int cnt, List<String> result)
throws IOException {
for (int arc = fsa.getFirstArc(node); arc != 0; arc = fsa.getNextArc(arc)) {
buffer[depth] = fsa.getArcLabel(arc);
if (fsa.isArcFinal(arc) || fsa.isArcTerminal(arc)) {
result.add(cnt + " " + new String(buffer, 0, depth + 1, "UTF-8"));
}
if (fsa.isArcFinal(arc)) {
cnt++;
}
if (!fsa.isArcTerminal(arc)) {
walkNode(buffer, depth + 1, fsa, fsa.getEndNode(arc), cnt, result);
cnt += fsa.getRightLanguageCount(fsa.getEndNode(arc));
}
}
}
private static void verifyContent(List<String> expected, FSA fsa) throws IOException {
final ArrayList<String> actual = new ArrayList<String>();
int count = 0;
for (ByteBuffer bb : fsa.getSequences()) {
assertEquals(0, bb.arrayOffset());
assertEquals(0, bb.position());
actual.add(new String(bb.array(), 0, bb.remaining(), "UTF-8"));
count++;
}
assertEquals(expected.size(), count);
Collections.sort(actual);
assertEquals(expected, actual);
}
}
|
UTF-8
|
Java
| 3,312 |
java
|
FSA5Test.java
|
Java
|
[] | null |
[] |
package morfologik.fsa.builders;
import static morfologik.fsa.FSAFlags.*;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import morfologik.fsa.FSA;
import morfologik.fsa.FSA5;
import morfologik.fsa.FSAFlags;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Additional tests for {@link FSA5}.
*/
public final class FSA5Test extends TestBase {
public List<String> expected = Arrays.asList("a", "aba", "ac", "b", "ba", "c");
@Test
public void testVersion5() throws IOException {
final FSA fsa = FSA.read(this.getClass().getResourceAsStream("abc.fsa"));
assertFalse(fsa.getFlags().contains(FSAFlags.NUMBERS));
verifyContent(expected, fsa);
}
@Test
public void testVersion5WithNumbers() throws IOException {
final FSA fsa = FSA.read(this.getClass().getResourceAsStream("abc-numbers.fsa"));
verifyContent(expected, fsa);
assertTrue(fsa.getFlags().contains(FSAFlags.NUMBERS));
}
@Test
public void testArcsAndNodes() throws IOException {
final FSA fsa1 = FSA.read(this.getClass().getResourceAsStream("abc.fsa"));
final FSA fsa2 = FSA.read(this.getClass().getResourceAsStream("abc-numbers.fsa"));
FSAInfo info1 = new FSAInfo(fsa1);
FSAInfo info2 = new FSAInfo(fsa2);
assertEquals(info1.arcsCount, info2.arcsCount);
assertEquals(info1.nodeCount, info2.nodeCount);
assertEquals(4, info2.nodeCount);
assertEquals(7, info2.arcsCount);
}
@Test
public void testNumbers() throws IOException {
final FSA fsa = FSA.read(this.getClass().getResourceAsStream("abc-numbers.fsa"));
assertTrue(fsa.getFlags().contains(NEXTBIT));
// Get all numbers for nodes.
byte[] buffer = new byte[128];
final ArrayList<String> result = new ArrayList<String>();
walkNode(buffer, 0, fsa, fsa.getRootNode(), 0, result);
Collections.sort(result);
assertEquals(Arrays.asList("0 c", "1 b", "2 ba", "3 a", "4 ac", "5 aba"), result);
}
public static void walkNode(byte[] buffer, int depth, FSA fsa, int node, int cnt, List<String> result)
throws IOException {
for (int arc = fsa.getFirstArc(node); arc != 0; arc = fsa.getNextArc(arc)) {
buffer[depth] = fsa.getArcLabel(arc);
if (fsa.isArcFinal(arc) || fsa.isArcTerminal(arc)) {
result.add(cnt + " " + new String(buffer, 0, depth + 1, "UTF-8"));
}
if (fsa.isArcFinal(arc)) {
cnt++;
}
if (!fsa.isArcTerminal(arc)) {
walkNode(buffer, depth + 1, fsa, fsa.getEndNode(arc), cnt, result);
cnt += fsa.getRightLanguageCount(fsa.getEndNode(arc));
}
}
}
private static void verifyContent(List<String> expected, FSA fsa) throws IOException {
final ArrayList<String> actual = new ArrayList<String>();
int count = 0;
for (ByteBuffer bb : fsa.getSequences()) {
assertEquals(0, bb.arrayOffset());
assertEquals(0, bb.position());
actual.add(new String(bb.array(), 0, bb.remaining(), "UTF-8"));
count++;
}
assertEquals(expected.size(), count);
Collections.sort(actual);
assertEquals(expected, actual);
}
}
| 3,312 | 0.651872 | 0.639795 | 104 | 29.846153 | 27.660986 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.923077 | false | false |
14
|
87f9b3ab30f533d5aefc81c43ca7934200dca494
| 30,021,821,415,909 |
5970e70092b9ed307c2b7605f420857cc156e28c
|
/app/src/main/java/com/zhenhaikj/factoryside/mvp/activity/BrandActivity.java
|
d748d5c0b0663282470e3149db8d297bd69cf5d1
|
[] |
no_license
|
LittleBigBoy/FactoryApp
|
https://github.com/LittleBigBoy/FactoryApp
|
71105521fcc3f845687fdeac0f516d3c92bf4c44
|
07c0d13181b0a751b0e2076fb42fc5a21da3a47d
|
refs/heads/master
| 2021-07-12T15:26:53.060000 | 2020-03-13T06:40:29 | 2020-03-13T06:40:29 | 164,363,149 | 1 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.zhenhaikj.factoryside.mvp.activity;
import android.app.AlertDialog;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.gyf.barlibrary.ImmersionBar;
import com.qmuiteam.qmui.widget.popup.QMUIPopup;
import com.zhenhaikj.factoryside.R;
import com.zhenhaikj.factoryside.mvp.adapter.BrandsAdapter;
import com.zhenhaikj.factoryside.mvp.adapter.CategoryAdapter;
import com.zhenhaikj.factoryside.mvp.base.BaseActivity;
import com.zhenhaikj.factoryside.mvp.base.BaseResult;
import com.zhenhaikj.factoryside.mvp.bean.Brand;
import com.zhenhaikj.factoryside.mvp.bean.Category;
import com.zhenhaikj.factoryside.mvp.bean.Category;
import com.zhenhaikj.factoryside.mvp.bean.CategoryData;
import com.zhenhaikj.factoryside.mvp.bean.Data;
import com.zhenhaikj.factoryside.mvp.bean.ProductType;
import com.zhenhaikj.factoryside.mvp.contract.AddBrandContract;
import com.zhenhaikj.factoryside.mvp.model.AddBrandModel;
import com.zhenhaikj.factoryside.mvp.presenter.AddBrandPresenter;
import com.zhenhaikj.factoryside.mvp.utils.MyUtils;
import java.util.ArrayList;
import java.util.List;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
public class BrandActivity extends BaseActivity<AddBrandPresenter, AddBrandModel> implements View.OnClickListener, AddBrandContract.View {
private static final String TAG = "BrandActivity";
@BindView(R.id.icon_back)
ImageView mIconBack;
@BindView(R.id.tv_title)
TextView mTvTitle;
@BindView(R.id.tv_save)
TextView mTvSave;
@BindView(R.id.icon_search)
ImageView mIconSearch;
@BindView(R.id.toolbar)
Toolbar mToolbar;
@BindView(R.id.rl_brand)
RecyclerView mRlBrand;
@BindView(R.id.iv_add_brand)
ImageView mIvAddBrand;
@BindView(R.id.view)
View mView;
private List<Brand> brandList = new ArrayList<>();
private Brand brand;
private BrandsAdapter brandsAdapter;
private String brandName;
private EditText et_brandName;
private Button btn_next;
private String userID;
private String FBrandID;//品牌id
private String FCategoryID;//分类id
private TextView tv_choose_category;
private String category;
private View dialog;
private AlertDialog alertDialog;
private AlertDialog categoryDialog;
private PopupWindow popupWindow;
private List<Category.DataBean> categoryList;
private QMUIPopup qmuiPopup;
private String categoryId;
private String fBrandID;
@Override
protected int setLayoutId() {
return R.layout.activity_brand;
}
@Override
protected void initImmersionBar() {
mImmersionBar = ImmersionBar.with(this);
// mImmersionBar.statusBarDarkFont(true, 0.2f); //原理:如果当前设备支持状态栏字体变色,会设置状态栏字体为黑色,如果当前设备不支持状态栏字体变色,会使当前状态栏加上透明度,否则不执行透明度
mImmersionBar.statusBarView(mView);
mImmersionBar.keyboardEnable(true);
mImmersionBar.init();
}
@Override
protected void initData() {
mTvTitle.setVisibility(View.VISIBLE);
mTvTitle.setText("品牌列表");
// for (int i = 0; i < 36; i++) {
// brandList.add(new Brand());
// }
brandsAdapter = new BrandsAdapter(R.layout.item_brand, brandList);
mRlBrand.setLayoutManager(new LinearLayoutManager(mActivity));
mRlBrand.setAdapter(brandsAdapter);
brandsAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
@Override
public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
switch (view.getId()) {
case R.id.iv_delete:
fBrandID = brandsAdapter.getData().get(position).getFBrandID();
mPresenter.DeleteFactoryBrand(fBrandID);
break;
case R.id.rl_brand:
break;
}
}
});
SPUtils spUtils = SPUtils.getInstance("token");
userID = spUtils.getString("userName");
mPresenter.GetBrand(userID);
}
@Override
protected void initView() {
}
@Override
protected void setListener() {
mIconBack.setOnClickListener(this);
mIvAddBrand.setOnClickListener(this);
}
@Override
public void onBackPressed() {
super.onBackPressed();
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.iv_add_brand:
dialog = LayoutInflater.from(mActivity).inflate(R.layout.dialog_brand_name, null);
et_brandName = dialog.findViewById(R.id.et_enter);
btn_next = dialog.findViewById(R.id.btn_next);
btn_next.setText("添加");
btn_next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
brandName = et_brandName.getText().toString();
if ("".equals(brandName) || brandName == null) {
MyUtils.showToast(mActivity, "请输入品牌名称!");
return;
}
mPresenter.AddFactoryBrand(userID, brandName);
}
});
alertDialog = new AlertDialog.Builder(mActivity).setView(dialog).create();
alertDialog.show();
break;
case R.id.icon_back:
finish();
break;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO: add setContentView(...) invocation
ButterKnife.bind(this);
}
@Override
public void AddFactoryBrand(BaseResult<Data> baseResult) {
switch (baseResult.getStatusCode()) {
case 200:
Data data = baseResult.getData();
if (data.isItem1()) {
alertDialog.dismiss();
mPresenter.GetBrand(userID);
ToastUtils.showShort( "添加品牌成功!");
} else {
ToastUtils.showShort( "添加品牌失败!");
}
break;
default:
ToastUtils.showShort("添加品牌失败!");
break;
}
}
@Override
public void GetFactoryCategory(BaseResult<CategoryData> baseResult) {
switch (baseResult.getStatusCode()) {
case 200:
categoryList = baseResult.getData().getData();
showPopWindow();
break;
case 401:
// ToastUtils.showShort(baseResult.getData());
break;
}
}
@Override
public void GetChildFactoryCategory(BaseResult<CategoryData> baseResult) {
switch (baseResult.getStatusCode()){
case 200:
break;
case 401:
break;
}
}
// @Override
// public void GetBrand(BaseResult<List<ProductType>> baseResult) {
// switch (baseResult.getStatusCode()){
// case 200:
// brandList=baseResult.getData();
// brandsAdapter.setNewData(brandList);
// FBrandID=brandList.get(1).getFBrandID();
// mPresenter.GetCategory(FBrandID);
// break;
// case 401:
// break;
// }
// }
//
// @Override
// public void GetCategory(BaseResult<Data<List<ProductType>>> baseResult) {
// switch (baseResult.getStatusCode()){
// case 200:
// brandList=baseResult.getData().getItem2();
// brandsAdapter.setNewData(brandList);
// break;
// case 401:
// break;
// }
// }
@Override
public void GetProducttype(BaseResult<Data<List<ProductType>>> baseResult) {
}
@Override
public void DeleteFactoryProducttype(BaseResult<Data> baseResult) {
}
@Override
public void DeleteFactoryBrand(BaseResult<Data> baseResult) {
switch (baseResult.getStatusCode()) {
case 200:
if (baseResult.getData().isItem1()){
ToastUtils.showShort("删除成功!");
}else {
ToastUtils.showShort(baseResult.getData().getItem2()+"");
}
mPresenter.GetBrand(userID);
break;
default:
ToastUtils.showShort("删除失败!");
break;
}
}
@Override
public void GetBrand(BaseResult<List<Brand>> baseResult) {
switch (baseResult.getStatusCode()) {
case 200:
brandList = baseResult.getData();
brandsAdapter.setNewData(brandList);
break;
case 401:
break;
}
}
@Override
public void GetBrandCategory(BaseResult<Data<Category>> baseResult) {
}
@Override
public void AddBrandCategory(BaseResult<Data> baseResult) {
}
@Override
public void GetChildFactoryCategory2(BaseResult<CategoryData> baseResult) {
}
@Override
public void DeleteFactoryProduct(BaseResult<Data> baseResult) {
}
public void showPopWindow() {
View view = LayoutInflater.from(mActivity).inflate(R.layout.category_pop, null);
final RecyclerView rv = view.findViewById(R.id.rv);
rv.setLayoutManager(new LinearLayoutManager(mActivity));
CategoryAdapter adapter = new CategoryAdapter(R.layout.category_item, categoryList);
rv.setAdapter(adapter);
adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
@Override
public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
popupWindow.dismiss();
tv_choose_category.setText(categoryList.get(position).getFCategoryName());
categoryId = categoryList.get(position).getFCategoryID();
}
});
popupWindow = new PopupWindow(view, tv_choose_category.getWidth(), ViewGroup.LayoutParams.WRAP_CONTENT);
// popupWindow.setAnimationStyle(R.style.popwindow_anim_style);
popupWindow.setBackgroundDrawable(new BitmapDrawable());
popupWindow.setFocusable(true);
popupWindow.setOutsideTouchable(true);
popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
@Override
public void onDismiss() {
// MyUtils.setWindowAlpa(mActivity, false);
}
});
if (popupWindow != null && !popupWindow.isShowing()) {
popupWindow.showAsDropDown(tv_choose_category, 0, 10);
// popupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);
}
}
}
|
UTF-8
|
Java
| 11,665 |
java
|
BrandActivity.java
|
Java
|
[
{
"context": "nce(\"token\");\n userID = spUtils.getString(\"userName\");\n mPresenter.GetBrand(userID);\n\n }\n\n ",
"end": 4575,
"score": 0.9986053109169006,
"start": 4567,
"tag": "USERNAME",
"value": "userName"
}
] | null |
[] |
package com.zhenhaikj.factoryside.mvp.activity;
import android.app.AlertDialog;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.gyf.barlibrary.ImmersionBar;
import com.qmuiteam.qmui.widget.popup.QMUIPopup;
import com.zhenhaikj.factoryside.R;
import com.zhenhaikj.factoryside.mvp.adapter.BrandsAdapter;
import com.zhenhaikj.factoryside.mvp.adapter.CategoryAdapter;
import com.zhenhaikj.factoryside.mvp.base.BaseActivity;
import com.zhenhaikj.factoryside.mvp.base.BaseResult;
import com.zhenhaikj.factoryside.mvp.bean.Brand;
import com.zhenhaikj.factoryside.mvp.bean.Category;
import com.zhenhaikj.factoryside.mvp.bean.Category;
import com.zhenhaikj.factoryside.mvp.bean.CategoryData;
import com.zhenhaikj.factoryside.mvp.bean.Data;
import com.zhenhaikj.factoryside.mvp.bean.ProductType;
import com.zhenhaikj.factoryside.mvp.contract.AddBrandContract;
import com.zhenhaikj.factoryside.mvp.model.AddBrandModel;
import com.zhenhaikj.factoryside.mvp.presenter.AddBrandPresenter;
import com.zhenhaikj.factoryside.mvp.utils.MyUtils;
import java.util.ArrayList;
import java.util.List;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
public class BrandActivity extends BaseActivity<AddBrandPresenter, AddBrandModel> implements View.OnClickListener, AddBrandContract.View {
private static final String TAG = "BrandActivity";
@BindView(R.id.icon_back)
ImageView mIconBack;
@BindView(R.id.tv_title)
TextView mTvTitle;
@BindView(R.id.tv_save)
TextView mTvSave;
@BindView(R.id.icon_search)
ImageView mIconSearch;
@BindView(R.id.toolbar)
Toolbar mToolbar;
@BindView(R.id.rl_brand)
RecyclerView mRlBrand;
@BindView(R.id.iv_add_brand)
ImageView mIvAddBrand;
@BindView(R.id.view)
View mView;
private List<Brand> brandList = new ArrayList<>();
private Brand brand;
private BrandsAdapter brandsAdapter;
private String brandName;
private EditText et_brandName;
private Button btn_next;
private String userID;
private String FBrandID;//品牌id
private String FCategoryID;//分类id
private TextView tv_choose_category;
private String category;
private View dialog;
private AlertDialog alertDialog;
private AlertDialog categoryDialog;
private PopupWindow popupWindow;
private List<Category.DataBean> categoryList;
private QMUIPopup qmuiPopup;
private String categoryId;
private String fBrandID;
@Override
protected int setLayoutId() {
return R.layout.activity_brand;
}
@Override
protected void initImmersionBar() {
mImmersionBar = ImmersionBar.with(this);
// mImmersionBar.statusBarDarkFont(true, 0.2f); //原理:如果当前设备支持状态栏字体变色,会设置状态栏字体为黑色,如果当前设备不支持状态栏字体变色,会使当前状态栏加上透明度,否则不执行透明度
mImmersionBar.statusBarView(mView);
mImmersionBar.keyboardEnable(true);
mImmersionBar.init();
}
@Override
protected void initData() {
mTvTitle.setVisibility(View.VISIBLE);
mTvTitle.setText("品牌列表");
// for (int i = 0; i < 36; i++) {
// brandList.add(new Brand());
// }
brandsAdapter = new BrandsAdapter(R.layout.item_brand, brandList);
mRlBrand.setLayoutManager(new LinearLayoutManager(mActivity));
mRlBrand.setAdapter(brandsAdapter);
brandsAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
@Override
public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
switch (view.getId()) {
case R.id.iv_delete:
fBrandID = brandsAdapter.getData().get(position).getFBrandID();
mPresenter.DeleteFactoryBrand(fBrandID);
break;
case R.id.rl_brand:
break;
}
}
});
SPUtils spUtils = SPUtils.getInstance("token");
userID = spUtils.getString("userName");
mPresenter.GetBrand(userID);
}
@Override
protected void initView() {
}
@Override
protected void setListener() {
mIconBack.setOnClickListener(this);
mIvAddBrand.setOnClickListener(this);
}
@Override
public void onBackPressed() {
super.onBackPressed();
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.iv_add_brand:
dialog = LayoutInflater.from(mActivity).inflate(R.layout.dialog_brand_name, null);
et_brandName = dialog.findViewById(R.id.et_enter);
btn_next = dialog.findViewById(R.id.btn_next);
btn_next.setText("添加");
btn_next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
brandName = et_brandName.getText().toString();
if ("".equals(brandName) || brandName == null) {
MyUtils.showToast(mActivity, "请输入品牌名称!");
return;
}
mPresenter.AddFactoryBrand(userID, brandName);
}
});
alertDialog = new AlertDialog.Builder(mActivity).setView(dialog).create();
alertDialog.show();
break;
case R.id.icon_back:
finish();
break;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO: add setContentView(...) invocation
ButterKnife.bind(this);
}
@Override
public void AddFactoryBrand(BaseResult<Data> baseResult) {
switch (baseResult.getStatusCode()) {
case 200:
Data data = baseResult.getData();
if (data.isItem1()) {
alertDialog.dismiss();
mPresenter.GetBrand(userID);
ToastUtils.showShort( "添加品牌成功!");
} else {
ToastUtils.showShort( "添加品牌失败!");
}
break;
default:
ToastUtils.showShort("添加品牌失败!");
break;
}
}
@Override
public void GetFactoryCategory(BaseResult<CategoryData> baseResult) {
switch (baseResult.getStatusCode()) {
case 200:
categoryList = baseResult.getData().getData();
showPopWindow();
break;
case 401:
// ToastUtils.showShort(baseResult.getData());
break;
}
}
@Override
public void GetChildFactoryCategory(BaseResult<CategoryData> baseResult) {
switch (baseResult.getStatusCode()){
case 200:
break;
case 401:
break;
}
}
// @Override
// public void GetBrand(BaseResult<List<ProductType>> baseResult) {
// switch (baseResult.getStatusCode()){
// case 200:
// brandList=baseResult.getData();
// brandsAdapter.setNewData(brandList);
// FBrandID=brandList.get(1).getFBrandID();
// mPresenter.GetCategory(FBrandID);
// break;
// case 401:
// break;
// }
// }
//
// @Override
// public void GetCategory(BaseResult<Data<List<ProductType>>> baseResult) {
// switch (baseResult.getStatusCode()){
// case 200:
// brandList=baseResult.getData().getItem2();
// brandsAdapter.setNewData(brandList);
// break;
// case 401:
// break;
// }
// }
@Override
public void GetProducttype(BaseResult<Data<List<ProductType>>> baseResult) {
}
@Override
public void DeleteFactoryProducttype(BaseResult<Data> baseResult) {
}
@Override
public void DeleteFactoryBrand(BaseResult<Data> baseResult) {
switch (baseResult.getStatusCode()) {
case 200:
if (baseResult.getData().isItem1()){
ToastUtils.showShort("删除成功!");
}else {
ToastUtils.showShort(baseResult.getData().getItem2()+"");
}
mPresenter.GetBrand(userID);
break;
default:
ToastUtils.showShort("删除失败!");
break;
}
}
@Override
public void GetBrand(BaseResult<List<Brand>> baseResult) {
switch (baseResult.getStatusCode()) {
case 200:
brandList = baseResult.getData();
brandsAdapter.setNewData(brandList);
break;
case 401:
break;
}
}
@Override
public void GetBrandCategory(BaseResult<Data<Category>> baseResult) {
}
@Override
public void AddBrandCategory(BaseResult<Data> baseResult) {
}
@Override
public void GetChildFactoryCategory2(BaseResult<CategoryData> baseResult) {
}
@Override
public void DeleteFactoryProduct(BaseResult<Data> baseResult) {
}
public void showPopWindow() {
View view = LayoutInflater.from(mActivity).inflate(R.layout.category_pop, null);
final RecyclerView rv = view.findViewById(R.id.rv);
rv.setLayoutManager(new LinearLayoutManager(mActivity));
CategoryAdapter adapter = new CategoryAdapter(R.layout.category_item, categoryList);
rv.setAdapter(adapter);
adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
@Override
public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
popupWindow.dismiss();
tv_choose_category.setText(categoryList.get(position).getFCategoryName());
categoryId = categoryList.get(position).getFCategoryID();
}
});
popupWindow = new PopupWindow(view, tv_choose_category.getWidth(), ViewGroup.LayoutParams.WRAP_CONTENT);
// popupWindow.setAnimationStyle(R.style.popwindow_anim_style);
popupWindow.setBackgroundDrawable(new BitmapDrawable());
popupWindow.setFocusable(true);
popupWindow.setOutsideTouchable(true);
popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
@Override
public void onDismiss() {
// MyUtils.setWindowAlpa(mActivity, false);
}
});
if (popupWindow != null && !popupWindow.isShowing()) {
popupWindow.showAsDropDown(tv_choose_category, 0, 10);
// popupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);
}
}
}
| 11,665 | 0.618952 | 0.614402 | 347 | 31.939482 | 25.263666 | 138 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.530259 | false | false |
14
|
c0f607fd4ca1d9862b172c93ed088fa5a66e8aab
| 13,657,996,019,187 |
852c96ccaa935ad2744b0a3dedf87c0e94b062fe
|
/docroot/WEB-INF/src/com/ssavr/solr/service/impl/IceCreamDocumentsLocalServiceImpl.java
|
e9259d2d359757e5e3376d64012c20693066672b
|
[] |
no_license
|
sartios/liferay-solr-tutorial
|
https://github.com/sartios/liferay-solr-tutorial
|
e0fef6b79485f63fcfdd9a6e33350a1db2b12e84
|
061b3455069fd6f19649bd3abbdeab08a5082502
|
refs/heads/master
| 2021-01-25T08:30:00.730000 | 2015-09-08T09:42:17 | 2015-09-08T09:42:17 | 42,049,812 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.ssavr.solr.service.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.search.Indexer;
import com.liferay.portal.kernel.search.IndexerRegistryUtil;
import com.liferay.portal.service.ServiceContext;
import com.ssavr.solr.beans.IceCreamBean;
import com.ssavr.solr.model.IceCream;
import com.ssavr.solr.model.IceCreamDocuments;
import com.ssavr.solr.service.IceCreamLocalServiceUtil;
import com.ssavr.solr.service.base.IceCreamDocumentsLocalServiceBaseImpl;
/**
* The implementation of the ice cream documents local service.
*
* <p>
* All custom service methods should be put in this class. Whenever methods are
* added, rerun ServiceBuilder to copy their definitions into the
* {@link com.ssavr.solr.service.IceCreamDocumentsLocalService} interface.
*
* <p>
* This is a local service. Methods of this service will not have security
* checks based on the propagated JAAS credentials because this service can only
* be accessed from within the same VM.
* </p>
*
* @author SAVRAMIS
* @see com.ssavr.solr.service.base.IceCreamDocumentsLocalServiceBaseImpl
* @see com.ssavr.solr.service.IceCreamDocumentsLocalServiceUtil
*/
public class IceCreamDocumentsLocalServiceImpl extends
IceCreamDocumentsLocalServiceBaseImpl {
/*
* NOTE FOR DEVELOPERS:
*
* Never reference this interface directly. Always use {@link
* com.ssavr.solr.service.IceCreamDocumentsLocalServiceUtil} to access the
* ice cream documents local service.
*/
public List<IceCreamDocuments> addIceCreamDocuments(long userId,
long companyId, ServiceContext serviceContext, long iceCreamId,
String[] documentIds) throws SystemException, PortalException,
Exception {
if (_log.isDebugEnabled()) {
_log.debug("addIceCreamDocuments()");
}
List<IceCreamDocuments> documents = new ArrayList<IceCreamDocuments>();
for (String documentId : documentIds) {
IceCreamDocuments document = addIceCreamDocument(userId, companyId,
serviceContext, iceCreamId, documentId);
documents.add(document);
}
return documents;
}
public IceCreamDocuments addIceCreamDocument(long userId, long companyId,
ServiceContext serviceContext, long iceCreamId, String documentId)
throws SystemException, PortalException, Exception {
if (_log.isDebugEnabled()) {
_log.debug("addIceCreamDocument()");
}
long iceCreamDocumentId = counterLocalService
.increment(IceCreamDocuments.class.getName());
IceCreamDocuments document = iceCreamDocumentsPersistence
.create(iceCreamDocumentId);
document.setUserId(userId);
document.setCompanyId(companyId);
document.setUuid(serviceContext.getUuid());
document.setIceCreamId(iceCreamId);
document.setDocumentId(Long.parseLong(documentId));
Date now = new Date();
document.setCreateDate(now);
document.setModifiedDate(now);
document = iceCreamDocumentsPersistence.update(document, false,
serviceContext);
IceCream iceCream = iceCreamLocalService.getIceCream(iceCreamId);
if (iceCream != null) {
if (_log.isDebugEnabled()) {
_log.debug("addUpdateIndex(" + iceCreamId + ")");
}
Indexer indexer = IndexerRegistryUtil
.getIndexer(IceCreamBean.class);
IceCreamBean bean = IceCreamLocalServiceUtil
.getIceCreamBean(iceCream);
indexer.reindex(bean);
}
return document;
}
public List<IceCreamDocuments> getIceCreamDocumentsByIceCreamId(
long iceCreamId) throws SystemException {
if (_log.isDebugEnabled()) {
_log.debug("getIceCreamDocumentsByIceCreamId()");
}
return iceCreamDocumentsPersistence.findByIceCreamId(iceCreamId);
}
public void deleteIceCreamDocumentsByIceCreamId(long iceCreamId)
throws SystemException {
if (_log.isDebugEnabled()) {
_log.debug("deleteIceCreamDocumentsByIceCreamId()");
}
List<IceCreamDocuments> documents = iceCreamDocumentsPersistence
.findByIceCreamId(iceCreamId);
for (IceCreamDocuments document : documents) {
iceCreamDocumentsPersistence.remove(document);
}
}
private static Log _log = LogFactoryUtil
.getLog(IceCreamDocumentsLocalServiceImpl.class);
}
|
UTF-8
|
Java
| 4,921 |
java
|
IceCreamDocumentsLocalServiceImpl.java
|
Java
|
[
{
"context": "ed from within the same VM.\n * </p>\n * \n * @author SAVRAMIS\n * @see com.ssavr.solr.service.base.IceCreamDocum",
"end": 1874,
"score": 0.9672318696975708,
"start": 1866,
"tag": "NAME",
"value": "SAVRAMIS"
}
] | null |
[] |
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.ssavr.solr.service.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.search.Indexer;
import com.liferay.portal.kernel.search.IndexerRegistryUtil;
import com.liferay.portal.service.ServiceContext;
import com.ssavr.solr.beans.IceCreamBean;
import com.ssavr.solr.model.IceCream;
import com.ssavr.solr.model.IceCreamDocuments;
import com.ssavr.solr.service.IceCreamLocalServiceUtil;
import com.ssavr.solr.service.base.IceCreamDocumentsLocalServiceBaseImpl;
/**
* The implementation of the ice cream documents local service.
*
* <p>
* All custom service methods should be put in this class. Whenever methods are
* added, rerun ServiceBuilder to copy their definitions into the
* {@link com.ssavr.solr.service.IceCreamDocumentsLocalService} interface.
*
* <p>
* This is a local service. Methods of this service will not have security
* checks based on the propagated JAAS credentials because this service can only
* be accessed from within the same VM.
* </p>
*
* @author SAVRAMIS
* @see com.ssavr.solr.service.base.IceCreamDocumentsLocalServiceBaseImpl
* @see com.ssavr.solr.service.IceCreamDocumentsLocalServiceUtil
*/
public class IceCreamDocumentsLocalServiceImpl extends
IceCreamDocumentsLocalServiceBaseImpl {
/*
* NOTE FOR DEVELOPERS:
*
* Never reference this interface directly. Always use {@link
* com.ssavr.solr.service.IceCreamDocumentsLocalServiceUtil} to access the
* ice cream documents local service.
*/
public List<IceCreamDocuments> addIceCreamDocuments(long userId,
long companyId, ServiceContext serviceContext, long iceCreamId,
String[] documentIds) throws SystemException, PortalException,
Exception {
if (_log.isDebugEnabled()) {
_log.debug("addIceCreamDocuments()");
}
List<IceCreamDocuments> documents = new ArrayList<IceCreamDocuments>();
for (String documentId : documentIds) {
IceCreamDocuments document = addIceCreamDocument(userId, companyId,
serviceContext, iceCreamId, documentId);
documents.add(document);
}
return documents;
}
public IceCreamDocuments addIceCreamDocument(long userId, long companyId,
ServiceContext serviceContext, long iceCreamId, String documentId)
throws SystemException, PortalException, Exception {
if (_log.isDebugEnabled()) {
_log.debug("addIceCreamDocument()");
}
long iceCreamDocumentId = counterLocalService
.increment(IceCreamDocuments.class.getName());
IceCreamDocuments document = iceCreamDocumentsPersistence
.create(iceCreamDocumentId);
document.setUserId(userId);
document.setCompanyId(companyId);
document.setUuid(serviceContext.getUuid());
document.setIceCreamId(iceCreamId);
document.setDocumentId(Long.parseLong(documentId));
Date now = new Date();
document.setCreateDate(now);
document.setModifiedDate(now);
document = iceCreamDocumentsPersistence.update(document, false,
serviceContext);
IceCream iceCream = iceCreamLocalService.getIceCream(iceCreamId);
if (iceCream != null) {
if (_log.isDebugEnabled()) {
_log.debug("addUpdateIndex(" + iceCreamId + ")");
}
Indexer indexer = IndexerRegistryUtil
.getIndexer(IceCreamBean.class);
IceCreamBean bean = IceCreamLocalServiceUtil
.getIceCreamBean(iceCream);
indexer.reindex(bean);
}
return document;
}
public List<IceCreamDocuments> getIceCreamDocumentsByIceCreamId(
long iceCreamId) throws SystemException {
if (_log.isDebugEnabled()) {
_log.debug("getIceCreamDocumentsByIceCreamId()");
}
return iceCreamDocumentsPersistence.findByIceCreamId(iceCreamId);
}
public void deleteIceCreamDocumentsByIceCreamId(long iceCreamId)
throws SystemException {
if (_log.isDebugEnabled()) {
_log.debug("deleteIceCreamDocumentsByIceCreamId()");
}
List<IceCreamDocuments> documents = iceCreamDocumentsPersistence
.findByIceCreamId(iceCreamId);
for (IceCreamDocuments document : documents) {
iceCreamDocumentsPersistence.remove(document);
}
}
private static Log _log = LogFactoryUtil
.getLog(IceCreamDocumentsLocalServiceImpl.class);
}
| 4,921 | 0.773826 | 0.771794 | 136 | 35.191177 | 26.208023 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.801471 | false | false |
14
|
8bcf4f3387d48aedc710de3690bc38317982d1b7
| 20,126,216,765,689 |
275e2dc6cb24b1b1e4cae629cca6076d7132bc00
|
/Learning-app/src/Com/techlab/java/Recursion.java
|
ba65a44c45b9526041859d4b5d20cb8fb40c6a5c
|
[] |
no_license
|
yadavgovind15/GOVIND-YADAV
|
https://github.com/yadavgovind15/GOVIND-YADAV
|
719eeff9d13d3607d5de93bb5105cf1acd170112
|
3b9b98488b4bc4231ef29cfff024325c50811d12
|
refs/heads/master
| 2020-12-04T11:01:59.412000 | 2020-02-27T11:57:24 | 2020-02-27T11:57:24 | 231,739,042 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Com.techlab.java;
public class Recursion {
public static void main(String[] args) {
sum(10,20);
}
static void sum(int a,int b) {
int sum=a+b;
sum(10,20);
System.out.println(sum);
}
}
|
UTF-8
|
Java
| 204 |
java
|
Recursion.java
|
Java
|
[] | null |
[] |
package Com.techlab.java;
public class Recursion {
public static void main(String[] args) {
sum(10,20);
}
static void sum(int a,int b) {
int sum=a+b;
sum(10,20);
System.out.println(sum);
}
}
| 204 | 0.651961 | 0.612745 | 15 | 12.533334 | 13.09894 | 40 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.866667 | false | false |
14
|
4c53dfb1b285964b49abcef92802084ac4fcb49f
| 20,126,216,764,499 |
d530671b90a88ada4ae7ed49cd830e8e6c20dc57
|
/src/controller/navigation/Key.java
|
07fc333279995317eb0a3183058b85903e2d6793
|
[] |
no_license
|
JBarberU/medioqre
|
https://github.com/JBarberU/medioqre
|
6fa1747feaf7fed1e6776023f7fa9b8964e0d356
|
0c3a4ef339d56396c8b0e46a17d4026c16e6a723
|
refs/heads/master
| 2021-01-22T00:19:56.499000 | 2012-05-22T16:37:41 | 2012-05-22T16:37:41 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package controller.navigation;
import model.Direction;
/**
* Callable interface.
*
* @author Johan
*/
interface Callable {
/**
* "On" callback - called on trigger, i.e. on a keydown event for example.
*/
public void on();
/**
* "Off" callback - called on untrigger, i.e. on a keyup event for example.
*/
public void off();
}
/**
* Key class for representing a single action key.
*
* @author Johan
*/
public class Key {
private final String key;
protected final Callable callback;
/**
* Create a new key with a name and callback, which is called on action.
*
* @param name
* The name
* @param callback
* A callback
*/
public Key(String name, Callable callback) {
this.key = name;
this.callback = callback;
}
/**
* Trigger the callback's down event.
*/
public void fire() {
if (callback != null)
callback.on();
}
/**
* Trigger the callback's up event.
*/
public void fireUp() {
if (callback != null)
callback.off();
}
/**
* Get the key name.
*
* @return The name
*/
public String getKey() {
return this.key;
}
@Override
public String toString() {
return this.key;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Key other = (Key) o;
return this.key.equals(other.key);
}
@Override
public int hashCode() {
return this.key.hashCode();
}
}
/**
* A navigation key with a direction.
*
* @author Johan
*
*/
class NavigationKey extends Key {
private final Direction direction;
/**
* Create a new navigation key.
*
* @param name
* The name
* @param callback
* The callback
* @param dir
* The associated direction
*/
public NavigationKey(String name, Callable callback, Direction dir) {
super(name, callback);
this.direction = dir;
}
/**
* Get the direction.
*
* @return The key's direction
*/
public Direction getDirection() {
return this.direction;
}
/**
* If this navigation key equals another navigation key.
*
* @return True if the <code>Key</code>s are equal and that the directions are the same
*/
@Override
public boolean equals(Object o) {
return super.equals(o)
&& this.direction == ((NavigationKey) o).direction;
}
@Override
public int hashCode() {
int hash = super.hashCode() * 17;
return hash + this.direction.hashCode();
}
}
|
UTF-8
|
Java
| 2,486 |
java
|
Key.java
|
Java
|
[
{
"context": "ection;\n\n/**\n * Callable interface.\n * \n * @author Johan\n */\ninterface Callable {\n\t/**\n\t * \"On\" callback -",
"end": 104,
"score": 0.9995811581611633,
"start": 99,
"tag": "NAME",
"value": "Johan"
},
{
"context": "r representing a single action key.\n * \n * @author Johan\n */\npublic class Key {\n\tprivate final String key;",
"end": 422,
"score": 0.9996021389961243,
"start": 417,
"tag": "NAME",
"value": "Johan"
},
{
"context": " A navigation key with a direction.\n * \n * @author Johan\n * \n */\nclass NavigationKey extends Key {\n\n\tpriva",
"end": 1541,
"score": 0.999660074710846,
"start": 1536,
"tag": "NAME",
"value": "Johan"
}
] | null |
[] |
package controller.navigation;
import model.Direction;
/**
* Callable interface.
*
* @author Johan
*/
interface Callable {
/**
* "On" callback - called on trigger, i.e. on a keydown event for example.
*/
public void on();
/**
* "Off" callback - called on untrigger, i.e. on a keyup event for example.
*/
public void off();
}
/**
* Key class for representing a single action key.
*
* @author Johan
*/
public class Key {
private final String key;
protected final Callable callback;
/**
* Create a new key with a name and callback, which is called on action.
*
* @param name
* The name
* @param callback
* A callback
*/
public Key(String name, Callable callback) {
this.key = name;
this.callback = callback;
}
/**
* Trigger the callback's down event.
*/
public void fire() {
if (callback != null)
callback.on();
}
/**
* Trigger the callback's up event.
*/
public void fireUp() {
if (callback != null)
callback.off();
}
/**
* Get the key name.
*
* @return The name
*/
public String getKey() {
return this.key;
}
@Override
public String toString() {
return this.key;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Key other = (Key) o;
return this.key.equals(other.key);
}
@Override
public int hashCode() {
return this.key.hashCode();
}
}
/**
* A navigation key with a direction.
*
* @author Johan
*
*/
class NavigationKey extends Key {
private final Direction direction;
/**
* Create a new navigation key.
*
* @param name
* The name
* @param callback
* The callback
* @param dir
* The associated direction
*/
public NavigationKey(String name, Callable callback, Direction dir) {
super(name, callback);
this.direction = dir;
}
/**
* Get the direction.
*
* @return The key's direction
*/
public Direction getDirection() {
return this.direction;
}
/**
* If this navigation key equals another navigation key.
*
* @return True if the <code>Key</code>s are equal and that the directions are the same
*/
@Override
public boolean equals(Object o) {
return super.equals(o)
&& this.direction == ((NavigationKey) o).direction;
}
@Override
public int hashCode() {
int hash = super.hashCode() * 17;
return hash + this.direction.hashCode();
}
}
| 2,486 | 0.61786 | 0.617056 | 143 | 16.384615 | 17.764553 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.174825 | false | false |
14
|
089d2611264e2d660b3d135323fa4272da64a0e5
| 26,345,329,408,223 |
9e9fea34b5c45438284fcdba10d0c3f61d266741
|
/jetexpress-petportal/src/main/java/org/springframework/samples/petportal/portlet/PetsController.java
|
88a1089e2fa45111885eeda9c0678379a589c45c
|
[] |
no_license
|
rock-hu/jetexpress
|
https://github.com/rock-hu/jetexpress
|
fbe8c4ffe98a6e071048e98bf9dc7595570c19e8
|
8290dad3bd3c5be2fe42338ff46a01648e3aaabd
|
refs/heads/master
| 2016-09-05T18:45:55.532000 | 2015-03-29T18:27:22 | 2015-03-29T18:27:22 | 32,805,101 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.springframework.samples.petportal.portlet;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletPreferences;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.samples.petportal.domain.Pet;
import org.springframework.samples.petportal.service.PetService;
import org.springframework.samples.petportal.validation.PetValidator;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.portlet.bind.PortletRequestDataBinder;
import org.springframework.web.portlet.util.PortletUtils;
/**
* This is a simple Controller which delegates to the
* {@link PetService PetService} and then populates the model with all
* returned Pets. This could have extended AbstractController in which
* case only the render phase would have required handling. However,
* this demonstrates the ability to simply implement the Controller
* interface.
*
* @author John A. Lewis
* @author Mark Fisher
* @author Juergen Hoeller
*/
@Controller
@RequestMapping("VIEW")
@SessionAttributes("pet")
public class PetsController {
private final PetService petService;
@Autowired
public PetsController(PetService petService) {
this.petService = petService;
}
/**
* For the page where the 'birthdate' is to be entered, the dateFormat is
* provided so that it may be displayed to the user. The format is
* retrieved from the PortletPreferences.
*/
@ModelAttribute("dateFormat")
protected String getDateFormat(PortletPreferences preferences) {
return preferences.getValue("dateFormat", PetService.DEFAULT_DATE_FORMAT);
}
/**
* Registers a PropertyEditor with the data binder for handling Dates
* using the format as currently specified in the PortletPreferences.
*/
@InitBinder
public void initBinder(PortletRequestDataBinder binder, PortletPreferences preferences) {
String formatString = preferences.getValue("dateFormat", PetService.DEFAULT_DATE_FORMAT);
SimpleDateFormat dateFormat = new SimpleDateFormat(formatString);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
binder.setAllowedFields(new String[] {"species", "breed", "name", "birthdate"});
}
@RequestMapping // default render (action=list)
public String listPets(Model model) {
model.addAttribute("pets", this.petService.getAllPets());
return "pets";
}
@RequestMapping(params = "action=view") // render phase
public String viewPet(@RequestParam("pet") int petId, Model model) {
model.addAttribute("pet", this.petService.getPet(petId));
return "petView";
}
@RequestMapping(params = "action=add") // render phase
public String showPetForm(Model model) {
// Used for the initial form as well as for redisplaying with errors.
if (!model.containsAttribute("pet")) {
model.addAttribute("pet", new Pet());
model.addAttribute("page", 0);
}
return "petAdd";
}
@RequestMapping(params = "action=add") // action phase
public void submitPage(
ActionRequest request, ActionResponse response,
@ModelAttribute("pet") Pet pet, BindingResult result,
@RequestParam("_page") int currentPage, Model model) {
if (request.getParameter("_cancel") != null) {
response.setRenderParameter("action", "list");
}
else if (request.getParameter("_finish") != null) {
new PetValidator().validate(pet, result);
if (!result.hasErrors()) {
this.petService.addPet(pet);
response.setRenderParameter("action", "list");
}
else {
model.addAttribute("page", currentPage);
}
}
else {
switch (currentPage) {
case 0: new PetValidator().validateSpecies(pet, result); break;
case 1: new PetValidator().validateBreed(pet, result); break;
case 2: new PetValidator().validateName(pet, result); break;
case 3: new PetValidator().validateBirthdate(pet, result); break;
}
int targetPage = currentPage;
if (!result.hasErrors()) {
targetPage = PortletUtils.getTargetPage(request, "_target", currentPage);
}
model.addAttribute("page", targetPage);
}
}
@RequestMapping(params = "action=delete") // action phase
public void deletePet(@RequestParam("pet") int petId, ActionResponse response) {
this.petService.deletePet(petId);
response.setRenderParameter("action", "list");
}
}
|
UTF-8
|
Java
| 4,964 |
java
|
PetsController.java
|
Java
|
[
{
"context": "nt the Controller \r\n * interface.\r\n * \r\n * @author John A. Lewis\r\n * @author Mark Fisher\r\n * @author Juergen Hoell",
"end": 1550,
"score": 0.9998535513877869,
"start": 1537,
"tag": "NAME",
"value": "John A. Lewis"
},
{
"context": "erface.\r\n * \r\n * @author John A. Lewis\r\n * @author Mark Fisher\r\n * @author Juergen Hoeller\r\n */\r\n@Controller\r\n@R",
"end": 1574,
"score": 0.9997902512550354,
"start": 1563,
"tag": "NAME",
"value": "Mark Fisher"
},
{
"context": " John A. Lewis\r\n * @author Mark Fisher\r\n * @author Juergen Hoeller\r\n */\r\n@Controller\r\n@RequestMapping(\"VIEW\")\r\n@Sess",
"end": 1602,
"score": 0.9998849034309387,
"start": 1587,
"tag": "NAME",
"value": "Juergen Hoeller"
}
] | null |
[] |
package org.springframework.samples.petportal.portlet;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletPreferences;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.samples.petportal.domain.Pet;
import org.springframework.samples.petportal.service.PetService;
import org.springframework.samples.petportal.validation.PetValidator;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.portlet.bind.PortletRequestDataBinder;
import org.springframework.web.portlet.util.PortletUtils;
/**
* This is a simple Controller which delegates to the
* {@link PetService PetService} and then populates the model with all
* returned Pets. This could have extended AbstractController in which
* case only the render phase would have required handling. However,
* this demonstrates the ability to simply implement the Controller
* interface.
*
* @author <NAME>
* @author <NAME>
* @author <NAME>
*/
@Controller
@RequestMapping("VIEW")
@SessionAttributes("pet")
public class PetsController {
private final PetService petService;
@Autowired
public PetsController(PetService petService) {
this.petService = petService;
}
/**
* For the page where the 'birthdate' is to be entered, the dateFormat is
* provided so that it may be displayed to the user. The format is
* retrieved from the PortletPreferences.
*/
@ModelAttribute("dateFormat")
protected String getDateFormat(PortletPreferences preferences) {
return preferences.getValue("dateFormat", PetService.DEFAULT_DATE_FORMAT);
}
/**
* Registers a PropertyEditor with the data binder for handling Dates
* using the format as currently specified in the PortletPreferences.
*/
@InitBinder
public void initBinder(PortletRequestDataBinder binder, PortletPreferences preferences) {
String formatString = preferences.getValue("dateFormat", PetService.DEFAULT_DATE_FORMAT);
SimpleDateFormat dateFormat = new SimpleDateFormat(formatString);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
binder.setAllowedFields(new String[] {"species", "breed", "name", "birthdate"});
}
@RequestMapping // default render (action=list)
public String listPets(Model model) {
model.addAttribute("pets", this.petService.getAllPets());
return "pets";
}
@RequestMapping(params = "action=view") // render phase
public String viewPet(@RequestParam("pet") int petId, Model model) {
model.addAttribute("pet", this.petService.getPet(petId));
return "petView";
}
@RequestMapping(params = "action=add") // render phase
public String showPetForm(Model model) {
// Used for the initial form as well as for redisplaying with errors.
if (!model.containsAttribute("pet")) {
model.addAttribute("pet", new Pet());
model.addAttribute("page", 0);
}
return "petAdd";
}
@RequestMapping(params = "action=add") // action phase
public void submitPage(
ActionRequest request, ActionResponse response,
@ModelAttribute("pet") Pet pet, BindingResult result,
@RequestParam("_page") int currentPage, Model model) {
if (request.getParameter("_cancel") != null) {
response.setRenderParameter("action", "list");
}
else if (request.getParameter("_finish") != null) {
new PetValidator().validate(pet, result);
if (!result.hasErrors()) {
this.petService.addPet(pet);
response.setRenderParameter("action", "list");
}
else {
model.addAttribute("page", currentPage);
}
}
else {
switch (currentPage) {
case 0: new PetValidator().validateSpecies(pet, result); break;
case 1: new PetValidator().validateBreed(pet, result); break;
case 2: new PetValidator().validateName(pet, result); break;
case 3: new PetValidator().validateBirthdate(pet, result); break;
}
int targetPage = currentPage;
if (!result.hasErrors()) {
targetPage = PortletUtils.getTargetPage(request, "_target", currentPage);
}
model.addAttribute("page", targetPage);
}
}
@RequestMapping(params = "action=delete") // action phase
public void deletePet(@RequestParam("pet") int petId, ActionResponse response) {
this.petService.deletePet(petId);
response.setRenderParameter("action", "list");
}
}
| 4,943 | 0.73751 | 0.736503 | 134 | 35.044777 | 27.263739 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.843284 | false | false |
14
|
99a92425b832ca4bb7e3fa8d7d9a9bcf16f00480
| 7,687,991,481,365 |
3d93a7f990b2e00cffd58297bf0f3a690faec0fd
|
/src/mainProgram/StageBuilder.java
|
0c5122811be9e44089ce417016a091d7732a1c1b
|
[] |
no_license
|
pokerus911/AMES_361
|
https://github.com/pokerus911/AMES_361
|
9ac78edf6b0294ee3fea89779ae4908c9acef324
|
8861ce88d603104d48bfa81f6c8023c370664f49
|
refs/heads/master
| 2021-04-09T17:00:33.652000 | 2014-12-10T20:29:24 | 2014-12-10T20:29:24 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package mainProgram;
import polls.AppearancePoll;
import polls.PersonalityPoll;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class StageBuilder {
public BorderPane getSplashScreen() {
BorderPane bpane = new BorderPane();
ImageView splashScreen = new ImageView(new Image(getClass()
.getResourceAsStream("/images/AnimeSplashScreen.png")));
bpane.setBottom(splashScreen);
return bpane;
}
public void editAppearance(BorderPane bottomContent, CharacterInfoDisplay characterInfo, GridPane root) {
System.out.println("Appearance");
Stage pollStage = new Stage();
pollStage.setTitle("Edit Appearance!");
pollStage.setHeight(350);
pollStage.setWidth(450);
AppearancePoll appearancePoll = new AppearancePoll();
pollStage.setScene(appearancePoll.makeAppearancePoll(bottomContent, pollStage,
characterInfo, root));
pollStage.show();
}
public void editPersonality(BorderPane bottomContent, CharacterInfoDisplay characterInfo,
GridPane root) {
System.out.println("Personality");
Stage pollStage = new Stage();
pollStage.setTitle("Personality Quiz!");
PersonalityPoll personalityPoll = new PersonalityPoll();
pollStage.setScene(personalityPoll.makePersonalityPoll(bottomContent, pollStage,
characterInfo, root));
pollStage.setHeight(450);
pollStage.show();
}
public void generateRomance(Protagonist myChar) {
System.out.println("Romance");
}
public void generateBackstory(Protagonist myChar) {
System.out.println("Backstory");
}
}
|
UTF-8
|
Java
| 1,875 |
java
|
StageBuilder.java
|
Java
|
[] | null |
[] |
package mainProgram;
import polls.AppearancePoll;
import polls.PersonalityPoll;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class StageBuilder {
public BorderPane getSplashScreen() {
BorderPane bpane = new BorderPane();
ImageView splashScreen = new ImageView(new Image(getClass()
.getResourceAsStream("/images/AnimeSplashScreen.png")));
bpane.setBottom(splashScreen);
return bpane;
}
public void editAppearance(BorderPane bottomContent, CharacterInfoDisplay characterInfo, GridPane root) {
System.out.println("Appearance");
Stage pollStage = new Stage();
pollStage.setTitle("Edit Appearance!");
pollStage.setHeight(350);
pollStage.setWidth(450);
AppearancePoll appearancePoll = new AppearancePoll();
pollStage.setScene(appearancePoll.makeAppearancePoll(bottomContent, pollStage,
characterInfo, root));
pollStage.show();
}
public void editPersonality(BorderPane bottomContent, CharacterInfoDisplay characterInfo,
GridPane root) {
System.out.println("Personality");
Stage pollStage = new Stage();
pollStage.setTitle("Personality Quiz!");
PersonalityPoll personalityPoll = new PersonalityPoll();
pollStage.setScene(personalityPoll.makePersonalityPoll(bottomContent, pollStage,
characterInfo, root));
pollStage.setHeight(450);
pollStage.show();
}
public void generateRomance(Protagonist myChar) {
System.out.println("Romance");
}
public void generateBackstory(Protagonist myChar) {
System.out.println("Backstory");
}
}
| 1,875 | 0.781867 | 0.777067 | 66 | 27.40909 | 23.774813 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.712121 | false | false |
14
|
179255b6f5fba9786b1b1c68f19ba0b77ccac32d
| 10,849,087,409,169 |
d912f9e1044645b2bcfc7b1d2a106dad9f5815b1
|
/src/main/java/pl/magodan/magodan/Service/UserService.java
|
f4b394fa7ee6f99e5129721365b9c9669803acf0
|
[] |
no_license
|
piotrg44/Magodan
|
https://github.com/piotrg44/Magodan
|
dde74853eb13b93e6ba851fab12deb61ee53f674
|
a3028901e36ac6eac6d4c0c0a96faa135428bc56
|
refs/heads/main
| 2023-04-07T04:18:25.878000 | 2021-04-16T06:32:21 | 2021-04-16T06:32:21 | 352,933,259 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package pl.magodan.magodan.Service;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import pl.magodan.magodan.Model.*;
import pl.magodan.magodan.Repository.GroupRepository;
import pl.magodan.magodan.Repository.TaskRepository;
import pl.magodan.magodan.Repository.UserGroupRepository;
import pl.magodan.magodan.Repository.UserRepository;
import pl.magodan.magodan.Service.Dtos.Mapper.MapperService;
import pl.magodan.magodan.Service.Dtos.UserResponse;
import javax.swing.*;
import java.util.List;
@Service
@AllArgsConstructor
public class UserService {
UserRepository userRepository;
TaskRepository taskRepository;
MapperService mapperService;
UserGroupRepository userGroupRepository;
GroupRepository groupRepository;
@Bean
public void initTaskAndUser() {
User user =
User
.builder()
.username("User1")
.role(Role.OWNER)
.build();
userRepository.save(user);
User user2 =
User
.builder()
.username("User2")
.role(Role.USER)
.build();
userRepository.save(user2);
User user3 =
User
.builder()
.username("User3")
.role(Role.USER)
.build();
userRepository.save(user3);
Task task =
Task
.builder()
.Description("Task1")
.owner(user)
.howManyTimesADay(3)
.isDaily(false)
.participants(List.of(user2, user3))
.title("Wyjdz z psem.")
.build();
taskRepository.save(task);
Group group1 =
Group
.builder()
.numberOfUsers(3)
.build();
groupRepository.save(group1);
UserGroup groupFamilyOne =
UserGroup
.builder()
.user(user)
.group(group1)
.build();
userGroupRepository.save(groupFamilyOne);
}
public List<UserResponse> findAll() {
return mapperService.usersToUsersResponse(userRepository.findAll());
}
}
|
UTF-8
|
Java
| 2,586 |
java
|
UserService.java
|
Java
|
[
{
"context": " .builder()\n .username(\"User1\")\n .role(Role.OWNER)\n ",
"end": 988,
"score": 0.9996638298034668,
"start": 983,
"tag": "USERNAME",
"value": "User1"
},
{
"context": " .builder()\n .username(\"User2\")\n .role(Role.USER)\n ",
"end": 1220,
"score": 0.9996806383132935,
"start": 1215,
"tag": "USERNAME",
"value": "User2"
},
{
"context": " .builder()\n .username(\"User3\")\n .role(Role.USER)\n ",
"end": 1452,
"score": 0.9996594190597534,
"start": 1447,
"tag": "USERNAME",
"value": "User3"
}
] | null |
[] |
package pl.magodan.magodan.Service;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import pl.magodan.magodan.Model.*;
import pl.magodan.magodan.Repository.GroupRepository;
import pl.magodan.magodan.Repository.TaskRepository;
import pl.magodan.magodan.Repository.UserGroupRepository;
import pl.magodan.magodan.Repository.UserRepository;
import pl.magodan.magodan.Service.Dtos.Mapper.MapperService;
import pl.magodan.magodan.Service.Dtos.UserResponse;
import javax.swing.*;
import java.util.List;
@Service
@AllArgsConstructor
public class UserService {
UserRepository userRepository;
TaskRepository taskRepository;
MapperService mapperService;
UserGroupRepository userGroupRepository;
GroupRepository groupRepository;
@Bean
public void initTaskAndUser() {
User user =
User
.builder()
.username("User1")
.role(Role.OWNER)
.build();
userRepository.save(user);
User user2 =
User
.builder()
.username("User2")
.role(Role.USER)
.build();
userRepository.save(user2);
User user3 =
User
.builder()
.username("User3")
.role(Role.USER)
.build();
userRepository.save(user3);
Task task =
Task
.builder()
.Description("Task1")
.owner(user)
.howManyTimesADay(3)
.isDaily(false)
.participants(List.of(user2, user3))
.title("Wyjdz z psem.")
.build();
taskRepository.save(task);
Group group1 =
Group
.builder()
.numberOfUsers(3)
.build();
groupRepository.save(group1);
UserGroup groupFamilyOne =
UserGroup
.builder()
.user(user)
.group(group1)
.build();
userGroupRepository.save(groupFamilyOne);
}
public List<UserResponse> findAll() {
return mapperService.usersToUsersResponse(userRepository.findAll());
}
}
| 2,586 | 0.517015 | 0.511214 | 87 | 28.724138 | 17.481478 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.367816 | false | false |
14
|
2580feccdd76379fa910051f9a6779860063b35d
| 8,469,675,573,119 |
a1b6a3a6e7801855191a607ba56a22f64d5c850b
|
/Android-project/app/src/main/java/com/example/myproject/MainActivity.java
|
7ba697566643e574fd9439d11350cccbc313df7e
|
[] |
no_license
|
shikashetty99/Location-finder-app
|
https://github.com/shikashetty99/Location-finder-app
|
5a73debfdc16df9d6df9d0b75d7a84315fb103db
|
10f6bde320f3e27474cdae693ce4ef35f28be9e2
|
refs/heads/master
| 2022-11-23T13:48:28.696000 | 2020-07-21T18:01:43 | 2020-07-21T18:01:43 | 281,467,990 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.myproject;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText e1,e2,e3,e4,e5;
Button b,b1,b2,b3,b4,b7;
Main1 Mydb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Mydb = new Main1(this);
e1 = (EditText) findViewById(R.id.editText);
e2 = (EditText) findViewById(R.id.editText2);
e3 = (EditText) findViewById(R.id.editText3);
e4 = (EditText) findViewById(R.id.editText4);
b = (Button) findViewById(R.id.button);
// b1=(Button)findViewById(R.id.button2);
b2 = (Button) findViewById(R.id.button3);
// b3=(Button)findViewById(R.id.button4);
// b4 = (Button) findViewById(R.id.button7);
/* b4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), MainStaff.class);
startActivity(i);
}
});*/
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String dept_id = e1.getText().toString();
String floor_no = e2.getText().toString();
int floor_no1 = Integer.parseInt(floor_no);
String no_of_rooms = e3.getText().toString();
int no_of_rooms1 = Integer.parseInt(no_of_rooms);
String dept_head = e4.getText().toString();
if(dept_id.equals(" ")||floor_no.equals("")||no_of_rooms.equals("")||dept_head.equals(""))
{
Toast.makeText(getApplicationContext(),"Please enter all fields",Toast.LENGTH_SHORT).show();
}
else {
Boolean isinserted = Mydb.insertdata(dept_id, floor_no1, no_of_rooms1, dept_head);
if (isinserted)
Toast.makeText(getApplicationContext(), "inserted", Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplicationContext(), "not inserted", Toast.LENGTH_LONG).show();
}
e1.getText().clear();
e2.getText().clear();
e3.getText().clear();
e4.getText().clear();
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder;
builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("change?")
.setMessage("Are you sure you want to update?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String dept_id = e1.getText().toString();
String floor_no = e2.getText().toString();
int floor_no1 = Integer.parseInt(floor_no);
String no_of_rooms = e3.getText().toString();
int no_of_rooms1 = Integer.parseInt(no_of_rooms);
String dept_head = e4.getText().toString();
if(dept_id.equals(" ")||floor_no.equals("")||no_of_rooms.equals("")||dept_head.equals(""))
{
Toast.makeText(getApplicationContext(),"Please enter all fields",Toast.LENGTH_SHORT).show();
}
else {
Boolean isupdated = Mydb.updatedata(dept_id, floor_no1, no_of_rooms1, dept_head);
if (isupdated)
Toast.makeText(getApplicationContext(), "updated", Toast.LENGTH_SHORT).show();
else
Toast.makeText(getApplicationContext(), "not updated", Toast.LENGTH_SHORT).show();
}
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
});
/*b3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),Main2Activity.class);
startActivity(i);
}
});*/
/* b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String s=e1.getText().toString();
Cursor res = Mydb.getAlldata(s);
if (res.getCount() == 0) {
// Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT).show();
showMessage("error", "Nothing found");
return;
}
StringBuffer buffer = new StringBuffer();
if(res.moveToNext()) {
buffer.append("DeptId:" + res.getString(0) + "\n");
buffer.append("Floorno:" + res.getString(1) + "\n");
buffer.append("No of rooms:" + res.getString(2) + "\n");
buffer.append("Depthead:" + res.getString(3) + "\n\n");
}
showMessage("Data", buffer.toString());
}
});
}
public void showMessage(String title, String Message) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}*/
}
}
|
UTF-8
|
Java
| 6,785 |
java
|
MainActivity.java
|
Java
|
[] | null |
[] |
package com.example.myproject;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText e1,e2,e3,e4,e5;
Button b,b1,b2,b3,b4,b7;
Main1 Mydb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Mydb = new Main1(this);
e1 = (EditText) findViewById(R.id.editText);
e2 = (EditText) findViewById(R.id.editText2);
e3 = (EditText) findViewById(R.id.editText3);
e4 = (EditText) findViewById(R.id.editText4);
b = (Button) findViewById(R.id.button);
// b1=(Button)findViewById(R.id.button2);
b2 = (Button) findViewById(R.id.button3);
// b3=(Button)findViewById(R.id.button4);
// b4 = (Button) findViewById(R.id.button7);
/* b4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), MainStaff.class);
startActivity(i);
}
});*/
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String dept_id = e1.getText().toString();
String floor_no = e2.getText().toString();
int floor_no1 = Integer.parseInt(floor_no);
String no_of_rooms = e3.getText().toString();
int no_of_rooms1 = Integer.parseInt(no_of_rooms);
String dept_head = e4.getText().toString();
if(dept_id.equals(" ")||floor_no.equals("")||no_of_rooms.equals("")||dept_head.equals(""))
{
Toast.makeText(getApplicationContext(),"Please enter all fields",Toast.LENGTH_SHORT).show();
}
else {
Boolean isinserted = Mydb.insertdata(dept_id, floor_no1, no_of_rooms1, dept_head);
if (isinserted)
Toast.makeText(getApplicationContext(), "inserted", Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplicationContext(), "not inserted", Toast.LENGTH_LONG).show();
}
e1.getText().clear();
e2.getText().clear();
e3.getText().clear();
e4.getText().clear();
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder;
builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("change?")
.setMessage("Are you sure you want to update?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String dept_id = e1.getText().toString();
String floor_no = e2.getText().toString();
int floor_no1 = Integer.parseInt(floor_no);
String no_of_rooms = e3.getText().toString();
int no_of_rooms1 = Integer.parseInt(no_of_rooms);
String dept_head = e4.getText().toString();
if(dept_id.equals(" ")||floor_no.equals("")||no_of_rooms.equals("")||dept_head.equals(""))
{
Toast.makeText(getApplicationContext(),"Please enter all fields",Toast.LENGTH_SHORT).show();
}
else {
Boolean isupdated = Mydb.updatedata(dept_id, floor_no1, no_of_rooms1, dept_head);
if (isupdated)
Toast.makeText(getApplicationContext(), "updated", Toast.LENGTH_SHORT).show();
else
Toast.makeText(getApplicationContext(), "not updated", Toast.LENGTH_SHORT).show();
}
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
});
/*b3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),Main2Activity.class);
startActivity(i);
}
});*/
/* b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String s=e1.getText().toString();
Cursor res = Mydb.getAlldata(s);
if (res.getCount() == 0) {
// Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT).show();
showMessage("error", "Nothing found");
return;
}
StringBuffer buffer = new StringBuffer();
if(res.moveToNext()) {
buffer.append("DeptId:" + res.getString(0) + "\n");
buffer.append("Floorno:" + res.getString(1) + "\n");
buffer.append("No of rooms:" + res.getString(2) + "\n");
buffer.append("Depthead:" + res.getString(3) + "\n\n");
}
showMessage("Data", buffer.toString());
}
});
}
public void showMessage(String title, String Message) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}*/
}
}
| 6,785 | 0.493294 | 0.484746 | 179 | 35.905029 | 31.928112 | 128 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.715084 | false | false |
14
|
31eff120b031e1c6abf0e385f0e616df3f75fd6f
| 9,517,647,567,392 |
f97f724555fd5857c37639cf6210be7e3773d3aa
|
/FinalExamJPASec/src/main/java/com/packt/webstore/service/impl/PropertyServiceImpl.java
|
6df9a374d562387a4b80e22bea6848c8dafcb38e
|
[] |
no_license
|
MaryamGhiasvand/RentProperty
|
https://github.com/MaryamGhiasvand/RentProperty
|
3d192a31c4722dd2f639fee85984a601e02e1a1f
|
8c3e2dd19e924a58078e2cd77186f3d98955aeab
|
refs/heads/master
| 2022-10-29T12:22:09.315000 | 2020-06-18T03:28:39 | 2020-06-18T03:28:39 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.packt.webstore.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.packt.webstore.domain.Credentials;
import com.packt.webstore.domain.Property;
import com.packt.webstore.domain.PropertyType;
import com.packt.webstore.repository.PropertyRepository;
import com.packt.webstore.service.PropertyService;
@Service
@Transactional
public class PropertyServiceImpl implements PropertyService{
@Autowired
PropertyRepository propertyRepository;
@Override
public List<Property> findAll() {
return (List<Property>) propertyRepository.findAll();
}
@Override
public void save(Property property) {
propertyRepository.save(property);
}
@Override
public Property fingPropertyById(Long id) {
return (Property) propertyRepository.findPropertyById(id);
}
@Override
public void delete(Long id) {
propertyRepository.delete(id);
}
@Override
public List<Property> findPropertyForSearch(int bathCount, int bedCount) {
return propertyRepository.findPropertyForSearch(bathCount, bedCount);
}
@Override
public List<Property> findPropertyByCity(String city) {
//return propertyRepository.findByState();
return null;
}
public List<Property> searchProperty(String search, int bathCount, int bedCount, PropertyType propertyType) {
return propertyRepository.findCity(search, bathCount , bedCount, propertyType);
}
@Override
public List<Property> findPropertyByOwener(Credentials owner) {
return (List<Property>) propertyRepository.findPropertyByOwner(owner);
}
}
|
UTF-8
|
Java
| 1,680 |
java
|
PropertyServiceImpl.java
|
Java
|
[] | null |
[] |
package com.packt.webstore.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.packt.webstore.domain.Credentials;
import com.packt.webstore.domain.Property;
import com.packt.webstore.domain.PropertyType;
import com.packt.webstore.repository.PropertyRepository;
import com.packt.webstore.service.PropertyService;
@Service
@Transactional
public class PropertyServiceImpl implements PropertyService{
@Autowired
PropertyRepository propertyRepository;
@Override
public List<Property> findAll() {
return (List<Property>) propertyRepository.findAll();
}
@Override
public void save(Property property) {
propertyRepository.save(property);
}
@Override
public Property fingPropertyById(Long id) {
return (Property) propertyRepository.findPropertyById(id);
}
@Override
public void delete(Long id) {
propertyRepository.delete(id);
}
@Override
public List<Property> findPropertyForSearch(int bathCount, int bedCount) {
return propertyRepository.findPropertyForSearch(bathCount, bedCount);
}
@Override
public List<Property> findPropertyByCity(String city) {
//return propertyRepository.findByState();
return null;
}
public List<Property> searchProperty(String search, int bathCount, int bedCount, PropertyType propertyType) {
return propertyRepository.findCity(search, bathCount , bedCount, propertyType);
}
@Override
public List<Property> findPropertyByOwener(Credentials owner) {
return (List<Property>) propertyRepository.findPropertyByOwner(owner);
}
}
| 1,680 | 0.797619 | 0.797619 | 63 | 25.666666 | 27.308931 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.253968 | false | false |
14
|
eb545e34f740bf8ddac7283671597a3cfa91e289
| 11,854,109,746,978 |
6723365777852c2b9fb4cfcb1d3de0194294dfb3
|
/odd-platform-api/src/main/java/com/provectus/oddplatform/mapper/TagMapperImpl.java
|
3f21d2d777aa7a68e8f47705d3d2b74e874566f6
|
[
"Apache-2.0"
] |
permissive
|
RustamGimadiev/odd-platform
|
https://github.com/RustamGimadiev/odd-platform
|
be5088e76fc6675e8f457ab81da0dc6319e003d1
|
69aab08ae21186e36de48d8f4d810f7a8af82501
|
refs/heads/main
| 2023-06-23T01:35:35.924000 | 2021-07-23T12:42:37 | 2021-07-23T12:42:37 | 388,759,698 | 1 | 0 |
Apache-2.0
| true | 2021-07-23T10:11:22 | 2021-07-23T10:11:22 | 2021-07-23T10:11:19 | 2021-07-23T09:25:18 | 1,686 | 0 | 0 | 0 | null | false | false |
package com.provectus.oddplatform.mapper;
import com.provectus.oddplatform.api.contract.model.Tag;
import com.provectus.oddplatform.api.contract.model.TagFormData;
import com.provectus.oddplatform.api.contract.model.TagsResponse;
import com.provectus.oddplatform.model.tables.pojos.TagPojo;
import com.provectus.oddplatform.utils.Page;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class TagMapperImpl implements TagMapper {
@Override
public TagPojo mapForm(final TagFormData form) {
return new TagPojo()
.setName(form.getName())
.setImportant(form.getImportant());
}
@Override
public TagPojo applyForm(final TagPojo pojo, final TagFormData form) {
pojo.setName(form.getName());
pojo.setImportant(form.getImportant());
return pojo;
}
@Override
public Tag mapPojo(final TagPojo pojo) {
return new Tag()
.id(pojo.getId())
.name(pojo.getName())
.important(pojo.getImportant());
}
@Override
public TagsResponse mapPojos(final List<TagPojo> pojos) {
return new TagsResponse()
.items(mapPojoList(pojos))
.pageInfo(pageInfo(pojos.size()));
}
@Override
public TagsResponse mapPojos(final Page<TagPojo> pojos) {
return new TagsResponse()
.items(mapPojoList(pojos.getData()))
.pageInfo(pageInfo(pojos));
}
@Override
public TagsResponse mapTags(final List<Tag> tags) {
return new TagsResponse()
.items(tags)
.pageInfo(pageInfo(tags.size()));
}
}
|
UTF-8
|
Java
| 1,655 |
java
|
TagMapperImpl.java
|
Java
|
[] | null |
[] |
package com.provectus.oddplatform.mapper;
import com.provectus.oddplatform.api.contract.model.Tag;
import com.provectus.oddplatform.api.contract.model.TagFormData;
import com.provectus.oddplatform.api.contract.model.TagsResponse;
import com.provectus.oddplatform.model.tables.pojos.TagPojo;
import com.provectus.oddplatform.utils.Page;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class TagMapperImpl implements TagMapper {
@Override
public TagPojo mapForm(final TagFormData form) {
return new TagPojo()
.setName(form.getName())
.setImportant(form.getImportant());
}
@Override
public TagPojo applyForm(final TagPojo pojo, final TagFormData form) {
pojo.setName(form.getName());
pojo.setImportant(form.getImportant());
return pojo;
}
@Override
public Tag mapPojo(final TagPojo pojo) {
return new Tag()
.id(pojo.getId())
.name(pojo.getName())
.important(pojo.getImportant());
}
@Override
public TagsResponse mapPojos(final List<TagPojo> pojos) {
return new TagsResponse()
.items(mapPojoList(pojos))
.pageInfo(pageInfo(pojos.size()));
}
@Override
public TagsResponse mapPojos(final Page<TagPojo> pojos) {
return new TagsResponse()
.items(mapPojoList(pojos.getData()))
.pageInfo(pageInfo(pojos));
}
@Override
public TagsResponse mapTags(final List<Tag> tags) {
return new TagsResponse()
.items(tags)
.pageInfo(pageInfo(tags.size()));
}
}
| 1,655 | 0.660423 | 0.660423 | 56 | 28.553572 | 21.553852 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.303571 | false | false |
14
|
515d373545c49a07b13a9e2f34db5f82c7cb6e1c
| 15,264,313,817,303 |
bd42514e62fcadc9cfab4ce3f0918bc06cb1d64c
|
/src/com/ascent/javabean/User.java
|
e815da50be1354a00fe2f1d296d3d5b10f872f54
|
[] |
no_license
|
Gingber/struts2Model
|
https://github.com/Gingber/struts2Model
|
ba32bef15844815dbb28ed50957a604bc8f4757b
|
db57ee2cd3903ae2bca68ed10cd6e8e794f51539
|
refs/heads/master
| 2021-01-20T04:39:48.288000 | 2013-11-09T08:59:40 | 2013-11-09T08:59:40 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
*
*/
package com.ascent.javabean;
import java.io.Serializable;
/**
* @author zy
* 实现O-R Mapping映射
* 类名 对应 表名
* 类属性 对应 表字段
* 类属性类型 对应 表字段类型
* 类关系 对应 表关系
*
*/
public class User implements Serializable {
private int id ;
private String username ;
private String password ;
private int age ;
private String email ;
public User(){}
/**
* @param id
* @param username
* @param password
* @param age
* @param email
*/
public User(int id, String username, String password, int age, String email) {
super();
this.id = id;
this.username = username;
this.password = password;
this.age = age;
this.email = email;
}
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the username
*/
public String getUsername() {
return username;
}
/**
* @param username the username to set
*/
public void setUsername(String username) {
this.username = username;
}
/**
* @return the password
*/
public String getPassword() {
return password;
}
/**
* @param password the password to set
*/
public void setPassword(String password) {
this.password = password;
}
/**
* @return the age
*/
public int getAge() {
return age;
}
/**
* @param age the age to set
*/
public void setAge(int age) {
this.age = age;
}
/**
* @return the email
*/
public String getEmail() {
return email;
}
/**
* @param email the email to set
*/
public void setEmail(String email) {
this.email = email;
}
}
|
GB18030
|
Java
| 1,690 |
java
|
User.java
|
Java
|
[
{
"context": "ean;\n\nimport java.io.Serializable;\n\n/**\n * @author zy\n * 实现O-R Mapping映射\n * 类名 对应 表名\n * 类属性 对应 表",
"end": 89,
"score": 0.9984782338142395,
"start": 87,
"tag": "USERNAME",
"value": "zy"
},
{
"context": "il) {\n\t\tsuper();\n\t\tthis.id = id;\n\t\tthis.username = username;\n\t\tthis.password = password;\n\t\tthis.age = age;\n\t\t",
"end": 602,
"score": 0.9988231062889099,
"start": 594,
"tag": "USERNAME",
"value": "username"
},
{
"context": " id;\n\t\tthis.username = username;\n\t\tthis.password = password;\n\t\tthis.age = age;\n\t\tthis.email = email;\n\t}\n\t/**\n",
"end": 630,
"score": 0.9977063536643982,
"start": 622,
"tag": "PASSWORD",
"value": "password"
}
] | null |
[] |
/**
*
*/
package com.ascent.javabean;
import java.io.Serializable;
/**
* @author zy
* 实现O-R Mapping映射
* 类名 对应 表名
* 类属性 对应 表字段
* 类属性类型 对应 表字段类型
* 类关系 对应 表关系
*
*/
public class User implements Serializable {
private int id ;
private String username ;
private String password ;
private int age ;
private String email ;
public User(){}
/**
* @param id
* @param username
* @param password
* @param age
* @param email
*/
public User(int id, String username, String password, int age, String email) {
super();
this.id = id;
this.username = username;
this.password = <PASSWORD>;
this.age = age;
this.email = email;
}
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the username
*/
public String getUsername() {
return username;
}
/**
* @param username the username to set
*/
public void setUsername(String username) {
this.username = username;
}
/**
* @return the password
*/
public String getPassword() {
return password;
}
/**
* @param password the password to set
*/
public void setPassword(String password) {
this.password = password;
}
/**
* @return the age
*/
public int getAge() {
return age;
}
/**
* @param age the age to set
*/
public void setAge(int age) {
this.age = age;
}
/**
* @return the email
*/
public String getEmail() {
return email;
}
/**
* @param email the email to set
*/
public void setEmail(String email) {
this.email = email;
}
}
| 1,692 | 0.604089 | 0.604089 | 108 | 13.944445 | 13.324186 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.231481 | false | false |
14
|
5b6795a67ffb6a400952aad7d863ef91f17bacd2
| 26,130,581,069,870 |
26d4c488bf522321f2388082a9288f2d8532c859
|
/GravitationalForce/src/com/prrathi/Objects/Mover.java
|
a42b8bc29ac6235689b2d5be0fbf86fda173154b
|
[
"MIT"
] |
permissive
|
prathimode/AdvancePhysicsMotion
|
https://github.com/prathimode/AdvancePhysicsMotion
|
275a5ba9583ad5cccf3bf98f994fad876d92385c
|
fe46b161b3ade92f0864b4895aa31c65fa6d6e9f
|
refs/heads/master
| 2020-03-28T14:37:51.867000 | 2018-12-09T19:07:00 | 2018-12-09T19:07:00 | 148,505,964 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.prrathi.Objects;
import com.prrathi.Style.Style;
import lombok.AccessLevel;
import lombok.Data;
import lombok.Getter;
import processing.core.PApplet;
import processing.core.PVector;
@Data
public class Mover{
@Getter(AccessLevel.PRIVATE) PApplet mScene;
PVector accelaration, velocity;
private float mass;
CircularObject object;
public Mover(PApplet scene, float x, float y, float mass)
{
this.mScene = scene;
this.accelaration = new PVector(0,0);
this.velocity = new PVector(0,0);
this.mass = mass;
object = new CircularObject(scene, x,y,mass*20);
object.setStyle(new Style(100.0f,200.0f,1.0f));
}
// update the speed and acceleration. Should be called when update needed in position.
// normally in each draw call
public void update() {
velocity.add(accelaration);
object.position.add(velocity);
accelaration.mult(0);
}
// Check for boundaries so that to update the movement direction
public void checkBoudaries() {
if(object.position.x > mScene.width )
{
object.position.x = mScene.width ;
velocity.x *= -1;
} else if( object.position.x <0 )
{
object.position.x = 0;
velocity.x *=-1;
}
if(object.position.y > mScene.height) {
velocity.y *=-1;
object.position.y = mScene.height;
} else if(object.position.y<0)
{
velocity.y *=-1;
object.position.y =0;
}
}
// Apply Force on the Mover
public void applyForce(PVector f)
{
// System.out.println(f.x +" " + f.y);
accelaration.add(f.div(mass));
}
// Render the mover on the scene
public void render() {
object.render();
}
}
|
UTF-8
|
Java
| 1,836 |
java
|
Mover.java
|
Java
|
[] | null |
[] |
package com.prrathi.Objects;
import com.prrathi.Style.Style;
import lombok.AccessLevel;
import lombok.Data;
import lombok.Getter;
import processing.core.PApplet;
import processing.core.PVector;
@Data
public class Mover{
@Getter(AccessLevel.PRIVATE) PApplet mScene;
PVector accelaration, velocity;
private float mass;
CircularObject object;
public Mover(PApplet scene, float x, float y, float mass)
{
this.mScene = scene;
this.accelaration = new PVector(0,0);
this.velocity = new PVector(0,0);
this.mass = mass;
object = new CircularObject(scene, x,y,mass*20);
object.setStyle(new Style(100.0f,200.0f,1.0f));
}
// update the speed and acceleration. Should be called when update needed in position.
// normally in each draw call
public void update() {
velocity.add(accelaration);
object.position.add(velocity);
accelaration.mult(0);
}
// Check for boundaries so that to update the movement direction
public void checkBoudaries() {
if(object.position.x > mScene.width )
{
object.position.x = mScene.width ;
velocity.x *= -1;
} else if( object.position.x <0 )
{
object.position.x = 0;
velocity.x *=-1;
}
if(object.position.y > mScene.height) {
velocity.y *=-1;
object.position.y = mScene.height;
} else if(object.position.y<0)
{
velocity.y *=-1;
object.position.y =0;
}
}
// Apply Force on the Mover
public void applyForce(PVector f)
{
// System.out.println(f.x +" " + f.y);
accelaration.add(f.div(mass));
}
// Render the mover on the scene
public void render() {
object.render();
}
}
| 1,836 | 0.594771 | 0.581155 | 70 | 25.214285 | 19.174309 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false |
14
|
f828ba22ee081bcdc130dd08b6daff11bef9a1c2
| 29,566,554,931,737 |
c86e6a9e06845a675d0a637d06460797a3707ceb
|
/src/main/java/com/kakaopay/coupon/controller/CouponController.java
|
c4a3eb6d497dc2183571bd40d5671ea8ce44c99b
|
[] |
no_license
|
donghak0205/coupon
|
https://github.com/donghak0205/coupon
|
73ffe4502d9fa7903aea37b5454b2b53f37c1fc3
|
7e4ffadbc086feadac2a5202186626c19ae69c8c
|
refs/heads/main
| 2023-02-17T08:21:12.851000 | 2021-01-20T12:53:53 | 2021-01-20T12:53:53 | 331,306,618 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.kakaopay.coupon.controller;
import com.kakaopay.coupon.aop.LogExecutionTime;
import com.kakaopay.coupon.domain.CouponResponse;
import com.kakaopay.coupon.domain.User;
import com.kakaopay.coupon.network.Header;
import com.kakaopay.coupon.service.CouponService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import static org.springframework.http.ResponseEntity.ok;
@RequestMapping("/coupon")
@RestController
public class CouponController {
private final CouponService couponService;
@Autowired
public CouponController(CouponService couponService) {
this.couponService = couponService;
}
/**
* 1. 쿠폰생성
*/
@PostMapping("/create/{num}")
@LogExecutionTime
public ResponseEntity<Header<String>> createCoupon(Authentication auth, @PathVariable Long num) {
User user = (User) auth.getPrincipal();
if(num>0) {
return ok().body(Header.OK(couponService.create(user, num)));
} else {
return ok().body(Header.ERROR("1이상 숫자를 입력해주세요!"));
}
}
/**
* 2. 생성된 쿠폰중 지급하기
* @return
*/
@PostMapping("/pay")
public Mono<Header<String>> payCoupon(Authentication auth) {
UserDetails user = (UserDetails) auth.getPrincipal();
Flux<CouponResponse> selectedFlux = couponService.selectCoupon(user.getUsername());
if(selectedFlux.count().block()>0){
return selectedFlux.filter(f->f.getCouponPay().equals(false))
.flatMap(fm->Mono.just(fm)).next()
.map(m->{
couponService.update(user.getUsername(), m, true, false);
return Header.OK(m.getCouponCode());
}
).defaultIfEmpty(Header.ERROR(user.getUsername() + "님은 생성된 쿠폰을 다 사용하셨습니다. 생성 후 지급해주세요.")).log();
} else {
return Mono.just(Header.ERROR(user.getUsername() + "님의 생성된 쿠폰이 없습니다. 확인바랍니다."));
}
/*
원래 소스
StringBuilder sb = new StringBuilder();
//selectedFlux.filter(f-> f.getCouponPay().equals(false)).map(m->m.getCouponCode());
selectedFlux.filter(f->f.getCouponPay().equals(false));
return selectedFlux.map(m->{
if(m.getCouponPay().equals(false)) {
couponService.update(user.getUsername(), m, true, false);
return m.getCouponCode();
}
else {
return "생성된 쿠폰을 다 사용하셨습니다. 확인바랍니다.";
}
}).map(n->Header.OK(n)).defaultIfEmpty(Header.ERROR("생성된 쿠폰이 없습니다. 확인바랍니다."));*/
}
/**
* 3. 지급된 쿠폰 조회
*/
@GetMapping("/selectPay")
public Flux<Header<String>> selectPayCoupon(Authentication auth) {
UserDetails user = (UserDetails) auth.getPrincipal();
Flux<CouponResponse> selectFlux = couponService.selectCoupon(user.getUsername(), true, false).log();
return selectFlux.map(n -> n.getCouponCode()).map(m->Header.OK(m)).defaultIfEmpty(Header.ERROR("지급된 쿠폰이 없습니다. 확인바랍니다."));
}
/**
* 4. (지급된 쿠폰) 사용하기
*/
@PostMapping("/use/{couponCode}")
public Mono<Header<String>> useCoupon(Authentication auth, @PathVariable String couponCode) {
UserDetails user = (UserDetails) auth.getPrincipal();
if(couponCode.length()!=36) {
return Mono.just(Header.ERROR("쿠폰코드 자리수가 틀렸습니다. 확인바랍니다."));
}
Mono<CouponResponse> selectedMono = couponService.selectCouponCode(couponCode);
return selectedMono.map(i -> {
if(!i.getCreatedUserId().equals(user.getUsername())){
return Header.OK("쿠폰코드는 발급한 사용자만 사용할 수 있습니다. 확인바랍니다.");
}
else if(i.getCouponPay()==false){
return Header.OK("아직 지급이 안된 쿠폰입니다. 확인바랍니다.");
}
else{
if(i.getCouponUse() ==false) {
couponService.update(user.getUsername(), i, true, true);
return Header.OK("쿠폰코드 : " + i.getCouponCode() + " 을 사용하였습니다.");
}
return Header.OK("사용된 쿠폰입니다. 확인바랍니다.");
}
}).defaultIfEmpty(Header.ERROR("존재하지 않는 쿠폰코드 입니다. 확인바랍니다."));
}
/**
* 5. 사용한 쿠폰 취소하기
*/
@PostMapping("/cancelUse/{couponCode}")
public Mono<Header<String>> cancelUseCoupon(Authentication auth, @PathVariable String couponCode) {
UserDetails user = (UserDetails) auth.getPrincipal();
if(couponCode.length()!=36) {
return Mono.just(Header.ERROR("쿠폰코드 자리수가 틀렸습니다. 확인바랍니다."));
}
Mono<CouponResponse> selectedMono = couponService.selectCouponCode(couponCode);
return selectedMono.map(i -> {
if(!i.getCreatedUserId().equals(user.getUsername())){
return Header.OK("쿠폰코드는 발급한 사용자만 취소할 수 있습니다. 확인바랍니다.");
}
else if(i.getCouponPay()==false){
return Header.OK("아직 지급이 안된 쿠폰입니다. 확인바랍니다.");
}
else{
if(i.getCouponUse() ==true) {
couponService.update(user.getUsername(), i, true, false);
return Header.OK("쿠폰코드 : " + i.getCouponCode() + " 을 사용 취소하였습니다.");
}
return Header.OK("사용된 쿠폰이 아닙니다. 확인바랍니다.");
}
}).defaultIfEmpty(Header.ERROR("존재하지 않는 쿠폰코드 입니다. 확인바랍니다."));
}
/**
* 6. 당일 만료된 쿠폰 조회
*/
@GetMapping("/selectExpireToday")
public Flux<Header<String>> selectExpireToday(Authentication auth) {
UserDetails user = (UserDetails) auth.getPrincipal();
Flux<CouponResponse> selectFlux = couponService.selectExpireToday(user.getUsername()).log();
return selectFlux.map(n -> Header.OK(n.getCouponCode())).defaultIfEmpty(Header.ERROR("더 이상 받아갈 쿠폰이 없습니다. 확인바랍니다."));
}
}
|
UTF-8
|
Java
| 7,105 |
java
|
CouponController.java
|
Java
|
[
{
"context": "defaultIfEmpty(Header.ERROR(user.getUsername() + \"님은 생성된 쿠폰을 다 사용하셨습니다. 생성 후 지급해주세요.\")).log();\n ",
"end": 2134,
"score": 0.7950204610824585,
"start": 2133,
"tag": "NAME",
"value": "님"
},
{
"context": "turn Mono.just(Header.ERROR(user.getUsername() + \"님의 생성된 쿠폰이 없습니다. 확인바랍니다.\"));\n }\n\n\n\n /*\n",
"end": 2260,
"score": 0.7324099540710449,
"start": 2259,
"tag": "NAME",
"value": "님"
},
{
"context": ") {\n couponService.update(user.getUsername(), i, true, false);\n return He",
"end": 5586,
"score": 0.9726581573486328,
"start": 5575,
"tag": "USERNAME",
"value": "getUsername"
}
] | null |
[] |
package com.kakaopay.coupon.controller;
import com.kakaopay.coupon.aop.LogExecutionTime;
import com.kakaopay.coupon.domain.CouponResponse;
import com.kakaopay.coupon.domain.User;
import com.kakaopay.coupon.network.Header;
import com.kakaopay.coupon.service.CouponService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import static org.springframework.http.ResponseEntity.ok;
@RequestMapping("/coupon")
@RestController
public class CouponController {
private final CouponService couponService;
@Autowired
public CouponController(CouponService couponService) {
this.couponService = couponService;
}
/**
* 1. 쿠폰생성
*/
@PostMapping("/create/{num}")
@LogExecutionTime
public ResponseEntity<Header<String>> createCoupon(Authentication auth, @PathVariable Long num) {
User user = (User) auth.getPrincipal();
if(num>0) {
return ok().body(Header.OK(couponService.create(user, num)));
} else {
return ok().body(Header.ERROR("1이상 숫자를 입력해주세요!"));
}
}
/**
* 2. 생성된 쿠폰중 지급하기
* @return
*/
@PostMapping("/pay")
public Mono<Header<String>> payCoupon(Authentication auth) {
UserDetails user = (UserDetails) auth.getPrincipal();
Flux<CouponResponse> selectedFlux = couponService.selectCoupon(user.getUsername());
if(selectedFlux.count().block()>0){
return selectedFlux.filter(f->f.getCouponPay().equals(false))
.flatMap(fm->Mono.just(fm)).next()
.map(m->{
couponService.update(user.getUsername(), m, true, false);
return Header.OK(m.getCouponCode());
}
).defaultIfEmpty(Header.ERROR(user.getUsername() + "님은 생성된 쿠폰을 다 사용하셨습니다. 생성 후 지급해주세요.")).log();
} else {
return Mono.just(Header.ERROR(user.getUsername() + "님의 생성된 쿠폰이 없습니다. 확인바랍니다."));
}
/*
원래 소스
StringBuilder sb = new StringBuilder();
//selectedFlux.filter(f-> f.getCouponPay().equals(false)).map(m->m.getCouponCode());
selectedFlux.filter(f->f.getCouponPay().equals(false));
return selectedFlux.map(m->{
if(m.getCouponPay().equals(false)) {
couponService.update(user.getUsername(), m, true, false);
return m.getCouponCode();
}
else {
return "생성된 쿠폰을 다 사용하셨습니다. 확인바랍니다.";
}
}).map(n->Header.OK(n)).defaultIfEmpty(Header.ERROR("생성된 쿠폰이 없습니다. 확인바랍니다."));*/
}
/**
* 3. 지급된 쿠폰 조회
*/
@GetMapping("/selectPay")
public Flux<Header<String>> selectPayCoupon(Authentication auth) {
UserDetails user = (UserDetails) auth.getPrincipal();
Flux<CouponResponse> selectFlux = couponService.selectCoupon(user.getUsername(), true, false).log();
return selectFlux.map(n -> n.getCouponCode()).map(m->Header.OK(m)).defaultIfEmpty(Header.ERROR("지급된 쿠폰이 없습니다. 확인바랍니다."));
}
/**
* 4. (지급된 쿠폰) 사용하기
*/
@PostMapping("/use/{couponCode}")
public Mono<Header<String>> useCoupon(Authentication auth, @PathVariable String couponCode) {
UserDetails user = (UserDetails) auth.getPrincipal();
if(couponCode.length()!=36) {
return Mono.just(Header.ERROR("쿠폰코드 자리수가 틀렸습니다. 확인바랍니다."));
}
Mono<CouponResponse> selectedMono = couponService.selectCouponCode(couponCode);
return selectedMono.map(i -> {
if(!i.getCreatedUserId().equals(user.getUsername())){
return Header.OK("쿠폰코드는 발급한 사용자만 사용할 수 있습니다. 확인바랍니다.");
}
else if(i.getCouponPay()==false){
return Header.OK("아직 지급이 안된 쿠폰입니다. 확인바랍니다.");
}
else{
if(i.getCouponUse() ==false) {
couponService.update(user.getUsername(), i, true, true);
return Header.OK("쿠폰코드 : " + i.getCouponCode() + " 을 사용하였습니다.");
}
return Header.OK("사용된 쿠폰입니다. 확인바랍니다.");
}
}).defaultIfEmpty(Header.ERROR("존재하지 않는 쿠폰코드 입니다. 확인바랍니다."));
}
/**
* 5. 사용한 쿠폰 취소하기
*/
@PostMapping("/cancelUse/{couponCode}")
public Mono<Header<String>> cancelUseCoupon(Authentication auth, @PathVariable String couponCode) {
UserDetails user = (UserDetails) auth.getPrincipal();
if(couponCode.length()!=36) {
return Mono.just(Header.ERROR("쿠폰코드 자리수가 틀렸습니다. 확인바랍니다."));
}
Mono<CouponResponse> selectedMono = couponService.selectCouponCode(couponCode);
return selectedMono.map(i -> {
if(!i.getCreatedUserId().equals(user.getUsername())){
return Header.OK("쿠폰코드는 발급한 사용자만 취소할 수 있습니다. 확인바랍니다.");
}
else if(i.getCouponPay()==false){
return Header.OK("아직 지급이 안된 쿠폰입니다. 확인바랍니다.");
}
else{
if(i.getCouponUse() ==true) {
couponService.update(user.getUsername(), i, true, false);
return Header.OK("쿠폰코드 : " + i.getCouponCode() + " 을 사용 취소하였습니다.");
}
return Header.OK("사용된 쿠폰이 아닙니다. 확인바랍니다.");
}
}).defaultIfEmpty(Header.ERROR("존재하지 않는 쿠폰코드 입니다. 확인바랍니다."));
}
/**
* 6. 당일 만료된 쿠폰 조회
*/
@GetMapping("/selectExpireToday")
public Flux<Header<String>> selectExpireToday(Authentication auth) {
UserDetails user = (UserDetails) auth.getPrincipal();
Flux<CouponResponse> selectFlux = couponService.selectExpireToday(user.getUsername()).log();
return selectFlux.map(n -> Header.OK(n.getCouponCode())).defaultIfEmpty(Header.ERROR("더 이상 받아갈 쿠폰이 없습니다. 확인바랍니다."));
}
}
| 7,105 | 0.585644 | 0.583584 | 181 | 33.867405 | 32.519169 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.40884 | false | false |
14
|
df8dbb230948d5f3d0a596309b559286c0ac384d
| 6,828,998,022,379 |
8becb26a281bb9e3f0ecfe3ee0d99b8c21e48274
|
/src/taeha/wheelloader/fseries_monitor/menu/monitoring/VersionInfoRMCUFragment.java
|
18fe6999c6d8bf46c1d83e526137ff89995e3775
|
[] |
no_license
|
Itgunny/ECS_MS12_02_WLF_MONITOR_Android_APP
|
https://github.com/Itgunny/ECS_MS12_02_WLF_MONITOR_Android_APP
|
74f0afc2b15768cd6acf3b88c80afd04cec69656
|
faf5fc00cf5565b21c1af2682ca836251fc82257
|
refs/heads/master
| 2020-03-21T13:38:27.577000 | 2018-01-09T07:57:09 | 2018-01-09T07:57:09 | 138,617,293 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package taeha.wheelloader.fseries_monitor.menu.monitoring;
import customlist.sensormonitoring.IconTextItem;
import customlist.versiondetail.IconTextItemVersion;
import taeha.wheelloader.fseries_monitor.main.R;
import taeha.wheelloader.fseries_monitor.main.R.string;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class VersionInfoRMCUFragment extends VersionInfoDetailFragment{
/////////////////CONSTANT////////////////////////////////////////////
protected static final int STATE_SERIALNUMBER = 0;
protected static final int STATE_MAKER = 1;
protected static final int STATE_VERSION = 2;
private static final int STATE_NETWORKTYPE = 3;
private static final int STATE_NUMOFDATA = 4;
private static final int STATE_BACKUPBATTERYVOLT = 5;
private static final int STATE_COMMSTATUS = 6;
private static final int STATE_NETWORKSERVICE = 7;
private static final int STATE_COMMANTENNA = 8;
private static final int STATE_GPSANTENNA = 9;
private static final int STATE_POSITIONUPDATE = 10;
private static final int STATE_GUARD = 11;
private static final int STATE_LOCKLEVEL = 12;
private static final int STATE_DISABLE = 0;
private static final int STATE_ENABLE = 1;
private static final int STATE_NOTAVAILABLE = 3;
private static final int STATE_RMCUNETWORKTYPE_NETWORK1_GSM = 0;
private static final int STATE_RMCUNETWORKTYPE_NETWORK1_CDMA = 1;
private static final int STATE_RMCUNETWORKTYPE_NETWORK1_3G = 2;
private static final int STATE_RMCUNETWORKTYPE_NETWORK1_WIFI = 3;
private static final int STATE_RMCUNETWORKTYPE_NETWORK1_ORBCOMM = 4;
private static final int STATE_RMCUNETWORKTYPE_NETWORK12_3G_ORBCOMM = 20;
private static final int STATE_RMCUNETWORKTYPE_NETWORK12_ORBCOMM_3G = 21;
private static final int STATE_RMCUNETWORKTYPE_NETWORK12_3G_WIFI = 22;
private static final int STATE_RMCUNETWORKTYPE_NETWORK12_WIFI_3G = 23;
private static final int STATE_RMCUNETWORKTYPE_NETWORK12_2G_3G = 24;
private static final int STATE_RMCUNETWORKTYPE_NETWORK12_3G_2G = 25;
private static final int STATE_RMCUNETWORKTYPE_NOTAVAILABLE = 255;
private static final int STATE_MACHINEPOSITIONSTATUS_INSIDE = 0;
private static final int STATE_MACHINEPOSITIONSTATUS_OUTSIDE = 1;
private static final int STATE_MACHINEPOSITIONSTATUS_NOTAVAILABLE = 3;
private static final int STATE_GPSANTENNA_NORMAL = 0;
private static final int STATE_GPSANTENNA_ABNORMAL = 1;
private static final int STATE_GPSANTENNA_NOTAVAILABLE = 3;
private static final int STATE_NETWORKSERVICESTATUS_LOCALSERVICE = 0;
private static final int STATE_NETWORKSERVICESTATUS_ROAMINGSERVICE = 1;
private static final int STATE_NETWORKSERVICESTATUS_SERVICENOTAVAILABLE = 2;
private static final int STATE_NETWORKSERVICESTATUS_NOTAUTHORIZEDSERVICE = 3;
private static final int STATE_NETWORKSERVICESTATUS_NOTAVAILABLE = 255;
private static final int STATE_NETWORKANTENNASTATUS_OFF = 0;
private static final int STATE_NETWORKANTENNASTATUS_MAIN_ON = 1;
private static final int STATE_NETWORKANTENNASTATUS_EMERGENCY_ON = 2;
private static final int STATE_NETWORKANTENNASTATUS_NOTAVAILABLE = 255;
private static final int STATE_LOCKLEVEL_UNLOCK = 0;
/////////////////////////////////////////////////////////////////////
/////////////////////VALUABLE////////////////////////////////////////
int RMCUNetworkType;
int RMCUBackupBatteryVolt;
int RMCUPowerSource;
int RMCUBoxOpeningStatus;
int NetworkCommStatus1;
int PositionUpdateStatus;
int MachinePositionStatus;
int GPSAntennaConnectionAlarmStatus;
int NetworkTransceiverStatus1;
int NetworkServiceStatus1;
int NetworkAntennaStatus1;
int RMCUData;
int LockLevel;
/////////////////////////////////////////////////////////////////////
//Life Cycle Function/////////////////////////////
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreateView(inflater, container, savedInstanceState);
TAG = "VersionInfoRMCUFragment";
Log.d(TAG, "onCreateView");
ParentActivity.ScreenIndex = ParentActivity.SCREEN_STATE_MENU_MONITORING_VERSIONINFO_RMCU;
ParentActivity._MenuBaseFragment._MenuInterTitleFragment.SetTitleText(ParentActivity.getResources().getString(R.string.Machine_Information)
+ " - " + ParentActivity.getResources().getString(R.string.RMCU), 318, 271);
return mRoot;
}
@Override
protected void InitValuables(){
super.InitValuables();
RMCUNetworkType = STATE_RMCUNETWORKTYPE_NOTAVAILABLE;
RMCUBackupBatteryVolt = 0;
RMCUPowerSource = 0;
RMCUBoxOpeningStatus = 0;
NetworkCommStatus1 = STATE_NOTAVAILABLE;
PositionUpdateStatus = 0;
MachinePositionStatus = STATE_MACHINEPOSITIONSTATUS_NOTAVAILABLE;
GPSAntennaConnectionAlarmStatus = STATE_GPSANTENNA_NOTAVAILABLE;
NetworkTransceiverStatus1 = 0;
NetworkServiceStatus1 = STATE_NETWORKSERVICESTATUS_NOTAVAILABLE;
NetworkAntennaStatus1 = STATE_NETWORKANTENNASTATUS_NOTAVAILABLE;
RMCUData = 0;
LockLevel = STATE_LOCKLEVEL_UNLOCK;
// adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_dark),null,
// ParentActivity.getResources().getString(string.Serial_Number),"" , ""));
// adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_light),null,
// ParentActivity.getResources().getString(string.Manufacturer),"" , ""));
// adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_dark),null,
// ParentActivity.getResources().getString(string.Program_Version),"" , ""));
// adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_light),null,
// ParentActivity.getResources().getString(string.Network_Type),"" , ""));
// adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_dark),null,
// ParentActivity.getResources().getString(string.Number_of_Messages_to_Transmit),"" , ""));
// adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_light),null,
// ParentActivity.getResources().getString(string.Back_up_Battery_Voltage),"" , ""));
// adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_dark),null,
// ParentActivity.getResources().getString(string.Network_Communication_Status),"" , ""));
// adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_light),null,
// ParentActivity.getResources().getString(string.Network_Service),"" , ""));
// adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_dark),null,
// ParentActivity.getResources().getString(string.Communication_Antenna),"" , ""));
// adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_light),null,
// ParentActivity.getResources().getString(string.GPS_Antenna),"" , ""));
// adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_dark),null,
// ParentActivity.getResources().getString(string.Position_Update),"" , ""));
// adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_light),null,
// ParentActivity.getResources().getString(string.Outside_of_Boundary),"" , ""));
// adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_dark),null,
// ParentActivity.getResources().getString(string.Lock_Level),"" , ""));
adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_dark),null,
getString(ParentActivity.getResources().getString(string.Program_Version), 277),"" , ""));
adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_light),null,
getString(ParentActivity.getResources().getString(string.Serial_Number), 278),"" , ""));
listView.setAdapter(adapter);
}
@Override
public void ShowHiddenPage(){
adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_dark),null,
getString(ParentActivity.getResources().getString(string.Manufacturer), 279),"" , ""));
adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_light),null,
getString(ParentActivity.getResources().getString(string.Network_Type), 275),"" , ""));
adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_dark),null,
getString(ParentActivity.getResources().getString(string.Number_of_Messages_to_Transmit), 280),"" , ""));
adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_light),null,
getString(ParentActivity.getResources().getString(string.Back_up_Battery_Voltage), 281),"" , ""));
adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_dark),null,
getString(ParentActivity.getResources().getString(string.Network_Communication_Status), 282),"" , ""));
adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_light),null,
getString(ParentActivity.getResources().getString(string.Network_Service), 283), "" , ""));
adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_dark),null,
getString(ParentActivity.getResources().getString(string.Communication_Antenna), 284),"" , ""));
adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_light),null,
getString(ParentActivity.getResources().getString(string.GPS_Antenna), 285),"" , ""));
adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_dark),null,
getString(ParentActivity.getResources().getString(string.Position_Update), 286),"" , ""));
adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_light),null,
getString(ParentActivity.getResources().getString(string.Outside_of_Boundary), 287),"" , ""));
adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_dark),null,
getString(ParentActivity.getResources().getString(string.Lock_Level),288) ,"" , ""));
}
@Override
protected void GetDataFromNative() {
// TODO Auto-generated method stub
ComponentCode = CAN1Comm.Get_ComponentCode_1699_PGN65330_RMCU();
ComponentBasicInformation = CAN1Comm.Get_ComponentBasicInformation_1698_PGN65330_RMCU();
if(ManufactureDayDisplayFlag == true)
{
ManufacturerCode = CAN1Comm.Get_ManufacturerCode_1700_PGN65330_RMCU();
RMCUNetworkType = CAN1Comm.Get_RMCUNetworkType_1621_PGN65329();
RMCUBackupBatteryVolt = CAN1Comm.Get_RMCUBackupBatteryVoltage_1590_PGN65329();
RMCUPowerSource = CAN1Comm.Get_RMCUPowerSource_1594_PGN65329();
RMCUBoxOpeningStatus = CAN1Comm.Get_RMCUBoxOpeningStatus_PGN65329();
NetworkCommStatus1 = CAN1Comm.Get_NetworkCommunicationStatus1_1622_PGN65329();
PositionUpdateStatus = CAN1Comm.Get_PositionUpdateStatus_852_PGN65329();
MachinePositionStatus = CAN1Comm.Get_MachinePositionStatus_1593_PGN65329();
GPSAntennaConnectionAlarmStatus = CAN1Comm.Get_GPSAntennaConnectionAlarmStatus_1595_PGN65329();
NetworkTransceiverStatus1 = CAN1Comm.Get_NetworkTransceiverStatus1_1623_PGN65329();
NetworkServiceStatus1 = CAN1Comm.Get_NetworkServiceStatus1_1624_PGN65329();
NetworkAntennaStatus1 = CAN1Comm.Get_NetworkAntennaStatus1_1625_PGN65329();
RMCUData = CAN1Comm.Get_RMCUData_NumberofMessagestoTransmit_855_PGN65329();
LockLevel = CAN1Comm.Get_LockLevel_823_PGN65348();
}
ProgramSubVersion = ParentActivity.FindProgramSubInfo(ComponentBasicInformation);
}
@Override
protected void UpdateUI() {
// TODO Auto-generated method stub
ManufactureDayDisplay(ComponentBasicInformation);
ModelDisplay(ComponentBasicInformation);
if(ManufactureDayDisplayFlag == true)
VersionDisplayHidden(ComponentBasicInformation,ProgramSubVersion);
else
VersionDisplay(ComponentBasicInformation,ProgramSubVersion);
SerialNumberDisplay(ComponentBasicInformation);
if(ManufactureDayDisplayFlag == true)
{
ManufacturerDisplay(ManufacturerCode);
NetworkTypeDisplay(RMCUNetworkType);
NumofDataDisplay(RMCUData);
BackupBatteryVoltDisplay(RMCUBackupBatteryVolt);
CommStatusDisplay(NetworkCommStatus1);
NetworkServiceDisplay(NetworkServiceStatus1);
NetworkAntennaDisplay(NetworkAntennaStatus1);
GPSAntennaDisplay(GPSAntennaConnectionAlarmStatus);
PositionUpdateDisplay(PositionUpdateStatus);
GuardDisplay(MachinePositionStatus);
LockLevelDisplay(LockLevel);
}
adapter.notifyDataSetChanged();
}
////////////////////////////////////////////////
public void NetworkTypeDisplay(int NetworkType){
switch (NetworkType) {
case STATE_RMCUNETWORKTYPE_NETWORK1_GSM:
adapter.UpdateSecond(STATE_NETWORKTYPE, "2G (GSM)");
break;
case STATE_RMCUNETWORKTYPE_NETWORK1_CDMA:
adapter.UpdateSecond(STATE_NETWORKTYPE, "2G (CDMA)");
break;
case STATE_RMCUNETWORKTYPE_NETWORK1_3G:
adapter.UpdateSecond(STATE_NETWORKTYPE, "3G");
break;
case STATE_RMCUNETWORKTYPE_NETWORK1_WIFI:
adapter.UpdateSecond(STATE_NETWORKTYPE, "WiFi");
break;
case STATE_RMCUNETWORKTYPE_NETWORK1_ORBCOMM:
adapter.UpdateSecond(STATE_NETWORKTYPE, "Orbcomm");
break;
case STATE_RMCUNETWORKTYPE_NETWORK12_3G_ORBCOMM:
adapter.UpdateSecond(STATE_NETWORKTYPE, "Network 1 : 3G & Network 2 : Orbcomm");
break;
case STATE_RMCUNETWORKTYPE_NETWORK12_ORBCOMM_3G:
adapter.UpdateSecond(STATE_NETWORKTYPE, "Network 1 : Orbcomm & Network 2 : 3G");
break;
case STATE_RMCUNETWORKTYPE_NETWORK12_3G_WIFI:
adapter.UpdateSecond(STATE_NETWORKTYPE, "Network 1 : 3G & Network 2 : WiFi");
break;
case STATE_RMCUNETWORKTYPE_NETWORK12_WIFI_3G:
adapter.UpdateSecond(STATE_NETWORKTYPE, "Network 1 : WiFi & Network 2 : 3G");
break;
case STATE_RMCUNETWORKTYPE_NETWORK12_2G_3G:
adapter.UpdateSecond(STATE_NETWORKTYPE, "Network 1 : 2G & Network 2 : 3G");
break;
case STATE_RMCUNETWORKTYPE_NETWORK12_3G_2G:
adapter.UpdateSecond(STATE_NETWORKTYPE, "Network 1 : 3G & Network 2 : 2G");
break;
case STATE_RMCUNETWORKTYPE_NOTAVAILABLE:
adapter.UpdateSecond(STATE_NETWORKTYPE, "-");
break;
default:
break;
}
}
public void NumofDataDisplay(int NumofData){
if(NumofData > 250){
adapter.UpdateSecond(STATE_NUMOFDATA, "-");
}else{
adapter.UpdateSecond(STATE_NUMOFDATA, Integer.toString(NumofData));
}
}
public void BackupBatteryVoltDisplay(int BatteryVolt){
float fBattery;
fBattery = (float)(BatteryVolt / 10.0);
if(BatteryVolt > 250){
adapter.UpdateSecond(STATE_BACKUPBATTERYVOLT, "-");
}else{
adapter.UpdateSecond(STATE_BACKUPBATTERYVOLT, Float.toString(fBattery) + " V");
}
}
public void CommStatusDisplay(int CommStatus){
switch (CommStatus) {
case STATE_DISABLE:
adapter.UpdateSecond(STATE_COMMSTATUS, "Disable");
break;
case STATE_ENABLE:
adapter.UpdateSecond(STATE_COMMSTATUS, "Enable");
break;
case STATE_NOTAVAILABLE:
adapter.UpdateSecond(STATE_COMMSTATUS, "-");
break;
default:
break;
}
}
public void NetworkServiceDisplay(int NetworkService){
switch (NetworkService) {
case STATE_NETWORKSERVICESTATUS_LOCALSERVICE:
adapter.UpdateSecond(STATE_NETWORKSERVICE, "Local");
break;
case STATE_NETWORKSERVICESTATUS_ROAMINGSERVICE:
adapter.UpdateSecond(STATE_NETWORKSERVICE, "Roaming");
break;
case STATE_NETWORKSERVICESTATUS_SERVICENOTAVAILABLE:
adapter.UpdateSecond(STATE_NETWORKSERVICE, "Service Not Available");
break;
case STATE_NETWORKSERVICESTATUS_NOTAUTHORIZEDSERVICE:
adapter.UpdateSecond(STATE_NETWORKSERVICE, "Not Authorized to Operate on Service");
break;
case STATE_NETWORKSERVICESTATUS_NOTAVAILABLE:
adapter.UpdateSecond(STATE_NETWORKSERVICE, "-");
break;
default:
break;
}
}
public void NetworkAntennaDisplay(int Antenna){
switch (Antenna) {
case STATE_NETWORKANTENNASTATUS_OFF:
adapter.UpdateSecond(STATE_COMMANTENNA, "Off");
break;
case STATE_NETWORKANTENNASTATUS_MAIN_ON:
adapter.UpdateSecond(STATE_COMMANTENNA, "Main On");
break;
case STATE_NETWORKANTENNASTATUS_EMERGENCY_ON:
adapter.UpdateSecond(STATE_COMMANTENNA, "Emergency On");
break;
case STATE_NETWORKANTENNASTATUS_NOTAVAILABLE:
adapter.UpdateSecond(STATE_COMMANTENNA, "-");
break;
default:
break;
}
}
public void GPSAntennaDisplay(int Antenna){
switch (Antenna) {
case STATE_GPSANTENNA_NORMAL:
adapter.UpdateSecond(STATE_GPSANTENNA, "Normal");
break;
case STATE_GPSANTENNA_ABNORMAL:
adapter.UpdateSecond(STATE_GPSANTENNA, "Abnormal");
break;
case STATE_GPSANTENNA_NOTAVAILABLE:
adapter.UpdateSecond(STATE_GPSANTENNA, "-");
break;
default:
break;
}
}
public void PositionUpdateDisplay(int PositionUpdate){
switch (PositionUpdate) {
case 0:
adapter.UpdateSecond(STATE_POSITIONUPDATE, "Not OK");
break;
case 1:
adapter.UpdateSecond(STATE_POSITIONUPDATE, "OK");
break;
case 3:
adapter.UpdateSecond(STATE_POSITIONUPDATE, "-");
break;
default:
break;
}
}
public void GuardDisplay(int Guard){
switch (Guard) {
case STATE_MACHINEPOSITIONSTATUS_INSIDE:
adapter.UpdateSecond(STATE_GUARD, "Inside of boundary");
break;
case STATE_MACHINEPOSITIONSTATUS_OUTSIDE:
adapter.UpdateSecond(STATE_GUARD, "Outside of boundary");
break;
case STATE_MACHINEPOSITIONSTATUS_NOTAVAILABLE:
adapter.UpdateSecond(STATE_GUARD, "-");
break;
default:
break;
}
}
public void LockLevelDisplay(int LockLevel){
switch (LockLevel) {
case STATE_LOCKLEVEL_UNLOCK:
adapter.UpdateSecond(STATE_LOCKLEVEL, "Unlock");
break;
case 1:
adapter.UpdateSecond(STATE_LOCKLEVEL, "Level 1");
break;
case 2:
adapter.UpdateSecond(STATE_LOCKLEVEL, "Level 2");
break;
default:
adapter.UpdateSecond(STATE_LOCKLEVEL, "-");
break;
}
}
////////////////////////////////////////////////
////////////////////////////////////////////////
}
|
UTF-8
|
Java
| 19,458 |
java
|
VersionInfoRMCUFragment.java
|
Java
|
[] | null |
[] |
package taeha.wheelloader.fseries_monitor.menu.monitoring;
import customlist.sensormonitoring.IconTextItem;
import customlist.versiondetail.IconTextItemVersion;
import taeha.wheelloader.fseries_monitor.main.R;
import taeha.wheelloader.fseries_monitor.main.R.string;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class VersionInfoRMCUFragment extends VersionInfoDetailFragment{
/////////////////CONSTANT////////////////////////////////////////////
protected static final int STATE_SERIALNUMBER = 0;
protected static final int STATE_MAKER = 1;
protected static final int STATE_VERSION = 2;
private static final int STATE_NETWORKTYPE = 3;
private static final int STATE_NUMOFDATA = 4;
private static final int STATE_BACKUPBATTERYVOLT = 5;
private static final int STATE_COMMSTATUS = 6;
private static final int STATE_NETWORKSERVICE = 7;
private static final int STATE_COMMANTENNA = 8;
private static final int STATE_GPSANTENNA = 9;
private static final int STATE_POSITIONUPDATE = 10;
private static final int STATE_GUARD = 11;
private static final int STATE_LOCKLEVEL = 12;
private static final int STATE_DISABLE = 0;
private static final int STATE_ENABLE = 1;
private static final int STATE_NOTAVAILABLE = 3;
private static final int STATE_RMCUNETWORKTYPE_NETWORK1_GSM = 0;
private static final int STATE_RMCUNETWORKTYPE_NETWORK1_CDMA = 1;
private static final int STATE_RMCUNETWORKTYPE_NETWORK1_3G = 2;
private static final int STATE_RMCUNETWORKTYPE_NETWORK1_WIFI = 3;
private static final int STATE_RMCUNETWORKTYPE_NETWORK1_ORBCOMM = 4;
private static final int STATE_RMCUNETWORKTYPE_NETWORK12_3G_ORBCOMM = 20;
private static final int STATE_RMCUNETWORKTYPE_NETWORK12_ORBCOMM_3G = 21;
private static final int STATE_RMCUNETWORKTYPE_NETWORK12_3G_WIFI = 22;
private static final int STATE_RMCUNETWORKTYPE_NETWORK12_WIFI_3G = 23;
private static final int STATE_RMCUNETWORKTYPE_NETWORK12_2G_3G = 24;
private static final int STATE_RMCUNETWORKTYPE_NETWORK12_3G_2G = 25;
private static final int STATE_RMCUNETWORKTYPE_NOTAVAILABLE = 255;
private static final int STATE_MACHINEPOSITIONSTATUS_INSIDE = 0;
private static final int STATE_MACHINEPOSITIONSTATUS_OUTSIDE = 1;
private static final int STATE_MACHINEPOSITIONSTATUS_NOTAVAILABLE = 3;
private static final int STATE_GPSANTENNA_NORMAL = 0;
private static final int STATE_GPSANTENNA_ABNORMAL = 1;
private static final int STATE_GPSANTENNA_NOTAVAILABLE = 3;
private static final int STATE_NETWORKSERVICESTATUS_LOCALSERVICE = 0;
private static final int STATE_NETWORKSERVICESTATUS_ROAMINGSERVICE = 1;
private static final int STATE_NETWORKSERVICESTATUS_SERVICENOTAVAILABLE = 2;
private static final int STATE_NETWORKSERVICESTATUS_NOTAUTHORIZEDSERVICE = 3;
private static final int STATE_NETWORKSERVICESTATUS_NOTAVAILABLE = 255;
private static final int STATE_NETWORKANTENNASTATUS_OFF = 0;
private static final int STATE_NETWORKANTENNASTATUS_MAIN_ON = 1;
private static final int STATE_NETWORKANTENNASTATUS_EMERGENCY_ON = 2;
private static final int STATE_NETWORKANTENNASTATUS_NOTAVAILABLE = 255;
private static final int STATE_LOCKLEVEL_UNLOCK = 0;
/////////////////////////////////////////////////////////////////////
/////////////////////VALUABLE////////////////////////////////////////
int RMCUNetworkType;
int RMCUBackupBatteryVolt;
int RMCUPowerSource;
int RMCUBoxOpeningStatus;
int NetworkCommStatus1;
int PositionUpdateStatus;
int MachinePositionStatus;
int GPSAntennaConnectionAlarmStatus;
int NetworkTransceiverStatus1;
int NetworkServiceStatus1;
int NetworkAntennaStatus1;
int RMCUData;
int LockLevel;
/////////////////////////////////////////////////////////////////////
//Life Cycle Function/////////////////////////////
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreateView(inflater, container, savedInstanceState);
TAG = "VersionInfoRMCUFragment";
Log.d(TAG, "onCreateView");
ParentActivity.ScreenIndex = ParentActivity.SCREEN_STATE_MENU_MONITORING_VERSIONINFO_RMCU;
ParentActivity._MenuBaseFragment._MenuInterTitleFragment.SetTitleText(ParentActivity.getResources().getString(R.string.Machine_Information)
+ " - " + ParentActivity.getResources().getString(R.string.RMCU), 318, 271);
return mRoot;
}
@Override
protected void InitValuables(){
super.InitValuables();
RMCUNetworkType = STATE_RMCUNETWORKTYPE_NOTAVAILABLE;
RMCUBackupBatteryVolt = 0;
RMCUPowerSource = 0;
RMCUBoxOpeningStatus = 0;
NetworkCommStatus1 = STATE_NOTAVAILABLE;
PositionUpdateStatus = 0;
MachinePositionStatus = STATE_MACHINEPOSITIONSTATUS_NOTAVAILABLE;
GPSAntennaConnectionAlarmStatus = STATE_GPSANTENNA_NOTAVAILABLE;
NetworkTransceiverStatus1 = 0;
NetworkServiceStatus1 = STATE_NETWORKSERVICESTATUS_NOTAVAILABLE;
NetworkAntennaStatus1 = STATE_NETWORKANTENNASTATUS_NOTAVAILABLE;
RMCUData = 0;
LockLevel = STATE_LOCKLEVEL_UNLOCK;
// adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_dark),null,
// ParentActivity.getResources().getString(string.Serial_Number),"" , ""));
// adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_light),null,
// ParentActivity.getResources().getString(string.Manufacturer),"" , ""));
// adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_dark),null,
// ParentActivity.getResources().getString(string.Program_Version),"" , ""));
// adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_light),null,
// ParentActivity.getResources().getString(string.Network_Type),"" , ""));
// adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_dark),null,
// ParentActivity.getResources().getString(string.Number_of_Messages_to_Transmit),"" , ""));
// adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_light),null,
// ParentActivity.getResources().getString(string.Back_up_Battery_Voltage),"" , ""));
// adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_dark),null,
// ParentActivity.getResources().getString(string.Network_Communication_Status),"" , ""));
// adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_light),null,
// ParentActivity.getResources().getString(string.Network_Service),"" , ""));
// adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_dark),null,
// ParentActivity.getResources().getString(string.Communication_Antenna),"" , ""));
// adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_light),null,
// ParentActivity.getResources().getString(string.GPS_Antenna),"" , ""));
// adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_dark),null,
// ParentActivity.getResources().getString(string.Position_Update),"" , ""));
// adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_light),null,
// ParentActivity.getResources().getString(string.Outside_of_Boundary),"" , ""));
// adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_dark),null,
// ParentActivity.getResources().getString(string.Lock_Level),"" , ""));
adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_dark),null,
getString(ParentActivity.getResources().getString(string.Program_Version), 277),"" , ""));
adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_light),null,
getString(ParentActivity.getResources().getString(string.Serial_Number), 278),"" , ""));
listView.setAdapter(adapter);
}
@Override
public void ShowHiddenPage(){
adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_dark),null,
getString(ParentActivity.getResources().getString(string.Manufacturer), 279),"" , ""));
adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_light),null,
getString(ParentActivity.getResources().getString(string.Network_Type), 275),"" , ""));
adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_dark),null,
getString(ParentActivity.getResources().getString(string.Number_of_Messages_to_Transmit), 280),"" , ""));
adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_light),null,
getString(ParentActivity.getResources().getString(string.Back_up_Battery_Voltage), 281),"" , ""));
adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_dark),null,
getString(ParentActivity.getResources().getString(string.Network_Communication_Status), 282),"" , ""));
adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_light),null,
getString(ParentActivity.getResources().getString(string.Network_Service), 283), "" , ""));
adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_dark),null,
getString(ParentActivity.getResources().getString(string.Communication_Antenna), 284),"" , ""));
adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_light),null,
getString(ParentActivity.getResources().getString(string.GPS_Antenna), 285),"" , ""));
adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_dark),null,
getString(ParentActivity.getResources().getString(string.Position_Update), 286),"" , ""));
adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_light),null,
getString(ParentActivity.getResources().getString(string.Outside_of_Boundary), 287),"" , ""));
adapter.addItem(new IconTextItemVersion(ParentActivity.getResources().getDrawable(R.drawable.menu_management_machine_monitoring_bg_dark),null,
getString(ParentActivity.getResources().getString(string.Lock_Level),288) ,"" , ""));
}
@Override
protected void GetDataFromNative() {
// TODO Auto-generated method stub
ComponentCode = CAN1Comm.Get_ComponentCode_1699_PGN65330_RMCU();
ComponentBasicInformation = CAN1Comm.Get_ComponentBasicInformation_1698_PGN65330_RMCU();
if(ManufactureDayDisplayFlag == true)
{
ManufacturerCode = CAN1Comm.Get_ManufacturerCode_1700_PGN65330_RMCU();
RMCUNetworkType = CAN1Comm.Get_RMCUNetworkType_1621_PGN65329();
RMCUBackupBatteryVolt = CAN1Comm.Get_RMCUBackupBatteryVoltage_1590_PGN65329();
RMCUPowerSource = CAN1Comm.Get_RMCUPowerSource_1594_PGN65329();
RMCUBoxOpeningStatus = CAN1Comm.Get_RMCUBoxOpeningStatus_PGN65329();
NetworkCommStatus1 = CAN1Comm.Get_NetworkCommunicationStatus1_1622_PGN65329();
PositionUpdateStatus = CAN1Comm.Get_PositionUpdateStatus_852_PGN65329();
MachinePositionStatus = CAN1Comm.Get_MachinePositionStatus_1593_PGN65329();
GPSAntennaConnectionAlarmStatus = CAN1Comm.Get_GPSAntennaConnectionAlarmStatus_1595_PGN65329();
NetworkTransceiverStatus1 = CAN1Comm.Get_NetworkTransceiverStatus1_1623_PGN65329();
NetworkServiceStatus1 = CAN1Comm.Get_NetworkServiceStatus1_1624_PGN65329();
NetworkAntennaStatus1 = CAN1Comm.Get_NetworkAntennaStatus1_1625_PGN65329();
RMCUData = CAN1Comm.Get_RMCUData_NumberofMessagestoTransmit_855_PGN65329();
LockLevel = CAN1Comm.Get_LockLevel_823_PGN65348();
}
ProgramSubVersion = ParentActivity.FindProgramSubInfo(ComponentBasicInformation);
}
@Override
protected void UpdateUI() {
// TODO Auto-generated method stub
ManufactureDayDisplay(ComponentBasicInformation);
ModelDisplay(ComponentBasicInformation);
if(ManufactureDayDisplayFlag == true)
VersionDisplayHidden(ComponentBasicInformation,ProgramSubVersion);
else
VersionDisplay(ComponentBasicInformation,ProgramSubVersion);
SerialNumberDisplay(ComponentBasicInformation);
if(ManufactureDayDisplayFlag == true)
{
ManufacturerDisplay(ManufacturerCode);
NetworkTypeDisplay(RMCUNetworkType);
NumofDataDisplay(RMCUData);
BackupBatteryVoltDisplay(RMCUBackupBatteryVolt);
CommStatusDisplay(NetworkCommStatus1);
NetworkServiceDisplay(NetworkServiceStatus1);
NetworkAntennaDisplay(NetworkAntennaStatus1);
GPSAntennaDisplay(GPSAntennaConnectionAlarmStatus);
PositionUpdateDisplay(PositionUpdateStatus);
GuardDisplay(MachinePositionStatus);
LockLevelDisplay(LockLevel);
}
adapter.notifyDataSetChanged();
}
////////////////////////////////////////////////
public void NetworkTypeDisplay(int NetworkType){
switch (NetworkType) {
case STATE_RMCUNETWORKTYPE_NETWORK1_GSM:
adapter.UpdateSecond(STATE_NETWORKTYPE, "2G (GSM)");
break;
case STATE_RMCUNETWORKTYPE_NETWORK1_CDMA:
adapter.UpdateSecond(STATE_NETWORKTYPE, "2G (CDMA)");
break;
case STATE_RMCUNETWORKTYPE_NETWORK1_3G:
adapter.UpdateSecond(STATE_NETWORKTYPE, "3G");
break;
case STATE_RMCUNETWORKTYPE_NETWORK1_WIFI:
adapter.UpdateSecond(STATE_NETWORKTYPE, "WiFi");
break;
case STATE_RMCUNETWORKTYPE_NETWORK1_ORBCOMM:
adapter.UpdateSecond(STATE_NETWORKTYPE, "Orbcomm");
break;
case STATE_RMCUNETWORKTYPE_NETWORK12_3G_ORBCOMM:
adapter.UpdateSecond(STATE_NETWORKTYPE, "Network 1 : 3G & Network 2 : Orbcomm");
break;
case STATE_RMCUNETWORKTYPE_NETWORK12_ORBCOMM_3G:
adapter.UpdateSecond(STATE_NETWORKTYPE, "Network 1 : Orbcomm & Network 2 : 3G");
break;
case STATE_RMCUNETWORKTYPE_NETWORK12_3G_WIFI:
adapter.UpdateSecond(STATE_NETWORKTYPE, "Network 1 : 3G & Network 2 : WiFi");
break;
case STATE_RMCUNETWORKTYPE_NETWORK12_WIFI_3G:
adapter.UpdateSecond(STATE_NETWORKTYPE, "Network 1 : WiFi & Network 2 : 3G");
break;
case STATE_RMCUNETWORKTYPE_NETWORK12_2G_3G:
adapter.UpdateSecond(STATE_NETWORKTYPE, "Network 1 : 2G & Network 2 : 3G");
break;
case STATE_RMCUNETWORKTYPE_NETWORK12_3G_2G:
adapter.UpdateSecond(STATE_NETWORKTYPE, "Network 1 : 3G & Network 2 : 2G");
break;
case STATE_RMCUNETWORKTYPE_NOTAVAILABLE:
adapter.UpdateSecond(STATE_NETWORKTYPE, "-");
break;
default:
break;
}
}
public void NumofDataDisplay(int NumofData){
if(NumofData > 250){
adapter.UpdateSecond(STATE_NUMOFDATA, "-");
}else{
adapter.UpdateSecond(STATE_NUMOFDATA, Integer.toString(NumofData));
}
}
public void BackupBatteryVoltDisplay(int BatteryVolt){
float fBattery;
fBattery = (float)(BatteryVolt / 10.0);
if(BatteryVolt > 250){
adapter.UpdateSecond(STATE_BACKUPBATTERYVOLT, "-");
}else{
adapter.UpdateSecond(STATE_BACKUPBATTERYVOLT, Float.toString(fBattery) + " V");
}
}
public void CommStatusDisplay(int CommStatus){
switch (CommStatus) {
case STATE_DISABLE:
adapter.UpdateSecond(STATE_COMMSTATUS, "Disable");
break;
case STATE_ENABLE:
adapter.UpdateSecond(STATE_COMMSTATUS, "Enable");
break;
case STATE_NOTAVAILABLE:
adapter.UpdateSecond(STATE_COMMSTATUS, "-");
break;
default:
break;
}
}
public void NetworkServiceDisplay(int NetworkService){
switch (NetworkService) {
case STATE_NETWORKSERVICESTATUS_LOCALSERVICE:
adapter.UpdateSecond(STATE_NETWORKSERVICE, "Local");
break;
case STATE_NETWORKSERVICESTATUS_ROAMINGSERVICE:
adapter.UpdateSecond(STATE_NETWORKSERVICE, "Roaming");
break;
case STATE_NETWORKSERVICESTATUS_SERVICENOTAVAILABLE:
adapter.UpdateSecond(STATE_NETWORKSERVICE, "Service Not Available");
break;
case STATE_NETWORKSERVICESTATUS_NOTAUTHORIZEDSERVICE:
adapter.UpdateSecond(STATE_NETWORKSERVICE, "Not Authorized to Operate on Service");
break;
case STATE_NETWORKSERVICESTATUS_NOTAVAILABLE:
adapter.UpdateSecond(STATE_NETWORKSERVICE, "-");
break;
default:
break;
}
}
public void NetworkAntennaDisplay(int Antenna){
switch (Antenna) {
case STATE_NETWORKANTENNASTATUS_OFF:
adapter.UpdateSecond(STATE_COMMANTENNA, "Off");
break;
case STATE_NETWORKANTENNASTATUS_MAIN_ON:
adapter.UpdateSecond(STATE_COMMANTENNA, "Main On");
break;
case STATE_NETWORKANTENNASTATUS_EMERGENCY_ON:
adapter.UpdateSecond(STATE_COMMANTENNA, "Emergency On");
break;
case STATE_NETWORKANTENNASTATUS_NOTAVAILABLE:
adapter.UpdateSecond(STATE_COMMANTENNA, "-");
break;
default:
break;
}
}
public void GPSAntennaDisplay(int Antenna){
switch (Antenna) {
case STATE_GPSANTENNA_NORMAL:
adapter.UpdateSecond(STATE_GPSANTENNA, "Normal");
break;
case STATE_GPSANTENNA_ABNORMAL:
adapter.UpdateSecond(STATE_GPSANTENNA, "Abnormal");
break;
case STATE_GPSANTENNA_NOTAVAILABLE:
adapter.UpdateSecond(STATE_GPSANTENNA, "-");
break;
default:
break;
}
}
public void PositionUpdateDisplay(int PositionUpdate){
switch (PositionUpdate) {
case 0:
adapter.UpdateSecond(STATE_POSITIONUPDATE, "Not OK");
break;
case 1:
adapter.UpdateSecond(STATE_POSITIONUPDATE, "OK");
break;
case 3:
adapter.UpdateSecond(STATE_POSITIONUPDATE, "-");
break;
default:
break;
}
}
public void GuardDisplay(int Guard){
switch (Guard) {
case STATE_MACHINEPOSITIONSTATUS_INSIDE:
adapter.UpdateSecond(STATE_GUARD, "Inside of boundary");
break;
case STATE_MACHINEPOSITIONSTATUS_OUTSIDE:
adapter.UpdateSecond(STATE_GUARD, "Outside of boundary");
break;
case STATE_MACHINEPOSITIONSTATUS_NOTAVAILABLE:
adapter.UpdateSecond(STATE_GUARD, "-");
break;
default:
break;
}
}
public void LockLevelDisplay(int LockLevel){
switch (LockLevel) {
case STATE_LOCKLEVEL_UNLOCK:
adapter.UpdateSecond(STATE_LOCKLEVEL, "Unlock");
break;
case 1:
adapter.UpdateSecond(STATE_LOCKLEVEL, "Level 1");
break;
case 2:
adapter.UpdateSecond(STATE_LOCKLEVEL, "Level 2");
break;
default:
adapter.UpdateSecond(STATE_LOCKLEVEL, "-");
break;
}
}
////////////////////////////////////////////////
////////////////////////////////////////////////
}
| 19,458 | 0.751156 | 0.731987 | 426 | 44.676056 | 38.330639 | 147 | false | false | 0 | 0 | 0 | 0 | 70 | 0.014339 | 3.481221 | false | false |
14
|
2c0a4b751f003f6b3a08ace6502129413df3c6e1
| 19,963,008,012,002 |
ac308cb5a8c1f9017fcc1bb8d1cfbe165ab59b49
|
/app/src/main/java/com/example/remindme/Adapter.java
|
1a27724e9820f0ee7ec050d033e14ded1633a65d
|
[] |
no_license
|
djackson136/Reminder-App
|
https://github.com/djackson136/Reminder-App
|
a5a829d473e402b2a18e20e7c5fdc4478c306258
|
e7060ce260924d867500339f1f16c6026585987f
|
refs/heads/master
| 2023-04-02T02:58:48.294000 | 2021-03-28T03:29:08 | 2021-03-28T03:29:08 | 351,296,412 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.remindme;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class Adapter extends RecyclerView.Adapter {
private ArrayList<Reminder> reminderData;
// private View.OnClickListener mOnItemClickListener;
private boolean isDeleting;
private Context parentContext;
public class ReminderViewHolder extends RecyclerView.ViewHolder {
public TextView textViewSub;
public TextView textViewDesc;
public TextView textViewPriority;
public TextView textViewSaveDate;
public Button deleteButton;
public ReminderViewHolder(@NonNull View itemView) {
super(itemView);
textViewSub = itemView.findViewById(R.id.textSubject);
textViewDesc = itemView.findViewById(R.id.textDescription);
textViewPriority = itemView.findViewById(R.id.textPriority);
textViewSaveDate = itemView.findViewById(R.id.textSaveDate);
deleteButton = itemView.findViewById(R.id.buttonDeleteMeal);
itemView.setTag(this);
// itemView.setOnClickListener(mOnItemClickListener);
}
public TextView getSubTextView() {
return textViewSub;
}
public TextView getDescTextView() {
return textViewDesc;
}
public TextView getPriorityTextView() { return textViewPriority; }
public TextView getDateTextView() {
return textViewSaveDate;
}
public Button getDeleteButton() {
return deleteButton;
}
}
public Adapter(ArrayList<Reminder> arrayList, Context context) {
reminderData = arrayList;
parentContext = context;
}
/*
public void setOnItemClickListener(View.OnClickListener itemClickListener) {
mOnItemClickListener = itemClickListener;
}
*/
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_view, parent, false);
return new ReminderViewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) {
ReminderViewHolder rvh = (ReminderViewHolder) holder;
rvh.getDescTextView().setText(reminderData.get(position).getSubject());
rvh.getSubTextView().setText(reminderData.get(position).getDescription());
rvh.getPriorityTextView().setText(reminderData.get(position).getPriority());
rvh.getDateTextView().setText(reminderData.get(position).getSaveDate());
if (isDeleting) {
rvh.getDeleteButton().setVisibility(View.VISIBLE);
rvh.getDeleteButton().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
deleteItem(position);
}
});
} else {
rvh.getDeleteButton().setVisibility(View.INVISIBLE);
}
}
public void setDelete(boolean b) {
isDeleting = b;
}
private void deleteItem(int position) {
Reminder reminder = reminderData.get(position);
DataSource ds = new DataSource(parentContext);
try {
ds.open();
boolean didDelete = ds.deleteReminder(reminder.getReminderID());
ds.close();
if (didDelete) {
reminderData.remove(position);
notifyDataSetChanged();
} else {
Toast.makeText(parentContext, "Delete Failed!", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(parentContext, "Delete Failed!", Toast.LENGTH_LONG).show();
}
}
@Override
public int getItemCount() {
return reminderData.size();
}
}
|
UTF-8
|
Java
| 4,548 |
java
|
Adapter.java
|
Java
|
[] | null |
[] |
package com.example.remindme;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class Adapter extends RecyclerView.Adapter {
private ArrayList<Reminder> reminderData;
// private View.OnClickListener mOnItemClickListener;
private boolean isDeleting;
private Context parentContext;
public class ReminderViewHolder extends RecyclerView.ViewHolder {
public TextView textViewSub;
public TextView textViewDesc;
public TextView textViewPriority;
public TextView textViewSaveDate;
public Button deleteButton;
public ReminderViewHolder(@NonNull View itemView) {
super(itemView);
textViewSub = itemView.findViewById(R.id.textSubject);
textViewDesc = itemView.findViewById(R.id.textDescription);
textViewPriority = itemView.findViewById(R.id.textPriority);
textViewSaveDate = itemView.findViewById(R.id.textSaveDate);
deleteButton = itemView.findViewById(R.id.buttonDeleteMeal);
itemView.setTag(this);
// itemView.setOnClickListener(mOnItemClickListener);
}
public TextView getSubTextView() {
return textViewSub;
}
public TextView getDescTextView() {
return textViewDesc;
}
public TextView getPriorityTextView() { return textViewPriority; }
public TextView getDateTextView() {
return textViewSaveDate;
}
public Button getDeleteButton() {
return deleteButton;
}
}
public Adapter(ArrayList<Reminder> arrayList, Context context) {
reminderData = arrayList;
parentContext = context;
}
/*
public void setOnItemClickListener(View.OnClickListener itemClickListener) {
mOnItemClickListener = itemClickListener;
}
*/
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_view, parent, false);
return new ReminderViewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) {
ReminderViewHolder rvh = (ReminderViewHolder) holder;
rvh.getDescTextView().setText(reminderData.get(position).getSubject());
rvh.getSubTextView().setText(reminderData.get(position).getDescription());
rvh.getPriorityTextView().setText(reminderData.get(position).getPriority());
rvh.getDateTextView().setText(reminderData.get(position).getSaveDate());
if (isDeleting) {
rvh.getDeleteButton().setVisibility(View.VISIBLE);
rvh.getDeleteButton().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
deleteItem(position);
}
});
} else {
rvh.getDeleteButton().setVisibility(View.INVISIBLE);
}
}
public void setDelete(boolean b) {
isDeleting = b;
}
private void deleteItem(int position) {
Reminder reminder = reminderData.get(position);
DataSource ds = new DataSource(parentContext);
try {
ds.open();
boolean didDelete = ds.deleteReminder(reminder.getReminderID());
ds.close();
if (didDelete) {
reminderData.remove(position);
notifyDataSetChanged();
} else {
Toast.makeText(parentContext, "Delete Failed!", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(parentContext, "Delete Failed!", Toast.LENGTH_LONG).show();
}
}
@Override
public int getItemCount() {
return reminderData.size();
}
}
| 4,548 | 0.596746 | 0.596746 | 127 | 34.811024 | 28.017635 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.527559 | false | false |
14
|
3036ee71864a49c2a1d88194f4107e271d0d3299
| 29,592,324,723,888 |
320d7abc25b7db900bca4923e718a0108a63c686
|
/src/main/java/com/project/ehealth/Patient.java
|
75dbd5f7a828f92b04c12f10aa49fd3ef98a68ff
|
[] |
no_license
|
saiprasanthkumar/EhealthSpringBoot
|
https://github.com/saiprasanthkumar/EhealthSpringBoot
|
161ed011b70c0c1c401940ee9fe21c30b44d9947
|
c6c981f811633f7410a6e21261f05618ef48cd03
|
refs/heads/main
| 2023-01-19T20:12:19.252000 | 2020-12-04T20:19:44 | 2020-12-04T20:19:44 | 317,114,483 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.project.ehealth;
public class Patient {
private String patientId;
private String patientName;
private Long amount;
private String password;
public String getPatientId() {
return patientId;
}
public void setPatientId(String patientId) {
this.patientId = patientId;
}
public String getPatientName() {
return patientName;
}
public void setPatientName(String patientName) {
this.patientName = patientName;
}
public Long getAmount() {
return amount;
}
public void setAmount(Long amount) {
this.amount = amount;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
|
UTF-8
|
Java
| 687 |
java
|
Patient.java
|
Java
|
[
{
"context": "d setPassword(String password) {\n\t\tthis.password = password;\n\t}\n\n\t\n}\n",
"end": 677,
"score": 0.9776337742805481,
"start": 669,
"tag": "PASSWORD",
"value": "password"
}
] | null |
[] |
package com.project.ehealth;
public class Patient {
private String patientId;
private String patientName;
private Long amount;
private String password;
public String getPatientId() {
return patientId;
}
public void setPatientId(String patientId) {
this.patientId = patientId;
}
public String getPatientName() {
return patientName;
}
public void setPatientName(String patientName) {
this.patientName = patientName;
}
public Long getAmount() {
return amount;
}
public void setAmount(Long amount) {
this.amount = amount;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
}
| 689 | 0.730713 | 0.730713 | 37 | 17.567568 | 14.933258 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.405405 | false | false |
14
|
ad09158d3207e3d7cf7df864467958d51e40c48d
| 10,977,936,436,068 |
e8104a1239ef91bf100eaec8244029cb8ea68c0a
|
/ChuongLV/Assignment4/src/fasttrackse/entity/DaoTaoNganHan.java
|
c636997bd18c3f81fe9d7ea474014f19c6205f33
|
[] |
no_license
|
FASTTRACKSE/FFSE1703.JavaWeb
|
https://github.com/FASTTRACKSE/FFSE1703.JavaWeb
|
72b868b34a934bb9504a218011ccce668d278ad6
|
b659082bf40c5d2128092ab3a3addd3caff770e9
|
refs/heads/master
| 2021-06-07T09:22:16.125000 | 2021-03-05T04:52:01 | 2021-03-05T04:52:01 | 137,868,312 | 0 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package fasttrackse.entity;
import java.util.List;
import org.springframework.stereotype.Component;
@Component
public class DaoTaoNganHan implements HeDaoTao {
private HocKi listHK;
public DaoTaoNganHan(HocKi listHK) {
super();
this.listHK = listHK;
}
public HocKi getListHK() {
return listHK;
}
public void setListHK(HocKi listHK) {
this.listHK = listHK;
}
public String hocKi() {
String result= "Trong vòng 6 tháng, mời bạn đi học buổi tối từ 18h30 đến 21h30"
+ listHK.thongTinHocKi();
return result;
}
}
|
UTF-8
|
Java
| 568 |
java
|
DaoTaoNganHan.java
|
Java
|
[] | null |
[] |
package fasttrackse.entity;
import java.util.List;
import org.springframework.stereotype.Component;
@Component
public class DaoTaoNganHan implements HeDaoTao {
private HocKi listHK;
public DaoTaoNganHan(HocKi listHK) {
super();
this.listHK = listHK;
}
public HocKi getListHK() {
return listHK;
}
public void setListHK(HocKi listHK) {
this.listHK = listHK;
}
public String hocKi() {
String result= "Trong vòng 6 tháng, mời bạn đi học buổi tối từ 18h30 đến 21h30"
+ listHK.thongTinHocKi();
return result;
}
}
| 568 | 0.710909 | 0.694545 | 38 | 13.5 | 18.275307 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.026316 | false | false |
14
|
de0dde832601cc754a638ea30e2d8347d936875d
| 10,977,936,436,982 |
fccd80fd51c2afa6ce76ddd1bb75ecce2561210c
|
/Heap/MedianTracker.java
|
7cb4d49154de9da26baa71adf6a4da48a13c17bb
|
[] |
no_license
|
FengxiangLan/CODE
|
https://github.com/FengxiangLan/CODE
|
4f3c0c2e5db1dadf832a28e52af4ee5ed805244e
|
5f0754543bbd83e616ef7dd2dcab671bbf97a0e8
|
refs/heads/master
| 2020-04-15T00:57:44.660000 | 2019-02-19T04:13:04 | 2019-02-19T04:13:04 | 164,258,281 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class MedianTracker {
private PriorityQueue<Integer> smallerPart;
private PriorityQueue<Integer> largerPart;
public Solution() {
largerPart = new PriorityQueue<Integer>();
smallerPart = new PriorityQueue<Integer>(11, Collections.reverseOrder());
}
public void read(int value) {
if (smallerPart.isEmpty() || value <= smallerPart.peek()) {
smallerPart.offer(value);
}
else {
largerPart.offer(value);
}
if (smallerPart.size() - largerPart.size() >= 2) {
largerPart.offer(smallerPart.poll());
}
else if (smallerPart.size() < largerPart.size()) {
smallerPart.offer(largerPart.poll());
}
}
public Double median() {
int size = size();
if (size == 0) {
return null;
}
else if (size % 2 != 0) {
return (double) (smallerPart.peek());
}
else {
return (smallerPart.peek() + largerPart.peek()) / 2.0;
}
}
private int size() {
return smallerPart.size() + largerPart.size();
}
}
|
UTF-8
|
Java
| 943 |
java
|
MedianTracker.java
|
Java
|
[] | null |
[] |
public class MedianTracker {
private PriorityQueue<Integer> smallerPart;
private PriorityQueue<Integer> largerPart;
public Solution() {
largerPart = new PriorityQueue<Integer>();
smallerPart = new PriorityQueue<Integer>(11, Collections.reverseOrder());
}
public void read(int value) {
if (smallerPart.isEmpty() || value <= smallerPart.peek()) {
smallerPart.offer(value);
}
else {
largerPart.offer(value);
}
if (smallerPart.size() - largerPart.size() >= 2) {
largerPart.offer(smallerPart.poll());
}
else if (smallerPart.size() < largerPart.size()) {
smallerPart.offer(largerPart.poll());
}
}
public Double median() {
int size = size();
if (size == 0) {
return null;
}
else if (size % 2 != 0) {
return (double) (smallerPart.peek());
}
else {
return (smallerPart.peek() + largerPart.peek()) / 2.0;
}
}
private int size() {
return smallerPart.size() + largerPart.size();
}
}
| 943 | 0.651113 | 0.64263 | 43 | 20.953489 | 20.740875 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.930233 | false | false |
14
|
9ab42019fd7f7e550c9a33aa152a137a70eaec29
| 10,977,936,435,731 |
879e263c35b56e2297b552bd9d8e90a4f68614a1
|
/src/main/java/com/dev24/client/faq/vo/FaqVO.java
|
e3b61e1b3ea0e023b9fbf90f4ce28595c096e2e0
|
[] |
no_license
|
SWAKSWAK/DEV24_swak_ex
|
https://github.com/SWAKSWAK/DEV24_swak_ex
|
23626d70f1f114957302dc7501c0c219a9516d36
|
de95850acfaf4daa5ff2056683177a030df2bb20
|
refs/heads/master
| 2023-01-21T16:12:03.616000 | 2020-11-26T12:00:55 | 2020-11-26T12:00:55 | 315,159,783 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.dev24.client.faq.vo;
import com.dev24.common.vo.CommonVO;
import lombok.Data;
@Data
public class FaqVO extends CommonVO {
private int faq_num =0; //FAQ 글번호
private String faq_content =""; //FAQ 글내용
private String faq_title =""; //FAQ 글제목
private String faq_writedate =""; //FAQ 글작성일
private String faq_category =""; //FAQ 카테고리
private int faq_readcnt =0; //글 조회수
}
|
UHC
|
Java
| 496 |
java
|
FaqVO.java
|
Java
|
[] | null |
[] |
package com.dev24.client.faq.vo;
import com.dev24.common.vo.CommonVO;
import lombok.Data;
@Data
public class FaqVO extends CommonVO {
private int faq_num =0; //FAQ 글번호
private String faq_content =""; //FAQ 글내용
private String faq_title =""; //FAQ 글제목
private String faq_writedate =""; //FAQ 글작성일
private String faq_category =""; //FAQ 카테고리
private int faq_readcnt =0; //글 조회수
}
| 496 | 0.603524 | 0.590308 | 18 | 24.222221 | 22.989262 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.444444 | false | false |
14
|
3ac3bea5e9e40c422f860abe8b58c44a041e7386
| 19,507,741,493,282 |
812dece30565c00e3f713d782d193e0ce233b509
|
/app/src/main/java/com/example/administrator/competition/activity/home/HomeKindActivity.java
|
4546ec3ef356f776bf42f9cd7c0e2ec6f2864555
|
[] |
no_license
|
woudoudi/NewCompetition
|
https://github.com/woudoudi/NewCompetition
|
90bf5207c0071244751bfb28d5825ce045796919
|
c14d4d06c82950057a36ec28769d7811d620ecd0
|
refs/heads/master
| 2021-05-18T00:07:52.370000 | 2020-03-29T11:29:33 | 2020-03-29T11:29:33 | 251,015,692 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.administrator.competition.activity.home;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.example.administrator.competition.R;
import com.example.administrator.competition.entity.CommonConfig;
import com.yidao.module_lib.base.BaseView;
import com.yidao.module_lib.manager.ViewManager;
import butterknife.BindView;
import butterknife.OnClick;
public class HomeKindActivity extends BaseView {
@BindView(R.id.tv_title)
TextView tvTitle;
@BindView(R.id.tv_king_title)
TextView tvKingTitle;
@BindView(R.id.tv_king_content)
TextView tvKingContent;
@BindView(R.id.tv_trumpet_title)
TextView tvTrumpetTitle;
@BindView(R.id.tv_trumpet_content)
TextView tvTrumpetContent;
@BindView(R.id.tv_free_title)
TextView tvFreeTitle;
@BindView(R.id.tv_free_content)
TextView tvFreeContent;
@Override
protected int getView() {
return R.layout.activity_home_king;
}
@Override
public void init() {
tvTitle.setText("王者专场");
}
@OnClick({R.id.iv_back, R.id.rl_king_live, R.id.rl_record, R.id.rl_free_confrontation})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.iv_back:
ViewManager.getInstance().finishView();
break;
case R.id.rl_king_live:
Bundle bundle = new Bundle();
bundle.putInt(CommonConfig.recordAndLiveKey,CommonConfig.LiveValue);
skipActivity(HomeRecordActivity.class,bundle);
break;
case R.id.rl_record:
bundle = new Bundle();
bundle.putInt(CommonConfig.recordAndLiveKey,CommonConfig.recordValue);
skipActivity(HomeRecordActivity.class,bundle);
break;
case R.id.rl_free_confrontation:
skipActivity(HomeFreeConfrontationActivity.class);
break;
}
}
}
|
UTF-8
|
Java
| 2,010 |
java
|
HomeKindActivity.java
|
Java
|
[] | null |
[] |
package com.example.administrator.competition.activity.home;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.example.administrator.competition.R;
import com.example.administrator.competition.entity.CommonConfig;
import com.yidao.module_lib.base.BaseView;
import com.yidao.module_lib.manager.ViewManager;
import butterknife.BindView;
import butterknife.OnClick;
public class HomeKindActivity extends BaseView {
@BindView(R.id.tv_title)
TextView tvTitle;
@BindView(R.id.tv_king_title)
TextView tvKingTitle;
@BindView(R.id.tv_king_content)
TextView tvKingContent;
@BindView(R.id.tv_trumpet_title)
TextView tvTrumpetTitle;
@BindView(R.id.tv_trumpet_content)
TextView tvTrumpetContent;
@BindView(R.id.tv_free_title)
TextView tvFreeTitle;
@BindView(R.id.tv_free_content)
TextView tvFreeContent;
@Override
protected int getView() {
return R.layout.activity_home_king;
}
@Override
public void init() {
tvTitle.setText("王者专场");
}
@OnClick({R.id.iv_back, R.id.rl_king_live, R.id.rl_record, R.id.rl_free_confrontation})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.iv_back:
ViewManager.getInstance().finishView();
break;
case R.id.rl_king_live:
Bundle bundle = new Bundle();
bundle.putInt(CommonConfig.recordAndLiveKey,CommonConfig.LiveValue);
skipActivity(HomeRecordActivity.class,bundle);
break;
case R.id.rl_record:
bundle = new Bundle();
bundle.putInt(CommonConfig.recordAndLiveKey,CommonConfig.recordValue);
skipActivity(HomeRecordActivity.class,bundle);
break;
case R.id.rl_free_confrontation:
skipActivity(HomeFreeConfrontationActivity.class);
break;
}
}
}
| 2,010 | 0.652348 | 0.652348 | 65 | 29.799999 | 21.906937 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.584615 | false | false |
14
|
304052a2711d0c24662a819d26bcd8b4168aed66
| 20,349,555,059,404 |
7d458fb6fee3b45c1b355f135ebcf42cc51ebe11
|
/Group2/17020913/lab03/Fraction.java
|
91412c6d80205d02ad510e37144664ad9f794bb3
|
[] |
no_license
|
oopuet/Int2204-2
|
https://github.com/oopuet/Int2204-2
|
27ea66a0c35781844df4d39647f2b147375eeb7e
|
f543e86640a214dc06e51886ad928ad5f7c6d99b
|
refs/heads/master
| 2018-12-20T22:24:22.971000 | 2018-11-30T01:57:14 | 2018-11-30T01:57:14 | 149,217,182 | 1 | 15 | null | false | 2018-10-13T01:56:25 | 2018-09-18T02:29:30 | 2018-10-11T15:48:50 | 2018-10-13T01:51:12 | 744 | 0 | 10 | 9 |
Java
| false | null |
package week_3;
import java.util.Scanner;
public class Fraction {
public int numerator;
public int denominator;
public int getNumerator() {
return numerator;
}
public void setNumerator(int numerator) {
this.numerator = numerator;
}
public int getDenominator() {
return denominator;
}
public void setDenominator(int denominator) {
this.denominator = denominator;
}
public static void main(String[] args) {
// tao ps1
Fraction p1 = new Fraction();
// tao ps2
p1.setFrac(-3, 5);
Fraction p2 = new Fraction();
p2.setFrac(3, -5);
Fraction str= new Fraction();
System.out.println("Tong 2 phan so la : " );p2.cong(p1);
System.out.println("Hieu 2 phan so la : " );p2.tru(p1);
System.out.println("Tich 2 phan so la : " );p2.nhan(p1);
System.out.println("Thuong 2 phan so la : " );p2.chia(p1);
}
public void setFrac(int a, int b) {
//tu so
this.numerator = a;
// mau so
this.denominator = b;}
public void cong(Fraction p1) {
Fraction p3 = new Fraction();
p3.denominator= p1.denominator*this.denominator;
p3.numerator=p1.numerator*this.denominator+p1.denominator*this.numerator;
// goi ham ucln
Main uc= new Main();
int ucln=uc.timUoc(p3.denominator, p3.numerator);
if(p3.numerator/ucln * p3.denominator/ucln <0)
System.out.println(-Math.abs(p3.numerator/ucln) +"/" + Math.abs(p3.denominator/ucln));
else if(p3.numerator/ucln * p3.denominator/ucln ==0)
System.out.println("0");
else if(p3.numerator/ucln ==1 && p3.denominator/ucln ==1)
System.out.println("1");
else
if(p3.numerator/ucln <0 && p3.denominator/ucln <0)
System.out.println(Math.abs(p3.numerator/ucln) +"/" + Math.abs(p3.denominator/ucln));
else
System.out.println(p3.numerator/ucln +"/"+p3.denominator/ucln);
};
public void tru(Fraction p1) {
Fraction p3 = new Fraction();
p3.denominator= p1.denominator*this.denominator;
p3.numerator=p1.numerator*this.denominator-this.numerator*p1.denominator;
// goi ham ucln
Main uc= new Main();
int ucln=uc.timUoc(p3.denominator, p3.numerator);
if(p3.numerator/ucln * p3.denominator/ucln <0)
System.out.println(-Math.abs(p3.numerator/ucln) +"/" + Math.abs(p3.denominator/ucln));
else if(p3.numerator/ucln * p3.denominator/ucln ==0)
System.out.println("0");
else if(p3.numerator/ucln ==1 && p3.denominator/ucln ==1)
System.out.println("1");
else
if(p3.numerator/ucln <0 && p3.denominator/ucln <0)
System.out.println(Math.abs(p3.numerator/ucln) +"/" + Math.abs(p3.denominator/ucln));
else
System.out.println(p3.numerator/ucln +"/"+p3.denominator/ucln);
};
public void nhan(Fraction p1) {
Fraction p3 = new Fraction();
p3.denominator= p1.denominator*this.denominator;
p3.numerator=p1.numerator*this.numerator;
// goi ham ucln
Main uc= new Main();
int ucln=uc.timUoc(p3.denominator, p3.numerator);
if(p3.numerator/ucln * p3.denominator/ucln <0)
System.out.println(-Math.abs(p3.numerator/ucln) +"/" + Math.abs(p3.denominator/ucln));
else if(p3.numerator/ucln * p3.denominator/ucln ==0)
System.out.println("0");
else if(p3.numerator/ucln ==1 && p3.denominator/ucln ==1)
System.out.println("1");
else
if(p3.numerator/ucln <0 && p3.denominator/ucln <0)
System.out.println(Math.abs(p3.numerator/ucln) +"/" + Math.abs(p3.denominator/ucln));
else
System.out.println(p3.numerator/ucln +"/"+p3.denominator/ucln);
};
public void chia(Fraction p1) {
Fraction p3 = new Fraction();
p3.denominator= p1.denominator*this.numerator;
p3.numerator=p1.numerator*this.denominator;
// goi ham ucln
Main uc= new Main();
int ucln=uc.timUoc(p3.denominator, p3.numerator);
if(p3.numerator/ucln * p3.denominator/ucln <0)
System.out.println(-Math.abs(p3.numerator/ucln) +"/" + Math.abs(p3.denominator/ucln));
else if(p3.numerator/ucln * p3.denominator/ucln ==0)
System.out.println("0");
else if(p3.numerator/ucln ==1 && p3.denominator/ucln ==1)
System.out.println("1");
else
if(p3.numerator/ucln <0 && p3.denominator/ucln <0)
System.out.println(Math.abs(p3.numerator/ucln) +"/" + Math.abs(p3.denominator/ucln));
else
System.out.println(p3.numerator/ucln +"/"+p3.denominator/ucln);
}
public boolean equals(Object obj) {
if(this == obj)
return true;
if(obj instanceof Fraction)
{
Fraction p1 =(Fraction ) obj;
return(this.numerator * p1.denominator == this.denominator* p1.numerator);
}
else return false;
}
}
|
UTF-8
|
Java
| 4,390 |
java
|
Fraction.java
|
Java
|
[] | null |
[] |
package week_3;
import java.util.Scanner;
public class Fraction {
public int numerator;
public int denominator;
public int getNumerator() {
return numerator;
}
public void setNumerator(int numerator) {
this.numerator = numerator;
}
public int getDenominator() {
return denominator;
}
public void setDenominator(int denominator) {
this.denominator = denominator;
}
public static void main(String[] args) {
// tao ps1
Fraction p1 = new Fraction();
// tao ps2
p1.setFrac(-3, 5);
Fraction p2 = new Fraction();
p2.setFrac(3, -5);
Fraction str= new Fraction();
System.out.println("Tong 2 phan so la : " );p2.cong(p1);
System.out.println("Hieu 2 phan so la : " );p2.tru(p1);
System.out.println("Tich 2 phan so la : " );p2.nhan(p1);
System.out.println("Thuong 2 phan so la : " );p2.chia(p1);
}
public void setFrac(int a, int b) {
//tu so
this.numerator = a;
// mau so
this.denominator = b;}
public void cong(Fraction p1) {
Fraction p3 = new Fraction();
p3.denominator= p1.denominator*this.denominator;
p3.numerator=p1.numerator*this.denominator+p1.denominator*this.numerator;
// goi ham ucln
Main uc= new Main();
int ucln=uc.timUoc(p3.denominator, p3.numerator);
if(p3.numerator/ucln * p3.denominator/ucln <0)
System.out.println(-Math.abs(p3.numerator/ucln) +"/" + Math.abs(p3.denominator/ucln));
else if(p3.numerator/ucln * p3.denominator/ucln ==0)
System.out.println("0");
else if(p3.numerator/ucln ==1 && p3.denominator/ucln ==1)
System.out.println("1");
else
if(p3.numerator/ucln <0 && p3.denominator/ucln <0)
System.out.println(Math.abs(p3.numerator/ucln) +"/" + Math.abs(p3.denominator/ucln));
else
System.out.println(p3.numerator/ucln +"/"+p3.denominator/ucln);
};
public void tru(Fraction p1) {
Fraction p3 = new Fraction();
p3.denominator= p1.denominator*this.denominator;
p3.numerator=p1.numerator*this.denominator-this.numerator*p1.denominator;
// goi ham ucln
Main uc= new Main();
int ucln=uc.timUoc(p3.denominator, p3.numerator);
if(p3.numerator/ucln * p3.denominator/ucln <0)
System.out.println(-Math.abs(p3.numerator/ucln) +"/" + Math.abs(p3.denominator/ucln));
else if(p3.numerator/ucln * p3.denominator/ucln ==0)
System.out.println("0");
else if(p3.numerator/ucln ==1 && p3.denominator/ucln ==1)
System.out.println("1");
else
if(p3.numerator/ucln <0 && p3.denominator/ucln <0)
System.out.println(Math.abs(p3.numerator/ucln) +"/" + Math.abs(p3.denominator/ucln));
else
System.out.println(p3.numerator/ucln +"/"+p3.denominator/ucln);
};
public void nhan(Fraction p1) {
Fraction p3 = new Fraction();
p3.denominator= p1.denominator*this.denominator;
p3.numerator=p1.numerator*this.numerator;
// goi ham ucln
Main uc= new Main();
int ucln=uc.timUoc(p3.denominator, p3.numerator);
if(p3.numerator/ucln * p3.denominator/ucln <0)
System.out.println(-Math.abs(p3.numerator/ucln) +"/" + Math.abs(p3.denominator/ucln));
else if(p3.numerator/ucln * p3.denominator/ucln ==0)
System.out.println("0");
else if(p3.numerator/ucln ==1 && p3.denominator/ucln ==1)
System.out.println("1");
else
if(p3.numerator/ucln <0 && p3.denominator/ucln <0)
System.out.println(Math.abs(p3.numerator/ucln) +"/" + Math.abs(p3.denominator/ucln));
else
System.out.println(p3.numerator/ucln +"/"+p3.denominator/ucln);
};
public void chia(Fraction p1) {
Fraction p3 = new Fraction();
p3.denominator= p1.denominator*this.numerator;
p3.numerator=p1.numerator*this.denominator;
// goi ham ucln
Main uc= new Main();
int ucln=uc.timUoc(p3.denominator, p3.numerator);
if(p3.numerator/ucln * p3.denominator/ucln <0)
System.out.println(-Math.abs(p3.numerator/ucln) +"/" + Math.abs(p3.denominator/ucln));
else if(p3.numerator/ucln * p3.denominator/ucln ==0)
System.out.println("0");
else if(p3.numerator/ucln ==1 && p3.denominator/ucln ==1)
System.out.println("1");
else
if(p3.numerator/ucln <0 && p3.denominator/ucln <0)
System.out.println(Math.abs(p3.numerator/ucln) +"/" + Math.abs(p3.denominator/ucln));
else
System.out.println(p3.numerator/ucln +"/"+p3.denominator/ucln);
}
public boolean equals(Object obj) {
if(this == obj)
return true;
if(obj instanceof Fraction)
{
Fraction p1 =(Fraction ) obj;
return(this.numerator * p1.denominator == this.denominator* p1.numerator);
}
else return false;
}
}
| 4,390 | 0.691116 | 0.657403 | 149 | 28.469799 | 25.322233 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.711409 | false | false |
14
|
fa1367ea4396f49b4aa5ab8b11484a379b3e775b
| 39,367,670,272,919 |
7414de9b39925e890ebb8813bdfb3933da39b01f
|
/qubit-sdk/src/main/java/com/qubit/android/sdk/internal/configuration/connector/ConfigurationRestModel.java
|
16544bc122cb048ed2020b0634bf0f93aaa831ac
|
[
"Apache-2.0"
] |
permissive
|
poqcommerce/qubit-sdk-android
|
https://github.com/poqcommerce/qubit-sdk-android
|
d76adf608a254c052791d34526fece0efbd9c66b
|
9663ee6d11802e69442a6ae32c92bb4e8f7cc762
|
refs/heads/master
| 2023-03-31T20:45:34.418000 | 2021-04-13T10:33:03 | 2021-04-13T10:33:03 | 344,514,654 | 0 | 0 |
Apache-2.0
| true | 2021-04-13T10:33:05 | 2021-03-04T15:09:13 | 2021-03-04T15:09:15 | 2021-04-13T10:33:04 | 603 | 0 | 0 | 0 | null | false | false |
package com.qubit.android.sdk.internal.configuration.connector;
import com.google.gson.annotations.SerializedName;
public class ConfigurationRestModel {
private String endpoint;
@SerializedName("data_location")
private String dataLocation;
@SerializedName("configuration_reload_interval")
private Integer configurationReloadInterval;
@SerializedName("queue_timeout")
private Integer queueTimeout;
private String vertical;
private String namespace;
@SerializedName("property_id")
private Long propertyId;
private Boolean disabled;
@SerializedName("lookup_attribute_url")
private String lookupAttributeUrl;
@SerializedName("lookup_get_request_timeout")
private Integer lookupGetRequestTimeout;
@SerializedName("lookup_cache_expire_time")
private Integer lookupCacheExpireTime;
@SerializedName("experience_api_host")
private String experienceApiHost;
@SerializedName("experience_api_cache_expire_time")
private Integer experienceApiCacheExpireTime;
@SerializedName("placement_api_endpoint")
private String placementApiHost;
@SerializedName("placement_api_timeout")
private Integer placementRequestTimeout;
public String getEndpoint() {
return endpoint;
}
public String getDataLocation() {
return dataLocation;
}
public Integer getConfigurationReloadInterval() {
return configurationReloadInterval;
}
public Integer getQueueTimeout() {
return queueTimeout;
}
public String getVertical() {
return vertical;
}
public String getNamespace() {
return namespace;
}
public Long getPropertyId() {
return propertyId;
}
public Boolean isDisabled() {
return disabled;
}
public String getLookupAttributeUrl() {
return lookupAttributeUrl;
}
public Integer getLookupGetRequestTimeout() {
return lookupGetRequestTimeout;
}
public Integer getLookupCacheExpireTime() {
return lookupCacheExpireTime;
}
public String getExperienceApiHost() {
return experienceApiHost;
}
public Integer getExperienceApiCacheExpireTime() {
return experienceApiCacheExpireTime;
}
public String getPlacementApiHost() {
return placementApiHost;
}
public Integer getPlacementRequestTimeout() {
return placementRequestTimeout;
}
}
|
UTF-8
|
Java
| 2,274 |
java
|
ConfigurationRestModel.java
|
Java
|
[] | null |
[] |
package com.qubit.android.sdk.internal.configuration.connector;
import com.google.gson.annotations.SerializedName;
public class ConfigurationRestModel {
private String endpoint;
@SerializedName("data_location")
private String dataLocation;
@SerializedName("configuration_reload_interval")
private Integer configurationReloadInterval;
@SerializedName("queue_timeout")
private Integer queueTimeout;
private String vertical;
private String namespace;
@SerializedName("property_id")
private Long propertyId;
private Boolean disabled;
@SerializedName("lookup_attribute_url")
private String lookupAttributeUrl;
@SerializedName("lookup_get_request_timeout")
private Integer lookupGetRequestTimeout;
@SerializedName("lookup_cache_expire_time")
private Integer lookupCacheExpireTime;
@SerializedName("experience_api_host")
private String experienceApiHost;
@SerializedName("experience_api_cache_expire_time")
private Integer experienceApiCacheExpireTime;
@SerializedName("placement_api_endpoint")
private String placementApiHost;
@SerializedName("placement_api_timeout")
private Integer placementRequestTimeout;
public String getEndpoint() {
return endpoint;
}
public String getDataLocation() {
return dataLocation;
}
public Integer getConfigurationReloadInterval() {
return configurationReloadInterval;
}
public Integer getQueueTimeout() {
return queueTimeout;
}
public String getVertical() {
return vertical;
}
public String getNamespace() {
return namespace;
}
public Long getPropertyId() {
return propertyId;
}
public Boolean isDisabled() {
return disabled;
}
public String getLookupAttributeUrl() {
return lookupAttributeUrl;
}
public Integer getLookupGetRequestTimeout() {
return lookupGetRequestTimeout;
}
public Integer getLookupCacheExpireTime() {
return lookupCacheExpireTime;
}
public String getExperienceApiHost() {
return experienceApiHost;
}
public Integer getExperienceApiCacheExpireTime() {
return experienceApiCacheExpireTime;
}
public String getPlacementApiHost() {
return placementApiHost;
}
public Integer getPlacementRequestTimeout() {
return placementRequestTimeout;
}
}
| 2,274 | 0.761653 | 0.761653 | 93 | 23.451612 | 18.397356 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.344086 | false | false |
14
|
854a8a4347964032ad24c03d559394eace2e4735
| 35,356,170,828,672 |
c0d3c5d10070e6db868845567b7d40b30cb38cbb
|
/app/src/main/java/com/example/tacademy/recycleviewtest/ChatActivity.java
|
e0395e39356d8d98b54547d9a2088ca5237934b5
|
[] |
no_license
|
201368002/RecyclerTest
|
https://github.com/201368002/RecyclerTest
|
53ec5914b22ad671dc3a86e1e854d007d69abbfe
|
3a9fb8d753c10956fff7778d19611601da5c4092
|
refs/heads/master
| 2021-01-22T02:25:32.672000 | 2017-02-07T04:42:57 | 2017-02-07T04:42:57 | 81,051,324 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.tacademy.recycleviewtest;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import com.example.tacademy.recycleviewtest.model.ChatMessage;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class ChatActivity extends AppCompatActivity {
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
onBasic();
// 1. 파베 디비 객체 획득
firebaseDatabase = FirebaseDatabase.getInstance();
// 2. 디비를 access 할 수 있는 참조 값 (root) 획득
databaseReference = firebaseDatabase.getReference();
// // 3. insert 적절한 경로 ( 가지를 하나 만들어서 ) 에다 메시지 입력
// databaseReference.child("chat").push()
// .setValue(new ChatMessage("삼다수", "하이"))
// .addOnCompleteListener(new OnCompleteListener<Void>() {
// @Override
// public void onComplete(@NonNull Task<Void> task) {
// if(task.isSuccessful()){
// Log.i("CHAT", "등록완료");
// }else{
// Log.i("CHAT", "등록실패");
// }
// }
// }); //push()는 가지에 대한 중복되지 않는 키가 하나 만들어 진다. 거기에 값을 넣는 것이 setValue()
// 4. select 등록된 데이터 가져오기
databaseReference.child("chat").addChildEventListener(new ChildEventListener() {
// 아이템을 검색하거나, 추가될 때 호출 (select, insert)
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
// s는 전번 데이터의 키를 가르킨다 (링크드리스트) -> 실질적으로 순차적으로 오기때문에 s는 잘 사용하지 X
//Log.i("CHAT", dataSnapshot.toString() + "/" + s);
// 파싱 : 데이터를 ChatMessage틀에 넣어준다.
ChatMessage chatMessage = dataSnapshot.getValue(ChatMessage.class);
Log.i("CHAT", chatMessage.getUsername());
}
// 아이템의 변화가 감지되면 호출 (update)
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
// 아이템이 삭제되면 호출 (delete)
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
ChatMessage chatMessage = dataSnapshot.getValue(ChatMessage.class);
Log.i("CHAT", dataSnapshot.getKey() + "삭제완료");
}
// 아이템의 순서가
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
// ===========================================
}
// Basic ==========================================
public void onBasic(){
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// delete 특정 메시지 삭제
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
databaseReference.child("chat")
.child("-Kc0U0ZM9sWYUq17_rYi")
.removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
Log.i("CHAT", "삭제완료");
}else{
Log.i("CHAT", "삭제실패");
}
}
});
}
});
}
// ================================================
}
|
UTF-8
|
Java
| 4,895 |
java
|
ChatActivity.java
|
Java
|
[] | null |
[] |
package com.example.tacademy.recycleviewtest;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import com.example.tacademy.recycleviewtest.model.ChatMessage;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class ChatActivity extends AppCompatActivity {
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
onBasic();
// 1. 파베 디비 객체 획득
firebaseDatabase = FirebaseDatabase.getInstance();
// 2. 디비를 access 할 수 있는 참조 값 (root) 획득
databaseReference = firebaseDatabase.getReference();
// // 3. insert 적절한 경로 ( 가지를 하나 만들어서 ) 에다 메시지 입력
// databaseReference.child("chat").push()
// .setValue(new ChatMessage("삼다수", "하이"))
// .addOnCompleteListener(new OnCompleteListener<Void>() {
// @Override
// public void onComplete(@NonNull Task<Void> task) {
// if(task.isSuccessful()){
// Log.i("CHAT", "등록완료");
// }else{
// Log.i("CHAT", "등록실패");
// }
// }
// }); //push()는 가지에 대한 중복되지 않는 키가 하나 만들어 진다. 거기에 값을 넣는 것이 setValue()
// 4. select 등록된 데이터 가져오기
databaseReference.child("chat").addChildEventListener(new ChildEventListener() {
// 아이템을 검색하거나, 추가될 때 호출 (select, insert)
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
// s는 전번 데이터의 키를 가르킨다 (링크드리스트) -> 실질적으로 순차적으로 오기때문에 s는 잘 사용하지 X
//Log.i("CHAT", dataSnapshot.toString() + "/" + s);
// 파싱 : 데이터를 ChatMessage틀에 넣어준다.
ChatMessage chatMessage = dataSnapshot.getValue(ChatMessage.class);
Log.i("CHAT", chatMessage.getUsername());
}
// 아이템의 변화가 감지되면 호출 (update)
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
// 아이템이 삭제되면 호출 (delete)
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
ChatMessage chatMessage = dataSnapshot.getValue(ChatMessage.class);
Log.i("CHAT", dataSnapshot.getKey() + "삭제완료");
}
// 아이템의 순서가
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
// ===========================================
}
// Basic ==========================================
public void onBasic(){
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// delete 특정 메시지 삭제
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
databaseReference.child("chat")
.child("-Kc0U0ZM9sWYUq17_rYi")
.removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
Log.i("CHAT", "삭제완료");
}else{
Log.i("CHAT", "삭제실패");
}
}
});
}
});
}
// ================================================
}
| 4,895 | 0.540782 | 0.538324 | 114 | 38.254387 | 24.716217 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.45614 | false | false |
14
|
937ad6c6a495eb79d8708223d06b3d1a7f99f4cd
| 38,319,698,245,230 |
78f8d9b609cf0a6f65792c2872d6922849017132
|
/FarmeworkPractise/src/main/java/com/frameworkpractise/pom/pages/WelcomePage.java
|
455ba747fe9dd0dba5150702a673c01a2156cd48
|
[] |
no_license
|
pallavsidana/POMPractice
|
https://github.com/pallavsidana/POMPractice
|
510bf6b687d54ddbad60a6c824196b46aeb9babb
|
d70174763adecbd36118c65605e4e7b32a498462
|
refs/heads/master
| 2023-03-07T03:39:21.437000 | 2021-02-18T11:06:26 | 2021-02-18T11:06:26 | 339,022,227 | 1 | 0 | null | false | 2021-02-18T10:19:45 | 2021-02-15T09:15:10 | 2021-02-17T15:44:00 | 2021-02-18T10:19:45 | 65 | 0 | 0 | 0 |
HTML
| false | false |
package com.frameworkpractise.pom.pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import com.frameworkpractise.base.BasePageObjects;
public class WelcomePage extends BasePageObjects {
@FindBy(xpath = "//*[@id='content']/ul/li[21]/a")
WebElement FormAuenticationLink;
public WelcomePage(WebDriver driver) {
super(driver);
}
// clicked on the Form Auenth=ication link from main page
// clicked on the Form Auenth=ication link from main page
public WebDriver FormAuentication() {
FormAuenticationLink.click();
return driver;
}
}
|
UTF-8
|
Java
| 656 |
java
|
WelcomePage.java
|
Java
|
[] | null |
[] |
package com.frameworkpractise.pom.pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import com.frameworkpractise.base.BasePageObjects;
public class WelcomePage extends BasePageObjects {
@FindBy(xpath = "//*[@id='content']/ul/li[21]/a")
WebElement FormAuenticationLink;
public WelcomePage(WebDriver driver) {
super(driver);
}
// clicked on the Form Auenth=ication link from main page
// clicked on the Form Auenth=ication link from main page
public WebDriver FormAuentication() {
FormAuenticationLink.click();
return driver;
}
}
| 656 | 0.736281 | 0.733232 | 27 | 22.296297 | 21.533463 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.888889 | false | false |
14
|
c1f5bfa6fac19fc97af42f2ce06c17ca1ca17c8d
| 38,981,123,223,208 |
0003855c11a4be542b9e145f136239c359b60bb8
|
/Actividades del informatorio/Ejercicios/ejercicio4.java
|
e5e26acff760d8cc4287b6b1d1a7fedca8eb770f
|
[] |
no_license
|
cdvcristiann/java-informatorio
|
https://github.com/cdvcristiann/java-informatorio
|
d3c92f1d7cfd9691d46696c03e7c99fcabe8f6aa
|
7b452bf78874e53e6ed625f9fe93ac1787d1b967
|
refs/heads/master
| 2023-01-31T23:47:32.128000 | 2020-12-16T20:01:40 | 2020-12-16T20:01:40 | 309,786,583 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Ejercicios;
import java.util.Scanner;
public class ejercicio4 {
public static void main(String[] args){
Scanner EntradaDeNumero = new Scanner(System.in);
System.out.println("ingrese un numero del 1 al 7 para ver que dia de la semana pertenece: ");
int numero = EntradaDeNumero.nextInt();
switch (numero) {
case 2:
System.out.println("Lunes");
break;
case 3:
System.out.println("martes");
break;
case 4:
System.out.println("miercoles");
break;
case 5:
System.out.println("jueves");
break;
case 6:
System.out.println("Viernes");
break;
case 7:
System.out.println("Sabado");
break;
case 1:
System.out.println("Domingo");
break;
default:
System.out.println("el numero ingresado no esta en el rango de los dias de la semana");
break;
} EntradaDeNumero.close();
}
}
|
UTF-8
|
Java
| 1,177 |
java
|
ejercicio4.java
|
Java
|
[] | null |
[] |
package Ejercicios;
import java.util.Scanner;
public class ejercicio4 {
public static void main(String[] args){
Scanner EntradaDeNumero = new Scanner(System.in);
System.out.println("ingrese un numero del 1 al 7 para ver que dia de la semana pertenece: ");
int numero = EntradaDeNumero.nextInt();
switch (numero) {
case 2:
System.out.println("Lunes");
break;
case 3:
System.out.println("martes");
break;
case 4:
System.out.println("miercoles");
break;
case 5:
System.out.println("jueves");
break;
case 6:
System.out.println("Viernes");
break;
case 7:
System.out.println("Sabado");
break;
case 1:
System.out.println("Domingo");
break;
default:
System.out.println("el numero ingresado no esta en el rango de los dias de la semana");
break;
} EntradaDeNumero.close();
}
}
| 1,177 | 0.483432 | 0.474936 | 39 | 29.179487 | 22.476051 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.564103 | false | false |
14
|
ef8a00b6eb604ba60972282bda55eeb09ea70cad
| 38,886,633,947,022 |
a19a446cbb87c4aad044ded8da82c942d2a21398
|
/src/main/java/com/jxy/jxyapi/util/IBusinessResult.java
|
79e867996cc114667c38ac76023c47025a50c2f5
|
[] |
no_license
|
lvzhongzhou/jxy-api
|
https://github.com/lvzhongzhou/jxy-api
|
7491b2bf69bb6eb41b9394bb74734cb0cc28fcb8
|
af5ebc7039a07bf18555c02c2d9321bbb9f2160a
|
refs/heads/master
| 2021-03-30T20:39:08.185000 | 2018-03-19T07:29:19 | 2018-03-19T07:29:19 | 124,661,764 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.jxy.jxyapi.util;
public interface IBusinessResult {
void setTimeout(long timeout);
}
|
UTF-8
|
Java
| 102 |
java
|
IBusinessResult.java
|
Java
|
[] | null |
[] |
package com.jxy.jxyapi.util;
public interface IBusinessResult {
void setTimeout(long timeout);
}
| 102 | 0.764706 | 0.764706 | 5 | 19.4 | 15.58974 | 34 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false |
14
|
7b26a564c4c74769ba1e995051ce4e142f51aead
| 38,886,633,944,899 |
51bafdc931b7bb9ad1049dd9c217bef17204882f
|
/src/main/java/net/canang/cfi/biz/bm/manager/BmFinder.java
|
4a3fd29584c653210eded7aeef8320686cab8a10
|
[
"Apache-2.0"
] |
permissive
|
rafizanbaharum/cfi-gov
|
https://github.com/rafizanbaharum/cfi-gov
|
05ece6854d807ce069f0b43c1738dc05ddca7ab6
|
fab98b340ccb54de59d47b1199139faae6230ac5
|
refs/heads/master
| 2020-12-24T16:16:16.368000 | 2013-10-24T17:46:16 | 2013-10-24T17:46:16 | 13,263,467 | 1 | 1 | null | false | 2016-03-09T19:50:19 | 2013-10-02T05:34:08 | 2015-09-14T05:47:46 | 2013-10-24T09:48:35 | 2,052 | 1 | 1 | 1 |
Java
| null | null |
package net.canang.cfi.biz.bm.manager;
import net.canang.cfi.core.bm.model.CfControl;
import net.canang.cfi.core.bm.model.CfControlItem;
import net.canang.cfi.core.bm.model.CfControlType;
import net.canang.cfi.core.dd.model.CfPeriod;
import net.canang.cfi.core.so.model.CfMetaState;
import java.util.List;
/**
* @author rafizan.baharum
* @since 10/3/13
*/
public interface BmFinder {
// ==================================================================================================== //
// FINDER METHODS
// ==================================================================================================== //
CfControl findControlById(Long id);
CfControlItem findControlItemById(Long id);
CfControl findControlByReferenceNo(String referenceNo);
CfControl findControlBySourceNo(String sourceNo);
List<CfControl> findControlsBySourceNo(String sourceNo);
List<CfControl> findControls(Integer offset, Integer limit);
List<CfControlItem> findControlItems(CfControl control);
List<CfControlItem> findControlItems(CfControl control, boolean voteDetailed);
List<CfControlItem> findControlItems(CfControl control, Integer level);
List<CfControlItem> findControlItems(CfControl control, Integer offset, Integer limit);
List<CfControlItem> findControlItems(CfControl control, Integer level, Integer offset, Integer limit);
List<CfControlItem> findControlItemChildren(CfControlItem item);
List<CfControlItem> findControlItemChildren(CfControlItem item, Integer offset, Integer limit);
// ==================================================================================================== //
// COUNT METHODS
// ==================================================================================================== //
Integer countControlItem(CfControl control);
// ==================================================================================================== //
// HELPER METHODS
// ==================================================================================================== //
boolean isExist(CfPeriod Period, CfControlType type);
boolean isExist(CfControl control, CfControlType type);
boolean isExist(CfControl control, CfControlType type, CfMetaState state);
}
|
UTF-8
|
Java
| 2,305 |
java
|
BmFinder.java
|
Java
|
[
{
"context": "MetaState;\n\nimport java.util.List;\n\n/**\n * @author rafizan.baharum\n * @since 10/3/13\n */\npublic interface ",
"end": 329,
"score": 0.6654217839241028,
"start": 324,
"tag": "NAME",
"value": "rafiz"
},
{
"context": "ate;\n\nimport java.util.List;\n\n/**\n * @author rafizan.baharum\n * @since 10/3/13\n */\npublic interface BmF",
"end": 331,
"score": 0.7009900808334351,
"start": 329,
"tag": "USERNAME",
"value": "an"
},
{
"context": ";\n\nimport java.util.List;\n\n/**\n * @author rafizan.baharum\n * @since 10/3/13\n */\npublic interface BmFinder {",
"end": 339,
"score": 0.6173250675201416,
"start": 332,
"tag": "NAME",
"value": "baharum"
}
] | null |
[] |
package net.canang.cfi.biz.bm.manager;
import net.canang.cfi.core.bm.model.CfControl;
import net.canang.cfi.core.bm.model.CfControlItem;
import net.canang.cfi.core.bm.model.CfControlType;
import net.canang.cfi.core.dd.model.CfPeriod;
import net.canang.cfi.core.so.model.CfMetaState;
import java.util.List;
/**
* @author rafizan.baharum
* @since 10/3/13
*/
public interface BmFinder {
// ==================================================================================================== //
// FINDER METHODS
// ==================================================================================================== //
CfControl findControlById(Long id);
CfControlItem findControlItemById(Long id);
CfControl findControlByReferenceNo(String referenceNo);
CfControl findControlBySourceNo(String sourceNo);
List<CfControl> findControlsBySourceNo(String sourceNo);
List<CfControl> findControls(Integer offset, Integer limit);
List<CfControlItem> findControlItems(CfControl control);
List<CfControlItem> findControlItems(CfControl control, boolean voteDetailed);
List<CfControlItem> findControlItems(CfControl control, Integer level);
List<CfControlItem> findControlItems(CfControl control, Integer offset, Integer limit);
List<CfControlItem> findControlItems(CfControl control, Integer level, Integer offset, Integer limit);
List<CfControlItem> findControlItemChildren(CfControlItem item);
List<CfControlItem> findControlItemChildren(CfControlItem item, Integer offset, Integer limit);
// ==================================================================================================== //
// COUNT METHODS
// ==================================================================================================== //
Integer countControlItem(CfControl control);
// ==================================================================================================== //
// HELPER METHODS
// ==================================================================================================== //
boolean isExist(CfPeriod Period, CfControlType type);
boolean isExist(CfControl control, CfControlType type);
boolean isExist(CfControl control, CfControlType type, CfMetaState state);
}
| 2,305 | 0.55141 | 0.549241 | 62 | 36.177418 | 38.215656 | 110 | false | false | 0 | 0 | 0 | 0 | 100 | 0.260304 | 0.612903 | false | false |
14
|
4dac98c1159dc6d5b340fe0274de07fbad82377f
| 33,852,932,288,520 |
2b4b045fcde7de43b34bdfc5199ff9397b9c6864
|
/src/main/java/useCase/command/TypeTextRandomlyCommand.java
|
632ebfd5388c8063da6b5437d3015e5dd54ab04c
|
[] |
no_license
|
likesm0887/STV-Project
|
https://github.com/likesm0887/STV-Project
|
d7b4cc80d5b0bc0569da2d9224cd541cce80c0aa
|
6475ede11e91f0ff0bc2acd972b24b9c77b6d900
|
refs/heads/master
| 2021-06-28T17:09:53.137000 | 2020-02-03T07:21:55 | 2020-02-03T07:21:55 | 173,348,667 | 5 | 4 | null | false | 2020-10-13T12:11:09 | 2019-03-01T18:20:07 | 2020-03-12T16:30:06 | 2020-10-13T12:11:07 | 70,341 | 2 | 3 | 2 |
Java
| false | false |
package useCase.command;
import adapter.device.DeviceDriver;
import org.apache.commons.lang3.RandomStringUtils;
public class TypeTextRandomlyCommand extends Command {
public TypeTextRandomlyCommand(DeviceDriver deviceDriver, String xPath) {
super(deviceDriver, xPath);
}
@Override
public void execute() {
String randomText = generateRandomText();
this.deviceDriver.waitAndTypeText(xPath, randomText);
}
public String generateRandomText() {
String randomText = RandomStringUtils.random(10);
return randomText;
}
}
|
UTF-8
|
Java
| 588 |
java
|
TypeTextRandomlyCommand.java
|
Java
|
[] | null |
[] |
package useCase.command;
import adapter.device.DeviceDriver;
import org.apache.commons.lang3.RandomStringUtils;
public class TypeTextRandomlyCommand extends Command {
public TypeTextRandomlyCommand(DeviceDriver deviceDriver, String xPath) {
super(deviceDriver, xPath);
}
@Override
public void execute() {
String randomText = generateRandomText();
this.deviceDriver.waitAndTypeText(xPath, randomText);
}
public String generateRandomText() {
String randomText = RandomStringUtils.random(10);
return randomText;
}
}
| 588 | 0.717687 | 0.712585 | 24 | 23.5 | 23.92523 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.458333 | false | false |
14
|
39c7f1f613944a18653c0226219688a148d4ff1c
| 33,852,932,288,159 |
01a5d6dd1af510e80330426f1afc2743ce7c5f7d
|
/src/com/diary/util/BaseConstants.java
|
40271c09b82f1164f3562cd20b4a7e8791fc4d2d
|
[] |
no_license
|
CNCUI/Diary
|
https://github.com/CNCUI/Diary
|
ee08d7569fc475c088547997e758aa0790bd795b
|
e4ffbb9207418a310304d0f38291fb7d01af047b
|
refs/heads/master
| 2021-05-11T00:49:15.851000 | 2018-03-19T13:30:42 | 2018-03-19T13:30:42 | 118,310,938 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.diary.util;
public enum BaseConstants {
START(0,"0","³ُت¼"),
ACCEPT(1,"1","½ستص"),
REFUSE(2,"2","¾ـ¾ّ");
int num;
String value;
String descri;
BaseConstants(int n,String val,String des){
num = n;
value = val;
descri = des;
}
public String getValue(){
return value;
}
}
|
WINDOWS-1256
|
Java
| 332 |
java
|
BaseConstants.java
|
Java
|
[] | null |
[] |
package com.diary.util;
public enum BaseConstants {
START(0,"0","³ُت¼"),
ACCEPT(1,"1","½ستص"),
REFUSE(2,"2","¾ـ¾ّ");
int num;
String value;
String descri;
BaseConstants(int n,String val,String des){
num = n;
value = val;
descri = des;
}
public String getValue(){
return value;
}
}
| 332 | 0.596875 | 0.5625 | 19 | 14.842105 | 11.122585 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.947368 | false | false |
14
|
beddd8d0da229802fe1ae1a1713ccefa5821f80d
| 17,008,070,552,258 |
e474e576a09ff3062907a67c543aa8b73b3c49e6
|
/SparkConverterGeneratorPlugin/src/com/helospark/spark/converter/handlers/service/collector/collectors/MethodCollectorChain.java
|
1d95947bb5cad1138bfd7ba3e404306217429efd
|
[
"MIT"
] |
permissive
|
shark300/SparkTools
|
https://github.com/shark300/SparkTools
|
e0af6e2db7198b7b60eca29877cf3a9af7b45997
|
afee01f9161ee1721d071bf597816b61273b429e
|
refs/heads/master
| 2021-01-22T22:45:08.607000 | 2017-03-18T11:26:47 | 2017-03-18T11:26:47 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.helospark.spark.converter.handlers.service.collector.collectors;
import java.util.List;
import com.helospark.spark.converter.handlers.domain.ConverterInputParameters;
import com.helospark.spark.converter.handlers.domain.ConverterTypeCodeGenerationRequest;
import com.helospark.spark.converter.handlers.service.common.domain.ConvertType;
import com.helospark.spark.converter.handlers.service.common.domain.SourceDestinationType;
public interface MethodCollectorChain {
public ConverterTypeCodeGenerationRequest handle(ConverterInputParameters converterInputParameters, SourceDestinationType sourceDestination,
List<ConverterTypeCodeGenerationRequest> result);
public boolean canHandle(ConvertType type);
}
|
UTF-8
|
Java
| 742 |
java
|
MethodCollectorChain.java
|
Java
|
[] | null |
[] |
package com.helospark.spark.converter.handlers.service.collector.collectors;
import java.util.List;
import com.helospark.spark.converter.handlers.domain.ConverterInputParameters;
import com.helospark.spark.converter.handlers.domain.ConverterTypeCodeGenerationRequest;
import com.helospark.spark.converter.handlers.service.common.domain.ConvertType;
import com.helospark.spark.converter.handlers.service.common.domain.SourceDestinationType;
public interface MethodCollectorChain {
public ConverterTypeCodeGenerationRequest handle(ConverterInputParameters converterInputParameters, SourceDestinationType sourceDestination,
List<ConverterTypeCodeGenerationRequest> result);
public boolean canHandle(ConvertType type);
}
| 742 | 0.8531 | 0.8531 | 16 | 45.375 | 43.181122 | 144 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.625 | false | false |
14
|
4001fe3b97de2ad79b5e7625024b42647341cd3e
| 11,458,972,813,204 |
1811ba8f5d58a94fc46aa8e00be267ef12eef709
|
/PrintDiagonalMatrix.java
|
62e6448a666fe00350e3bb187df86eb08584de01
|
[] |
no_license
|
saugatchetry/ProgrammingPractice
|
https://github.com/saugatchetry/ProgrammingPractice
|
45bb37234dc22873276700d9006fbce4a7f9a779
|
6eb0815d85b9d8da774d33e0d38f6c8423b8354d
|
refs/heads/master
| 2020-03-28T07:19:25.019000 | 2018-09-19T21:53:38 | 2018-09-19T21:53:38 | 147,894,334 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class PrintDiagonalMatrix {
public static void main(String[] args) {
int[][] matrix = new int[][]{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}
};
printDiagonal(matrix);
}
private static void printDiagonal(int[][] matrix) {
int rows = matrix.length - 1;
int columns = matrix[0].length - 1;
for(int k = 0; k <= rows; k++){
int j = 0;
int i = k;
while(i >= 0){
System.out.print(matrix[i][j]+" ");
i--;
j++;
}
System.out.println();
}
for(int k = 1; k <= columns; k++){
int i = rows;
int j = k;
while(j <= columns){
System.out.print(matrix[i][j]+" ");
i--;
j++;
}
System.out.println();
}
}
}
|
UTF-8
|
Java
| 1,000 |
java
|
PrintDiagonalMatrix.java
|
Java
|
[] | null |
[] |
public class PrintDiagonalMatrix {
public static void main(String[] args) {
int[][] matrix = new int[][]{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}
};
printDiagonal(matrix);
}
private static void printDiagonal(int[][] matrix) {
int rows = matrix.length - 1;
int columns = matrix[0].length - 1;
for(int k = 0; k <= rows; k++){
int j = 0;
int i = k;
while(i >= 0){
System.out.print(matrix[i][j]+" ");
i--;
j++;
}
System.out.println();
}
for(int k = 1; k <= columns; k++){
int i = rows;
int j = k;
while(j <= columns){
System.out.print(matrix[i][j]+" ");
i--;
j++;
}
System.out.println();
}
}
}
| 1,000 | 0.354 | 0.324 | 40 | 24 | 15.771811 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.875 | false | false |
14
|
9cb395ed05c54dde046d137a74c9c3acf0585acf
| 8,005,819,089,831 |
21e2712eac8e1cca5245d11386d30d3fb2addf07
|
/src/elements/array_string/minimize_unfairness.java
|
6b3646a7b6c6ea059e649cee3e9400c897a1e484
|
[] |
no_license
|
shou3301/interview_questions
|
https://github.com/shou3301/interview_questions
|
f00c399f5af44c9c58fe4ecb6e273a84ce94eafc
|
24995a3c15fc994ca1fb060e275eb83ede898a55
|
refs/heads/master
| 2016-09-05T14:12:07.754000 | 2015-06-07T06:54:44 | 2015-06-07T06:54:44 | 33,974,479 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
Description
You are given a list of N integers, the goal is to minimize the unfairness by selecting K integers from the list.
The unfairness is defined as following:
Max(x1,x2,…,xk) − Min(x1,x2,…,xk)
where (x1,x2,x3,…,xk) are K numbers selected from the list N, and the Max() picks the greatest integer among the elements of K, and the Min() picks the smallest integer among the elements of K.
Input
The input should include two lines. The first line should be a list of N non-negative integers less than or equal to 1,000,000,000, where 0 < N <= 100,000. And the second line should be K, where 2 <= K <= N.
Output
The result should be the number of minimum unfairness.
Sample Input
10 100 300 200 1000 20 30
3
Sample Output
20
*/
class Solution {
public int minimizeUnfairness(int [] a, int k) {
Arrays.sort(a);
int dis = Integer.MAX_VALUE;
for (int i = 0; i < a.length + 1 - k; i++) {
dis = Math.min(dis, a[i+k-1] - a[i]);
}
return dis;
}
}
|
UTF-8
|
Java
| 1,023 |
java
|
minimize_unfairness.java
|
Java
|
[] | null |
[] |
/*
Description
You are given a list of N integers, the goal is to minimize the unfairness by selecting K integers from the list.
The unfairness is defined as following:
Max(x1,x2,…,xk) − Min(x1,x2,…,xk)
where (x1,x2,x3,…,xk) are K numbers selected from the list N, and the Max() picks the greatest integer among the elements of K, and the Min() picks the smallest integer among the elements of K.
Input
The input should include two lines. The first line should be a list of N non-negative integers less than or equal to 1,000,000,000, where 0 < N <= 100,000. And the second line should be K, where 2 <= K <= N.
Output
The result should be the number of minimum unfairness.
Sample Input
10 100 300 200 1000 20 30
3
Sample Output
20
*/
class Solution {
public int minimizeUnfairness(int [] a, int k) {
Arrays.sort(a);
int dis = Integer.MAX_VALUE;
for (int i = 0; i < a.length + 1 - k; i++) {
dis = Math.min(dis, a[i+k-1] - a[i]);
}
return dis;
}
}
| 1,023 | 0.665025 | 0.615764 | 34 | 28.882353 | 48.888084 | 207 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.852941 | false | false |
14
|
dbe1f120647ee71b1c74edf44e5ea6c9cb719a94
| 11,733,850,713,278 |
ec568b717aaacdc500e5538aee82954b66d16284
|
/Java/Proyectos_InterfazGrafica/Empresa_CRUD_Avanzado_Swing/Proyecto_3T_E1/src/vista/FicherosTabla.java
|
7127694771676ea4dfe8cbb722e33422a201f28e
|
[] |
no_license
|
srepeto/Portfolio_SaraRepeto
|
https://github.com/srepeto/Portfolio_SaraRepeto
|
93aa787fb30b53fa4da2a28b432dc43dfce1dd9e
|
c0292d5841a4b18d0db3dcf75eed940c8ad00750
|
refs/heads/master
| 2023-02-20T00:25:00.407000 | 2021-01-25T20:41:30 | 2021-01-25T20:43:26 | 332,539,573 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package vista;
import java.io.File;
import java.net.URL;
import java.sql.*;
import controlador.TestGestionSAFA;
import modelo.ExtraerFicheros;
import javax.help.HelpBroker;
import javax.help.HelpSet;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class FicherosTabla {
JFrame marco;
public FicherosTabla (JFrame marco) {
this.marco = marco;
}
public void FichTablaGUI () {
JPanel panelFichTab = new JPanel();
panelFichTab.setBorder(new EmptyBorder(0,-35,0,0));
Icon logoMariaDB = new ImageIcon(TestGestionSAFA.class.getResource("/Fich_tabla.png"));
JLabel etiLogoMariaDB = new JLabel(logoMariaDB);
etiLogoMariaDB.setBorder(new EmptyBorder(70, 40, 40, 40));
JPanel panelBotFT = new JPanel(new GridLayout(1,3,5,0));
//panelBotFT.setBorder(new EmptyBorder(70, 5, 0, 5));
JButton botGestionFT = new JButton("Gestión Empresas");
botGestionFT.setPreferredSize(new Dimension(270,40));
botGestionFT.setBorder(new EmptyBorder(0,40,0,0));
JButton botAsigFT = new JButton("Asignación Alumnos");
botAsigFT.setPreferredSize(new Dimension(270,40));
botAsigFT.setBorder(new EmptyBorder(0,0,0,0));
JButton botFichFT = new JButton("Ficheros a BBDD");
botFichFT.setPreferredSize(new Dimension(270,40));
botFichFT.setBorder(new EmptyBorder(0,0,0,0));
botFichFT.setSelected(true);
botFichFT.setFocusable(false);
JButton botFichTab = new JButton("Importar info a BBDD");
botFichTab.setPreferredSize(new Dimension(157,30));
JPanel panelIcono = new JPanel();
panelIcono.setBorder(new EmptyBorder(10,300,0,0));
JLabel fondo;
ImageIcon img = new ImageIcon("res/SAFA.jpg");
Image img1 = img.getImage();
Image newImg = img1.getScaledInstance(50,50, Image.SCALE_SMOOTH);
ImageIcon imgg = new ImageIcon(newImg);
fondo = new JLabel("",imgg,JLabel.CENTER);
JPanel panelBoton = new JPanel();
panelBoton.add(botFichTab);
JPanel panelMenu = new JPanel(new FlowLayout());
panelMenu.setBorder(new EmptyBorder(-5,-5,-5,680));
JMenuBar barra = new JMenuBar();
JMenu menu = new JMenu("Menú");
JMenuItem ayuda = new JMenuItem("Ayuda");
menu.add(ayuda);
barra.add(menu);
menu.add(ayuda);
panelMenu.add(barra);
panelIcono.add(fondo);
panelIcono.setBorder(BorderFactory.createEmptyBorder(7,460,0,0));
panelBoton.setBorder(BorderFactory.createEmptyBorder(0,120,40,0));
panelBotFT.add(botGestionFT);
panelBotFT.add(botAsigFT);
panelBotFT.add(botFichFT);
panelFichTab.add(panelMenu);
panelFichTab.add(panelBotFT, BorderLayout.NORTH);
panelFichTab.add(etiLogoMariaDB, BorderLayout.CENTER);
panelFichTab.add(panelBoton, BorderLayout.SOUTH);
panelFichTab.add(panelIcono);
File fichero = new File("help/help_set.hs");
try {
URL hsURL = fichero.toURI().toURL();
HelpSet helpset = new HelpSet(getClass().getClassLoader(), hsURL);
HelpBroker hb = helpset.createHelpBroker();
hb.enableHelpOnButton(ayuda, "inicio", helpset);
ayuda.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1, 0));
} catch (Exception e) {
System.out.println(e);
}
// -------- ACCIONES DE BOTONES -----------
ActionListener accionBotFT = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource() == botAsigFT) {
AsigAlum ObjAA = new AsigAlum(marco);
ObjAA.asigAlumGUI();
}
if(e.getSource() == botFichTab) {
try {
ExtraerFicheros objFT = new ExtraerFicheros();
objFT.FichXML();
objFT.FichDat();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
if(e.getSource() == botGestionFT) {
GestionEmpresas ObjGE = new GestionEmpresas(marco);
ObjGE.GestEmpGUI();
}
}
};
botFichTab.addActionListener(accionBotFT);
botAsigFT.addActionListener(accionBotFT);
botGestionFT.addActionListener(accionBotFT);
// -----------------
marco.setContentPane(panelFichTab);
marco.invalidate();
marco.setSize(800,525);
marco.validate();
marco.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
marco.setResizable(false);
marco.setVisible(true);
}
}
|
UTF-8
|
Java
| 4,936 |
java
|
FicherosTabla.java
|
Java
|
[] | null |
[] |
package vista;
import java.io.File;
import java.net.URL;
import java.sql.*;
import controlador.TestGestionSAFA;
import modelo.ExtraerFicheros;
import javax.help.HelpBroker;
import javax.help.HelpSet;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class FicherosTabla {
JFrame marco;
public FicherosTabla (JFrame marco) {
this.marco = marco;
}
public void FichTablaGUI () {
JPanel panelFichTab = new JPanel();
panelFichTab.setBorder(new EmptyBorder(0,-35,0,0));
Icon logoMariaDB = new ImageIcon(TestGestionSAFA.class.getResource("/Fich_tabla.png"));
JLabel etiLogoMariaDB = new JLabel(logoMariaDB);
etiLogoMariaDB.setBorder(new EmptyBorder(70, 40, 40, 40));
JPanel panelBotFT = new JPanel(new GridLayout(1,3,5,0));
//panelBotFT.setBorder(new EmptyBorder(70, 5, 0, 5));
JButton botGestionFT = new JButton("Gestión Empresas");
botGestionFT.setPreferredSize(new Dimension(270,40));
botGestionFT.setBorder(new EmptyBorder(0,40,0,0));
JButton botAsigFT = new JButton("Asignación Alumnos");
botAsigFT.setPreferredSize(new Dimension(270,40));
botAsigFT.setBorder(new EmptyBorder(0,0,0,0));
JButton botFichFT = new JButton("Ficheros a BBDD");
botFichFT.setPreferredSize(new Dimension(270,40));
botFichFT.setBorder(new EmptyBorder(0,0,0,0));
botFichFT.setSelected(true);
botFichFT.setFocusable(false);
JButton botFichTab = new JButton("Importar info a BBDD");
botFichTab.setPreferredSize(new Dimension(157,30));
JPanel panelIcono = new JPanel();
panelIcono.setBorder(new EmptyBorder(10,300,0,0));
JLabel fondo;
ImageIcon img = new ImageIcon("res/SAFA.jpg");
Image img1 = img.getImage();
Image newImg = img1.getScaledInstance(50,50, Image.SCALE_SMOOTH);
ImageIcon imgg = new ImageIcon(newImg);
fondo = new JLabel("",imgg,JLabel.CENTER);
JPanel panelBoton = new JPanel();
panelBoton.add(botFichTab);
JPanel panelMenu = new JPanel(new FlowLayout());
panelMenu.setBorder(new EmptyBorder(-5,-5,-5,680));
JMenuBar barra = new JMenuBar();
JMenu menu = new JMenu("Menú");
JMenuItem ayuda = new JMenuItem("Ayuda");
menu.add(ayuda);
barra.add(menu);
menu.add(ayuda);
panelMenu.add(barra);
panelIcono.add(fondo);
panelIcono.setBorder(BorderFactory.createEmptyBorder(7,460,0,0));
panelBoton.setBorder(BorderFactory.createEmptyBorder(0,120,40,0));
panelBotFT.add(botGestionFT);
panelBotFT.add(botAsigFT);
panelBotFT.add(botFichFT);
panelFichTab.add(panelMenu);
panelFichTab.add(panelBotFT, BorderLayout.NORTH);
panelFichTab.add(etiLogoMariaDB, BorderLayout.CENTER);
panelFichTab.add(panelBoton, BorderLayout.SOUTH);
panelFichTab.add(panelIcono);
File fichero = new File("help/help_set.hs");
try {
URL hsURL = fichero.toURI().toURL();
HelpSet helpset = new HelpSet(getClass().getClassLoader(), hsURL);
HelpBroker hb = helpset.createHelpBroker();
hb.enableHelpOnButton(ayuda, "inicio", helpset);
ayuda.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1, 0));
} catch (Exception e) {
System.out.println(e);
}
// -------- ACCIONES DE BOTONES -----------
ActionListener accionBotFT = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource() == botAsigFT) {
AsigAlum ObjAA = new AsigAlum(marco);
ObjAA.asigAlumGUI();
}
if(e.getSource() == botFichTab) {
try {
ExtraerFicheros objFT = new ExtraerFicheros();
objFT.FichXML();
objFT.FichDat();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
if(e.getSource() == botGestionFT) {
GestionEmpresas ObjGE = new GestionEmpresas(marco);
ObjGE.GestEmpGUI();
}
}
};
botFichTab.addActionListener(accionBotFT);
botAsigFT.addActionListener(accionBotFT);
botGestionFT.addActionListener(accionBotFT);
// -----------------
marco.setContentPane(panelFichTab);
marco.invalidate();
marco.setSize(800,525);
marco.validate();
marco.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
marco.setResizable(false);
marco.setVisible(true);
}
}
| 4,936 | 0.608555 | 0.589297 | 139 | 34.489208 | 23.585865 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.007194 | false | false |
14
|
0190ca682bff249963701fb41aceb0142ca65ca6
| 11,115,375,414,030 |
021a4e043c4b12c7af00f5c4cd9d30c2bde20eed
|
/src/main/java/com/tgt/app/controller/ProductPricingController.java
|
54e139d8b081b7678c0398dfa2e66f50ac819be4
|
[] |
no_license
|
Bonythomasv/MyRetail-RestFullService
|
https://github.com/Bonythomasv/MyRetail-RestFullService
|
e5a0c0fbb81d10d96984e78702bc784811a5f6f0
|
15c67a7d40d18e8f7cc5eaad92009222ba23dd9f
|
refs/heads/master
| 2021-01-01T04:26:31.166000 | 2016-04-26T23:52:40 | 2016-04-26T23:52:40 | 57,010,789 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.tgt.app.controller;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.tgt.app.service.ProductService;
import com.tgt.response.ProductPricing;
/**
* @author BonyThomas:
* @Description: This controller provides the REST methods
*/
@RestController
public class ProductPricingController {
private static final Logger log = LoggerFactory.getLogger(ProductPricingController.class);
// Spring DI inject the service
@Autowired
private ProductService productService;
/*
* @Description: HTTP GET method for querying the Product Information
* @param: UserId from URL
* @return: ProductPricing JSON
* Sample Response JSON is : {"id":13860428,"name":"The Big Lebowski (Blu-ray) (Widescreen)","current_price":{"value": 13.49,"currency_code":"USD"}}
*/
@RequestMapping(value= "/products/{id}",method = RequestMethod.GET)
public ProductPricing productPricing(@PathVariable(value="id") String Id) throws Exception {
//log.info("IDproductPricing.getName()=="" is "+Id);
ProductPricing productPricing = new ProductPricing();
//Numeric value validation for Id
String regex = "[0-9]+";
if(Id==null || !Id.matches(regex))
{
productPricing.setErrorMsg("Product Id in URL arguments should be a number");
}
else
{
productPricing= productService.searchProductPrice(Id.toString());
if (productPricing==null || productPricing.getCurrentPrice() == null||productPricing.getName()==null)
{
productPricing = new ProductPricing();
productPricing.setErrorMsg("No Products Found with the Id "+Id);
}
}
return productPricing;
}
/*
* @Description: //inserting product Price to Mongo DB: Pay Load JSON data will be inserted
* @param: ProductPricing JSON
* @return: success/failure Message
*/
@RequestMapping(value= "/products/{id}",method = RequestMethod.PUT)
public String productPricing(@PathVariable(value="id") String Id, @RequestBody Map<String, Object> insertProductPricing ) throws Exception {
System.out.println("ID is "+Id);
String responseMsg ="";
String regex = "[0-9]+";
log.info("Id.matches(regex) is "+Id.matches(regex));
if(Id==null || !Id.matches(regex) || insertProductPricing == null)
{
responseMsg= "Incorrect Data!!! Please vallidate Id or RequestBody";
}
else
{
if( productService.insertNewProduct(insertProductPricing) == true)
responseMsg = "Product Data Inserted Successfully";
else
responseMsg = "Product Data Insert Failed";
}
return responseMsg;
}
/*
* @Description: To handle improper URL arguments. This helps to avoid Querying the entire data in Mongo DB
* @return: Error Message
*/
@RequestMapping(value= "/products",method = RequestMethod.GET)
public ProductPricing productPricingNoArgs() throws Exception {
ProductPricing productPricing = new ProductPricing();
productPricing.setErrorMsg("Product Id is missing in Rest Service URL arguments ");
return productPricing;
}
}
|
UTF-8
|
Java
| 3,462 |
java
|
ProductPricingController.java
|
Java
|
[
{
"context": " com.tgt.response.ProductPricing;\n\n\n/**\n * @author BonyThomas:\n * @Description: This controller provides the RE",
"end": 597,
"score": 0.9997040629386902,
"start": 587,
"tag": "NAME",
"value": "BonyThomas"
}
] | null |
[] |
package com.tgt.app.controller;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.tgt.app.service.ProductService;
import com.tgt.response.ProductPricing;
/**
* @author BonyThomas:
* @Description: This controller provides the REST methods
*/
@RestController
public class ProductPricingController {
private static final Logger log = LoggerFactory.getLogger(ProductPricingController.class);
// Spring DI inject the service
@Autowired
private ProductService productService;
/*
* @Description: HTTP GET method for querying the Product Information
* @param: UserId from URL
* @return: ProductPricing JSON
* Sample Response JSON is : {"id":13860428,"name":"The Big Lebowski (Blu-ray) (Widescreen)","current_price":{"value": 13.49,"currency_code":"USD"}}
*/
@RequestMapping(value= "/products/{id}",method = RequestMethod.GET)
public ProductPricing productPricing(@PathVariable(value="id") String Id) throws Exception {
//log.info("IDproductPricing.getName()=="" is "+Id);
ProductPricing productPricing = new ProductPricing();
//Numeric value validation for Id
String regex = "[0-9]+";
if(Id==null || !Id.matches(regex))
{
productPricing.setErrorMsg("Product Id in URL arguments should be a number");
}
else
{
productPricing= productService.searchProductPrice(Id.toString());
if (productPricing==null || productPricing.getCurrentPrice() == null||productPricing.getName()==null)
{
productPricing = new ProductPricing();
productPricing.setErrorMsg("No Products Found with the Id "+Id);
}
}
return productPricing;
}
/*
* @Description: //inserting product Price to Mongo DB: Pay Load JSON data will be inserted
* @param: ProductPricing JSON
* @return: success/failure Message
*/
@RequestMapping(value= "/products/{id}",method = RequestMethod.PUT)
public String productPricing(@PathVariable(value="id") String Id, @RequestBody Map<String, Object> insertProductPricing ) throws Exception {
System.out.println("ID is "+Id);
String responseMsg ="";
String regex = "[0-9]+";
log.info("Id.matches(regex) is "+Id.matches(regex));
if(Id==null || !Id.matches(regex) || insertProductPricing == null)
{
responseMsg= "Incorrect Data!!! Please vallidate Id or RequestBody";
}
else
{
if( productService.insertNewProduct(insertProductPricing) == true)
responseMsg = "Product Data Inserted Successfully";
else
responseMsg = "Product Data Insert Failed";
}
return responseMsg;
}
/*
* @Description: To handle improper URL arguments. This helps to avoid Querying the entire data in Mongo DB
* @return: Error Message
*/
@RequestMapping(value= "/products",method = RequestMethod.GET)
public ProductPricing productPricingNoArgs() throws Exception {
ProductPricing productPricing = new ProductPricing();
productPricing.setErrorMsg("Product Id is missing in Rest Service URL arguments ");
return productPricing;
}
}
| 3,462 | 0.716927 | 0.711727 | 108 | 31.055555 | 33.389629 | 152 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.453704 | false | false |
14
|
3cebab0c730b6bb3a90deb6f6aeec34f859c92a7
| 4,389,456,638,527 |
1bc1f7dc1ac8740b48ba7f4a70143e0dd7a1a108
|
/framework/application/kernel/core/src/main/java/org/ldp4j/application/kernel/lifecycle/DefaultLifecycleEnvironment.java
|
5b4903266e6ee0498d120cbe099ff7f28c47ce40
|
[
"Apache-2.0"
] |
permissive
|
tool-recommender-bot/ldp4j
|
https://github.com/tool-recommender-bot/ldp4j
|
a23cfacd88a0d24f9d38f9c703fcfbad58ad2e50
|
4236dfb3a746be390155c1056bbb5a8d4dccc49f
|
refs/heads/master
| 2020-04-18T21:45:39.082000 | 2017-06-16T22:26:04 | 2017-06-16T22:26:04 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
* This file is part of the LDP4j Project:
* http://www.ldp4j.org/
*
* Center for Open Middleware
* http://www.centeropenmiddleware.com/
* #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
* Copyright (C) 2014-2016 Center for Open Middleware.
* #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
* 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.
* #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
* Artifact : org.ldp4j.framework:ldp4j-application-kernel-core:0.2.2
* Bundle : ldp4j-application-kernel-core-0.2.2.jar
* #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
*/
package org.ldp4j.application.kernel.lifecycle;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Iterator;
import java.util.LinkedList;
import org.ldp4j.application.ApplicationContext;
import org.ldp4j.application.engine.ApplicationContextBootstrapException;
import org.ldp4j.application.lifecycle.ApplicationLifecycleListener;
import org.ldp4j.application.lifecycle.LifecycleEnvironment;
import org.ldp4j.application.lifecycle.Managed;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Lists;
final class DefaultLifecycleEnvironment implements LifecycleEnvironment {
private static final Logger LOGGER=LoggerFactory.getLogger(DefaultLifecycleEnvironment.class);
private final LinkedList<Managed> managedObjects; // NOSONAR
private final LinkedList<ApplicationLifecycleListener> listeners; // NOSONAR
DefaultLifecycleEnvironment() {
this.managedObjects=Lists.newLinkedList();
this.listeners=Lists.newLinkedList();
}
@Override
public void register(Managed managed) {
checkNotNull(managed,"Managed objects cannot be null");
this.managedObjects.add(managed);
LOGGER.debug("Registered managed object {}",managed);
}
@Override
public void addApplicationLifecycleListener(ApplicationLifecycleListener listener) {
checkNotNull(listener,"Application lifecycle listeners cannot be null");
this.listeners.add(listener);
LOGGER.debug("Registered application lifecycle listener {}",listener);
}
void start(ApplicationContext context) throws ApplicationContextBootstrapException {
LOGGER.info("Starting application components...");
LOGGER.debug("Starting managed objects...");
for(Managed managed:this.managedObjects) {
try {
managed.start();
LOGGER.trace("Started managed object {}.",managed);
} catch(Exception e) {
LOGGER.warn("Could not start managed object {}",managed,e);
throw new ApplicationContextBootstrapException("Could not start managed object "+managed, e);
}
}
LOGGER.debug("Notifying start-up event to application lifecycle listeners...");
for(ApplicationLifecycleListener listener:this.listeners) {
try {
listener.applicationStarted(context);
LOGGER.trace("Notified start-up to {}.",listener);
} catch(Exception e) {
LOGGER.warn("Listener {} failed when notifying startup",listener,e);
throw new ApplicationContextBootstrapException("Listeners "+listener+" failed when notifying startup", e);
}
}
LOGGER.info("Application components started.");
}
void stop() {
LOGGER.info("Stopping application components...");
LOGGER.debug("Stopping managed objects...");
Iterator<Managed> iterator = this.managedObjects.descendingIterator();
while(iterator.hasNext()) {
Managed managed=iterator.next();
try {
managed.stop();
LOGGER.trace("Stopped managed object {}.",managed);
} catch(Exception e) {
LOGGER.warn("Could not stop managed object {}",managed,e);
}
}
LOGGER.debug("Notifying stop event to application lifecycle listeners...");
for(ApplicationLifecycleListener listener:this.listeners) {
try {
listener.applicationStopped();
LOGGER.trace("Notified stop to {}.",listener);
} catch(Exception e) {
LOGGER.warn("Listener {} failed when notifying stop",listener,e);
}
}
LOGGER.info("Application components stopped.");
}
}
|
UTF-8
|
Java
| 4,694 |
java
|
DefaultLifecycleEnvironment.java
|
Java
|
[] | null |
[] |
/**
* #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
* This file is part of the LDP4j Project:
* http://www.ldp4j.org/
*
* Center for Open Middleware
* http://www.centeropenmiddleware.com/
* #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
* Copyright (C) 2014-2016 Center for Open Middleware.
* #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
* 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.
* #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
* Artifact : org.ldp4j.framework:ldp4j-application-kernel-core:0.2.2
* Bundle : ldp4j-application-kernel-core-0.2.2.jar
* #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
*/
package org.ldp4j.application.kernel.lifecycle;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Iterator;
import java.util.LinkedList;
import org.ldp4j.application.ApplicationContext;
import org.ldp4j.application.engine.ApplicationContextBootstrapException;
import org.ldp4j.application.lifecycle.ApplicationLifecycleListener;
import org.ldp4j.application.lifecycle.LifecycleEnvironment;
import org.ldp4j.application.lifecycle.Managed;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Lists;
final class DefaultLifecycleEnvironment implements LifecycleEnvironment {
private static final Logger LOGGER=LoggerFactory.getLogger(DefaultLifecycleEnvironment.class);
private final LinkedList<Managed> managedObjects; // NOSONAR
private final LinkedList<ApplicationLifecycleListener> listeners; // NOSONAR
DefaultLifecycleEnvironment() {
this.managedObjects=Lists.newLinkedList();
this.listeners=Lists.newLinkedList();
}
@Override
public void register(Managed managed) {
checkNotNull(managed,"Managed objects cannot be null");
this.managedObjects.add(managed);
LOGGER.debug("Registered managed object {}",managed);
}
@Override
public void addApplicationLifecycleListener(ApplicationLifecycleListener listener) {
checkNotNull(listener,"Application lifecycle listeners cannot be null");
this.listeners.add(listener);
LOGGER.debug("Registered application lifecycle listener {}",listener);
}
void start(ApplicationContext context) throws ApplicationContextBootstrapException {
LOGGER.info("Starting application components...");
LOGGER.debug("Starting managed objects...");
for(Managed managed:this.managedObjects) {
try {
managed.start();
LOGGER.trace("Started managed object {}.",managed);
} catch(Exception e) {
LOGGER.warn("Could not start managed object {}",managed,e);
throw new ApplicationContextBootstrapException("Could not start managed object "+managed, e);
}
}
LOGGER.debug("Notifying start-up event to application lifecycle listeners...");
for(ApplicationLifecycleListener listener:this.listeners) {
try {
listener.applicationStarted(context);
LOGGER.trace("Notified start-up to {}.",listener);
} catch(Exception e) {
LOGGER.warn("Listener {} failed when notifying startup",listener,e);
throw new ApplicationContextBootstrapException("Listeners "+listener+" failed when notifying startup", e);
}
}
LOGGER.info("Application components started.");
}
void stop() {
LOGGER.info("Stopping application components...");
LOGGER.debug("Stopping managed objects...");
Iterator<Managed> iterator = this.managedObjects.descendingIterator();
while(iterator.hasNext()) {
Managed managed=iterator.next();
try {
managed.stop();
LOGGER.trace("Stopped managed object {}.",managed);
} catch(Exception e) {
LOGGER.warn("Could not stop managed object {}",managed,e);
}
}
LOGGER.debug("Notifying stop event to application lifecycle listeners...");
for(ApplicationLifecycleListener listener:this.listeners) {
try {
listener.applicationStopped();
LOGGER.trace("Notified stop to {}.",listener);
} catch(Exception e) {
LOGGER.warn("Listener {} failed when notifying stop",listener,e);
}
}
LOGGER.info("Application components stopped.");
}
}
| 4,694 | 0.683 | 0.676395 | 120 | 38.125 | 29.583094 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.916667 | false | false |
14
|
405528f078bab5a54b0173b15ba00bc772f556da
| 25,804,163,576,861 |
0369843cb236c235d21bfb4a8265ca545ce0cc94
|
/de.robind.swt.msg/src/main/java/de/robind/swt/msg/SWTAttrResponse.java
|
b9fa3a6dcc5709621b88c60aa7a0e82c3778246d
|
[] |
no_license
|
drobin/swt-ria
|
https://github.com/drobin/swt-ria
|
a44de167d715bfd44d3d0c4120107d74783f7f9c
|
2a54f5402176b9757491dc2d3f633f88d10da5fe
|
refs/heads/master
| 2021-01-15T11:43:16.536000 | 2012-02-04T16:59:43 | 2012-02-04T16:59:43 | 2,867,448 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package de.robind.swt.msg;
/**
* The response-message of a {@link SWTAttrRequest}.
* <p>
* Updating an attribute does not return a result, so this message does not
* has any properties.
*
* @author Robin Doer
*/
public interface SWTAttrResponse extends SWTResponse {
}
|
UTF-8
|
Java
| 277 |
java
|
SWTAttrResponse.java
|
Java
|
[
{
"context": "sage does not\n * has any properties.\n *\n * @author Robin Doer\n */\npublic interface SWTAttrResponse extends SWTR",
"end": 215,
"score": 0.9998546838760376,
"start": 205,
"tag": "NAME",
"value": "Robin Doer"
}
] | null |
[] |
package de.robind.swt.msg;
/**
* The response-message of a {@link SWTAttrRequest}.
* <p>
* Updating an attribute does not return a result, so this message does not
* has any properties.
*
* @author <NAME>
*/
public interface SWTAttrResponse extends SWTResponse {
}
| 273 | 0.718412 | 0.718412 | 12 | 22.083334 | 24.243412 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.166667 | false | false |
14
|
f310b8ab38dd86314ec16a0a54d18f2cbd1ead08
| 21,303,037,858,548 |
ae069bf92ccd1e3dd000b3c6b3ca894cd9eca537
|
/Selenium-examples/01-02-2021-20210208T121350Z-001/01-02-2021/tests/AddProductToCart.java
|
6eee8f20f24587f043c4869c93ba54f9cb48103c
|
[] |
no_license
|
vsale85/ITBootcamp
|
https://github.com/vsale85/ITBootcamp
|
0c2de36a65cf88c9bd4b9427bd6726f51f1cadb4
|
c88aef12c3dece1ae3744eac42bd2ab034d8888d
|
refs/heads/main
| 2023-03-03T23:23:25.421000 | 2021-02-10T16:04:33 | 2021-02-10T16:04:33 | 337,772,753 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package tests;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class AddProductToCart extends BaseTests {
@BeforeMethod
public void beforeMethod() throws InterruptedException {
driver.navigate().to("http://cms.demo.katalon.com/");
Thread.sleep(2000);
}
// @Test (priority = 5)
public void addProductToCart() throws InterruptedException {
mainPage.navigateToShop();
Thread.sleep(2000);
shopPage.addToCartClick();
Thread.sleep(2000);
shopPage.viewCartClick();
Thread.sleep(2000);
String name = cartPage.getProductName().getText();
Assert.assertEquals(name, "Flying Ninja");
}
@Test (priority = 6)
public void add3ProductToCart() throws InterruptedException {
mainPage.navigateToShop();
Thread.sleep(2000);
shopPage.addToCartClick3();
Thread.sleep(2000);
shopPage.viewCartClick();
Thread.sleep(2000);
String name1 = cartPage.getProductName().getText();
Assert.assertEquals(name1, citac.getCellData("cartRemove", 2, 2));
String name2 = cartPage.getProductName2().getText();
Assert.assertEquals(name2, citac.getCellData("cartRemove", 3, 2));
String name3 = cartPage.getProductName3().getText();
Assert.assertEquals(name3, citac.getCellData("cartRemove", 4, 2));
}
@Test (priority = 15)
public void add2ProductToCart() throws InterruptedException {
mainPage.navigateToShop();
Thread.sleep(2000);
shopPage.addToCart2Products();
Thread.sleep(2000);
shopPage.viewCartClick();
Thread.sleep(2000);
String name1 = cartPage.getProductName().getText();
Assert.assertEquals(name1, citac.getCellData("cartRemove", 2, 2));
String name2 = cartPage.getProductName2().getText();
Assert.assertEquals(name2, citac.getCellData("cartRemove", 3, 2));
}
@Test (priority = 16)
public void deleteOneProductFromCart() throws InterruptedException {
mainPage.navigateToCart();
Thread.sleep(2000);
cartPage.deleteProduct();
Thread.sleep(2000);
String verifyOneProduct = cartPage.getProductName().getText();
System.out.println(verifyOneProduct);
String expected = citac.getCellData("cartRemove", 3, 2);
Thread.sleep(2000);
Assert.assertEquals(verifyOneProduct, expected);
}
@Test (priority = 10)
public void delete3ProductFromCart() throws InterruptedException {
mainPage.navigateToCart();
Thread.sleep(2000);
cartPage.deleteProduct();
Thread.sleep(2000);
cartPage.deleteProduct();
Thread.sleep(2000);
cartPage.deleteProduct();
Thread.sleep(2000);
String verifyRemove = cartPage.getVerifyRemove().getText();
System.out.println(verifyRemove);
String expected = citac.getCellData("cartRemove", 1, 2);
Thread.sleep(2000);
Assert.assertEquals(verifyRemove, expected);
}
@AfterMethod
public void afterMethod() throws InterruptedException {
// driver.manage().deleteAllCookies();
driver.navigate().refresh();
Thread.sleep(2000);
}
}
|
UTF-8
|
Java
| 3,089 |
java
|
AddProductToCart.java
|
Java
|
[] | null |
[] |
package tests;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class AddProductToCart extends BaseTests {
@BeforeMethod
public void beforeMethod() throws InterruptedException {
driver.navigate().to("http://cms.demo.katalon.com/");
Thread.sleep(2000);
}
// @Test (priority = 5)
public void addProductToCart() throws InterruptedException {
mainPage.navigateToShop();
Thread.sleep(2000);
shopPage.addToCartClick();
Thread.sleep(2000);
shopPage.viewCartClick();
Thread.sleep(2000);
String name = cartPage.getProductName().getText();
Assert.assertEquals(name, "Flying Ninja");
}
@Test (priority = 6)
public void add3ProductToCart() throws InterruptedException {
mainPage.navigateToShop();
Thread.sleep(2000);
shopPage.addToCartClick3();
Thread.sleep(2000);
shopPage.viewCartClick();
Thread.sleep(2000);
String name1 = cartPage.getProductName().getText();
Assert.assertEquals(name1, citac.getCellData("cartRemove", 2, 2));
String name2 = cartPage.getProductName2().getText();
Assert.assertEquals(name2, citac.getCellData("cartRemove", 3, 2));
String name3 = cartPage.getProductName3().getText();
Assert.assertEquals(name3, citac.getCellData("cartRemove", 4, 2));
}
@Test (priority = 15)
public void add2ProductToCart() throws InterruptedException {
mainPage.navigateToShop();
Thread.sleep(2000);
shopPage.addToCart2Products();
Thread.sleep(2000);
shopPage.viewCartClick();
Thread.sleep(2000);
String name1 = cartPage.getProductName().getText();
Assert.assertEquals(name1, citac.getCellData("cartRemove", 2, 2));
String name2 = cartPage.getProductName2().getText();
Assert.assertEquals(name2, citac.getCellData("cartRemove", 3, 2));
}
@Test (priority = 16)
public void deleteOneProductFromCart() throws InterruptedException {
mainPage.navigateToCart();
Thread.sleep(2000);
cartPage.deleteProduct();
Thread.sleep(2000);
String verifyOneProduct = cartPage.getProductName().getText();
System.out.println(verifyOneProduct);
String expected = citac.getCellData("cartRemove", 3, 2);
Thread.sleep(2000);
Assert.assertEquals(verifyOneProduct, expected);
}
@Test (priority = 10)
public void delete3ProductFromCart() throws InterruptedException {
mainPage.navigateToCart();
Thread.sleep(2000);
cartPage.deleteProduct();
Thread.sleep(2000);
cartPage.deleteProduct();
Thread.sleep(2000);
cartPage.deleteProduct();
Thread.sleep(2000);
String verifyRemove = cartPage.getVerifyRemove().getText();
System.out.println(verifyRemove);
String expected = citac.getCellData("cartRemove", 1, 2);
Thread.sleep(2000);
Assert.assertEquals(verifyRemove, expected);
}
@AfterMethod
public void afterMethod() throws InterruptedException {
// driver.manage().deleteAllCookies();
driver.navigate().refresh();
Thread.sleep(2000);
}
}
| 3,089 | 0.710586 | 0.673033 | 109 | 26.339449 | 21.814573 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.201835 | false | false |
14
|
36e218121821ed20d1bae27b6f0b77a482b1de92
| 35,227,321,802,187 |
fa091afe016e854eda207cf4bd6e6c7771f041c3
|
/server/src/main/java/net/workspace/web/web/plugin/Worker.java
|
2d788c184eba06b96b7847b5679f168c4c8d8c68
|
[] |
no_license
|
rusteer/and-message
|
https://github.com/rusteer/and-message
|
ae2e4750cb2fb8804dfc5cecfe753270bcbd8cc9
|
ee06bf0988a7a37570aa740fe3c687f0cbf7ea20
|
refs/heads/master
| 2016-06-10T07:59:27.603000 | 2016-04-14T10:59:55 | 2016-04-14T10:59:55 | 56,229,403 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package net.workspace.web.web.plugin;
import javax.servlet.http.HttpServletRequest;
import net.workspace.web.entity.AreaEntity;
import net.workspace.web.entity.IpInfoEntity;
import net.workspace.web.entity.LogEntity;
import net.workspace.web.entity.client.ClientEntity;
import net.workspace.web.service.AreaService;
import net.workspace.web.service.IpInfoService;
import net.workspace.web.service.LogService;
import net.workspace.web.service.MobileInfoService;
import net.workspace.web.service.OrderService;
import net.workspace.web.service.SettingService;
import net.workspace.web.service.biz.BizService;
import net.workspace.web.service.channel.ChannelService;
import net.workspace.web.service.client.ClientService;
import net.workspace.web.service.record.OrderRecordService;
import net.workspace.web.web.WebUtil;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
public abstract class Worker {
protected static final Logger clientLogger = LoggerFactory.getLogger("PluginLogger");
protected static final Logger errorLogger = LoggerFactory.getLogger("ErrorLogger");
@Autowired
OrderService orderService;
@Autowired
ClientService clientService;
@Autowired
OrderRecordService orderRecordService;
@Autowired
AreaService areaService;
@Autowired
BizService bizService;
@Autowired
LogService logService;
@Autowired
SettingService settingService;
@Autowired
ChannelService channelService;
@Autowired
MobileInfoService mobileAreaService;
@Autowired
private IpInfoService ipRangeService;
protected void log(HttpServletRequest request, LogEntity entity) {
clientLogger.info(WebUtil.getRequestIp(request) + ",http://" + request.getHeader("HOST") + request.getHeader("REQUEST_PATH") + ":" + entity.toString() + "\n");
//clientLogger.info(getRemoteAddr(request) + request.getHeader("URI") + ":" + entity.toString() + "\n");
logService.log(entity);
}
protected boolean noPhoneArea(ClientEntity client) {
return client.getProvinceId() == null || client.getProvinceId() == 0;
}
protected void checkAreaByIp(HttpServletRequest request, ClientEntity client) {
if (client == null) {
errorLogger.error("Worker.checkAreaByIp:client is null");
return;
}
if (noPhoneArea(client) && "Y".equals(settingService.get().getEnableNoPhonePay())) {
String ip = WebUtil.getRequestIp(request);
IpInfoEntity info = this.ipRangeService.getAreaCode(ip);
if (info != null) {
client.setIpProvinceId(info.getProvinceId());
client.setIpAreaId(info.getCityId());
client.setIp(ip);
} else {
errorLogger.warn("no-ip-range-set: " + ip);
}
}
}
public abstract String execute(HttpServletRequest request, JSONObject input) throws Exception;
}
|
UTF-8
|
Java
| 3,068 |
java
|
Worker.java
|
Java
|
[] | null |
[] |
package net.workspace.web.web.plugin;
import javax.servlet.http.HttpServletRequest;
import net.workspace.web.entity.AreaEntity;
import net.workspace.web.entity.IpInfoEntity;
import net.workspace.web.entity.LogEntity;
import net.workspace.web.entity.client.ClientEntity;
import net.workspace.web.service.AreaService;
import net.workspace.web.service.IpInfoService;
import net.workspace.web.service.LogService;
import net.workspace.web.service.MobileInfoService;
import net.workspace.web.service.OrderService;
import net.workspace.web.service.SettingService;
import net.workspace.web.service.biz.BizService;
import net.workspace.web.service.channel.ChannelService;
import net.workspace.web.service.client.ClientService;
import net.workspace.web.service.record.OrderRecordService;
import net.workspace.web.web.WebUtil;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
public abstract class Worker {
protected static final Logger clientLogger = LoggerFactory.getLogger("PluginLogger");
protected static final Logger errorLogger = LoggerFactory.getLogger("ErrorLogger");
@Autowired
OrderService orderService;
@Autowired
ClientService clientService;
@Autowired
OrderRecordService orderRecordService;
@Autowired
AreaService areaService;
@Autowired
BizService bizService;
@Autowired
LogService logService;
@Autowired
SettingService settingService;
@Autowired
ChannelService channelService;
@Autowired
MobileInfoService mobileAreaService;
@Autowired
private IpInfoService ipRangeService;
protected void log(HttpServletRequest request, LogEntity entity) {
clientLogger.info(WebUtil.getRequestIp(request) + ",http://" + request.getHeader("HOST") + request.getHeader("REQUEST_PATH") + ":" + entity.toString() + "\n");
//clientLogger.info(getRemoteAddr(request) + request.getHeader("URI") + ":" + entity.toString() + "\n");
logService.log(entity);
}
protected boolean noPhoneArea(ClientEntity client) {
return client.getProvinceId() == null || client.getProvinceId() == 0;
}
protected void checkAreaByIp(HttpServletRequest request, ClientEntity client) {
if (client == null) {
errorLogger.error("Worker.checkAreaByIp:client is null");
return;
}
if (noPhoneArea(client) && "Y".equals(settingService.get().getEnableNoPhonePay())) {
String ip = WebUtil.getRequestIp(request);
IpInfoEntity info = this.ipRangeService.getAreaCode(ip);
if (info != null) {
client.setIpProvinceId(info.getProvinceId());
client.setIpAreaId(info.getCityId());
client.setIp(ip);
} else {
errorLogger.warn("no-ip-range-set: " + ip);
}
}
}
public abstract String execute(HttpServletRequest request, JSONObject input) throws Exception;
}
| 3,068 | 0.721969 | 0.720665 | 73 | 41.027397 | 28.610743 | 167 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.726027 | false | false |
14
|
47c1fd0e3ab848b83cbe93f7beb36b8a080b82a2
| 38,663,295,614,727 |
2e5918aaaf429f17c851cf211a4b473c2997af35
|
/generator/src/main/java/com/etsoft/comm/generate/Render3_Controller.java
|
c0471bf870bb83cabf5586df3bb74ad91372aa0e
|
[] |
no_license
|
ahchchxx/demo
|
https://github.com/ahchchxx/demo
|
7880b3ca8c434d995c609d8dbd0971a46512f52c
|
0f9448107eb1dbaf1a0f6100e0a5bcec497b1019
|
refs/heads/main
| 2023-03-29T03:41:52.289000 | 2021-03-26T01:06:26 | 2021-03-26T01:06:26 | 316,188,022 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.etsoft.comm.generate;
import com.etsoft.comm.tool.*;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
public class Render3_Controller {
public static List<String> ignoreFieldList = new ArrayList<>();
static {
ignoreFieldList.add("id");
ignoreFieldList.add("del_flag");
}
public static void create(GContext gCtx) throws Exception {
String fileStr = gCtx.getControllerSampleFileStr();
// 开始替换
fileStr = fileStr.replaceFirst("##className#", gCtx.getClassName(false));
fileStr = fileStr.replaceFirst("##ClassNameSuffix#", gCtx.getControllerClassNameSuffix());
fileStr = fileStr.replace("##ClassEntityName#", gCtx.getEntityClassNameSuffix());
fileStr = fileStr.replace("##ClassServiceName#", gCtx.getServiceClassNameSuffix());
// fileStr = fileStr.replace("##pkFieldCamel#", StringUnit.getCamelName(pkField, false));
// Pagination Query List
ResultSet l_rset = gCtx.getL_rset();
MyStringBuilder sb = new MyStringBuilder();
for (int i = 1; i <= l_rset.getMetaData().getColumnCount(); i++) {
String col_name = l_rset.getMetaData().getColumnName(i).toLowerCase();
if (ignoreFieldList.indexOf(col_name) > -1) { // exsit in the ignore fields
continue;
}
String colName = StringUnit.getCamelName(col_name, false);
String ColName = StringUnit.getCamelName(col_name, true);
String javaType = TypeHelper.getTypeFromDb2Java(l_rset.getMetaData(), i);
if ("Date".equals(javaType)) {
// sb.appendLine("\t\tif (bean.get" + ColName + "() != null) {");
// sb.appendLine("\t\t\tqw.eq(\"" + col_name + "\", bean.get" + ColName + "());");
// sb.appendLine("\t\t}");
sb.appendLine("\t\tif (!StringUtils.isEmpty(request.getParameter(\"" + colName + "_01\"))) {");
sb.appendLine("\t\t\tString[] dateRange = request.getParameter(\"" + colName + "_01\").split(\",\");");
sb.appendLine("\t\t\tif (dateRange.length > 1) {// date range");
sb.appendLine("\t\t\t\tDate end = DateUtil.parse(dateRange[1]);");
sb.appendLine("\t\t\t\tqw.between(\"" + col_name + "\", dateRange[0], DateUtil.endOfDay(end));");
sb.appendLine("\t\t\t} else if (dateRange.length == 1) {// date");
sb.appendLine("\t\t\t\tDate end = DateUtil.parse(dateRange[0]);");
sb.appendLine("\t\t\t\tqw.between(\"" + col_name + "\", dateRange[0], DateUtil.endOfDay(end));");
sb.appendLine("\t\t\t}");
sb.appendLine("\t\t}");
} else if ("String".equals(javaType)) {
sb.appendLine("\t\tif (!StringUtils.isEmpty(bean.get" + ColName + "())) {");
sb.appendLine("\t\t\tqw.like(\"`" + col_name + "`\", bean.get" + ColName + "());");
sb.appendLine("\t\t}");
} else {
sb.appendLine("\t\tif (bean.get" + ColName + "() != null) {");
sb.appendLine("\t\t\tqw.eq(\"`" + col_name + "`\", bean.get" + ColName + "());");
sb.appendLine("\t\t}");
}
}
fileStr = fileStr.replaceFirst("\t\t##PaginationQueryList#", sb.toString());
// 输出内容
FileHelper.writeFile(gCtx.getControllerFileFullPath(), gCtx.getTable_name(), fileStr);
}
}
|
UTF-8
|
Java
| 3,500 |
java
|
Render3_Controller.java
|
Java
|
[] | null |
[] |
package com.etsoft.comm.generate;
import com.etsoft.comm.tool.*;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
public class Render3_Controller {
public static List<String> ignoreFieldList = new ArrayList<>();
static {
ignoreFieldList.add("id");
ignoreFieldList.add("del_flag");
}
public static void create(GContext gCtx) throws Exception {
String fileStr = gCtx.getControllerSampleFileStr();
// 开始替换
fileStr = fileStr.replaceFirst("##className#", gCtx.getClassName(false));
fileStr = fileStr.replaceFirst("##ClassNameSuffix#", gCtx.getControllerClassNameSuffix());
fileStr = fileStr.replace("##ClassEntityName#", gCtx.getEntityClassNameSuffix());
fileStr = fileStr.replace("##ClassServiceName#", gCtx.getServiceClassNameSuffix());
// fileStr = fileStr.replace("##pkFieldCamel#", StringUnit.getCamelName(pkField, false));
// Pagination Query List
ResultSet l_rset = gCtx.getL_rset();
MyStringBuilder sb = new MyStringBuilder();
for (int i = 1; i <= l_rset.getMetaData().getColumnCount(); i++) {
String col_name = l_rset.getMetaData().getColumnName(i).toLowerCase();
if (ignoreFieldList.indexOf(col_name) > -1) { // exsit in the ignore fields
continue;
}
String colName = StringUnit.getCamelName(col_name, false);
String ColName = StringUnit.getCamelName(col_name, true);
String javaType = TypeHelper.getTypeFromDb2Java(l_rset.getMetaData(), i);
if ("Date".equals(javaType)) {
// sb.appendLine("\t\tif (bean.get" + ColName + "() != null) {");
// sb.appendLine("\t\t\tqw.eq(\"" + col_name + "\", bean.get" + ColName + "());");
// sb.appendLine("\t\t}");
sb.appendLine("\t\tif (!StringUtils.isEmpty(request.getParameter(\"" + colName + "_01\"))) {");
sb.appendLine("\t\t\tString[] dateRange = request.getParameter(\"" + colName + "_01\").split(\",\");");
sb.appendLine("\t\t\tif (dateRange.length > 1) {// date range");
sb.appendLine("\t\t\t\tDate end = DateUtil.parse(dateRange[1]);");
sb.appendLine("\t\t\t\tqw.between(\"" + col_name + "\", dateRange[0], DateUtil.endOfDay(end));");
sb.appendLine("\t\t\t} else if (dateRange.length == 1) {// date");
sb.appendLine("\t\t\t\tDate end = DateUtil.parse(dateRange[0]);");
sb.appendLine("\t\t\t\tqw.between(\"" + col_name + "\", dateRange[0], DateUtil.endOfDay(end));");
sb.appendLine("\t\t\t}");
sb.appendLine("\t\t}");
} else if ("String".equals(javaType)) {
sb.appendLine("\t\tif (!StringUtils.isEmpty(bean.get" + ColName + "())) {");
sb.appendLine("\t\t\tqw.like(\"`" + col_name + "`\", bean.get" + ColName + "());");
sb.appendLine("\t\t}");
} else {
sb.appendLine("\t\tif (bean.get" + ColName + "() != null) {");
sb.appendLine("\t\t\tqw.eq(\"`" + col_name + "`\", bean.get" + ColName + "());");
sb.appendLine("\t\t}");
}
}
fileStr = fileStr.replaceFirst("\t\t##PaginationQueryList#", sb.toString());
// 输出内容
FileHelper.writeFile(gCtx.getControllerFileFullPath(), gCtx.getTable_name(), fileStr);
}
}
| 3,500 | 0.564007 | 0.559988 | 69 | 49.492752 | 36.81234 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.043478 | false | false |
14
|
b2292f1c279239ff1383da39cb226ac43598bfa1
| 37,323,265,830,449 |
26b7f30c6640b8017a06786e4a2414ad8a4d71dd
|
/src/number_of_direct_superinterfaces/i64948.java
|
55de7281493a661479e6a6c62f26fb8f1f2bfdcc
|
[] |
no_license
|
vincentclee/jvm-limits
|
https://github.com/vincentclee/jvm-limits
|
b72a2f2dcc18caa458f1e77924221d585f23316b
|
2fd1c26d1f7984ea8163bc103ad14b6d72282281
|
refs/heads/master
| 2020-05-18T11:18:41.711000 | 2014-09-14T04:25:18 | 2014-09-14T04:25:18 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package number_of_direct_superinterfaces;
public interface i64948 {}
|
UTF-8
|
Java
| 69 |
java
|
i64948.java
|
Java
|
[] | null |
[] |
package number_of_direct_superinterfaces;
public interface i64948 {}
| 69 | 0.826087 | 0.753623 | 3 | 22.333334 | 16.937796 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false |
14
|
1560ddc3fc2a9082a38311d1747cc31f09eceb0a
| 34,823,594,881,696 |
c0baba045aaf7654167c7402d68e706923a8fbab
|
/Selection Sort/src/com/company/Main.java
|
562398a0914a8fadc5b1d407b5c881227895476c
|
[
"MIT"
] |
permissive
|
maulanarasoky/Java-Programming
|
https://github.com/maulanarasoky/Java-Programming
|
21806d76538e00d3b03fc1bae947de55439b0eb5
|
a7d556134ac44336bc844c7b8e81d1c102bd4ce0
|
refs/heads/master
| 2020-05-30T08:57:18.325000 | 2019-05-31T16:43:58 | 2019-05-31T16:44:35 | 170,107,007 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
Author : Maulana Rasoky Nasution
Website : https://mul-code.blogspot.com
*/
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int size, swap;
System.out.println("=============================");
System.out.println("\t\tSELECTION SORT");
System.out.println("=============================");
System.out.print("Enter amount of data : ");
size = input.nextInt();
System.out.println();
int [] array = new int [size];
for (int i = 0; i < size; i++){
System.out.print((i+1) + " - data : ");
array[i] = input.nextInt();
}
System.out.println("\nData before sorting");
for (int i = 0; i < size; i++) {
System.out.print(array[i] + " ");
}
for (int i = 0; i < size; i++) {
for (int j = i+1; j < size; j++) {
if (array[i] > array[j]) {
swap = array[i];
array[i] = array[j];
array[j] = swap;
}
}
}
System.out.println("\nData after sorting Ascending");
for (int i = 0; i < size; i++) {
System.out.print(array[i] + " ");
}
for (int i = 0; i < size; i++) {
for (int j = i+1; j < size; j++) {
if (array[i] < array[j]) {
swap = array[i];
array[i] = array[j];
array[j] = swap;
}
}
}
System.out.println("\nData after sorting Descending");
for (int i = 0; i < size; i++) {
System.out.print(array[i] + " ");
}
}
}
|
UTF-8
|
Java
| 1,791 |
java
|
Main.java
|
Java
|
[
{
"context": "/*\nAuthor : Maulana Rasoky Nasution\nWebsite : https://mul-code.blogspot.com\n*/\npackag",
"end": 36,
"score": 0.9998828768730164,
"start": 13,
"tag": "NAME",
"value": "Maulana Rasoky Nasution"
}
] | null |
[] |
/*
Author : <NAME>
Website : https://mul-code.blogspot.com
*/
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int size, swap;
System.out.println("=============================");
System.out.println("\t\tSELECTION SORT");
System.out.println("=============================");
System.out.print("Enter amount of data : ");
size = input.nextInt();
System.out.println();
int [] array = new int [size];
for (int i = 0; i < size; i++){
System.out.print((i+1) + " - data : ");
array[i] = input.nextInt();
}
System.out.println("\nData before sorting");
for (int i = 0; i < size; i++) {
System.out.print(array[i] + " ");
}
for (int i = 0; i < size; i++) {
for (int j = i+1; j < size; j++) {
if (array[i] > array[j]) {
swap = array[i];
array[i] = array[j];
array[j] = swap;
}
}
}
System.out.println("\nData after sorting Ascending");
for (int i = 0; i < size; i++) {
System.out.print(array[i] + " ");
}
for (int i = 0; i < size; i++) {
for (int j = i+1; j < size; j++) {
if (array[i] < array[j]) {
swap = array[i];
array[i] = array[j];
array[j] = swap;
}
}
}
System.out.println("\nData after sorting Descending");
for (int i = 0; i < size; i++) {
System.out.print(array[i] + " ");
}
}
}
| 1,774 | 0.417644 | 0.412619 | 59 | 29.355932 | 18.84078 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.711864 | false | false |
14
|
127bcafb9dcae5b9b36f9dda103fad8c80ac6460
| 37,048,387,926,408 |
80b766f8fa26c4a2964e929cd60d2dc5e4ae916b
|
/src/MaxPointsonaLine.java
|
6452113279b0c3202c4462f7da80c458ba4bc329
|
[] |
no_license
|
yao23/Leetcode
|
https://github.com/yao23/Leetcode
|
f0210891bd6e19deeb1e78f358424d3e6c94aab2
|
61d4bbc3ad7e5e18caa8f1cbc112993a3183fff7
|
refs/heads/master
| 2021-01-20T20:57:26.620000 | 2017-05-06T17:07:08 | 2017-05-06T17:07:08 | 14,696,083 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.util.Map;
import java.util.HashMap;
public class MaxPointsonaLine {
public int maxPoints(Point[] points) {
Map<Double, Integer> map = new HashMap<Double, Integer>();
int res = 0;
int len = points.length;
for( int i = 0; i < len; i++ ) {
int InvalidK = 0;
int add = 1;
for( int j = i + 1; j < len; j++ ) {
if( points[j].x == points[i].x ) {
if( points[j].y == points[i].y )
add++;
else
InvalidK++;
continue;
}
double k = points[j].y == points[i].y ? 0.0 :
(1.0 * (points[j].y - points[i].y)) /
(points[j].x - points[i].x);
if( map.containsKey(k) ) {
int count = map.get(k);
map.put(k, count + 1);
}
else
map.put(k, 1);
}
for( Integer it : map.values() ) {
if( it + add > res )
res = it.intValue() + add;
}
res = Math.max(InvalidK + add, res);
map.clear();
}
return res;
}
}
class Point{
int x;
int y;
Point() { x = 0; y = 0; }
Point(int a, int b) { x = a; y = b; }
}
|
UTF-8
|
Java
| 1,037 |
java
|
MaxPointsonaLine.java
|
Java
|
[] | null |
[] |
import java.util.Map;
import java.util.HashMap;
public class MaxPointsonaLine {
public int maxPoints(Point[] points) {
Map<Double, Integer> map = new HashMap<Double, Integer>();
int res = 0;
int len = points.length;
for( int i = 0; i < len; i++ ) {
int InvalidK = 0;
int add = 1;
for( int j = i + 1; j < len; j++ ) {
if( points[j].x == points[i].x ) {
if( points[j].y == points[i].y )
add++;
else
InvalidK++;
continue;
}
double k = points[j].y == points[i].y ? 0.0 :
(1.0 * (points[j].y - points[i].y)) /
(points[j].x - points[i].x);
if( map.containsKey(k) ) {
int count = map.get(k);
map.put(k, count + 1);
}
else
map.put(k, 1);
}
for( Integer it : map.values() ) {
if( it + add > res )
res = it.intValue() + add;
}
res = Math.max(InvalidK + add, res);
map.clear();
}
return res;
}
}
class Point{
int x;
int y;
Point() { x = 0; y = 0; }
Point(int a, int b) { x = a; y = b; }
}
| 1,037 | 0.495661 | 0.483124 | 46 | 21.543478 | 15.155293 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.76087 | false | false |
14
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.