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
2c6c5f65459a90f36b5ce0739cb62ee3dc17ea7c
18,468,359,396,588
29a0fa49b422185d69233cf2ca73f87279477e82
/src/main/java/Test_Fibonacci_print.java
79b3c500648a3acc396d656f0664092378171ceb
[]
no_license
vinnie5/gitDemo
https://github.com/vinnie5/gitDemo
0902345268ad9781cd889809c0ebe5dc21a87c0c
541b76bd9255c3660142f8e48267c9647e0e0cc6
refs/heads/master
2021-12-11T02:39:31.998000
2019-11-16T05:00:09
2019-11-16T05:00:09
221,854,792
0
0
null
false
2021-12-14T21:36:01
2019-11-15T06:00:32
2019-11-16T05:00:12
2021-12-14T21:35:59
93
0
0
3
HTML
false
false
import org.testng.annotations.Test; import junit.framework.TestCase; public class Test_Fibonacci_print extends TestCase { @Test public void test(){ fibo f = new fibo() ; int number = f.Fibonacci_print(2) ; assertEquals(1,number) ; } }
UTF-8
Java
266
java
Test_Fibonacci_print.java
Java
[]
null
[]
import org.testng.annotations.Test; import junit.framework.TestCase; public class Test_Fibonacci_print extends TestCase { @Test public void test(){ fibo f = new fibo() ; int number = f.Fibonacci_print(2) ; assertEquals(1,number) ; } }
266
0.661654
0.654135
19
13
16.261028
52
false
false
0
0
0
0
0
0
1.263158
false
false
10
be18a6c7700a9d5400aa883573639e51e12f2de9
33,294,586,492,884
957e88c3486be4e494caeb872fef742624a419c6
/src/main/java/swb/bookstore/app/BookStoreController.java
f319dea7060d7ccc021620f63f2f14ac2c642834
[]
no_license
sanmaru/Se-Book
https://github.com/sanmaru/Se-Book
50c31040ba3223c1b6c2a2930fab3cc914db4212
3cb21d6eb4f76374e7b3a1dcff4a10baf2e3aca6
refs/heads/master
2020-04-03T02:04:29.722000
2018-10-27T09:18:41
2018-10-27T09:18:41
154,946,221
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package swb.bookstore.app; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import swb.bookstore.domain.Book; import swb.bookstore.domain.BookDao; import java.util.List; @Controller public class BookStoreController { @Autowired private BookDao bookDao; @RequestMapping("/") public String homePage() { return "index"; } @RequestMapping("/search") public String search(@RequestParam("query") String query, Model model) { model.addAttribute("query", query); List<Book> results = bookDao.findBooks(query); model.addAttribute("results", results); model.addAttribute("numResults", results.size()); return "search"; } @RequestMapping("/books/{book}") public String books(@PathVariable("book") String book, Model model) { model.addAttribute("book", bookDao.findBook(book)); return "book"; } }
UTF-8
Java
1,182
java
BookStoreController.java
Java
[]
null
[]
package swb.bookstore.app; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import swb.bookstore.domain.Book; import swb.bookstore.domain.BookDao; import java.util.List; @Controller public class BookStoreController { @Autowired private BookDao bookDao; @RequestMapping("/") public String homePage() { return "index"; } @RequestMapping("/search") public String search(@RequestParam("query") String query, Model model) { model.addAttribute("query", query); List<Book> results = bookDao.findBooks(query); model.addAttribute("results", results); model.addAttribute("numResults", results.size()); return "search"; } @RequestMapping("/books/{book}") public String books(@PathVariable("book") String book, Model model) { model.addAttribute("book", bookDao.findBook(book)); return "book"; } }
1,182
0.719966
0.719966
38
30.105263
23.302122
76
false
false
0
0
0
0
0
0
0.657895
false
false
10
93639599b5afdf3911b2e7a776148498aecfe73d
18,614,388,277,687
8bb4ca7c8457932257d13df08bb0b51774b357d0
/wms-entity/src/main/java/com/wms/entity/GspProductRegisterSpecs.java
59d0fceb7f541121ce3b9d80af5ad559e1738397
[]
no_license
suanyuan/WAREWMS_JAVA
https://github.com/suanyuan/WAREWMS_JAVA
96633be23f6512df72317ee65ded0c4e986d928e
772cd0ab12e0334d423574b32d3c0c7b3f3213b4
refs/heads/dev
2023-01-25T00:02:03.946000
2020-03-10T07:34:05
2020-03-10T07:34:05
246,244,026
0
1
null
false
2023-01-02T21:58:56
2020-03-10T08:16:48
2020-03-10T08:21:01
2023-01-02T21:58:53
17,322
0
1
27
Java
false
false
package com.wms.entity; import javax.persistence.Entity; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; import java.io.Serializable; import java.util.Date; @Entity public class GspProductRegisterSpecs implements Serializable { private static final long serialVersionUID = 1L; @Transient private int hashCode = Integer.MIN_VALUE; public static long getSerialVersionUID() { return serialVersionUID; } public int getHashCode() { return hashCode; } public void setHashCode(int hashCode) { this.hashCode = hashCode; } public String getLlong() { return llong; } public void setLlong(String llong) { this.llong = llong; } private String specsId; private String productRegisterId; private String productRegisterNo; private String productNameMain; private String enterpriseId;//附加 private String enterpriseName;//附加 private String specsName; private String productCode; private String productName; private String productRemark; private String productModel; private String productionAddress; private String barCode; private String unit; private String packingUnit; private String categories; private String conversionRate; private String llong; private String wide; private String hight; private String productLine; private String manageCategories; private String packingRequire; private String storageCondition; private String transportCondition; private String createId; @Temporal(TemporalType.TIMESTAMP) private Date createDate; private String createDateDC; private String editId; @Temporal(TemporalType.TIMESTAMP) private Date editDate; private String editDateDC; private String isUse; private String isCertificate; private String isDoublec; private String attacheCardCategory;//附卡类别 private String coldHainMark; //冷链标志 private String sterilizationMarkers;//灭菌标志 private String medicalDeviceMark;//医疗器械标志 private String maintenanceCycle;//养护周期 private String wight;//重量 private String packagingUnit;//包装单位 private String licenseOrRecordNo;//产品许可证 备案号 private String productEnterpriseName; //产品许可证 备案号 private String licenseNo; private String recordNo; private String alternatName1; private String alternatName2; private String alternatName3; private String alternatName4; private String alternatName5; private String type; public String getCreateDateDC() { return createDateDC; } public void setCreateDateDC(String createDateDC) { this.createDateDC = createDateDC; } public String getEditDateDC() { return editDateDC; } public void setEditDateDC(String editDateDC) { this.editDateDC = editDateDC; } public String getLicenseOrRecordNo() { return licenseOrRecordNo; } public void setLicenseOrRecordNo(String licenseOrRecordNo) { this.licenseOrRecordNo = licenseOrRecordNo; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getLicenseNo() { return licenseNo; } public void setLicenseNo(String licenseNo) { this.licenseNo = licenseNo; } public String getRecordNo() { return recordNo; } public void setRecordNo(String recordNo) { this.recordNo = recordNo; } public GspProductRegisterSpecs() { } public String getPackagingUnit() { return packagingUnit; } public void setPackagingUnit(String packagingUnit) { this.packagingUnit = packagingUnit; } public String getColdHainMark() { return coldHainMark; } public void setColdHainMark(String coldHainMark) { this.coldHainMark = coldHainMark; } public String getSterilizationMarkers() { return sterilizationMarkers; } public void setSterilizationMarkers(String sterilizationMarkers) { this.sterilizationMarkers = sterilizationMarkers; } public String getMedicalDeviceMark() { return medicalDeviceMark; } public void setMedicalDeviceMark(String medicalDeviceMark) { this.medicalDeviceMark = medicalDeviceMark; } public String getMaintenanceCycle() { return maintenanceCycle; } public void setMaintenanceCycle(String maintenanceCycle) { this.maintenanceCycle = maintenanceCycle; } public String getWight() { return wight; } public void setWight(String wight) { this.wight = wight; } public String getSpecsId() { return specsId; } public void setSpecsId(String specsId) { this.specsId = specsId; } public String getProductRegisterId() { return productRegisterId; } public void setProductRegisterId(String productRegisterId) { this.productRegisterId = productRegisterId; } public String getSpecsName() { return specsName; } public void setSpecsName(String specsName) { this.specsName = specsName; } public String getProductCode() { return productCode; } public void setProductCode(String productCode) { this.productCode = productCode; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public String getProductRemark() { return productRemark; } public void setProductRemark(String productRemark) { this.productRemark = productRemark; } public String getProductModel() { return productModel; } public void setProductModel(String productModel) { this.productModel = productModel; } public String getProductionAddress() { return productionAddress; } public void setProductionAddress(String productionAddress) { this.productionAddress = productionAddress; } public String getBarCode() { return barCode; } public void setBarCode(String barCode) { this.barCode = barCode; } public String getUnit() { return unit; } public void setUnit(String unit) { this.unit = unit; } public String getPackingUnit() { return packingUnit; } public void setPackingUnit(String packingUnit) { this.packingUnit = packingUnit; } public String getCategories() { return categories; } public void setCategories(String categories) { this.categories = categories; } public String getConversionRate() { return conversionRate; } public void setConversionRate(String conversionRate) { this.conversionRate = conversionRate; } public String getLong() { return llong; } public void setLong(String llong) { this.llong = llong; } public String getWide() { return wide; } public void setWide(String wide) { this.wide = wide; } public String getHight() { return hight; } public void setHight(String hight) { this.hight = hight; } public String getProductLine() { return productLine; } public void setProductLine(String productLine) { this.productLine = productLine; } public String getManageCategories() { return manageCategories; } public void setManageCategories(String manageCategories) { this.manageCategories = manageCategories; } public String getStorageCondition() { return storageCondition; } public void setStorageCondition(String storageCondition) { this.storageCondition = storageCondition; } public String getTransportCondition() { return transportCondition; } public void setTransportCondition(String transportCondition) { this.transportCondition = transportCondition; } public String getCreateId() { return createId; } public void setCreateId(String createId) { this.createId = createId; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public String getEditId() { return editId; } public void setEditId(String editId) { this.editId = editId; } public Date getEditDate() { return editDate; } public void setEditDate(Date editDate) { this.editDate = editDate; } public String getIsUse() { return isUse; } public void setIsUse(String isUse) { this.isUse = isUse; } public String getAlternatName1() { return alternatName1; } public void setAlternatName1(String alternatName1) { this.alternatName1 = alternatName1; } public String getAlternatName2() { return alternatName2; } public void setAlternatName2(String alternatName2) { this.alternatName2 = alternatName2; } public String getAlternatName3() { return alternatName3; } public void setAlternatName3(String alternatName3) { this.alternatName3 = alternatName3; } public String getAlternatName4() { return alternatName4; } public void setAlternatName4(String alternatName4) { this.alternatName4 = alternatName4; } public String getAlternatName5() { return alternatName5; } public void setAlternatName5(String alternatName5) { this.alternatName5 = alternatName5; } public String getProductNameMain() { return productNameMain; } public void setProductNameMain(String productNameMain) { this.productNameMain = productNameMain; } public String getProductRegisterNo() { return productRegisterNo; } public void setProductRegisterNo(String productRegisterNo) { this.productRegisterNo = productRegisterNo; } public String getPackingRequire() { return packingRequire; } public void setPackingRequire(String packingRequire) { this.packingRequire = packingRequire; } public String getIsCertificate() { return isCertificate; } public void setIsCertificate(String isCertificate) { this.isCertificate = isCertificate; } public String getIsDoublec() { return isDoublec; } public void setIsDoublec(String isDoublec) { this.isDoublec = isDoublec; } public String getAttacheCardCategory() { return attacheCardCategory; } public void setAttacheCardCategory(String attacheCardCategory) { this.attacheCardCategory = attacheCardCategory; } public String getEnterpriseId() { return enterpriseId; } public void setEnterpriseId(String enterpriseId) { this.enterpriseId = enterpriseId; } public String getEnterpriseName() { return enterpriseName; } public void setEnterpriseName(String enterpriseName) { this.enterpriseName = enterpriseName; } public String getProductEnterpriseName() { return productEnterpriseName; } public void setProductEnterpriseName(String productEnterpriseName) { this.productEnterpriseName = productEnterpriseName; } }
UTF-8
Java
10,839
java
GspProductRegisterSpecs.java
Java
[]
null
[]
package com.wms.entity; import javax.persistence.Entity; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; import java.io.Serializable; import java.util.Date; @Entity public class GspProductRegisterSpecs implements Serializable { private static final long serialVersionUID = 1L; @Transient private int hashCode = Integer.MIN_VALUE; public static long getSerialVersionUID() { return serialVersionUID; } public int getHashCode() { return hashCode; } public void setHashCode(int hashCode) { this.hashCode = hashCode; } public String getLlong() { return llong; } public void setLlong(String llong) { this.llong = llong; } private String specsId; private String productRegisterId; private String productRegisterNo; private String productNameMain; private String enterpriseId;//附加 private String enterpriseName;//附加 private String specsName; private String productCode; private String productName; private String productRemark; private String productModel; private String productionAddress; private String barCode; private String unit; private String packingUnit; private String categories; private String conversionRate; private String llong; private String wide; private String hight; private String productLine; private String manageCategories; private String packingRequire; private String storageCondition; private String transportCondition; private String createId; @Temporal(TemporalType.TIMESTAMP) private Date createDate; private String createDateDC; private String editId; @Temporal(TemporalType.TIMESTAMP) private Date editDate; private String editDateDC; private String isUse; private String isCertificate; private String isDoublec; private String attacheCardCategory;//附卡类别 private String coldHainMark; //冷链标志 private String sterilizationMarkers;//灭菌标志 private String medicalDeviceMark;//医疗器械标志 private String maintenanceCycle;//养护周期 private String wight;//重量 private String packagingUnit;//包装单位 private String licenseOrRecordNo;//产品许可证 备案号 private String productEnterpriseName; //产品许可证 备案号 private String licenseNo; private String recordNo; private String alternatName1; private String alternatName2; private String alternatName3; private String alternatName4; private String alternatName5; private String type; public String getCreateDateDC() { return createDateDC; } public void setCreateDateDC(String createDateDC) { this.createDateDC = createDateDC; } public String getEditDateDC() { return editDateDC; } public void setEditDateDC(String editDateDC) { this.editDateDC = editDateDC; } public String getLicenseOrRecordNo() { return licenseOrRecordNo; } public void setLicenseOrRecordNo(String licenseOrRecordNo) { this.licenseOrRecordNo = licenseOrRecordNo; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getLicenseNo() { return licenseNo; } public void setLicenseNo(String licenseNo) { this.licenseNo = licenseNo; } public String getRecordNo() { return recordNo; } public void setRecordNo(String recordNo) { this.recordNo = recordNo; } public GspProductRegisterSpecs() { } public String getPackagingUnit() { return packagingUnit; } public void setPackagingUnit(String packagingUnit) { this.packagingUnit = packagingUnit; } public String getColdHainMark() { return coldHainMark; } public void setColdHainMark(String coldHainMark) { this.coldHainMark = coldHainMark; } public String getSterilizationMarkers() { return sterilizationMarkers; } public void setSterilizationMarkers(String sterilizationMarkers) { this.sterilizationMarkers = sterilizationMarkers; } public String getMedicalDeviceMark() { return medicalDeviceMark; } public void setMedicalDeviceMark(String medicalDeviceMark) { this.medicalDeviceMark = medicalDeviceMark; } public String getMaintenanceCycle() { return maintenanceCycle; } public void setMaintenanceCycle(String maintenanceCycle) { this.maintenanceCycle = maintenanceCycle; } public String getWight() { return wight; } public void setWight(String wight) { this.wight = wight; } public String getSpecsId() { return specsId; } public void setSpecsId(String specsId) { this.specsId = specsId; } public String getProductRegisterId() { return productRegisterId; } public void setProductRegisterId(String productRegisterId) { this.productRegisterId = productRegisterId; } public String getSpecsName() { return specsName; } public void setSpecsName(String specsName) { this.specsName = specsName; } public String getProductCode() { return productCode; } public void setProductCode(String productCode) { this.productCode = productCode; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public String getProductRemark() { return productRemark; } public void setProductRemark(String productRemark) { this.productRemark = productRemark; } public String getProductModel() { return productModel; } public void setProductModel(String productModel) { this.productModel = productModel; } public String getProductionAddress() { return productionAddress; } public void setProductionAddress(String productionAddress) { this.productionAddress = productionAddress; } public String getBarCode() { return barCode; } public void setBarCode(String barCode) { this.barCode = barCode; } public String getUnit() { return unit; } public void setUnit(String unit) { this.unit = unit; } public String getPackingUnit() { return packingUnit; } public void setPackingUnit(String packingUnit) { this.packingUnit = packingUnit; } public String getCategories() { return categories; } public void setCategories(String categories) { this.categories = categories; } public String getConversionRate() { return conversionRate; } public void setConversionRate(String conversionRate) { this.conversionRate = conversionRate; } public String getLong() { return llong; } public void setLong(String llong) { this.llong = llong; } public String getWide() { return wide; } public void setWide(String wide) { this.wide = wide; } public String getHight() { return hight; } public void setHight(String hight) { this.hight = hight; } public String getProductLine() { return productLine; } public void setProductLine(String productLine) { this.productLine = productLine; } public String getManageCategories() { return manageCategories; } public void setManageCategories(String manageCategories) { this.manageCategories = manageCategories; } public String getStorageCondition() { return storageCondition; } public void setStorageCondition(String storageCondition) { this.storageCondition = storageCondition; } public String getTransportCondition() { return transportCondition; } public void setTransportCondition(String transportCondition) { this.transportCondition = transportCondition; } public String getCreateId() { return createId; } public void setCreateId(String createId) { this.createId = createId; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public String getEditId() { return editId; } public void setEditId(String editId) { this.editId = editId; } public Date getEditDate() { return editDate; } public void setEditDate(Date editDate) { this.editDate = editDate; } public String getIsUse() { return isUse; } public void setIsUse(String isUse) { this.isUse = isUse; } public String getAlternatName1() { return alternatName1; } public void setAlternatName1(String alternatName1) { this.alternatName1 = alternatName1; } public String getAlternatName2() { return alternatName2; } public void setAlternatName2(String alternatName2) { this.alternatName2 = alternatName2; } public String getAlternatName3() { return alternatName3; } public void setAlternatName3(String alternatName3) { this.alternatName3 = alternatName3; } public String getAlternatName4() { return alternatName4; } public void setAlternatName4(String alternatName4) { this.alternatName4 = alternatName4; } public String getAlternatName5() { return alternatName5; } public void setAlternatName5(String alternatName5) { this.alternatName5 = alternatName5; } public String getProductNameMain() { return productNameMain; } public void setProductNameMain(String productNameMain) { this.productNameMain = productNameMain; } public String getProductRegisterNo() { return productRegisterNo; } public void setProductRegisterNo(String productRegisterNo) { this.productRegisterNo = productRegisterNo; } public String getPackingRequire() { return packingRequire; } public void setPackingRequire(String packingRequire) { this.packingRequire = packingRequire; } public String getIsCertificate() { return isCertificate; } public void setIsCertificate(String isCertificate) { this.isCertificate = isCertificate; } public String getIsDoublec() { return isDoublec; } public void setIsDoublec(String isDoublec) { this.isDoublec = isDoublec; } public String getAttacheCardCategory() { return attacheCardCategory; } public void setAttacheCardCategory(String attacheCardCategory) { this.attacheCardCategory = attacheCardCategory; } public String getEnterpriseId() { return enterpriseId; } public void setEnterpriseId(String enterpriseId) { this.enterpriseId = enterpriseId; } public String getEnterpriseName() { return enterpriseName; } public void setEnterpriseName(String enterpriseName) { this.enterpriseName = enterpriseName; } public String getProductEnterpriseName() { return productEnterpriseName; } public void setProductEnterpriseName(String productEnterpriseName) { this.productEnterpriseName = productEnterpriseName; } }
10,839
0.721586
0.718235
559
18.218246
18.821133
70
false
false
0
0
0
0
0
0
0.298748
false
false
10
5732d7fed1a17487bccf63447b00ad0d1d020408
6,880,537,661,898
d709ceb8eb3f8b1019e9799be853e132ccf22abc
/2.JavaCore/src/com/javarush/task/task19/task1916/Solution.java
553d5e90bde852a153776e263452316127c3d836
[]
no_license
ohoinets1994/JavaRushTasks
https://github.com/ohoinets1994/JavaRushTasks
b0660e19da9de23981070b23d5f8efa0949ba7e0
889514174f82f7bae372e083fc07155388e37ee3
refs/heads/master
2021-01-23T05:45:05.503000
2017-06-12T13:34:28
2017-06-12T13:34:28
91,817,078
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.javarush.task.task19.task1916; import java.io.*; import java.util.ArrayList; import java.util.List; /* Отслеживаем изменения */ public class Solution { public static List<LineItem> lines = new ArrayList<LineItem>(); public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String firstFile = reader.readLine(); String secondFile = reader.readLine(); reader.close(); BufferedReader file1 = new BufferedReader(new FileReader(firstFile)); BufferedReader file2 = new BufferedReader(new FileReader(secondFile)); ArrayList<String> list_1 = new ArrayList<>(); ArrayList<String> list_2 = new ArrayList<>(); while (file1.ready()) { list_1.add(file1.readLine()); } while (file2.ready()) { list_2.add(file2.readLine()); } file1.close(); file2.close(); for (int i = 0; i < list_1.size(); i++) { try { if (list_1.get(i).equals(list_2.get(0))) { lines.add(new LineItem(Type.SAME, list_1.get(i))); list_2.remove(0); } else if (list_1.get(i).equals(list_2.get(1))) { lines.add(new LineItem(Type.ADDED, list_2.get(0))); list_2.remove(0); i--; } else { lines.add(new LineItem(Type.REMOVED, list_1.get(i))); } } catch (Exception e) { if (list_1.size() >= list_2.size()) { lines.add(new LineItem(Type.REMOVED, list_1.get(i))); } } } if (list_2.size() < list_1.size()) { lines.add(new LineItem(Type.ADDED, list_2.get(0))); } // for (LineItem i: lines) { // System.out.println(i.type + " " + i.line); // } } public static enum Type { ADDED, //добавлена новая строка REMOVED, //удалена строка SAME //без изменений } public static class LineItem { public Type type; public String line; public LineItem(Type type, String line) { this.type = type; this.line = line; } } }
UTF-8
Java
2,424
java
Solution.java
Java
[]
null
[]
package com.javarush.task.task19.task1916; import java.io.*; import java.util.ArrayList; import java.util.List; /* Отслеживаем изменения */ public class Solution { public static List<LineItem> lines = new ArrayList<LineItem>(); public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String firstFile = reader.readLine(); String secondFile = reader.readLine(); reader.close(); BufferedReader file1 = new BufferedReader(new FileReader(firstFile)); BufferedReader file2 = new BufferedReader(new FileReader(secondFile)); ArrayList<String> list_1 = new ArrayList<>(); ArrayList<String> list_2 = new ArrayList<>(); while (file1.ready()) { list_1.add(file1.readLine()); } while (file2.ready()) { list_2.add(file2.readLine()); } file1.close(); file2.close(); for (int i = 0; i < list_1.size(); i++) { try { if (list_1.get(i).equals(list_2.get(0))) { lines.add(new LineItem(Type.SAME, list_1.get(i))); list_2.remove(0); } else if (list_1.get(i).equals(list_2.get(1))) { lines.add(new LineItem(Type.ADDED, list_2.get(0))); list_2.remove(0); i--; } else { lines.add(new LineItem(Type.REMOVED, list_1.get(i))); } } catch (Exception e) { if (list_1.size() >= list_2.size()) { lines.add(new LineItem(Type.REMOVED, list_1.get(i))); } } } if (list_2.size() < list_1.size()) { lines.add(new LineItem(Type.ADDED, list_2.get(0))); } // for (LineItem i: lines) { // System.out.println(i.type + " " + i.line); // } } public static enum Type { ADDED, //добавлена новая строка REMOVED, //удалена строка SAME //без изменений } public static class LineItem { public Type type; public String line; public LineItem(Type type, String line) { this.type = type; this.line = line; } } }
2,424
0.515897
0.498516
78
29.243589
23.901608
85
false
false
0
0
0
0
0
0
0.512821
false
false
10
6531d202484a02e9aa96bc9112ecad37ea6c14b7
18,030,272,761,929
38c3ee1c871e7726e058e4292317b54f13910909
/webapppractice/src/com/practice/core/java/oops/TestingFinal.java
d82a8d08a469975bcaca6e160e13586fb01c64bb
[]
no_license
gaurovojha/javademos
https://github.com/gaurovojha/javademos
567b3f894f282715f453a06ae0995458f960113f
e7df184e836be4685df4b907c13fc46727bddd72
refs/heads/master
2018-01-09T07:10:58.784000
2015-10-14T16:48:47
2015-10-14T16:48:47
44,000,272
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.practice.core.java.oops; /** * Created by gojha on 7/29/2015. */ public class TestingFinal { public static void main(String[] args) { Data d = new Data(); d.setInfo("This is a Data class"); d.setId(1234); FinalAllabout test = new FinalAllabout(d); Data d1 = new Data(); d.setInfo("This is another Data class"); d.setId(5678); System.out.println(test.toString()); } }
UTF-8
Java
459
java
TestingFinal.java
Java
[ { "context": "ge com.practice.core.java.oops;\n\n/**\n * Created by gojha on 7/29/2015.\n */\npublic class TestingFinal\n{\n ", "end": 61, "score": 0.99969482421875, "start": 56, "tag": "USERNAME", "value": "gojha" } ]
null
[]
package com.practice.core.java.oops; /** * Created by gojha on 7/29/2015. */ public class TestingFinal { public static void main(String[] args) { Data d = new Data(); d.setInfo("This is a Data class"); d.setId(1234); FinalAllabout test = new FinalAllabout(d); Data d1 = new Data(); d.setInfo("This is another Data class"); d.setId(5678); System.out.println(test.toString()); } }
459
0.581699
0.546841
20
21.950001
17.755211
50
false
false
0
0
0
0
0
0
0.45
false
false
10
5cba794a8e8519879bbc643251077b0a6fc3a35b
3,539,053,053,398
313a9a775c0506f4bbe86f5622b381560d935c80
/part5/Type.java
8ad706a6bd0529ab8808c432ce56475b1b5f902b
[]
no_license
codcodcod/lft
https://github.com/codcodcod/lft
74422abb1c07084481176ec480a58dcd5ba588b3
fe33f479e53520d6a62baa5bfb0f77077bbd3aa5
refs/heads/master
2021-01-10T13:05:10.794000
2015-12-12T17:14:30
2015-12-12T17:14:30
47,885,741
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package part5; public enum Type { INTEGER, BOOLEAN }
UTF-8
Java
55
java
Type.java
Java
[]
null
[]
package part5; public enum Type { INTEGER, BOOLEAN }
55
0.727273
0.709091
3
17
15.253415
37
false
false
0
0
0
0
0
0
0.666667
false
false
10
ca25e8ec50569c27eb57bab354899c9a5c9dc26a
33,578,054,329,725
1131b4ebed931c9dc123bbb183e5e5973513e11d
/app/src/main/java/com/volynski/familytrack/data/FamilyTrackRepository.java
580691927638bf1f9254a3e6853bd47f5b59b1b3
[]
no_license
DmitryVolynski/FamilyTrack
https://github.com/DmitryVolynski/FamilyTrack
62e7c93ba64141ec80656b757e90eb31392a12ee
e59bc6afb4e49d425ddd955843c46f41ae2852f9
refs/heads/master
2021-03-24T13:59:54.478000
2017-11-30T09:44:34
2017-11-30T09:44:34
100,989,159
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.volynski.familytrack.data; import android.content.Context; import android.database.Cursor; import android.provider.ContactsContract; import android.support.annotation.NonNull; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthCredential; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.GoogleAuthProvider; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.Query; import com.google.firebase.database.ValueEventListener; import com.volynski.familytrack.R; import com.volynski.familytrack.StringKeys; import com.volynski.familytrack.data.models.firebase.GeofenceEvent; import com.volynski.familytrack.data.models.firebase.Group; import com.volynski.familytrack.data.models.firebase.Location; import com.volynski.familytrack.data.models.firebase.Membership; import com.volynski.familytrack.data.models.firebase.Settings; import com.volynski.familytrack.data.models.firebase.User; import com.volynski.familytrack.data.models.firebase.Zone; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; import timber.log.Timber; /** * Created by DmitryVolynski on 17.08.2017. */ public class FamilyTrackRepository implements FamilyTrackDataSource { private static final String TAG = FamilyTrackRepository.class.getSimpleName(); private FirebaseDatabase mFirebaseDatabase; private String mGoogleAccountIdToken; private FirebaseAuth mFirebaseAuth; private Context mContext; // TODO проверить необходимость передачи GoogleSignInAccount в конструктор public FamilyTrackRepository(String googleAccountIdToken, Context context) { mGoogleAccountIdToken = googleAccountIdToken; mContext = context.getApplicationContext(); } private void firebaseAuthWithGoogle(String idToken) { AuthCredential credential = GoogleAuthProvider.getCredential(idToken, null); mFirebaseAuth = FirebaseAuth.getInstance(); if (mFirebaseAuth.getCurrentUser() == null) { mFirebaseAuth.signInWithCredential(credential) .addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { Timber.v(TAG, "signInWithCredential:onComplete:" + task.isSuccessful()); // If sign in fails, display a message to the user. If sign in succeeds // the auth state listener will be notified and logic to handle the // signed in user can be handled in the listener. if (!task.isSuccessful()) { Timber.e("signInWithCredential failed", task.getException()); } } }); } } @Override public FirebaseDatabase getFirebaseConnection() { if (mFirebaseDatabase == null) { firebaseAuthWithGoogle(mGoogleAccountIdToken); mFirebaseDatabase = FirebaseDatabase.getInstance(); } return mFirebaseDatabase; } @Override public void createUser(@NonNull User user, final CreateUserCallback callback) { DatabaseReference ref = getFirebaseConnection().getReference(Group.REGISTERED_USERS_GROUP_KEY); DatabaseReference newUserRef = ref.push(); newUserRef.setValue(user); if (callback != null) { user.setUserUuid(newUserRef.getKey()); callback.onCreateUserCompleted(new FirebaseResult<>(user)); } } @Override public void updateUser(@NonNull final User user, final UpdateUserCallback callback) { getUserGroups(user.getUserUuid(), new GetUserGroupsCallback() { @Override public void onGetUserGroupsCompleted(FirebaseResult<List<Group>> result) { Map<String, Object> childUpdates = new HashMap<>(); childUpdates.put(FamilyTrackDbRefsHelper.userRef(user.getUserUuid()), user); if (result.getData() != null) { for (Group group : result.getData()) { childUpdates.put(FamilyTrackDbRefsHelper .userOfGroupRef(group.getGroupUuid(), user.getUserUuid()), user.cloneForGroupNode(group.getGroupUuid())); } } mFirebaseDatabase.getReference() .updateChildren(childUpdates) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (callback != null) { callback.onUpdateUserCompleted(new FirebaseResult<>(FirebaseResult.RESULT_OK)); } } }); } }); } @Override public void changeUserStatus(@NonNull String userUuid, int newStatus) { } @Override public void getUserByUuid(@NonNull String userUuid, @NonNull final GetUserByUuidCallback callback) { DatabaseReference ref = getFirebaseConnection().getReference(Group.REGISTERED_USERS_GROUP_KEY); Query query = ref.orderByKey().equalTo(userUuid).limitToFirst(1); query.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { User user = null; if (dataSnapshot.getChildrenCount() > 0) { user = FirebaseUtil.getUserFromSnapshot(dataSnapshot.getChildren().iterator().next()); } callback.onGetUserByUuidCompleted(new FirebaseResult<>(user)); } @Override public void onCancelled(DatabaseError databaseError) { callback.onGetUserByUuidCompleted(new FirebaseResult<User>(databaseError)); } }); } @Override public void getUserByEmail(@NonNull String userEmail, @NonNull final GetUserByEmailCallback callback) { DatabaseReference ref = getFirebaseConnection().getReference(Group.REGISTERED_USERS_GROUP_KEY); Query query = ref.orderByChild(User.FIELD_EMAIL).equalTo(userEmail).limitToFirst(1); query.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { User user = null; if (dataSnapshot.getChildrenCount() > 0) { user = FirebaseUtil.getUserFromSnapshot(dataSnapshot.getChildren().iterator().next()); } callback.onGetUserByEmailCompleted(new FirebaseResult<>(user)); } @Override public void onCancelled(DatabaseError databaseError) { callback.onGetUserByEmailCompleted(new FirebaseResult<User>(databaseError)); } }); } @Override public void getUserByPhone(@NonNull String userPhone, @NonNull final GetUserByPhoneCallback callback) { DatabaseReference ref = getFirebaseConnection().getReference(Group.REGISTERED_USERS_GROUP_KEY); Query query = ref.orderByChild(User.FIELD_PHONE).equalTo(userPhone).limitToFirst(1); query.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { User user = null; if (dataSnapshot.getChildrenCount() > 0) { user = FirebaseUtil.getUserFromSnapshot(dataSnapshot.getChildren().iterator().next()); } callback.onGetUserByPhoneCompleted(new FirebaseResult<>(user)); } @Override public void onCancelled(DatabaseError databaseError) { callback.onGetUserByPhoneCompleted(new FirebaseResult<User>(databaseError)); } }); } @Override public void createGroup(@NonNull final Group group, String adminUuid, final CreateGroupCallback callback) { // что необходимо сделать при создании новой группы // - исключить пользователя из текущей активной группы (заменить статус на USER_DEPARTED) // - создать новую группу // - включить туда пользователя в роли ROLE_ADMIN и статусе USER_JOINED // Эти изменения делаются в двух местах - // 1. groups/<groupUuid>/members/<userUuid>/memberships/<groupUuid>/statusId <- USER_DEPARTED // 2. registered_users/<userUuid>/memberships/<groupUuid>/statusId <- USER_DEPARTED // 3. то же самое для новой группы, но со статусом USER_JOINED - в тех же двух местах getUserByUuid(adminUuid, new GetUserByUuidCallback() { @Override public void onGetUserByUuidCompleted(FirebaseResult<User> result) { String currentGroupUuid = null; if (result.getData() != null) { User currentUser = result.getData(); // если пользователь не входит в группу, то исключать его не нужно if (currentUser.getActiveMembership() != null) { currentGroupUuid = currentUser.getActiveMembership().getGroupUuid(); } DatabaseReference ref = getFirebaseConnection() .getReference(FamilyTrackDbRefsHelper.NODE_GROUPS); String newGroupKey = ref.push().getKey(); Membership newMembership = new Membership(newGroupKey, group.getName(), Membership.ROLE_ADMIN, Membership.USER_JOINED); currentUser.setMemberships(new HashMap<String, Membership>()); currentUser.addMembership(newMembership); group.setGroupUuid(newGroupKey); group.addMember(currentUser); DatabaseReference newGroupRef = mFirebaseDatabase .getReference(FamilyTrackDbRefsHelper.groupRef(newGroupKey)); newGroupRef.setValue(group); Map<String, Object> childUpdates = new HashMap<>(); if (currentGroupUuid != null) { childUpdates.put(FamilyTrackDbRefsHelper .userMembershipRef(currentUser.getUserUuid(), currentGroupUuid) + Membership.FIELD_STATUS_ID, Membership.USER_DEPARTED); childUpdates.put(FamilyTrackDbRefsHelper .groupOfUserRef(currentUser.getUserUuid(), currentGroupUuid) + Membership.FIELD_STATUS_ID, Membership.USER_DEPARTED); } childUpdates.put(FamilyTrackDbRefsHelper .groupOfUserRef(currentUser.getUserUuid(), newGroupKey), newMembership); mFirebaseDatabase.getReference() .updateChildren(childUpdates) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (callback != null) { callback.onCreateGroupCompleted(new FirebaseResult<>(group)); } } }); } else { if (callback != null) { callback.onCreateGroupCompleted( new FirebaseResult<Group>(FamilyTrackException.getInstance(mContext, FamilyTrackException.DB_USER_BY_UUID_NOT_FOUND))); } } } }); } /** * Membership records will be physically deleted from * - registered_users/<userUuid>/memberships/<groupUuid> * - groups/<groupUuid>/members/<userUuid> */ @Override public void removeUserFromGroup(@NonNull String groupUuid, @NonNull String userUuid, final RemoveUserFromGroupCallback callback) { String key1 = FamilyTrackDbRefsHelper.userOfGroupRef(groupUuid, userUuid); String key2 = FamilyTrackDbRefsHelper.groupOfUserRef(userUuid, groupUuid); Map<String, Object> childUpdates = new HashMap<>(); childUpdates.put(key1, null); childUpdates.put(key2, null); getFirebaseConnection().getReference() .updateChildren(childUpdates) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (callback != null) { callback.onRemoveUserFromGroupCompleted(new FirebaseResult<>(FirebaseResult.RESULT_OK)); } } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Timber.e(e); if (callback != null) { callback.onRemoveUserFromGroupCompleted( new FirebaseResult<String>(FamilyTrackException.getInstance(mContext, FamilyTrackException.DB_REMOVE_USER_FAILED))); } } }); } @Override public void getGroupByUuid(@NonNull String groupUuid, boolean trackGroupNode, final @NonNull GetGroupByUuidCallback callback) { DatabaseReference ref = getFirebaseConnection() .getReference(FamilyTrackDbRefsHelper.groupRef(groupUuid)); Query query = ref.orderByValue(); ValueEventListener listener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { // get Group object with all members Group group = FirebaseUtil.getGroupFromSnapshot(dataSnapshot); callback.onGetGroupByUuidCompleted(new FirebaseResult<>(group)); } @Override public void onCancelled(DatabaseError databaseError) { } }; if (trackGroupNode) { query.addValueEventListener(listener); } else { query.addListenerForSingleValueEvent(listener); } } @Override public void getContactsToInvite(@NonNull final String groupUuid, @NonNull final GetContactsToInviteCallback callback) { User user; // read contacts from ContactsContract.Data.CONTENT_URI Cursor cursor = mContext.getContentResolver().query( ContactsContract.Data.CONTENT_URI, null, ContactsContract.Data.HAS_PHONE_NUMBER + "!=0 AND (" + ContactsContract.Data.MIMETYPE + "=? OR " + ContactsContract.Data.MIMETYPE + "=?)", new String[]{ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE}, ContactsContract.Data.CONTACT_ID); // merge same contacts with emails & phone numbers final Map<String, User> contacts = new HashMap<>(); while (cursor.moveToNext()) { String key = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.CONTACT_ID)); boolean isNew = !contacts.containsKey(key); if (isNew) { String givenName = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME)); user = new User(key, "", "", cursor.getString(cursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME)), StringKeys.CREATED_FROM_CONTACTS_KEY, "", "", null, null); } else { user = contacts.get(key); } //Timber.v(user.getDisplayName() + "/" + cursor.getString(cursor.getColumnIndex(ContactsContract.Data.MIMETYPE))); String mimeType = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.MIMETYPE)); try { String data = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.DATA1)); if (mimeType.equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)) { user.setEmail(data); } else { user.setPhone(formatPhoneString(data)); } if (isNew) { contacts.put(key, user); } else { contacts.remove(key); contacts.put(key, user); } } catch (Exception e) { Timber.e(e); } } cursor.close(); getGroupByUuid(groupUuid, false, new GetGroupByUuidCallback() { @Override public void onGetGroupByUuidCompleted(FirebaseResult<Group> result) { List<User> users = new ArrayList<>(); if (result.getData() == null) { Timber.v(String.format(mContext.getString(R.string.ex_group_with_uuid_not_found), groupUuid)); callback.onGetContactsToInviteCompleted(new FirebaseResult<List<User>>(users)); } // select contacts that have phone number and email + not already invited in group for (String key : contacts.keySet()) { User u = contacts.get(key); if (!u.getPhone().equals("") && !u.getEmail().equals("") && !isUserInGroup(u, result.getData())) { users.add(u); } } callback.onGetContactsToInviteCompleted(new FirebaseResult<List<User>>(users)); } }); } private String formatPhoneString(String data) { String result = null; if (data != null) { result = data.replaceAll("[ ()-]", ""); } return result; } /** * Checks if user from phone contact list is already invited * @param user - user from phone contacts * @param group * @return true if group already contains user with email that equals user email */ private boolean isUserInGroup(User user, Group group) { boolean result = false; if (group.getMembers() != null) { for (String key : group.getMembers().keySet()) { result = user.getEmail().equals(group.getMembers().get(key).getEmail()); if (result) { break; } } } return result; } @Override public void inviteUsers(@NonNull final String groupUuid, @NonNull final List<User> usersToinvite, @NonNull final InviteUsersCallback callback) { // check that group exists getGroupByUuid(groupUuid, false, new GetGroupByUuidCallback() { @Override public void onGetGroupByUuidCompleted(FirebaseResult<Group> result) { if (result.getData() == null) { // group not found callback.onInviteUsersCompleted( new FirebaseResult<String>(FamilyTrackException.getInstance(mContext, FamilyTrackException.DB_GROUP_NOT_FOUND))); return; } CountDownLatch countDownLatch = new CountDownLatch(usersToinvite.size()); for (User user : usersToinvite) { inviteUser(user, result.getData(), countDownLatch, callback); } } }); } private void inviteUser(final User user, final Group group, final CountDownLatch countDownLatch, final InviteUsersCallback callback) { if (isUserAlreadyInvited(user, group)) { return; } //закончил здесь, почему-то вместо uuid подставляется id пользователя из контактов // проверяем логинился ли такой пользователь в системе final Map<String, Object> childUpdates = new HashMap<>(); getUserByPhone(user.getPhone(), new GetUserByPhoneCallback() { @Override public void onGetUserByPhoneCompleted(FirebaseResult<User> result) { User dbUser = result.getData(); Membership newMembership = new Membership(group.getGroupUuid(), group.getName(), Membership.ROLE_UNDEFINED, Membership.USER_INVITED); if (dbUser == null) { // пользователь не найден, вначале создаем пользователя в ветке registered_users user.addMembership(newMembership); user.setUserUuid(getFirebaseConnection().getReference(Group.REGISTERED_USERS_GROUP_KEY).push().getKey()); childUpdates.put(FamilyTrackDbRefsHelper.userRef(user.getUserUuid()), user); group.addMember(user); childUpdates.put(FamilyTrackDbRefsHelper.groupRef(group.getGroupUuid()), group); } else { // пользователь уже регистрировался в системе, // просто добавляем его в группу в качестве приглашенного dbUser.addMembership(newMembership); childUpdates.put(FamilyTrackDbRefsHelper.userRef(dbUser.getUserUuid()), dbUser); group.addMember(dbUser); childUpdates.put(FamilyTrackDbRefsHelper.groupRef(group.getGroupUuid()), group); } getFirebaseConnection() .getReference() .updateChildren(childUpdates) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { countDownLatch.countDown(); if (countDownLatch.getCount() == 0 && callback != null) { callback.onInviteUsersCompleted(new FirebaseResult<>(FirebaseResult.RESULT_OK)); } } }); } }); } /** * checks if user already is member of group * @param user - user to check * @param group - group of mUsers from firebase wich we want to check against membership of user * @return true if user already in group */ private boolean isUserAlreadyInvited(User user, Group group) { boolean result = false; for (String key : group.getMembers().keySet()) { User groupUser = group.getMembers().get(key); if (user.getPhone().equals(groupUser.getPhone()) && user.getEmail().equals(groupUser.getEmail())) { result = true; break; } } return result; } @Override public void getUserGroups(@NonNull String userUuid, @NonNull final GetUserGroupsCallback callback) { final List<Group> groups = new ArrayList<>(); getUserByUuid(userUuid, new GetUserByUuidCallback() { @Override public void onGetUserByUuidCompleted(FirebaseResult<User> result) { if (result.getException() != null) { callback.onGetUserGroupsCompleted(new FirebaseResult<List<Group>>(result.getException())); } final List<Group> groups = new ArrayList<Group>(); if (result.getData() != null && result.getData().getMemberships() != null) { //Timber.v("Starting for, number of groups=" + result.getData().getMemberships().size()); final CountDownLatch doneSignal = new CountDownLatch(result.getData().getMemberships().size()); for (String key : result.getData().getMemberships().keySet()) { Membership membership = result.getData().getMemberships().get(key); // now read data of each group in list //Timber.v("Call getGroupByUuid for " + membership.getGroupUuid()); getGroupByUuid(membership.getGroupUuid(), false, new GetGroupByUuidCallback() { @Override public synchronized void onGetGroupByUuidCompleted(FirebaseResult<Group> result) { //Timber.v("onGetGroupByUuidCompleted"); if (result.getData() != null) { groups.add(result.getData()); } doneSignal.countDown(); if (doneSignal.getCount() == 0) { // all requests completed, should call callback callback.onGetUserGroupsCompleted(new FirebaseResult<List<Group>>(groups)); } } }); } } } }); } @Override public void changeUserMembership(@NonNull String userUuid, @NonNull String fromGroupUuid, @NonNull String toGroupUuid, final @NonNull ChangeUserMembershipCallback callback) { // groups/-KtrkQ0jWp4m3dQg43V9/members/-KtrkPuXJZs21vF6mMzS/memberships/-KtrkQ0jWp4m3dQg43V9 // registered_users/-Ku_qk0QFapzaREjRYCZ/memberships/-KtrkQ0jWp4m3dQg43V9 Map<String, Object> childUpdates = new HashMap<>(); if (!fromGroupUuid.equals("")) { childUpdates.put(FamilyTrackDbRefsHelper.userMembershipRef(userUuid, fromGroupUuid) + Membership.FIELD_STATUS_ID, Membership.USER_DEPARTED); childUpdates.put(FamilyTrackDbRefsHelper.groupOfUserRef(userUuid, fromGroupUuid) + Membership.FIELD_STATUS_ID, Membership.USER_DEPARTED); } if (!toGroupUuid.equals("")) { childUpdates.put(FamilyTrackDbRefsHelper.userMembershipRef(userUuid, toGroupUuid) + Membership.FIELD_STATUS_ID, Membership.USER_JOINED); childUpdates.put(FamilyTrackDbRefsHelper.groupOfUserRef(userUuid, toGroupUuid) + Membership.FIELD_STATUS_ID, Membership.USER_JOINED); childUpdates.put(FamilyTrackDbRefsHelper.userMembershipRef(userUuid, toGroupUuid) + Membership.FIELD_ROLE_ID, Membership.ROLE_MEMBER); childUpdates.put(FamilyTrackDbRefsHelper.groupOfUserRef(userUuid, toGroupUuid) + Membership.FIELD_ROLE_ID, Membership.ROLE_MEMBER); } mFirebaseDatabase.getReference() .updateChildren(childUpdates) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (callback != null) { callback.onChangeUserMembershipCompleted(new FirebaseResult<String>(FirebaseResult.RESULT_OK)); } } }); } @Override public void getGroupsAvailableToJoin(@NonNull String phoneNumber, final @NonNull GetGroupsAvailableToJoinCallback callback) { this.getUserByPhone(phoneNumber, new GetUserByPhoneCallback() { @Override public void onGetUserByPhoneCompleted(FirebaseResult<User> result) { if (result.getException() != null) { callback.onGetGroupsAvailableToJoinCompleted(new FirebaseResult<List<Group>>(result.getException())); } List<Group> groups = new ArrayList<Group>(); if (result.getData() != null) { if (result.getData().getMemberships() != null) { for (String key : result.getData().getMemberships().keySet()) { Membership membership = result.getData().getMemberships().get(key); if (membership.getStatusId() == Membership.USER_INVITED || membership.getStatusId() == Membership.USER_DEPARTED) groups.add(new Group(membership.getGroupUuid(), membership.getGroupName())); } } } callback.onGetGroupsAvailableToJoinCompleted(new FirebaseResult<List<Group>>(groups)); } }); } @Override public void addUserToGroup(@NonNull String userUuid, @NonNull String groupUuid, final AddUserToGroupCallback callback) { // для перевода пользователя в состояние MEMMBER нам необходимо: // - изменить статус пользователя в ветке registered_users/<user_key> // - изменить статус пользователя в ветке groups/<group_key>/members/<user_key>/memberships/<group_key> Map<String, Object> childUpdates = new HashMap<>(); childUpdates.put(FamilyTrackDbRefsHelper.groupOfUserRef(userUuid, groupUuid) + User.FIELD_ROLE_ID, Membership.ROLE_MEMBER); childUpdates.put(FamilyTrackDbRefsHelper.groupOfUserRef(userUuid, groupUuid) + User.FIELD_STATUS_ID, Membership.USER_JOINED); childUpdates.put(FamilyTrackDbRefsHelper.userMembershipRef(userUuid, groupUuid) + User.FIELD_ROLE_ID, Membership.ROLE_MEMBER); childUpdates.put(FamilyTrackDbRefsHelper.userMembershipRef(userUuid, groupUuid) + User.FIELD_STATUS_ID, Membership.USER_JOINED); mFirebaseDatabase.getReference() .updateChildren(childUpdates) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (callback != null) { callback.onAddUserToGroupCompleted(new FirebaseResult<String>(FirebaseResult.RESULT_OK)); } } }); } @Override public void updateUserLocation(@NonNull final String userUuid, @NonNull final Location location, @NonNull final UpdateUserLocationCallback callback) { //Timber.v("Started"); getUserByUuid(userUuid, new GetUserByUuidCallback() { @Override public void onGetUserByUuidCompleted(FirebaseResult<User> result) { // check if user exists User user = result.getData(); if (user == null) { callback.onUpdateUserLocationCompleted( new FirebaseResult<String>(FamilyTrackException.getInstance(mContext, FamilyTrackException.DB_USER_BY_UUID_NOT_FOUND))); return; } // now prepare data for updates // we should update user location in three nodes: // - /groups/<groupUuid>/members/<userUuid> - for active group only! // - /registered_users/<userUuid> // - /history/<userUuid>/<new location> Map<String, Object> childUpdates = new HashMap<>(); childUpdates.put(FamilyTrackDbRefsHelper.userRef(userUuid) + User.FIELD_LAST_KNOWN_LOCATION, location); if (user.getActiveMembership() != null) { childUpdates.put(FamilyTrackDbRefsHelper.userOfGroupRef( user.getActiveMembership().getGroupUuid(), userUuid) + User.FIELD_LAST_KNOWN_LOCATION, location); } String historyItemPath = FamilyTrackDbRefsHelper.userHistory(userUuid); DatabaseReference ref = getFirebaseConnection().getReference(historyItemPath); String historyItemKey = ref.push().getKey(); childUpdates.put(historyItemPath + "/" + historyItemKey, location); mFirebaseDatabase.getReference() .updateChildren(childUpdates) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (callback != null) { callback.onUpdateUserLocationCompleted( new FirebaseResult<String>(FirebaseResult.RESULT_OK)); } } }); } }); } @Override public void getUserTrack(@NonNull String userUuid, long periodStart, long periodEnd, final @NonNull GetUserTrackCallback callback) { String historyItemPath = FamilyTrackDbRefsHelper.userHistory(userUuid); DatabaseReference ref = getFirebaseConnection().getReference(historyItemPath); Query query = ref.orderByChild(Location.FIELD_TIMESTAMP).startAt(periodStart).endAt(periodEnd); query.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { List<Location> locations = new ArrayList<>(); if (dataSnapshot.getChildren() != null) { for (DataSnapshot snapshot : dataSnapshot.getChildren()) { locations.add(FirebaseUtil.getLocationFromSnapshot(snapshot)); } } callback.onGetUserTrackCompleted(new FirebaseResult<>(locations)); } @Override public void onCancelled(DatabaseError databaseError) { } }); } // -------------------------------------------------------------------------------------------- // // zones operations // // -------------------------------------------------------------------------------------------- @Override public void createZone(@NonNull String groupUuid, @NonNull Zone zone, CreateZoneCallback callback) { DatabaseReference ref = getFirebaseConnection() .getReference(FamilyTrackDbRefsHelper.zonesOfGroup(groupUuid)); DatabaseReference newRec = ref.push(); newRec.setValue(zone); if (callback != null) { callback.onCreateZoneCompleted(new FirebaseResult<>(newRec.getKey())); } } @Override public void updateZone(@NonNull String groupUuid, @NonNull Zone zone, UpdateZoneCallback callback) { DatabaseReference ref = getFirebaseConnection() .getReference(FamilyTrackDbRefsHelper.zoneOfGroup(groupUuid, zone.getUuid())); ref.setValue(zone); if (callback != null) { callback.onUpdateZoneCompleted(new FirebaseResult<>(zone.getUuid())); } } @Override public void removeZone(@NonNull String groupUuid, @NonNull String zoneUuid, final RemoveZoneCallback callback) { DatabaseReference ref = getFirebaseConnection() .getReference(FamilyTrackDbRefsHelper.zoneOfGroup(groupUuid, zoneUuid)); ref.removeValue(new DatabaseReference.CompletionListener() { @Override public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) { if (callback != null) { if (databaseError != null) { callback.onRemoveZoneCompleted(new FirebaseResult<String>(databaseError)); } else { callback.onRemoveZoneCompleted(new FirebaseResult<>(FirebaseResult.RESULT_OK)); } } } }); } @Override public void getSettingsByGroupUuid(@NonNull String groupUuid, @NonNull final GetSettingsByGroupUuidCallback callback) { DatabaseReference ref = getFirebaseConnection() .getReference(FamilyTrackDbRefsHelper.groupSettingsRef(groupUuid)); Query query = ref.orderByValue(); query.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { Settings s = Settings.getDefaultInstance(); if (dataSnapshot.getChildrenCount() > 0) { s = dataSnapshot.getValue(Settings.class); } callback.onGetSettingsByGroupUuidCompleted(new FirebaseResult<>(s)); } @Override public void onCancelled(DatabaseError databaseError) { } }); } @Override public void updateSettingsByGroupUuid(@NonNull String groupUuid, @NonNull Settings settings, UpdateSettingsByGroupUuidCallback callback) { DatabaseReference ref = getFirebaseConnection() .getReference(FamilyTrackDbRefsHelper.groupSettingsRef(groupUuid)); ref.setValue(settings); if (callback != null) { callback.onUpdateSettingsByGroupUuidCompleted(new FirebaseResult<>(FirebaseResult.RESULT_OK)); } } @Override public void deleteGeofenceEvent(@NonNull String userUuid, @NonNull String eventUuid, DeleteGeofenceEventsCallback callback) { DatabaseReference ref = getFirebaseConnection() .getReference(FamilyTrackDbRefsHelper.geofenceEventRef(userUuid, eventUuid)); ref.setValue(null); if (callback != null) { callback.onDeleteGeofenceEventsCompleted(new FirebaseResult<>(FirebaseResult.RESULT_OK)); } } @Override public void deleteGeofenceEvents(@NonNull String userUuid, DeleteGeofenceEventsCallback callback) { DatabaseReference ref = getFirebaseConnection() .getReference(FamilyTrackDbRefsHelper.geofenceEventsRef(userUuid)); ref.setValue(null); if (callback != null) { callback.onDeleteGeofenceEventsCompleted(new FirebaseResult<>(FirebaseResult.RESULT_OK)); } } // чтобы не забыть как это рабоотает // уведомление формируется для каждого пользователя группы в роли Admin // и записывается по адресу geofence_events/<groupAdminUuid>/<event> // каждый администратор получает уведомление об изменении прослушиваемого узла, читает эти данные, // формирует сообщение и удаляет их @Override public void createGeofenceEvent(@NonNull final String groupUuid, final GeofenceEvent geofenceEvent, final CreateGeofenceEventCallback callback) { getGroupByUuid(groupUuid, false, new GetGroupByUuidCallback() { @Override public void onGetGroupByUuidCompleted(FirebaseResult<Group> result) { if (result.getData() == null) { //Timber.v("Group with key ='" + groupUuid + "' not found"); if (callback != null) { callback.onCreateGeofenceEventCompleted(new FirebaseResult<>(FirebaseResult.RESULT_FAILED)); } return; } for (String key : result.getData().getMembers().keySet()) { User user = result.getData().getMembers().get(key); if (user.getActiveMembership() != null) { if (user.getActiveMembership().getStatusId() == Membership.USER_JOINED && user.getActiveMembership().getRoleId() == Membership.ROLE_ADMIN) { String path = FamilyTrackDbRefsHelper.geofenceEventsRef(user.getUserUuid()); String newKey = getFirebaseConnection().getReference(path).push().getKey(); geofenceEvent.setEventUuid(newKey); getFirebaseConnection().getReference(path + newKey).setValue(geofenceEvent); } } } if (callback != null) { callback.onCreateGeofenceEventCompleted(new FirebaseResult<>(FirebaseResult.RESULT_OK)); } } }); } @Override public void getGeofenceEventsByUserUuid(@NonNull String userUuid, final @NonNull GetGeofenceEventsByUserUuidCallback callback) { DatabaseReference ref = getFirebaseConnection() .getReference(FamilyTrackDbRefsHelper.geofenceEventsRef(userUuid)); Query query = ref.orderByKey(); query.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { List<GeofenceEvent> events = new ArrayList<>(); if (dataSnapshot.getChildren() != null) { for (DataSnapshot snapshot : dataSnapshot.getChildren()) { events.add(FirebaseUtil.getGeofenceEventFromSnapshot(snapshot)); } } callback.onGetGeofenceEventsByUserUuidCompleted(new FirebaseResult<>(events)); } @Override public void onCancelled(DatabaseError databaseError) { } }); } }
UTF-8
Java
44,199
java
FamilyTrackRepository.java
Java
[ { "context": "tch;\n\nimport timber.log.Timber;\n\n/**\n * Created by DmitryVolynski on 17.08.2017.\n */\n\npublic class FamilyTrackRepos", "end": 1562, "score": 0.9937216639518738, "start": 1548, "tag": "NAME", "value": "DmitryVolynski" }, { "context": "romGroupCallback callback) {\n String key1 = FamilyTrackDbRefsHelper.userOfGroupRef(groupUuid, userUuid);\n String key2 = Family", "end": 13062, "score": 0.8597896695137024, "start": 13023, "tag": "KEY", "value": "FamilyTrackDbRefsHelper.userOfGroupRef(" }, { "context": "ey1 = FamilyTrackDbRefsHelper.userOfGroupRef(groupUuid, userUuid);\n String key2 = FamilyTrackDbRef", "end": 13072, "score": 0.6120284795761108, "start": 13067, "tag": "KEY", "value": "Uuid," }, { "context": "groupUuid, userUuid);\n String key2 = FamilyTrackDbRefsHelper.groupOfUserRef(userUuid, groupUuid);\n\n Map<String, Object>", "end": 13145, "score": 0.8133556246757507, "start": 13112, "tag": "KEY", "value": "TrackDbRefsHelper.groupOfUserRef(" }, { "context": "key2 = FamilyTrackDbRefsHelper.groupOfUserRef(userUuid, groupUuid);\n\n Map<String, Object> childUp", "end": 13153, "score": 0.6072375774383545, "start": 13149, "tag": "KEY", "value": "Uuid" } ]
null
[]
package com.volynski.familytrack.data; import android.content.Context; import android.database.Cursor; import android.provider.ContactsContract; import android.support.annotation.NonNull; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthCredential; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.GoogleAuthProvider; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.Query; import com.google.firebase.database.ValueEventListener; import com.volynski.familytrack.R; import com.volynski.familytrack.StringKeys; import com.volynski.familytrack.data.models.firebase.GeofenceEvent; import com.volynski.familytrack.data.models.firebase.Group; import com.volynski.familytrack.data.models.firebase.Location; import com.volynski.familytrack.data.models.firebase.Membership; import com.volynski.familytrack.data.models.firebase.Settings; import com.volynski.familytrack.data.models.firebase.User; import com.volynski.familytrack.data.models.firebase.Zone; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; import timber.log.Timber; /** * Created by DmitryVolynski on 17.08.2017. */ public class FamilyTrackRepository implements FamilyTrackDataSource { private static final String TAG = FamilyTrackRepository.class.getSimpleName(); private FirebaseDatabase mFirebaseDatabase; private String mGoogleAccountIdToken; private FirebaseAuth mFirebaseAuth; private Context mContext; // TODO проверить необходимость передачи GoogleSignInAccount в конструктор public FamilyTrackRepository(String googleAccountIdToken, Context context) { mGoogleAccountIdToken = googleAccountIdToken; mContext = context.getApplicationContext(); } private void firebaseAuthWithGoogle(String idToken) { AuthCredential credential = GoogleAuthProvider.getCredential(idToken, null); mFirebaseAuth = FirebaseAuth.getInstance(); if (mFirebaseAuth.getCurrentUser() == null) { mFirebaseAuth.signInWithCredential(credential) .addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { Timber.v(TAG, "signInWithCredential:onComplete:" + task.isSuccessful()); // If sign in fails, display a message to the user. If sign in succeeds // the auth state listener will be notified and logic to handle the // signed in user can be handled in the listener. if (!task.isSuccessful()) { Timber.e("signInWithCredential failed", task.getException()); } } }); } } @Override public FirebaseDatabase getFirebaseConnection() { if (mFirebaseDatabase == null) { firebaseAuthWithGoogle(mGoogleAccountIdToken); mFirebaseDatabase = FirebaseDatabase.getInstance(); } return mFirebaseDatabase; } @Override public void createUser(@NonNull User user, final CreateUserCallback callback) { DatabaseReference ref = getFirebaseConnection().getReference(Group.REGISTERED_USERS_GROUP_KEY); DatabaseReference newUserRef = ref.push(); newUserRef.setValue(user); if (callback != null) { user.setUserUuid(newUserRef.getKey()); callback.onCreateUserCompleted(new FirebaseResult<>(user)); } } @Override public void updateUser(@NonNull final User user, final UpdateUserCallback callback) { getUserGroups(user.getUserUuid(), new GetUserGroupsCallback() { @Override public void onGetUserGroupsCompleted(FirebaseResult<List<Group>> result) { Map<String, Object> childUpdates = new HashMap<>(); childUpdates.put(FamilyTrackDbRefsHelper.userRef(user.getUserUuid()), user); if (result.getData() != null) { for (Group group : result.getData()) { childUpdates.put(FamilyTrackDbRefsHelper .userOfGroupRef(group.getGroupUuid(), user.getUserUuid()), user.cloneForGroupNode(group.getGroupUuid())); } } mFirebaseDatabase.getReference() .updateChildren(childUpdates) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (callback != null) { callback.onUpdateUserCompleted(new FirebaseResult<>(FirebaseResult.RESULT_OK)); } } }); } }); } @Override public void changeUserStatus(@NonNull String userUuid, int newStatus) { } @Override public void getUserByUuid(@NonNull String userUuid, @NonNull final GetUserByUuidCallback callback) { DatabaseReference ref = getFirebaseConnection().getReference(Group.REGISTERED_USERS_GROUP_KEY); Query query = ref.orderByKey().equalTo(userUuid).limitToFirst(1); query.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { User user = null; if (dataSnapshot.getChildrenCount() > 0) { user = FirebaseUtil.getUserFromSnapshot(dataSnapshot.getChildren().iterator().next()); } callback.onGetUserByUuidCompleted(new FirebaseResult<>(user)); } @Override public void onCancelled(DatabaseError databaseError) { callback.onGetUserByUuidCompleted(new FirebaseResult<User>(databaseError)); } }); } @Override public void getUserByEmail(@NonNull String userEmail, @NonNull final GetUserByEmailCallback callback) { DatabaseReference ref = getFirebaseConnection().getReference(Group.REGISTERED_USERS_GROUP_KEY); Query query = ref.orderByChild(User.FIELD_EMAIL).equalTo(userEmail).limitToFirst(1); query.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { User user = null; if (dataSnapshot.getChildrenCount() > 0) { user = FirebaseUtil.getUserFromSnapshot(dataSnapshot.getChildren().iterator().next()); } callback.onGetUserByEmailCompleted(new FirebaseResult<>(user)); } @Override public void onCancelled(DatabaseError databaseError) { callback.onGetUserByEmailCompleted(new FirebaseResult<User>(databaseError)); } }); } @Override public void getUserByPhone(@NonNull String userPhone, @NonNull final GetUserByPhoneCallback callback) { DatabaseReference ref = getFirebaseConnection().getReference(Group.REGISTERED_USERS_GROUP_KEY); Query query = ref.orderByChild(User.FIELD_PHONE).equalTo(userPhone).limitToFirst(1); query.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { User user = null; if (dataSnapshot.getChildrenCount() > 0) { user = FirebaseUtil.getUserFromSnapshot(dataSnapshot.getChildren().iterator().next()); } callback.onGetUserByPhoneCompleted(new FirebaseResult<>(user)); } @Override public void onCancelled(DatabaseError databaseError) { callback.onGetUserByPhoneCompleted(new FirebaseResult<User>(databaseError)); } }); } @Override public void createGroup(@NonNull final Group group, String adminUuid, final CreateGroupCallback callback) { // что необходимо сделать при создании новой группы // - исключить пользователя из текущей активной группы (заменить статус на USER_DEPARTED) // - создать новую группу // - включить туда пользователя в роли ROLE_ADMIN и статусе USER_JOINED // Эти изменения делаются в двух местах - // 1. groups/<groupUuid>/members/<userUuid>/memberships/<groupUuid>/statusId <- USER_DEPARTED // 2. registered_users/<userUuid>/memberships/<groupUuid>/statusId <- USER_DEPARTED // 3. то же самое для новой группы, но со статусом USER_JOINED - в тех же двух местах getUserByUuid(adminUuid, new GetUserByUuidCallback() { @Override public void onGetUserByUuidCompleted(FirebaseResult<User> result) { String currentGroupUuid = null; if (result.getData() != null) { User currentUser = result.getData(); // если пользователь не входит в группу, то исключать его не нужно if (currentUser.getActiveMembership() != null) { currentGroupUuid = currentUser.getActiveMembership().getGroupUuid(); } DatabaseReference ref = getFirebaseConnection() .getReference(FamilyTrackDbRefsHelper.NODE_GROUPS); String newGroupKey = ref.push().getKey(); Membership newMembership = new Membership(newGroupKey, group.getName(), Membership.ROLE_ADMIN, Membership.USER_JOINED); currentUser.setMemberships(new HashMap<String, Membership>()); currentUser.addMembership(newMembership); group.setGroupUuid(newGroupKey); group.addMember(currentUser); DatabaseReference newGroupRef = mFirebaseDatabase .getReference(FamilyTrackDbRefsHelper.groupRef(newGroupKey)); newGroupRef.setValue(group); Map<String, Object> childUpdates = new HashMap<>(); if (currentGroupUuid != null) { childUpdates.put(FamilyTrackDbRefsHelper .userMembershipRef(currentUser.getUserUuid(), currentGroupUuid) + Membership.FIELD_STATUS_ID, Membership.USER_DEPARTED); childUpdates.put(FamilyTrackDbRefsHelper .groupOfUserRef(currentUser.getUserUuid(), currentGroupUuid) + Membership.FIELD_STATUS_ID, Membership.USER_DEPARTED); } childUpdates.put(FamilyTrackDbRefsHelper .groupOfUserRef(currentUser.getUserUuid(), newGroupKey), newMembership); mFirebaseDatabase.getReference() .updateChildren(childUpdates) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (callback != null) { callback.onCreateGroupCompleted(new FirebaseResult<>(group)); } } }); } else { if (callback != null) { callback.onCreateGroupCompleted( new FirebaseResult<Group>(FamilyTrackException.getInstance(mContext, FamilyTrackException.DB_USER_BY_UUID_NOT_FOUND))); } } } }); } /** * Membership records will be physically deleted from * - registered_users/<userUuid>/memberships/<groupUuid> * - groups/<groupUuid>/members/<userUuid> */ @Override public void removeUserFromGroup(@NonNull String groupUuid, @NonNull String userUuid, final RemoveUserFromGroupCallback callback) { String key1 = FamilyTrackDbRefsHelper.userOfGroupRef(groupUuid, userUuid); String key2 = FamilyTrackDbRefsHelper.groupOfUserRef(userUuid, groupUuid); Map<String, Object> childUpdates = new HashMap<>(); childUpdates.put(key1, null); childUpdates.put(key2, null); getFirebaseConnection().getReference() .updateChildren(childUpdates) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (callback != null) { callback.onRemoveUserFromGroupCompleted(new FirebaseResult<>(FirebaseResult.RESULT_OK)); } } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Timber.e(e); if (callback != null) { callback.onRemoveUserFromGroupCompleted( new FirebaseResult<String>(FamilyTrackException.getInstance(mContext, FamilyTrackException.DB_REMOVE_USER_FAILED))); } } }); } @Override public void getGroupByUuid(@NonNull String groupUuid, boolean trackGroupNode, final @NonNull GetGroupByUuidCallback callback) { DatabaseReference ref = getFirebaseConnection() .getReference(FamilyTrackDbRefsHelper.groupRef(groupUuid)); Query query = ref.orderByValue(); ValueEventListener listener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { // get Group object with all members Group group = FirebaseUtil.getGroupFromSnapshot(dataSnapshot); callback.onGetGroupByUuidCompleted(new FirebaseResult<>(group)); } @Override public void onCancelled(DatabaseError databaseError) { } }; if (trackGroupNode) { query.addValueEventListener(listener); } else { query.addListenerForSingleValueEvent(listener); } } @Override public void getContactsToInvite(@NonNull final String groupUuid, @NonNull final GetContactsToInviteCallback callback) { User user; // read contacts from ContactsContract.Data.CONTENT_URI Cursor cursor = mContext.getContentResolver().query( ContactsContract.Data.CONTENT_URI, null, ContactsContract.Data.HAS_PHONE_NUMBER + "!=0 AND (" + ContactsContract.Data.MIMETYPE + "=? OR " + ContactsContract.Data.MIMETYPE + "=?)", new String[]{ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE}, ContactsContract.Data.CONTACT_ID); // merge same contacts with emails & phone numbers final Map<String, User> contacts = new HashMap<>(); while (cursor.moveToNext()) { String key = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.CONTACT_ID)); boolean isNew = !contacts.containsKey(key); if (isNew) { String givenName = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME)); user = new User(key, "", "", cursor.getString(cursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME)), StringKeys.CREATED_FROM_CONTACTS_KEY, "", "", null, null); } else { user = contacts.get(key); } //Timber.v(user.getDisplayName() + "/" + cursor.getString(cursor.getColumnIndex(ContactsContract.Data.MIMETYPE))); String mimeType = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.MIMETYPE)); try { String data = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.DATA1)); if (mimeType.equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)) { user.setEmail(data); } else { user.setPhone(formatPhoneString(data)); } if (isNew) { contacts.put(key, user); } else { contacts.remove(key); contacts.put(key, user); } } catch (Exception e) { Timber.e(e); } } cursor.close(); getGroupByUuid(groupUuid, false, new GetGroupByUuidCallback() { @Override public void onGetGroupByUuidCompleted(FirebaseResult<Group> result) { List<User> users = new ArrayList<>(); if (result.getData() == null) { Timber.v(String.format(mContext.getString(R.string.ex_group_with_uuid_not_found), groupUuid)); callback.onGetContactsToInviteCompleted(new FirebaseResult<List<User>>(users)); } // select contacts that have phone number and email + not already invited in group for (String key : contacts.keySet()) { User u = contacts.get(key); if (!u.getPhone().equals("") && !u.getEmail().equals("") && !isUserInGroup(u, result.getData())) { users.add(u); } } callback.onGetContactsToInviteCompleted(new FirebaseResult<List<User>>(users)); } }); } private String formatPhoneString(String data) { String result = null; if (data != null) { result = data.replaceAll("[ ()-]", ""); } return result; } /** * Checks if user from phone contact list is already invited * @param user - user from phone contacts * @param group * @return true if group already contains user with email that equals user email */ private boolean isUserInGroup(User user, Group group) { boolean result = false; if (group.getMembers() != null) { for (String key : group.getMembers().keySet()) { result = user.getEmail().equals(group.getMembers().get(key).getEmail()); if (result) { break; } } } return result; } @Override public void inviteUsers(@NonNull final String groupUuid, @NonNull final List<User> usersToinvite, @NonNull final InviteUsersCallback callback) { // check that group exists getGroupByUuid(groupUuid, false, new GetGroupByUuidCallback() { @Override public void onGetGroupByUuidCompleted(FirebaseResult<Group> result) { if (result.getData() == null) { // group not found callback.onInviteUsersCompleted( new FirebaseResult<String>(FamilyTrackException.getInstance(mContext, FamilyTrackException.DB_GROUP_NOT_FOUND))); return; } CountDownLatch countDownLatch = new CountDownLatch(usersToinvite.size()); for (User user : usersToinvite) { inviteUser(user, result.getData(), countDownLatch, callback); } } }); } private void inviteUser(final User user, final Group group, final CountDownLatch countDownLatch, final InviteUsersCallback callback) { if (isUserAlreadyInvited(user, group)) { return; } //закончил здесь, почему-то вместо uuid подставляется id пользователя из контактов // проверяем логинился ли такой пользователь в системе final Map<String, Object> childUpdates = new HashMap<>(); getUserByPhone(user.getPhone(), new GetUserByPhoneCallback() { @Override public void onGetUserByPhoneCompleted(FirebaseResult<User> result) { User dbUser = result.getData(); Membership newMembership = new Membership(group.getGroupUuid(), group.getName(), Membership.ROLE_UNDEFINED, Membership.USER_INVITED); if (dbUser == null) { // пользователь не найден, вначале создаем пользователя в ветке registered_users user.addMembership(newMembership); user.setUserUuid(getFirebaseConnection().getReference(Group.REGISTERED_USERS_GROUP_KEY).push().getKey()); childUpdates.put(FamilyTrackDbRefsHelper.userRef(user.getUserUuid()), user); group.addMember(user); childUpdates.put(FamilyTrackDbRefsHelper.groupRef(group.getGroupUuid()), group); } else { // пользователь уже регистрировался в системе, // просто добавляем его в группу в качестве приглашенного dbUser.addMembership(newMembership); childUpdates.put(FamilyTrackDbRefsHelper.userRef(dbUser.getUserUuid()), dbUser); group.addMember(dbUser); childUpdates.put(FamilyTrackDbRefsHelper.groupRef(group.getGroupUuid()), group); } getFirebaseConnection() .getReference() .updateChildren(childUpdates) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { countDownLatch.countDown(); if (countDownLatch.getCount() == 0 && callback != null) { callback.onInviteUsersCompleted(new FirebaseResult<>(FirebaseResult.RESULT_OK)); } } }); } }); } /** * checks if user already is member of group * @param user - user to check * @param group - group of mUsers from firebase wich we want to check against membership of user * @return true if user already in group */ private boolean isUserAlreadyInvited(User user, Group group) { boolean result = false; for (String key : group.getMembers().keySet()) { User groupUser = group.getMembers().get(key); if (user.getPhone().equals(groupUser.getPhone()) && user.getEmail().equals(groupUser.getEmail())) { result = true; break; } } return result; } @Override public void getUserGroups(@NonNull String userUuid, @NonNull final GetUserGroupsCallback callback) { final List<Group> groups = new ArrayList<>(); getUserByUuid(userUuid, new GetUserByUuidCallback() { @Override public void onGetUserByUuidCompleted(FirebaseResult<User> result) { if (result.getException() != null) { callback.onGetUserGroupsCompleted(new FirebaseResult<List<Group>>(result.getException())); } final List<Group> groups = new ArrayList<Group>(); if (result.getData() != null && result.getData().getMemberships() != null) { //Timber.v("Starting for, number of groups=" + result.getData().getMemberships().size()); final CountDownLatch doneSignal = new CountDownLatch(result.getData().getMemberships().size()); for (String key : result.getData().getMemberships().keySet()) { Membership membership = result.getData().getMemberships().get(key); // now read data of each group in list //Timber.v("Call getGroupByUuid for " + membership.getGroupUuid()); getGroupByUuid(membership.getGroupUuid(), false, new GetGroupByUuidCallback() { @Override public synchronized void onGetGroupByUuidCompleted(FirebaseResult<Group> result) { //Timber.v("onGetGroupByUuidCompleted"); if (result.getData() != null) { groups.add(result.getData()); } doneSignal.countDown(); if (doneSignal.getCount() == 0) { // all requests completed, should call callback callback.onGetUserGroupsCompleted(new FirebaseResult<List<Group>>(groups)); } } }); } } } }); } @Override public void changeUserMembership(@NonNull String userUuid, @NonNull String fromGroupUuid, @NonNull String toGroupUuid, final @NonNull ChangeUserMembershipCallback callback) { // groups/-KtrkQ0jWp4m3dQg43V9/members/-KtrkPuXJZs21vF6mMzS/memberships/-KtrkQ0jWp4m3dQg43V9 // registered_users/-Ku_qk0QFapzaREjRYCZ/memberships/-KtrkQ0jWp4m3dQg43V9 Map<String, Object> childUpdates = new HashMap<>(); if (!fromGroupUuid.equals("")) { childUpdates.put(FamilyTrackDbRefsHelper.userMembershipRef(userUuid, fromGroupUuid) + Membership.FIELD_STATUS_ID, Membership.USER_DEPARTED); childUpdates.put(FamilyTrackDbRefsHelper.groupOfUserRef(userUuid, fromGroupUuid) + Membership.FIELD_STATUS_ID, Membership.USER_DEPARTED); } if (!toGroupUuid.equals("")) { childUpdates.put(FamilyTrackDbRefsHelper.userMembershipRef(userUuid, toGroupUuid) + Membership.FIELD_STATUS_ID, Membership.USER_JOINED); childUpdates.put(FamilyTrackDbRefsHelper.groupOfUserRef(userUuid, toGroupUuid) + Membership.FIELD_STATUS_ID, Membership.USER_JOINED); childUpdates.put(FamilyTrackDbRefsHelper.userMembershipRef(userUuid, toGroupUuid) + Membership.FIELD_ROLE_ID, Membership.ROLE_MEMBER); childUpdates.put(FamilyTrackDbRefsHelper.groupOfUserRef(userUuid, toGroupUuid) + Membership.FIELD_ROLE_ID, Membership.ROLE_MEMBER); } mFirebaseDatabase.getReference() .updateChildren(childUpdates) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (callback != null) { callback.onChangeUserMembershipCompleted(new FirebaseResult<String>(FirebaseResult.RESULT_OK)); } } }); } @Override public void getGroupsAvailableToJoin(@NonNull String phoneNumber, final @NonNull GetGroupsAvailableToJoinCallback callback) { this.getUserByPhone(phoneNumber, new GetUserByPhoneCallback() { @Override public void onGetUserByPhoneCompleted(FirebaseResult<User> result) { if (result.getException() != null) { callback.onGetGroupsAvailableToJoinCompleted(new FirebaseResult<List<Group>>(result.getException())); } List<Group> groups = new ArrayList<Group>(); if (result.getData() != null) { if (result.getData().getMemberships() != null) { for (String key : result.getData().getMemberships().keySet()) { Membership membership = result.getData().getMemberships().get(key); if (membership.getStatusId() == Membership.USER_INVITED || membership.getStatusId() == Membership.USER_DEPARTED) groups.add(new Group(membership.getGroupUuid(), membership.getGroupName())); } } } callback.onGetGroupsAvailableToJoinCompleted(new FirebaseResult<List<Group>>(groups)); } }); } @Override public void addUserToGroup(@NonNull String userUuid, @NonNull String groupUuid, final AddUserToGroupCallback callback) { // для перевода пользователя в состояние MEMMBER нам необходимо: // - изменить статус пользователя в ветке registered_users/<user_key> // - изменить статус пользователя в ветке groups/<group_key>/members/<user_key>/memberships/<group_key> Map<String, Object> childUpdates = new HashMap<>(); childUpdates.put(FamilyTrackDbRefsHelper.groupOfUserRef(userUuid, groupUuid) + User.FIELD_ROLE_ID, Membership.ROLE_MEMBER); childUpdates.put(FamilyTrackDbRefsHelper.groupOfUserRef(userUuid, groupUuid) + User.FIELD_STATUS_ID, Membership.USER_JOINED); childUpdates.put(FamilyTrackDbRefsHelper.userMembershipRef(userUuid, groupUuid) + User.FIELD_ROLE_ID, Membership.ROLE_MEMBER); childUpdates.put(FamilyTrackDbRefsHelper.userMembershipRef(userUuid, groupUuid) + User.FIELD_STATUS_ID, Membership.USER_JOINED); mFirebaseDatabase.getReference() .updateChildren(childUpdates) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (callback != null) { callback.onAddUserToGroupCompleted(new FirebaseResult<String>(FirebaseResult.RESULT_OK)); } } }); } @Override public void updateUserLocation(@NonNull final String userUuid, @NonNull final Location location, @NonNull final UpdateUserLocationCallback callback) { //Timber.v("Started"); getUserByUuid(userUuid, new GetUserByUuidCallback() { @Override public void onGetUserByUuidCompleted(FirebaseResult<User> result) { // check if user exists User user = result.getData(); if (user == null) { callback.onUpdateUserLocationCompleted( new FirebaseResult<String>(FamilyTrackException.getInstance(mContext, FamilyTrackException.DB_USER_BY_UUID_NOT_FOUND))); return; } // now prepare data for updates // we should update user location in three nodes: // - /groups/<groupUuid>/members/<userUuid> - for active group only! // - /registered_users/<userUuid> // - /history/<userUuid>/<new location> Map<String, Object> childUpdates = new HashMap<>(); childUpdates.put(FamilyTrackDbRefsHelper.userRef(userUuid) + User.FIELD_LAST_KNOWN_LOCATION, location); if (user.getActiveMembership() != null) { childUpdates.put(FamilyTrackDbRefsHelper.userOfGroupRef( user.getActiveMembership().getGroupUuid(), userUuid) + User.FIELD_LAST_KNOWN_LOCATION, location); } String historyItemPath = FamilyTrackDbRefsHelper.userHistory(userUuid); DatabaseReference ref = getFirebaseConnection().getReference(historyItemPath); String historyItemKey = ref.push().getKey(); childUpdates.put(historyItemPath + "/" + historyItemKey, location); mFirebaseDatabase.getReference() .updateChildren(childUpdates) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (callback != null) { callback.onUpdateUserLocationCompleted( new FirebaseResult<String>(FirebaseResult.RESULT_OK)); } } }); } }); } @Override public void getUserTrack(@NonNull String userUuid, long periodStart, long periodEnd, final @NonNull GetUserTrackCallback callback) { String historyItemPath = FamilyTrackDbRefsHelper.userHistory(userUuid); DatabaseReference ref = getFirebaseConnection().getReference(historyItemPath); Query query = ref.orderByChild(Location.FIELD_TIMESTAMP).startAt(periodStart).endAt(periodEnd); query.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { List<Location> locations = new ArrayList<>(); if (dataSnapshot.getChildren() != null) { for (DataSnapshot snapshot : dataSnapshot.getChildren()) { locations.add(FirebaseUtil.getLocationFromSnapshot(snapshot)); } } callback.onGetUserTrackCompleted(new FirebaseResult<>(locations)); } @Override public void onCancelled(DatabaseError databaseError) { } }); } // -------------------------------------------------------------------------------------------- // // zones operations // // -------------------------------------------------------------------------------------------- @Override public void createZone(@NonNull String groupUuid, @NonNull Zone zone, CreateZoneCallback callback) { DatabaseReference ref = getFirebaseConnection() .getReference(FamilyTrackDbRefsHelper.zonesOfGroup(groupUuid)); DatabaseReference newRec = ref.push(); newRec.setValue(zone); if (callback != null) { callback.onCreateZoneCompleted(new FirebaseResult<>(newRec.getKey())); } } @Override public void updateZone(@NonNull String groupUuid, @NonNull Zone zone, UpdateZoneCallback callback) { DatabaseReference ref = getFirebaseConnection() .getReference(FamilyTrackDbRefsHelper.zoneOfGroup(groupUuid, zone.getUuid())); ref.setValue(zone); if (callback != null) { callback.onUpdateZoneCompleted(new FirebaseResult<>(zone.getUuid())); } } @Override public void removeZone(@NonNull String groupUuid, @NonNull String zoneUuid, final RemoveZoneCallback callback) { DatabaseReference ref = getFirebaseConnection() .getReference(FamilyTrackDbRefsHelper.zoneOfGroup(groupUuid, zoneUuid)); ref.removeValue(new DatabaseReference.CompletionListener() { @Override public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) { if (callback != null) { if (databaseError != null) { callback.onRemoveZoneCompleted(new FirebaseResult<String>(databaseError)); } else { callback.onRemoveZoneCompleted(new FirebaseResult<>(FirebaseResult.RESULT_OK)); } } } }); } @Override public void getSettingsByGroupUuid(@NonNull String groupUuid, @NonNull final GetSettingsByGroupUuidCallback callback) { DatabaseReference ref = getFirebaseConnection() .getReference(FamilyTrackDbRefsHelper.groupSettingsRef(groupUuid)); Query query = ref.orderByValue(); query.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { Settings s = Settings.getDefaultInstance(); if (dataSnapshot.getChildrenCount() > 0) { s = dataSnapshot.getValue(Settings.class); } callback.onGetSettingsByGroupUuidCompleted(new FirebaseResult<>(s)); } @Override public void onCancelled(DatabaseError databaseError) { } }); } @Override public void updateSettingsByGroupUuid(@NonNull String groupUuid, @NonNull Settings settings, UpdateSettingsByGroupUuidCallback callback) { DatabaseReference ref = getFirebaseConnection() .getReference(FamilyTrackDbRefsHelper.groupSettingsRef(groupUuid)); ref.setValue(settings); if (callback != null) { callback.onUpdateSettingsByGroupUuidCompleted(new FirebaseResult<>(FirebaseResult.RESULT_OK)); } } @Override public void deleteGeofenceEvent(@NonNull String userUuid, @NonNull String eventUuid, DeleteGeofenceEventsCallback callback) { DatabaseReference ref = getFirebaseConnection() .getReference(FamilyTrackDbRefsHelper.geofenceEventRef(userUuid, eventUuid)); ref.setValue(null); if (callback != null) { callback.onDeleteGeofenceEventsCompleted(new FirebaseResult<>(FirebaseResult.RESULT_OK)); } } @Override public void deleteGeofenceEvents(@NonNull String userUuid, DeleteGeofenceEventsCallback callback) { DatabaseReference ref = getFirebaseConnection() .getReference(FamilyTrackDbRefsHelper.geofenceEventsRef(userUuid)); ref.setValue(null); if (callback != null) { callback.onDeleteGeofenceEventsCompleted(new FirebaseResult<>(FirebaseResult.RESULT_OK)); } } // чтобы не забыть как это рабоотает // уведомление формируется для каждого пользователя группы в роли Admin // и записывается по адресу geofence_events/<groupAdminUuid>/<event> // каждый администратор получает уведомление об изменении прослушиваемого узла, читает эти данные, // формирует сообщение и удаляет их @Override public void createGeofenceEvent(@NonNull final String groupUuid, final GeofenceEvent geofenceEvent, final CreateGeofenceEventCallback callback) { getGroupByUuid(groupUuid, false, new GetGroupByUuidCallback() { @Override public void onGetGroupByUuidCompleted(FirebaseResult<Group> result) { if (result.getData() == null) { //Timber.v("Group with key ='" + groupUuid + "' not found"); if (callback != null) { callback.onCreateGeofenceEventCompleted(new FirebaseResult<>(FirebaseResult.RESULT_FAILED)); } return; } for (String key : result.getData().getMembers().keySet()) { User user = result.getData().getMembers().get(key); if (user.getActiveMembership() != null) { if (user.getActiveMembership().getStatusId() == Membership.USER_JOINED && user.getActiveMembership().getRoleId() == Membership.ROLE_ADMIN) { String path = FamilyTrackDbRefsHelper.geofenceEventsRef(user.getUserUuid()); String newKey = getFirebaseConnection().getReference(path).push().getKey(); geofenceEvent.setEventUuid(newKey); getFirebaseConnection().getReference(path + newKey).setValue(geofenceEvent); } } } if (callback != null) { callback.onCreateGeofenceEventCompleted(new FirebaseResult<>(FirebaseResult.RESULT_OK)); } } }); } @Override public void getGeofenceEventsByUserUuid(@NonNull String userUuid, final @NonNull GetGeofenceEventsByUserUuidCallback callback) { DatabaseReference ref = getFirebaseConnection() .getReference(FamilyTrackDbRefsHelper.geofenceEventsRef(userUuid)); Query query = ref.orderByKey(); query.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { List<GeofenceEvent> events = new ArrayList<>(); if (dataSnapshot.getChildren() != null) { for (DataSnapshot snapshot : dataSnapshot.getChildren()) { events.add(FirebaseUtil.getGeofenceEventFromSnapshot(snapshot)); } } callback.onGetGeofenceEventsByUserUuidCompleted(new FirebaseResult<>(events)); } @Override public void onCancelled(DatabaseError databaseError) { } }); } }
44,199
0.572108
0.571
925
45.806488
34.196606
149
false
false
0
0
0
0
0
0
0.472432
false
false
10
49286c3009eb00d1eb852e18a4e767f5b2f9ca51
19,877,108,712,409
fc25f30ba7c0ffa5537a396a3b80573c6ba5874d
/backend/src/main/java/com/ecommerce/application/IDealService.java
0d9ed00decad3c64173cbc83d81d5b5a7ecd4a70
[]
no_license
psS2mj/Web_PJT_GuaranTicket
https://github.com/psS2mj/Web_PJT_GuaranTicket
2c05fbf2219eb2836465e91feb79cbb86ca71ac6
ed0c022bc88ef5247fafdd80ae8d80ed5b89e62b
refs/heads/master
2023-01-21T12:14:28.845000
2020-10-12T08:38:45
2020-10-12T08:38:45
316,261,383
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ecommerce.application; import com.ecommerce.domain.Deal; import com.ecommerce.domain.DealDetail; import com.ecommerce.domain.DealList; import java.util.List; import org.springframework.transaction.annotation.Transactional; public interface IDealService { List<DealList> list(); DealDetail get(long did); @Transactional DealDetail create(Deal deal); List<DealList> getBySeller(long seller); DealDetail update(long did, long buyer); }
UTF-8
Java
453
java
IDealService.java
Java
[]
null
[]
package com.ecommerce.application; import com.ecommerce.domain.Deal; import com.ecommerce.domain.DealDetail; import com.ecommerce.domain.DealList; import java.util.List; import org.springframework.transaction.annotation.Transactional; public interface IDealService { List<DealList> list(); DealDetail get(long did); @Transactional DealDetail create(Deal deal); List<DealList> getBySeller(long seller); DealDetail update(long did, long buyer); }
453
0.80574
0.80574
17
25.705883
17.380735
64
false
false
0
0
0
0
0
0
1.058824
false
false
10
8877837fa4565640d33455d39cdae0972952c793
2,113,123,955,383
38f464461c50db8238b8a73994ce9ca8b0d189f3
/t-monitor/ms-device/src/main/java/com/viettel/msdevicemanage/service/mapper/DeviceCatMapper.java
fdaa130d36de30f1dcd34f6d0d767fcf940b4c54
[]
no_license
ngtoan194/ThingHub
https://github.com/ngtoan194/ThingHub
f00f6175b81d529c070b2519aa71d882553ab3d4
314b225d9f20e8446601580dfd1780685a7c8a02
refs/heads/master
2020-09-29T15:42:51.978000
2019-12-10T10:19:43
2019-12-10T10:19:43
227,064,813
0
0
null
false
2020-10-13T18:07:16
2019-12-10T08:19:19
2019-12-10T10:20:13
2020-10-13T18:07:14
35,425
0
0
8
Java
false
false
package com.viettel.msdevicemanage.service.mapper; import com.viettel.msdevicemanage.domain.DeviceCat; import com.viettel.msdevicemanage.service.dto.DeviceCatDTO; import org.mapstruct.Mapper; import org.mapstruct.Mapping; /** * Mapper for the entity {@link DeviceCat} and its DTO {@link DeviceCatDTO}. */ @Mapper(componentModel = "spring", uses = {PropListMapper.class}) public interface DeviceCatMapper extends EntityMapper<DeviceCatDTO, DeviceCat> { @Mapping(target = "devices", ignore = true) DeviceCat toEntity(DeviceCatDTO deviceCatDTO); default DeviceCat fromId(Long id) { if (id == null) { return null; } DeviceCat deviceCat = new DeviceCat(); deviceCat.setId(id); return deviceCat; } }
UTF-8
Java
769
java
DeviceCatMapper.java
Java
[]
null
[]
package com.viettel.msdevicemanage.service.mapper; import com.viettel.msdevicemanage.domain.DeviceCat; import com.viettel.msdevicemanage.service.dto.DeviceCatDTO; import org.mapstruct.Mapper; import org.mapstruct.Mapping; /** * Mapper for the entity {@link DeviceCat} and its DTO {@link DeviceCatDTO}. */ @Mapper(componentModel = "spring", uses = {PropListMapper.class}) public interface DeviceCatMapper extends EntityMapper<DeviceCatDTO, DeviceCat> { @Mapping(target = "devices", ignore = true) DeviceCat toEntity(DeviceCatDTO deviceCatDTO); default DeviceCat fromId(Long id) { if (id == null) { return null; } DeviceCat deviceCat = new DeviceCat(); deviceCat.setId(id); return deviceCat; } }
769
0.706112
0.706112
26
28.576923
25.158228
80
false
false
0
0
0
0
0
0
0.5
false
false
10
8eddfa006b842dbf2fadd4761f7685c5fc391a0d
14,388,140,468,397
7f3503a7916377ba5d5912ccfdb489dea571f9c1
/src/main/java/com/softserve/edu/servicecenter/application/OrderController.java
95dca21e7cba615e6c6fa27eacbbad6bb5829b0e
[]
no_license
khdimon/ServiceCenter
https://github.com/khdimon/ServiceCenter
dbdbcf1a1e1b7176fd4cee097918e2f3bc7a04af
3598dc5ef098fc7213d9c9790180254f9928ee52
refs/heads/master
2020-09-06T14:21:53.980000
2017-07-04T17:32:05
2017-07-04T17:32:05
94,419,817
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.softserve.edu.servicecenter.application; import com.softserve.edu.servicecenter.entity.Client; import com.softserve.edu.servicecenter.entity.Order; import com.softserve.edu.servicecenter.entity.Service; import com.softserve.edu.servicecenter.service.OrderServiceImpl; import com.softserve.edu.servicecenter.service.ServiceService; import java.util.List; import java.util.stream.Collectors; public class OrderController { public void printAllOrders() { OrderServiceImpl service = new OrderServiceImpl(); List<Order> orders = service.getAllOrders(); OrderView orderView = new OrderView(); orderView.printOrders(orders); } public void addOrder() { ClientController clientController = new ClientController(); Client client = clientController.getNewClient(); ServiceService serviceService = new ServiceService(); List<Service> services = serviceService.getAllService(); List<String> servicesStr = services.stream() .map((s) -> s.getId() + ". " + s.getName()) .collect(Collectors.toList()); Menu menu = new Menu("Выберите сервис:", servicesStr); menu.print(); int serviceId = menu.selectPoint(); } }
UTF-8
Java
1,270
java
OrderController.java
Java
[]
null
[]
package com.softserve.edu.servicecenter.application; import com.softserve.edu.servicecenter.entity.Client; import com.softserve.edu.servicecenter.entity.Order; import com.softserve.edu.servicecenter.entity.Service; import com.softserve.edu.servicecenter.service.OrderServiceImpl; import com.softserve.edu.servicecenter.service.ServiceService; import java.util.List; import java.util.stream.Collectors; public class OrderController { public void printAllOrders() { OrderServiceImpl service = new OrderServiceImpl(); List<Order> orders = service.getAllOrders(); OrderView orderView = new OrderView(); orderView.printOrders(orders); } public void addOrder() { ClientController clientController = new ClientController(); Client client = clientController.getNewClient(); ServiceService serviceService = new ServiceService(); List<Service> services = serviceService.getAllService(); List<String> servicesStr = services.stream() .map((s) -> s.getId() + ". " + s.getName()) .collect(Collectors.toList()); Menu menu = new Menu("Выберите сервис:", servicesStr); menu.print(); int serviceId = menu.selectPoint(); } }
1,270
0.699045
0.699045
34
35.941177
23.799334
67
false
false
0
0
0
0
0
0
0.617647
false
false
10
6a7df97a58083e9de2116a91c40d77a5938a33d2
21,560,735,852,458
029a264756059f8aa756b9a1e92d7d552deca05f
/ABoardGame/ABoardGame.java
4e7ec9695566b3b8ceafe27459e91fcb61529cac
[]
no_license
nickcorin/topcoder
https://github.com/nickcorin/topcoder
1db1db6dd8d656bbbdc21ef21a77f829d7f0fd6b
8f57e93923246357e226212171af3e00f4c81b88
refs/heads/master
2018-01-10T09:43:46.085000
2016-01-29T12:21:42
2016-01-29T12:21:42
50,441,453
0
2
null
null
null
null
null
null
null
null
null
null
null
null
null
public class ABoardGame{ public String whoWins(String[] board){ int currentLevel = 1; // Setting the current level. int N = board.length; // Calculating the length of the board. int levels = N/2; // Calculating the amount of levels. // Iterates for the amount of levels on the board. for(int i = 0 ; i < levels ; i++){ int startingPoint = (N/2)-currentLevel; // Starts the grid scan at the top left corner of the level. int aCount = 0; // The initial amount of A's. int bCount = 0; // The initial amount of B's. // Nested loop iterates through the current levels inner grid ( starting at the top left corner ). for(int j = 0 ; j < currentLevel*2 ; j++){ for(int k = 0 ; k < currentLevel*2 ; k++){ // Checking if the current block is the outer edge of the current levels grid. if( j == 0 || j == currentLevel*2-1 || k == 0 || k == currentLevel*2-1 ){ // Checking the current block for an 'A' or 'B'. if(board[startingPoint+j].charAt(startingPoint+k) == 'A'){ aCount++; } else if(board[startingPoint+j].charAt(startingPoint+k) == 'B') { bCount++; } } else { continue; // Continuing the loop if the current block is not on the outer edge of the current levels grid. } } } // Returns the winner, if there is a clear winner at the current level. if(aCount > bCount){ return "Alice"; } else if(bCount > aCount){ return "Bob"; } currentLevel++; // Increments the level. } return "Draw"; // Returns 'Draw' if there is no clear winner after scanning the entire grid. } }
UTF-8
Java
1,818
java
ABoardGame.java
Java
[ { "context": "\t\n\t\t\tif(aCount > bCount){\n return \"Alice\";\n\t\t\t} else if(bCount > aCount){\n ", "end": 1575, "score": 0.9991729259490967, "start": 1570, "tag": "NAME", "value": "Alice" }, { "context": "else if(bCount > aCount){\n return \"Bob\";\n\t\t\t}\n currentLevel++;\t\t// Increments", "end": 1636, "score": 0.9987695813179016, "start": 1633, "tag": "NAME", "value": "Bob" } ]
null
[]
public class ABoardGame{ public String whoWins(String[] board){ int currentLevel = 1; // Setting the current level. int N = board.length; // Calculating the length of the board. int levels = N/2; // Calculating the amount of levels. // Iterates for the amount of levels on the board. for(int i = 0 ; i < levels ; i++){ int startingPoint = (N/2)-currentLevel; // Starts the grid scan at the top left corner of the level. int aCount = 0; // The initial amount of A's. int bCount = 0; // The initial amount of B's. // Nested loop iterates through the current levels inner grid ( starting at the top left corner ). for(int j = 0 ; j < currentLevel*2 ; j++){ for(int k = 0 ; k < currentLevel*2 ; k++){ // Checking if the current block is the outer edge of the current levels grid. if( j == 0 || j == currentLevel*2-1 || k == 0 || k == currentLevel*2-1 ){ // Checking the current block for an 'A' or 'B'. if(board[startingPoint+j].charAt(startingPoint+k) == 'A'){ aCount++; } else if(board[startingPoint+j].charAt(startingPoint+k) == 'B') { bCount++; } } else { continue; // Continuing the loop if the current block is not on the outer edge of the current levels grid. } } } // Returns the winner, if there is a clear winner at the current level. if(aCount > bCount){ return "Alice"; } else if(bCount > aCount){ return "Bob"; } currentLevel++; // Increments the level. } return "Draw"; // Returns 'Draw' if there is no clear winner after scanning the entire grid. } }
1,818
0.552805
0.544004
49
36.122448
32.676292
113
false
false
0
0
0
0
0
0
3.673469
false
false
10
48aaaee93b64b8e72fb290402a150f2086675461
1,846,835,987,490
e531733d3d6013ed0d5e503c5c1a165331bef432
/entrance/Java代码/3.Object类与String类/Object/src/cn/itcast/stringbuffer/Demo1.java
e649ee1ef607fa370b0462195ce40d0923b785b4
[]
no_license
FuckingError/Introduction-To-Java
https://github.com/FuckingError/Introduction-To-Java
ee895a5795c86c48d8a58085ff069c5d7cb6b545
670feb88dd8aadcd617fcc1cf62e6da6524efa66
refs/heads/master
2020-04-03T21:03:45.470000
2018-10-31T13:40:49
2018-10-31T13:40:49
155,561,760
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.itcast.stringbuffer; /* StringBuffer() 字符缓冲区 存储字符的容器 实质为字符数组,长度默认为16,如果长度不够用,则变为原数组的一倍 String 长度不可改变 增加 append(boolean b) 可以添加任意类型的数据到容器中 insert(int offset,boolean b) 在指定位置插入字符串 删除 delete(int start,int end) 根据指定索引值删除对应的内容 deleteCharAt(int index) 删除一个字符 查看 indexOf(String str,int fromIndex) 查找索引值 capacity() 查看字符数组的长度 length() 查看储存字符的个数 charAt(int index) 查看指定索引值的字符 toString() 把字符缓冲类的内容转换成字符串 修改 replace(int start,int end,string str); reverse() 反转 setCharAt(int index,char ch) 把指定索引值的字符替换成指定的字符 substring(int start,int end) 截取 */ public class Demo1 { public static void main(String[] args) { StringBuffer sb = new StringBuffer(); sb.append("abc78981455878459558658"); /*添加的方法 sb.append(3.14f); */ /*插入的方法 * */ sb.insert(2, "周杰伦"); /*删除的方法 sb.delete(2, 5);//包头不包尾 */ /*删除一个字符 sb.deleteCharAt(2); */ /*替换 sb.replace(2, 5, "刘清"); */ /*反转 sb.reverse(); */ //sb.setCharAt(2, '刘');//替换单个字符 /* * 截取 字符串输出 * System.out.println(sb.substring(2,5)); */ /* * 查看索引值 int index = sb.indexOf("ab",0); System.out.println(index); */ /*查看字符数组长度 */ System.out.println("查看字符数组 的长度:"+sb.capacity()); //查看存储的字符个数 //System.out.println("查看存储的字符个数:"+sb.length()); /*查看指定索引值的字符 System.out.println(sb.charAt(2)); */ /*转换成字符串 System.out.println(sb.toString()); */ } }
GB18030
Java
2,032
java
Demo1.java
Java
[ { "context": "f);\n\t\t*/\n\t\t\n\t\t/*插入的方法\n\t\t * \n\t\t */\n\t\tsb.insert(2, \"周杰伦\");\n\t\t\n\t\t/*删除的方法\n\t\tsb.delete(2, 5);//包头不包尾\n\t\t*/\n\t\t", "end": 843, "score": 0.9998306035995483, "start": 840, "tag": "NAME", "value": "周杰伦" }, { "context": ");\n */\n \n\t\t/*替换\n\t\tsb.replace(2, 5, \"刘清\");\n\t\t*/\n\t\t\n\t\t/*反转\n\t\tsb.reverse();\n\t\t*/\n\t\t\n\t //s", "end": 976, "score": 0.9997976422309875, "start": 974, "tag": "NAME", "value": "刘清" }, { "context": "反转\n\t\tsb.reverse();\n\t\t*/\n\t\t\n\t //sb.setCharAt(2, '刘');//替换单个字符\n\t\t\n\t\t/*\n\t\t * 截取 字符串输出\n\t\t * System.out", "end": 1043, "score": 0.9997503757476807, "start": 1042, "tag": "NAME", "value": "刘" } ]
null
[]
package cn.itcast.stringbuffer; /* StringBuffer() 字符缓冲区 存储字符的容器 实质为字符数组,长度默认为16,如果长度不够用,则变为原数组的一倍 String 长度不可改变 增加 append(boolean b) 可以添加任意类型的数据到容器中 insert(int offset,boolean b) 在指定位置插入字符串 删除 delete(int start,int end) 根据指定索引值删除对应的内容 deleteCharAt(int index) 删除一个字符 查看 indexOf(String str,int fromIndex) 查找索引值 capacity() 查看字符数组的长度 length() 查看储存字符的个数 charAt(int index) 查看指定索引值的字符 toString() 把字符缓冲类的内容转换成字符串 修改 replace(int start,int end,string str); reverse() 反转 setCharAt(int index,char ch) 把指定索引值的字符替换成指定的字符 substring(int start,int end) 截取 */ public class Demo1 { public static void main(String[] args) { StringBuffer sb = new StringBuffer(); sb.append("abc78981455878459558658"); /*添加的方法 sb.append(3.14f); */ /*插入的方法 * */ sb.insert(2, "周杰伦"); /*删除的方法 sb.delete(2, 5);//包头不包尾 */ /*删除一个字符 sb.deleteCharAt(2); */ /*替换 sb.replace(2, 5, "刘清"); */ /*反转 sb.reverse(); */ //sb.setCharAt(2, '刘');//替换单个字符 /* * 截取 字符串输出 * System.out.println(sb.substring(2,5)); */ /* * 查看索引值 int index = sb.indexOf("ab",0); System.out.println(index); */ /*查看字符数组长度 */ System.out.println("查看字符数组 的长度:"+sb.capacity()); //查看存储的字符个数 //System.out.println("查看存储的字符个数:"+sb.length()); /*查看指定索引值的字符 System.out.println(sb.charAt(2)); */ /*转换成字符串 System.out.println(sb.toString()); */ } }
2,032
0.608254
0.583221
93
14.892473
15.223399
50
false
false
0
0
0
0
0
0
1.548387
false
false
10
17b2f6583103e149ab0f46d1d797280c85bd75a1
25,469,156,098,780
84fbc1625824ba75a02d1777116fe300456842e5
/Engagement_Challenges/Engagement_4/powerbroker_2/source/org/digitalapex/powerbroker/stage/PeriodOverseerBuilder.java
c23c17fd30b2c56c90eb94d45b70f98df7452ee6
[]
no_license
unshorn-forks/STAC
https://github.com/unshorn-forks/STAC
bd41dee06c3ab124177476dcb14a7652c3ddd7b3
6919d7cc84dbe050cef29ccced15676f24bb96de
refs/heads/master
2023-03-18T06:37:11.922000
2018-04-18T17:01:03
2018-04-18T17:01:03
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.digitalapex.powerbroker.stage; import org.digitalapex.powerbroker.CommodityGoBetween; import org.digitalapex.talkers.TalkersIdentity; public class PeriodOverseerBuilder { private CommodityGoBetween commodityGoBetween; private TalkersIdentity identity; public PeriodOverseerBuilder setCommodityGoBetween(CommodityGoBetween commodityGoBetween) { this.commodityGoBetween = commodityGoBetween; return this; } public PeriodOverseerBuilder defineIdentity(TalkersIdentity identity) { this.identity = identity; return this; } public PeriodOverseer generatePeriodOverseer() { return new PeriodOverseer(identity, commodityGoBetween); } }
UTF-8
Java
716
java
PeriodOverseerBuilder.java
Java
[]
null
[]
package org.digitalapex.powerbroker.stage; import org.digitalapex.powerbroker.CommodityGoBetween; import org.digitalapex.talkers.TalkersIdentity; public class PeriodOverseerBuilder { private CommodityGoBetween commodityGoBetween; private TalkersIdentity identity; public PeriodOverseerBuilder setCommodityGoBetween(CommodityGoBetween commodityGoBetween) { this.commodityGoBetween = commodityGoBetween; return this; } public PeriodOverseerBuilder defineIdentity(TalkersIdentity identity) { this.identity = identity; return this; } public PeriodOverseer generatePeriodOverseer() { return new PeriodOverseer(identity, commodityGoBetween); } }
716
0.77095
0.77095
23
30.173914
27.455343
95
false
false
0
0
0
0
0
0
0.478261
false
false
10
b48b4efdc1b9758a5773d31b93e9b3868273071e
953,482,777,325
ba53601e5014c9c8d4a20ae4e4078a3b60dac268
/speeddating/speeddating-ui/src/main/java/de/swprojekt/speeddating/ui/event/AudioPlayer.java
e6808506442cc4985529967cf2ef37e936725e91
[]
no_license
nliedmey/hs_os_softwareprojekt
https://github.com/nliedmey/hs_os_softwareprojekt
2f453476444e4420346d9cc8fdec8ba58429bc4b
62487effaf344da16cb22370378c76801aff8de3
refs/heads/master
2023-01-13T22:51:45.595000
2020-01-16T11:59:12
2020-01-16T11:59:12
312,782,700
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package de.swprojekt.speeddating.ui.event; import com.vaadin.flow.component.Component; import com.vaadin.flow.component.Tag; /* * Zusaetzliche selbst erstellte Vaadin-Komponente zur Audioausgabe des Signaltons */ @Tag("audio") //Klasse Audio wird genutzt public class AudioPlayer extends Component { public AudioPlayer(){ } @SuppressWarnings("deprecation") public void play() { System.out.println("Ton muesste kommen"); getElement().callFunction("play"); //Ton abspielen } public void setSource(String path){ getElement().setProperty("src",path); //Quelle des Tons setzen } }
UTF-8
Java
652
java
AudioPlayer.java
Java
[]
null
[]
package de.swprojekt.speeddating.ui.event; import com.vaadin.flow.component.Component; import com.vaadin.flow.component.Tag; /* * Zusaetzliche selbst erstellte Vaadin-Komponente zur Audioausgabe des Signaltons */ @Tag("audio") //Klasse Audio wird genutzt public class AudioPlayer extends Component { public AudioPlayer(){ } @SuppressWarnings("deprecation") public void play() { System.out.println("Ton muesste kommen"); getElement().callFunction("play"); //Ton abspielen } public void setSource(String path){ getElement().setProperty("src",path); //Quelle des Tons setzen } }
652
0.685583
0.685583
23
26.434782
23.658487
82
false
false
0
0
0
0
0
0
0.521739
false
false
10
bfe99e6102493b3d8ca3a11d45802de495c7a822
9,887,014,752,285
9ade262217cbce864429ca85251b1d0009d1ac48
/LicenseKeyFormatting.java
e63972662a9b086a80b783d23539f4d71737aa1e
[]
no_license
Neo-Leo/Strings
https://github.com/Neo-Leo/Strings
a58af1393c34fa9a2517e4ee0f9e21cbfee4603b
57950c39d1cd527e2092bae92757e7f16673bc62
refs/heads/master
2021-01-11T02:30:38.368000
2018-01-04T04:55:49
2018-01-04T04:55:49
70,956,777
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Nilanshu Sharma * https://leetcode.com/problems/license-key-formatting/ */ public class Solution { public String licenseKeyFormatting(String S, int K) { if(S == null || S.length() == 0 || K == 0) return S; int i = S.length()-1, tempK=K; StringBuilder sb = new StringBuilder(); while(i>=0){ char ch = S.charAt(i--); if(!Character.isDigit(ch) && (ch != '-') && Character.isLowerCase(ch)){ ch = Character.toUpperCase(ch); } if(ch != '-') { sb.append(ch); tempK--; } if(tempK == 0){ sb.append("-"); tempK = K; } } int n = sb.length(); if(n == 0) return ""; if(sb.charAt(n-1) == '-') sb.deleteCharAt(n-1); sb.reverse(); return new String(sb); } }
UTF-8
Java
938
java
LicenseKeyFormatting.java
Java
[ { "context": "/*\r\n * Nilanshu Sharma\r\n * https://leetcode.com/problems/license-key-for", "end": 22, "score": 0.9998799562454224, "start": 7, "tag": "NAME", "value": "Nilanshu Sharma" } ]
null
[]
/* * <NAME> * https://leetcode.com/problems/license-key-formatting/ */ public class Solution { public String licenseKeyFormatting(String S, int K) { if(S == null || S.length() == 0 || K == 0) return S; int i = S.length()-1, tempK=K; StringBuilder sb = new StringBuilder(); while(i>=0){ char ch = S.charAt(i--); if(!Character.isDigit(ch) && (ch != '-') && Character.isLowerCase(ch)){ ch = Character.toUpperCase(ch); } if(ch != '-') { sb.append(ch); tempK--; } if(tempK == 0){ sb.append("-"); tempK = K; } } int n = sb.length(); if(n == 0) return ""; if(sb.charAt(n-1) == '-') sb.deleteCharAt(n-1); sb.reverse(); return new String(sb); } }
929
0.425373
0.416844
31
28.32258
19.704899
83
false
false
0
0
0
0
0
0
0.645161
false
false
10
f0ccd9c0c911f431870fe7d965cbebcbdc0c1a03
21,199,958,606,171
1b9706a3b1ddd17e9a062e050312747137011b0c
/src/nl/peterbjornx/intelme/model/parts/code/CPDHeader.java
eeee6198e83f38ca286eb576f4a0ae15fbe75175
[ "MIT" ]
permissive
peterbjornx/meimagetool
https://github.com/peterbjornx/meimagetool
cc253d4a18e0904fc12fdcf8a92c2900cab63798
ddece2a2a699f8527102da079a184502a02c8d87
refs/heads/master
2020-04-26T11:15:38.075000
2019-03-03T00:31:37
2019-03-03T00:31:37
173,510,548
36
4
null
null
null
null
null
null
null
null
null
null
null
null
null
package nl.peterbjornx.intelme.model.parts.code; import nl.peterbjornx.intelme.io.ByteBufTools; import java.nio.ByteBuffer; public class CPDHeader { private String marker; private int entries; private int HeaderVersion; private int EntryVersion; private int HeaderLength; private int HeaderChecksum; private String PartitionName; public CPDHeader(ByteBuffer buf) { marker = ByteBufTools.readCString(buf,4); entries = buf.getInt(); HeaderVersion = buf.get() & 0xFF; EntryVersion = buf.get() & 0xFF; HeaderLength = buf.get() & 0xFF; HeaderChecksum = buf.get() & 0xFF; PartitionName = ByteBufTools.readCString(buf,4); } public String getMarker() { return marker; } public int getEntries() { return entries; } public int getHeaderVersion() { return HeaderVersion; } public int getEntryVersion() { return EntryVersion; } public int getHeaderLength() { return HeaderLength; } public int getHeaderChecksum() { return HeaderChecksum; } public String getPartitionName() { return PartitionName; } }
UTF-8
Java
1,204
java
CPDHeader.java
Java
[]
null
[]
package nl.peterbjornx.intelme.model.parts.code; import nl.peterbjornx.intelme.io.ByteBufTools; import java.nio.ByteBuffer; public class CPDHeader { private String marker; private int entries; private int HeaderVersion; private int EntryVersion; private int HeaderLength; private int HeaderChecksum; private String PartitionName; public CPDHeader(ByteBuffer buf) { marker = ByteBufTools.readCString(buf,4); entries = buf.getInt(); HeaderVersion = buf.get() & 0xFF; EntryVersion = buf.get() & 0xFF; HeaderLength = buf.get() & 0xFF; HeaderChecksum = buf.get() & 0xFF; PartitionName = ByteBufTools.readCString(buf,4); } public String getMarker() { return marker; } public int getEntries() { return entries; } public int getHeaderVersion() { return HeaderVersion; } public int getEntryVersion() { return EntryVersion; } public int getHeaderLength() { return HeaderLength; } public int getHeaderChecksum() { return HeaderChecksum; } public String getPartitionName() { return PartitionName; } }
1,204
0.640365
0.635382
53
21.716982
16.621624
56
false
false
0
0
0
0
0
0
0.490566
false
false
10
10cc3285c6df3a337d965b9f130fc9ab91aa8c68
27,006,754,386,733
8e55003607bb79923e4ad1e3a1f667831d46ac4e
/src/main/java/robot/subsystems/drivetrain/commands/VelocityDrive.java
76df5f2848620cf4d97ca8bea9f647a701bfee07
[]
no_license
orel-david/trajectory_follower
https://github.com/orel-david/trajectory_follower
28b03f18422c5dd4465354c684003589642526c5
6c3635444caef0c2dc968314918107e9a6090b54
refs/heads/master
2020-08-29T00:51:36.657000
2019-11-22T18:15:48
2019-11-22T18:15:48
217,871,070
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package robot.subsystems.drivetrain.commands; import com.stormbots.MiniPID; import edu.wpi.first.wpilibj.command.Command; import robot.Constants; import robot.Robot; import edu.wpi.first.networktables.NetworkTableEntry; public class VelocityDrive extends Command { private double angularVelocity; private double linearVelocity; private double angularOutput; private NetworkTableEntry linearVelocityEntry = Robot.velocityTable.getEntry("distance"); private NetworkTableEntry angularVelocityEntry = Robot.velocityTable.getEntry("angle"); private MiniPID angular = new MiniPID(Constants.Drivetrain.angularPID[0], Constants.Drivetrain.angularPID[1], Constants.Drivetrain.angularPID[2]); public VelocityDrive(double angularVelocity, double linearVelocity) { requires(Robot.m_drivetrain); this.angularVelocity = angularVelocity; this.linearVelocity = linearVelocity; } @Override protected void initialize() { } @Override protected void execute() { angularVelocityEntry.setDouble(Robot.m_drivetrain.getAngularVelocity()); linearVelocityEntry.setDouble((Robot.m_drivetrain.getLeftVelocity()+Robot.m_drivetrain.getRightVelocity())/2); angularOutput = angular.getOutput(Robot.m_drivetrain.getAngularVelocity(), angularVelocity); Robot.m_drivetrain.setArcadeVelocities(linearVelocity,angularVelocity + angularOutput); } @Override protected boolean isFinished() { return false; } @Override protected void interrupted() { } @Override protected void end() { } }
UTF-8
Java
1,618
java
VelocityDrive.java
Java
[]
null
[]
package robot.subsystems.drivetrain.commands; import com.stormbots.MiniPID; import edu.wpi.first.wpilibj.command.Command; import robot.Constants; import robot.Robot; import edu.wpi.first.networktables.NetworkTableEntry; public class VelocityDrive extends Command { private double angularVelocity; private double linearVelocity; private double angularOutput; private NetworkTableEntry linearVelocityEntry = Robot.velocityTable.getEntry("distance"); private NetworkTableEntry angularVelocityEntry = Robot.velocityTable.getEntry("angle"); private MiniPID angular = new MiniPID(Constants.Drivetrain.angularPID[0], Constants.Drivetrain.angularPID[1], Constants.Drivetrain.angularPID[2]); public VelocityDrive(double angularVelocity, double linearVelocity) { requires(Robot.m_drivetrain); this.angularVelocity = angularVelocity; this.linearVelocity = linearVelocity; } @Override protected void initialize() { } @Override protected void execute() { angularVelocityEntry.setDouble(Robot.m_drivetrain.getAngularVelocity()); linearVelocityEntry.setDouble((Robot.m_drivetrain.getLeftVelocity()+Robot.m_drivetrain.getRightVelocity())/2); angularOutput = angular.getOutput(Robot.m_drivetrain.getAngularVelocity(), angularVelocity); Robot.m_drivetrain.setArcadeVelocities(linearVelocity,angularVelocity + angularOutput); } @Override protected boolean isFinished() { return false; } @Override protected void interrupted() { } @Override protected void end() { } }
1,618
0.74042
0.737948
53
29.528301
34.763134
150
false
false
0
0
0
0
0
0
0.471698
false
false
10
666879286979809e213c4e9485d14932eb7614a8
27,006,754,388,271
c6520185cf09c50642b4a288e4c6b44747bef186
/page/src/main/java/org/cs/mgr/rmw/ctl/RmwUserInfoCtl.java
1f9b1d9743c43a5c335b86b19efecb4da9d91a6b
[]
no_license
Gsk2019/rmw
https://github.com/Gsk2019/rmw
ee3fddeed3a044513baedfee14c5ad9ad75033d9
b5680a6f8574537d4ab0e9d674c24b82656b847e
refs/heads/master
2022-12-02T05:14:10.195000
2019-09-19T07:59:08
2019-09-19T07:59:08
194,377,900
0
0
null
false
2022-11-24T05:57:13
2019-06-29T07:32:15
2019-09-19T07:59:10
2022-11-24T05:57:10
15,604
0
0
10
JavaScript
false
false
package org.cs.mgr.rmw.ctl; import org.apache.log4j.Logger; import org.cs.core.ctl.BaseCtl; import org.cs.rmw.model.RmwUserInfo; import org.cs.rmw.service.IRmwUserInfoService; import org.cs.util.DateUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.cs.util.Pager; import org.cs.util.StringUtil; import com.alibaba.fastjson.JSONObject; @Controller @RequestMapping("/rmwUserInfoCtl") public class RmwUserInfoCtl extends BaseCtl { private Logger log = Logger.getLogger(RmwUserInfoCtl.class); @Autowired private IRmwUserInfoService rmwUserInfoService; @RequestMapping("list") public String list(ModelMap mm, @RequestParam(required=false)String menuCode){ mm.put(MENU_CODE, menuCode); return "bis/rmwuserinfo/list"; } @RequestMapping(value="list2", method = RequestMethod.GET, produces="application/json;charset=UTF-8") @ResponseBody public String list2(int page, int pageSize){ // Pager pager = this.rmwUserInfoService.getRmwUserInfos(new Pager(page, pageSize)); JSONObject json = new JSONObject(); // json.put("rows", pager.getResults()); // json.put("total", pager.getTotal()); return JSONObject.toJSONString(json, features); } @RequestMapping("transfer") public String transfer(String id, String action, ModelMap mm){ RmwUserInfo rmwUserInfo = null; if(StringUtil.isNotBlank(id)){ rmwUserInfo = this.rmwUserInfoService.findById(id.trim()); mm.put("rmwUserInfo", rmwUserInfo); } return "bis/rmwUserInfo" + action; } @RequestMapping(value="add", method = RequestMethod.POST) @ResponseBody public String add(RmwUserInfo rmwUserInfo){ if(rmwUserInfo != null ){ this.rmwUserInfoService.add(rmwUserInfo); } return AJAX_SUCCESS; } @RequestMapping("del") @ResponseBody public String del(String id){ if(StringUtil.isNotBlank(id)){ this.rmwUserInfoService.deleteById(id); } return AJAX_SUCCESS; } }
UTF-8
Java
2,253
java
RmwUserInfoCtl.java
Java
[]
null
[]
package org.cs.mgr.rmw.ctl; import org.apache.log4j.Logger; import org.cs.core.ctl.BaseCtl; import org.cs.rmw.model.RmwUserInfo; import org.cs.rmw.service.IRmwUserInfoService; import org.cs.util.DateUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.cs.util.Pager; import org.cs.util.StringUtil; import com.alibaba.fastjson.JSONObject; @Controller @RequestMapping("/rmwUserInfoCtl") public class RmwUserInfoCtl extends BaseCtl { private Logger log = Logger.getLogger(RmwUserInfoCtl.class); @Autowired private IRmwUserInfoService rmwUserInfoService; @RequestMapping("list") public String list(ModelMap mm, @RequestParam(required=false)String menuCode){ mm.put(MENU_CODE, menuCode); return "bis/rmwuserinfo/list"; } @RequestMapping(value="list2", method = RequestMethod.GET, produces="application/json;charset=UTF-8") @ResponseBody public String list2(int page, int pageSize){ // Pager pager = this.rmwUserInfoService.getRmwUserInfos(new Pager(page, pageSize)); JSONObject json = new JSONObject(); // json.put("rows", pager.getResults()); // json.put("total", pager.getTotal()); return JSONObject.toJSONString(json, features); } @RequestMapping("transfer") public String transfer(String id, String action, ModelMap mm){ RmwUserInfo rmwUserInfo = null; if(StringUtil.isNotBlank(id)){ rmwUserInfo = this.rmwUserInfoService.findById(id.trim()); mm.put("rmwUserInfo", rmwUserInfo); } return "bis/rmwUserInfo" + action; } @RequestMapping(value="add", method = RequestMethod.POST) @ResponseBody public String add(RmwUserInfo rmwUserInfo){ if(rmwUserInfo != null ){ this.rmwUserInfoService.add(rmwUserInfo); } return AJAX_SUCCESS; } @RequestMapping("del") @ResponseBody public String del(String id){ if(StringUtil.isNotBlank(id)){ this.rmwUserInfoService.deleteById(id); } return AJAX_SUCCESS; } }
2,253
0.765646
0.76387
80
27.15
23.860062
102
false
false
0
0
0
0
0
0
1.6125
false
false
10
24ff3a753b1e06d4ee826bde52cbc4ca1384bbc5
22,548,578,356,292
6238696ed551c995ad0735554d96f5a99f88f238
/src/main/java/demo/designpattern/createrpattern/PersonDirector.java
fa48fd77e83bcdf7b7b62f51d868c894ab545898
[]
no_license
ostrichevil/test
https://github.com/ostrichevil/test
70c018858bd14a1fb170b9cfaed71a3b69b8a3e1
f59fcf3595a36b0402ba08fd2029523cb2ddc79d
refs/heads/master
2021-04-27T00:03:11.766000
2018-05-10T07:16:23
2018-05-10T07:16:23
123,659,972
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package demo.designpattern.createrpattern; public class PersonDirector { public Person director(PersonBuilder personBuilder) { personBuilder.buildHead(); personBuilder.buildBody(); personBuilder.buildFoot(); return personBuilder.buildPerson(); } }
UTF-8
Java
290
java
PersonDirector.java
Java
[]
null
[]
package demo.designpattern.createrpattern; public class PersonDirector { public Person director(PersonBuilder personBuilder) { personBuilder.buildHead(); personBuilder.buildBody(); personBuilder.buildFoot(); return personBuilder.buildPerson(); } }
290
0.706897
0.706897
11
25.363636
19.354458
57
false
false
0
0
0
0
0
0
0.454545
false
false
10
d82758c23a27dfc5e9de7e555f6a56bfa48424bf
20,736,102,137,514
f3114a4e43dec88b5d5722b79d32a7da6d02e6e7
/ht-services/src/main/java/pl/touk/humantask/dao/BasicDao.java
f3c42037c5b2e45ed09609f1b357918e9811f0a0
[]
no_license
TouK/wsht
https://github.com/TouK/wsht
a592110a69188cc9d399030afd080143c305aaed
4d9ba5b8c5bf94576426b9d471f9a21ed684c889
refs/heads/master
2021-01-23T17:32:08.991000
2009-10-07T14:08:53
2009-10-07T14:08:53
330,160
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright (C) 2009 TouK sp. z o.o. s.k.a. * All rights reserved */ package pl.touk.humantask.dao; import java.io.Serializable; import pl.touk.humantask.model.Base; /** * Basic DAO operations for domain objects extending {@link Base}. * @author Witek Wołejszo */ public interface BasicDao<T extends Base, ID extends Serializable> { /** * Retrieves domain object from persistent store. * @param id Identifier of the object requested * @return requested domain object */ T fetch(ID id); /** * Saves domain object in persistent store. * @param entity Domain object to be updated */ void update(T entity); /** * Creates domain object in persistent store. * @param entity Domain object to be created */ void create(T entity); }
UTF-8
Java
816
java
BasicDao.java
Java
[ { "context": " domain objects extending {@link Base}.\n * @author Witek Wołejszo\n */\npublic interface BasicDao<T extends Base, ID ", "end": 272, "score": 0.9998824000358582, "start": 258, "tag": "NAME", "value": "Witek Wołejszo" } ]
null
[]
/* * Copyright (C) 2009 TouK sp. z o.o. s.k.a. * All rights reserved */ package pl.touk.humantask.dao; import java.io.Serializable; import pl.touk.humantask.model.Base; /** * Basic DAO operations for domain objects extending {@link Base}. * @author <NAME> */ public interface BasicDao<T extends Base, ID extends Serializable> { /** * Retrieves domain object from persistent store. * @param id Identifier of the object requested * @return requested domain object */ T fetch(ID id); /** * Saves domain object in persistent store. * @param entity Domain object to be updated */ void update(T entity); /** * Creates domain object in persistent store. * @param entity Domain object to be created */ void create(T entity); }
807
0.655215
0.650307
37
21.027027
21.28124
68
false
false
0
0
0
0
0
0
0.189189
false
false
10
31e1a6d4a6fb014501e31a76c449dc2bb3ada5bf
29,308,856,862,270
19f7e40c448029530d191a262e5215571382bf9f
/decompiled/instagram/sources/p000X/AVF.java
2a86b7cbe8d60dc6ede685ba6f1c217c6356a74c
[]
no_license
stanvanrooy/decompiled-instagram
https://github.com/stanvanrooy/decompiled-instagram
c1fb553c52e98fd82784a3a8a17abab43b0f52eb
3091a40af7accf6c0a80b9dda608471d503c4d78
refs/heads/master
2022-12-07T22:31:43.155000
2020-08-26T03:42:04
2020-08-26T03:42:04
283,347,288
18
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package p000X; import java.util.HashMap; import java.util.Map; /* renamed from: X.AVF */ public final class AVF { public String A00; public final Map A01; public AVF(String str, Map map) { boolean z; this.A00 = str; HashMap hashMap = new HashMap(); if (map != null) { for (Map.Entry entry : map.entrySet()) { String str2 = (String) entry.getValue(); if (str2 != null) { z = false; if (str2.equalsIgnoreCase("false")) { hashMap.put(entry.getKey(), Boolean.valueOf(z)); } } z = true; hashMap.put(entry.getKey(), Boolean.valueOf(z)); } } this.A01 = new B34(hashMap); } }
UTF-8
Java
823
java
AVF.java
Java
[]
null
[]
package p000X; import java.util.HashMap; import java.util.Map; /* renamed from: X.AVF */ public final class AVF { public String A00; public final Map A01; public AVF(String str, Map map) { boolean z; this.A00 = str; HashMap hashMap = new HashMap(); if (map != null) { for (Map.Entry entry : map.entrySet()) { String str2 = (String) entry.getValue(); if (str2 != null) { z = false; if (str2.equalsIgnoreCase("false")) { hashMap.put(entry.getKey(), Boolean.valueOf(z)); } } z = true; hashMap.put(entry.getKey(), Boolean.valueOf(z)); } } this.A01 = new B34(hashMap); } }
823
0.470231
0.45079
30
26.433332
18.73443
72
false
false
0
0
0
0
0
0
0.566667
false
false
10
c926640efa89b4a1157ab83bd0a23047588de234
13,477,607,420,353
a38a36ed87f15a4d8f9502cb63ec6c08df832e84
/src/main/java/normal/cat1/cat10/cat108/p1089/v1/Solution.java
cfc11b6a65da0b336ac50702b993e6609791b369
[ "LicenseRef-scancode-unknown-license-reference", "ICU" ]
permissive
kun368/LeetCodeKt
https://github.com/kun368/LeetCodeKt
1c3e88f448c5bfa4dd266b63d0d3f804df1bc6f3
50496e9eed7eb728c513078f117a4eb1553895b4
refs/heads/master
2023-08-31T04:41:18.408000
2023-08-26T09:39:20
2023-08-26T09:39:20
176,044,829
4
1
NOASSERTION
false
2022-11-05T12:32:56
2019-03-17T01:55:40
2022-10-01T14:34:36
2022-11-05T12:32:55
498
1
0
0
Java
false
false
package normal.cat1.cat10.cat108.p1089.v1; import java.util.Arrays; class Solution { public void duplicateZeros(int[] arr) { for (int i = 0; i < arr.length - 1; ++i) { if (arr[i] != 0) continue; for (int j = arr.length - 1; j > i; --j) { arr[j] = arr[j - 1]; } i += 1; } } public static void main(String[] args) { int[] ints = {1, 0, 2, 3, 0, 4, 5, 0}; new Solution().duplicateZeros(ints); System.out.println(Arrays.toString(ints)); ints = new int[]{1, 2, 3}; new Solution().duplicateZeros(ints); System.out.println(Arrays.toString(ints)); } }
UTF-8
Java
691
java
Solution.java
Java
[]
null
[]
package normal.cat1.cat10.cat108.p1089.v1; import java.util.Arrays; class Solution { public void duplicateZeros(int[] arr) { for (int i = 0; i < arr.length - 1; ++i) { if (arr[i] != 0) continue; for (int j = arr.length - 1; j > i; --j) { arr[j] = arr[j - 1]; } i += 1; } } public static void main(String[] args) { int[] ints = {1, 0, 2, 3, 0, 4, 5, 0}; new Solution().duplicateZeros(ints); System.out.println(Arrays.toString(ints)); ints = new int[]{1, 2, 3}; new Solution().duplicateZeros(ints); System.out.println(Arrays.toString(ints)); } }
691
0.503618
0.463097
25
26.68
19.5422
54
false
false
0
0
0
0
0
0
0.96
false
false
10
59f6392043828c4ffd0c50a710179e804217c974
14,826,227,140,808
3fe0743818467cc44f7b1d473f10608737e25d13
/JCudnnJava/src/main/java/jcuda/jcudnn/cudnnBackendDescriptorType.java
b0a705196cdd49f62476126b9ea7928a43744eb5
[ "MIT" ]
permissive
jcuda/jcudnn
https://github.com/jcuda/jcudnn
5c06bff914d57d75ff3702b7f168e2237fc36f72
913bb617522526017c0bab7d610a758bb7bd7264
refs/heads/master
2023-07-27T07:09:22.816000
2023-06-23T17:25:53
2023-06-23T17:25:53
43,024,293
28
10
MIT
false
2022-07-09T13:17:26
2015-09-23T20:13:32
2022-06-24T10:28:26
2022-07-09T13:03:47
296
27
7
0
C++
false
false
/* * JCudnn - Java bindings for cuDNN, the NVIDIA CUDA * Deep Neural Network library, to be used with JCuda * * Copyright (c) 2015-2018 Marco Hutter - http://www.jcuda.org * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package jcuda.jcudnn; public class cudnnBackendDescriptorType { public static final int CUDNN_BACKEND_POINTWISE_DESCRIPTOR = 0; public static final int CUDNN_BACKEND_CONVOLUTION_DESCRIPTOR = 1; public static final int CUDNN_BACKEND_ENGINE_DESCRIPTOR = 2; public static final int CUDNN_BACKEND_ENGINECFG_DESCRIPTOR = 3; public static final int CUDNN_BACKEND_ENGINEHEUR_DESCRIPTOR = 4; public static final int CUDNN_BACKEND_EXECUTION_PLAN_DESCRIPTOR = 5; public static final int CUDNN_BACKEND_INTERMEDIATE_INFO_DESCRIPTOR = 6; public static final int CUDNN_BACKEND_KNOB_CHOICE_DESCRIPTOR = 7; public static final int CUDNN_BACKEND_KNOB_INFO_DESCRIPTOR = 8; public static final int CUDNN_BACKEND_LAYOUT_INFO_DESCRIPTOR = 9; public static final int CUDNN_BACKEND_OPERATION_CONVOLUTION_FORWARD_DESCRIPTOR = 10; public static final int CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_FILTER_DESCRIPTOR = 11; public static final int CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_DATA_DESCRIPTOR = 12; public static final int CUDNN_BACKEND_OPERATION_POINTWISE_DESCRIPTOR = 13; public static final int CUDNN_BACKEND_OPERATION_GEN_STATS_DESCRIPTOR = 14; public static final int CUDNN_BACKEND_OPERATIONGRAPH_DESCRIPTOR = 15; public static final int CUDNN_BACKEND_VARIANT_PACK_DESCRIPTOR = 16; public static final int CUDNN_BACKEND_TENSOR_DESCRIPTOR = 17; public static final int CUDNN_BACKEND_MATMUL_DESCRIPTOR = 18; public static final int CUDNN_BACKEND_OPERATION_MATMUL_DESCRIPTOR = 19; public static final int CUDNN_BACKEND_OPERATION_BN_FINALIZE_STATISTICS_DESCRIPTOR = 20; public static final int CUDNN_BACKEND_REDUCTION_DESCRIPTOR = 21; public static final int CUDNN_BACKEND_OPERATION_REDUCTION_DESCRIPTOR = 22; public static final int CUDNN_BACKEND_OPERATION_BN_BWD_WEIGHTS_DESCRIPTOR = 23; public static final int CUDNN_BACKEND_RESAMPLE_DESCRIPTOR = 24; public static final int CUDNN_BACKEND_OPERATION_RESAMPLE_FWD_DESCRIPTOR = 25; public static final int CUDNN_BACKEND_OPERATION_RESAMPLE_BWD_DESCRIPTOR = 26; public static final int CUDNN_BACKEND_OPERATION_CONCAT_DESCRIPTOR = 27; public static final int CUDNN_BACKEND_OPERATION_SIGNAL_DESCRIPTOR = 28; public static final int CUDNN_BACKEND_OPERATION_NORM_FORWARD_DESCRIPTOR = 29; public static final int CUDNN_BACKEND_OPERATION_NORM_BACKWARD_DESCRIPTOR = 30; public static final int CUDNN_BACKEND_OPERATION_RESHAPE_DESCRIPTOR = 31; public static final int CUDNN_BACKEND_RNG_DESCRIPTOR = 32; public static final int CUDNN_BACKEND_OPERATION_RNG_DESCRIPTOR = 33; /** * Private constructor to prevent instantiation */ private cudnnBackendDescriptorType() { // Private constructor to prevent instantiation } /** * Returns a string representation of the given constant * * @return A string representation of the given constant */ public static String stringFor(int n) { switch (n) { case CUDNN_BACKEND_POINTWISE_DESCRIPTOR: return "CUDNN_BACKEND_POINTWISE_DESCRIPTOR"; case CUDNN_BACKEND_CONVOLUTION_DESCRIPTOR: return "CUDNN_BACKEND_CONVOLUTION_DESCRIPTOR"; case CUDNN_BACKEND_ENGINE_DESCRIPTOR: return "CUDNN_BACKEND_ENGINE_DESCRIPTOR"; case CUDNN_BACKEND_ENGINECFG_DESCRIPTOR: return "CUDNN_BACKEND_ENGINECFG_DESCRIPTOR"; case CUDNN_BACKEND_ENGINEHEUR_DESCRIPTOR: return "CUDNN_BACKEND_ENGINEHEUR_DESCRIPTOR"; case CUDNN_BACKEND_EXECUTION_PLAN_DESCRIPTOR: return "CUDNN_BACKEND_EXECUTION_PLAN_DESCRIPTOR"; case CUDNN_BACKEND_INTERMEDIATE_INFO_DESCRIPTOR: return "CUDNN_BACKEND_INTERMEDIATE_INFO_DESCRIPTOR"; case CUDNN_BACKEND_KNOB_CHOICE_DESCRIPTOR: return "CUDNN_BACKEND_KNOB_CHOICE_DESCRIPTOR"; case CUDNN_BACKEND_KNOB_INFO_DESCRIPTOR: return "CUDNN_BACKEND_KNOB_INFO_DESCRIPTOR"; case CUDNN_BACKEND_LAYOUT_INFO_DESCRIPTOR: return "CUDNN_BACKEND_LAYOUT_INFO_DESCRIPTOR"; case CUDNN_BACKEND_OPERATION_CONVOLUTION_FORWARD_DESCRIPTOR: return "CUDNN_BACKEND_OPERATION_CONVOLUTION_FORWARD_DESCRIPTOR"; case CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_FILTER_DESCRIPTOR: return "CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_FILTER_DESCRIPTOR"; case CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_DATA_DESCRIPTOR: return "CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_DATA_DESCRIPTOR"; case CUDNN_BACKEND_OPERATION_POINTWISE_DESCRIPTOR: return "CUDNN_BACKEND_OPERATION_POINTWISE_DESCRIPTOR"; case CUDNN_BACKEND_OPERATION_GEN_STATS_DESCRIPTOR: return "CUDNN_BACKEND_OPERATION_GEN_STATS_DESCRIPTOR"; case CUDNN_BACKEND_OPERATIONGRAPH_DESCRIPTOR: return "CUDNN_BACKEND_OPERATIONGRAPH_DESCRIPTOR"; case CUDNN_BACKEND_VARIANT_PACK_DESCRIPTOR: return "CUDNN_BACKEND_VARIANT_PACK_DESCRIPTOR"; case CUDNN_BACKEND_TENSOR_DESCRIPTOR: return "CUDNN_BACKEND_TENSOR_DESCRIPTOR"; case CUDNN_BACKEND_MATMUL_DESCRIPTOR: return "CUDNN_BACKEND_MATMUL_DESCRIPTOR"; case CUDNN_BACKEND_OPERATION_MATMUL_DESCRIPTOR: return "CUDNN_BACKEND_OPERATION_MATMUL_DESCRIPTOR"; case CUDNN_BACKEND_OPERATION_BN_FINALIZE_STATISTICS_DESCRIPTOR: return "CUDNN_BACKEND_OPERATION_BN_FINALIZE_STATISTICS_DESCRIPTOR"; case CUDNN_BACKEND_REDUCTION_DESCRIPTOR: return "CUDNN_BACKEND_REDUCTION_DESCRIPTOR"; case CUDNN_BACKEND_OPERATION_REDUCTION_DESCRIPTOR: return "CUDNN_BACKEND_OPERATION_REDUCTION_DESCRIPTOR"; case CUDNN_BACKEND_OPERATION_BN_BWD_WEIGHTS_DESCRIPTOR: return "CUDNN_BACKEND_OPERATION_BN_BWD_WEIGHTS_DESCRIPTOR"; case CUDNN_BACKEND_RESAMPLE_DESCRIPTOR: return "CUDNN_BACKEND_RESAMPLE_DESCRIPTOR"; case CUDNN_BACKEND_OPERATION_RESAMPLE_FWD_DESCRIPTOR: return "CUDNN_BACKEND_OPERATION_RESAMPLE_FWD_DESCRIPTOR"; case CUDNN_BACKEND_OPERATION_RESAMPLE_BWD_DESCRIPTOR: return "CUDNN_BACKEND_OPERATION_RESAMPLE_BWD_DESCRIPTOR"; case CUDNN_BACKEND_OPERATION_CONCAT_DESCRIPTOR: return "CUDNN_BACKEND_OPERATION_CONCAT_DESCRIPTOR"; case CUDNN_BACKEND_OPERATION_SIGNAL_DESCRIPTOR: return "CUDNN_BACKEND_OPERATION_SIGNAL_DESCRIPTOR"; case CUDNN_BACKEND_OPERATION_NORM_FORWARD_DESCRIPTOR: return "CUDNN_BACKEND_OPERATION_NORM_FORWARD_DESCRIPTOR"; case CUDNN_BACKEND_OPERATION_NORM_BACKWARD_DESCRIPTOR: return "CUDNN_BACKEND_OPERATION_NORM_BACKWARD_DESCRIPTOR"; case CUDNN_BACKEND_OPERATION_RESHAPE_DESCRIPTOR: return "CUDNN_BACKEND_OPERATION_RESHAPE_DESCRIPTOR"; case CUDNN_BACKEND_RNG_DESCRIPTOR: return "CUDNN_BACKEND_RNG_DESCRIPTOR"; case CUDNN_BACKEND_OPERATION_RNG_DESCRIPTOR: return "CUDNN_BACKEND_OPERATION_RNG_DESCRIPTOR"; } return "INVALID cudnnBackendDescriptorType: "+n; } }
UTF-8
Java
8,194
java
cudnnBackendDescriptorType.java
Java
[ { "context": "o be used with JCuda\n *\n * Copyright (c) 2015-2018 Marco Hutter - http://www.jcuda.org\n *\n * Permission is hereby", "end": 152, "score": 0.9998656511306763, "start": 140, "tag": "NAME", "value": "Marco Hutter" } ]
null
[]
/* * JCudnn - Java bindings for cuDNN, the NVIDIA CUDA * Deep Neural Network library, to be used with JCuda * * Copyright (c) 2015-2018 <NAME> - http://www.jcuda.org * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package jcuda.jcudnn; public class cudnnBackendDescriptorType { public static final int CUDNN_BACKEND_POINTWISE_DESCRIPTOR = 0; public static final int CUDNN_BACKEND_CONVOLUTION_DESCRIPTOR = 1; public static final int CUDNN_BACKEND_ENGINE_DESCRIPTOR = 2; public static final int CUDNN_BACKEND_ENGINECFG_DESCRIPTOR = 3; public static final int CUDNN_BACKEND_ENGINEHEUR_DESCRIPTOR = 4; public static final int CUDNN_BACKEND_EXECUTION_PLAN_DESCRIPTOR = 5; public static final int CUDNN_BACKEND_INTERMEDIATE_INFO_DESCRIPTOR = 6; public static final int CUDNN_BACKEND_KNOB_CHOICE_DESCRIPTOR = 7; public static final int CUDNN_BACKEND_KNOB_INFO_DESCRIPTOR = 8; public static final int CUDNN_BACKEND_LAYOUT_INFO_DESCRIPTOR = 9; public static final int CUDNN_BACKEND_OPERATION_CONVOLUTION_FORWARD_DESCRIPTOR = 10; public static final int CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_FILTER_DESCRIPTOR = 11; public static final int CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_DATA_DESCRIPTOR = 12; public static final int CUDNN_BACKEND_OPERATION_POINTWISE_DESCRIPTOR = 13; public static final int CUDNN_BACKEND_OPERATION_GEN_STATS_DESCRIPTOR = 14; public static final int CUDNN_BACKEND_OPERATIONGRAPH_DESCRIPTOR = 15; public static final int CUDNN_BACKEND_VARIANT_PACK_DESCRIPTOR = 16; public static final int CUDNN_BACKEND_TENSOR_DESCRIPTOR = 17; public static final int CUDNN_BACKEND_MATMUL_DESCRIPTOR = 18; public static final int CUDNN_BACKEND_OPERATION_MATMUL_DESCRIPTOR = 19; public static final int CUDNN_BACKEND_OPERATION_BN_FINALIZE_STATISTICS_DESCRIPTOR = 20; public static final int CUDNN_BACKEND_REDUCTION_DESCRIPTOR = 21; public static final int CUDNN_BACKEND_OPERATION_REDUCTION_DESCRIPTOR = 22; public static final int CUDNN_BACKEND_OPERATION_BN_BWD_WEIGHTS_DESCRIPTOR = 23; public static final int CUDNN_BACKEND_RESAMPLE_DESCRIPTOR = 24; public static final int CUDNN_BACKEND_OPERATION_RESAMPLE_FWD_DESCRIPTOR = 25; public static final int CUDNN_BACKEND_OPERATION_RESAMPLE_BWD_DESCRIPTOR = 26; public static final int CUDNN_BACKEND_OPERATION_CONCAT_DESCRIPTOR = 27; public static final int CUDNN_BACKEND_OPERATION_SIGNAL_DESCRIPTOR = 28; public static final int CUDNN_BACKEND_OPERATION_NORM_FORWARD_DESCRIPTOR = 29; public static final int CUDNN_BACKEND_OPERATION_NORM_BACKWARD_DESCRIPTOR = 30; public static final int CUDNN_BACKEND_OPERATION_RESHAPE_DESCRIPTOR = 31; public static final int CUDNN_BACKEND_RNG_DESCRIPTOR = 32; public static final int CUDNN_BACKEND_OPERATION_RNG_DESCRIPTOR = 33; /** * Private constructor to prevent instantiation */ private cudnnBackendDescriptorType() { // Private constructor to prevent instantiation } /** * Returns a string representation of the given constant * * @return A string representation of the given constant */ public static String stringFor(int n) { switch (n) { case CUDNN_BACKEND_POINTWISE_DESCRIPTOR: return "CUDNN_BACKEND_POINTWISE_DESCRIPTOR"; case CUDNN_BACKEND_CONVOLUTION_DESCRIPTOR: return "CUDNN_BACKEND_CONVOLUTION_DESCRIPTOR"; case CUDNN_BACKEND_ENGINE_DESCRIPTOR: return "CUDNN_BACKEND_ENGINE_DESCRIPTOR"; case CUDNN_BACKEND_ENGINECFG_DESCRIPTOR: return "CUDNN_BACKEND_ENGINECFG_DESCRIPTOR"; case CUDNN_BACKEND_ENGINEHEUR_DESCRIPTOR: return "CUDNN_BACKEND_ENGINEHEUR_DESCRIPTOR"; case CUDNN_BACKEND_EXECUTION_PLAN_DESCRIPTOR: return "CUDNN_BACKEND_EXECUTION_PLAN_DESCRIPTOR"; case CUDNN_BACKEND_INTERMEDIATE_INFO_DESCRIPTOR: return "CUDNN_BACKEND_INTERMEDIATE_INFO_DESCRIPTOR"; case CUDNN_BACKEND_KNOB_CHOICE_DESCRIPTOR: return "CUDNN_BACKEND_KNOB_CHOICE_DESCRIPTOR"; case CUDNN_BACKEND_KNOB_INFO_DESCRIPTOR: return "CUDNN_BACKEND_KNOB_INFO_DESCRIPTOR"; case CUDNN_BACKEND_LAYOUT_INFO_DESCRIPTOR: return "CUDNN_BACKEND_LAYOUT_INFO_DESCRIPTOR"; case CUDNN_BACKEND_OPERATION_CONVOLUTION_FORWARD_DESCRIPTOR: return "CUDNN_BACKEND_OPERATION_CONVOLUTION_FORWARD_DESCRIPTOR"; case CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_FILTER_DESCRIPTOR: return "CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_FILTER_DESCRIPTOR"; case CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_DATA_DESCRIPTOR: return "CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_DATA_DESCRIPTOR"; case CUDNN_BACKEND_OPERATION_POINTWISE_DESCRIPTOR: return "CUDNN_BACKEND_OPERATION_POINTWISE_DESCRIPTOR"; case CUDNN_BACKEND_OPERATION_GEN_STATS_DESCRIPTOR: return "CUDNN_BACKEND_OPERATION_GEN_STATS_DESCRIPTOR"; case CUDNN_BACKEND_OPERATIONGRAPH_DESCRIPTOR: return "CUDNN_BACKEND_OPERATIONGRAPH_DESCRIPTOR"; case CUDNN_BACKEND_VARIANT_PACK_DESCRIPTOR: return "CUDNN_BACKEND_VARIANT_PACK_DESCRIPTOR"; case CUDNN_BACKEND_TENSOR_DESCRIPTOR: return "CUDNN_BACKEND_TENSOR_DESCRIPTOR"; case CUDNN_BACKEND_MATMUL_DESCRIPTOR: return "CUDNN_BACKEND_MATMUL_DESCRIPTOR"; case CUDNN_BACKEND_OPERATION_MATMUL_DESCRIPTOR: return "CUDNN_BACKEND_OPERATION_MATMUL_DESCRIPTOR"; case CUDNN_BACKEND_OPERATION_BN_FINALIZE_STATISTICS_DESCRIPTOR: return "CUDNN_BACKEND_OPERATION_BN_FINALIZE_STATISTICS_DESCRIPTOR"; case CUDNN_BACKEND_REDUCTION_DESCRIPTOR: return "CUDNN_BACKEND_REDUCTION_DESCRIPTOR"; case CUDNN_BACKEND_OPERATION_REDUCTION_DESCRIPTOR: return "CUDNN_BACKEND_OPERATION_REDUCTION_DESCRIPTOR"; case CUDNN_BACKEND_OPERATION_BN_BWD_WEIGHTS_DESCRIPTOR: return "CUDNN_BACKEND_OPERATION_BN_BWD_WEIGHTS_DESCRIPTOR"; case CUDNN_BACKEND_RESAMPLE_DESCRIPTOR: return "CUDNN_BACKEND_RESAMPLE_DESCRIPTOR"; case CUDNN_BACKEND_OPERATION_RESAMPLE_FWD_DESCRIPTOR: return "CUDNN_BACKEND_OPERATION_RESAMPLE_FWD_DESCRIPTOR"; case CUDNN_BACKEND_OPERATION_RESAMPLE_BWD_DESCRIPTOR: return "CUDNN_BACKEND_OPERATION_RESAMPLE_BWD_DESCRIPTOR"; case CUDNN_BACKEND_OPERATION_CONCAT_DESCRIPTOR: return "CUDNN_BACKEND_OPERATION_CONCAT_DESCRIPTOR"; case CUDNN_BACKEND_OPERATION_SIGNAL_DESCRIPTOR: return "CUDNN_BACKEND_OPERATION_SIGNAL_DESCRIPTOR"; case CUDNN_BACKEND_OPERATION_NORM_FORWARD_DESCRIPTOR: return "CUDNN_BACKEND_OPERATION_NORM_FORWARD_DESCRIPTOR"; case CUDNN_BACKEND_OPERATION_NORM_BACKWARD_DESCRIPTOR: return "CUDNN_BACKEND_OPERATION_NORM_BACKWARD_DESCRIPTOR"; case CUDNN_BACKEND_OPERATION_RESHAPE_DESCRIPTOR: return "CUDNN_BACKEND_OPERATION_RESHAPE_DESCRIPTOR"; case CUDNN_BACKEND_RNG_DESCRIPTOR: return "CUDNN_BACKEND_RNG_DESCRIPTOR"; case CUDNN_BACKEND_OPERATION_RNG_DESCRIPTOR: return "CUDNN_BACKEND_OPERATION_RNG_DESCRIPTOR"; } return "INVALID cudnnBackendDescriptorType: "+n; } }
8,188
0.748841
0.740786
121
66.710747
38.542763
153
false
false
0
0
0
0
0
0
0.77686
false
false
10
2f6f43550f59b3144646f378a8b41aac8d7c5165
12,232,066,906,047
3d3f92f8286c34fabdc986bbbd4282836f7c4ef5
/array_utils/src/main/java/com/hoverdroids/array_utils/DisplayNameEnum.java
55bfa721bdc221a0aaf406f4ccf70a6d4f3cf18f
[]
no_license
hoverdroids/HoverDroids_Android_Utils
https://github.com/hoverdroids/HoverDroids_Android_Utils
c6a1d7e36cfe05027cdddc8e358fae25237ffe2c
180976e6ff9a075eb94b8cdca4be5d7897b03543
refs/heads/master
2020-04-04T19:11:25.362000
2019-06-23T15:59:01
2019-06-23T16:00:01
156,195,655
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hoverdroids.array_utils; public interface DisplayNameEnum { String displayName(); }
UTF-8
Java
101
java
DisplayNameEnum.java
Java
[]
null
[]
package com.hoverdroids.array_utils; public interface DisplayNameEnum { String displayName(); }
101
0.772277
0.772277
6
15.833333
15.507167
36
false
false
0
0
0
0
0
0
0.333333
false
false
10
261bc5393d80204cc66ea3c17f9c6fda3ada1ef3
22,488,448,815,806
4fe35510459d61553c3e82765475d999e3f3d5bb
/itask/src/main/java/com/panwy/itask/entity/task/MyTask.java
a4af7c72670ebad853c90d9bb719781fb36f42fa
[]
no_license
pwypwy/ITask
https://github.com/pwypwy/ITask
e16a26dfd1caf0a0695971c59777674c156d2e93
2e7f790d71eeeb73d1d2358b48d356d520598b63
refs/heads/master
2022-09-18T04:48:52.640000
2020-06-05T13:48:49
2020-06-05T13:48:49
267,744,221
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.panwy.itask.entity.task; import java.util.List; import java.util.Map; import lombok.Data; @Data public class MyTask { /** * 执行任务列表 */ private List<SimpleTask> executingTasks; /** * 未启动任务列表 */ private List<SimpleTask> initTasks; /** * 暂停任务列表 */ private List<SimpleTask> suspendTasks; /** * 已完成任务列表 */ private List<SimpleTask> finishTasks; /** * 已终止任务列表 */ private List<SimpleTask> stopTasks; public static MyTask init(Map<String,List<SimpleTask>> map){ MyTask myTask = new MyTask(); myTask.setExecutingTasks(map.get("进行中")); myTask.setInitTasks(map.get("未启动")); myTask.setSuspendTasks(map.get("已暂停")); myTask.setStopTasks(map.get("已终止")); myTask.setFinishTasks(map.get("已完成")); return myTask; } }
UTF-8
Java
965
java
MyTask.java
Java
[]
null
[]
package com.panwy.itask.entity.task; import java.util.List; import java.util.Map; import lombok.Data; @Data public class MyTask { /** * 执行任务列表 */ private List<SimpleTask> executingTasks; /** * 未启动任务列表 */ private List<SimpleTask> initTasks; /** * 暂停任务列表 */ private List<SimpleTask> suspendTasks; /** * 已完成任务列表 */ private List<SimpleTask> finishTasks; /** * 已终止任务列表 */ private List<SimpleTask> stopTasks; public static MyTask init(Map<String,List<SimpleTask>> map){ MyTask myTask = new MyTask(); myTask.setExecutingTasks(map.get("进行中")); myTask.setInitTasks(map.get("未启动")); myTask.setSuspendTasks(map.get("已暂停")); myTask.setStopTasks(map.get("已终止")); myTask.setFinishTasks(map.get("已完成")); return myTask; } }
965
0.59954
0.59954
44
18.772728
17.808149
64
false
false
0
0
0
0
0
0
0.386364
false
false
10
566f90b93c107fcf7246c81f045188b5655bac24
23,210,003,311,303
b43d74e67675edcbfa9e549da8b9de450e80e687
/spring-annotation/src/main/java/com/cn/lg/annotation/TransactionalTest.java
2403eb6c1835ce10d569019ff1dc9c57e5363423
[]
no_license
SirLiuGang/Spring
https://github.com/SirLiuGang/Spring
60e54019c2e9bc6d3ca48710e6143ec024cc191d
31e38344d1e2c4025bdac99a748c8dd18629401a
refs/heads/master
2022-06-26T03:19:50.797000
2019-12-15T06:54:08
2019-12-15T06:54:08
170,708,895
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cn.lg.annotation; import org.springframework.transaction.annotation.Transactional; /** * @author: 刘钢 * @Date: 2019/3/2 20:55 * @Description: */ @Transactional public class TransactionalTest { /** * 方法上的注解会覆盖类上的注解 */ @Transactional(rollbackFor = Exception.class) public void save() { } }
UTF-8
Java
364
java
TransactionalTest.java
Java
[ { "context": "saction.annotation.Transactional;\n/**\n * @author: 刘钢\n * @Date: 2019/3/2 20:55\n * @Description:\n */\n@Tr", "end": 114, "score": 0.9997087717056274, "start": 112, "tag": "NAME", "value": "刘钢" } ]
null
[]
package com.cn.lg.annotation; import org.springframework.transaction.annotation.Transactional; /** * @author: 刘钢 * @Date: 2019/3/2 20:55 * @Description: */ @Transactional public class TransactionalTest { /** * 方法上的注解会覆盖类上的注解 */ @Transactional(rollbackFor = Exception.class) public void save() { } }
364
0.668675
0.638554
19
16.473684
17.150629
64
false
false
0
0
0
0
0
0
0.105263
false
false
10
d5b6c1ecdc08d0bfff2bb23beecebb4584610e55
22,832,046,198,856
58d7ff7c645c26771faae523e4ccb1e8f932b3e8
/MUD/model/items/shield/HeavyShield.java
d6f5fd5c74645ebb082136933a17d7ef83a4810e
[]
no_license
djeisenberg/Academic
https://github.com/djeisenberg/Academic
c0ac2de7462498db0edbce91a0265e6460506637
c5d0c0c9b57b74d11472b79986f7c16e06e60771
refs/heads/master
2021-01-18T18:31:58.782000
2015-04-23T18:59:03
2015-04-23T18:59:03
24,281,041
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package model.items.shield; import model.items.Armor; public class HeavyShield extends Armor{ /** * */ private static final long serialVersionUID = 1L; public HeavyShield() { this.name = "Heavy Shield"; this.description = ""; this.iID = 800; this.ilevel = 2; this.cost = 0; this.idef = 6; this.imdef = 2; this.eqslot = slots.get(1).toString(); } }
UTF-8
Java
387
java
HeavyShield.java
Java
[]
null
[]
package model.items.shield; import model.items.Armor; public class HeavyShield extends Armor{ /** * */ private static final long serialVersionUID = 1L; public HeavyShield() { this.name = "Heavy Shield"; this.description = ""; this.iID = 800; this.ilevel = 2; this.cost = 0; this.idef = 6; this.imdef = 2; this.eqslot = slots.get(1).toString(); } }
387
0.633075
0.609819
28
12.857142
14.123724
49
false
false
0
0
0
0
0
0
1.392857
false
false
10
9d84b0d3749df8d6445c1d28cffaad74360c92e5
4,526,895,566,658
c2f58b1c30cea1be18ed6fa29ff75856340a444e
/src/main/java/frc/robot/constants/fields/HomeField.java
98efa44556d51c440f7dc850394bf43d70e3e852
[]
no_license
Programming-TRIGON/RobotTemplate2020
https://github.com/Programming-TRIGON/RobotTemplate2020
c193a9d16ebf1d0ef91ec9759d259b41f27e7656
14365344ca5bc3cd389eed20bfd4a2414fb97923
refs/heads/master
2020-11-30T04:19:09.182000
2020-01-15T10:06:29
2020-01-15T10:06:29
230,300,319
0
4
null
false
2020-01-15T10:06:31
2019-12-26T17:12:27
2020-01-15T09:14:54
2020-01-15T10:06:30
176
0
2
0
Java
false
false
package frc.robot.constants.fields; import frc.robot.constants.FieldConstants; /** * Home field dimensions and distances. */ public class HomeField extends FieldConstants { public HomeField() { feederConstants.ROCKET_TO_FEEDER = 250; feederConstants.SIDE_WALL_TO_MIDDLE_FEEDER = 50; } }
UTF-8
Java
315
java
HomeField.java
Java
[]
null
[]
package frc.robot.constants.fields; import frc.robot.constants.FieldConstants; /** * Home field dimensions and distances. */ public class HomeField extends FieldConstants { public HomeField() { feederConstants.ROCKET_TO_FEEDER = 250; feederConstants.SIDE_WALL_TO_MIDDLE_FEEDER = 50; } }
315
0.714286
0.698413
13
23.23077
20.88118
56
false
false
0
0
0
0
0
0
0.307692
false
false
10
28ad86c9be432b7e7ac825c0f3a5eb78f3cd791b
22,754,736,767,541
0c717ed55c8ffb1891cbeb2225e9362a8bf0e6e0
/VineyardAndroidClient/src/com/formichelli/vineyard/entities/Worker.java
b0ec1f2a0571a00c1eb440b6b50b0051689f063c
[]
no_license
danyf90/MultipathDetectionAlgorithm
https://github.com/danyf90/MultipathDetectionAlgorithm
aa6d563cd433435a6af73fb9d2206a25cfe07846
6ad0a0cd543f55e3d15de70e1dc42e55febee935
refs/heads/master
2016-09-06T17:27:18.579000
2014-06-08T13:39:39
2014-06-08T13:39:39
39,912,007
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.formichelli.vineyard.entities; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; import org.json.JSONException; import org.json.JSONObject; public class Worker { public final static String ID = "id"; public final static String USERNAME = "username"; public final static String PASSWORD = "password"; public final static String NAME = "name"; public final static String EMAIL = "email"; public final static String ROLES = "role"; private int id; private String username; private String name; private String email; private Set<Role> roles; private List<WorkGroup> groups; public enum Role { OPERATOR, ADMIN; } public Worker() { groups = new ArrayList<WorkGroup>(); } public Worker(JSONObject jsonObject) throws JSONException { setId(jsonObject.getInt(ID)); setUsername(jsonObject.getString(USERNAME)); setEmail(jsonObject.getString(EMAIL)); setName(jsonObject.getString(NAME)); roles = new HashSet<Role>(); setRoles(jsonObject.getString(ROLES)); groups = new ArrayList<WorkGroup>(); } public int getId() { return id; } public void setId(int id) { if (id < 0) throw new IllegalArgumentException("id cannot be negative"); this.id = id; } public String getUsername() { return this.username; } public void setUsername(String username) { if (username == null || username.compareTo("") == 0) throw new IllegalArgumentException( "username cannot be neither null nor empty"); this.username = username; } public String getName() { return this.name; } public void setName(String name) { if (name == null || name.compareTo("") == 0) throw new IllegalArgumentException( "name cannot be neither null nor empty"); this.name = name; } public String getEmail() { return this.email; } public void setEmail(String email) { if (email == null || email.compareTo("") == 0) throw new IllegalArgumentException( "email cannot be neither null nor empty"); this.email = email; } public Set<Role> getRole() { return roles; } public void setRoles(Set<Role> roles) { if (roles != null) this.roles = roles; else this.roles.clear(); } public void addRole(Role role) { if (role != null) roles.add(role); } public void setRoles(String rolesJSON) { this.roles.clear(); if (rolesJSON != null) { String[] roles = rolesJSON.split(","); for (String role : roles) this.roles.add(Role.valueOf(role.toUpperCase(Locale.US))); } } public List<WorkGroup> getGroups() { return groups; } public void setGroups(List<WorkGroup> groups) { if (groups == null) this.groups.clear(); else this.groups = groups; } public void addGroup(WorkGroup group) { if (group != null) groups.add(group); } public void removeGroup(WorkGroup group) { groups.remove(group); } }
UTF-8
Java
2,898
java
Worker.java
Java
[ { "context": "D = \"id\";\n\tpublic final static String USERNAME = \"username\";\n\tpublic final static String PASSWORD = \"passwor", "end": 338, "score": 0.9988581538200378, "start": 330, "tag": "USERNAME", "value": "username" }, { "context": "sername\";\n\tpublic final static String PASSWORD = \"password\";\n\tpublic final static String NAME = \"name\";\n\tpub", "end": 389, "score": 0.9986155033111572, "start": 381, "tag": "PASSWORD", "value": "password" } ]
null
[]
package com.formichelli.vineyard.entities; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; import org.json.JSONException; import org.json.JSONObject; public class Worker { public final static String ID = "id"; public final static String USERNAME = "username"; public final static String PASSWORD = "<PASSWORD>"; public final static String NAME = "name"; public final static String EMAIL = "email"; public final static String ROLES = "role"; private int id; private String username; private String name; private String email; private Set<Role> roles; private List<WorkGroup> groups; public enum Role { OPERATOR, ADMIN; } public Worker() { groups = new ArrayList<WorkGroup>(); } public Worker(JSONObject jsonObject) throws JSONException { setId(jsonObject.getInt(ID)); setUsername(jsonObject.getString(USERNAME)); setEmail(jsonObject.getString(EMAIL)); setName(jsonObject.getString(NAME)); roles = new HashSet<Role>(); setRoles(jsonObject.getString(ROLES)); groups = new ArrayList<WorkGroup>(); } public int getId() { return id; } public void setId(int id) { if (id < 0) throw new IllegalArgumentException("id cannot be negative"); this.id = id; } public String getUsername() { return this.username; } public void setUsername(String username) { if (username == null || username.compareTo("") == 0) throw new IllegalArgumentException( "username cannot be neither null nor empty"); this.username = username; } public String getName() { return this.name; } public void setName(String name) { if (name == null || name.compareTo("") == 0) throw new IllegalArgumentException( "name cannot be neither null nor empty"); this.name = name; } public String getEmail() { return this.email; } public void setEmail(String email) { if (email == null || email.compareTo("") == 0) throw new IllegalArgumentException( "email cannot be neither null nor empty"); this.email = email; } public Set<Role> getRole() { return roles; } public void setRoles(Set<Role> roles) { if (roles != null) this.roles = roles; else this.roles.clear(); } public void addRole(Role role) { if (role != null) roles.add(role); } public void setRoles(String rolesJSON) { this.roles.clear(); if (rolesJSON != null) { String[] roles = rolesJSON.split(","); for (String role : roles) this.roles.add(Role.valueOf(role.toUpperCase(Locale.US))); } } public List<WorkGroup> getGroups() { return groups; } public void setGroups(List<WorkGroup> groups) { if (groups == null) this.groups.clear(); else this.groups = groups; } public void addGroup(WorkGroup group) { if (group != null) groups.add(group); } public void removeGroup(WorkGroup group) { groups.remove(group); } }
2,900
0.689096
0.687716
144
19.131945
17.627411
63
false
false
0
0
0
0
0
0
1.611111
false
false
10
8eacf6e7ea60309219de6f02510bd16e89db1e18
5,772,436,088,194
dc1dbb7e5a4b95bf44170d2f51fd08b3814f2ac9
/data_defect4j/preprossed_method_corpus/Chart/25/org/jfree/chart/needle/MeterNeedle_readObject_411.java
047c004c6645f8535d29a2c0a897a8799bd6ec1a
[]
no_license
hvdthong/NetML
https://github.com/hvdthong/NetML
dca6cf4d34c5799b400d718e0a6cd2e0b167297d
9bb103da21327912e5a29cbf9be9ff4d058731a5
refs/heads/master
2021-06-30T15:03:52.618000
2020-10-07T01:58:48
2020-10-07T01:58:48
150,383,588
1
1
null
true
2018-09-26T07:08:45
2018-09-26T07:08:44
2018-03-01T05:04:19
2018-01-15T07:59:20
172,367
0
0
0
null
false
null
org jfree chart needl base repres needl link org jfree chart plot compass plot compassplot meter needl meterneedl serializ serial support param stream input stream except ioexcept error class found except classnotfoundexcept classpath problem read object readobject object input stream objectinputstream stream except ioexcept class found except classnotfoundexcept stream read object defaultreadobject outlin stroke outlinestrok serial util serialutil read stroke readstrok stream outlin paint outlinepaint serial util serialutil read paint readpaint stream fill paint fillpaint serial util serialutil read paint readpaint stream highlight paint highlightpaint serial util serialutil read paint readpaint stream
UTF-8
Java
1,118
java
MeterNeedle_readObject_411.java
Java
[]
null
[]
org jfree chart needl base repres needl link org jfree chart plot compass plot compassplot meter needl meterneedl serializ serial support param stream input stream except ioexcept error class found except classnotfoundexcept classpath problem read object readobject object input stream objectinputstream stream except ioexcept class found except classnotfoundexcept stream read object defaultreadobject outlin stroke outlinestrok serial util serialutil read stroke readstrok stream outlin paint outlinepaint serial util serialutil read paint readpaint stream fill paint fillpaint serial util serialutil read paint readpaint stream highlight paint highlightpaint serial util serialutil read paint readpaint stream
1,118
0.555456
0.555456
367
1.901907
10.364536
81
false
false
0
0
0
0
343
0.306798
0
false
false
10
5a526f6acd9f7133c1ac9b3c2d6113042174c6b9
13,666,585,973,895
fbb9fe43f41a083afb783ed5f17d4911949d7f12
/OOP/Assignments/1-Introduction.java
0870c5fe4f6cda68d8b4d0c11a051686367cd04e
[]
no_license
shadowprince10/Bootcamp-Semester-3---4
https://github.com/shadowprince10/Bootcamp-Semester-3---4
dd28ca4b5d655f459737727ce9493e1ffbe0f3ae
c669eda4a96a0bb2e68e63a01badc12cc1ddafe0
refs/heads/main
2023-04-29T20:13:28.760000
2021-05-17T11:40:11
2021-05-17T11:40:11
367,536,159
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Scanner; public class main { private static Scanner scan; private static String firstNumberString; private static String secondNumberString; private static Character firstNumberChar; private static Character secondNumberChar; private static Float resultFloat; private static Integer firstSecondSum; private static Integer firstSecondSubtraction; private static Integer firstSecondMultiplication; private static Integer firstSecondDivision; private static Integer firstSecondModulo; private static String p1, p2; private static Boolean p1Bool, p2Bool; private static Boolean valid = true; public main() { // TODO Auto-generated constructor stub } public static void title() { System.out.println(" /$$$$$$$ /$$$$$ /$$$$$ /$$$$$$$ /$$$$$$$$ /$$ /$$"); System.out.println("| $$__ $$ |__ $$ |__ $$ | $$__ $$|__ $$__/ | $$ | $$"); System.out.println("| $$ \ $$ | $$ | $$ | $$ \ $$ | $$ /$$$$$$ | $$$$$$$ | $$ /$$$$$$"); System.out.println("| $$$$$$$ | $$ /$$$$$$ | $$ | $$$$$$$/ | $$ |____ $$ | $$__ $$ | $$ /$$__ $$"); System.out.println("| $$__ $$ /$$ | $$ |______/ /$$ | $$ | $$____/ | $$ /$$$$$$$ | $$ \ $$ | $$| $$$$$$$$"); System.out.println("| $$ \ $$| $$ | $$ | $$ | $$ | $$ | $$ /$$__ $$ | $$ | $$| $$| $$_____/"); System.out.println("| $$$$$$$/| $$$$$$/ | $$$$$$ /| $$ | $$| $$$$$$$| $$$$$$$/| $$| $$$$$$$"); System.out.println("|_______/ \______/ \______/ |__/ |__/ \_______/|_______/ |__/ \_______/"); for (int i = 0; i < 2; i++) { System.out.println(""); } } public static void pressEnter() { System.out.println("Press enter to proceed. ."); scan.nextLine(); // similar to getchar() in C to catch one enter key from user } public static void displayMenu() { System.out.println("1. Start the Simulation!!"); System.out.println("2. Close App"); } public static void simulationMenu() { Integer firstNumber; Integer secondNumber; do { System.out.print("Input the first number [1 - 100](inclusive): "); firstNumber = scan.nextInt(); } while (firstNumber < 1 || firstNumber > 100); scan.nextLine(); do { System.out.print("Input the second number [1 - 100](inclusive): "); secondNumber = scan.nextInt(); } while (secondNumber < 1 || secondNumber > 100); scan.nextLine(); firstNumberString = firstNumber.toString(); // convert the first number to string secondNumberString = secondNumber.toString(); // convert the second number to string firstNumberChar = (char) (firstNumber + '0'); // convert the third number string to character secondNumberChar = (char) (secondNumber + '0'); // convert the second number string to character resultFloat = firstNumber.floatValue() / secondNumber.floatValue(); // convert the result of division of first number and second number to float System.out.println("Table consisting of basic Java data types"); System.out.println("+================================================================================================+"); System.out.println("+ + (String type) | (Character Type) | * (Integer type) | / (Floating Type) | input 1 == input 2 (Boolean Type) +"); System.out.printf("+ %-4d + %-10d | %c %c | %5d | %5f | %10s", firstNumberString, secondNumberString, firstNumberChar, secondNumberChar, (firstNumber * secondNumber), resultFloat, (firstNumber == secondNumber)); System.out.println("+================================================================================================+"); pressEnter(); firstSecondSum = firstNumber + secondNumber; firstSecondSubtraction = firstNumber - secondNumber; firstSecondMultiplication = firstNumber * secondNumber; firstSecondDivision = firstNumber / secondNumber; firstSecondModulo = firstNumber % secondNumber; System.out.println("Table consisting of basic arithmetic operation"); System.out.println("+================================================================================================+"); System.out.println("+Data Type : Integer +"); System.out.println("+================================================================================================+"); System.out.println("+ + | - | * | / | % |"); System.out.println("+================================================================================================+"); System.out.printf("+ %-3d | %-3d | %5d | %3d | %3d", firstSecondSum, firstSecondSubtraction, firstSecondMultiplication, firstSecondDivision, firstSecondModulo); System.out.println("+================================================================================================+"); pressEnter(); do { System.out.print("Give me value for p1 [true | false]: "); p1 = scan.nextLine(); } while (p1 != "true" && p1 != "false"); scan.nextLine(); do { System.out.print("Give me value for p2 [true | false]: "); p2 = scan.nextLine(); } while (p2 != "true" && p2 != "false"); scan.nextLine(); scan.close(); p1Bool = Boolean.parseBoolean(p1); // convert string p1 to Boolean p2Bool = Boolean.parseBoolean(p2); // convert string p2 to Boolean System.out.println("+================================================================================================+"); System.out.println("+Logical Table"); System.out.println("+================================================================================================+"); System.out.println("+ P1 = T , P2 = F +"); System.out.println("+================================================================================================+"); System.out.println("+ !P1 | !P2 | && | || +"); System.out.printf("+ %-10s | %-10s | %10s | %10s |", !(p1Bool), !(p2Bool), (p1Bool && p2Bool), (p1Bool || p2Bool)); System.out.println("+================================================================================================+"); pressEnter(); } public static void closeAppMenu() { System.out.println("Thank you for using the apps"); } public static void mainMenu() { int menu; while (valid) { title(); displayMenu(); scan = new Scanner(System.in); do { System.out.print("Choice >> "); menu = scan.nextInt(); } while (menu < 1 || menu > 2); scan.nextLine(); scan.close(); switch(menu) { case 1: simulationMenu(); break; case 2: closeAppMenu(); valid = false; scan.nextLine(); // similar to getchar() in C System.exit(0); // similar to exit(0) in C // System.exit(0): successfully exit out of Java Program // System.exit(nonzero value): unsuccessfully exit out of Java Program break; } } } public static void main(String[] args) { // TODO Auto-generated method stub mainMenu(); } } /* Resources: * https://www.homeandlearn.co.uk/java/java_formatted_strings.html#:~:text=printf(%20%22%25%2D15s%20%25,means%20fifteen%20characters%20left%2Djustified. * https://www.javatpoint.com/string-comparison-in-java * https://www.w3schools.com/java/ref_string_charat.asp * https://stackoverflow.com/questions/17984975/convert-int-to-char-in-java * https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html * https://www.tutorialspoint.com/java-program-to-convert-string-to-boolean#:~:text=To%20convert%20String%20to%20Boolean%2C%20use%20the%20parseBoolean()%20method,to%20the%20string%20%22true%22. */
UTF-8
Java
8,136
java
1-Introduction.java
Java
[]
null
[]
import java.util.Scanner; public class main { private static Scanner scan; private static String firstNumberString; private static String secondNumberString; private static Character firstNumberChar; private static Character secondNumberChar; private static Float resultFloat; private static Integer firstSecondSum; private static Integer firstSecondSubtraction; private static Integer firstSecondMultiplication; private static Integer firstSecondDivision; private static Integer firstSecondModulo; private static String p1, p2; private static Boolean p1Bool, p2Bool; private static Boolean valid = true; public main() { // TODO Auto-generated constructor stub } public static void title() { System.out.println(" /$$$$$$$ /$$$$$ /$$$$$ /$$$$$$$ /$$$$$$$$ /$$ /$$"); System.out.println("| $$__ $$ |__ $$ |__ $$ | $$__ $$|__ $$__/ | $$ | $$"); System.out.println("| $$ \ $$ | $$ | $$ | $$ \ $$ | $$ /$$$$$$ | $$$$$$$ | $$ /$$$$$$"); System.out.println("| $$$$$$$ | $$ /$$$$$$ | $$ | $$$$$$$/ | $$ |____ $$ | $$__ $$ | $$ /$$__ $$"); System.out.println("| $$__ $$ /$$ | $$ |______/ /$$ | $$ | $$____/ | $$ /$$$$$$$ | $$ \ $$ | $$| $$$$$$$$"); System.out.println("| $$ \ $$| $$ | $$ | $$ | $$ | $$ | $$ /$$__ $$ | $$ | $$| $$| $$_____/"); System.out.println("| $$$$$$$/| $$$$$$/ | $$$$$$ /| $$ | $$| $$$$$$$| $$$$$$$/| $$| $$$$$$$"); System.out.println("|_______/ \______/ \______/ |__/ |__/ \_______/|_______/ |__/ \_______/"); for (int i = 0; i < 2; i++) { System.out.println(""); } } public static void pressEnter() { System.out.println("Press enter to proceed. ."); scan.nextLine(); // similar to getchar() in C to catch one enter key from user } public static void displayMenu() { System.out.println("1. Start the Simulation!!"); System.out.println("2. Close App"); } public static void simulationMenu() { Integer firstNumber; Integer secondNumber; do { System.out.print("Input the first number [1 - 100](inclusive): "); firstNumber = scan.nextInt(); } while (firstNumber < 1 || firstNumber > 100); scan.nextLine(); do { System.out.print("Input the second number [1 - 100](inclusive): "); secondNumber = scan.nextInt(); } while (secondNumber < 1 || secondNumber > 100); scan.nextLine(); firstNumberString = firstNumber.toString(); // convert the first number to string secondNumberString = secondNumber.toString(); // convert the second number to string firstNumberChar = (char) (firstNumber + '0'); // convert the third number string to character secondNumberChar = (char) (secondNumber + '0'); // convert the second number string to character resultFloat = firstNumber.floatValue() / secondNumber.floatValue(); // convert the result of division of first number and second number to float System.out.println("Table consisting of basic Java data types"); System.out.println("+================================================================================================+"); System.out.println("+ + (String type) | (Character Type) | * (Integer type) | / (Floating Type) | input 1 == input 2 (Boolean Type) +"); System.out.printf("+ %-4d + %-10d | %c %c | %5d | %5f | %10s", firstNumberString, secondNumberString, firstNumberChar, secondNumberChar, (firstNumber * secondNumber), resultFloat, (firstNumber == secondNumber)); System.out.println("+================================================================================================+"); pressEnter(); firstSecondSum = firstNumber + secondNumber; firstSecondSubtraction = firstNumber - secondNumber; firstSecondMultiplication = firstNumber * secondNumber; firstSecondDivision = firstNumber / secondNumber; firstSecondModulo = firstNumber % secondNumber; System.out.println("Table consisting of basic arithmetic operation"); System.out.println("+================================================================================================+"); System.out.println("+Data Type : Integer +"); System.out.println("+================================================================================================+"); System.out.println("+ + | - | * | / | % |"); System.out.println("+================================================================================================+"); System.out.printf("+ %-3d | %-3d | %5d | %3d | %3d", firstSecondSum, firstSecondSubtraction, firstSecondMultiplication, firstSecondDivision, firstSecondModulo); System.out.println("+================================================================================================+"); pressEnter(); do { System.out.print("Give me value for p1 [true | false]: "); p1 = scan.nextLine(); } while (p1 != "true" && p1 != "false"); scan.nextLine(); do { System.out.print("Give me value for p2 [true | false]: "); p2 = scan.nextLine(); } while (p2 != "true" && p2 != "false"); scan.nextLine(); scan.close(); p1Bool = Boolean.parseBoolean(p1); // convert string p1 to Boolean p2Bool = Boolean.parseBoolean(p2); // convert string p2 to Boolean System.out.println("+================================================================================================+"); System.out.println("+Logical Table"); System.out.println("+================================================================================================+"); System.out.println("+ P1 = T , P2 = F +"); System.out.println("+================================================================================================+"); System.out.println("+ !P1 | !P2 | && | || +"); System.out.printf("+ %-10s | %-10s | %10s | %10s |", !(p1Bool), !(p2Bool), (p1Bool && p2Bool), (p1Bool || p2Bool)); System.out.println("+================================================================================================+"); pressEnter(); } public static void closeAppMenu() { System.out.println("Thank you for using the apps"); } public static void mainMenu() { int menu; while (valid) { title(); displayMenu(); scan = new Scanner(System.in); do { System.out.print("Choice >> "); menu = scan.nextInt(); } while (menu < 1 || menu > 2); scan.nextLine(); scan.close(); switch(menu) { case 1: simulationMenu(); break; case 2: closeAppMenu(); valid = false; scan.nextLine(); // similar to getchar() in C System.exit(0); // similar to exit(0) in C // System.exit(0): successfully exit out of Java Program // System.exit(nonzero value): unsuccessfully exit out of Java Program break; } } } public static void main(String[] args) { // TODO Auto-generated method stub mainMenu(); } } /* Resources: * https://www.homeandlearn.co.uk/java/java_formatted_strings.html#:~:text=printf(%20%22%25%2D15s%20%25,means%20fifteen%20characters%20left%2Djustified. * https://www.javatpoint.com/string-comparison-in-java * https://www.w3schools.com/java/ref_string_charat.asp * https://stackoverflow.com/questions/17984975/convert-int-to-char-in-java * https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html * https://www.tutorialspoint.com/java-program-to-convert-string-to-boolean#:~:text=To%20convert%20String%20to%20Boolean%2C%20use%20the%20parseBoolean()%20method,to%20the%20string%20%22true%22. */
8,136
0.484882
0.468166
186
42.741936
47.716999
213
false
false
0
0
0
0
98
0.120452
3.688172
false
false
10
d94e3a10818dc73bbced24dbbb52c27761d87096
12,764,642,850,123
8625eaa50cd2ed4e9b50c48e2568f44a6db4bc65
/src/main/java/com/simplesarkar/web/AadharCardStatusCall.java
bd2cab585988be64e2b64f23450d380772022af9
[]
no_license
rajesh-yapstone/sooper
https://github.com/rajesh-yapstone/sooper
07257487270c25b4d9be76c721a1d6f869ffd401
985a4f7915e24b0eb46c5552ccda41b176f28a96
refs/heads/master
2021-01-11T22:43:24.144000
2018-07-06T00:20:06
2018-07-06T00:20:06
79,020,916
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.simplesarkar.web; import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.Map.Entry; import javax.imageio.ImageIO; import org.apache.log4j.Logger; public class AadharCardStatusCall { final static Logger log = Logger.getLogger(AadharCardStatusCall.class); public static void getCaptcha(){ String charset = null; try { String path = "captcha_image.jpeg"; URL url = new URL("https://indianvisaonline.gov.in/visa/Rimage.jsp"); BufferedImage image = ImageIO.read(url); ImageIO.write(image, "jpeg", new File(path)); URLConnection connection = url.openConnection(); connection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"); connection.setRequestProperty("Host", "indianvisaonline.gov.in" ); connection.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); connection.setRequestProperty("Accept-Language","en-US,en;q=0.5"); connection.setRequestProperty("Accept-Encoding","gzip,dflate,br"); connection.setRequestProperty("Connection","Keep-Alive"); connection.setRequestProperty("Cache-Control","max-age=0"); InputStream response = connection.getInputStream(); HttpURLConnection httpConnection = (HttpURLConnection) connection; int status = httpConnection.getResponseCode(); log.info("status="+status); for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { log.info(header.getKey() + "=" + header.getValue()); } String contentType = connection.getHeaderField("Content-Type"); for (String param : contentType.replace(" ", "").split(";")) { if (param.startsWith("charset=")) { charset = param.split("=", 2)[1]; break; } } if (charset != null) { try (BufferedReader reader = new BufferedReader(new InputStreamReader(response, charset))) { for (String line; (line = reader.readLine()) != null;) { log.info(line);; } } } log.info("response="+getStringFromInputStream(response)); }catch(Exception e){ log.error("error"); log.error(e); } } private static String getStringFromInputStream(InputStream is) { BufferedReader br = null; StringBuilder sb = new StringBuilder(); String line; try { br = new BufferedReader(new InputStreamReader(is)); while ((line = br.readLine()) != null) { sb.append(line); } } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } return sb.toString(); } public static void main(String [] args){ getCaptcha(); log.info("done"); } }
UTF-8
Java
3,005
java
AadharCardStatusCall.java
Java
[]
null
[]
package com.simplesarkar.web; import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.Map.Entry; import javax.imageio.ImageIO; import org.apache.log4j.Logger; public class AadharCardStatusCall { final static Logger log = Logger.getLogger(AadharCardStatusCall.class); public static void getCaptcha(){ String charset = null; try { String path = "captcha_image.jpeg"; URL url = new URL("https://indianvisaonline.gov.in/visa/Rimage.jsp"); BufferedImage image = ImageIO.read(url); ImageIO.write(image, "jpeg", new File(path)); URLConnection connection = url.openConnection(); connection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"); connection.setRequestProperty("Host", "indianvisaonline.gov.in" ); connection.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); connection.setRequestProperty("Accept-Language","en-US,en;q=0.5"); connection.setRequestProperty("Accept-Encoding","gzip,dflate,br"); connection.setRequestProperty("Connection","Keep-Alive"); connection.setRequestProperty("Cache-Control","max-age=0"); InputStream response = connection.getInputStream(); HttpURLConnection httpConnection = (HttpURLConnection) connection; int status = httpConnection.getResponseCode(); log.info("status="+status); for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { log.info(header.getKey() + "=" + header.getValue()); } String contentType = connection.getHeaderField("Content-Type"); for (String param : contentType.replace(" ", "").split(";")) { if (param.startsWith("charset=")) { charset = param.split("=", 2)[1]; break; } } if (charset != null) { try (BufferedReader reader = new BufferedReader(new InputStreamReader(response, charset))) { for (String line; (line = reader.readLine()) != null;) { log.info(line);; } } } log.info("response="+getStringFromInputStream(response)); }catch(Exception e){ log.error("error"); log.error(e); } } private static String getStringFromInputStream(InputStream is) { BufferedReader br = null; StringBuilder sb = new StringBuilder(); String line; try { br = new BufferedReader(new InputStreamReader(is)); while ((line = br.readLine()) != null) { sb.append(line); } } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } return sb.toString(); } public static void main(String [] args){ getCaptcha(); log.info("done"); } }
3,005
0.68619
0.675541
115
25.130434
27.671213
151
false
false
0
0
0
0
0
0
2.478261
false
false
10
e37c617c23a51d3cd62bca538b848351899ed9c0
4,552,665,389,169
823b5a98bd30101aa23a4b68a1f866d4868c8a09
/taskexecuter/src/main/java/org/myeducation/taskexecuter/core/processor/circuit/validator/users/ExistValidator.java
1c89668143fc5496d53b2859ed7a16a472887a7e
[]
no_license
avfrolov/myeducation
https://github.com/avfrolov/myeducation
722ea73f7a7bf5a203b7e06fca73c097071477d2
db9b0fdb689dfb166686ee62bca5c5b7c061ebec
refs/heads/master
2021-01-16T19:51:19.490000
2013-06-11T22:23:21
2013-06-11T22:23:21
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.myeducation.taskexecuter.core.processor.circuit.validator.users; import org.apache.commons.lang.StringUtils; import org.myeducation.taskexecuter.core.processor.circuit.jaxb.rules.Data; import org.myeducation.taskexecuter.core.processor.circuit.jaxb.rules.Rule; import org.myeducation.taskexecuter.core.processor.circuit.jaxb.scheme.*; import org.myeducation.taskexecuter.core.processor.circuit.validator.UserValidator; import java.util.List; /** * Created with IntelliJ IDEA. * User: andrey * Date: 11.05.13 * Time: 22:23 * To change this template use File | Settings | File Templates. */ public class ExistValidator implements UserValidator { @Override public boolean validate(Circuit circuit, Rule rule) { switch (rule.getSubtype()) { case NAME: return validateByName(circuit.getNode(), rule.getData()); case COUNT: return validateByCount(circuit.getNode(), rule.getData()); case VALUE: return validateByValue(circuit.getNode(), rule.getData()); default: throw new IllegalArgumentException("Rule subtype = " + rule.getSubtype() + " doesn't supported"); } } private boolean validateByName(List<Node> nodes, Data data) { if (StringUtils.isEmpty(data.getValue())) { return false; } for (Node node : nodes) { switch (data.getElement()) { case CAPACITOR: if (checkCollectionByName(node.getElements().getCapacitor(), data.getValue())) return true; break; case DIODE: if (checkCollectionByName(node.getElements().getDiode(), data.getValue())) return true; break; case INDUCTOR: if (checkCollectionByName(node.getElements().getInductor(), data.getValue())) return true; break; case RESISTOR: if (checkCollectionByName(node.getElements().getResistor(), data.getValue())) return true; break; case SWITCH: if (checkCollectionByName(node.getElements().getSwitch(), data.getValue())) return true; break; case TRANSISTOR: if (checkCollectionByName(node.getElements().getTransistor(), data.getValue())) return true; break; default: throw new IllegalArgumentException("ElementType = " + data.getElement() + "not supported"); } } return false; } private boolean validateByValue(List<Node> nodes, Data data) { double value = 0; try { value = Double.valueOf(data.getValue()); } catch (NumberFormatException nfe) { return false; } for (Node node : nodes) { switch (data.getElement()) { case CAPACITOR: for (Capacitor capacitor : node.getElements().getCapacitor()) { if (capacitor.getValue() == value) { return true; } } break; case DIODE: for (Diode diode : node.getElements().getDiode()) { if (diode.getMaxCurrent() == value || diode.getMaxPotential() == value) { return true; } } break; case INDUCTOR: for (Inductor inductor : node.getElements().getInductor()) { if (inductor.getValue() == value) { return true; } } break; case RESISTOR: for (Resistor resistor : node.getElements().getResistor()) { if (resistor.getValue() == value) { return true; } } break; case TRANSISTOR: for (Transistor transistor : node.getElements().getTransistor()) { if (transistor.getGain() == (int) value) { return true; } } break; case SWITCH: boolean en; try { en = Boolean.valueOf(data.getValue()); } catch (RuntimeException re) { return false; } for (Switch mSwitch : node.getElements().getSwitch()) { if (mSwitch.isEnabled() == en) { return true; } } break; default: throw new IllegalArgumentException("ElementType = " + data.getElement() + "not supported"); } } return false; } private boolean validateByCount(List<Node> nodes, Data data) { if (data == null) { return false; } try { Double.valueOf(data.getValue()); } catch (RuntimeException re) { return false; } int count = 0; for (Node node : nodes) { System.out.println("lol"); switch (data.getElement()) { case CAPACITOR: count += node.getElements().getCapacitor().size(); break; case DIODE: count += node.getElements().getDiode().size(); break; case INDUCTOR: count += node.getElements().getInductor().size(); break; case RESISTOR: count += node.getElements().getResistor().size(); break; case SWITCH: count += node.getElements().getSwitch().size(); break; case TRANSISTOR: count += node.getElements().getTransistor().size(); break; default: throw new IllegalArgumentException("ElementType = " + data.getElement() + "not supported"); } } return Integer.valueOf(data.getValue()) == count; } private boolean checkCollectionByName(List<? extends Element> elements, String name) { for (Element element : elements) { if (element.getName().equalsIgnoreCase(name)) { return true; } } return false; } }
UTF-8
Java
6,833
java
ExistValidator.java
Java
[ { "context": "List;\n\n/**\n * Created with IntelliJ IDEA.\n * User: andrey\n * Date: 11.05.13\n * Time: 22:23\n * To change thi", "end": 507, "score": 0.9588267803192139, "start": 501, "tag": "USERNAME", "value": "andrey" } ]
null
[]
package org.myeducation.taskexecuter.core.processor.circuit.validator.users; import org.apache.commons.lang.StringUtils; import org.myeducation.taskexecuter.core.processor.circuit.jaxb.rules.Data; import org.myeducation.taskexecuter.core.processor.circuit.jaxb.rules.Rule; import org.myeducation.taskexecuter.core.processor.circuit.jaxb.scheme.*; import org.myeducation.taskexecuter.core.processor.circuit.validator.UserValidator; import java.util.List; /** * Created with IntelliJ IDEA. * User: andrey * Date: 11.05.13 * Time: 22:23 * To change this template use File | Settings | File Templates. */ public class ExistValidator implements UserValidator { @Override public boolean validate(Circuit circuit, Rule rule) { switch (rule.getSubtype()) { case NAME: return validateByName(circuit.getNode(), rule.getData()); case COUNT: return validateByCount(circuit.getNode(), rule.getData()); case VALUE: return validateByValue(circuit.getNode(), rule.getData()); default: throw new IllegalArgumentException("Rule subtype = " + rule.getSubtype() + " doesn't supported"); } } private boolean validateByName(List<Node> nodes, Data data) { if (StringUtils.isEmpty(data.getValue())) { return false; } for (Node node : nodes) { switch (data.getElement()) { case CAPACITOR: if (checkCollectionByName(node.getElements().getCapacitor(), data.getValue())) return true; break; case DIODE: if (checkCollectionByName(node.getElements().getDiode(), data.getValue())) return true; break; case INDUCTOR: if (checkCollectionByName(node.getElements().getInductor(), data.getValue())) return true; break; case RESISTOR: if (checkCollectionByName(node.getElements().getResistor(), data.getValue())) return true; break; case SWITCH: if (checkCollectionByName(node.getElements().getSwitch(), data.getValue())) return true; break; case TRANSISTOR: if (checkCollectionByName(node.getElements().getTransistor(), data.getValue())) return true; break; default: throw new IllegalArgumentException("ElementType = " + data.getElement() + "not supported"); } } return false; } private boolean validateByValue(List<Node> nodes, Data data) { double value = 0; try { value = Double.valueOf(data.getValue()); } catch (NumberFormatException nfe) { return false; } for (Node node : nodes) { switch (data.getElement()) { case CAPACITOR: for (Capacitor capacitor : node.getElements().getCapacitor()) { if (capacitor.getValue() == value) { return true; } } break; case DIODE: for (Diode diode : node.getElements().getDiode()) { if (diode.getMaxCurrent() == value || diode.getMaxPotential() == value) { return true; } } break; case INDUCTOR: for (Inductor inductor : node.getElements().getInductor()) { if (inductor.getValue() == value) { return true; } } break; case RESISTOR: for (Resistor resistor : node.getElements().getResistor()) { if (resistor.getValue() == value) { return true; } } break; case TRANSISTOR: for (Transistor transistor : node.getElements().getTransistor()) { if (transistor.getGain() == (int) value) { return true; } } break; case SWITCH: boolean en; try { en = Boolean.valueOf(data.getValue()); } catch (RuntimeException re) { return false; } for (Switch mSwitch : node.getElements().getSwitch()) { if (mSwitch.isEnabled() == en) { return true; } } break; default: throw new IllegalArgumentException("ElementType = " + data.getElement() + "not supported"); } } return false; } private boolean validateByCount(List<Node> nodes, Data data) { if (data == null) { return false; } try { Double.valueOf(data.getValue()); } catch (RuntimeException re) { return false; } int count = 0; for (Node node : nodes) { System.out.println("lol"); switch (data.getElement()) { case CAPACITOR: count += node.getElements().getCapacitor().size(); break; case DIODE: count += node.getElements().getDiode().size(); break; case INDUCTOR: count += node.getElements().getInductor().size(); break; case RESISTOR: count += node.getElements().getResistor().size(); break; case SWITCH: count += node.getElements().getSwitch().size(); break; case TRANSISTOR: count += node.getElements().getTransistor().size(); break; default: throw new IllegalArgumentException("ElementType = " + data.getElement() + "not supported"); } } return Integer.valueOf(data.getValue()) == count; } private boolean checkCollectionByName(List<? extends Element> elements, String name) { for (Element element : elements) { if (element.getName().equalsIgnoreCase(name)) { return true; } } return false; } }
6,833
0.480316
0.47856
182
36.543957
28.653591
113
false
false
0
0
0
0
0
0
0.467033
false
false
10
d871daeea1675ad78968d941b5cc5ffb6cee4079
21,973,052,756,879
431a2e0e9188ba493c6073a2b7a0e40c0031af20
/service-v1/src/main/java/com/mwz/v1/controller/UserController.java
d42f5a26ca9e13fb4aeef1f6275bed5d33d906fb
[]
no_license
mwzgithub/spring-cloud
https://github.com/mwzgithub/spring-cloud
5cda119d99615e4ca5ff178120aa05fc702d184a
9e30a4ce8177581aa4a0cc1876cc7483fe0d3984
refs/heads/master
2021-01-14T07:23:08.170000
2020-11-01T06:08:38
2020-11-01T06:08:38
242,638,345
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mwz.v1.controller; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.mwz.v1.service.IUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; /** * <p> * 前端控制器 * </p> * * @author mwz * @since 2020-02-24 */ @RestController @RequestMapping("/v1/user") public class UserController { @Autowired private IUserService IUserService; @GetMapping("/list") public ResponseEntity<Object> list() { return new ResponseEntity<>(IUserService.list(), HttpStatus.OK); } }
UTF-8
Java
877
java
UserController.java
Java
[ { "context": "Valid;\n\n/**\n * <p>\n * 前端控制器\n * </p>\n *\n * @author mwz\n * @since 2020-02-24\n */\n@RestController\n@Request", "end": 560, "score": 0.9996523857116699, "start": 557, "tag": "USERNAME", "value": "mwz" } ]
null
[]
package com.mwz.v1.controller; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.mwz.v1.service.IUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; /** * <p> * 前端控制器 * </p> * * @author mwz * @since 2020-02-24 */ @RestController @RequestMapping("/v1/user") public class UserController { @Autowired private IUserService IUserService; @GetMapping("/list") public ResponseEntity<Object> list() { return new ResponseEntity<>(IUserService.list(), HttpStatus.OK); } }
877
0.762399
0.749712
37
22.432432
23.121933
72
false
false
0
0
0
0
0
0
0.351351
false
false
10
bf8605627d3d563636ba6cca497de4378a8a7282
15,427,522,535,511
5f209db3d0e4ded90aff6c2ca55a53aa698cdef5
/src/com/yurwar/view/View.java
e0043930cda843db1ecdc849f65caa1b2c148cfb
[]
no_license
Yurwar/hello-world-mvc
https://github.com/Yurwar/hello-world-mvc
c9639817d9464f0fa9236896753533b922d2be19
96cfe74e1e6531b5b16efec3dc9ff5c1485715c3
refs/heads/master
2020-05-29T18:40:00.544000
2019-05-29T06:47:52
2019-05-29T06:50:17
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yurwar.view; public class View { public static final String INCORRECT_INPUT = "Incorrect input, please repeat."; public static final String USER_INPUT_WORD = "Your word is: "; public static final String ENTER_WORD = "Enter the word "; public static final String USAGE = "Usage: Enter given words to get their concatenation"; public void printMessage(String message) { System.out.println(message); } }
UTF-8
Java
447
java
View.java
Java
[]
null
[]
package com.yurwar.view; public class View { public static final String INCORRECT_INPUT = "Incorrect input, please repeat."; public static final String USER_INPUT_WORD = "Your word is: "; public static final String ENTER_WORD = "Enter the word "; public static final String USAGE = "Usage: Enter given words to get their concatenation"; public void printMessage(String message) { System.out.println(message); } }
447
0.709172
0.709172
12
36.25
32.073158
93
false
false
0
0
0
0
0
0
0.583333
false
false
10
58297512469c3a583b3e52ad341a9e04191c7311
21,517,786,159,348
7b8869b3c8dc94f662ecfc06a1d4f628b4f7b391
/GeoQuiz/app/src/main/java/com/daveshah/geoquiz/QuestionBank.java
d05df355a500b9d4b770f16719e20a426f324123
[]
no_license
Cleveland-Android-Group/android-101-workshops
https://github.com/Cleveland-Android-Group/android-101-workshops
de1ad6be182537a16fa001e0529766bdeb4b7409
dba4ea79dd1d6a8243177321f412a56e2820ddac
refs/heads/master
2021-01-10T20:49:40.970000
2015-05-21T01:35:27
2015-05-21T01:35:27
32,902,370
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.daveshah.geoquiz; import android.content.Context; import java.util.Arrays; import java.util.List; public class QuestionBank { private final Context context; private final List<TrueFalse> questions; public QuestionBank(Context context) { this.context = context; this.questions = Arrays.asList( new TrueFalse(context.getString(R.string.question_oceans), true), new TrueFalse(context.getString(R.string.question_mideast), false), new TrueFalse(context.getString(R.string.question_java), true), new TrueFalse(context.getString(R.string.question_monkey), false), new TrueFalse(context.getString(R.string.question_quest), true), new TrueFalse(context.getString(R.string.question_assyria), false) ); } public TrueFalse questionNumber(int i) { try { return questions.get(i); } catch (IndexOutOfBoundsException e) { return null; } } public int getQuestionCount() { return questions.size(); } }
UTF-8
Java
1,113
java
QuestionBank.java
Java
[]
null
[]
package com.daveshah.geoquiz; import android.content.Context; import java.util.Arrays; import java.util.List; public class QuestionBank { private final Context context; private final List<TrueFalse> questions; public QuestionBank(Context context) { this.context = context; this.questions = Arrays.asList( new TrueFalse(context.getString(R.string.question_oceans), true), new TrueFalse(context.getString(R.string.question_mideast), false), new TrueFalse(context.getString(R.string.question_java), true), new TrueFalse(context.getString(R.string.question_monkey), false), new TrueFalse(context.getString(R.string.question_quest), true), new TrueFalse(context.getString(R.string.question_assyria), false) ); } public TrueFalse questionNumber(int i) { try { return questions.get(i); } catch (IndexOutOfBoundsException e) { return null; } } public int getQuestionCount() { return questions.size(); } }
1,113
0.636119
0.636119
37
29.081081
27.444666
83
false
false
0
0
0
0
0
0
0.594595
false
false
10
9b9973d4aee6a87c6040fa3b49b28e50294ba220
28,278,064,684,449
ead5a617b23c541865a6b57cf8cffcc1137352f2
/decompiled/sources/com/fasterxml/jackson/core/p116io/JsonStringEncoder.java
b701b8954b90eec78237f995965f85e29df5ed4b
[]
no_license
erred/uva-ssn
https://github.com/erred/uva-ssn
73a6392a096b38c092482113e322fdbf9c3c4c0e
4fb8ea447766a735289b96e2510f5a8d93345a8c
refs/heads/master
2022-02-26T20:52:50.515000
2019-10-14T12:30:33
2019-10-14T12:30:33
210,376,140
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.fasterxml.jackson.core.p116io; import com.fasterxml.jackson.core.util.BufferRecycler; import com.fasterxml.jackson.core.util.ByteArrayBuilder; import com.fasterxml.jackson.core.util.TextBuffer; import java.lang.ref.SoftReference; /* renamed from: com.fasterxml.jackson.core.io.JsonStringEncoder */ public final class JsonStringEncoder { /* renamed from: HB */ private static final byte[] f6137HB = CharTypes.copyHexBytes(); /* renamed from: HC */ private static final char[] f6138HC = CharTypes.copyHexChars(); private static final int SURR1_FIRST = 55296; private static final int SURR1_LAST = 56319; private static final int SURR2_FIRST = 56320; private static final int SURR2_LAST = 57343; protected static final ThreadLocal<SoftReference<JsonStringEncoder>> _threadEncoder = new ThreadLocal<>(); protected ByteArrayBuilder _bytes; protected final char[] _qbuf = new char[6]; protected TextBuffer _text; public JsonStringEncoder() { this._qbuf[0] = '\\'; this._qbuf[2] = '0'; this._qbuf[3] = '0'; } public static JsonStringEncoder getInstance() { JsonStringEncoder jsonStringEncoder; SoftReference softReference = (SoftReference) _threadEncoder.get(); if (softReference == null) { jsonStringEncoder = null; } else { jsonStringEncoder = (JsonStringEncoder) softReference.get(); } if (jsonStringEncoder != null) { return jsonStringEncoder; } JsonStringEncoder jsonStringEncoder2 = new JsonStringEncoder(); _threadEncoder.set(new SoftReference(jsonStringEncoder2)); return jsonStringEncoder2; } /* JADX WARNING: Code restructure failed: missing block: B:10:0x0031, code lost: if (r9 >= 0) goto L_0x003a; */ /* JADX WARNING: Code restructure failed: missing block: B:11:0x0033, code lost: r1 = _appendNumeric(r1, r11._qbuf); */ /* JADX WARNING: Code restructure failed: missing block: B:12:0x003a, code lost: r1 = _appendNamed(r9, r11._qbuf); */ /* JADX WARNING: Code restructure failed: missing block: B:13:0x0040, code lost: r9 = r6 + r1; */ /* JADX WARNING: Code restructure failed: missing block: B:14:0x0043, code lost: if (r9 <= r7.length) goto L_0x005b; */ /* JADX WARNING: Code restructure failed: missing block: B:15:0x0045, code lost: r9 = r7.length - r6; */ /* JADX WARNING: Code restructure failed: missing block: B:16:0x0047, code lost: if (r9 <= 0) goto L_0x004e; */ /* JADX WARNING: Code restructure failed: missing block: B:17:0x0049, code lost: java.lang.System.arraycopy(r11._qbuf, 0, r7, r6, r9); */ /* JADX WARNING: Code restructure failed: missing block: B:18:0x004e, code lost: r6 = r0.finishCurrentSegment(); r1 = r1 - r9; java.lang.System.arraycopy(r11._qbuf, r9, r6, 0, r1); r7 = r6; r6 = r1; */ /* JADX WARNING: Code restructure failed: missing block: B:19:0x005b, code lost: java.lang.System.arraycopy(r11._qbuf, 0, r7, r6, r1); r6 = r9; */ /* JADX WARNING: Code restructure failed: missing block: B:9:0x0029, code lost: r8 = r1 + 1; r1 = r12.charAt(r1); r9 = r2[r1]; */ /* Code decompiled incorrectly, please refer to instructions dump. */ public char[] quoteAsString(java.lang.String r12) { /* r11 = this; com.fasterxml.jackson.core.util.TextBuffer r0 = r11._text if (r0 != 0) goto L_0x000c com.fasterxml.jackson.core.util.TextBuffer r0 = new com.fasterxml.jackson.core.util.TextBuffer r1 = 0 r0.<init>(r1) r11._text = r0 L_0x000c: char[] r1 = r0.emptyAndGetCurrentSegment() int[] r2 = com.fasterxml.jackson.core.p116io.CharTypes.get7BitOutputEscapes() int r3 = r2.length int r4 = r12.length() r5 = 0 r7 = r1 r1 = 0 r6 = 0 L_0x001d: if (r1 >= r4) goto L_0x0078 L_0x001f: char r8 = r12.charAt(r1) if (r8 >= r3) goto L_0x0063 r9 = r2[r8] if (r9 == 0) goto L_0x0063 int r8 = r1 + 1 char r1 = r12.charAt(r1) r9 = r2[r1] if (r9 >= 0) goto L_0x003a char[] r9 = r11._qbuf int r1 = r11._appendNumeric(r1, r9) goto L_0x0040 L_0x003a: char[] r1 = r11._qbuf int r1 = r11._appendNamed(r9, r1) L_0x0040: int r9 = r6 + r1 int r10 = r7.length if (r9 <= r10) goto L_0x005b int r9 = r7.length int r9 = r9 - r6 if (r9 <= 0) goto L_0x004e char[] r10 = r11._qbuf java.lang.System.arraycopy(r10, r5, r7, r6, r9) L_0x004e: char[] r6 = r0.finishCurrentSegment() int r1 = r1 - r9 char[] r7 = r11._qbuf java.lang.System.arraycopy(r7, r9, r6, r5, r1) r7 = r6 r6 = r1 goto L_0x0061 L_0x005b: char[] r10 = r11._qbuf java.lang.System.arraycopy(r10, r5, r7, r6, r1) r6 = r9 L_0x0061: r1 = r8 goto L_0x001d L_0x0063: int r9 = r7.length if (r6 < r9) goto L_0x006c char[] r6 = r0.finishCurrentSegment() r7 = r6 r6 = 0 L_0x006c: int r9 = r6 + 1 r7[r6] = r8 int r1 = r1 + 1 if (r1 < r4) goto L_0x0076 r6 = r9 goto L_0x0078 L_0x0076: r6 = r9 goto L_0x001f L_0x0078: r0.setCurrentLength(r6) char[] r12 = r0.contentsAsArray() return r12 */ throw new UnsupportedOperationException("Method not decompiled: com.fasterxml.jackson.core.p116io.JsonStringEncoder.quoteAsString(java.lang.String):char[]"); } /* JADX WARNING: Code restructure failed: missing block: B:10:0x002e, code lost: r9.append(r7._qbuf, 0, r4); r4 = r5; */ /* JADX WARNING: Code restructure failed: missing block: B:6:0x0017, code lost: r5 = r4 + 1; r4 = r8.charAt(r4); r6 = r0[r4]; */ /* JADX WARNING: Code restructure failed: missing block: B:7:0x001f, code lost: if (r6 >= 0) goto L_0x0028; */ /* JADX WARNING: Code restructure failed: missing block: B:8:0x0021, code lost: r4 = _appendNumeric(r4, r7._qbuf); */ /* JADX WARNING: Code restructure failed: missing block: B:9:0x0028, code lost: r4 = _appendNamed(r6, r7._qbuf); */ /* Code decompiled incorrectly, please refer to instructions dump. */ public void quoteAsString(java.lang.CharSequence r8, java.lang.StringBuilder r9) { /* r7 = this; int[] r0 = com.fasterxml.jackson.core.p116io.CharTypes.get7BitOutputEscapes() int r1 = r0.length int r2 = r8.length() r3 = 0 r4 = 0 L_0x000b: if (r4 >= r2) goto L_0x003c L_0x000d: char r5 = r8.charAt(r4) if (r5 >= r1) goto L_0x0035 r6 = r0[r5] if (r6 == 0) goto L_0x0035 int r5 = r4 + 1 char r4 = r8.charAt(r4) r6 = r0[r4] if (r6 >= 0) goto L_0x0028 char[] r6 = r7._qbuf int r4 = r7._appendNumeric(r4, r6) goto L_0x002e L_0x0028: char[] r4 = r7._qbuf int r4 = r7._appendNamed(r6, r4) L_0x002e: char[] r6 = r7._qbuf r9.append(r6, r3, r4) r4 = r5 goto L_0x000b L_0x0035: r9.append(r5) int r4 = r4 + 1 if (r4 < r2) goto L_0x000d L_0x003c: return */ throw new UnsupportedOperationException("Method not decompiled: com.fasterxml.jackson.core.p116io.JsonStringEncoder.quoteAsString(java.lang.CharSequence, java.lang.StringBuilder):void"); } /* JADX WARNING: Code restructure failed: missing block: B:18:0x0043, code lost: if (r4 < r5.length) goto L_0x004a; */ /* JADX WARNING: Code restructure failed: missing block: B:19:0x0045, code lost: r5 = r0.finishCurrentSegment(); r4 = 0; */ /* JADX WARNING: Code restructure failed: missing block: B:20:0x004a, code lost: r7 = r2 + 1; r2 = r11.charAt(r2); */ /* JADX WARNING: Code restructure failed: missing block: B:21:0x0050, code lost: if (r2 > 127) goto L_0x005e; */ /* JADX WARNING: Code restructure failed: missing block: B:22:0x0052, code lost: r4 = _appendByte(r2, r6[r2], r0, r4); r5 = r0.getCurrentSegment(); */ /* JADX WARNING: Code restructure failed: missing block: B:25:0x0060, code lost: if (r2 > 2047) goto L_0x0072; */ /* JADX WARNING: Code restructure failed: missing block: B:26:0x0062, code lost: r6 = r4 + 1; r5[r4] = (byte) ((r2 >> 6) | 192); r2 = (r2 & '?') | 128; r4 = r6; */ /* JADX WARNING: Code restructure failed: missing block: B:28:0x0075, code lost: if (r2 < 55296) goto L_0x00d3; */ /* JADX WARNING: Code restructure failed: missing block: B:30:0x007a, code lost: if (r2 <= 57343) goto L_0x007d; */ /* JADX WARNING: Code restructure failed: missing block: B:32:0x0080, code lost: if (r2 <= 56319) goto L_0x0085; */ /* JADX WARNING: Code restructure failed: missing block: B:33:0x0082, code lost: _illegal(r2); */ /* JADX WARNING: Code restructure failed: missing block: B:34:0x0085, code lost: if (r7 < r1) goto L_0x008a; */ /* JADX WARNING: Code restructure failed: missing block: B:35:0x0087, code lost: _illegal(r2); */ /* JADX WARNING: Code restructure failed: missing block: B:36:0x008a, code lost: r6 = r7 + 1; r2 = _convert(r2, r11.charAt(r7)); */ /* JADX WARNING: Code restructure failed: missing block: B:37:0x0097, code lost: if (r2 <= 1114111) goto L_0x009c; */ /* JADX WARNING: Code restructure failed: missing block: B:38:0x0099, code lost: _illegal(r2); */ /* JADX WARNING: Code restructure failed: missing block: B:39:0x009c, code lost: r7 = r4 + 1; r5[r4] = (byte) ((r2 >> 18) | 240); */ /* JADX WARNING: Code restructure failed: missing block: B:40:0x00a6, code lost: if (r7 < r5.length) goto L_0x00ad; */ /* JADX WARNING: Code restructure failed: missing block: B:41:0x00a8, code lost: r5 = r0.finishCurrentSegment(); r7 = 0; */ /* JADX WARNING: Code restructure failed: missing block: B:42:0x00ad, code lost: r4 = r7 + 1; r5[r7] = (byte) (((r2 >> 12) & 63) | 128); */ /* JADX WARNING: Code restructure failed: missing block: B:43:0x00b9, code lost: if (r4 < r5.length) goto L_0x00c1; */ /* JADX WARNING: Code restructure failed: missing block: B:44:0x00bb, code lost: r5 = r0.finishCurrentSegment(); r4 = 0; */ /* JADX WARNING: Code restructure failed: missing block: B:45:0x00c1, code lost: r7 = r4 + 1; r5[r4] = (byte) (((r2 >> 6) & 63) | 128); r2 = (r2 & '?') | 128; r4 = r7; r7 = r6; */ /* JADX WARNING: Code restructure failed: missing block: B:46:0x00d3, code lost: r6 = r4 + 1; r5[r4] = (byte) ((r2 >> 12) | 224); */ /* JADX WARNING: Code restructure failed: missing block: B:47:0x00dd, code lost: if (r6 < r5.length) goto L_0x00e4; */ /* JADX WARNING: Code restructure failed: missing block: B:48:0x00df, code lost: r5 = r0.finishCurrentSegment(); r6 = 0; */ /* JADX WARNING: Code restructure failed: missing block: B:49:0x00e4, code lost: r4 = r6 + 1; r5[r6] = (byte) (((r2 >> 6) & 63) | 128); r2 = (r2 & '?') | 128; */ /* JADX WARNING: Code restructure failed: missing block: B:51:0x00f4, code lost: if (r4 < r5.length) goto L_0x00fc; */ /* JADX WARNING: Code restructure failed: missing block: B:52:0x00f6, code lost: r5 = r0.finishCurrentSegment(); r4 = 0; */ /* JADX WARNING: Code restructure failed: missing block: B:53:0x00fc, code lost: r6 = r4 + 1; r5[r4] = (byte) r2; r4 = r6; */ /* Code decompiled incorrectly, please refer to instructions dump. */ public byte[] quoteAsUTF8(java.lang.String r11) { /* r10 = this; com.fasterxml.jackson.core.util.ByteArrayBuilder r0 = r10._bytes if (r0 != 0) goto L_0x000c com.fasterxml.jackson.core.util.ByteArrayBuilder r0 = new com.fasterxml.jackson.core.util.ByteArrayBuilder r1 = 0 r0.<init>(r1) r10._bytes = r0 L_0x000c: int r1 = r11.length() byte[] r2 = r0.resetAndGetFirstSegment() r3 = 0 r5 = r2 r2 = 0 r4 = 0 L_0x0018: if (r2 >= r1) goto L_0x0104 int[] r6 = com.fasterxml.jackson.core.p116io.CharTypes.get7BitOutputEscapes() L_0x001e: char r7 = r11.charAt(r2) r8 = 127(0x7f, float:1.78E-43) if (r7 > r8) goto L_0x0042 r9 = r6[r7] if (r9 == 0) goto L_0x002b goto L_0x0042 L_0x002b: int r8 = r5.length if (r4 < r8) goto L_0x0034 byte[] r4 = r0.finishCurrentSegment() r5 = r4 r4 = 0 L_0x0034: int r8 = r4 + 1 byte r7 = (byte) r7 r5[r4] = r7 int r2 = r2 + 1 if (r2 < r1) goto L_0x0040 r4 = r8 goto L_0x0104 L_0x0040: r4 = r8 goto L_0x001e L_0x0042: int r7 = r5.length if (r4 < r7) goto L_0x004a byte[] r5 = r0.finishCurrentSegment() r4 = 0 L_0x004a: int r7 = r2 + 1 char r2 = r11.charAt(r2) if (r2 > r8) goto L_0x005e r5 = r6[r2] int r4 = r10._appendByte(r2, r5, r0, r4) byte[] r5 = r0.getCurrentSegment() L_0x005c: r2 = r7 goto L_0x0018 L_0x005e: r6 = 2047(0x7ff, float:2.868E-42) if (r2 > r6) goto L_0x0072 int r6 = r4 + 1 int r8 = r2 >> 6 r8 = r8 | 192(0xc0, float:2.69E-43) byte r8 = (byte) r8 r5[r4] = r8 r2 = r2 & 63 r2 = r2 | 128(0x80, float:1.794E-43) r4 = r6 goto L_0x00f3 L_0x0072: r6 = 55296(0xd800, float:7.7486E-41) if (r2 < r6) goto L_0x00d3 r6 = 57343(0xdfff, float:8.0355E-41) if (r2 <= r6) goto L_0x007d goto L_0x00d3 L_0x007d: r6 = 56319(0xdbff, float:7.892E-41) if (r2 <= r6) goto L_0x0085 _illegal(r2) L_0x0085: if (r7 < r1) goto L_0x008a _illegal(r2) L_0x008a: int r6 = r7 + 1 char r7 = r11.charAt(r7) int r2 = _convert(r2, r7) r7 = 1114111(0x10ffff, float:1.561202E-39) if (r2 <= r7) goto L_0x009c _illegal(r2) L_0x009c: int r7 = r4 + 1 int r8 = r2 >> 18 r8 = r8 | 240(0xf0, float:3.36E-43) byte r8 = (byte) r8 r5[r4] = r8 int r4 = r5.length if (r7 < r4) goto L_0x00ad byte[] r5 = r0.finishCurrentSegment() r7 = 0 L_0x00ad: int r4 = r7 + 1 int r8 = r2 >> 12 r8 = r8 & 63 r8 = r8 | 128(0x80, float:1.794E-43) byte r8 = (byte) r8 r5[r7] = r8 int r7 = r5.length if (r4 < r7) goto L_0x00c1 byte[] r4 = r0.finishCurrentSegment() r5 = r4 r4 = 0 L_0x00c1: int r7 = r4 + 1 int r8 = r2 >> 6 r8 = r8 & 63 r8 = r8 | 128(0x80, float:1.794E-43) byte r8 = (byte) r8 r5[r4] = r8 r2 = r2 & 63 r2 = r2 | 128(0x80, float:1.794E-43) r4 = r7 r7 = r6 goto L_0x00f3 L_0x00d3: int r6 = r4 + 1 int r8 = r2 >> 12 r8 = r8 | 224(0xe0, float:3.14E-43) byte r8 = (byte) r8 r5[r4] = r8 int r4 = r5.length if (r6 < r4) goto L_0x00e4 byte[] r5 = r0.finishCurrentSegment() r6 = 0 L_0x00e4: int r4 = r6 + 1 int r8 = r2 >> 6 r8 = r8 & 63 r8 = r8 | 128(0x80, float:1.794E-43) byte r8 = (byte) r8 r5[r6] = r8 r2 = r2 & 63 r2 = r2 | 128(0x80, float:1.794E-43) L_0x00f3: int r6 = r5.length if (r4 < r6) goto L_0x00fc byte[] r4 = r0.finishCurrentSegment() r5 = r4 r4 = 0 L_0x00fc: int r6 = r4 + 1 byte r2 = (byte) r2 r5[r4] = r2 r4 = r6 goto L_0x005c L_0x0104: com.fasterxml.jackson.core.util.ByteArrayBuilder r11 = r10._bytes byte[] r11 = r11.completeAndCoalesce(r4) return r11 */ throw new UnsupportedOperationException("Method not decompiled: com.fasterxml.jackson.core.p116io.JsonStringEncoder.quoteAsUTF8(java.lang.String):byte[]"); } public byte[] encodeAsUTF8(String str) { int i; ByteArrayBuilder byteArrayBuilder = this._bytes; if (byteArrayBuilder == null) { byteArrayBuilder = new ByteArrayBuilder((BufferRecycler) null); this._bytes = byteArrayBuilder; } int length = str.length(); byte[] resetAndGetFirstSegment = byteArrayBuilder.resetAndGetFirstSegment(); byte[] bArr = resetAndGetFirstSegment; int length2 = resetAndGetFirstSegment.length; int i2 = 0; int i3 = 0; loop0: while (true) { if (i2 >= length) { break; } int i4 = i2 + 1; int charAt = str.charAt(i2); while (charAt <= 127) { if (i3 >= length2) { byte[] finishCurrentSegment = byteArrayBuilder.finishCurrentSegment(); length2 = finishCurrentSegment.length; bArr = finishCurrentSegment; i3 = 0; } int i5 = i3 + 1; bArr[i3] = (byte) charAt; if (i4 >= length) { i3 = i5; break loop0; } int i6 = i4 + 1; int charAt2 = str.charAt(i4); i4 = i6; charAt = charAt2; i3 = i5; } if (i3 >= length2) { bArr = byteArrayBuilder.finishCurrentSegment(); length2 = bArr.length; i3 = 0; } if (charAt < 2048) { int i7 = i3 + 1; bArr[i3] = (byte) ((charAt >> 6) | 192); i = i7; } else if (charAt < 55296 || charAt > 57343) { int i8 = i3 + 1; bArr[i3] = (byte) ((charAt >> 12) | 224); if (i8 >= length2) { bArr = byteArrayBuilder.finishCurrentSegment(); length2 = bArr.length; i8 = 0; } i = i8 + 1; bArr[i8] = (byte) (((charAt >> 6) & 63) | 128); } else { if (charAt > 56319) { _illegal(charAt); } if (i4 >= length) { _illegal(charAt); } int i9 = i4 + 1; charAt = _convert(charAt, str.charAt(i4)); if (charAt > 1114111) { _illegal(charAt); } int i10 = i3 + 1; bArr[i3] = (byte) ((charAt >> 18) | 240); if (i10 >= length2) { bArr = byteArrayBuilder.finishCurrentSegment(); length2 = bArr.length; i10 = 0; } int i11 = i10 + 1; bArr[i10] = (byte) (((charAt >> 12) & 63) | 128); if (i11 >= length2) { byte[] finishCurrentSegment2 = byteArrayBuilder.finishCurrentSegment(); length2 = finishCurrentSegment2.length; bArr = finishCurrentSegment2; i11 = 0; } int i12 = i11 + 1; bArr[i11] = (byte) (((charAt >> 6) & 63) | 128); i = i12; i4 = i9; } if (i >= length2) { byte[] finishCurrentSegment3 = byteArrayBuilder.finishCurrentSegment(); length2 = finishCurrentSegment3.length; bArr = finishCurrentSegment3; i = 0; } int i13 = i + 1; bArr[i] = (byte) ((charAt & 63) | 128); i2 = i4; i3 = i13; } return this._bytes.completeAndCoalesce(i3); } private int _appendNumeric(int i, char[] cArr) { cArr[1] = 'u'; cArr[4] = f6138HC[i >> 4]; cArr[5] = f6138HC[i & 15]; return 6; } private int _appendNamed(int i, char[] cArr) { cArr[1] = (char) i; return 2; } private int _appendByte(int i, int i2, ByteArrayBuilder byteArrayBuilder, int i3) { byteArrayBuilder.setCurrentSegmentLength(i3); byteArrayBuilder.append(92); if (i2 < 0) { byteArrayBuilder.append(117); if (i > 255) { int i4 = i >> 8; byteArrayBuilder.append(f6137HB[i4 >> 4]); byteArrayBuilder.append(f6137HB[i4 & 15]); i &= 255; } else { byteArrayBuilder.append(48); byteArrayBuilder.append(48); } byteArrayBuilder.append(f6137HB[i >> 4]); byteArrayBuilder.append(f6137HB[i & 15]); } else { byteArrayBuilder.append((byte) i2); } return byteArrayBuilder.getCurrentSegmentLength(); } private static int _convert(int i, int i2) { if (i2 >= 56320 && i2 <= 57343) { return ((i - 55296) << 10) + 65536 + (i2 - 56320); } StringBuilder sb = new StringBuilder(); sb.append("Broken surrogate pair: first char 0x"); sb.append(Integer.toHexString(i)); sb.append(", second 0x"); sb.append(Integer.toHexString(i2)); sb.append("; illegal combination"); throw new IllegalArgumentException(sb.toString()); } private static void _illegal(int i) { throw new IllegalArgumentException(UTF8Writer.illegalSurrogateDesc(i)); } }
UTF-8
Java
23,632
java
JsonStringEncoder.java
Java
[]
null
[]
package com.fasterxml.jackson.core.p116io; import com.fasterxml.jackson.core.util.BufferRecycler; import com.fasterxml.jackson.core.util.ByteArrayBuilder; import com.fasterxml.jackson.core.util.TextBuffer; import java.lang.ref.SoftReference; /* renamed from: com.fasterxml.jackson.core.io.JsonStringEncoder */ public final class JsonStringEncoder { /* renamed from: HB */ private static final byte[] f6137HB = CharTypes.copyHexBytes(); /* renamed from: HC */ private static final char[] f6138HC = CharTypes.copyHexChars(); private static final int SURR1_FIRST = 55296; private static final int SURR1_LAST = 56319; private static final int SURR2_FIRST = 56320; private static final int SURR2_LAST = 57343; protected static final ThreadLocal<SoftReference<JsonStringEncoder>> _threadEncoder = new ThreadLocal<>(); protected ByteArrayBuilder _bytes; protected final char[] _qbuf = new char[6]; protected TextBuffer _text; public JsonStringEncoder() { this._qbuf[0] = '\\'; this._qbuf[2] = '0'; this._qbuf[3] = '0'; } public static JsonStringEncoder getInstance() { JsonStringEncoder jsonStringEncoder; SoftReference softReference = (SoftReference) _threadEncoder.get(); if (softReference == null) { jsonStringEncoder = null; } else { jsonStringEncoder = (JsonStringEncoder) softReference.get(); } if (jsonStringEncoder != null) { return jsonStringEncoder; } JsonStringEncoder jsonStringEncoder2 = new JsonStringEncoder(); _threadEncoder.set(new SoftReference(jsonStringEncoder2)); return jsonStringEncoder2; } /* JADX WARNING: Code restructure failed: missing block: B:10:0x0031, code lost: if (r9 >= 0) goto L_0x003a; */ /* JADX WARNING: Code restructure failed: missing block: B:11:0x0033, code lost: r1 = _appendNumeric(r1, r11._qbuf); */ /* JADX WARNING: Code restructure failed: missing block: B:12:0x003a, code lost: r1 = _appendNamed(r9, r11._qbuf); */ /* JADX WARNING: Code restructure failed: missing block: B:13:0x0040, code lost: r9 = r6 + r1; */ /* JADX WARNING: Code restructure failed: missing block: B:14:0x0043, code lost: if (r9 <= r7.length) goto L_0x005b; */ /* JADX WARNING: Code restructure failed: missing block: B:15:0x0045, code lost: r9 = r7.length - r6; */ /* JADX WARNING: Code restructure failed: missing block: B:16:0x0047, code lost: if (r9 <= 0) goto L_0x004e; */ /* JADX WARNING: Code restructure failed: missing block: B:17:0x0049, code lost: java.lang.System.arraycopy(r11._qbuf, 0, r7, r6, r9); */ /* JADX WARNING: Code restructure failed: missing block: B:18:0x004e, code lost: r6 = r0.finishCurrentSegment(); r1 = r1 - r9; java.lang.System.arraycopy(r11._qbuf, r9, r6, 0, r1); r7 = r6; r6 = r1; */ /* JADX WARNING: Code restructure failed: missing block: B:19:0x005b, code lost: java.lang.System.arraycopy(r11._qbuf, 0, r7, r6, r1); r6 = r9; */ /* JADX WARNING: Code restructure failed: missing block: B:9:0x0029, code lost: r8 = r1 + 1; r1 = r12.charAt(r1); r9 = r2[r1]; */ /* Code decompiled incorrectly, please refer to instructions dump. */ public char[] quoteAsString(java.lang.String r12) { /* r11 = this; com.fasterxml.jackson.core.util.TextBuffer r0 = r11._text if (r0 != 0) goto L_0x000c com.fasterxml.jackson.core.util.TextBuffer r0 = new com.fasterxml.jackson.core.util.TextBuffer r1 = 0 r0.<init>(r1) r11._text = r0 L_0x000c: char[] r1 = r0.emptyAndGetCurrentSegment() int[] r2 = com.fasterxml.jackson.core.p116io.CharTypes.get7BitOutputEscapes() int r3 = r2.length int r4 = r12.length() r5 = 0 r7 = r1 r1 = 0 r6 = 0 L_0x001d: if (r1 >= r4) goto L_0x0078 L_0x001f: char r8 = r12.charAt(r1) if (r8 >= r3) goto L_0x0063 r9 = r2[r8] if (r9 == 0) goto L_0x0063 int r8 = r1 + 1 char r1 = r12.charAt(r1) r9 = r2[r1] if (r9 >= 0) goto L_0x003a char[] r9 = r11._qbuf int r1 = r11._appendNumeric(r1, r9) goto L_0x0040 L_0x003a: char[] r1 = r11._qbuf int r1 = r11._appendNamed(r9, r1) L_0x0040: int r9 = r6 + r1 int r10 = r7.length if (r9 <= r10) goto L_0x005b int r9 = r7.length int r9 = r9 - r6 if (r9 <= 0) goto L_0x004e char[] r10 = r11._qbuf java.lang.System.arraycopy(r10, r5, r7, r6, r9) L_0x004e: char[] r6 = r0.finishCurrentSegment() int r1 = r1 - r9 char[] r7 = r11._qbuf java.lang.System.arraycopy(r7, r9, r6, r5, r1) r7 = r6 r6 = r1 goto L_0x0061 L_0x005b: char[] r10 = r11._qbuf java.lang.System.arraycopy(r10, r5, r7, r6, r1) r6 = r9 L_0x0061: r1 = r8 goto L_0x001d L_0x0063: int r9 = r7.length if (r6 < r9) goto L_0x006c char[] r6 = r0.finishCurrentSegment() r7 = r6 r6 = 0 L_0x006c: int r9 = r6 + 1 r7[r6] = r8 int r1 = r1 + 1 if (r1 < r4) goto L_0x0076 r6 = r9 goto L_0x0078 L_0x0076: r6 = r9 goto L_0x001f L_0x0078: r0.setCurrentLength(r6) char[] r12 = r0.contentsAsArray() return r12 */ throw new UnsupportedOperationException("Method not decompiled: com.fasterxml.jackson.core.p116io.JsonStringEncoder.quoteAsString(java.lang.String):char[]"); } /* JADX WARNING: Code restructure failed: missing block: B:10:0x002e, code lost: r9.append(r7._qbuf, 0, r4); r4 = r5; */ /* JADX WARNING: Code restructure failed: missing block: B:6:0x0017, code lost: r5 = r4 + 1; r4 = r8.charAt(r4); r6 = r0[r4]; */ /* JADX WARNING: Code restructure failed: missing block: B:7:0x001f, code lost: if (r6 >= 0) goto L_0x0028; */ /* JADX WARNING: Code restructure failed: missing block: B:8:0x0021, code lost: r4 = _appendNumeric(r4, r7._qbuf); */ /* JADX WARNING: Code restructure failed: missing block: B:9:0x0028, code lost: r4 = _appendNamed(r6, r7._qbuf); */ /* Code decompiled incorrectly, please refer to instructions dump. */ public void quoteAsString(java.lang.CharSequence r8, java.lang.StringBuilder r9) { /* r7 = this; int[] r0 = com.fasterxml.jackson.core.p116io.CharTypes.get7BitOutputEscapes() int r1 = r0.length int r2 = r8.length() r3 = 0 r4 = 0 L_0x000b: if (r4 >= r2) goto L_0x003c L_0x000d: char r5 = r8.charAt(r4) if (r5 >= r1) goto L_0x0035 r6 = r0[r5] if (r6 == 0) goto L_0x0035 int r5 = r4 + 1 char r4 = r8.charAt(r4) r6 = r0[r4] if (r6 >= 0) goto L_0x0028 char[] r6 = r7._qbuf int r4 = r7._appendNumeric(r4, r6) goto L_0x002e L_0x0028: char[] r4 = r7._qbuf int r4 = r7._appendNamed(r6, r4) L_0x002e: char[] r6 = r7._qbuf r9.append(r6, r3, r4) r4 = r5 goto L_0x000b L_0x0035: r9.append(r5) int r4 = r4 + 1 if (r4 < r2) goto L_0x000d L_0x003c: return */ throw new UnsupportedOperationException("Method not decompiled: com.fasterxml.jackson.core.p116io.JsonStringEncoder.quoteAsString(java.lang.CharSequence, java.lang.StringBuilder):void"); } /* JADX WARNING: Code restructure failed: missing block: B:18:0x0043, code lost: if (r4 < r5.length) goto L_0x004a; */ /* JADX WARNING: Code restructure failed: missing block: B:19:0x0045, code lost: r5 = r0.finishCurrentSegment(); r4 = 0; */ /* JADX WARNING: Code restructure failed: missing block: B:20:0x004a, code lost: r7 = r2 + 1; r2 = r11.charAt(r2); */ /* JADX WARNING: Code restructure failed: missing block: B:21:0x0050, code lost: if (r2 > 127) goto L_0x005e; */ /* JADX WARNING: Code restructure failed: missing block: B:22:0x0052, code lost: r4 = _appendByte(r2, r6[r2], r0, r4); r5 = r0.getCurrentSegment(); */ /* JADX WARNING: Code restructure failed: missing block: B:25:0x0060, code lost: if (r2 > 2047) goto L_0x0072; */ /* JADX WARNING: Code restructure failed: missing block: B:26:0x0062, code lost: r6 = r4 + 1; r5[r4] = (byte) ((r2 >> 6) | 192); r2 = (r2 & '?') | 128; r4 = r6; */ /* JADX WARNING: Code restructure failed: missing block: B:28:0x0075, code lost: if (r2 < 55296) goto L_0x00d3; */ /* JADX WARNING: Code restructure failed: missing block: B:30:0x007a, code lost: if (r2 <= 57343) goto L_0x007d; */ /* JADX WARNING: Code restructure failed: missing block: B:32:0x0080, code lost: if (r2 <= 56319) goto L_0x0085; */ /* JADX WARNING: Code restructure failed: missing block: B:33:0x0082, code lost: _illegal(r2); */ /* JADX WARNING: Code restructure failed: missing block: B:34:0x0085, code lost: if (r7 < r1) goto L_0x008a; */ /* JADX WARNING: Code restructure failed: missing block: B:35:0x0087, code lost: _illegal(r2); */ /* JADX WARNING: Code restructure failed: missing block: B:36:0x008a, code lost: r6 = r7 + 1; r2 = _convert(r2, r11.charAt(r7)); */ /* JADX WARNING: Code restructure failed: missing block: B:37:0x0097, code lost: if (r2 <= 1114111) goto L_0x009c; */ /* JADX WARNING: Code restructure failed: missing block: B:38:0x0099, code lost: _illegal(r2); */ /* JADX WARNING: Code restructure failed: missing block: B:39:0x009c, code lost: r7 = r4 + 1; r5[r4] = (byte) ((r2 >> 18) | 240); */ /* JADX WARNING: Code restructure failed: missing block: B:40:0x00a6, code lost: if (r7 < r5.length) goto L_0x00ad; */ /* JADX WARNING: Code restructure failed: missing block: B:41:0x00a8, code lost: r5 = r0.finishCurrentSegment(); r7 = 0; */ /* JADX WARNING: Code restructure failed: missing block: B:42:0x00ad, code lost: r4 = r7 + 1; r5[r7] = (byte) (((r2 >> 12) & 63) | 128); */ /* JADX WARNING: Code restructure failed: missing block: B:43:0x00b9, code lost: if (r4 < r5.length) goto L_0x00c1; */ /* JADX WARNING: Code restructure failed: missing block: B:44:0x00bb, code lost: r5 = r0.finishCurrentSegment(); r4 = 0; */ /* JADX WARNING: Code restructure failed: missing block: B:45:0x00c1, code lost: r7 = r4 + 1; r5[r4] = (byte) (((r2 >> 6) & 63) | 128); r2 = (r2 & '?') | 128; r4 = r7; r7 = r6; */ /* JADX WARNING: Code restructure failed: missing block: B:46:0x00d3, code lost: r6 = r4 + 1; r5[r4] = (byte) ((r2 >> 12) | 224); */ /* JADX WARNING: Code restructure failed: missing block: B:47:0x00dd, code lost: if (r6 < r5.length) goto L_0x00e4; */ /* JADX WARNING: Code restructure failed: missing block: B:48:0x00df, code lost: r5 = r0.finishCurrentSegment(); r6 = 0; */ /* JADX WARNING: Code restructure failed: missing block: B:49:0x00e4, code lost: r4 = r6 + 1; r5[r6] = (byte) (((r2 >> 6) & 63) | 128); r2 = (r2 & '?') | 128; */ /* JADX WARNING: Code restructure failed: missing block: B:51:0x00f4, code lost: if (r4 < r5.length) goto L_0x00fc; */ /* JADX WARNING: Code restructure failed: missing block: B:52:0x00f6, code lost: r5 = r0.finishCurrentSegment(); r4 = 0; */ /* JADX WARNING: Code restructure failed: missing block: B:53:0x00fc, code lost: r6 = r4 + 1; r5[r4] = (byte) r2; r4 = r6; */ /* Code decompiled incorrectly, please refer to instructions dump. */ public byte[] quoteAsUTF8(java.lang.String r11) { /* r10 = this; com.fasterxml.jackson.core.util.ByteArrayBuilder r0 = r10._bytes if (r0 != 0) goto L_0x000c com.fasterxml.jackson.core.util.ByteArrayBuilder r0 = new com.fasterxml.jackson.core.util.ByteArrayBuilder r1 = 0 r0.<init>(r1) r10._bytes = r0 L_0x000c: int r1 = r11.length() byte[] r2 = r0.resetAndGetFirstSegment() r3 = 0 r5 = r2 r2 = 0 r4 = 0 L_0x0018: if (r2 >= r1) goto L_0x0104 int[] r6 = com.fasterxml.jackson.core.p116io.CharTypes.get7BitOutputEscapes() L_0x001e: char r7 = r11.charAt(r2) r8 = 127(0x7f, float:1.78E-43) if (r7 > r8) goto L_0x0042 r9 = r6[r7] if (r9 == 0) goto L_0x002b goto L_0x0042 L_0x002b: int r8 = r5.length if (r4 < r8) goto L_0x0034 byte[] r4 = r0.finishCurrentSegment() r5 = r4 r4 = 0 L_0x0034: int r8 = r4 + 1 byte r7 = (byte) r7 r5[r4] = r7 int r2 = r2 + 1 if (r2 < r1) goto L_0x0040 r4 = r8 goto L_0x0104 L_0x0040: r4 = r8 goto L_0x001e L_0x0042: int r7 = r5.length if (r4 < r7) goto L_0x004a byte[] r5 = r0.finishCurrentSegment() r4 = 0 L_0x004a: int r7 = r2 + 1 char r2 = r11.charAt(r2) if (r2 > r8) goto L_0x005e r5 = r6[r2] int r4 = r10._appendByte(r2, r5, r0, r4) byte[] r5 = r0.getCurrentSegment() L_0x005c: r2 = r7 goto L_0x0018 L_0x005e: r6 = 2047(0x7ff, float:2.868E-42) if (r2 > r6) goto L_0x0072 int r6 = r4 + 1 int r8 = r2 >> 6 r8 = r8 | 192(0xc0, float:2.69E-43) byte r8 = (byte) r8 r5[r4] = r8 r2 = r2 & 63 r2 = r2 | 128(0x80, float:1.794E-43) r4 = r6 goto L_0x00f3 L_0x0072: r6 = 55296(0xd800, float:7.7486E-41) if (r2 < r6) goto L_0x00d3 r6 = 57343(0xdfff, float:8.0355E-41) if (r2 <= r6) goto L_0x007d goto L_0x00d3 L_0x007d: r6 = 56319(0xdbff, float:7.892E-41) if (r2 <= r6) goto L_0x0085 _illegal(r2) L_0x0085: if (r7 < r1) goto L_0x008a _illegal(r2) L_0x008a: int r6 = r7 + 1 char r7 = r11.charAt(r7) int r2 = _convert(r2, r7) r7 = 1114111(0x10ffff, float:1.561202E-39) if (r2 <= r7) goto L_0x009c _illegal(r2) L_0x009c: int r7 = r4 + 1 int r8 = r2 >> 18 r8 = r8 | 240(0xf0, float:3.36E-43) byte r8 = (byte) r8 r5[r4] = r8 int r4 = r5.length if (r7 < r4) goto L_0x00ad byte[] r5 = r0.finishCurrentSegment() r7 = 0 L_0x00ad: int r4 = r7 + 1 int r8 = r2 >> 12 r8 = r8 & 63 r8 = r8 | 128(0x80, float:1.794E-43) byte r8 = (byte) r8 r5[r7] = r8 int r7 = r5.length if (r4 < r7) goto L_0x00c1 byte[] r4 = r0.finishCurrentSegment() r5 = r4 r4 = 0 L_0x00c1: int r7 = r4 + 1 int r8 = r2 >> 6 r8 = r8 & 63 r8 = r8 | 128(0x80, float:1.794E-43) byte r8 = (byte) r8 r5[r4] = r8 r2 = r2 & 63 r2 = r2 | 128(0x80, float:1.794E-43) r4 = r7 r7 = r6 goto L_0x00f3 L_0x00d3: int r6 = r4 + 1 int r8 = r2 >> 12 r8 = r8 | 224(0xe0, float:3.14E-43) byte r8 = (byte) r8 r5[r4] = r8 int r4 = r5.length if (r6 < r4) goto L_0x00e4 byte[] r5 = r0.finishCurrentSegment() r6 = 0 L_0x00e4: int r4 = r6 + 1 int r8 = r2 >> 6 r8 = r8 & 63 r8 = r8 | 128(0x80, float:1.794E-43) byte r8 = (byte) r8 r5[r6] = r8 r2 = r2 & 63 r2 = r2 | 128(0x80, float:1.794E-43) L_0x00f3: int r6 = r5.length if (r4 < r6) goto L_0x00fc byte[] r4 = r0.finishCurrentSegment() r5 = r4 r4 = 0 L_0x00fc: int r6 = r4 + 1 byte r2 = (byte) r2 r5[r4] = r2 r4 = r6 goto L_0x005c L_0x0104: com.fasterxml.jackson.core.util.ByteArrayBuilder r11 = r10._bytes byte[] r11 = r11.completeAndCoalesce(r4) return r11 */ throw new UnsupportedOperationException("Method not decompiled: com.fasterxml.jackson.core.p116io.JsonStringEncoder.quoteAsUTF8(java.lang.String):byte[]"); } public byte[] encodeAsUTF8(String str) { int i; ByteArrayBuilder byteArrayBuilder = this._bytes; if (byteArrayBuilder == null) { byteArrayBuilder = new ByteArrayBuilder((BufferRecycler) null); this._bytes = byteArrayBuilder; } int length = str.length(); byte[] resetAndGetFirstSegment = byteArrayBuilder.resetAndGetFirstSegment(); byte[] bArr = resetAndGetFirstSegment; int length2 = resetAndGetFirstSegment.length; int i2 = 0; int i3 = 0; loop0: while (true) { if (i2 >= length) { break; } int i4 = i2 + 1; int charAt = str.charAt(i2); while (charAt <= 127) { if (i3 >= length2) { byte[] finishCurrentSegment = byteArrayBuilder.finishCurrentSegment(); length2 = finishCurrentSegment.length; bArr = finishCurrentSegment; i3 = 0; } int i5 = i3 + 1; bArr[i3] = (byte) charAt; if (i4 >= length) { i3 = i5; break loop0; } int i6 = i4 + 1; int charAt2 = str.charAt(i4); i4 = i6; charAt = charAt2; i3 = i5; } if (i3 >= length2) { bArr = byteArrayBuilder.finishCurrentSegment(); length2 = bArr.length; i3 = 0; } if (charAt < 2048) { int i7 = i3 + 1; bArr[i3] = (byte) ((charAt >> 6) | 192); i = i7; } else if (charAt < 55296 || charAt > 57343) { int i8 = i3 + 1; bArr[i3] = (byte) ((charAt >> 12) | 224); if (i8 >= length2) { bArr = byteArrayBuilder.finishCurrentSegment(); length2 = bArr.length; i8 = 0; } i = i8 + 1; bArr[i8] = (byte) (((charAt >> 6) & 63) | 128); } else { if (charAt > 56319) { _illegal(charAt); } if (i4 >= length) { _illegal(charAt); } int i9 = i4 + 1; charAt = _convert(charAt, str.charAt(i4)); if (charAt > 1114111) { _illegal(charAt); } int i10 = i3 + 1; bArr[i3] = (byte) ((charAt >> 18) | 240); if (i10 >= length2) { bArr = byteArrayBuilder.finishCurrentSegment(); length2 = bArr.length; i10 = 0; } int i11 = i10 + 1; bArr[i10] = (byte) (((charAt >> 12) & 63) | 128); if (i11 >= length2) { byte[] finishCurrentSegment2 = byteArrayBuilder.finishCurrentSegment(); length2 = finishCurrentSegment2.length; bArr = finishCurrentSegment2; i11 = 0; } int i12 = i11 + 1; bArr[i11] = (byte) (((charAt >> 6) & 63) | 128); i = i12; i4 = i9; } if (i >= length2) { byte[] finishCurrentSegment3 = byteArrayBuilder.finishCurrentSegment(); length2 = finishCurrentSegment3.length; bArr = finishCurrentSegment3; i = 0; } int i13 = i + 1; bArr[i] = (byte) ((charAt & 63) | 128); i2 = i4; i3 = i13; } return this._bytes.completeAndCoalesce(i3); } private int _appendNumeric(int i, char[] cArr) { cArr[1] = 'u'; cArr[4] = f6138HC[i >> 4]; cArr[5] = f6138HC[i & 15]; return 6; } private int _appendNamed(int i, char[] cArr) { cArr[1] = (char) i; return 2; } private int _appendByte(int i, int i2, ByteArrayBuilder byteArrayBuilder, int i3) { byteArrayBuilder.setCurrentSegmentLength(i3); byteArrayBuilder.append(92); if (i2 < 0) { byteArrayBuilder.append(117); if (i > 255) { int i4 = i >> 8; byteArrayBuilder.append(f6137HB[i4 >> 4]); byteArrayBuilder.append(f6137HB[i4 & 15]); i &= 255; } else { byteArrayBuilder.append(48); byteArrayBuilder.append(48); } byteArrayBuilder.append(f6137HB[i >> 4]); byteArrayBuilder.append(f6137HB[i & 15]); } else { byteArrayBuilder.append((byte) i2); } return byteArrayBuilder.getCurrentSegmentLength(); } private static int _convert(int i, int i2) { if (i2 >= 56320 && i2 <= 57343) { return ((i - 55296) << 10) + 65536 + (i2 - 56320); } StringBuilder sb = new StringBuilder(); sb.append("Broken surrogate pair: first char 0x"); sb.append(Integer.toHexString(i)); sb.append(", second 0x"); sb.append(Integer.toHexString(i2)); sb.append("; illegal combination"); throw new IllegalArgumentException(sb.toString()); } private static void _illegal(int i) { throw new IllegalArgumentException(UTF8Writer.illegalSurrogateDesc(i)); } }
23,632
0.501058
0.413422
660
34.806061
24.299994
194
false
false
0
0
0
0
0
0
0.533333
false
false
10
3c87af637ef4e6c17c8849608a6a2dd229d37f4d
29,600,914,610,000
d76e3ca25140436561209a2c07e1c771f6e08273
/pcenter/src/main/java/com/pcenter/entity/User.java
93c3f26d40b1d8d7e4f1437952575e5e89790b00
[]
no_license
xngithub/pcenter
https://github.com/xngithub/pcenter
8424c3cc395566b4afb85ee4c0279e2295cbb23d
506f2cb4b3bb3baf50180aac485349c0a41291bb
refs/heads/master
2016-03-23T19:37:14.504000
2014-09-14T08:56:56
2014-09-14T08:56:56
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.pcenter.entity; import org.apache.commons.lang.builder.ToStringBuilder; public class User { private Integer id; private String loginname; private String password; private String realname; private Role role; private Integer state; private String remark; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getLoginname() { return loginname; } public void setLoginname(String loginname) { this.loginname = loginname; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getRealname() { return realname; } public void setRealname(String realname) { this.realname = realname; } public Role getRole() { return role; } public void setRole(Role role) { this.role = role; } public Integer getState() { return state; } public void setState(Integer state) { this.state = state; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
UTF-8
Java
1,270
java
User.java
Java
[]
null
[]
package com.pcenter.entity; import org.apache.commons.lang.builder.ToStringBuilder; public class User { private Integer id; private String loginname; private String password; private String realname; private Role role; private Integer state; private String remark; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getLoginname() { return loginname; } public void setLoginname(String loginname) { this.loginname = loginname; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getRealname() { return realname; } public void setRealname(String realname) { this.realname = realname; } public Role getRole() { return role; } public void setRole(Role role) { this.role = role; } public Integer getState() { return state; } public void setState(Integer state) { this.state = state; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
1,270
0.669291
0.669291
74
15.162162
14.820573
55
false
false
0
0
0
0
0
0
1.243243
false
false
10
e7303af6a4a98cf2df3b89d90b1f2b4e97f56314
7,473,243,129,610
2d2ec3f64e0150d03785b4bcb8437137dfe7e4c6
/src/main/java/DynamicSample.java
57d478d62902a1a650af96cf96d434ba10542944
[]
no_license
hangshisitu/modao
https://github.com/hangshisitu/modao
1e62edef9ecb68f897e8bc5b02555d68e71a0ec8
285abfccb0c1436c9671a6091e8b59268cbc0aff
refs/heads/main
2023-03-06T20:03:32.352000
2021-02-23T08:36:37
2021-02-23T08:36:37
323,586,411
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.ArrayList; //爬楼梯 public class DynamicSample { public int doMain(int start, int end) { int[] stepCnt = new int[end]; for(int i=end-1;i>=start;--i) { int cnt = 0; if(end-i==1) { stepCnt[i] =1; }else if(end-i==2) { stepCnt[i] =2; }else { stepCnt[i] = stepCnt[i+1]+ stepCnt[i+2]; } } return stepCnt[start]; } }
UTF-8
Java
528
java
DynamicSample.java
Java
[]
null
[]
import java.util.ArrayList; //爬楼梯 public class DynamicSample { public int doMain(int start, int end) { int[] stepCnt = new int[end]; for(int i=end-1;i>=start;--i) { int cnt = 0; if(end-i==1) { stepCnt[i] =1; }else if(end-i==2) { stepCnt[i] =2; }else { stepCnt[i] = stepCnt[i+1]+ stepCnt[i+2]; } } return stepCnt[start]; } }
528
0.396552
0.381226
25
19.879999
14.342441
56
false
false
0
0
0
0
0
0
0.4
false
false
10
11291aa9d3bac8d0f2319b05fb6ab2f168920b92
33,603,824,171,777
6dc773c1f7f38bb97bdb829ea81c2c3c10b1af77
/s3_paseadores-back/src/main/java/co/edu/uniandes/csw/paseadores/persistence/ClientePersistence.java
11a314d55dc48ac6122fa3af29b64a7cf596b2e9
[ "MIT" ]
permissive
Uniandes-ISIS2603-backup/s3_Paseadores_201920
https://github.com/Uniandes-ISIS2603-backup/s3_Paseadores_201920
a69a02822e9062fa2a6a0e2b37cf6f78a21de432
7a3f26893ed2a36ccf39967ee9b4b9ed1d1224dc
refs/heads/master
2020-07-02T09:42:03.912000
2019-12-05T12:52:46
2019-12-05T12:52:46
201,489,644
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package co.edu.uniandes.csw.paseadores.persistence; import co.edu.uniandes.csw.paseadores.entities.ClienteEntity; import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; /** *Clase que maneja la persistencia para el cliente. * * @author Santiago Bolaños */ @Stateless public class ClientePersistence { @PersistenceContext( unitName = "paseadoresPU") protected EntityManager em; /** * Crea un cliente en la base de datos. * * @param cliente. objeto cliente que se creará en la base de datos. * @return la entidad cliente creada con un id dado por la base de datos. */ public ClienteEntity create ( ClienteEntity cliente ) { em.persist(cliente); return cliente; } /** * Retorna todos los clientes de la base de datos. * * @return una lista con todos los clientes de la base de datos. * "select u from ClienteEntity u" es como un "select * from ClienteEntity;" - * "SELECT * FROM table_name" en SQL */ public List<ClienteEntity> findAll() { TypedQuery query = em.createQuery("Select u from ClienteEntity u",ClienteEntity.class); return query.getResultList(); } /** * Busca si hay un cliente con el id que de envía por parámetro * * @param clienteId. Id del cliente * @return Cliente buscado. */ public ClienteEntity find( Long clienteId ) { return em.find(ClienteEntity.class, clienteId); } /** * Actualiza un cliente. * * @param cliente La entidad del cliente con los nuevos datos.l * @return Cliente actualizado. */ public ClienteEntity update(ClienteEntity cliente) { return em.merge(cliente); } /** * Elimina un cliente de la base de datos dado su id. * * @param clienteId id del cliente a eliminar. */ public void delete( Long clienteId) { ClienteEntity cliente = em.find(ClienteEntity.class , clienteId); em.remove(cliente); } }
UTF-8
Java
2,353
java
ClientePersistence.java
Java
[ { "context": "ja la persistencia para el cliente.\n * \n * @author Santiago Bolaños \n */\n@Stateless\npublic class ClientePersistence \n", "end": 561, "score": 0.9998745322227478, "start": 545, "tag": "NAME", "value": "Santiago Bolaños" } ]
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 co.edu.uniandes.csw.paseadores.persistence; import co.edu.uniandes.csw.paseadores.entities.ClienteEntity; import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; /** *Clase que maneja la persistencia para el cliente. * * @author <NAME> */ @Stateless public class ClientePersistence { @PersistenceContext( unitName = "paseadoresPU") protected EntityManager em; /** * Crea un cliente en la base de datos. * * @param cliente. objeto cliente que se creará en la base de datos. * @return la entidad cliente creada con un id dado por la base de datos. */ public ClienteEntity create ( ClienteEntity cliente ) { em.persist(cliente); return cliente; } /** * Retorna todos los clientes de la base de datos. * * @return una lista con todos los clientes de la base de datos. * "select u from ClienteEntity u" es como un "select * from ClienteEntity;" - * "SELECT * FROM table_name" en SQL */ public List<ClienteEntity> findAll() { TypedQuery query = em.createQuery("Select u from ClienteEntity u",ClienteEntity.class); return query.getResultList(); } /** * Busca si hay un cliente con el id que de envía por parámetro * * @param clienteId. Id del cliente * @return Cliente buscado. */ public ClienteEntity find( Long clienteId ) { return em.find(ClienteEntity.class, clienteId); } /** * Actualiza un cliente. * * @param cliente La entidad del cliente con los nuevos datos.l * @return Cliente actualizado. */ public ClienteEntity update(ClienteEntity cliente) { return em.merge(cliente); } /** * Elimina un cliente de la base de datos dado su id. * * @param clienteId id del cliente a eliminar. */ public void delete( Long clienteId) { ClienteEntity cliente = em.find(ClienteEntity.class , clienteId); em.remove(cliente); } }
2,342
0.655172
0.655172
83
27.313253
25.02429
95
false
false
0
0
0
0
0
0
0.277108
false
false
10
acb97038282c35f5662900b722c9c648b1dc6554
18,880,676,262,980
463e26b61b94dea9561f128ddef4baf9d93da464
/java/IHM/TP3/chrono/src/tst/ChronoMain.java
96105de7ec8207054c9c317e63295c8189df8dcd
[]
no_license
lambdhack/DUT_Info
https://github.com/lambdhack/DUT_Info
077034c7d998baa1d1accf21605474bcc7a48ed7
573d2ebd21c47a3c99c92ead181d458bc5cf7f78
refs/heads/master
2020-03-11T02:28:40.535000
2018-06-09T20:24:35
2018-06-09T20:24:35
129,720,154
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
public class ChronoMain { public static void main(String[] args) { new ChronoGUItmp(); } }
UTF-8
Java
108
java
ChronoMain.java
Java
[]
null
[]
public class ChronoMain { public static void main(String[] args) { new ChronoGUItmp(); } }
108
0.611111
0.611111
6
17
16.237816
44
false
false
0
0
0
0
0
0
0.166667
false
false
10
2e8b4c8e3999eaa700b9480041d0fa787b3b2f3e
20,942,260,577,684
f43b9c6fb46bfa36d4fd3dd61742c9a4a6534c04
/src/main/java/com/example/mysqldemo/controller/BehaviorCotroller.java
a62c3a8484d2ff3f047beadf0cdfb84ddff2f8bb
[]
no_license
luoxianming/luoxm
https://github.com/luoxianming/luoxm
96dc5448a42f0e07ea94882ccf6aa361089f4160
5ce294db6ad7d21c9812d62edccec8d1d67e3773
refs/heads/master
2021-12-01T08:09:49.211000
2021-11-14T14:53:23
2021-11-14T14:53:23
110,954,659
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.mysqldemo.controller; import com.example.mysqldemo.dao.BehaviorDao; import com.example.mysqldemo.service.BehaviorService; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; /** * @Author: luoxianming * @Date: 2020/8/27 21:16 */ @RequestMapping("/behavior") @RestController public class BehaviorCotroller { @Resource private BehaviorService behaviorService; @GetMapping(value= "/inport") public void inprot(){ behaviorService.insert(); } }
UTF-8
Java
663
java
BehaviorCotroller.java
Java
[ { "context": "import javax.annotation.Resource;\n\n/**\n * @Author: luoxianming\n * @Date: 2020/8/27 21:16\n */\n@RequestMapping(\"/b", "end": 391, "score": 0.9996174573898315, "start": 380, "tag": "USERNAME", "value": "luoxianming" } ]
null
[]
package com.example.mysqldemo.controller; import com.example.mysqldemo.dao.BehaviorDao; import com.example.mysqldemo.service.BehaviorService; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; /** * @Author: luoxianming * @Date: 2020/8/27 21:16 */ @RequestMapping("/behavior") @RestController public class BehaviorCotroller { @Resource private BehaviorService behaviorService; @GetMapping(value= "/inport") public void inprot(){ behaviorService.insert(); } }
663
0.770739
0.754148
26
24.5
20.744322
62
false
false
0
0
0
0
0
0
0.346154
false
false
10
1044d63a60689ebcb36258a4736da60c641f43e7
2,113,123,934,355
a4f443e9bc0479034c4b3e60c49bf8ce66ab5b1b
/src/main/java/com/accessstop/station/StationRepositoryImpl.java
103c36716b227f587a85c2443b4c7264c491d64d
[]
no_license
andersontaraujo/access-stop-api
https://github.com/andersontaraujo/access-stop-api
483d20f79177a20fc099cc4e790eb3fb872c8eb7
2f5d2e6f7428b203c469a29525b92de0cb221a6c
refs/heads/master
2020-04-17T16:13:17.750000
2019-01-22T00:26:57
2019-01-22T00:26:57
166,731,786
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.accessstop.station; import java.util.LinkedList; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import org.springframework.stereotype.Repository; @Repository public class StationRepositoryImpl implements StationCustomRepository { private EntityManager em; public StationRepositoryImpl(EntityManager entityManager) { this.em = entityManager; } @Override public List<Station> search(StationFilter filter) { CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<Station> criteria = builder.createQuery(Station.class); Root<Station> root = criteria.from(Station.class); List<Predicate> predicates = new LinkedList<>(); if (filter.getName() != null) { predicates.add(builder.like(builder.upper(root.get(Station_.NAME)), "%" + filter.getName().toUpperCase() + "%")); } if (filter.getAddress() != null) { predicates.add(builder.like(builder.upper(root.get(Station_.ADDRESS)), "%" + filter.getAddress().toUpperCase() + "%")); } criteria.select(root).where(predicates.toArray(new Predicate[predicates.size()])); return em.createQuery(criteria).getResultList(); } }
UTF-8
Java
1,405
java
StationRepositoryImpl.java
Java
[]
null
[]
package com.accessstop.station; import java.util.LinkedList; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import org.springframework.stereotype.Repository; @Repository public class StationRepositoryImpl implements StationCustomRepository { private EntityManager em; public StationRepositoryImpl(EntityManager entityManager) { this.em = entityManager; } @Override public List<Station> search(StationFilter filter) { CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<Station> criteria = builder.createQuery(Station.class); Root<Station> root = criteria.from(Station.class); List<Predicate> predicates = new LinkedList<>(); if (filter.getName() != null) { predicates.add(builder.like(builder.upper(root.get(Station_.NAME)), "%" + filter.getName().toUpperCase() + "%")); } if (filter.getAddress() != null) { predicates.add(builder.like(builder.upper(root.get(Station_.ADDRESS)), "%" + filter.getAddress().toUpperCase() + "%")); } criteria.select(root).where(predicates.toArray(new Predicate[predicates.size()])); return em.createQuery(criteria).getResultList(); } }
1,405
0.720285
0.720285
39
35.025642
32.998436
131
false
false
0
0
0
0
0
0
0.769231
false
false
10
9bea95e8bdb3bc1bddaff756744f877aad42d0d7
31,997,506,409,078
38cbe3507929f1f9f70bd7d3bf6464f3ca020103
/src/business/custom/CustomerBO.java
a6a23fc62194696b9e47b9d36787f15d34ca190b
[ "MIT" ]
permissive
TharinduMadhu/POS-With-Layered-Architecture
https://github.com/TharinduMadhu/POS-With-Layered-Architecture
d97827506654f5b9343b13254eb9fe82a238e221
4c592bec87a27c6832a9f913db19e2daa4d334b2
refs/heads/master
2022-11-29T11:05:19.567000
2020-08-09T11:43:14
2020-08-09T11:43:14
284,195,790
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package business.custom; import business.SuperBO; import dao.SuperDAO; import util.CustomerTM; import java.util.List; public interface CustomerBO extends SuperBO { public String generateNewCustomerId() throws Exception; public List<CustomerTM> getAllCustomers() throws Exception; public boolean saveCustomer(String id, String name, String address) throws Exception; public boolean deleteCustomer(String customerId) throws Exception; public boolean updateCustomer(String id, String name, String address) throws Exception; }
UTF-8
Java
551
java
CustomerBO.java
Java
[]
null
[]
package business.custom; import business.SuperBO; import dao.SuperDAO; import util.CustomerTM; import java.util.List; public interface CustomerBO extends SuperBO { public String generateNewCustomerId() throws Exception; public List<CustomerTM> getAllCustomers() throws Exception; public boolean saveCustomer(String id, String name, String address) throws Exception; public boolean deleteCustomer(String customerId) throws Exception; public boolean updateCustomer(String id, String name, String address) throws Exception; }
551
0.791289
0.791289
18
29.611111
31.32826
91
false
false
0
0
0
0
0
0
0.777778
false
false
10
ef77cee6455fd707c78f4e4ad4e5baa8aecdcb7d
4,861,903,039,874
e6853bb1092461ce0a11429fe303461a355f7a27
/random-stuff/src/main/java/org/russell/annotations/AnnotationReader.java
b0979d149c8b41e3c3dbc4beee5e1b17d19601a9
[]
no_license
RussellRC/RussellTests
https://github.com/RussellRC/RussellTests
4885ba2260c4c54ab3694e3e3fd30b50d4a8c8dc
6c56f3ced3527ae879f4188f2a5391b791bdb4fe
refs/heads/master
2022-07-01T22:49:12.714000
2022-06-08T17:20:08
2022-06-08T17:20:08
52,841,551
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.russell.annotations; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.russell.annotations.TextAsset.MarketingContext; import org.russell.annotations.annotation.AnnotationMap; import org.russell.annotations.annotation.AnnotationProperty; import org.russell.annotations.annotation.NestedAnnotationProperty; public class AnnotationReader { public static void main(String[] args) throws Exception { TextAsset ta1 = new TextAsset(); ta1.keyPath = "my.text.asset.1"; ta1.description = "text asset 1 descriptio"; ta1.mc = new MarketingContext(); ta1.mc.segment = "all"; ta1.mc.geo = "ww"; ta1.mc.format = "common"; ta1.locales = new LinkedHashMap<String, String>(); ta1.locales.put("en", "hello"); ta1.locales.put("es", "hola"); //printAnnotation(ta1); System.out.println("+++++"); Fragment f1 = new Fragment(); f1.keyPath = "my.fragment.asset.1"; f1.description = "fragment 1 description"; f1.assetType = "astro"; f1.mc = new MarketingContext(); f1.mc.segment = "all"; f1.mc.geo = "ww"; f1.mc.format = "common"; f1.locales = new LinkedHashMap<String, String>(); f1.locales.put("en", "hello f"); f1.locales.put("es", "hola f"); System.out.println(); printAnnotation(f1); System.out.println(); System.out.println("=== end ==="); } private static List<Field> getAllFieldsHelper(List<Field> fields, final Class<?> type) { fields.addAll(Arrays.asList(type.getDeclaredFields())); if (type.getSuperclass() != null) { fields = getAllFieldsHelper(fields, type.getSuperclass()); } return fields; } public static List<Field> getAllFields(final Class<?> type) { return getAllFieldsHelper(new ArrayList<Field>(), type); } public static void printAnnotation(Object obj) throws Exception { if (obj == null) { return; } for (Field field : getAllFields(obj.getClass())) { if (field.isAnnotationPresent(AnnotationProperty.class)) { final AnnotationProperty annotation = field.getAnnotation(AnnotationProperty.class); final Object fieldValue = field.get(obj); if (fieldValue == null && annotation.ignoreNull()) { continue; } System.out.println(annotation.value() + "=" + fieldValue); } else if (field.isAnnotationPresent(NestedAnnotationProperty.class)) { final Object nestedObject = field.get(obj); printAnnotation(nestedObject); } else if (field.isAnnotationPresent(AnnotationMap.class)) { final Object fieldObject = field.get(obj); if (!(fieldObject instanceof Map)) { continue; } final Map<?, ?> map = (Map<?, ?>) field.get(obj); final AnnotationMap annotation = field.getAnnotation(AnnotationMap.class); for (final Object key : map.keySet()) { if (key == null || map.get(key) == null) { continue; } System.out.println(annotation.keyProperty() + "=" + String.valueOf(key)); System.out.println(annotation.valueProperty() + "=" + map.get(key)); } } } } }
UTF-8
Java
3,698
java
AnnotationReader.java
Java
[]
null
[]
package org.russell.annotations; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.russell.annotations.TextAsset.MarketingContext; import org.russell.annotations.annotation.AnnotationMap; import org.russell.annotations.annotation.AnnotationProperty; import org.russell.annotations.annotation.NestedAnnotationProperty; public class AnnotationReader { public static void main(String[] args) throws Exception { TextAsset ta1 = new TextAsset(); ta1.keyPath = "my.text.asset.1"; ta1.description = "text asset 1 descriptio"; ta1.mc = new MarketingContext(); ta1.mc.segment = "all"; ta1.mc.geo = "ww"; ta1.mc.format = "common"; ta1.locales = new LinkedHashMap<String, String>(); ta1.locales.put("en", "hello"); ta1.locales.put("es", "hola"); //printAnnotation(ta1); System.out.println("+++++"); Fragment f1 = new Fragment(); f1.keyPath = "my.fragment.asset.1"; f1.description = "fragment 1 description"; f1.assetType = "astro"; f1.mc = new MarketingContext(); f1.mc.segment = "all"; f1.mc.geo = "ww"; f1.mc.format = "common"; f1.locales = new LinkedHashMap<String, String>(); f1.locales.put("en", "hello f"); f1.locales.put("es", "hola f"); System.out.println(); printAnnotation(f1); System.out.println(); System.out.println("=== end ==="); } private static List<Field> getAllFieldsHelper(List<Field> fields, final Class<?> type) { fields.addAll(Arrays.asList(type.getDeclaredFields())); if (type.getSuperclass() != null) { fields = getAllFieldsHelper(fields, type.getSuperclass()); } return fields; } public static List<Field> getAllFields(final Class<?> type) { return getAllFieldsHelper(new ArrayList<Field>(), type); } public static void printAnnotation(Object obj) throws Exception { if (obj == null) { return; } for (Field field : getAllFields(obj.getClass())) { if (field.isAnnotationPresent(AnnotationProperty.class)) { final AnnotationProperty annotation = field.getAnnotation(AnnotationProperty.class); final Object fieldValue = field.get(obj); if (fieldValue == null && annotation.ignoreNull()) { continue; } System.out.println(annotation.value() + "=" + fieldValue); } else if (field.isAnnotationPresent(NestedAnnotationProperty.class)) { final Object nestedObject = field.get(obj); printAnnotation(nestedObject); } else if (field.isAnnotationPresent(AnnotationMap.class)) { final Object fieldObject = field.get(obj); if (!(fieldObject instanceof Map)) { continue; } final Map<?, ?> map = (Map<?, ?>) field.get(obj); final AnnotationMap annotation = field.getAnnotation(AnnotationMap.class); for (final Object key : map.keySet()) { if (key == null || map.get(key) == null) { continue; } System.out.println(annotation.keyProperty() + "=" + String.valueOf(key)); System.out.println(annotation.valueProperty() + "=" + map.get(key)); } } } } }
3,698
0.573824
0.566522
98
36.734695
25.190519
100
false
false
0
0
0
0
0
0
0.704082
false
false
10
6cf669b0435775d17cc83caa2e3c473e65832789
22,299,470,258,621
d5ccb592bc01315bd3d367bd71b3a754321da775
/src/me/fluglow/DeletePasscodeCmd.java
d34e6dd610de347a8e5ed7fa1ea275d3d3740e29
[ "MIT" ]
permissive
Fluglow/DoorPasscodes
https://github.com/Fluglow/DoorPasscodes
a8feeb681507eb9e2ac153298acc66bfed76eb73
446d0abbd74eecfa36b0d5d465e3b668773bdd61
refs/heads/master
2020-03-15T16:17:02.106000
2018-05-05T09:11:27
2018-05-05T09:11:27
132,231,546
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package me.fluglow; import org.bukkit.ChatColor; import org.bukkit.block.Block; import org.bukkit.block.BlockState; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.material.Door; public class DeletePasscodeCmd implements CommandExecutor { private final PasscodeDoorManager manager; DeletePasscodeCmd(PasscodeDoorManager manager) { this.manager = manager; } @Override public boolean onCommand(CommandSender commandSender, Command command, String s, String[] strings) { if(!(commandSender instanceof Player)) { commandSender.sendMessage(ChatColor.RED + "Only a player can use this command."); return true; } Player player = (Player)commandSender; Block block = player.getTargetBlock(null, 5); if(block == null) { player.sendMessage(ChatColor.RED + "Please look at the door you want to remove a passcode from."); return true; } BlockState state = block.getState(); if(!(state.getData() instanceof Door)) { player.sendMessage(ChatColor.RED + "You must be looking at a door!"); return true; } manager.deleteDoor(manager.getDoorByLocation(state.getLocation())); player.sendMessage(ChatColor.YELLOW + "passcode removed!"); return true; } }
UTF-8
Java
1,319
java
DeletePasscodeCmd.java
Java
[]
null
[]
package me.fluglow; import org.bukkit.ChatColor; import org.bukkit.block.Block; import org.bukkit.block.BlockState; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.material.Door; public class DeletePasscodeCmd implements CommandExecutor { private final PasscodeDoorManager manager; DeletePasscodeCmd(PasscodeDoorManager manager) { this.manager = manager; } @Override public boolean onCommand(CommandSender commandSender, Command command, String s, String[] strings) { if(!(commandSender instanceof Player)) { commandSender.sendMessage(ChatColor.RED + "Only a player can use this command."); return true; } Player player = (Player)commandSender; Block block = player.getTargetBlock(null, 5); if(block == null) { player.sendMessage(ChatColor.RED + "Please look at the door you want to remove a passcode from."); return true; } BlockState state = block.getState(); if(!(state.getData() instanceof Door)) { player.sendMessage(ChatColor.RED + "You must be looking at a door!"); return true; } manager.deleteDoor(manager.getDoorByLocation(state.getLocation())); player.sendMessage(ChatColor.YELLOW + "passcode removed!"); return true; } }
1,319
0.752085
0.751327
47
27.063829
27.113947
101
false
false
0
0
0
0
0
0
1.787234
false
false
10
3537fa85e4a0188bdbd366c301843e634b823a3f
20,504,173,899,150
353a0c6c9bc439cea5c5cd2154164cbeff62a55f
/src/lk/ijse/payrollSystem/controller/SalaryController.java
6bc5141442f59aa429fa3109c1aa40aecf44c295
[]
no_license
DanudiDevindi/payroll-system
https://github.com/DanudiDevindi/payroll-system
a06e5650b73627e7a938605e6f5bcd11892c0cf6
26e28ed41930ad8977470b5181f7365eee01cee2
refs/heads/master
2020-05-31T06:15:33.394000
2019-06-04T05:58:31
2019-06-04T05:58:31
190,138,311
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 lk.ijse.payrollSystem.controller; import java.util.ArrayList; import lk.ijse.payrollSystem.business.BoFactory; import lk.ijse.payrollSystem.business.custom.EmployeeBo; import lk.ijse.payrollSystem.business.custom.LevelBo; import lk.ijse.payrollSystem.business.custom.SalaryBo; import lk.ijse.payrollSystem.dto.EmployeeDTO; import lk.ijse.payrollSystem.dto.LevelDTO; import lk.ijse.payrollSystem.dto.SalaryDTO; /** * * @author acer */ public class SalaryController { private SalaryBo salaryBo1; private EmployeeBo employeeBo1; private LevelBo levelBo1; public SalaryController() { salaryBo1=BoFactory.getInstance().getBO(BoFactory.BOTypes.SALARY); employeeBo1=BoFactory.getInstance().getBO(BoFactory.BOTypes.EMPLOYEE); levelBo1=BoFactory.getInstance().getBO(BoFactory.BOTypes.LEVEL); } public ArrayList<String> getEmployees() throws Exception { return employeeBo1.getEmployees(); } public String getSelectedeId(String selectedeId) throws Exception { return employeeBo1.getSelectedeId(selectedeId); } public ArrayList<String> getAllLeves() throws Exception { return levelBo1.getLevels(); } public String getSelectedItemCode(String selectedItem) throws Exception { return levelBo1.getSelectedItemCode(selectedItem); } public boolean saveSalary(SalaryDTO salary) throws Exception { return salaryBo1.saveSalary(salary); } public boolean deleteSalary(String salId)throws Exception{ return salaryBo1.deleteSalary(salId); } public SalaryDTO searchSalary(String salId) throws Exception{ return salaryBo1.searchSalary(salId); } public boolean updateSalary(SalaryDTO salary) throws Exception { return salaryBo1.updateSalary(salary); } public ArrayList<SalaryDTO> getAllSalary()throws Exception{ return salaryBo1.getAllSalary(); } public EmployeeDTO searchEmployees(String eId) throws Exception { return employeeBo1.searchEmployees(eId); } public LevelDTO searchlevels(String lName) throws Exception { return levelBo1.searchlevels(lName); } public String searchSalaryId(String string) throws Exception { return salaryBo1.searchSalaryID(string) ; //To change body of generated methods, choose Tools | Templates. } }
UTF-8
Java
2,584
java
SalaryController.java
Java
[ { "context": "se.payrollSystem.dto.SalaryDTO;\n\n/**\n *\n * @author acer\n */\npublic class SalaryController {\n private S", "end": 627, "score": 0.9341430068016052, "start": 623, "tag": "USERNAME", "value": "acer" } ]
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 lk.ijse.payrollSystem.controller; import java.util.ArrayList; import lk.ijse.payrollSystem.business.BoFactory; import lk.ijse.payrollSystem.business.custom.EmployeeBo; import lk.ijse.payrollSystem.business.custom.LevelBo; import lk.ijse.payrollSystem.business.custom.SalaryBo; import lk.ijse.payrollSystem.dto.EmployeeDTO; import lk.ijse.payrollSystem.dto.LevelDTO; import lk.ijse.payrollSystem.dto.SalaryDTO; /** * * @author acer */ public class SalaryController { private SalaryBo salaryBo1; private EmployeeBo employeeBo1; private LevelBo levelBo1; public SalaryController() { salaryBo1=BoFactory.getInstance().getBO(BoFactory.BOTypes.SALARY); employeeBo1=BoFactory.getInstance().getBO(BoFactory.BOTypes.EMPLOYEE); levelBo1=BoFactory.getInstance().getBO(BoFactory.BOTypes.LEVEL); } public ArrayList<String> getEmployees() throws Exception { return employeeBo1.getEmployees(); } public String getSelectedeId(String selectedeId) throws Exception { return employeeBo1.getSelectedeId(selectedeId); } public ArrayList<String> getAllLeves() throws Exception { return levelBo1.getLevels(); } public String getSelectedItemCode(String selectedItem) throws Exception { return levelBo1.getSelectedItemCode(selectedItem); } public boolean saveSalary(SalaryDTO salary) throws Exception { return salaryBo1.saveSalary(salary); } public boolean deleteSalary(String salId)throws Exception{ return salaryBo1.deleteSalary(salId); } public SalaryDTO searchSalary(String salId) throws Exception{ return salaryBo1.searchSalary(salId); } public boolean updateSalary(SalaryDTO salary) throws Exception { return salaryBo1.updateSalary(salary); } public ArrayList<SalaryDTO> getAllSalary()throws Exception{ return salaryBo1.getAllSalary(); } public EmployeeDTO searchEmployees(String eId) throws Exception { return employeeBo1.searchEmployees(eId); } public LevelDTO searchlevels(String lName) throws Exception { return levelBo1.searchlevels(lName); } public String searchSalaryId(String string) throws Exception { return salaryBo1.searchSalaryID(string) ; //To change body of generated methods, choose Tools | Templates. } }
2,584
0.727941
0.720975
82
30.512196
28.494007
113
false
false
0
0
0
0
0
0
0.390244
false
false
10
121269690a92180219d36e30d3892949f3ddfaf1
20,504,173,898,511
758a5f93be75c5642931d17f53f414e10ba5b4e1
/leetco/src/binarySearch/M_419BattleshipsInaBoard.java
b6f56ff3521f69e44db69c829874ba1ad247dca7
[]
no_license
yguozhen/leetco
https://github.com/yguozhen/leetco
efa16dfd0aa251a573b852fa766216929914e745
fac2dfa279d820d04afdc09325e8710a8e15a3a1
refs/heads/master
2022-12-01T20:12:35.895000
2020-08-15T15:28:29
2020-08-15T15:28:29
274,302,583
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package binarySearch; public class M_419BattleshipsInaBoard { //solution1 change "X" to "." in board public int countBattleships(char[][] board) { int count = 0; for(int i = 0; i < board.length; i ++){ for(int j = 0; j < board[0].length; j++){ if(board[i][j] == '.'){ continue; } if(board[i][j] == 'X'){ board[i][j] = '.'; int temp1 = i; int temp2 = j; while(i < board.length && j < board[0].length){ if(i + 1 < board.length && board[i + 1][j] == 'X'){ i = i + 1; board[i][j] = '.'; continue; } else if(j + 1 < board[0].length && board[i][j + 1] == 'X'){ j = j + 1; board[i][j] = '.'; continue; } else { count ++; break; } } i = temp1; j = temp2; } } } return count; } //solution2 without change the value in board public int countBattleships2(char[][] board) { if(board == null){ return 0; } int res = 0; for(int i = 0; i < board.length; i ++){ for(int j = 0; j < board[0].length; j ++){ if(board[i][j] == '.'){ continue; } if(i + 1 < board.length && board[i + 1][j] == 'X'){ continue; } if(j + 1 < board[0].length && board[i][j + 1] == 'X'){ continue; } res ++; } } return res; } }
UTF-8
Java
2,016
java
M_419BattleshipsInaBoard.java
Java
[]
null
[]
package binarySearch; public class M_419BattleshipsInaBoard { //solution1 change "X" to "." in board public int countBattleships(char[][] board) { int count = 0; for(int i = 0; i < board.length; i ++){ for(int j = 0; j < board[0].length; j++){ if(board[i][j] == '.'){ continue; } if(board[i][j] == 'X'){ board[i][j] = '.'; int temp1 = i; int temp2 = j; while(i < board.length && j < board[0].length){ if(i + 1 < board.length && board[i + 1][j] == 'X'){ i = i + 1; board[i][j] = '.'; continue; } else if(j + 1 < board[0].length && board[i][j + 1] == 'X'){ j = j + 1; board[i][j] = '.'; continue; } else { count ++; break; } } i = temp1; j = temp2; } } } return count; } //solution2 without change the value in board public int countBattleships2(char[][] board) { if(board == null){ return 0; } int res = 0; for(int i = 0; i < board.length; i ++){ for(int j = 0; j < board[0].length; j ++){ if(board[i][j] == '.'){ continue; } if(i + 1 < board.length && board[i + 1][j] == 'X'){ continue; } if(j + 1 < board[0].length && board[i][j + 1] == 'X'){ continue; } res ++; } } return res; } }
2,016
0.300595
0.284722
64
30.5
18.757498
83
false
false
0
0
0
0
0
0
0.5
false
false
10
122161a2661f7d2896ec1a2eaf440817e9ff9ac6
11,570,641,924,166
3099a023b6bbac55d14971a9c1a358ad82df2505
/Poppy_v1.0/src/main/java/com/ipsos/poppy/admin/UserManagementRepository.java
0ab559b9b28984637304c51ef4ee7cb19ea9fe2a
[]
no_license
arvindprem/Poppy
https://github.com/arvindprem/Poppy
7f1022ee5f23c825611f27cc055cd37d0da7b531
d6358eca9b70a41db729b5f77864a42aaa345396
refs/heads/master
2020-03-28T12:24:51.750000
2018-11-13T09:59:27
2018-11-13T09:59:27
148,295,071
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ipsos.poppy.admin; import java.io.Serializable; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.query.Query; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.fasterxml.jackson.databind.ObjectMapper; import com.ipsos.poppy.entity.Login; @Repository public class UserManagementRepository { @Autowired private SessionFactory sessionFactory; @SuppressWarnings("unchecked") public String getAllUsers() { String userJson = null; try (Session session = sessionFactory.openSession()) { Transaction trans = session.beginTransaction(); List<Login> jsonList = session.createQuery("From Login").list(); Map<String, Object> userDatamap = new HashMap<>(); userDatamap.put("data", jsonList); userJson = new ObjectMapper().writeValueAsString(userDatamap); trans.commit(); } catch (Exception e) { e.printStackTrace(); } return userJson; } public boolean edituserInfo(Login editInfo) { boolean isUpdated = false; try (Session session = sessionFactory.openSession()) { Transaction trans = session.beginTransaction(); if (checkUserNameExist(session, editInfo)) { Login loginDbValue = session.get(Login.class, editInfo.getId()); loginDbValue.setUserName(editInfo.getUserName()); loginDbValue.setCountry(editInfo.getCountry()); loginDbValue.setLevel(editInfo.getLevel()); loginDbValue.setFirstName(editInfo.getFirstName()); loginDbValue.setWatchWord(editInfo.getWatchWord()); session.update(loginDbValue); trans.commit(); isUpdated = true; } } catch (Exception e) { e.printStackTrace(); } return isUpdated; } public boolean addNewUser(Login userInfo) { boolean isAdded = false; Transaction trans = null; userInfo.setCreationDateTime(new Date()); try (Session session = sessionFactory.openSession()) { trans = session.beginTransaction(); if (checkUserNameExist(session, userInfo)) { session.save(userInfo); trans.commit(); isAdded = true; } } catch (Exception e) { e.printStackTrace(); } return isAdded; } @SuppressWarnings("unchecked") public boolean checkUserNameExist(Session session, Login userInfo) { String hql = "FROM Login WHERE UserName = :USERNAME"; if (userInfo.getId() != 0) { hql += " AND UserId <> :USERID "; } Query<Login> query = session.createQuery(hql); query.setParameter("USERNAME", userInfo.getUserName()); if (userInfo.getId() != 0) { query.setParameter("USERID", userInfo.getId()); } List<Login> validCredential = query.list(); return validCredential.isEmpty(); } public boolean deleteUserInfo(String userID) { boolean isDeleted = false; Transaction trans = null; try (Session session = sessionFactory.openSession()) { trans = session.beginTransaction(); Serializable id = Long.valueOf(userID); Object persistentInstance = session.load(Login.class, id); if (persistentInstance != null) { session.delete(persistentInstance); } trans.commit(); isDeleted = true; } catch (Exception e) { e.printStackTrace(); } return isDeleted; } @SuppressWarnings("unchecked") public String getFilteredResult(Login filtered) { Transaction trans = null; String filteredJson = null; try (Session session = sessionFactory.openSession()) { trans = session.beginTransaction(); String filterSearchQuery = queryMaker(filtered); System.out.println(filterSearchQuery); Query<Login> query = session.createQuery(filterSearchQuery); if (!filtered.getUserName().equals("")) { System.out.println(1); query.setParameter("USERNAME", filtered.getUserName()); } if (!filtered.getCountry().equals("")) { System.out.println(3); query.setParameter("COUNTRY", filtered.getCountry()); } if (!filtered.getLevel().equals("")) { query.setParameter("LEVEL", filtered.getLevel()); System.out.println(2); } List<Login> filteredList = query.list(); Map<String, Object> userDatamap = new HashMap<>(); userDatamap.put("data", filteredList); filteredJson = new ObjectMapper().writeValueAsString(userDatamap); trans.commit(); System.out.println("json " + filteredJson); } catch (Exception e) { e.printStackTrace(); } return filteredJson; } private String queryMaker(Login filtered) { String filterSearchQuery = null; StringBuilder sqlQuery = new StringBuilder("FROM Login WHERE "); if (!filtered.getUserName().equals("")) { sqlQuery.append("UserName = :USERNAME AND "); } if (!filtered.getCountry().equals("")) { sqlQuery.append("country = :COUNTRY AND "); } if (!filtered.getLevel().equals("")) { sqlQuery.append("Level = :LEVEL AND "); } filterSearchQuery = sqlQuery.toString(); filterSearchQuery = filterSearchQuery.substring(0, filterSearchQuery.lastIndexOf("AND")); return filterSearchQuery; } }
UTF-8
Java
5,061
java
UserManagementRepository.java
Java
[ { "context": "o) {\n\t\tString hql = \"FROM Login WHERE UserName = :USERNAME\";\n\t\tif (userInfo.getId() != 0) {\n\t\t\thql += \" AND ", "end": 2445, "score": 0.8948395252227783, "start": 2437, "tag": "USERNAME", "value": "USERNAME" } ]
null
[]
package com.ipsos.poppy.admin; import java.io.Serializable; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.query.Query; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.fasterxml.jackson.databind.ObjectMapper; import com.ipsos.poppy.entity.Login; @Repository public class UserManagementRepository { @Autowired private SessionFactory sessionFactory; @SuppressWarnings("unchecked") public String getAllUsers() { String userJson = null; try (Session session = sessionFactory.openSession()) { Transaction trans = session.beginTransaction(); List<Login> jsonList = session.createQuery("From Login").list(); Map<String, Object> userDatamap = new HashMap<>(); userDatamap.put("data", jsonList); userJson = new ObjectMapper().writeValueAsString(userDatamap); trans.commit(); } catch (Exception e) { e.printStackTrace(); } return userJson; } public boolean edituserInfo(Login editInfo) { boolean isUpdated = false; try (Session session = sessionFactory.openSession()) { Transaction trans = session.beginTransaction(); if (checkUserNameExist(session, editInfo)) { Login loginDbValue = session.get(Login.class, editInfo.getId()); loginDbValue.setUserName(editInfo.getUserName()); loginDbValue.setCountry(editInfo.getCountry()); loginDbValue.setLevel(editInfo.getLevel()); loginDbValue.setFirstName(editInfo.getFirstName()); loginDbValue.setWatchWord(editInfo.getWatchWord()); session.update(loginDbValue); trans.commit(); isUpdated = true; } } catch (Exception e) { e.printStackTrace(); } return isUpdated; } public boolean addNewUser(Login userInfo) { boolean isAdded = false; Transaction trans = null; userInfo.setCreationDateTime(new Date()); try (Session session = sessionFactory.openSession()) { trans = session.beginTransaction(); if (checkUserNameExist(session, userInfo)) { session.save(userInfo); trans.commit(); isAdded = true; } } catch (Exception e) { e.printStackTrace(); } return isAdded; } @SuppressWarnings("unchecked") public boolean checkUserNameExist(Session session, Login userInfo) { String hql = "FROM Login WHERE UserName = :USERNAME"; if (userInfo.getId() != 0) { hql += " AND UserId <> :USERID "; } Query<Login> query = session.createQuery(hql); query.setParameter("USERNAME", userInfo.getUserName()); if (userInfo.getId() != 0) { query.setParameter("USERID", userInfo.getId()); } List<Login> validCredential = query.list(); return validCredential.isEmpty(); } public boolean deleteUserInfo(String userID) { boolean isDeleted = false; Transaction trans = null; try (Session session = sessionFactory.openSession()) { trans = session.beginTransaction(); Serializable id = Long.valueOf(userID); Object persistentInstance = session.load(Login.class, id); if (persistentInstance != null) { session.delete(persistentInstance); } trans.commit(); isDeleted = true; } catch (Exception e) { e.printStackTrace(); } return isDeleted; } @SuppressWarnings("unchecked") public String getFilteredResult(Login filtered) { Transaction trans = null; String filteredJson = null; try (Session session = sessionFactory.openSession()) { trans = session.beginTransaction(); String filterSearchQuery = queryMaker(filtered); System.out.println(filterSearchQuery); Query<Login> query = session.createQuery(filterSearchQuery); if (!filtered.getUserName().equals("")) { System.out.println(1); query.setParameter("USERNAME", filtered.getUserName()); } if (!filtered.getCountry().equals("")) { System.out.println(3); query.setParameter("COUNTRY", filtered.getCountry()); } if (!filtered.getLevel().equals("")) { query.setParameter("LEVEL", filtered.getLevel()); System.out.println(2); } List<Login> filteredList = query.list(); Map<String, Object> userDatamap = new HashMap<>(); userDatamap.put("data", filteredList); filteredJson = new ObjectMapper().writeValueAsString(userDatamap); trans.commit(); System.out.println("json " + filteredJson); } catch (Exception e) { e.printStackTrace(); } return filteredJson; } private String queryMaker(Login filtered) { String filterSearchQuery = null; StringBuilder sqlQuery = new StringBuilder("FROM Login WHERE "); if (!filtered.getUserName().equals("")) { sqlQuery.append("UserName = :USERNAME AND "); } if (!filtered.getCountry().equals("")) { sqlQuery.append("country = :COUNTRY AND "); } if (!filtered.getLevel().equals("")) { sqlQuery.append("Level = :LEVEL AND "); } filterSearchQuery = sqlQuery.toString(); filterSearchQuery = filterSearchQuery.substring(0, filterSearchQuery.lastIndexOf("AND")); return filterSearchQuery; } }
5,061
0.712112
0.710927
179
27.273743
21.185215
91
false
false
0
0
0
0
0
0
2.424581
false
false
10
8e20419b18002074ee58a2689125d0783ceab12f
11,398,843,244,036
b9c5db63e7453664bd659c1921a0aa412c27fd88
/app/src/main/java/com/kay/accessappexercise/data/model/UserResponse.java
8180bf25e593b91348502538d38dbf0cb4ec311a
[]
no_license
Kay326/AccessAppExercise
https://github.com/Kay326/AccessAppExercise
0e29468f27fef0c6375c6515affaa1536164e912
49d0c56ba0e473d59ba212e668be5f28b8a2a345
refs/heads/master
2022-09-27T02:32:30.441000
2020-06-07T17:25:02
2020-06-07T17:25:02
269,168,491
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kay.accessappexercise.data.model; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public final class UserResponse { @Expose @SerializedName("login") private String login; @Expose @SerializedName("id") private String id; @Expose @SerializedName("avatar_url") private String avatarUrl; @Expose @SerializedName("site_admin") private boolean siteAdmin; public String getLogin() { return login; } public String getId() { return id; } public String getAvatarUrl() { return avatarUrl; } public boolean isSiteAdmin() { return siteAdmin; } }
UTF-8
Java
713
java
UserResponse.java
Java
[]
null
[]
package com.kay.accessappexercise.data.model; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public final class UserResponse { @Expose @SerializedName("login") private String login; @Expose @SerializedName("id") private String id; @Expose @SerializedName("avatar_url") private String avatarUrl; @Expose @SerializedName("site_admin") private boolean siteAdmin; public String getLogin() { return login; } public String getId() { return id; } public String getAvatarUrl() { return avatarUrl; } public boolean isSiteAdmin() { return siteAdmin; } }
713
0.650771
0.650771
39
17.282051
14.942537
50
false
false
0
0
0
0
0
0
0.282051
false
false
10
45a09d184e167a4a356ef0573fb2e102a0b21596
23,149,873,746,806
b70a707ac0e946f74ee2aae6cf5505aab07e5938
/src/main/java/com/pessoal/compras/token/RefreshTokenPostProcessor.java
69dcb90a9411f21ddb2d65b6fbd5fbc4955612a8
[]
no_license
antonio-pedro/compras-api
https://github.com/antonio-pedro/compras-api
ceeb9ca5b5cdda5aa5b150e444b6d315331f569b
dcdec83a82aa1f137188785cd8745d2d1698f8ae
refs/heads/master
2021-04-11T11:06:33.304000
2020-04-08T01:43:22
2020-04-08T01:43:22
249,014,141
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.pessoal.compras.token; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.MethodParameter; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; import org.springframework.http.server.ServletServerHttpRequest; import org.springframework.http.server.ServletServerHttpResponse; import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; import org.springframework.security.oauth2.common.OAuth2AccessToken; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; import com.pessoal.compras.config.property.ComprasApiProperty; @ControllerAdvice //É um controlador avançado que irá um pouco antes do retorno para a aplicação tira o refreshToken do corpo e coloca no cookie public class RefreshTokenPostProcessor implements ResponseBodyAdvice<OAuth2AccessToken> { //Objeto de retorno do Oauth (corpo com token e refreshToken) @Autowired private ComprasApiProperty comprasApiProperty; @Override //Este método serve para verificar se é a hora de mexer no corpo da requisição que devolve o token e o refreshToken public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) { return returnType.getMethod().getName().equals("postAccessToken"); } @Override //Este método é chamado se o nome acima for postAccessToken public OAuth2AccessToken beforeBodyWrite(OAuth2AccessToken body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) { HttpServletRequest req = ((ServletServerHttpRequest) request).getServletRequest(); //Convertendo a Requisição HttpServletResponse resp = ((ServletServerHttpResponse) response).getServletResponse();//Convertendo a Resposta DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken) body;//Converter o body para retirar o token do corpo da requisição String refreshToken = body.getRefreshToken().getValue(); //Aqui eu tiro o refreshToken do corpo da requisição adicionarRefreshTokenNoCookie(refreshToken, req, resp); //Adicionar o refreshToken no cookie removerRefreshTokenDoBody(token); return body; } private void removerRefreshTokenDoBody(DefaultOAuth2AccessToken token) { token.setRefreshToken(null);//Seto o refreshToken para null de forma ela não ficar mais no corpo da requisição } private void adicionarRefreshTokenNoCookie(String refreshToken, HttpServletRequest req, HttpServletResponse resp) { Cookie refreshTokenCookie = new Cookie("refreshToken", refreshToken); //Criar um cookie refreshTokenCookie.setHttpOnly(true);//Só existir em http refreshTokenCookie.setSecure(comprasApiProperty.getSeguranca().isEnableHttps()); // TODO: Mudar para true em producao (HTTPS) refreshTokenCookie.setPath(req.getContextPath() + "/oauth/token");//Se tiver alguma requisição para o path refreshTokenCookie.setMaxAge(2592000); //tempo que o cookie vai expirar(30 dias) resp.addCookie(refreshTokenCookie);//adiciono o cookie na resposta } }
UTF-8
Java
3,498
java
RefreshTokenPostProcessor.java
Java
[]
null
[]
package com.pessoal.compras.token; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.MethodParameter; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; import org.springframework.http.server.ServletServerHttpRequest; import org.springframework.http.server.ServletServerHttpResponse; import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; import org.springframework.security.oauth2.common.OAuth2AccessToken; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; import com.pessoal.compras.config.property.ComprasApiProperty; @ControllerAdvice //É um controlador avançado que irá um pouco antes do retorno para a aplicação tira o refreshToken do corpo e coloca no cookie public class RefreshTokenPostProcessor implements ResponseBodyAdvice<OAuth2AccessToken> { //Objeto de retorno do Oauth (corpo com token e refreshToken) @Autowired private ComprasApiProperty comprasApiProperty; @Override //Este método serve para verificar se é a hora de mexer no corpo da requisição que devolve o token e o refreshToken public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) { return returnType.getMethod().getName().equals("postAccessToken"); } @Override //Este método é chamado se o nome acima for postAccessToken public OAuth2AccessToken beforeBodyWrite(OAuth2AccessToken body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) { HttpServletRequest req = ((ServletServerHttpRequest) request).getServletRequest(); //Convertendo a Requisição HttpServletResponse resp = ((ServletServerHttpResponse) response).getServletResponse();//Convertendo a Resposta DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken) body;//Converter o body para retirar o token do corpo da requisição String refreshToken = body.getRefreshToken().getValue(); //Aqui eu tiro o refreshToken do corpo da requisição adicionarRefreshTokenNoCookie(refreshToken, req, resp); //Adicionar o refreshToken no cookie removerRefreshTokenDoBody(token); return body; } private void removerRefreshTokenDoBody(DefaultOAuth2AccessToken token) { token.setRefreshToken(null);//Seto o refreshToken para null de forma ela não ficar mais no corpo da requisição } private void adicionarRefreshTokenNoCookie(String refreshToken, HttpServletRequest req, HttpServletResponse resp) { Cookie refreshTokenCookie = new Cookie("refreshToken", refreshToken); //Criar um cookie refreshTokenCookie.setHttpOnly(true);//Só existir em http refreshTokenCookie.setSecure(comprasApiProperty.getSeguranca().isEnableHttps()); // TODO: Mudar para true em producao (HTTPS) refreshTokenCookie.setPath(req.getContextPath() + "/oauth/token");//Se tiver alguma requisição para o path refreshTokenCookie.setMaxAge(2592000); //tempo que o cookie vai expirar(30 dias) resp.addCookie(refreshTokenCookie);//adiciono o cookie na resposta } }
3,498
0.821583
0.816115
64
53.296875
44.696083
151
false
false
0
0
0
0
0
0
1.609375
false
false
10
8a31efc9a40bc1e3098e13a9e0b99e6679deabe5
18,717,467,506,605
2444919c01029a62cea781fa0db5b54f30fbc26f
/core/src/com/ludux/twitchgame/battle/BattleScreen.java
b651a6b4d5dc6c40604aaaa2f3a83eb388cbf368
[]
no_license
kleitus448/TwitchGame
https://github.com/kleitus448/TwitchGame
0f76aca4eb0a7ce3777074b0116fcc8e95a637a8
271fc2837e3046b8d9d926e4dfee9ab158f5d9a8
refs/heads/master
2020-04-07T06:24:58.732000
2018-03-07T06:11:40
2018-03-07T06:11:40
113,656,329
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ludux.twitchgame.battle; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.ScreenAdapter; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.scenes.scene2d.Group; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.utils.viewport.FitViewport; import com.ludux.twitchgame.Server.Connection.Client; import com.ludux.twitchgame.Const; import com.ludux.twitchgame.Main; import com.ludux.twitchgame.Server.Connection.PreparingBattle; import com.ludux.twitchgame.battle.battleactors.*; import com.ludux.twitchgame.label.BattleLabel; public class BattleScreen extends ScreenAdapter { private Stage stage; private Main app; public BattleScreen(PreparingBattle battle, Client client) { Gdx.graphics.setResizable(true); app = (Main) Gdx.app.getApplicationListener(); //Изменение матрицы проекции для полосок здоровья и маны ShapeRenderer renderer = app.getRenderer(); Matrix4 matrix4 = renderer.getProjectionMatrix().setToOrtho2D (0,0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); renderer.setProjectionMatrix(matrix4); this.stage = app.getStage(); this.stage.setViewport(new FitViewport(Const.LANDSCAPE_VIEWPORT_WIDTH, Const.LANDSCAPE_VIEWPORT_HEIGHT)); this.stage.getViewport().update(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), true); this.stage.addActor(new BALocation()); this.stage.addActor(new ElfGroup(renderer)); this.stage.addActor(new Inventory()); this.stage.addActor(new BattleButton("Закончить ход", app.getCommandListener().getClient())); //app.getMusic().stop(); //app.setMusic(Gdx.audio.newMusic(Gdx.files.internal("core/assets/Music/Guiles_Theme.mp3"))); app.getCommandListener().changeTouch(); } @Override public void render(float delta) { String name = app.getCommandListener().getClient().name; stage.addActor(BattleLabel.getBattleLabels(app.getCommandListener().getBattle(), name)); stage.act(); stage.draw(); stage.getActors().pop(); } @Override public void resize(int width, int height) {stage.getViewport().update(width,height);} }
UTF-8
Java
2,350
java
BattleScreen.java
Java
[]
null
[]
package com.ludux.twitchgame.battle; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.ScreenAdapter; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.scenes.scene2d.Group; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.utils.viewport.FitViewport; import com.ludux.twitchgame.Server.Connection.Client; import com.ludux.twitchgame.Const; import com.ludux.twitchgame.Main; import com.ludux.twitchgame.Server.Connection.PreparingBattle; import com.ludux.twitchgame.battle.battleactors.*; import com.ludux.twitchgame.label.BattleLabel; public class BattleScreen extends ScreenAdapter { private Stage stage; private Main app; public BattleScreen(PreparingBattle battle, Client client) { Gdx.graphics.setResizable(true); app = (Main) Gdx.app.getApplicationListener(); //Изменение матрицы проекции для полосок здоровья и маны ShapeRenderer renderer = app.getRenderer(); Matrix4 matrix4 = renderer.getProjectionMatrix().setToOrtho2D (0,0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); renderer.setProjectionMatrix(matrix4); this.stage = app.getStage(); this.stage.setViewport(new FitViewport(Const.LANDSCAPE_VIEWPORT_WIDTH, Const.LANDSCAPE_VIEWPORT_HEIGHT)); this.stage.getViewport().update(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), true); this.stage.addActor(new BALocation()); this.stage.addActor(new ElfGroup(renderer)); this.stage.addActor(new Inventory()); this.stage.addActor(new BattleButton("Закончить ход", app.getCommandListener().getClient())); //app.getMusic().stop(); //app.setMusic(Gdx.audio.newMusic(Gdx.files.internal("core/assets/Music/Guiles_Theme.mp3"))); app.getCommandListener().changeTouch(); } @Override public void render(float delta) { String name = app.getCommandListener().getClient().name; stage.addActor(BattleLabel.getBattleLabels(app.getCommandListener().getBattle(), name)); stage.act(); stage.draw(); stage.getActors().pop(); } @Override public void resize(int width, int height) {stage.getViewport().update(width,height);} }
2,350
0.719337
0.714972
55
40.618183
29.259026
113
false
false
0
0
0
0
0
0
0.872727
false
false
10
e24f734557a4b4169be9001aa70c69cb07a935a6
25,744,034,001,211
5dfc341a547e5637d84748b18de667af31fd8bdf
/src/com/soledede/connector/udp/UDPReactor.java
6cea6a47853d45e59f74e60d4a15d83083708481
[]
no_license
wbj0110/TChat
https://github.com/wbj0110/TChat
fca685e8545b1c7e61b8cc17ee86d302ca3cfb85
5621c7a5df2f69cc00d400a89509c215f88d8695
refs/heads/master
2016-09-06T09:32:13.007000
2014-11-13T07:56:49
2014-11-13T07:56:49
26,576,537
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.soledede.connector.udp; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.nio.channels.DatagramChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.util.Iterator; import java.util.Set; /** * UDP数据包接受 * * 与TCP不同的就是使用DatagramChannel来代替了TCP中的ServerSocketChannel和SocketChannel, * DatagramChannel是专门用于UDP的SelectableChannel。 *另外一个不同点是,UDP中没有了Acceptor类,不用专门处理建立事件的相关事件,直接读取或写入数据 */ public class UDPReactor implements Runnable { private final static String module = UDPReactor.class.getName(); private final Selector selector; public UDPReactor(int port) throws IOException { selector = Selector.open(); InetSocketAddress address = new InetSocketAddress(InetAddress.getLocalHost(), port);//绑定socketAddress DatagramChannel channelRec = openDatagramChannel(); channelRec.socket().bind(address); //绑定socketAddress //向selector注册该channel SelectionKey key = channelRec.register(selector, SelectionKey.OP_READ); //向selector注册该channel key.attach(new UDPHandler(key, channelRec));//当事件触发后交由UDPHandler处理 } //生成一个DatagramChannel实例 private DatagramChannel openDatagramChannel() { DatagramChannel channel = null; try { channel = DatagramChannel.open(); channel.configureBlocking(false); } catch (Exception e) { } return channel; } public void run() { // normally in a new Thread while (!Thread.interrupted()) { try { selector.select(); Set selected = selector.selectedKeys(); Iterator it = selected.iterator(); //Selector如果发现channel有WRITE或READ事件发生,下列遍历就会进行。 while (it.hasNext()) //触发SocketReadHandler dispatch( (SelectionKey) (it.next())); selected.clear(); } catch (IOException ex) { } } } //运行Acceptor或SocketReadHandler private void dispatch(SelectionKey k) { Runnable r = (Runnable) (k.attachment()); if (r != null) { r.run(); } } }
UTF-8
Java
2,294
java
UDPReactor.java
Java
[]
null
[]
package com.soledede.connector.udp; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.nio.channels.DatagramChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.util.Iterator; import java.util.Set; /** * UDP数据包接受 * * 与TCP不同的就是使用DatagramChannel来代替了TCP中的ServerSocketChannel和SocketChannel, * DatagramChannel是专门用于UDP的SelectableChannel。 *另外一个不同点是,UDP中没有了Acceptor类,不用专门处理建立事件的相关事件,直接读取或写入数据 */ public class UDPReactor implements Runnable { private final static String module = UDPReactor.class.getName(); private final Selector selector; public UDPReactor(int port) throws IOException { selector = Selector.open(); InetSocketAddress address = new InetSocketAddress(InetAddress.getLocalHost(), port);//绑定socketAddress DatagramChannel channelRec = openDatagramChannel(); channelRec.socket().bind(address); //绑定socketAddress //向selector注册该channel SelectionKey key = channelRec.register(selector, SelectionKey.OP_READ); //向selector注册该channel key.attach(new UDPHandler(key, channelRec));//当事件触发后交由UDPHandler处理 } //生成一个DatagramChannel实例 private DatagramChannel openDatagramChannel() { DatagramChannel channel = null; try { channel = DatagramChannel.open(); channel.configureBlocking(false); } catch (Exception e) { } return channel; } public void run() { // normally in a new Thread while (!Thread.interrupted()) { try { selector.select(); Set selected = selector.selectedKeys(); Iterator it = selected.iterator(); //Selector如果发现channel有WRITE或READ事件发生,下列遍历就会进行。 while (it.hasNext()) //触发SocketReadHandler dispatch( (SelectionKey) (it.next())); selected.clear(); } catch (IOException ex) { } } } //运行Acceptor或SocketReadHandler private void dispatch(SelectionKey k) { Runnable r = (Runnable) (k.attachment()); if (r != null) { r.run(); } } }
2,294
0.704678
0.704678
79
24.987341
22.809332
99
false
false
0
0
0
0
0
0
0.392405
false
false
10
5166027179ac65093d4d08a35b3aa4dd7b9bc7c4
39,333,310,532,894
81e4329f1b6133e019c1ad518b205b66f569778f
/Server/Server/Common/SerializableLock.java
104e31cbbebae3600e0573ab260f779ee5c03dc7
[]
no_license
yiqiaowang/comp512
https://github.com/yiqiaowang/comp512
6cb6bb2b18b053601f9471bcabc6b438170ae837
36a61dc083b17c8b12eb13381ae2de1422e437c1
refs/heads/master
2020-03-28T23:00:42.985000
2018-11-30T16:15:26
2018-11-30T16:15:26
149,270,890
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package Server.Common; import java.io.Serializable; public final class SerializableLock implements Serializable { }
UTF-8
Java
118
java
SerializableLock.java
Java
[]
null
[]
package Server.Common; import java.io.Serializable; public final class SerializableLock implements Serializable { }
118
0.822034
0.822034
6
18.666666
21.982317
61
false
false
0
0
0
0
0
0
0.333333
false
false
10
a600220771d2c0f18d91336d3293c7ad2c08f6a3
36,730,560,359,842
3c484a02e05a82619eb160b9dd8c431f479161f2
/src/power_plant/PowerProfile.java
6fcba3839d13901192e962d2e3c1fad057992b19
[]
no_license
schmidie/powerplant-controller
https://github.com/schmidie/powerplant-controller
ce34ecf74069bc12da1a2cc7c115d7229ecd0e65
1254f5123aa1cfd9b8c71d0626eaeaea3e2c1f76
refs/heads/master
2021-01-10T04:06:34.188000
2015-12-27T16:00:08
2015-12-27T16:00:08
48,646,081
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package power_plant; import java.time.Instant; import java.time.ZonedDateTime; import java.util.LinkedList; /* * PowerProfile representing a Profile with: * start, end and a series of <time|power> tuples * A valid PowerProfile needs to satisfy the following constrains: * * valid time-interval (start <= end) * * valid series of timestamp/power tuples within given time and power range * * E.g.: <time1|power1>,<time2|power2> => * start <= time1 <= time2 <= end * -6000 <= power1 <= 6000 and -6000 <= power2 <= 6000 */ public class PowerProfile { private ZonedDateTime start = null; private ZonedDateTime end = null; // We use LinkedList for the power/time tuples as we need to keep the order private LinkedList<PowerTimeTuple> plan = new LinkedList<PowerTimeTuple>(); /* * PowerProfile Validations */ /* * validateTuple(Integer power, ZonedDateTime dateTime) * returns: validateTimeRange(dateTime) and validatePowerRange(power) */ private boolean validateTuple(Integer power, ZonedDateTime dateTime){ if(!validatePowerRange(power) || !validateTimeRange(dateTime)){ return false; } return true; } /* * validateTimeRange(ZonedDateTime dateTime) * returns: start <= dateTime <= end and last-dateTime <= dateTime */ private boolean validateTimeRange(ZonedDateTime dateTime){ boolean retval = true; Instant dateTime_inst = dateTime.toInstant(); if (start != null && end != null ){ if (dateTime_inst.isBefore(start.toInstant()) || dateTime_inst.isAfter(end.toInstant())){ retval = false; } else if(!plan.isEmpty() && (dateTime_inst.isBefore(plan.getLast().getTime().toInstant()))){ retval = false; } } else{ retval = false; } return retval; } /* * validatePowerRange(Integer power) * returns: -6000 <= power <= 6000 */ private boolean validatePowerRange(Integer power){ if(Math.abs(power) > 6000 ){ return false; } return true; } /* * PowerProfile Setter and Getter * Note: * We create only valid PowerProfiles! * So always check the given constrains setting start, end and the <time|power> tuples */ // Setter public boolean setStart(ZonedDateTime start) { // We can set a start if no end-date is set. if(this.end == null || start.toInstant().isBefore(this.end.toInstant())){ this.start = start; return true; } return false; } public boolean setEnd(ZonedDateTime end) { // We can set a end if no start-date is set. if(this.start == null || end.toInstant().isAfter(this.start.toInstant())){ this.end = end; return true; } return false; } public boolean pushNextPlanEntry(Integer power, ZonedDateTime dateTime) { if(validateTuple(power,dateTime)){ PowerTimeTuple ptt = new PowerTimeTuple(power, dateTime); plan.add(ptt); return true; } return false; } // Getter public ZonedDateTime getStart() { return start; } public ZonedDateTime getEnd() { return end; } public PowerTimeTuple pullAndRemoveNextPlanEntry() { return plan.poll(); } public LinkedList<PowerTimeTuple> getPlan(){ return plan; } }
UTF-8
Java
3,233
java
PowerProfile.java
Java
[]
null
[]
package power_plant; import java.time.Instant; import java.time.ZonedDateTime; import java.util.LinkedList; /* * PowerProfile representing a Profile with: * start, end and a series of <time|power> tuples * A valid PowerProfile needs to satisfy the following constrains: * * valid time-interval (start <= end) * * valid series of timestamp/power tuples within given time and power range * * E.g.: <time1|power1>,<time2|power2> => * start <= time1 <= time2 <= end * -6000 <= power1 <= 6000 and -6000 <= power2 <= 6000 */ public class PowerProfile { private ZonedDateTime start = null; private ZonedDateTime end = null; // We use LinkedList for the power/time tuples as we need to keep the order private LinkedList<PowerTimeTuple> plan = new LinkedList<PowerTimeTuple>(); /* * PowerProfile Validations */ /* * validateTuple(Integer power, ZonedDateTime dateTime) * returns: validateTimeRange(dateTime) and validatePowerRange(power) */ private boolean validateTuple(Integer power, ZonedDateTime dateTime){ if(!validatePowerRange(power) || !validateTimeRange(dateTime)){ return false; } return true; } /* * validateTimeRange(ZonedDateTime dateTime) * returns: start <= dateTime <= end and last-dateTime <= dateTime */ private boolean validateTimeRange(ZonedDateTime dateTime){ boolean retval = true; Instant dateTime_inst = dateTime.toInstant(); if (start != null && end != null ){ if (dateTime_inst.isBefore(start.toInstant()) || dateTime_inst.isAfter(end.toInstant())){ retval = false; } else if(!plan.isEmpty() && (dateTime_inst.isBefore(plan.getLast().getTime().toInstant()))){ retval = false; } } else{ retval = false; } return retval; } /* * validatePowerRange(Integer power) * returns: -6000 <= power <= 6000 */ private boolean validatePowerRange(Integer power){ if(Math.abs(power) > 6000 ){ return false; } return true; } /* * PowerProfile Setter and Getter * Note: * We create only valid PowerProfiles! * So always check the given constrains setting start, end and the <time|power> tuples */ // Setter public boolean setStart(ZonedDateTime start) { // We can set a start if no end-date is set. if(this.end == null || start.toInstant().isBefore(this.end.toInstant())){ this.start = start; return true; } return false; } public boolean setEnd(ZonedDateTime end) { // We can set a end if no start-date is set. if(this.start == null || end.toInstant().isAfter(this.start.toInstant())){ this.end = end; return true; } return false; } public boolean pushNextPlanEntry(Integer power, ZonedDateTime dateTime) { if(validateTuple(power,dateTime)){ PowerTimeTuple ptt = new PowerTimeTuple(power, dateTime); plan.add(ptt); return true; } return false; } // Getter public ZonedDateTime getStart() { return start; } public ZonedDateTime getEnd() { return end; } public PowerTimeTuple pullAndRemoveNextPlanEntry() { return plan.poll(); } public LinkedList<PowerTimeTuple> getPlan(){ return plan; } }
3,233
0.662233
0.651098
119
25.168068
25.211149
94
false
false
0
0
0
0
0
0
1.957983
false
false
10
5e6a7da3e537163c1c86db528e652ad76bc22748
38,689,065,430,277
d20dd1bcb88ad4880174c11e9c071ab65225620f
/src/main/java/de/tum/in/www1/artemis/domain/notification/NotificationTargetFactory.java
dd8fccb1195a2510f96cc317d628a6e00edce99e
[ "MIT" ]
permissive
ls1intum/Artemis
https://github.com/ls1intum/Artemis
17152300df61ba0f544f266850cbd5e12e8b68a7
16fa6a5dd9e46106255100477c7f542c96ece4af
refs/heads/develop
2023-09-03T20:06:17.874000
2023-09-03T07:33:38
2023-09-03T07:33:38
69,562,331
343
432
MIT
false
2023-09-14T13:25:51
2016-09-29T11:46:05
2023-09-14T08:47:41
2023-09-14T13:25:50
302,097
361
252
480
Java
false
false
package de.tum.in.www1.artemis.domain.notification; import de.tum.in.www1.artemis.domain.*; import de.tum.in.www1.artemis.domain.metis.AnswerPost; import de.tum.in.www1.artemis.domain.metis.Post; import de.tum.in.www1.artemis.domain.metis.conversation.Conversation; import de.tum.in.www1.artemis.domain.tutorialgroups.TutorialGroup; public class NotificationTargetFactory { // shared constants public static final String COURSES_TEXT = "courses"; public static final String PROGRAMMING_EXERCISES_TEXT = "programming-exercises"; public static final String COURSE_MANAGEMENT_TEXT = "course-management"; public static final String EXERCISES_TEXT = "exercises"; public static final String EXAMS_TEXT = "exams"; public static final String LECTURES_TEXT = "lectures"; public static final String TUTORIAL_GROUP_MANAGEMENT_TEXT = "tutorial-groups-management"; public static final String TUTORIAL_GROUPS_TEXT = "tutorial-groups"; public static final String NEW_MESSAGE_TEXT = "new-message"; public static final String NEW_REPLY_TEXT = "new-reply"; public static final String MESSAGE_TEXT = "message"; public static final String CONVERSATION_TEXT = "conversation"; public static final String CONVERSATION_CREATION_TEXT = "conversation-creation"; public static final String CONVERSATION_DELETION_TEXT = "conversation-deletion"; public static final String ATTACHMENT_UPDATED_TEXT = "attachmentUpdated"; public static final String EXERCISE_RELEASED_TEXT = "exerciseReleased"; public static final String EXERCISE_UPDATED_TEXT = "exerciseUpdated"; public static final String DUPLICATE_TEST_CASE_TEXT = "duplicateTestCase"; public static final String COURSE_ARCHIVE_UPDATED_TEXT = "courseArchiveUpdated"; public static final String EXAM_ARCHIVE_UPDATED_TEXT = "examArchiveUpdated"; public static final String PLAGIARISM_TEXT = "plagiarism-cases"; public static final String PLAGIARISM_DETECTED_TEXT = "plagiarismDetected"; public static final String PRIVACY = "privacy"; // EXERCISE related targets /** * Create the needed target for "ExerciseReleased" notifications * * @param exercise that was released * @return the final target property */ public static NotificationTarget createExerciseReleasedTarget(Exercise exercise) { return createExerciseTarget(exercise, EXERCISE_RELEASED_TEXT); } /** * Create the needed target for "ExerciseUpdated" notifications * * @param exercise that was updated * @return the final target property */ public static NotificationTarget createExerciseUpdatedTarget(Exercise exercise) { return createExerciseTarget(exercise, EXERCISE_UPDATED_TEXT); } /** * Create a NotificationTarget for a GroupNotification for an ProgrammingExercise in an Exam or if duplicated test cases were detected. * * @param programmingExercise for which to create the notification * @param message to use for the notification * @return the final NotificationTarget for this case */ public static NotificationTarget createExamProgrammingExerciseOrTestCaseTarget(ProgrammingExercise programmingExercise, String message) { NotificationTarget target = new NotificationTarget(PROGRAMMING_EXERCISES_TEXT, programmingExercise.getCourseViaExerciseGroupOrCourseMember().getId(), COURSE_MANAGEMENT_TEXT); target.setIdentifier(programmingExercise.getId()); target.setMessage(message); return target; } /** * Create a NotificationTarget for a GroupNotification for an Exercise in an Exam including the updated Problem Statement. * * @param exercise for which to create the notification * @return the final NotificationTarget for this case */ public static NotificationTarget createExamExerciseTargetWithExerciseUpdate(Exercise exercise) { NotificationTarget target = new NotificationTarget(EXAMS_TEXT, exercise.getCourseViaExerciseGroupOrCourseMember().getId(), COURSES_TEXT); target.setProblemStatement(exercise.getProblemStatement()); target.setExerciseId(exercise.getId()); target.setExamId(exercise.getExamViaExerciseGroupOrCourseMember().getId()); return target; } /** * Create a NotificationTarget for a GroupNotification for an Exercise. * * @param exercise for which to create the notification * @param message to use for the notification * @return the final NotificationTarget for this case */ public static NotificationTarget createExerciseTarget(Exercise exercise, String message) { return new NotificationTarget(message, exercise.getId(), EXERCISES_TEXT, exercise.getCourseViaExerciseGroupOrCourseMember().getId(), COURSES_TEXT); } /** * Create a NotificationTarget for a SingleUserNotification for a successful data export creation * * @param dataExport the data export that was created * @param message to use for the notification * @return the final NotificationTarget for this case */ public static NotificationTarget createDataExportCreatedTarget(DataExport dataExport, String message) { NotificationTarget notificationTarget = new NotificationTarget(); notificationTarget.setEntity(message); notificationTarget.setIdentifier(dataExport.getId()); notificationTarget.setMainPage(PRIVACY); return notificationTarget; } /** * Create a NotificationTarget for a SingleUserNotification for a failed data export creation * * @param message to use for the notification * @return the final NotificationTarget for this case */ public static NotificationTarget createDataExportFailedTarget(String message) { NotificationTarget notificationTarget = new NotificationTarget(); notificationTarget.setEntity(message); notificationTarget.setMainPage(PRIVACY); return notificationTarget; } /** * Create a NotificationTarget for a GroupNotification for a duplicate test case. * * @param exercise with duplicated test cases * @return the final NotificationTarget for this case */ public static NotificationTarget createDuplicateTestCaseTarget(Exercise exercise) { return new NotificationTarget(DUPLICATE_TEST_CASE_TEXT, exercise.getId(), PROGRAMMING_EXERCISES_TEXT, exercise.getCourseViaExerciseGroupOrCourseMember().getId(), COURSE_MANAGEMENT_TEXT); } // LECTURE related targets /** * Create a NotificationTarget for a GroupNotification for a Lecture. * * @param lecture for which to create the notification * @param message to use for the notification * @return the final NotificationTarget for this case */ public static NotificationTarget createLectureTarget(Lecture lecture, String message) { return new NotificationTarget(message, lecture.getId(), LECTURES_TEXT, lecture.getCourse().getId(), COURSES_TEXT); } /** * Create the needed target for "AttachmentUpdated" notifications * * @param lecture where an attachment was updated * @return the final NotificationTarget */ public static NotificationTarget createAttachmentUpdatedTarget(Lecture lecture) { return createLectureTarget(lecture, ATTACHMENT_UPDATED_TEXT); } // COURSE related targets /** * Create a NotificationTarget for a GroupNotification for a Course. * * @param course for which to create the notification * @param message to use for the notification * @return the final NotificationTarget for this case */ public static NotificationTarget createCourseTarget(Course course, String message) { return new NotificationTarget(message, course.getId(), COURSES_TEXT, course.getId(), COURSES_TEXT); } // POST related targets /** * Create a NotificationTarget for "LecturePost" notifications * * @param post which contains the needed lecture * @param course the post belongs to * @return the final NotificationTarget */ public static NotificationTarget createLecturePostTarget(Post post, Course course) { NotificationTarget target = new NotificationTarget(post.getId(), course.getId()); target.setLectureId(post.getLecture().getId()); return target; } /** * Create a NotificationTarget for "ExercisePost" notifications * * @param post which contains the needed exercise * @param course the post belongs to * @return the final NotificationTarget */ public static NotificationTarget createExercisePostTarget(Post post, Course course) { NotificationTarget target = new NotificationTarget(post.getId(), course.getId()); target.setExerciseId(post.getExercise().getId()); return target; } /** * Create a NotificationTarget for "CoursePost" notifications * * @param post course-wide post * @param course the post belongs to * @return the final NotificationTarget */ public static NotificationTarget createCoursePostTarget(Post post, Course course) { return new NotificationTarget(post.getId(), course.getId()); } // Plagiarism related targets /** * Create a NotificationTarget for plagiarism case related notifications * * @param plagiarismCaseId is the id of the PlagiarismCase * @param courseId of the Course * @return the final NotificationTarget */ public static NotificationTarget createPlagiarismCaseTarget(Long plagiarismCaseId, Long courseId) { return new NotificationTarget(PLAGIARISM_DETECTED_TEXT, plagiarismCaseId, PLAGIARISM_TEXT, courseId, COURSES_TEXT); } // Tutorial Group related targets /** * Create a NotificationTarget for notifications related to a Tutorial Group. * * @param tutorialGroup that is related to the notification * @param courseId of the course to which the tutorial group belongs * @param isManagement true if the notification should link to the tutorial group management page * @param isDetailPage true if the notification should lik to the detail page of the tutorial group * @return the created NotificationTarget */ public static NotificationTarget createTutorialGroupTarget(TutorialGroup tutorialGroup, Long courseId, boolean isManagement, boolean isDetailPage) { var notificationTarget = new NotificationTarget(); if (isDetailPage) { notificationTarget.setIdentifier(tutorialGroup.getId()); } notificationTarget.setEntity(isManagement ? TUTORIAL_GROUP_MANAGEMENT_TEXT : TUTORIAL_GROUPS_TEXT); notificationTarget.setCourseId(courseId); notificationTarget.setMainPage(isManagement ? COURSE_MANAGEMENT_TEXT : COURSES_TEXT); return notificationTarget; } // Conversation related targets /** * Create a NotificationTarget for notifications related to a new message in conversation. * * @param message that is related to the notification * @param courseId of the course to which the conversation belongs * @return the created NotificationTarget */ public static NotificationTarget createConversationMessageTarget(Post message, Long courseId) { var notificationTarget = new NotificationTarget(NEW_MESSAGE_TEXT, message.getId(), MESSAGE_TEXT, courseId, COURSES_TEXT); notificationTarget.setConversationId(message.getConversation().getId()); return notificationTarget; } /** * Create a NotificationTarget for notifications related to a new conversation creation. * * @param conversation that is related to the notification * @param courseId of the course to which the conversation belongs * @return the created NotificationTarget */ public static NotificationTarget createConversationCreationTarget(Conversation conversation, Long courseId) { var notificationTarget = new NotificationTarget(CONVERSATION_CREATION_TEXT, conversation.getId(), CONVERSATION_TEXT, courseId, COURSES_TEXT); notificationTarget.setConversationId(conversation.getId()); return notificationTarget; } /** * Create a NotificationTarget for notifications related to a new message reply in conversation. * * @param messageReply that is related to the notification * @param courseId of the course to which the tutorial group belongs * @return the created NotificationTarget */ public static NotificationTarget createMessageReplyTarget(AnswerPost messageReply, Long courseId) { var notificationTarget = new NotificationTarget(NEW_REPLY_TEXT, messageReply.getPost().getId(), MESSAGE_TEXT, courseId, COURSES_TEXT); notificationTarget.setConversationId(messageReply.getPost().getConversation().getId()); return notificationTarget; } /** * Create a NotificationTarget for notifications related to conversation deletion. * * @param conversation that is related to the notification * @param courseId of the course to which the tutorial group belongs * @return the created NotificationTarget */ public static NotificationTarget createConversationDeletionTarget(Conversation conversation, Long courseId) { var notificationTarget = new NotificationTarget(CONVERSATION_DELETION_TEXT, conversation.getId(), CONVERSATION_TEXT, courseId, COURSES_TEXT); notificationTarget.setConversationId(conversation.getId()); return notificationTarget; } /// URL/Link related methods /** * Extracts a viable URL from the provided notification and baseUrl * * @param notification which transient target property will be used for creating the URL * @param baseUrl the prefix (depends on current set up (e.g. "http://localhost:9000/courses")) * @return viable URL to the notification related page */ public static String extractNotificationUrl(Notification notification, String baseUrl) { NotificationTarget target = notification.getTargetTransient(); if (target == null) { return ""; } StringBuilder url = new StringBuilder(baseUrl); if (target.getMainPage() != null) { url.append("/").append(target.getMainPage()); } if (target.getCourseId() != null) { url.append("/").append(target.getCourseId()); } if (target.getEntity() != null) { url.append("/").append(target.getEntity()); } if (target.getIdentifier() != null) { url.append("/").append(target.getIdentifier()); } return url.toString(); } /** * Extracts a viable URL from the provided notification that is based on a Post and baseUrl * * @param post which information will be needed to create the URL * @param baseUrl the prefix (depends on current set up (e.g. "http://localhost:9000/courses")) * @return viable URL to the notification related page */ public static String extractNotificationUrl(Post post, String baseUrl) { // e.g. http://localhost:8080/courses/1/discussion?searchText=%2382 for announcement post return baseUrl + "/courses/" + post.getCourse().getId() + "/discussion?searchText=%23" + post.getId(); } }
UTF-8
Java
15,569
java
NotificationTargetFactory.java
Java
[]
null
[]
package de.tum.in.www1.artemis.domain.notification; import de.tum.in.www1.artemis.domain.*; import de.tum.in.www1.artemis.domain.metis.AnswerPost; import de.tum.in.www1.artemis.domain.metis.Post; import de.tum.in.www1.artemis.domain.metis.conversation.Conversation; import de.tum.in.www1.artemis.domain.tutorialgroups.TutorialGroup; public class NotificationTargetFactory { // shared constants public static final String COURSES_TEXT = "courses"; public static final String PROGRAMMING_EXERCISES_TEXT = "programming-exercises"; public static final String COURSE_MANAGEMENT_TEXT = "course-management"; public static final String EXERCISES_TEXT = "exercises"; public static final String EXAMS_TEXT = "exams"; public static final String LECTURES_TEXT = "lectures"; public static final String TUTORIAL_GROUP_MANAGEMENT_TEXT = "tutorial-groups-management"; public static final String TUTORIAL_GROUPS_TEXT = "tutorial-groups"; public static final String NEW_MESSAGE_TEXT = "new-message"; public static final String NEW_REPLY_TEXT = "new-reply"; public static final String MESSAGE_TEXT = "message"; public static final String CONVERSATION_TEXT = "conversation"; public static final String CONVERSATION_CREATION_TEXT = "conversation-creation"; public static final String CONVERSATION_DELETION_TEXT = "conversation-deletion"; public static final String ATTACHMENT_UPDATED_TEXT = "attachmentUpdated"; public static final String EXERCISE_RELEASED_TEXT = "exerciseReleased"; public static final String EXERCISE_UPDATED_TEXT = "exerciseUpdated"; public static final String DUPLICATE_TEST_CASE_TEXT = "duplicateTestCase"; public static final String COURSE_ARCHIVE_UPDATED_TEXT = "courseArchiveUpdated"; public static final String EXAM_ARCHIVE_UPDATED_TEXT = "examArchiveUpdated"; public static final String PLAGIARISM_TEXT = "plagiarism-cases"; public static final String PLAGIARISM_DETECTED_TEXT = "plagiarismDetected"; public static final String PRIVACY = "privacy"; // EXERCISE related targets /** * Create the needed target for "ExerciseReleased" notifications * * @param exercise that was released * @return the final target property */ public static NotificationTarget createExerciseReleasedTarget(Exercise exercise) { return createExerciseTarget(exercise, EXERCISE_RELEASED_TEXT); } /** * Create the needed target for "ExerciseUpdated" notifications * * @param exercise that was updated * @return the final target property */ public static NotificationTarget createExerciseUpdatedTarget(Exercise exercise) { return createExerciseTarget(exercise, EXERCISE_UPDATED_TEXT); } /** * Create a NotificationTarget for a GroupNotification for an ProgrammingExercise in an Exam or if duplicated test cases were detected. * * @param programmingExercise for which to create the notification * @param message to use for the notification * @return the final NotificationTarget for this case */ public static NotificationTarget createExamProgrammingExerciseOrTestCaseTarget(ProgrammingExercise programmingExercise, String message) { NotificationTarget target = new NotificationTarget(PROGRAMMING_EXERCISES_TEXT, programmingExercise.getCourseViaExerciseGroupOrCourseMember().getId(), COURSE_MANAGEMENT_TEXT); target.setIdentifier(programmingExercise.getId()); target.setMessage(message); return target; } /** * Create a NotificationTarget for a GroupNotification for an Exercise in an Exam including the updated Problem Statement. * * @param exercise for which to create the notification * @return the final NotificationTarget for this case */ public static NotificationTarget createExamExerciseTargetWithExerciseUpdate(Exercise exercise) { NotificationTarget target = new NotificationTarget(EXAMS_TEXT, exercise.getCourseViaExerciseGroupOrCourseMember().getId(), COURSES_TEXT); target.setProblemStatement(exercise.getProblemStatement()); target.setExerciseId(exercise.getId()); target.setExamId(exercise.getExamViaExerciseGroupOrCourseMember().getId()); return target; } /** * Create a NotificationTarget for a GroupNotification for an Exercise. * * @param exercise for which to create the notification * @param message to use for the notification * @return the final NotificationTarget for this case */ public static NotificationTarget createExerciseTarget(Exercise exercise, String message) { return new NotificationTarget(message, exercise.getId(), EXERCISES_TEXT, exercise.getCourseViaExerciseGroupOrCourseMember().getId(), COURSES_TEXT); } /** * Create a NotificationTarget for a SingleUserNotification for a successful data export creation * * @param dataExport the data export that was created * @param message to use for the notification * @return the final NotificationTarget for this case */ public static NotificationTarget createDataExportCreatedTarget(DataExport dataExport, String message) { NotificationTarget notificationTarget = new NotificationTarget(); notificationTarget.setEntity(message); notificationTarget.setIdentifier(dataExport.getId()); notificationTarget.setMainPage(PRIVACY); return notificationTarget; } /** * Create a NotificationTarget for a SingleUserNotification for a failed data export creation * * @param message to use for the notification * @return the final NotificationTarget for this case */ public static NotificationTarget createDataExportFailedTarget(String message) { NotificationTarget notificationTarget = new NotificationTarget(); notificationTarget.setEntity(message); notificationTarget.setMainPage(PRIVACY); return notificationTarget; } /** * Create a NotificationTarget for a GroupNotification for a duplicate test case. * * @param exercise with duplicated test cases * @return the final NotificationTarget for this case */ public static NotificationTarget createDuplicateTestCaseTarget(Exercise exercise) { return new NotificationTarget(DUPLICATE_TEST_CASE_TEXT, exercise.getId(), PROGRAMMING_EXERCISES_TEXT, exercise.getCourseViaExerciseGroupOrCourseMember().getId(), COURSE_MANAGEMENT_TEXT); } // LECTURE related targets /** * Create a NotificationTarget for a GroupNotification for a Lecture. * * @param lecture for which to create the notification * @param message to use for the notification * @return the final NotificationTarget for this case */ public static NotificationTarget createLectureTarget(Lecture lecture, String message) { return new NotificationTarget(message, lecture.getId(), LECTURES_TEXT, lecture.getCourse().getId(), COURSES_TEXT); } /** * Create the needed target for "AttachmentUpdated" notifications * * @param lecture where an attachment was updated * @return the final NotificationTarget */ public static NotificationTarget createAttachmentUpdatedTarget(Lecture lecture) { return createLectureTarget(lecture, ATTACHMENT_UPDATED_TEXT); } // COURSE related targets /** * Create a NotificationTarget for a GroupNotification for a Course. * * @param course for which to create the notification * @param message to use for the notification * @return the final NotificationTarget for this case */ public static NotificationTarget createCourseTarget(Course course, String message) { return new NotificationTarget(message, course.getId(), COURSES_TEXT, course.getId(), COURSES_TEXT); } // POST related targets /** * Create a NotificationTarget for "LecturePost" notifications * * @param post which contains the needed lecture * @param course the post belongs to * @return the final NotificationTarget */ public static NotificationTarget createLecturePostTarget(Post post, Course course) { NotificationTarget target = new NotificationTarget(post.getId(), course.getId()); target.setLectureId(post.getLecture().getId()); return target; } /** * Create a NotificationTarget for "ExercisePost" notifications * * @param post which contains the needed exercise * @param course the post belongs to * @return the final NotificationTarget */ public static NotificationTarget createExercisePostTarget(Post post, Course course) { NotificationTarget target = new NotificationTarget(post.getId(), course.getId()); target.setExerciseId(post.getExercise().getId()); return target; } /** * Create a NotificationTarget for "CoursePost" notifications * * @param post course-wide post * @param course the post belongs to * @return the final NotificationTarget */ public static NotificationTarget createCoursePostTarget(Post post, Course course) { return new NotificationTarget(post.getId(), course.getId()); } // Plagiarism related targets /** * Create a NotificationTarget for plagiarism case related notifications * * @param plagiarismCaseId is the id of the PlagiarismCase * @param courseId of the Course * @return the final NotificationTarget */ public static NotificationTarget createPlagiarismCaseTarget(Long plagiarismCaseId, Long courseId) { return new NotificationTarget(PLAGIARISM_DETECTED_TEXT, plagiarismCaseId, PLAGIARISM_TEXT, courseId, COURSES_TEXT); } // Tutorial Group related targets /** * Create a NotificationTarget for notifications related to a Tutorial Group. * * @param tutorialGroup that is related to the notification * @param courseId of the course to which the tutorial group belongs * @param isManagement true if the notification should link to the tutorial group management page * @param isDetailPage true if the notification should lik to the detail page of the tutorial group * @return the created NotificationTarget */ public static NotificationTarget createTutorialGroupTarget(TutorialGroup tutorialGroup, Long courseId, boolean isManagement, boolean isDetailPage) { var notificationTarget = new NotificationTarget(); if (isDetailPage) { notificationTarget.setIdentifier(tutorialGroup.getId()); } notificationTarget.setEntity(isManagement ? TUTORIAL_GROUP_MANAGEMENT_TEXT : TUTORIAL_GROUPS_TEXT); notificationTarget.setCourseId(courseId); notificationTarget.setMainPage(isManagement ? COURSE_MANAGEMENT_TEXT : COURSES_TEXT); return notificationTarget; } // Conversation related targets /** * Create a NotificationTarget for notifications related to a new message in conversation. * * @param message that is related to the notification * @param courseId of the course to which the conversation belongs * @return the created NotificationTarget */ public static NotificationTarget createConversationMessageTarget(Post message, Long courseId) { var notificationTarget = new NotificationTarget(NEW_MESSAGE_TEXT, message.getId(), MESSAGE_TEXT, courseId, COURSES_TEXT); notificationTarget.setConversationId(message.getConversation().getId()); return notificationTarget; } /** * Create a NotificationTarget for notifications related to a new conversation creation. * * @param conversation that is related to the notification * @param courseId of the course to which the conversation belongs * @return the created NotificationTarget */ public static NotificationTarget createConversationCreationTarget(Conversation conversation, Long courseId) { var notificationTarget = new NotificationTarget(CONVERSATION_CREATION_TEXT, conversation.getId(), CONVERSATION_TEXT, courseId, COURSES_TEXT); notificationTarget.setConversationId(conversation.getId()); return notificationTarget; } /** * Create a NotificationTarget for notifications related to a new message reply in conversation. * * @param messageReply that is related to the notification * @param courseId of the course to which the tutorial group belongs * @return the created NotificationTarget */ public static NotificationTarget createMessageReplyTarget(AnswerPost messageReply, Long courseId) { var notificationTarget = new NotificationTarget(NEW_REPLY_TEXT, messageReply.getPost().getId(), MESSAGE_TEXT, courseId, COURSES_TEXT); notificationTarget.setConversationId(messageReply.getPost().getConversation().getId()); return notificationTarget; } /** * Create a NotificationTarget for notifications related to conversation deletion. * * @param conversation that is related to the notification * @param courseId of the course to which the tutorial group belongs * @return the created NotificationTarget */ public static NotificationTarget createConversationDeletionTarget(Conversation conversation, Long courseId) { var notificationTarget = new NotificationTarget(CONVERSATION_DELETION_TEXT, conversation.getId(), CONVERSATION_TEXT, courseId, COURSES_TEXT); notificationTarget.setConversationId(conversation.getId()); return notificationTarget; } /// URL/Link related methods /** * Extracts a viable URL from the provided notification and baseUrl * * @param notification which transient target property will be used for creating the URL * @param baseUrl the prefix (depends on current set up (e.g. "http://localhost:9000/courses")) * @return viable URL to the notification related page */ public static String extractNotificationUrl(Notification notification, String baseUrl) { NotificationTarget target = notification.getTargetTransient(); if (target == null) { return ""; } StringBuilder url = new StringBuilder(baseUrl); if (target.getMainPage() != null) { url.append("/").append(target.getMainPage()); } if (target.getCourseId() != null) { url.append("/").append(target.getCourseId()); } if (target.getEntity() != null) { url.append("/").append(target.getEntity()); } if (target.getIdentifier() != null) { url.append("/").append(target.getIdentifier()); } return url.toString(); } /** * Extracts a viable URL from the provided notification that is based on a Post and baseUrl * * @param post which information will be needed to create the URL * @param baseUrl the prefix (depends on current set up (e.g. "http://localhost:9000/courses")) * @return viable URL to the notification related page */ public static String extractNotificationUrl(Post post, String baseUrl) { // e.g. http://localhost:8080/courses/1/discussion?searchText=%2382 for announcement post return baseUrl + "/courses/" + post.getCourse().getId() + "/discussion?searchText=%23" + post.getId(); } }
15,569
0.713598
0.711992
366
41.53825
38.828156
169
false
false
0
0
0
0
0
0
0.418033
false
false
10
695c5d82fb72525f947834dfc7d35217e3aa996b
38,689,065,430,478
d87d2da7bdadeaba291a1345fa7eb3706ffd2c0b
/model/src/test/java/test/ureeka/model/testmodel/SimpleClass.java
89be10b9ae3d78c9182930bcb50d7190c393cb8e
[]
no_license
sunbayc/ureeka
https://github.com/sunbayc/ureeka
1cabc3cbd22384b74d8b13be458f4af3de38f721
04c635fe438f4e36c1513ad5ff96e33da77cc9e6
refs/heads/master
2020-12-24T15:49:32.821000
2011-06-24T04:59:53
2011-06-24T04:59:53
1,910,869
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package test.ureeka.model.testmodel; import ureeka.model.AbstractPropertiesOwner; import ureeka.model.DefaultProperty; import ureeka.model.Property; import ureeka.model.Range; public class SimpleClass extends AbstractPropertiesOwner { private static final long serialVersionUID = 6472591246820054224L; public final Property<String> firstField = new DefaultProperty<String>(this, "firstField") { private static final long serialVersionUID = 1921517962165518847L; public Range<String> getRange() { return new Range<String>("1", "3"); } }; public final Property<Long> secondField = new DefaultProperty<Long>(this, "secondField") { private static final long serialVersionUID = 1921517962165518847L; public Range<Long> getRange() { return new Range<Long>(1L, 10L); } }; public String getFirstField() { return firstField.get(); } public void setFirstField(String value) { firstField.set(value); } public Long getSecondField() { return secondField.get(); } public void setSecondField(Long secondField) { this.secondField.set(secondField); } }
UTF-8
Java
1,105
java
SimpleClass.java
Java
[]
null
[]
package test.ureeka.model.testmodel; import ureeka.model.AbstractPropertiesOwner; import ureeka.model.DefaultProperty; import ureeka.model.Property; import ureeka.model.Range; public class SimpleClass extends AbstractPropertiesOwner { private static final long serialVersionUID = 6472591246820054224L; public final Property<String> firstField = new DefaultProperty<String>(this, "firstField") { private static final long serialVersionUID = 1921517962165518847L; public Range<String> getRange() { return new Range<String>("1", "3"); } }; public final Property<Long> secondField = new DefaultProperty<Long>(this, "secondField") { private static final long serialVersionUID = 1921517962165518847L; public Range<Long> getRange() { return new Range<Long>(1L, 10L); } }; public String getFirstField() { return firstField.get(); } public void setFirstField(String value) { firstField.set(value); } public Long getSecondField() { return secondField.get(); } public void setSecondField(Long secondField) { this.secondField.set(secondField); } }
1,105
0.742986
0.686878
48
22.041666
25.433702
93
false
false
0
0
0
0
0
0
1.541667
false
false
10
a5f817aa39f77e53b25ba7400b5bfc2f54a996ab
39,161,511,842,294
1be50c1c36592b4956a0d3d81b99a0fa3acdb63b
/src/edu/psu/compbio/seqcode/gse/datasets/alignments/BLATAlignmentHitRegion.java
d1528fbcfe8cc4b2bbcb1be49f8561269dd4e1b0
[ "MIT" ]
permissive
shaunmahony/multigps-archive
https://github.com/shaunmahony/multigps-archive
63aee145cc764b516d4d018c1bb7533a64269b17
08a3b0324025c629c8de5c2a5a2c0d56d5bf4574
refs/heads/master
2021-06-07T23:22:25.209000
2016-11-25T02:33:04
2016-11-25T02:33:04
16,091,126
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.psu.compbio.seqcode.gse.datasets.alignments; import edu.psu.compbio.seqcode.gse.datasets.general.NamedStrandedRegion; import edu.psu.compbio.seqcode.gse.datasets.general.Region; import edu.psu.compbio.seqcode.gse.datasets.species.Genome; public abstract class BLATAlignmentHitRegion extends NamedStrandedRegion { public double percentIdentity; public int alignmentLength; public int numMismatches; public int numGapOpenings; public int queryStart; public int queryEnd; /** * Construct a new alignment hit region from an existing one * @param r */ public BLATAlignmentHitRegion(BLATAlignmentHitRegion r) { super(r); this.percentIdentity = r.getPercentIdentity(); this.alignmentLength = r.getAlignmentLength(); this.numMismatches = r.getNumMismatches(); this.numGapOpenings = r.getNumGapOpenings(); this.queryStart = r.getQueryStart(); this.queryEnd = r.getQueryEnd(); } /** * Construct a new alignment hit region from an existing region and the * additional information that is described by this object * @param r : a Region that represents the Target's genome, chrom, start, and end * @param name : the Query name * @param strand : the strand of the alignment (in the Target) * @param percentIdentity : percent identity between sequences, as a fraction (0 <= percentIdentity <= 1). * @param alignmentLength : length of the alignment (in the Target) in bp * @param numMismatches * @param numGapOpenings * @param queryStart * @param queryEnd */ public BLATAlignmentHitRegion(Region r, String name, char strand, double percentIdentity, int alignmentLength, int numMismatches, int numGapOpenings, int queryStart, int queryEnd) { super(r, name, strand); this.percentIdentity = percentIdentity; this.alignmentLength = alignmentLength; this.numMismatches = numMismatches; this.numGapOpenings = numGapOpenings; this.queryStart = queryStart; this.queryEnd = queryEnd; } /** * Construct a new alignment hit region from scratch * @param genome * @param chrom * @param subjectStart * @param subjectEnd * @param name * @param strand * @param percentIdentity * @param alignmentLength * @param numMismatches * @param numGapOpenings * @param queryStart * @param queryEnd */ public BLATAlignmentHitRegion(Genome genome, String chrom, int alignmentStart, int alignmentEnd, String name, char strand, double percentIdentity, int alignmentLength, int numMismatches, int numGapOpenings, int queryStart, int queryEnd) { super(genome, chrom, alignmentStart, alignmentEnd, name, strand); this.percentIdentity = percentIdentity; this.alignmentLength = alignmentLength; this.numMismatches = numMismatches; this.numGapOpenings = numGapOpenings; this.queryStart = queryStart; this.queryEnd = queryEnd; } /** * */ public String toString() { return super.toString() + ",% identity: " + percentIdentity + ", alignment length: " + alignmentLength + ", mismatches: " + numMismatches + ", gap openings: " + numGapOpenings + ", query start: " + queryStart + ", query end: " + queryEnd; } /** * @return the percentIdentity (between 0 and 1, inclusive) */ public double getPercentIdentity() { return percentIdentity; } /** * @return the alignmentLength */ public int getAlignmentLength() { return alignmentLength; } /** * @return the numMismatches */ public int getNumMismatches() { return numMismatches; } /** * @return the numGapOpenings */ public int getNumGapOpenings() { return numGapOpenings; } /** * @return the queryStart */ public int getQueryStart() { return queryStart; } /** * @return the queryEnd */ public int getQueryEnd() { return queryEnd; } /** * @return the subjectStart */ public int getSubjectStart() { return super.getStart(); } /** * @return the subjectEnd */ public int getSubjectEnd() { return super.getEnd(); } }
UTF-8
Java
4,388
java
BLATAlignmentHitRegion.java
Java
[]
null
[]
package edu.psu.compbio.seqcode.gse.datasets.alignments; import edu.psu.compbio.seqcode.gse.datasets.general.NamedStrandedRegion; import edu.psu.compbio.seqcode.gse.datasets.general.Region; import edu.psu.compbio.seqcode.gse.datasets.species.Genome; public abstract class BLATAlignmentHitRegion extends NamedStrandedRegion { public double percentIdentity; public int alignmentLength; public int numMismatches; public int numGapOpenings; public int queryStart; public int queryEnd; /** * Construct a new alignment hit region from an existing one * @param r */ public BLATAlignmentHitRegion(BLATAlignmentHitRegion r) { super(r); this.percentIdentity = r.getPercentIdentity(); this.alignmentLength = r.getAlignmentLength(); this.numMismatches = r.getNumMismatches(); this.numGapOpenings = r.getNumGapOpenings(); this.queryStart = r.getQueryStart(); this.queryEnd = r.getQueryEnd(); } /** * Construct a new alignment hit region from an existing region and the * additional information that is described by this object * @param r : a Region that represents the Target's genome, chrom, start, and end * @param name : the Query name * @param strand : the strand of the alignment (in the Target) * @param percentIdentity : percent identity between sequences, as a fraction (0 <= percentIdentity <= 1). * @param alignmentLength : length of the alignment (in the Target) in bp * @param numMismatches * @param numGapOpenings * @param queryStart * @param queryEnd */ public BLATAlignmentHitRegion(Region r, String name, char strand, double percentIdentity, int alignmentLength, int numMismatches, int numGapOpenings, int queryStart, int queryEnd) { super(r, name, strand); this.percentIdentity = percentIdentity; this.alignmentLength = alignmentLength; this.numMismatches = numMismatches; this.numGapOpenings = numGapOpenings; this.queryStart = queryStart; this.queryEnd = queryEnd; } /** * Construct a new alignment hit region from scratch * @param genome * @param chrom * @param subjectStart * @param subjectEnd * @param name * @param strand * @param percentIdentity * @param alignmentLength * @param numMismatches * @param numGapOpenings * @param queryStart * @param queryEnd */ public BLATAlignmentHitRegion(Genome genome, String chrom, int alignmentStart, int alignmentEnd, String name, char strand, double percentIdentity, int alignmentLength, int numMismatches, int numGapOpenings, int queryStart, int queryEnd) { super(genome, chrom, alignmentStart, alignmentEnd, name, strand); this.percentIdentity = percentIdentity; this.alignmentLength = alignmentLength; this.numMismatches = numMismatches; this.numGapOpenings = numGapOpenings; this.queryStart = queryStart; this.queryEnd = queryEnd; } /** * */ public String toString() { return super.toString() + ",% identity: " + percentIdentity + ", alignment length: " + alignmentLength + ", mismatches: " + numMismatches + ", gap openings: " + numGapOpenings + ", query start: " + queryStart + ", query end: " + queryEnd; } /** * @return the percentIdentity (between 0 and 1, inclusive) */ public double getPercentIdentity() { return percentIdentity; } /** * @return the alignmentLength */ public int getAlignmentLength() { return alignmentLength; } /** * @return the numMismatches */ public int getNumMismatches() { return numMismatches; } /** * @return the numGapOpenings */ public int getNumGapOpenings() { return numGapOpenings; } /** * @return the queryStart */ public int getQueryStart() { return queryStart; } /** * @return the queryEnd */ public int getQueryEnd() { return queryEnd; } /** * @return the subjectStart */ public int getSubjectStart() { return super.getStart(); } /** * @return the subjectEnd */ public int getSubjectEnd() { return super.getEnd(); } }
4,388
0.647903
0.646992
161
25.254658
24.129381
110
false
false
0
0
0
0
0
0
1.099379
false
false
10
473580ae10c38004d773ef0caed6ff6083bf3681
39,161,511,840,582
527089a285e5b8b5d7a6688821fb849c1214aefc
/src/main/java/com/abcbank/banking/config/datasource/DataSourceConfig.java
982310c7795446e0615e64807cc953d289d9f018
[]
no_license
shyam-anand/ABCBanking
https://github.com/shyam-anand/ABCBanking
c640dba9502af1756a76acbfff05a0dfd679526b
cce3669aaa9a757e525d1c6e2672492a1349996e
refs/heads/master
2021-01-20T13:11:50.092000
2017-08-29T09:06:50
2017-08-29T09:06:50
101,737,655
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.abcbank.banking.config.datasource; 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.jdbc.datasource.DriverManagerDataSource; import javax.sql.DataSource; /** * @author Shyam Anand (shyamwdr@gmail.com) * 26/08/17 */ @Configuration public class DataSourceConfig { private final String dataSourceUrl; private final String dataSourceUser; private final String dataSourcePassword; private final String dataSourceDriver; @Autowired public DataSourceConfig(@Value("${spring.datasource.url}") String url, @Value("${spring.datasource.username}") String user, @Value("${spring.datasource.password}") String password, @Value("${spring.datasource.driver-class-name}") String driver) { dataSourceUrl = url; dataSourceUser = user; dataSourcePassword = password; dataSourceDriver = driver; } @Bean public DataSource dataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(dataSourceDriver); dataSource.setUrl(dataSourceUrl); dataSource.setUsername(dataSourceUser); dataSource.setPassword(dataSourcePassword); return dataSource; } }
UTF-8
Java
1,521
java
DataSourceConfig.java
Java
[ { "context": "rce;\n\nimport javax.sql.DataSource;\n\n/**\n * @author Shyam Anand (shyamwdr@gmail.com)\n * 26/08/17\n */\n@Con", "end": 408, "score": 0.9998863339424133, "start": 397, "tag": "NAME", "value": "Shyam Anand" }, { "context": "avax.sql.DataSource;\n\n/**\n * @author Shyam Anand (shyamwdr@gmail.com)\n * 26/08/17\n */\n@Configuration\npublic cl", "end": 428, "score": 0.9999333620071411, "start": 410, "tag": "EMAIL", "value": "shyamwdr@gmail.com" }, { "context": " dataSourceUrl = url;\n dataSourceUser = user;\n dataSourcePassword = password;\n d", "end": 1080, "score": 0.7968504428863525, "start": 1076, "tag": "USERNAME", "value": "user" }, { "context": "ataSourceUser = user;\n dataSourcePassword = password;\n dataSourceDriver = driver;\n }\n\n @B", "end": 1119, "score": 0.9987263083457947, "start": 1111, "tag": "PASSWORD", "value": "password" }, { "context": "rl(dataSourceUrl);\n dataSource.setUsername(dataSourceUser);\n dataSource.setPassword(dataSourcePasswo", "end": 1430, "score": 0.9951443672180176, "start": 1416, "tag": "USERNAME", "value": "dataSourceUser" }, { "context": "e(dataSourceUser);\n dataSource.setPassword(dataSourcePassword);\n\n return dataSource;\n }\n}\n", "end": 1482, "score": 0.9153401851654053, "start": 1464, "tag": "PASSWORD", "value": "dataSourcePassword" } ]
null
[]
package com.abcbank.banking.config.datasource; 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.jdbc.datasource.DriverManagerDataSource; import javax.sql.DataSource; /** * @author <NAME> (<EMAIL>) * 26/08/17 */ @Configuration public class DataSourceConfig { private final String dataSourceUrl; private final String dataSourceUser; private final String dataSourcePassword; private final String dataSourceDriver; @Autowired public DataSourceConfig(@Value("${spring.datasource.url}") String url, @Value("${spring.datasource.username}") String user, @Value("${spring.datasource.password}") String password, @Value("${spring.datasource.driver-class-name}") String driver) { dataSourceUrl = url; dataSourceUser = user; dataSourcePassword = <PASSWORD>; dataSourceDriver = driver; } @Bean public DataSource dataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(dataSourceDriver); dataSource.setUrl(dataSourceUrl); dataSource.setUsername(dataSourceUser); dataSource.setPassword(<PASSWORD>); return dataSource; } }
1,499
0.702827
0.698882
44
33.56818
26.475029
93
false
false
0
0
0
0
0
0
0.545455
false
false
10
434486f54b8298627ce1e5fe08cc7598a75fd4e0
39,230,231,312,104
fc34d2a7c42a0396c4efe8efa4943a862fe46b88
/src/main/java/org/biojava/nbio/structure/align/symm/ecodcensus/EcodCensus.java
935edf8aeab4a60029a2f7d12d4fea37b5c0de39
[]
no_license
josemduarte/symmetry
https://github.com/josemduarte/symmetry
bd5192b83699aef1fdeb0d1b88d5ac9dbc43d215
4767b2e83f811a2e40aea74044dd42130e8934bf
refs/heads/master
2020-12-06T19:08:31.509000
2015-05-20T10:49:13
2015-05-20T10:49:13
28,813,022
0
0
null
true
2015-01-05T13:12:02
2015-01-05T13:12:02
2014-11-21T01:10:35
2014-10-24T21:19:32
4,216
0
0
0
null
null
null
package org.biojava.nbio.structure.align.symm.ecodcensus; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.util.Iterator; import java.util.List; import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.AtomPositionMap; import org.biojava.nbio.structure.ResidueRangeAndLength; import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.StructureTools; import org.biojava.nbio.structure.align.model.AFPChain; import org.biojava.nbio.structure.align.symm.CESymmParameters; import org.biojava.nbio.structure.align.symm.CESymmParameters.OrderDetectorMethod; import org.biojava.nbio.structure.align.symm.CESymmParameters.RefineMethod; import org.biojava.nbio.structure.align.symm.CeSymm; import org.biojava.nbio.structure.align.symm.order.OrderDetectionFailedException; import org.biojava.nbio.structure.align.symm.order.OrderDetector; import org.biojava.nbio.structure.align.symm.order.SequenceFunctionOrderDetector; import org.biojava.nbio.structure.align.symm.protodomain.Protodomain; import org.biojava.nbio.structure.align.symm.protodomain.ProtodomainCreationException; import org.biojava.nbio.structure.align.util.AtomCache; import org.biojava.nbio.structure.ecod.EcodDatabase; import org.biojava.nbio.structure.ecod.EcodDomain; import org.biojava.nbio.structure.ecod.EcodFactory; import org.biojava.nbio.structure.io.LocalPDBDirectory.ObsoleteBehavior; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class EcodCensus { private static final Logger logger = LoggerFactory.getLogger(EcodCensus.class); public static void main(String[] args) { String outFilename; outFilename = "/tmp/EcodCensus.tsv"; // outFilename = "-"; PrintStream out = System.out; if( !outFilename.equalsIgnoreCase("-") ) { try { out = new PrintStream(new FileOutputStream(outFilename),true); } catch (FileNotFoundException e) { logger.error("Can't write to "+outFilename); } } String ecodVersion = "develop83"; EcodDatabase ecod = EcodFactory.getEcodDatabase(ecodVersion); AtomCache cache = new AtomCache(); cache.setObsoleteBehavior(ObsoleteBehavior.FETCH_OBSOLETE); CeSymm cesymm = new CeSymm(); CESymmParameters param = (CESymmParameters) cesymm.getParameters(); param.setRefineMethod(RefineMethod.SINGLE); OrderDetector detector; //detector = new RotationOrderDetector(8, RotationOrderMethod.SINGLE_CUSP_FIXED_SSE); detector = new SequenceFunctionOrderDetector(); param.setOrderDetectorMethod(OrderDetectorMethod.SEQUENCE_FUNCTION); EcodRepresentatives ecodreps = new EcodRepresentatives(ecod); List<EcodDomain> reps; try { reps = ecodreps.getDomains(3); } catch (IOException e) { logger.error("Error fetching ECOD domains",e); System.exit(1); return; } for(EcodDomain d: reps) { String rangeStr = String.format("%s.%s",d.getPdbId(),d.getRange()); Atom[] ca1, ca2; try { Structure struct = cache.getStructure(rangeStr); ca1 = StructureTools.getRepresentativeAtomArray(struct); ca2 = StructureTools.getRepresentativeAtomArray(struct.clone()); } catch (IOException e) { logger.error("Error getting structure for "+d.getDomainId(),e); continue; } catch (StructureException e) { logger.error("Error getting structure for "+d.getDomainId(),e); continue; } AFPChain afpChain; try { afpChain = cesymm.align(ca1, ca2); // afpChain.setName1(d.getDomainId()); // afpChain.setName2(d.getDomainId()); afpChain.setName1(rangeStr); afpChain.setName2(rangeStr); } catch (StructureException e) { logger.error("Error running CE-Symm on "+d.getDomainId(),e); continue; } int order; try { order = detector.calculateOrder(afpChain, ca1); } catch (OrderDetectionFailedException e) { logger.error("Error getting order for "+d.getDomainId(),e); order = 1; } // Protodomain protodomain; // try { // protodomain = Protodomain.fromSymmetryAlignment(afpChain, ca1, order, cache); // } catch (ProtodomainCreationException e) { // logger.error("Error getting protodomain for "+d.getDomainId(),e); // continue; // } String protodomainName = d.getDomainId(); // Iterator<ResidueRangeAndLength> it = protodomain.getRanges().iterator(); AtomPositionMap map = new AtomPositionMap(ca1); List<ResidueRangeAndLength> unsplicedRanges = ResidueRangeAndLength.parseMultiple(d.getRange(),map); List<ResidueRangeAndLength> splicedRanges = Protodomain.spliceApproxConsecutive(map, unsplicedRanges, 4); Iterator<ResidueRangeAndLength> it = splicedRanges.iterator(); StringBuilder protodomainRangeStr = new StringBuilder(); if(it.hasNext()) { protodomainRangeStr.append(d.getPdbId()); protodomainRangeStr.append("_"); ResidueRangeAndLength range = it.next(); protodomainRangeStr.append(range.toString()); } while(it.hasNext()) { ResidueRangeAndLength range = it.next(); protodomainRangeStr.append(range.toString()); } out.format("%s\t%s%n",protodomainName,protodomainRangeStr); } if( out != System.out) { out.close(); } } }
UTF-8
Java
5,315
java
EcodCensus.java
Java
[]
null
[]
package org.biojava.nbio.structure.align.symm.ecodcensus; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.util.Iterator; import java.util.List; import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.AtomPositionMap; import org.biojava.nbio.structure.ResidueRangeAndLength; import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.StructureTools; import org.biojava.nbio.structure.align.model.AFPChain; import org.biojava.nbio.structure.align.symm.CESymmParameters; import org.biojava.nbio.structure.align.symm.CESymmParameters.OrderDetectorMethod; import org.biojava.nbio.structure.align.symm.CESymmParameters.RefineMethod; import org.biojava.nbio.structure.align.symm.CeSymm; import org.biojava.nbio.structure.align.symm.order.OrderDetectionFailedException; import org.biojava.nbio.structure.align.symm.order.OrderDetector; import org.biojava.nbio.structure.align.symm.order.SequenceFunctionOrderDetector; import org.biojava.nbio.structure.align.symm.protodomain.Protodomain; import org.biojava.nbio.structure.align.symm.protodomain.ProtodomainCreationException; import org.biojava.nbio.structure.align.util.AtomCache; import org.biojava.nbio.structure.ecod.EcodDatabase; import org.biojava.nbio.structure.ecod.EcodDomain; import org.biojava.nbio.structure.ecod.EcodFactory; import org.biojava.nbio.structure.io.LocalPDBDirectory.ObsoleteBehavior; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class EcodCensus { private static final Logger logger = LoggerFactory.getLogger(EcodCensus.class); public static void main(String[] args) { String outFilename; outFilename = "/tmp/EcodCensus.tsv"; // outFilename = "-"; PrintStream out = System.out; if( !outFilename.equalsIgnoreCase("-") ) { try { out = new PrintStream(new FileOutputStream(outFilename),true); } catch (FileNotFoundException e) { logger.error("Can't write to "+outFilename); } } String ecodVersion = "develop83"; EcodDatabase ecod = EcodFactory.getEcodDatabase(ecodVersion); AtomCache cache = new AtomCache(); cache.setObsoleteBehavior(ObsoleteBehavior.FETCH_OBSOLETE); CeSymm cesymm = new CeSymm(); CESymmParameters param = (CESymmParameters) cesymm.getParameters(); param.setRefineMethod(RefineMethod.SINGLE); OrderDetector detector; //detector = new RotationOrderDetector(8, RotationOrderMethod.SINGLE_CUSP_FIXED_SSE); detector = new SequenceFunctionOrderDetector(); param.setOrderDetectorMethod(OrderDetectorMethod.SEQUENCE_FUNCTION); EcodRepresentatives ecodreps = new EcodRepresentatives(ecod); List<EcodDomain> reps; try { reps = ecodreps.getDomains(3); } catch (IOException e) { logger.error("Error fetching ECOD domains",e); System.exit(1); return; } for(EcodDomain d: reps) { String rangeStr = String.format("%s.%s",d.getPdbId(),d.getRange()); Atom[] ca1, ca2; try { Structure struct = cache.getStructure(rangeStr); ca1 = StructureTools.getRepresentativeAtomArray(struct); ca2 = StructureTools.getRepresentativeAtomArray(struct.clone()); } catch (IOException e) { logger.error("Error getting structure for "+d.getDomainId(),e); continue; } catch (StructureException e) { logger.error("Error getting structure for "+d.getDomainId(),e); continue; } AFPChain afpChain; try { afpChain = cesymm.align(ca1, ca2); // afpChain.setName1(d.getDomainId()); // afpChain.setName2(d.getDomainId()); afpChain.setName1(rangeStr); afpChain.setName2(rangeStr); } catch (StructureException e) { logger.error("Error running CE-Symm on "+d.getDomainId(),e); continue; } int order; try { order = detector.calculateOrder(afpChain, ca1); } catch (OrderDetectionFailedException e) { logger.error("Error getting order for "+d.getDomainId(),e); order = 1; } // Protodomain protodomain; // try { // protodomain = Protodomain.fromSymmetryAlignment(afpChain, ca1, order, cache); // } catch (ProtodomainCreationException e) { // logger.error("Error getting protodomain for "+d.getDomainId(),e); // continue; // } String protodomainName = d.getDomainId(); // Iterator<ResidueRangeAndLength> it = protodomain.getRanges().iterator(); AtomPositionMap map = new AtomPositionMap(ca1); List<ResidueRangeAndLength> unsplicedRanges = ResidueRangeAndLength.parseMultiple(d.getRange(),map); List<ResidueRangeAndLength> splicedRanges = Protodomain.spliceApproxConsecutive(map, unsplicedRanges, 4); Iterator<ResidueRangeAndLength> it = splicedRanges.iterator(); StringBuilder protodomainRangeStr = new StringBuilder(); if(it.hasNext()) { protodomainRangeStr.append(d.getPdbId()); protodomainRangeStr.append("_"); ResidueRangeAndLength range = it.next(); protodomainRangeStr.append(range.toString()); } while(it.hasNext()) { ResidueRangeAndLength range = it.next(); protodomainRangeStr.append(range.toString()); } out.format("%s\t%s%n",protodomainName,protodomainRangeStr); } if( out != System.out) { out.close(); } } }
5,315
0.74826
0.74412
148
34.912163
26.168613
108
false
false
0
0
0
0
0
0
2.939189
false
false
10
b5dc2afbb003f8af76574fb1822754e4de114f77
38,302,518,376,650
baab092a50a4a9982328a6a4c529a9217f5de31e
/src/main/java/in/ankushs/linode4j/model/enums/EventAction.java
15353681ef7b0ad46a02838ddb6394e0da9b9ca2
[ "MIT" ]
permissive
Adsizzlerlabs/linode4j
https://github.com/Adsizzlerlabs/linode4j
530ecf2fa4bb8779b649db072199500c47f82089
f3ac56d74fc9b85901382d37eaffc74b432619ca
refs/heads/master
2021-09-01T18:36:09.563000
2017-12-28T08:27:37
2017-12-28T08:27:37
113,029,323
1
0
null
true
2017-12-04T10:33:58
2017-12-04T10:33:58
2017-12-04T10:33:50
2017-12-03T20:09:13
144
0
0
0
null
false
null
package in.ankushs.linode4j.model.enums; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import in.ankushs.linode4j.jackson.EventActionDeserializer; import in.ankushs.linode4j.util.Strings; import lombok.Getter; /** * Created by ankushsharma on 29/11/17. */ @Getter @JsonDeserialize(using = EventActionDeserializer.class) public enum EventAction { UNKNOWN, LINODE_BOOT, LINODE_CREATE, LINODE_DELETE, LINODE_SHUTDOWN, LINODE_REBOOT, LINODE_SNAPSHOT, LINODE_ADDIP, LINODE_MIGRATE, LINODE_REBUILD, LINODE_CLONE, LINODE_KVMIFY, DISK_CREATE, DISK_DELETE, DISK_DUPLICATE, DISK_RESIZE, BACKUPS_ENABLE, BACKUPS_CANCEL, BACKUPS_RESTORE, PASSWORD_RESET, DOMAIN_CREATE, DOMAIN_DELETE, DOMAIN_RECORD_CREATE, DOMAIN_RECORD_DELETE, STACKSCRIPT_CREATE, STACKSCRIPT_PUBLICIZE, STACKSCRIPT_REVISE, STACKSCRIPT_DELETE; public static EventAction from(final String code){ EventAction result; if(!Strings.hasText(code)){ result = UNKNOWN; } else{ switch(code){ case "linode_boot" : result = LINODE_BOOT; break; case "linode_create" : result = LINODE_CREATE; break; case "linode_delete" : result = LINODE_DELETE; break; case "linode_shutdown" : result = LINODE_SHUTDOWN; break; case "linode_reboot" : result = LINODE_REBOOT; break; case "linode_snapshot" : result = LINODE_SNAPSHOT; break; case "linode_addip" : result = LINODE_ADDIP; break; case "linode_migrate" : result = LINODE_MIGRATE; break; case "linode_rebuild" : result = LINODE_REBUILD; break; case "linode_clone" : result = LINODE_CLONE; break; case "linode_kvmify" : result = LINODE_KVMIFY; break; case "disk_create" : result = DISK_CREATE; break; case "disk_delete" : result = DISK_DELETE; break; case "disk_duplicate" : result = DISK_DUPLICATE; break; case "disk_resize" : result = DISK_RESIZE; break; case "backups_enable" : result = BACKUPS_ENABLE; break; case "backups_cancel" : result = BACKUPS_CANCEL; break; case "backups_restore" : result = BACKUPS_RESTORE; break; case "password_reset" : result = PASSWORD_RESET; break; case "domain_create" : result = DOMAIN_CREATE; break; case "domain_delete" : result = DOMAIN_DELETE; break; case "domain_record_create" : result = DOMAIN_RECORD_CREATE; break; case "stackscript_create" : result = STACKSCRIPT_CREATE; break; case "stackscript_publicize" : result = STACKSCRIPT_PUBLICIZE; break; case "stackscript_revise" : result = STACKSCRIPT_REVISE; break; case "stackscript_delete" : result = STACKSCRIPT_DELETE; break; default : result = UNKNOWN; break; } } return result; } }
UTF-8
Java
3,126
java
EventAction.java
Java
[ { "context": ".Strings;\nimport lombok.Getter;\n\n/**\n * Created by ankushsharma on 29/11/17.\n */\n@Getter\n@JsonDeserialize(using =", "end": 262, "score": 0.9995909929275513, "start": 250, "tag": "USERNAME", "value": "ankushsharma" } ]
null
[]
package in.ankushs.linode4j.model.enums; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import in.ankushs.linode4j.jackson.EventActionDeserializer; import in.ankushs.linode4j.util.Strings; import lombok.Getter; /** * Created by ankushsharma on 29/11/17. */ @Getter @JsonDeserialize(using = EventActionDeserializer.class) public enum EventAction { UNKNOWN, LINODE_BOOT, LINODE_CREATE, LINODE_DELETE, LINODE_SHUTDOWN, LINODE_REBOOT, LINODE_SNAPSHOT, LINODE_ADDIP, LINODE_MIGRATE, LINODE_REBUILD, LINODE_CLONE, LINODE_KVMIFY, DISK_CREATE, DISK_DELETE, DISK_DUPLICATE, DISK_RESIZE, BACKUPS_ENABLE, BACKUPS_CANCEL, BACKUPS_RESTORE, PASSWORD_RESET, DOMAIN_CREATE, DOMAIN_DELETE, DOMAIN_RECORD_CREATE, DOMAIN_RECORD_DELETE, STACKSCRIPT_CREATE, STACKSCRIPT_PUBLICIZE, STACKSCRIPT_REVISE, STACKSCRIPT_DELETE; public static EventAction from(final String code){ EventAction result; if(!Strings.hasText(code)){ result = UNKNOWN; } else{ switch(code){ case "linode_boot" : result = LINODE_BOOT; break; case "linode_create" : result = LINODE_CREATE; break; case "linode_delete" : result = LINODE_DELETE; break; case "linode_shutdown" : result = LINODE_SHUTDOWN; break; case "linode_reboot" : result = LINODE_REBOOT; break; case "linode_snapshot" : result = LINODE_SNAPSHOT; break; case "linode_addip" : result = LINODE_ADDIP; break; case "linode_migrate" : result = LINODE_MIGRATE; break; case "linode_rebuild" : result = LINODE_REBUILD; break; case "linode_clone" : result = LINODE_CLONE; break; case "linode_kvmify" : result = LINODE_KVMIFY; break; case "disk_create" : result = DISK_CREATE; break; case "disk_delete" : result = DISK_DELETE; break; case "disk_duplicate" : result = DISK_DUPLICATE; break; case "disk_resize" : result = DISK_RESIZE; break; case "backups_enable" : result = BACKUPS_ENABLE; break; case "backups_cancel" : result = BACKUPS_CANCEL; break; case "backups_restore" : result = BACKUPS_RESTORE; break; case "password_reset" : result = PASSWORD_RESET; break; case "domain_create" : result = DOMAIN_CREATE; break; case "domain_delete" : result = DOMAIN_DELETE; break; case "domain_record_create" : result = DOMAIN_RECORD_CREATE; break; case "stackscript_create" : result = STACKSCRIPT_CREATE; break; case "stackscript_publicize" : result = STACKSCRIPT_PUBLICIZE; break; case "stackscript_revise" : result = STACKSCRIPT_REVISE; break; case "stackscript_delete" : result = STACKSCRIPT_DELETE; break; default : result = UNKNOWN; break; } } return result; } }
3,126
0.603967
0.601088
82
37.121952
26.483953
85
false
false
0
0
0
0
0
0
1.097561
false
false
10
e201e566ae9f56f3aa4699b7f9c292d1fb5e30dd
38,302,518,377,450
97a3c3438218214f7909eacbedcb5889f8f174b7
/src/main/java/ru/job4j/map/PutContainsKey.java
48ff0129d9bf08a732ac29ddcb50c4b5ab60e5f6
[ "MIT" ]
permissive
peterarsentev/course_test
https://github.com/peterarsentev/course_test
9090537a229489634bbda6adbda0a29950e5ba75
e57d69381f617d0dad160fe0bb35d8ee15b316c4
refs/heads/master
2022-09-12T09:25:11.405000
2022-07-23T12:23:52
2022-07-23T12:24:07
63,581,968
25
205
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.job4j.map; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; public class PutContainsKey { public static Map<Integer, User> addNewElementWithoutCheck(List<User> list) { Map<Integer, User> result = new HashMap<>(); for (User user : list) { result.put(user.id, user); } return result; } public static Map<Integer, User> addNewElementWithCheck(List<User> list) { Map<Integer, User> result = new HashMap<>(); for (User user : list) { result.put(user.id, user); } return result; } public record User(int id, String name) { } }
UTF-8
Java
697
java
PutContainsKey.java
Java
[]
null
[]
package ru.job4j.map; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; public class PutContainsKey { public static Map<Integer, User> addNewElementWithoutCheck(List<User> list) { Map<Integer, User> result = new HashMap<>(); for (User user : list) { result.put(user.id, user); } return result; } public static Map<Integer, User> addNewElementWithCheck(List<User> list) { Map<Integer, User> result = new HashMap<>(); for (User user : list) { result.put(user.id, user); } return result; } public record User(int id, String name) { } }
697
0.609756
0.608321
28
23.892857
22.113892
81
false
false
0
0
0
0
0
0
0.642857
false
false
10
a6208637b26f4c093e9b75b8802ed4ffa20be75f
37,142,877,214,476
05dca9da9ebb261c586c50eecd040e6b114cbbca
/app/src/main/java/com/example/chipmunk/sprout/Login_Register/Register_SetUsrName.java
93816d183bdebd4988ba465504b417a65dc9c451
[]
no_license
Chipmunkkk/Sprout
https://github.com/Chipmunkkk/Sprout
a33c7746e7bde0e79b6e8fae8952b2b94d402412
637a41079a552f1cdbf841bed4cedbd1f5964648
refs/heads/master
2020-12-25T18:42:59.547000
2017-06-16T01:20:02
2017-06-16T01:20:02
93,980,246
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.chipmunk.sprout.Login_Register; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import com.example.chipmunk.sprout.Utils.ActivityCollector; import com.example.chipmunk.sprout.R; import com.example.chipmunk.sprout.MainPage; public class Register_SetUsrName extends AppCompatActivity { private Button Btn_SetUsrName; private Intent intent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.register_set_usrname); Btn_SetUsrName = (Button) findViewById(R.id.btn_SetUsrName); Btn_SetUsrName.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { intent = new Intent(); intent.setClass(Register_SetUsrName.this,MainPage.class); ActivityCollector.addActivity(Register_SetUsrName.this); startActivity(intent); } }); } }
UTF-8
Java
1,119
java
Register_SetUsrName.java
Java
[]
null
[]
package com.example.chipmunk.sprout.Login_Register; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import com.example.chipmunk.sprout.Utils.ActivityCollector; import com.example.chipmunk.sprout.R; import com.example.chipmunk.sprout.MainPage; public class Register_SetUsrName extends AppCompatActivity { private Button Btn_SetUsrName; private Intent intent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.register_set_usrname); Btn_SetUsrName = (Button) findViewById(R.id.btn_SetUsrName); Btn_SetUsrName.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { intent = new Intent(); intent.setClass(Register_SetUsrName.this,MainPage.class); ActivityCollector.addActivity(Register_SetUsrName.this); startActivity(intent); } }); } }
1,119
0.700626
0.699732
34
31.911764
23.591333
73
false
false
0
0
0
0
0
0
0.588235
false
false
10
0992a47be9c6c5133a3f3390ff5103bdfb198a1b
38,972,533,288,529
602235d74af426eb47a41029c3b30a296fecdb27
/onebusaway-gtfs-transformer/src/main/java/org/onebusaway/gtfs_transformer/impl/DeferredValueSetter.java
cc938e86bd8f24ef8903a995f49426f9173fdc1c
[ "Apache-2.0" ]
permissive
ergosarapu/onebusaway-gtfs-modules
https://github.com/ergosarapu/onebusaway-gtfs-modules
f57ef68cb0400c12c6527df411941f672da80dee
12f92cdea8b522d18fe525fe2837681a0f122378
refs/heads/master
2021-01-19T07:02:39.085000
2013-12-06T14:50:36
2013-12-06T14:50:36
14,492,809
0
1
NOASSERTION
true
2020-02-19T09:51:33
2013-11-18T13:17:03
2013-12-06T14:50:48
2020-02-19T09:47:31
1,593
0
1
0
Java
false
false
/** * Copyright (C) 2012 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onebusaway.gtfs_transformer.impl; import java.io.Serializable; import java.lang.reflect.Method; import org.apache.commons.beanutils.Converter; import org.onebusaway.csv_entities.schema.BeanWrapper; import org.onebusaway.gtfs.model.AgencyAndId; import org.onebusaway.gtfs.model.IdentityBean; import org.onebusaway.gtfs.serialization.GtfsReader; import org.onebusaway.gtfs.serialization.GtfsReaderContext; import org.onebusaway.gtfs.services.GtfsRelationalDao; public class DeferredValueSetter { private final DeferredValueSupport _support; private final GtfsRelationalDao _dao; private final Object _value; public DeferredValueSetter(GtfsReader reader, EntitySchemaCache schemaCache, GtfsRelationalDao dao, Object value) { _support = new DeferredValueSupport(reader, schemaCache); _dao = dao; _value = value; } public void setValue(BeanWrapper bean, String propertyName) { Class<?> expectedValueType = bean.getPropertyType(propertyName); Class<?> actualValueType = _value.getClass(); Object resolvedValue = resolveValue(bean, propertyName, expectedValueType, actualValueType); bean.setPropertyValue(propertyName, resolvedValue); } private Object resolveValue(BeanWrapper bean, String propertyName, Class<?> expectedValueType, Class<?> actualValueType) { /** * When we introspect the "id" property of an IdentityBean instance, the * return type is always Serializable, when the actual type is String or * AgencyAndId. This causes trouble with the "isAssignableFrom" check below, * so we do a first check here. */ Object parentObject = bean.getWrappedInstance(Object.class); if (parentObject instanceof IdentityBean && propertyName.equals("id")) { Class<?> idType = getIdentityBeanIdType(parentObject); if (idType == AgencyAndId.class && actualValueType == String.class) { return _support.resolveAgencyAndId(bean, propertyName, (String) _value); } } if (expectedValueType.isAssignableFrom(actualValueType)) { return _value; } if (isPrimitiveAssignable(expectedValueType, actualValueType)) { return _value; } if (actualValueType == String.class) { String stringValue = (String) _value; if (AgencyAndId.class.isAssignableFrom(expectedValueType)) { return _support.resolveAgencyAndId(bean, propertyName, stringValue); } if (IdentityBean.class.isAssignableFrom(expectedValueType)) { Serializable id = stringValue; if (getIdType(expectedValueType) == AgencyAndId.class) { GtfsReaderContext context = _support.getReader().getGtfsReaderContext(); String agencyId = context.getAgencyForEntity(expectedValueType, stringValue); id = new AgencyAndId(agencyId, stringValue); } Object entity = _dao.getEntityForId(expectedValueType, id); if (entity == null) { throw new IllegalStateException("entity not found: type=" + expectedValueType.getName() + " id=" + id); } return entity; } Class<?> parentEntityType = parentObject.getClass(); Converter converter = _support.resolveConverter(parentEntityType, propertyName, expectedValueType); if (converter != null) { return converter.convert(expectedValueType, _value); } } throw new IllegalStateException("no conversion possible from type \"" + actualValueType.getName() + "\" to type \"" + expectedValueType.getName() + "\""); } private Class<?> getIdentityBeanIdType(Object bean) { try { return bean.getClass().getMethod("getId").getReturnType(); } catch (NoSuchMethodException e) { throw new IllegalStateException(e); } } private boolean isPrimitiveAssignable(Class<?> expectedValueType, Class<?> actualValueType) { if (!expectedValueType.isPrimitive()) { return false; } return expectedValueType == Double.TYPE && (actualValueType == Double.class || actualValueType == Float.class) || expectedValueType == Long.TYPE && (actualValueType == Long.class || actualValueType == Integer.class || actualValueType == Short.class) || expectedValueType == Integer.TYPE && (actualValueType == Integer.class || actualValueType == Short.class) || expectedValueType == Short.TYPE && (actualValueType == Short.class) || expectedValueType == Boolean.TYPE && (actualValueType == Boolean.class); } private static Class<?> getIdType(Class<?> valueType) { try { Method m = valueType.getMethod("getId"); return m.getReturnType(); } catch (Throwable ex) { throw new IllegalStateException( "could not find method \"getId\" for IdentityBean classs", ex); } } }
UTF-8
Java
5,461
java
DeferredValueSetter.java
Java
[]
null
[]
/** * Copyright (C) 2012 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onebusaway.gtfs_transformer.impl; import java.io.Serializable; import java.lang.reflect.Method; import org.apache.commons.beanutils.Converter; import org.onebusaway.csv_entities.schema.BeanWrapper; import org.onebusaway.gtfs.model.AgencyAndId; import org.onebusaway.gtfs.model.IdentityBean; import org.onebusaway.gtfs.serialization.GtfsReader; import org.onebusaway.gtfs.serialization.GtfsReaderContext; import org.onebusaway.gtfs.services.GtfsRelationalDao; public class DeferredValueSetter { private final DeferredValueSupport _support; private final GtfsRelationalDao _dao; private final Object _value; public DeferredValueSetter(GtfsReader reader, EntitySchemaCache schemaCache, GtfsRelationalDao dao, Object value) { _support = new DeferredValueSupport(reader, schemaCache); _dao = dao; _value = value; } public void setValue(BeanWrapper bean, String propertyName) { Class<?> expectedValueType = bean.getPropertyType(propertyName); Class<?> actualValueType = _value.getClass(); Object resolvedValue = resolveValue(bean, propertyName, expectedValueType, actualValueType); bean.setPropertyValue(propertyName, resolvedValue); } private Object resolveValue(BeanWrapper bean, String propertyName, Class<?> expectedValueType, Class<?> actualValueType) { /** * When we introspect the "id" property of an IdentityBean instance, the * return type is always Serializable, when the actual type is String or * AgencyAndId. This causes trouble with the "isAssignableFrom" check below, * so we do a first check here. */ Object parentObject = bean.getWrappedInstance(Object.class); if (parentObject instanceof IdentityBean && propertyName.equals("id")) { Class<?> idType = getIdentityBeanIdType(parentObject); if (idType == AgencyAndId.class && actualValueType == String.class) { return _support.resolveAgencyAndId(bean, propertyName, (String) _value); } } if (expectedValueType.isAssignableFrom(actualValueType)) { return _value; } if (isPrimitiveAssignable(expectedValueType, actualValueType)) { return _value; } if (actualValueType == String.class) { String stringValue = (String) _value; if (AgencyAndId.class.isAssignableFrom(expectedValueType)) { return _support.resolveAgencyAndId(bean, propertyName, stringValue); } if (IdentityBean.class.isAssignableFrom(expectedValueType)) { Serializable id = stringValue; if (getIdType(expectedValueType) == AgencyAndId.class) { GtfsReaderContext context = _support.getReader().getGtfsReaderContext(); String agencyId = context.getAgencyForEntity(expectedValueType, stringValue); id = new AgencyAndId(agencyId, stringValue); } Object entity = _dao.getEntityForId(expectedValueType, id); if (entity == null) { throw new IllegalStateException("entity not found: type=" + expectedValueType.getName() + " id=" + id); } return entity; } Class<?> parentEntityType = parentObject.getClass(); Converter converter = _support.resolveConverter(parentEntityType, propertyName, expectedValueType); if (converter != null) { return converter.convert(expectedValueType, _value); } } throw new IllegalStateException("no conversion possible from type \"" + actualValueType.getName() + "\" to type \"" + expectedValueType.getName() + "\""); } private Class<?> getIdentityBeanIdType(Object bean) { try { return bean.getClass().getMethod("getId").getReturnType(); } catch (NoSuchMethodException e) { throw new IllegalStateException(e); } } private boolean isPrimitiveAssignable(Class<?> expectedValueType, Class<?> actualValueType) { if (!expectedValueType.isPrimitive()) { return false; } return expectedValueType == Double.TYPE && (actualValueType == Double.class || actualValueType == Float.class) || expectedValueType == Long.TYPE && (actualValueType == Long.class || actualValueType == Integer.class || actualValueType == Short.class) || expectedValueType == Integer.TYPE && (actualValueType == Integer.class || actualValueType == Short.class) || expectedValueType == Short.TYPE && (actualValueType == Short.class) || expectedValueType == Boolean.TYPE && (actualValueType == Boolean.class); } private static Class<?> getIdType(Class<?> valueType) { try { Method m = valueType.getMethod("getId"); return m.getReturnType(); } catch (Throwable ex) { throw new IllegalStateException( "could not find method \"getId\" for IdentityBean classs", ex); } } }
5,461
0.69273
0.691265
144
36.923611
28.153616
112
false
false
0
0
0
0
0
0
0.659722
false
false
10
5865838dbe535bfec3257deef42e5f6f38b60d2a
37,400,575,247,807
ac34bf13d332bdb4ab40adeac1a16ea8dbd3a9b1
/Bolt.java
c67f26baf1fee47c701241b11109cf9f3dd0a5e1
[ "MIT" ]
permissive
Slabrosse/FastenerHierarchy
https://github.com/Slabrosse/FastenerHierarchy
803da5b5356778b7116893bfb4a5e70d8f7358b2
3112736927c9fc098b287b0a610ba7dc0138422b
refs/heads/master
2021-02-04T03:49:22.593000
2020-02-27T20:50:16
2020-02-27T20:50:16
243,614,005
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.Serializable; // child class of Fastenener public abstract class Bolt extends Fastener implements Serializable { private static final long serialVersionUID = -7601595982017834757L; private Threads threadSize; private double length; // 6 parameter constructor public Bolt(double len, Threads threadS, Enum<Materials.ThreadedMaterials> material, Enum<?> finish, double unitPrice, int numberPerUnit) throws IllegalFastener{ // passes information to Fastener super(material, finish, unitPrice, numberPerUnit); // check that materials and finishes match conditions if (material == Materials.ThreadedMaterials.Brass && finish != Finishes.BoltFinish.Plain || material == Materials.ThreadedMaterials.Stainless_Steel && finish != Finishes.BoltFinish.Plain || len < 0.5 || len >= 0.5 && len <= 6 && len % 0.25 != 0 || len >= 6 && len <= 11 && len % 0.5 != 0 || len >= 11 && len <= 20 && len % 1 != 0 || len > 20) throw new IllegalFastener(); else{ this.threadSize = threadS; this.length = len; } } // end constructor public String toString() { return + length + " long, " + threadSize + " thread, " + super.toString(); } } // end Bolt
UTF-8
Java
1,339
java
Bolt.java
Java
[]
null
[]
import java.io.Serializable; // child class of Fastenener public abstract class Bolt extends Fastener implements Serializable { private static final long serialVersionUID = -7601595982017834757L; private Threads threadSize; private double length; // 6 parameter constructor public Bolt(double len, Threads threadS, Enum<Materials.ThreadedMaterials> material, Enum<?> finish, double unitPrice, int numberPerUnit) throws IllegalFastener{ // passes information to Fastener super(material, finish, unitPrice, numberPerUnit); // check that materials and finishes match conditions if (material == Materials.ThreadedMaterials.Brass && finish != Finishes.BoltFinish.Plain || material == Materials.ThreadedMaterials.Stainless_Steel && finish != Finishes.BoltFinish.Plain || len < 0.5 || len >= 0.5 && len <= 6 && len % 0.25 != 0 || len >= 6 && len <= 11 && len % 0.5 != 0 || len >= 11 && len <= 20 && len % 1 != 0 || len > 20) throw new IllegalFastener(); else{ this.threadSize = threadS; this.length = len; } } // end constructor public String toString() { return + length + " long, " + threadSize + " thread, " + super.toString(); } } // end Bolt
1,339
0.614638
0.582524
30
43.666668
35.123909
114
false
false
0
0
0
0
0
0
1.033333
false
false
10
40e30e26ffb4fa8b05d396271b1812a310dc0810
7,834,020,391,552
6c0e37fb19ce7aa32bc54c70056cc55586729a1c
/merchant/app/src/main/java/com/hybunion/member/adapter/GroupAdapter.java
27da4b4db33d5970deaff5deb9f77bee87a99276
[]
no_license
ming95957/Test
https://github.com/ming95957/Test
bf4ed3e46e2bd0973cbb4ff2b21f2857d984af46
52c4b33c7527cf8e13eebb4f2c278fa751c87bb3
refs/heads/master
2017-12-01T06:11:36.056000
2016-07-04T01:22:29
2016-07-04T01:22:29
62,524,781
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hybunion.member.adapter; import android.content.Context; import android.graphics.Color; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.hybunion.R; import com.hybunion.member.model.GroupInfo; import java.util.ArrayList; public class GroupAdapter extends BaseAdapter { private Context mContext; public ArrayList<GroupInfo> groupBean=new ArrayList<GroupInfo>(); private LayoutInflater inflater; public GroupAdapter(Context context) { super(); this.mContext=context; } @Override public int getCount() { // TODO Auto-generated method stub return groupBean.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return groupBean.get(position); } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub ViewHolder holder; // System.out.println(groupBean); if(convertView==null){ inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.activity_group_item, null); holder=new ViewHolder(); holder.tv_id=(TextView) convertView.findViewById(R.id.tv_id); holder.couponcoding=(TextView) convertView.findViewById(R.id.couponcoding); holder.cite_num=(TextView) convertView.findViewById(R.id.cite_num); holder.user_num=(TextView) convertView.findViewById(R.id.user_num); convertView.setTag(holder); }else{ holder=(ViewHolder) convertView.getTag(); } String tv_id=groupBean.get(position).getTv_id(); String couponcoding=groupBean.get(position).getCouponCode(); String cite_num=groupBean.get(position).getRecipientsCount(); String user_num=groupBean.get(position).getHasUseCount(); holder.tv_id.setText(position+1+""); holder.tv_id.setTextColor(Color.parseColor("#FF5816")); holder.couponcoding.setText(couponcoding); holder.cite_num.setText(cite_num); holder.user_num.setText(user_num); return convertView; } static class ViewHolder{ TextView tv_id; TextView couponcoding; TextView cite_num; TextView user_num; } }
UTF-8
Java
2,366
java
GroupAdapter.java
Java
[]
null
[]
package com.hybunion.member.adapter; import android.content.Context; import android.graphics.Color; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.hybunion.R; import com.hybunion.member.model.GroupInfo; import java.util.ArrayList; public class GroupAdapter extends BaseAdapter { private Context mContext; public ArrayList<GroupInfo> groupBean=new ArrayList<GroupInfo>(); private LayoutInflater inflater; public GroupAdapter(Context context) { super(); this.mContext=context; } @Override public int getCount() { // TODO Auto-generated method stub return groupBean.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return groupBean.get(position); } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub ViewHolder holder; // System.out.println(groupBean); if(convertView==null){ inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.activity_group_item, null); holder=new ViewHolder(); holder.tv_id=(TextView) convertView.findViewById(R.id.tv_id); holder.couponcoding=(TextView) convertView.findViewById(R.id.couponcoding); holder.cite_num=(TextView) convertView.findViewById(R.id.cite_num); holder.user_num=(TextView) convertView.findViewById(R.id.user_num); convertView.setTag(holder); }else{ holder=(ViewHolder) convertView.getTag(); } String tv_id=groupBean.get(position).getTv_id(); String couponcoding=groupBean.get(position).getCouponCode(); String cite_num=groupBean.get(position).getRecipientsCount(); String user_num=groupBean.get(position).getHasUseCount(); holder.tv_id.setText(position+1+""); holder.tv_id.setTextColor(Color.parseColor("#FF5816")); holder.couponcoding.setText(couponcoding); holder.cite_num.setText(cite_num); holder.user_num.setText(user_num); return convertView; } static class ViewHolder{ TextView tv_id; TextView couponcoding; TextView cite_num; TextView user_num; } }
2,366
0.745562
0.743449
85
26.835295
22.286291
89
false
false
0
0
0
0
0
0
1.635294
false
false
10
862c55115f9fd3e6e6a020d6b039b34958b18149
33,011,118,681,912
c898410b85a07a59cbf19061ab4084e317e28bd5
/hw13_exceptions/src/exceptions/LogArgumentException.java
66b302aa96585ada0ac52533caa5fa5fcb044c87
[]
no_license
lejabque/java-intro
https://github.com/lejabque/java-intro
d113c451b28fe93d586e36953f6d7788684e9fdd
259c020a07dee2f9c0ae632dcfb374c6670c86d5
refs/heads/master
2020-07-25T16:37:15.776000
2020-03-24T00:28:43
2020-03-24T00:28:43
208,357,194
1
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package exceptions; public class LogArgumentException extends EvaluatingException { public LogArgumentException(int x, int y) { super("Invalid argument of logarithm: x: " + Integer.toString(x) + " y: " + Integer.toString(y)); } }
UTF-8
Java
247
java
LogArgumentException.java
Java
[]
null
[]
package exceptions; public class LogArgumentException extends EvaluatingException { public LogArgumentException(int x, int y) { super("Invalid argument of logarithm: x: " + Integer.toString(x) + " y: " + Integer.toString(y)); } }
247
0.700405
0.700405
7
34.285713
36.569756
105
false
false
0
0
0
0
0
0
0.428571
false
false
10
3253bad1aaf2b57828b802c991aabd5e16f4d72e
33,011,118,680,408
1067224e87046fe0d0138ec24ad210c4d0338cb8
/InterviewQuestions/HashMap/src/hashmap/Item.java
3a87760f34a70bcaf40597b874057ff32c3a599d
[]
no_license
lovelylavs/InterviewQuestions
https://github.com/lovelylavs/InterviewQuestions
f021339dd0338bbad3cb82bb90e34877f6086dee
aa932f85d82e387707f8d3d22892ba5efa52124c
refs/heads/master
2021-01-10T07:38:04.005000
2020-05-15T06:50:28
2020-05-15T06:50:28
45,262,671
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 hashmap; /** * * @author Lavanya */ public class Item { private String key;//hash key private Object element;//elements to be mapped public Item(String key,Object element)//constructor { this.key = key; this.element = element; } public String getKey() //Getter / Setter { return key; } public void setKey(String key) { this.key=key; } public Object getElement() //Getter / Setter { return element; } public void setElement(Object element) { this.element=element; } public String toString() { String s = "<Item("; s+=this.key+","+this.element+")>"; return s; } }
UTF-8
Java
928
java
Item.java
Java
[ { "context": "e editor.\n */\n\npackage hashmap;\n\n/**\n *\n * @author Lavanya\n */\npublic class Item \n{\n private String key;/", "end": 229, "score": 0.9734017252922058, "start": 222, "tag": "NAME", "value": "Lavanya" } ]
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 hashmap; /** * * @author Lavanya */ public class Item { private String key;//hash key private Object element;//elements to be mapped public Item(String key,Object element)//constructor { this.key = key; this.element = element; } public String getKey() //Getter / Setter { return key; } public void setKey(String key) { this.key=key; } public Object getElement() //Getter / Setter { return element; } public void setElement(Object element) { this.element=element; } public String toString() { String s = "<Item("; s+=this.key+","+this.element+")>"; return s; } }
928
0.581897
0.581897
47
18.74468
18.930408
79
false
false
0
0
0
0
0
0
0.361702
false
false
10
a37a1088d8bf0ba9f4f3815e46697b981097d60c
12,687,333,433,296
d0e74ff6e8d37984cea892dfe8508e2b44de5446
/logistics-wms-city-1.1.3.44.5/logistics-wms-city-manager/src/main/java/com/yougou/logistics/city/manager/BillChPlanManager.java
9fddc661c0cdf6d70c15e1fba46f3e9858a7abd2
[]
no_license
heaven6059/wms
https://github.com/heaven6059/wms
fb39f31968045ba7e0635a4416a405a226448b5a
5885711e188e8e5c136956956b794f2a2d2e2e81
refs/heads/master
2021-01-14T11:20:10.574000
2015-04-11T08:11:59
2015-04-11T08:11:59
29,462,213
1
4
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yougou.logistics.city.manager; import com.yougou.logistics.base.common.exception.ManagerException; import com.yougou.logistics.base.common.model.AuthorityParams; import com.yougou.logistics.base.manager.BaseCrudManager; import com.yougou.logistics.city.common.model.BillChPlan; import com.yougou.logistics.city.common.model.SystemUser; /* * 请写出类的用途 * @author qin.dy * @date Mon Nov 04 14:14:53 CST 2013 * @version 1.0.0 * @copyright (C) 2013 YouGou Information Technology Co.,Ltd * All Rights Reserved. * * The software for the YouGou technology development, without the * company's written consent, and any other individuals and * organizations shall not be used, Copying, Modify or distribute * the software. * */ public interface BillChPlanManager extends BaseCrudManager { public String check(BillChPlan billChPlan,String planNos) throws ManagerException; public String invalid(BillChPlan billChPlan, String[] planNos, SystemUser user) throws ManagerException; public String deleteMain(BillChPlan billChPlan,String planNos) throws ManagerException; public Object saveMain(BillChPlan billChPlan, AuthorityParams authorityParams) throws ManagerException; public void editMainInfo(BillChPlan billChPlan, AuthorityParams authorityParams) throws ManagerException; }
UTF-8
Java
1,319
java
BillChPlanManager.java
Java
[ { "context": "ommon.model.SystemUser;\n\n/*\n * 请写出类的用途 \n * @author qin.dy\n * @date Mon Nov 04 14:14:53 CST 2013\n * @versio", "end": 382, "score": 0.9743167757987976, "start": 376, "tag": "NAME", "value": "qin.dy" } ]
null
[]
package com.yougou.logistics.city.manager; import com.yougou.logistics.base.common.exception.ManagerException; import com.yougou.logistics.base.common.model.AuthorityParams; import com.yougou.logistics.base.manager.BaseCrudManager; import com.yougou.logistics.city.common.model.BillChPlan; import com.yougou.logistics.city.common.model.SystemUser; /* * 请写出类的用途 * @author qin.dy * @date Mon Nov 04 14:14:53 CST 2013 * @version 1.0.0 * @copyright (C) 2013 YouGou Information Technology Co.,Ltd * All Rights Reserved. * * The software for the YouGou technology development, without the * company's written consent, and any other individuals and * organizations shall not be used, Copying, Modify or distribute * the software. * */ public interface BillChPlanManager extends BaseCrudManager { public String check(BillChPlan billChPlan,String planNos) throws ManagerException; public String invalid(BillChPlan billChPlan, String[] planNos, SystemUser user) throws ManagerException; public String deleteMain(BillChPlan billChPlan,String planNos) throws ManagerException; public Object saveMain(BillChPlan billChPlan, AuthorityParams authorityParams) throws ManagerException; public void editMainInfo(BillChPlan billChPlan, AuthorityParams authorityParams) throws ManagerException; }
1,319
0.807663
0.793103
29
44.034481
34.288315
106
false
false
0
0
0
0
0
0
0.931035
false
false
10
c305e819bae2c1202b2882afc8329e9a2dc5559a
19,834,159,009,758
dbc8f3bb3f94dac032494767dbb6d68ea016e324
/app/src/main/java/com/example/williams/asd/Rest.java
41cead78489793643bc2ad65eec3bc6326039091
[]
no_license
adamhongmy/asd
https://github.com/adamhongmy/asd
2fe73ddc4868b0bab5ec5be8f4e7dde759d47146
5ef0234d0b4db1192264fd4c09136f9e9af6cc50
refs/heads/master
2020-12-24T14:18:14.666000
2015-06-18T09:08:03
2015-06-18T09:08:03
37,516,667
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.williams.asd; import android.content.Intent; import android.media.MediaPlayer; import android.os.CountDownTimer; import android.provider.MediaStore; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import android.widget.Toast; import org.w3c.dom.Text; import java.util.concurrent.TimeUnit; public class Rest extends ActionBarActivity { private static final String FORMAT = "%02d"; private TextView timer; private static int counter = 1; private static int totalPushup; private int recentPushup; private int set; private CountDownTimer countDownTimer; public final static String EXTRA_MESSAGE = "com.example.williams.MESSAGE"; private MediaPlayer relaxMusic; private MediaPlayer btnContSound; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_rest); btnContSound = MediaPlayer.create(Rest.this, R.raw.elixir_collect_02); relaxMusic = MediaPlayer.create(Rest.this, R.raw.harehareyukai); relaxMusic.start(); Intent mIntent = getIntent(); recentPushup = mIntent.getIntExtra("totalPushup", 0); set = mIntent.getIntExtra("targetSet", 0); totalPushup += recentPushup; if(set == counter) { proceedTodayResult(); }else { countDownTimer = new CountDownTimer(30000, 1000) { // adjust the milli seconds here public void onTick(long millisUntilFinished) { timer = (TextView) findViewById(R.id.timer); timer.setText("" + String.format(FORMAT, TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)))); } public void onFinish() { proceedTotalPushUp(); } }.start(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_rest, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } public void btnContinue(View v){ proceedTotalPushUp(); } public void proceedTodayResult(){ relaxMusic.stop(); Intent intent = new Intent(Rest.this, TodayResult.class); String message = String.valueOf(totalPushup); intent.putExtra("todayResult", message); startActivity(intent); } public void proceedTotalPushUp(){ relaxMusic.stop(); btnContSound.start(); countDownTimer.cancel(); counter++; Intent intent = new Intent(Rest.this, TotalPushUp.class); startActivity(intent); } @Override public void onBackPressed() { // super.onBackPressed(); // Comment this super call to avoid calling finish() } public static void setTotalPushup(int totalPushup) { Rest.totalPushup = totalPushup; } public static void setCounter(int counter) { Rest.counter = counter; } }
UTF-8
Java
3,911
java
Rest.java
Java
[]
null
[]
package com.example.williams.asd; import android.content.Intent; import android.media.MediaPlayer; import android.os.CountDownTimer; import android.provider.MediaStore; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import android.widget.Toast; import org.w3c.dom.Text; import java.util.concurrent.TimeUnit; public class Rest extends ActionBarActivity { private static final String FORMAT = "%02d"; private TextView timer; private static int counter = 1; private static int totalPushup; private int recentPushup; private int set; private CountDownTimer countDownTimer; public final static String EXTRA_MESSAGE = "com.example.williams.MESSAGE"; private MediaPlayer relaxMusic; private MediaPlayer btnContSound; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_rest); btnContSound = MediaPlayer.create(Rest.this, R.raw.elixir_collect_02); relaxMusic = MediaPlayer.create(Rest.this, R.raw.harehareyukai); relaxMusic.start(); Intent mIntent = getIntent(); recentPushup = mIntent.getIntExtra("totalPushup", 0); set = mIntent.getIntExtra("targetSet", 0); totalPushup += recentPushup; if(set == counter) { proceedTodayResult(); }else { countDownTimer = new CountDownTimer(30000, 1000) { // adjust the milli seconds here public void onTick(long millisUntilFinished) { timer = (TextView) findViewById(R.id.timer); timer.setText("" + String.format(FORMAT, TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)))); } public void onFinish() { proceedTotalPushUp(); } }.start(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_rest, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } public void btnContinue(View v){ proceedTotalPushUp(); } public void proceedTodayResult(){ relaxMusic.stop(); Intent intent = new Intent(Rest.this, TodayResult.class); String message = String.valueOf(totalPushup); intent.putExtra("todayResult", message); startActivity(intent); } public void proceedTotalPushUp(){ relaxMusic.stop(); btnContSound.start(); countDownTimer.cancel(); counter++; Intent intent = new Intent(Rest.this, TotalPushUp.class); startActivity(intent); } @Override public void onBackPressed() { // super.onBackPressed(); // Comment this super call to avoid calling finish() } public static void setTotalPushup(int totalPushup) { Rest.totalPushup = totalPushup; } public static void setCounter(int counter) { Rest.counter = counter; } }
3,911
0.632319
0.627717
121
30.322313
26.249979
166
false
false
0
0
0
0
0
0
0.578512
false
false
10
46b633f1ae8818b1db5703eece679cef1448a99a
28,398,323,786,479
933831b0ef0a7aac315e9c4ececc7d44e4946deb
/PracticeSession/src/org/training/Practice3.java
63f10a6f0c79037d1d8ab0623f07009c78f45354
[]
no_license
vikramvino1995/MyProjects
https://github.com/vikramvino1995/MyProjects
7d9fdb86f2e0a309e4db4a2dcb74ea52a29391ba
bc41e86c13fd065dbfcff0ffc48ef3c7225e1fe3
refs/heads/main
2023-08-14T14:37:36.643000
2021-08-30T14:50:22
2021-08-30T14:50:22
401,375,502
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.training; public abstract class Practice3 { public void method() { System.out.println("Old Method"); } /*public static void main(String[] args) { //initialisation outside loop int i =0; for(;i<100;i++) { System.out.println(i); }*/ }
UTF-8
Java
308
java
Practice3.java
Java
[]
null
[]
package org.training; public abstract class Practice3 { public void method() { System.out.println("Old Method"); } /*public static void main(String[] args) { //initialisation outside loop int i =0; for(;i<100;i++) { System.out.println(i); }*/ }
308
0.558442
0.542208
31
8.935484
12.367845
43
false
false
0
0
0
0
0
0
1.612903
false
false
10
174849b9691f076c498ab76f02bb81cbf6dd550a
24,833,500,934,188
cbdffc49a84de21cdc86d46a0d41da7ef1249a05
/class_02/src/day18/Test02.java
86fabda73e96ae2ca111677597375f1e73dc5415
[]
no_license
gogorailgun/gogorailgun
https://github.com/gogorailgun/gogorailgun
7ea26a50bd72d8a504b12d7bac733370e5df4e93
6bf88cdf493c392ebf9fdfd759ecba7b69ecf935
refs/heads/master
2022-12-24T10:22:30.978000
2020-10-07T11:22:15
2020-10-07T11:22:15
283,906,678
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package day18; public class Test02 { public Test02() { Test02_01 t1 = new Test02_01(); try { t1.createExcpt(); // 이 함수는 예외를 전이하는 함수이므로 함수를 호출한 곳에서 예외처리를 한다 } catch(Exception e) { e.printStackTrace(); } try { abc(); } catch(Exception e) { e.printStackTrace(); } Test02_02 t2 = new Test02_02(); t2.createExcpt(); } public void abc() throws Exception{ Test02_01 t1 = new Test02_01(); t1.createExcpt(); // 이 함수는 예외를 전이하는 함수이므로 함수를 호출한 곳에서 예외처리를 한다 } public static void main(String[] args) { } } class Test02_01{ public void createExcpt() throws Exception { System.out.println("여기는 Test02_01"); throw new Exception(); // 강제로 예외를 발생했으니 이 라인이 실행이 되면 무조건 예외가 발생한다. } } class Test02_02 extends Test02_01{ public void createExcpt() throws NumberFormatException{ System.out.println("여기는 Test02_02"); throw new NumberFormatException(); } }
UTF-8
Java
1,106
java
Test02.java
Java
[]
null
[]
package day18; public class Test02 { public Test02() { Test02_01 t1 = new Test02_01(); try { t1.createExcpt(); // 이 함수는 예외를 전이하는 함수이므로 함수를 호출한 곳에서 예외처리를 한다 } catch(Exception e) { e.printStackTrace(); } try { abc(); } catch(Exception e) { e.printStackTrace(); } Test02_02 t2 = new Test02_02(); t2.createExcpt(); } public void abc() throws Exception{ Test02_01 t1 = new Test02_01(); t1.createExcpt(); // 이 함수는 예외를 전이하는 함수이므로 함수를 호출한 곳에서 예외처리를 한다 } public static void main(String[] args) { } } class Test02_01{ public void createExcpt() throws Exception { System.out.println("여기는 Test02_01"); throw new Exception(); // 강제로 예외를 발생했으니 이 라인이 실행이 되면 무조건 예외가 발생한다. } } class Test02_02 extends Test02_01{ public void createExcpt() throws NumberFormatException{ System.out.println("여기는 Test02_02"); throw new NumberFormatException(); } }
1,106
0.652318
0.590508
51
16.784313
19.479816
68
false
false
0
0
0
0
0
0
1.529412
false
false
10
1771105d514b268cac37f27cca1240838902e2f1
25,623,774,935,767
b20984a1d64d3ecf51b931a00580475e8a8ae5d4
/MadBobServer/src/net/session/AbstractClient.java
8da19e26117f37d647f20185cfe7eccbf1d8b322
[]
no_license
zonalizengcun/ymwl
https://github.com/zonalizengcun/ymwl
4a58217f4906c01db7dc585a6ccf4de8997e428b
79ae6937b11ad50b403886fad6b4d303966a479f
refs/heads/master
2021-01-19T00:01:10.675000
2016-12-09T22:58:41
2016-12-09T22:58:41
72,840,075
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.session; import java.util.concurrent.ArrayBlockingQueue; import world.World; public abstract class AbstractClient { private volatile boolean isProcessing; private String token; private ArrayBlockingQueue<Packet> queue = new ArrayBlockingQueue<Packet>(512); public AbstractClient(String token){ this.token = token; } public boolean isProcessing() { return isProcessing; } public void setProcessing(boolean isProcessing) { this.isProcessing = isProcessing; } public void putPacket(Packet packet) { try { this.queue.put(packet); } catch (InterruptedException e) { e.printStackTrace(); } } public void process() { this.setProcessing(true); Packet packet; while (queue.size() > 0) { packet = queue.poll(); if (packet != null) { try { World.getDefault().getHandlerManager().handle(packet); } catch (Exception e) { e.printStackTrace(); this.setProcessing(false); } } } this.setProcessing(false); } public String getToken() { return token; } public void setToken(String token) { this.token = token; } }
UTF-8
Java
1,108
java
AbstractClient.java
Java
[]
null
[]
package net.session; import java.util.concurrent.ArrayBlockingQueue; import world.World; public abstract class AbstractClient { private volatile boolean isProcessing; private String token; private ArrayBlockingQueue<Packet> queue = new ArrayBlockingQueue<Packet>(512); public AbstractClient(String token){ this.token = token; } public boolean isProcessing() { return isProcessing; } public void setProcessing(boolean isProcessing) { this.isProcessing = isProcessing; } public void putPacket(Packet packet) { try { this.queue.put(packet); } catch (InterruptedException e) { e.printStackTrace(); } } public void process() { this.setProcessing(true); Packet packet; while (queue.size() > 0) { packet = queue.poll(); if (packet != null) { try { World.getDefault().getHandlerManager().handle(packet); } catch (Exception e) { e.printStackTrace(); this.setProcessing(false); } } } this.setProcessing(false); } public String getToken() { return token; } public void setToken(String token) { this.token = token; } }
1,108
0.691336
0.687726
60
17.466667
17.648859
80
false
false
0
0
0
0
0
0
1.783333
false
false
10
dc35e0add3a376911d65dc79b9dc1b5a749eb678
19,774,029,436,304
13fcb685c3c4b072e2ccf9d2ff8930bef1557dd2
/MedCareFinal1/src/com/prediction/heart/HomeServlet.java
8d13b2a6eba1c7177e453d7adfd3c3d460e8577f
[]
no_license
primeuser/bayesian_sclassification
https://github.com/primeuser/bayesian_sclassification
880ef20e303f1fff45b4d2cd7448ed9b5415c506
53ac0d93728cdd05c9edd8090cfa1911fddeafc5
refs/heads/master
2020-03-28T12:44:25.909000
2018-09-11T14:17:30
2018-09-11T14:17:30
148,329,357
5
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.prediction.heart; import weka.gui.GenericPropertiesCreator; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.prediction.heart.nb.NaiveBayesClassifier; /** * * @author Puri */ public class HomeServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final String HOME = "/"; private static final String FORM = "/form"; public double[] value = new double[5]; public static double chol1; public static double hbp1; public static double smoke1; public static double alch1; public static double pulse_rate1; /** * @see HttpServlet#HttpServlet() */ public HomeServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request,response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String result = ""; try { Map<QuestionType, Double> paramaters = new HashMap<QuestionType, Double>(); paramaters.put(QuestionType.AGE, Double.parseDouble(request.getParameter("age"))); paramaters.put(QuestionType.GENDER, Double.parseDouble(request.getParameter("gender"))); paramaters.put(QuestionType.CHEST_PAIN, Double.parseDouble(request.getParameter("chest_pain"))); paramaters.put(QuestionType.CIGS, Double.parseDouble(request.getParameter("cigs"))); paramaters.put(QuestionType.YEAR, Double.parseDouble(request.getParameter("year"))); paramaters.put(QuestionType.REST_ECG, Double.parseDouble(request.getParameter("rest_ecg"))); paramaters.put(QuestionType.H_BP, Double.parseDouble(request.getParameter("h_bp"))); paramaters.put(QuestionType.L_BP, Double.parseDouble(request.getParameter("l_bp"))); paramaters.put(QuestionType.PULSERATE, Double.parseDouble(request.getParameter("pulserate"))); paramaters.put(QuestionType.CHOLESTEROL, Double.parseDouble(request.getParameter("chol"))); paramaters.put(QuestionType.F_H, Double.parseDouble(request.getParameter("f_h"))); paramaters.put(QuestionType.ALCH, Double.parseDouble(request.getParameter("alch"))); // paramaters.put(QuestionType.THALACH, Double.parseDouble(request.getParameter("thalach"))); // paramaters.put(QuestionType.EXANG, Double.parseDouble(request.getParameter("exang"))); // paramaters.put(QuestionType.SLOPE, Double.parseDouble(request.getParameter("slope"))); // paramaters.put(QuestionType.CA, Double.parseDouble(request.getParameter("ca"))); // paramaters.put(QuestionType.THAL, Double.parseDouble(request.getParameter("thal"))); // paramaters.put(QuestionType.OLDPEAK, Double.parseDouble(request.getParameter("oldpeak"))); /*ServletContext context = getServletContext();*/ String dataFile = getServletContext().getRealPath("data/datasets/book2(2).arff"); String modelFile = getServletContext().getRealPath("data/realfinalmodel.nb.model"); /*String dataFile = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/data/datasets/heart.arff"; String modelFile = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/data/heart.nb.model";*/ /*String dataFile = "data/datasets/heart.arff"; String modelFile = "data/heart.nb.model";*/ NaiveBayesClassifier.train(dataFile, modelFile); result = NaiveBayesClassifier.medicalBot(modelFile, paramaters); chol1=Double.parseDouble(request.getParameter("chol")); hbp1=Double.parseDouble(request.getParameter("h_bp")); smoke1=Double.parseDouble(request.getParameter("cigs")); alch1=Double.parseDouble(request.getParameter("alch")); pulse_rate1=Double.parseDouble(request.getParameter("pulserate")); request.setAttribute("hbp1", request.getParameter("h_bp")); request.setAttribute("chol1",request.getParameter("chol")); request.setAttribute("smoke1",request.getParameter("cigs1")); request.setAttribute("alch1",request.getParameter("alch")); request.setAttribute("pulse_rate1",request.getParameter("pulserate")); } catch (Exception e) { e.printStackTrace(); } request.setAttribute("result", result); System.out.println(result); RequestDispatcher rd = request.getRequestDispatcher("output.jsp"); rd.forward(request, response); } private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String path = request.getServletPath(); switch (path) { case HOME: RequestDispatcher home = request.getRequestDispatcher("index.jsp"); home.forward(request, response); break; case FORM: RequestDispatcher form = request.getRequestDispatcher("newinterface.jsp"); form.forward(request, response); break; } } }
UTF-8
Java
6,219
java
HomeServlet.java
Java
[ { "context": ".heart.nb.NaiveBayesClassifier;\n\n/**\n *\n * @author Puri\n */\npublic class HomeServlet extends HttpServlet ", "end": 621, "score": 0.9997332096099854, "start": 617, "tag": "NAME", "value": "Puri" } ]
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.prediction.heart; import weka.gui.GenericPropertiesCreator; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.prediction.heart.nb.NaiveBayesClassifier; /** * * @author Puri */ public class HomeServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final String HOME = "/"; private static final String FORM = "/form"; public double[] value = new double[5]; public static double chol1; public static double hbp1; public static double smoke1; public static double alch1; public static double pulse_rate1; /** * @see HttpServlet#HttpServlet() */ public HomeServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request,response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String result = ""; try { Map<QuestionType, Double> paramaters = new HashMap<QuestionType, Double>(); paramaters.put(QuestionType.AGE, Double.parseDouble(request.getParameter("age"))); paramaters.put(QuestionType.GENDER, Double.parseDouble(request.getParameter("gender"))); paramaters.put(QuestionType.CHEST_PAIN, Double.parseDouble(request.getParameter("chest_pain"))); paramaters.put(QuestionType.CIGS, Double.parseDouble(request.getParameter("cigs"))); paramaters.put(QuestionType.YEAR, Double.parseDouble(request.getParameter("year"))); paramaters.put(QuestionType.REST_ECG, Double.parseDouble(request.getParameter("rest_ecg"))); paramaters.put(QuestionType.H_BP, Double.parseDouble(request.getParameter("h_bp"))); paramaters.put(QuestionType.L_BP, Double.parseDouble(request.getParameter("l_bp"))); paramaters.put(QuestionType.PULSERATE, Double.parseDouble(request.getParameter("pulserate"))); paramaters.put(QuestionType.CHOLESTEROL, Double.parseDouble(request.getParameter("chol"))); paramaters.put(QuestionType.F_H, Double.parseDouble(request.getParameter("f_h"))); paramaters.put(QuestionType.ALCH, Double.parseDouble(request.getParameter("alch"))); // paramaters.put(QuestionType.THALACH, Double.parseDouble(request.getParameter("thalach"))); // paramaters.put(QuestionType.EXANG, Double.parseDouble(request.getParameter("exang"))); // paramaters.put(QuestionType.SLOPE, Double.parseDouble(request.getParameter("slope"))); // paramaters.put(QuestionType.CA, Double.parseDouble(request.getParameter("ca"))); // paramaters.put(QuestionType.THAL, Double.parseDouble(request.getParameter("thal"))); // paramaters.put(QuestionType.OLDPEAK, Double.parseDouble(request.getParameter("oldpeak"))); /*ServletContext context = getServletContext();*/ String dataFile = getServletContext().getRealPath("data/datasets/book2(2).arff"); String modelFile = getServletContext().getRealPath("data/realfinalmodel.nb.model"); /*String dataFile = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/data/datasets/heart.arff"; String modelFile = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/data/heart.nb.model";*/ /*String dataFile = "data/datasets/heart.arff"; String modelFile = "data/heart.nb.model";*/ NaiveBayesClassifier.train(dataFile, modelFile); result = NaiveBayesClassifier.medicalBot(modelFile, paramaters); chol1=Double.parseDouble(request.getParameter("chol")); hbp1=Double.parseDouble(request.getParameter("h_bp")); smoke1=Double.parseDouble(request.getParameter("cigs")); alch1=Double.parseDouble(request.getParameter("alch")); pulse_rate1=Double.parseDouble(request.getParameter("pulserate")); request.setAttribute("hbp1", request.getParameter("h_bp")); request.setAttribute("chol1",request.getParameter("chol")); request.setAttribute("smoke1",request.getParameter("cigs1")); request.setAttribute("alch1",request.getParameter("alch")); request.setAttribute("pulse_rate1",request.getParameter("pulserate")); } catch (Exception e) { e.printStackTrace(); } request.setAttribute("result", result); System.out.println(result); RequestDispatcher rd = request.getRequestDispatcher("output.jsp"); rd.forward(request, response); } private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String path = request.getServletPath(); switch (path) { case HOME: RequestDispatcher home = request.getRequestDispatcher("index.jsp"); home.forward(request, response); break; case FORM: RequestDispatcher form = request.getRequestDispatcher("newinterface.jsp"); form.forward(request, response); break; } } }
6,219
0.666023
0.662808
133
45.759399
37.070175
125
false
false
0
0
0
0
0
0
1.87218
false
false
10
b928af9e8c04a31d01c66da2d42e4e49bce59cb9
7,275,674,631,057
d8d36b6804d8b1443d0c7e6ed8d120315b735472
/src/main/java/com/xd/wyq/food/medicine/repository/MonitorFolderRepository.java
689294e19105f1b8111986c10aa4127d7cad6a06
[]
no_license
pw971959756/wyq_food_medicine
https://github.com/pw971959756/wyq_food_medicine
41bab3558427a2286286e4938a05285f3662f044
344fa4bd3c7f3418ad93f79cbb98602494d30a3e
refs/heads/master
2021-01-25T11:33:52.714000
2018-03-01T09:23:47
2018-03-01T09:23:47
123,408,989
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xd.wyq.food.medicine.repository; import com.xd.wyq.food.medicine.entity.MonitorFolder; import org.springframework.data.jpa.repository.JpaRepository; /** * Created by pengwei * 2018/3/1. */ public interface MonitorFolderRepository extends JpaRepository<MonitorFolder,Integer> { }
UTF-8
Java
299
java
MonitorFolderRepository.java
Java
[ { "context": "a.jpa.repository.JpaRepository;\n\n/**\n * Created by pengwei\n * 2018/3/1.\n */\npublic interface MonitorFolderRe", "end": 188, "score": 0.9993743300437927, "start": 181, "tag": "USERNAME", "value": "pengwei" } ]
null
[]
package com.xd.wyq.food.medicine.repository; import com.xd.wyq.food.medicine.entity.MonitorFolder; import org.springframework.data.jpa.repository.JpaRepository; /** * Created by pengwei * 2018/3/1. */ public interface MonitorFolderRepository extends JpaRepository<MonitorFolder,Integer> { }
299
0.789298
0.769231
14
20.357143
27.822414
87
false
false
0
0
0
0
0
0
0.285714
false
false
10
0b23e68f7f69617c64dddfabed78bd029fdbbab6
7,275,674,627,880
b68766fa97199aca1610b867755cb767fcbe8ac6
/app/src/main/java/com/dev/muslim/pantaumeter/InputMeteran.java
57ba6ce81e3f4043f3838d0624a6e6affe7397c9
[]
no_license
nanda20/PantauMeter
https://github.com/nanda20/PantauMeter
d40113bc08b51e9be405f72bb9b11091152b97aa
658d84bef37c2a2325309f8eb1715bda4a8b9631
refs/heads/master
2021-01-01T20:09:18.541000
2018-01-24T14:01:53
2018-01-24T14:01:53
98,779,672
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.dev.muslim.pantaumeter; import android.Manifest; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.AsyncTask; import android.os.Environment; import android.provider.MediaStore; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.JsonHttpResponseHandler; import com.loopj.android.http.RequestParams; import com.loopj.android.http.SyncHttpClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import cz.msebera.android.httpclient.Header; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.RequestBody; import pub.devrel.easypermissions.EasyPermissions; import retrofit2.Call; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.Callback; import retrofit2.converter.gson.GsonConverterFactory; import static android.provider.ContactsContract.CommonDataKinds.Website.URL; public class InputMeteran extends AppCompatActivity { private static final String TAG = "InputMeteran"; TextView id_pel,txtStatusUpload; ImageView imageView; EditText txtStandIni,txtKelainan; Button btnUpload,btnDraf; public boolean statusUpload=false; Intent intent; //utilitys for capture private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100; public static final int MEDIA_TYPE_IMAGE = 1; private static final String IMAGE_DIRECTORY_NAME = "PantauMeter"; private Uri fileUri; // file url to store image/video private GetConnection connection= null; private String id1=""; private String status; //upload // private static final String SERVER_PATH = "http://192.168.1.116:8080/manajemen_pelanggan/api/upload/"; private static String SERVER_PATH = GetConnection.IP +"/manajemen_pelanggan/api/upload/"; private static final int READ_REQUEST_CODE = 300; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_input_meteran); id_pel= (TextView)findViewById(R.id.idPelanggan); imageView = (ImageView)findViewById(R.id.fotoMeter); txtStandIni = (EditText)findViewById(R.id.standIni); txtKelainan= (EditText)findViewById(R.id.kelainan); btnUpload= (Button)findViewById(R.id.btnUpload); btnDraf= (Button)findViewById(R.id.btnDraf); txtStatusUpload =(TextView)findViewById(R.id.txtStatusUpload); intent= getIntent(); status = intent.getStringExtra("status"); if(status.equals("draf")){ id1=String.valueOf(intent.getIntExtra("id1",0)); id_pel.setText(String.valueOf(intent.getIntExtra("no_pel",0))); txtStandIni.setText(intent.getStringExtra("stand")); txtKelainan.setText(intent.getStringExtra("keterangan")); Uri uri= Uri.parse(intent.getStringExtra("foto").toString()); fileUri =uri; imageView.setImageURI(uri); btnDraf.setEnabled(false); }else{ btnDraf.setEnabled(true); } id_pel.setText(String.valueOf(intent.getIntExtra("no_pel",0))); id1=String.valueOf(intent.getIntExtra("id1",0)); imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { captureImage(); } }); btnUpload.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { connection= GetConnection.getInstance(); if(connection.isNetworkAvailable(getApplicationContext())) { new UploadFileToServer().execute(); }else{ // Toast.makeText(getApplicationContext(),"Tidak Ada Jaringan Internet",Toast.LENGTH_LONG).show(); AlertDialog.Builder dialogDraf = new AlertDialog.Builder(InputMeteran.this); dialogDraf.setCancelable(false); dialogDraf.setTitle("Tidak Ada Jaringan Internet"); dialogDraf.setMessage("Gagal Upload,Coba beberapa saat Lagi , Simpan ke draf ?" ); dialogDraf.setPositiveButton("Close", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { } }) .setNegativeButton("Save ", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { saveToDraf(); } }); final AlertDialog alert = dialogDraf.create(); alert.show(); } } }); btnDraf.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { saveToDraf(); } }); } public void saveToDraf(){ DataPojo draf= new DataPojo(); draf.setId1(Integer.valueOf(id1)); draf.setId_pel(Integer.valueOf(id_pel.getText().toString())); draf.setStandKini(txtStandIni.getText().toString()); draf.setNama(intent.getStringExtra("nama")); draf.setFoto(fileUri.getPath().toString()); draf.setKeterangan(txtKelainan.getText().toString()); Toast.makeText(getApplicationContext(),"Berhasil Menyimpan Ke Draf",Toast.LENGTH_SHORT).show(); btnDraf.setEnabled(false); btnUpload.setEnabled(false); new SqlPelangganHelper(getApplicationContext()).addDraf(draf); new SqlPelangganHelper(getApplicationContext()).updateStatus(Integer.valueOf(id_pel.getText().toString())); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) { if (resultCode == RESULT_OK) { // successfully captured the image // display it in image view previewCapturedImage(); } else if (resultCode == RESULT_CANCELED) { // user cancelled Image capture Toast.makeText(getApplicationContext(), "User cancelled image capture", Toast.LENGTH_SHORT) .show(); } else { // failed to capture image Toast.makeText(getApplicationContext(), "Sorry! Failed to capture image", Toast.LENGTH_SHORT) .show(); } } } private void previewCapturedImage() { try { BitmapFactory.Options options = new BitmapFactory.Options(); // down sizing image as it throws OutOfMemory Exception for larger // images options.inSampleSize = 8; final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(), options); imageView.setImageBitmap(bitmap); } catch (NullPointerException e) { e.printStackTrace(); } } private void captureImage() { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // start the image capture Intent startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE); } public Uri getOutputMediaFileUri(int type) { return Uri.fromFile(getOutputMediaFile(type)); } private static File getOutputMediaFile(int type) { // External sdcard location File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), IMAGE_DIRECTORY_NAME); // Create the storage directory if it does not exist if (!mediaStorageDir.exists()) { if (!mediaStorageDir.mkdirs()) { Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create " + IMAGE_DIRECTORY_NAME + " directory"); return null; } } // Create a media file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date()); File mediaFile; if (type == MEDIA_TYPE_IMAGE) { mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg"); } else { return null; } return mediaFile; } public class UploadFileToServer extends AsyncTask<Void, Integer, String> { private final ProgressDialog dialog = new ProgressDialog(InputMeteran.this); protected void onPreExecute() { this.dialog.setMessage("Loading..."); this.dialog.setCancelable(false); this.dialog.show(); Log.d("TASK","onPreExecute"); } @Override protected String doInBackground(Void... params) { Log.d("TASK","doInBackground"); uploadImage2(); return null; } @Override protected void onProgressUpdate(Integer... progress) { Log.d("TASK","onProgressUpdate"); connection= GetConnection.getInstance(); if(!connection.isNetworkAvailable(getApplicationContext())) { Toast.makeText(getApplicationContext(),"Upload Terhenti, Coba beberapa saat lagi ",Toast.LENGTH_LONG).show(); onCancelled(); onDestroy(); // txtStatusUpload.setText("Gagal Upload,Coba beberapa saat Lagi"); // saveToDraf(); if (dialog.isShowing()) { dialog.dismiss(); } } } @Override protected void onPostExecute(String s) { // Here if you wish to do future process for ex. move to another activity do here if (dialog.isShowing()) { dialog.dismiss(); } if(statusUpload==true){ Toast.makeText(getApplicationContext(),"Data Berhasil di Upload",Toast.LENGTH_LONG).show(); btnUpload.setEnabled(false); btnDraf.setEnabled(false); if(status.equals("draf")) { new SqlPelangganHelper(getApplicationContext()).deleteDraf(Integer.valueOf(id1)); } txtStatusUpload.setText("Data Berhasil Di Upload"); }else{ // new SqlPelangganHelper(getApplicationContext()).update(Integer.valueOf(String.valueOf(id_pel.getText()))); final AlertDialog.Builder dialogDraf = new AlertDialog.Builder(InputMeteran.this); dialogDraf.setCancelable(false); dialogDraf.setTitle("Tidak Ada Jaringan Internet"); dialogDraf.setMessage("Data Gagal di Upload,Coba beberapa saat Lagi , Simpan ke draf ?" ); dialogDraf.setPositiveButton("Close", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { } }) .setNegativeButton("Save ", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { saveToDraf(); } }); final AlertDialog alert = dialogDraf.create(); alert.show(); // Toast.makeText(getApplicationContext(),"Data Gagal di Upload",Toast.LENGTH_LONG).show(); txtStatusUpload.setText("Gagal Upload,Coba beberapa saat Lagi"); } } } //upload image using loopj private void uploadImage2(){ File myFile = new File(fileUri.getPath()); SyncHttpClient client = new SyncHttpClient(); RequestParams params= new RequestParams(); try { params.put("file", photoCompressor(myFile)); } catch (FileNotFoundException e) { e.printStackTrace(); } // params.setUseJsonStreamer(false); params.put("id1",id1); params.put("id_pel",String.valueOf(id_pel.getText())); params.put("stand_kini",String.valueOf(txtStandIni.getText())); params.put("kelainan",String.valueOf(txtKelainan.getText())); //client.setConnectTimeout(3000); client.post(SERVER_PATH, params, new JsonHttpResponseHandler(){ @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { super.onSuccess(statusCode, headers, response); Log.d("response"," Success "+response.toString()); statusUpload=true; } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); Log.d("response"," Failed "+errorResponse.toString()); statusUpload=false; // Toast.makeText(getApplicationContext(),"Data Gagal di Upload",Toast.LENGTH_LONG).show(); } }); } private void uploadImage() { if (EasyPermissions.hasPermissions(this, Manifest.permission.READ_EXTERNAL_STORAGE)) { String filePath = getRealPathFromURIPath(fileUri, InputMeteran.this); File filePhoto = new File(fileUri.getPath()); Log.d("FileName", "Filename " + filePhoto.getName()); RequestBody mFile = RequestBody.create(MediaType.parse("multipart/form-data"), photoCompressor(filePhoto)); // RequestBody mFile = RequestBody.create(MediaType.parse("image/*"), file); MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", photoCompressor(filePhoto).getName(), mFile); RequestBody filename = RequestBody.create(MediaType.parse("text/plain"), photoCompressor(filePhoto).getName()); Retrofit retrofit = new Retrofit.Builder() .baseUrl(SERVER_PATH) .addConverterFactory(GsonConverterFactory.create()) .build(); UploadImageInterface uploadImage = retrofit.create(UploadImageInterface.class); Call<UploadObject> fileUpload = uploadImage.uploadFile(fileToUpload, filename); fileUpload.enqueue(new Callback<UploadObject>() { @Override public void onResponse(Call<UploadObject> call, Response<UploadObject> response) { Log.d("Response", response.raw().message()); Log.d("Response", "Success " + response.body().getSuccess()); Toast.makeText(getBaseContext(), "Success " + response.body().getSuccess(), Toast.LENGTH_LONG).show(); } @Override public void onFailure(Call<UploadObject> call, Throwable t) { Log.d("Response", "Error " + t.getMessage()); Toast.makeText(getBaseContext(), "Canot Upload " + t.getMessage(), Toast.LENGTH_LONG).show(); } }); } else { EasyPermissions.requestPermissions(this, "This app needs access to your file storage so that it can read photos", READ_REQUEST_CODE, Manifest.permission.READ_EXTERNAL_STORAGE); } } private String getRealPathFromURIPath(Uri contentURI, Activity activity) { Cursor cursor = activity.getContentResolver().query(contentURI, null, null, null, null); if (cursor == null) { return contentURI.getPath(); } else { cursor.moveToFirst(); int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); return cursor.getString(idx); } } public File photoCompressor(File photoFile) { Bitmap b = BitmapFactory.decodeFile(photoFile.getAbsolutePath()); int originalWidth = b.getWidth(); int originalHeight = b.getHeight(); int boundWidth = 800; int boundHeight = 800; int newWidth = originalWidth; int newHeight = originalHeight; //check if the image needs to be scale width if (originalWidth > boundWidth) { //scale width to fit newWidth = boundWidth; //scale height to maintain aspect ratio newHeight = (newWidth * originalHeight) / originalWidth; } //now check if we need to scale even the new height if (newHeight > boundHeight) { //scale height to fit instead newHeight = boundHeight; //scale width to maintain aspect ratio newWidth = (newHeight * originalWidth) / originalHeight; } Log.i(TAG, "Original Image:" + originalHeight + " x" + originalWidth); Log.i(TAG, "New Image:" + newHeight + " x" + newWidth); try { Bitmap out = Bitmap.createScaledBitmap(b, newWidth, newHeight, true); FileOutputStream fOut; fOut = new FileOutputStream(photoFile); out.compress(Bitmap.CompressFormat.JPEG, 100, fOut); fOut.flush(); fOut.close(); b.recycle(); out.recycle(); } catch (OutOfMemoryError exception) { Log.e(TAG, "OutofMemory excpetion" + exception); exception.printStackTrace(); } catch (FileNotFoundException e) { Log.e(TAG, "File not found excpetion" + e); e.printStackTrace(); } catch (IOException e) { Log.e(TAG, "IO exception excpetion" + e); e.printStackTrace(); } return photoFile; } }
UTF-8
Java
18,931
java
InputMeteran.java
Java
[ { "context": "private static final String SERVER_PATH = \"http://192.168.1.116:8080/manajemen_pelanggan/api/upload/\";\n privat", "end": 2472, "score": 0.999660849571228, "start": 2459, "tag": "IP_ADDRESS", "value": "192.168.1.116" } ]
null
[]
package com.dev.muslim.pantaumeter; import android.Manifest; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.AsyncTask; import android.os.Environment; import android.provider.MediaStore; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.JsonHttpResponseHandler; import com.loopj.android.http.RequestParams; import com.loopj.android.http.SyncHttpClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import cz.msebera.android.httpclient.Header; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.RequestBody; import pub.devrel.easypermissions.EasyPermissions; import retrofit2.Call; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.Callback; import retrofit2.converter.gson.GsonConverterFactory; import static android.provider.ContactsContract.CommonDataKinds.Website.URL; public class InputMeteran extends AppCompatActivity { private static final String TAG = "InputMeteran"; TextView id_pel,txtStatusUpload; ImageView imageView; EditText txtStandIni,txtKelainan; Button btnUpload,btnDraf; public boolean statusUpload=false; Intent intent; //utilitys for capture private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100; public static final int MEDIA_TYPE_IMAGE = 1; private static final String IMAGE_DIRECTORY_NAME = "PantauMeter"; private Uri fileUri; // file url to store image/video private GetConnection connection= null; private String id1=""; private String status; //upload // private static final String SERVER_PATH = "http://192.168.1.116:8080/manajemen_pelanggan/api/upload/"; private static String SERVER_PATH = GetConnection.IP +"/manajemen_pelanggan/api/upload/"; private static final int READ_REQUEST_CODE = 300; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_input_meteran); id_pel= (TextView)findViewById(R.id.idPelanggan); imageView = (ImageView)findViewById(R.id.fotoMeter); txtStandIni = (EditText)findViewById(R.id.standIni); txtKelainan= (EditText)findViewById(R.id.kelainan); btnUpload= (Button)findViewById(R.id.btnUpload); btnDraf= (Button)findViewById(R.id.btnDraf); txtStatusUpload =(TextView)findViewById(R.id.txtStatusUpload); intent= getIntent(); status = intent.getStringExtra("status"); if(status.equals("draf")){ id1=String.valueOf(intent.getIntExtra("id1",0)); id_pel.setText(String.valueOf(intent.getIntExtra("no_pel",0))); txtStandIni.setText(intent.getStringExtra("stand")); txtKelainan.setText(intent.getStringExtra("keterangan")); Uri uri= Uri.parse(intent.getStringExtra("foto").toString()); fileUri =uri; imageView.setImageURI(uri); btnDraf.setEnabled(false); }else{ btnDraf.setEnabled(true); } id_pel.setText(String.valueOf(intent.getIntExtra("no_pel",0))); id1=String.valueOf(intent.getIntExtra("id1",0)); imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { captureImage(); } }); btnUpload.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { connection= GetConnection.getInstance(); if(connection.isNetworkAvailable(getApplicationContext())) { new UploadFileToServer().execute(); }else{ // Toast.makeText(getApplicationContext(),"Tidak Ada Jaringan Internet",Toast.LENGTH_LONG).show(); AlertDialog.Builder dialogDraf = new AlertDialog.Builder(InputMeteran.this); dialogDraf.setCancelable(false); dialogDraf.setTitle("Tidak Ada Jaringan Internet"); dialogDraf.setMessage("Gagal Upload,Coba beberapa saat Lagi , Simpan ke draf ?" ); dialogDraf.setPositiveButton("Close", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { } }) .setNegativeButton("Save ", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { saveToDraf(); } }); final AlertDialog alert = dialogDraf.create(); alert.show(); } } }); btnDraf.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { saveToDraf(); } }); } public void saveToDraf(){ DataPojo draf= new DataPojo(); draf.setId1(Integer.valueOf(id1)); draf.setId_pel(Integer.valueOf(id_pel.getText().toString())); draf.setStandKini(txtStandIni.getText().toString()); draf.setNama(intent.getStringExtra("nama")); draf.setFoto(fileUri.getPath().toString()); draf.setKeterangan(txtKelainan.getText().toString()); Toast.makeText(getApplicationContext(),"Berhasil Menyimpan Ke Draf",Toast.LENGTH_SHORT).show(); btnDraf.setEnabled(false); btnUpload.setEnabled(false); new SqlPelangganHelper(getApplicationContext()).addDraf(draf); new SqlPelangganHelper(getApplicationContext()).updateStatus(Integer.valueOf(id_pel.getText().toString())); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) { if (resultCode == RESULT_OK) { // successfully captured the image // display it in image view previewCapturedImage(); } else if (resultCode == RESULT_CANCELED) { // user cancelled Image capture Toast.makeText(getApplicationContext(), "User cancelled image capture", Toast.LENGTH_SHORT) .show(); } else { // failed to capture image Toast.makeText(getApplicationContext(), "Sorry! Failed to capture image", Toast.LENGTH_SHORT) .show(); } } } private void previewCapturedImage() { try { BitmapFactory.Options options = new BitmapFactory.Options(); // down sizing image as it throws OutOfMemory Exception for larger // images options.inSampleSize = 8; final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(), options); imageView.setImageBitmap(bitmap); } catch (NullPointerException e) { e.printStackTrace(); } } private void captureImage() { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // start the image capture Intent startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE); } public Uri getOutputMediaFileUri(int type) { return Uri.fromFile(getOutputMediaFile(type)); } private static File getOutputMediaFile(int type) { // External sdcard location File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), IMAGE_DIRECTORY_NAME); // Create the storage directory if it does not exist if (!mediaStorageDir.exists()) { if (!mediaStorageDir.mkdirs()) { Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create " + IMAGE_DIRECTORY_NAME + " directory"); return null; } } // Create a media file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date()); File mediaFile; if (type == MEDIA_TYPE_IMAGE) { mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg"); } else { return null; } return mediaFile; } public class UploadFileToServer extends AsyncTask<Void, Integer, String> { private final ProgressDialog dialog = new ProgressDialog(InputMeteran.this); protected void onPreExecute() { this.dialog.setMessage("Loading..."); this.dialog.setCancelable(false); this.dialog.show(); Log.d("TASK","onPreExecute"); } @Override protected String doInBackground(Void... params) { Log.d("TASK","doInBackground"); uploadImage2(); return null; } @Override protected void onProgressUpdate(Integer... progress) { Log.d("TASK","onProgressUpdate"); connection= GetConnection.getInstance(); if(!connection.isNetworkAvailable(getApplicationContext())) { Toast.makeText(getApplicationContext(),"Upload Terhenti, Coba beberapa saat lagi ",Toast.LENGTH_LONG).show(); onCancelled(); onDestroy(); // txtStatusUpload.setText("Gagal Upload,Coba beberapa saat Lagi"); // saveToDraf(); if (dialog.isShowing()) { dialog.dismiss(); } } } @Override protected void onPostExecute(String s) { // Here if you wish to do future process for ex. move to another activity do here if (dialog.isShowing()) { dialog.dismiss(); } if(statusUpload==true){ Toast.makeText(getApplicationContext(),"Data Berhasil di Upload",Toast.LENGTH_LONG).show(); btnUpload.setEnabled(false); btnDraf.setEnabled(false); if(status.equals("draf")) { new SqlPelangganHelper(getApplicationContext()).deleteDraf(Integer.valueOf(id1)); } txtStatusUpload.setText("Data Berhasil Di Upload"); }else{ // new SqlPelangganHelper(getApplicationContext()).update(Integer.valueOf(String.valueOf(id_pel.getText()))); final AlertDialog.Builder dialogDraf = new AlertDialog.Builder(InputMeteran.this); dialogDraf.setCancelable(false); dialogDraf.setTitle("Tidak Ada Jaringan Internet"); dialogDraf.setMessage("Data Gagal di Upload,Coba beberapa saat Lagi , Simpan ke draf ?" ); dialogDraf.setPositiveButton("Close", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { } }) .setNegativeButton("Save ", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { saveToDraf(); } }); final AlertDialog alert = dialogDraf.create(); alert.show(); // Toast.makeText(getApplicationContext(),"Data Gagal di Upload",Toast.LENGTH_LONG).show(); txtStatusUpload.setText("Gagal Upload,Coba beberapa saat Lagi"); } } } //upload image using loopj private void uploadImage2(){ File myFile = new File(fileUri.getPath()); SyncHttpClient client = new SyncHttpClient(); RequestParams params= new RequestParams(); try { params.put("file", photoCompressor(myFile)); } catch (FileNotFoundException e) { e.printStackTrace(); } // params.setUseJsonStreamer(false); params.put("id1",id1); params.put("id_pel",String.valueOf(id_pel.getText())); params.put("stand_kini",String.valueOf(txtStandIni.getText())); params.put("kelainan",String.valueOf(txtKelainan.getText())); //client.setConnectTimeout(3000); client.post(SERVER_PATH, params, new JsonHttpResponseHandler(){ @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { super.onSuccess(statusCode, headers, response); Log.d("response"," Success "+response.toString()); statusUpload=true; } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); Log.d("response"," Failed "+errorResponse.toString()); statusUpload=false; // Toast.makeText(getApplicationContext(),"Data Gagal di Upload",Toast.LENGTH_LONG).show(); } }); } private void uploadImage() { if (EasyPermissions.hasPermissions(this, Manifest.permission.READ_EXTERNAL_STORAGE)) { String filePath = getRealPathFromURIPath(fileUri, InputMeteran.this); File filePhoto = new File(fileUri.getPath()); Log.d("FileName", "Filename " + filePhoto.getName()); RequestBody mFile = RequestBody.create(MediaType.parse("multipart/form-data"), photoCompressor(filePhoto)); // RequestBody mFile = RequestBody.create(MediaType.parse("image/*"), file); MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", photoCompressor(filePhoto).getName(), mFile); RequestBody filename = RequestBody.create(MediaType.parse("text/plain"), photoCompressor(filePhoto).getName()); Retrofit retrofit = new Retrofit.Builder() .baseUrl(SERVER_PATH) .addConverterFactory(GsonConverterFactory.create()) .build(); UploadImageInterface uploadImage = retrofit.create(UploadImageInterface.class); Call<UploadObject> fileUpload = uploadImage.uploadFile(fileToUpload, filename); fileUpload.enqueue(new Callback<UploadObject>() { @Override public void onResponse(Call<UploadObject> call, Response<UploadObject> response) { Log.d("Response", response.raw().message()); Log.d("Response", "Success " + response.body().getSuccess()); Toast.makeText(getBaseContext(), "Success " + response.body().getSuccess(), Toast.LENGTH_LONG).show(); } @Override public void onFailure(Call<UploadObject> call, Throwable t) { Log.d("Response", "Error " + t.getMessage()); Toast.makeText(getBaseContext(), "Canot Upload " + t.getMessage(), Toast.LENGTH_LONG).show(); } }); } else { EasyPermissions.requestPermissions(this, "This app needs access to your file storage so that it can read photos", READ_REQUEST_CODE, Manifest.permission.READ_EXTERNAL_STORAGE); } } private String getRealPathFromURIPath(Uri contentURI, Activity activity) { Cursor cursor = activity.getContentResolver().query(contentURI, null, null, null, null); if (cursor == null) { return contentURI.getPath(); } else { cursor.moveToFirst(); int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); return cursor.getString(idx); } } public File photoCompressor(File photoFile) { Bitmap b = BitmapFactory.decodeFile(photoFile.getAbsolutePath()); int originalWidth = b.getWidth(); int originalHeight = b.getHeight(); int boundWidth = 800; int boundHeight = 800; int newWidth = originalWidth; int newHeight = originalHeight; //check if the image needs to be scale width if (originalWidth > boundWidth) { //scale width to fit newWidth = boundWidth; //scale height to maintain aspect ratio newHeight = (newWidth * originalHeight) / originalWidth; } //now check if we need to scale even the new height if (newHeight > boundHeight) { //scale height to fit instead newHeight = boundHeight; //scale width to maintain aspect ratio newWidth = (newHeight * originalWidth) / originalHeight; } Log.i(TAG, "Original Image:" + originalHeight + " x" + originalWidth); Log.i(TAG, "New Image:" + newHeight + " x" + newWidth); try { Bitmap out = Bitmap.createScaledBitmap(b, newWidth, newHeight, true); FileOutputStream fOut; fOut = new FileOutputStream(photoFile); out.compress(Bitmap.CompressFormat.JPEG, 100, fOut); fOut.flush(); fOut.close(); b.recycle(); out.recycle(); } catch (OutOfMemoryError exception) { Log.e(TAG, "OutofMemory excpetion" + exception); exception.printStackTrace(); } catch (FileNotFoundException e) { Log.e(TAG, "File not found excpetion" + e); e.printStackTrace(); } catch (IOException e) { Log.e(TAG, "IO exception excpetion" + e); e.printStackTrace(); } return photoFile; } }
18,931
0.608684
0.605462
480
38.439583
30.92997
188
false
false
0
0
0
0
0
0
0.720833
false
false
10
5cba609ae762a40f01e3ca1bb2bb9273dce126c7
16,793,322,166,637
2e7d26e66471f57213441a5c09366b01c825a701
/DyClock.java
8c6e116718f4c167e3f738b3e17f68c392ec8fa3
[]
no_license
Neptune-KK/-
https://github.com/Neptune-KK/-
6adf8110fb8f6ce795af147f4bc73a3518cacdfb
0f40779f7ac39f0a34a63e38485255ed0582be8b
refs/heads/master
2022-10-30T09:29:50.088000
2020-06-15T14:44:16
2020-06-15T14:44:16
272,463,873
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dyclock; import java.awt.event.*; import javax.swing.*; public class DyClock extends StillClock{ public DyClock() { Timer time=new Timer(1000,new TimerListener()); time.start(); } class TimerListener implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { setCurrentTime(); repaint(); } } public static void main(String[] args) { JFrame f=new JFrame("钟"); DyClock clock=new DyClock(); f.add(clock); f.setLocationRelativeTo(null); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setSize(200,200); f.setVisible(true); } }
UTF-8
Java
665
java
DyClock.java
Java
[]
null
[]
package dyclock; import java.awt.event.*; import javax.swing.*; public class DyClock extends StillClock{ public DyClock() { Timer time=new Timer(1000,new TimerListener()); time.start(); } class TimerListener implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { setCurrentTime(); repaint(); } } public static void main(String[] args) { JFrame f=new JFrame("钟"); DyClock clock=new DyClock(); f.add(clock); f.setLocationRelativeTo(null); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setSize(200,200); f.setVisible(true); } }
665
0.641026
0.625943
29
21.862068
16.353264
55
false
false
0
0
0
0
0
0
1.62069
false
false
10
dc393327f114a632b17f9f883790b4ac691a131a
28,157,805,654,889
c663d9443ce7b296c29bb2dc2d8c5fd15bcf8d9e
/src_java_hidmc/src/dbg/hid2pwm/Launcher.java
2be1f887ad8c0098ec739273e77745daec51ab09
[]
no_license
dbg4f/dbg-misc-electronics
https://github.com/dbg4f/dbg-misc-electronics
db18f753be35b26ad5571e8d4f2141f7c19ba937
48e84b72f2c6eac8374f34eeffe79c1247a8b2ae
refs/heads/master
2021-01-01T17:56:55.559000
2014-11-22T19:00:07
2014-11-22T19:00:07
33,182,919
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dbg.hid2pwm; import org.apache.log4j.Logger; import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; public class Launcher { private static final Logger log = Logger.getLogger(Launcher.class); public static void main(String[] args) throws Exception { XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("hidmc-components.xml")); PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer(); cfg.setLocation(new ClassPathResource("hidmc.properties")); cfg.postProcessBeanFactory(beanFactory); Host host = (Host)beanFactory.getBean("host"); log.info("host = " + host); } }
UTF-8
Java
814
java
Launcher.java
Java
[]
null
[]
package dbg.hid2pwm; import org.apache.log4j.Logger; import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; public class Launcher { private static final Logger log = Logger.getLogger(Launcher.class); public static void main(String[] args) throws Exception { XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("hidmc-components.xml")); PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer(); cfg.setLocation(new ClassPathResource("hidmc.properties")); cfg.postProcessBeanFactory(beanFactory); Host host = (Host)beanFactory.getBean("host"); log.info("host = " + host); } }
814
0.750614
0.748157
25
30.559999
31.367601
99
false
false
0
0
0
0
0
0
0.48
false
false
10
215fee1e9b503723102b4288c772fb109a9b8267
29,497,835,422,402
b2a4d78747f8eb11e36e0900304257547158decf
/hw06/Root.java
0cf28d9f63091d94be4100cda16c6c506c17af8b
[]
no_license
mek217/CSE2
https://github.com/mek217/CSE2
007fa008331e2942cd339f9b97fae56b2fdfb199
323b868144dfa984a8ebc6e7ac0de8fd9181acf5
refs/heads/master
2020-06-06T16:49:54.288000
2014-12-08T03:51:54
2014-12-08T03:51:54
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
//////////////////////////////////////////////////////////////////////////// //Matthew Koh //10/14/14 //Hw06 //Program Root import java.util.Scanner; public class Root{ public static void main(String[] args){ Scanner myScan; myScan = new Scanner(System.in); String lastCheck; //Wrap the code in an infinite loop. Give user the option to break out after each run of the program. while(true){ //Force user to enter a double greater than 0 System.out.print("Enter a double greater than 0- "); if(myScan.hasNextDouble()){ double x = myScan.nextDouble(); if(x > 0){ //Declare variables low, middle, and high double low = 0.0, high = x + 1; double mid = (low+high)/2; //LOOP ALL OF THIS: while(high-low > 0.0000001){ //If middle squared is greater than x, then set high to middle. if(mid*mid > x){ high = mid; } //If middle squared is less than x, then set low to middle. else if(mid*mid < x){ low = mid; } //Reset mid to match the new high and low mid = (low+high)/2; } //Print calculated output System.out.println("The square root of your number is " + mid + ", with a tolerance level of 0.0000001."); } else{ System.out.println("User did not enter a double greater than 0"); } } else{ System.out.println("User did not enter a double. "); } //Give user the option to break out of the infinite loop after each run of the program System.out.print("Enter y or Y to go again- "); lastCheck = myScan.next(); if(lastCheck.equals("Y") || lastCheck.equals("y")){ } else{ break; } } } }
UTF-8
Java
2,562
java
Root.java
Java
[ { "context": "///////////////////////////////////////////////\n//Matthew Koh\n//10/14/14\n//Hw06\n//Program Root\n\nimport java.uti", "end": 90, "score": 0.9998849630355835, "start": 79, "tag": "NAME", "value": "Matthew Koh" } ]
null
[]
//////////////////////////////////////////////////////////////////////////// //<NAME> //10/14/14 //Hw06 //Program Root import java.util.Scanner; public class Root{ public static void main(String[] args){ Scanner myScan; myScan = new Scanner(System.in); String lastCheck; //Wrap the code in an infinite loop. Give user the option to break out after each run of the program. while(true){ //Force user to enter a double greater than 0 System.out.print("Enter a double greater than 0- "); if(myScan.hasNextDouble()){ double x = myScan.nextDouble(); if(x > 0){ //Declare variables low, middle, and high double low = 0.0, high = x + 1; double mid = (low+high)/2; //LOOP ALL OF THIS: while(high-low > 0.0000001){ //If middle squared is greater than x, then set high to middle. if(mid*mid > x){ high = mid; } //If middle squared is less than x, then set low to middle. else if(mid*mid < x){ low = mid; } //Reset mid to match the new high and low mid = (low+high)/2; } //Print calculated output System.out.println("The square root of your number is " + mid + ", with a tolerance level of 0.0000001."); } else{ System.out.println("User did not enter a double greater than 0"); } } else{ System.out.println("User did not enter a double. "); } //Give user the option to break out of the infinite loop after each run of the program System.out.print("Enter y or Y to go again- "); lastCheck = myScan.next(); if(lastCheck.equals("Y") || lastCheck.equals("y")){ } else{ break; } } } }
2,557
0.382123
0.369243
76
32.723682
26.380116
126
false
false
0
0
0
0
86
0.033568
0.328947
false
false
10
c4d2522b6167042fd8b57095994e7bf9cc5c9be2
29,497,835,425,527
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/2/2_4015e48cca211628f660c292c3a46a58caf2f8fc/ContentName/2_4015e48cca211628f660c292c3a46a58caf2f8fc_ContentName_t.java
1c8145a388cdb3e2b59ab866eed8c6b152e7332d
[]
no_license
zhongxingyu/Seer
https://github.com/zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516000
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
false
2023-06-22T07:55:57
2020-04-28T11:07:49
2023-06-21T00:53:27
2023-06-22T07:55:57
2,849,868
2
2
0
null
false
false
package com.parc.ccn.data; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.net.URLEncoder; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CoderResult; import java.nio.charset.CodingErrorAction; import java.nio.charset.UnsupportedCharsetException; import java.util.ArrayList; import java.util.Arrays; import javax.xml.stream.XMLStreamException; import com.parc.ccn.Library; import com.parc.ccn.data.util.DataUtils; import com.parc.ccn.data.util.GenericXMLEncodable; import com.parc.ccn.data.util.XMLDecoder; import com.parc.ccn.data.util.XMLEncodable; import com.parc.ccn.data.util.XMLEncoder; public class ContentName extends GenericXMLEncodable implements XMLEncodable, Comparable<ContentName> { public static final String SCHEME = "ccn:"; public static final String SEPARATOR = "/"; public static final ContentName ROOT = new ContentName(0, (ArrayList<byte []>)null); public static final String CONTENT_NAME_ELEMENT = "Name"; private static final String COMPONENT_ELEMENT = "Component"; protected ArrayList<byte []> _components; protected Integer _prefixCount; protected static class DotDotComponent extends Exception { // Need to strip off a component private static final long serialVersionUID = 4667513234636853164L; }; // Constructors // ContentNames consist of a sequence of byte[] components which may not // be assumed to follow any string encoding, or any other particular encoding. // The constructors therefore provide for creation only from byte[]s. // To create a ContentName from Strings, a client must call one of the static // methods that implements a conversion. public ContentName() { this(0, (ArrayList<byte[]>)null); } public ContentName(byte components[][]) { if (null == components) { _components = null; } else { _components = new ArrayList<byte []>(components.length); for (int i=0; i < components.length; ++i) { _components.add(components[i].clone()); } } } public ContentName(ContentName parent, byte [] name) { this(parent.count() + ((null != name) ? 1 : 0), parent.components(), parent.prefixCount()); if (null != name) { byte [] c = new byte[name.length]; System.arraycopy(name,0,c,0,name.length); _components.add(c); } } public ContentName(ContentName parent, byte [] name, int prefixCount) { this(parent, name); _prefixCount = prefixCount; } public ContentName(ContentName name, int prefixCount) { this(name, null); _prefixCount = prefixCount; } public ContentName(ContentName parent, byte[] name1, byte[] name2) { this (parent.count() + ((null != name1) ? 1 : 0) + ((null != name2) ? 1 : 0), parent.components(), parent.prefixCount()); if (null != name1) { byte [] c = new byte[name1.length]; System.arraycopy(name1,0,c,0,name1.length); _components.add(c); } if (null != name2) { byte [] c = new byte[name2.length]; System.arraycopy(name2,0,c,0,name2.length); _components.add(c); } } /** * Basic constructor for extending or contracting names. * @param count * @param components */ public ContentName(int count, byte components[][]) { if (0 >= count) { _components = new ArrayList<byte []>(0); } else { int max = (null == components) ? 0 : ((count > components.length) ? components.length : count); _components = new ArrayList<byte []>(max); for (int i=0; i < max; ++i) { byte [] c = new byte[components[i].length]; System.arraycopy(components[i],0,c,0,components[i].length); _components.add(c); } } } /** * Basic constructor for extending or contracting names. * Shallow copy, as we don't tend to alter name components * once created. * @param count * @param components */ public ContentName(int count, ArrayList<byte []>components) { if (0 >= count) { _components = new ArrayList<byte[]>(0); } else { int max = (null == components) ? 0 : ((count > components.size()) ? components.size() : count); _components = new ArrayList<byte []>(max); for (int i=0; i < max; ++i) { _components.add(components.get(i)); } } } public ContentName(int count, ArrayList<byte []>components, Integer prefixCount) { this(count, components); _prefixCount = prefixCount; } /** * Return the <code>ContentName</code> represented by the given URI. * A CCN <code>ContentName</code> consists of a sequence of binary components * of any length (including 0), which allows such things as encrypted * name components. It is often convenient to work with string * representations of names in various forms. * <p> * The canonical String representation of a CCN <code>ContentName</code> is a * URI encoding of the name according to RFC 3986 with the addition * of special treatment for name components of 0 length or containing * only one or more of the byte value 0x2E, which is the US-ASCII * encoding of '.'. The major features of the URI encoding are the * use of a limited set of characters and the use of percent-encoding * to encode all other byte values. The combination of percent-encoding * and special treatment for certain name components allows the * canonical CCN string representation to encode all possible CCN names. * <p> * The characters in the URI are limited to the <i>unreserved</i> characters * "a" through "z", "A" through "Z", "0" through "9", and "-", "_", ".", and "~" * plus the <i>reserved</i> delimiters "/" (interpreted as component separator) * and ":" (legal only in the optional scheme specification "ccn:" at the start * of the URI). * <p> * The decoding from a URI String to a ContentName translates each unreserved * character to its US-ASCII byte encoding, except for the "." which is subject * to special handling described below. Any other byte value in a component * (including those corresponding to "/" and ":") must be percent-encoded in * the URI. * <p> * The resolution rules for relative references are always applied in this * decoding (regardless of whether the URI has a scheme specification or not): * <ul> * <li> "//" in the URI is interpreted as "/" * <li> "/./" and "/." in the URI are interpreted as "/" and "" * <li> "/../" and "/.." in the URI are interpreted as removing the preceding component * </ul> * <p> * Any component of 0 length, or containing only one or more of the byte * value 0x2E ("."), is represented in the URI by one "." per byte plus the * suffix "..." which provides unambiguous representation of all possible name * components in conjunction with the use of the resolution rules given above. * Thus the decoding from URI String to ContentName makes conversions such as: * <ul> * <li> "/.../" in the URI is converted to a 0-length name component * <li> "/..../" in the URI is converted to the name component {0x2E} * <li> "/...../" in the URI is converted to the name component {0x2E, 0x2E} * <li> "/....../" in the URI is conveted to the name component {0x2E, 0x2E, 0x2E} * </ul> * <p> * Note that this URI encoding is very similar to but not the same as the * application/x-www-form-urlencoded MIME format that is used by the Java * {@link java.net.URLDecoder}. * @param name * @return * @throws MalformedContentNameStringException */ public static ContentName fromURI(String name) throws MalformedContentNameStringException { ContentName result = new ContentName(); if((name == null) || (name.length() == 0)) { result._components = null; } else { String[] parts; String justname = name; if (!name.startsWith(SEPARATOR)){ if (!name.startsWith(SCHEME + SEPARATOR)) { throw new MalformedContentNameStringException("ContentName strings must begin with " + SEPARATOR + " or " + SCHEME + SEPARATOR); } justname = name.substring(SCHEME.length()); } parts = justname.split(SEPARATOR); if (parts.length == 0) { // We've been asked to parse the root name. result._components = new ArrayList<byte []>(0); } else { result._components = new ArrayList<byte []>(parts.length - 1); } // Leave off initial empty component for (int i=1; i < parts.length; ++i) { try { byte[] component = componentParseURI(parts[i]); if (null != component) { result._components.add(component); } } catch (DotDotComponent c) { // Need to strip "parent" if (result._components.size() < 1) { throw new MalformedContentNameStringException("ContentName string contains too many .. components: " + name); } else { result._components.remove(result._components.size()-1); } } } } return result; } public static ContentName fromURI(String parts[]) throws MalformedContentNameStringException { ContentName result = new ContentName(); if ((parts == null) || (parts.length == 0)) { result._components = null; } else { result._components = new ArrayList<byte []>(parts.length); for (int i=0; i < parts.length; ++i) { try { byte[] component = componentParseURI(parts[i]); if (null != component) { result._components.add(component); } } catch (DotDotComponent c) { // Need to strip "parent" if (result._components.size() < 1) { throw new MalformedContentNameStringException("ContentName parts contains too many .. components"); } else { result._components.remove(result._components.size()-1); } } } } return result; } /** * Return the <code>ContentName</code> created by appending one component * to the supplied parent. The new component is converted from URI * string encoding. * @param parent * @param name * @return * @throws MalformedContentNameStringException */ public static ContentName fromURI(ContentName parent, String name) throws MalformedContentNameStringException { ContentName result = new ContentName(parent.count(), parent.components()); if (null != name) { try { byte[] decodedName = componentParseURI(name); if (null != decodedName) { result._components.add(decodedName); } } catch (DotDotComponent c) { // Need to strip "parent" if (result._components.size() < 1) { throw new MalformedContentNameStringException("ContentName parts contains too many .. components"); } else { result._components.remove(result._components.size()-1); } } } return result; } /** * Return the <code>ContentName</code> created from a native Java String. * In native strings only "/" is special, interpreted as component delimiter, * while all other characters will be encoded as UTF-8 in the output <code>ContentName</code> * Native String representations do not incorporate a URI scheme, and so must * begin with the component delimiter "/". * TODO use Java string escaping rules? * @param parent * @param name * @return * @throws MalformedContentNameStringException if name does not start with "/" */ public static ContentName fromNative(String name) throws MalformedContentNameStringException { ContentName result = new ContentName(); if (!name.startsWith(SEPARATOR)){ throw new MalformedContentNameStringException("ContentName native strings must begin with " + SEPARATOR); } if((name == null) || (name.length() == 0)) { result._components = null; } else { String[] parts; parts = name.split(SEPARATOR); if (parts.length == 0) { // We've been asked to parse the root name. result._components = new ArrayList<byte []>(0); } else { result._components = new ArrayList<byte []>(parts.length - 1); } // Leave off initial empty component for (int i=1; i < parts.length; ++i) { byte[] component = componentParseNative(parts[i]); if (null != component) { result._components.add(component); } } } return result; } /** * As in fromNative(String name) except also sets a prefix length */ public static ContentName fromNative(String name, int prefixCount) throws MalformedContentNameStringException { ContentName result = fromNative(name); result._prefixCount = prefixCount; return result; } /** * Return the <code>ContentName</code> created by appending one component * to the supplied parent. The new component is specified by a native * Java String which will be encoded as UTF-8 in the output <code>ContentName</code> * This method intentionally throws no declared exceptions * so you can be confident in encoding any native Java String * @param parent * @param name * @return */ public static ContentName fromNative(ContentName parent, String name) { ContentName result = new ContentName(parent.count(), parent.components()); if (null != name) { byte[] decodedName = componentParseNative(name); if (null != decodedName) { result._components.add(decodedName); } } return result; } public static ContentName fromNative(ContentName parent, String name1, String name2) { ContentName result = new ContentName(parent.count(), parent.components()); if (null != name1) { byte[] decodedName = componentParseNative(name1); if (null != decodedName) { result._components.add(decodedName); } } if (null != name2) { byte[] decodedName = componentParseNative(name2); if (null != decodedName) { result._components.add(decodedName); } } return result; } public static ContentName fromNative(String parts[]) { ContentName result = new ContentName(); if ((parts == null) || (parts.length == 0)) { result._components = null; } else { result._components = new ArrayList<byte []>(parts.length); for (int i=0; i < parts.length; ++i) { byte[] component = componentParseNative(parts[i]); if (null != component) { result._components.add(component); } } } return result; } public ContentName clone() { return new ContentName(count(), components()); } public ContentName parent() { return new ContentName(count()-1, components()); } public Integer prefixCount() { return _prefixCount; } public String toString() { if (null == _components) return null; // toString of root name is "/" if (0 == _components.size()) return SEPARATOR; StringBuffer nameBuf = new StringBuffer(); for (int i=0; i < _components.size(); ++i) { nameBuf.append(SEPARATOR); nameBuf.append(componentPrintURI(_components.get(i))); } return nameBuf.toString(); } /** * TODO This needs to convert to printing RFC 3986 URI format * Print bytes in the syntax of the application/x-www-form-urlencoded * MIME format, including byte sequences that are not legal character * encodings in any character set and byte sequences that have special * meaning for URI resolution per RFC 3986. * * All sub-sequences of the input * bytes that are legal UTF-8 will be translated into the * application/x-www-form-urlencoded format using the UTF-8 encoding * scheme, just as java.net.URLEncoder would do if invoked with the * encoding name "UTF-8". Those sub-sequences of input bytes that * are not legal UTF-8 will be translated into application/x-www-form-urlencoded * byte representations. Each byte is represented by the 3-character string * "%xy", where xy is the two-digit hexadecimal representation of the byte. * The net result is that UTF-8 is preserved but that any arbitrary * byte sequence is translated to a string representation that * can be parsed by parseComponent() to recover exactly the input sequence. * * Empty path components and path components "." and ".." have special * meaning for relative URI resolution per RFC 3986. To guarantee * these component variations are preserved and recovered exactly when * the URI is parsed by parseComponent() we use a convention that * components that are empty or consist entirely of '.' characters will * have "..." appended. This is intended to be consistent with the CCN C * library handling of URI representation of names. * @param bs input byte array * @return */ public static String componentPrintURI(byte[] bs, int offset, int length) { // NHB: Van is expecting the URI encoding rules if (null == bs || bs.length == 0) { // Empty component represented by three '.' return "..."; } try { // Note that this would probably be more efficient as simple loop: // In order to use the URLEncoder class to handle the // parts that are UTF-8 already, we decode the bytes into Java String // as though they were UTF-8. Wherever that fails // (i.e. where byte sub-sequences are NOT legal UTF-8) // we directly convert those bytes to the %xy output format. // To get enough control over the decoding, we must use // the charset decoder and NOT simply new String(bs) because // the String constructor will decode illegal UTF-8 sub-sequences // with Unicode "Replacement Character" U+FFFD. StringBuffer result = new StringBuffer(); Charset charset = Charset.forName("UTF-8"); CharsetDecoder decoder = charset.newDecoder(); // Leave nothing to defaults: we want to be notified on anything illegal decoder.onMalformedInput(CodingErrorAction.REPORT); decoder.onUnmappableCharacter(CodingErrorAction.REPORT); ByteBuffer input = ByteBuffer.wrap(bs, offset, length); CharBuffer output = CharBuffer.allocate(((int)decoder.maxCharsPerByte()*length)+1); while (input.remaining() > 0) { CoderResult cr = decoder.decode(input, output, true); assert(!cr.isOverflow()); // URLEncode whatever was successfully decoded from UTF-8 output.flip(); result.append(URLEncoder.encode(output.toString(), "UTF-8")); output.clear(); if (cr.isError()) { for (int i=0; i<cr.length(); i++) { result.append(String.format("%%%02X", input.get())); } } } int i = 0; for (i = 0; i < result.length() && result.charAt(i) == '.'; i++) { continue; } if (i == result.length()) { // all dots result.append("..."); } return result.toString(); } catch (UnsupportedCharsetException e) { throw new RuntimeException("UTF-8 not supported charset", e); } catch (UnsupportedEncodingException e) { throw new RuntimeException("UTF-8 not supported", e); } } public static String componentPrintURI(byte [] bs) { return componentPrintURI(bs, 0, bs.length); } public static String componentPrintNative(byte[] bs) { // Native string print is the one place where we can just use // Java native platform decoding. Note that this is not // necessarily invertible, since there may be byte sequences // that do not correspond to any legal native character encoding // that may be converted to e.g. Unicode "Replacement Character" U+FFFD. return new String(bs); } // UrlEncoded in case we want variant compatible with java.net.URLEncoder // again in future // protected static String componentPrintUrlEncoded(byte[] bs) { // // NHB: Van is expecting the URI encoding rules // if (null == bs || bs.length == 0) { // // Empty component represented by three '.' // return "..."; // } // try { // // Note that this would probably be more efficient as simple loop: // // In order to use the URLEncoder class to handle the // // parts that are UTF-8 already, we decode the bytes into Java String // // as though they were UTF-8. Wherever that fails // // (i.e. where byte sub-sequences are NOT legal UTF-8) // // we directly convert those bytes to the %xy output format. // // To get enough control over the decoding, we must use // // the charset decoder and NOT simply new String(bs) because // // the String constructor will decode illegal UTF-8 sub-sequences // // with Unicode "Replacement Character" U+FFFD. // StringBuffer result = new StringBuffer(); // Charset charset = Charset.forName("UTF-8"); // CharsetDecoder decoder = charset.newDecoder(); // // Leave nothing to defaults: we want to be notified on anything illegal // decoder.onMalformedInput(CodingErrorAction.REPORT); // decoder.onUnmappableCharacter(CodingErrorAction.REPORT); // ByteBuffer input = ByteBuffer.wrap(bs); // CharBuffer output = CharBuffer.allocate(((int)decoder.maxCharsPerByte()*bs.length)+1); // while (input.remaining() > 0) { // CoderResult cr = decoder.decode(input, output, true); // assert(!cr.isOverflow()); // // URLEncode whatever was successfully decoded from UTF-8 // output.flip(); // result.append(URLEncoder.encode(output.toString(), "UTF-8")); // output.clear(); // if (cr.isError()) { // for (int i=0; i<cr.length(); i++) { // result.append(String.format("%%%02X", input.get())); // } // } // } // int i = 0; // for (i = 0; i < result.length() && result.charAt(i) == '.'; i++) { // continue; // } // if (i == result.length()) { // // all dots // result.append("..."); // } // return result.toString(); // } catch (UnsupportedCharsetException e) { // throw new RuntimeException("UTF-8 not supported charset", e); // } catch (UnsupportedEncodingException e) { // throw new RuntimeException("UTF-8 not supported", e); // } // } public static String hexPrint(byte [] bs) { if (null == bs) return new String(); BigInteger bi = new BigInteger(1,bs); return bi.toString(16); } /* * TODO This needs to convert to parsing RFC 3986 URI format * Parse component in the syntax of the application/x-www-form-urlencoded * MIME format, including representations of bytes that are not legal character * encodings in any character set. This method is the inverse of * printComponent() and for any input sequence of bytes it must be the case * that parseComponent(printComponent(input)) == input. * * Note in particular that this method interprets sequences of more than * two dots ('.') as representing an empty component or dot component value * as encoded by componentPrint. That is, the component value will be * the value obtained by removing three dots. * @param name a single component of a name * @return */ public static byte[] componentParseURI(String name) throws DotDotComponent { byte[] decodedName = null; boolean alldots = true; // does this component contain only dots after unescaping? try { ByteBuffer result = ByteBuffer.allocate(name.length()); for (int i = 0; i < name.length(); i++) { if (name.charAt(i) == '%') { // This is a byte string %xy where xy are hex digits // Since the input string must be compatible with the output // of componentPrint(), we may convert the byte values directly. // There is no need to go through a character representation. if (name.length()-1 < i+2) { throw new IllegalArgumentException("malformed %xy byte representation: too short"); } if (name.charAt(i+1) == '-') { throw new IllegalArgumentException("malformed %xy byte representation: negative value not permitted"); } try { result.put(new Integer(Integer.parseInt(name.substring(i+1, i+3),16)).byteValue()); } catch (NumberFormatException e) { throw new IllegalArgumentException("malformed %xy byte representation: not legal hex number",e); } i+=2; // for loop will increment by one more to get net +3 so past byte string } else if (name.charAt(i) == '+') { // This is the one character translated to a different one result.put(" ".getBytes("UTF-8")); } else { // This character remains the same result.put(name.substring(i, i+1).getBytes("UTF-8")); } if (result.get(result.position()-1) != '.') { alldots = false; } } result.flip(); if (alldots) { if (result.limit() <= 1) { return null; } else if (result.limit() == 2) { throw new DotDotComponent(); } else { // Remove the three '.' extra result.limit(result.limit()-3); } } decodedName = new byte[result.limit()]; System.arraycopy(result.array(), 0, decodedName, 0, result.limit()); } catch (UnsupportedEncodingException e) { Library.logger().severe("UTF-8 not supported."); throw new RuntimeException("UTF-8 not supported", e); } return decodedName; } /** * Parse native string component: just UTF-8 encode * For full names in native strings only "/" is special * but for an individual component we will even allow that. * This method intentionally throws no declared exceptions * so you can be confident in encoding any native Java String * TODO make this use Java string escaping rules? * @param name * @return */ public static byte[] componentParseNative(String name) { try { return name.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { Library.logger().severe("UTF-8 not supported."); throw new RuntimeException("UTF-8 not supported", e); } } // UrlEncoded in case we want to enable it again // protected static byte[] componentParseUrlEncoded(String name) throws DotDotComponent { // byte[] decodedName = null; // boolean alldots = true; // does this component contain only dots after unescaping? // try { // ByteBuffer result = ByteBuffer.allocate(name.length()); // for (int i = 0; i < name.length(); i++) { // if (name.charAt(i) == '%') { // // This is a byte string %xy where xy are hex digits // // Since the input string must be compatible with the output // // of componentPrint(), we may convert the byte values directly. // // There is no need to go through a character representation. // if (name.length()-1 < i+2) { // throw new IllegalArgumentException("malformed %xy byte representation: too short"); // } // if (name.charAt(i+1) == '-') { // throw new IllegalArgumentException("malformed %xy byte representation: negative value not permitted"); // } // try { // result.put(new Integer(Integer.parseInt(name.substring(i+1, i+3),16)).byteValue()); // } catch (NumberFormatException e) { // throw new IllegalArgumentException("malformed %xy byte representation: not legal hex number",e); // } // i+=2; // for loop will increment by one more to get net +3 so past byte string // } else if (name.charAt(i) == '+') { // // This is the one character translated to a different one // result.put(" ".getBytes("UTF-8")); // } else { // // This character remains the same // result.put(name.substring(i, i+1).getBytes("UTF-8")); // } // if (result.get(result.position()-1) != '.') { // alldots = false; // } // } // result.flip(); // if (alldots) { // if (result.limit() <= 1) { // return null; // } else if (result.limit() == 2) { // throw new DotDotComponent(); // } else { // // Remove the three '.' extra // result.limit(result.limit()-3); // } // } // decodedName = new byte[result.limit()]; // System.arraycopy(result.array(), 0, decodedName, 0, result.limit()); // } catch (UnsupportedEncodingException e) { // Library.logger().severe("UTF-8 not supported."); // throw new RuntimeException("UTF-8 not supported", e); // } // return decodedName; // } public ArrayList<byte[]> components() { return _components; } public int count() { if (null == _components) return 0; return _components.size(); } /** * Get the i'th component, indexed from 0. * @param i * @return */ public final byte[] component(int i) { if ((null == _components) || (i >= _components.size())) return null; return _components.get(i); } public final byte [] lastComponent() { if (null == _components || _components.size() == 0) return null; return _components.get(_components.size()-1); } public String stringComponent(int i) { if ((null == _components) || (i >= _components.size())) return null; return componentPrintURI(_components.get(i)); } public void decode(XMLDecoder decoder) throws XMLStreamException { decoder.readStartElement(CONTENT_NAME_ELEMENT); _components = new ArrayList<byte []>(); while (decoder.peekStartElement(COMPONENT_ELEMENT)) { _components.add(decoder.readBinaryElement(COMPONENT_ELEMENT)); } decoder.readEndElement(); } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final ContentName other = (ContentName)obj; if (other.count() != this.count()) return false; for (int i=0; i < count(); ++i) { if (!Arrays.equals(other.component(i), this.component(i))) return false; } if (prefixCount() != other.prefixCount()) return false; return true; } /** * Check prefix match up to the first componentCount * components. * @param obj * @param componentCount if larger than the number of * components, take this as the whole thing. * @return */ private boolean equals(ContentName obj, int componentCount) { if (this == obj) return true; if (obj == null) return false; if ((componentCount > this.count()) && (obj.count() != this.count())) return false; for (int i=0; i < componentCount; ++i) { if (!Arrays.equals(obj.component(i), this.component(i))) return false; } return true; } /** * Parses the canonical URI representation. * @param str * @return * @throws MalformedContentNameStringException */ public static ContentName parse(String str) throws MalformedContentNameStringException { if(str == null) return null; if(str.length() == 0) return ROOT; return fromURI(str); } /** * Uses the canonical URI representation * @param str * @return */ public boolean contains(String str) { try { byte[] parsed = componentParseURI(str); if (null == parsed) { return false; } else { return contains(parsed); } } catch (DotDotComponent c) { return false; } } public boolean contains(byte [] component) { return (containsWhere(component) > 0); } /** * Uses the canonical URI representation * @param str * @return */ public int containsWhere(String str) { try { byte[] parsed = componentParseURI(str); if (null == parsed) { return -1; } else { return containsWhere(parsed); } } catch (DotDotComponent c) { return -1; } } int containsWhere(byte [] component) { int i=0; boolean result = false; for (i=0; i < _components.size(); ++i) { if (Arrays.equals(_components.get(i),component)) { result = true; break; } } if (result) return i; return -1; } /** * Slice the name off right before the given component * @param name * @param component * @return */ public ContentName cut(byte [] component) { int offset = this.containsWhere(component); if (offset < 0) { // unfragmented return this; } // else need to cut it return new ContentName(offset, this.components()); } public ContentName cut(String component) { try { byte[] parsed = componentParseURI(component); if (null == parsed) { return this; } else { return cut(parsed); } } catch (DotDotComponent c) { return this; } } public boolean isPrefixOf(ContentName other) { if (null == other) return false; int count = _prefixCount == null ? count() : prefixCount(); if (count > other.count()) return false; return this.equals(other, count); } /** * Compare our name to the name of the ContentObject. * If our name is 1 component longer than the ContentObject * and no prefix count is set, our name might contain a digest. * In that case, try matching the content to the last component as * a digest. * * @param other * @return */ public boolean isPrefixOf(ContentObject other) { boolean match = isPrefixOf(other.name()); if (match || prefixCount() != null) return match; if (count() == other.name().count() + 1) { if (DataUtils.compare(component(count() - 1), other.contentDigest()) == 0) { return true; } } return false; } public void encode(XMLEncoder encoder) throws XMLStreamException { if (!validate()) { throw new XMLStreamException("Cannot encode " + this.getClass().getName() + ": field values missing."); } encoder.writeStartElement(CONTENT_NAME_ELEMENT); for (int i=0; i < count(); ++i) { encoder.writeElement(COMPONENT_ELEMENT, _components.get(i)); } encoder.writeEndElement(); } public boolean validate() { return (null != _components); } public ContentName copy(int nameComponentCount) { return new ContentName(nameComponentCount, this.components()); } public int compareTo(ContentName o) { if (this == o) return 0; int len = (this.count() > o.count()) ? this.count() : o.count(); int componentResult = 0; for (int i=0; i < len; ++i) { componentResult = DataUtils.compare(this.component(i), o.component(i)); if (0 != componentResult) return componentResult; } if (this.count() < o.count()) return -1; else if (this.count() > o.count()) return 1; if (this.prefixCount() == null && o.prefixCount() != null) return -1; if (this.prefixCount() != null && o.prefixCount() == null) return 1; if (this.prefixCount() != null) { if (this.prefixCount() < o.prefixCount()) return -1; if (this.prefixCount() > o.prefixCount()) return 1; } return 0; } }
UTF-8
Java
35,439
java
2_4015e48cca211628f660c292c3a46a58caf2f8fc_ContentName_t.java
Java
[]
null
[]
package com.parc.ccn.data; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.net.URLEncoder; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CoderResult; import java.nio.charset.CodingErrorAction; import java.nio.charset.UnsupportedCharsetException; import java.util.ArrayList; import java.util.Arrays; import javax.xml.stream.XMLStreamException; import com.parc.ccn.Library; import com.parc.ccn.data.util.DataUtils; import com.parc.ccn.data.util.GenericXMLEncodable; import com.parc.ccn.data.util.XMLDecoder; import com.parc.ccn.data.util.XMLEncodable; import com.parc.ccn.data.util.XMLEncoder; public class ContentName extends GenericXMLEncodable implements XMLEncodable, Comparable<ContentName> { public static final String SCHEME = "ccn:"; public static final String SEPARATOR = "/"; public static final ContentName ROOT = new ContentName(0, (ArrayList<byte []>)null); public static final String CONTENT_NAME_ELEMENT = "Name"; private static final String COMPONENT_ELEMENT = "Component"; protected ArrayList<byte []> _components; protected Integer _prefixCount; protected static class DotDotComponent extends Exception { // Need to strip off a component private static final long serialVersionUID = 4667513234636853164L; }; // Constructors // ContentNames consist of a sequence of byte[] components which may not // be assumed to follow any string encoding, or any other particular encoding. // The constructors therefore provide for creation only from byte[]s. // To create a ContentName from Strings, a client must call one of the static // methods that implements a conversion. public ContentName() { this(0, (ArrayList<byte[]>)null); } public ContentName(byte components[][]) { if (null == components) { _components = null; } else { _components = new ArrayList<byte []>(components.length); for (int i=0; i < components.length; ++i) { _components.add(components[i].clone()); } } } public ContentName(ContentName parent, byte [] name) { this(parent.count() + ((null != name) ? 1 : 0), parent.components(), parent.prefixCount()); if (null != name) { byte [] c = new byte[name.length]; System.arraycopy(name,0,c,0,name.length); _components.add(c); } } public ContentName(ContentName parent, byte [] name, int prefixCount) { this(parent, name); _prefixCount = prefixCount; } public ContentName(ContentName name, int prefixCount) { this(name, null); _prefixCount = prefixCount; } public ContentName(ContentName parent, byte[] name1, byte[] name2) { this (parent.count() + ((null != name1) ? 1 : 0) + ((null != name2) ? 1 : 0), parent.components(), parent.prefixCount()); if (null != name1) { byte [] c = new byte[name1.length]; System.arraycopy(name1,0,c,0,name1.length); _components.add(c); } if (null != name2) { byte [] c = new byte[name2.length]; System.arraycopy(name2,0,c,0,name2.length); _components.add(c); } } /** * Basic constructor for extending or contracting names. * @param count * @param components */ public ContentName(int count, byte components[][]) { if (0 >= count) { _components = new ArrayList<byte []>(0); } else { int max = (null == components) ? 0 : ((count > components.length) ? components.length : count); _components = new ArrayList<byte []>(max); for (int i=0; i < max; ++i) { byte [] c = new byte[components[i].length]; System.arraycopy(components[i],0,c,0,components[i].length); _components.add(c); } } } /** * Basic constructor for extending or contracting names. * Shallow copy, as we don't tend to alter name components * once created. * @param count * @param components */ public ContentName(int count, ArrayList<byte []>components) { if (0 >= count) { _components = new ArrayList<byte[]>(0); } else { int max = (null == components) ? 0 : ((count > components.size()) ? components.size() : count); _components = new ArrayList<byte []>(max); for (int i=0; i < max; ++i) { _components.add(components.get(i)); } } } public ContentName(int count, ArrayList<byte []>components, Integer prefixCount) { this(count, components); _prefixCount = prefixCount; } /** * Return the <code>ContentName</code> represented by the given URI. * A CCN <code>ContentName</code> consists of a sequence of binary components * of any length (including 0), which allows such things as encrypted * name components. It is often convenient to work with string * representations of names in various forms. * <p> * The canonical String representation of a CCN <code>ContentName</code> is a * URI encoding of the name according to RFC 3986 with the addition * of special treatment for name components of 0 length or containing * only one or more of the byte value 0x2E, which is the US-ASCII * encoding of '.'. The major features of the URI encoding are the * use of a limited set of characters and the use of percent-encoding * to encode all other byte values. The combination of percent-encoding * and special treatment for certain name components allows the * canonical CCN string representation to encode all possible CCN names. * <p> * The characters in the URI are limited to the <i>unreserved</i> characters * "a" through "z", "A" through "Z", "0" through "9", and "-", "_", ".", and "~" * plus the <i>reserved</i> delimiters "/" (interpreted as component separator) * and ":" (legal only in the optional scheme specification "ccn:" at the start * of the URI). * <p> * The decoding from a URI String to a ContentName translates each unreserved * character to its US-ASCII byte encoding, except for the "." which is subject * to special handling described below. Any other byte value in a component * (including those corresponding to "/" and ":") must be percent-encoded in * the URI. * <p> * The resolution rules for relative references are always applied in this * decoding (regardless of whether the URI has a scheme specification or not): * <ul> * <li> "//" in the URI is interpreted as "/" * <li> "/./" and "/." in the URI are interpreted as "/" and "" * <li> "/../" and "/.." in the URI are interpreted as removing the preceding component * </ul> * <p> * Any component of 0 length, or containing only one or more of the byte * value 0x2E ("."), is represented in the URI by one "." per byte plus the * suffix "..." which provides unambiguous representation of all possible name * components in conjunction with the use of the resolution rules given above. * Thus the decoding from URI String to ContentName makes conversions such as: * <ul> * <li> "/.../" in the URI is converted to a 0-length name component * <li> "/..../" in the URI is converted to the name component {0x2E} * <li> "/...../" in the URI is converted to the name component {0x2E, 0x2E} * <li> "/....../" in the URI is conveted to the name component {0x2E, 0x2E, 0x2E} * </ul> * <p> * Note that this URI encoding is very similar to but not the same as the * application/x-www-form-urlencoded MIME format that is used by the Java * {@link java.net.URLDecoder}. * @param name * @return * @throws MalformedContentNameStringException */ public static ContentName fromURI(String name) throws MalformedContentNameStringException { ContentName result = new ContentName(); if((name == null) || (name.length() == 0)) { result._components = null; } else { String[] parts; String justname = name; if (!name.startsWith(SEPARATOR)){ if (!name.startsWith(SCHEME + SEPARATOR)) { throw new MalformedContentNameStringException("ContentName strings must begin with " + SEPARATOR + " or " + SCHEME + SEPARATOR); } justname = name.substring(SCHEME.length()); } parts = justname.split(SEPARATOR); if (parts.length == 0) { // We've been asked to parse the root name. result._components = new ArrayList<byte []>(0); } else { result._components = new ArrayList<byte []>(parts.length - 1); } // Leave off initial empty component for (int i=1; i < parts.length; ++i) { try { byte[] component = componentParseURI(parts[i]); if (null != component) { result._components.add(component); } } catch (DotDotComponent c) { // Need to strip "parent" if (result._components.size() < 1) { throw new MalformedContentNameStringException("ContentName string contains too many .. components: " + name); } else { result._components.remove(result._components.size()-1); } } } } return result; } public static ContentName fromURI(String parts[]) throws MalformedContentNameStringException { ContentName result = new ContentName(); if ((parts == null) || (parts.length == 0)) { result._components = null; } else { result._components = new ArrayList<byte []>(parts.length); for (int i=0; i < parts.length; ++i) { try { byte[] component = componentParseURI(parts[i]); if (null != component) { result._components.add(component); } } catch (DotDotComponent c) { // Need to strip "parent" if (result._components.size() < 1) { throw new MalformedContentNameStringException("ContentName parts contains too many .. components"); } else { result._components.remove(result._components.size()-1); } } } } return result; } /** * Return the <code>ContentName</code> created by appending one component * to the supplied parent. The new component is converted from URI * string encoding. * @param parent * @param name * @return * @throws MalformedContentNameStringException */ public static ContentName fromURI(ContentName parent, String name) throws MalformedContentNameStringException { ContentName result = new ContentName(parent.count(), parent.components()); if (null != name) { try { byte[] decodedName = componentParseURI(name); if (null != decodedName) { result._components.add(decodedName); } } catch (DotDotComponent c) { // Need to strip "parent" if (result._components.size() < 1) { throw new MalformedContentNameStringException("ContentName parts contains too many .. components"); } else { result._components.remove(result._components.size()-1); } } } return result; } /** * Return the <code>ContentName</code> created from a native Java String. * In native strings only "/" is special, interpreted as component delimiter, * while all other characters will be encoded as UTF-8 in the output <code>ContentName</code> * Native String representations do not incorporate a URI scheme, and so must * begin with the component delimiter "/". * TODO use Java string escaping rules? * @param parent * @param name * @return * @throws MalformedContentNameStringException if name does not start with "/" */ public static ContentName fromNative(String name) throws MalformedContentNameStringException { ContentName result = new ContentName(); if (!name.startsWith(SEPARATOR)){ throw new MalformedContentNameStringException("ContentName native strings must begin with " + SEPARATOR); } if((name == null) || (name.length() == 0)) { result._components = null; } else { String[] parts; parts = name.split(SEPARATOR); if (parts.length == 0) { // We've been asked to parse the root name. result._components = new ArrayList<byte []>(0); } else { result._components = new ArrayList<byte []>(parts.length - 1); } // Leave off initial empty component for (int i=1; i < parts.length; ++i) { byte[] component = componentParseNative(parts[i]); if (null != component) { result._components.add(component); } } } return result; } /** * As in fromNative(String name) except also sets a prefix length */ public static ContentName fromNative(String name, int prefixCount) throws MalformedContentNameStringException { ContentName result = fromNative(name); result._prefixCount = prefixCount; return result; } /** * Return the <code>ContentName</code> created by appending one component * to the supplied parent. The new component is specified by a native * Java String which will be encoded as UTF-8 in the output <code>ContentName</code> * This method intentionally throws no declared exceptions * so you can be confident in encoding any native Java String * @param parent * @param name * @return */ public static ContentName fromNative(ContentName parent, String name) { ContentName result = new ContentName(parent.count(), parent.components()); if (null != name) { byte[] decodedName = componentParseNative(name); if (null != decodedName) { result._components.add(decodedName); } } return result; } public static ContentName fromNative(ContentName parent, String name1, String name2) { ContentName result = new ContentName(parent.count(), parent.components()); if (null != name1) { byte[] decodedName = componentParseNative(name1); if (null != decodedName) { result._components.add(decodedName); } } if (null != name2) { byte[] decodedName = componentParseNative(name2); if (null != decodedName) { result._components.add(decodedName); } } return result; } public static ContentName fromNative(String parts[]) { ContentName result = new ContentName(); if ((parts == null) || (parts.length == 0)) { result._components = null; } else { result._components = new ArrayList<byte []>(parts.length); for (int i=0; i < parts.length; ++i) { byte[] component = componentParseNative(parts[i]); if (null != component) { result._components.add(component); } } } return result; } public ContentName clone() { return new ContentName(count(), components()); } public ContentName parent() { return new ContentName(count()-1, components()); } public Integer prefixCount() { return _prefixCount; } public String toString() { if (null == _components) return null; // toString of root name is "/" if (0 == _components.size()) return SEPARATOR; StringBuffer nameBuf = new StringBuffer(); for (int i=0; i < _components.size(); ++i) { nameBuf.append(SEPARATOR); nameBuf.append(componentPrintURI(_components.get(i))); } return nameBuf.toString(); } /** * TODO This needs to convert to printing RFC 3986 URI format * Print bytes in the syntax of the application/x-www-form-urlencoded * MIME format, including byte sequences that are not legal character * encodings in any character set and byte sequences that have special * meaning for URI resolution per RFC 3986. * * All sub-sequences of the input * bytes that are legal UTF-8 will be translated into the * application/x-www-form-urlencoded format using the UTF-8 encoding * scheme, just as java.net.URLEncoder would do if invoked with the * encoding name "UTF-8". Those sub-sequences of input bytes that * are not legal UTF-8 will be translated into application/x-www-form-urlencoded * byte representations. Each byte is represented by the 3-character string * "%xy", where xy is the two-digit hexadecimal representation of the byte. * The net result is that UTF-8 is preserved but that any arbitrary * byte sequence is translated to a string representation that * can be parsed by parseComponent() to recover exactly the input sequence. * * Empty path components and path components "." and ".." have special * meaning for relative URI resolution per RFC 3986. To guarantee * these component variations are preserved and recovered exactly when * the URI is parsed by parseComponent() we use a convention that * components that are empty or consist entirely of '.' characters will * have "..." appended. This is intended to be consistent with the CCN C * library handling of URI representation of names. * @param bs input byte array * @return */ public static String componentPrintURI(byte[] bs, int offset, int length) { // NHB: Van is expecting the URI encoding rules if (null == bs || bs.length == 0) { // Empty component represented by three '.' return "..."; } try { // Note that this would probably be more efficient as simple loop: // In order to use the URLEncoder class to handle the // parts that are UTF-8 already, we decode the bytes into Java String // as though they were UTF-8. Wherever that fails // (i.e. where byte sub-sequences are NOT legal UTF-8) // we directly convert those bytes to the %xy output format. // To get enough control over the decoding, we must use // the charset decoder and NOT simply new String(bs) because // the String constructor will decode illegal UTF-8 sub-sequences // with Unicode "Replacement Character" U+FFFD. StringBuffer result = new StringBuffer(); Charset charset = Charset.forName("UTF-8"); CharsetDecoder decoder = charset.newDecoder(); // Leave nothing to defaults: we want to be notified on anything illegal decoder.onMalformedInput(CodingErrorAction.REPORT); decoder.onUnmappableCharacter(CodingErrorAction.REPORT); ByteBuffer input = ByteBuffer.wrap(bs, offset, length); CharBuffer output = CharBuffer.allocate(((int)decoder.maxCharsPerByte()*length)+1); while (input.remaining() > 0) { CoderResult cr = decoder.decode(input, output, true); assert(!cr.isOverflow()); // URLEncode whatever was successfully decoded from UTF-8 output.flip(); result.append(URLEncoder.encode(output.toString(), "UTF-8")); output.clear(); if (cr.isError()) { for (int i=0; i<cr.length(); i++) { result.append(String.format("%%%02X", input.get())); } } } int i = 0; for (i = 0; i < result.length() && result.charAt(i) == '.'; i++) { continue; } if (i == result.length()) { // all dots result.append("..."); } return result.toString(); } catch (UnsupportedCharsetException e) { throw new RuntimeException("UTF-8 not supported charset", e); } catch (UnsupportedEncodingException e) { throw new RuntimeException("UTF-8 not supported", e); } } public static String componentPrintURI(byte [] bs) { return componentPrintURI(bs, 0, bs.length); } public static String componentPrintNative(byte[] bs) { // Native string print is the one place where we can just use // Java native platform decoding. Note that this is not // necessarily invertible, since there may be byte sequences // that do not correspond to any legal native character encoding // that may be converted to e.g. Unicode "Replacement Character" U+FFFD. return new String(bs); } // UrlEncoded in case we want variant compatible with java.net.URLEncoder // again in future // protected static String componentPrintUrlEncoded(byte[] bs) { // // NHB: Van is expecting the URI encoding rules // if (null == bs || bs.length == 0) { // // Empty component represented by three '.' // return "..."; // } // try { // // Note that this would probably be more efficient as simple loop: // // In order to use the URLEncoder class to handle the // // parts that are UTF-8 already, we decode the bytes into Java String // // as though they were UTF-8. Wherever that fails // // (i.e. where byte sub-sequences are NOT legal UTF-8) // // we directly convert those bytes to the %xy output format. // // To get enough control over the decoding, we must use // // the charset decoder and NOT simply new String(bs) because // // the String constructor will decode illegal UTF-8 sub-sequences // // with Unicode "Replacement Character" U+FFFD. // StringBuffer result = new StringBuffer(); // Charset charset = Charset.forName("UTF-8"); // CharsetDecoder decoder = charset.newDecoder(); // // Leave nothing to defaults: we want to be notified on anything illegal // decoder.onMalformedInput(CodingErrorAction.REPORT); // decoder.onUnmappableCharacter(CodingErrorAction.REPORT); // ByteBuffer input = ByteBuffer.wrap(bs); // CharBuffer output = CharBuffer.allocate(((int)decoder.maxCharsPerByte()*bs.length)+1); // while (input.remaining() > 0) { // CoderResult cr = decoder.decode(input, output, true); // assert(!cr.isOverflow()); // // URLEncode whatever was successfully decoded from UTF-8 // output.flip(); // result.append(URLEncoder.encode(output.toString(), "UTF-8")); // output.clear(); // if (cr.isError()) { // for (int i=0; i<cr.length(); i++) { // result.append(String.format("%%%02X", input.get())); // } // } // } // int i = 0; // for (i = 0; i < result.length() && result.charAt(i) == '.'; i++) { // continue; // } // if (i == result.length()) { // // all dots // result.append("..."); // } // return result.toString(); // } catch (UnsupportedCharsetException e) { // throw new RuntimeException("UTF-8 not supported charset", e); // } catch (UnsupportedEncodingException e) { // throw new RuntimeException("UTF-8 not supported", e); // } // } public static String hexPrint(byte [] bs) { if (null == bs) return new String(); BigInteger bi = new BigInteger(1,bs); return bi.toString(16); } /* * TODO This needs to convert to parsing RFC 3986 URI format * Parse component in the syntax of the application/x-www-form-urlencoded * MIME format, including representations of bytes that are not legal character * encodings in any character set. This method is the inverse of * printComponent() and for any input sequence of bytes it must be the case * that parseComponent(printComponent(input)) == input. * * Note in particular that this method interprets sequences of more than * two dots ('.') as representing an empty component or dot component value * as encoded by componentPrint. That is, the component value will be * the value obtained by removing three dots. * @param name a single component of a name * @return */ public static byte[] componentParseURI(String name) throws DotDotComponent { byte[] decodedName = null; boolean alldots = true; // does this component contain only dots after unescaping? try { ByteBuffer result = ByteBuffer.allocate(name.length()); for (int i = 0; i < name.length(); i++) { if (name.charAt(i) == '%') { // This is a byte string %xy where xy are hex digits // Since the input string must be compatible with the output // of componentPrint(), we may convert the byte values directly. // There is no need to go through a character representation. if (name.length()-1 < i+2) { throw new IllegalArgumentException("malformed %xy byte representation: too short"); } if (name.charAt(i+1) == '-') { throw new IllegalArgumentException("malformed %xy byte representation: negative value not permitted"); } try { result.put(new Integer(Integer.parseInt(name.substring(i+1, i+3),16)).byteValue()); } catch (NumberFormatException e) { throw new IllegalArgumentException("malformed %xy byte representation: not legal hex number",e); } i+=2; // for loop will increment by one more to get net +3 so past byte string } else if (name.charAt(i) == '+') { // This is the one character translated to a different one result.put(" ".getBytes("UTF-8")); } else { // This character remains the same result.put(name.substring(i, i+1).getBytes("UTF-8")); } if (result.get(result.position()-1) != '.') { alldots = false; } } result.flip(); if (alldots) { if (result.limit() <= 1) { return null; } else if (result.limit() == 2) { throw new DotDotComponent(); } else { // Remove the three '.' extra result.limit(result.limit()-3); } } decodedName = new byte[result.limit()]; System.arraycopy(result.array(), 0, decodedName, 0, result.limit()); } catch (UnsupportedEncodingException e) { Library.logger().severe("UTF-8 not supported."); throw new RuntimeException("UTF-8 not supported", e); } return decodedName; } /** * Parse native string component: just UTF-8 encode * For full names in native strings only "/" is special * but for an individual component we will even allow that. * This method intentionally throws no declared exceptions * so you can be confident in encoding any native Java String * TODO make this use Java string escaping rules? * @param name * @return */ public static byte[] componentParseNative(String name) { try { return name.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { Library.logger().severe("UTF-8 not supported."); throw new RuntimeException("UTF-8 not supported", e); } } // UrlEncoded in case we want to enable it again // protected static byte[] componentParseUrlEncoded(String name) throws DotDotComponent { // byte[] decodedName = null; // boolean alldots = true; // does this component contain only dots after unescaping? // try { // ByteBuffer result = ByteBuffer.allocate(name.length()); // for (int i = 0; i < name.length(); i++) { // if (name.charAt(i) == '%') { // // This is a byte string %xy where xy are hex digits // // Since the input string must be compatible with the output // // of componentPrint(), we may convert the byte values directly. // // There is no need to go through a character representation. // if (name.length()-1 < i+2) { // throw new IllegalArgumentException("malformed %xy byte representation: too short"); // } // if (name.charAt(i+1) == '-') { // throw new IllegalArgumentException("malformed %xy byte representation: negative value not permitted"); // } // try { // result.put(new Integer(Integer.parseInt(name.substring(i+1, i+3),16)).byteValue()); // } catch (NumberFormatException e) { // throw new IllegalArgumentException("malformed %xy byte representation: not legal hex number",e); // } // i+=2; // for loop will increment by one more to get net +3 so past byte string // } else if (name.charAt(i) == '+') { // // This is the one character translated to a different one // result.put(" ".getBytes("UTF-8")); // } else { // // This character remains the same // result.put(name.substring(i, i+1).getBytes("UTF-8")); // } // if (result.get(result.position()-1) != '.') { // alldots = false; // } // } // result.flip(); // if (alldots) { // if (result.limit() <= 1) { // return null; // } else if (result.limit() == 2) { // throw new DotDotComponent(); // } else { // // Remove the three '.' extra // result.limit(result.limit()-3); // } // } // decodedName = new byte[result.limit()]; // System.arraycopy(result.array(), 0, decodedName, 0, result.limit()); // } catch (UnsupportedEncodingException e) { // Library.logger().severe("UTF-8 not supported."); // throw new RuntimeException("UTF-8 not supported", e); // } // return decodedName; // } public ArrayList<byte[]> components() { return _components; } public int count() { if (null == _components) return 0; return _components.size(); } /** * Get the i'th component, indexed from 0. * @param i * @return */ public final byte[] component(int i) { if ((null == _components) || (i >= _components.size())) return null; return _components.get(i); } public final byte [] lastComponent() { if (null == _components || _components.size() == 0) return null; return _components.get(_components.size()-1); } public String stringComponent(int i) { if ((null == _components) || (i >= _components.size())) return null; return componentPrintURI(_components.get(i)); } public void decode(XMLDecoder decoder) throws XMLStreamException { decoder.readStartElement(CONTENT_NAME_ELEMENT); _components = new ArrayList<byte []>(); while (decoder.peekStartElement(COMPONENT_ELEMENT)) { _components.add(decoder.readBinaryElement(COMPONENT_ELEMENT)); } decoder.readEndElement(); } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final ContentName other = (ContentName)obj; if (other.count() != this.count()) return false; for (int i=0; i < count(); ++i) { if (!Arrays.equals(other.component(i), this.component(i))) return false; } if (prefixCount() != other.prefixCount()) return false; return true; } /** * Check prefix match up to the first componentCount * components. * @param obj * @param componentCount if larger than the number of * components, take this as the whole thing. * @return */ private boolean equals(ContentName obj, int componentCount) { if (this == obj) return true; if (obj == null) return false; if ((componentCount > this.count()) && (obj.count() != this.count())) return false; for (int i=0; i < componentCount; ++i) { if (!Arrays.equals(obj.component(i), this.component(i))) return false; } return true; } /** * Parses the canonical URI representation. * @param str * @return * @throws MalformedContentNameStringException */ public static ContentName parse(String str) throws MalformedContentNameStringException { if(str == null) return null; if(str.length() == 0) return ROOT; return fromURI(str); } /** * Uses the canonical URI representation * @param str * @return */ public boolean contains(String str) { try { byte[] parsed = componentParseURI(str); if (null == parsed) { return false; } else { return contains(parsed); } } catch (DotDotComponent c) { return false; } } public boolean contains(byte [] component) { return (containsWhere(component) > 0); } /** * Uses the canonical URI representation * @param str * @return */ public int containsWhere(String str) { try { byte[] parsed = componentParseURI(str); if (null == parsed) { return -1; } else { return containsWhere(parsed); } } catch (DotDotComponent c) { return -1; } } int containsWhere(byte [] component) { int i=0; boolean result = false; for (i=0; i < _components.size(); ++i) { if (Arrays.equals(_components.get(i),component)) { result = true; break; } } if (result) return i; return -1; } /** * Slice the name off right before the given component * @param name * @param component * @return */ public ContentName cut(byte [] component) { int offset = this.containsWhere(component); if (offset < 0) { // unfragmented return this; } // else need to cut it return new ContentName(offset, this.components()); } public ContentName cut(String component) { try { byte[] parsed = componentParseURI(component); if (null == parsed) { return this; } else { return cut(parsed); } } catch (DotDotComponent c) { return this; } } public boolean isPrefixOf(ContentName other) { if (null == other) return false; int count = _prefixCount == null ? count() : prefixCount(); if (count > other.count()) return false; return this.equals(other, count); } /** * Compare our name to the name of the ContentObject. * If our name is 1 component longer than the ContentObject * and no prefix count is set, our name might contain a digest. * In that case, try matching the content to the last component as * a digest. * * @param other * @return */ public boolean isPrefixOf(ContentObject other) { boolean match = isPrefixOf(other.name()); if (match || prefixCount() != null) return match; if (count() == other.name().count() + 1) { if (DataUtils.compare(component(count() - 1), other.contentDigest()) == 0) { return true; } } return false; } public void encode(XMLEncoder encoder) throws XMLStreamException { if (!validate()) { throw new XMLStreamException("Cannot encode " + this.getClass().getName() + ": field values missing."); } encoder.writeStartElement(CONTENT_NAME_ELEMENT); for (int i=0; i < count(); ++i) { encoder.writeElement(COMPONENT_ELEMENT, _components.get(i)); } encoder.writeEndElement(); } public boolean validate() { return (null != _components); } public ContentName copy(int nameComponentCount) { return new ContentName(nameComponentCount, this.components()); } public int compareTo(ContentName o) { if (this == o) return 0; int len = (this.count() > o.count()) ? this.count() : o.count(); int componentResult = 0; for (int i=0; i < len; ++i) { componentResult = DataUtils.compare(this.component(i), o.component(i)); if (0 != componentResult) return componentResult; } if (this.count() < o.count()) return -1; else if (this.count() > o.count()) return 1; if (this.prefixCount() == null && o.prefixCount() != null) return -1; if (this.prefixCount() != null && o.prefixCount() == null) return 1; if (this.prefixCount() != null) { if (this.prefixCount() < o.prefixCount()) return -1; if (this.prefixCount() > o.prefixCount()) return 1; } return 0; } }
35,439
0.629081
0.622055
980
34.161224
26.92428
134
false
false
0
0
0
0
0
0
2.743878
false
false
10
f738300224a8b0f976c965f8bc729f444baf45a7
31,052,613,563,870
bf8f5396889d4a0adec72c4b342dd4022d1a6a8d
/src/main/java/com/test/utils/DuplicateUtil.java
840e4f6dc38cc99f4e124e14a0e33e3f4ab8d760
[]
no_license
95hx/spring-and-libgdx
https://github.com/95hx/spring-and-libgdx
76ba81e7aafae290f86964fa07cb4d14bb00b710
86562b595ac2414ed164e9c6ec72de06a59bd870
refs/heads/master
2020-06-20T15:29:26.328000
2019-07-17T01:51:59
2019-07-17T01:51:59
197,163,962
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.test.utils; import java.util.Arrays; import java.util.HashSet; import java.util.List; /** * @Author: hx * @Date: 2019/7/15 19:06 * @Description: 字符串去重,用于ttf字体加载 */ public class DuplicateUtil { public static String listString(List<String> strList) { HashSet<String> strSet = new HashSet<>(); strList.forEach(e -> { String[] split = e.split(""); strSet.addAll(Arrays.asList(split)); }); StringBuilder stringBuilder = new StringBuilder(); strSet.forEach(stringBuilder::append); return stringBuilder.toString(); } public static String string(String str) { String[] split = str.split(""); HashSet<String> strSet = new HashSet<>(Arrays.asList(split)); StringBuilder stringBuilder = new StringBuilder(); strSet.forEach(stringBuilder::append); return stringBuilder.toString(); } public static StringBuilder stringBuilder(StringBuilder o) { String[] split = o.toString().split(""); HashSet<String> strSet = new HashSet<>(Arrays.asList(split)); StringBuilder stringBuilder= new StringBuilder(); strSet.forEach(stringBuilder::append); return stringBuilder; } }
UTF-8
Java
1,268
java
DuplicateUtil.java
Java
[ { "context": "l.HashSet;\nimport java.util.List;\n\n/**\n * @Author: hx\n * @Date: 2019/7/15 19:06\n * @Description: 字符串去重,", "end": 118, "score": 0.9985817074775696, "start": 116, "tag": "USERNAME", "value": "hx" } ]
null
[]
package com.test.utils; import java.util.Arrays; import java.util.HashSet; import java.util.List; /** * @Author: hx * @Date: 2019/7/15 19:06 * @Description: 字符串去重,用于ttf字体加载 */ public class DuplicateUtil { public static String listString(List<String> strList) { HashSet<String> strSet = new HashSet<>(); strList.forEach(e -> { String[] split = e.split(""); strSet.addAll(Arrays.asList(split)); }); StringBuilder stringBuilder = new StringBuilder(); strSet.forEach(stringBuilder::append); return stringBuilder.toString(); } public static String string(String str) { String[] split = str.split(""); HashSet<String> strSet = new HashSet<>(Arrays.asList(split)); StringBuilder stringBuilder = new StringBuilder(); strSet.forEach(stringBuilder::append); return stringBuilder.toString(); } public static StringBuilder stringBuilder(StringBuilder o) { String[] split = o.toString().split(""); HashSet<String> strSet = new HashSet<>(Arrays.asList(split)); StringBuilder stringBuilder= new StringBuilder(); strSet.forEach(stringBuilder::append); return stringBuilder; } }
1,268
0.642857
0.634029
38
31.789474
21.381445
69
false
false
0
0
0
0
0
0
0.578947
false
false
10
f0dfe37beacba92fae05d7593e7b42499580f806
28,132,035,842,694
29d688ba7892a6df213e37e059779fbb8591c14a
/src/com/isometricgame/engine/main/InputHandler.java
e7f1ee984aa468d124a5c6ff863e9c615adb6a60
[]
no_license
neil-galloway/ProjectTwo
https://github.com/neil-galloway/ProjectTwo
77715700f410c57e06054f540dd0f6f28ab2bed7
3112ec9f8b4b90b9307290af76a7a5dc1a507097
refs/heads/master
2016-09-06T10:41:20.874000
2014-08-20T20:55:52
2014-08-20T20:55:52
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.isometricgame.engine.main; import com.isometricgame.data.livingthings.PlayerChar; public class InputHandler { public enum GameContext{ Inventory, Menu, InGame } private GameContext context; private MouseControl mouseController; private KeyboardActionState keyboardController; private PlayerChar playerChar; public InputHandler(GameContext context, MouseControl mouseController, KeyboardActionState keyboardController, PlayerChar playerChar){ this.context = context; this.mouseController = mouseController; this.keyboardController = keyboardController; this.playerChar = playerChar; } public void update(){ switch(context){ case InGame: inGameUpdate(); break; case Inventory: break; case Menu: break; default: break; } } private void inGameUpdate(){ int xVelocity; int yVelocity; if(keyboardController.isDownPressed() && keyboardController.isUpPressed() || !keyboardController.isDownPressed() && !keyboardController.isUpPressed()){ yVelocity = 0; } else if (keyboardController.isDownPressed()){ yVelocity = 1; } else if (keyboardController.isUpPressed()){ yVelocity = -1; } if(keyboardController.isLeftPressed() && keyboardController.isRightPressed() || !keyboardController.isLeftPressed() && !keyboardController.isRightPressed()){ xVelocity = 0; } else if (keyboardController.isLeftPressed()){ xVelocity = -1; } else if (keyboardController.isRightPressed()){ xVelocity = 1; } } }
UTF-8
Java
1,607
java
InputHandler.java
Java
[]
null
[]
package com.isometricgame.engine.main; import com.isometricgame.data.livingthings.PlayerChar; public class InputHandler { public enum GameContext{ Inventory, Menu, InGame } private GameContext context; private MouseControl mouseController; private KeyboardActionState keyboardController; private PlayerChar playerChar; public InputHandler(GameContext context, MouseControl mouseController, KeyboardActionState keyboardController, PlayerChar playerChar){ this.context = context; this.mouseController = mouseController; this.keyboardController = keyboardController; this.playerChar = playerChar; } public void update(){ switch(context){ case InGame: inGameUpdate(); break; case Inventory: break; case Menu: break; default: break; } } private void inGameUpdate(){ int xVelocity; int yVelocity; if(keyboardController.isDownPressed() && keyboardController.isUpPressed() || !keyboardController.isDownPressed() && !keyboardController.isUpPressed()){ yVelocity = 0; } else if (keyboardController.isDownPressed()){ yVelocity = 1; } else if (keyboardController.isUpPressed()){ yVelocity = -1; } if(keyboardController.isLeftPressed() && keyboardController.isRightPressed() || !keyboardController.isLeftPressed() && !keyboardController.isRightPressed()){ xVelocity = 0; } else if (keyboardController.isLeftPressed()){ xVelocity = -1; } else if (keyboardController.isRightPressed()){ xVelocity = 1; } } }
1,607
0.692595
0.688861
61
25.344263
33.050823
165
false
false
0
0
0
0
0
0
1.639344
false
false
10
ed70c89c2b10ea0d8773ac0273a8903bd7772eff
5,059,471,535,786
3e6038fa8316756dd9cfb0d46a6409316aa6d28e
/src/Projectile.java
1d2523a84da9b0517c332958ee22f834c3740f19
[]
no_license
erickjcalder/T08G01
https://github.com/erickjcalder/T08G01
25058fe80a3b7fb6bf0b998b8b69ead9c354bad0
9f7ee445d3a7805e384dadf74b6026f32770a7ec
refs/heads/master
2020-04-21T13:31:03.549000
2019-04-14T04:59:26
2019-04-14T04:59:26
169,601,341
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.awt.Graphics; import java.awt.Image; import java.awt.Toolkit; /** * Projectiles are any object that is shot by an Enemy or Player * * @author Vlad * @version Demo 2 */ public class Projectile extends Entity { Image projectile = Toolkit.getDefaultToolkit().getImage("resources/Projectile.png"); Image web = Toolkit.getDefaultToolkit().getImage("resources/Web Projectile.png"); private String type; public Projectile(int x, int y, int velX, int velY, Handler handler, String type) { super(x, y, handler); this.setName("projectile"); this.setTeam(""); this.setX(x); this.setY(y); this.setVelocityX(velX); this.setVelocityY(velY); this.type = type; if (type.equals("player")) { setWidth(20); setHeight(20); } if (type.equals("web")) { setWidth(90); setHeight(90); } } @Override public void tick() { setX(getX() + (int) getVelocityX()); setY(getY() + (int) getVelocityY()); } /** * Draws the Projectile to the screen * * @param Graphics * the graphics object that is used to draw to the screen */ @Override public void render(Graphics g) { if (type.equals("player")) { g.drawImage(projectile, getX(), getY(), null); } if (type.equals("web")) { g.drawImage(web, getX(), getY(), 90, 90, null); } } /** * Handles all AI or controls. * * @param input * Action to be performed. */ public void logicInterface(String input) { } /** * Represents the computation of the Projectile's movement. */ public void movementLogic() { } public void attackLogic(int direction) { } @Override protected void checkInteraction(Entity initiator) { // TODO Auto-generated method stub } public String getType() { return new String(this.type); } }
UTF-8
Java
1,887
java
Projectile.java
Java
[ { "context": "that is shot by an Enemy or Player\r\n *\r\n * @author Vlad\r\n * @version Demo 2\r\n */\r\n\r\npublic class Projecti", "end": 169, "score": 0.9991933703422546, "start": 165, "tag": "NAME", "value": "Vlad" } ]
null
[]
import java.awt.Graphics; import java.awt.Image; import java.awt.Toolkit; /** * Projectiles are any object that is shot by an Enemy or Player * * @author Vlad * @version Demo 2 */ public class Projectile extends Entity { Image projectile = Toolkit.getDefaultToolkit().getImage("resources/Projectile.png"); Image web = Toolkit.getDefaultToolkit().getImage("resources/Web Projectile.png"); private String type; public Projectile(int x, int y, int velX, int velY, Handler handler, String type) { super(x, y, handler); this.setName("projectile"); this.setTeam(""); this.setX(x); this.setY(y); this.setVelocityX(velX); this.setVelocityY(velY); this.type = type; if (type.equals("player")) { setWidth(20); setHeight(20); } if (type.equals("web")) { setWidth(90); setHeight(90); } } @Override public void tick() { setX(getX() + (int) getVelocityX()); setY(getY() + (int) getVelocityY()); } /** * Draws the Projectile to the screen * * @param Graphics * the graphics object that is used to draw to the screen */ @Override public void render(Graphics g) { if (type.equals("player")) { g.drawImage(projectile, getX(), getY(), null); } if (type.equals("web")) { g.drawImage(web, getX(), getY(), 90, 90, null); } } /** * Handles all AI or controls. * * @param input * Action to be performed. */ public void logicInterface(String input) { } /** * Represents the computation of the Projectile's movement. */ public void movementLogic() { } public void attackLogic(int direction) { } @Override protected void checkInteraction(Entity initiator) { // TODO Auto-generated method stub } public String getType() { return new String(this.type); } }
1,887
0.615262
0.608373
97
17.474226
20.493948
85
false
false
0
0
0
0
0
0
1.42268
false
false
10
8932e40c3b01e9c961b51fb52dd3bdd2bfff8817
6,408,091,269,521
ac9352c855160232be7c2f5c672fa91fbfeceaba
/src/productledger/Product.java
65ef242a8d50b4be0d9754694bcf4dbdc28fbfde
[]
no_license
Nirzak/Product-Ledger
https://github.com/Nirzak/Product-Ledger
538593c912f2923b541ccdf2a26154e25e05c202
a27fbf2d404f90f704048e2c1a2cbdb46c07dfca
refs/heads/main
2023-06-12T04:54:24.299000
2021-06-28T16:56:01
2021-06-28T16:56:01
381,032,870
1
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 productledger; /** * * @author NirZak */ public class Product { private String name; private int buyPrice; private int sellPrice; private int availableQuantity; private int profit; Product(String name, int buyPrice, int sellPrice, int availableQuantity, int profit){ this.name = name; this.buyPrice = buyPrice; this.sellPrice = sellPrice; this.availableQuantity = availableQuantity; this.profit = profit; } public String getName(){ return this.name; } public int getBuyPrice() { return this.buyPrice; } public int getSellPrice() { return this.sellPrice; } public int getAvailableQuantity() { return this.availableQuantity; } public int getProfit(){ return this.profit; } public void setAvailableQuantity(int availableQuantity) { this.availableQuantity = availableQuantity; } public void setProfit(int profit) { this.profit = profit; } /*public void setName(String name){ this.name = name; } public void setBuyPrice(int buyPrice) { this.buyPrice = buyPrice; } public void setSellPrice(int sellPrice) { this.sellPrice = sellPrice; } */ }
UTF-8
Java
1,500
java
Product.java
Java
[ { "context": "tor.\n */\npackage productledger;\n\n/**\n *\n * @author NirZak\n */\npublic class Product {\n private Strin", "end": 228, "score": 0.7761895656585693, "start": 227, "tag": "NAME", "value": "N" }, { "context": "r.\n */\npackage productledger;\n\n/**\n *\n * @author NirZak\n */\npublic class Product {\n private String n", "end": 231, "score": 0.6201354265213013, "start": 228, "tag": "USERNAME", "value": "irZ" }, { "context": " */\npackage productledger;\n\n/**\n *\n * @author NirZak\n */\npublic class Product {\n private String nam", "end": 233, "score": 0.5067842602729797, "start": 231, "tag": "NAME", "value": "ak" } ]
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 productledger; /** * * @author NirZak */ public class Product { private String name; private int buyPrice; private int sellPrice; private int availableQuantity; private int profit; Product(String name, int buyPrice, int sellPrice, int availableQuantity, int profit){ this.name = name; this.buyPrice = buyPrice; this.sellPrice = sellPrice; this.availableQuantity = availableQuantity; this.profit = profit; } public String getName(){ return this.name; } public int getBuyPrice() { return this.buyPrice; } public int getSellPrice() { return this.sellPrice; } public int getAvailableQuantity() { return this.availableQuantity; } public int getProfit(){ return this.profit; } public void setAvailableQuantity(int availableQuantity) { this.availableQuantity = availableQuantity; } public void setProfit(int profit) { this.profit = profit; } /*public void setName(String name){ this.name = name; } public void setBuyPrice(int buyPrice) { this.buyPrice = buyPrice; } public void setSellPrice(int sellPrice) { this.sellPrice = sellPrice; } */ }
1,500
0.627333
0.627333
67
21.38806
19.841879
89
false
false
0
0
0
0
0
0
0.41791
false
false
10
84ce420ad8ed66267e14b473d9fc1877094fd033
6,408,091,269,446
b8781f70931403b3fd726e0b9393c1cc9d95b1f2
/FettlePath/src/main/java/com/application/fettlepath/repository/search/UserSearchRepository.java
742a31c742f4fb339675e73cb9380464c5303a0c
[]
no_license
swachil/fettlepath
https://github.com/swachil/fettlepath
8d8e9b1f0a2ac575011da58ce090e2ef45a201c0
8b0294964b97b1d5be3c48fd6d51cb88f1e46bd3
refs/heads/master
2021-07-05T19:43:57.841000
2019-03-15T02:11:06
2019-03-15T02:11:06
175,605,424
1
1
null
false
2020-09-18T11:43:00
2019-03-14T11:06:34
2019-03-15T02:11:44
2019-03-19T16:10:19
761
0
1
1
Java
false
false
package com.application.fettlepath.repository.search; import com.application.fettlepath.domain.User; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; /** * Spring Data Elasticsearch repository for the User entity. */ public interface UserSearchRepository extends ElasticsearchRepository<User, Long> { }
UTF-8
Java
340
java
UserSearchRepository.java
Java
[]
null
[]
package com.application.fettlepath.repository.search; import com.application.fettlepath.domain.User; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; /** * Spring Data Elasticsearch repository for the User entity. */ public interface UserSearchRepository extends ElasticsearchRepository<User, Long> { }
340
0.832353
0.832353
10
33
33.322666
83
false
false
0
0
0
0
0
0
0.4
false
false
10
6a71d489cc3df7e7f60133be0dc75accd70df24b
5,025,111,776,688
6c7de008fa43102f37e3815a6fca8edba29c3d83
/venus-service/src/main/java/com/babel/venus/config/CustomerConfig.java
0a4e65eaf68267c6a4ab93cb05bd36931b92a01d
[]
no_license
joey12492/Venus
https://github.com/joey12492/Venus
ecb6d2a92ce56e24bd6e8472fd86c878dadd9b6c
c81a0b2259a9c4df08eeba26d52ee278781ac574
refs/heads/master
2021-05-05T03:55:46.196000
2018-01-23T02:04:41
2018-01-23T02:04:41
118,542,260
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.babel.venus.config; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.PostConstruct; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import com.babel.uaa.utils.DomainAppidUtils; @Component @ConfigurationProperties(prefix = "customer") public class CustomerConfig { private final Logger log = LoggerFactory.getLogger(CustomerConfig.class); private String runType; //forsetti对接payment,cms,config时的配置信息缓存时间,为0表示不缓存 private Integer cacheInterval; /** * 配置见注册中心的git */ private Integer lotteryRunSideType; /** * www.baidu.com|plat_owner_test */ private List<String> domainAppidBinds;//真实会员平台商appid配置 /** * 权限资源配置 * exp:/v2/api-docs|ROLE_ADMIN */ private List<String> permitResRoles; @PostConstruct public void init(){ log.info("-----lotteryRunSideType="+lotteryRunSideType); log.info("-----domainAppidBinds="+domainAppidBinds +"\n domainAppidMap="+getDomainAppidMap()); log.info("-----permitResRoles="+permitResRoles +"\n permitResRoleMap="+getPermitResRoleMap()); } /** * @return the domainAppidBinds */ public List<String> getDomainAppidBinds() { return domainAppidBinds; } /** * @param domainAppidBinds the domainAppidBinds to set */ public void setDomainAppidBinds(List<String> domainAppidBinds) { this.domainAppidBinds = domainAppidBinds; domainAppidMap= DomainAppidUtils.getDomainAppidListToMap(domainAppidBinds); } private Map<String, String> domainAppidMap=new HashMap<>(); private Map<String, String> getDomainAppidMap(){ if(domainAppidMap.isEmpty()){ domainAppidMap= DomainAppidUtils.getDomainAppidListToMap(domainAppidBinds); log.info("-----domainAppidBinds="+domainAppidBinds +"\n domainAppidMap="+domainAppidMap); } return domainAppidMap; } /** * @return the permitResRoles */ public List<String> getPermitResRoles() { return permitResRoles; } private Map<String, String> permitResRoleMap=new HashMap<>(); public Map<String, String> getPermitResRoleMap(){ if(permitResRoleMap.isEmpty()){ permitResRoleMap= DomainAppidUtils.getDomainAppidListToMap(permitResRoles); log.info("-----permitResRoles="+permitResRoles +"\n permitResRoleMap="+permitResRoleMap); } return permitResRoleMap; } /** * @param permitResRoles the permitResRoles to set */ public void setPermitResRoles(List<String> permitResRoles) { this.permitResRoles = permitResRoles; permitResRoleMap= DomainAppidUtils.getDomainAppidListToMap(permitResRoles); } //origin忽略http/https public String getAppid(String origin){ if(origin==null){ return null; } origin=origin.trim(); if(origin.startsWith("http://")){ origin=origin.substring("http://".length()); } else if(origin.startsWith("https://")){ origin=origin.substring("https://".length()); } return getDomainAppidMap().get(origin); } /** * @param lotteryRunSideType the lotteryRunSideType to set */ public void setLotteryRunSideType(Integer lotteryRunSideType) { this.lotteryRunSideType = lotteryRunSideType; log.info("-----lotteryRunSideType--"+lotteryRunSideType); } /** * @return the lotteryRunSideType */ public Integer getLotteryRunSideType() { return lotteryRunSideType; } public String getRunType() { return runType; } public void setRunType(String runType) { this.runType = runType; } public boolean isRunTypeProd(){ return "prod".equals(runType); } /** * @return the cacheInterval */ public Integer getCacheInterval() { return cacheInterval; } /** * @param cacheInterval the cacheInterval to set */ public void setCacheInterval(Integer cacheInterval) { this.cacheInterval = cacheInterval; log.info("-----cacheInterval--"+cacheInterval); } }
UTF-8
Java
4,004
java
CustomerConfig.java
Java
[]
null
[]
package com.babel.venus.config; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.PostConstruct; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import com.babel.uaa.utils.DomainAppidUtils; @Component @ConfigurationProperties(prefix = "customer") public class CustomerConfig { private final Logger log = LoggerFactory.getLogger(CustomerConfig.class); private String runType; //forsetti对接payment,cms,config时的配置信息缓存时间,为0表示不缓存 private Integer cacheInterval; /** * 配置见注册中心的git */ private Integer lotteryRunSideType; /** * www.baidu.com|plat_owner_test */ private List<String> domainAppidBinds;//真实会员平台商appid配置 /** * 权限资源配置 * exp:/v2/api-docs|ROLE_ADMIN */ private List<String> permitResRoles; @PostConstruct public void init(){ log.info("-----lotteryRunSideType="+lotteryRunSideType); log.info("-----domainAppidBinds="+domainAppidBinds +"\n domainAppidMap="+getDomainAppidMap()); log.info("-----permitResRoles="+permitResRoles +"\n permitResRoleMap="+getPermitResRoleMap()); } /** * @return the domainAppidBinds */ public List<String> getDomainAppidBinds() { return domainAppidBinds; } /** * @param domainAppidBinds the domainAppidBinds to set */ public void setDomainAppidBinds(List<String> domainAppidBinds) { this.domainAppidBinds = domainAppidBinds; domainAppidMap= DomainAppidUtils.getDomainAppidListToMap(domainAppidBinds); } private Map<String, String> domainAppidMap=new HashMap<>(); private Map<String, String> getDomainAppidMap(){ if(domainAppidMap.isEmpty()){ domainAppidMap= DomainAppidUtils.getDomainAppidListToMap(domainAppidBinds); log.info("-----domainAppidBinds="+domainAppidBinds +"\n domainAppidMap="+domainAppidMap); } return domainAppidMap; } /** * @return the permitResRoles */ public List<String> getPermitResRoles() { return permitResRoles; } private Map<String, String> permitResRoleMap=new HashMap<>(); public Map<String, String> getPermitResRoleMap(){ if(permitResRoleMap.isEmpty()){ permitResRoleMap= DomainAppidUtils.getDomainAppidListToMap(permitResRoles); log.info("-----permitResRoles="+permitResRoles +"\n permitResRoleMap="+permitResRoleMap); } return permitResRoleMap; } /** * @param permitResRoles the permitResRoles to set */ public void setPermitResRoles(List<String> permitResRoles) { this.permitResRoles = permitResRoles; permitResRoleMap= DomainAppidUtils.getDomainAppidListToMap(permitResRoles); } //origin忽略http/https public String getAppid(String origin){ if(origin==null){ return null; } origin=origin.trim(); if(origin.startsWith("http://")){ origin=origin.substring("http://".length()); } else if(origin.startsWith("https://")){ origin=origin.substring("https://".length()); } return getDomainAppidMap().get(origin); } /** * @param lotteryRunSideType the lotteryRunSideType to set */ public void setLotteryRunSideType(Integer lotteryRunSideType) { this.lotteryRunSideType = lotteryRunSideType; log.info("-----lotteryRunSideType--"+lotteryRunSideType); } /** * @return the lotteryRunSideType */ public Integer getLotteryRunSideType() { return lotteryRunSideType; } public String getRunType() { return runType; } public void setRunType(String runType) { this.runType = runType; } public boolean isRunTypeProd(){ return "prod".equals(runType); } /** * @return the cacheInterval */ public Integer getCacheInterval() { return cacheInterval; } /** * @param cacheInterval the cacheInterval to set */ public void setCacheInterval(Integer cacheInterval) { this.cacheInterval = cacheInterval; log.info("-----cacheInterval--"+cacheInterval); } }
4,004
0.732635
0.731614
160
23.475
22.678169
78
false
false
0
0
0
0
0
0
1.49375
false
false
10
a2e0aa8e9e9485f81a299302ba817815f33ab1c1
26,250,840,158,514
1ebda59d376d1ede5efaec8f08e79a275104afaa
/src/babelnet/Synset.java
2da04a651d2bafcd773e93db747b50bc141700dd
[]
no_license
jackee777/babelnet_offline
https://github.com/jackee777/babelnet_offline
6a171cc10119f5100ec8263a5abd8c69f8330b77
ae9a1a46397eda00e6833fc63fc4f130b853eab3
refs/heads/master
2020-06-04T10:15:38.066000
2020-04-02T12:21:30
2020-04-02T12:21:30
191,981,369
4
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package babelnet; import java.util.HashMap; import java.util.List; import java.util.Set; import com.google.common.collect.Multimap; import it.uniroma1.lcl.babelnet.BabelSense; import it.uniroma1.lcl.babelnet.BabelSynsetType; import it.uniroma1.lcl.babelnet.WordNetSynsetID; import it.uniroma1.lcl.babelnet.data.BabelCategory; import it.uniroma1.lcl.babelnet.data.BabelExample; import it.uniroma1.lcl.babelnet.data.BabelGloss; import it.uniroma1.lcl.babelnet.data.BabelImage; import it.uniroma1.lcl.kb.Domain; public class Synset { List<BabelSense> senses = null; List<WordNetSynsetID> wnOffsets = null; String mainSense = null; List<BabelGloss> glosses = null; List<BabelExample> examples = null; List<BabelImage> images = null; BabelSynsetType synsetType = null; List<BabelCategory> categories = null; Multimap<BabelSense, BabelSense> translations = null; HashMap<Domain, Double> domains = null; Set<String> lnToCompound = null; Set<String> lnToOtherForm = null; }
UTF-8
Java
982
java
Synset.java
Java
[]
null
[]
package babelnet; import java.util.HashMap; import java.util.List; import java.util.Set; import com.google.common.collect.Multimap; import it.uniroma1.lcl.babelnet.BabelSense; import it.uniroma1.lcl.babelnet.BabelSynsetType; import it.uniroma1.lcl.babelnet.WordNetSynsetID; import it.uniroma1.lcl.babelnet.data.BabelCategory; import it.uniroma1.lcl.babelnet.data.BabelExample; import it.uniroma1.lcl.babelnet.data.BabelGloss; import it.uniroma1.lcl.babelnet.data.BabelImage; import it.uniroma1.lcl.kb.Domain; public class Synset { List<BabelSense> senses = null; List<WordNetSynsetID> wnOffsets = null; String mainSense = null; List<BabelGloss> glosses = null; List<BabelExample> examples = null; List<BabelImage> images = null; BabelSynsetType synsetType = null; List<BabelCategory> categories = null; Multimap<BabelSense, BabelSense> translations = null; HashMap<Domain, Double> domains = null; Set<String> lnToCompound = null; Set<String> lnToOtherForm = null; }
982
0.792261
0.784114
31
30.67742
16.353725
54
false
false
0
0
0
0
0
0
1.258065
false
false
10
ce29e55ede3702476c2b3d112c042c34418dfe2b
9,268,539,468,464
c986e92aeff1c55073c5c1d3e647956a8c658070
/t1/t1-web/src/main/java/com/azunitech/t1/web/link/Article.java
92bd1937361db913719f1ddf274973164eee262a
[]
no_license
billgql/jpa
https://github.com/billgql/jpa
a5dffe35c92b7a14e1250e4fac0a0d0b121041f8
f7150d39f86eab94703cb0eb0ca4605a96a3d210
refs/heads/master
2016-09-08T18:38:35
2015-05-12T07:14:22
2015-05-12T07:14:22
32,373,057
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.azunitech.t1.web.link; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlID; import javax.xml.bind.annotation.XmlRootElement; import org.jboss.resteasy.links.RESTServiceDiscovery; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Article { @XmlAttribute private String author; @XmlID @XmlAttribute private String title; @XmlElementRef private RESTServiceDiscovery rest; public Article(){} public Article(String author, String title){ this.author = author; this.title = title; } }
UTF-8
Java
769
java
Article.java
Java
[]
null
[]
package com.azunitech.t1.web.link; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlID; import javax.xml.bind.annotation.XmlRootElement; import org.jboss.resteasy.links.RESTServiceDiscovery; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Article { @XmlAttribute private String author; @XmlID @XmlAttribute private String title; @XmlElementRef private RESTServiceDiscovery rest; public Article(){} public Article(String author, String title){ this.author = author; this.title = title; } }
769
0.739922
0.738622
26
27.5
16.39477
53
false
false
0
0
0
0
0
0
0.653846
false
false
10
58cdc0dd0e5964a94fdbbf752ec4b1f302341d4c
13,477,607,437,184
d2f527ea4eba624b63c35d118789d92adb90e465
/community/mahout-mr/mr/src/test/java/org/apache/mahout/vectorizer/collocations/llr/GramTest.java
f04d5c607c019d0d10e7c62c7d2d84cbd2d83b5f
[ "Apache-2.0", "CPL-1.0", "GPL-2.0-or-later", "MIT", "LicenseRef-scancode-mit-old-style", "LicenseRef-scancode-public-domain", "Classpath-exception-2.0" ]
permissive
apache/mahout
https://github.com/apache/mahout
070c039ad1c5dcedabb847bb1097494a5b2a46ef
09f8a2461166311bb94f7e697a634e3475eeb2fd
refs/heads/trunk
2023-08-16T15:08:13.076000
2023-07-27T18:16:20
2023-07-27T18:16:20
20,089,859
2,197
1,135
Apache-2.0
false
2023-03-17T21:21:32
2014-05-23T07:00:07
2023-03-17T08:10:52
2023-03-17T21:21:31
68,448
2,042
953
6
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.mahout.vectorizer.collocations.llr; import org.apache.mahout.common.MahoutTestCase; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInput; import java.io.DataInputStream; import java.io.DataOutput; import java.io.DataOutputStream; import java.util.Arrays; import java.util.HashMap; public final class GramTest extends MahoutTestCase { @Test public void testConstructorsGetters() { Gram one = new Gram("foo", 2, Gram.Type.HEAD); assertEquals("foo", one.getString()); assertEquals(2, one.getFrequency()); assertEquals(Gram.Type.HEAD, one.getType()); Gram oneClone = new Gram(one); assertEquals("foo", oneClone.getString()); assertEquals(2, oneClone.getFrequency()); assertEquals(Gram.Type.HEAD, oneClone.getType()); Gram two = new Gram("foo", 3, Gram.Type.TAIL); assertEquals(Gram.Type.TAIL, two.getType()); Gram three = new Gram("foo", 4, Gram.Type.UNIGRAM); assertEquals(Gram.Type.UNIGRAM, three.getType()); Gram four = new Gram("foo", 5, Gram.Type.NGRAM); assertEquals(Gram.Type.NGRAM, four.getType()); } @Test(expected = NullPointerException.class) public void testNull1() { new Gram(null, 4, Gram.Type.UNIGRAM); } @Test(expected = NullPointerException.class) public void testNull2() { new Gram("foo", 4, null); } @Test public void testEquality() { Gram one = new Gram("foo", 2, Gram.Type.HEAD); Gram two = new Gram("foo", 3, Gram.Type.HEAD); assertEquals(one, two); assertEquals(two, one); Gram three = new Gram("foo", 4, Gram.Type.TAIL); Gram four = new Gram("foo", Gram.Type.UNIGRAM); assertTrue(!three.equals(two)); assertTrue(!four.equals(one)); assertTrue(!one.equals(four)); Gram five = new Gram("foo", 5, Gram.Type.UNIGRAM); assertEquals(four, five); Gram six = new Gram("foo", 6, Gram.Type.NGRAM); Gram seven = new Gram("foo", 7, Gram.Type.NGRAM); assertTrue(!five.equals(six)); assertEquals(six, seven); Gram eight = new Gram("foobar", 4, Gram.Type.TAIL); assertTrue(!eight.equals(four)); assertTrue(!eight.equals(three)); assertTrue(!eight.equals(two)); assertTrue(!eight.equals(one)); } @Test public void testHashing() { Gram[] input = { new Gram("foo", 2, Gram.Type.HEAD), new Gram("foo", 3, Gram.Type.HEAD), new Gram("foo", 4, Gram.Type.TAIL), new Gram("foo", 5, Gram.Type.TAIL), new Gram("bar", 6, Gram.Type.HEAD), new Gram("bar", 7, Gram.Type.TAIL), new Gram("bar", 8, Gram.Type.NGRAM), new Gram("bar", Gram.Type.UNIGRAM) }; HashMap<Gram,Gram> map = new HashMap<>(); for (Gram n : input) { Gram val = map.get(n); if (val != null) { val.incrementFrequency(n.getFrequency()); } else { map.put(n, n); } } // frequencies of the items in the map. int[] freq = { 5, 3, 9, 5, 6, 7, 8, 1 }; // true if the index should be the item in the map boolean[] memb = { true, false, true, false, true, true, true, true }; for (int i = 0; i < input.length; i++) { assertEquals(freq[i], input[i].getFrequency()); assertEquals(memb[i], input[i] == map.get(input[i])); } } @Test public void testWritable() throws Exception { Gram one = new Gram("foo", 2, Gram.Type.HEAD); Gram two = new Gram("foobar", 3, Gram.Type.UNIGRAM); assertEquals("foo", one.getString()); assertEquals(2, one.getFrequency()); assertEquals(Gram.Type.HEAD, one.getType()); assertEquals("foobar", two.getString()); assertEquals(3, two.getFrequency()); assertEquals(Gram.Type.UNIGRAM, two.getType()); ByteArrayOutputStream bout = new ByteArrayOutputStream(); DataOutput out = new DataOutputStream(bout); two.write(out); byte[] b = bout.toByteArray(); ByteArrayInputStream bin = new ByteArrayInputStream(b); DataInput din = new DataInputStream(bin); one.readFields(din); assertEquals("foobar", one.getString()); assertEquals(3, one.getFrequency()); assertEquals(Gram.Type.UNIGRAM, one.getType()); } @Test public void testSorting() { Gram[] input = { new Gram("foo", 2, Gram.Type.HEAD), new Gram("foo", 3, Gram.Type.HEAD), new Gram("foo", 4, Gram.Type.TAIL), new Gram("foo", 5, Gram.Type.TAIL), new Gram("bar", 6, Gram.Type.HEAD), new Gram("bar", 7, Gram.Type.TAIL), new Gram("bar", 8, Gram.Type.NGRAM), new Gram("bar", Gram.Type.UNIGRAM) }; Gram[] sorted = new Gram[input.length]; int[] expectations = { 4, 0, 1, 5, 2, 3, 7, 6 }; System.arraycopy(input, 0, sorted, 0, input.length); Arrays.sort(sorted); for (int i=0; i < sorted.length; i++) { assertSame(input[expectations[i]], sorted[i]); } } }
UTF-8
Java
6,089
java
GramTest.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.mahout.vectorizer.collocations.llr; import org.apache.mahout.common.MahoutTestCase; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInput; import java.io.DataInputStream; import java.io.DataOutput; import java.io.DataOutputStream; import java.util.Arrays; import java.util.HashMap; public final class GramTest extends MahoutTestCase { @Test public void testConstructorsGetters() { Gram one = new Gram("foo", 2, Gram.Type.HEAD); assertEquals("foo", one.getString()); assertEquals(2, one.getFrequency()); assertEquals(Gram.Type.HEAD, one.getType()); Gram oneClone = new Gram(one); assertEquals("foo", oneClone.getString()); assertEquals(2, oneClone.getFrequency()); assertEquals(Gram.Type.HEAD, oneClone.getType()); Gram two = new Gram("foo", 3, Gram.Type.TAIL); assertEquals(Gram.Type.TAIL, two.getType()); Gram three = new Gram("foo", 4, Gram.Type.UNIGRAM); assertEquals(Gram.Type.UNIGRAM, three.getType()); Gram four = new Gram("foo", 5, Gram.Type.NGRAM); assertEquals(Gram.Type.NGRAM, four.getType()); } @Test(expected = NullPointerException.class) public void testNull1() { new Gram(null, 4, Gram.Type.UNIGRAM); } @Test(expected = NullPointerException.class) public void testNull2() { new Gram("foo", 4, null); } @Test public void testEquality() { Gram one = new Gram("foo", 2, Gram.Type.HEAD); Gram two = new Gram("foo", 3, Gram.Type.HEAD); assertEquals(one, two); assertEquals(two, one); Gram three = new Gram("foo", 4, Gram.Type.TAIL); Gram four = new Gram("foo", Gram.Type.UNIGRAM); assertTrue(!three.equals(two)); assertTrue(!four.equals(one)); assertTrue(!one.equals(four)); Gram five = new Gram("foo", 5, Gram.Type.UNIGRAM); assertEquals(four, five); Gram six = new Gram("foo", 6, Gram.Type.NGRAM); Gram seven = new Gram("foo", 7, Gram.Type.NGRAM); assertTrue(!five.equals(six)); assertEquals(six, seven); Gram eight = new Gram("foobar", 4, Gram.Type.TAIL); assertTrue(!eight.equals(four)); assertTrue(!eight.equals(three)); assertTrue(!eight.equals(two)); assertTrue(!eight.equals(one)); } @Test public void testHashing() { Gram[] input = { new Gram("foo", 2, Gram.Type.HEAD), new Gram("foo", 3, Gram.Type.HEAD), new Gram("foo", 4, Gram.Type.TAIL), new Gram("foo", 5, Gram.Type.TAIL), new Gram("bar", 6, Gram.Type.HEAD), new Gram("bar", 7, Gram.Type.TAIL), new Gram("bar", 8, Gram.Type.NGRAM), new Gram("bar", Gram.Type.UNIGRAM) }; HashMap<Gram,Gram> map = new HashMap<>(); for (Gram n : input) { Gram val = map.get(n); if (val != null) { val.incrementFrequency(n.getFrequency()); } else { map.put(n, n); } } // frequencies of the items in the map. int[] freq = { 5, 3, 9, 5, 6, 7, 8, 1 }; // true if the index should be the item in the map boolean[] memb = { true, false, true, false, true, true, true, true }; for (int i = 0; i < input.length; i++) { assertEquals(freq[i], input[i].getFrequency()); assertEquals(memb[i], input[i] == map.get(input[i])); } } @Test public void testWritable() throws Exception { Gram one = new Gram("foo", 2, Gram.Type.HEAD); Gram two = new Gram("foobar", 3, Gram.Type.UNIGRAM); assertEquals("foo", one.getString()); assertEquals(2, one.getFrequency()); assertEquals(Gram.Type.HEAD, one.getType()); assertEquals("foobar", two.getString()); assertEquals(3, two.getFrequency()); assertEquals(Gram.Type.UNIGRAM, two.getType()); ByteArrayOutputStream bout = new ByteArrayOutputStream(); DataOutput out = new DataOutputStream(bout); two.write(out); byte[] b = bout.toByteArray(); ByteArrayInputStream bin = new ByteArrayInputStream(b); DataInput din = new DataInputStream(bin); one.readFields(din); assertEquals("foobar", one.getString()); assertEquals(3, one.getFrequency()); assertEquals(Gram.Type.UNIGRAM, one.getType()); } @Test public void testSorting() { Gram[] input = { new Gram("foo", 2, Gram.Type.HEAD), new Gram("foo", 3, Gram.Type.HEAD), new Gram("foo", 4, Gram.Type.TAIL), new Gram("foo", 5, Gram.Type.TAIL), new Gram("bar", 6, Gram.Type.HEAD), new Gram("bar", 7, Gram.Type.TAIL), new Gram("bar", 8, Gram.Type.NGRAM), new Gram("bar", Gram.Type.UNIGRAM) }; Gram[] sorted = new Gram[input.length]; int[] expectations = { 4, 0, 1, 5, 2, 3, 7, 6 }; System.arraycopy(input, 0, sorted, 0, input.length); Arrays.sort(sorted); for (int i=0; i < sorted.length; i++) { assertSame(input[expectations[i]], sorted[i]); } } }
6,089
0.605354
0.5955
215
27.32093
20.648876
75
false
false
0
0
0
0
0
0
1.004651
false
false
10
b1f7f45d8881794318cd11b21614bf4ec5f86534
24,807,731,160,836
b75affdef107cebd688b58d0c823a4d9fe79f34b
/app/src/main/java/com/dengpan/pan/pantalker/fragments/panel/PanelFragment.java
ffa32b57eab91d441b587480d6271e3722c74949
[]
no_license
dengpan20/PanTalker_Client
https://github.com/dengpan20/PanTalker_Client
4d035382aaf1765c0d680f27954339bd217919e1
5ab2ef58c2753e54b9b5e1589badbd682eac9162
refs/heads/master
2020-03-19T05:18:24.293000
2018-06-29T10:30:08
2018-06-29T10:30:08
135,918,894
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.dengpan.pan.pantalker.fragments.panel; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.TabLayout; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.TextView; import com.dengpan.pan.common.app.Application; import com.dengpan.pan.common.app.Fragment; import com.dengpan.pan.common.tools.AudioRecordHelper; import com.dengpan.pan.common.tools.UiTool; import com.dengpan.pan.common.widget.AudioRecordView; import com.dengpan.pan.common.widget.GalleryView; import com.dengpan.pan.common.widget.recycler.RecyclerAdapter; import com.dengpan.pan.face.Face; import com.dengpan.pan.pantalker.R; import net.qiujuer.genius.ui.Ui; import java.io.File; import java.util.List; /** * A simple {@link Fragment} subclass. */ public class PanelFragment extends Fragment { private View mFacePanel, mGalleryPanel,mRecordPanel; private PanelCallback mCallback; public PanelFragment() { // Required empty public constructor } @Override protected int getContentLayoutId() { return R.layout.fragment_panel; } @Override protected void initWidget(View root) { super.initWidget(root); initFace(root); initRecord(root); initGallery(root); } public void setup(PanelCallback callback){ this.mCallback = callback; } private void initFace(View root) { final View facePanel =mFacePanel = root.findViewById(R.id.lay_panel_face); View backspace = root.findViewById(R.id.im_backspace); backspace.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { PanelCallback callback = mCallback; if(callback == null) return; //模拟键盘删除 KeyEvent event= new KeyEvent(0, 0, 0, KeyEvent.KEYCODE_DEL, 0, 0, 0, 0, KeyEvent.KEYCODE_ENDCALL); callback.getInputEditText().dispatchKeyEvent(event); } }); TabLayout tabLayout = facePanel.findViewById(R.id.tab); ViewPager viewPager = facePanel.findViewById(R.id.pager); tabLayout.setupWithViewPager(viewPager); //表情显示48dp final int minFaceSize = (int) Ui.dipToPx(getResources(),48); int totalScreen = UiTool.getScreenWidth(getActivity()); final int spanCount = totalScreen/minFaceSize; viewPager.setAdapter(new PagerAdapter() { @Override public int getCount() { return Face.getAll(getContext())==null? 0:Face.getAll(getContext()).size(); } @Override public boolean isViewFromObject(@NonNull View view, @NonNull Object object) { return view == object; } @NonNull @Override public Object instantiateItem(@NonNull ViewGroup container, int position) { LayoutInflater inflater = LayoutInflater.from(getContext()); RecyclerView recyclerView = (RecyclerView) inflater.inflate(R.layout.layout_face_content, container, false); recyclerView.setLayoutManager(new GridLayoutManager(getContext(),spanCount)); List<Face.Bean> faces = Face.getAll(getContext()).get(position).faces; FaceAdapter faceAdapter = new FaceAdapter(faces, new RecyclerAdapter.ViewHolder.AdapterListenerImpl<Face.Bean>() { @Override public void onItemClick(RecyclerAdapter.ViewHolder holder, Face.Bean bean) { if (mCallback == null){ return; } EditText editText = mCallback.getInputEditText(); Face.inputFace(getContext(),editText.getText(),bean,(int)(editText.getTextSize()+Ui.dipToPx(getResources(),2))); } }); recyclerView.setAdapter(faceAdapter); container.addView(recyclerView); return recyclerView; } @Override public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { // super.destroyItem(container, position, object); container.removeView((View) object); } @Nullable @Override public CharSequence getPageTitle(int position) { return Face.getAll(getContext()).get(position).name; } }); } public void showFace() { mRecordPanel.setVisibility(View.GONE); mGalleryPanel.setVisibility(View.GONE); mFacePanel.setVisibility(View.VISIBLE); } public void showRecord(){ mRecordPanel.setVisibility(View.VISIBLE); mGalleryPanel.setVisibility(View.GONE); mFacePanel.setVisibility(View.GONE); } public void showGallery(){ mRecordPanel.setVisibility(View.GONE); mGalleryPanel.setVisibility(View.VISIBLE); mFacePanel.setVisibility(View.GONE); } private void initRecord(View root) { final View recordView = mRecordPanel = root.findViewById(R.id.lay_panel_record); AudioRecordView audioRecordView = root.findViewById(R.id.view_audio_record); File tmpFile = Application.getAudioTmpFile(true); final AudioRecordHelper helper= new AudioRecordHelper(tmpFile, new AudioRecordHelper.RecordCallback() { @Override public void onRecordStart() { } @Override public void onProgress(long time) { } @Override public void onRecordDone(File file, long time) { //时间小于1s 不发送 if(time<1000){ return; } //更改为一个发送录音的文件 File audioFile = Application.getAudioTmpFile(false); if (file.renameTo(audioFile)){ if(mCallback != null){ mCallback.onRecordDone(audioFile,time); } } } }); //audioView 初始化 audioRecordView.setup(new AudioRecordView.Callback() { @Override public void requestStartRecord() { helper.recordAsync(); } @Override public void requestStopRecord(int type) { switch (type){ case AudioRecordView.END_TYPE_CANCEL: case AudioRecordView.END_TYPE_DELETE: helper.stop(true); break; case AudioRecordView.END_TYPE_NONE: case AudioRecordView.END_TYPE_PLAY: helper.stop(false); break; } } }); } private void initGallery(View root) { final View galleryPanel= mGalleryPanel = root.findViewById(R.id.lay_panel_gallery); final GalleryView galleryView=galleryPanel.findViewById(R.id.view_gallery); final TextView selectSize = galleryPanel.findViewById(R.id.txt_gallery_select_count); galleryView.setup(getLoaderManager(), new GalleryView.SelectedChangeListener() { @Override public void onSelectedCountChanged(int count) { String sizeStr = getText(R.string.label_gallery_selected_size).toString(); selectSize.setText(String.format(sizeStr,count)); } }); galleryPanel.findViewById(R.id.btn_send).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onGallerySendClick(galleryView,galleryView.getSelectedPath()); } }); } private void onGallerySendClick(GalleryView galleryView, String[] selectedPath) { galleryView.clear(); PanelCallback callback = mCallback; if(mCallback == null){ return; } callback.onSendGallery(selectedPath); } // 回调聊天界面的Callback public interface PanelCallback { EditText getInputEditText(); // 返回需要发送的图片 void onSendGallery(String[] paths); // 返回录音文件和时常 void onRecordDone(File file, long time); } }
UTF-8
Java
8,852
java
PanelFragment.java
Java
[]
null
[]
package com.dengpan.pan.pantalker.fragments.panel; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.TabLayout; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.TextView; import com.dengpan.pan.common.app.Application; import com.dengpan.pan.common.app.Fragment; import com.dengpan.pan.common.tools.AudioRecordHelper; import com.dengpan.pan.common.tools.UiTool; import com.dengpan.pan.common.widget.AudioRecordView; import com.dengpan.pan.common.widget.GalleryView; import com.dengpan.pan.common.widget.recycler.RecyclerAdapter; import com.dengpan.pan.face.Face; import com.dengpan.pan.pantalker.R; import net.qiujuer.genius.ui.Ui; import java.io.File; import java.util.List; /** * A simple {@link Fragment} subclass. */ public class PanelFragment extends Fragment { private View mFacePanel, mGalleryPanel,mRecordPanel; private PanelCallback mCallback; public PanelFragment() { // Required empty public constructor } @Override protected int getContentLayoutId() { return R.layout.fragment_panel; } @Override protected void initWidget(View root) { super.initWidget(root); initFace(root); initRecord(root); initGallery(root); } public void setup(PanelCallback callback){ this.mCallback = callback; } private void initFace(View root) { final View facePanel =mFacePanel = root.findViewById(R.id.lay_panel_face); View backspace = root.findViewById(R.id.im_backspace); backspace.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { PanelCallback callback = mCallback; if(callback == null) return; //模拟键盘删除 KeyEvent event= new KeyEvent(0, 0, 0, KeyEvent.KEYCODE_DEL, 0, 0, 0, 0, KeyEvent.KEYCODE_ENDCALL); callback.getInputEditText().dispatchKeyEvent(event); } }); TabLayout tabLayout = facePanel.findViewById(R.id.tab); ViewPager viewPager = facePanel.findViewById(R.id.pager); tabLayout.setupWithViewPager(viewPager); //表情显示48dp final int minFaceSize = (int) Ui.dipToPx(getResources(),48); int totalScreen = UiTool.getScreenWidth(getActivity()); final int spanCount = totalScreen/minFaceSize; viewPager.setAdapter(new PagerAdapter() { @Override public int getCount() { return Face.getAll(getContext())==null? 0:Face.getAll(getContext()).size(); } @Override public boolean isViewFromObject(@NonNull View view, @NonNull Object object) { return view == object; } @NonNull @Override public Object instantiateItem(@NonNull ViewGroup container, int position) { LayoutInflater inflater = LayoutInflater.from(getContext()); RecyclerView recyclerView = (RecyclerView) inflater.inflate(R.layout.layout_face_content, container, false); recyclerView.setLayoutManager(new GridLayoutManager(getContext(),spanCount)); List<Face.Bean> faces = Face.getAll(getContext()).get(position).faces; FaceAdapter faceAdapter = new FaceAdapter(faces, new RecyclerAdapter.ViewHolder.AdapterListenerImpl<Face.Bean>() { @Override public void onItemClick(RecyclerAdapter.ViewHolder holder, Face.Bean bean) { if (mCallback == null){ return; } EditText editText = mCallback.getInputEditText(); Face.inputFace(getContext(),editText.getText(),bean,(int)(editText.getTextSize()+Ui.dipToPx(getResources(),2))); } }); recyclerView.setAdapter(faceAdapter); container.addView(recyclerView); return recyclerView; } @Override public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { // super.destroyItem(container, position, object); container.removeView((View) object); } @Nullable @Override public CharSequence getPageTitle(int position) { return Face.getAll(getContext()).get(position).name; } }); } public void showFace() { mRecordPanel.setVisibility(View.GONE); mGalleryPanel.setVisibility(View.GONE); mFacePanel.setVisibility(View.VISIBLE); } public void showRecord(){ mRecordPanel.setVisibility(View.VISIBLE); mGalleryPanel.setVisibility(View.GONE); mFacePanel.setVisibility(View.GONE); } public void showGallery(){ mRecordPanel.setVisibility(View.GONE); mGalleryPanel.setVisibility(View.VISIBLE); mFacePanel.setVisibility(View.GONE); } private void initRecord(View root) { final View recordView = mRecordPanel = root.findViewById(R.id.lay_panel_record); AudioRecordView audioRecordView = root.findViewById(R.id.view_audio_record); File tmpFile = Application.getAudioTmpFile(true); final AudioRecordHelper helper= new AudioRecordHelper(tmpFile, new AudioRecordHelper.RecordCallback() { @Override public void onRecordStart() { } @Override public void onProgress(long time) { } @Override public void onRecordDone(File file, long time) { //时间小于1s 不发送 if(time<1000){ return; } //更改为一个发送录音的文件 File audioFile = Application.getAudioTmpFile(false); if (file.renameTo(audioFile)){ if(mCallback != null){ mCallback.onRecordDone(audioFile,time); } } } }); //audioView 初始化 audioRecordView.setup(new AudioRecordView.Callback() { @Override public void requestStartRecord() { helper.recordAsync(); } @Override public void requestStopRecord(int type) { switch (type){ case AudioRecordView.END_TYPE_CANCEL: case AudioRecordView.END_TYPE_DELETE: helper.stop(true); break; case AudioRecordView.END_TYPE_NONE: case AudioRecordView.END_TYPE_PLAY: helper.stop(false); break; } } }); } private void initGallery(View root) { final View galleryPanel= mGalleryPanel = root.findViewById(R.id.lay_panel_gallery); final GalleryView galleryView=galleryPanel.findViewById(R.id.view_gallery); final TextView selectSize = galleryPanel.findViewById(R.id.txt_gallery_select_count); galleryView.setup(getLoaderManager(), new GalleryView.SelectedChangeListener() { @Override public void onSelectedCountChanged(int count) { String sizeStr = getText(R.string.label_gallery_selected_size).toString(); selectSize.setText(String.format(sizeStr,count)); } }); galleryPanel.findViewById(R.id.btn_send).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onGallerySendClick(galleryView,galleryView.getSelectedPath()); } }); } private void onGallerySendClick(GalleryView galleryView, String[] selectedPath) { galleryView.clear(); PanelCallback callback = mCallback; if(mCallback == null){ return; } callback.onSendGallery(selectedPath); } // 回调聊天界面的Callback public interface PanelCallback { EditText getInputEditText(); // 返回需要发送的图片 void onSendGallery(String[] paths); // 返回录音文件和时常 void onRecordDone(File file, long time); } }
8,852
0.605631
0.603113
254
33.401573
28.225403
136
false
false
0
0
0
0
0
0
0.531496
false
false
10
b3420648b2124a9da889b74847fb2702deec42c9
14,602,888,862,472
2c57a8d6549b0299998622f0ddd3317835bd1076
/src/com/giszo/zeppelin/ui/library/AlbumAdapter.java
8f4e30a5d0b19fb76c96d12c58e11e95ff6f5df1
[]
no_license
giszo/zeppelin-android
https://github.com/giszo/zeppelin-android
5168c8e15af1f1ec5e986b90c26987594079e282
7166832f754ce2189e9eb68c65efbcd2557e2bc8
refs/heads/master
2021-01-20T05:58:34.496000
2014-02-02T21:22:48
2014-02-02T21:22:48
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.giszo.zeppelin.ui.library; import java.util.ArrayList; import java.util.List; import com.giszo.zeppelin.R; import com.giszo.zeppelin.utils.TimeFormatter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Filter; import android.widget.TextView; public class AlbumAdapter extends ArrayAdapter<Album> { private List<Album> albums; public AlbumAdapter(Context context) { super(context, R.layout.library_album_item); } public void set(List<Album> albums) { this.albums = albums; clear(); addAll(albums); } @Override public Filter getFilter() { return new AlbumFilter(); } @Override public View getView(int position, View convertView, ViewGroup group) { Album album = getItem(position); View view = LayoutInflater.from(getContext()).inflate(R.layout.library_album_item, null); TextView name = (TextView)view.findViewById(R.id.library_album_item_name); TextView description = (TextView)view.findViewById(R.id.library_album_item_descriptipn); // set name name.setText(album.getName()); // set description StringBuilder sb = new StringBuilder(); sb.append(getContext().getResources().getQuantityString(R.plurals.number_of_songs, album.getSongs(), album.getSongs())); sb.append(", "); sb.append(TimeFormatter.format(album.getLength())); description.setText(sb.toString()); return view; } private class AlbumFilter extends Filter { @Override protected FilterResults performFiltering(CharSequence constraint) { String filter = constraint.toString().toLowerCase(); FilterResults res = new FilterResults(); if (constraint == null || constraint.length() == 0) { res.values = albums; res.count = albums.size(); } else { List<Album> filtered = new ArrayList<Album>(); for (Album album : albums) { if (album.getName().toLowerCase().contains(filter)) filtered.add(album); } res.values = filtered; res.count = filtered.size(); } return res; } @Override protected void publishResults(CharSequence constraint, FilterResults results) { clear(); addAll((List<Album>)results.values); notifyDataSetChanged(); } } }
UTF-8
Java
2,298
java
AlbumAdapter.java
Java
[]
null
[]
package com.giszo.zeppelin.ui.library; import java.util.ArrayList; import java.util.List; import com.giszo.zeppelin.R; import com.giszo.zeppelin.utils.TimeFormatter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Filter; import android.widget.TextView; public class AlbumAdapter extends ArrayAdapter<Album> { private List<Album> albums; public AlbumAdapter(Context context) { super(context, R.layout.library_album_item); } public void set(List<Album> albums) { this.albums = albums; clear(); addAll(albums); } @Override public Filter getFilter() { return new AlbumFilter(); } @Override public View getView(int position, View convertView, ViewGroup group) { Album album = getItem(position); View view = LayoutInflater.from(getContext()).inflate(R.layout.library_album_item, null); TextView name = (TextView)view.findViewById(R.id.library_album_item_name); TextView description = (TextView)view.findViewById(R.id.library_album_item_descriptipn); // set name name.setText(album.getName()); // set description StringBuilder sb = new StringBuilder(); sb.append(getContext().getResources().getQuantityString(R.plurals.number_of_songs, album.getSongs(), album.getSongs())); sb.append(", "); sb.append(TimeFormatter.format(album.getLength())); description.setText(sb.toString()); return view; } private class AlbumFilter extends Filter { @Override protected FilterResults performFiltering(CharSequence constraint) { String filter = constraint.toString().toLowerCase(); FilterResults res = new FilterResults(); if (constraint == null || constraint.length() == 0) { res.values = albums; res.count = albums.size(); } else { List<Album> filtered = new ArrayList<Album>(); for (Album album : albums) { if (album.getName().toLowerCase().contains(filter)) filtered.add(album); } res.values = filtered; res.count = filtered.size(); } return res; } @Override protected void publishResults(CharSequence constraint, FilterResults results) { clear(); addAll((List<Album>)results.values); notifyDataSetChanged(); } } }
2,298
0.71758
0.717145
88
25.113636
24.824581
122
false
false
0
0
0
0
0
0
2.227273
false
false
10
da382ad1dd84b422f487850db6c04abb73d3596c
16,466,904,618,177
0b84f7f3a2ecc41b8a99bebc89b6c30cb7095431
/Source/LifeCheckerAS/app/src/main/java/dei/isep/lifechecker/lifeCheckerMain.java
c4f38deec639884cdde2bece9eae2d95accdd47f
[]
no_license
askpt/SIMOV
https://github.com/askpt/SIMOV
fe0e6f60d4ed4e1666e5730f6cf892d1f05b6afc
5a17dba5facdb7e8ae72b3939d0ac2ccec667d80
refs/heads/master
2020-02-26T14:52:27.721000
2015-01-16T10:39:00
2015-01-16T10:39:00
27,091,497
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dei.isep.lifechecker; import dei.isep.lifechecker.database.alertaBDD; import dei.isep.lifechecker.database.estadoMarcacaoBDD; import dei.isep.lifechecker.databaseonline.alertaHttp; import dei.isep.lifechecker.databaseonline.estadoMarcacaoHttp; import dei.isep.lifechecker.json.alertaJson; import dei.isep.lifechecker.json.estadoMarcacaoJson; import dei.isep.lifechecker.model.alerta; import dei.isep.lifechecker.model.estadoMarcacao; import dei.isep.lifechecker.other.preferenciasAplicacao; import android.app.Activity; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.os.Handler; import android.view.Gravity; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.Timer; import java.util.TimerTask; public class lifeCheckerMain extends Activity { Intent intent = null; ArrayList<estadoMarcacao> listaEstMar; ArrayList<alerta> listaAlerta; ProgressBar pbLoadingInicial; TextView txtView; TimerTask mTimerTask; Timer t = new Timer(); final Handler handler = new Handler(); @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.home); pbLoadingInicial =(ProgressBar) findViewById(R.id.loading_home_aplication_respconta_loading); txtView = (TextView) findViewById(R.id.home_txt_bem_vindo); inicialisar(); } private void inicialisar() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); preferenciasAplicacao prefApp = new preferenciasAplicacao(getApplicationContext()); int configuracao = prefApp.getTipoUser(); if(configuracao == 1 || configuracao == 2 || networkInfo != null) { if(mTimerTask!=null){ mTimerTask.cancel(); } txtView.setText(getResources().getString(R.string.configuracao_inicial)); configuracaoPrimeiro(); } else { txtView.setText(getResources().getString(R.string.erro_sem_net)); Toast toast = Toast.makeText(this,getResources().getString(R.string.toat_des_sec_reverific),Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, 250); toast.show(); timerNoNet(); } } protected void timerNoNet() { mTimerTask = new TimerTask() { @Override public void run() { handler.post(new Runnable() { @Override public void run() { inicialisar(); } }); } }; t.schedule(mTimerTask,50000); } private void configuracaoPrimeiro() { Intent novaActivity; preferenciasAplicacao prefApp = new preferenciasAplicacao(getApplicationContext()); int configuracao = prefApp.getTipoUser(); //0 = configuração (após instalação da aplicação) //1 = vista resposnavel; //2 = vista paciente //3 = Depois de carregar em "sair" ou ter inserido estados de marcações switch (configuracao) { case 0: preencherEstadosMarcacoes(); break; case 1: novaActivity = new Intent(lifeCheckerMain.this, responsavelMenu.class); startActivity(novaActivity); break; case 2: novaActivity = new Intent(lifeCheckerMain.this, pacienteMenu.class); startActivity(novaActivity); break; case 3: novaActivity = new Intent(lifeCheckerMain.this, configuracaoMenu.class); startActivity(novaActivity); break; } } public void preencherEstadosMarcacoes() { estadoMarcacaoHttp estMarHttp = new estadoMarcacaoHttp(); estMarHttp.retornarEstadosMarcacoes(recuperarEstamarcacao); } public void preencherTiposAlertas() { alertaHttp alertHttp = new alertaHttp(); alertHttp.retornarTiposAlertas(recuperarAlerta); } interfaceResultadoAsyncPost recuperarEstamarcacao = new interfaceResultadoAsyncPost() { @Override public void obterResultado(final int codigo, final String conteudo) { runOnUiThread(new Runnable() { @Override public void run() { if (codigo == 1 && conteudo.length() > 10) { estadoMarcacaoJson estMarcJson = new estadoMarcacaoJson(conteudo); listaEstMar = estMarcJson.transformJsonEstadoMarcacao(); estadoMarcacaoBDD estMarBDD = new estadoMarcacaoBDD(getApplicationContext()); for (int i = 0; i < listaEstMar.size(); i++) { estMarBDD.inserirEstadoMarcacaoComId(listaEstMar.get(i)); } preencherTiposAlertas(); } } }); } }; interfaceResultadoAsyncPost recuperarAlerta = new interfaceResultadoAsyncPost() { @Override public void obterResultado(final int codigo, final String conteudo) { runOnUiThread(new Runnable() { @Override public void run() { if (codigo == 1 && conteudo.length() > 10) { alertaJson alertJson= new alertaJson(conteudo); listaAlerta = alertJson.transformJsonAlertas(); alertaBDD alrtBdd = new alertaBDD(getApplicationContext()); for (int i = 0; i < listaAlerta.size(); i++) { alrtBdd.inserirAlertaId(listaAlerta.get(i)); } preferenciasAplicacao prefApp = new preferenciasAplicacao(getApplicationContext()); prefApp.setTipoUser(3); Intent Activity = new Intent(lifeCheckerMain.this, configuracaoMenu.class); startActivity(Activity); } } }); } }; }
UTF-8
Java
6,490
java
lifeCheckerMain.java
Java
[]
null
[]
package dei.isep.lifechecker; import dei.isep.lifechecker.database.alertaBDD; import dei.isep.lifechecker.database.estadoMarcacaoBDD; import dei.isep.lifechecker.databaseonline.alertaHttp; import dei.isep.lifechecker.databaseonline.estadoMarcacaoHttp; import dei.isep.lifechecker.json.alertaJson; import dei.isep.lifechecker.json.estadoMarcacaoJson; import dei.isep.lifechecker.model.alerta; import dei.isep.lifechecker.model.estadoMarcacao; import dei.isep.lifechecker.other.preferenciasAplicacao; import android.app.Activity; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.os.Handler; import android.view.Gravity; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.Timer; import java.util.TimerTask; public class lifeCheckerMain extends Activity { Intent intent = null; ArrayList<estadoMarcacao> listaEstMar; ArrayList<alerta> listaAlerta; ProgressBar pbLoadingInicial; TextView txtView; TimerTask mTimerTask; Timer t = new Timer(); final Handler handler = new Handler(); @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.home); pbLoadingInicial =(ProgressBar) findViewById(R.id.loading_home_aplication_respconta_loading); txtView = (TextView) findViewById(R.id.home_txt_bem_vindo); inicialisar(); } private void inicialisar() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); preferenciasAplicacao prefApp = new preferenciasAplicacao(getApplicationContext()); int configuracao = prefApp.getTipoUser(); if(configuracao == 1 || configuracao == 2 || networkInfo != null) { if(mTimerTask!=null){ mTimerTask.cancel(); } txtView.setText(getResources().getString(R.string.configuracao_inicial)); configuracaoPrimeiro(); } else { txtView.setText(getResources().getString(R.string.erro_sem_net)); Toast toast = Toast.makeText(this,getResources().getString(R.string.toat_des_sec_reverific),Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, 250); toast.show(); timerNoNet(); } } protected void timerNoNet() { mTimerTask = new TimerTask() { @Override public void run() { handler.post(new Runnable() { @Override public void run() { inicialisar(); } }); } }; t.schedule(mTimerTask,50000); } private void configuracaoPrimeiro() { Intent novaActivity; preferenciasAplicacao prefApp = new preferenciasAplicacao(getApplicationContext()); int configuracao = prefApp.getTipoUser(); //0 = configuração (após instalação da aplicação) //1 = vista resposnavel; //2 = vista paciente //3 = Depois de carregar em "sair" ou ter inserido estados de marcações switch (configuracao) { case 0: preencherEstadosMarcacoes(); break; case 1: novaActivity = new Intent(lifeCheckerMain.this, responsavelMenu.class); startActivity(novaActivity); break; case 2: novaActivity = new Intent(lifeCheckerMain.this, pacienteMenu.class); startActivity(novaActivity); break; case 3: novaActivity = new Intent(lifeCheckerMain.this, configuracaoMenu.class); startActivity(novaActivity); break; } } public void preencherEstadosMarcacoes() { estadoMarcacaoHttp estMarHttp = new estadoMarcacaoHttp(); estMarHttp.retornarEstadosMarcacoes(recuperarEstamarcacao); } public void preencherTiposAlertas() { alertaHttp alertHttp = new alertaHttp(); alertHttp.retornarTiposAlertas(recuperarAlerta); } interfaceResultadoAsyncPost recuperarEstamarcacao = new interfaceResultadoAsyncPost() { @Override public void obterResultado(final int codigo, final String conteudo) { runOnUiThread(new Runnable() { @Override public void run() { if (codigo == 1 && conteudo.length() > 10) { estadoMarcacaoJson estMarcJson = new estadoMarcacaoJson(conteudo); listaEstMar = estMarcJson.transformJsonEstadoMarcacao(); estadoMarcacaoBDD estMarBDD = new estadoMarcacaoBDD(getApplicationContext()); for (int i = 0; i < listaEstMar.size(); i++) { estMarBDD.inserirEstadoMarcacaoComId(listaEstMar.get(i)); } preencherTiposAlertas(); } } }); } }; interfaceResultadoAsyncPost recuperarAlerta = new interfaceResultadoAsyncPost() { @Override public void obterResultado(final int codigo, final String conteudo) { runOnUiThread(new Runnable() { @Override public void run() { if (codigo == 1 && conteudo.length() > 10) { alertaJson alertJson= new alertaJson(conteudo); listaAlerta = alertJson.transformJsonAlertas(); alertaBDD alrtBdd = new alertaBDD(getApplicationContext()); for (int i = 0; i < listaAlerta.size(); i++) { alrtBdd.inserirAlertaId(listaAlerta.get(i)); } preferenciasAplicacao prefApp = new preferenciasAplicacao(getApplicationContext()); prefApp.setTipoUser(3); Intent Activity = new Intent(lifeCheckerMain.this, configuracaoMenu.class); startActivity(Activity); } } }); } }; }
6,490
0.604073
0.599753
191
32.931938
28.764444
124
false
false
0
0
0
0
0
0
0.602094
false
false
10
da9e782fcd828eca01652cfc8626bca03c78f86a
15,152,644,620,824
ed5159d056e98d6715357d0d14a9b3f20b764f89
/src/irvine/oeis/a013/A013690.java
6dfd2c44147a577ff5944104a7e4c1235716fcb6
[]
no_license
flywind2/joeis
https://github.com/flywind2/joeis
c5753169cf562939b04dd246f8a2958e97f74558
e5efd6971a0062ac99f4fae21a7c78c9f9e74fea
refs/heads/master
2020-09-13T18:34:35.080000
2019-11-19T05:40:55
2019-11-19T05:40:55
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package irvine.oeis.a013; import irvine.oeis.ContinuedFractionSequence; /** * A013690 Continued fraction for <code>zeta(14)</code>. * @author Sean A. Irvine */ public class A013690 extends ContinuedFractionSequence { /** Construct the sequence. */ public A013690() { super(new A013672()); } }
UTF-8
Java
309
java
A013690.java
Java
[ { "context": "ued fraction for <code>zeta(14)</code>.\n * @author Sean A. Irvine\n */\npublic class A013690 extends ContinuedFractio", "end": 160, "score": 0.9998931288719177, "start": 146, "tag": "NAME", "value": "Sean A. Irvine" } ]
null
[]
package irvine.oeis.a013; import irvine.oeis.ContinuedFractionSequence; /** * A013690 Continued fraction for <code>zeta(14)</code>. * @author <NAME> */ public class A013690 extends ContinuedFractionSequence { /** Construct the sequence. */ public A013690() { super(new A013672()); } }
301
0.705502
0.61165
15
19.6
19.767988
56
false
false
0
0
0
0
0
0
0.2
false
false
10
3ad9889ebdf508bb04697a1305188c4ada717b0a
2,611,340,179,440
c4623aa95fb8cdd0ee1bc68962711c33af44604e
/src/com/yelp/android/ai/e.java
4be387bdcc3933c70e7e5416b2f2c692724b64b2
[]
no_license
reverseengineeringer/com.yelp.android
https://github.com/reverseengineeringer/com.yelp.android
48f7f2c830a3a1714112649a6a0a3110f7bdc2b1
b0ac8d4f6cd5fc5543f0d8de399b6d7b3a2184c8
refs/heads/master
2021-01-19T02:07:25.997000
2016-07-19T16:37:24
2016-07-19T16:37:24
38,555,675
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yelp.android.ai; import com.bumptech.glide.load.engine.i; public class e<Z> implements c<Z, Z> { private static final e<?> a = new e(); public static <Z> c<Z, Z> b() { return a; } public i<Z> a(i<Z> parami) { return parami; } public String a() { return ""; } } /* Location: * Qualified Name: com.yelp.android.ai.e * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
UTF-8
Java
441
java
e.java
Java
[]
null
[]
package com.yelp.android.ai; import com.bumptech.glide.load.engine.i; public class e<Z> implements c<Z, Z> { private static final e<?> a = new e(); public static <Z> c<Z, Z> b() { return a; } public i<Z> a(i<Z> parami) { return parami; } public String a() { return ""; } } /* Location: * Qualified Name: com.yelp.android.ai.e * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
441
0.571429
0.555556
30
13.733334
13.798389
44
false
false
0
0
0
0
0
0
0.266667
false
false
10
71d3cb99af4f9f97d9880335df49bd87d7ed492f
1,460,288,907,550
01f0c6eda2208ebf6b7bbffa42d2b611e9d9685b
/PT15314_WEB_MOB1014/src/Slide5/Student.java
83f82434bf9a009cf91ab851d50b9b4fdea10e40
[]
no_license
dungna29/PT15314-WEB
https://github.com/dungna29/PT15314-WEB
f6c6018deb3c5bb31d92a10bfbedddfedc209dc3
a910b70a6e14d1828f04885457fb0bc5d9898afc
refs/heads/master
2020-12-05T20:56:54.853000
2020-03-16T06:52:12
2020-03-16T06:52:12
232,245,330
1
3
null
false
2020-01-07T08:56:46
2020-01-07T04:55:00
2020-01-07T08:34:42
2020-01-07T08:34:40
17
0
1
1
Java
false
false
/* * 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 Slide5; /** * * @author Nguyen Anh Dung */ public class Student implements Comparable<Student>{ private String tenSV; private String monSV; private int tuoiSV; public Student() { } public Student(String tenSV, String monSV, int tuoiSV) { this.tenSV = tenSV; this.monSV = monSV; this.tuoiSV = tuoiSV; } public String getTenSV() { return tenSV; } public void setTenSV(String tenSV) { this.tenSV = tenSV; } public String getMonSV() { return monSV; } public void setMonSV(String monSV) { this.monSV = monSV; } public int getTuoiSV() { return tuoiSV; } public void setTuoiSV(int tuoiSV) { this.tuoiSV = tuoiSV; } @Override public int compareTo(Student o) { // return this.tenSV.compareTo(o.getTenSV());//Sắp xếp xuôi từ bé đến lớn // return -this.tenSV.compareTo(o.getTenSV());Sắp xếp ngược và sử với chuỗi if (this.tuoiSV > o.getTuoiSV()) { return -1; }else if(this.tuoiSV < o.getTuoiSV()){ return 1; }else{ return 0; } } }
UTF-8
Java
1,459
java
Student.java
Java
[ { "context": "itor.\r\n */\r\npackage Slide5;\r\n\r\n/**\r\n *\r\n * @author Nguyen Anh Dung\r\n */\r\npublic class Student implements Comparable<", "end": 244, "score": 0.9998540282249451, "start": 229, "tag": "NAME", "value": "Nguyen Anh Dung" } ]
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 Slide5; /** * * @author <NAME> */ public class Student implements Comparable<Student>{ private String tenSV; private String monSV; private int tuoiSV; public Student() { } public Student(String tenSV, String monSV, int tuoiSV) { this.tenSV = tenSV; this.monSV = monSV; this.tuoiSV = tuoiSV; } public String getTenSV() { return tenSV; } public void setTenSV(String tenSV) { this.tenSV = tenSV; } public String getMonSV() { return monSV; } public void setMonSV(String monSV) { this.monSV = monSV; } public int getTuoiSV() { return tuoiSV; } public void setTuoiSV(int tuoiSV) { this.tuoiSV = tuoiSV; } @Override public int compareTo(Student o) { // return this.tenSV.compareTo(o.getTenSV());//Sắp xếp xuôi từ bé đến lớn // return -this.tenSV.compareTo(o.getTenSV());Sắp xếp ngược và sử với chuỗi if (this.tuoiSV > o.getTuoiSV()) { return -1; }else if(this.tuoiSV < o.getTuoiSV()){ return 1; }else{ return 0; } } }
1,450
0.562151
0.559358
62
21.096775
20.72221
82
false
false
0
0
0
0
0
0
0.370968
false
false
10
0f1576323499016bff056046ef2d42e66b8889cc
27,839,978,079,120
ca030864a3a1c24be6b9d1802c2353da4ca0d441
/classes10.dex_source_from_JADX/com/facebook/ads/internal/thirdparty/http/C1970m.java
39e904eeb111ac98ed7c7b5469da4f991a3f5b20
[]
no_license
pxson001/facebook-app
https://github.com/pxson001/facebook-app
87aa51e29195eeaae69adeb30219547f83a5b7b1
640630f078980f9818049625ebc42569c67c69f7
refs/heads/master
2020-04-07T20:36:45.758000
2018-03-07T09:04:57
2018-03-07T09:04:57
124,208,458
4
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.facebook.ads.internal.thirdparty.http; public class C1970m extends Exception { public C1971n f14293a; public C1970m(Exception exception, C1971n c1971n) { super(exception); this.f14293a = c1971n; } public final C1971n m14434a() { return this.f14293a; } }
UTF-8
Java
313
java
C1970m.java
Java
[]
null
[]
package com.facebook.ads.internal.thirdparty.http; public class C1970m extends Exception { public C1971n f14293a; public C1970m(Exception exception, C1971n c1971n) { super(exception); this.f14293a = c1971n; } public final C1971n m14434a() { return this.f14293a; } }
313
0.667732
0.514377
14
21.357143
18.748741
55
true
false
0
0
0
0
0
0
0.428571
false
false
10
f372d8c1742ab2ff1de65246d43e822b6407db80
21,182,778,754,998
d01ec13bbc934182423043bf020d762eb76d3956
/array/TargetArrayintheGivenOrder.java
782f12ad82f1cd812dbeb59373fb936884903741
[]
no_license
cindyycheungg/LeetCode
https://github.com/cindyycheungg/LeetCode
227b1d25d3ef8149a9f7d59dd66ad5fee3e5798b
df7b075d2d952445f240d7de7ae1fd7ed79583bf
refs/heads/master
2021-05-25T22:28:46.777000
2020-09-24T02:29:50
2020-09-24T02:29:50
253,947,164
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
class Solution { public int[] createTargetArray(int[] nums, int[] index) { LinkedList<Integer> target = new LinkedList<>(); int[] targ = new int[nums.length]; // added the elements in nums in the correct order for(int i = 0; i < index.length; i++) target.add(index[i], nums[i]); // add(index, object) //moving linked list to final answer array for(int i = 0; i < target.size(); i++) targ[i]= target.get(i); return targ; } }
UTF-8
Java
489
java
TargetArrayintheGivenOrder.java
Java
[]
null
[]
class Solution { public int[] createTargetArray(int[] nums, int[] index) { LinkedList<Integer> target = new LinkedList<>(); int[] targ = new int[nums.length]; // added the elements in nums in the correct order for(int i = 0; i < index.length; i++) target.add(index[i], nums[i]); // add(index, object) //moving linked list to final answer array for(int i = 0; i < target.size(); i++) targ[i]= target.get(i); return targ; } }
489
0.584867
0.580777
11
43.545456
28.892792
98
false
false
0
0
0
0
0
0
1.272727
false
false
10
d17e6a589f036598da0cb277e665dfee2654bc57
13,108,240,247,428
49c668f9f95fe6e4601c3fe161e45932ebcbb6f6
/__backup/jdk8-boot2-beetlsql-hikaricp-layui-plus-xiandafu-2018-admin/admin-console/src/main/java/com/ibeetl/admin/console/service/FunctionConsoleService.java
3a5eda804d47b9b8d940a0e7d298ed5d6d83793f
[ "BSD-3-Clause" ]
permissive
service-java/summer-cli-beetlsql
https://github.com/service-java/summer-cli-beetlsql
9f4ad4e2fe79654faec38a28edb41ea6c7984a01
b6e25e644a2af79d374537f1a11d80a406167da2
refs/heads/master
2020-05-31T16:33:15.825000
2020-05-22T04:30:08
2020-05-22T04:30:08
190,384,189
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ibeetl.admin.console.service; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.beetl.sql.core.engine.PageQuery; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.ibeetl.admin.console.dao.FunctionConsoleDao; import com.ibeetl.admin.console.dao.RoleFunctionConsoleDao; import com.ibeetl.admin.console.controller.dto.RoleDataAccessFunctionDTO; import com.ibeetl.admin.core.dao.CoreMenuDao; import com.ibeetl.admin.core.dao.CoreRoleMenuDao; import com.ibeetl.admin.core.entity.CoreFunction; import com.ibeetl.admin.core.entity.CoreMenu; import com.ibeetl.admin.core.entity.CoreRoleFunction; import com.ibeetl.admin.core.entity.CoreRoleMenu; import com.ibeetl.admin.core.rbac.tree.FunctionItem; import com.ibeetl.admin.core.service.BaseService; import com.ibeetl.admin.core.service.CorePlatformService; import com.ibeetl.admin.core.util.PlatformException; /** * @author lijiazhi */ @Service @Transactional public class FunctionConsoleService extends BaseService<CoreFunction> { @Autowired FunctionConsoleDao functionDao; @Autowired CoreMenuDao menuDao; @Autowired RoleFunctionConsoleDao roleFunctionConsoleDao; @Autowired CoreRoleMenuDao sysRoleMenuDao; @Autowired CorePlatformService platformService; public void queryByCondtion(PageQuery<CoreFunction> query) { functionDao.queryByCondtion(query); List<CoreFunction> list = query.getList(); this.queryListAfter(list); //处理父功能名称显示 FunctionItem root = platformService.buildFunction(); for (CoreFunction function : list) { Long parentId = function.getParentId(); String name = ""; if (parentId != 0) { FunctionItem item = root.findChild(parentId); name = item != null ? item.getName() : ""; } function.set("parentFunctionText", name); } } public Long saveFunction(CoreFunction function) { functionDao.insert(function, true); platformService.clearFunctionCache(); return function.getId(); } /** * 删除功能点,跟菜单有关联的无法删除,删除功能点导致所有缓存都需要更新 * * @param functionId * @return */ public void deleteFunction(Long functionId) { deleteFunctionId(functionId); platformService.clearFunctionCache(); } public void batchDeleteFunction(List<Long> functionIds) { for (Long id : functionIds) { deleteFunctionId(id); } platformService.clearFunctionCache(); } public void updateFunction(CoreFunction function) { functionDao.updateById(function); platformService.clearFunctionCache(); } public CoreFunction getFunction(Long functionId) { return functionDao.unique(functionId); } public CoreFunction getFunction(String code) { CoreFunction query = new CoreFunction(); query.setCode(code); CoreFunction db = functionDao.templateOne(query); return db; } /** * 得到角色对应的所有功能点 * * @param roleId * @return */ public List<Long> getFunctionByRole(Long roleId) { return this.roleFunctionConsoleDao.getFunctionIdByRole(roleId); } /** * 得到角色对应的所有数据权限功能点 * * @param roleId * @return */ public List<RoleDataAccessFunctionDTO> getQueryFunctionByRole(Long roleId) { return this.roleFunctionConsoleDao.getQueryFunctionAndRoleData(roleId); } /** * 更新角色对应的功能点所有, * * @param roleId * @param data,必须包含id,和 dataAcerssType,采用模板更新 */ public void updateFunctionAccessByRole(List<RoleDataAccessFunctionDTO> data) { for (RoleDataAccessFunctionDTO fun : data) { Long roleId = fun.getRoleId(); Long functionId = fun.getId(); int accessType = fun.getDataAccessType(); CoreRoleFunction template = new CoreRoleFunction(); template.setRoleId(roleId); template.setFunctionId(functionId); CoreRoleFunction ret = roleFunctionConsoleDao.templateOne(template); if (ret != null) { ret.setDataAccessType(accessType); roleFunctionConsoleDao.updateById(ret); } else { template.setDataAccessType(accessType); template.setCreateTime(new Date()); roleFunctionConsoleDao.insert(template); } } } /** * 给角色赋予功能同时,根据赋予的功能权限,更新能访问的菜单 * * @param adds * @param updates * @param dels * @return 返回增加的项的id,用于前端 */ public void updateSysRoleFunction(Long roleId, List<Long> adds, List<Long> dels) { for (Long del : dels) { //获得功能关联的菜单 CoreRoleFunction temp = new CoreRoleFunction(); temp.setRoleId(roleId); temp.setFunctionId(del); CoreRoleFunction roleFunction = roleFunctionConsoleDao.templateOne(temp); if (roleFunction == null) { throw new PlatformException("已经被删除了RoleId=" + roleId + " functionId=" + del); } CoreMenu menu = queryFunctionMenu(roleFunction.getFunctionId()); roleFunctionConsoleDao.deleteById(roleFunction.getId()); if (menu != null) { //同时,需要删除与此功能关联的菜单 CoreRoleMenu sysRoleMenu = querySysRoleMenu(roleFunction.getRoleId(), menu.getId()); if (sysRoleMenu != null) { sysRoleMenuDao.deleteById(sysRoleMenu.getId()); } } } for (Long add : adds) { CoreRoleFunction function = new CoreRoleFunction(); function.setCreateTime(new Date()); function.setRoleId(roleId); function.setFunctionId(add); this.sqlManager.insert(function); CoreMenu menu = queryFunctionMenu(add); if (menu != null) { //同时,需要增加菜单 CoreRoleMenu roleMenu = new CoreRoleMenu(); roleMenu.setMenuId(menu.getId()); roleMenu.setRoleId(roleId); sysRoleMenuDao.insert(roleMenu); } } //清楚缓存 platformService.clearFunctionCache(); } private CoreMenu queryFunctionMenu(Long functionId) { CoreMenu query = new CoreMenu(); query.setFunctionId(functionId); List<CoreMenu> menus = menuDao.template(query); return menus.isEmpty() ? null : menus.get(0); } private CoreRoleMenu querySysRoleMenu(Long roleId, Long menuId) { CoreRoleMenu query = new CoreRoleMenu(); query.setMenuId(menuId); query.setRoleId(roleId); List<CoreRoleMenu> menus = sysRoleMenuDao.template(query); return menus.isEmpty() ? null : menus.get(0); } /** * 删除某一个功能点及其子功能,对应的role-function 需要删除,菜单对应的function需要设置成空 * * @param functionId */ private void deleteFunctionId(Long functionId) { FunctionItem root = platformService.buildFunction(); FunctionItem fun = root.findChild(functionId); List<FunctionItem> all = fun.findAllItem(); //也删除自身 all.add(fun); realDeleteFunction(all); } private void realDeleteFunction(List<FunctionItem> all) { List<Long> ids = new ArrayList<>(all.size()); for (FunctionItem item : all) { ids.add(item.getId()); this.functionDao.deleteById(item.getId()); } //删除角色和功能的关系 this.roleFunctionConsoleDao.deleteRoleFunction(ids); //设置菜单对应的功能项为空 menuDao.clearMenuFunction(ids); } }
UTF-8
Java
8,307
java
FunctionConsoleService.java
Java
[ { "context": "admin.core.util.PlatformException;\n\n/**\n * @author lijiazhi\n */\n@Service\n@Transactional\npublic class Function", "end": 1062, "score": 0.9994202256202698, "start": 1054, "tag": "USERNAME", "value": "lijiazhi" } ]
null
[]
package com.ibeetl.admin.console.service; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.beetl.sql.core.engine.PageQuery; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.ibeetl.admin.console.dao.FunctionConsoleDao; import com.ibeetl.admin.console.dao.RoleFunctionConsoleDao; import com.ibeetl.admin.console.controller.dto.RoleDataAccessFunctionDTO; import com.ibeetl.admin.core.dao.CoreMenuDao; import com.ibeetl.admin.core.dao.CoreRoleMenuDao; import com.ibeetl.admin.core.entity.CoreFunction; import com.ibeetl.admin.core.entity.CoreMenu; import com.ibeetl.admin.core.entity.CoreRoleFunction; import com.ibeetl.admin.core.entity.CoreRoleMenu; import com.ibeetl.admin.core.rbac.tree.FunctionItem; import com.ibeetl.admin.core.service.BaseService; import com.ibeetl.admin.core.service.CorePlatformService; import com.ibeetl.admin.core.util.PlatformException; /** * @author lijiazhi */ @Service @Transactional public class FunctionConsoleService extends BaseService<CoreFunction> { @Autowired FunctionConsoleDao functionDao; @Autowired CoreMenuDao menuDao; @Autowired RoleFunctionConsoleDao roleFunctionConsoleDao; @Autowired CoreRoleMenuDao sysRoleMenuDao; @Autowired CorePlatformService platformService; public void queryByCondtion(PageQuery<CoreFunction> query) { functionDao.queryByCondtion(query); List<CoreFunction> list = query.getList(); this.queryListAfter(list); //处理父功能名称显示 FunctionItem root = platformService.buildFunction(); for (CoreFunction function : list) { Long parentId = function.getParentId(); String name = ""; if (parentId != 0) { FunctionItem item = root.findChild(parentId); name = item != null ? item.getName() : ""; } function.set("parentFunctionText", name); } } public Long saveFunction(CoreFunction function) { functionDao.insert(function, true); platformService.clearFunctionCache(); return function.getId(); } /** * 删除功能点,跟菜单有关联的无法删除,删除功能点导致所有缓存都需要更新 * * @param functionId * @return */ public void deleteFunction(Long functionId) { deleteFunctionId(functionId); platformService.clearFunctionCache(); } public void batchDeleteFunction(List<Long> functionIds) { for (Long id : functionIds) { deleteFunctionId(id); } platformService.clearFunctionCache(); } public void updateFunction(CoreFunction function) { functionDao.updateById(function); platformService.clearFunctionCache(); } public CoreFunction getFunction(Long functionId) { return functionDao.unique(functionId); } public CoreFunction getFunction(String code) { CoreFunction query = new CoreFunction(); query.setCode(code); CoreFunction db = functionDao.templateOne(query); return db; } /** * 得到角色对应的所有功能点 * * @param roleId * @return */ public List<Long> getFunctionByRole(Long roleId) { return this.roleFunctionConsoleDao.getFunctionIdByRole(roleId); } /** * 得到角色对应的所有数据权限功能点 * * @param roleId * @return */ public List<RoleDataAccessFunctionDTO> getQueryFunctionByRole(Long roleId) { return this.roleFunctionConsoleDao.getQueryFunctionAndRoleData(roleId); } /** * 更新角色对应的功能点所有, * * @param roleId * @param data,必须包含id,和 dataAcerssType,采用模板更新 */ public void updateFunctionAccessByRole(List<RoleDataAccessFunctionDTO> data) { for (RoleDataAccessFunctionDTO fun : data) { Long roleId = fun.getRoleId(); Long functionId = fun.getId(); int accessType = fun.getDataAccessType(); CoreRoleFunction template = new CoreRoleFunction(); template.setRoleId(roleId); template.setFunctionId(functionId); CoreRoleFunction ret = roleFunctionConsoleDao.templateOne(template); if (ret != null) { ret.setDataAccessType(accessType); roleFunctionConsoleDao.updateById(ret); } else { template.setDataAccessType(accessType); template.setCreateTime(new Date()); roleFunctionConsoleDao.insert(template); } } } /** * 给角色赋予功能同时,根据赋予的功能权限,更新能访问的菜单 * * @param adds * @param updates * @param dels * @return 返回增加的项的id,用于前端 */ public void updateSysRoleFunction(Long roleId, List<Long> adds, List<Long> dels) { for (Long del : dels) { //获得功能关联的菜单 CoreRoleFunction temp = new CoreRoleFunction(); temp.setRoleId(roleId); temp.setFunctionId(del); CoreRoleFunction roleFunction = roleFunctionConsoleDao.templateOne(temp); if (roleFunction == null) { throw new PlatformException("已经被删除了RoleId=" + roleId + " functionId=" + del); } CoreMenu menu = queryFunctionMenu(roleFunction.getFunctionId()); roleFunctionConsoleDao.deleteById(roleFunction.getId()); if (menu != null) { //同时,需要删除与此功能关联的菜单 CoreRoleMenu sysRoleMenu = querySysRoleMenu(roleFunction.getRoleId(), menu.getId()); if (sysRoleMenu != null) { sysRoleMenuDao.deleteById(sysRoleMenu.getId()); } } } for (Long add : adds) { CoreRoleFunction function = new CoreRoleFunction(); function.setCreateTime(new Date()); function.setRoleId(roleId); function.setFunctionId(add); this.sqlManager.insert(function); CoreMenu menu = queryFunctionMenu(add); if (menu != null) { //同时,需要增加菜单 CoreRoleMenu roleMenu = new CoreRoleMenu(); roleMenu.setMenuId(menu.getId()); roleMenu.setRoleId(roleId); sysRoleMenuDao.insert(roleMenu); } } //清楚缓存 platformService.clearFunctionCache(); } private CoreMenu queryFunctionMenu(Long functionId) { CoreMenu query = new CoreMenu(); query.setFunctionId(functionId); List<CoreMenu> menus = menuDao.template(query); return menus.isEmpty() ? null : menus.get(0); } private CoreRoleMenu querySysRoleMenu(Long roleId, Long menuId) { CoreRoleMenu query = new CoreRoleMenu(); query.setMenuId(menuId); query.setRoleId(roleId); List<CoreRoleMenu> menus = sysRoleMenuDao.template(query); return menus.isEmpty() ? null : menus.get(0); } /** * 删除某一个功能点及其子功能,对应的role-function 需要删除,菜单对应的function需要设置成空 * * @param functionId */ private void deleteFunctionId(Long functionId) { FunctionItem root = platformService.buildFunction(); FunctionItem fun = root.findChild(functionId); List<FunctionItem> all = fun.findAllItem(); //也删除自身 all.add(fun); realDeleteFunction(all); } private void realDeleteFunction(List<FunctionItem> all) { List<Long> ids = new ArrayList<>(all.size()); for (FunctionItem item : all) { ids.add(item.getId()); this.functionDao.deleteById(item.getId()); } //删除角色和功能的关系 this.roleFunctionConsoleDao.deleteRoleFunction(ids); //设置菜单对应的功能项为空 menuDao.clearMenuFunction(ids); } }
8,307
0.635841
0.635458
256
29.582031
24.10364
100
false
false
0
0
0
0
0
0
0.433594
false
false
10
a820223712ba7ae16f90f064eea73dd6119f917d
29,094,108,506,093
aba9d958c486e53d4ea80cf2bd876161c4473676
/Java/Esercizi/ContoBancario/v1.0/src/com/company/Account.java
736e88eda2d4c91268a7ed3da2778aba44f98055
[]
no_license
zaninifrancesco/Exercise
https://github.com/zaninifrancesco/Exercise
fd3128798ae3e9f0ccc197689c46fef5ed237d23
b5ac21a26de76f74ce78ab2595ecbc6efd3bacf3
refs/heads/main
2023-05-15T15:48:46.693000
2021-05-23T20:25:01
2021-05-23T20:25:01
305,166,981
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.company; public class Account { private String name; private int numAccount; private int amount; public Account(String n, int numAccount, int amount){ this.amount = amount; this.numAccount = numAccount; this.name = n; } public int getAmount() { return amount; } public void deposita(int amountToDeposit){ this.amount += amountToDeposit; } public void prelieva(int amountToWithdrawn){ this.amount -= amountToWithdrawn; } public void showAccountInfo(){ System.out.println("ACCOUNT NAME: " + this.name + "\nACCOUNT NUMBER " + this.numAccount + "\nAMOUNT AVAILABLE: " + this.amount); } public int getNumAccount(){ return numAccount; } }
UTF-8
Java
778
java
Account.java
Java
[]
null
[]
package com.company; public class Account { private String name; private int numAccount; private int amount; public Account(String n, int numAccount, int amount){ this.amount = amount; this.numAccount = numAccount; this.name = n; } public int getAmount() { return amount; } public void deposita(int amountToDeposit){ this.amount += amountToDeposit; } public void prelieva(int amountToWithdrawn){ this.amount -= amountToWithdrawn; } public void showAccountInfo(){ System.out.println("ACCOUNT NAME: " + this.name + "\nACCOUNT NUMBER " + this.numAccount + "\nAMOUNT AVAILABLE: " + this.amount); } public int getNumAccount(){ return numAccount; } }
778
0.625964
0.625964
35
21.228571
25.756092
136
false
false
0
0
0
0
0
0
0.4
false
false
10
4ad86d3563ff4ea2565dc8d33c57a9602685f584
11,725,260,765,196
8d0db4a2a852cf3df50036930638194b3440f387
/src/com/simple1c/ui/DataSourcesToolWindow.java
f3a6e5bab8aee3fd2a3125e1bc2eed47d5ee5d15
[]
no_license
khorevaa/intellij-1c
https://github.com/khorevaa/intellij-1c
f99ca04abf97792d5991e69740275a0b4f8f60dc
aa412fd471932b35675d43974300c688d3c1b31f
refs/heads/master
2021-06-10T07:50:22.594000
2017-01-27T00:04:20
2017-01-27T00:04:20
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.simple1c.ui; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.SimpleToolWindowPanel; import com.intellij.openapi.wm.ToolWindow; import com.intellij.ui.PopupHandler; import com.intellij.ui.components.JBList; import com.intellij.ui.content.ContentManager; import com.intellij.util.containers.ContainerUtil; import com.simple1c.dataSources.DataSource; import com.simple1c.dataSources.DataSourceStorage; import com.simple1c.ui.Actions.MyActionConstants; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.Comparator; import java.util.List; public class DataSourcesToolWindow //extend this because DataProvider implementation must be in the control tree extends SimpleToolWindowPanel implements DataProvider { private final DataSourceStorage dataSourceStorage; private JPanel content; private JBList dataSourcesList; private final List<AnAction> actions; public static DataKey<DataSource> DataSourceKey = DataKey.create("SelectedDataSource"); public DataSourcesToolWindow(Project project, List<AnAction> actions) { super(true, true); this.dataSourceStorage = DataSourceStorage.instance(project); this.actions = actions; } public void initContent(@NotNull ToolWindow toolWindow) { ContentManager contentManager = toolWindow.getContentManager(); JComponent component = createComponent(); toolWindow.getContentManager().addContent(contentManager.getFactory().createContent(component, "", true)); } private JComponent createComponent() { dataSourcesList.setEmptyText("Click 'Add' to create a data source"); setDataSources(ContainerUtil.sorted(dataSourceStorage.getAll(), Comparator.comparing(DataSource::getName))); dataSourceStorage.addUpdateListener(this::setDataSources); ActionManager actionManager = ActionManager.getInstance(); final ActionToolbar actionToolbar = actionManager .createActionToolbar(ActionPlaces.UNKNOWN, (ActionGroup) actionManager.getAction(MyActionConstants.Groups.DataSourcesToolbar), true); actionToolbar.setTargetComponent(this.content); setContent(content); setToolbar(actionToolbar.getComponent()); DefaultActionGroup popupActionGroup = new DefaultActionGroup(); popupActionGroup.addAll(actions); PopupHandler.installPopupHandler(dataSourcesList, popupActionGroup, ActionPlaces.UNKNOWN, actionManager); return getComponent(); } private void setDataSources(@NotNull Iterable<DataSource> dataSources) { List<ListItem> listItems = ContainerUtil.map(dataSources, dataSource -> { ListItem listItem = new ListItem(); listItem.DisplayName = dataSource.getName(); listItem.DataSource = dataSource; return listItem; }); ListItem[] result = new ListItem[listItems.size()]; listItems.toArray(result); //noinspection unchecked dataSourcesList.setListData(result); } @Nullable @Override public Object getData(@NonNls String dataId) { if (DataSourceKey.is(dataId)) return ((ListItem) dataSourcesList.getModel() .getElementAt(dataSourcesList.getSelectedIndex())).DataSource; return null; } private class ListItem { String DisplayName; DataSource DataSource; @Override public String toString() { return DisplayName; } } }
UTF-8
Java
3,707
java
DataSourcesToolWindow.java
Java
[]
null
[]
package com.simple1c.ui; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.SimpleToolWindowPanel; import com.intellij.openapi.wm.ToolWindow; import com.intellij.ui.PopupHandler; import com.intellij.ui.components.JBList; import com.intellij.ui.content.ContentManager; import com.intellij.util.containers.ContainerUtil; import com.simple1c.dataSources.DataSource; import com.simple1c.dataSources.DataSourceStorage; import com.simple1c.ui.Actions.MyActionConstants; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.Comparator; import java.util.List; public class DataSourcesToolWindow //extend this because DataProvider implementation must be in the control tree extends SimpleToolWindowPanel implements DataProvider { private final DataSourceStorage dataSourceStorage; private JPanel content; private JBList dataSourcesList; private final List<AnAction> actions; public static DataKey<DataSource> DataSourceKey = DataKey.create("SelectedDataSource"); public DataSourcesToolWindow(Project project, List<AnAction> actions) { super(true, true); this.dataSourceStorage = DataSourceStorage.instance(project); this.actions = actions; } public void initContent(@NotNull ToolWindow toolWindow) { ContentManager contentManager = toolWindow.getContentManager(); JComponent component = createComponent(); toolWindow.getContentManager().addContent(contentManager.getFactory().createContent(component, "", true)); } private JComponent createComponent() { dataSourcesList.setEmptyText("Click 'Add' to create a data source"); setDataSources(ContainerUtil.sorted(dataSourceStorage.getAll(), Comparator.comparing(DataSource::getName))); dataSourceStorage.addUpdateListener(this::setDataSources); ActionManager actionManager = ActionManager.getInstance(); final ActionToolbar actionToolbar = actionManager .createActionToolbar(ActionPlaces.UNKNOWN, (ActionGroup) actionManager.getAction(MyActionConstants.Groups.DataSourcesToolbar), true); actionToolbar.setTargetComponent(this.content); setContent(content); setToolbar(actionToolbar.getComponent()); DefaultActionGroup popupActionGroup = new DefaultActionGroup(); popupActionGroup.addAll(actions); PopupHandler.installPopupHandler(dataSourcesList, popupActionGroup, ActionPlaces.UNKNOWN, actionManager); return getComponent(); } private void setDataSources(@NotNull Iterable<DataSource> dataSources) { List<ListItem> listItems = ContainerUtil.map(dataSources, dataSource -> { ListItem listItem = new ListItem(); listItem.DisplayName = dataSource.getName(); listItem.DataSource = dataSource; return listItem; }); ListItem[] result = new ListItem[listItems.size()]; listItems.toArray(result); //noinspection unchecked dataSourcesList.setListData(result); } @Nullable @Override public Object getData(@NonNls String dataId) { if (DataSourceKey.is(dataId)) return ((ListItem) dataSourcesList.getModel() .getElementAt(dataSourcesList.getSelectedIndex())).DataSource; return null; } private class ListItem { String DisplayName; DataSource DataSource; @Override public String toString() { return DisplayName; } } }
3,707
0.722147
0.721068
92
39.29348
28.572386
116
false
false
0
0
0
0
0
0
0.706522
false
false
10