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
e8b02107076bd456937c60c3b12251978292fe3e
6,279,242,204,641
7c3e769ad1e036004fcd47540d018524d8cf69c4
/bogoLive/src/main/java/com/bogokj/dynamic/modle/DynamicInfoModel.java
e9ae7adf3b0667b6786cca5b3fa8586515a2eadc
[]
no_license
zkbqhuang/bogo_live_android
https://github.com/zkbqhuang/bogo_live_android
b813ed99f7237f4dd2e77014c311bc8da74ecbf9
a51799fa7038f089b10209e7ec446a0000a68d8a
refs/heads/master
2022-07-06T15:29:08.344000
2020-05-11T03:11:12
2020-05-11T03:11:12
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bogokj.dynamic.modle; import com.bogokj.hybrid.model.BaseActModel; public class DynamicInfoModel extends BaseActModel { private DynamicModel data; public DynamicModel getData() { return data; } public void setData(DynamicModel data) { this.data = data; } }
UTF-8
Java
309
java
DynamicInfoModel.java
Java
[]
null
[]
package com.bogokj.dynamic.modle; import com.bogokj.hybrid.model.BaseActModel; public class DynamicInfoModel extends BaseActModel { private DynamicModel data; public DynamicModel getData() { return data; } public void setData(DynamicModel data) { this.data = data; } }
309
0.695793
0.695793
15
19.6
18.445595
52
false
false
0
0
0
0
0
0
0.333333
false
false
3
292258cd176388a90c75f3ac8ca2f5482919aaff
23,897,198,045,411
60eaea35ae1523318cbccddc86565ba1713fb1d8
/jfaster-admin/src/main/java/com/abocode/jfaster/admin/system/service/UserService.java
8710c5832611b238c93b0d9d8edd53808c6348fc
[ "Apache-2.0" ]
permissive
abocode/jfaster
https://github.com/abocode/jfaster
61c278721bf3e7704bd3e505e2270d82a89e9b26
7cb5ebb309fad4acf5f74b7556e142e368b5a55e
refs/heads/development3.0
2022-11-30T18:43:10.056000
2020-09-23T12:35:59
2020-09-23T12:35:59
117,775,785
2
1
Apache-2.0
false
2022-11-24T09:35:43
2018-01-17T03:03:18
2020-09-23T12:37:16
2022-11-24T09:35:40
46,884
2
1
7
JavaScript
false
false
package com.abocode.jfaster.admin.system.service; import com.abocode.jfaster.admin.system.dto.ExlUserDto; import com.abocode.jfaster.api.system.UserDto; import com.abocode.jfaster.core.common.model.json.ComboBox; import com.abocode.jfaster.core.persistence.hibernate.qbc.CriteriaQuery; import com.abocode.jfaster.core.repository.DataGridData; import com.abocode.jfaster.core.repository.DataGridParam; import com.abocode.jfaster.system.entity.User; import org.springframework.web.multipart.MultipartFile; import java.util.List; import java.util.Map; public interface UserService { String getMenus(User u); Object getAll(); void restPassword(String id, String password); void updatePwd(User user, String password, String newPassword); void lockById(String id); List<ComboBox> findComboBox(String id, String[] fields); CriteriaQuery buildCq(User user, DataGridParam dataGridParam, String orgIds); void del(String id); void saveUser(User user, String roleId, String password, String orgIds); void importFile(Map<String, MultipartFile> fileMap); List<ExlUserDto> findExportUserList(User user, String orgIds, DataGridParam dataGridParam); DataGridData findDataGridData(UserDto userDto, String departid, DataGridParam dataGridParam); }
UTF-8
Java
1,292
java
UserService.java
Java
[]
null
[]
package com.abocode.jfaster.admin.system.service; import com.abocode.jfaster.admin.system.dto.ExlUserDto; import com.abocode.jfaster.api.system.UserDto; import com.abocode.jfaster.core.common.model.json.ComboBox; import com.abocode.jfaster.core.persistence.hibernate.qbc.CriteriaQuery; import com.abocode.jfaster.core.repository.DataGridData; import com.abocode.jfaster.core.repository.DataGridParam; import com.abocode.jfaster.system.entity.User; import org.springframework.web.multipart.MultipartFile; import java.util.List; import java.util.Map; public interface UserService { String getMenus(User u); Object getAll(); void restPassword(String id, String password); void updatePwd(User user, String password, String newPassword); void lockById(String id); List<ComboBox> findComboBox(String id, String[] fields); CriteriaQuery buildCq(User user, DataGridParam dataGridParam, String orgIds); void del(String id); void saveUser(User user, String roleId, String password, String orgIds); void importFile(Map<String, MultipartFile> fileMap); List<ExlUserDto> findExportUserList(User user, String orgIds, DataGridParam dataGridParam); DataGridData findDataGridData(UserDto userDto, String departid, DataGridParam dataGridParam); }
1,292
0.786378
0.786378
40
31.299999
30.605719
97
false
false
0
0
0
0
0
0
0.925
false
false
3
62b67d2f1a4b9ada63d0d22ed6da096a4dd47716
5,102,421,205,064
e4a1010e91212e3538ae9af11fefe20ebb22b5c7
/src/test/java/klobid/steps/definition/HubungiKamiDefs.java
3d606b136c11fa1d443da682a1026545bb0afa6d
[]
no_license
YudhiPrasetyo/klobautomationproject
https://github.com/YudhiPrasetyo/klobautomationproject
675664d8a3547aee024742709c9647072ef6477c
c5e2b8150dad907542daa4063e6e0b6f57a8fc43
refs/heads/master
2020-05-09T20:51:02.276000
2019-04-16T05:31:34
2019-04-16T05:31:34
181,422,358
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package klobid.steps.definition; import cucumber.api.PendingException; import cucumber.api.java.en.And; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import klobid.steps.enduserstep.HubungiKamiStep; import net.thucydides.core.annotations.Steps; public class HubungiKamiDefs { @Steps HubungiKamiStep hubungiKamiStep; @When("^user klik link hubungi kami$") public void userKlikLinkHubungiKami() { hubungiKamiStep.klikContactUs(); } @Then("^user seharusnya melihat form hubungi kami$") public void userSeharusnyaMelihatFormHubungiKami() { hubungiKamiStep.formHubungiKami(); } @When("^user klik field emailContactUs \"([^\"]*)\"$") public void userKlikFieldEmailContactUs(String emailContactUs) { hubungiKamiStep.emailContactUs(emailContactUs); } @And("^klik button jenis pertanyaan$") public void klikButtonJenisPertanyaan() { hubungiKamiStep.buttonJenis(); } @Then("^muncul dropdown jenis pertanyaan$") public void munculDropdownJenisPertanyaan() { hubungiKamiStep.popUpJenis(); } @When("^user pilih saran$") public void userPilihSaran() { hubungiKamiStep.pilihSaran(); } @And("^user input detail pesan \"([^\"]*)\"$") public void userInputDetailPesan(String detailIsiPesan){ hubungiKamiStep.detailPesan(detailIsiPesan); } @And("^user upload foto contact us$") public void userUploadFotoContactUs() { hubungiKamiStep.pilihFile(); } @And("^klik button kirim pesan$") public void klikButtonKirimPesan() { hubungiKamiStep.btnKlikContatcUs(); } @Then("^muncul text terima kasih telah menghubungi kami$") public void munculTextTerimaKasihTelahMenghubungiKami() { hubungiKamiStep.containSukses(); } @When("^user klik button lihat tiket anda$") public void userKlikButtonLihatTiketAnda() { hubungiKamiStep.klikBtnLihatTiketAnda(); } @Then("^user seharusnya melihat form lihat tiket anda$") public void userSeharusnyaMelihatFormLihatTiketAnda() { hubungiKamiStep.formLihatTiketAnda(); } @When("^user input nomor tiket \"([^\"]*)\"$") public void userInputNomorTiket(String nomorTiket) { hubungiKamiStep.inputNomorTiket(nomorTiket); } @And("^user input email tiket \"([^\"]*)\"$") public void userInputEmailTiket(String emailTiket) { hubungiKamiStep.inputEmailTiket(emailTiket); } @And("^user klik button cari tiket$") public void userKlikButtonCariTiket() { hubungiKamiStep.klikBtnCariTiket(); } @Then("^user seharusnya melihat form tiket result$") public void userSeharusnyaMelihatFormTiketResult() { hubungiKamiStep.formDetailTiket(); } @When("^user tambah detail pesan \"([^\"]*)\"$") public void userTambahDetailPesan(String detailPesan) { hubungiKamiStep.txtComment(detailPesan); } @And("^user klik button kirim pesan$") public void userKlikButtonKirimPesan() { hubungiKamiStep.btnSendComment(); } @Then("^user seharusnya melihat komentar berhasil di muat$") public void userSeharusnyaMelihatKomentarBerhasilDiMuat() { hubungiKamiStep.resultPesan(); } @When("^user klik button tutup$") public void userKlikButtonTutup() { hubungiKamiStep.btnClose(); } @Then("^user seharusnya melihat status tiket close$") public void userSeharusnyaMelihatStatusTiketClose() { hubungiKamiStep.statusClosed(); } @Then("^user seharusnya melihat error message$") public void userSeharusnyaMelihatErrorMessage() { hubungiKamiStep.errorMessage(); } @Then("^muncul alert tiket tidak di temukan$") public void munculAlertTiketTidakDiTemukan() { hubungiKamiStep.popUpAlert(); } }
UTF-8
Java
3,873
java
HubungiKamiDefs.java
Java
[]
null
[]
package klobid.steps.definition; import cucumber.api.PendingException; import cucumber.api.java.en.And; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import klobid.steps.enduserstep.HubungiKamiStep; import net.thucydides.core.annotations.Steps; public class HubungiKamiDefs { @Steps HubungiKamiStep hubungiKamiStep; @When("^user klik link hubungi kami$") public void userKlikLinkHubungiKami() { hubungiKamiStep.klikContactUs(); } @Then("^user seharusnya melihat form hubungi kami$") public void userSeharusnyaMelihatFormHubungiKami() { hubungiKamiStep.formHubungiKami(); } @When("^user klik field emailContactUs \"([^\"]*)\"$") public void userKlikFieldEmailContactUs(String emailContactUs) { hubungiKamiStep.emailContactUs(emailContactUs); } @And("^klik button jenis pertanyaan$") public void klikButtonJenisPertanyaan() { hubungiKamiStep.buttonJenis(); } @Then("^muncul dropdown jenis pertanyaan$") public void munculDropdownJenisPertanyaan() { hubungiKamiStep.popUpJenis(); } @When("^user pilih saran$") public void userPilihSaran() { hubungiKamiStep.pilihSaran(); } @And("^user input detail pesan \"([^\"]*)\"$") public void userInputDetailPesan(String detailIsiPesan){ hubungiKamiStep.detailPesan(detailIsiPesan); } @And("^user upload foto contact us$") public void userUploadFotoContactUs() { hubungiKamiStep.pilihFile(); } @And("^klik button kirim pesan$") public void klikButtonKirimPesan() { hubungiKamiStep.btnKlikContatcUs(); } @Then("^muncul text terima kasih telah menghubungi kami$") public void munculTextTerimaKasihTelahMenghubungiKami() { hubungiKamiStep.containSukses(); } @When("^user klik button lihat tiket anda$") public void userKlikButtonLihatTiketAnda() { hubungiKamiStep.klikBtnLihatTiketAnda(); } @Then("^user seharusnya melihat form lihat tiket anda$") public void userSeharusnyaMelihatFormLihatTiketAnda() { hubungiKamiStep.formLihatTiketAnda(); } @When("^user input nomor tiket \"([^\"]*)\"$") public void userInputNomorTiket(String nomorTiket) { hubungiKamiStep.inputNomorTiket(nomorTiket); } @And("^user input email tiket \"([^\"]*)\"$") public void userInputEmailTiket(String emailTiket) { hubungiKamiStep.inputEmailTiket(emailTiket); } @And("^user klik button cari tiket$") public void userKlikButtonCariTiket() { hubungiKamiStep.klikBtnCariTiket(); } @Then("^user seharusnya melihat form tiket result$") public void userSeharusnyaMelihatFormTiketResult() { hubungiKamiStep.formDetailTiket(); } @When("^user tambah detail pesan \"([^\"]*)\"$") public void userTambahDetailPesan(String detailPesan) { hubungiKamiStep.txtComment(detailPesan); } @And("^user klik button kirim pesan$") public void userKlikButtonKirimPesan() { hubungiKamiStep.btnSendComment(); } @Then("^user seharusnya melihat komentar berhasil di muat$") public void userSeharusnyaMelihatKomentarBerhasilDiMuat() { hubungiKamiStep.resultPesan(); } @When("^user klik button tutup$") public void userKlikButtonTutup() { hubungiKamiStep.btnClose(); } @Then("^user seharusnya melihat status tiket close$") public void userSeharusnyaMelihatStatusTiketClose() { hubungiKamiStep.statusClosed(); } @Then("^user seharusnya melihat error message$") public void userSeharusnyaMelihatErrorMessage() { hubungiKamiStep.errorMessage(); } @Then("^muncul alert tiket tidak di temukan$") public void munculAlertTiketTidakDiTemukan() { hubungiKamiStep.popUpAlert(); } }
3,873
0.683966
0.683966
134
27.902985
22.888721
68
false
false
0
0
0
0
0
0
0.231343
false
false
3
3d9d6853728f8a3c5b8d5f17402983e23a07748d
15,659,450,822,871
8e4627e93c942be284546ede14e1a8e6c5e3ac4e
/POO_MauroTalamantes/src/poo/Camara.java
6936efb49d9e13923e61cefbb9a114d54066aa72
[]
no_license
MauroTalamantes/POO_MauroTalamantes
https://github.com/MauroTalamantes/POO_MauroTalamantes
94dc1c50d43dda85c538a1cfba16643a2222bc3b
d038f7c1b2de9bb7958fc640dbdec6a5f82696fb
refs/heads/master
2020-07-04T10:47:04.823000
2019-12-02T17:14:25
2019-12-02T17:14:25
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/**/ package poo; /** * Crear objetos * @author Mauro Talamantes Villagrana */ public class Camara { private String marca; private double precio; private String software; private double peso; private double calidad; public Camara(){ marca = "Desconocido"; precio = 0; software = "Desconocido"; peso = 0; calidad = 0; } public Camara(String marca, double precio, String software, double peso, double calidad ){ this.marca = marca; this.precio = precio; this.software = software; this.peso = peso; this.calidad = calidad; } public void saludar(){ System.out.println("Hola mundo"); } public String getCamara (){ return this.marca; }; public void setCamara (String marca){ this.marca=marca; }; public double getCamara1 (){ return this.precio; }; public void setCamara (double precio){ this.precio=precio; }; public String getCamara2 (){ return this.software; }; public void setCamara1 (String software){ this.software=software; }; public double getCamara3 (){ return this.peso; }; public void setCamara2 (double peso){ this.peso=peso; }; public double getCamara4 (){ return this.calidad; }; public void setCamara3 (double calidad){ this.calidad=calidad; }; }
UTF-8
Java
1,659
java
Camara.java
Java
[ { "context": "\npackage poo;\r\n\r\n/**\r\n * Crear objetos\r\n * @author Mauro Talamantes Villagrana\r\n */\r\npublic class Camara {\r\n \r\n private St", "end": 91, "score": 0.9998573064804077, "start": 64, "tag": "NAME", "value": "Mauro Talamantes Villagrana" } ]
null
[]
/**/ package poo; /** * Crear objetos * @author <NAME> */ public class Camara { private String marca; private double precio; private String software; private double peso; private double calidad; public Camara(){ marca = "Desconocido"; precio = 0; software = "Desconocido"; peso = 0; calidad = 0; } public Camara(String marca, double precio, String software, double peso, double calidad ){ this.marca = marca; this.precio = precio; this.software = software; this.peso = peso; this.calidad = calidad; } public void saludar(){ System.out.println("Hola mundo"); } public String getCamara (){ return this.marca; }; public void setCamara (String marca){ this.marca=marca; }; public double getCamara1 (){ return this.precio; }; public void setCamara (double precio){ this.precio=precio; }; public String getCamara2 (){ return this.software; }; public void setCamara1 (String software){ this.software=software; }; public double getCamara3 (){ return this.peso; }; public void setCamara2 (double peso){ this.peso=peso; }; public double getCamara4 (){ return this.calidad; }; public void setCamara3 (double calidad){ this.calidad=calidad; }; }
1,638
0.514165
0.508137
73
20.561644
13.834626
50
false
false
0
0
0
0
0
0
0.561644
false
false
3
43a0419af2f0282bd49177f0fa8c887e46f700df
12,927,851,629,256
80fc0b633a3498d9dce830008a11ab70b1dfb245
/src/test/java/hope/back/server/web/property/register/PropertyRegistrationTest.java
d126a8bb65b59fbd43296234fff263d38dc863e5
[]
no_license
apstergGitHub/kerberos
https://github.com/apstergGitHub/kerberos
2bcdb019b8ef2c473fbd58eb666b8642dc220307
4cfc4e719d15ab58142e1d7cbd63f9b412b25193
refs/heads/master
2021-07-04T08:21:56.490000
2019-03-20T17:31:08
2019-03-20T17:31:08
133,170,113
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package hope.back.server.web.property.register; import hope.back.AbstractTestCase; import io.vertx.core.json.JsonObject; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.RunTestOnContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import io.vertx.rxjava.core.Vertx; import io.vertx.rxjava.ext.web.client.WebClient; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; import static org.apache.commons.lang3.RandomStringUtils.randomNumeric; @RunWith(VertxUnitRunner.class) public class PropertyRegistrationTest extends AbstractTestCase { private static final String USER_ID = randomAlphanumeric(8); private static final String PRICE_PER_NIGHT = randomNumeric(8); @Rule public RunTestOnContext rule = new RunTestOnContext(); @Before public void setUp(TestContext context) { super.setUp(); new Vertx(rule.vertx()) .deployVerticle( PropertyRegistration.class.getName(), context.asyncAssertSuccess()); } @Test public void whenEventResponseIsSuccessfulReturn201(TestContext context) { final Async async = context.async(); final Vertx vertx = new Vertx(rule.vertx()); final WebClient client = WebClient.create(vertx); vertx.eventBus().consumer("property-registration", msg -> msg.reply("any")); client.post(8091, "localhost", "/property/register") .putHeader("Content-Type", "application/json") .rxSendJsonObject(new JsonObject().put("userId", "215155").put("username", "testUsername")) .subscribe(resp -> { context.assertEquals(201, resp.statusCode()); async.complete(); }, error -> context.fail(error.getMessage())); } @Test public void whenEventResponseIsFailureReturn400(TestContext context) { final Async async = context.async(); final Vertx vertx = new Vertx(rule.vertx()); final WebClient client = WebClient.create(vertx); vertx.eventBus().consumer("property-registration", msg -> msg.fail(400, "failure")); client.post(8091, "localhost", "/property/register") .putHeader("Content-Type", "application/json") .rxSendJsonObject(new JsonObject().put("userId", "215155").put("username", "testUsername")) .subscribe(resp -> { context.assertEquals(400, resp.statusCode()); async.complete(); }, error -> context.fail(error.getMessage())); } @Test public void eventSentBasedOnBody(TestContext context) { final Async async = context.async(); final Vertx vertx = new Vertx(rule.vertx()); final WebClient client = WebClient.create(vertx); client.post(8091, "localhost", "/property/register") .putHeader("Content-Type", "application/json") .rxSendJsonObject(new JsonObject().put("userId", USER_ID).put("pricePerNight", PRICE_PER_NIGHT)) .subscribe(); //http://openmymind.net/Multiple-Collections-Versus-Embedded-Documents/#5 //https://stackoverflow.com/questions/5373198/mongodb-relationships-embed-or-reference vertx.eventBus().<JsonObject>consumer("property-registration", msg -> { context.assertEquals(new JsonObject().put("userId", USER_ID).put("pricePerNight", PRICE_PER_NIGHT), msg.body()); msg.reply("any"); async.complete(); }); } }
UTF-8
Java
3,806
java
PropertyRegistrationTest.java
Java
[ { "context": "Object().put(\"userId\", \"215155\").put(\"username\", \"testUsername\"))\n .subscribe(resp -> {\n ", "end": 1759, "score": 0.9994415640830994, "start": 1747, "tag": "USERNAME", "value": "testUsername" }, { "context": "Object().put(\"userId\", \"215155\").put(\"username\", \"testUsername\"))\n .subscribe(resp -> {\n ", "end": 2586, "score": 0.9992954134941101, "start": 2574, "tag": "USERNAME", "value": "testUsername" } ]
null
[]
package hope.back.server.web.property.register; import hope.back.AbstractTestCase; import io.vertx.core.json.JsonObject; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.RunTestOnContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import io.vertx.rxjava.core.Vertx; import io.vertx.rxjava.ext.web.client.WebClient; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; import static org.apache.commons.lang3.RandomStringUtils.randomNumeric; @RunWith(VertxUnitRunner.class) public class PropertyRegistrationTest extends AbstractTestCase { private static final String USER_ID = randomAlphanumeric(8); private static final String PRICE_PER_NIGHT = randomNumeric(8); @Rule public RunTestOnContext rule = new RunTestOnContext(); @Before public void setUp(TestContext context) { super.setUp(); new Vertx(rule.vertx()) .deployVerticle( PropertyRegistration.class.getName(), context.asyncAssertSuccess()); } @Test public void whenEventResponseIsSuccessfulReturn201(TestContext context) { final Async async = context.async(); final Vertx vertx = new Vertx(rule.vertx()); final WebClient client = WebClient.create(vertx); vertx.eventBus().consumer("property-registration", msg -> msg.reply("any")); client.post(8091, "localhost", "/property/register") .putHeader("Content-Type", "application/json") .rxSendJsonObject(new JsonObject().put("userId", "215155").put("username", "testUsername")) .subscribe(resp -> { context.assertEquals(201, resp.statusCode()); async.complete(); }, error -> context.fail(error.getMessage())); } @Test public void whenEventResponseIsFailureReturn400(TestContext context) { final Async async = context.async(); final Vertx vertx = new Vertx(rule.vertx()); final WebClient client = WebClient.create(vertx); vertx.eventBus().consumer("property-registration", msg -> msg.fail(400, "failure")); client.post(8091, "localhost", "/property/register") .putHeader("Content-Type", "application/json") .rxSendJsonObject(new JsonObject().put("userId", "215155").put("username", "testUsername")) .subscribe(resp -> { context.assertEquals(400, resp.statusCode()); async.complete(); }, error -> context.fail(error.getMessage())); } @Test public void eventSentBasedOnBody(TestContext context) { final Async async = context.async(); final Vertx vertx = new Vertx(rule.vertx()); final WebClient client = WebClient.create(vertx); client.post(8091, "localhost", "/property/register") .putHeader("Content-Type", "application/json") .rxSendJsonObject(new JsonObject().put("userId", USER_ID).put("pricePerNight", PRICE_PER_NIGHT)) .subscribe(); //http://openmymind.net/Multiple-Collections-Versus-Embedded-Documents/#5 //https://stackoverflow.com/questions/5373198/mongodb-relationships-embed-or-reference vertx.eventBus().<JsonObject>consumer("property-registration", msg -> { context.assertEquals(new JsonObject().put("userId", USER_ID).put("pricePerNight", PRICE_PER_NIGHT), msg.body()); msg.reply("any"); async.complete(); }); } }
3,806
0.633473
0.620074
94
39.5
30.85441
124
false
false
0
0
0
0
0
0
0.734043
false
false
3
3beb7010124ac9483959b066eb10c5fb4558650b
14,903,536,533,093
f22f449dac170fb7c30ad10622ec5653488a7782
/src/DimaAndConyLine.java
aa4709aeb47b4f06f272f565f8c14abe0ab06abb
[]
no_license
Abkreno/CodeForces
https://github.com/Abkreno/CodeForces
ba64361afac810cc7b5bd8be6e7b7c5da950bc90
124417ebc3009a66d8c5268911c7837b16fb124b
refs/heads/master
2021-01-15T23:07:54.144000
2016-01-15T12:41:39
2016-01-15T12:41:39
35,565,870
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedList; public class DimaAndConyLine { public static void main(String[] args) throws Exception { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(bf.readLine()); int nums[] = new int[n]; int connect[] = new int[n]; LinkedList<Integer> covered[] = new LinkedList[n]; String l[] = bf.readLine().split(" "); for (int i = 0; i < n; i++) { nums[i] = Integer.parseInt(l[i]); connect[i] = nums[i]; } Arrays.sort(nums); int id = 1; boolean flag = false; for (int i = 0; i < n - 1; i++) { int from = Arrays.binarySearch(nums, connect[i]); int to = Arrays.binarySearch(nums, connect[i + 1]); if (covered[from] == null) covered[from] = new LinkedList<Integer>(); if (covered[to] == null) covered[to] = new LinkedList<Integer>(); covered[from].add(id); covered[to].add(id++); if (from > to) { int temp = from; from = to; to = temp; } HashSet<Integer> soFar = new HashSet<Integer>(); for (int j = from + 1; j < to; j++) { if (covered[j] != null) { for (int x : covered[j]) { if (soFar.contains(x)) { soFar.remove(x); } else if (!covered[from].contains(x) && !covered[to].contains(x)) { soFar.add(x); } } } } if (soFar.size() > 0) { flag = true; break; } } System.out.println(flag ? "yes" : "no"); } }
UTF-8
Java
1,538
java
DimaAndConyLine.java
Java
[]
null
[]
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedList; public class DimaAndConyLine { public static void main(String[] args) throws Exception { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(bf.readLine()); int nums[] = new int[n]; int connect[] = new int[n]; LinkedList<Integer> covered[] = new LinkedList[n]; String l[] = bf.readLine().split(" "); for (int i = 0; i < n; i++) { nums[i] = Integer.parseInt(l[i]); connect[i] = nums[i]; } Arrays.sort(nums); int id = 1; boolean flag = false; for (int i = 0; i < n - 1; i++) { int from = Arrays.binarySearch(nums, connect[i]); int to = Arrays.binarySearch(nums, connect[i + 1]); if (covered[from] == null) covered[from] = new LinkedList<Integer>(); if (covered[to] == null) covered[to] = new LinkedList<Integer>(); covered[from].add(id); covered[to].add(id++); if (from > to) { int temp = from; from = to; to = temp; } HashSet<Integer> soFar = new HashSet<Integer>(); for (int j = from + 1; j < to; j++) { if (covered[j] != null) { for (int x : covered[j]) { if (soFar.contains(x)) { soFar.remove(x); } else if (!covered[from].contains(x) && !covered[to].contains(x)) { soFar.add(x); } } } } if (soFar.size() > 0) { flag = true; break; } } System.out.println(flag ? "yes" : "no"); } }
1,538
0.587776
0.583225
57
25.982456
16.68647
75
false
false
0
0
0
0
0
0
3.508772
false
false
3
859463dfb28c66a76749f94e4f09a2a27ec3583b
25,082,609,060,648
0ec9494d780bb818014f2d3c18933d4417040128
/coral-base/coral-common/src/main/java/com/coral/base/common/convert/SimpleJsonTree.java
ff8d5527102150d1e9bf32d5f385779724851d98
[]
no_license
coralloc8/springboot-example
https://github.com/coralloc8/springboot-example
c7e14c3ab0ecac1920365267dc7abb086fcde880
80b80afe4e666c6285f3dd492d436c6f6c03216d
refs/heads/master
2023-02-19T23:54:44.445000
2023-02-13T09:03:40
2023-02-13T09:03:40
274,320,100
1
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.coral.base.common.convert; import java.util.List; import java.util.Map; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * @author huss */ @Data @AllArgsConstructor @NoArgsConstructor public class SimpleJsonTree { private String label; private Object value; // @Default // private boolean joined = false; // @Default // private boolean expand = true; /** * 额外属性 */ private Map<String, Object> extraAttributes; private List<SimpleJsonTree> children; }
UTF-8
Java
567
java
SimpleJsonTree.java
Java
[ { "context": ";\nimport lombok.NoArgsConstructor;\n\n/**\n * @author huss\n */\n@Data\n@AllArgsConstructor\n@NoArgsConstructor\n", "end": 193, "score": 0.9995684623718262, "start": 189, "tag": "USERNAME", "value": "huss" } ]
null
[]
package com.coral.base.common.convert; import java.util.List; import java.util.Map; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * @author huss */ @Data @AllArgsConstructor @NoArgsConstructor public class SimpleJsonTree { private String label; private Object value; // @Default // private boolean joined = false; // @Default // private boolean expand = true; /** * 额外属性 */ private Map<String, Object> extraAttributes; private List<SimpleJsonTree> children; }
567
0.695886
0.695886
31
17.032259
14.418814
48
false
false
0
0
0
0
0
0
0.419355
false
false
3
a78b63ddcb236ee4b26cfe2f263a33b4c2d03c26
18,159,121,760,339
237896cb41adf485d01fdffaa20ad12b9e452913
/src/main/java/com/suraj/employee/rest/service/impl/EmployeeServiceImpl.java
b98860b60eeb96c4641e134f5f0915b213f527f8
[]
no_license
surajtech003/EmployeeCrudRestAppWithDBMySql
https://github.com/surajtech003/EmployeeCrudRestAppWithDBMySql
0e39720f14d8d114307a891bee0faedf2d454cc7
85f26734d3d0fe3966d4a648a04da097b5403fee
refs/heads/master
2020-06-05T21:32:34.232000
2019-06-18T14:04:23
2019-06-18T14:04:23
192,551,726
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.suraj.employee.rest.service.impl; import java.util.List; import java.util.concurrent.CompletableFuture; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; import com.suraj.employee.rest.dao.EmployeeDao; import com.suraj.employee.rest.model.Employee; import com.suraj.employee.rest.service.EmployeeService; @Service public class EmployeeServiceImpl implements EmployeeService { @Autowired private EmployeeDao employeeDao; @Override public Employee getEmployeeById(Integer id) { return employeeDao.getOne(id); } @Override public Employee createEmployee(Employee employee) { return employeeDao.save(employee); } @Override public List<Employee> getAllEmployees() { return employeeDao.findAll(); } @Override public void deleteEmployeeById(Integer id) { employeeDao.delete(id); } @Override public void deleteAllEmployees() { employeeDao.deleteAll(); } @Override public Employee updateEmployeeById(Employee employee, Integer employeeId) { return employeeDao.save(employee); } @Override public List<Employee> findEmployeesByAddress(String address) { //return employeeDao.findByAddress(address); return employeeDao.findEmployeeByAddress(address); } @Override public List<Employee> findEmployeesByAddressAndDept(String address, int deptNum) { //return employeeDao.findByAddressAndDeptNum(address, deptNum); return employeeDao.findEmployeeByAddressAndDeptNum(address, deptNum); } @Override public List<Employee> findEmployeeByDeptNum(int deptNum, PageRequest pageRequest) { return employeeDao.findByDeptNum(deptNum, pageRequest); } @Override public CompletableFuture<Employee> findByAddress(String address) { return employeeDao.findByAddress(address); } @Override public List<Employee> findByEmployeeNameOrAddress(String employeeName, String address) { return employeeDao.findByEmployeeNameOrAddress(employeeName, address); } }
UTF-8
Java
2,021
java
EmployeeServiceImpl.java
Java
[]
null
[]
package com.suraj.employee.rest.service.impl; import java.util.List; import java.util.concurrent.CompletableFuture; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; import com.suraj.employee.rest.dao.EmployeeDao; import com.suraj.employee.rest.model.Employee; import com.suraj.employee.rest.service.EmployeeService; @Service public class EmployeeServiceImpl implements EmployeeService { @Autowired private EmployeeDao employeeDao; @Override public Employee getEmployeeById(Integer id) { return employeeDao.getOne(id); } @Override public Employee createEmployee(Employee employee) { return employeeDao.save(employee); } @Override public List<Employee> getAllEmployees() { return employeeDao.findAll(); } @Override public void deleteEmployeeById(Integer id) { employeeDao.delete(id); } @Override public void deleteAllEmployees() { employeeDao.deleteAll(); } @Override public Employee updateEmployeeById(Employee employee, Integer employeeId) { return employeeDao.save(employee); } @Override public List<Employee> findEmployeesByAddress(String address) { //return employeeDao.findByAddress(address); return employeeDao.findEmployeeByAddress(address); } @Override public List<Employee> findEmployeesByAddressAndDept(String address, int deptNum) { //return employeeDao.findByAddressAndDeptNum(address, deptNum); return employeeDao.findEmployeeByAddressAndDeptNum(address, deptNum); } @Override public List<Employee> findEmployeeByDeptNum(int deptNum, PageRequest pageRequest) { return employeeDao.findByDeptNum(deptNum, pageRequest); } @Override public CompletableFuture<Employee> findByAddress(String address) { return employeeDao.findByAddress(address); } @Override public List<Employee> findByEmployeeNameOrAddress(String employeeName, String address) { return employeeDao.findByEmployeeNameOrAddress(employeeName, address); } }
2,021
0.800099
0.800099
78
24.910257
25.835369
84
false
false
0
0
0
0
0
0
1.217949
false
false
3
2cddf5cace5d54397509f956c411069304e337ca
18,159,121,758,042
943fc926eeb42dd30031e4306860db4a23cc1091
/src/pe/Ventas/package-info.java
67e624466eabb41d015e31a770a546da2e33a1f8
[]
no_license
Francocg/soapventas
https://github.com/Francocg/soapventas
09f2a12fb160535697f34dca13493b996ca3569f
30d4fa29e39e01db2551f939032249f58fa8422e
refs/heads/master
2023-05-01T20:24:45.135000
2021-05-18T02:52:05
2021-05-18T02:52:05
368,381,763
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
@javax.xml.bind.annotation.XmlSchema(namespace = "http://Ventas.pe/") package pe.Ventas;
UTF-8
Java
89
java
package-info.java
Java
[]
null
[]
@javax.xml.bind.annotation.XmlSchema(namespace = "http://Ventas.pe/") package pe.Ventas;
89
0.752809
0.752809
2
43.5
25.5
69
false
false
0
0
0
0
0
0
0.5
false
false
3
deea7c7b0c7bc8ab6a1b70515a29f3121c1c0a87
9,311,489,150,629
2145c58b47ec1bf9fb2c2c50536222f68a9bafaa
/app/src/main/java/com/maxiee/heartbeat/ui/GalleryActivity.java
ed2ddc9f16e1b6976e43c6f2be263c10d344b856
[ "Apache-2.0" ]
permissive
XXpanda/HeartBeat
https://github.com/XXpanda/HeartBeat
98ba1ae6372e35d5eebdc16efd7837fa861eca34
b26d7f5753435f42b57f3750fdcafaf3191064cc
refs/heads/master
2021-01-15T09:23:15.492000
2015-10-24T05:10:27
2015-10-24T05:10:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.maxiee.heartbeat.ui; import android.graphics.Color; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.widget.ImageView; import com.bumptech.glide.Glide; import com.maxiee.heartbeat.R; import com.maxiee.heartbeat.database.api.GetImageByEventKeyApi; import com.maxiee.heartbeat.ui.common.BaseActivity; /** * Created by maxiee on 15-8-26. */ public class GalleryActivity extends BaseActivity { public static final String EVENT_ID = "event_id"; public static final String PATH = "path"; private ImageView mImage; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_gallery); int eventId = getIntent().getIntExtra(EVENT_ID, -1); String path = ""; if (eventId == -1) { path = getIntent().getStringExtra(PATH); } Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setBackgroundColor(Color.BLACK); toolbar.setTitle(""); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); mImage = (ImageView) findViewById(R.id.imageview); if (eventId != -1) { final String imagePath = new GetImageByEventKeyApi(this, eventId).exec(); Glide.with(this).load(imagePath).into(mImage); } else { Glide.with(this).load(path).into(mImage); } } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { this.onBackPressed(); return true; } return super.onOptionsItemSelected(item); } }
UTF-8
Java
1,789
java
GalleryActivity.java
Java
[ { "context": "artbeat.ui.common.BaseActivity;\n\n/**\n * Created by maxiee on 15-8-26.\n */\npublic class GalleryActivity exte", "end": 402, "score": 0.999678373336792, "start": 396, "tag": "USERNAME", "value": "maxiee" } ]
null
[]
package com.maxiee.heartbeat.ui; import android.graphics.Color; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.widget.ImageView; import com.bumptech.glide.Glide; import com.maxiee.heartbeat.R; import com.maxiee.heartbeat.database.api.GetImageByEventKeyApi; import com.maxiee.heartbeat.ui.common.BaseActivity; /** * Created by maxiee on 15-8-26. */ public class GalleryActivity extends BaseActivity { public static final String EVENT_ID = "event_id"; public static final String PATH = "path"; private ImageView mImage; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_gallery); int eventId = getIntent().getIntExtra(EVENT_ID, -1); String path = ""; if (eventId == -1) { path = getIntent().getStringExtra(PATH); } Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setBackgroundColor(Color.BLACK); toolbar.setTitle(""); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); mImage = (ImageView) findViewById(R.id.imageview); if (eventId != -1) { final String imagePath = new GetImageByEventKeyApi(this, eventId).exec(); Glide.with(this).load(imagePath).into(mImage); } else { Glide.with(this).load(path).into(mImage); } } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { this.onBackPressed(); return true; } return super.onOptionsItemSelected(item); } }
1,789
0.659027
0.653997
58
29.844828
22.018646
85
false
false
0
0
0
0
0
0
0.568965
false
false
3
ffe46069944133ceb79bbfbf42886fe71d8d623d
31,353,261,298,197
5636ed4aac1b8f4a15f34feb94ea929f7ecf05b3
/picasa-to-blog/src/main/java/com/axisdesktop/picasatoblog/picasarss/ItemNode.java
c3353705e4319fe4d4c7ac81009251b7aff5bfa8
[]
no_license
fopcoder/com.axisdesktop.picasatoblog
https://github.com/fopcoder/com.axisdesktop.picasatoblog
ce3b0819bf4579859eb37606405aea2985e78671
50d6ff6fec90bf4b9e894a90385ec7e2c7da1f2c
refs/heads/master
2021-01-21T14:04:16.420000
2016-01-29T19:57:20
2016-01-29T19:57:20
40,922,719
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.axisdesktop.picasatoblog.picasarss; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement( name = "item" ) @XmlAccessorType( XmlAccessType.FIELD ) public class ItemNode { private String link; private GroupNode group; public String getLink() { return link; } public void setLink( String link ) { this.link = link; } public GroupNode getGroup() { return group; } public void setGroup( GroupNode group ) { this.group = group; } }
UTF-8
Java
572
java
ItemNode.java
Java
[]
null
[]
package com.axisdesktop.picasatoblog.picasarss; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement( name = "item" ) @XmlAccessorType( XmlAccessType.FIELD ) public class ItemNode { private String link; private GroupNode group; public String getLink() { return link; } public void setLink( String link ) { this.link = link; } public GroupNode getGroup() { return group; } public void setGroup( GroupNode group ) { this.group = group; } }
572
0.748252
0.748252
28
19.428572
17.569105
49
false
false
0
0
0
0
0
0
1
false
false
3
545612d6c3eff3ef0703e78d365e8183594a1533
17,910,013,659,409
1ff65599329bc3958cdb1f356a31fbf14a16ae56
/src/com/demo/FlashTesting.java
cb8610b92ca6a9c923c42ffa44c15bda735e586f
[]
no_license
shilpareddy92/DemoProject
https://github.com/shilpareddy92/DemoProject
6eb3dc7e34ef585b378cd25933ce6c120baf2866
9f63ddf949737dcae7a5c0ae5ddd2e3a67a1db22
refs/heads/master
2020-06-12T13:12:24.759000
2019-10-04T10:26:49
2019-10-04T10:26:49
194,309,926
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.demo; import java.util.concurrent.TimeUnit; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.sikuli.script.FindFailed; import org.sikuli.script.Pattern; import org.sikuli.script.Screen; public class FlashTesting { public static void main(String[] args) throws FindFailed { System.setProperty("webdriver.chrome.driver", "D:\\Selenium\\Drivers\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("https://www.youtube.com/watch?v=SpjCrTHkzCA"); driver.manage().window().maximize(); driver.manage().deleteAllCookies(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); JavascriptExecutor Js = (JavascriptExecutor)driver; boolean isPageLoaded = Js.executeScript("return document.readyState").toString().equals("complete"); if (isPageLoaded) { System.out.println("page was loaded completley"); } else { System.out.println("page is not loaded completley"); } Screen s= new Screen(); Pattern p = new Pattern("C:\\Users\\SDagadapally\\Desktop\\pause.png"); s.wait(p, 2000); s.click(); s.click(); } }
UTF-8
Java
1,238
java
FlashTesting.java
Java
[ { "context": " Screen();\r\n\t\tPattern p = new Pattern(\"C:\\\\Users\\\\SDagadapally\\\\Desktop\\\\pause.png\");\r\n\t\ts.wait(p, 2000);\r\n\t\ts.c", "end": 1150, "score": 0.9126631617546082, "start": 1138, "tag": "USERNAME", "value": "SDagadapally" } ]
null
[]
package com.demo; import java.util.concurrent.TimeUnit; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.sikuli.script.FindFailed; import org.sikuli.script.Pattern; import org.sikuli.script.Screen; public class FlashTesting { public static void main(String[] args) throws FindFailed { System.setProperty("webdriver.chrome.driver", "D:\\Selenium\\Drivers\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("https://www.youtube.com/watch?v=SpjCrTHkzCA"); driver.manage().window().maximize(); driver.manage().deleteAllCookies(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); JavascriptExecutor Js = (JavascriptExecutor)driver; boolean isPageLoaded = Js.executeScript("return document.readyState").toString().equals("complete"); if (isPageLoaded) { System.out.println("page was loaded completley"); } else { System.out.println("page is not loaded completley"); } Screen s= new Screen(); Pattern p = new Pattern("C:\\Users\\SDagadapally\\Desktop\\pause.png"); s.wait(p, 2000); s.click(); s.click(); } }
1,238
0.705977
0.701131
43
26.790697
26.870541
103
false
false
0
0
0
0
0
0
1.744186
false
false
3
3c14bb49daf4753b2528742499a4775f629ce9ce
27,109,833,633,782
a5e74b8b711090e611e4b6c3a8472206496e73dd
/src/main/java/com/buit/commons/enums/SslbEnum.java
8302435421732611390a7a2188056e790917f2c1
[]
no_license
gfz1103/op
https://github.com/gfz1103/op
0fd5545961b0a0b381f209ef6bdc3881848fb410
a6857bf4eff8e85310b0c2dc39827474237a167f
refs/heads/master
2023-06-17T19:10:38.141000
2021-07-19T01:39:18
2021-07-19T01:39:18
387,306,271
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.buit.commons.enums; /** * @author All */ public enum SslbEnum { //所属类别 | SSLB 1 个人 2 科室 3 全院 4 B类模板 code_1(1), code_2(2), code_3(3), code_4(4); private Integer code; SslbEnum(Integer code) { this.code = code; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } }
UTF-8
Java
430
java
SslbEnum.java
Java
[ { "context": "package com.buit.commons.enums;\n\n\n/**\n * @author All\n */\npublic enum SslbEnum {\n //所属类别 | SSLB 1 个", "end": 52, "score": 0.777710497379303, "start": 49, "tag": "NAME", "value": "All" } ]
null
[]
package com.buit.commons.enums; /** * @author All */ public enum SslbEnum { //所属类别 | SSLB 1 个人 2 科室 3 全院 4 B类模板 code_1(1), code_2(2), code_3(3), code_4(4); private Integer code; SslbEnum(Integer code) { this.code = code; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } }
430
0.539604
0.509901
27
13.962963
12.670998
40
false
false
0
0
0
0
0
0
0.37037
false
false
3
481c1c1edd8fc2d538fc096d8818afc29209afa0
22,308,060,184,067
2436dd7962667f75d3d349460dd7fff02aaa7b02
/src/main/java/com/mohsinkerai/adminlte/report/ReportingController.java
a5a2604a7edff6ccb1485e1917d5d80e5f3a53c1
[]
no_license
mohsinkerai/volunteer-data-collection
https://github.com/mohsinkerai/volunteer-data-collection
4fdbe49287f2316f276f1655b428ddd6560be51f
20023a997ad07a6dbae5d9fc37669f5b2541a80d
refs/heads/master
2022-06-28T17:02:47.669000
2020-05-23T16:39:05
2020-05-23T16:39:05
247,723,880
0
0
null
false
2022-06-21T02:59:59
2020-03-16T14:29:57
2020-05-23T16:39:31
2022-06-21T02:59:59
7,490
0
0
3
JavaScript
false
false
package com.mohsinkerai.adminlte.report; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.mohsinkerai.adminlte.jamatkhana.Jamatkhana; import com.mohsinkerai.adminlte.person.Person; import com.mohsinkerai.adminlte.person.PersonService; import com.mohsinkerai.adminlte.report.dto.JamatkhanaAndDateDto; import com.mohsinkerai.adminlte.report.generator.PersonDumpReportGenerator; import com.mohsinkerai.adminlte.report.validator.ReportValidator; import com.mohsinkerai.adminlte.users.MyUserService; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import net.sf.jasperreports.engine.JRException; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import java.sql.Date; import java.time.LocalDate; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Set; import static com.mohsinkerai.adminlte.report.ReportingController.REPORT_CONTROLLER_NAME; @RequestMapping(REPORT_CONTROLLER_NAME) @Controller @AllArgsConstructor @Slf4j @PreAuthorize("hasAuthority('REPORT')") public class ReportingController { public static final String REPORT_CONTROLLER_NAME = "user/report"; private final ReportValidator reportValidator; private final MyUserService myUserService; private final PersonService personService; private final PersonDumpReportGenerator personDumpReportGenerator; @GetMapping("forms/dump") public String formsDumpSelectorPage(Model model) { JamatkhanaAndDateDto dto = new JamatkhanaAndDateDto(null, LocalDate.now(), LocalDate.now()); Set<Jamatkhana> jks = myUserService.getCurrentLoggedInUser().getJamatkhanas(); ArrayList<Jamatkhana> jamatkhanas = Lists.newArrayList(jks); jamatkhanas.sort(Comparator.comparing(Jamatkhana::getName)); model.addAttribute("jks", jamatkhanas); model.addAttribute("data", dto); model.addAttribute("urlPath", ReportingController.REPORT_CONTROLLER_NAME + "/forms/dump"); return "report/" + "by-jamatkhana"; } @GetMapping("forms/dump/download") public HttpEntity<byte[]> formsDumper(JamatkhanaAndDateDto jamatkhanaAndDateDto, Model model) throws JRException { LocalDate fromDate = jamatkhanaAndDateDto.getFromDate(); LocalDate toDate = jamatkhanaAndDateDto.getToDate(); Jamatkhana jamatkhana = jamatkhanaAndDateDto.getJamatkhana(); if (!reportValidator.isJkAllowed(jamatkhana)) { throw new RuntimeException("Jamatkhana you are trying to search is not allowed"); } List<Person> jamatkhanaSummary = personService .findByJamatkhanaAndCreatedDateBetween(jamatkhana, fromDate, toDate); ImmutableMap<String, Object> params = ImmutableMap.of( "REPORT_NAME", "Entries by JK Summary", "FROM_DATE", Date.valueOf(fromDate), "TO_DATE", Date.valueOf(toDate)); // Return Report Here byte[] bytes = personDumpReportGenerator.generateXLSXReport(jamatkhanaSummary, Maps.newHashMap(params)); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")); headers.set(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=" + "persons-dump-" + jamatkhana.getName() + ".xlsx"); return new HttpEntity<byte[]>(bytes, headers); } @GetMapping("forms/all/dump") public String formsDumpAllAssignedJKSelectorPage(Model model) { JamatkhanaAndDateDto dto = new JamatkhanaAndDateDto(null, LocalDate.now(), LocalDate.now()); model.addAttribute("jks", Lists.newArrayList()); model.addAttribute("data", dto); model.addAttribute("urlPath", ReportingController.REPORT_CONTROLLER_NAME + "/forms/all/dump"); return "report/" + "by-jamatkhana"; } @GetMapping("forms/all/dump/download") public HttpEntity<byte[]> formsDumperAllAssignedJK(JamatkhanaAndDateDto jamatkhanaAndDateDto, Model model) throws JRException { LocalDate fromDate = jamatkhanaAndDateDto.getFromDate(); LocalDate toDate = jamatkhanaAndDateDto.getToDate(); Set<Jamatkhana> jamatkhanas = myUserService.getCurrentLoggedInUser().getJamatkhanas(); List<Person> jamatkhanaSummary = personService .findByJamatkhanaInAndCreatedDateBetween(jamatkhanas, fromDate, toDate); ImmutableMap<String, Object> params = ImmutableMap.of( "REPORT_NAME", "Entries by JK Summary", "FROM_DATE", Date.valueOf(fromDate), "TO_DATE", Date.valueOf(toDate)); // Return Report Here byte[] bytes = personDumpReportGenerator.generateXLSXReport(jamatkhanaSummary, Maps.newHashMap(params)); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")); headers.set(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=" + "persons-dump-all-assigned-jk" + ".xlsx"); return new HttpEntity<byte[]>(bytes, headers); } }
UTF-8
Java
5,295
java
ReportingController.java
Java
[]
null
[]
package com.mohsinkerai.adminlte.report; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.mohsinkerai.adminlte.jamatkhana.Jamatkhana; import com.mohsinkerai.adminlte.person.Person; import com.mohsinkerai.adminlte.person.PersonService; import com.mohsinkerai.adminlte.report.dto.JamatkhanaAndDateDto; import com.mohsinkerai.adminlte.report.generator.PersonDumpReportGenerator; import com.mohsinkerai.adminlte.report.validator.ReportValidator; import com.mohsinkerai.adminlte.users.MyUserService; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import net.sf.jasperreports.engine.JRException; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import java.sql.Date; import java.time.LocalDate; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Set; import static com.mohsinkerai.adminlte.report.ReportingController.REPORT_CONTROLLER_NAME; @RequestMapping(REPORT_CONTROLLER_NAME) @Controller @AllArgsConstructor @Slf4j @PreAuthorize("hasAuthority('REPORT')") public class ReportingController { public static final String REPORT_CONTROLLER_NAME = "user/report"; private final ReportValidator reportValidator; private final MyUserService myUserService; private final PersonService personService; private final PersonDumpReportGenerator personDumpReportGenerator; @GetMapping("forms/dump") public String formsDumpSelectorPage(Model model) { JamatkhanaAndDateDto dto = new JamatkhanaAndDateDto(null, LocalDate.now(), LocalDate.now()); Set<Jamatkhana> jks = myUserService.getCurrentLoggedInUser().getJamatkhanas(); ArrayList<Jamatkhana> jamatkhanas = Lists.newArrayList(jks); jamatkhanas.sort(Comparator.comparing(Jamatkhana::getName)); model.addAttribute("jks", jamatkhanas); model.addAttribute("data", dto); model.addAttribute("urlPath", ReportingController.REPORT_CONTROLLER_NAME + "/forms/dump"); return "report/" + "by-jamatkhana"; } @GetMapping("forms/dump/download") public HttpEntity<byte[]> formsDumper(JamatkhanaAndDateDto jamatkhanaAndDateDto, Model model) throws JRException { LocalDate fromDate = jamatkhanaAndDateDto.getFromDate(); LocalDate toDate = jamatkhanaAndDateDto.getToDate(); Jamatkhana jamatkhana = jamatkhanaAndDateDto.getJamatkhana(); if (!reportValidator.isJkAllowed(jamatkhana)) { throw new RuntimeException("Jamatkhana you are trying to search is not allowed"); } List<Person> jamatkhanaSummary = personService .findByJamatkhanaAndCreatedDateBetween(jamatkhana, fromDate, toDate); ImmutableMap<String, Object> params = ImmutableMap.of( "REPORT_NAME", "Entries by JK Summary", "FROM_DATE", Date.valueOf(fromDate), "TO_DATE", Date.valueOf(toDate)); // Return Report Here byte[] bytes = personDumpReportGenerator.generateXLSXReport(jamatkhanaSummary, Maps.newHashMap(params)); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")); headers.set(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=" + "persons-dump-" + jamatkhana.getName() + ".xlsx"); return new HttpEntity<byte[]>(bytes, headers); } @GetMapping("forms/all/dump") public String formsDumpAllAssignedJKSelectorPage(Model model) { JamatkhanaAndDateDto dto = new JamatkhanaAndDateDto(null, LocalDate.now(), LocalDate.now()); model.addAttribute("jks", Lists.newArrayList()); model.addAttribute("data", dto); model.addAttribute("urlPath", ReportingController.REPORT_CONTROLLER_NAME + "/forms/all/dump"); return "report/" + "by-jamatkhana"; } @GetMapping("forms/all/dump/download") public HttpEntity<byte[]> formsDumperAllAssignedJK(JamatkhanaAndDateDto jamatkhanaAndDateDto, Model model) throws JRException { LocalDate fromDate = jamatkhanaAndDateDto.getFromDate(); LocalDate toDate = jamatkhanaAndDateDto.getToDate(); Set<Jamatkhana> jamatkhanas = myUserService.getCurrentLoggedInUser().getJamatkhanas(); List<Person> jamatkhanaSummary = personService .findByJamatkhanaInAndCreatedDateBetween(jamatkhanas, fromDate, toDate); ImmutableMap<String, Object> params = ImmutableMap.of( "REPORT_NAME", "Entries by JK Summary", "FROM_DATE", Date.valueOf(fromDate), "TO_DATE", Date.valueOf(toDate)); // Return Report Here byte[] bytes = personDumpReportGenerator.generateXLSXReport(jamatkhanaSummary, Maps.newHashMap(params)); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")); headers.set(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=" + "persons-dump-all-assigned-jk" + ".xlsx"); return new HttpEntity<byte[]>(bytes, headers); } }
5,295
0.779603
0.779037
126
41.023811
33.33654
129
false
false
0
0
0
0
0
0
0.825397
false
false
3
c3eda8f0fd52a5125aa5c7022fc9adc19f5e08fd
18,580,028,567,554
f2aefd62332f70f313bb6ae3c0d7d9683c50ac3a
/Tic/src/jtbisign/engine/Screen.java
9b9ef0204b786c7d31f6bd4bc273049ef7678e6a
[]
no_license
JustinBis/CS1971
https://github.com/JustinBis/CS1971
4fe198eeedf9a2425a2a31ff1b2c4a6d7f01cd50
4dc31162ecf4b68d4c1fc32dbb017492b92435a7
refs/heads/master
2015-09-26T10:41:25.542000
2015-09-23T03:41:56
2015-09-23T03:41:56
42,846,294
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package jtbisign.engine; import java.awt.Color; import java.awt.Graphics2D; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; import cs1971.Vec2i; public abstract class Screen { private Application parentApplication; /** * If this screen should have a background color, this will be set */ private boolean drawBackground = false; private Color backgroundColor; protected Screen(Application parentApplication, Vec2i screenSize) { this.parentApplication = parentApplication; this.screenSize = screenSize; } /** * If this screen has a background color to draw before everything else, this will be true * @return true if the background is set for drawing, false otherwise */ public boolean getDrawBackground() { return this.drawBackground; } /** * Will set the drawBackground boolean to false, disabling background drawing. * To turn it on again, set the background color again using setBackgroundColor * @param drawBackground The boolean to store */ public void disableDrawBackground() { this.drawBackground = false; } /** * Sets the background color for this screen and automatically set drawBackground to true * @param bgColor the color of the background to draw */ public void setBackgroundColor(Color bgColor) { this.drawBackground = true; this.backgroundColor = bgColor; } /** * Returns the full width of the screen in pixels * @return an int representing the height of the screen */ public int getScreenWidth() { return this.screenSize.x; } /** * Returns the full height of the screen in pixels * @return an int representing the height of the screen */ public int getScreenHeight() { return this.screenSize.y; } // Event handlers // The following events will all be passed through from the main application // Note that these all return a boolean. If this handler should be transparent, // and the event should propagate up the stack the method will return true /** * Event handler for each application update or 'tick'. * @param nanosSincePreviousTick The number of nanoseconds passed since the previous tick * @return true if this event should propagate up the stack of screens, false otherwise */ protected boolean onTick(long nanosSincePreviousTick) { return true; } /** * Event handler for the application's draw calls * @param g a Graphics2D context to which you should draw * @return true if this event should propagate up the stack of screens, false otherwise */ protected boolean onDraw(Graphics2D g) { if (this.getDrawBackground()) { java.awt.geom.Rectangle2D.Float bgRect = new java.awt.geom.Rectangle2D.Float( 0, 0, this.getScreenWidth(), this.getScreenHeight()); g.setColor(this.backgroundColor); g.fill(bgRect); } return true; } /** * Event handler for key typed events * @param e the KeyEvent containing the key typed data * @return true if this event should propagate up the stack of screens, false otherwise */ protected boolean onKeyTyped(KeyEvent e) { return true; } /** * Event handler for key pressed events * @param e the KeyEvent containing the key pressed data * @return true if this event should propagate up the stack of screens, false otherwise */ protected boolean onKeyPressed(KeyEvent e) { return true; } /** * Event handler for key released events * @param e the KeyEvent containing the key released data * @return true if this event should propagate up the stack of screens, false otherwise */ protected boolean onKeyReleased(KeyEvent e) { return true; } /** * Event handler for mouse click events * @param e the MouseEvent containing the click data * @return true if this event should propagate up the stack of screens, false otherwise */ protected boolean onMouseClicked(MouseEvent e) { return true; } /** * Event handler for mouse press events * @param e the MouseEvent containing the mouse press data * @return true if this event should propagate up the stack of screens, false otherwise */ protected boolean onMousePressed(MouseEvent e) { return true; } /** * Event handler for mouse release events * @param e the MouseEvent containing the mouse release data * @return true if this event should propagate up the stack of screens, false otherwise */ protected boolean onMouseReleased(MouseEvent e) { return true; } /** * Event handler for mouse dragged events * @param e the MouseEvent containing the mouse drag data * @return true if this event should propagate up the stack of screens, false otherwise */ protected boolean onMouseDragged(MouseEvent e) { return true; } /** * Event handler for mouse move events * @param e the MouseEvent containing the mouse move data * @return true if this event should propagate up the stack of screens, false otherwise */ protected boolean onMouseMoved(MouseEvent e) { return true; } /** * Event handler for mouse wheel movement (scrolling) events * @param e the MouseWheelEvent containing the mouse wheel movement data * @return true if this event should propagate up the stack of screens, false otherwise */ protected boolean onMouseWheelMoved(MouseWheelEvent e) { return true; } /** * This screen's current size as a Vec2i representing the integer height and width of this screen */ protected Vec2i screenSize; /** * Returns this screen's current size * @return a Vec2i representing the integer height and width of this screen */ public Vec2i getScreenSize() { return screenSize; } /** * Event handler for window resizing * @param newSize a Vec2i of the new x and y size of the window * @return true if this event should propagate up the stack of screens, false otherwise */ protected boolean onResize(Vec2i newSize) { // Store the screen size for easy access later if needed screenSize = newSize; this.rebuildLayout(); return true; } /** * Each Screen is created and owned by an Application. This function returns that Application. * @return the Application that owns this Screen */ public Application getParentApplication() { return this.parentApplication; } /** * Rebuilds the layout of this screen using the stored screenSize */ public abstract void rebuildLayout(); }
UTF-8
Java
6,357
java
Screen.java
Java
[]
null
[]
package jtbisign.engine; import java.awt.Color; import java.awt.Graphics2D; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; import cs1971.Vec2i; public abstract class Screen { private Application parentApplication; /** * If this screen should have a background color, this will be set */ private boolean drawBackground = false; private Color backgroundColor; protected Screen(Application parentApplication, Vec2i screenSize) { this.parentApplication = parentApplication; this.screenSize = screenSize; } /** * If this screen has a background color to draw before everything else, this will be true * @return true if the background is set for drawing, false otherwise */ public boolean getDrawBackground() { return this.drawBackground; } /** * Will set the drawBackground boolean to false, disabling background drawing. * To turn it on again, set the background color again using setBackgroundColor * @param drawBackground The boolean to store */ public void disableDrawBackground() { this.drawBackground = false; } /** * Sets the background color for this screen and automatically set drawBackground to true * @param bgColor the color of the background to draw */ public void setBackgroundColor(Color bgColor) { this.drawBackground = true; this.backgroundColor = bgColor; } /** * Returns the full width of the screen in pixels * @return an int representing the height of the screen */ public int getScreenWidth() { return this.screenSize.x; } /** * Returns the full height of the screen in pixels * @return an int representing the height of the screen */ public int getScreenHeight() { return this.screenSize.y; } // Event handlers // The following events will all be passed through from the main application // Note that these all return a boolean. If this handler should be transparent, // and the event should propagate up the stack the method will return true /** * Event handler for each application update or 'tick'. * @param nanosSincePreviousTick The number of nanoseconds passed since the previous tick * @return true if this event should propagate up the stack of screens, false otherwise */ protected boolean onTick(long nanosSincePreviousTick) { return true; } /** * Event handler for the application's draw calls * @param g a Graphics2D context to which you should draw * @return true if this event should propagate up the stack of screens, false otherwise */ protected boolean onDraw(Graphics2D g) { if (this.getDrawBackground()) { java.awt.geom.Rectangle2D.Float bgRect = new java.awt.geom.Rectangle2D.Float( 0, 0, this.getScreenWidth(), this.getScreenHeight()); g.setColor(this.backgroundColor); g.fill(bgRect); } return true; } /** * Event handler for key typed events * @param e the KeyEvent containing the key typed data * @return true if this event should propagate up the stack of screens, false otherwise */ protected boolean onKeyTyped(KeyEvent e) { return true; } /** * Event handler for key pressed events * @param e the KeyEvent containing the key pressed data * @return true if this event should propagate up the stack of screens, false otherwise */ protected boolean onKeyPressed(KeyEvent e) { return true; } /** * Event handler for key released events * @param e the KeyEvent containing the key released data * @return true if this event should propagate up the stack of screens, false otherwise */ protected boolean onKeyReleased(KeyEvent e) { return true; } /** * Event handler for mouse click events * @param e the MouseEvent containing the click data * @return true if this event should propagate up the stack of screens, false otherwise */ protected boolean onMouseClicked(MouseEvent e) { return true; } /** * Event handler for mouse press events * @param e the MouseEvent containing the mouse press data * @return true if this event should propagate up the stack of screens, false otherwise */ protected boolean onMousePressed(MouseEvent e) { return true; } /** * Event handler for mouse release events * @param e the MouseEvent containing the mouse release data * @return true if this event should propagate up the stack of screens, false otherwise */ protected boolean onMouseReleased(MouseEvent e) { return true; } /** * Event handler for mouse dragged events * @param e the MouseEvent containing the mouse drag data * @return true if this event should propagate up the stack of screens, false otherwise */ protected boolean onMouseDragged(MouseEvent e) { return true; } /** * Event handler for mouse move events * @param e the MouseEvent containing the mouse move data * @return true if this event should propagate up the stack of screens, false otherwise */ protected boolean onMouseMoved(MouseEvent e) { return true; } /** * Event handler for mouse wheel movement (scrolling) events * @param e the MouseWheelEvent containing the mouse wheel movement data * @return true if this event should propagate up the stack of screens, false otherwise */ protected boolean onMouseWheelMoved(MouseWheelEvent e) { return true; } /** * This screen's current size as a Vec2i representing the integer height and width of this screen */ protected Vec2i screenSize; /** * Returns this screen's current size * @return a Vec2i representing the integer height and width of this screen */ public Vec2i getScreenSize() { return screenSize; } /** * Event handler for window resizing * @param newSize a Vec2i of the new x and y size of the window * @return true if this event should propagate up the stack of screens, false otherwise */ protected boolean onResize(Vec2i newSize) { // Store the screen size for easy access later if needed screenSize = newSize; this.rebuildLayout(); return true; } /** * Each Screen is created and owned by an Application. This function returns that Application. * @return the Application that owns this Screen */ public Application getParentApplication() { return this.parentApplication; } /** * Rebuilds the layout of this screen using the stored screenSize */ public abstract void rebuildLayout(); }
6,357
0.732421
0.729432
225
27.253334
28.781519
98
false
false
0
0
0
0
0
0
1.342222
false
false
3
e16717146af8087cb4533a0df62cfff5b0f9008b
28,870,770,172,787
3791c09b0d3ac3bd30871adb46a3f99e2f085fca
/src/bsearch/Sqrt.java
efa5f666d49902c34516258934b18e592b38d9a5
[]
no_license
haleyhao/LeetCode
https://github.com/haleyhao/LeetCode
0279aed67dcec1ebb7c3965fdcb6fe6b51ee8e26
232b5873592817ffd3db164c0fc04ad3e56c7414
refs/heads/master
2020-03-31T20:17:12.571000
2019-11-12T05:59:00
2019-11-12T05:59:00
152,533,489
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package bsearch; public class Sqrt { // LeetCode 69 // b search public int mySqrt(int x) { if (x < 1) return 0; int low = 1; int high = x; while (low <= high) { int mid = (high - low) / 2 + low; if (x / mid == mid) return mid; if (x / mid > mid) low = mid + 1; if (x / mid < mid) high = mid - 1; } return high; } }
UTF-8
Java
428
java
Sqrt.java
Java
[]
null
[]
package bsearch; public class Sqrt { // LeetCode 69 // b search public int mySqrt(int x) { if (x < 1) return 0; int low = 1; int high = x; while (low <= high) { int mid = (high - low) / 2 + low; if (x / mid == mid) return mid; if (x / mid > mid) low = mid + 1; if (x / mid < mid) high = mid - 1; } return high; } }
428
0.422897
0.404206
18
22.777779
14.366456
46
false
false
0
0
0
0
0
0
0.5
false
false
3
2c577639648ba9620ea0ad06b6bc25a594557afb
8,220,567,471,245
5072a81358b2f39837ba62f183a3cea9ba6e00fc
/src/net/kihar/anticheat/check/ICheck.java
9fc7459175b5372e11f6e5be7b479c7ec565944b
[]
no_license
Grac3T/Kihar-Anticheat-Source-Code
https://github.com/Grac3T/Kihar-Anticheat-Source-Code
153b88a7fb45c596b1712b4f71078c3c8c1d515a
05ac1b5232c08d2ada8a07d1f8eb743f5f3d9f88
refs/heads/master
2023-08-11T00:28:25.865000
2021-10-09T00:36:30
2021-10-09T00:36:30
415,162,388
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.kihar.anticheat.check; public interface ICheck<T> { Class<T> getType(); void handle(T type); }
UTF-8
Java
113
java
ICheck.java
Java
[]
null
[]
package net.kihar.anticheat.check; public interface ICheck<T> { Class<T> getType(); void handle(T type); }
113
0.699115
0.699115
9
11.555555
13.250669
34
false
false
0
0
0
0
0
0
0.555556
false
false
3
4a13f820feeaf52a67be15b1d51d640df855ff0b
27,238,682,604,626
e0ce2962dc0a9ad8f4f5c8cce385b17721db4731
/test/com/catalyser/util/PositionReaderUtilTest.java
7f1703da53210e506ad861bc82f32224aa2f0ee8
[]
no_license
Techno1234/MarsRover
https://github.com/Techno1234/MarsRover
067dd268349f11a843d72dc5321c36e06ab54a5c
ce749e5713aa8e1843a76b554c3195e0519c6358
refs/heads/master
2021-08-15T20:49:21.889000
2017-11-18T08:50:35
2017-11-18T08:50:35
111,189,392
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.catalyser.util; import static org.junit.Assert.assertEquals; import java.awt.Point; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Scanner; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.testng.PowerMockTestCase; import com.catalyser.Rover; import com.catalyser.common.Direction; @PrepareForTest({ Scanner.class, PositionReaderUtil.class }) @RunWith(PowerMockRunner.class) public class PositionReaderUtilTest extends PowerMockTestCase { public static final String ERROR_MESSAGE_INCORRECT_VALUE_UPPERLIMIT_X = "Incorrect upper right X coordinate;Cannot be less than or equal to 0"; public static final String ERROR_MESSAGE_INCORRECT_VALUE_UPPERLIMIT_Y = "Incorrect upper right Y coordinate; Cannot be less than or equal to 0"; public static final String ERROR_MESSAGE_INCORRECT_TYPE_UPPERLIMIT_X = "Incorrect input for x coordinate ; Required interger"; public static final String ERROR_MESSAGE_INCORRECT_TYPE_UPPERLIMIT_Y = "Incorrect input for y coordinate ; Required interger"; public static final String ERROR_MESSAGE_INCORRECT_ROVER_COORDINATE_X = "Incorrect input for rover; x coordinate needs to be an interger"; public static final String ERROR_MESSAGE_INCORRECT_ROVER_COORDINATE_Y = "Incorrect input for rover; y coordinate needs to be an interger"; public static final String ERROR_MESSAGE_INCORRECT_TYPE_DIRECTION = "Incorrect input for direction; direction can be one of N/S/E/W"; private static final String INSTRUCTIONS_1 = "LMLMLMLMM"; private static final String INSTRUCTIONS_2 = "MMRMMRMRRM"; private final ByteArrayOutputStream output = new ByteArrayOutputStream(); @Rule public ExpectedException expected = ExpectedException.none(); @Before public void setUp() throws Exception { PowerMockito.mockStatic(PositionReaderUtil.class); System.setOut(new PrintStream(output)); } @Test public void readUppperLimitWithValidXY() throws Exception { final Point upperRightLimit = new Point(); final StringBuffer testInputs = new StringBuffer("5 5").append("\n").append("1 2 N").append("\n") .append(INSTRUCTIONS_1); final Scanner scannerWithInputs = new Scanner(testInputs.toString()); PowerMockito.doCallRealMethod().when(PositionReaderUtil.class, "readUpperLimit", scannerWithInputs, upperRightLimit); PositionReaderUtil.readUpperLimit(scannerWithInputs, upperRightLimit); assertEquals(5, upperRightLimit.x); assertEquals(5, upperRightLimit.y); } @Test public void readUppperLimitWithValidDoubleDigitInputs() throws Exception { final Point upperRightLimit = new Point(); final StringBuffer testInputs = new StringBuffer("15 10").append("\n").append("1 2 N").append("\n") .append(INSTRUCTIONS_1); final Scanner scannerWithInputs = new Scanner(testInputs.toString()); PowerMockito.doCallRealMethod().when(PositionReaderUtil.class, "readUpperLimit", scannerWithInputs, upperRightLimit); PositionReaderUtil.readUpperLimit(scannerWithInputs, upperRightLimit); assertEquals(15, upperRightLimit.x); assertEquals(10, upperRightLimit.y); } @Test(expected = Exception.class) public void readUppperLimitWithInvalidValueX() throws Exception { Point upperRightLimit = new Point(); StringBuffer testInputs = new StringBuffer("0 5").append("\n").append("1 2 N").append("\n").append("LMLMLML"); Scanner scannerWithInputs = new Scanner(testInputs.toString()); PowerMockito.doCallRealMethod().when(PositionReaderUtil.class, "readUpperLimit", scannerWithInputs, upperRightLimit); PositionReaderUtil.readUpperLimit(scannerWithInputs, upperRightLimit); expected.expectMessage(ERROR_MESSAGE_INCORRECT_VALUE_UPPERLIMIT_X); } @Test(expected = Exception.class) public void readUppperLimitWithInvalidTypeX() throws Exception { Point upperRightLimit = new Point(); StringBuffer testInputs = new StringBuffer("D 0").append("\n"); Scanner scannerWithInputs = new Scanner(testInputs.toString()); PowerMockito.doCallRealMethod().when(PositionReaderUtil.class, "readUpperLimit", scannerWithInputs, upperRightLimit); PositionReaderUtil.readUpperLimit(scannerWithInputs, upperRightLimit); expected.expectMessage(ERROR_MESSAGE_INCORRECT_TYPE_UPPERLIMIT_X); } @Test(expected = Exception.class) public void readUppperLimitWithInvalidTypeY() throws Exception { Point upperRightLimit = new Point(); StringBuffer testInputs = new StringBuffer("1 D").append("\n"); Scanner scannerWithInputs = new Scanner(testInputs.toString()); PowerMockito.doCallRealMethod().when(PositionReaderUtil.class, "readUpperLimit", scannerWithInputs, upperRightLimit); PositionReaderUtil.readUpperLimit(scannerWithInputs, upperRightLimit); expected.expectMessage(ERROR_MESSAGE_INCORRECT_TYPE_UPPERLIMIT_Y); } @Test(expected = Exception.class) public void readUppperLimitWithInvalidValueY() throws Exception { Point upperRightLimit = new Point(); StringBuffer testInputs = new StringBuffer("5 0").append("\n").append("1 2 N").append("\n").append("LMLMLML"); Scanner scannerWithInputs = new Scanner(testInputs.toString()); PowerMockito.doCallRealMethod().when(PositionReaderUtil.class, "readUpperLimit", scannerWithInputs, upperRightLimit); PositionReaderUtil.readUpperLimit(scannerWithInputs, upperRightLimit); expected.expectMessage(ERROR_MESSAGE_INCORRECT_VALUE_UPPERLIMIT_Y); } @Test public void testReadRoverInputsValidXY() throws Exception { final Point upperRightLimit = new Point(); final StringBuffer testInputs = new StringBuffer("5 5").append("\n").append("1 2 N").append("\n") .append(INSTRUCTIONS_1); final Scanner scannerWithInputs = new Scanner(testInputs.toString()); PowerMockito.doCallRealMethod().when(PositionReaderUtil.class, "readUpperLimit", scannerWithInputs, upperRightLimit); PositionReaderUtil.readUpperLimit(scannerWithInputs, upperRightLimit); assertEquals(5, upperRightLimit.x); assertEquals(5, upperRightLimit.y); } @Test() public void testReadRoverInputs() throws Exception { final StringBuffer testInputs = new StringBuffer("1 2 N ").append("\n").append(INSTRUCTIONS_1).append("\n") .append("N").append("\n").append("\n"); Scanner scannerWithInputs = new Scanner(testInputs.toString()); final Map<Rover, String> roverInstructionMap = new LinkedHashMap<Rover, String>(); PositionReaderUtil.readRoverInputs(roverInstructionMap, scannerWithInputs); PowerMockito.doCallRealMethod().when(PositionReaderUtil.class, "readRoverInputs", roverInstructionMap, scannerWithInputs); PositionReaderUtil.readRoverInputs(roverInstructionMap, scannerWithInputs); Iterator<Entry<Rover, String>> itr = roverInstructionMap.entrySet().iterator(); Entry<Rover, String> entry = itr.next(); Rover rover = entry.getKey(); String instructions = entry.getValue(); assertEquals(1, rover.getPoint().x); assertEquals(2, rover.getPoint().y); assertEquals(Direction.N, rover.getDirection()); assertEquals(INSTRUCTIONS_1, instructions); } @Test() public void testReadRoverDoubleDigitInputs() throws Exception { final StringBuffer testInputs = new StringBuffer("12 24 N ").append("\n").append(INSTRUCTIONS_1).append("\n") .append("N").append("\n"); Scanner scannerWithInputs = new Scanner(testInputs.toString()); final Map<Rover, String> roverInstructionMap = new LinkedHashMap<Rover, String>(); PositionReaderUtil.readRoverInputs(roverInstructionMap, scannerWithInputs); PowerMockito.doCallRealMethod().when(PositionReaderUtil.class, "readRoverInputs", roverInstructionMap, scannerWithInputs); PositionReaderUtil.readRoverInputs(roverInstructionMap, scannerWithInputs); Iterator<Entry<Rover, String>> itr = roverInstructionMap.entrySet().iterator(); Entry<Rover, String> entry = itr.next(); Rover rover = entry.getKey(); String instructions = entry.getValue(); assertEquals(12, rover.getPoint().x); assertEquals(24, rover.getPoint().y); assertEquals(Direction.N, rover.getDirection()); assertEquals(INSTRUCTIONS_1, instructions); } @Test() public void testReadMultipleRoverInputs() throws Exception { final StringBuffer testInputs = new StringBuffer("1 2 N ").append("\n").append(INSTRUCTIONS_1).append("\n") .append("Y").append("\n").append("3 3 E").append("\n").append(INSTRUCTIONS_2).append("\n").append("N") .append("\n"); Scanner scannerWithInputs = new Scanner(testInputs.toString()); final Map<Rover, String> roverInstructionMap = new LinkedHashMap<Rover, String>(); PositionReaderUtil.readRoverInputs(roverInstructionMap, scannerWithInputs); PowerMockito.doCallRealMethod().when(PositionReaderUtil.class, "readRoverInputs", roverInstructionMap, scannerWithInputs); PositionReaderUtil.readRoverInputs(roverInstructionMap, scannerWithInputs); Iterator<Entry<Rover, String>> itr = roverInstructionMap.entrySet().iterator(); Entry<Rover, String> entry = itr.next(); Rover rover = entry.getKey(); String instructions = entry.getValue(); assertEquals(1, rover.getPoint().x); assertEquals(2, rover.getPoint().y); assertEquals(Direction.N, rover.getDirection()); assertEquals(INSTRUCTIONS_1, instructions); entry = itr.next(); rover = entry.getKey(); instructions = entry.getValue(); assertEquals(3, rover.getPoint().x); assertEquals(3, rover.getPoint().y); assertEquals(Direction.E, rover.getDirection()); assertEquals(INSTRUCTIONS_2, instructions); } @Test(expected = Exception.class) public void testReadRoverInvalidInputTypeX() throws Exception { final StringBuffer testInputs = new StringBuffer("@ @ @ @ ").append("\n"); Scanner scannerWithInputs = new Scanner(testInputs.toString()); final Map<Rover, String> roverInstructionMap = new LinkedHashMap<Rover, String>(); PositionReaderUtil.readRoverInputs(roverInstructionMap, scannerWithInputs); PowerMockito.doCallRealMethod().when(PositionReaderUtil.class, "readRoverInputs", roverInstructionMap, scannerWithInputs); PositionReaderUtil.readRoverInputs(roverInstructionMap, scannerWithInputs); expected.expectMessage(ERROR_MESSAGE_INCORRECT_ROVER_COORDINATE_X); } @Test(expected = Exception.class) public void testReadRoverInvalidInputTypeY() throws Exception { final StringBuffer testInputs = new StringBuffer("0 @ N").append("\n"); Scanner scannerWithInputs = new Scanner(testInputs.toString()); final Map<Rover, String> roverInstructionMap = new LinkedHashMap<Rover, String>(); PositionReaderUtil.readRoverInputs(roverInstructionMap, scannerWithInputs); PowerMockito.doCallRealMethod().when(PositionReaderUtil.class, "readRoverInputs", roverInstructionMap, scannerWithInputs); PositionReaderUtil.readRoverInputs(roverInstructionMap, scannerWithInputs); expected.expectMessage(ERROR_MESSAGE_INCORRECT_ROVER_COORDINATE_Y); } @Test(expected = Exception.class) public void testReadRoverInvalidInputTypeDirection() throws Exception { final StringBuffer testInputs = new StringBuffer("0 1 @").append("\n"); Scanner scannerWithInputs = new Scanner(testInputs.toString()); final Map<Rover, String> roverInstructionMap = new LinkedHashMap<Rover, String>(); PositionReaderUtil.readRoverInputs(roverInstructionMap, scannerWithInputs); PowerMockito.doCallRealMethod().when(PositionReaderUtil.class, "readRoverInputs", roverInstructionMap, scannerWithInputs); PositionReaderUtil.readRoverInputs(roverInstructionMap, scannerWithInputs); expected.expectMessage(ERROR_MESSAGE_INCORRECT_TYPE_DIRECTION); } @After public void cleanUpStreams() { System.setOut(null); } }
UTF-8
Java
11,983
java
PositionReaderUtilTest.java
Java
[]
null
[]
package com.catalyser.util; import static org.junit.Assert.assertEquals; import java.awt.Point; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Scanner; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.testng.PowerMockTestCase; import com.catalyser.Rover; import com.catalyser.common.Direction; @PrepareForTest({ Scanner.class, PositionReaderUtil.class }) @RunWith(PowerMockRunner.class) public class PositionReaderUtilTest extends PowerMockTestCase { public static final String ERROR_MESSAGE_INCORRECT_VALUE_UPPERLIMIT_X = "Incorrect upper right X coordinate;Cannot be less than or equal to 0"; public static final String ERROR_MESSAGE_INCORRECT_VALUE_UPPERLIMIT_Y = "Incorrect upper right Y coordinate; Cannot be less than or equal to 0"; public static final String ERROR_MESSAGE_INCORRECT_TYPE_UPPERLIMIT_X = "Incorrect input for x coordinate ; Required interger"; public static final String ERROR_MESSAGE_INCORRECT_TYPE_UPPERLIMIT_Y = "Incorrect input for y coordinate ; Required interger"; public static final String ERROR_MESSAGE_INCORRECT_ROVER_COORDINATE_X = "Incorrect input for rover; x coordinate needs to be an interger"; public static final String ERROR_MESSAGE_INCORRECT_ROVER_COORDINATE_Y = "Incorrect input for rover; y coordinate needs to be an interger"; public static final String ERROR_MESSAGE_INCORRECT_TYPE_DIRECTION = "Incorrect input for direction; direction can be one of N/S/E/W"; private static final String INSTRUCTIONS_1 = "LMLMLMLMM"; private static final String INSTRUCTIONS_2 = "MMRMMRMRRM"; private final ByteArrayOutputStream output = new ByteArrayOutputStream(); @Rule public ExpectedException expected = ExpectedException.none(); @Before public void setUp() throws Exception { PowerMockito.mockStatic(PositionReaderUtil.class); System.setOut(new PrintStream(output)); } @Test public void readUppperLimitWithValidXY() throws Exception { final Point upperRightLimit = new Point(); final StringBuffer testInputs = new StringBuffer("5 5").append("\n").append("1 2 N").append("\n") .append(INSTRUCTIONS_1); final Scanner scannerWithInputs = new Scanner(testInputs.toString()); PowerMockito.doCallRealMethod().when(PositionReaderUtil.class, "readUpperLimit", scannerWithInputs, upperRightLimit); PositionReaderUtil.readUpperLimit(scannerWithInputs, upperRightLimit); assertEquals(5, upperRightLimit.x); assertEquals(5, upperRightLimit.y); } @Test public void readUppperLimitWithValidDoubleDigitInputs() throws Exception { final Point upperRightLimit = new Point(); final StringBuffer testInputs = new StringBuffer("15 10").append("\n").append("1 2 N").append("\n") .append(INSTRUCTIONS_1); final Scanner scannerWithInputs = new Scanner(testInputs.toString()); PowerMockito.doCallRealMethod().when(PositionReaderUtil.class, "readUpperLimit", scannerWithInputs, upperRightLimit); PositionReaderUtil.readUpperLimit(scannerWithInputs, upperRightLimit); assertEquals(15, upperRightLimit.x); assertEquals(10, upperRightLimit.y); } @Test(expected = Exception.class) public void readUppperLimitWithInvalidValueX() throws Exception { Point upperRightLimit = new Point(); StringBuffer testInputs = new StringBuffer("0 5").append("\n").append("1 2 N").append("\n").append("LMLMLML"); Scanner scannerWithInputs = new Scanner(testInputs.toString()); PowerMockito.doCallRealMethod().when(PositionReaderUtil.class, "readUpperLimit", scannerWithInputs, upperRightLimit); PositionReaderUtil.readUpperLimit(scannerWithInputs, upperRightLimit); expected.expectMessage(ERROR_MESSAGE_INCORRECT_VALUE_UPPERLIMIT_X); } @Test(expected = Exception.class) public void readUppperLimitWithInvalidTypeX() throws Exception { Point upperRightLimit = new Point(); StringBuffer testInputs = new StringBuffer("D 0").append("\n"); Scanner scannerWithInputs = new Scanner(testInputs.toString()); PowerMockito.doCallRealMethod().when(PositionReaderUtil.class, "readUpperLimit", scannerWithInputs, upperRightLimit); PositionReaderUtil.readUpperLimit(scannerWithInputs, upperRightLimit); expected.expectMessage(ERROR_MESSAGE_INCORRECT_TYPE_UPPERLIMIT_X); } @Test(expected = Exception.class) public void readUppperLimitWithInvalidTypeY() throws Exception { Point upperRightLimit = new Point(); StringBuffer testInputs = new StringBuffer("1 D").append("\n"); Scanner scannerWithInputs = new Scanner(testInputs.toString()); PowerMockito.doCallRealMethod().when(PositionReaderUtil.class, "readUpperLimit", scannerWithInputs, upperRightLimit); PositionReaderUtil.readUpperLimit(scannerWithInputs, upperRightLimit); expected.expectMessage(ERROR_MESSAGE_INCORRECT_TYPE_UPPERLIMIT_Y); } @Test(expected = Exception.class) public void readUppperLimitWithInvalidValueY() throws Exception { Point upperRightLimit = new Point(); StringBuffer testInputs = new StringBuffer("5 0").append("\n").append("1 2 N").append("\n").append("LMLMLML"); Scanner scannerWithInputs = new Scanner(testInputs.toString()); PowerMockito.doCallRealMethod().when(PositionReaderUtil.class, "readUpperLimit", scannerWithInputs, upperRightLimit); PositionReaderUtil.readUpperLimit(scannerWithInputs, upperRightLimit); expected.expectMessage(ERROR_MESSAGE_INCORRECT_VALUE_UPPERLIMIT_Y); } @Test public void testReadRoverInputsValidXY() throws Exception { final Point upperRightLimit = new Point(); final StringBuffer testInputs = new StringBuffer("5 5").append("\n").append("1 2 N").append("\n") .append(INSTRUCTIONS_1); final Scanner scannerWithInputs = new Scanner(testInputs.toString()); PowerMockito.doCallRealMethod().when(PositionReaderUtil.class, "readUpperLimit", scannerWithInputs, upperRightLimit); PositionReaderUtil.readUpperLimit(scannerWithInputs, upperRightLimit); assertEquals(5, upperRightLimit.x); assertEquals(5, upperRightLimit.y); } @Test() public void testReadRoverInputs() throws Exception { final StringBuffer testInputs = new StringBuffer("1 2 N ").append("\n").append(INSTRUCTIONS_1).append("\n") .append("N").append("\n").append("\n"); Scanner scannerWithInputs = new Scanner(testInputs.toString()); final Map<Rover, String> roverInstructionMap = new LinkedHashMap<Rover, String>(); PositionReaderUtil.readRoverInputs(roverInstructionMap, scannerWithInputs); PowerMockito.doCallRealMethod().when(PositionReaderUtil.class, "readRoverInputs", roverInstructionMap, scannerWithInputs); PositionReaderUtil.readRoverInputs(roverInstructionMap, scannerWithInputs); Iterator<Entry<Rover, String>> itr = roverInstructionMap.entrySet().iterator(); Entry<Rover, String> entry = itr.next(); Rover rover = entry.getKey(); String instructions = entry.getValue(); assertEquals(1, rover.getPoint().x); assertEquals(2, rover.getPoint().y); assertEquals(Direction.N, rover.getDirection()); assertEquals(INSTRUCTIONS_1, instructions); } @Test() public void testReadRoverDoubleDigitInputs() throws Exception { final StringBuffer testInputs = new StringBuffer("12 24 N ").append("\n").append(INSTRUCTIONS_1).append("\n") .append("N").append("\n"); Scanner scannerWithInputs = new Scanner(testInputs.toString()); final Map<Rover, String> roverInstructionMap = new LinkedHashMap<Rover, String>(); PositionReaderUtil.readRoverInputs(roverInstructionMap, scannerWithInputs); PowerMockito.doCallRealMethod().when(PositionReaderUtil.class, "readRoverInputs", roverInstructionMap, scannerWithInputs); PositionReaderUtil.readRoverInputs(roverInstructionMap, scannerWithInputs); Iterator<Entry<Rover, String>> itr = roverInstructionMap.entrySet().iterator(); Entry<Rover, String> entry = itr.next(); Rover rover = entry.getKey(); String instructions = entry.getValue(); assertEquals(12, rover.getPoint().x); assertEquals(24, rover.getPoint().y); assertEquals(Direction.N, rover.getDirection()); assertEquals(INSTRUCTIONS_1, instructions); } @Test() public void testReadMultipleRoverInputs() throws Exception { final StringBuffer testInputs = new StringBuffer("1 2 N ").append("\n").append(INSTRUCTIONS_1).append("\n") .append("Y").append("\n").append("3 3 E").append("\n").append(INSTRUCTIONS_2).append("\n").append("N") .append("\n"); Scanner scannerWithInputs = new Scanner(testInputs.toString()); final Map<Rover, String> roverInstructionMap = new LinkedHashMap<Rover, String>(); PositionReaderUtil.readRoverInputs(roverInstructionMap, scannerWithInputs); PowerMockito.doCallRealMethod().when(PositionReaderUtil.class, "readRoverInputs", roverInstructionMap, scannerWithInputs); PositionReaderUtil.readRoverInputs(roverInstructionMap, scannerWithInputs); Iterator<Entry<Rover, String>> itr = roverInstructionMap.entrySet().iterator(); Entry<Rover, String> entry = itr.next(); Rover rover = entry.getKey(); String instructions = entry.getValue(); assertEquals(1, rover.getPoint().x); assertEquals(2, rover.getPoint().y); assertEquals(Direction.N, rover.getDirection()); assertEquals(INSTRUCTIONS_1, instructions); entry = itr.next(); rover = entry.getKey(); instructions = entry.getValue(); assertEquals(3, rover.getPoint().x); assertEquals(3, rover.getPoint().y); assertEquals(Direction.E, rover.getDirection()); assertEquals(INSTRUCTIONS_2, instructions); } @Test(expected = Exception.class) public void testReadRoverInvalidInputTypeX() throws Exception { final StringBuffer testInputs = new StringBuffer("@ @ @ @ ").append("\n"); Scanner scannerWithInputs = new Scanner(testInputs.toString()); final Map<Rover, String> roverInstructionMap = new LinkedHashMap<Rover, String>(); PositionReaderUtil.readRoverInputs(roverInstructionMap, scannerWithInputs); PowerMockito.doCallRealMethod().when(PositionReaderUtil.class, "readRoverInputs", roverInstructionMap, scannerWithInputs); PositionReaderUtil.readRoverInputs(roverInstructionMap, scannerWithInputs); expected.expectMessage(ERROR_MESSAGE_INCORRECT_ROVER_COORDINATE_X); } @Test(expected = Exception.class) public void testReadRoverInvalidInputTypeY() throws Exception { final StringBuffer testInputs = new StringBuffer("0 @ N").append("\n"); Scanner scannerWithInputs = new Scanner(testInputs.toString()); final Map<Rover, String> roverInstructionMap = new LinkedHashMap<Rover, String>(); PositionReaderUtil.readRoverInputs(roverInstructionMap, scannerWithInputs); PowerMockito.doCallRealMethod().when(PositionReaderUtil.class, "readRoverInputs", roverInstructionMap, scannerWithInputs); PositionReaderUtil.readRoverInputs(roverInstructionMap, scannerWithInputs); expected.expectMessage(ERROR_MESSAGE_INCORRECT_ROVER_COORDINATE_Y); } @Test(expected = Exception.class) public void testReadRoverInvalidInputTypeDirection() throws Exception { final StringBuffer testInputs = new StringBuffer("0 1 @").append("\n"); Scanner scannerWithInputs = new Scanner(testInputs.toString()); final Map<Rover, String> roverInstructionMap = new LinkedHashMap<Rover, String>(); PositionReaderUtil.readRoverInputs(roverInstructionMap, scannerWithInputs); PowerMockito.doCallRealMethod().when(PositionReaderUtil.class, "readRoverInputs", roverInstructionMap, scannerWithInputs); PositionReaderUtil.readRoverInputs(roverInstructionMap, scannerWithInputs); expected.expectMessage(ERROR_MESSAGE_INCORRECT_TYPE_DIRECTION); } @After public void cleanUpStreams() { System.setOut(null); } }
11,983
0.776767
0.770842
303
38.551155
36.431271
145
false
false
0
0
0
0
0
0
2.085809
false
false
3
cc8dec432d074d737e7f4a0dcfa89a9c5b94c115
8,718,783,662,045
793da0470d60c64c39c798a41194d87632160895
/ nobrainerproject/NoBrainer/src/fr/uhp/nobrain/plateform/playerinvite/PlayerInviteView.java
fbd230bc707c19f36a0d81ed4afe3a0e2fd72ffc
[]
no_license
ThomasHuraux/nobrainerproject
https://github.com/ThomasHuraux/nobrainerproject
0f3d192bea79855f14a0f139304e4a782f2faf50
aa2f73223b49ec015bb064a8be4e91780e258d43
refs/heads/master
2021-01-10T15:15:26.778000
2015-06-05T06:37:52
2015-06-05T06:37:52
36,915,888
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package fr.uhp.nobrain.plateform.playerinvite; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.GridLayout; import java.util.ArrayList; import java.util.Observable; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import fr.uhp.nobrain.friends.Invitation; import fr.uhp.nobrain.friends.InvitationPersistance; import fr.uhp.nobrain.mvc.Model; import fr.uhp.nobrain.mvc.View; import fr.uhp.nobrain.player.PlayerPersistance; import fr.uhp.nobrain.tools.Context; public class PlayerInviteView extends JPanel implements View{ private PlayerInvite model; private static final long serialVersionUID = 1L; private ArrayList<JLabel> name; private ArrayList<JButton> invite; private JButton returnB; public void initialize(Model m) { model = (PlayerInvite) m; name = new ArrayList<JLabel>(); invite = new ArrayList<JButton>(); returnB = new JButton("Return"); JPanel inpan = new JPanel(); inpan.setLayout(new GridLayout(model.getPlayers().size(),1)); boolean b = false; for(int i = 0; i<model.getPlayers().size();i++){ try { JLabel l = new JLabel(model.getPlayers().get(i).getName()); l.setPreferredSize(new Dimension(180,20)); l.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); name.add(l); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } try { if (!InvitationPersistance.alreadyExists(new Invitation(Context.getCurrentPlayer(), PlayerPersistance.select(getNames().get(i).getText())))) invite.add(new JButton("Invite")); else { JButton button = new JButton("Sent"); button.setEnabled(false); invite.add(button); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } JPanel line = new JPanel(); line.add(name.get(i)); line.add(invite.get(i)); if(b) line.setBackground(Color.lightGray); b = !b; line.setPreferredSize(new Dimension(290,20)); inpan.add(line); } inpan.setPreferredSize(new Dimension(290,440)); JScrollPane jsp = new JScrollPane(inpan); setLayout(new BorderLayout()); add(jsp,BorderLayout.CENTER); add(returnB,BorderLayout.SOUTH); model.attach(this); makeController(); } public JButton getReturnB() { return returnB; } public ArrayList<JLabel> getNames() { return name; } public ArrayList<JButton> getInvite() { return invite; } @Override public void makeController() { PlayerInviteController pic = new PlayerInviteController(); pic.initialize(model, this); } @Override public void update(Observable o, Object arg) { // TODO Auto-generated method stub } }
UTF-8
Java
2,775
java
PlayerInviteView.java
Java
[]
null
[]
package fr.uhp.nobrain.plateform.playerinvite; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.GridLayout; import java.util.ArrayList; import java.util.Observable; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import fr.uhp.nobrain.friends.Invitation; import fr.uhp.nobrain.friends.InvitationPersistance; import fr.uhp.nobrain.mvc.Model; import fr.uhp.nobrain.mvc.View; import fr.uhp.nobrain.player.PlayerPersistance; import fr.uhp.nobrain.tools.Context; public class PlayerInviteView extends JPanel implements View{ private PlayerInvite model; private static final long serialVersionUID = 1L; private ArrayList<JLabel> name; private ArrayList<JButton> invite; private JButton returnB; public void initialize(Model m) { model = (PlayerInvite) m; name = new ArrayList<JLabel>(); invite = new ArrayList<JButton>(); returnB = new JButton("Return"); JPanel inpan = new JPanel(); inpan.setLayout(new GridLayout(model.getPlayers().size(),1)); boolean b = false; for(int i = 0; i<model.getPlayers().size();i++){ try { JLabel l = new JLabel(model.getPlayers().get(i).getName()); l.setPreferredSize(new Dimension(180,20)); l.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); name.add(l); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } try { if (!InvitationPersistance.alreadyExists(new Invitation(Context.getCurrentPlayer(), PlayerPersistance.select(getNames().get(i).getText())))) invite.add(new JButton("Invite")); else { JButton button = new JButton("Sent"); button.setEnabled(false); invite.add(button); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } JPanel line = new JPanel(); line.add(name.get(i)); line.add(invite.get(i)); if(b) line.setBackground(Color.lightGray); b = !b; line.setPreferredSize(new Dimension(290,20)); inpan.add(line); } inpan.setPreferredSize(new Dimension(290,440)); JScrollPane jsp = new JScrollPane(inpan); setLayout(new BorderLayout()); add(jsp,BorderLayout.CENTER); add(returnB,BorderLayout.SOUTH); model.attach(this); makeController(); } public JButton getReturnB() { return returnB; } public ArrayList<JLabel> getNames() { return name; } public ArrayList<JButton> getInvite() { return invite; } @Override public void makeController() { PlayerInviteController pic = new PlayerInviteController(); pic.initialize(model, this); } @Override public void update(Observable o, Object arg) { // TODO Auto-generated method stub } }
2,775
0.705946
0.699099
116
22.922413
19.070717
87
false
false
0
0
0
0
0
0
2.362069
false
false
3
178e97fe54d74cb03c4dd2620b837b3f4784ecdb
15,487,652,071,483
a721d9ffd9e6add1ea4625ec4d4cdcea9a1b53a8
/Pro_170906_SaveMyWallet/src/es/savemywallet/web/controllers/WalletController.java
5b705550ef87dc77fb221f2fb24cdab0cac27ea6
[]
no_license
hugo1988/SaveMyWallet
https://github.com/hugo1988/SaveMyWallet
588735950bfc1e8863bbf0a1e6987e786ef3220e
77410f17c678da0d621e615b7ad229bcfaa4f4af
refs/heads/master
2021-06-24T17:47:21.849000
2017-09-12T07:03:50
2017-09-12T07:03:50
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package es.savemywallet.web.controllers; import java.io.IOException; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; 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.servlet.ModelAndView; import es.savemywallet.com.beans.User; import es.savemywallet.com.beans.Wallet; import es.savemywallet.com.services.WalletService; import es.savemywallet.com.utils.LoginStatus; import es.savemywallet.com.utils.TemplateLoader; @Controller public class WalletController { /* * -------------------------------------------------------------------------------- * CREATE OBJECT * -------------------------------------------------------------------------------- */ /** * Crear wallet (FORMULARIO) * (requiere estar logueado) * Abre la vista de formulario para añadir una nueva wallet * * @param request HttpServletRequest * @param response HttpServletResponse * * @return ModelAndView */ @RequestMapping(value = { "/create_wallet" }) public ModelAndView createWallet(HttpServletRequest request, HttpServletResponse response){ //- TEMPLATE LOADER String view = "create_wallet.jsp"; String title = "Crear Cartera"; String menu = "wallet"; String submenu = "create_wallet"; ModelAndView modelAndView = TemplateLoader.start(request, view, title, menu, submenu); //-- Requerir login Object[] loginStatus = LoginStatus.gete(response, request); if (!(boolean) loginStatus[0]) { response = (HttpServletResponse) loginStatus[1]; return null; } //-CONTROLLER FUNCTIONS //--Session HttpSession session = request.getSession(true); User user = (User) session.getAttribute("user"); modelAndView.addObject("user", user); return modelAndView; } // -------------------------------------------------------------------------------- /** * Register new wallet * * @param request * @param nameWallet * @param descriptionWallet * @return */ @RequestMapping(value = "/add_wallet", method = RequestMethod.POST) public ModelAndView addWallet(HttpServletRequest request, HttpServletResponse response, @RequestParam("name") String name, @RequestParam("description") String description) { //-- Requerir login Object[] loginStatus = LoginStatus.gete(response, request); if (!(boolean) loginStatus[0]) { response = (HttpServletResponse) loginStatus[1]; return null; } //-CONTROLLER FUNCTIONS //--Session HttpSession session = request.getSession(true); User user = (User) session.getAttribute("user"); Wallet wallet = new Wallet(); wallet.setUserId(user.getId()); wallet.setName(name); wallet.setDescription(description); WalletService walletService = new WalletService(); walletService.addWallet(wallet); try { response.sendRedirect("create_wallet.html"); } catch (IOException e) { e.printStackTrace(); } return null; } /* * -------------------------------------------------------------------------------- * EDIT OBJECT * -------------------------------------------------------------------------------- */ /** * Edit send form * * @return */ @RequestMapping(value = "/edit_wallet", method = RequestMethod.GET) public ModelAndView editWallet(HttpServletRequest request, HttpServletResponse response, @RequestParam("idWallet") int idWallet) { //- TEMPLATE LOADER String view = "edit_wallet.jsp"; String title = "Editar Cartera"; String menu = "wallet"; String submenu = "create_wallet"; ModelAndView modelAndView = TemplateLoader.start(request, view, title, menu, submenu); //-- Requerir login Object[] loginStatus = LoginStatus.gete(response, request); if (!(boolean) loginStatus[0]) { response = (HttpServletResponse) loginStatus[1]; return null; } //-CONTROLLER FUNCTIONS //--Session HttpSession session = request.getSession(true); User user = (User) session.getAttribute("user"); modelAndView.addObject("user", user); WalletService walletService = new WalletService(); Wallet wallet = walletService.findByPrimaryIdWallet(idWallet); modelAndView.addObject("wallet", wallet); return modelAndView; } // -------------------------------------------------------------------------------- /** * Update wallet * * @param request * @param nameWallet * @param descriptionWallet * @return */ @RequestMapping(value = "/update_wallet", method = RequestMethod.POST) public ModelAndView updateWallet(HttpServletRequest request, HttpServletResponse response, @RequestParam("id_wallet") int idWallet, @RequestParam("name_wallet") String nameWallet, @RequestParam("description") String description) { //-- Requerir login Object[] loginStatus = LoginStatus.gete(response, request); if (!(boolean) loginStatus[0]) { response = (HttpServletResponse) loginStatus[1]; return null; } //-CONTROLLER FUNCTIONS //--Session HttpSession session = request.getSession(true); User user = (User) session.getAttribute("user"); Wallet wallet = new Wallet(); wallet.setId(idWallet); wallet.setUserId(user.getId()); wallet.setName(nameWallet); wallet.setDescription(description); WalletService walletService = new WalletService(); walletService.updateWallet(wallet); try { response.sendRedirect("list_wallet.html"); } catch (IOException e) { e.printStackTrace(); } return null; } /* * -------------------------------------------------------------------------------- * DELETE OBJECT * -------------------------------------------------------------------------------- */ /** * Elimina una Wallet de un usuario * (requiere estar logueado) * Elimina la wallet del usuario registrado cuyo id se obtiene como parámetro * * @param request HttpServletRequest * @param response HttpServletResponse * @param idWallet ID de la wallet a eliminar * * @return ModelAndView */ @RequestMapping(value = "/delete_wallet", method = RequestMethod.GET) public ModelAndView deleteteWallet(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") int id) { //-- Requerir login Object[] loginStatus = LoginStatus.gete(response, request); if (!(boolean) loginStatus[0]) { response = (HttpServletResponse) loginStatus[1]; return null; } WalletService walletService = new WalletService(); walletService.deleteWallet(id); try { response.sendRedirect("list_wallet.html"); } catch (IOException e) { e.printStackTrace(); } return null; } /* * -------------------------------------------------------------------------------- * LIST OBJECT * -------------------------------------------------------------------------------- */ /** * Listar wallets del usuario * (requiere estar logueado) * Lista las wallet pertenecientes a la id del usuario logueado y las muestra en la vista * * @param request HttpServletRequest * @param response HttpServletResponse * * @return ModelAndView */ @RequestMapping(value = { "/main", "/", "/list_wallet" }) public ModelAndView listWallet(HttpServletRequest request, HttpServletResponse response) { //- TEMPLATE LOADER String view = "list_wallet.jsp"; String title = "Mis Carteras"; String menu = "wallet"; String submenu = "list_wallet"; ModelAndView modelAndView = TemplateLoader.start(request, view, title, menu, submenu); //Scripts modelAndView.addObject("script_modal", true); //-- Requerir login Object[] loginStatus = LoginStatus.gete(response, request); if (!(boolean) loginStatus[0]) { response = (HttpServletResponse) loginStatus[1]; return null; } //-CONTROLLER FUNCTIONS HttpSession session = request.getSession(true); User user = (User) session.getAttribute("user"); int userId = user.getId(); WalletService walletService = new WalletService(); List<Wallet> list = walletService.listWallet(userId); modelAndView.addObject("list", list); return modelAndView; } }
ISO-8859-1
Java
8,324
java
WalletController.java
Java
[]
null
[]
package es.savemywallet.web.controllers; import java.io.IOException; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; 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.servlet.ModelAndView; import es.savemywallet.com.beans.User; import es.savemywallet.com.beans.Wallet; import es.savemywallet.com.services.WalletService; import es.savemywallet.com.utils.LoginStatus; import es.savemywallet.com.utils.TemplateLoader; @Controller public class WalletController { /* * -------------------------------------------------------------------------------- * CREATE OBJECT * -------------------------------------------------------------------------------- */ /** * Crear wallet (FORMULARIO) * (requiere estar logueado) * Abre la vista de formulario para añadir una nueva wallet * * @param request HttpServletRequest * @param response HttpServletResponse * * @return ModelAndView */ @RequestMapping(value = { "/create_wallet" }) public ModelAndView createWallet(HttpServletRequest request, HttpServletResponse response){ //- TEMPLATE LOADER String view = "create_wallet.jsp"; String title = "Crear Cartera"; String menu = "wallet"; String submenu = "create_wallet"; ModelAndView modelAndView = TemplateLoader.start(request, view, title, menu, submenu); //-- Requerir login Object[] loginStatus = LoginStatus.gete(response, request); if (!(boolean) loginStatus[0]) { response = (HttpServletResponse) loginStatus[1]; return null; } //-CONTROLLER FUNCTIONS //--Session HttpSession session = request.getSession(true); User user = (User) session.getAttribute("user"); modelAndView.addObject("user", user); return modelAndView; } // -------------------------------------------------------------------------------- /** * Register new wallet * * @param request * @param nameWallet * @param descriptionWallet * @return */ @RequestMapping(value = "/add_wallet", method = RequestMethod.POST) public ModelAndView addWallet(HttpServletRequest request, HttpServletResponse response, @RequestParam("name") String name, @RequestParam("description") String description) { //-- Requerir login Object[] loginStatus = LoginStatus.gete(response, request); if (!(boolean) loginStatus[0]) { response = (HttpServletResponse) loginStatus[1]; return null; } //-CONTROLLER FUNCTIONS //--Session HttpSession session = request.getSession(true); User user = (User) session.getAttribute("user"); Wallet wallet = new Wallet(); wallet.setUserId(user.getId()); wallet.setName(name); wallet.setDescription(description); WalletService walletService = new WalletService(); walletService.addWallet(wallet); try { response.sendRedirect("create_wallet.html"); } catch (IOException e) { e.printStackTrace(); } return null; } /* * -------------------------------------------------------------------------------- * EDIT OBJECT * -------------------------------------------------------------------------------- */ /** * Edit send form * * @return */ @RequestMapping(value = "/edit_wallet", method = RequestMethod.GET) public ModelAndView editWallet(HttpServletRequest request, HttpServletResponse response, @RequestParam("idWallet") int idWallet) { //- TEMPLATE LOADER String view = "edit_wallet.jsp"; String title = "Editar Cartera"; String menu = "wallet"; String submenu = "create_wallet"; ModelAndView modelAndView = TemplateLoader.start(request, view, title, menu, submenu); //-- Requerir login Object[] loginStatus = LoginStatus.gete(response, request); if (!(boolean) loginStatus[0]) { response = (HttpServletResponse) loginStatus[1]; return null; } //-CONTROLLER FUNCTIONS //--Session HttpSession session = request.getSession(true); User user = (User) session.getAttribute("user"); modelAndView.addObject("user", user); WalletService walletService = new WalletService(); Wallet wallet = walletService.findByPrimaryIdWallet(idWallet); modelAndView.addObject("wallet", wallet); return modelAndView; } // -------------------------------------------------------------------------------- /** * Update wallet * * @param request * @param nameWallet * @param descriptionWallet * @return */ @RequestMapping(value = "/update_wallet", method = RequestMethod.POST) public ModelAndView updateWallet(HttpServletRequest request, HttpServletResponse response, @RequestParam("id_wallet") int idWallet, @RequestParam("name_wallet") String nameWallet, @RequestParam("description") String description) { //-- Requerir login Object[] loginStatus = LoginStatus.gete(response, request); if (!(boolean) loginStatus[0]) { response = (HttpServletResponse) loginStatus[1]; return null; } //-CONTROLLER FUNCTIONS //--Session HttpSession session = request.getSession(true); User user = (User) session.getAttribute("user"); Wallet wallet = new Wallet(); wallet.setId(idWallet); wallet.setUserId(user.getId()); wallet.setName(nameWallet); wallet.setDescription(description); WalletService walletService = new WalletService(); walletService.updateWallet(wallet); try { response.sendRedirect("list_wallet.html"); } catch (IOException e) { e.printStackTrace(); } return null; } /* * -------------------------------------------------------------------------------- * DELETE OBJECT * -------------------------------------------------------------------------------- */ /** * Elimina una Wallet de un usuario * (requiere estar logueado) * Elimina la wallet del usuario registrado cuyo id se obtiene como parámetro * * @param request HttpServletRequest * @param response HttpServletResponse * @param idWallet ID de la wallet a eliminar * * @return ModelAndView */ @RequestMapping(value = "/delete_wallet", method = RequestMethod.GET) public ModelAndView deleteteWallet(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") int id) { //-- Requerir login Object[] loginStatus = LoginStatus.gete(response, request); if (!(boolean) loginStatus[0]) { response = (HttpServletResponse) loginStatus[1]; return null; } WalletService walletService = new WalletService(); walletService.deleteWallet(id); try { response.sendRedirect("list_wallet.html"); } catch (IOException e) { e.printStackTrace(); } return null; } /* * -------------------------------------------------------------------------------- * LIST OBJECT * -------------------------------------------------------------------------------- */ /** * Listar wallets del usuario * (requiere estar logueado) * Lista las wallet pertenecientes a la id del usuario logueado y las muestra en la vista * * @param request HttpServletRequest * @param response HttpServletResponse * * @return ModelAndView */ @RequestMapping(value = { "/main", "/", "/list_wallet" }) public ModelAndView listWallet(HttpServletRequest request, HttpServletResponse response) { //- TEMPLATE LOADER String view = "list_wallet.jsp"; String title = "Mis Carteras"; String menu = "wallet"; String submenu = "list_wallet"; ModelAndView modelAndView = TemplateLoader.start(request, view, title, menu, submenu); //Scripts modelAndView.addObject("script_modal", true); //-- Requerir login Object[] loginStatus = LoginStatus.gete(response, request); if (!(boolean) loginStatus[0]) { response = (HttpServletResponse) loginStatus[1]; return null; } //-CONTROLLER FUNCTIONS HttpSession session = request.getSession(true); User user = (User) session.getAttribute("user"); int userId = user.getId(); WalletService walletService = new WalletService(); List<Wallet> list = walletService.listWallet(userId); modelAndView.addObject("list", list); return modelAndView; } }
8,324
0.638308
0.636866
286
28.097902
25.354084
94
false
false
0
0
0
0
0
0
2.146853
false
false
3
72e421cae34e9841165afc0257acd26fd64d3d8b
26,190,710,627,422
bcaa577ee0abd6c8d02734fdaafe1de71783a2fa
/app/src/main/java/lu/maycrosoft/transporteit/lu/NextStationsURLHandler.java
cdc0ea05e08ca13a36f1e33d8e6a7549729458d7
[]
no_license
Mayni91/Transporteit.lu
https://github.com/Mayni91/Transporteit.lu
df433e98af918bd9b74d1a6db7f1215bf4ce5dcd
4d029aabf07ab67c1f357e7a71486e039d5f7296
refs/heads/master
2020-06-28T08:31:29.071000
2017-01-17T14:31:54
2017-01-17T14:31:54
74,464,953
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package lu.maycrosoft.transporteit.lu; import android.os.AsyncTask; import android.util.Log; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; /** * This class handles all connections in the background which are called when the user interacts with a marker, * such that he can be shown all the concerned information of the selected busstation. * This information is called over tha API url with a given ID of a station. * This is again done by an AsyncTask such that we can assure that the application stays responsive. * */ public class NextStationsURLHandler extends AsyncTask<Void, Void, ArrayList<BusInformation>> { private String id; public NextStationsURLHandler(String id){ this.id = id; } @Override protected ArrayList<BusInformation> doInBackground(Void... params) { HttpURLConnection urlConnection = null; BufferedReader reader = null; ArrayList<BusInformation> busInformations = new ArrayList<>(); String content = ""; try { id=id.replaceAll(" ","%20"); URL url = new URL("http://travelplanner.mobiliteit.lu/restproxy/departureBoard?accessId=cdt&format=json&id="+id); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // Read the input stream into a String InputStream inputStream = urlConnection.getInputStream(); Log.d("ERROR", inputStream.toString()); if (inputStream == null) { // Nothing to do. Log.i("INPUT", "Test"); return null; } reader = new BufferedReader(new InputStreamReader(inputStream, "UTF8")); String line; while ((line = reader.readLine()) != null) { content += line; } busInformations = getBusInformationFromJSON(content); } catch(FileNotFoundException exception) { if( busInformations == null){ ArrayList<String> times = new ArrayList<>(); times.add("No Information"); BusInformation busInfo = new BusInformation("No Information",times,"No Information"); busInformations.add(busInfo); } } catch (IOException e) { e.printStackTrace(); return null; } finally{ if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (final IOException e) { Log.e("PlaceholderFragment", "Error closing stream", e); } } } return busInformations; } private ArrayList<BusInformation> getBusInformationFromJSON(String json){ ArrayList<BusInformation> busInformations = new ArrayList<>(); ArrayList<BusInformation> tempBusInformations = new ArrayList<>(); try { JSONObject jsonObj = new JSONObject(json); if (jsonObj.has("Departure")) { JSONArray listOfBusInformation = (JSONArray) jsonObj.get("Departure"); for (int i = 0; i < listOfBusInformation.length(); i++) { ArrayList<String> times = new ArrayList<>(); JSONObject busInformation = listOfBusInformation.getJSONObject(i); times.add((String) busInformation.get("time")); BusInformation busInfo = new BusInformation((String) busInformation.get("name"), times, (String) busInformation.get("direction")); tempBusInformations.add(busInfo); } ArrayList<String> times = new ArrayList<>(); busInformations = tempBusInformations; for (int i = 0; i < busInformations.size(); i++) { for (int j = i + 1; j < tempBusInformations.size(); j++) { if (busInformations.get(i).getBusLine().equals(tempBusInformations.get(j).getBusLine()) && busInformations.get(i).getDestinationStationName().equals(tempBusInformations.get(j).getDestinationStationName())) { times.add(tempBusInformations.get(j).getTimes().get(0)); busInformations.remove(j); } } busInformations.get(i).setTimes(times); } for (int i = 0; i < busInformations.size(); i++) { Collections.sort(busInformations.get(i).getTimes().subList(0, busInformations.get(i).getTimes().size())); } } else{ ArrayList<String> times = new ArrayList<>(); times.add(""); BusInformation busInfo = new BusInformation("",times,""); busInformations.add(busInfo); } } catch (JSONException e) { e.printStackTrace(); } Map<String, BusInformation> map = new LinkedHashMap<>(); for (BusInformation businfo : busInformations) { map.put(businfo.getId(), businfo); } busInformations.clear(); busInformations.addAll(map.values()); return busInformations; } }
UTF-8
Java
5,843
java
NextStationsURLHandler.java
Java
[]
null
[]
package lu.maycrosoft.transporteit.lu; import android.os.AsyncTask; import android.util.Log; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; /** * This class handles all connections in the background which are called when the user interacts with a marker, * such that he can be shown all the concerned information of the selected busstation. * This information is called over tha API url with a given ID of a station. * This is again done by an AsyncTask such that we can assure that the application stays responsive. * */ public class NextStationsURLHandler extends AsyncTask<Void, Void, ArrayList<BusInformation>> { private String id; public NextStationsURLHandler(String id){ this.id = id; } @Override protected ArrayList<BusInformation> doInBackground(Void... params) { HttpURLConnection urlConnection = null; BufferedReader reader = null; ArrayList<BusInformation> busInformations = new ArrayList<>(); String content = ""; try { id=id.replaceAll(" ","%20"); URL url = new URL("http://travelplanner.mobiliteit.lu/restproxy/departureBoard?accessId=cdt&format=json&id="+id); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // Read the input stream into a String InputStream inputStream = urlConnection.getInputStream(); Log.d("ERROR", inputStream.toString()); if (inputStream == null) { // Nothing to do. Log.i("INPUT", "Test"); return null; } reader = new BufferedReader(new InputStreamReader(inputStream, "UTF8")); String line; while ((line = reader.readLine()) != null) { content += line; } busInformations = getBusInformationFromJSON(content); } catch(FileNotFoundException exception) { if( busInformations == null){ ArrayList<String> times = new ArrayList<>(); times.add("No Information"); BusInformation busInfo = new BusInformation("No Information",times,"No Information"); busInformations.add(busInfo); } } catch (IOException e) { e.printStackTrace(); return null; } finally{ if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (final IOException e) { Log.e("PlaceholderFragment", "Error closing stream", e); } } } return busInformations; } private ArrayList<BusInformation> getBusInformationFromJSON(String json){ ArrayList<BusInformation> busInformations = new ArrayList<>(); ArrayList<BusInformation> tempBusInformations = new ArrayList<>(); try { JSONObject jsonObj = new JSONObject(json); if (jsonObj.has("Departure")) { JSONArray listOfBusInformation = (JSONArray) jsonObj.get("Departure"); for (int i = 0; i < listOfBusInformation.length(); i++) { ArrayList<String> times = new ArrayList<>(); JSONObject busInformation = listOfBusInformation.getJSONObject(i); times.add((String) busInformation.get("time")); BusInformation busInfo = new BusInformation((String) busInformation.get("name"), times, (String) busInformation.get("direction")); tempBusInformations.add(busInfo); } ArrayList<String> times = new ArrayList<>(); busInformations = tempBusInformations; for (int i = 0; i < busInformations.size(); i++) { for (int j = i + 1; j < tempBusInformations.size(); j++) { if (busInformations.get(i).getBusLine().equals(tempBusInformations.get(j).getBusLine()) && busInformations.get(i).getDestinationStationName().equals(tempBusInformations.get(j).getDestinationStationName())) { times.add(tempBusInformations.get(j).getTimes().get(0)); busInformations.remove(j); } } busInformations.get(i).setTimes(times); } for (int i = 0; i < busInformations.size(); i++) { Collections.sort(busInformations.get(i).getTimes().subList(0, busInformations.get(i).getTimes().size())); } } else{ ArrayList<String> times = new ArrayList<>(); times.add(""); BusInformation busInfo = new BusInformation("",times,""); busInformations.add(busInfo); } } catch (JSONException e) { e.printStackTrace(); } Map<String, BusInformation> map = new LinkedHashMap<>(); for (BusInformation businfo : busInformations) { map.put(businfo.getId(), businfo); } busInformations.clear(); busInformations.addAll(map.values()); return busInformations; } }
5,843
0.576416
0.574876
161
35.291927
31.371674
151
false
false
0
0
0
0
0
0
0.602484
false
false
3
f0747648281b052a6dff586147635411d23fda49
27,814,208,229,421
691599a1fcfacd488aa04d78e804c2e0c0d69459
/JavaPractice/src/com/practice/oops/interfacekeyword/PracticeBattery.java
7d91c82218aadb03761f483119e8f27559d07e28
[]
no_license
SudhaReddy2016/java-practice
https://github.com/SudhaReddy2016/java-practice
73f18d7dc9031669d60da5a561997f54db5d577e
d786fcc12d83ee4899c9fd7c7d90d9c236451073
refs/heads/master
2022-06-05T18:54:22.851000
2020-05-02T04:33:17
2020-05-02T04:33:17
260,610,537
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.practice.oops.interfacekeyword; public interface PracticeBattery { public String battery(); public void battery1(); }
UTF-8
Java
143
java
PracticeBattery.java
Java
[]
null
[]
package com.practice.oops.interfacekeyword; public interface PracticeBattery { public String battery(); public void battery1(); }
143
0.734266
0.727273
8
16.125
16.571342
43
false
false
0
0
0
0
0
0
0.75
false
false
3
6b30a53cb7e90fbf1957a597d7ed31dfe2cc167b
20,177,756,406,595
bfc9cde4a227705699cf0643d47c56fd63eb6994
/lib-common-core/src/main/java/com/gcml/common/app/lifecycle/AppDelegate.java
0ee202d4e5e6425027d0fab9b3fa06938e21105a
[]
no_license
dcy000/MLxiao
https://github.com/dcy000/MLxiao
debcf371230832bef283507dedbbff8cd6271fb7
02df66d1d22c3a0658ef1a86acb28885c2dbb691
refs/heads/master
2021-01-20T10:14:11.370000
2018-10-19T10:23:02
2018-10-19T10:23:02
101,597,000
4
3
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.gcml.common.app.lifecycle; import android.annotation.SuppressLint; import android.app.Activity; import android.app.Application; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.view.View; import com.gcml.common.utils.ManifestParser; import java.util.ArrayList; import java.util.List; import timber.log.Timber; /** * Created by afirez on 2018/6/15. */ public enum AppDelegate implements AppLifecycleCallbacks { @SuppressLint("StaticFieldLeak") INSTANCE; private static final String APP_LIFECYCLE_CALLBACKS = "AppLifecycleCallbacks"; private static final String ACTIVITY_LIFECYCLE_CALLBACKS = "ActivityLifecycleCallbacks"; private static final String FRAGMENT_LIFECYCLE_CALLBACKS = "FragmentLifecycleCallbacks"; private Application app; public Application app() { return app; } private ManifestParser<AppLifecycleCallbacks> mAppLifecycleCallbacksManifestParser; private final ArrayList<AppLifecycleCallbacks> mAppLifecycleCallbacksList = new ArrayList<>(); private Application.ActivityLifecycleCallbacks mAppActivityLifecycleCallbacks; private ManifestParser<Application.ActivityLifecycleCallbacks> mActivityLifecycleCallbacksManifestParser; private final ArrayList<Application.ActivityLifecycleCallbacks> mActivityLifecycleCallbacksList = new ArrayList<>(); private FragmentManager.FragmentLifecycleCallbacks mAppFragmentLifecycleCallbacks; private ManifestParser<FragmentManager.FragmentLifecycleCallbacks> mFragmentLifecycleCallbacksManifestParser; private final ArrayList<FragmentManager.FragmentLifecycleCallbacks> mFragmentLifecycleCallbacksList = new ArrayList<>(); @Override public void attachBaseContext(Application app, Context base) { this.app = app; if (mAppLifecycleCallbacksManifestParser == null) { mAppLifecycleCallbacksManifestParser = new ManifestParser<>(app, APP_LIFECYCLE_CALLBACKS); //parse AppLifecycleCallbacks List<AppLifecycleCallbacks> appLifecycleCallbacksList = mAppLifecycleCallbacksManifestParser.parse(); mAppLifecycleCallbacksList.clear(); mAppLifecycleCallbacksList.addAll(appLifecycleCallbacksList); } for (AppLifecycleCallbacks appLifecycleCallbacks : mAppLifecycleCallbacksList) { if (appLifecycleCallbacks != null) { appLifecycleCallbacks.attachBaseContext(app, base); Timber.i("attachBaseContext[after]: %s", appLifecycleCallbacks); } } Timber.i("attachBaseContext[after]: %s", this); } @Override public void onCreate(Application app) { for (AppLifecycleCallbacks appLifecycleCallbacks : mAppLifecycleCallbacksList) { if (appLifecycleCallbacks != null) { appLifecycleCallbacks.onCreate(app); Timber.i("onCreate: %s", appLifecycleCallbacks); } } app.registerActivityLifecycleCallbacks(appActivityLifecycleCallbacks()); if (mActivityLifecycleCallbacksManifestParser == null) { mActivityLifecycleCallbacksManifestParser = new ManifestParser<>(app, ACTIVITY_LIFECYCLE_CALLBACKS); //parse ActivityLifecycleCallbacks List<Application.ActivityLifecycleCallbacks> activityLifecycleCallbacksList = mActivityLifecycleCallbacksManifestParser.parse(); mActivityLifecycleCallbacksList.clear(); mActivityLifecycleCallbacksList.addAll(activityLifecycleCallbacksList); } for (Application.ActivityLifecycleCallbacks activityLifecycleCallbacks : mActivityLifecycleCallbacksList) { if (activityLifecycleCallbacks != null) { app.registerActivityLifecycleCallbacks(activityLifecycleCallbacks); } } if (mFragmentLifecycleCallbacksManifestParser == null) { mFragmentLifecycleCallbacksManifestParser = new ManifestParser<>(app, FRAGMENT_LIFECYCLE_CALLBACKS); //parse FragmentLifecycleCallbacks List<FragmentManager.FragmentLifecycleCallbacks> fragmentLifecycleCallbacksList = mFragmentLifecycleCallbacksManifestParser.parse(); mFragmentLifecycleCallbacksList.clear(); mFragmentLifecycleCallbacksList.addAll(fragmentLifecycleCallbacksList); } Timber.i("onCreate[after]: %s", this); } @Override public void onTerminate(Application app) { for (AppLifecycleCallbacks appLifecycleCallbacks : mAppLifecycleCallbacksList) { if (appLifecycleCallbacks != null) { appLifecycleCallbacks.onTerminate(app); Timber.i("onCreate[after]: %s", appLifecycleCallbacks); } } mAppLifecycleCallbacksList.clear(); mAppLifecycleCallbacksManifestParser = null; if (mAppActivityLifecycleCallbacks != null) { app.unregisterActivityLifecycleCallbacks(mAppActivityLifecycleCallbacks); mAppActivityLifecycleCallbacks = null; } for (Application.ActivityLifecycleCallbacks activityLifecycleCallbacks : mActivityLifecycleCallbacksList) { if (activityLifecycleCallbacks != null) { app.unregisterActivityLifecycleCallbacks(activityLifecycleCallbacks); } } mActivityLifecycleCallbacksList.clear(); mActivityLifecycleCallbacksManifestParser = null; mAppFragmentLifecycleCallbacks = null; mFragmentLifecycleCallbacksList.clear(); mFragmentLifecycleCallbacksManifestParser = null; Timber.i("onTerminate[after]: %s", this); } private Application.ActivityLifecycleCallbacks appActivityLifecycleCallbacks() { if (mAppActivityLifecycleCallbacks == null) { mAppActivityLifecycleCallbacks = new Application.ActivityLifecycleCallbacks() { @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) { Timber.i("onActivityCreated: %s %s", activity, savedInstanceState); if (activity instanceof FragmentActivity) { FragmentManager fm = ((FragmentActivity) activity).getSupportFragmentManager(); fm.registerFragmentLifecycleCallbacks(appFragmentLifecycleCallbacks(), true); for (FragmentManager.FragmentLifecycleCallbacks fragmentLifecycleCallbacks : mFragmentLifecycleCallbacksList) { fm.registerFragmentLifecycleCallbacks(fragmentLifecycleCallbacks, true); } } } @Override public void onActivityStarted(Activity activity) { Timber.i("onActivityStarted: %s", activity); } @Override public void onActivityResumed(Activity activity) { Timber.i("onActivityResumed: %s", activity); } @Override public void onActivityPaused(Activity activity) { Timber.i("onActivityPaused: %s", activity); } @Override public void onActivityStopped(Activity activity) { Timber.i("onActivityStopped: %s", activity); } @Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) { Timber.i("onActivitySaveInstanceState: %s %s", activity, outState); } @Override public void onActivityDestroyed(Activity activity) { Timber.i("onActivityDestroyed: %s", activity); } }; } return mAppActivityLifecycleCallbacks; } private FragmentManager.FragmentLifecycleCallbacks appFragmentLifecycleCallbacks() { if (mAppFragmentLifecycleCallbacks == null) { mAppFragmentLifecycleCallbacks = new FragmentManager.FragmentLifecycleCallbacks() { @Override public void onFragmentPreAttached(FragmentManager fm, Fragment f, Context context) { Timber.i("onFragmentPreAttached: %s %s", f, fm); } @Override public void onFragmentAttached(FragmentManager fm, Fragment f, Context context) { Timber.i("onFragmentAttached: %s %s", f, fm); } @Override public void onFragmentPreCreated(FragmentManager fm, Fragment f, Bundle savedInstanceState) { Timber.i("onFragmentPreCreated: %s %s", f, fm); } @Override public void onFragmentCreated(FragmentManager fm, Fragment f, Bundle savedInstanceState) { Timber.i("onFragmentCreated: %s %s", f, fm); } @Override public void onFragmentActivityCreated(FragmentManager fm, Fragment f, Bundle savedInstanceState) { Timber.i("onFragmentActivityCreated: %s %s", f, fm); } @Override public void onFragmentViewCreated(FragmentManager fm, Fragment f, View v, Bundle savedInstanceState) { Timber.i("onFragmentViewCreated: %s %s", f, fm); } @Override public void onFragmentStarted(FragmentManager fm, Fragment f) { Timber.i("onFragmentStarted: %s %s", f, fm); } @Override public void onFragmentResumed(FragmentManager fm, Fragment f) { Timber.i("onFragmentResumed: %s %s", f, fm); } @Override public void onFragmentPaused(FragmentManager fm, Fragment f) { Timber.i("onFragmentPaused: %s %s", f, fm); } @Override public void onFragmentStopped(FragmentManager fm, Fragment f) { Timber.i("onFragmentStopped: %s %s", f, fm); } @Override public void onFragmentSaveInstanceState(FragmentManager fm, Fragment f, Bundle outState) { Timber.i("onFragmentSaveInstanceState: %s %s %s", f, fm, outState); } @Override public void onFragmentViewDestroyed(FragmentManager fm, Fragment f) { Timber.i("onFragmentViewDestroyed: %s %s", f, fm); } @Override public void onFragmentDestroyed(FragmentManager fm, Fragment f) { Timber.i("onFragmentDestroyed: %s %s", f, fm); } @Override public void onFragmentDetached(FragmentManager fm, Fragment f) { Timber.i("onFragmentDetached: %s %s", f, fm); } }; } return mAppFragmentLifecycleCallbacks; } }
UTF-8
Java
11,228
java
AppDelegate.java
Java
[ { "context": "ist;\n\nimport timber.log.Timber;\n\n/**\n * Created by afirez on 2018/6/15.\n */\n\npublic enum AppDelegate implem", "end": 510, "score": 0.9997007250785828, "start": 504, "tag": "USERNAME", "value": "afirez" } ]
null
[]
package com.gcml.common.app.lifecycle; import android.annotation.SuppressLint; import android.app.Activity; import android.app.Application; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.view.View; import com.gcml.common.utils.ManifestParser; import java.util.ArrayList; import java.util.List; import timber.log.Timber; /** * Created by afirez on 2018/6/15. */ public enum AppDelegate implements AppLifecycleCallbacks { @SuppressLint("StaticFieldLeak") INSTANCE; private static final String APP_LIFECYCLE_CALLBACKS = "AppLifecycleCallbacks"; private static final String ACTIVITY_LIFECYCLE_CALLBACKS = "ActivityLifecycleCallbacks"; private static final String FRAGMENT_LIFECYCLE_CALLBACKS = "FragmentLifecycleCallbacks"; private Application app; public Application app() { return app; } private ManifestParser<AppLifecycleCallbacks> mAppLifecycleCallbacksManifestParser; private final ArrayList<AppLifecycleCallbacks> mAppLifecycleCallbacksList = new ArrayList<>(); private Application.ActivityLifecycleCallbacks mAppActivityLifecycleCallbacks; private ManifestParser<Application.ActivityLifecycleCallbacks> mActivityLifecycleCallbacksManifestParser; private final ArrayList<Application.ActivityLifecycleCallbacks> mActivityLifecycleCallbacksList = new ArrayList<>(); private FragmentManager.FragmentLifecycleCallbacks mAppFragmentLifecycleCallbacks; private ManifestParser<FragmentManager.FragmentLifecycleCallbacks> mFragmentLifecycleCallbacksManifestParser; private final ArrayList<FragmentManager.FragmentLifecycleCallbacks> mFragmentLifecycleCallbacksList = new ArrayList<>(); @Override public void attachBaseContext(Application app, Context base) { this.app = app; if (mAppLifecycleCallbacksManifestParser == null) { mAppLifecycleCallbacksManifestParser = new ManifestParser<>(app, APP_LIFECYCLE_CALLBACKS); //parse AppLifecycleCallbacks List<AppLifecycleCallbacks> appLifecycleCallbacksList = mAppLifecycleCallbacksManifestParser.parse(); mAppLifecycleCallbacksList.clear(); mAppLifecycleCallbacksList.addAll(appLifecycleCallbacksList); } for (AppLifecycleCallbacks appLifecycleCallbacks : mAppLifecycleCallbacksList) { if (appLifecycleCallbacks != null) { appLifecycleCallbacks.attachBaseContext(app, base); Timber.i("attachBaseContext[after]: %s", appLifecycleCallbacks); } } Timber.i("attachBaseContext[after]: %s", this); } @Override public void onCreate(Application app) { for (AppLifecycleCallbacks appLifecycleCallbacks : mAppLifecycleCallbacksList) { if (appLifecycleCallbacks != null) { appLifecycleCallbacks.onCreate(app); Timber.i("onCreate: %s", appLifecycleCallbacks); } } app.registerActivityLifecycleCallbacks(appActivityLifecycleCallbacks()); if (mActivityLifecycleCallbacksManifestParser == null) { mActivityLifecycleCallbacksManifestParser = new ManifestParser<>(app, ACTIVITY_LIFECYCLE_CALLBACKS); //parse ActivityLifecycleCallbacks List<Application.ActivityLifecycleCallbacks> activityLifecycleCallbacksList = mActivityLifecycleCallbacksManifestParser.parse(); mActivityLifecycleCallbacksList.clear(); mActivityLifecycleCallbacksList.addAll(activityLifecycleCallbacksList); } for (Application.ActivityLifecycleCallbacks activityLifecycleCallbacks : mActivityLifecycleCallbacksList) { if (activityLifecycleCallbacks != null) { app.registerActivityLifecycleCallbacks(activityLifecycleCallbacks); } } if (mFragmentLifecycleCallbacksManifestParser == null) { mFragmentLifecycleCallbacksManifestParser = new ManifestParser<>(app, FRAGMENT_LIFECYCLE_CALLBACKS); //parse FragmentLifecycleCallbacks List<FragmentManager.FragmentLifecycleCallbacks> fragmentLifecycleCallbacksList = mFragmentLifecycleCallbacksManifestParser.parse(); mFragmentLifecycleCallbacksList.clear(); mFragmentLifecycleCallbacksList.addAll(fragmentLifecycleCallbacksList); } Timber.i("onCreate[after]: %s", this); } @Override public void onTerminate(Application app) { for (AppLifecycleCallbacks appLifecycleCallbacks : mAppLifecycleCallbacksList) { if (appLifecycleCallbacks != null) { appLifecycleCallbacks.onTerminate(app); Timber.i("onCreate[after]: %s", appLifecycleCallbacks); } } mAppLifecycleCallbacksList.clear(); mAppLifecycleCallbacksManifestParser = null; if (mAppActivityLifecycleCallbacks != null) { app.unregisterActivityLifecycleCallbacks(mAppActivityLifecycleCallbacks); mAppActivityLifecycleCallbacks = null; } for (Application.ActivityLifecycleCallbacks activityLifecycleCallbacks : mActivityLifecycleCallbacksList) { if (activityLifecycleCallbacks != null) { app.unregisterActivityLifecycleCallbacks(activityLifecycleCallbacks); } } mActivityLifecycleCallbacksList.clear(); mActivityLifecycleCallbacksManifestParser = null; mAppFragmentLifecycleCallbacks = null; mFragmentLifecycleCallbacksList.clear(); mFragmentLifecycleCallbacksManifestParser = null; Timber.i("onTerminate[after]: %s", this); } private Application.ActivityLifecycleCallbacks appActivityLifecycleCallbacks() { if (mAppActivityLifecycleCallbacks == null) { mAppActivityLifecycleCallbacks = new Application.ActivityLifecycleCallbacks() { @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) { Timber.i("onActivityCreated: %s %s", activity, savedInstanceState); if (activity instanceof FragmentActivity) { FragmentManager fm = ((FragmentActivity) activity).getSupportFragmentManager(); fm.registerFragmentLifecycleCallbacks(appFragmentLifecycleCallbacks(), true); for (FragmentManager.FragmentLifecycleCallbacks fragmentLifecycleCallbacks : mFragmentLifecycleCallbacksList) { fm.registerFragmentLifecycleCallbacks(fragmentLifecycleCallbacks, true); } } } @Override public void onActivityStarted(Activity activity) { Timber.i("onActivityStarted: %s", activity); } @Override public void onActivityResumed(Activity activity) { Timber.i("onActivityResumed: %s", activity); } @Override public void onActivityPaused(Activity activity) { Timber.i("onActivityPaused: %s", activity); } @Override public void onActivityStopped(Activity activity) { Timber.i("onActivityStopped: %s", activity); } @Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) { Timber.i("onActivitySaveInstanceState: %s %s", activity, outState); } @Override public void onActivityDestroyed(Activity activity) { Timber.i("onActivityDestroyed: %s", activity); } }; } return mAppActivityLifecycleCallbacks; } private FragmentManager.FragmentLifecycleCallbacks appFragmentLifecycleCallbacks() { if (mAppFragmentLifecycleCallbacks == null) { mAppFragmentLifecycleCallbacks = new FragmentManager.FragmentLifecycleCallbacks() { @Override public void onFragmentPreAttached(FragmentManager fm, Fragment f, Context context) { Timber.i("onFragmentPreAttached: %s %s", f, fm); } @Override public void onFragmentAttached(FragmentManager fm, Fragment f, Context context) { Timber.i("onFragmentAttached: %s %s", f, fm); } @Override public void onFragmentPreCreated(FragmentManager fm, Fragment f, Bundle savedInstanceState) { Timber.i("onFragmentPreCreated: %s %s", f, fm); } @Override public void onFragmentCreated(FragmentManager fm, Fragment f, Bundle savedInstanceState) { Timber.i("onFragmentCreated: %s %s", f, fm); } @Override public void onFragmentActivityCreated(FragmentManager fm, Fragment f, Bundle savedInstanceState) { Timber.i("onFragmentActivityCreated: %s %s", f, fm); } @Override public void onFragmentViewCreated(FragmentManager fm, Fragment f, View v, Bundle savedInstanceState) { Timber.i("onFragmentViewCreated: %s %s", f, fm); } @Override public void onFragmentStarted(FragmentManager fm, Fragment f) { Timber.i("onFragmentStarted: %s %s", f, fm); } @Override public void onFragmentResumed(FragmentManager fm, Fragment f) { Timber.i("onFragmentResumed: %s %s", f, fm); } @Override public void onFragmentPaused(FragmentManager fm, Fragment f) { Timber.i("onFragmentPaused: %s %s", f, fm); } @Override public void onFragmentStopped(FragmentManager fm, Fragment f) { Timber.i("onFragmentStopped: %s %s", f, fm); } @Override public void onFragmentSaveInstanceState(FragmentManager fm, Fragment f, Bundle outState) { Timber.i("onFragmentSaveInstanceState: %s %s %s", f, fm, outState); } @Override public void onFragmentViewDestroyed(FragmentManager fm, Fragment f) { Timber.i("onFragmentViewDestroyed: %s %s", f, fm); } @Override public void onFragmentDestroyed(FragmentManager fm, Fragment f) { Timber.i("onFragmentDestroyed: %s %s", f, fm); } @Override public void onFragmentDetached(FragmentManager fm, Fragment f) { Timber.i("onFragmentDetached: %s %s", f, fm); } }; } return mAppFragmentLifecycleCallbacks; } }
11,228
0.638582
0.637691
253
43.379448
36.069519
144
false
false
0
0
0
0
0
0
0.652174
false
false
3
957db1b8edb1001abf27c389e5850770a6f3d85e
16,681,652,999,002
b1af7c61dcea66cb9e94806359818a464879dbe7
/bssv/J564200/com/beone/fedex/beshipments/NaftaNetCostMethodCode.java
3fcdd80cc9a4db35b201bbff623bdfeb571bb830
[]
no_license
PPatel0212/Java-Web-Services-JDE
https://github.com/PPatel0212/Java-Web-Services-JDE
aa8c17bac68a73db153de903129246bf2d1f06ae
c296873106455f69aa541e45ae73a15756e9a413
refs/heads/master
2022-12-29T18:17:41.801000
2020-10-07T21:09:57
2020-10-07T21:09:57
264,015,732
0
0
null
false
2020-06-22T01:14:32
2020-05-14T20:15:26
2020-06-21T21:17:57
2020-06-22T01:14:31
803
0
0
0
Java
false
false
/** * Generated from schema type t=NaftaNetCostMethodCode@http://www.beone.com/fedex/beshipments */ package be.e1.bssv.J564200.com.beone.fedex.beshipments; import java.util.HashMap; import java.util.Map; import com.bea.xbean.util.XsTypeConverter; public class NaftaNetCostMethodCode implements java.io.Serializable { private java.lang.String value; private static Map map = new HashMap(); protected NaftaNetCostMethodCode(java.lang.String value) { this.value = value; } public static final java.lang.String _nc = "NC"; public static final java.lang.String _no = "NO"; public static final NaftaNetCostMethodCode nc = new NaftaNetCostMethodCode(_nc); public static final NaftaNetCostMethodCode no = new NaftaNetCostMethodCode(_no); public java.lang.String getValue() { return this.value; } public static NaftaNetCostMethodCode fromValue(java.lang.String value) { if (map.containsKey(value)) return (NaftaNetCostMethodCode) map.get(value); else throw new IllegalArgumentException(); } public static NaftaNetCostMethodCode fromString(String value) { return fromValue(value); } public String toXML() { return XsTypeConverter.printString(this.value).toString(); } public String toString() { return String.valueOf(value); } public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof NaftaNetCostMethodCode)) return false; final NaftaNetCostMethodCode x = (NaftaNetCostMethodCode) obj; if (x.value.equals(value)) return true; return false; } public int hashCode() { return value.hashCode(); } static { map.put(_nc, nc); map.put(_no, no); } }
UTF-8
Java
1,690
java
NaftaNetCostMethodCode.java
Java
[]
null
[]
/** * Generated from schema type t=NaftaNetCostMethodCode@http://www.beone.com/fedex/beshipments */ package be.e1.bssv.J564200.com.beone.fedex.beshipments; import java.util.HashMap; import java.util.Map; import com.bea.xbean.util.XsTypeConverter; public class NaftaNetCostMethodCode implements java.io.Serializable { private java.lang.String value; private static Map map = new HashMap(); protected NaftaNetCostMethodCode(java.lang.String value) { this.value = value; } public static final java.lang.String _nc = "NC"; public static final java.lang.String _no = "NO"; public static final NaftaNetCostMethodCode nc = new NaftaNetCostMethodCode(_nc); public static final NaftaNetCostMethodCode no = new NaftaNetCostMethodCode(_no); public java.lang.String getValue() { return this.value; } public static NaftaNetCostMethodCode fromValue(java.lang.String value) { if (map.containsKey(value)) return (NaftaNetCostMethodCode) map.get(value); else throw new IllegalArgumentException(); } public static NaftaNetCostMethodCode fromString(String value) { return fromValue(value); } public String toXML() { return XsTypeConverter.printString(this.value).toString(); } public String toString() { return String.valueOf(value); } public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof NaftaNetCostMethodCode)) return false; final NaftaNetCostMethodCode x = (NaftaNetCostMethodCode) obj; if (x.value.equals(value)) return true; return false; } public int hashCode() { return value.hashCode(); } static { map.put(_nc, nc); map.put(_no, no); } }
1,690
0.721302
0.71716
66
24.60606
26.735449
93
false
false
0
0
0
0
0
0
0.409091
false
false
3
2517dafe3cb83df6c75979d43e5554b304420c8c
31,851,477,531,107
bd3e12efc24453f0fb5ce38d1b064432a925e69d
/main/java/thexnator/furnituremod/util/utilobjects/MatrixStack.java
c79a4ebc843354c5a72cbeb208703e48a0a7182b
[]
no_license
TheXnator/FurnitureMod
https://github.com/TheXnator/FurnitureMod
62e91aff9a9e46d72ab819bbf30f019aea3cbd20
b3699f71e75d467886d5429de40b127fb94b194d
refs/heads/master
2021-01-18T21:34:22.987000
2016-06-05T10:41:47
2016-06-05T10:41:47
50,041,844
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package thexnator.furnituremod.util.utilobjects; import java.util.Stack; import org.lwjgl.util.vector.Matrix4f; import org.lwjgl.util.vector.Vector3f; import thexnator.furnituremod.util.utilobjects.vectors.Vec3M; public class MatrixStack{ private Stack<Matrix4f> stack=new Stack<>(); public Matrix4f get(){ if(stack.isEmpty())stack.push(new Matrix4f()); return stack.peek(); } public void set(Matrix4f matrix){ stack.set(stack.size()-1, matrix); } protected Matrix4f getNewObject(){ if(stack.isEmpty())return new Matrix4f(); return get().transpose(null); } public void rotate(Vector3f vec){rotate(vec.x, vec.y, vec.z);} public void rotate(Vec3M vec){rotate(vec.x, vec.y, vec.z);} public void rotate(float angle,float x,float y,float z){ Matrix4f.rotate((float)Math.toRadians(angle), new Vector3f(x,y,z), get(), get()); } public void rotate(double x,double y,double z){ Matrix4f.rotate((float)Math.toRadians(x), new Vector3f(1, 0, 0), get(), get()); Matrix4f.rotate((float)Math.toRadians(y), new Vector3f(0, 1, 0), get(), get()); Matrix4f.rotate((float)Math.toRadians(z), new Vector3f(0, 0, 1), get(), get()); } public void translate(double x,double y,double z){translate(new Vector3f((float)x, (float)y, (float)z));} public void translate(Vec3M vec){translate(vec.x,vec.y,vec.z);} public void translate(Vector3f vec){ Matrix4f.translate(vec, get(), get()); } public void pushMatrix(){ stack.push(getNewObject()); } public void popMatrix(){ stack.pop(); } public void scale(double scale){ scale((float)scale); } public void scale(double x,double y,double z){ scale(new Vector3f((float)x,(float)y,(float)z)); } public void scale(float x,float y,float z){ scale(new Vector3f(x,y,z)); } public void scale(float scale){ scale(new Vector3f(scale, scale, scale)); } public void scale(Vec3M vec){ get().scale(new Vector3f(vec.getX(), vec.getY(), vec.getZ())); } public void scale(Vector3f vec){ get().scale(vec); } }
UTF-8
Java
1,984
java
MatrixStack.java
Java
[]
null
[]
package thexnator.furnituremod.util.utilobjects; import java.util.Stack; import org.lwjgl.util.vector.Matrix4f; import org.lwjgl.util.vector.Vector3f; import thexnator.furnituremod.util.utilobjects.vectors.Vec3M; public class MatrixStack{ private Stack<Matrix4f> stack=new Stack<>(); public Matrix4f get(){ if(stack.isEmpty())stack.push(new Matrix4f()); return stack.peek(); } public void set(Matrix4f matrix){ stack.set(stack.size()-1, matrix); } protected Matrix4f getNewObject(){ if(stack.isEmpty())return new Matrix4f(); return get().transpose(null); } public void rotate(Vector3f vec){rotate(vec.x, vec.y, vec.z);} public void rotate(Vec3M vec){rotate(vec.x, vec.y, vec.z);} public void rotate(float angle,float x,float y,float z){ Matrix4f.rotate((float)Math.toRadians(angle), new Vector3f(x,y,z), get(), get()); } public void rotate(double x,double y,double z){ Matrix4f.rotate((float)Math.toRadians(x), new Vector3f(1, 0, 0), get(), get()); Matrix4f.rotate((float)Math.toRadians(y), new Vector3f(0, 1, 0), get(), get()); Matrix4f.rotate((float)Math.toRadians(z), new Vector3f(0, 0, 1), get(), get()); } public void translate(double x,double y,double z){translate(new Vector3f((float)x, (float)y, (float)z));} public void translate(Vec3M vec){translate(vec.x,vec.y,vec.z);} public void translate(Vector3f vec){ Matrix4f.translate(vec, get(), get()); } public void pushMatrix(){ stack.push(getNewObject()); } public void popMatrix(){ stack.pop(); } public void scale(double scale){ scale((float)scale); } public void scale(double x,double y,double z){ scale(new Vector3f((float)x,(float)y,(float)z)); } public void scale(float x,float y,float z){ scale(new Vector3f(x,y,z)); } public void scale(float scale){ scale(new Vector3f(scale, scale, scale)); } public void scale(Vec3M vec){ get().scale(new Vector3f(vec.getX(), vec.getY(), vec.getZ())); } public void scale(Vector3f vec){ get().scale(vec); } }
1,984
0.699093
0.679435
63
30.492064
25.84746
106
false
false
0
0
0
0
0
0
2.349206
false
false
3
13927d49ea6cc9edb94a646cd91b2e36ac382b95
31,851,477,530,811
5557bbeb98dc88f6b7da7641d67e89004c33259d
/src/main/java/com/sap/oss/phosphor/fosstars/util/Deserialization.java
adf1ea7d5a1ce783bbd1b7dd7239e9c0f90fa0ae
[ "Apache-2.0" ]
permissive
SAP/fosstars-rating-core
https://github.com/SAP/fosstars-rating-core
5a4e0afd49915ca52c178765257b8864da6ecebc
7b129aeb89b5f493f34d0874c9bbb39bd1d6d80e
refs/heads/master
2023-08-31T22:44:34.267000
2023-08-18T08:21:24
2023-08-18T08:21:24
236,462,734
50
30
Apache-2.0
false
2023-09-05T06:06:15
2020-01-27T10:08:24
2023-07-25T14:32:24
2023-09-05T06:06:11
33,795
50
24
76
Java
false
false
package com.sap.oss.phosphor.fosstars.util; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.jsontype.BasicPolymorphicTypeValidator; import com.fasterxml.jackson.databind.jsontype.BasicPolymorphicTypeValidator.Builder; import com.fasterxml.jackson.databind.jsontype.PolymorphicTypeValidator; import com.sap.oss.phosphor.fosstars.model.feature.BooleanFeature; import com.sap.oss.phosphor.fosstars.model.feature.BoundedDoubleFeature; import com.sap.oss.phosphor.fosstars.model.feature.BoundedIntegerFeature; import com.sap.oss.phosphor.fosstars.model.feature.DateFeature; import com.sap.oss.phosphor.fosstars.model.feature.DoubleFeature; import com.sap.oss.phosphor.fosstars.model.feature.EnumFeature; import com.sap.oss.phosphor.fosstars.model.feature.LgtmGradeFeature; import com.sap.oss.phosphor.fosstars.model.feature.OwaspDependencyCheckCvssThreshold; import com.sap.oss.phosphor.fosstars.model.feature.OwaspDependencyCheckUsageFeature; import com.sap.oss.phosphor.fosstars.model.feature.PositiveIntegerFeature; import com.sap.oss.phosphor.fosstars.model.feature.StringFeature; import com.sap.oss.phosphor.fosstars.model.feature.example.NumberOfCommitsLastMonthExample; import com.sap.oss.phosphor.fosstars.model.feature.example.NumberOfContributorsLastMonthExample; import com.sap.oss.phosphor.fosstars.model.feature.example.SecurityReviewDoneExample; import com.sap.oss.phosphor.fosstars.model.feature.example.StaticCodeAnalysisDoneExample; import com.sap.oss.phosphor.fosstars.model.feature.oss.ArtifactVersionFeature; import com.sap.oss.phosphor.fosstars.model.feature.oss.ArtifactVersionsFeature; import com.sap.oss.phosphor.fosstars.model.feature.oss.LanguagesFeature; import com.sap.oss.phosphor.fosstars.model.feature.oss.PackageManagersFeature; import com.sap.oss.phosphor.fosstars.model.feature.oss.SecurityReviewsFeature; import com.sap.oss.phosphor.fosstars.model.feature.oss.VulnerabilitiesFeature; import com.sap.oss.phosphor.fosstars.model.math.DoubleInterval; import com.sap.oss.phosphor.fosstars.model.qa.ScoreTestVector; import com.sap.oss.phosphor.fosstars.model.qa.StandardTestVector; import com.sap.oss.phosphor.fosstars.model.qa.TestScoreValue; import com.sap.oss.phosphor.fosstars.model.rating.NotApplicableLabel; import com.sap.oss.phosphor.fosstars.model.rating.example.SecurityRatingExample; import com.sap.oss.phosphor.fosstars.model.rating.oss.OssArtifactSecurityRating.ArtifactSecurityLabel; import com.sap.oss.phosphor.fosstars.model.rating.oss.OssRulesOfPlayRating; import com.sap.oss.phosphor.fosstars.model.rating.oss.OssSecurityRating; import com.sap.oss.phosphor.fosstars.model.rating.oss.SecurityRiskIntroducedByOss; import com.sap.oss.phosphor.fosstars.model.score.AverageCompositeScore; import com.sap.oss.phosphor.fosstars.model.score.WeightedCompositeScore; import com.sap.oss.phosphor.fosstars.model.score.example.ProjectActivityScoreExample; import com.sap.oss.phosphor.fosstars.model.score.example.SecurityScoreExample; import com.sap.oss.phosphor.fosstars.model.score.example.SecurityTestingScoreExample; import com.sap.oss.phosphor.fosstars.model.score.oss.ArtifactLatestReleaseAgeScore; import com.sap.oss.phosphor.fosstars.model.score.oss.ArtifactReleaseHistoryScore; import com.sap.oss.phosphor.fosstars.model.score.oss.ArtifactVersionUpToDateScore; import com.sap.oss.phosphor.fosstars.model.score.oss.ArtifactVersionVulnerabilityScore; import com.sap.oss.phosphor.fosstars.model.score.oss.BanditScore; import com.sap.oss.phosphor.fosstars.model.score.oss.CodeqlScore; import com.sap.oss.phosphor.fosstars.model.score.oss.CommunityCommitmentScore; import com.sap.oss.phosphor.fosstars.model.score.oss.DependabotScore; import com.sap.oss.phosphor.fosstars.model.score.oss.DependencyScanScore; import com.sap.oss.phosphor.fosstars.model.score.oss.FindSecBugsScore; import com.sap.oss.phosphor.fosstars.model.score.oss.FuzzingScore; import com.sap.oss.phosphor.fosstars.model.score.oss.GoSecScore; import com.sap.oss.phosphor.fosstars.model.score.oss.MemorySafetyTestingScore; import com.sap.oss.phosphor.fosstars.model.score.oss.MyPyScore; import com.sap.oss.phosphor.fosstars.model.score.oss.NoHttpToolScore; import com.sap.oss.phosphor.fosstars.model.score.oss.OssArtifactSecurityScore; import com.sap.oss.phosphor.fosstars.model.score.oss.OssRulesOfPlayScore; import com.sap.oss.phosphor.fosstars.model.score.oss.OssSecurityScore; import com.sap.oss.phosphor.fosstars.model.score.oss.OwaspDependencyScanScore; import com.sap.oss.phosphor.fosstars.model.score.oss.ProjectActivityScore; import com.sap.oss.phosphor.fosstars.model.score.oss.ProjectPopularityScore; import com.sap.oss.phosphor.fosstars.model.score.oss.ProjectSecurityAwarenessScore; import com.sap.oss.phosphor.fosstars.model.score.oss.ProjectSecurityTestingScore; import com.sap.oss.phosphor.fosstars.model.score.oss.PylintScore; import com.sap.oss.phosphor.fosstars.model.score.oss.SecurityReviewScore; import com.sap.oss.phosphor.fosstars.model.score.oss.SnykDependencyScanScore; import com.sap.oss.phosphor.fosstars.model.score.oss.StaticAnalysisScore; import com.sap.oss.phosphor.fosstars.model.score.oss.UnpatchedVulnerabilitiesScore; import com.sap.oss.phosphor.fosstars.model.score.oss.VulnerabilityDiscoveryAndSecurityTestingScore; import com.sap.oss.phosphor.fosstars.model.score.oss.VulnerabilityLifetimeScore; import com.sap.oss.phosphor.fosstars.model.score.oss.risk.AdoptedRiskLikelihoodFactor; import com.sap.oss.phosphor.fosstars.model.score.oss.risk.CalculatedSecurityRiskIntroducedByOss; import com.sap.oss.phosphor.fosstars.model.score.oss.risk.DataConfidentialityRiskImpactFactor; import com.sap.oss.phosphor.fosstars.model.score.oss.risk.FunctionalityRiskLikelihoodFactor; import com.sap.oss.phosphor.fosstars.model.score.oss.risk.HandlingUntrustedDataRiskLikelihoodFactor; import com.sap.oss.phosphor.fosstars.model.score.oss.risk.ImpactScore; import com.sap.oss.phosphor.fosstars.model.score.oss.risk.RiskImpactScore; import com.sap.oss.phosphor.fosstars.model.score.oss.risk.RiskLikelihoodCoefficient; import com.sap.oss.phosphor.fosstars.model.score.oss.risk.RiskLikelihoodFactors; import com.sap.oss.phosphor.fosstars.model.score.oss.risk.RiskLikelihoodScore; import com.sap.oss.phosphor.fosstars.model.score.oss.risk.UsageRiskLikelihoodFactor; import com.sap.oss.phosphor.fosstars.model.subject.oss.GitHubOrganization; import com.sap.oss.phosphor.fosstars.model.subject.oss.GitHubProject; import com.sap.oss.phosphor.fosstars.model.subject.oss.MavenArtifact; import com.sap.oss.phosphor.fosstars.model.subject.oss.NpmArtifact; import com.sap.oss.phosphor.fosstars.model.value.ArtifactVersionValue; import com.sap.oss.phosphor.fosstars.model.value.ArtifactVersionsValue; import com.sap.oss.phosphor.fosstars.model.value.BooleanValue; import com.sap.oss.phosphor.fosstars.model.value.CVSS; import com.sap.oss.phosphor.fosstars.model.value.DateValue; import com.sap.oss.phosphor.fosstars.model.value.DoubleValue; import com.sap.oss.phosphor.fosstars.model.value.EnumValue; import com.sap.oss.phosphor.fosstars.model.value.ExpiringValue; import com.sap.oss.phosphor.fosstars.model.value.IntegerValue; import com.sap.oss.phosphor.fosstars.model.value.LanguagesValue; import com.sap.oss.phosphor.fosstars.model.value.LgtmGradeValue; import com.sap.oss.phosphor.fosstars.model.value.NotApplicableValue; import com.sap.oss.phosphor.fosstars.model.value.OwaspDependencyCheckCvssThresholdValue; import com.sap.oss.phosphor.fosstars.model.value.OwaspDependencyCheckUsageValue; import com.sap.oss.phosphor.fosstars.model.value.PackageManagersValue; import com.sap.oss.phosphor.fosstars.model.value.ScoreValue; import com.sap.oss.phosphor.fosstars.model.value.SecurityReviewsValue; import com.sap.oss.phosphor.fosstars.model.value.StringValue; import com.sap.oss.phosphor.fosstars.model.value.UnknownValue; import com.sap.oss.phosphor.fosstars.model.value.ValueHashSet; import com.sap.oss.phosphor.fosstars.model.value.VulnerabilitiesValue; import com.sap.oss.phosphor.fosstars.model.weight.ImmutableWeight; import com.sap.oss.phosphor.fosstars.model.weight.MutableWeight; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; /** * The class holds common functionality for JSON and YAML serialization/deserialization. */ public abstract class Deserialization { /** * A type reference for deserialization to a Map. */ static final TypeReference<Map<String, Object>> MAP_TYPE_REFERENCE = new TypeReference<Map<String, Object>>() {}; /** * A list of types that are allowed for deserialization by default. */ private static final List<String> DEFAULT_ALLOWED_SUB_TYPES = Collections.singletonList( "com.sap.oss.phosphor.fosstars"); /** * A list of classes that are allowed for deserialization. */ private static final List<String> ALLOWED_SUB_TYPES = new ArrayList<>(DEFAULT_ALLOWED_SUB_TYPES); /** * Allows deserialization of a specified packages or classes. * * @param patterns The packages or classes. */ public static void allow(String... patterns) { Objects.requireNonNull(patterns, "Oh no! Patterns are null!"); ALLOWED_SUB_TYPES.addAll(Arrays.asList(patterns)); } /** * Creates a validator for deserialization. * * @return A validator for deserialization. */ static PolymorphicTypeValidator validator() { Builder builder = BasicPolymorphicTypeValidator.builder(); ALLOWED_SUB_TYPES.forEach(builder::allowIfSubType); return builder.build(); } /** * Reads a list from a node. * * @param root The node. * @param property A field that has the list. * @return A list of elements. * @throws IOException If something went wrong. */ public static List<String> readListFrom(JsonNode root, String property) throws IOException { if (!root.has(property)) { return emptyList(); } JsonNode node = root.get(property); if (node.isTextual()) { return singletonList(node.asText()); } if (!node.isArray()) { throw new IOException( String.format("Oops! '%s' is not an array and not a string!", property)); } List<String> list = new ArrayList<>(); Iterator<JsonNode> iterator = node.elements(); while (iterator.hasNext()) { JsonNode element = iterator.next(); if (!element.isTextual()) { throw new IOException(String.format("Oops! Element of '%s' is not a string!", property)); } list.add(element.asText()); } return list; } /** * Registers known sub-types in an {@link ObjectMapper}. * * @param mapper The {@link ObjectMapper}. * @return The same {@link ObjectMapper}; */ static ObjectMapper registerSubTypesIn(ObjectMapper mapper) { // features mapper.registerSubtypes( PositiveIntegerFeature.class, DoubleFeature.class, BooleanFeature.class, BoundedIntegerFeature.class, BoundedDoubleFeature.class, DateFeature.class, EnumFeature.class, VulnerabilitiesFeature.class, SecurityReviewDoneExample.class, StaticCodeAnalysisDoneExample.class, NumberOfCommitsLastMonthExample.class, NumberOfContributorsLastMonthExample.class, LgtmGradeFeature.class, LanguagesFeature.class, PackageManagersFeature.class, StringFeature.class, ArtifactVersionFeature.class, ArtifactVersionsFeature.class, OwaspDependencyCheckUsageFeature.class, OwaspDependencyCheckCvssThreshold.class, SecurityReviewsFeature.class ); // values mapper.registerSubtypes( IntegerValue.class, DoubleValue.class, BooleanValue.class, DateValue.class, ScoreValue.class, ExpiringValue.class, VulnerabilitiesValue.class, UnknownValue.class, NotApplicableValue.class, EnumValue.class, LgtmGradeValue.class, LanguagesValue.class, PackageManagersValue.class, StringValue.class, ArtifactVersionValue.class, ArtifactVersionsValue.class, OwaspDependencyCheckUsageValue.class, OwaspDependencyCheckCvssThresholdValue.class, SecurityReviewsValue.class, TestScoreValue.class ); // labels mapper.registerSubtypes( ArtifactSecurityLabel.class, OssSecurityRating.SecurityLabel.class, SecurityRatingExample.SecurityLabelExample.class, OssRulesOfPlayRating.OssRulesOfPlayLabel.class, NotApplicableLabel.class, SecurityRiskIntroducedByOss.OssSecurityRiskLabel.class ); // scores mapper.registerSubtypes( SecurityScoreExample.class, ProjectActivityScoreExample.class, SecurityTestingScoreExample.class, WeightedCompositeScore.class, AverageCompositeScore.class, ProjectActivityScore.class, ProjectPopularityScore.class, CommunityCommitmentScore.class, ProjectSecurityAwarenessScore.class, ProjectSecurityTestingScore.class, UnpatchedVulnerabilitiesScore.class, VulnerabilityLifetimeScore.class, OssSecurityScore.class, DependencyScanScore.class, CodeqlScore.class, NoHttpToolScore.class, MemorySafetyTestingScore.class, FindSecBugsScore.class, FuzzingScore.class, StaticAnalysisScore.class, DependabotScore.class, SnykDependencyScanScore.class, OwaspDependencyScanScore.class, VulnerabilityDiscoveryAndSecurityTestingScore.class, SecurityReviewScore.class, OssArtifactSecurityScore.class, OssRulesOfPlayScore.class, ArtifactLatestReleaseAgeScore.class, ArtifactVersionUpToDateScore.class, ArtifactVersionVulnerabilityScore.class, ArtifactReleaseHistoryScore.class, UsageRiskLikelihoodFactor.class, FunctionalityRiskLikelihoodFactor.class, HandlingUntrustedDataRiskLikelihoodFactor.class, AdoptedRiskLikelihoodFactor.class, RiskLikelihoodCoefficient.class, RiskLikelihoodFactors.class, RiskLikelihoodScore.class, DataConfidentialityRiskImpactFactor.class, ImpactScore.class, RiskImpactScore.class, RiskImpactScore.ConfidentialityRiskImpactFactor.class, RiskImpactScore.IntegrityRiskImpactFactor.class, RiskImpactScore.AvailabilityRiskImpactFactor.class, CalculatedSecurityRiskIntroducedByOss.class, BanditScore.class, GoSecScore.class, PylintScore.class, MyPyScore.class ); // ratings mapper.registerSubtypes( SecurityRatingExample.class, OssSecurityRating.class, OssRulesOfPlayScore.class, SecurityRiskIntroducedByOss.class ); // weights mapper.registerSubtypes(MutableWeight.class, ImmutableWeight.class); // test vectors mapper.registerSubtypes(StandardTestVector.class, ScoreTestVector.class); // artifacts mapper.registerSubtypes(MavenArtifact.class, NpmArtifact.class); // other mapper.registerSubtypes( GitHubProject.class, GitHubOrganization.class, DoubleInterval.class, ValueHashSet.class, CVSS.V2.class, CVSS.V3.class); return mapper; } }
UTF-8
Java
15,685
java
Deserialization.java
Java
[]
null
[]
package com.sap.oss.phosphor.fosstars.util; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.jsontype.BasicPolymorphicTypeValidator; import com.fasterxml.jackson.databind.jsontype.BasicPolymorphicTypeValidator.Builder; import com.fasterxml.jackson.databind.jsontype.PolymorphicTypeValidator; import com.sap.oss.phosphor.fosstars.model.feature.BooleanFeature; import com.sap.oss.phosphor.fosstars.model.feature.BoundedDoubleFeature; import com.sap.oss.phosphor.fosstars.model.feature.BoundedIntegerFeature; import com.sap.oss.phosphor.fosstars.model.feature.DateFeature; import com.sap.oss.phosphor.fosstars.model.feature.DoubleFeature; import com.sap.oss.phosphor.fosstars.model.feature.EnumFeature; import com.sap.oss.phosphor.fosstars.model.feature.LgtmGradeFeature; import com.sap.oss.phosphor.fosstars.model.feature.OwaspDependencyCheckCvssThreshold; import com.sap.oss.phosphor.fosstars.model.feature.OwaspDependencyCheckUsageFeature; import com.sap.oss.phosphor.fosstars.model.feature.PositiveIntegerFeature; import com.sap.oss.phosphor.fosstars.model.feature.StringFeature; import com.sap.oss.phosphor.fosstars.model.feature.example.NumberOfCommitsLastMonthExample; import com.sap.oss.phosphor.fosstars.model.feature.example.NumberOfContributorsLastMonthExample; import com.sap.oss.phosphor.fosstars.model.feature.example.SecurityReviewDoneExample; import com.sap.oss.phosphor.fosstars.model.feature.example.StaticCodeAnalysisDoneExample; import com.sap.oss.phosphor.fosstars.model.feature.oss.ArtifactVersionFeature; import com.sap.oss.phosphor.fosstars.model.feature.oss.ArtifactVersionsFeature; import com.sap.oss.phosphor.fosstars.model.feature.oss.LanguagesFeature; import com.sap.oss.phosphor.fosstars.model.feature.oss.PackageManagersFeature; import com.sap.oss.phosphor.fosstars.model.feature.oss.SecurityReviewsFeature; import com.sap.oss.phosphor.fosstars.model.feature.oss.VulnerabilitiesFeature; import com.sap.oss.phosphor.fosstars.model.math.DoubleInterval; import com.sap.oss.phosphor.fosstars.model.qa.ScoreTestVector; import com.sap.oss.phosphor.fosstars.model.qa.StandardTestVector; import com.sap.oss.phosphor.fosstars.model.qa.TestScoreValue; import com.sap.oss.phosphor.fosstars.model.rating.NotApplicableLabel; import com.sap.oss.phosphor.fosstars.model.rating.example.SecurityRatingExample; import com.sap.oss.phosphor.fosstars.model.rating.oss.OssArtifactSecurityRating.ArtifactSecurityLabel; import com.sap.oss.phosphor.fosstars.model.rating.oss.OssRulesOfPlayRating; import com.sap.oss.phosphor.fosstars.model.rating.oss.OssSecurityRating; import com.sap.oss.phosphor.fosstars.model.rating.oss.SecurityRiskIntroducedByOss; import com.sap.oss.phosphor.fosstars.model.score.AverageCompositeScore; import com.sap.oss.phosphor.fosstars.model.score.WeightedCompositeScore; import com.sap.oss.phosphor.fosstars.model.score.example.ProjectActivityScoreExample; import com.sap.oss.phosphor.fosstars.model.score.example.SecurityScoreExample; import com.sap.oss.phosphor.fosstars.model.score.example.SecurityTestingScoreExample; import com.sap.oss.phosphor.fosstars.model.score.oss.ArtifactLatestReleaseAgeScore; import com.sap.oss.phosphor.fosstars.model.score.oss.ArtifactReleaseHistoryScore; import com.sap.oss.phosphor.fosstars.model.score.oss.ArtifactVersionUpToDateScore; import com.sap.oss.phosphor.fosstars.model.score.oss.ArtifactVersionVulnerabilityScore; import com.sap.oss.phosphor.fosstars.model.score.oss.BanditScore; import com.sap.oss.phosphor.fosstars.model.score.oss.CodeqlScore; import com.sap.oss.phosphor.fosstars.model.score.oss.CommunityCommitmentScore; import com.sap.oss.phosphor.fosstars.model.score.oss.DependabotScore; import com.sap.oss.phosphor.fosstars.model.score.oss.DependencyScanScore; import com.sap.oss.phosphor.fosstars.model.score.oss.FindSecBugsScore; import com.sap.oss.phosphor.fosstars.model.score.oss.FuzzingScore; import com.sap.oss.phosphor.fosstars.model.score.oss.GoSecScore; import com.sap.oss.phosphor.fosstars.model.score.oss.MemorySafetyTestingScore; import com.sap.oss.phosphor.fosstars.model.score.oss.MyPyScore; import com.sap.oss.phosphor.fosstars.model.score.oss.NoHttpToolScore; import com.sap.oss.phosphor.fosstars.model.score.oss.OssArtifactSecurityScore; import com.sap.oss.phosphor.fosstars.model.score.oss.OssRulesOfPlayScore; import com.sap.oss.phosphor.fosstars.model.score.oss.OssSecurityScore; import com.sap.oss.phosphor.fosstars.model.score.oss.OwaspDependencyScanScore; import com.sap.oss.phosphor.fosstars.model.score.oss.ProjectActivityScore; import com.sap.oss.phosphor.fosstars.model.score.oss.ProjectPopularityScore; import com.sap.oss.phosphor.fosstars.model.score.oss.ProjectSecurityAwarenessScore; import com.sap.oss.phosphor.fosstars.model.score.oss.ProjectSecurityTestingScore; import com.sap.oss.phosphor.fosstars.model.score.oss.PylintScore; import com.sap.oss.phosphor.fosstars.model.score.oss.SecurityReviewScore; import com.sap.oss.phosphor.fosstars.model.score.oss.SnykDependencyScanScore; import com.sap.oss.phosphor.fosstars.model.score.oss.StaticAnalysisScore; import com.sap.oss.phosphor.fosstars.model.score.oss.UnpatchedVulnerabilitiesScore; import com.sap.oss.phosphor.fosstars.model.score.oss.VulnerabilityDiscoveryAndSecurityTestingScore; import com.sap.oss.phosphor.fosstars.model.score.oss.VulnerabilityLifetimeScore; import com.sap.oss.phosphor.fosstars.model.score.oss.risk.AdoptedRiskLikelihoodFactor; import com.sap.oss.phosphor.fosstars.model.score.oss.risk.CalculatedSecurityRiskIntroducedByOss; import com.sap.oss.phosphor.fosstars.model.score.oss.risk.DataConfidentialityRiskImpactFactor; import com.sap.oss.phosphor.fosstars.model.score.oss.risk.FunctionalityRiskLikelihoodFactor; import com.sap.oss.phosphor.fosstars.model.score.oss.risk.HandlingUntrustedDataRiskLikelihoodFactor; import com.sap.oss.phosphor.fosstars.model.score.oss.risk.ImpactScore; import com.sap.oss.phosphor.fosstars.model.score.oss.risk.RiskImpactScore; import com.sap.oss.phosphor.fosstars.model.score.oss.risk.RiskLikelihoodCoefficient; import com.sap.oss.phosphor.fosstars.model.score.oss.risk.RiskLikelihoodFactors; import com.sap.oss.phosphor.fosstars.model.score.oss.risk.RiskLikelihoodScore; import com.sap.oss.phosphor.fosstars.model.score.oss.risk.UsageRiskLikelihoodFactor; import com.sap.oss.phosphor.fosstars.model.subject.oss.GitHubOrganization; import com.sap.oss.phosphor.fosstars.model.subject.oss.GitHubProject; import com.sap.oss.phosphor.fosstars.model.subject.oss.MavenArtifact; import com.sap.oss.phosphor.fosstars.model.subject.oss.NpmArtifact; import com.sap.oss.phosphor.fosstars.model.value.ArtifactVersionValue; import com.sap.oss.phosphor.fosstars.model.value.ArtifactVersionsValue; import com.sap.oss.phosphor.fosstars.model.value.BooleanValue; import com.sap.oss.phosphor.fosstars.model.value.CVSS; import com.sap.oss.phosphor.fosstars.model.value.DateValue; import com.sap.oss.phosphor.fosstars.model.value.DoubleValue; import com.sap.oss.phosphor.fosstars.model.value.EnumValue; import com.sap.oss.phosphor.fosstars.model.value.ExpiringValue; import com.sap.oss.phosphor.fosstars.model.value.IntegerValue; import com.sap.oss.phosphor.fosstars.model.value.LanguagesValue; import com.sap.oss.phosphor.fosstars.model.value.LgtmGradeValue; import com.sap.oss.phosphor.fosstars.model.value.NotApplicableValue; import com.sap.oss.phosphor.fosstars.model.value.OwaspDependencyCheckCvssThresholdValue; import com.sap.oss.phosphor.fosstars.model.value.OwaspDependencyCheckUsageValue; import com.sap.oss.phosphor.fosstars.model.value.PackageManagersValue; import com.sap.oss.phosphor.fosstars.model.value.ScoreValue; import com.sap.oss.phosphor.fosstars.model.value.SecurityReviewsValue; import com.sap.oss.phosphor.fosstars.model.value.StringValue; import com.sap.oss.phosphor.fosstars.model.value.UnknownValue; import com.sap.oss.phosphor.fosstars.model.value.ValueHashSet; import com.sap.oss.phosphor.fosstars.model.value.VulnerabilitiesValue; import com.sap.oss.phosphor.fosstars.model.weight.ImmutableWeight; import com.sap.oss.phosphor.fosstars.model.weight.MutableWeight; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; /** * The class holds common functionality for JSON and YAML serialization/deserialization. */ public abstract class Deserialization { /** * A type reference for deserialization to a Map. */ static final TypeReference<Map<String, Object>> MAP_TYPE_REFERENCE = new TypeReference<Map<String, Object>>() {}; /** * A list of types that are allowed for deserialization by default. */ private static final List<String> DEFAULT_ALLOWED_SUB_TYPES = Collections.singletonList( "com.sap.oss.phosphor.fosstars"); /** * A list of classes that are allowed for deserialization. */ private static final List<String> ALLOWED_SUB_TYPES = new ArrayList<>(DEFAULT_ALLOWED_SUB_TYPES); /** * Allows deserialization of a specified packages or classes. * * @param patterns The packages or classes. */ public static void allow(String... patterns) { Objects.requireNonNull(patterns, "Oh no! Patterns are null!"); ALLOWED_SUB_TYPES.addAll(Arrays.asList(patterns)); } /** * Creates a validator for deserialization. * * @return A validator for deserialization. */ static PolymorphicTypeValidator validator() { Builder builder = BasicPolymorphicTypeValidator.builder(); ALLOWED_SUB_TYPES.forEach(builder::allowIfSubType); return builder.build(); } /** * Reads a list from a node. * * @param root The node. * @param property A field that has the list. * @return A list of elements. * @throws IOException If something went wrong. */ public static List<String> readListFrom(JsonNode root, String property) throws IOException { if (!root.has(property)) { return emptyList(); } JsonNode node = root.get(property); if (node.isTextual()) { return singletonList(node.asText()); } if (!node.isArray()) { throw new IOException( String.format("Oops! '%s' is not an array and not a string!", property)); } List<String> list = new ArrayList<>(); Iterator<JsonNode> iterator = node.elements(); while (iterator.hasNext()) { JsonNode element = iterator.next(); if (!element.isTextual()) { throw new IOException(String.format("Oops! Element of '%s' is not a string!", property)); } list.add(element.asText()); } return list; } /** * Registers known sub-types in an {@link ObjectMapper}. * * @param mapper The {@link ObjectMapper}. * @return The same {@link ObjectMapper}; */ static ObjectMapper registerSubTypesIn(ObjectMapper mapper) { // features mapper.registerSubtypes( PositiveIntegerFeature.class, DoubleFeature.class, BooleanFeature.class, BoundedIntegerFeature.class, BoundedDoubleFeature.class, DateFeature.class, EnumFeature.class, VulnerabilitiesFeature.class, SecurityReviewDoneExample.class, StaticCodeAnalysisDoneExample.class, NumberOfCommitsLastMonthExample.class, NumberOfContributorsLastMonthExample.class, LgtmGradeFeature.class, LanguagesFeature.class, PackageManagersFeature.class, StringFeature.class, ArtifactVersionFeature.class, ArtifactVersionsFeature.class, OwaspDependencyCheckUsageFeature.class, OwaspDependencyCheckCvssThreshold.class, SecurityReviewsFeature.class ); // values mapper.registerSubtypes( IntegerValue.class, DoubleValue.class, BooleanValue.class, DateValue.class, ScoreValue.class, ExpiringValue.class, VulnerabilitiesValue.class, UnknownValue.class, NotApplicableValue.class, EnumValue.class, LgtmGradeValue.class, LanguagesValue.class, PackageManagersValue.class, StringValue.class, ArtifactVersionValue.class, ArtifactVersionsValue.class, OwaspDependencyCheckUsageValue.class, OwaspDependencyCheckCvssThresholdValue.class, SecurityReviewsValue.class, TestScoreValue.class ); // labels mapper.registerSubtypes( ArtifactSecurityLabel.class, OssSecurityRating.SecurityLabel.class, SecurityRatingExample.SecurityLabelExample.class, OssRulesOfPlayRating.OssRulesOfPlayLabel.class, NotApplicableLabel.class, SecurityRiskIntroducedByOss.OssSecurityRiskLabel.class ); // scores mapper.registerSubtypes( SecurityScoreExample.class, ProjectActivityScoreExample.class, SecurityTestingScoreExample.class, WeightedCompositeScore.class, AverageCompositeScore.class, ProjectActivityScore.class, ProjectPopularityScore.class, CommunityCommitmentScore.class, ProjectSecurityAwarenessScore.class, ProjectSecurityTestingScore.class, UnpatchedVulnerabilitiesScore.class, VulnerabilityLifetimeScore.class, OssSecurityScore.class, DependencyScanScore.class, CodeqlScore.class, NoHttpToolScore.class, MemorySafetyTestingScore.class, FindSecBugsScore.class, FuzzingScore.class, StaticAnalysisScore.class, DependabotScore.class, SnykDependencyScanScore.class, OwaspDependencyScanScore.class, VulnerabilityDiscoveryAndSecurityTestingScore.class, SecurityReviewScore.class, OssArtifactSecurityScore.class, OssRulesOfPlayScore.class, ArtifactLatestReleaseAgeScore.class, ArtifactVersionUpToDateScore.class, ArtifactVersionVulnerabilityScore.class, ArtifactReleaseHistoryScore.class, UsageRiskLikelihoodFactor.class, FunctionalityRiskLikelihoodFactor.class, HandlingUntrustedDataRiskLikelihoodFactor.class, AdoptedRiskLikelihoodFactor.class, RiskLikelihoodCoefficient.class, RiskLikelihoodFactors.class, RiskLikelihoodScore.class, DataConfidentialityRiskImpactFactor.class, ImpactScore.class, RiskImpactScore.class, RiskImpactScore.ConfidentialityRiskImpactFactor.class, RiskImpactScore.IntegrityRiskImpactFactor.class, RiskImpactScore.AvailabilityRiskImpactFactor.class, CalculatedSecurityRiskIntroducedByOss.class, BanditScore.class, GoSecScore.class, PylintScore.class, MyPyScore.class ); // ratings mapper.registerSubtypes( SecurityRatingExample.class, OssSecurityRating.class, OssRulesOfPlayScore.class, SecurityRiskIntroducedByOss.class ); // weights mapper.registerSubtypes(MutableWeight.class, ImmutableWeight.class); // test vectors mapper.registerSubtypes(StandardTestVector.class, ScoreTestVector.class); // artifacts mapper.registerSubtypes(MavenArtifact.class, NpmArtifact.class); // other mapper.registerSubtypes( GitHubProject.class, GitHubOrganization.class, DoubleInterval.class, ValueHashSet.class, CVSS.V2.class, CVSS.V3.class); return mapper; } }
15,685
0.780937
0.78081
348
44.071838
27.446981
102
false
false
0
0
0
0
0
0
0.744253
false
false
3
8d02a6ad44996a0d9000cd16e0f7698e8372e91c
26,199,300,535,249
041a29f963e4b88de50d8114c1b9fe6bdb0ca0ee
/wuyuan-web2/src/main/java/com/wuyuan/webapps/controller/MyConstants.java
d5f4fdd5a05f238c581ca1b61f5e1fb65c8519b5
[]
no_license
my-queqiao/queqiao
https://github.com/my-queqiao/queqiao
aa695d60e83d6e0c3e79dca57b261d9bb2b383d1
3098a5d2659e7d2ae625fd5637d4c73a0e5db2dd
refs/heads/master
2022-12-20T04:35:11.215000
2020-05-22T09:30:56
2020-05-22T09:30:56
148,271,648
0
0
null
false
2022-12-16T02:54:30
2018-09-11T06:35:29
2020-05-22T09:32:49
2022-12-16T02:54:27
81,644
0
0
16
JavaScript
false
false
package com.wuyuan.webapps.controller; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import com.wuyuan.webapps.pojo.Message; /** * 常量 * @author admin * */ public interface MyConstants { /* session中属性的记录,可以写到这儿 * session.setAttribute(username+"Authority", secuObject); session.setAttribute("currentUserName", user.getUserName()); */ //注意,map键是唯一的。 static Map<String,Object> map = new HashMap<String, Object>();//聊天功能存放<userName,session>(每个用户对应的ip、端口) static Map<String,Object> security = new HashMap<String, Object>();//控制进入首页的权限 static Map<String,Object> online = new HashMap<String, Object>();//查看用户是否在线 //static Map<Date, HashMap<String,Object>> message = new HashMap<Date, HashMap<String,Object>>();//暂存用户聊天记录 static List<Message> message = new ArrayList<Message>();//暂存用户聊天记录 }
UTF-8
Java
1,060
java
MyConstants.java
Java
[ { "context": "an.webapps.pojo.Message;\r\n\r\n/**\r\n * 常量\r\n * @author admin\r\n *\r\n */\r\npublic interface MyConstants {\r\n /* ses", "end": 242, "score": 0.9989696741104126, "start": 237, "tag": "USERNAME", "value": "admin" } ]
null
[]
package com.wuyuan.webapps.controller; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import com.wuyuan.webapps.pojo.Message; /** * 常量 * @author admin * */ public interface MyConstants { /* session中属性的记录,可以写到这儿 * session.setAttribute(username+"Authority", secuObject); session.setAttribute("currentUserName", user.getUserName()); */ //注意,map键是唯一的。 static Map<String,Object> map = new HashMap<String, Object>();//聊天功能存放<userName,session>(每个用户对应的ip、端口) static Map<String,Object> security = new HashMap<String, Object>();//控制进入首页的权限 static Map<String,Object> online = new HashMap<String, Object>();//查看用户是否在线 //static Map<Date, HashMap<String,Object>> message = new HashMap<Date, HashMap<String,Object>>();//暂存用户聊天记录 static List<Message> message = new ArrayList<Message>();//暂存用户聊天记录 }
1,060
0.716484
0.716484
29
29.379311
31.459238
108
false
false
0
0
0
0
0
0
1.482759
false
false
3
b49bec3d33df84cab502466653a3727278ac98d2
20,830,591,450,460
6ee51a4da78d8f7932e3f3553005036fc4a4dd6e
/src/sf/browser/model/items/DownloadItem.java
3dba9835a5f0b5f64761cd33e6c6fe16fffdaa40
[ "MIT" ]
permissive
sunnyfarmer/SFBrowser
https://github.com/sunnyfarmer/SFBrowser
206ce6f8541e06ba44394dfd0ed9721b24583591
1f27685ddfce82c09e4794245426ad82c032df57
refs/heads/master
2016-09-06T10:43:20.216000
2014-01-20T15:39:37
2014-01-20T15:39:37
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package sf.browser.model.items; import java.io.File; import java.util.Random; import sf.browser.R; import sf.browser.events.EventConstants; import sf.browser.events.EventController; import sf.browser.ui.activities.DownloadsListActivity; import sf.browser.ui.runnables.DownloadRunnable; import sf.browser.utils.IOUtils; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; public class DownloadItem { private Context mContext; private String mUrl; private String mFileName; private int mProgress; private String mErrorMessage; private DownloadRunnable mRunnable; private boolean mIsFinished; private boolean mIsAborted; private NotificationManager mNotificationManager; private Notification mNotification; private int mNotificationId; public DownloadItem(Context context, String url) { this.mContext = context; this.mUrl = url; this.mFileName = this.mUrl.substring(mUrl.lastIndexOf("/")+1); checkFileName(); this.mProgress = 0; this.mRunnable = null; this.mErrorMessage = null; this.mIsFinished = false; this.mIsAborted = false; Random r = new Random(); mNotificationId = r.nextInt(); mNotification = null; mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE); } /** * Gets the download url. * @return */ public String getUrl() { return this.mUrl; } /** * Gets the filename on disk. * @return */ public String getFileName() { return mFileName; } public void updateFileName(String fileName) { mFileName = fileName; checkFileName(); } public String getFilePath() { return IOUtils.getDownloadFolder().getAbsolutePath() + File.separator + mFileName; } /** * Gets the download progress * @return */ public int getProgress() { return this.mProgress; } public void setErrorMessage(String errorMessage) { this.mErrorMessage = errorMessage; } public String getErrorMessage() { return mErrorMessage; } /** * Trigger a start download event. */ public void onStart() { createNotification(); EventController.getInstance().fireDownloadEvent(EventConstants.EVT_DOWNLOAD_ON_START, this); } /** * Set this item is download finished state. Trigger a finished download event. */ public void onFinished() { this.mProgress = 100; this.mRunnable = null; this.mIsFinished = true; updateNotificationOnEnd(); EventController.getInstance().fireDownloadEvent(EventConstants.EVT_DOWNLOAD_ON_FINISHED, this); } /** * Set the current progress. Trigger a progress download event. * @param progress The current progress. */ public void onProgress(int progress) { this.mProgress = progress; EventController.getInstance().fireDownloadEvent(EventConstants.EVT_DOWNLOAD_ON_PROGRESS, this); } /** * Start the current download. */ public void startDownload() { if (mRunnable != null) { this.mRunnable.abort(); } mRunnable = new DownloadRunnable(this); new Thread(mRunnable).start(); } /** * Abort the current download. */ public void abortDownload() { if (this.mRunnable != null) { this.mRunnable.abort(); } this.mIsAborted = true; } public boolean isFinished() { return this.mIsFinished; } public boolean isAborted() { return this.mIsAborted; } /** * Remove query parameters from file name */ private void checkFileName() { int queryParamStart = mFileName.indexOf("?"); if (queryParamStart > 0) { mFileName = mFileName.substring(0, queryParamStart); } } /** * Create the download notification. */ private void createNotification() { mNotification = new Notification(R.drawable.download_anim, mContext.getString(R.string.DownloadNotification_DownloadStart), System.currentTimeMillis()); Intent notificationIntent = new Intent(this.mContext.getApplicationContext(), DownloadsListActivity.class); PendingIntent contentIntent = PendingIntent.getActivity(mContext.getApplicationContext(), 0, notificationIntent, 0); mNotification.setLatestEventInfo(mContext.getApplicationContext(), mContext.getString(R.string.DownloadNotification_DownloadInProgress), mFileName, contentIntent); mNotificationManager.notify(mNotificationId, mNotification); } private void updateNotificationOnEnd() { if (mNotification != null) { this.mNotificationManager.cancel(mNotificationId); } String message; if (mIsAborted) { message = mContext.getString(R.string.DownloadNotification_DownloadCanceled); } else { message = mContext.getString(R.string.DownloadNotification_DownloadComplete); } mNotification = new Notification(R.drawable.stat_sys_download, mContext.getString(R.string.DownloadNotification_DownloadComplete), System.currentTimeMillis()); mNotification.flags |= Notification.FLAG_AUTO_CANCEL; Intent notificationIntent = new Intent(mContext.getApplicationContext(), DownloadsListActivity.class); PendingIntent contentIntent = PendingIntent.getActivity(mContext.getApplicationContext(), 0, notificationIntent, 0); mNotification.setLatestEventInfo(mContext.getApplicationContext(), mFileName, message, contentIntent); mNotificationManager.notify(mNotificationId, mNotification); } }
UTF-8
Java
5,305
java
DownloadItem.java
Java
[]
null
[]
package sf.browser.model.items; import java.io.File; import java.util.Random; import sf.browser.R; import sf.browser.events.EventConstants; import sf.browser.events.EventController; import sf.browser.ui.activities.DownloadsListActivity; import sf.browser.ui.runnables.DownloadRunnable; import sf.browser.utils.IOUtils; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; public class DownloadItem { private Context mContext; private String mUrl; private String mFileName; private int mProgress; private String mErrorMessage; private DownloadRunnable mRunnable; private boolean mIsFinished; private boolean mIsAborted; private NotificationManager mNotificationManager; private Notification mNotification; private int mNotificationId; public DownloadItem(Context context, String url) { this.mContext = context; this.mUrl = url; this.mFileName = this.mUrl.substring(mUrl.lastIndexOf("/")+1); checkFileName(); this.mProgress = 0; this.mRunnable = null; this.mErrorMessage = null; this.mIsFinished = false; this.mIsAborted = false; Random r = new Random(); mNotificationId = r.nextInt(); mNotification = null; mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE); } /** * Gets the download url. * @return */ public String getUrl() { return this.mUrl; } /** * Gets the filename on disk. * @return */ public String getFileName() { return mFileName; } public void updateFileName(String fileName) { mFileName = fileName; checkFileName(); } public String getFilePath() { return IOUtils.getDownloadFolder().getAbsolutePath() + File.separator + mFileName; } /** * Gets the download progress * @return */ public int getProgress() { return this.mProgress; } public void setErrorMessage(String errorMessage) { this.mErrorMessage = errorMessage; } public String getErrorMessage() { return mErrorMessage; } /** * Trigger a start download event. */ public void onStart() { createNotification(); EventController.getInstance().fireDownloadEvent(EventConstants.EVT_DOWNLOAD_ON_START, this); } /** * Set this item is download finished state. Trigger a finished download event. */ public void onFinished() { this.mProgress = 100; this.mRunnable = null; this.mIsFinished = true; updateNotificationOnEnd(); EventController.getInstance().fireDownloadEvent(EventConstants.EVT_DOWNLOAD_ON_FINISHED, this); } /** * Set the current progress. Trigger a progress download event. * @param progress The current progress. */ public void onProgress(int progress) { this.mProgress = progress; EventController.getInstance().fireDownloadEvent(EventConstants.EVT_DOWNLOAD_ON_PROGRESS, this); } /** * Start the current download. */ public void startDownload() { if (mRunnable != null) { this.mRunnable.abort(); } mRunnable = new DownloadRunnable(this); new Thread(mRunnable).start(); } /** * Abort the current download. */ public void abortDownload() { if (this.mRunnable != null) { this.mRunnable.abort(); } this.mIsAborted = true; } public boolean isFinished() { return this.mIsFinished; } public boolean isAborted() { return this.mIsAborted; } /** * Remove query parameters from file name */ private void checkFileName() { int queryParamStart = mFileName.indexOf("?"); if (queryParamStart > 0) { mFileName = mFileName.substring(0, queryParamStart); } } /** * Create the download notification. */ private void createNotification() { mNotification = new Notification(R.drawable.download_anim, mContext.getString(R.string.DownloadNotification_DownloadStart), System.currentTimeMillis()); Intent notificationIntent = new Intent(this.mContext.getApplicationContext(), DownloadsListActivity.class); PendingIntent contentIntent = PendingIntent.getActivity(mContext.getApplicationContext(), 0, notificationIntent, 0); mNotification.setLatestEventInfo(mContext.getApplicationContext(), mContext.getString(R.string.DownloadNotification_DownloadInProgress), mFileName, contentIntent); mNotificationManager.notify(mNotificationId, mNotification); } private void updateNotificationOnEnd() { if (mNotification != null) { this.mNotificationManager.cancel(mNotificationId); } String message; if (mIsAborted) { message = mContext.getString(R.string.DownloadNotification_DownloadCanceled); } else { message = mContext.getString(R.string.DownloadNotification_DownloadComplete); } mNotification = new Notification(R.drawable.stat_sys_download, mContext.getString(R.string.DownloadNotification_DownloadComplete), System.currentTimeMillis()); mNotification.flags |= Notification.FLAG_AUTO_CANCEL; Intent notificationIntent = new Intent(mContext.getApplicationContext(), DownloadsListActivity.class); PendingIntent contentIntent = PendingIntent.getActivity(mContext.getApplicationContext(), 0, notificationIntent, 0); mNotification.setLatestEventInfo(mContext.getApplicationContext(), mFileName, message, contentIntent); mNotificationManager.notify(mNotificationId, mNotification); } }
5,305
0.748162
0.746089
210
24.261906
30.302019
165
false
false
0
0
0
0
0
0
1.652381
false
false
3
a783825e564d43a569ebacbf954162766ada7402
33,749,853,039,282
048530710461c7961f0625b10fd684eab754f119
/mylibrary/src/main/java/com/lyt/asyncmanager/library/type/TaskType.java
9319c1c4a99a40514d7708635ffed966f8e6d95f
[]
no_license
liyunte/AsyncManager
https://github.com/liyunte/AsyncManager
3037c827ea56f1993b078113abb7f2e0ce032c65
600cdae710b1668981a48ef8e3ae3635ceaaaa8c
refs/heads/master
2020-05-13T22:30:06.309000
2019-04-16T10:32:31
2019-04-16T10:32:31
181,668,163
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lyt.asyncmanager.library.type; public enum TaskType { AUTO,//全部 WORK,//任务 FINISH,//完成 }
UTF-8
Java
126
java
TaskType.java
Java
[]
null
[]
package com.lyt.asyncmanager.library.type; public enum TaskType { AUTO,//全部 WORK,//任务 FINISH,//完成 }
126
0.649123
0.649123
8
13.25
13.264143
42
false
false
0
0
0
0
0
0
0.5
false
false
3
75d957e5162780494fe4f768f3f6a141a8932e8d
37,701,222,934,860
1dc3e710675e26da63d7a4a5654142b955c976f8
/src/test/java/com/rahulshettyacademy/dataLoads/DataReader.java
5ee2f65f15bd5a17d0a7c72c60cb14673d6a44ba
[]
no_license
ramizkazak/DesignPatterns
https://github.com/ramizkazak/DesignPatterns
97389d28e5648c63e4e40d838d985a02f17f016c
0f57c2fb11d0c726f763f54d8f6e110a30f3b4b9
refs/heads/master
2023-07-07T17:36:06.343000
2021-08-20T19:54:09
2021-08-20T19:54:09
392,101,047
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.rahulshettyacademy.dataLoads; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.List; public class DataReader { public List<HashMap<String, String>> getJsonData(String jsonFilePath) { //Convert json file content to json string try { String jsonContent = FileUtils.readFileToString(new File("reservationDetails.json"), StandardCharsets.UTF_8); ObjectMapper mapper = new ObjectMapper(); List<HashMap<String, String>> data = mapper.readValue(jsonContent, new TypeReference<List<HashMap<String, String>>>() { }); return data; }catch (IOException e){ System.out.println(e); } return null; } }
UTF-8
Java
959
java
DataReader.java
Java
[]
null
[]
package com.rahulshettyacademy.dataLoads; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.List; public class DataReader { public List<HashMap<String, String>> getJsonData(String jsonFilePath) { //Convert json file content to json string try { String jsonContent = FileUtils.readFileToString(new File("reservationDetails.json"), StandardCharsets.UTF_8); ObjectMapper mapper = new ObjectMapper(); List<HashMap<String, String>> data = mapper.readValue(jsonContent, new TypeReference<List<HashMap<String, String>>>() { }); return data; }catch (IOException e){ System.out.println(e); } return null; } }
959
0.68926
0.688217
33
28.060606
31.862335
131
false
false
0
0
0
0
0
0
0.606061
false
false
3
89def3f6a63914e93f0ff08e6e0d6353ca6eac32
34,668,976,049,381
e15612b3bdd2ee28127e1152669d86fa9323a9ce
/com.synet.tool.rsc/src/com/synet/tool/rsc/service/PoutEntityService.java
a772560c53c1511f20ced5732eb385dfe68dec28
[]
no_license
ChalmersA/RSC50
https://github.com/ChalmersA/RSC50
6fb4283832768c365fafd0370ce32b2a90b9baf1
b119479e06a51521384d3dcd5b509302970b9064
refs/heads/master
2018-11-02T06:37:03.864000
2018-11-01T14:26:07
2018-11-01T14:26:07
143,941,858
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.synet.tool.rsc.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.synet.tool.rsc.RSCConstants; import com.synet.tool.rsc.model.Tb1046IedEntity; import com.synet.tool.rsc.model.Tb1056SvcbEntity; import com.synet.tool.rsc.model.Tb1061PoutEntity; import com.synet.tool.rsc.model.Tb1064StrapEntity; import com.synet.tool.rsc.util.RuleType; public class PoutEntityService extends BaseService{ @SuppressWarnings("unchecked") public List<Tb1061PoutEntity> getByIed(Tb1046IedEntity ied) { return (List<Tb1061PoutEntity>) beanDao.getListByCriteria(Tb1061PoutEntity.class, "tb1046IedByF1046Code", ied); } public List<Tb1061PoutEntity> getWarningData(Tb1046IedEntity ied) { return getWarningData(ied, RuleType.IED_WARN); } public List<Tb1061PoutEntity> getWarningData(Tb1046IedEntity ied, RuleType rtyp) { String hql = "from " + Tb1061PoutEntity.class.getName() + " where tb1046IedByF1046Code=:ied " + "and f1061Type between :min and :max"; Map<String, Object> params = new HashMap<>(); params.put("ied", ied); params.put("min", rtyp.getMin()); params.put("max", rtyp.getMax()); return (List<Tb1061PoutEntity>) hqlDao.getListByHql(hql, params); } public List<Tb1061PoutEntity> getOtherData(Tb1046IedEntity ied) { String hql = "from " + Tb1061PoutEntity.class.getName() + " where tb1046IedByF1046Code=:ied " + "and f1061Type=:type"; Map<String, Object> params = new HashMap<>(); params.put("ied", ied); params.put("type", RSCConstants.OTHERS_ID); return (List<Tb1061PoutEntity>) hqlDao.getListByHql(hql, params); } /** * 根据条件查找虚端子 * @param iedEntity * @param svcbEntity * @return */ @SuppressWarnings("unchecked") public List<Tb1061PoutEntity> getPoutEntityByProperties(Tb1046IedEntity iedEntity, Tb1056SvcbEntity svcbEntity) { Map<String, Object> params = new HashMap<>(); if(iedEntity !=null) { params.put("tb1046IedByF1046Code", iedEntity); } if(svcbEntity != null) { params.put("tb1056SvcbByCbCode", svcbEntity); } if(params.isEmpty()) { return new ArrayList<>(); } return (List<Tb1061PoutEntity>) beanDao.getListByCriteria(Tb1061PoutEntity.class, params); } public Tb1061PoutEntity getPoutEntity(String devName, String f1061RefAddr) { Tb1046IedEntity iedEntity = (Tb1046IedEntity) beanDao.getObject(Tb1046IedEntity.class, "f1046Name", devName); if (iedEntity != null) { Map<String, Object> params = new HashMap<>(); params.put("tb1046IedByF1046Code", iedEntity); params.put("f1061RefAddr", f1061RefAddr); return (Tb1061PoutEntity) beanDao.getObject(Tb1061PoutEntity.class, params); } return null; } /** * 根据关联的保护压板查找开出虚端子 * @param straps * @return */ @SuppressWarnings("unchecked") public List<Tb1061PoutEntity> getByStraps(List<Tb1064StrapEntity> straps) { return (List<Tb1061PoutEntity>) hqlDao.selectInObjects(Tb1061PoutEntity.class, "tb1064StrapByF1064Code", straps); } }
UTF-8
Java
3,036
java
PoutEntityService.java
Java
[]
null
[]
package com.synet.tool.rsc.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.synet.tool.rsc.RSCConstants; import com.synet.tool.rsc.model.Tb1046IedEntity; import com.synet.tool.rsc.model.Tb1056SvcbEntity; import com.synet.tool.rsc.model.Tb1061PoutEntity; import com.synet.tool.rsc.model.Tb1064StrapEntity; import com.synet.tool.rsc.util.RuleType; public class PoutEntityService extends BaseService{ @SuppressWarnings("unchecked") public List<Tb1061PoutEntity> getByIed(Tb1046IedEntity ied) { return (List<Tb1061PoutEntity>) beanDao.getListByCriteria(Tb1061PoutEntity.class, "tb1046IedByF1046Code", ied); } public List<Tb1061PoutEntity> getWarningData(Tb1046IedEntity ied) { return getWarningData(ied, RuleType.IED_WARN); } public List<Tb1061PoutEntity> getWarningData(Tb1046IedEntity ied, RuleType rtyp) { String hql = "from " + Tb1061PoutEntity.class.getName() + " where tb1046IedByF1046Code=:ied " + "and f1061Type between :min and :max"; Map<String, Object> params = new HashMap<>(); params.put("ied", ied); params.put("min", rtyp.getMin()); params.put("max", rtyp.getMax()); return (List<Tb1061PoutEntity>) hqlDao.getListByHql(hql, params); } public List<Tb1061PoutEntity> getOtherData(Tb1046IedEntity ied) { String hql = "from " + Tb1061PoutEntity.class.getName() + " where tb1046IedByF1046Code=:ied " + "and f1061Type=:type"; Map<String, Object> params = new HashMap<>(); params.put("ied", ied); params.put("type", RSCConstants.OTHERS_ID); return (List<Tb1061PoutEntity>) hqlDao.getListByHql(hql, params); } /** * 根据条件查找虚端子 * @param iedEntity * @param svcbEntity * @return */ @SuppressWarnings("unchecked") public List<Tb1061PoutEntity> getPoutEntityByProperties(Tb1046IedEntity iedEntity, Tb1056SvcbEntity svcbEntity) { Map<String, Object> params = new HashMap<>(); if(iedEntity !=null) { params.put("tb1046IedByF1046Code", iedEntity); } if(svcbEntity != null) { params.put("tb1056SvcbByCbCode", svcbEntity); } if(params.isEmpty()) { return new ArrayList<>(); } return (List<Tb1061PoutEntity>) beanDao.getListByCriteria(Tb1061PoutEntity.class, params); } public Tb1061PoutEntity getPoutEntity(String devName, String f1061RefAddr) { Tb1046IedEntity iedEntity = (Tb1046IedEntity) beanDao.getObject(Tb1046IedEntity.class, "f1046Name", devName); if (iedEntity != null) { Map<String, Object> params = new HashMap<>(); params.put("tb1046IedByF1046Code", iedEntity); params.put("f1061RefAddr", f1061RefAddr); return (Tb1061PoutEntity) beanDao.getObject(Tb1061PoutEntity.class, params); } return null; } /** * 根据关联的保护压板查找开出虚端子 * @param straps * @return */ @SuppressWarnings("unchecked") public List<Tb1061PoutEntity> getByStraps(List<Tb1064StrapEntity> straps) { return (List<Tb1061PoutEntity>) hqlDao.selectInObjects(Tb1061PoutEntity.class, "tb1064StrapByF1064Code", straps); } }
3,036
0.744139
0.674481
87
33.321838
31.137255
115
false
false
0
0
0
0
0
0
2.068965
false
false
3
2e290171c7dfa3430b7334445d18d1a48ec75ffa
37,048,387,903,334
2922bbb50881de2816dbfa6f6e1983cce2a0d59f
/src/main/java/ru/doublebyte/amznsm/services/SessionStorage.java
707eeacf02ed724f6554eb50b5bd11b4e2174fd5
[ "BSD-3-Clause" ]
permissive
n-at/amzn-stock-monitoring
https://github.com/n-at/amzn-stock-monitoring
e801e2d9b93613142a5a7264340b2620c2dfd678
f1ddcfa846a969c8260eb4adff9cc22c3e9b9a18
refs/heads/master
2022-09-02T22:45:39.955000
2021-11-28T15:53:15
2021-11-28T15:53:15
97,122,881
0
0
BSD-3-Clause
false
2022-09-01T22:19:39
2017-07-13T12:59:31
2021-11-28T15:53:20
2022-09-01T22:19:38
70
0
0
1
Java
false
false
package ru.doublebyte.amznsm.services; public class SessionStorage { private boolean authorized = false; public boolean isAuthorized() { return authorized; } public void setAuthorized(boolean authorized) { this.authorized = authorized; } }
UTF-8
Java
281
java
SessionStorage.java
Java
[]
null
[]
package ru.doublebyte.amznsm.services; public class SessionStorage { private boolean authorized = false; public boolean isAuthorized() { return authorized; } public void setAuthorized(boolean authorized) { this.authorized = authorized; } }
281
0.683274
0.683274
15
17.733334
18.277369
51
false
false
0
0
0
0
0
0
0.266667
false
false
3
24bc27351c46c72511194fb537f9849cb269f9ce
19,353,122,652,956
9ab4eeec786f456df53342c77c6c9b0395efca27
/yun-common/src/main/java/com/wdq/yun/common/enums/RespCode.java
a3744ba450f90d28841eb0f10bc8af9d918250a5
[]
no_license
dreamlikey/yun
https://github.com/dreamlikey/yun
c5e62858218f2c540a2eca84666bc1089ddf8b57
038734014e7cb0a3c583a879e734b813c15d4493
refs/heads/develope
2022-12-31T03:06:25.377000
2019-09-25T03:02:41
2019-09-25T03:02:41
162,272,665
0
0
null
false
2022-12-16T15:53:48
2018-12-18T10:43:14
2019-09-25T03:03:20
2022-12-16T15:53:45
622
0
0
10
Java
false
false
package com.wdq.yun.common.enums; /** * @author wudq * @date 2019/8/21 * @Description: */ public enum RespCode { PASS_OK(0,"操作成功"); private int code; private String desc; RespCode(int code, String desc) { this.code = code; this.desc = desc; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } }
UTF-8
Java
549
java
RespCode.java
Java
[ { "context": "package com.wdq.yun.common.enums;\n\n/**\n * @author wudq\n * @date 2019/8/21\n * @Description:\n */\npublic en", "end": 54, "score": 0.9996490478515625, "start": 50, "tag": "USERNAME", "value": "wudq" } ]
null
[]
package com.wdq.yun.common.enums; /** * @author wudq * @date 2019/8/21 * @Description: */ public enum RespCode { PASS_OK(0,"操作成功"); private int code; private String desc; RespCode(int code, String desc) { this.code = code; this.desc = desc; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } }
549
0.550832
0.536044
33
15.393939
12.380188
38
false
false
0
0
0
0
0
0
0.363636
false
false
3
4f6b416a4d18284f66e09c2056e04f7046228241
11,493,332,551,518
84a034932c8b3ca5826adc72a8833b1658a06eab
/app/src/androidTest/java/be/kdg/teame/kandoe/util/AssertionHelper.java
a282f367ab34dd3fa6236e958c0fe4c54e836fb9
[]
no_license
matdestr/AndroidClient
https://github.com/matdestr/AndroidClient
e36c59916f074b8c3a6aaa9ee4e8f5cb1ba119cc
1df806c55489141446419679554f5353fbff0995
refs/heads/master
2020-04-15T14:26:04.550000
2016-03-20T22:57:13
2016-03-20T22:57:13
51,150,878
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package be.kdg.teame.kandoe.util; import android.app.Activity; import android.support.test.runner.lifecycle.ActivityLifecycleMonitorRegistry; import android.support.test.runner.lifecycle.Stage; import java.util.Collection; import static android.support.test.InstrumentationRegistry.getInstrumentation; import static android.support.test.internal.util.Checks.checkNotNull; import static junit.framework.Assert.assertTrue; public class AssertionHelper { private static Activity currentActivity; public static void assertCurrentActivityIsInstanceOf(Class<? extends Activity> activityClass) { currentActivity = getActivityInstance(); checkNotNull(currentActivity); checkNotNull(activityClass); assertTrue(currentActivity.getClass().isAssignableFrom(activityClass)); } public static Activity getActivityInstance(){ getInstrumentation().runOnMainSync(new Runnable() { public void run() { Collection resumedActivities = ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED); if (resumedActivities.iterator().hasNext()) { currentActivity = (Activity) resumedActivities.iterator().next(); } } }); return currentActivity; } }
UTF-8
Java
1,320
java
AssertionHelper.java
Java
[]
null
[]
package be.kdg.teame.kandoe.util; import android.app.Activity; import android.support.test.runner.lifecycle.ActivityLifecycleMonitorRegistry; import android.support.test.runner.lifecycle.Stage; import java.util.Collection; import static android.support.test.InstrumentationRegistry.getInstrumentation; import static android.support.test.internal.util.Checks.checkNotNull; import static junit.framework.Assert.assertTrue; public class AssertionHelper { private static Activity currentActivity; public static void assertCurrentActivityIsInstanceOf(Class<? extends Activity> activityClass) { currentActivity = getActivityInstance(); checkNotNull(currentActivity); checkNotNull(activityClass); assertTrue(currentActivity.getClass().isAssignableFrom(activityClass)); } public static Activity getActivityInstance(){ getInstrumentation().runOnMainSync(new Runnable() { public void run() { Collection resumedActivities = ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED); if (resumedActivities.iterator().hasNext()) { currentActivity = (Activity) resumedActivities.iterator().next(); } } }); return currentActivity; } }
1,320
0.725758
0.725758
35
36.714287
32.739292
130
false
false
0
0
0
0
0
0
0.485714
false
false
3
f838bc8715f2babf40799d6948026888d6331e3e
5,652,177,026,360
6435815e410bde09b701e69dbfdd0443b2344ba8
/src/projet/java/ProjetJAVA.java
d57dfb386b153c6b6e7976065b65d5010496ddea
[]
no_license
rey49/projetjava
https://github.com/rey49/projetjava
41c4331b19ad5e60caec998cdaffbe658c190f3b
cd23aa7a8272ca40b75c6865a82da82d68a3d069
refs/heads/master
2021-01-13T02:37:40.149000
2015-05-11T00:26:55
2015-05-11T00:26:55
33,928,070
2
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 projet.java; import Vue.*; import static java.lang.Integer.parseInt; /** * * @author Panda */ public class ProjetJAVA { /** * @param args the command line arguments */ public static void main(String[] args) { MainFen fenetre = new MainFen(); } }
UTF-8
Java
512
java
ProjetJAVA.java
Java
[ { "context": "java.lang.Integer.parseInt;\r\n\r\n/**\r\n *\r\n * @author Panda\r\n */\r\npublic class ProjetJAVA {\r\n\r\n /**\r\n ", "end": 299, "score": 0.9076624512672424, "start": 294, "tag": "NAME", "value": "Panda" } ]
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 projet.java; import Vue.*; import static java.lang.Integer.parseInt; /** * * @author Panda */ public class ProjetJAVA { /** * @param args the command line arguments */ public static void main(String[] args) { MainFen fenetre = new MainFen(); } }
512
0.617188
0.617188
26
17.692308
21.292414
79
false
false
0
0
0
0
0
0
0.269231
false
false
3
6b2e7b59338ca43faab7094021ca394c7817b60d
8,306,466,820,221
125f0dc29a5922112d38d22f3480e6e4919d8f66
/src/ua/dp/ort/OOP_16/StudentsHandler.java
f476ae0eaa2f142c1760815da064477b70b3b9a1
[]
no_license
Unholyjava/ort-javabase-kaluzhny
https://github.com/Unholyjava/ort-javabase-kaluzhny
7aa2298093428d33a99d1da0b9aea1df2734787b
092cc851ee57d5938975a4263046bb31ca8f6fba
refs/heads/master
2021-01-11T07:09:35.002000
2017-03-26T10:15:38
2017-03-26T10:15:38
72,472,753
0
0
null
false
2017-03-26T10:15:39
2016-10-31T19:55:52
2016-11-05T20:50:24
2017-03-26T10:15:39
17,197
0
0
3
Java
null
null
package ua.dp.ort.OOP_16; import java.util.ArrayList; import java.util.List; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * This class has user's settings for XML SAXparser. * Class StudentsHandler extends class DefaultHandler * and override some methods of class DefaultHandler. * This class save information about element of XML-file in fields, * and direct result (list of students) save in field _studentArray. * @author Kaluzhniy * */ public class StudentsHandler extends DefaultHandler{ private List<Student> _studentArray = new ArrayList<>(); private Student _studentTemp; private Address _adressTemp; private String _nameElement; private Attributes _attributes; @Override /** * Method startDocument receive notification * of the beginning of the document. * Method throws SAXException */ public void startDocument() throws SAXException { super.startDocument(); System.out.println("Start parsing"); } @Override /** * Method endDocument receive notification * of the end of the document. * Method throws SAXException */ public void endDocument() throws SAXException { super.endDocument(); System.out.println("End parsing"); } @Override /** * Method startElement receive notification * of the start of an element, * set element name and element attributes in corresponding fields. */ public void startElement(String arg0, String arg1, String arg2, Attributes arg3) throws SAXException { super.startElement(arg0, arg1, arg2, arg3); setNameElement(arg2); setAttributes(arg3); } @Override /** * Method endElement receive notification * of the end of an element, set element name as empty string. */ public void endElement(String uri, String localName, String qName) throws SAXException { super.endElement(uri, localName, qName); setNameElement(""); } @Override /** * Method characters receive notification * of character data inside an element, * has user's settings for correctly parser from XML-file. * Element names and attributes are save in corresponding fields, * direct result (list of students) save in field _studentArray. */ public void characters(char[] ch, int start, int length) throws SAXException { super.characters(ch, start, length); if (getNameElement().equals("student")) { setStudentTemp(new Student()); getStudentTemp().setLogin(getAttributes().getValue("login")); getStudentTemp().setFaculty(getAttributes().getValue("faculty")); //System.out.println(getStudentTemp().getLogin()); //System.out.println(getStudentTemp().getFaculty()); } if (getNameElement().equals("name")) { getStudentTemp().setName(new String (ch, start, length)); //System.out.println(getStudentTemp().getName()); } if (getNameElement().equals("phone")) { getStudentTemp().setPhone(Long.valueOf(new String (ch, start, length))); //System.out.println(getStudentTemp().getPhone()); } if (getNameElement().equals("country")) { setAdressTemp(new Address()); getAdressTemp().setCountry(new String (ch, start, length)); //System.out.println(getAdressTemp().getCountry()); } if (getNameElement().equals("city")) { getAdressTemp().setCity(new String (ch, start, length)); //System.out.println(getAdressTemp().getCity()); } if (getNameElement().equals("street")) { getAdressTemp().setStreet(new String (ch, start, length)); //System.out.println(getAdressTemp().getStreet()); getStudentTemp().setAddress(getAdressTemp()); getStudentArray().add(getStudentTemp()); } } private String getNameElement() { return _nameElement; } private void setNameElement(String nameElement) { _nameElement = nameElement; } private Attributes getAttributes() { return _attributes; } private void setAttributes(Attributes attributes) { _attributes = attributes; } private Student getStudentTemp() { return _studentTemp; } private void setStudentTemp(Student studentTemp) { _studentTemp = studentTemp; } private Address getAdressTemp() { return _adressTemp; } private void setAdressTemp(Address adressTemp) { _adressTemp = adressTemp; } /** * Getter-method for return list of students - parsing result * @return studentArray */ public List<Student> getStudentArray() { return _studentArray; } }
UTF-8
Java
4,574
java
StudentsHandler.java
Java
[ { "context": "students) save in field _studentArray.\r\n * @author Kaluzhniy\r\n *\r\n */\r\npublic class StudentsHandler extends De", "end": 525, "score": 0.9179617166519165, "start": 516, "tag": "USERNAME", "value": "Kaluzhniy" } ]
null
[]
package ua.dp.ort.OOP_16; import java.util.ArrayList; import java.util.List; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * This class has user's settings for XML SAXparser. * Class StudentsHandler extends class DefaultHandler * and override some methods of class DefaultHandler. * This class save information about element of XML-file in fields, * and direct result (list of students) save in field _studentArray. * @author Kaluzhniy * */ public class StudentsHandler extends DefaultHandler{ private List<Student> _studentArray = new ArrayList<>(); private Student _studentTemp; private Address _adressTemp; private String _nameElement; private Attributes _attributes; @Override /** * Method startDocument receive notification * of the beginning of the document. * Method throws SAXException */ public void startDocument() throws SAXException { super.startDocument(); System.out.println("Start parsing"); } @Override /** * Method endDocument receive notification * of the end of the document. * Method throws SAXException */ public void endDocument() throws SAXException { super.endDocument(); System.out.println("End parsing"); } @Override /** * Method startElement receive notification * of the start of an element, * set element name and element attributes in corresponding fields. */ public void startElement(String arg0, String arg1, String arg2, Attributes arg3) throws SAXException { super.startElement(arg0, arg1, arg2, arg3); setNameElement(arg2); setAttributes(arg3); } @Override /** * Method endElement receive notification * of the end of an element, set element name as empty string. */ public void endElement(String uri, String localName, String qName) throws SAXException { super.endElement(uri, localName, qName); setNameElement(""); } @Override /** * Method characters receive notification * of character data inside an element, * has user's settings for correctly parser from XML-file. * Element names and attributes are save in corresponding fields, * direct result (list of students) save in field _studentArray. */ public void characters(char[] ch, int start, int length) throws SAXException { super.characters(ch, start, length); if (getNameElement().equals("student")) { setStudentTemp(new Student()); getStudentTemp().setLogin(getAttributes().getValue("login")); getStudentTemp().setFaculty(getAttributes().getValue("faculty")); //System.out.println(getStudentTemp().getLogin()); //System.out.println(getStudentTemp().getFaculty()); } if (getNameElement().equals("name")) { getStudentTemp().setName(new String (ch, start, length)); //System.out.println(getStudentTemp().getName()); } if (getNameElement().equals("phone")) { getStudentTemp().setPhone(Long.valueOf(new String (ch, start, length))); //System.out.println(getStudentTemp().getPhone()); } if (getNameElement().equals("country")) { setAdressTemp(new Address()); getAdressTemp().setCountry(new String (ch, start, length)); //System.out.println(getAdressTemp().getCountry()); } if (getNameElement().equals("city")) { getAdressTemp().setCity(new String (ch, start, length)); //System.out.println(getAdressTemp().getCity()); } if (getNameElement().equals("street")) { getAdressTemp().setStreet(new String (ch, start, length)); //System.out.println(getAdressTemp().getStreet()); getStudentTemp().setAddress(getAdressTemp()); getStudentArray().add(getStudentTemp()); } } private String getNameElement() { return _nameElement; } private void setNameElement(String nameElement) { _nameElement = nameElement; } private Attributes getAttributes() { return _attributes; } private void setAttributes(Attributes attributes) { _attributes = attributes; } private Student getStudentTemp() { return _studentTemp; } private void setStudentTemp(Student studentTemp) { _studentTemp = studentTemp; } private Address getAdressTemp() { return _adressTemp; } private void setAdressTemp(Address adressTemp) { _adressTemp = adressTemp; } /** * Getter-method for return list of students - parsing result * @return studentArray */ public List<Student> getStudentArray() { return _studentArray; } }
4,574
0.68955
0.686926
165
25.709091
23.914753
103
false
false
0
0
0
0
0
0
1.757576
false
false
3
aada8118ae37d5a2db3a4b1e4cb143e6ceb53c20
5,385,889,036,371
b0bd8fb1d507a219563c25635cca2138d81e03a7
/src/day31/MethodCallAnotherMethod.java
bb4b37dd86b20f372a59696bda93b1dcc0b2605a
[]
no_license
sharifamiri/JavaCodeExercises
https://github.com/sharifamiri/JavaCodeExercises
8c490e65de79748950dc75caf28875e46f87cc4f
b2160e213d4a8bfb583e1878f916110860b7d5ce
refs/heads/master
2022-12-30T10:08:29.663000
2020-10-14T06:57:59
2020-10-14T06:57:59
222,198,225
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package day31; public class MethodCallAnotherMethod { public static void main(String[] args) { // prepare(); // addIngredients(); // testAndBringToTable(); AskSpouseToDoAll(); } public static void AskSpouseToDoAll() { prepare(); addIngredients(); testAndBringToTable(); } public static void prepare() { System.out.println("Step1: Boil Water"); } public static void addIngredients() { System.out.println("Step2: Add Pasta"); System.out.println("Step2: Add Oil"); } public static void testAndBringToTable() { System.out.println("Step1: READY"); } }
UTF-8
Java
589
java
MethodCallAnotherMethod.java
Java
[]
null
[]
package day31; public class MethodCallAnotherMethod { public static void main(String[] args) { // prepare(); // addIngredients(); // testAndBringToTable(); AskSpouseToDoAll(); } public static void AskSpouseToDoAll() { prepare(); addIngredients(); testAndBringToTable(); } public static void prepare() { System.out.println("Step1: Boil Water"); } public static void addIngredients() { System.out.println("Step2: Add Pasta"); System.out.println("Step2: Add Oil"); } public static void testAndBringToTable() { System.out.println("Step1: READY"); } }
589
0.685908
0.675722
32
17.40625
16.469402
43
false
false
0
0
0
0
0
0
1.53125
false
false
3
bc4f4d2d53f542c3bec876c3052e478419ea16d7
36,593,121,379,118
17a2eca990f86b225e8f08a2346df892a35c486c
/pinyougouinterface/src/main/java/com/tianzhen/service/UserService.java
f8d03ea57f1bb87736a03f66b7710130ce5fe527
[]
no_license
tianzhen45/pingyougou
https://github.com/tianzhen45/pingyougou
280c6242062f56bb3cd0295069767f64115d7590
244e554d49e3812e982b61a4ee2dacb933c5ff7c
refs/heads/master
2022-12-26T12:36:13.379000
2019-09-19T12:03:32
2019-09-19T12:03:32
221,680,011
0
0
null
false
2022-12-15T23:42:03
2019-11-14T11:19:15
2019-11-14T11:21:55
2022-12-15T23:42:00
13,495
0
0
15
JavaScript
false
false
package com.tianzhen.service; import com.github.pagehelper.PageInfo; import com.tianzhen.pojo.User; import java.util.List; import java.util.Map; public interface UserService { List<User> findAll(); void save(User user); void update(User user); PageInfo<User> findByPage(int pageNum, int pageSize); void delete(Integer id); List<Map<String,Object>> findAllByIdAndName(); User findById(Integer id); User findByUsername(String username); boolean sendCode(String phone); boolean checkSmsCode(String phone, String smsCode); }
UTF-8
Java
574
java
UserService.java
Java
[]
null
[]
package com.tianzhen.service; import com.github.pagehelper.PageInfo; import com.tianzhen.pojo.User; import java.util.List; import java.util.Map; public interface UserService { List<User> findAll(); void save(User user); void update(User user); PageInfo<User> findByPage(int pageNum, int pageSize); void delete(Integer id); List<Map<String,Object>> findAllByIdAndName(); User findById(Integer id); User findByUsername(String username); boolean sendCode(String phone); boolean checkSmsCode(String phone, String smsCode); }
574
0.721254
0.721254
30
18.133333
18.6989
57
false
false
0
0
0
0
0
0
0.6
false
false
3
bb10191938d1cff549faa7ded307ceb16e859d2d
33,947,421,549,062
dc75a48a99505bbadf7c7c49e231b82a3468f9b8
/03-bill_splitter/debugging.java
2e5affa2bd87e74f1728fe903afa5c61d5eb5881
[]
no_license
fdrHighSchool/fall-2020-work-LippieVIII
https://github.com/fdrHighSchool/fall-2020-work-LippieVIII
a9d86d0484708f81db056ea78cd76c77a6d26dd1
81dd4792c5a17d194fbde2e838c778ad7022ff15
refs/heads/main
2023-02-24T21:59:42.801000
2021-01-16T04:09:46
2021-01-16T04:09:46
305,387,937
0
1
null
false
2020-10-19T13:10:39
2020-10-19T13:10:30
2020-10-19T13:10:38
2020-10-19T13:10:38
0
0
0
1
null
false
false
import java.util.*; public class debugging { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Welcome to the Bill-Splitter"); System.out.print("Enter the total, pre-tax: "); double total = input.nextInt(); System.out.print("How many people? "); int numPeople = input.nextInt(); double perPerson = numPeople / total; System.out.println("Each person must pay $" + perPerson + ", plus tip"); }//end main method }//end class
UTF-8
Java
496
java
debugging.java
Java
[]
null
[]
import java.util.*; public class debugging { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Welcome to the Bill-Splitter"); System.out.print("Enter the total, pre-tax: "); double total = input.nextInt(); System.out.print("How many people? "); int numPeople = input.nextInt(); double perPerson = numPeople / total; System.out.println("Each person must pay $" + perPerson + ", plus tip"); }//end main method }//end class
496
0.685484
0.685484
18
26.555555
21.294815
74
false
false
0
0
0
0
0
0
1.611111
false
false
3
8fcb60055ef422a2fd28c6b21d726e0df8a0ea32
37,993,280,714,052
4a793718587da2d5cc2abc2608893acc9e2596bb
/WS5_180125529/src/ict/test/TestEdit.java
406925d6f68267bf0c803a7ad9646511df7b6128
[]
no_license
billjjjj/ITP4511_ESD
https://github.com/billjjjj/ITP4511_ESD
7a12ced857f8c632112d8ab8feffcf890dc83082
7ae4486b999bc85d0750504be0d89893bc31d284
refs/heads/master
2020-07-20T22:34:51.100000
2019-12-22T01:29:10
2019-12-22T01:29:10
206,720,203
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ict.test; import ict.bean.CustomerBean; import ict.db.CustomerDB; import static ict.test.ConnectionValue.*; public class TestEdit { public static void main(String[] args) { CustomerDB customerDB = new CustomerDB(url, username, password); CustomerBean cb = new CustomerBean(); cb.setCustId("1"); cb.setName("Andy"); cb.setTel("222222"); cb.setAge(99); customerDB.editRecord(cb); } }
UTF-8
Java
458
java
TestEdit.java
Java
[ { "context": ");\n cb.setCustId(\"1\");\n cb.setName(\"Andy\");\n cb.setTel(\"222222\");\n cb.setAge", "end": 358, "score": 0.9993896484375, "start": 354, "tag": "NAME", "value": "Andy" } ]
null
[]
package ict.test; import ict.bean.CustomerBean; import ict.db.CustomerDB; import static ict.test.ConnectionValue.*; public class TestEdit { public static void main(String[] args) { CustomerDB customerDB = new CustomerDB(url, username, password); CustomerBean cb = new CustomerBean(); cb.setCustId("1"); cb.setName("Andy"); cb.setTel("222222"); cb.setAge(99); customerDB.editRecord(cb); } }
458
0.644105
0.624454
19
23.105263
18.948391
72
false
false
0
0
0
0
0
0
0.684211
false
false
3
9f29191622eb95367463b36ebcbd3f4851d5d32b
35,631,048,711,524
9265289eea789fe7bc567084b74e1b6bfc60068c
/de/alex/lobbysystem/utils/utils.java
cc6a0641740d93a670c78b14f1ce7737b19b28a4
[]
no_license
GoldenGamerLP/LobbySystem
https://github.com/GoldenGamerLP/LobbySystem
e64086105a309110b13b9df517bc376a9f767893
44432aab3306bf394fde732f7701ab26ef8416db
refs/heads/main
2023-02-25T19:33:00.837000
2021-01-20T18:17:20
2021-01-20T18:17:20
325,292,347
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package de.alex.lobbysystem.utils; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.boss.BarFlag; import org.bukkit.boss.BarStyle; import org.bukkit.boss.BossBar; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import java.util.Arrays; public class utils { public final static ItemStack compass = utils.getItem(utils.colorString("&8» &f&nCompass"), Material.BLAZE_POWDER, 1, utils.colorString("&8» &7Rechtsklick")); static final BarFlag[] EMPTY_ARRAY = new BarFlag[0]; public static BossBar createBossbar(String title, org.bukkit.boss.BarColor ch, BarStyle style) { BossBar bs = Bukkit.createBossBar(title, ch, style, EMPTY_ARRAY); bs.addFlag(BarFlag.CREATE_FOG); bs.addFlag(BarFlag.DARKEN_SKY); return bs; } public static void teleport(Player p, Location loc) { p.sendMessage("Teleported!"); p.teleport(new Location(loc.getWorld(), loc.getX(), loc.getY(), loc.getZ())); } public static String colorString(String string) { return ChatColor.translateAlternateColorCodes('&', string); } public static Boolean permissionMSG(String perm, Player p) { if (p.hasPermission(perm)) { return true; } else { p.sendMessage(utils.colorString(String.format("&9Lobby &8» &cDazu hast du keine Berechtigung! &7(&e%s&7)", perm))); return false; } } public static ItemStack getItem(String name, Material mat, int i, String lore) { ItemStack stack = new ItemStack(mat, i); ItemMeta meta = stack.getItemMeta(); meta.setDisplayName(utils.colorString(name)); meta.setLore(Arrays.asList(lore)); stack.setItemMeta(meta); return stack; } public static boolean isBetween(int a, int b, int c) { return b > a ? c > a && c < b : c > b && c < a; } public static boolean isNumeric(String strNum) { if (strNum == null) { return false; } try { double d = Double.parseDouble(strNum); } catch (NumberFormatException nfe) { return false; } return true; } }
UTF-8
Java
2,373
java
utils.java
Java
[]
null
[]
package de.alex.lobbysystem.utils; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.boss.BarFlag; import org.bukkit.boss.BarStyle; import org.bukkit.boss.BossBar; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import java.util.Arrays; public class utils { public final static ItemStack compass = utils.getItem(utils.colorString("&8» &f&nCompass"), Material.BLAZE_POWDER, 1, utils.colorString("&8» &7Rechtsklick")); static final BarFlag[] EMPTY_ARRAY = new BarFlag[0]; public static BossBar createBossbar(String title, org.bukkit.boss.BarColor ch, BarStyle style) { BossBar bs = Bukkit.createBossBar(title, ch, style, EMPTY_ARRAY); bs.addFlag(BarFlag.CREATE_FOG); bs.addFlag(BarFlag.DARKEN_SKY); return bs; } public static void teleport(Player p, Location loc) { p.sendMessage("Teleported!"); p.teleport(new Location(loc.getWorld(), loc.getX(), loc.getY(), loc.getZ())); } public static String colorString(String string) { return ChatColor.translateAlternateColorCodes('&', string); } public static Boolean permissionMSG(String perm, Player p) { if (p.hasPermission(perm)) { return true; } else { p.sendMessage(utils.colorString(String.format("&9Lobby &8» &cDazu hast du keine Berechtigung! &7(&e%s&7)", perm))); return false; } } public static ItemStack getItem(String name, Material mat, int i, String lore) { ItemStack stack = new ItemStack(mat, i); ItemMeta meta = stack.getItemMeta(); meta.setDisplayName(utils.colorString(name)); meta.setLore(Arrays.asList(lore)); stack.setItemMeta(meta); return stack; } public static boolean isBetween(int a, int b, int c) { return b > a ? c > a && c < b : c > b && c < a; } public static boolean isNumeric(String strNum) { if (strNum == null) { return false; } try { double d = Double.parseDouble(strNum); } catch (NumberFormatException nfe) { return false; } return true; } }
2,373
0.624051
0.620253
71
31.380281
30.601191
162
false
false
0
0
0
0
0
0
0.788732
false
false
3
b313c4ee80e18df1db464bf10054fa5e35cbeba6
36,971,078,501,624
e3c9f3aa32379b803670498fe0fa02f9f493b80c
/src/test/java/com/mikaelson/login/TestBuild.java
2a17ea4fd2939eb0312bb570cd12aefc2dbb79b0
[]
no_license
niklausmikaelson1002/sourcecode
https://github.com/niklausmikaelson1002/sourcecode
1767d4290f6e7bceb2bccf2da2c2624e76d10554
4523c3cc217646af5e412252f6b007cddf965694
refs/heads/master
2022-12-06T23:18:31.812000
2016-06-12T16:32:58
2016-06-12T16:32:58
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/****************************************************************************** * @File name : TestBuild.java * * @Author : Hasee * * @Date : 2015年12月2日 * * @Copyright Notice: * Copyright (c) 2020 Mikaelson Niklaus, Inc. All Rights Reserved. * This software is published under the terms of the Mikaelson Niklaus Software * License version 1.0, a copy of which has been included with this * distribution in the LICENSE.txt file. * * * ---------------------------------------------------------------------------- * Date Who Version Comments * 2015年12月2日 下午10:56:55 Hasee 1.0 Initial Version *****************************************************************************/ package com.mikaelson.login; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; import com.mikaelson.login.service.ILoginService; /** * */ @ContextConfiguration(locations = { "classpath*:spring-context.xml" }) public class TestBuild extends AbstractJUnit4SpringContextTests { public <T> T getBean(Class<T> type) { return applicationContext.getBean(type); } public Object getBean(String beanName) { return applicationContext.getBean(beanName); } protected ApplicationContext getContext() { return applicationContext; } @Test public void testLogin() { System.out.println("============="+applicationContext); ILoginService loginService = getBean(ILoginService.class) ; loginService.sayHello(); } }
UTF-8
Java
1,748
java
TestBuild.java
Java
[ { "context": " : TestBuild.java\r\n *\r\n * @Author : Hasee\r\n *\r\n * @Date : 2015年12月2日\r\n *\r\n * @C", "end": 152, "score": 0.9998361468315125, "start": 147, "tag": "NAME", "value": "Hasee" }, { "context": "\n *\r\n * @Copyright Notice: \r\n * Copyright (c) 2020 Mikaelson Niklaus, Inc. All Rights Reserved.\r\n * This software is ", "end": 260, "score": 0.9993385076522827, "start": 243, "tag": "NAME", "value": "Mikaelson Niklaus" } ]
null
[]
/****************************************************************************** * @File name : TestBuild.java * * @Author : Hasee * * @Date : 2015年12月2日 * * @Copyright Notice: * Copyright (c) 2020 <NAME>, Inc. All Rights Reserved. * This software is published under the terms of the Mikaelson Niklaus Software * License version 1.0, a copy of which has been included with this * distribution in the LICENSE.txt file. * * * ---------------------------------------------------------------------------- * Date Who Version Comments * 2015年12月2日 下午10:56:55 Hasee 1.0 Initial Version *****************************************************************************/ package com.mikaelson.login; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; import com.mikaelson.login.service.ILoginService; /** * */ @ContextConfiguration(locations = { "classpath*:spring-context.xml" }) public class TestBuild extends AbstractJUnit4SpringContextTests { public <T> T getBean(Class<T> type) { return applicationContext.getBean(type); } public Object getBean(String beanName) { return applicationContext.getBean(beanName); } protected ApplicationContext getContext() { return applicationContext; } @Test public void testLogin() { System.out.println("============="+applicationContext); ILoginService loginService = getBean(ILoginService.class) ; loginService.sayHello(); } }
1,737
0.58545
0.567552
55
29.49091
28.390697
80
false
false
0
0
0
0
0
0
0.745455
false
false
3
5c8981f1fcbbe30d7d05437e2d639103b04119ef
30,794,915,544,482
ea6374a0e18371bdd034c6790c149563deafe413
/project2/tss/src/coreservlets/q2.java
9270d836820d9935e5deb6c16dccd77d69b7fa2c
[]
no_license
kinsumliu/CSE-532-Database
https://github.com/kinsumliu/CSE-532-Database
007421a0c05afa5c70fafe1c1ae75bd67476e460
3f36401fb918584e402a7fcfa328b121faebb2f4
refs/heads/master
2021-01-01T16:44:41.002000
2014-12-01T16:25:49
2014-12-01T16:25:49
24,272,008
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/**************************************************************************** * CSE532 -- Project 2 * File name: q2.java * Author(s): Kin Sum Liu (109247869), Hao-Tsung Yang (109892492) * Brief description: Servlet to execute Query 2 and create the html to display the result ****************************************************************************/ package coreservlets; import java.io.*; import javax.servlet.*; import javax.servlet.annotation.*; import javax.servlet.http.*; import java.util.*; import java.sql.*; @WebServlet("/query2") public class q2 extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // http://stackoverflow.com/questions/11652431/eclipse-add-jar-to-dynamic-web-project Connection conn = null; try { // Register JDBC driver Class.forName("org.postgresql.Driver"); conn = DriverManager.getConnection( "jdbc:postgresql://localhost:5432/tss", "kinsumliu", "pw"); // Open a connection Statement stmt = conn.createStatement(); ResultSet rs = stmt .executeQuery("SELECT C1.name AS name1, C2.name AS name2 " + "FROM Contestants C1, Contestants C2, " + "Performances P1, Performances P2 " + "WHERE P1.piece = P2.piece AND " + "P1.contestant = C1.oid AND " + "P2.contestant = C2.oid AND " + "C1.name < C2.name AND " + "( SELECT avg(r.score) FROM unnest(P1.results) r) = ( SELECT avg(r.score) FROM unnest(P2.results) r) "); String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n"; String title = "Query 2"; docType += "<HTML>\n" + "<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" + "<H1 ALIGN=CENTER>" + title + "</H1>\n"; while (rs.next()) { String name1 = rs.getString("name1"); String name2 = rs.getString("name2"); docType += name1 + " " + name2 + "<br>\n"; } docType += "</HTML>"; PrintWriter out = response.getWriter(); out.println(docType); rs.close(); stmt.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
UTF-8
Java
2,406
java
q2.java
Java
[ { "context": "-- Project 2\r\n * File name: q2.java\r\n * Author(s): Kin Sum Liu (109247869), Hao-Tsung Yang (109892492)\r\n * Brief", "end": 167, "score": 0.9996376633644104, "start": 156, "tag": "NAME", "value": "Kin Sum Liu" }, { "context": "e: q2.java\r\n * Author(s): Kin Sum Liu (109247869), Hao-Tsung Yang (109892492)\r\n * Brief description: Servlet to exe", "end": 195, "score": 0.9998650550842285, "start": 181, "tag": "NAME", "value": "Hao-Tsung Yang" } ]
null
[]
/**************************************************************************** * CSE532 -- Project 2 * File name: q2.java * Author(s): <NAME> (109247869), <NAME> (109892492) * Brief description: Servlet to execute Query 2 and create the html to display the result ****************************************************************************/ package coreservlets; import java.io.*; import javax.servlet.*; import javax.servlet.annotation.*; import javax.servlet.http.*; import java.util.*; import java.sql.*; @WebServlet("/query2") public class q2 extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // http://stackoverflow.com/questions/11652431/eclipse-add-jar-to-dynamic-web-project Connection conn = null; try { // Register JDBC driver Class.forName("org.postgresql.Driver"); conn = DriverManager.getConnection( "jdbc:postgresql://localhost:5432/tss", "kinsumliu", "pw"); // Open a connection Statement stmt = conn.createStatement(); ResultSet rs = stmt .executeQuery("SELECT C1.name AS name1, C2.name AS name2 " + "FROM Contestants C1, Contestants C2, " + "Performances P1, Performances P2 " + "WHERE P1.piece = P2.piece AND " + "P1.contestant = C1.oid AND " + "P2.contestant = C2.oid AND " + "C1.name < C2.name AND " + "( SELECT avg(r.score) FROM unnest(P1.results) r) = ( SELECT avg(r.score) FROM unnest(P2.results) r) "); String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n"; String title = "Query 2"; docType += "<HTML>\n" + "<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" + "<H1 ALIGN=CENTER>" + title + "</H1>\n"; while (rs.next()) { String name1 = rs.getString("name1"); String name2 = rs.getString("name2"); docType += name1 + " " + name2 + "<br>\n"; } docType += "</HTML>"; PrintWriter out = response.getWriter(); out.println(docType); rs.close(); stmt.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
2,393
0.585204
0.556941
73
30.958904
25.277332
113
false
false
0
0
0
0
0
0
2.780822
false
false
3
716bab91f6c10e94a723ef56b3f2cdd9e0187025
18,013,092,871,418
07fa65b44a285b8a9bb433f7157c5146434cf2ec
/src/main/java/com/assertsolutions/dto/Response.java
11acae67e2dd0ca340b41e01e93508993380a300
[]
no_license
neckstrauss/rest-kafka
https://github.com/neckstrauss/rest-kafka
380c7ebe978f837e262ca151fb8e7870ce7cd52e
c451a8594bbe281842ace191cd417a577e091e1c
refs/heads/master
2020-06-22T02:58:11.895000
2019-07-23T19:33:36
2019-07-23T19:33:36
197,616,347
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.assertsolutions.dto; import java.text.SimpleDateFormat; import java.util.Date; /** * * @author Assert Solutions S.A.S * */ public class Response { private Data data; public Response(String response, String message, Date fecha) { super(); String pattern = "yyyy-MM-dd HH:mm:ssZ"; this.data = new Data(response, message, new SimpleDateFormat(pattern).format(fecha)); } public Data getData() { return data; } public void setData(Data data) { this.data = data; } private class Data{ private String response; private String message; private String fecha; public Data(String response, String message, String fecha) { super(); this.response = response; this.message = message; this.fecha = fecha; } public String getResponse() { return response; } public void setResponse(String response) { this.response = response; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getFecha() { return fecha; } public void setFecha(String fecha) { this.fecha = fecha; } } }
UTF-8
Java
1,276
java
Response.java
Java
[]
null
[]
package com.assertsolutions.dto; import java.text.SimpleDateFormat; import java.util.Date; /** * * @author Assert Solutions S.A.S * */ public class Response { private Data data; public Response(String response, String message, Date fecha) { super(); String pattern = "yyyy-MM-dd HH:mm:ssZ"; this.data = new Data(response, message, new SimpleDateFormat(pattern).format(fecha)); } public Data getData() { return data; } public void setData(Data data) { this.data = data; } private class Data{ private String response; private String message; private String fecha; public Data(String response, String message, String fecha) { super(); this.response = response; this.message = message; this.fecha = fecha; } public String getResponse() { return response; } public void setResponse(String response) { this.response = response; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getFecha() { return fecha; } public void setFecha(String fecha) { this.fecha = fecha; } } }
1,276
0.611285
0.611285
73
15.479452
17.690729
87
false
false
0
0
0
0
0
0
1.506849
false
false
3
4679c81f34c4088c38ccb8f3115cd30eba632aaf
19,250,043,422,029
624abcd9562f276f6d492282cc8e20251bb9d935
/hejiameng/src/main/java/com/sangame/hjm/cases/PreferenceRecommendTest.java
ec2ac188f118d76ec277d57045db32ec3626ef98
[]
no_license
shangguanxiaoguan/AutoTest
https://github.com/shangguanxiaoguan/AutoTest
45864c986ef4564b3d1b210f3c63e8cf8e9d6e4b
afd41d39b318b0191ae795ef36e262a6c196e679
refs/heads/master
2022-07-12T07:42:14.136000
2019-08-15T06:08:01
2019-08-15T06:08:01
188,189,539
0
0
null
false
2022-06-29T17:34:22
2019-05-23T08:05:32
2019-08-15T06:08:24
2022-06-29T17:34:22
5,970
0
0
19
Java
false
false
package com.sangame.hjm.cases; import com.google.gson.Gson; import com.sangame.hjm.config.TestConfig; import com.sangame.hjm.model.InterfaceName; import com.sangame.hjm.model.JmProject; import com.sangame.hjm.model.SearchHomeJoinHeadlineResult; import com.sangame.hjm.utils.ConfigFile; import com.sangame.hjm.utils.DateFormatChange; import com.sangame.hjm.utils.DatebaseUtil; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.apache.ibatis.session.SqlSession; import org.apache.tools.ant.taskdefs.condition.Http; import org.testng.Assert; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.io.IOException; import java.util.List; /** * 查询优选推荐接口测试 */ public class PreferenceRecommendTest { @BeforeTest public void beforeTest(){ TestConfig.preferenceRecommendUrl = ConfigFile.getUrl(InterfaceName.PREFERENCERECOMMEND); TestConfig.defaultHttpClient = new DefaultHttpClient(); } @Test public void preferenceRecommend() throws IOException { SqlSession sqlSession = DatebaseUtil.getSqlSession(); //发送请求,获取接口返回结果 SearchHomeJoinHeadlineResult result = getResponseResult(); System.out.println("查询优选推荐接口返回的结果:" + result.toString()); System.out.println("查询优选推荐接口返回的data结果:" + result.getData().toString()); //查询数据库数据 SqlSession expectedSession = DatebaseUtil.getSqlSession(); List<JmProject> expectedResult = expectedSession.selectList("getPreferenceRecommend"); System.out.println("查询数据库优选推荐结果:" + expectedResult.toString()); //验证结果 Assert.assertEquals(result.getCode(), 0); Assert.assertEquals(result.getData().size(), expectedResult.size()); if (!result.getData().isEmpty() && !expectedResult.isEmpty()) { for (int i = 0; i < expectedResult.size(); i++) { Assert.assertEquals(result.getData().get(i).getCreateAt(), DateFormatChange.dateFormatChange(expectedResult.get(i).getCreateAt())); Assert.assertEquals(result.getData().get(i).getUpdateAt(), DateFormatChange.dateFormatChange(expectedResult.get(i).getUpdateAt())); Assert.assertEquals(result.getData().get(i).getCreator(), expectedResult.get(i).getCreator()); Assert.assertEquals(result.getData().get(i).getModifier(), expectedResult.get(i).getModifier()); if (expectedResult.get(i).getDeleteFlag() == 0){ Assert.assertEquals(result.getData().get(i).isDeleteFlag(), false); }else if(expectedResult.get(i).getDeleteFlag() == 1){ Assert.assertEquals(result.getData().get(i).isDeleteFlag(), true); } Assert.assertEquals(result.getData().get(i).getId(), expectedResult.get(i).getId()); Assert.assertEquals(result.getData().get(i).getCategoryId(), expectedResult.get(i).getCategoryId()); Assert.assertEquals(result.getData().get(i).getSubCategoryId(), expectedResult.get(i).getSubCategoryId()); Assert.assertEquals(result.getData().get(i).getCompanyId(), expectedResult.get(i).getCompanyId()); Assert.assertEquals(result.getData().get(i).getTitle(), expectedResult.get(i).getTitle()); Assert.assertEquals(result.getData().get(i).getKeyword(), expectedResult.get(i).getKeyword()); Assert.assertEquals(result.getData().get(i).getPhoto(), expectedResult.get(i).getPhoto()); Assert.assertEquals(result.getData().get(i).getRecommendFlag(), expectedResult.get(i).getRecommendFlag()); Assert.assertEquals(result.getData().get(i).getBuildDate(), DateFormatChange.stringDateFormatChange(expectedResult.get(i).getBuildDate())); Assert.assertEquals(result.getData().get(i).getOriginAddr(), expectedResult.get(i).getOriginAddr()); Assert.assertEquals(result.getData().get(i).getBusinessModel(), expectedResult.get(i).getBusinessModel()); Assert.assertEquals(result.getData().get(i).getProduct(), expectedResult.get(i).getProduct()); Assert.assertEquals(result.getData().get(i).getCrowd(), expectedResult.get(i).getCrowd()); Assert.assertEquals(result.getData().get(i).getArea(), expectedResult.get(i).getArea()); Assert.assertEquals(result.getData().get(i).getSupport(), expectedResult.get(i).getSupport()); Assert.assertEquals(result.getData().get(i).getInvestMin(), expectedResult.get(i).getInvestMin()); Assert.assertEquals(result.getData().get(i).getInvestMax(), expectedResult.get(i).getInvestMax()); Assert.assertEquals(result.getData().get(i).getMargin(), expectedResult.get(i).getMargin()); Assert.assertEquals(result.getData().get(i).getFacilityCost(), expectedResult.get(i).getFacilityCost()); // if (expectedResult.get(i).getOtherCost() == null){ // Assert.assertEquals(result.getData().get(i).getOtherCost(),expectedResult.get(i).getOtherCost()); // } Assert.assertEquals(result.getData().get(i).getOtherCost(), expectedResult.get(i).getOtherCost()); Assert.assertEquals(result.getData().get(i).getDescription(), expectedResult.get(i).getDescription()); Assert.assertEquals(result.getData().get(i).getCompanyName(), expectedResult.get(i).getCompanyName()); Assert.assertEquals(result.getData().get(i).getRegisterTime(), expectedResult.get(i).getRegisterTime()); Assert.assertEquals(result.getData().get(i).getState(), expectedResult.get(i).getState()); Assert.assertEquals(result.getData().get(i).getStateName(), "上架中"); Assert.assertEquals(result.getData().get(i).getAttribute(), expectedResult.get(i).getAttribute()); Assert.assertEquals(result.getData().get(i).getAttributeName(), "推荐"); Assert.assertEquals(result.getData().get(i).getProjectExtra(), expectedResult.get(i).getProjectExtra()); Assert.assertEquals(result.getData().get(i).getProjectPhotos(), expectedResult.get(i).getProjectPhotos()); Assert.assertEquals(result.getData().get(i).getLikes(), expectedResult.get(i).getLikes()); } } } private SearchHomeJoinHeadlineResult getResponseResult() throws IOException { HttpGet get = new HttpGet(TestConfig.preferenceRecommendUrl); System.out.println("查询优选推荐Url get:" + get); HttpResponse response = TestConfig.defaultHttpClient.execute(get); String result = EntityUtils.toString(response.getEntity()); SearchHomeJoinHeadlineResult resultClass = new Gson().fromJson(result,SearchHomeJoinHeadlineResult.class); return resultClass; } }
UTF-8
Java
7,158
java
PreferenceRecommendTest.java
Java
[]
null
[]
package com.sangame.hjm.cases; import com.google.gson.Gson; import com.sangame.hjm.config.TestConfig; import com.sangame.hjm.model.InterfaceName; import com.sangame.hjm.model.JmProject; import com.sangame.hjm.model.SearchHomeJoinHeadlineResult; import com.sangame.hjm.utils.ConfigFile; import com.sangame.hjm.utils.DateFormatChange; import com.sangame.hjm.utils.DatebaseUtil; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.apache.ibatis.session.SqlSession; import org.apache.tools.ant.taskdefs.condition.Http; import org.testng.Assert; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.io.IOException; import java.util.List; /** * 查询优选推荐接口测试 */ public class PreferenceRecommendTest { @BeforeTest public void beforeTest(){ TestConfig.preferenceRecommendUrl = ConfigFile.getUrl(InterfaceName.PREFERENCERECOMMEND); TestConfig.defaultHttpClient = new DefaultHttpClient(); } @Test public void preferenceRecommend() throws IOException { SqlSession sqlSession = DatebaseUtil.getSqlSession(); //发送请求,获取接口返回结果 SearchHomeJoinHeadlineResult result = getResponseResult(); System.out.println("查询优选推荐接口返回的结果:" + result.toString()); System.out.println("查询优选推荐接口返回的data结果:" + result.getData().toString()); //查询数据库数据 SqlSession expectedSession = DatebaseUtil.getSqlSession(); List<JmProject> expectedResult = expectedSession.selectList("getPreferenceRecommend"); System.out.println("查询数据库优选推荐结果:" + expectedResult.toString()); //验证结果 Assert.assertEquals(result.getCode(), 0); Assert.assertEquals(result.getData().size(), expectedResult.size()); if (!result.getData().isEmpty() && !expectedResult.isEmpty()) { for (int i = 0; i < expectedResult.size(); i++) { Assert.assertEquals(result.getData().get(i).getCreateAt(), DateFormatChange.dateFormatChange(expectedResult.get(i).getCreateAt())); Assert.assertEquals(result.getData().get(i).getUpdateAt(), DateFormatChange.dateFormatChange(expectedResult.get(i).getUpdateAt())); Assert.assertEquals(result.getData().get(i).getCreator(), expectedResult.get(i).getCreator()); Assert.assertEquals(result.getData().get(i).getModifier(), expectedResult.get(i).getModifier()); if (expectedResult.get(i).getDeleteFlag() == 0){ Assert.assertEquals(result.getData().get(i).isDeleteFlag(), false); }else if(expectedResult.get(i).getDeleteFlag() == 1){ Assert.assertEquals(result.getData().get(i).isDeleteFlag(), true); } Assert.assertEquals(result.getData().get(i).getId(), expectedResult.get(i).getId()); Assert.assertEquals(result.getData().get(i).getCategoryId(), expectedResult.get(i).getCategoryId()); Assert.assertEquals(result.getData().get(i).getSubCategoryId(), expectedResult.get(i).getSubCategoryId()); Assert.assertEquals(result.getData().get(i).getCompanyId(), expectedResult.get(i).getCompanyId()); Assert.assertEquals(result.getData().get(i).getTitle(), expectedResult.get(i).getTitle()); Assert.assertEquals(result.getData().get(i).getKeyword(), expectedResult.get(i).getKeyword()); Assert.assertEquals(result.getData().get(i).getPhoto(), expectedResult.get(i).getPhoto()); Assert.assertEquals(result.getData().get(i).getRecommendFlag(), expectedResult.get(i).getRecommendFlag()); Assert.assertEquals(result.getData().get(i).getBuildDate(), DateFormatChange.stringDateFormatChange(expectedResult.get(i).getBuildDate())); Assert.assertEquals(result.getData().get(i).getOriginAddr(), expectedResult.get(i).getOriginAddr()); Assert.assertEquals(result.getData().get(i).getBusinessModel(), expectedResult.get(i).getBusinessModel()); Assert.assertEquals(result.getData().get(i).getProduct(), expectedResult.get(i).getProduct()); Assert.assertEquals(result.getData().get(i).getCrowd(), expectedResult.get(i).getCrowd()); Assert.assertEquals(result.getData().get(i).getArea(), expectedResult.get(i).getArea()); Assert.assertEquals(result.getData().get(i).getSupport(), expectedResult.get(i).getSupport()); Assert.assertEquals(result.getData().get(i).getInvestMin(), expectedResult.get(i).getInvestMin()); Assert.assertEquals(result.getData().get(i).getInvestMax(), expectedResult.get(i).getInvestMax()); Assert.assertEquals(result.getData().get(i).getMargin(), expectedResult.get(i).getMargin()); Assert.assertEquals(result.getData().get(i).getFacilityCost(), expectedResult.get(i).getFacilityCost()); // if (expectedResult.get(i).getOtherCost() == null){ // Assert.assertEquals(result.getData().get(i).getOtherCost(),expectedResult.get(i).getOtherCost()); // } Assert.assertEquals(result.getData().get(i).getOtherCost(), expectedResult.get(i).getOtherCost()); Assert.assertEquals(result.getData().get(i).getDescription(), expectedResult.get(i).getDescription()); Assert.assertEquals(result.getData().get(i).getCompanyName(), expectedResult.get(i).getCompanyName()); Assert.assertEquals(result.getData().get(i).getRegisterTime(), expectedResult.get(i).getRegisterTime()); Assert.assertEquals(result.getData().get(i).getState(), expectedResult.get(i).getState()); Assert.assertEquals(result.getData().get(i).getStateName(), "上架中"); Assert.assertEquals(result.getData().get(i).getAttribute(), expectedResult.get(i).getAttribute()); Assert.assertEquals(result.getData().get(i).getAttributeName(), "推荐"); Assert.assertEquals(result.getData().get(i).getProjectExtra(), expectedResult.get(i).getProjectExtra()); Assert.assertEquals(result.getData().get(i).getProjectPhotos(), expectedResult.get(i).getProjectPhotos()); Assert.assertEquals(result.getData().get(i).getLikes(), expectedResult.get(i).getLikes()); } } } private SearchHomeJoinHeadlineResult getResponseResult() throws IOException { HttpGet get = new HttpGet(TestConfig.preferenceRecommendUrl); System.out.println("查询优选推荐Url get:" + get); HttpResponse response = TestConfig.defaultHttpClient.execute(get); String result = EntityUtils.toString(response.getEntity()); SearchHomeJoinHeadlineResult resultClass = new Gson().fromJson(result,SearchHomeJoinHeadlineResult.class); return resultClass; } }
7,158
0.682078
0.681506
109
63.091743
43.678883
155
false
false
0
0
0
0
0
0
1.06422
false
false
3
1f2a64de3755796f20093ee1ed1f6f39b2d71a3c
2,740,189,178,111
0f77c5ec508d6e8b558f726980067d1058e350d7
/1_39_120042/com/ankamagames/wakfu/common/game/dungeon/AbstractDungeonLadder.java
4d4051a9fe344590f1245ce13f90cfb68d804855
[]
no_license
nightwolf93/Wakxy-Core-Decompiled
https://github.com/nightwolf93/Wakxy-Core-Decompiled
aa589ebb92197bf48e6576026648956f93b8bf7f
2967f8f8fba89018f63b36e3978fc62908aa4d4d
refs/heads/master
2016-09-05T11:07:45.145000
2014-12-30T16:21:30
2014-12-30T16:21:30
29,250,176
5
5
null
true
2015-01-14T15:17:02
2015-01-14T15:17:02
2015-01-14T15:16:54
2014-12-30T16:28:28
9,832
0
0
0
null
null
null
package com.ankamagames.wakfu.common.game.dungeon; import org.apache.log4j.*; import com.ankamagames.framework.kernel.core.common.collections.*; import java.util.*; import java.nio.*; public abstract class AbstractDungeonLadder { protected static Logger m_logger; protected final DungeonLadderDefinition m_definition; protected final SortedList<DungeonLadderResult> m_results; private final ArrayList<DungeonLadderEventListener> m_eventListeners; public AbstractDungeonLadder(final DungeonLadderDefinition definition) { super(); this.m_definition = definition; this.m_results = new SortedList<DungeonLadderResult>(this.m_definition.getLadderType().getResultComparator()); this.m_eventListeners = new ArrayList<DungeonLadderEventListener>(); } public short getInstanceId() { return this.m_definition.getInstanceId(); } public ArrayList<DungeonLadderResult> getResults() { return this.m_results; } public DungeonLadderDefinition getDefinition() { return this.m_definition; } public int insertResult(final DungeonLadderResult result) { this.m_results.add(result); this.fireLadderChanged(); return this.m_results.indexOf(result); } protected void removeLastResult() { this.m_results.remove(this.m_results.getLast()); } public void removeResult(final long resultUid) { DungeonLadderResult resultToRemove = null; for (int i = 0, size = this.m_results.size(); i < size; ++i) { final DungeonLadderResult result = this.m_results.get(i); if (result.getUid() == resultUid) { resultToRemove = result; break; } } this.m_results.remove(resultToRemove); this.fireLadderChanged(); } public int getEstimatedPositionInLadder(final DungeonLadderResult result) { this.m_results.add(result); final int position = this.m_results.indexOf(result); this.m_results.remove(result); return position; } public void reset() { this.m_results.clear(); this.fireLadderReset(); } protected void fireLadderChanged() { for (int i = 0, size = this.m_eventListeners.size(); i < size; ++i) { this.m_eventListeners.get(i).onLadderChanged(this); } } protected void fireLadderReset() { for (int i = 0, size = this.m_eventListeners.size(); i < size; ++i) { this.m_eventListeners.get(i).onLadderReset(this); } } public void addEventListener(final DungeonLadderEventListener listener) { if (!this.m_eventListeners.contains(listener)) { this.m_eventListeners.add(listener); } } public DungeonLadderResult getFirstResult() { return this.m_results.get(0); } public void serialize(final ByteBuffer buffer) { buffer.putShort(this.m_definition.getInstanceId()); buffer.putShort((short)this.m_results.size()); for (int i = 0; i < this.m_results.size(); ++i) { this.m_results.get(i).serialize(buffer); } } public void unserializeResults(final ByteBuffer buffer) { final short resultsCount = buffer.getShort(); for (int i = 0; i < resultsCount; ++i) { final DungeonLadderResult result = DungeonLadderResult.fromBuild(buffer); this.insertResult(result); } } public int serializedSize() { int resultsSize = 0; for (int i = 0; i < this.m_results.size(); ++i) { final DungeonLadderResult dungeonLadderResult = this.m_results.get(i); resultsSize += dungeonLadderResult.serializedSize(); } return 4 + resultsSize; } @Override public String toString() { final StringBuffer sb = new StringBuffer(); sb.append("DungeonLadder(instanceId=").append(this.m_definition.getInstanceId()).append(", ladderType=").append(this.m_definition.getLadderType().name()).append(", resultCount=").append(this.m_results.size()).append(")"); return sb.toString(); } static { AbstractDungeonLadder.m_logger = Logger.getLogger((Class)AbstractDungeonLadder.class); } }
UTF-8
Java
4,355
java
AbstractDungeonLadder.java
Java
[]
null
[]
package com.ankamagames.wakfu.common.game.dungeon; import org.apache.log4j.*; import com.ankamagames.framework.kernel.core.common.collections.*; import java.util.*; import java.nio.*; public abstract class AbstractDungeonLadder { protected static Logger m_logger; protected final DungeonLadderDefinition m_definition; protected final SortedList<DungeonLadderResult> m_results; private final ArrayList<DungeonLadderEventListener> m_eventListeners; public AbstractDungeonLadder(final DungeonLadderDefinition definition) { super(); this.m_definition = definition; this.m_results = new SortedList<DungeonLadderResult>(this.m_definition.getLadderType().getResultComparator()); this.m_eventListeners = new ArrayList<DungeonLadderEventListener>(); } public short getInstanceId() { return this.m_definition.getInstanceId(); } public ArrayList<DungeonLadderResult> getResults() { return this.m_results; } public DungeonLadderDefinition getDefinition() { return this.m_definition; } public int insertResult(final DungeonLadderResult result) { this.m_results.add(result); this.fireLadderChanged(); return this.m_results.indexOf(result); } protected void removeLastResult() { this.m_results.remove(this.m_results.getLast()); } public void removeResult(final long resultUid) { DungeonLadderResult resultToRemove = null; for (int i = 0, size = this.m_results.size(); i < size; ++i) { final DungeonLadderResult result = this.m_results.get(i); if (result.getUid() == resultUid) { resultToRemove = result; break; } } this.m_results.remove(resultToRemove); this.fireLadderChanged(); } public int getEstimatedPositionInLadder(final DungeonLadderResult result) { this.m_results.add(result); final int position = this.m_results.indexOf(result); this.m_results.remove(result); return position; } public void reset() { this.m_results.clear(); this.fireLadderReset(); } protected void fireLadderChanged() { for (int i = 0, size = this.m_eventListeners.size(); i < size; ++i) { this.m_eventListeners.get(i).onLadderChanged(this); } } protected void fireLadderReset() { for (int i = 0, size = this.m_eventListeners.size(); i < size; ++i) { this.m_eventListeners.get(i).onLadderReset(this); } } public void addEventListener(final DungeonLadderEventListener listener) { if (!this.m_eventListeners.contains(listener)) { this.m_eventListeners.add(listener); } } public DungeonLadderResult getFirstResult() { return this.m_results.get(0); } public void serialize(final ByteBuffer buffer) { buffer.putShort(this.m_definition.getInstanceId()); buffer.putShort((short)this.m_results.size()); for (int i = 0; i < this.m_results.size(); ++i) { this.m_results.get(i).serialize(buffer); } } public void unserializeResults(final ByteBuffer buffer) { final short resultsCount = buffer.getShort(); for (int i = 0; i < resultsCount; ++i) { final DungeonLadderResult result = DungeonLadderResult.fromBuild(buffer); this.insertResult(result); } } public int serializedSize() { int resultsSize = 0; for (int i = 0; i < this.m_results.size(); ++i) { final DungeonLadderResult dungeonLadderResult = this.m_results.get(i); resultsSize += dungeonLadderResult.serializedSize(); } return 4 + resultsSize; } @Override public String toString() { final StringBuffer sb = new StringBuffer(); sb.append("DungeonLadder(instanceId=").append(this.m_definition.getInstanceId()).append(", ladderType=").append(this.m_definition.getLadderType().name()).append(", resultCount=").append(this.m_results.size()).append(")"); return sb.toString(); } static { AbstractDungeonLadder.m_logger = Logger.getLogger((Class)AbstractDungeonLadder.class); } }
4,355
0.632836
0.63054
126
33.563492
31.648741
229
false
false
0
0
0
0
0
0
0.531746
false
false
3
834aa34c686462aeb29af65f9be9087d748732e3
38,276,748,544,780
d789ee47f30de3ff71c89cceded6ed125bdfb583
/map/test_practice/src/sample/TComparator.java
b359bc593394abe069e77d4fcfdb3e45b00b8b8f
[]
no_license
qtov/an2sem1-cs.ubb
https://github.com/qtov/an2sem1-cs.ubb
6fbe13d5a2f59a2b350a94bbe90c878e87f8f180
da4c78d41ddcadad2b85c592bd51ae3d717a9bfc
refs/heads/master
2021-09-07T19:54:29.973000
2018-02-28T06:19:56
2018-02-28T06:19:56
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package sample; import java.util.Comparator; public class TComparator implements Comparator<Task> { @Override public int compare(Task a, Task b) { int c; c = a.getUser().compareTo(b.getUser()); if (c == 0) { c = a.getStatus().compareTo(b.getStatus()); } return -c; } }
UTF-8
Java
338
java
TComparator.java
Java
[]
null
[]
package sample; import java.util.Comparator; public class TComparator implements Comparator<Task> { @Override public int compare(Task a, Task b) { int c; c = a.getUser().compareTo(b.getUser()); if (c == 0) { c = a.getStatus().compareTo(b.getStatus()); } return -c; } }
338
0.556213
0.553254
18
17.777779
18.718842
55
false
false
0
0
0
0
0
0
0.388889
false
false
3
626c088fb0cd4e663ace439bb2ca9ae80c7a7e58
18,622,978,239,764
91dcc329132c9da596c0ca87173e4d2097fca694
/src/test/java/de/dfki/mlt/rudimant/compiler/tree/FragmentTest.java
12d94224fb2270b6d46d4244d7648dd5c8fd5b77
[]
no_license
bkiefer/vonda
https://github.com/bkiefer/vonda
5cccdf92cd81ce2e2366f370d116d2c53b5db8fb
6ea4d0105f9c1f158ac4897a0acc4049f4ff6a07
refs/heads/master
2023-09-01T11:31:09.013000
2023-08-28T16:57:21
2023-08-29T15:57:08
114,249,263
12
4
null
false
2023-07-19T08:44:45
2017-12-14T12:42:03
2023-04-28T00:12:04
2023-07-19T08:36:24
44,120
7
3
1
Java
false
false
/* * The Creative Commons CC-BY-NC 4.0 License * * http://creativecommons.org/licenses/by-nc/4.0/legalcode * * Creative Commons (CC) by DFKI GmbH * - Bernd Kiefer <kiefer@dfki.de> * - Anna Welker <anna.welker@dfki.de> * - Christophe Biwer <christophe.biwer@dfki.de> * * 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 de.dfki.mlt.rudimant.compiler.tree; import static de.dfki.mlt.rudimant.compiler.Visualize.*; import static de.dfki.mlt.rudimant.compiler.tree.TestUtilities.*; import static org.junit.Assert.*; import org.junit.BeforeClass; import org.junit.Test; import de.dfki.mlt.rudimant.compiler.TypeException; import de.dfki.mlt.rudimant.compiler.tree.ExpConditional; import de.dfki.mlt.rudimant.compiler.tree.RudiTree; public class FragmentTest { @BeforeClass public static void setUpClass() { setUpNonEmpty(); } @Test public void test1() { String conditionalExp = "int i = true ? 1 : 2;"; RudiTree dtr = getNodeOfInterest(parseAndTypecheck(conditionalExp)); assertTrue(dtr instanceof StatVarDef); dtr = ((StatVarDef)dtr).toAssign; assertTrue(dtr instanceof ExpAssignment); dtr = ((ExpAssignment)dtr).right; assertTrue(dtr instanceof ExpConditional); String type_boolean = ((ExpConditional) dtr).boolexp.getType().toJava(); assertEquals("boolean part of conditional", "boolean", type_boolean); String type_then = ((ExpConditional) dtr).thenexp.getType().toJava(); assertEquals("then part", "int", type_then); String type_else = ((ExpConditional) dtr).elseexp.getType().toJava(); assertEquals("else part", "int", type_else); } @Test public void testFinal1() { String fin = "final boolean b = true;"; String s = generate(fin); String expected = "final boolean b = true;"; assertEquals(expected, getForMarked(s, expected)); } @Test public void testFinal2() { String fin = "final b = true;"; String s = generate(fin); String expected = "final boolean b = true;"; assertEquals(expected, getForMarked(s, expected)); } // TODO: do we really need to check this? /* @Test(expected=TypeException.class) public void testFinal3() throws Throwable { String fin = "final boolean b = true; b = false;"; getTypeError(fin); }*/ @Test public void testFunctionCall() throws Throwable { String in = "p = myLastDA().getProposition();"; String s = generate(in); String expected = "String p = myLastDA().getProposition();"; assertEquals(expected, getForMarked(s, expected)); } }
UTF-8
Java
2,988
java
FragmentTest.java
Java
[ { "context": "ode\n *\n * Creative Commons (CC) by DFKI GmbH\n * - Bernd Kiefer <kiefer@dfki.de>\n * - Anna Welker <anna.welker@d", "end": 169, "score": 0.9998884201049805, "start": 157, "tag": "NAME", "value": "Bernd Kiefer" }, { "context": "ive Commons (CC) by DFKI GmbH\n * - Bernd Kiefer <kiefer@dfki.de>\n * - Anna Welker <anna.welker@dfki.de>\n * - Ch", "end": 185, "score": 0.9999205470085144, "start": 171, "tag": "EMAIL", "value": "kiefer@dfki.de" }, { "context": "FKI GmbH\n * - Bernd Kiefer <kiefer@dfki.de>\n * - Anna Welker <anna.welker@dfki.de>\n * - Christophe Biwer <chr", "end": 204, "score": 0.9998818635940552, "start": 193, "tag": "NAME", "value": "Anna Welker" }, { "context": " Bernd Kiefer <kiefer@dfki.de>\n * - Anna Welker <anna.welker@dfki.de>\n * - Christophe Biwer <christophe.biwer@dfki.de", "end": 225, "score": 0.9999272227287292, "start": 206, "tag": "EMAIL", "value": "anna.welker@dfki.de" }, { "context": ".de>\n * - Anna Welker <anna.welker@dfki.de>\n * - Christophe Biwer <christophe.biwer@dfki.de>\n *\n * THE SOFTWARE IS ", "end": 249, "score": 0.999879002571106, "start": 233, "tag": "NAME", "value": "Christophe Biwer" }, { "context": "ker <anna.welker@dfki.de>\n * - Christophe Biwer <christophe.biwer@dfki.de>\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT ", "end": 275, "score": 0.9999301433563232, "start": 251, "tag": "EMAIL", "value": "christophe.biwer@dfki.de" } ]
null
[]
/* * The Creative Commons CC-BY-NC 4.0 License * * http://creativecommons.org/licenses/by-nc/4.0/legalcode * * Creative Commons (CC) by DFKI GmbH * - <NAME> <<EMAIL>> * - <NAME> <<EMAIL>> * - <NAME> <<EMAIL>> * * 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 de.dfki.mlt.rudimant.compiler.tree; import static de.dfki.mlt.rudimant.compiler.Visualize.*; import static de.dfki.mlt.rudimant.compiler.tree.TestUtilities.*; import static org.junit.Assert.*; import org.junit.BeforeClass; import org.junit.Test; import de.dfki.mlt.rudimant.compiler.TypeException; import de.dfki.mlt.rudimant.compiler.tree.ExpConditional; import de.dfki.mlt.rudimant.compiler.tree.RudiTree; public class FragmentTest { @BeforeClass public static void setUpClass() { setUpNonEmpty(); } @Test public void test1() { String conditionalExp = "int i = true ? 1 : 2;"; RudiTree dtr = getNodeOfInterest(parseAndTypecheck(conditionalExp)); assertTrue(dtr instanceof StatVarDef); dtr = ((StatVarDef)dtr).toAssign; assertTrue(dtr instanceof ExpAssignment); dtr = ((ExpAssignment)dtr).right; assertTrue(dtr instanceof ExpConditional); String type_boolean = ((ExpConditional) dtr).boolexp.getType().toJava(); assertEquals("boolean part of conditional", "boolean", type_boolean); String type_then = ((ExpConditional) dtr).thenexp.getType().toJava(); assertEquals("then part", "int", type_then); String type_else = ((ExpConditional) dtr).elseexp.getType().toJava(); assertEquals("else part", "int", type_else); } @Test public void testFinal1() { String fin = "final boolean b = true;"; String s = generate(fin); String expected = "final boolean b = true;"; assertEquals(expected, getForMarked(s, expected)); } @Test public void testFinal2() { String fin = "final b = true;"; String s = generate(fin); String expected = "final boolean b = true;"; assertEquals(expected, getForMarked(s, expected)); } // TODO: do we really need to check this? /* @Test(expected=TypeException.class) public void testFinal3() throws Throwable { String fin = "final boolean b = true; b = false;"; getTypeError(fin); }*/ @Test public void testFunctionCall() throws Throwable { String in = "p = myLastDA().getProposition();"; String s = generate(in); String expected = "String p = myLastDA().getProposition();"; assertEquals(expected, getForMarked(s, expected)); } }
2,931
0.703146
0.699799
92
31.47826
25.638149
79
false
false
0
0
0
0
0
0
0.728261
false
false
0
994adb67431c6424c28a2ae272aa214566c763b9
5,514,738,024,289
1806c8a1d9c9f12cb7801725867e5fb5a03ce212
/seata-order-service2001/src/main/java/com/atzy/springcloud/service/AccountService.java
98b20f5c0dbcd6a395b264e41fc690b4de86074b
[]
no_license
1243303478/springcloud2020
https://github.com/1243303478/springcloud2020
a19649e29a7d2dfc45ea5e7fd527b2dec35f713d
7fc065996c64ea46cc74ed0cf8f1c70f3400dcc7
refs/heads/master
2023-03-29T05:42:57.767000
2021-03-30T16:47:13
2021-03-30T16:47:13
334,857,122
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.atzy.springcloud.service; import com.atzy.springcloud.domain.CommonResult; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import java.math.BigDecimal; @FeignClient(value = "seata-account-service") public interface AccountService { /** * 减少对应用户余额 (money 增减余额) * @param userId * @param money */ @PostMapping("/account/change") public CommonResult<Object> changeUserAccount(@RequestParam("userId") long userId, @RequestParam("money") BigDecimal money); }
UTF-8
Java
702
java
AccountService.java
Java
[]
null
[]
package com.atzy.springcloud.service; import com.atzy.springcloud.domain.CommonResult; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import java.math.BigDecimal; @FeignClient(value = "seata-account-service") public interface AccountService { /** * 减少对应用户余额 (money 增减余额) * @param userId * @param money */ @PostMapping("/account/change") public CommonResult<Object> changeUserAccount(@RequestParam("userId") long userId, @RequestParam("money") BigDecimal money); }
702
0.769912
0.769912
20
32.900002
29.652824
128
false
false
0
0
0
0
0
0
0.45
false
false
0
2d919bb95b5ce37dcfbc58ddf6bea6b093815211
5,514,738,022,307
b56a4a115b24c95877d7b11a84f4292df0bfc10b
/CodeRacing/local-runner/decompile/org/slf4j/impl/Log4jLoggerFactory.java
64974d6c589e51b15c9762b7143f0774a866ffd6
[ "Apache-2.0" ]
permissive
tyamgin/AiCup
https://github.com/tyamgin/AiCup
fd020f8b74b37b97c3a91b67ba1781585e0dcb56
5a7a7ec15d99da52b1c7a7de77f6a7ca22356903
refs/heads/master
2020-03-30T06:00:59.997000
2020-01-16T09:10:57
2020-01-16T09:10:57
15,261,033
16
8
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.slf4j.impl; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.apache.log4j.LogManager; import org.slf4j.ILoggerFactory; public class Log4jLoggerFactory implements ILoggerFactory { ConcurrentMap loggerMap = new ConcurrentHashMap(); public org.slf4j.Logger getLogger(String paramString) { org.slf4j.Logger localLogger1 = (org.slf4j.Logger)this.loggerMap.get(paramString); if (localLogger1 != null) { return localLogger1; } org.apache.log4j.Logger localLogger; if (paramString.equalsIgnoreCase("ROOT")) { localLogger = LogManager.getRootLogger(); } else { localLogger = LogManager.getLogger(paramString); } Log4jLoggerAdapter localLog4jLoggerAdapter = new Log4jLoggerAdapter(localLogger); org.slf4j.Logger localLogger2 = (org.slf4j.Logger)this.loggerMap.putIfAbsent(paramString, localLog4jLoggerAdapter); return localLogger2 == null ? localLog4jLoggerAdapter : localLogger2; } } /* Location: D:\Projects\AiCup\CodeRacing\local-runner\local-runner.jar!\org\slf4j\impl\Log4jLoggerFactory.class * Java compiler version: 5 (49.0) * JD-Core Version: 0.7.1 */
UTF-8
Java
1,210
java
Log4jLoggerFactory.java
Java
[]
null
[]
package org.slf4j.impl; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.apache.log4j.LogManager; import org.slf4j.ILoggerFactory; public class Log4jLoggerFactory implements ILoggerFactory { ConcurrentMap loggerMap = new ConcurrentHashMap(); public org.slf4j.Logger getLogger(String paramString) { org.slf4j.Logger localLogger1 = (org.slf4j.Logger)this.loggerMap.get(paramString); if (localLogger1 != null) { return localLogger1; } org.apache.log4j.Logger localLogger; if (paramString.equalsIgnoreCase("ROOT")) { localLogger = LogManager.getRootLogger(); } else { localLogger = LogManager.getLogger(paramString); } Log4jLoggerAdapter localLog4jLoggerAdapter = new Log4jLoggerAdapter(localLogger); org.slf4j.Logger localLogger2 = (org.slf4j.Logger)this.loggerMap.putIfAbsent(paramString, localLog4jLoggerAdapter); return localLogger2 == null ? localLog4jLoggerAdapter : localLogger2; } } /* Location: D:\Projects\AiCup\CodeRacing\local-runner\local-runner.jar!\org\slf4j\impl\Log4jLoggerFactory.class * Java compiler version: 5 (49.0) * JD-Core Version: 0.7.1 */
1,210
0.744628
0.719835
35
33.599998
32.6078
125
false
false
0
0
0
0
0
0
0.428571
false
false
0
26da1bef3b463b8aedba30800b03c637760b9328
17,729,625,045,548
447520f40e82a060368a0802a391697bc00be96f
/apks/test_apks/insecurebank/source/com/google/android/gms/common/internal/DowngradeableSafeParcel.java
5b4799a4bb9d382ebc0393c5008486bc12bbf830
[ "Apache-2.0" ]
permissive
iantal/AndroidPermissions
https://github.com/iantal/AndroidPermissions
7f3343a9c29d82dbcd4ecd98b3a50ddf8d179465
d623b732734243590b5f004d167e542e2e2ae249
refs/heads/master
2023-07-19T01:29:26.689000
2019-09-30T19:01:42
2019-09-30T19:01:42
107,239,248
0
0
Apache-2.0
false
2023-07-16T07:41:38
2017-10-17T08:22:57
2019-09-30T19:01:44
2023-07-16T07:41:38
1,616,319
0
0
1
null
false
false
package com.google.android.gms.common.internal; import com.google.android.gms.common.internal.safeparcel.SafeParcelable; import java.lang.reflect.Field; public abstract class DowngradeableSafeParcel implements SafeParcelable { private static final Object zzZZ = new Object(); private static ClassLoader zzaaa = null; private static Integer zzaab = null; private boolean zzaac = false; public DowngradeableSafeParcel() {} private static boolean zza(Class<?> paramClass) { try { boolean bool = "SAFE_PARCELABLE_NULL_STRING".equals(paramClass.getField("NULL").get(null)); return bool; } catch (IllegalAccessException paramClass) { return false; } catch (NoSuchFieldException paramClass) {} return false; } protected static boolean zzca(String paramString) { ClassLoader localClassLoader = zznD(); if (localClassLoader == null) { return true; } try { boolean bool = zza(localClassLoader.loadClass(paramString)); return bool; } catch (Exception paramString) {} return false; } protected static ClassLoader zznD() { synchronized (zzZZ) { ClassLoader localClassLoader = zzaaa; return localClassLoader; } } protected static Integer zznE() { synchronized (zzZZ) { Integer localInteger = zzaab; return localInteger; } } protected boolean zznF() { return this.zzaac; } }
UTF-8
Java
1,474
java
DowngradeableSafeParcel.java
Java
[]
null
[]
package com.google.android.gms.common.internal; import com.google.android.gms.common.internal.safeparcel.SafeParcelable; import java.lang.reflect.Field; public abstract class DowngradeableSafeParcel implements SafeParcelable { private static final Object zzZZ = new Object(); private static ClassLoader zzaaa = null; private static Integer zzaab = null; private boolean zzaac = false; public DowngradeableSafeParcel() {} private static boolean zza(Class<?> paramClass) { try { boolean bool = "SAFE_PARCELABLE_NULL_STRING".equals(paramClass.getField("NULL").get(null)); return bool; } catch (IllegalAccessException paramClass) { return false; } catch (NoSuchFieldException paramClass) {} return false; } protected static boolean zzca(String paramString) { ClassLoader localClassLoader = zznD(); if (localClassLoader == null) { return true; } try { boolean bool = zza(localClassLoader.loadClass(paramString)); return bool; } catch (Exception paramString) {} return false; } protected static ClassLoader zznD() { synchronized (zzZZ) { ClassLoader localClassLoader = zzaaa; return localClassLoader; } } protected static Integer zznE() { synchronized (zzZZ) { Integer localInteger = zzaab; return localInteger; } } protected boolean zznF() { return this.zzaac; } }
1,474
0.668928
0.668928
68
20.67647
20.671408
97
false
false
0
0
0
0
0
0
0.308824
false
false
0
f89825a916c96646105ae5abcc068be9c36fe8b2
20,272,245,697,597
fd0143ee2cd39bdc0ea4615c7e5fd4e7055312eb
/src/com/github/serivesmejia/eocvsim/gui/util/GuiUtil.java
59862455e43b4503da027681d354ffe5f48e35bc
[ "MIT" ]
permissive
BenCaunt/EOCV-Sim
https://github.com/BenCaunt/EOCV-Sim
3cc34e58ffe5e83db09d60ae188dd84942ea63e3
b7595267295bbeed8fa765219b8d7df056015165
refs/heads/master
2023-01-06T21:41:47.739000
2020-10-29T08:14:05
2020-10-29T08:14:05
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.github.serivesmejia.eocvsim.gui.util; import javax.imageio.ImageIO; import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.AbstractDocument; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.DocumentFilter; import java.awt.*; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; public class GuiUtil { public static void jTextFieldOnlyNumbers(JTextField field, int minNumber, int onMinNumberChangeTo) { ((AbstractDocument)field.getDocument()).setDocumentFilter(new DocumentFilter(){ Pattern regEx = Pattern.compile("\\d*"); @Override public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException { Matcher matcher = regEx.matcher(text); if(!matcher.matches()){ return; } if(field.getText().length() == 0) { try { int number = Integer.parseInt(text); if (number <= minNumber) { text = String.valueOf(onMinNumberChangeTo); } } catch (NumberFormatException ex) { } } super.replace(fb, offset, length, text, attrs); } }); } public static ImageIcon scaleImage(ImageIcon icon, int w, int h) { int nw = icon.getIconWidth(); int nh = icon.getIconHeight(); if(icon.getIconWidth() > w) { nw = w; nh = (nw * icon.getIconHeight()) / icon.getIconWidth(); } if(nh > h) { nh = h; nw = (icon.getIconWidth() * nh) / icon.getIconHeight(); } return new ImageIcon(icon.getImage().getScaledInstance(nw, nh, Image.SCALE_DEFAULT)); } public static ImageIcon loadImageIcon(String path) throws IOException { return new ImageIcon(ImageIO.read(GuiUtil.class.getResourceAsStream(path))); } }
UTF-8
Java
2,197
java
GuiUtil.java
Java
[ { "context": "package com.github.serivesmejia.eocvsim.gui.util;\n\nimport javax.imageio.ImageIO;\n", "end": 31, "score": 0.9994227290153503, "start": 19, "tag": "USERNAME", "value": "serivesmejia" } ]
null
[]
package com.github.serivesmejia.eocvsim.gui.util; import javax.imageio.ImageIO; import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.AbstractDocument; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.DocumentFilter; import java.awt.*; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; public class GuiUtil { public static void jTextFieldOnlyNumbers(JTextField field, int minNumber, int onMinNumberChangeTo) { ((AbstractDocument)field.getDocument()).setDocumentFilter(new DocumentFilter(){ Pattern regEx = Pattern.compile("\\d*"); @Override public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException { Matcher matcher = regEx.matcher(text); if(!matcher.matches()){ return; } if(field.getText().length() == 0) { try { int number = Integer.parseInt(text); if (number <= minNumber) { text = String.valueOf(onMinNumberChangeTo); } } catch (NumberFormatException ex) { } } super.replace(fb, offset, length, text, attrs); } }); } public static ImageIcon scaleImage(ImageIcon icon, int w, int h) { int nw = icon.getIconWidth(); int nh = icon.getIconHeight(); if(icon.getIconWidth() > w) { nw = w; nh = (nw * icon.getIconHeight()) / icon.getIconWidth(); } if(nh > h) { nh = h; nw = (icon.getIconWidth() * nh) / icon.getIconHeight(); } return new ImageIcon(icon.getImage().getScaledInstance(nw, nh, Image.SCALE_DEFAULT)); } public static ImageIcon loadImageIcon(String path) throws IOException { return new ImageIcon(ImageIO.read(GuiUtil.class.getResourceAsStream(path))); } }
2,197
0.593081
0.592626
71
29.943663
29.61865
135
false
false
0
0
0
0
0
0
0.591549
false
false
0
c6b86bab16bb3fbf6a4b7017a2d1335dc537feee
19,344,532,705,345
7f857b5c11b069f899b08cb6a960c45bf299d6b4
/alumni_server-master/src/main/java/cn/edu/seu/alumni_server/controller/dto/FavoriteDTO.java
b2084fa92ee40ab7eb64b16f631a9fecf24c7339
[ "Apache-2.0" ]
permissive
Jamesbing-wu/ly_schoolhelper
https://github.com/Jamesbing-wu/ly_schoolhelper
ee47477a090ae5b66d258f47a7277785a1400caf
0605ceabfb545520c2a84371298d5710947a44ec
refs/heads/master
2022-11-30T19:38:01.592000
2020-05-07T12:58:23
2020-05-07T12:58:23
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.edu.seu.alumni_server.controller.dto; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; @Data @AllArgsConstructor @NoArgsConstructor public class FavoriteDTO { private Long accountId; private Long favoriteAccountId; private Integer status; private String avatar; private String name; private String city; private String school; private String college; private String startTime; private String company; private String position; public void setStartTime(final String startTime){ SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy"); this.startTime = dateFormat.format(new Date(Long.parseLong(startTime))); } }
UTF-8
Java
872
java
FavoriteDTO.java
Java
[]
null
[]
package cn.edu.seu.alumni_server.controller.dto; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; @Data @AllArgsConstructor @NoArgsConstructor public class FavoriteDTO { private Long accountId; private Long favoriteAccountId; private Integer status; private String avatar; private String name; private String city; private String school; private String college; private String startTime; private String company; private String position; public void setStartTime(final String startTime){ SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy"); this.startTime = dateFormat.format(new Date(Long.parseLong(startTime))); } }
872
0.760321
0.760321
33
25.424242
18.864799
80
false
false
0
0
0
0
0
0
0.636364
false
false
0
6ed1f924b4992b59f750500b9e016c324d261334
25,786,983,711,434
a3a60ca4a8ba9e4d661d18f696ebe48bd1018a6d
/app/src/main/java/com/sudipasarkar/kisanseva/manageotp.java
020593198f3ca8572f1a24996978539a01790b04
[]
no_license
Sudipa-Sarkar/Farmers_desk
https://github.com/Sudipa-Sarkar/Farmers_desk
b499a3fd1bcdeac15a3e1865c575ce56291f78d9
69ce0999940981c335f349f5e39d97b925ea3046
refs/heads/master
2023-06-23T18:51:19.667000
2021-07-23T09:17:35
2021-07-23T09:17:35
388,743,709
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sudipasarkar.kisanseva; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.FirebaseException; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.PhoneAuthCredential; import com.google.firebase.auth.PhoneAuthProvider; import java.util.concurrent.TimeUnit; public class manageotp extends AppCompatActivity { EditText otp; Button verify; String phonenumber; FirebaseAuth mAuth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_manageotp); phonenumber=getIntent().getStringExtra("mobile").toString(); otp=(EditText)findViewById(R.id.otp); verify=(Button)findViewById(R.id.verify); mAuth=FirebaseAuth.getInstance(); initiateotp(); } private void initiateotp() { PhoneAuthProvider.getInstance().verifyPhoneNumber( phonenumber, 60, TimeUnit.SECONDS, this, new PhoneAuthProvider.OnVerificationStateChangedCallbacks() { @Override public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) { signInWithPhoneAuthCredential(phoneAuthCredential); } @Override public void onVerificationFailed(FirebaseException e) { Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show(); } @Override public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) { super.onCodeSent(s, forceResendingToken); } }); } private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) { mAuth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { startActivity(new Intent(manageotp.this,MainActivity.class)); } else { Toast.makeText(getApplicationContext(),"Code Error",Toast.LENGTH_LONG).show(); } } }); } }
UTF-8
Java
3,002
java
manageotp.java
Java
[]
null
[]
package com.sudipasarkar.kisanseva; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.FirebaseException; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.PhoneAuthCredential; import com.google.firebase.auth.PhoneAuthProvider; import java.util.concurrent.TimeUnit; public class manageotp extends AppCompatActivity { EditText otp; Button verify; String phonenumber; FirebaseAuth mAuth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_manageotp); phonenumber=getIntent().getStringExtra("mobile").toString(); otp=(EditText)findViewById(R.id.otp); verify=(Button)findViewById(R.id.verify); mAuth=FirebaseAuth.getInstance(); initiateotp(); } private void initiateotp() { PhoneAuthProvider.getInstance().verifyPhoneNumber( phonenumber, 60, TimeUnit.SECONDS, this, new PhoneAuthProvider.OnVerificationStateChangedCallbacks() { @Override public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) { signInWithPhoneAuthCredential(phoneAuthCredential); } @Override public void onVerificationFailed(FirebaseException e) { Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show(); } @Override public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) { super.onCodeSent(s, forceResendingToken); } }); } private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) { mAuth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { startActivity(new Intent(manageotp.this,MainActivity.class)); } else { Toast.makeText(getApplicationContext(),"Code Error",Toast.LENGTH_LONG).show(); } } }); } }
3,002
0.637575
0.636909
82
35.621952
27.756626
113
false
false
0
0
0
0
0
0
0.597561
false
false
0
36291901e71bf83dc6c5caaf6651415cdba71d68
13,211,319,450,910
69d34af382ca52f7fbca523a3e3a79e4f02d43b8
/app/src/main/java/com/felipe/palma/desafioitbam/adapter/ProductAdapter.java
480cde0c39e1cc3312d6b6e6f8fa62d603645376
[]
no_license
felipepalma14/desafio-itbam
https://github.com/felipepalma14/desafio-itbam
69857734850ae667f1c08294a426dbe8de1f82d8
fe14e518ef8a815e2485776f9f28d630ec4a26ef
refs/heads/master
2020-06-14T20:42:47.928000
2019-07-08T14:56:29
2019-07-08T14:56:29
195,120,496
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.felipe.palma.desafioitbam.adapter; import android.content.Context; import android.graphics.Paint; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Filter; import android.widget.Filterable; import android.widget.ImageView; import android.widget.TextView; import androidx.recyclerview.widget.RecyclerView; import com.felipe.palma.desafioitbam.R; import com.felipe.palma.desafioitbam.model.Product; import com.felipe.palma.desafioitbam.mvp.RecyclerItemClickListener; import com.makeramen.roundedimageview.RoundedTransformationBuilder; import com.mohan.ribbonview.RibbonView; import com.squareup.picasso.Picasso; import com.squareup.picasso.Transformation; import java.util.ArrayList; import java.util.List; /** * Created by Felipe Palma on 03/07/2019. */ public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ViewHolder> implements Filterable { private Context context; private List<Product> productList; private List<Product> productListFiltered; private RecyclerItemClickListener listener; class ViewHolder extends RecyclerView.ViewHolder { TextView productName, productPrice, productRegularPrice; ImageView productImage; RibbonView productDiscount; ViewHolder(View view) { super(view); productName = view.findViewById(R.id.product_name); productPrice = view.findViewById(R.id.product_price); productRegularPrice = view.findViewById(R.id.product_regular_price); productImage = view.findViewById(R.id.product_image); productDiscount = view.findViewById(R.id.product_ribbon_discount_percentage); view.setOnClickListener(view1 -> listener.onItemClick(productListFiltered.get(getAdapterPosition()))); } } public ProductAdapter(Context context, List<Product> productList, RecyclerItemClickListener listener) { this.context = context; this.listener = listener; this.productList = productList; this.productListFiltered = productList; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.item_product, parent, false); return new ViewHolder(itemView); } @Override public void onBindViewHolder(ViewHolder holder, final int position) { final Product product = productListFiltered.get(position); String productName = product.getName().substring(0,1) + product.getName().toLowerCase().substring(1,product.getName().length()); holder.productName.setText(productName); holder.productPrice.setText(product.getActualPrice()); if(!product.getDiscountPercentage().equals("") && product.getOnSale()) { holder.productRegularPrice.setText(product.getRegularPrice()); holder.productRegularPrice.setPaintFlags(holder.productRegularPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); holder.productDiscount.setText(product.getDiscountPercentage()); holder.productDiscount.setRibbonFillColor(context.getResources().getColor(R.color.txt_price_color)); }else{ if (!product.getOnSale()){ holder.productDiscount.setText("Sem Stock"); holder.productDiscount.setRibbonFillColor(context.getResources().getColor(R.color.grey)); }else { holder.productRegularPrice.setVisibility(View.INVISIBLE); holder.productDiscount.setVisibility(View.GONE); } } Transformation transformation = new RoundedTransformationBuilder() .cornerRadiusDp(20) .oval(false) .build(); if (product.getImage().isEmpty()) { //url.isEmpty() Picasso.with(context) .load(R.drawable.ic_no_image) .placeholder(R.drawable.ic_loading) .error(R.drawable.ic_no_image) .resize(200, 200) .centerCrop() .transform(transformation) .into(holder.productImage); }else{ Picasso.with(context) .load(product.getImage()) .placeholder(R.drawable.ic_loading) .error(R.drawable.ic_no_image) //.resize(200, 200) .centerInside() .fit() .transform(transformation) .into(holder.productImage); } } @Override public Filter getFilter() { return new Filter() { @Override protected FilterResults performFiltering(CharSequence charSequence) { String charString = charSequence.toString(); if (charString.isEmpty()) { productListFiltered = productList; } else { List<Product> filteredList = new ArrayList<>(); for (Product product : productList) { if (product.getName().toLowerCase().contains(charString.toLowerCase())) { filteredList.add(product); } } productListFiltered = filteredList; } FilterResults filterResults = new FilterResults(); filterResults.values = productListFiltered; return filterResults; } @Override protected void publishResults(CharSequence charSequence, FilterResults filterResults) { productListFiltered = (ArrayList<Product>) filterResults.values; notifyDataSetChanged(); } }; } @Override public int getItemCount() { return productListFiltered.size(); } }
UTF-8
Java
6,041
java
ProductAdapter.java
Java
[ { "context": "rayList;\nimport java.util.List;\n\n/**\n * Created by Felipe Palma on 03/07/2019.\n */\npublic class ProductAdapter e", "end": 842, "score": 0.9998884201049805, "start": 830, "tag": "NAME", "value": "Felipe Palma" } ]
null
[]
package com.felipe.palma.desafioitbam.adapter; import android.content.Context; import android.graphics.Paint; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Filter; import android.widget.Filterable; import android.widget.ImageView; import android.widget.TextView; import androidx.recyclerview.widget.RecyclerView; import com.felipe.palma.desafioitbam.R; import com.felipe.palma.desafioitbam.model.Product; import com.felipe.palma.desafioitbam.mvp.RecyclerItemClickListener; import com.makeramen.roundedimageview.RoundedTransformationBuilder; import com.mohan.ribbonview.RibbonView; import com.squareup.picasso.Picasso; import com.squareup.picasso.Transformation; import java.util.ArrayList; import java.util.List; /** * Created by <NAME> on 03/07/2019. */ public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ViewHolder> implements Filterable { private Context context; private List<Product> productList; private List<Product> productListFiltered; private RecyclerItemClickListener listener; class ViewHolder extends RecyclerView.ViewHolder { TextView productName, productPrice, productRegularPrice; ImageView productImage; RibbonView productDiscount; ViewHolder(View view) { super(view); productName = view.findViewById(R.id.product_name); productPrice = view.findViewById(R.id.product_price); productRegularPrice = view.findViewById(R.id.product_regular_price); productImage = view.findViewById(R.id.product_image); productDiscount = view.findViewById(R.id.product_ribbon_discount_percentage); view.setOnClickListener(view1 -> listener.onItemClick(productListFiltered.get(getAdapterPosition()))); } } public ProductAdapter(Context context, List<Product> productList, RecyclerItemClickListener listener) { this.context = context; this.listener = listener; this.productList = productList; this.productListFiltered = productList; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.item_product, parent, false); return new ViewHolder(itemView); } @Override public void onBindViewHolder(ViewHolder holder, final int position) { final Product product = productListFiltered.get(position); String productName = product.getName().substring(0,1) + product.getName().toLowerCase().substring(1,product.getName().length()); holder.productName.setText(productName); holder.productPrice.setText(product.getActualPrice()); if(!product.getDiscountPercentage().equals("") && product.getOnSale()) { holder.productRegularPrice.setText(product.getRegularPrice()); holder.productRegularPrice.setPaintFlags(holder.productRegularPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); holder.productDiscount.setText(product.getDiscountPercentage()); holder.productDiscount.setRibbonFillColor(context.getResources().getColor(R.color.txt_price_color)); }else{ if (!product.getOnSale()){ holder.productDiscount.setText("Sem Stock"); holder.productDiscount.setRibbonFillColor(context.getResources().getColor(R.color.grey)); }else { holder.productRegularPrice.setVisibility(View.INVISIBLE); holder.productDiscount.setVisibility(View.GONE); } } Transformation transformation = new RoundedTransformationBuilder() .cornerRadiusDp(20) .oval(false) .build(); if (product.getImage().isEmpty()) { //url.isEmpty() Picasso.with(context) .load(R.drawable.ic_no_image) .placeholder(R.drawable.ic_loading) .error(R.drawable.ic_no_image) .resize(200, 200) .centerCrop() .transform(transformation) .into(holder.productImage); }else{ Picasso.with(context) .load(product.getImage()) .placeholder(R.drawable.ic_loading) .error(R.drawable.ic_no_image) //.resize(200, 200) .centerInside() .fit() .transform(transformation) .into(holder.productImage); } } @Override public Filter getFilter() { return new Filter() { @Override protected FilterResults performFiltering(CharSequence charSequence) { String charString = charSequence.toString(); if (charString.isEmpty()) { productListFiltered = productList; } else { List<Product> filteredList = new ArrayList<>(); for (Product product : productList) { if (product.getName().toLowerCase().contains(charString.toLowerCase())) { filteredList.add(product); } } productListFiltered = filteredList; } FilterResults filterResults = new FilterResults(); filterResults.values = productListFiltered; return filterResults; } @Override protected void publishResults(CharSequence charSequence, FilterResults filterResults) { productListFiltered = (ArrayList<Product>) filterResults.values; notifyDataSetChanged(); } }; } @Override public int getItemCount() { return productListFiltered.size(); } }
6,035
0.631187
0.626883
170
34.529411
30.418875
136
false
false
0
0
0
0
0
0
0.482353
false
false
0
e8133e0eff0977cbf3086e17ac0a81879d7b4b86
31,018,253,858,074
0d9eed2aebe102c15a744e072b687e039241345b
/bhozidarest/src/main/java/com/bhozida/service/CostService.java
12ca861bcf09e5ead71c15813929545318dc6aae
[]
no_license
dkambarami/bhozida-spring-rest
https://github.com/dkambarami/bhozida-spring-rest
03329640444e4309ca014153ac3b65bd6858b721
6137cf68ab7c6d03f069a319073249c72ccf383b
refs/heads/master
2023-01-18T23:06:45.622000
2020-11-10T00:11:06
2020-11-10T00:11:06
262,121,862
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bhozida.service; import com.bhozida.model.Cost; public interface CostService extends JpaCrudService<Cost, Long> { }
UTF-8
Java
129
java
CostService.java
Java
[]
null
[]
package com.bhozida.service; import com.bhozida.model.Cost; public interface CostService extends JpaCrudService<Cost, Long> { }
129
0.806202
0.806202
6
20.666666
23.619671
65
false
false
0
0
0
0
0
0
0.5
false
false
0
1bbcf94c34b60389c1cf4868b8e65372794ccc5a
3,401,614,140,844
81888ddea5f5ef5aa9e06d123ef71b869550bf74
/src/main/java/com/tiandy/controller/HelloController.java
f6bd480e0b187fbae60031fa450da720c89f8005
[]
no_license
duanyuming1995/helloworld
https://github.com/duanyuming1995/helloworld
de979aa2f86ec122fe5051aad0455dc1b21cbcea
9e998c1f466babe871d2535e58a4b0a09e24d6b7
refs/heads/master
2020-04-28T17:13:48.310000
2019-03-13T14:34:22
2019-03-13T14:34:22
175,438,313
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tiandy.controller; import com.tiandy.pojo.Product; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import static javafx.scene.input.KeyCode.S; @Controller @RequestMapping(value = "/duan") public class HelloController { @RequestMapping(value = "/hello1") public String hello1(){ return "hello"; } @RequestMapping(value = "/hello2") @ResponseBody//请求对象时必备 public Product hello2(@RequestParam(value = "username",required = false,defaultValue = "段玉铭") String name){ Product product = new Product(); product.setId(111); product.setName(name); return product; } /** * restful * 以资源为导向 *http://localhost:8080/product.do/1 *http://localhost:8080/product.do/2 * 利于seo优化(网站排名) * * id=1 * http://localhost:8080/product.do?id=1 * http://localhost:8080/product.do?id=2 */ @RequestMapping(value = "/hello3/{prodeuctId}/{productName}")//可变参数通过{}定义 @ResponseBody public Product getProduct(@PathVariable(value = "prodeuctId") Integer id,@PathVariable String productName){ Product product = new Product(); product.setId(id); product.setName(productName); return product; } }
UTF-8
Java
1,366
java
HelloController.java
Java
[ { "context": "lue = \"username\",required = false,defaultValue = \"段玉铭\") String name){\n Product product = new Pro", "end": 547, "score": 0.9429569244384766, "start": 544, "tag": "NAME", "value": "段玉铭" } ]
null
[]
package com.tiandy.controller; import com.tiandy.pojo.Product; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import static javafx.scene.input.KeyCode.S; @Controller @RequestMapping(value = "/duan") public class HelloController { @RequestMapping(value = "/hello1") public String hello1(){ return "hello"; } @RequestMapping(value = "/hello2") @ResponseBody//请求对象时必备 public Product hello2(@RequestParam(value = "username",required = false,defaultValue = "段玉铭") String name){ Product product = new Product(); product.setId(111); product.setName(name); return product; } /** * restful * 以资源为导向 *http://localhost:8080/product.do/1 *http://localhost:8080/product.do/2 * 利于seo优化(网站排名) * * id=1 * http://localhost:8080/product.do?id=1 * http://localhost:8080/product.do?id=2 */ @RequestMapping(value = "/hello3/{prodeuctId}/{productName}")//可变参数通过{}定义 @ResponseBody public Product getProduct(@PathVariable(value = "prodeuctId") Integer id,@PathVariable String productName){ Product product = new Product(); product.setId(id); product.setName(productName); return product; } }
1,366
0.655624
0.633282
47
26.617022
24.857512
111
false
false
0
0
0
0
0
0
0.361702
false
false
0
36d2a8efe3e444f598ce057ea4aaf6c5eb775122
515,396,093,374
38a353947152ac1ac3fb0071abe46851cf18b50a
/src/java/Server.java
421a88257d72e090641e21ef7cdd069a9030b92e
[]
no_license
NguyenVanTung11041998/QuanLyBanHang
https://github.com/NguyenVanTung11041998/QuanLyBanHang
63d6283b87fe119eddcc6cb3e2899ede75ee43ac
205243a5cb344920a08078c09747825733e1692a
refs/heads/master
2020-09-13T23:17:03.614000
2019-12-15T15:48:09
2019-12-15T15:48:09
222,934,655
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
import Corba_DAO.*; import DAO.*; import DTO.*; import org.omg.CORBA.ORB; import org.omg.CosNaming.NameComponent; import org.omg.CosNaming.NamingContextExt; import org.omg.CosNaming.NamingContextExtHelper; import org.omg.PortableServer.POA; import org.omg.PortableServer.POAHelper; public class Server { public static void main(String[] args) { try { // create and initialize the ORB ORB orb = ORB.init(args, null); // get reference to rootpoa & activate the POAManager POA rootpoa = POAHelper.narrow(orb.resolve_initial_references("RootPOA")); rootpoa.the_POAManager().activate(); // create servant and register it with the ORB AccountAdminDAO accountImpl = new AccountAdminDAO(); accountImpl.setOrb(orb); org.omg.CORBA.Object ref = rootpoa.servant_to_reference(accountImpl); IAccountAdminDAO href = IAccountAdminDAOHelper.narrow(ref); org.omg.CORBA.Object objRef = orb.resolve_initial_references("NameService"); NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef); String name = "IAccountAdmin"; NameComponent path[] = ncRef.to_name(name); ncRef.rebind(path, href); NhaSanXuatDAO nhaSanXuatDAO = new NhaSanXuatDAO(); nhaSanXuatDAO.setOrb(orb); ref = rootpoa.servant_to_reference(nhaSanXuatDAO); INhaSanXuatDAO href1 = INhaSanXuatDAOHelper.narrow(ref); objRef = orb.resolve_initial_references("NameService"); ncRef = NamingContextExtHelper.narrow(objRef); name = "INhaSanXuat"; path = ncRef.to_name(name); ncRef.rebind(path, href1); NhaCungCapDAO nhaCungCapDAO = new NhaCungCapDAO(); nhaCungCapDAO.setOrb(orb); ref = rootpoa.servant_to_reference(nhaCungCapDAO); INhaCungCapDAO href2 = INhaCungCapDAOHelper.narrow(ref); objRef = orb.resolve_initial_references("NameService"); ncRef = NamingContextExtHelper.narrow(objRef); name = "INhaCungCap"; path = ncRef.to_name(name); ncRef.rebind(path, href2); SanPhamDAO sanPhamDAO = new SanPhamDAO(); sanPhamDAO.setOrb(orb); ref = rootpoa.servant_to_reference(sanPhamDAO); ISanPhamDAO href3 = ISanPhamDAOHelper.narrow(ref); objRef = orb.resolve_initial_references("NameService"); ncRef = NamingContextExtHelper.narrow(objRef); name = "ISanPham"; path = ncRef.to_name(name); ncRef.rebind(path, href3); PhieuNhapDAO phieuNhapDAO = new PhieuNhapDAO(); phieuNhapDAO.setOrb(orb); ref = rootpoa.servant_to_reference(phieuNhapDAO); IPhieuNhapDAO href4 = IPhieuNhapDAOHelper.narrow(ref); objRef = orb.resolve_initial_references("NameService"); ncRef = NamingContextExtHelper.narrow(objRef); name = "IPhieuNhap"; path = ncRef.to_name(name); ncRef.rebind(path, href4); PhieuNhapChiTietDAO phieuNhapChiTietDAO = new PhieuNhapChiTietDAO(); sanPhamDAO.setOrb(orb); ref = rootpoa.servant_to_reference(phieuNhapChiTietDAO); IPhieuNhapChiTietDAO href5 = IPhieuNhapChiTietDAOHelper.narrow(ref); objRef = orb.resolve_initial_references("NameService"); ncRef = NamingContextExtHelper.narrow(objRef); name = "IPhieuNhapChiTiet"; path = ncRef.to_name(name); ncRef.rebind(path, href5); HoaDonChiTietDAO hoaDonChiTietDAO = new HoaDonChiTietDAO(); hoaDonChiTietDAO.setOrb(orb); ref = rootpoa.servant_to_reference(hoaDonChiTietDAO); IHoaDonChiTietDAO href6 = IHoaDonChiTietDAOHelper.narrow(ref); objRef = orb.resolve_initial_references("NameService"); ncRef = NamingContextExtHelper.narrow(objRef); name = "IHoaDonChiTiet"; path = ncRef.to_name(name); ncRef.rebind(path, href6); HoaDonDAO hoaDonDAO = new HoaDonDAO(); hoaDonDAO.setOrb(orb); ref = rootpoa.servant_to_reference(hoaDonDAO); IHoaDonDAO href7 = IHoaDonDAOHelper.narrow(ref); objRef = orb.resolve_initial_references("NameService"); ncRef = NamingContextExtHelper.narrow(objRef); name = "IHoaDon"; path = ncRef.to_name(name); ncRef.rebind(path, href7); KhachHangDAO khachHangDAO = new KhachHangDAO(); khachHangDAO.setOrb(orb); ref = rootpoa.servant_to_reference(khachHangDAO); IKhachHangDAO href8 = IKhachHangDAOHelper.narrow(ref); objRef = orb.resolve_initial_references("NameService"); ncRef = NamingContextExtHelper.narrow(objRef); name = "IKhachHang"; path = ncRef.to_name(name); ncRef.rebind(path, href8); GioHangDAO gioHangDAO = new GioHangDAO(); gioHangDAO.setOrb(orb); ref = rootpoa.servant_to_reference(gioHangDAO); IGioHangDAO href9 = IGioHangDAOHelper.narrow(ref); objRef = orb.resolve_initial_references("NameService"); ncRef = NamingContextExtHelper.narrow(objRef); name = "IGioHang"; path = ncRef.to_name(name); ncRef.rebind(path, href9); DanhMucDAO danhMucDAO = new DanhMucDAO(); danhMucDAO.setOrb(orb); ref = rootpoa.servant_to_reference(danhMucDAO); IDanhMucDAO href10 = IDanhMucDAOHelper.narrow(ref); objRef = orb.resolve_initial_references("NameService"); ncRef = NamingContextExtHelper.narrow(objRef); name = "IDanhMuc"; path = ncRef.to_name(name); ncRef.rebind(path, href10); LoaiSanPhamDAO loaiSanPhamDAO = new LoaiSanPhamDAO(); loaiSanPhamDAO.setOrb(orb); ref = rootpoa.servant_to_reference(loaiSanPhamDAO); ILoaiSanPhamDAO href11 = ILoaiSanPhamDAOHelper.narrow(ref); objRef = orb.resolve_initial_references("NameService"); ncRef = NamingContextExtHelper.narrow(objRef); name = "ILoaiSanPham"; path = ncRef.to_name(name); ncRef.rebind(path, href11); System.out.println("Ready.."); orb.run(); } catch (Exception e) { System.err.println("ERROR: " + e); e.printStackTrace(System.out); } System.out.println("Exiting ..."); } }
UTF-8
Java
6,875
java
Server.java
Java
[ { "context": "textExtHelper.narrow(objRef);\n name = \"ISanPham\";\n path = ncRef.to_name(name);\n ", "end": 2629, "score": 0.6938348412513733, "start": 2621, "tag": "NAME", "value": "ISanPham" }, { "context": "textExtHelper.narrow(objRef);\n name = \"IPhieuNhap\";\n path = ncRef.to_name(name);\n ", "end": 3108, "score": 0.6242133378982544, "start": 3098, "tag": "NAME", "value": "IPhieuNhap" }, { "context": "extExtHelper.narrow(objRef);\n name = \"IHoaDon\";\n path = ncRef.to_name(name);\n ", "end": 4600, "score": 0.7149631977081299, "start": 4594, "tag": "USERNAME", "value": "HoaDon" }, { "context": "textExtHelper.narrow(objRef);\n name = \"IGioHang\";\n path = ncRef.to_name(name);\n ", "end": 5542, "score": 0.6234281659126282, "start": 5534, "tag": "USERNAME", "value": "IGioHang" }, { "context": "textExtHelper.narrow(objRef);\n name = \"IDanhMuc\";\n path = ncRef.to_name(name);\n ", "end": 6006, "score": 0.6266393661499023, "start": 5998, "tag": "NAME", "value": "IDanhMuc" }, { "context": "textExtHelper.narrow(objRef);\n name = \"ILoaiSanPham\";\n path = ncRef.to_name(name);\n ", "end": 6503, "score": 0.6761729717254639, "start": 6491, "tag": "NAME", "value": "ILoaiSanPham" } ]
null
[]
import Corba_DAO.*; import DAO.*; import DTO.*; import org.omg.CORBA.ORB; import org.omg.CosNaming.NameComponent; import org.omg.CosNaming.NamingContextExt; import org.omg.CosNaming.NamingContextExtHelper; import org.omg.PortableServer.POA; import org.omg.PortableServer.POAHelper; public class Server { public static void main(String[] args) { try { // create and initialize the ORB ORB orb = ORB.init(args, null); // get reference to rootpoa & activate the POAManager POA rootpoa = POAHelper.narrow(orb.resolve_initial_references("RootPOA")); rootpoa.the_POAManager().activate(); // create servant and register it with the ORB AccountAdminDAO accountImpl = new AccountAdminDAO(); accountImpl.setOrb(orb); org.omg.CORBA.Object ref = rootpoa.servant_to_reference(accountImpl); IAccountAdminDAO href = IAccountAdminDAOHelper.narrow(ref); org.omg.CORBA.Object objRef = orb.resolve_initial_references("NameService"); NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef); String name = "IAccountAdmin"; NameComponent path[] = ncRef.to_name(name); ncRef.rebind(path, href); NhaSanXuatDAO nhaSanXuatDAO = new NhaSanXuatDAO(); nhaSanXuatDAO.setOrb(orb); ref = rootpoa.servant_to_reference(nhaSanXuatDAO); INhaSanXuatDAO href1 = INhaSanXuatDAOHelper.narrow(ref); objRef = orb.resolve_initial_references("NameService"); ncRef = NamingContextExtHelper.narrow(objRef); name = "INhaSanXuat"; path = ncRef.to_name(name); ncRef.rebind(path, href1); NhaCungCapDAO nhaCungCapDAO = new NhaCungCapDAO(); nhaCungCapDAO.setOrb(orb); ref = rootpoa.servant_to_reference(nhaCungCapDAO); INhaCungCapDAO href2 = INhaCungCapDAOHelper.narrow(ref); objRef = orb.resolve_initial_references("NameService"); ncRef = NamingContextExtHelper.narrow(objRef); name = "INhaCungCap"; path = ncRef.to_name(name); ncRef.rebind(path, href2); SanPhamDAO sanPhamDAO = new SanPhamDAO(); sanPhamDAO.setOrb(orb); ref = rootpoa.servant_to_reference(sanPhamDAO); ISanPhamDAO href3 = ISanPhamDAOHelper.narrow(ref); objRef = orb.resolve_initial_references("NameService"); ncRef = NamingContextExtHelper.narrow(objRef); name = "ISanPham"; path = ncRef.to_name(name); ncRef.rebind(path, href3); PhieuNhapDAO phieuNhapDAO = new PhieuNhapDAO(); phieuNhapDAO.setOrb(orb); ref = rootpoa.servant_to_reference(phieuNhapDAO); IPhieuNhapDAO href4 = IPhieuNhapDAOHelper.narrow(ref); objRef = orb.resolve_initial_references("NameService"); ncRef = NamingContextExtHelper.narrow(objRef); name = "IPhieuNhap"; path = ncRef.to_name(name); ncRef.rebind(path, href4); PhieuNhapChiTietDAO phieuNhapChiTietDAO = new PhieuNhapChiTietDAO(); sanPhamDAO.setOrb(orb); ref = rootpoa.servant_to_reference(phieuNhapChiTietDAO); IPhieuNhapChiTietDAO href5 = IPhieuNhapChiTietDAOHelper.narrow(ref); objRef = orb.resolve_initial_references("NameService"); ncRef = NamingContextExtHelper.narrow(objRef); name = "IPhieuNhapChiTiet"; path = ncRef.to_name(name); ncRef.rebind(path, href5); HoaDonChiTietDAO hoaDonChiTietDAO = new HoaDonChiTietDAO(); hoaDonChiTietDAO.setOrb(orb); ref = rootpoa.servant_to_reference(hoaDonChiTietDAO); IHoaDonChiTietDAO href6 = IHoaDonChiTietDAOHelper.narrow(ref); objRef = orb.resolve_initial_references("NameService"); ncRef = NamingContextExtHelper.narrow(objRef); name = "IHoaDonChiTiet"; path = ncRef.to_name(name); ncRef.rebind(path, href6); HoaDonDAO hoaDonDAO = new HoaDonDAO(); hoaDonDAO.setOrb(orb); ref = rootpoa.servant_to_reference(hoaDonDAO); IHoaDonDAO href7 = IHoaDonDAOHelper.narrow(ref); objRef = orb.resolve_initial_references("NameService"); ncRef = NamingContextExtHelper.narrow(objRef); name = "IHoaDon"; path = ncRef.to_name(name); ncRef.rebind(path, href7); KhachHangDAO khachHangDAO = new KhachHangDAO(); khachHangDAO.setOrb(orb); ref = rootpoa.servant_to_reference(khachHangDAO); IKhachHangDAO href8 = IKhachHangDAOHelper.narrow(ref); objRef = orb.resolve_initial_references("NameService"); ncRef = NamingContextExtHelper.narrow(objRef); name = "IKhachHang"; path = ncRef.to_name(name); ncRef.rebind(path, href8); GioHangDAO gioHangDAO = new GioHangDAO(); gioHangDAO.setOrb(orb); ref = rootpoa.servant_to_reference(gioHangDAO); IGioHangDAO href9 = IGioHangDAOHelper.narrow(ref); objRef = orb.resolve_initial_references("NameService"); ncRef = NamingContextExtHelper.narrow(objRef); name = "IGioHang"; path = ncRef.to_name(name); ncRef.rebind(path, href9); DanhMucDAO danhMucDAO = new DanhMucDAO(); danhMucDAO.setOrb(orb); ref = rootpoa.servant_to_reference(danhMucDAO); IDanhMucDAO href10 = IDanhMucDAOHelper.narrow(ref); objRef = orb.resolve_initial_references("NameService"); ncRef = NamingContextExtHelper.narrow(objRef); name = "IDanhMuc"; path = ncRef.to_name(name); ncRef.rebind(path, href10); LoaiSanPhamDAO loaiSanPhamDAO = new LoaiSanPhamDAO(); loaiSanPhamDAO.setOrb(orb); ref = rootpoa.servant_to_reference(loaiSanPhamDAO); ILoaiSanPhamDAO href11 = ILoaiSanPhamDAOHelper.narrow(ref); objRef = orb.resolve_initial_references("NameService"); ncRef = NamingContextExtHelper.narrow(objRef); name = "ILoaiSanPham"; path = ncRef.to_name(name); ncRef.rebind(path, href11); System.out.println("Ready.."); orb.run(); } catch (Exception e) { System.err.println("ERROR: " + e); e.printStackTrace(System.out); } System.out.println("Exiting ..."); } }
6,875
0.597673
0.593891
153
43.934639
20.510693
88
false
false
0
0
0
0
0
0
0.901961
false
false
0
2a2cbcad5d50db242fa3433e8a2d09a9a430bea7
21,182,778,722,982
8466474c6203a560b31fb996eff683e98f08f720
/rpc-spring-boot-consumer/src/main/java/com/foresee/gpz/boot/consumer/BootConsumerController.java
0c2b8eae2c750ca54508477104576ce36c992918
[]
no_license
guhao0907/test_20180609
https://github.com/guhao0907/test_20180609
5e023f0bed0359a3153a419f1a8b8e4bd2925e13
6a3d9168f13988c2627b4b9db87767ebbbf7d89b
refs/heads/master
2020-03-19T16:14:57.549000
2018-06-20T16:03:38
2018-06-20T16:03:38
136,707,602
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.foresee.gpz.boot.consumer; import com.alibaba.dubbo.config.annotation.Reference; import com.foresee.gpz.api.IHelloWorld; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; /** * @Auther: guhao * @Date: 2018/6/10 15:21 * @Description: */ @RestController public class BootConsumerController { @Reference(version = "1.0.0") private IHelloWorld helloWorld; @GetMapping(value = "/hello.do") public void hello(){ helloWorld.sayHello("spring boot dubbo!"); } }
UTF-8
Java
635
java
BootConsumerController.java
Java
[ { "context": "b.bind.annotation.RestController;\n\n/**\n * @Auther: guhao\n * @Date: 2018/6/10 15:21\n * @Description:\n */\n@R", "end": 338, "score": 0.9995155930519104, "start": 333, "tag": "USERNAME", "value": "guhao" } ]
null
[]
package com.foresee.gpz.boot.consumer; import com.alibaba.dubbo.config.annotation.Reference; import com.foresee.gpz.api.IHelloWorld; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; /** * @Auther: guhao * @Date: 2018/6/10 15:21 * @Description: */ @RestController public class BootConsumerController { @Reference(version = "1.0.0") private IHelloWorld helloWorld; @GetMapping(value = "/hello.do") public void hello(){ helloWorld.sayHello("spring boot dubbo!"); } }
635
0.742496
0.720379
24
25.375
20.920111
62
false
false
0
0
0
0
0
0
0.333333
false
false
0
83eaa6cbdda0e27cf86597b6bae7f91ef7424f9e
33,079,838,184,428
ce58efd2ca6349901e4b0738084cdf935e098dfd
/carservice-common/src/main/java/com/szyciov/util/ExcelImp.java
f5d9e9896b45983b892e8cf2da7f9366fbd9a2dc
[]
no_license
li551933/ruyue-taxi
https://github.com/li551933/ruyue-taxi
8d97e1e38e5cb25470992e0f0bc7624d3d32c3ad
c548a8aad2c29e4e4bea7749c4f44f93758b9c55
refs/heads/master
2019-06-28T16:44:16.302000
2017-07-05T09:35:26
2017-07-05T09:35:26
101,281,398
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.szyciov.util; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.web.multipart.MultipartFile; /** * * 解析excel调用的方法 * */ public class ExcelImp { /** * mulfile Excel路径 * */ public Map<Integer, Map> excelImp(MultipartFile mulfile) throws IOException{ InputStream is = mulfile.getInputStream(); try { if(mulfile.getOriginalFilename().endsWith("xlsx")){ return new ExcelXss().excelAllImport(is); }else if(mulfile.getOriginalFilename().endsWith("xls")){ return new ExcelHss().excelAllImport(is); }else{ System.out.println("不可解析文件"); } is = null; }finally { is.close(); } return new HashMap<Integer, Map>(); } /** * mulfile Excel路径 * nullable 允许为空的list * */ public Map<String, Map> excelImp(MultipartFile mulfile,List<String> nullable) throws IOException{ InputStream is = mulfile.getInputStream(); try { if(mulfile.getOriginalFilename().endsWith("xlsx")){ ExcelXss xss = new ExcelXss(); xss.setExtraParam(nullable); return xss.excelImport(is); }else if(mulfile.getOriginalFilename().endsWith("xls")){ ExcelHss hss = new ExcelHss(); hss.setExtraParam(nullable); return hss.excelImport(is); }else{ System.out.println("不可解析文件"); } is = null; }finally { is.close(); } return new HashMap<String, Map>(); } /** * 有规则接口 * */ public Map<Integer, Map> excelImp(MultipartFile mulfile,ExcelRuleImport excelRuleImport) throws IOException{ InputStream is = mulfile.getInputStream(); try { if(mulfile.getOriginalFilename().endsWith("xlsx")){ ExcelXss xss = new ExcelXss(); if(excelRuleImport.VerifyFirstTitle(xss.getTitleXss(is))) { return xss.excelRuleImport(is, excelRuleImport); } }else if(mulfile.getOriginalFilename().endsWith("xls")){ ExcelHss hss = new ExcelHss(); if(excelRuleImport.VerifyFirstTitle(hss.getTitleHss(is))) { return hss.excelRuleImport(is, excelRuleImport); } }else{ System.out.println("不可解析文件"); } is = null; }finally { if(is!=null) { is.close(); } } return new HashMap<Integer, Map>(); } public static void main(String[] args) throws Exception { // 构造 XSSFWorkbook 对象,strPath 传入文件路径 /*ExcelImp ep = new ExcelImp(); String path = "D://111.xls"; String path1 = "D://222.xlsx"; ep.excelImp(path);*/ ExcelXss e = new ExcelXss(); String path = "D://222.xlsx"; InputStream is = new FileInputStream(new File(path)); e.excelRuleImport(is,new ExcelRuleImport(){ @Override public boolean excelRuleImport(int index, Map<String, String> map) { if(map.get("法人住所地址") == null || "".equals(map.get("法人住所地址"))){ return false; } return true; } @Override public boolean VerifyFirstTitle(String[] columns) { return true; } }); } }
UTF-8
Java
3,074
java
ExcelImp.java
Java
[]
null
[]
package com.szyciov.util; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.web.multipart.MultipartFile; /** * * 解析excel调用的方法 * */ public class ExcelImp { /** * mulfile Excel路径 * */ public Map<Integer, Map> excelImp(MultipartFile mulfile) throws IOException{ InputStream is = mulfile.getInputStream(); try { if(mulfile.getOriginalFilename().endsWith("xlsx")){ return new ExcelXss().excelAllImport(is); }else if(mulfile.getOriginalFilename().endsWith("xls")){ return new ExcelHss().excelAllImport(is); }else{ System.out.println("不可解析文件"); } is = null; }finally { is.close(); } return new HashMap<Integer, Map>(); } /** * mulfile Excel路径 * nullable 允许为空的list * */ public Map<String, Map> excelImp(MultipartFile mulfile,List<String> nullable) throws IOException{ InputStream is = mulfile.getInputStream(); try { if(mulfile.getOriginalFilename().endsWith("xlsx")){ ExcelXss xss = new ExcelXss(); xss.setExtraParam(nullable); return xss.excelImport(is); }else if(mulfile.getOriginalFilename().endsWith("xls")){ ExcelHss hss = new ExcelHss(); hss.setExtraParam(nullable); return hss.excelImport(is); }else{ System.out.println("不可解析文件"); } is = null; }finally { is.close(); } return new HashMap<String, Map>(); } /** * 有规则接口 * */ public Map<Integer, Map> excelImp(MultipartFile mulfile,ExcelRuleImport excelRuleImport) throws IOException{ InputStream is = mulfile.getInputStream(); try { if(mulfile.getOriginalFilename().endsWith("xlsx")){ ExcelXss xss = new ExcelXss(); if(excelRuleImport.VerifyFirstTitle(xss.getTitleXss(is))) { return xss.excelRuleImport(is, excelRuleImport); } }else if(mulfile.getOriginalFilename().endsWith("xls")){ ExcelHss hss = new ExcelHss(); if(excelRuleImport.VerifyFirstTitle(hss.getTitleHss(is))) { return hss.excelRuleImport(is, excelRuleImport); } }else{ System.out.println("不可解析文件"); } is = null; }finally { if(is!=null) { is.close(); } } return new HashMap<Integer, Map>(); } public static void main(String[] args) throws Exception { // 构造 XSSFWorkbook 对象,strPath 传入文件路径 /*ExcelImp ep = new ExcelImp(); String path = "D://111.xls"; String path1 = "D://222.xlsx"; ep.excelImp(path);*/ ExcelXss e = new ExcelXss(); String path = "D://222.xlsx"; InputStream is = new FileInputStream(new File(path)); e.excelRuleImport(is,new ExcelRuleImport(){ @Override public boolean excelRuleImport(int index, Map<String, String> map) { if(map.get("法人住所地址") == null || "".equals(map.get("法人住所地址"))){ return false; } return true; } @Override public boolean VerifyFirstTitle(String[] columns) { return true; } }); } }
3,074
0.672542
0.669153
116
24.431034
22.371559
109
false
false
0
0
0
0
0
0
2.655172
false
false
0
f15679cb8783a6363dd8d46d6ef2cc0244a9204f
10,642,929,010,616
85358c397ceb170f6f3095fd1c71cfb567548b2f
/core/src/main/java/org/tpl/business/model/validator/FantasyRoundValidator.java
770d15b34277f93c6248c3a05092be47a9df9d58
[]
no_license
jordyrk/tpliga
https://github.com/jordyrk/tpliga
2b9f8583bb2aac0d161322cce8df50993bf19237
7067a47f95544b65ef20671642ccce29f673f8b8
refs/heads/master
2021-12-31T01:48:32.560000
2020-07-19T18:55:22
2020-07-19T18:55:22
59,592,092
0
0
null
false
2021-12-09T19:47:33
2016-05-24T16:59:05
2020-07-19T18:55:34
2021-12-09T19:47:31
206,740
0
0
2
Java
false
false
package org.tpl.business.model.validator; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; import org.tpl.business.model.fantasy.FantasyRound; import org.tpl.business.model.fantasy.FantasySeason; public class FantasyRoundValidator implements Validator{ public boolean supports(Class type) { return FantasyRound.class.equals(type); } public void validate(Object o, Errors errors) { } }
UTF-8
Java
514
java
FantasyRoundValidator.java
Java
[]
null
[]
package org.tpl.business.model.validator; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; import org.tpl.business.model.fantasy.FantasyRound; import org.tpl.business.model.fantasy.FantasySeason; public class FantasyRoundValidator implements Validator{ public boolean supports(Class type) { return FantasyRound.class.equals(type); } public void validate(Object o, Errors errors) { } }
514
0.791829
0.791829
18
27.611111
23.788744
56
false
false
0
0
0
0
0
0
0.444444
false
false
0
28cbbf5c409eaeb9d31f14193b9ea20a205e5072
20,693,152,484,947
76d5a597ec5055c6230a4f2cbc8613d57232468d
/MusicPlayer/dreammusicplayer/src/main/java/com/example/dreammusicplayer/DownloadActivity.java
c7d54f7812c80e6c5fa04b9c9edf9e8b815c60a8
[]
no_license
AngryBird-ChangeWorld/BodyTestClient
https://github.com/AngryBird-ChangeWorld/BodyTestClient
e18ddcb9114e797830486d34ca954ed84318dc1d
5705b837725332609ce21c2d4e62fdb818f0094a
refs/heads/master
2020-04-12T07:56:06.175000
2018-11-28T13:48:14
2018-11-28T13:48:14
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.dreammusicplayer; import android.content.Intent; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.Toast; import com.example.dreammusicplayer.Utils.Constant; import com.example.dreammusicplayer.download.DownloadService; import com.example.dreammusicplayer.xmlparser.DownloadReceiver; import com.example.dreammusicplayer.xmlparser.MusicInfo; import com.example.dreammusicplayer.xmlparser.XMLContentHandler; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import java.io.FileInputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.parsers.SAXParserFactory; /** * 下载界面 */ public class DownloadActivity extends AppCompatActivity implements Serializable { private final static int UPDATE = 1; private List<MusicInfo> musicInfos; private ListView downloadList; private List<Map<String, String>> list; private Handler handler; private String fileName; private Map<String, View> viewMap; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_download); downloadList = (ListView) findViewById(R.id.downloadList); list = new ArrayList<>(); handler = new Handler(); updateList(); downloadList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { fileName = list.get(position).get("musicName"); final String str = fileName; MusicInfo musicInfo = musicInfos.get(position); final String lrcName = musicInfo.getLrcName(); Button button = (Button) view.findViewById(R.id.download); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { download(lrcName); download(str); } }); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(0, UPDATE, 1, R.string.update); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == UPDATE) { updateList(); } return super.onOptionsItemSelected(item); } public void updateList() { list.clear(); fileName = "mp3.xml"; musicInfos = xmlParser("mp3.xml"); if (musicInfos == null) return; for (MusicInfo info : musicInfos) { Map<String, String> map = new HashMap<>(); map.put("musicName", info.getMp3Name()); map.put("musicSize", info.getMp3Size() + "k"); list.add(map); } String[] from = {"musicName", "musicSize"}; int[] to = {R.id.downMusicName, R.id.downMusicSize}; SimpleAdapter adapter = new SimpleAdapter(this, list, R.layout.download_adapter_item, from, to); downloadList.setAdapter(adapter); } public List<MusicInfo> xmlParser(String urlPath) { Log.w("tag", "xmlParser开始运行"); try { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { download(urlPath); // while (!DownloadReceiver.isFinsihed()){ // Thread.sleep(10); // } XMLReader reader = SAXParserFactory.newInstance().newSAXParser() .getXMLReader(); XMLContentHandler handler = new XMLContentHandler(); reader.setContentHandler(handler); reader.parse(new InputSource(new FileInputStream(Constant.SAVE_PATH + "/mp3.xml"))); Log.w("tag", "xmlParser运行结束"); return handler.getMusicInfos(); } } catch (Exception e) { e.printStackTrace(); } return null; } /** * 从网络上下载指定名字的文件 * * @param fileName */ public void download(String fileName) { Intent intent = new Intent(this, DownloadService.class); intent.putExtra("url", Constant.DOWNLOAD_PATH + fileName); startService(intent); Log.w("tag", "startService:" + intent); handler.postDelayed(checkDownloadFinished,0); } private Runnable checkDownloadFinished = new Runnable() { @Override public void run() { handler.postDelayed(checkDownloadFinished, 10); if (DownloadReceiver.isFinsihed()) { DownloadReceiver.setIsFinsihed(false); Toast.makeText(DownloadActivity.this, DownloadReceiver.getFileName() + "下载完成", Toast.LENGTH_SHORT).show(); handler.removeCallbacks(checkDownloadFinished); } } }; }
UTF-8
Java
4,752
java
DownloadActivity.java
Java
[]
null
[]
package com.example.dreammusicplayer; import android.content.Intent; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.Toast; import com.example.dreammusicplayer.Utils.Constant; import com.example.dreammusicplayer.download.DownloadService; import com.example.dreammusicplayer.xmlparser.DownloadReceiver; import com.example.dreammusicplayer.xmlparser.MusicInfo; import com.example.dreammusicplayer.xmlparser.XMLContentHandler; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import java.io.FileInputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.parsers.SAXParserFactory; /** * 下载界面 */ public class DownloadActivity extends AppCompatActivity implements Serializable { private final static int UPDATE = 1; private List<MusicInfo> musicInfos; private ListView downloadList; private List<Map<String, String>> list; private Handler handler; private String fileName; private Map<String, View> viewMap; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_download); downloadList = (ListView) findViewById(R.id.downloadList); list = new ArrayList<>(); handler = new Handler(); updateList(); downloadList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { fileName = list.get(position).get("musicName"); final String str = fileName; MusicInfo musicInfo = musicInfos.get(position); final String lrcName = musicInfo.getLrcName(); Button button = (Button) view.findViewById(R.id.download); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { download(lrcName); download(str); } }); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(0, UPDATE, 1, R.string.update); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == UPDATE) { updateList(); } return super.onOptionsItemSelected(item); } public void updateList() { list.clear(); fileName = "mp3.xml"; musicInfos = xmlParser("mp3.xml"); if (musicInfos == null) return; for (MusicInfo info : musicInfos) { Map<String, String> map = new HashMap<>(); map.put("musicName", info.getMp3Name()); map.put("musicSize", info.getMp3Size() + "k"); list.add(map); } String[] from = {"musicName", "musicSize"}; int[] to = {R.id.downMusicName, R.id.downMusicSize}; SimpleAdapter adapter = new SimpleAdapter(this, list, R.layout.download_adapter_item, from, to); downloadList.setAdapter(adapter); } public List<MusicInfo> xmlParser(String urlPath) { Log.w("tag", "xmlParser开始运行"); try { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { download(urlPath); // while (!DownloadReceiver.isFinsihed()){ // Thread.sleep(10); // } XMLReader reader = SAXParserFactory.newInstance().newSAXParser() .getXMLReader(); XMLContentHandler handler = new XMLContentHandler(); reader.setContentHandler(handler); reader.parse(new InputSource(new FileInputStream(Constant.SAVE_PATH + "/mp3.xml"))); Log.w("tag", "xmlParser运行结束"); return handler.getMusicInfos(); } } catch (Exception e) { e.printStackTrace(); } return null; } /** * 从网络上下载指定名字的文件 * * @param fileName */ public void download(String fileName) { Intent intent = new Intent(this, DownloadService.class); intent.putExtra("url", Constant.DOWNLOAD_PATH + fileName); startService(intent); Log.w("tag", "startService:" + intent); handler.postDelayed(checkDownloadFinished,0); } private Runnable checkDownloadFinished = new Runnable() { @Override public void run() { handler.postDelayed(checkDownloadFinished, 10); if (DownloadReceiver.isFinsihed()) { DownloadReceiver.setIsFinsihed(false); Toast.makeText(DownloadActivity.this, DownloadReceiver.getFileName() + "下载完成", Toast.LENGTH_SHORT).show(); handler.removeCallbacks(checkDownloadFinished); } } }; }
4,752
0.731998
0.729016
162
27.975309
21.926632
87
false
false
0
0
0
0
0
0
2.37037
false
false
0
666185179992efbfbcf0f621e1fc79db74956c32
12,635,793,852,503
97da474923e072ecbd29a99aff1a3665d680381c
/FluentInterfacesDSL/src/main/java/game/nested/dsl/PlayerBuilder.java
0a04944e60b29124eb1bf0d488e9ea65e4b95ae7
[]
no_license
terentyevkirill/othr-ajp-labs
https://github.com/terentyevkirill/othr-ajp-labs
9d72391ebabd6682f0f8600eb4666a5f5024888e
f90c0f54b69dc67c689c6ecb61d8adb20f91a8b6
refs/heads/master
2023-03-27T22:01:03.991000
2020-06-09T14:11:18
2020-06-09T14:11:18
251,613,758
0
0
null
false
2021-03-31T22:05:31
2020-03-31T13:40:08
2020-06-09T14:12:07
2021-03-31T22:05:30
379
0
0
1
Java
false
false
package game.nested.dsl; public interface PlayerBuilder extends LocationBuilder { LocationBuilder asMaster(); }
UTF-8
Java
117
java
PlayerBuilder.java
Java
[]
null
[]
package game.nested.dsl; public interface PlayerBuilder extends LocationBuilder { LocationBuilder asMaster(); }
117
0.794872
0.794872
5
22.4
20.809612
56
false
false
0
0
0
0
0
0
0.4
false
false
0
35ca47af7201b9a1a02f7c8c7a44f9ae5413b4e3
26,096,221,356,929
75367b86f0b4198eb4652743eb2af2dedc37fa51
/src/main/java/test/DBCPTest.java
9bc1385dbf66baa96b5e81c4ab8cb18f0dd3624a
[]
no_license
zhang0415/databasesPond
https://github.com/zhang0415/databasesPond
5b7fa1880a63e535d06e1ab815b5409a6b23eab2
f09104da27158a4b1a31a523670770f667fc4318
refs/heads/master
2023-03-05T14:05:39.576000
2021-02-18T18:19:36
2021-02-18T18:19:36
340,139,133
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package test; import org.apache.commons.dbcp.BasicDataSourceFactory; import javax.sql.DataSource; import java.sql.*; import java.util.Properties; public class DBCPTest { public static DataSource dataSource; static String sql = "select * from guest"; static { Properties properties = new Properties(); try { // properties.load(DBCPTest.class.getClassLoader(). // getResourceAsStream("dbcp.properties")); properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("dbcp.properties")); // 通过基础数据源工厂类 来创建连接池 dataSource = BasicDataSourceFactory.createDataSource(properties); Connection conn = getConn(); PreparedStatement stat = conn.prepareStatement(sql); ResultSet rs = stat.executeQuery(); while (rs.next()){ System.out.print(rs.getString("name")+" \t "); System.out.println(rs.getString("role")); } closeConnection(conn); // DatabaseMetaData metaData = conn.getMetaData(); // // System.out.println(metaData.getDatabaseProductName() + " " + // metaData.getDatabaseProductVersion()); // // closeConnection(conn); } catch (Exception e) { e.printStackTrace(); } } public static Connection getConn(){ Connection conn = null; try { conn = dataSource.getConnection(); } catch (Exception e) { e.printStackTrace(); } return conn; } public static void closeConnection(Connection connection){ try { if (connection !=null && !connection.isClosed()){ connection.close(); } } catch (SQLException e) { e.printStackTrace(); } } public static void main(String[] args) { for (int i = 0; i < 35; i++) { Connection conn = getConn(); System.out.println("成功获取连接" + i); closeConnection(conn); } } }
UTF-8
Java
2,149
java
DBCPTest.java
Java
[]
null
[]
package test; import org.apache.commons.dbcp.BasicDataSourceFactory; import javax.sql.DataSource; import java.sql.*; import java.util.Properties; public class DBCPTest { public static DataSource dataSource; static String sql = "select * from guest"; static { Properties properties = new Properties(); try { // properties.load(DBCPTest.class.getClassLoader(). // getResourceAsStream("dbcp.properties")); properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("dbcp.properties")); // 通过基础数据源工厂类 来创建连接池 dataSource = BasicDataSourceFactory.createDataSource(properties); Connection conn = getConn(); PreparedStatement stat = conn.prepareStatement(sql); ResultSet rs = stat.executeQuery(); while (rs.next()){ System.out.print(rs.getString("name")+" \t "); System.out.println(rs.getString("role")); } closeConnection(conn); // DatabaseMetaData metaData = conn.getMetaData(); // // System.out.println(metaData.getDatabaseProductName() + " " + // metaData.getDatabaseProductVersion()); // // closeConnection(conn); } catch (Exception e) { e.printStackTrace(); } } public static Connection getConn(){ Connection conn = null; try { conn = dataSource.getConnection(); } catch (Exception e) { e.printStackTrace(); } return conn; } public static void closeConnection(Connection connection){ try { if (connection !=null && !connection.isClosed()){ connection.close(); } } catch (SQLException e) { e.printStackTrace(); } } public static void main(String[] args) { for (int i = 0; i < 35; i++) { Connection conn = getConn(); System.out.println("成功获取连接" + i); closeConnection(conn); } } }
2,149
0.564846
0.56342
67
30.41791
23.887266
115
false
false
0
0
0
0
0
0
0.477612
false
false
0
87b8bd3a505fd558381e77d30bf5a01679d36a55
10,144,712,816,495
9c1e0581ab6a887dc95839f476baab962a3a2df2
/BetaJobBoard/src/main/java/com/model/interfaces/VerificationTokenDao.java
3b42df0e297fdde375afe798f588dea24aca5728
[ "MIT" ]
permissive
veryintelligentperson/Beta-Job-Board
https://github.com/veryintelligentperson/Beta-Job-Board
cf3e361d48f9ba24b69853b02d49eea99c08c275
7b0c06640b296d32f2421df1c45725a27efe88d0
refs/heads/master
2021-01-10T20:13:11.236000
2015-07-22T17:26:01
2015-07-22T17:26:01
39,518,367
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.model.interfaces; import com.model.beans.VerificationToken; /** * Created by michal on 04.07.15. */ public interface VerificationTokenDao { void createOrUpdateToken(VerificationToken token); void deleteToken(int id); VerificationToken getTokenById(int id); VerificationToken getVerificationTokenByToken(String token); }
UTF-8
Java
355
java
VerificationTokenDao.java
Java
[ { "context": ".model.beans.VerificationToken;\n\n/**\n * Created by michal on 04.07.15.\n */\npublic interface VerificationTok", "end": 98, "score": 0.9884657859802246, "start": 92, "tag": "USERNAME", "value": "michal" } ]
null
[]
package com.model.interfaces; import com.model.beans.VerificationToken; /** * Created by michal on 04.07.15. */ public interface VerificationTokenDao { void createOrUpdateToken(VerificationToken token); void deleteToken(int id); VerificationToken getTokenById(int id); VerificationToken getVerificationTokenByToken(String token); }
355
0.769014
0.752113
16
21.1875
21.895258
64
false
false
0
0
0
0
0
0
0.375
false
false
0
dca0d9f9f9e49c5a833667d3379ce8849179fac0
5,119,601,020,951
e4f3397db1a1614e9d9c2a20a48a3790309efb3d
/org/alphamodder/alpharpg/util/DeathData.java
3c00d5a2ab574ab5f1ea586dc8270b9afb64d6b0
[]
no_license
AlphaModder/AlphaRPG
https://github.com/AlphaModder/AlphaRPG
7506e97b6255bc9fa9f31f00deb592502e2754f5
5f7077d1d1d7a10fbbd7d21d669f18e16d5a05a2
refs/heads/master
2016-09-16T00:20:59.435000
2013-11-08T17:15:56
2013-11-08T17:15:56
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.alphamodder.alpharpg.util; import java.util.HashMap; import java.util.Map; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.event.entity.EntityDeathEvent; public class DeathData { private static Map<EntityType, EntityClass> classes = new HashMap<EntityType, EntityClass>(); static{ classes.put(EntityType.ARROW, EntityClass.OTHER); classes.put(EntityType.BAT, EntityClass.PEACEFUL); classes.put(EntityType.BLAZE, EntityClass.HOSTILE); classes.put(EntityType.BOAT, EntityClass.OTHER); classes.put(EntityType.CAVE_SPIDER, EntityClass.HOSTILE); classes.put(EntityType.CHICKEN, EntityClass.PEACEFUL); classes.put(EntityType.COMPLEX_PART, EntityClass.OTHER); classes.put(EntityType.COW, EntityClass.PEACEFUL); classes.put(EntityType.CREEPER, EntityClass.HOSTILE); classes.put(EntityType.DROPPED_ITEM, EntityClass.OTHER); classes.put(EntityType.EGG, EntityClass.OTHER); classes.put(EntityType.ENDER_CRYSTAL, EntityClass.OTHER); classes.put(EntityType.ENDER_DRAGON, EntityClass.BOSS); classes.put(EntityType.ENDER_PEARL, EntityClass.OTHER); classes.put(EntityType.ENDER_SIGNAL, EntityClass.OTHER); classes.put(EntityType.ENDERMAN, EntityClass.HOSTILE); classes.put(EntityType.EXPERIENCE_ORB, EntityClass.OTHER); classes.put(EntityType.FALLING_BLOCK, EntityClass.OTHER); classes.put(EntityType.FIREBALL, EntityClass.OTHER); classes.put(EntityType.FIREWORK, EntityClass.OTHER); classes.put(EntityType.FISHING_HOOK, EntityClass.OTHER); classes.put(EntityType.GHAST, EntityClass.HOSTILE); classes.put(EntityType.GIANT, EntityClass.HOSTILE); classes.put(EntityType.IRON_GOLEM, EntityClass.PEACEFUL); classes.put(EntityType.ITEM_FRAME, EntityClass.OTHER); classes.put(EntityType.LIGHTNING, EntityClass.OTHER); classes.put(EntityType.MAGMA_CUBE, EntityClass.HOSTILE); classes.put(EntityType.MINECART, EntityClass.OTHER); classes.put(EntityType.MINECART_CHEST, EntityClass.OTHER); classes.put(EntityType.MINECART_FURNACE, EntityClass.OTHER); classes.put(EntityType.MINECART_HOPPER, EntityClass.OTHER); classes.put(EntityType.MINECART_MOB_SPAWNER, EntityClass.OTHER); classes.put(EntityType.MINECART_TNT, EntityClass.OTHER); classes.put(EntityType.MUSHROOM_COW, EntityClass.PEACEFUL); classes.put(EntityType.OCELOT, EntityClass.PEACEFUL); classes.put(EntityType.PAINTING, EntityClass.OTHER); classes.put(EntityType.PIG, EntityClass.PEACEFUL); classes.put(EntityType.PIG_ZOMBIE, EntityClass.HOSTILE); classes.put(EntityType.PLAYER, EntityClass.PLAYER); classes.put(EntityType.PRIMED_TNT, EntityClass.OTHER); classes.put(EntityType.SHEEP, EntityClass.PEACEFUL); classes.put(EntityType.SILVERFISH, EntityClass.HOSTILE); classes.put(EntityType.SKELETON, EntityClass.HOSTILE); classes.put(EntityType.SLIME, EntityClass.HOSTILE); classes.put(EntityType.SMALL_FIREBALL, EntityClass.OTHER); classes.put(EntityType.SNOWBALL, EntityClass.OTHER); classes.put(EntityType.SNOWMAN, EntityClass.PEACEFUL); classes.put(EntityType.SPIDER, EntityClass.HOSTILE); classes.put(EntityType.SPLASH_POTION, EntityClass.OTHER); classes.put(EntityType.SQUID, EntityClass.PEACEFUL); classes.put(EntityType.THROWN_EXP_BOTTLE, EntityClass.OTHER); classes.put(EntityType.UNKNOWN, EntityClass.OTHER); classes.put(EntityType.VILLAGER, EntityClass.PEACEFUL); classes.put(EntityType.WEATHER, EntityClass.OTHER); classes.put(EntityType.WITCH, EntityClass.HOSTILE); classes.put(EntityType.WITHER, EntityClass.BOSS); classes.put(EntityType.WITHER_SKULL, EntityClass.OTHER); classes.put(EntityType.WOLF, EntityClass.PEACEFUL); classes.put(EntityType.ZOMBIE, EntityClass.HOSTILE); } public enum EntityClass{ HOSTILE, PLAYER, PEACEFUL, OTHER, BOSS; } private Map<DeathCause, Integer> deaths = new HashMap<DeathCause, Integer>(); private Map<Entity, Integer> kills = new HashMap<Entity, Integer>(); public int getKills(){ int amount = 0; for(Entity e : kills.keySet()){ amount = amount + kills.get(e); } return amount; } public int getKills(EntityClass type){ int amount = 0; for(Entity e : kills.keySet()){ if(classes.get(e.getType()) == type){ amount = amount + kills.get(e); } } return amount; } public int getKills(EntityType type){ int amount = 0; for(Entity e : kills.keySet()){ if(e.getType() == type){ amount = amount + kills.get(e); } } return amount; } public int getKills(String username){ int amount = 0; for(Entity e : kills.keySet()){ if(e instanceof Player && ((Player)e).getName() == username){ amount = amount + kills.get(e); } } return amount; } public int getKills(Entity entity){ if(kills.containsKey(entity)){ return kills.get(entity); } return 0; } public int getDeaths(){ int amount = 0; for(DeathCause d : deaths.keySet()){ amount = amount + deaths.get(d); } return amount; } public int getDeaths(EntityType type){ int amount = 0; for(DeathCause d : deaths.keySet()){ if(d.isEntity() && d.getEntity().getType() == type){ amount = amount + deaths.get(d); } } return amount; } public int getDeaths(EntityClass type){ int amount = 0; for(DeathCause d : deaths.keySet()){ if(d.isEntity() && classes.get(d.getEntity()) == type){ amount = amount + deaths.get(d); } } return amount; } public int getDeaths(String username){ int amount = 0; for(DeathCause d : deaths.keySet()){ if(d.isEntity() && d.getEntity() instanceof Player && ((Player)d.getEntity()).getName() == username){ amount = amount + deaths.get(d); } } return amount; } public int getDeaths(Entity entity){ int amount = 0; for(DeathCause d : deaths.keySet()){ if(d.isEntity() && d.getEntity() == entity){ amount = amount + deaths.get(d); } } return amount; } public void die(EntityDeathEvent event){ DamageCause cause = event.getEntity().getLastDamageCause().getCause(); if(cause == DamageCause.CONTACT || cause == DamageCause.ENTITY_ATTACK || cause == DamageCause.ENTITY_EXPLOSION || cause == DamageCause.PROJECTILE){ if(deaths.containsKey(new DeathCause(event.getEntity().getLastDamageCause().getEntity(), cause))){ deaths.put(new DeathCause(event.getEntity().getLastDamageCause().getEntity(), cause), deaths.get(new DeathCause(event.getEntity().getLastDamageCause().getEntity(), cause))); } else{ deaths.put(new DeathCause(event.getEntity().getLastDamageCause().getEntity(), cause), 1); } } else{ if(deaths.containsKey(new DeathCause(null, cause))){ deaths.put(new DeathCause(null, cause), deaths.get(new DeathCause(null, cause))); } else{ deaths.put(new DeathCause(null, cause), 1); } } } public void kill(EntityDeathEvent event){ if(kills.containsKey(event.getEntity())){ kills.put(event.getEntity(), kills.get(event.getEntity()) + 1); } else{ kills.put(event.getEntity(), 1); } } }
UTF-8
Java
7,040
java
DeathData.java
Java
[]
null
[]
package org.alphamodder.alpharpg.util; import java.util.HashMap; import java.util.Map; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.event.entity.EntityDeathEvent; public class DeathData { private static Map<EntityType, EntityClass> classes = new HashMap<EntityType, EntityClass>(); static{ classes.put(EntityType.ARROW, EntityClass.OTHER); classes.put(EntityType.BAT, EntityClass.PEACEFUL); classes.put(EntityType.BLAZE, EntityClass.HOSTILE); classes.put(EntityType.BOAT, EntityClass.OTHER); classes.put(EntityType.CAVE_SPIDER, EntityClass.HOSTILE); classes.put(EntityType.CHICKEN, EntityClass.PEACEFUL); classes.put(EntityType.COMPLEX_PART, EntityClass.OTHER); classes.put(EntityType.COW, EntityClass.PEACEFUL); classes.put(EntityType.CREEPER, EntityClass.HOSTILE); classes.put(EntityType.DROPPED_ITEM, EntityClass.OTHER); classes.put(EntityType.EGG, EntityClass.OTHER); classes.put(EntityType.ENDER_CRYSTAL, EntityClass.OTHER); classes.put(EntityType.ENDER_DRAGON, EntityClass.BOSS); classes.put(EntityType.ENDER_PEARL, EntityClass.OTHER); classes.put(EntityType.ENDER_SIGNAL, EntityClass.OTHER); classes.put(EntityType.ENDERMAN, EntityClass.HOSTILE); classes.put(EntityType.EXPERIENCE_ORB, EntityClass.OTHER); classes.put(EntityType.FALLING_BLOCK, EntityClass.OTHER); classes.put(EntityType.FIREBALL, EntityClass.OTHER); classes.put(EntityType.FIREWORK, EntityClass.OTHER); classes.put(EntityType.FISHING_HOOK, EntityClass.OTHER); classes.put(EntityType.GHAST, EntityClass.HOSTILE); classes.put(EntityType.GIANT, EntityClass.HOSTILE); classes.put(EntityType.IRON_GOLEM, EntityClass.PEACEFUL); classes.put(EntityType.ITEM_FRAME, EntityClass.OTHER); classes.put(EntityType.LIGHTNING, EntityClass.OTHER); classes.put(EntityType.MAGMA_CUBE, EntityClass.HOSTILE); classes.put(EntityType.MINECART, EntityClass.OTHER); classes.put(EntityType.MINECART_CHEST, EntityClass.OTHER); classes.put(EntityType.MINECART_FURNACE, EntityClass.OTHER); classes.put(EntityType.MINECART_HOPPER, EntityClass.OTHER); classes.put(EntityType.MINECART_MOB_SPAWNER, EntityClass.OTHER); classes.put(EntityType.MINECART_TNT, EntityClass.OTHER); classes.put(EntityType.MUSHROOM_COW, EntityClass.PEACEFUL); classes.put(EntityType.OCELOT, EntityClass.PEACEFUL); classes.put(EntityType.PAINTING, EntityClass.OTHER); classes.put(EntityType.PIG, EntityClass.PEACEFUL); classes.put(EntityType.PIG_ZOMBIE, EntityClass.HOSTILE); classes.put(EntityType.PLAYER, EntityClass.PLAYER); classes.put(EntityType.PRIMED_TNT, EntityClass.OTHER); classes.put(EntityType.SHEEP, EntityClass.PEACEFUL); classes.put(EntityType.SILVERFISH, EntityClass.HOSTILE); classes.put(EntityType.SKELETON, EntityClass.HOSTILE); classes.put(EntityType.SLIME, EntityClass.HOSTILE); classes.put(EntityType.SMALL_FIREBALL, EntityClass.OTHER); classes.put(EntityType.SNOWBALL, EntityClass.OTHER); classes.put(EntityType.SNOWMAN, EntityClass.PEACEFUL); classes.put(EntityType.SPIDER, EntityClass.HOSTILE); classes.put(EntityType.SPLASH_POTION, EntityClass.OTHER); classes.put(EntityType.SQUID, EntityClass.PEACEFUL); classes.put(EntityType.THROWN_EXP_BOTTLE, EntityClass.OTHER); classes.put(EntityType.UNKNOWN, EntityClass.OTHER); classes.put(EntityType.VILLAGER, EntityClass.PEACEFUL); classes.put(EntityType.WEATHER, EntityClass.OTHER); classes.put(EntityType.WITCH, EntityClass.HOSTILE); classes.put(EntityType.WITHER, EntityClass.BOSS); classes.put(EntityType.WITHER_SKULL, EntityClass.OTHER); classes.put(EntityType.WOLF, EntityClass.PEACEFUL); classes.put(EntityType.ZOMBIE, EntityClass.HOSTILE); } public enum EntityClass{ HOSTILE, PLAYER, PEACEFUL, OTHER, BOSS; } private Map<DeathCause, Integer> deaths = new HashMap<DeathCause, Integer>(); private Map<Entity, Integer> kills = new HashMap<Entity, Integer>(); public int getKills(){ int amount = 0; for(Entity e : kills.keySet()){ amount = amount + kills.get(e); } return amount; } public int getKills(EntityClass type){ int amount = 0; for(Entity e : kills.keySet()){ if(classes.get(e.getType()) == type){ amount = amount + kills.get(e); } } return amount; } public int getKills(EntityType type){ int amount = 0; for(Entity e : kills.keySet()){ if(e.getType() == type){ amount = amount + kills.get(e); } } return amount; } public int getKills(String username){ int amount = 0; for(Entity e : kills.keySet()){ if(e instanceof Player && ((Player)e).getName() == username){ amount = amount + kills.get(e); } } return amount; } public int getKills(Entity entity){ if(kills.containsKey(entity)){ return kills.get(entity); } return 0; } public int getDeaths(){ int amount = 0; for(DeathCause d : deaths.keySet()){ amount = amount + deaths.get(d); } return amount; } public int getDeaths(EntityType type){ int amount = 0; for(DeathCause d : deaths.keySet()){ if(d.isEntity() && d.getEntity().getType() == type){ amount = amount + deaths.get(d); } } return amount; } public int getDeaths(EntityClass type){ int amount = 0; for(DeathCause d : deaths.keySet()){ if(d.isEntity() && classes.get(d.getEntity()) == type){ amount = amount + deaths.get(d); } } return amount; } public int getDeaths(String username){ int amount = 0; for(DeathCause d : deaths.keySet()){ if(d.isEntity() && d.getEntity() instanceof Player && ((Player)d.getEntity()).getName() == username){ amount = amount + deaths.get(d); } } return amount; } public int getDeaths(Entity entity){ int amount = 0; for(DeathCause d : deaths.keySet()){ if(d.isEntity() && d.getEntity() == entity){ amount = amount + deaths.get(d); } } return amount; } public void die(EntityDeathEvent event){ DamageCause cause = event.getEntity().getLastDamageCause().getCause(); if(cause == DamageCause.CONTACT || cause == DamageCause.ENTITY_ATTACK || cause == DamageCause.ENTITY_EXPLOSION || cause == DamageCause.PROJECTILE){ if(deaths.containsKey(new DeathCause(event.getEntity().getLastDamageCause().getEntity(), cause))){ deaths.put(new DeathCause(event.getEntity().getLastDamageCause().getEntity(), cause), deaths.get(new DeathCause(event.getEntity().getLastDamageCause().getEntity(), cause))); } else{ deaths.put(new DeathCause(event.getEntity().getLastDamageCause().getEntity(), cause), 1); } } else{ if(deaths.containsKey(new DeathCause(null, cause))){ deaths.put(new DeathCause(null, cause), deaths.get(new DeathCause(null, cause))); } else{ deaths.put(new DeathCause(null, cause), 1); } } } public void kill(EntityDeathEvent event){ if(kills.containsKey(event.getEntity())){ kills.put(event.getEntity(), kills.get(event.getEntity()) + 1); } else{ kills.put(event.getEntity(), 1); } } }
7,040
0.731818
0.72983
194
35.288658
27.525606
177
false
false
0
0
0
0
0
0
2.974227
false
false
0
ae41d5c55e0c3936794fd42ef1d96acc29936f9d
5,119,601,020,053
0aba3ca0c2da8626bed808155a854858f93b80e0
/services/swr/src/main/java/com/huaweicloud/sdk/swr/v2/SwrAsyncClient.java
122ed66357b7892c1e7b2910d02474c0dd864fcc
[ "Apache-2.0" ]
permissive
LanYus/huaweicloud-sdk-java-v3
https://github.com/LanYus/huaweicloud-sdk-java-v3
5b51e0953f5b1a8a5d38bccbaa7389222a8c0ea7
761a9c43c0ea287a927707891c529389e43e8280
refs/heads/master
2023-05-31T15:46:06.772000
2021-06-10T12:06:03
2021-06-10T12:06:03
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.huaweicloud.sdk.swr.v2; import com.huaweicloud.sdk.core.HcClient; import com.huaweicloud.sdk.core.ClientBuilder; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import com.huaweicloud.sdk.core.invoker.AsyncInvoker; import com.huaweicloud.sdk.swr.v2.model.*; public class SwrAsyncClient { protected HcClient hcClient; public SwrAsyncClient(HcClient hcClient) { this.hcClient = hcClient; } public static ClientBuilder<SwrAsyncClient> newBuilder() { return new ClientBuilder<>(SwrAsyncClient::new); } /** * 创建镜像自动同步任务 * 创建镜像自动同步任务 * * @param CreateImageSyncRepoRequest 请求对象 * @return CompletableFuture<CreateImageSyncRepoResponse> */ public CompletableFuture<CreateImageSyncRepoResponse> createImageSyncRepoAsync(CreateImageSyncRepoRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.createImageSyncRepo); } /** * 创建镜像自动同步任务 * 创建镜像自动同步任务 * * @param CreateImageSyncRepoRequest 请求对象 * @return AsyncInvoker<CreateImageSyncRepoRequest, CreateImageSyncRepoResponse> */ public AsyncInvoker<CreateImageSyncRepoRequest, CreateImageSyncRepoResponse> createImageSyncRepoAsyncInvoker(CreateImageSyncRepoRequest request) { return new AsyncInvoker<CreateImageSyncRepoRequest, CreateImageSyncRepoResponse>(request, SwrMeta.createImageSyncRepo, hcClient); } /** * 手动同步镜像 * 手动同步镜像 * * @param CreateManualImageSyncRepoRequest 请求对象 * @return CompletableFuture<CreateManualImageSyncRepoResponse> */ public CompletableFuture<CreateManualImageSyncRepoResponse> createManualImageSyncRepoAsync(CreateManualImageSyncRepoRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.createManualImageSyncRepo); } /** * 手动同步镜像 * 手动同步镜像 * * @param CreateManualImageSyncRepoRequest 请求对象 * @return AsyncInvoker<CreateManualImageSyncRepoRequest, CreateManualImageSyncRepoResponse> */ public AsyncInvoker<CreateManualImageSyncRepoRequest, CreateManualImageSyncRepoResponse> createManualImageSyncRepoAsyncInvoker(CreateManualImageSyncRepoRequest request) { return new AsyncInvoker<CreateManualImageSyncRepoRequest, CreateManualImageSyncRepoResponse>(request, SwrMeta.createManualImageSyncRepo, hcClient); } /** * 创建组织 * 创建组织 * * @param CreateNamespaceRequest 请求对象 * @return CompletableFuture<CreateNamespaceResponse> */ public CompletableFuture<CreateNamespaceResponse> createNamespaceAsync(CreateNamespaceRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.createNamespace); } /** * 创建组织 * 创建组织 * * @param CreateNamespaceRequest 请求对象 * @return AsyncInvoker<CreateNamespaceRequest, CreateNamespaceResponse> */ public AsyncInvoker<CreateNamespaceRequest, CreateNamespaceResponse> createNamespaceAsyncInvoker(CreateNamespaceRequest request) { return new AsyncInvoker<CreateNamespaceRequest, CreateNamespaceResponse>(request, SwrMeta.createNamespace, hcClient); } /** * 创建组织权限 * 创建组织权限 * * @param CreateNamespaceAuthRequest 请求对象 * @return CompletableFuture<CreateNamespaceAuthResponse> */ public CompletableFuture<CreateNamespaceAuthResponse> createNamespaceAuthAsync(CreateNamespaceAuthRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.createNamespaceAuth); } /** * 创建组织权限 * 创建组织权限 * * @param CreateNamespaceAuthRequest 请求对象 * @return AsyncInvoker<CreateNamespaceAuthRequest, CreateNamespaceAuthResponse> */ public AsyncInvoker<CreateNamespaceAuthRequest, CreateNamespaceAuthResponse> createNamespaceAuthAsyncInvoker(CreateNamespaceAuthRequest request) { return new AsyncInvoker<CreateNamespaceAuthRequest, CreateNamespaceAuthResponse>(request, SwrMeta.createNamespaceAuth, hcClient); } /** * 在组织下创建镜像仓库 * 在组织下创建镜像仓库。 * * @param CreateRepoRequest 请求对象 * @return CompletableFuture<CreateRepoResponse> */ public CompletableFuture<CreateRepoResponse> createRepoAsync(CreateRepoRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.createRepo); } /** * 在组织下创建镜像仓库 * 在组织下创建镜像仓库。 * * @param CreateRepoRequest 请求对象 * @return AsyncInvoker<CreateRepoRequest, CreateRepoResponse> */ public AsyncInvoker<CreateRepoRequest, CreateRepoResponse> createRepoAsyncInvoker(CreateRepoRequest request) { return new AsyncInvoker<CreateRepoRequest, CreateRepoResponse>(request, SwrMeta.createRepo, hcClient); } /** * 创建共享账号 * 创建共享账号。镜像上传后,您可以共享私有镜像给其他帐号,并授予下载该镜像的权限。 * * @param CreateRepoDomainsRequest 请求对象 * @return CompletableFuture<CreateRepoDomainsResponse> */ public CompletableFuture<CreateRepoDomainsResponse> createRepoDomainsAsync(CreateRepoDomainsRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.createRepoDomains); } /** * 创建共享账号 * 创建共享账号。镜像上传后,您可以共享私有镜像给其他帐号,并授予下载该镜像的权限。 * * @param CreateRepoDomainsRequest 请求对象 * @return AsyncInvoker<CreateRepoDomainsRequest, CreateRepoDomainsResponse> */ public AsyncInvoker<CreateRepoDomainsRequest, CreateRepoDomainsResponse> createRepoDomainsAsyncInvoker(CreateRepoDomainsRequest request) { return new AsyncInvoker<CreateRepoDomainsRequest, CreateRepoDomainsResponse>(request, SwrMeta.createRepoDomains, hcClient); } /** * 创建镜像老化规则 * 创建镜像老化规则 * * @param CreateRetentionRequest 请求对象 * @return CompletableFuture<CreateRetentionResponse> */ public CompletableFuture<CreateRetentionResponse> createRetentionAsync(CreateRetentionRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.createRetention); } /** * 创建镜像老化规则 * 创建镜像老化规则 * * @param CreateRetentionRequest 请求对象 * @return AsyncInvoker<CreateRetentionRequest, CreateRetentionResponse> */ public AsyncInvoker<CreateRetentionRequest, CreateRetentionResponse> createRetentionAsyncInvoker(CreateRetentionRequest request) { return new AsyncInvoker<CreateRetentionRequest, CreateRetentionResponse>(request, SwrMeta.createRetention, hcClient); } /** * 生成临时登录指令 * 调用该接口,通过获取响应消息头的X-Swr-Dockerlogin的值及响应消息体的host值,可生成临时登录指令。 * * @param CreateSecretRequest 请求对象 * @return CompletableFuture<CreateSecretResponse> */ public CompletableFuture<CreateSecretResponse> createSecretAsync(CreateSecretRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.createSecret); } /** * 生成临时登录指令 * 调用该接口,通过获取响应消息头的X-Swr-Dockerlogin的值及响应消息体的host值,可生成临时登录指令。 * * @param CreateSecretRequest 请求对象 * @return AsyncInvoker<CreateSecretRequest, CreateSecretResponse> */ public AsyncInvoker<CreateSecretRequest, CreateSecretResponse> createSecretAsyncInvoker(CreateSecretRequest request) { return new AsyncInvoker<CreateSecretRequest, CreateSecretResponse>(request, SwrMeta.createSecret, hcClient); } /** * 创建触发器 * 创建触发器 * * @param CreateTriggerRequest 请求对象 * @return CompletableFuture<CreateTriggerResponse> */ public CompletableFuture<CreateTriggerResponse> createTriggerAsync(CreateTriggerRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.createTrigger); } /** * 创建触发器 * 创建触发器 * * @param CreateTriggerRequest 请求对象 * @return AsyncInvoker<CreateTriggerRequest, CreateTriggerResponse> */ public AsyncInvoker<CreateTriggerRequest, CreateTriggerResponse> createTriggerAsyncInvoker(CreateTriggerRequest request) { return new AsyncInvoker<CreateTriggerRequest, CreateTriggerResponse>(request, SwrMeta.createTrigger, hcClient); } /** * 创建镜像权限 * 创建镜像权限 * * @param CreateUserRepositoryAuthRequest 请求对象 * @return CompletableFuture<CreateUserRepositoryAuthResponse> */ public CompletableFuture<CreateUserRepositoryAuthResponse> createUserRepositoryAuthAsync(CreateUserRepositoryAuthRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.createUserRepositoryAuth); } /** * 创建镜像权限 * 创建镜像权限 * * @param CreateUserRepositoryAuthRequest 请求对象 * @return AsyncInvoker<CreateUserRepositoryAuthRequest, CreateUserRepositoryAuthResponse> */ public AsyncInvoker<CreateUserRepositoryAuthRequest, CreateUserRepositoryAuthResponse> createUserRepositoryAuthAsyncInvoker(CreateUserRepositoryAuthRequest request) { return new AsyncInvoker<CreateUserRepositoryAuthRequest, CreateUserRepositoryAuthResponse>(request, SwrMeta.createUserRepositoryAuth, hcClient); } /** * 删除镜像自动同步任务 * 删除镜像自动同步任务 * * @param DeleteImageSyncRepoRequest 请求对象 * @return CompletableFuture<DeleteImageSyncRepoResponse> */ public CompletableFuture<DeleteImageSyncRepoResponse> deleteImageSyncRepoAsync(DeleteImageSyncRepoRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.deleteImageSyncRepo); } /** * 删除镜像自动同步任务 * 删除镜像自动同步任务 * * @param DeleteImageSyncRepoRequest 请求对象 * @return AsyncInvoker<DeleteImageSyncRepoRequest, DeleteImageSyncRepoResponse> */ public AsyncInvoker<DeleteImageSyncRepoRequest, DeleteImageSyncRepoResponse> deleteImageSyncRepoAsyncInvoker(DeleteImageSyncRepoRequest request) { return new AsyncInvoker<DeleteImageSyncRepoRequest, DeleteImageSyncRepoResponse>(request, SwrMeta.deleteImageSyncRepo, hcClient); } /** * 删除组织权限 * 删除组织权限 * * @param DeleteNamespaceAuthRequest 请求对象 * @return CompletableFuture<DeleteNamespaceAuthResponse> */ public CompletableFuture<DeleteNamespaceAuthResponse> deleteNamespaceAuthAsync(DeleteNamespaceAuthRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.deleteNamespaceAuth); } /** * 删除组织权限 * 删除组织权限 * * @param DeleteNamespaceAuthRequest 请求对象 * @return AsyncInvoker<DeleteNamespaceAuthRequest, DeleteNamespaceAuthResponse> */ public AsyncInvoker<DeleteNamespaceAuthRequest, DeleteNamespaceAuthResponse> deleteNamespaceAuthAsyncInvoker(DeleteNamespaceAuthRequest request) { return new AsyncInvoker<DeleteNamespaceAuthRequest, DeleteNamespaceAuthResponse>(request, SwrMeta.deleteNamespaceAuth, hcClient); } /** * 删除组织 * 删除组织 * * @param DeleteNamespacesRequest 请求对象 * @return CompletableFuture<DeleteNamespacesResponse> */ public CompletableFuture<DeleteNamespacesResponse> deleteNamespacesAsync(DeleteNamespacesRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.deleteNamespaces); } /** * 删除组织 * 删除组织 * * @param DeleteNamespacesRequest 请求对象 * @return AsyncInvoker<DeleteNamespacesRequest, DeleteNamespacesResponse> */ public AsyncInvoker<DeleteNamespacesRequest, DeleteNamespacesResponse> deleteNamespacesAsyncInvoker(DeleteNamespacesRequest request) { return new AsyncInvoker<DeleteNamespacesRequest, DeleteNamespacesResponse>(request, SwrMeta.deleteNamespaces, hcClient); } /** * 删除组织下的镜像仓库 * 删除组织下的镜像仓库。 * * @param DeleteRepoRequest 请求对象 * @return CompletableFuture<DeleteRepoResponse> */ public CompletableFuture<DeleteRepoResponse> deleteRepoAsync(DeleteRepoRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.deleteRepo); } /** * 删除组织下的镜像仓库 * 删除组织下的镜像仓库。 * * @param DeleteRepoRequest 请求对象 * @return AsyncInvoker<DeleteRepoRequest, DeleteRepoResponse> */ public AsyncInvoker<DeleteRepoRequest, DeleteRepoResponse> deleteRepoAsyncInvoker(DeleteRepoRequest request) { return new AsyncInvoker<DeleteRepoRequest, DeleteRepoResponse>(request, SwrMeta.deleteRepo, hcClient); } /** * 删除共享账号 * 删除共享账号 * * @param DeleteRepoDomainsRequest 请求对象 * @return CompletableFuture<DeleteRepoDomainsResponse> */ public CompletableFuture<DeleteRepoDomainsResponse> deleteRepoDomainsAsync(DeleteRepoDomainsRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.deleteRepoDomains); } /** * 删除共享账号 * 删除共享账号 * * @param DeleteRepoDomainsRequest 请求对象 * @return AsyncInvoker<DeleteRepoDomainsRequest, DeleteRepoDomainsResponse> */ public AsyncInvoker<DeleteRepoDomainsRequest, DeleteRepoDomainsResponse> deleteRepoDomainsAsyncInvoker(DeleteRepoDomainsRequest request) { return new AsyncInvoker<DeleteRepoDomainsRequest, DeleteRepoDomainsResponse>(request, SwrMeta.deleteRepoDomains, hcClient); } /** * 删除指定tag的镜像 * 删除镜像仓库中指定tag的镜像 * * @param DeleteRepoTagRequest 请求对象 * @return CompletableFuture<DeleteRepoTagResponse> */ public CompletableFuture<DeleteRepoTagResponse> deleteRepoTagAsync(DeleteRepoTagRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.deleteRepoTag); } /** * 删除指定tag的镜像 * 删除镜像仓库中指定tag的镜像 * * @param DeleteRepoTagRequest 请求对象 * @return AsyncInvoker<DeleteRepoTagRequest, DeleteRepoTagResponse> */ public AsyncInvoker<DeleteRepoTagRequest, DeleteRepoTagResponse> deleteRepoTagAsyncInvoker(DeleteRepoTagRequest request) { return new AsyncInvoker<DeleteRepoTagRequest, DeleteRepoTagResponse>(request, SwrMeta.deleteRepoTag, hcClient); } /** * 删除镜像老化规则 * 删除镜像老化规则 * * @param DeleteRetentionRequest 请求对象 * @return CompletableFuture<DeleteRetentionResponse> */ public CompletableFuture<DeleteRetentionResponse> deleteRetentionAsync(DeleteRetentionRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.deleteRetention); } /** * 删除镜像老化规则 * 删除镜像老化规则 * * @param DeleteRetentionRequest 请求对象 * @return AsyncInvoker<DeleteRetentionRequest, DeleteRetentionResponse> */ public AsyncInvoker<DeleteRetentionRequest, DeleteRetentionResponse> deleteRetentionAsyncInvoker(DeleteRetentionRequest request) { return new AsyncInvoker<DeleteRetentionRequest, DeleteRetentionResponse>(request, SwrMeta.deleteRetention, hcClient); } /** * 删除触发器 * 删除触发器 * * @param DeleteTriggerRequest 请求对象 * @return CompletableFuture<DeleteTriggerResponse> */ public CompletableFuture<DeleteTriggerResponse> deleteTriggerAsync(DeleteTriggerRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.deleteTrigger); } /** * 删除触发器 * 删除触发器 * * @param DeleteTriggerRequest 请求对象 * @return AsyncInvoker<DeleteTriggerRequest, DeleteTriggerResponse> */ public AsyncInvoker<DeleteTriggerRequest, DeleteTriggerResponse> deleteTriggerAsyncInvoker(DeleteTriggerRequest request) { return new AsyncInvoker<DeleteTriggerRequest, DeleteTriggerResponse>(request, SwrMeta.deleteTrigger, hcClient); } /** * 删除镜像权限 * 删除镜像权限 * * @param DeleteUserRepositoryAuthRequest 请求对象 * @return CompletableFuture<DeleteUserRepositoryAuthResponse> */ public CompletableFuture<DeleteUserRepositoryAuthResponse> deleteUserRepositoryAuthAsync(DeleteUserRepositoryAuthRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.deleteUserRepositoryAuth); } /** * 删除镜像权限 * 删除镜像权限 * * @param DeleteUserRepositoryAuthRequest 请求对象 * @return AsyncInvoker<DeleteUserRepositoryAuthRequest, DeleteUserRepositoryAuthResponse> */ public AsyncInvoker<DeleteUserRepositoryAuthRequest, DeleteUserRepositoryAuthResponse> deleteUserRepositoryAuthAsyncInvoker(DeleteUserRepositoryAuthRequest request) { return new AsyncInvoker<DeleteUserRepositoryAuthRequest, DeleteUserRepositoryAuthResponse>(request, SwrMeta.deleteUserRepositoryAuth, hcClient); } /** * 获取镜像自动同步任务列表 * 获取镜像自动同步任务列表 * * @param ListImageAutoSyncReposDetailsRequest 请求对象 * @return CompletableFuture<ListImageAutoSyncReposDetailsResponse> */ public CompletableFuture<ListImageAutoSyncReposDetailsResponse> listImageAutoSyncReposDetailsAsync(ListImageAutoSyncReposDetailsRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.listImageAutoSyncReposDetails); } /** * 获取镜像自动同步任务列表 * 获取镜像自动同步任务列表 * * @param ListImageAutoSyncReposDetailsRequest 请求对象 * @return AsyncInvoker<ListImageAutoSyncReposDetailsRequest, ListImageAutoSyncReposDetailsResponse> */ public AsyncInvoker<ListImageAutoSyncReposDetailsRequest, ListImageAutoSyncReposDetailsResponse> listImageAutoSyncReposDetailsAsyncInvoker(ListImageAutoSyncReposDetailsRequest request) { return new AsyncInvoker<ListImageAutoSyncReposDetailsRequest, ListImageAutoSyncReposDetailsResponse>(request, SwrMeta.listImageAutoSyncReposDetails, hcClient); } /** * 查询组织列表 * 查询组织列表 * * @param ListNamespacesRequest 请求对象 * @return CompletableFuture<ListNamespacesResponse> */ public CompletableFuture<ListNamespacesResponse> listNamespacesAsync(ListNamespacesRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.listNamespaces); } /** * 查询组织列表 * 查询组织列表 * * @param ListNamespacesRequest 请求对象 * @return AsyncInvoker<ListNamespacesRequest, ListNamespacesResponse> */ public AsyncInvoker<ListNamespacesRequest, ListNamespacesResponse> listNamespacesAsyncInvoker(ListNamespacesRequest request) { return new AsyncInvoker<ListNamespacesRequest, ListNamespacesResponse>(request, SwrMeta.listNamespaces, hcClient); } /** * 获取共享账号列表 * 获取共享账号列表 * * @param ListRepoDomainsRequest 请求对象 * @return CompletableFuture<ListRepoDomainsResponse> */ public CompletableFuture<ListRepoDomainsResponse> listRepoDomainsAsync(ListRepoDomainsRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.listRepoDomains); } /** * 获取共享账号列表 * 获取共享账号列表 * * @param ListRepoDomainsRequest 请求对象 * @return AsyncInvoker<ListRepoDomainsRequest, ListRepoDomainsResponse> */ public AsyncInvoker<ListRepoDomainsRequest, ListRepoDomainsResponse> listRepoDomainsAsyncInvoker(ListRepoDomainsRequest request) { return new AsyncInvoker<ListRepoDomainsRequest, ListRepoDomainsResponse>(request, SwrMeta.listRepoDomains, hcClient); } /** * 查询镜像列表 * 查询镜像列表 * * @param ListReposDetailsRequest 请求对象 * @return CompletableFuture<ListReposDetailsResponse> */ public CompletableFuture<ListReposDetailsResponse> listReposDetailsAsync(ListReposDetailsRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.listReposDetails); } /** * 查询镜像列表 * 查询镜像列表 * * @param ListReposDetailsRequest 请求对象 * @return AsyncInvoker<ListReposDetailsRequest, ListReposDetailsResponse> */ public AsyncInvoker<ListReposDetailsRequest, ListReposDetailsResponse> listReposDetailsAsyncInvoker(ListReposDetailsRequest request) { return new AsyncInvoker<ListReposDetailsRequest, ListReposDetailsResponse>(request, SwrMeta.listReposDetails, hcClient); } /** * 查询镜像tag列表 * 查询镜像tag列表 * * @param ListRepositoryTagsRequest 请求对象 * @return CompletableFuture<ListRepositoryTagsResponse> */ public CompletableFuture<ListRepositoryTagsResponse> listRepositoryTagsAsync(ListRepositoryTagsRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.listRepositoryTags); } /** * 查询镜像tag列表 * 查询镜像tag列表 * * @param ListRepositoryTagsRequest 请求对象 * @return AsyncInvoker<ListRepositoryTagsRequest, ListRepositoryTagsResponse> */ public AsyncInvoker<ListRepositoryTagsRequest, ListRepositoryTagsResponse> listRepositoryTagsAsyncInvoker(ListRepositoryTagsRequest request) { return new AsyncInvoker<ListRepositoryTagsRequest, ListRepositoryTagsResponse>(request, SwrMeta.listRepositoryTags, hcClient); } /** * 获取镜像老化记录 * 获取镜像老化记录 * * @param ListRetentionHistoriesRequest 请求对象 * @return CompletableFuture<ListRetentionHistoriesResponse> */ public CompletableFuture<ListRetentionHistoriesResponse> listRetentionHistoriesAsync(ListRetentionHistoriesRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.listRetentionHistories); } /** * 获取镜像老化记录 * 获取镜像老化记录 * * @param ListRetentionHistoriesRequest 请求对象 * @return AsyncInvoker<ListRetentionHistoriesRequest, ListRetentionHistoriesResponse> */ public AsyncInvoker<ListRetentionHistoriesRequest, ListRetentionHistoriesResponse> listRetentionHistoriesAsyncInvoker(ListRetentionHistoriesRequest request) { return new AsyncInvoker<ListRetentionHistoriesRequest, ListRetentionHistoriesResponse>(request, SwrMeta.listRetentionHistories, hcClient); } /** * 获取镜像老化规则列表 * 获取镜像老化规则列表 * * @param ListRetentionsRequest 请求对象 * @return CompletableFuture<ListRetentionsResponse> */ public CompletableFuture<ListRetentionsResponse> listRetentionsAsync(ListRetentionsRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.listRetentions); } /** * 获取镜像老化规则列表 * 获取镜像老化规则列表 * * @param ListRetentionsRequest 请求对象 * @return AsyncInvoker<ListRetentionsRequest, ListRetentionsResponse> */ public AsyncInvoker<ListRetentionsRequest, ListRetentionsResponse> listRetentionsAsyncInvoker(ListRetentionsRequest request) { return new AsyncInvoker<ListRetentionsRequest, ListRetentionsResponse>(request, SwrMeta.listRetentions, hcClient); } /** * 查询共享镜像列表 * 查询共享镜像列表 * * @param ListSharedReposDetailsRequest 请求对象 * @return CompletableFuture<ListSharedReposDetailsResponse> */ public CompletableFuture<ListSharedReposDetailsResponse> listSharedReposDetailsAsync(ListSharedReposDetailsRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.listSharedReposDetails); } /** * 查询共享镜像列表 * 查询共享镜像列表 * * @param ListSharedReposDetailsRequest 请求对象 * @return AsyncInvoker<ListSharedReposDetailsRequest, ListSharedReposDetailsResponse> */ public AsyncInvoker<ListSharedReposDetailsRequest, ListSharedReposDetailsResponse> listSharedReposDetailsAsyncInvoker(ListSharedReposDetailsRequest request) { return new AsyncInvoker<ListSharedReposDetailsRequest, ListSharedReposDetailsResponse>(request, SwrMeta.listSharedReposDetails, hcClient); } /** * 获取镜像仓库下的触发器列表 * 获取镜像仓库下的触发器列表 * * @param ListTriggersDetailsRequest 请求对象 * @return CompletableFuture<ListTriggersDetailsResponse> */ public CompletableFuture<ListTriggersDetailsResponse> listTriggersDetailsAsync(ListTriggersDetailsRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.listTriggersDetails); } /** * 获取镜像仓库下的触发器列表 * 获取镜像仓库下的触发器列表 * * @param ListTriggersDetailsRequest 请求对象 * @return AsyncInvoker<ListTriggersDetailsRequest, ListTriggersDetailsResponse> */ public AsyncInvoker<ListTriggersDetailsRequest, ListTriggersDetailsResponse> listTriggersDetailsAsyncInvoker(ListTriggersDetailsRequest request) { return new AsyncInvoker<ListTriggersDetailsRequest, ListTriggersDetailsResponse>(request, SwrMeta.listTriggersDetails, hcClient); } /** * 判断共享账号是否存在 * 判断共享租户是否存在 * * @param ShowAccessDomainRequest 请求对象 * @return CompletableFuture<ShowAccessDomainResponse> */ public CompletableFuture<ShowAccessDomainResponse> showAccessDomainAsync(ShowAccessDomainRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.showAccessDomain); } /** * 判断共享账号是否存在 * 判断共享租户是否存在 * * @param ShowAccessDomainRequest 请求对象 * @return AsyncInvoker<ShowAccessDomainRequest, ShowAccessDomainResponse> */ public AsyncInvoker<ShowAccessDomainRequest, ShowAccessDomainResponse> showAccessDomainAsyncInvoker(ShowAccessDomainRequest request) { return new AsyncInvoker<ShowAccessDomainRequest, ShowAccessDomainResponse>(request, SwrMeta.showAccessDomain, hcClient); } /** * 获取组织详情 * 获取组织详情 * * @param ShowNamespaceRequest 请求对象 * @return CompletableFuture<ShowNamespaceResponse> */ public CompletableFuture<ShowNamespaceResponse> showNamespaceAsync(ShowNamespaceRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.showNamespace); } /** * 获取组织详情 * 获取组织详情 * * @param ShowNamespaceRequest 请求对象 * @return AsyncInvoker<ShowNamespaceRequest, ShowNamespaceResponse> */ public AsyncInvoker<ShowNamespaceRequest, ShowNamespaceResponse> showNamespaceAsyncInvoker(ShowNamespaceRequest request) { return new AsyncInvoker<ShowNamespaceRequest, ShowNamespaceResponse>(request, SwrMeta.showNamespace, hcClient); } /** * 查询组织权限 * 查询组织权限 * * @param ShowNamespaceAuthRequest 请求对象 * @return CompletableFuture<ShowNamespaceAuthResponse> */ public CompletableFuture<ShowNamespaceAuthResponse> showNamespaceAuthAsync(ShowNamespaceAuthRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.showNamespaceAuth); } /** * 查询组织权限 * 查询组织权限 * * @param ShowNamespaceAuthRequest 请求对象 * @return AsyncInvoker<ShowNamespaceAuthRequest, ShowNamespaceAuthResponse> */ public AsyncInvoker<ShowNamespaceAuthRequest, ShowNamespaceAuthResponse> showNamespaceAuthAsyncInvoker(ShowNamespaceAuthRequest request) { return new AsyncInvoker<ShowNamespaceAuthRequest, ShowNamespaceAuthResponse>(request, SwrMeta.showNamespaceAuth, hcClient); } /** * 查询镜像概要信息 * 查询镜像概要信息 * * @param ShowRepositoryRequest 请求对象 * @return CompletableFuture<ShowRepositoryResponse> */ public CompletableFuture<ShowRepositoryResponse> showRepositoryAsync(ShowRepositoryRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.showRepository); } /** * 查询镜像概要信息 * 查询镜像概要信息 * * @param ShowRepositoryRequest 请求对象 * @return AsyncInvoker<ShowRepositoryRequest, ShowRepositoryResponse> */ public AsyncInvoker<ShowRepositoryRequest, ShowRepositoryResponse> showRepositoryAsyncInvoker(ShowRepositoryRequest request) { return new AsyncInvoker<ShowRepositoryRequest, ShowRepositoryResponse>(request, SwrMeta.showRepository, hcClient); } /** * 获取镜像老化规则记录 * 获取镜像老化规则记录 * * @param ShowRetentionRequest 请求对象 * @return CompletableFuture<ShowRetentionResponse> */ public CompletableFuture<ShowRetentionResponse> showRetentionAsync(ShowRetentionRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.showRetention); } /** * 获取镜像老化规则记录 * 获取镜像老化规则记录 * * @param ShowRetentionRequest 请求对象 * @return AsyncInvoker<ShowRetentionRequest, ShowRetentionResponse> */ public AsyncInvoker<ShowRetentionRequest, ShowRetentionResponse> showRetentionAsyncInvoker(ShowRetentionRequest request) { return new AsyncInvoker<ShowRetentionRequest, ShowRetentionResponse>(request, SwrMeta.showRetention, hcClient); } /** * 获取镜像同步任务信息 * 获取镜像同步任务信息 * * @param ShowSyncJobRequest 请求对象 * @return CompletableFuture<ShowSyncJobResponse> */ public CompletableFuture<ShowSyncJobResponse> showSyncJobAsync(ShowSyncJobRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.showSyncJob); } /** * 获取镜像同步任务信息 * 获取镜像同步任务信息 * * @param ShowSyncJobRequest 请求对象 * @return AsyncInvoker<ShowSyncJobRequest, ShowSyncJobResponse> */ public AsyncInvoker<ShowSyncJobRequest, ShowSyncJobResponse> showSyncJobAsyncInvoker(ShowSyncJobRequest request) { return new AsyncInvoker<ShowSyncJobRequest, ShowSyncJobResponse>(request, SwrMeta.showSyncJob, hcClient); } /** * 获取触发器详情 * 获取触发器详情 * * @param ShowTriggerRequest 请求对象 * @return CompletableFuture<ShowTriggerResponse> */ public CompletableFuture<ShowTriggerResponse> showTriggerAsync(ShowTriggerRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.showTrigger); } /** * 获取触发器详情 * 获取触发器详情 * * @param ShowTriggerRequest 请求对象 * @return AsyncInvoker<ShowTriggerRequest, ShowTriggerResponse> */ public AsyncInvoker<ShowTriggerRequest, ShowTriggerResponse> showTriggerAsyncInvoker(ShowTriggerRequest request) { return new AsyncInvoker<ShowTriggerRequest, ShowTriggerResponse>(request, SwrMeta.showTrigger, hcClient); } /** * 查询镜像权限 * 查询镜像权限 * * @param ShowUserRepositoryAuthRequest 请求对象 * @return CompletableFuture<ShowUserRepositoryAuthResponse> */ public CompletableFuture<ShowUserRepositoryAuthResponse> showUserRepositoryAuthAsync(ShowUserRepositoryAuthRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.showUserRepositoryAuth); } /** * 查询镜像权限 * 查询镜像权限 * * @param ShowUserRepositoryAuthRequest 请求对象 * @return AsyncInvoker<ShowUserRepositoryAuthRequest, ShowUserRepositoryAuthResponse> */ public AsyncInvoker<ShowUserRepositoryAuthRequest, ShowUserRepositoryAuthResponse> showUserRepositoryAuthAsyncInvoker(ShowUserRepositoryAuthRequest request) { return new AsyncInvoker<ShowUserRepositoryAuthRequest, ShowUserRepositoryAuthResponse>(request, SwrMeta.showUserRepositoryAuth, hcClient); } /** * 更新组织权限 * 更新组织权限 * * @param UpdateNamespaceAuthRequest 请求对象 * @return CompletableFuture<UpdateNamespaceAuthResponse> */ public CompletableFuture<UpdateNamespaceAuthResponse> updateNamespaceAuthAsync(UpdateNamespaceAuthRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.updateNamespaceAuth); } /** * 更新组织权限 * 更新组织权限 * * @param UpdateNamespaceAuthRequest 请求对象 * @return AsyncInvoker<UpdateNamespaceAuthRequest, UpdateNamespaceAuthResponse> */ public AsyncInvoker<UpdateNamespaceAuthRequest, UpdateNamespaceAuthResponse> updateNamespaceAuthAsyncInvoker(UpdateNamespaceAuthRequest request) { return new AsyncInvoker<UpdateNamespaceAuthRequest, UpdateNamespaceAuthResponse>(request, SwrMeta.updateNamespaceAuth, hcClient); } /** * 更新镜像仓库的概要信息 * 更新租户命名空间下的镜像概要信息,包括镜像类型、是否公有、描述信息 * * @param UpdateRepoRequest 请求对象 * @return CompletableFuture<UpdateRepoResponse> */ public CompletableFuture<UpdateRepoResponse> updateRepoAsync(UpdateRepoRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.updateRepo); } /** * 更新镜像仓库的概要信息 * 更新租户命名空间下的镜像概要信息,包括镜像类型、是否公有、描述信息 * * @param UpdateRepoRequest 请求对象 * @return AsyncInvoker<UpdateRepoRequest, UpdateRepoResponse> */ public AsyncInvoker<UpdateRepoRequest, UpdateRepoResponse> updateRepoAsyncInvoker(UpdateRepoRequest request) { return new AsyncInvoker<UpdateRepoRequest, UpdateRepoResponse>(request, SwrMeta.updateRepo, hcClient); } /** * 更新共享账号 * 更新共享账号 * * @param UpdateRepoDomainsRequest 请求对象 * @return CompletableFuture<UpdateRepoDomainsResponse> */ public CompletableFuture<UpdateRepoDomainsResponse> updateRepoDomainsAsync(UpdateRepoDomainsRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.updateRepoDomains); } /** * 更新共享账号 * 更新共享账号 * * @param UpdateRepoDomainsRequest 请求对象 * @return AsyncInvoker<UpdateRepoDomainsRequest, UpdateRepoDomainsResponse> */ public AsyncInvoker<UpdateRepoDomainsRequest, UpdateRepoDomainsResponse> updateRepoDomainsAsyncInvoker(UpdateRepoDomainsRequest request) { return new AsyncInvoker<UpdateRepoDomainsRequest, UpdateRepoDomainsResponse>(request, SwrMeta.updateRepoDomains, hcClient); } /** * 修改镜像老化规则 * 修改镜像老化规则 * * @param UpdateRetentionRequest 请求对象 * @return CompletableFuture<UpdateRetentionResponse> */ public CompletableFuture<UpdateRetentionResponse> updateRetentionAsync(UpdateRetentionRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.updateRetention); } /** * 修改镜像老化规则 * 修改镜像老化规则 * * @param UpdateRetentionRequest 请求对象 * @return AsyncInvoker<UpdateRetentionRequest, UpdateRetentionResponse> */ public AsyncInvoker<UpdateRetentionRequest, UpdateRetentionResponse> updateRetentionAsyncInvoker(UpdateRetentionRequest request) { return new AsyncInvoker<UpdateRetentionRequest, UpdateRetentionResponse>(request, SwrMeta.updateRetention, hcClient); } /** * 更新触发器配置 * 更新触发器配置 * * @param UpdateTriggerRequest 请求对象 * @return CompletableFuture<UpdateTriggerResponse> */ public CompletableFuture<UpdateTriggerResponse> updateTriggerAsync(UpdateTriggerRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.updateTrigger); } /** * 更新触发器配置 * 更新触发器配置 * * @param UpdateTriggerRequest 请求对象 * @return AsyncInvoker<UpdateTriggerRequest, UpdateTriggerResponse> */ public AsyncInvoker<UpdateTriggerRequest, UpdateTriggerResponse> updateTriggerAsyncInvoker(UpdateTriggerRequest request) { return new AsyncInvoker<UpdateTriggerRequest, UpdateTriggerResponse>(request, SwrMeta.updateTrigger, hcClient); } /** * 更新镜像权限 * 更新镜像权限 * * @param UpdateUserRepositoryAuthRequest 请求对象 * @return CompletableFuture<UpdateUserRepositoryAuthResponse> */ public CompletableFuture<UpdateUserRepositoryAuthResponse> updateUserRepositoryAuthAsync(UpdateUserRepositoryAuthRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.updateUserRepositoryAuth); } /** * 更新镜像权限 * 更新镜像权限 * * @param UpdateUserRepositoryAuthRequest 请求对象 * @return AsyncInvoker<UpdateUserRepositoryAuthRequest, UpdateUserRepositoryAuthResponse> */ public AsyncInvoker<UpdateUserRepositoryAuthRequest, UpdateUserRepositoryAuthResponse> updateUserRepositoryAuthAsyncInvoker(UpdateUserRepositoryAuthRequest request) { return new AsyncInvoker<UpdateUserRepositoryAuthRequest, UpdateUserRepositoryAuthResponse>(request, SwrMeta.updateUserRepositoryAuth, hcClient); } /** * 查询所有API版本信息 * 查询所有API版本信息 * * @param ListApiVersionsRequest 请求对象 * @return CompletableFuture<ListApiVersionsResponse> */ public CompletableFuture<ListApiVersionsResponse> listApiVersionsAsync(ListApiVersionsRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.listApiVersions); } /** * 查询所有API版本信息 * 查询所有API版本信息 * * @param ListApiVersionsRequest 请求对象 * @return AsyncInvoker<ListApiVersionsRequest, ListApiVersionsResponse> */ public AsyncInvoker<ListApiVersionsRequest, ListApiVersionsResponse> listApiVersionsAsyncInvoker(ListApiVersionsRequest request) { return new AsyncInvoker<ListApiVersionsRequest, ListApiVersionsResponse>(request, SwrMeta.listApiVersions, hcClient); } /** * 查询指定API版本信息 * 查询指定API版本信息 * * @param ShowApiVersionRequest 请求对象 * @return CompletableFuture<ShowApiVersionResponse> */ public CompletableFuture<ShowApiVersionResponse> showApiVersionAsync(ShowApiVersionRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.showApiVersion); } /** * 查询指定API版本信息 * 查询指定API版本信息 * * @param ShowApiVersionRequest 请求对象 * @return AsyncInvoker<ShowApiVersionRequest, ShowApiVersionResponse> */ public AsyncInvoker<ShowApiVersionRequest, ShowApiVersionResponse> showApiVersionAsyncInvoker(ShowApiVersionRequest request) { return new AsyncInvoker<ShowApiVersionRequest, ShowApiVersionResponse>(request, SwrMeta.showApiVersion, hcClient); } }
UTF-8
Java
40,258
java
SwrAsyncClient.java
Java
[]
null
[]
package com.huaweicloud.sdk.swr.v2; import com.huaweicloud.sdk.core.HcClient; import com.huaweicloud.sdk.core.ClientBuilder; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import com.huaweicloud.sdk.core.invoker.AsyncInvoker; import com.huaweicloud.sdk.swr.v2.model.*; public class SwrAsyncClient { protected HcClient hcClient; public SwrAsyncClient(HcClient hcClient) { this.hcClient = hcClient; } public static ClientBuilder<SwrAsyncClient> newBuilder() { return new ClientBuilder<>(SwrAsyncClient::new); } /** * 创建镜像自动同步任务 * 创建镜像自动同步任务 * * @param CreateImageSyncRepoRequest 请求对象 * @return CompletableFuture<CreateImageSyncRepoResponse> */ public CompletableFuture<CreateImageSyncRepoResponse> createImageSyncRepoAsync(CreateImageSyncRepoRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.createImageSyncRepo); } /** * 创建镜像自动同步任务 * 创建镜像自动同步任务 * * @param CreateImageSyncRepoRequest 请求对象 * @return AsyncInvoker<CreateImageSyncRepoRequest, CreateImageSyncRepoResponse> */ public AsyncInvoker<CreateImageSyncRepoRequest, CreateImageSyncRepoResponse> createImageSyncRepoAsyncInvoker(CreateImageSyncRepoRequest request) { return new AsyncInvoker<CreateImageSyncRepoRequest, CreateImageSyncRepoResponse>(request, SwrMeta.createImageSyncRepo, hcClient); } /** * 手动同步镜像 * 手动同步镜像 * * @param CreateManualImageSyncRepoRequest 请求对象 * @return CompletableFuture<CreateManualImageSyncRepoResponse> */ public CompletableFuture<CreateManualImageSyncRepoResponse> createManualImageSyncRepoAsync(CreateManualImageSyncRepoRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.createManualImageSyncRepo); } /** * 手动同步镜像 * 手动同步镜像 * * @param CreateManualImageSyncRepoRequest 请求对象 * @return AsyncInvoker<CreateManualImageSyncRepoRequest, CreateManualImageSyncRepoResponse> */ public AsyncInvoker<CreateManualImageSyncRepoRequest, CreateManualImageSyncRepoResponse> createManualImageSyncRepoAsyncInvoker(CreateManualImageSyncRepoRequest request) { return new AsyncInvoker<CreateManualImageSyncRepoRequest, CreateManualImageSyncRepoResponse>(request, SwrMeta.createManualImageSyncRepo, hcClient); } /** * 创建组织 * 创建组织 * * @param CreateNamespaceRequest 请求对象 * @return CompletableFuture<CreateNamespaceResponse> */ public CompletableFuture<CreateNamespaceResponse> createNamespaceAsync(CreateNamespaceRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.createNamespace); } /** * 创建组织 * 创建组织 * * @param CreateNamespaceRequest 请求对象 * @return AsyncInvoker<CreateNamespaceRequest, CreateNamespaceResponse> */ public AsyncInvoker<CreateNamespaceRequest, CreateNamespaceResponse> createNamespaceAsyncInvoker(CreateNamespaceRequest request) { return new AsyncInvoker<CreateNamespaceRequest, CreateNamespaceResponse>(request, SwrMeta.createNamespace, hcClient); } /** * 创建组织权限 * 创建组织权限 * * @param CreateNamespaceAuthRequest 请求对象 * @return CompletableFuture<CreateNamespaceAuthResponse> */ public CompletableFuture<CreateNamespaceAuthResponse> createNamespaceAuthAsync(CreateNamespaceAuthRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.createNamespaceAuth); } /** * 创建组织权限 * 创建组织权限 * * @param CreateNamespaceAuthRequest 请求对象 * @return AsyncInvoker<CreateNamespaceAuthRequest, CreateNamespaceAuthResponse> */ public AsyncInvoker<CreateNamespaceAuthRequest, CreateNamespaceAuthResponse> createNamespaceAuthAsyncInvoker(CreateNamespaceAuthRequest request) { return new AsyncInvoker<CreateNamespaceAuthRequest, CreateNamespaceAuthResponse>(request, SwrMeta.createNamespaceAuth, hcClient); } /** * 在组织下创建镜像仓库 * 在组织下创建镜像仓库。 * * @param CreateRepoRequest 请求对象 * @return CompletableFuture<CreateRepoResponse> */ public CompletableFuture<CreateRepoResponse> createRepoAsync(CreateRepoRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.createRepo); } /** * 在组织下创建镜像仓库 * 在组织下创建镜像仓库。 * * @param CreateRepoRequest 请求对象 * @return AsyncInvoker<CreateRepoRequest, CreateRepoResponse> */ public AsyncInvoker<CreateRepoRequest, CreateRepoResponse> createRepoAsyncInvoker(CreateRepoRequest request) { return new AsyncInvoker<CreateRepoRequest, CreateRepoResponse>(request, SwrMeta.createRepo, hcClient); } /** * 创建共享账号 * 创建共享账号。镜像上传后,您可以共享私有镜像给其他帐号,并授予下载该镜像的权限。 * * @param CreateRepoDomainsRequest 请求对象 * @return CompletableFuture<CreateRepoDomainsResponse> */ public CompletableFuture<CreateRepoDomainsResponse> createRepoDomainsAsync(CreateRepoDomainsRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.createRepoDomains); } /** * 创建共享账号 * 创建共享账号。镜像上传后,您可以共享私有镜像给其他帐号,并授予下载该镜像的权限。 * * @param CreateRepoDomainsRequest 请求对象 * @return AsyncInvoker<CreateRepoDomainsRequest, CreateRepoDomainsResponse> */ public AsyncInvoker<CreateRepoDomainsRequest, CreateRepoDomainsResponse> createRepoDomainsAsyncInvoker(CreateRepoDomainsRequest request) { return new AsyncInvoker<CreateRepoDomainsRequest, CreateRepoDomainsResponse>(request, SwrMeta.createRepoDomains, hcClient); } /** * 创建镜像老化规则 * 创建镜像老化规则 * * @param CreateRetentionRequest 请求对象 * @return CompletableFuture<CreateRetentionResponse> */ public CompletableFuture<CreateRetentionResponse> createRetentionAsync(CreateRetentionRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.createRetention); } /** * 创建镜像老化规则 * 创建镜像老化规则 * * @param CreateRetentionRequest 请求对象 * @return AsyncInvoker<CreateRetentionRequest, CreateRetentionResponse> */ public AsyncInvoker<CreateRetentionRequest, CreateRetentionResponse> createRetentionAsyncInvoker(CreateRetentionRequest request) { return new AsyncInvoker<CreateRetentionRequest, CreateRetentionResponse>(request, SwrMeta.createRetention, hcClient); } /** * 生成临时登录指令 * 调用该接口,通过获取响应消息头的X-Swr-Dockerlogin的值及响应消息体的host值,可生成临时登录指令。 * * @param CreateSecretRequest 请求对象 * @return CompletableFuture<CreateSecretResponse> */ public CompletableFuture<CreateSecretResponse> createSecretAsync(CreateSecretRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.createSecret); } /** * 生成临时登录指令 * 调用该接口,通过获取响应消息头的X-Swr-Dockerlogin的值及响应消息体的host值,可生成临时登录指令。 * * @param CreateSecretRequest 请求对象 * @return AsyncInvoker<CreateSecretRequest, CreateSecretResponse> */ public AsyncInvoker<CreateSecretRequest, CreateSecretResponse> createSecretAsyncInvoker(CreateSecretRequest request) { return new AsyncInvoker<CreateSecretRequest, CreateSecretResponse>(request, SwrMeta.createSecret, hcClient); } /** * 创建触发器 * 创建触发器 * * @param CreateTriggerRequest 请求对象 * @return CompletableFuture<CreateTriggerResponse> */ public CompletableFuture<CreateTriggerResponse> createTriggerAsync(CreateTriggerRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.createTrigger); } /** * 创建触发器 * 创建触发器 * * @param CreateTriggerRequest 请求对象 * @return AsyncInvoker<CreateTriggerRequest, CreateTriggerResponse> */ public AsyncInvoker<CreateTriggerRequest, CreateTriggerResponse> createTriggerAsyncInvoker(CreateTriggerRequest request) { return new AsyncInvoker<CreateTriggerRequest, CreateTriggerResponse>(request, SwrMeta.createTrigger, hcClient); } /** * 创建镜像权限 * 创建镜像权限 * * @param CreateUserRepositoryAuthRequest 请求对象 * @return CompletableFuture<CreateUserRepositoryAuthResponse> */ public CompletableFuture<CreateUserRepositoryAuthResponse> createUserRepositoryAuthAsync(CreateUserRepositoryAuthRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.createUserRepositoryAuth); } /** * 创建镜像权限 * 创建镜像权限 * * @param CreateUserRepositoryAuthRequest 请求对象 * @return AsyncInvoker<CreateUserRepositoryAuthRequest, CreateUserRepositoryAuthResponse> */ public AsyncInvoker<CreateUserRepositoryAuthRequest, CreateUserRepositoryAuthResponse> createUserRepositoryAuthAsyncInvoker(CreateUserRepositoryAuthRequest request) { return new AsyncInvoker<CreateUserRepositoryAuthRequest, CreateUserRepositoryAuthResponse>(request, SwrMeta.createUserRepositoryAuth, hcClient); } /** * 删除镜像自动同步任务 * 删除镜像自动同步任务 * * @param DeleteImageSyncRepoRequest 请求对象 * @return CompletableFuture<DeleteImageSyncRepoResponse> */ public CompletableFuture<DeleteImageSyncRepoResponse> deleteImageSyncRepoAsync(DeleteImageSyncRepoRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.deleteImageSyncRepo); } /** * 删除镜像自动同步任务 * 删除镜像自动同步任务 * * @param DeleteImageSyncRepoRequest 请求对象 * @return AsyncInvoker<DeleteImageSyncRepoRequest, DeleteImageSyncRepoResponse> */ public AsyncInvoker<DeleteImageSyncRepoRequest, DeleteImageSyncRepoResponse> deleteImageSyncRepoAsyncInvoker(DeleteImageSyncRepoRequest request) { return new AsyncInvoker<DeleteImageSyncRepoRequest, DeleteImageSyncRepoResponse>(request, SwrMeta.deleteImageSyncRepo, hcClient); } /** * 删除组织权限 * 删除组织权限 * * @param DeleteNamespaceAuthRequest 请求对象 * @return CompletableFuture<DeleteNamespaceAuthResponse> */ public CompletableFuture<DeleteNamespaceAuthResponse> deleteNamespaceAuthAsync(DeleteNamespaceAuthRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.deleteNamespaceAuth); } /** * 删除组织权限 * 删除组织权限 * * @param DeleteNamespaceAuthRequest 请求对象 * @return AsyncInvoker<DeleteNamespaceAuthRequest, DeleteNamespaceAuthResponse> */ public AsyncInvoker<DeleteNamespaceAuthRequest, DeleteNamespaceAuthResponse> deleteNamespaceAuthAsyncInvoker(DeleteNamespaceAuthRequest request) { return new AsyncInvoker<DeleteNamespaceAuthRequest, DeleteNamespaceAuthResponse>(request, SwrMeta.deleteNamespaceAuth, hcClient); } /** * 删除组织 * 删除组织 * * @param DeleteNamespacesRequest 请求对象 * @return CompletableFuture<DeleteNamespacesResponse> */ public CompletableFuture<DeleteNamespacesResponse> deleteNamespacesAsync(DeleteNamespacesRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.deleteNamespaces); } /** * 删除组织 * 删除组织 * * @param DeleteNamespacesRequest 请求对象 * @return AsyncInvoker<DeleteNamespacesRequest, DeleteNamespacesResponse> */ public AsyncInvoker<DeleteNamespacesRequest, DeleteNamespacesResponse> deleteNamespacesAsyncInvoker(DeleteNamespacesRequest request) { return new AsyncInvoker<DeleteNamespacesRequest, DeleteNamespacesResponse>(request, SwrMeta.deleteNamespaces, hcClient); } /** * 删除组织下的镜像仓库 * 删除组织下的镜像仓库。 * * @param DeleteRepoRequest 请求对象 * @return CompletableFuture<DeleteRepoResponse> */ public CompletableFuture<DeleteRepoResponse> deleteRepoAsync(DeleteRepoRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.deleteRepo); } /** * 删除组织下的镜像仓库 * 删除组织下的镜像仓库。 * * @param DeleteRepoRequest 请求对象 * @return AsyncInvoker<DeleteRepoRequest, DeleteRepoResponse> */ public AsyncInvoker<DeleteRepoRequest, DeleteRepoResponse> deleteRepoAsyncInvoker(DeleteRepoRequest request) { return new AsyncInvoker<DeleteRepoRequest, DeleteRepoResponse>(request, SwrMeta.deleteRepo, hcClient); } /** * 删除共享账号 * 删除共享账号 * * @param DeleteRepoDomainsRequest 请求对象 * @return CompletableFuture<DeleteRepoDomainsResponse> */ public CompletableFuture<DeleteRepoDomainsResponse> deleteRepoDomainsAsync(DeleteRepoDomainsRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.deleteRepoDomains); } /** * 删除共享账号 * 删除共享账号 * * @param DeleteRepoDomainsRequest 请求对象 * @return AsyncInvoker<DeleteRepoDomainsRequest, DeleteRepoDomainsResponse> */ public AsyncInvoker<DeleteRepoDomainsRequest, DeleteRepoDomainsResponse> deleteRepoDomainsAsyncInvoker(DeleteRepoDomainsRequest request) { return new AsyncInvoker<DeleteRepoDomainsRequest, DeleteRepoDomainsResponse>(request, SwrMeta.deleteRepoDomains, hcClient); } /** * 删除指定tag的镜像 * 删除镜像仓库中指定tag的镜像 * * @param DeleteRepoTagRequest 请求对象 * @return CompletableFuture<DeleteRepoTagResponse> */ public CompletableFuture<DeleteRepoTagResponse> deleteRepoTagAsync(DeleteRepoTagRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.deleteRepoTag); } /** * 删除指定tag的镜像 * 删除镜像仓库中指定tag的镜像 * * @param DeleteRepoTagRequest 请求对象 * @return AsyncInvoker<DeleteRepoTagRequest, DeleteRepoTagResponse> */ public AsyncInvoker<DeleteRepoTagRequest, DeleteRepoTagResponse> deleteRepoTagAsyncInvoker(DeleteRepoTagRequest request) { return new AsyncInvoker<DeleteRepoTagRequest, DeleteRepoTagResponse>(request, SwrMeta.deleteRepoTag, hcClient); } /** * 删除镜像老化规则 * 删除镜像老化规则 * * @param DeleteRetentionRequest 请求对象 * @return CompletableFuture<DeleteRetentionResponse> */ public CompletableFuture<DeleteRetentionResponse> deleteRetentionAsync(DeleteRetentionRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.deleteRetention); } /** * 删除镜像老化规则 * 删除镜像老化规则 * * @param DeleteRetentionRequest 请求对象 * @return AsyncInvoker<DeleteRetentionRequest, DeleteRetentionResponse> */ public AsyncInvoker<DeleteRetentionRequest, DeleteRetentionResponse> deleteRetentionAsyncInvoker(DeleteRetentionRequest request) { return new AsyncInvoker<DeleteRetentionRequest, DeleteRetentionResponse>(request, SwrMeta.deleteRetention, hcClient); } /** * 删除触发器 * 删除触发器 * * @param DeleteTriggerRequest 请求对象 * @return CompletableFuture<DeleteTriggerResponse> */ public CompletableFuture<DeleteTriggerResponse> deleteTriggerAsync(DeleteTriggerRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.deleteTrigger); } /** * 删除触发器 * 删除触发器 * * @param DeleteTriggerRequest 请求对象 * @return AsyncInvoker<DeleteTriggerRequest, DeleteTriggerResponse> */ public AsyncInvoker<DeleteTriggerRequest, DeleteTriggerResponse> deleteTriggerAsyncInvoker(DeleteTriggerRequest request) { return new AsyncInvoker<DeleteTriggerRequest, DeleteTriggerResponse>(request, SwrMeta.deleteTrigger, hcClient); } /** * 删除镜像权限 * 删除镜像权限 * * @param DeleteUserRepositoryAuthRequest 请求对象 * @return CompletableFuture<DeleteUserRepositoryAuthResponse> */ public CompletableFuture<DeleteUserRepositoryAuthResponse> deleteUserRepositoryAuthAsync(DeleteUserRepositoryAuthRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.deleteUserRepositoryAuth); } /** * 删除镜像权限 * 删除镜像权限 * * @param DeleteUserRepositoryAuthRequest 请求对象 * @return AsyncInvoker<DeleteUserRepositoryAuthRequest, DeleteUserRepositoryAuthResponse> */ public AsyncInvoker<DeleteUserRepositoryAuthRequest, DeleteUserRepositoryAuthResponse> deleteUserRepositoryAuthAsyncInvoker(DeleteUserRepositoryAuthRequest request) { return new AsyncInvoker<DeleteUserRepositoryAuthRequest, DeleteUserRepositoryAuthResponse>(request, SwrMeta.deleteUserRepositoryAuth, hcClient); } /** * 获取镜像自动同步任务列表 * 获取镜像自动同步任务列表 * * @param ListImageAutoSyncReposDetailsRequest 请求对象 * @return CompletableFuture<ListImageAutoSyncReposDetailsResponse> */ public CompletableFuture<ListImageAutoSyncReposDetailsResponse> listImageAutoSyncReposDetailsAsync(ListImageAutoSyncReposDetailsRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.listImageAutoSyncReposDetails); } /** * 获取镜像自动同步任务列表 * 获取镜像自动同步任务列表 * * @param ListImageAutoSyncReposDetailsRequest 请求对象 * @return AsyncInvoker<ListImageAutoSyncReposDetailsRequest, ListImageAutoSyncReposDetailsResponse> */ public AsyncInvoker<ListImageAutoSyncReposDetailsRequest, ListImageAutoSyncReposDetailsResponse> listImageAutoSyncReposDetailsAsyncInvoker(ListImageAutoSyncReposDetailsRequest request) { return new AsyncInvoker<ListImageAutoSyncReposDetailsRequest, ListImageAutoSyncReposDetailsResponse>(request, SwrMeta.listImageAutoSyncReposDetails, hcClient); } /** * 查询组织列表 * 查询组织列表 * * @param ListNamespacesRequest 请求对象 * @return CompletableFuture<ListNamespacesResponse> */ public CompletableFuture<ListNamespacesResponse> listNamespacesAsync(ListNamespacesRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.listNamespaces); } /** * 查询组织列表 * 查询组织列表 * * @param ListNamespacesRequest 请求对象 * @return AsyncInvoker<ListNamespacesRequest, ListNamespacesResponse> */ public AsyncInvoker<ListNamespacesRequest, ListNamespacesResponse> listNamespacesAsyncInvoker(ListNamespacesRequest request) { return new AsyncInvoker<ListNamespacesRequest, ListNamespacesResponse>(request, SwrMeta.listNamespaces, hcClient); } /** * 获取共享账号列表 * 获取共享账号列表 * * @param ListRepoDomainsRequest 请求对象 * @return CompletableFuture<ListRepoDomainsResponse> */ public CompletableFuture<ListRepoDomainsResponse> listRepoDomainsAsync(ListRepoDomainsRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.listRepoDomains); } /** * 获取共享账号列表 * 获取共享账号列表 * * @param ListRepoDomainsRequest 请求对象 * @return AsyncInvoker<ListRepoDomainsRequest, ListRepoDomainsResponse> */ public AsyncInvoker<ListRepoDomainsRequest, ListRepoDomainsResponse> listRepoDomainsAsyncInvoker(ListRepoDomainsRequest request) { return new AsyncInvoker<ListRepoDomainsRequest, ListRepoDomainsResponse>(request, SwrMeta.listRepoDomains, hcClient); } /** * 查询镜像列表 * 查询镜像列表 * * @param ListReposDetailsRequest 请求对象 * @return CompletableFuture<ListReposDetailsResponse> */ public CompletableFuture<ListReposDetailsResponse> listReposDetailsAsync(ListReposDetailsRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.listReposDetails); } /** * 查询镜像列表 * 查询镜像列表 * * @param ListReposDetailsRequest 请求对象 * @return AsyncInvoker<ListReposDetailsRequest, ListReposDetailsResponse> */ public AsyncInvoker<ListReposDetailsRequest, ListReposDetailsResponse> listReposDetailsAsyncInvoker(ListReposDetailsRequest request) { return new AsyncInvoker<ListReposDetailsRequest, ListReposDetailsResponse>(request, SwrMeta.listReposDetails, hcClient); } /** * 查询镜像tag列表 * 查询镜像tag列表 * * @param ListRepositoryTagsRequest 请求对象 * @return CompletableFuture<ListRepositoryTagsResponse> */ public CompletableFuture<ListRepositoryTagsResponse> listRepositoryTagsAsync(ListRepositoryTagsRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.listRepositoryTags); } /** * 查询镜像tag列表 * 查询镜像tag列表 * * @param ListRepositoryTagsRequest 请求对象 * @return AsyncInvoker<ListRepositoryTagsRequest, ListRepositoryTagsResponse> */ public AsyncInvoker<ListRepositoryTagsRequest, ListRepositoryTagsResponse> listRepositoryTagsAsyncInvoker(ListRepositoryTagsRequest request) { return new AsyncInvoker<ListRepositoryTagsRequest, ListRepositoryTagsResponse>(request, SwrMeta.listRepositoryTags, hcClient); } /** * 获取镜像老化记录 * 获取镜像老化记录 * * @param ListRetentionHistoriesRequest 请求对象 * @return CompletableFuture<ListRetentionHistoriesResponse> */ public CompletableFuture<ListRetentionHistoriesResponse> listRetentionHistoriesAsync(ListRetentionHistoriesRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.listRetentionHistories); } /** * 获取镜像老化记录 * 获取镜像老化记录 * * @param ListRetentionHistoriesRequest 请求对象 * @return AsyncInvoker<ListRetentionHistoriesRequest, ListRetentionHistoriesResponse> */ public AsyncInvoker<ListRetentionHistoriesRequest, ListRetentionHistoriesResponse> listRetentionHistoriesAsyncInvoker(ListRetentionHistoriesRequest request) { return new AsyncInvoker<ListRetentionHistoriesRequest, ListRetentionHistoriesResponse>(request, SwrMeta.listRetentionHistories, hcClient); } /** * 获取镜像老化规则列表 * 获取镜像老化规则列表 * * @param ListRetentionsRequest 请求对象 * @return CompletableFuture<ListRetentionsResponse> */ public CompletableFuture<ListRetentionsResponse> listRetentionsAsync(ListRetentionsRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.listRetentions); } /** * 获取镜像老化规则列表 * 获取镜像老化规则列表 * * @param ListRetentionsRequest 请求对象 * @return AsyncInvoker<ListRetentionsRequest, ListRetentionsResponse> */ public AsyncInvoker<ListRetentionsRequest, ListRetentionsResponse> listRetentionsAsyncInvoker(ListRetentionsRequest request) { return new AsyncInvoker<ListRetentionsRequest, ListRetentionsResponse>(request, SwrMeta.listRetentions, hcClient); } /** * 查询共享镜像列表 * 查询共享镜像列表 * * @param ListSharedReposDetailsRequest 请求对象 * @return CompletableFuture<ListSharedReposDetailsResponse> */ public CompletableFuture<ListSharedReposDetailsResponse> listSharedReposDetailsAsync(ListSharedReposDetailsRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.listSharedReposDetails); } /** * 查询共享镜像列表 * 查询共享镜像列表 * * @param ListSharedReposDetailsRequest 请求对象 * @return AsyncInvoker<ListSharedReposDetailsRequest, ListSharedReposDetailsResponse> */ public AsyncInvoker<ListSharedReposDetailsRequest, ListSharedReposDetailsResponse> listSharedReposDetailsAsyncInvoker(ListSharedReposDetailsRequest request) { return new AsyncInvoker<ListSharedReposDetailsRequest, ListSharedReposDetailsResponse>(request, SwrMeta.listSharedReposDetails, hcClient); } /** * 获取镜像仓库下的触发器列表 * 获取镜像仓库下的触发器列表 * * @param ListTriggersDetailsRequest 请求对象 * @return CompletableFuture<ListTriggersDetailsResponse> */ public CompletableFuture<ListTriggersDetailsResponse> listTriggersDetailsAsync(ListTriggersDetailsRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.listTriggersDetails); } /** * 获取镜像仓库下的触发器列表 * 获取镜像仓库下的触发器列表 * * @param ListTriggersDetailsRequest 请求对象 * @return AsyncInvoker<ListTriggersDetailsRequest, ListTriggersDetailsResponse> */ public AsyncInvoker<ListTriggersDetailsRequest, ListTriggersDetailsResponse> listTriggersDetailsAsyncInvoker(ListTriggersDetailsRequest request) { return new AsyncInvoker<ListTriggersDetailsRequest, ListTriggersDetailsResponse>(request, SwrMeta.listTriggersDetails, hcClient); } /** * 判断共享账号是否存在 * 判断共享租户是否存在 * * @param ShowAccessDomainRequest 请求对象 * @return CompletableFuture<ShowAccessDomainResponse> */ public CompletableFuture<ShowAccessDomainResponse> showAccessDomainAsync(ShowAccessDomainRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.showAccessDomain); } /** * 判断共享账号是否存在 * 判断共享租户是否存在 * * @param ShowAccessDomainRequest 请求对象 * @return AsyncInvoker<ShowAccessDomainRequest, ShowAccessDomainResponse> */ public AsyncInvoker<ShowAccessDomainRequest, ShowAccessDomainResponse> showAccessDomainAsyncInvoker(ShowAccessDomainRequest request) { return new AsyncInvoker<ShowAccessDomainRequest, ShowAccessDomainResponse>(request, SwrMeta.showAccessDomain, hcClient); } /** * 获取组织详情 * 获取组织详情 * * @param ShowNamespaceRequest 请求对象 * @return CompletableFuture<ShowNamespaceResponse> */ public CompletableFuture<ShowNamespaceResponse> showNamespaceAsync(ShowNamespaceRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.showNamespace); } /** * 获取组织详情 * 获取组织详情 * * @param ShowNamespaceRequest 请求对象 * @return AsyncInvoker<ShowNamespaceRequest, ShowNamespaceResponse> */ public AsyncInvoker<ShowNamespaceRequest, ShowNamespaceResponse> showNamespaceAsyncInvoker(ShowNamespaceRequest request) { return new AsyncInvoker<ShowNamespaceRequest, ShowNamespaceResponse>(request, SwrMeta.showNamespace, hcClient); } /** * 查询组织权限 * 查询组织权限 * * @param ShowNamespaceAuthRequest 请求对象 * @return CompletableFuture<ShowNamespaceAuthResponse> */ public CompletableFuture<ShowNamespaceAuthResponse> showNamespaceAuthAsync(ShowNamespaceAuthRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.showNamespaceAuth); } /** * 查询组织权限 * 查询组织权限 * * @param ShowNamespaceAuthRequest 请求对象 * @return AsyncInvoker<ShowNamespaceAuthRequest, ShowNamespaceAuthResponse> */ public AsyncInvoker<ShowNamespaceAuthRequest, ShowNamespaceAuthResponse> showNamespaceAuthAsyncInvoker(ShowNamespaceAuthRequest request) { return new AsyncInvoker<ShowNamespaceAuthRequest, ShowNamespaceAuthResponse>(request, SwrMeta.showNamespaceAuth, hcClient); } /** * 查询镜像概要信息 * 查询镜像概要信息 * * @param ShowRepositoryRequest 请求对象 * @return CompletableFuture<ShowRepositoryResponse> */ public CompletableFuture<ShowRepositoryResponse> showRepositoryAsync(ShowRepositoryRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.showRepository); } /** * 查询镜像概要信息 * 查询镜像概要信息 * * @param ShowRepositoryRequest 请求对象 * @return AsyncInvoker<ShowRepositoryRequest, ShowRepositoryResponse> */ public AsyncInvoker<ShowRepositoryRequest, ShowRepositoryResponse> showRepositoryAsyncInvoker(ShowRepositoryRequest request) { return new AsyncInvoker<ShowRepositoryRequest, ShowRepositoryResponse>(request, SwrMeta.showRepository, hcClient); } /** * 获取镜像老化规则记录 * 获取镜像老化规则记录 * * @param ShowRetentionRequest 请求对象 * @return CompletableFuture<ShowRetentionResponse> */ public CompletableFuture<ShowRetentionResponse> showRetentionAsync(ShowRetentionRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.showRetention); } /** * 获取镜像老化规则记录 * 获取镜像老化规则记录 * * @param ShowRetentionRequest 请求对象 * @return AsyncInvoker<ShowRetentionRequest, ShowRetentionResponse> */ public AsyncInvoker<ShowRetentionRequest, ShowRetentionResponse> showRetentionAsyncInvoker(ShowRetentionRequest request) { return new AsyncInvoker<ShowRetentionRequest, ShowRetentionResponse>(request, SwrMeta.showRetention, hcClient); } /** * 获取镜像同步任务信息 * 获取镜像同步任务信息 * * @param ShowSyncJobRequest 请求对象 * @return CompletableFuture<ShowSyncJobResponse> */ public CompletableFuture<ShowSyncJobResponse> showSyncJobAsync(ShowSyncJobRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.showSyncJob); } /** * 获取镜像同步任务信息 * 获取镜像同步任务信息 * * @param ShowSyncJobRequest 请求对象 * @return AsyncInvoker<ShowSyncJobRequest, ShowSyncJobResponse> */ public AsyncInvoker<ShowSyncJobRequest, ShowSyncJobResponse> showSyncJobAsyncInvoker(ShowSyncJobRequest request) { return new AsyncInvoker<ShowSyncJobRequest, ShowSyncJobResponse>(request, SwrMeta.showSyncJob, hcClient); } /** * 获取触发器详情 * 获取触发器详情 * * @param ShowTriggerRequest 请求对象 * @return CompletableFuture<ShowTriggerResponse> */ public CompletableFuture<ShowTriggerResponse> showTriggerAsync(ShowTriggerRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.showTrigger); } /** * 获取触发器详情 * 获取触发器详情 * * @param ShowTriggerRequest 请求对象 * @return AsyncInvoker<ShowTriggerRequest, ShowTriggerResponse> */ public AsyncInvoker<ShowTriggerRequest, ShowTriggerResponse> showTriggerAsyncInvoker(ShowTriggerRequest request) { return new AsyncInvoker<ShowTriggerRequest, ShowTriggerResponse>(request, SwrMeta.showTrigger, hcClient); } /** * 查询镜像权限 * 查询镜像权限 * * @param ShowUserRepositoryAuthRequest 请求对象 * @return CompletableFuture<ShowUserRepositoryAuthResponse> */ public CompletableFuture<ShowUserRepositoryAuthResponse> showUserRepositoryAuthAsync(ShowUserRepositoryAuthRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.showUserRepositoryAuth); } /** * 查询镜像权限 * 查询镜像权限 * * @param ShowUserRepositoryAuthRequest 请求对象 * @return AsyncInvoker<ShowUserRepositoryAuthRequest, ShowUserRepositoryAuthResponse> */ public AsyncInvoker<ShowUserRepositoryAuthRequest, ShowUserRepositoryAuthResponse> showUserRepositoryAuthAsyncInvoker(ShowUserRepositoryAuthRequest request) { return new AsyncInvoker<ShowUserRepositoryAuthRequest, ShowUserRepositoryAuthResponse>(request, SwrMeta.showUserRepositoryAuth, hcClient); } /** * 更新组织权限 * 更新组织权限 * * @param UpdateNamespaceAuthRequest 请求对象 * @return CompletableFuture<UpdateNamespaceAuthResponse> */ public CompletableFuture<UpdateNamespaceAuthResponse> updateNamespaceAuthAsync(UpdateNamespaceAuthRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.updateNamespaceAuth); } /** * 更新组织权限 * 更新组织权限 * * @param UpdateNamespaceAuthRequest 请求对象 * @return AsyncInvoker<UpdateNamespaceAuthRequest, UpdateNamespaceAuthResponse> */ public AsyncInvoker<UpdateNamespaceAuthRequest, UpdateNamespaceAuthResponse> updateNamespaceAuthAsyncInvoker(UpdateNamespaceAuthRequest request) { return new AsyncInvoker<UpdateNamespaceAuthRequest, UpdateNamespaceAuthResponse>(request, SwrMeta.updateNamespaceAuth, hcClient); } /** * 更新镜像仓库的概要信息 * 更新租户命名空间下的镜像概要信息,包括镜像类型、是否公有、描述信息 * * @param UpdateRepoRequest 请求对象 * @return CompletableFuture<UpdateRepoResponse> */ public CompletableFuture<UpdateRepoResponse> updateRepoAsync(UpdateRepoRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.updateRepo); } /** * 更新镜像仓库的概要信息 * 更新租户命名空间下的镜像概要信息,包括镜像类型、是否公有、描述信息 * * @param UpdateRepoRequest 请求对象 * @return AsyncInvoker<UpdateRepoRequest, UpdateRepoResponse> */ public AsyncInvoker<UpdateRepoRequest, UpdateRepoResponse> updateRepoAsyncInvoker(UpdateRepoRequest request) { return new AsyncInvoker<UpdateRepoRequest, UpdateRepoResponse>(request, SwrMeta.updateRepo, hcClient); } /** * 更新共享账号 * 更新共享账号 * * @param UpdateRepoDomainsRequest 请求对象 * @return CompletableFuture<UpdateRepoDomainsResponse> */ public CompletableFuture<UpdateRepoDomainsResponse> updateRepoDomainsAsync(UpdateRepoDomainsRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.updateRepoDomains); } /** * 更新共享账号 * 更新共享账号 * * @param UpdateRepoDomainsRequest 请求对象 * @return AsyncInvoker<UpdateRepoDomainsRequest, UpdateRepoDomainsResponse> */ public AsyncInvoker<UpdateRepoDomainsRequest, UpdateRepoDomainsResponse> updateRepoDomainsAsyncInvoker(UpdateRepoDomainsRequest request) { return new AsyncInvoker<UpdateRepoDomainsRequest, UpdateRepoDomainsResponse>(request, SwrMeta.updateRepoDomains, hcClient); } /** * 修改镜像老化规则 * 修改镜像老化规则 * * @param UpdateRetentionRequest 请求对象 * @return CompletableFuture<UpdateRetentionResponse> */ public CompletableFuture<UpdateRetentionResponse> updateRetentionAsync(UpdateRetentionRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.updateRetention); } /** * 修改镜像老化规则 * 修改镜像老化规则 * * @param UpdateRetentionRequest 请求对象 * @return AsyncInvoker<UpdateRetentionRequest, UpdateRetentionResponse> */ public AsyncInvoker<UpdateRetentionRequest, UpdateRetentionResponse> updateRetentionAsyncInvoker(UpdateRetentionRequest request) { return new AsyncInvoker<UpdateRetentionRequest, UpdateRetentionResponse>(request, SwrMeta.updateRetention, hcClient); } /** * 更新触发器配置 * 更新触发器配置 * * @param UpdateTriggerRequest 请求对象 * @return CompletableFuture<UpdateTriggerResponse> */ public CompletableFuture<UpdateTriggerResponse> updateTriggerAsync(UpdateTriggerRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.updateTrigger); } /** * 更新触发器配置 * 更新触发器配置 * * @param UpdateTriggerRequest 请求对象 * @return AsyncInvoker<UpdateTriggerRequest, UpdateTriggerResponse> */ public AsyncInvoker<UpdateTriggerRequest, UpdateTriggerResponse> updateTriggerAsyncInvoker(UpdateTriggerRequest request) { return new AsyncInvoker<UpdateTriggerRequest, UpdateTriggerResponse>(request, SwrMeta.updateTrigger, hcClient); } /** * 更新镜像权限 * 更新镜像权限 * * @param UpdateUserRepositoryAuthRequest 请求对象 * @return CompletableFuture<UpdateUserRepositoryAuthResponse> */ public CompletableFuture<UpdateUserRepositoryAuthResponse> updateUserRepositoryAuthAsync(UpdateUserRepositoryAuthRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.updateUserRepositoryAuth); } /** * 更新镜像权限 * 更新镜像权限 * * @param UpdateUserRepositoryAuthRequest 请求对象 * @return AsyncInvoker<UpdateUserRepositoryAuthRequest, UpdateUserRepositoryAuthResponse> */ public AsyncInvoker<UpdateUserRepositoryAuthRequest, UpdateUserRepositoryAuthResponse> updateUserRepositoryAuthAsyncInvoker(UpdateUserRepositoryAuthRequest request) { return new AsyncInvoker<UpdateUserRepositoryAuthRequest, UpdateUserRepositoryAuthResponse>(request, SwrMeta.updateUserRepositoryAuth, hcClient); } /** * 查询所有API版本信息 * 查询所有API版本信息 * * @param ListApiVersionsRequest 请求对象 * @return CompletableFuture<ListApiVersionsResponse> */ public CompletableFuture<ListApiVersionsResponse> listApiVersionsAsync(ListApiVersionsRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.listApiVersions); } /** * 查询所有API版本信息 * 查询所有API版本信息 * * @param ListApiVersionsRequest 请求对象 * @return AsyncInvoker<ListApiVersionsRequest, ListApiVersionsResponse> */ public AsyncInvoker<ListApiVersionsRequest, ListApiVersionsResponse> listApiVersionsAsyncInvoker(ListApiVersionsRequest request) { return new AsyncInvoker<ListApiVersionsRequest, ListApiVersionsResponse>(request, SwrMeta.listApiVersions, hcClient); } /** * 查询指定API版本信息 * 查询指定API版本信息 * * @param ShowApiVersionRequest 请求对象 * @return CompletableFuture<ShowApiVersionResponse> */ public CompletableFuture<ShowApiVersionResponse> showApiVersionAsync(ShowApiVersionRequest request) { return hcClient.asyncInvokeHttp(request, SwrMeta.showApiVersion); } /** * 查询指定API版本信息 * 查询指定API版本信息 * * @param ShowApiVersionRequest 请求对象 * @return AsyncInvoker<ShowApiVersionRequest, ShowApiVersionResponse> */ public AsyncInvoker<ShowApiVersionRequest, ShowApiVersionResponse> showApiVersionAsyncInvoker(ShowApiVersionRequest request) { return new AsyncInvoker<ShowApiVersionRequest, ShowApiVersionResponse>(request, SwrMeta.showApiVersion, hcClient); } }
40,258
0.742515
0.74246
990
35.908081
43.245865
190
false
false
0
0
0
0
0
0
0.365657
false
false
0
2193f7ab0ac9c4268f266c31c3499188696db290
23,304,492,600,210
c927aca1fe4dc9159890f6fbb6f4fbc488b83c43
/src/java/com/cardpay/pccredit/bank/model/CustomerOverdue.java
546a82781bb30ff24b0eebef739787f66cf43950
[ "Apache-2.0" ]
permissive
wangxu2013/StatisticsCredit
https://github.com/wangxu2013/StatisticsCredit
2c7911cb8afc9fae677323515ad3798f082e52cf
c8ba870913f70c36b757d4e0fcdb89e875dcbf25
refs/heads/master
2021-01-21T07:34:51.508000
2015-06-24T07:26:03
2015-06-24T07:26:03
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package com.cardpay.pccredit.bank.model; import java.util.Date; /** * @author shaoming * * 2014年11月28日 上午10:53:16 */ public class CustomerOverdue extends BaseModel{ private String id; private String customerId; private String productId; private String numberDaysOverdue; private String currentBalance; private String minimumPayment; private String reminder; private String reminderWay; private Date reminderDate; private String overduePaybackAll; private Date lateDate; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getCustomerId() { return customerId; } public void setCustomerId(String customerId) { this.customerId = customerId; } public String getProductId() { return productId; } public void setProductId(String productId) { this.productId = productId; } public String getNumberDaysOverdue() { return numberDaysOverdue; } public void setNumberDaysOverdue(String numberDaysOverdue) { this.numberDaysOverdue = numberDaysOverdue; } public String getCurrentBalance() { return currentBalance; } public void setCurrentBalance(String currentBalance) { this.currentBalance = currentBalance; } public String getMinimumPayment() { return minimumPayment; } public void setMinimumPayment(String minimumPayment) { this.minimumPayment = minimumPayment; } public String getReminder() { return reminder; } public void setReminder(String reminder) { this.reminder = reminder; } public String getReminderWay() { return reminderWay; } public void setReminderWay(String reminderWay) { this.reminderWay = reminderWay; } public Date getReminderDate() { return reminderDate; } public void setReminderDate(Date reminderDate) { this.reminderDate = reminderDate; } public String getOverduePaybackAll() { return overduePaybackAll; } public void setOverduePaybackAll(String overduePaybackAll) { this.overduePaybackAll = overduePaybackAll; } public Date getLateDate() { return lateDate; } public void setLateDate(Date lateDate) { this.lateDate = lateDate; } }
UTF-8
Java
2,211
java
CustomerOverdue.java
Java
[ { "context": "odel;\r\n\r\nimport java.util.Date;\r\n\r\n/**\r\n * @author shaoming\r\n *\r\n * 2014年11月28日 上午10:53:16\r\n */\r\npublic cla", "end": 109, "score": 0.9992828369140625, "start": 101, "tag": "USERNAME", "value": "shaoming" } ]
null
[]
/** * */ package com.cardpay.pccredit.bank.model; import java.util.Date; /** * @author shaoming * * 2014年11月28日 上午10:53:16 */ public class CustomerOverdue extends BaseModel{ private String id; private String customerId; private String productId; private String numberDaysOverdue; private String currentBalance; private String minimumPayment; private String reminder; private String reminderWay; private Date reminderDate; private String overduePaybackAll; private Date lateDate; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getCustomerId() { return customerId; } public void setCustomerId(String customerId) { this.customerId = customerId; } public String getProductId() { return productId; } public void setProductId(String productId) { this.productId = productId; } public String getNumberDaysOverdue() { return numberDaysOverdue; } public void setNumberDaysOverdue(String numberDaysOverdue) { this.numberDaysOverdue = numberDaysOverdue; } public String getCurrentBalance() { return currentBalance; } public void setCurrentBalance(String currentBalance) { this.currentBalance = currentBalance; } public String getMinimumPayment() { return minimumPayment; } public void setMinimumPayment(String minimumPayment) { this.minimumPayment = minimumPayment; } public String getReminder() { return reminder; } public void setReminder(String reminder) { this.reminder = reminder; } public String getReminderWay() { return reminderWay; } public void setReminderWay(String reminderWay) { this.reminderWay = reminderWay; } public Date getReminderDate() { return reminderDate; } public void setReminderDate(Date reminderDate) { this.reminderDate = reminderDate; } public String getOverduePaybackAll() { return overduePaybackAll; } public void setOverduePaybackAll(String overduePaybackAll) { this.overduePaybackAll = overduePaybackAll; } public Date getLateDate() { return lateDate; } public void setLateDate(Date lateDate) { this.lateDate = lateDate; } }
2,211
0.725125
0.718764
92
21.923914
17.118027
61
false
false
0
0
0
0
0
0
1.467391
false
false
0
25b41ba209fe7160508f683c8b7d90615bc9aac9
7,490,423,021,344
40ce0bb9783e8e2eba0c0ff6ba2653505e997e2e
/AToS/src/hu/ak_akademia/atos/db/entity/City.java
9442d129cb019376f5770634d7ac781be988719a
[]
no_license
markosa84/atos
https://github.com/markosa84/atos
97f94233cdebfc5b54241e3251b2c4646a64865a
265cb53bd3b8f1ab9b0000aaf954c0fd44ea1989
refs/heads/master
2022-11-09T22:34:06.657000
2020-06-20T16:54:46
2020-06-20T16:54:46
254,889,513
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package hu.ak_akademia.atos.db.entity; public class City { private final Long cityId; private final Long countryId; private final String name; private City(Builder builder) { this.cityId = builder.cityId; this.countryId = builder.countryId; this.name = builder.name; } public Long getCityId() { return cityId; } public Long getCountryId() { return countryId; } public String getName() { return name; } public static Builder builder() { return new Builder(); } public static final class Builder { private Long cityId; private Long countryId; private String name; private Builder() { } public Builder withCityId(Long cityId) { this.cityId = cityId; return this; } public Builder withCountryId(Long countryId) { this.countryId = countryId; return this; } public Builder withName(String name) { this.name = name; return this; } public City build() { return new City(this); } } @Override public String toString() { StringBuilder builder2 = new StringBuilder(); builder2.append("City [cityId="); builder2.append(cityId); builder2.append(", countryId="); builder2.append(countryId); builder2.append(", name="); builder2.append(name); builder2.append("]"); return builder2.toString(); } }
UTF-8
Java
1,363
java
City.java
Java
[]
null
[]
package hu.ak_akademia.atos.db.entity; public class City { private final Long cityId; private final Long countryId; private final String name; private City(Builder builder) { this.cityId = builder.cityId; this.countryId = builder.countryId; this.name = builder.name; } public Long getCityId() { return cityId; } public Long getCountryId() { return countryId; } public String getName() { return name; } public static Builder builder() { return new Builder(); } public static final class Builder { private Long cityId; private Long countryId; private String name; private Builder() { } public Builder withCityId(Long cityId) { this.cityId = cityId; return this; } public Builder withCountryId(Long countryId) { this.countryId = countryId; return this; } public Builder withName(String name) { this.name = name; return this; } public City build() { return new City(this); } } @Override public String toString() { StringBuilder builder2 = new StringBuilder(); builder2.append("City [cityId="); builder2.append(cityId); builder2.append(", countryId="); builder2.append(countryId); builder2.append(", name="); builder2.append(name); builder2.append("]"); return builder2.toString(); } }
1,363
0.652238
0.645635
72
16.958334
14.303688
48
false
false
0
0
0
0
0
0
1.791667
false
false
0
b5aadee45677e525fbcd64305ed6fab955b56b7d
26,723,286,566,262
882e77219bce59ae57cbad7e9606507b34eebfcf
/mi2s_securitycenter_miui12/src/main/java/miuix/recyclerview/widget/c.java
c676ab969885a74014bc1b2acf042a30b4a9a0cf
[]
no_license
CrackerCat/XiaomiFramework
https://github.com/CrackerCat/XiaomiFramework
17a12c1752296fa1a52f61b83ecf165f328f4523
0b7952df317dac02ebd1feea7507afb789cef2e3
refs/heads/master
2022-06-12T03:30:33.285000
2020-05-06T11:30:54
2020-05-06T11:30:54
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package miuix.recyclerview.widget; import android.view.View; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.recyclerview.widget.O; import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public abstract class c extends O { private static final List<RecyclerView.u> h = new ArrayList(); private static final List<b> i = new ArrayList(); private static final List<a> j = new ArrayList(); private ArrayList<RecyclerView.u> k = new ArrayList<>(); private ArrayList<RecyclerView.u> l = new ArrayList<>(); private ArrayList<b> m = new ArrayList<>(); private ArrayList<a> n = new ArrayList<>(); private ArrayList<ArrayList<RecyclerView.u>> o = new ArrayList<>(); private ArrayList<ArrayList<b>> p = new ArrayList<>(); private ArrayList<ArrayList<a>> q = new ArrayList<>(); private ArrayList<RecyclerView.u> r = new ArrayList<>(); private ArrayList<RecyclerView.u> s = new ArrayList<>(); private ArrayList<RecyclerView.u> t = new ArrayList<>(); private ArrayList<RecyclerView.u> u = new ArrayList<>(); static class a { /* renamed from: a reason: collision with root package name */ RecyclerView.u f8921a; /* renamed from: b reason: collision with root package name */ RecyclerView.u f8922b; /* renamed from: c reason: collision with root package name */ int f8923c; /* renamed from: d reason: collision with root package name */ int f8924d; int e; int f; private a(RecyclerView.u uVar, RecyclerView.u uVar2) { this.f8921a = uVar; this.f8922b = uVar2; } a(RecyclerView.u uVar, RecyclerView.u uVar2, int i, int i2, int i3, int i4) { this(uVar, uVar2); this.f8923c = i; this.f8924d = i2; this.e = i3; this.f = i4; } public String toString() { return "ChangeInfo{oldHolder=" + this.f8921a + ", newHolder=" + this.f8922b + ", fromX=" + this.f8923c + ", fromY=" + this.f8924d + ", toX=" + this.e + ", toY=" + this.f + '}'; } } static class b { /* renamed from: a reason: collision with root package name */ RecyclerView.u f8925a; /* renamed from: b reason: collision with root package name */ int f8926b; /* renamed from: c reason: collision with root package name */ int f8927c; /* renamed from: d reason: collision with root package name */ int f8928d; int e; b(RecyclerView.u uVar, int i, int i2, int i3, int i4) { this.f8925a = uVar; this.f8926b = i; this.f8927c = i2; this.f8928d = i3; this.e = i4; } public String toString() { return "MoveInfo{holder=" + this.f8925a + ", fromX=" + this.f8926b + ", fromY=" + this.f8927c + ", toX=" + this.f8928d + ", toY=" + this.e + '}'; } } static void a(View view) { view.setTranslationX(0.0f); view.setTranslationY(0.0f); view.setAlpha(1.0f); } private void a(List<RecyclerView.u> list) { for (int size = list.size() - 1; size >= 0; size--) { b(list.get(size).itemView); } list.clear(); } private void a(List<a> list, RecyclerView.u uVar) { for (int size = list.size() - 1; size >= 0; size--) { a aVar = list.get(size); if (a(aVar, uVar) && aVar.f8921a == null && aVar.f8922b == null) { list.remove(aVar); } } } private boolean a(a aVar, RecyclerView.u uVar) { boolean z = false; if (aVar.f8922b == uVar) { aVar.f8922b = null; } else if (aVar.f8921a != uVar) { return false; } else { aVar.f8921a = null; z = true; } uVar.itemView.setAlpha(1.0f); uVar.itemView.setTranslationX(0.0f); uVar.itemView.setTranslationY(0.0f); a(uVar, z); return true; } private void b(View view) { d.a.b.b((T[]) new View[]{view}); } private void c(a aVar) { RecyclerView.u uVar = aVar.f8921a; if (uVar != null) { a(aVar, uVar); } RecyclerView.u uVar2 = aVar.f8922b; if (uVar2 != null) { a(aVar, uVar2); } } private void j() { if (!g()) { a(); } } /* access modifiers changed from: private */ public void k() { List<b> remove = this.p.isEmpty() ? i : this.p.remove(0); List<a> remove2 = this.q.isEmpty() ? j : this.q.remove(0); List<RecyclerView.u> remove3 = this.o.isEmpty() ? h : this.o.remove(0); for (b a2 : remove) { a(a2); } for (a a3 : remove2) { a(a3); } if (!remove3.isEmpty()) { b bVar = new b(this, remove3); if (!remove.isEmpty() || !remove2.isEmpty()) { remove3.get(0).itemView.postDelayed(bVar, 50); } else { bVar.run(); } } } /* access modifiers changed from: package-private */ public void A(RecyclerView.u uVar) { this.t.add(uVar); m(uVar); } /* access modifiers changed from: package-private */ public abstract void B(RecyclerView.u uVar); /* access modifiers changed from: package-private */ public abstract void C(RecyclerView.u uVar); /* access modifiers changed from: package-private */ public abstract void a(a aVar); /* access modifiers changed from: package-private */ public abstract void a(b bVar); public boolean a(RecyclerView.u uVar, int i2, int i3, int i4, int i5) { C(uVar); int i6 = i5 - i3; if (i4 - i2 == 0 && i6 == 0) { j(uVar); return false; } b bVar = new b(uVar, i2, i3, i4, i5); b(bVar); this.m.add(bVar); return true; } public boolean a(@NonNull RecyclerView.u uVar, @Nullable RecyclerView.ItemAnimator.c cVar, @NonNull RecyclerView.ItemAnimator.c cVar2) { if (cVar == null || (cVar.f1118a == cVar2.f1118a && cVar.f1119b == cVar2.f1119b)) { return f(uVar); } return a(uVar, cVar.f1118a, cVar.f1119b, cVar2.f1118a, cVar2.f1119b); } public boolean a(RecyclerView.u uVar, RecyclerView.u uVar2, int i2, int i3, int i4, int i5) { if (uVar == uVar2) { return a(uVar2, i2, i3, i4, i5); } a aVar = new a(uVar, uVar2, i2, i3, i4, i5); b(aVar); a(aVar); return true; } public boolean a(@NonNull RecyclerView.u uVar, @NonNull List<Object> list) { return !list.isEmpty() || super.a(uVar, list); } public void b() { int size = this.m.size(); while (true) { size--; if (size < 0) { break; } b bVar = this.m.get(size); View view = bVar.f8925a.itemView; view.setTranslationY(0.0f); view.setTranslationX(0.0f); j(bVar.f8925a); this.m.remove(size); } for (int size2 = this.k.size() - 1; size2 >= 0; size2--) { l(this.k.get(size2)); this.k.remove(size2); } int size3 = this.l.size(); while (true) { size3--; if (size3 < 0) { break; } RecyclerView.u uVar = this.l.get(size3); uVar.itemView.setAlpha(1.0f); h(uVar); this.l.remove(size3); } for (int size4 = this.n.size() - 1; size4 >= 0; size4--) { c(this.n.get(size4)); } this.n.clear(); if (g()) { for (int size5 = this.p.size() - 1; size5 >= 0; size5--) { ArrayList arrayList = this.p.get(size5); for (int size6 = arrayList.size() - 1; size6 >= 0; size6--) { b bVar2 = (b) arrayList.get(size6); View view2 = bVar2.f8925a.itemView; view2.setTranslationY(0.0f); view2.setTranslationX(0.0f); j(bVar2.f8925a); arrayList.remove(size6); if (arrayList.isEmpty()) { this.p.remove(arrayList); } } } for (int size7 = this.o.size() - 1; size7 >= 0; size7--) { ArrayList arrayList2 = this.o.get(size7); for (int size8 = arrayList2.size() - 1; size8 >= 0; size8--) { RecyclerView.u uVar2 = (RecyclerView.u) arrayList2.get(size8); uVar2.itemView.setAlpha(1.0f); h(uVar2); arrayList2.remove(size8); if (arrayList2.isEmpty()) { this.o.remove(arrayList2); } } } for (int size9 = this.q.size() - 1; size9 >= 0; size9--) { ArrayList arrayList3 = this.q.get(size9); for (int size10 = arrayList3.size() - 1; size10 >= 0; size10--) { c((a) arrayList3.get(size10)); if (arrayList3.isEmpty()) { this.q.remove(arrayList3); } } } a((List<RecyclerView.u>) this.t); a((List<RecyclerView.u>) this.s); a((List<RecyclerView.u>) this.r); a((List<RecyclerView.u>) this.u); a(); } } /* access modifiers changed from: package-private */ public abstract void b(a aVar); /* access modifiers changed from: package-private */ public abstract void b(b bVar); public void d(@NonNull RecyclerView.u uVar) { View view = uVar.itemView; b(view); int size = this.m.size(); while (true) { size--; if (size < 0) { break; } else if (this.m.get(size).f8925a == uVar) { view.setTranslationY(0.0f); view.setTranslationX(0.0f); j(uVar); this.m.remove(size); } } a((List<a>) this.n, uVar); if (this.k.remove(uVar)) { view.setAlpha(1.0f); l(uVar); } if (this.l.remove(uVar)) { view.setAlpha(1.0f); h(uVar); } for (int size2 = this.q.size() - 1; size2 >= 0; size2--) { ArrayList arrayList = this.q.get(size2); a((List<a>) arrayList, uVar); if (arrayList.isEmpty()) { this.q.remove(size2); } } for (int size3 = this.p.size() - 1; size3 >= 0; size3--) { ArrayList arrayList2 = this.p.get(size3); int size4 = arrayList2.size() - 1; while (true) { if (size4 < 0) { break; } else if (((b) arrayList2.get(size4)).f8925a == uVar) { view.setTranslationY(0.0f); view.setTranslationX(0.0f); j(uVar); arrayList2.remove(size4); if (arrayList2.isEmpty()) { this.p.remove(size3); } } else { size4--; } } } for (int size5 = this.o.size() - 1; size5 >= 0; size5--) { ArrayList arrayList3 = this.o.get(size5); if (arrayList3.remove(uVar)) { view.setAlpha(1.0f); h(uVar); if (arrayList3.isEmpty()) { this.o.remove(size5); } } } this.t.remove(uVar); this.r.remove(uVar); this.u.remove(uVar); this.s.remove(uVar); j(); } /* access modifiers changed from: package-private */ public void e(RecyclerView.u uVar, boolean z) { a(uVar, z); this.u.remove(uVar); j(); } /* access modifiers changed from: package-private */ public void f(RecyclerView.u uVar, boolean z) { this.u.add(uVar); b(uVar, z); } public boolean f(RecyclerView.u uVar) { B(uVar); this.l.add(uVar); return true; } public boolean g() { return !this.l.isEmpty() || !this.n.isEmpty() || !this.m.isEmpty() || !this.k.isEmpty() || !this.s.isEmpty() || !this.t.isEmpty() || !this.r.isEmpty() || !this.u.isEmpty() || !this.p.isEmpty() || !this.o.isEmpty() || !this.q.isEmpty(); } public boolean g(RecyclerView.u uVar) { C(uVar); this.k.add(uVar); return true; } public void i() { boolean z = !this.k.isEmpty(); boolean z2 = !this.m.isEmpty(); boolean z3 = !this.n.isEmpty(); boolean z4 = !this.l.isEmpty(); if (z || z2 || z3 || z4) { this.p.add(new ArrayList(this.m)); this.m.clear(); this.q.add(new ArrayList(this.n)); this.n.clear(); this.o.add(new ArrayList(this.l)); this.l.clear(); a aVar = new a(this); if (z) { Iterator<RecyclerView.u> it = this.k.iterator(); while (it.hasNext()) { u(it.next()); } this.k.get(0).itemView.postDelayed(aVar, 100); this.k.clear(); return; } aVar.run(); } } /* access modifiers changed from: package-private */ public abstract void t(RecyclerView.u uVar); /* access modifiers changed from: package-private */ public abstract void u(RecyclerView.u uVar); /* access modifiers changed from: package-private */ public void v(RecyclerView.u uVar) { h(uVar); this.r.remove(uVar); j(); } /* access modifiers changed from: package-private */ public void w(RecyclerView.u uVar) { this.r.add(uVar); i(uVar); } /* access modifiers changed from: package-private */ public void x(RecyclerView.u uVar) { j(uVar); this.s.remove(uVar); j(); } /* access modifiers changed from: package-private */ public void y(RecyclerView.u uVar) { this.s.add(uVar); k(uVar); } /* access modifiers changed from: package-private */ public void z(RecyclerView.u uVar) { l(uVar); this.t.remove(uVar); j(); } }
UTF-8
Java
14,832
java
c.java
Java
[]
null
[]
package miuix.recyclerview.widget; import android.view.View; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.recyclerview.widget.O; import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public abstract class c extends O { private static final List<RecyclerView.u> h = new ArrayList(); private static final List<b> i = new ArrayList(); private static final List<a> j = new ArrayList(); private ArrayList<RecyclerView.u> k = new ArrayList<>(); private ArrayList<RecyclerView.u> l = new ArrayList<>(); private ArrayList<b> m = new ArrayList<>(); private ArrayList<a> n = new ArrayList<>(); private ArrayList<ArrayList<RecyclerView.u>> o = new ArrayList<>(); private ArrayList<ArrayList<b>> p = new ArrayList<>(); private ArrayList<ArrayList<a>> q = new ArrayList<>(); private ArrayList<RecyclerView.u> r = new ArrayList<>(); private ArrayList<RecyclerView.u> s = new ArrayList<>(); private ArrayList<RecyclerView.u> t = new ArrayList<>(); private ArrayList<RecyclerView.u> u = new ArrayList<>(); static class a { /* renamed from: a reason: collision with root package name */ RecyclerView.u f8921a; /* renamed from: b reason: collision with root package name */ RecyclerView.u f8922b; /* renamed from: c reason: collision with root package name */ int f8923c; /* renamed from: d reason: collision with root package name */ int f8924d; int e; int f; private a(RecyclerView.u uVar, RecyclerView.u uVar2) { this.f8921a = uVar; this.f8922b = uVar2; } a(RecyclerView.u uVar, RecyclerView.u uVar2, int i, int i2, int i3, int i4) { this(uVar, uVar2); this.f8923c = i; this.f8924d = i2; this.e = i3; this.f = i4; } public String toString() { return "ChangeInfo{oldHolder=" + this.f8921a + ", newHolder=" + this.f8922b + ", fromX=" + this.f8923c + ", fromY=" + this.f8924d + ", toX=" + this.e + ", toY=" + this.f + '}'; } } static class b { /* renamed from: a reason: collision with root package name */ RecyclerView.u f8925a; /* renamed from: b reason: collision with root package name */ int f8926b; /* renamed from: c reason: collision with root package name */ int f8927c; /* renamed from: d reason: collision with root package name */ int f8928d; int e; b(RecyclerView.u uVar, int i, int i2, int i3, int i4) { this.f8925a = uVar; this.f8926b = i; this.f8927c = i2; this.f8928d = i3; this.e = i4; } public String toString() { return "MoveInfo{holder=" + this.f8925a + ", fromX=" + this.f8926b + ", fromY=" + this.f8927c + ", toX=" + this.f8928d + ", toY=" + this.e + '}'; } } static void a(View view) { view.setTranslationX(0.0f); view.setTranslationY(0.0f); view.setAlpha(1.0f); } private void a(List<RecyclerView.u> list) { for (int size = list.size() - 1; size >= 0; size--) { b(list.get(size).itemView); } list.clear(); } private void a(List<a> list, RecyclerView.u uVar) { for (int size = list.size() - 1; size >= 0; size--) { a aVar = list.get(size); if (a(aVar, uVar) && aVar.f8921a == null && aVar.f8922b == null) { list.remove(aVar); } } } private boolean a(a aVar, RecyclerView.u uVar) { boolean z = false; if (aVar.f8922b == uVar) { aVar.f8922b = null; } else if (aVar.f8921a != uVar) { return false; } else { aVar.f8921a = null; z = true; } uVar.itemView.setAlpha(1.0f); uVar.itemView.setTranslationX(0.0f); uVar.itemView.setTranslationY(0.0f); a(uVar, z); return true; } private void b(View view) { d.a.b.b((T[]) new View[]{view}); } private void c(a aVar) { RecyclerView.u uVar = aVar.f8921a; if (uVar != null) { a(aVar, uVar); } RecyclerView.u uVar2 = aVar.f8922b; if (uVar2 != null) { a(aVar, uVar2); } } private void j() { if (!g()) { a(); } } /* access modifiers changed from: private */ public void k() { List<b> remove = this.p.isEmpty() ? i : this.p.remove(0); List<a> remove2 = this.q.isEmpty() ? j : this.q.remove(0); List<RecyclerView.u> remove3 = this.o.isEmpty() ? h : this.o.remove(0); for (b a2 : remove) { a(a2); } for (a a3 : remove2) { a(a3); } if (!remove3.isEmpty()) { b bVar = new b(this, remove3); if (!remove.isEmpty() || !remove2.isEmpty()) { remove3.get(0).itemView.postDelayed(bVar, 50); } else { bVar.run(); } } } /* access modifiers changed from: package-private */ public void A(RecyclerView.u uVar) { this.t.add(uVar); m(uVar); } /* access modifiers changed from: package-private */ public abstract void B(RecyclerView.u uVar); /* access modifiers changed from: package-private */ public abstract void C(RecyclerView.u uVar); /* access modifiers changed from: package-private */ public abstract void a(a aVar); /* access modifiers changed from: package-private */ public abstract void a(b bVar); public boolean a(RecyclerView.u uVar, int i2, int i3, int i4, int i5) { C(uVar); int i6 = i5 - i3; if (i4 - i2 == 0 && i6 == 0) { j(uVar); return false; } b bVar = new b(uVar, i2, i3, i4, i5); b(bVar); this.m.add(bVar); return true; } public boolean a(@NonNull RecyclerView.u uVar, @Nullable RecyclerView.ItemAnimator.c cVar, @NonNull RecyclerView.ItemAnimator.c cVar2) { if (cVar == null || (cVar.f1118a == cVar2.f1118a && cVar.f1119b == cVar2.f1119b)) { return f(uVar); } return a(uVar, cVar.f1118a, cVar.f1119b, cVar2.f1118a, cVar2.f1119b); } public boolean a(RecyclerView.u uVar, RecyclerView.u uVar2, int i2, int i3, int i4, int i5) { if (uVar == uVar2) { return a(uVar2, i2, i3, i4, i5); } a aVar = new a(uVar, uVar2, i2, i3, i4, i5); b(aVar); a(aVar); return true; } public boolean a(@NonNull RecyclerView.u uVar, @NonNull List<Object> list) { return !list.isEmpty() || super.a(uVar, list); } public void b() { int size = this.m.size(); while (true) { size--; if (size < 0) { break; } b bVar = this.m.get(size); View view = bVar.f8925a.itemView; view.setTranslationY(0.0f); view.setTranslationX(0.0f); j(bVar.f8925a); this.m.remove(size); } for (int size2 = this.k.size() - 1; size2 >= 0; size2--) { l(this.k.get(size2)); this.k.remove(size2); } int size3 = this.l.size(); while (true) { size3--; if (size3 < 0) { break; } RecyclerView.u uVar = this.l.get(size3); uVar.itemView.setAlpha(1.0f); h(uVar); this.l.remove(size3); } for (int size4 = this.n.size() - 1; size4 >= 0; size4--) { c(this.n.get(size4)); } this.n.clear(); if (g()) { for (int size5 = this.p.size() - 1; size5 >= 0; size5--) { ArrayList arrayList = this.p.get(size5); for (int size6 = arrayList.size() - 1; size6 >= 0; size6--) { b bVar2 = (b) arrayList.get(size6); View view2 = bVar2.f8925a.itemView; view2.setTranslationY(0.0f); view2.setTranslationX(0.0f); j(bVar2.f8925a); arrayList.remove(size6); if (arrayList.isEmpty()) { this.p.remove(arrayList); } } } for (int size7 = this.o.size() - 1; size7 >= 0; size7--) { ArrayList arrayList2 = this.o.get(size7); for (int size8 = arrayList2.size() - 1; size8 >= 0; size8--) { RecyclerView.u uVar2 = (RecyclerView.u) arrayList2.get(size8); uVar2.itemView.setAlpha(1.0f); h(uVar2); arrayList2.remove(size8); if (arrayList2.isEmpty()) { this.o.remove(arrayList2); } } } for (int size9 = this.q.size() - 1; size9 >= 0; size9--) { ArrayList arrayList3 = this.q.get(size9); for (int size10 = arrayList3.size() - 1; size10 >= 0; size10--) { c((a) arrayList3.get(size10)); if (arrayList3.isEmpty()) { this.q.remove(arrayList3); } } } a((List<RecyclerView.u>) this.t); a((List<RecyclerView.u>) this.s); a((List<RecyclerView.u>) this.r); a((List<RecyclerView.u>) this.u); a(); } } /* access modifiers changed from: package-private */ public abstract void b(a aVar); /* access modifiers changed from: package-private */ public abstract void b(b bVar); public void d(@NonNull RecyclerView.u uVar) { View view = uVar.itemView; b(view); int size = this.m.size(); while (true) { size--; if (size < 0) { break; } else if (this.m.get(size).f8925a == uVar) { view.setTranslationY(0.0f); view.setTranslationX(0.0f); j(uVar); this.m.remove(size); } } a((List<a>) this.n, uVar); if (this.k.remove(uVar)) { view.setAlpha(1.0f); l(uVar); } if (this.l.remove(uVar)) { view.setAlpha(1.0f); h(uVar); } for (int size2 = this.q.size() - 1; size2 >= 0; size2--) { ArrayList arrayList = this.q.get(size2); a((List<a>) arrayList, uVar); if (arrayList.isEmpty()) { this.q.remove(size2); } } for (int size3 = this.p.size() - 1; size3 >= 0; size3--) { ArrayList arrayList2 = this.p.get(size3); int size4 = arrayList2.size() - 1; while (true) { if (size4 < 0) { break; } else if (((b) arrayList2.get(size4)).f8925a == uVar) { view.setTranslationY(0.0f); view.setTranslationX(0.0f); j(uVar); arrayList2.remove(size4); if (arrayList2.isEmpty()) { this.p.remove(size3); } } else { size4--; } } } for (int size5 = this.o.size() - 1; size5 >= 0; size5--) { ArrayList arrayList3 = this.o.get(size5); if (arrayList3.remove(uVar)) { view.setAlpha(1.0f); h(uVar); if (arrayList3.isEmpty()) { this.o.remove(size5); } } } this.t.remove(uVar); this.r.remove(uVar); this.u.remove(uVar); this.s.remove(uVar); j(); } /* access modifiers changed from: package-private */ public void e(RecyclerView.u uVar, boolean z) { a(uVar, z); this.u.remove(uVar); j(); } /* access modifiers changed from: package-private */ public void f(RecyclerView.u uVar, boolean z) { this.u.add(uVar); b(uVar, z); } public boolean f(RecyclerView.u uVar) { B(uVar); this.l.add(uVar); return true; } public boolean g() { return !this.l.isEmpty() || !this.n.isEmpty() || !this.m.isEmpty() || !this.k.isEmpty() || !this.s.isEmpty() || !this.t.isEmpty() || !this.r.isEmpty() || !this.u.isEmpty() || !this.p.isEmpty() || !this.o.isEmpty() || !this.q.isEmpty(); } public boolean g(RecyclerView.u uVar) { C(uVar); this.k.add(uVar); return true; } public void i() { boolean z = !this.k.isEmpty(); boolean z2 = !this.m.isEmpty(); boolean z3 = !this.n.isEmpty(); boolean z4 = !this.l.isEmpty(); if (z || z2 || z3 || z4) { this.p.add(new ArrayList(this.m)); this.m.clear(); this.q.add(new ArrayList(this.n)); this.n.clear(); this.o.add(new ArrayList(this.l)); this.l.clear(); a aVar = new a(this); if (z) { Iterator<RecyclerView.u> it = this.k.iterator(); while (it.hasNext()) { u(it.next()); } this.k.get(0).itemView.postDelayed(aVar, 100); this.k.clear(); return; } aVar.run(); } } /* access modifiers changed from: package-private */ public abstract void t(RecyclerView.u uVar); /* access modifiers changed from: package-private */ public abstract void u(RecyclerView.u uVar); /* access modifiers changed from: package-private */ public void v(RecyclerView.u uVar) { h(uVar); this.r.remove(uVar); j(); } /* access modifiers changed from: package-private */ public void w(RecyclerView.u uVar) { this.r.add(uVar); i(uVar); } /* access modifiers changed from: package-private */ public void x(RecyclerView.u uVar) { j(uVar); this.s.remove(uVar); j(); } /* access modifiers changed from: package-private */ public void y(RecyclerView.u uVar) { this.s.add(uVar); k(uVar); } /* access modifiers changed from: package-private */ public void z(RecyclerView.u uVar) { l(uVar); this.t.remove(uVar); j(); } }
14,832
0.496292
0.467435
466
30.828325
25.65696
243
false
false
0
0
0
0
0
0
0.744635
false
false
0
08a9e93b79a57d6842e06d97f55fedd066fc0c7b
26,723,286,563,110
73d707771bf802b93dc8ca51b2ab6a5ed77f804c
/Java Coding/ArrayList2D.java
4ebbf8536c66dabc47bb688dc13676389747e9c0
[]
no_license
gautam0209/Coding-Practice
https://github.com/gautam0209/Coding-Practice
bef7140bf7f1e33f30630ff2fb0776a8071650cb
4e148a132084428eb358cfa67f5162eb43c6a90d
refs/heads/master
2021-09-18T10:42:22.672000
2018-07-13T06:31:44
2018-07-13T06:31:44
100,292,910
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package hackerrank; import java.util.ArrayList; import java.util.Scanner; /** * Created by Gautam Vashisht on 7/3/2017. */ public class ArrayList2D { public static void main(String ar[]) { ArrayList<ArrayList<Integer>> al = new ArrayList<ArrayList<Integer>>(); Scanner s = new Scanner(System.in); int n = s.nextInt(); int cols,r,c; ArrayList<Integer> temp; for(int i =0 ;i <n; i++) { temp = new ArrayList<Integer>(); cols = s.nextInt(); for(int j=0;j<cols;j++) temp.add(s.nextInt()); al.add(temp); } //System.out.println(al.get(0).get(2)); n = s.nextInt(); for(int i =0;i<n;i++) { r = s.nextInt(); c = s.nextInt(); try { System.out.println(al.get(r-1).get(c-1)); } catch(Exception e) { System.out.println("ERROR!"); } } } }
UTF-8
Java
1,078
java
ArrayList2D.java
Java
[ { "context": ";\r\nimport java.util.Scanner;\r\n\r\n/**\r\n * Created by Gautam Vashisht on 7/3/2017.\r\n */\r\npublic class ArrayList2D {\r\n\r\n", "end": 115, "score": 0.9998534321784973, "start": 100, "tag": "NAME", "value": "Gautam Vashisht" } ]
null
[]
package hackerrank; import java.util.ArrayList; import java.util.Scanner; /** * Created by <NAME> on 7/3/2017. */ public class ArrayList2D { public static void main(String ar[]) { ArrayList<ArrayList<Integer>> al = new ArrayList<ArrayList<Integer>>(); Scanner s = new Scanner(System.in); int n = s.nextInt(); int cols,r,c; ArrayList<Integer> temp; for(int i =0 ;i <n; i++) { temp = new ArrayList<Integer>(); cols = s.nextInt(); for(int j=0;j<cols;j++) temp.add(s.nextInt()); al.add(temp); } //System.out.println(al.get(0).get(2)); n = s.nextInt(); for(int i =0;i<n;i++) { r = s.nextInt(); c = s.nextInt(); try { System.out.println(al.get(r-1).get(c-1)); } catch(Exception e) { System.out.println("ERROR!"); } } } }
1,069
0.444341
0.431354
47
20.936171
18.021742
79
false
false
0
0
0
0
0
0
0.553191
false
false
0
b88a718a6a2d5635df2574db06aa9a2db8e84e07
32,530,082,355,216
fea1504c974cee16205cd2ee2f54d142f503d291
/src/main/java/com/lming/chcservice/service/HospitalService.java
8a52a434f4023f08c0ecbf3bf3709cce63517107
[]
no_license
shinyzo/chcservice
https://github.com/shinyzo/chcservice
df9f2b0aa44287d4e4f0da69337ff69b065e9ff5
fd169e524d952480db45d6a7069ced965c6936d8
refs/heads/master
2021-05-07T13:39:13.694000
2017-11-29T10:19:14
2017-11-29T10:19:14
109,595,795
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lming.chcservice.service; import com.lming.chcservice.entity.Hospital; import java.util.List; public interface HospitalService { public List<Hospital> findAll(); }
UTF-8
Java
184
java
HospitalService.java
Java
[]
null
[]
package com.lming.chcservice.service; import com.lming.chcservice.entity.Hospital; import java.util.List; public interface HospitalService { public List<Hospital> findAll(); }
184
0.777174
0.777174
10
17.4
17.928747
44
false
false
0
0
0
0
0
0
0.4
false
false
0
7c9639274f399f08e29ae13dae23e99e35f11ccb
3,375,844,339,748
1a41a5b6a5a916fe2c695548fb6763efdb1d1e32
/workspace/P0/src/P0.java
686acdab61d4ec01bd499b2fac98ce320f210652
[]
no_license
IanTheGuitarGuy/Vurt
https://github.com/IanTheGuitarGuy/Vurt
15d52868833b476aa6535e968b1586629ab3447b
8ae9c3ddf091e0779964c93efb5b5903457429e4
refs/heads/master
2021-05-28T12:33:18.093000
2014-10-01T22:13:44
2014-10-01T22:13:44
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// P0 Assignment // Author: Ian Arcuri // Date: Aug 26, 2014 // Class: CS160 // Email: arcuri.ian@gmail.com public class P0 { public static void main(String[] args) { System.out.println("Hello World!"); } }
UTF-8
Java
222
java
P0.java
Java
[ { "context": "// P0 Assignment\n// Author: Ian Arcuri\n// Date: Aug 26, 2014\n// Class: CS160\n// Email: a", "end": 38, "score": 0.9998798370361328, "start": 28, "tag": "NAME", "value": "Ian Arcuri" }, { "context": "ri\n// Date: Aug 26, 2014\n// Class: CS160\n// Email: arcuri.ian@gmail.com\n\npublic class P0 {\n\n\tpublic static void main(Stri", "end": 107, "score": 0.9999302625656128, "start": 87, "tag": "EMAIL", "value": "arcuri.ian@gmail.com" } ]
null
[]
// P0 Assignment // Author: <NAME> // Date: Aug 26, 2014 // Class: CS160 // Email: <EMAIL> public class P0 { public static void main(String[] args) { System.out.println("Hello World!"); } }
205
0.635135
0.585586
15
13.8
13.929345
41
false
false
0
0
0
0
0
0
0.666667
false
false
0
1ccd1c717c549230f053074b0b67ff1610238025
23,072,564,372,132
b82c9ee10977e9b9e6e4996aac573f7cc2900e9a
/app/src/main/java/com/loslink/myview/widget/CleanNewView.java
5c0af2daf8e88467cf6235d7dc85900244caf470
[]
no_license
loslink/MyViewDemo
https://github.com/loslink/MyViewDemo
1ef17ee2b85085366b14f9076293bf32696ace1d
6cdabfc4e05c1df77e635ba4ee622c79ea1da283
refs/heads/master
2021-06-10T21:18:48.267000
2021-03-17T12:12:33
2021-03-17T12:12:33
139,956,502
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.loslink.myview.widget; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ValueAnimator; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ComposeShader; import android.graphics.LinearGradient; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PointF; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.RectF; import android.graphics.Shader; import android.graphics.drawable.BitmapDrawable; import androidx.annotation.ColorRes; import androidx.annotation.Nullable; import android.util.AttributeSet; import android.view.View; import android.view.animation.LinearInterpolator; import com.loslink.myview.R; import com.loslink.myview.model.Bubble; import com.loslink.myview.utils.DipToPx; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; public class CleanNewView extends View { private Paint itemPaint, circleWhitePaint, circleInnerPaint, bunblePaint; private long duration = 3000; private Context context; private float canvasWidth, canvasHeight; private float OUTER_RADIUS = 133; private float BAR_WIDTH = 18; private float BAR_HEIGHT = 5; private float INNER_OUT_RADIUS = 90; private float INNER_IN_RADIUS = 80; private float startDegree = -215, endDegree = 35f; private float currentDegree = startDegree; private float itemDegree = 5f; private ValueAnimator animator, repeatAnimator; private RectF itemRectF; private Path itemPath; private int colorBitWidth = 100, colorBitHeigth = 10; private Bitmap colorBitmap, startColorBitmap; private float levelProgress = 0f;//垃圾级别 private float junkFileSizeMax = 400f;//垃圾分界最高 private boolean isStart = false; private Runnable delayRunnable; private List<Bubble> bubbles = new ArrayList<>(); private float centerWidth = 100, centerHeight = 100; private List<ValueAnimator> animatorList; private MainCleanNewView.CleanState currentCleanState; private float junkFileSize; private int blueItemCount = 6; private Matrix shadowMatrix; private Bitmap shadowBitmap; public CleanNewView(Context context) { this(context, null); } public CleanNewView(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public CleanNewView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); this.context = context; init(); } public void init() { OUTER_RADIUS = DipToPx.dipToPx(context, OUTER_RADIUS); BAR_WIDTH = DipToPx.dipToPx(context, BAR_WIDTH); BAR_HEIGHT = DipToPx.dipToPx(context, BAR_HEIGHT); INNER_OUT_RADIUS = OUTER_RADIUS - BAR_WIDTH - DipToPx.dipToPx(context, 10); INNER_IN_RADIUS = INNER_OUT_RADIUS - DipToPx.dipToPx(context, 8); itemRectF = new RectF(OUTER_RADIUS - BAR_WIDTH, -BAR_HEIGHT / 2, OUTER_RADIUS, BAR_HEIGHT / 2); itemPath = new Path(); itemPath.addRoundRect(itemRectF, BAR_HEIGHT / 2, BAR_HEIGHT / 2, Path.Direction.CCW);//耗性能 itemPaint = new Paint(); itemPaint.setAntiAlias(true); itemPaint.setStyle(Paint.Style.FILL); itemPaint.setShadowLayer(4f, 2f, 2f, Color.parseColor("#22000000")); circleWhitePaint = new Paint(); circleWhitePaint.setAntiAlias(true); circleWhitePaint.setColor(Color.WHITE); circleWhitePaint.setStyle(Paint.Style.FILL); // circleWhitePaint.setShadowLayer(10,6f,6f,Color.parseColor("#11000000"));//需要关闭硬件加速 // setLayerType(LAYER_TYPE_SOFTWARE, null);//对单独的View在运行时阶段禁用硬件加速,阴影才有效(不要放onDraw里) circleInnerPaint = new Paint(); circleInnerPaint.setAntiAlias(true); circleInnerPaint.setColor(Color.RED); circleInnerPaint.setStyle(Paint.Style.FILL); bunblePaint = new Paint(); bunblePaint.setAntiAlias(true); bunblePaint.setColor(Color.WHITE); bunblePaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP)); shadowMatrix = new Matrix(); shadowBitmap = ((BitmapDrawable) getResources().getDrawable(R.mipmap.ic_main_clean_shadow)).getBitmap(); float resultW = (INNER_OUT_RADIUS + DipToPx.dipToPx(context, 6)) * 2f; float par = resultW / (float) shadowBitmap.getWidth(); shadowMatrix.setScale(par, par); shadowMatrix.postTranslate(-resultW / 2, -resultW / 2); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); canvasWidth = w; canvasHeight = h; } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); destroy(); } @Override protected void onDraw(Canvas canvas) { canvas.drawColor(getColor(R.color.cleanViewBgColor)); canvas.translate(canvas.getWidth() / 2, canvas.getHeight() / 2); drawOuterItems(canvas); drowCircle(canvas); } /** * 画内圈 * * @param canvas */ private void drowCircle(Canvas canvas) { float progress = (currentDegree - startDegree) / (endDegree - startDegree); if (currentCleanState == MainCleanNewView.CleanState.Checking) { progress = junkFileSize / junkFileSizeMax; if (progress > 1f) { progress = 1f; } } canvas.drawBitmap(shadowBitmap, shadowMatrix, circleWhitePaint); canvas.drawCircle(0, 0, INNER_OUT_RADIUS, circleWhitePaint); int pixel = getStartBitmapColor(progress); int a = Color.alpha(pixel); int r = Color.red(pixel); int g = Color.green(pixel); int b = Color.blue(pixel); int startColor = Color.argb(a * 2 / 3, r, g, b); LinearGradient linearGradient = new LinearGradient(-INNER_IN_RADIUS, -INNER_IN_RADIUS, INNER_IN_RADIUS - DipToPx.dipToPx(context, 80), INNER_IN_RADIUS - DipToPx.dipToPx(context, 80), pixel, getBitmapColor(progress), Shader.TileMode.CLAMP); circleInnerPaint.setShader(linearGradient); //调用saveLayer时,会生成了一个全新的bitmap,这个bitmap的大小就是我们指定的保存区域的大小,新生成的bitmap是全透明的,在调用saveLayer后所有的绘图操作都是在这个bitmap上进行的。 int layerID = canvas.saveLayer(-canvasWidth / 2, -canvasHeight / 2, canvasWidth / 2, canvasHeight / 2, circleInnerPaint, Canvas.ALL_SAVE_FLAG); canvas.drawCircle(0, 0, INNER_IN_RADIUS, circleInnerPaint); linearGradient = null; drawBunbles(canvas); } /** * 绘制小气泡 * * @param canvas */ private void drawBunbles(Canvas canvas) { canvas.save(); canvas.translate(-INNER_IN_RADIUS, -INNER_IN_RADIUS); for (Bubble bubble : bubbles) { if (bubble.pointF.x > 30) { bunblePaint.setAlpha(bubble.alph); canvas.drawCircle(bubble.pointF.x, bubble.pointF.y, bubble.radio, bunblePaint); } } canvas.restore(); } /** * 绘制外圈小块 * * @param canvas */ private void drawOuterItems(Canvas canvas) { canvas.save(); canvas.rotate(startDegree); float lastDegree = startDegree; int itemIndex = 0; while (true) { if (lastDegree > endDegree) { break; } switch (currentCleanState) { case Analysing: itemPaint.setColor(getColor(R.color.cleanItemGrayColor)); break; case AnalyseFinish: break; case Checking: int currentItem = (int) ((currentDegree - startDegree) / itemDegree); if (itemIndex >= (currentItem - blueItemCount) && itemIndex <= currentItem) { itemPaint.setColor(Color.parseColor("#3c8ef4")); } else { itemPaint.setColor(getColor(R.color.cleanItemGrayColor)); } break; case CheckFinish: if (isStart && lastDegree <= currentDegree) { float progress = (lastDegree - startDegree) / (endDegree - startDegree); itemPaint.setColor(getBitmapColor(progress)); } else { itemPaint.setColor(getColor(R.color.cleanItemGrayColor)); } break; case BestState: itemPaint.setColor(getColor(R.color.cleanItemGrayColor)); break; } canvas.drawPath(itemPath, itemPaint); canvas.rotate(itemDegree); lastDegree = lastDegree + itemDegree; itemIndex++; } canvas.restore(); } public void setCleanState(MainCleanNewView.CleanState cleanState) { currentCleanState = cleanState; switch (cleanState) { case Analysing: levelProgress = 0.5f; break; case AnalyseFinish: break; case Checking: levelProgress = 1f; break; case CheckFinish: break; case BestState: levelProgress = 0f; postInvalidate(); break; } } public void setJunkFileSize(float junkFileSize) { this.junkFileSize = junkFileSize; } /** * 开始动画 */ public void startAnimation() { if (currentCleanState == MainCleanNewView.CleanState.Checking) { startRepeatAnimation(); return; } if (animator != null && animator.isRunning()) { animator.cancel(); } cancelBunblesAnim(); if (delayRunnable != null) { removeCallbacks(delayRunnable); } animator = ValueAnimator.ofFloat(startDegree, endDegree); animator.setDuration(duration); animator.setInterpolator(new LinearInterpolator()); animator.setRepeatCount(0); animator.setRepeatMode(ValueAnimator.RESTART); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { currentDegree = (float) animation.getAnimatedValue(); postInvalidate(); } }); animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); delayRunnable = new Runnable() { @Override public void run() { cancelBunblesAnim(); } }; postDelayed(delayRunnable, 3000); } }); animator.start(); isStart = true; anima((int) (duration / 1000) * 2);//启动气泡 } public void startRepeatAnimation() { if (repeatAnimator != null && repeatAnimator.isRunning()) { repeatAnimator.cancel(); } repeatAnimator = ValueAnimator.ofFloat(startDegree, endDegree + (itemDegree * blueItemCount)); final long duration = 1500; repeatAnimator.setDuration(duration); repeatAnimator.setInterpolator(new LinearInterpolator()); repeatAnimator.setRepeatCount(ValueAnimator.INFINITE); repeatAnimator.setRepeatMode(ValueAnimator.RESTART); repeatAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { currentDegree = (float) animation.getAnimatedValue(); postInvalidate(); if (currentCleanState == MainCleanNewView.CleanState.CheckFinish) { repeatAnimator.cancel(); startAnimation(); } } }); repeatAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationRepeat(Animator animation) { super.onAnimationRepeat(animation); for (int i = 0; i < duration / 500; i++) { startBunblesAnim(i * 500); } } }); repeatAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); } }); for (int i = 0; i < duration / 500; i++) { startBunblesAnim(i * 500); } repeatAnimator.start(); isStart = true; } private Bubble getRodmBubble() { float startRadius = DipToPx.dipToPx(context, 3); float endRadius = DipToPx.dipToPx(context, 7); float radios = (float) (Math.random() * (endRadius - startRadius) + startRadius); float centerDX = (float) (Math.random() * centerWidth); float centerDY = (float) (Math.random() * centerHeight); PointF centerPointf = new PointF(INNER_IN_RADIUS + centerDX, INNER_IN_RADIUS + centerDY); float startDX = (float) (Math.random() * INNER_IN_RADIUS * 2); float startDY = INNER_IN_RADIUS * 2; PointF startPointF = new PointF(startDX, startDY); float endDX = (float) (Math.random() * INNER_IN_RADIUS * 2); float endDY = (float) (Math.random() * (INNER_IN_RADIUS - centerHeight / 2)); PointF endPointF = new PointF(endDX, endDY); return new Bubble(startPointF, centerPointf, endPointF, radios, INNER_IN_RADIUS * 2); } private void anima(int count) { bubbles.clear(); if (count == 0) count = 1; for (int i = 0; i < count; i++) startBunblesAnim(i * 500); } private void startBunblesAnim(long delay) { final List<Bubble> bubbles1 = new ArrayList<>(); final int count = 2 + (int) (Math.random() * 3); for (int x = 0; x < count; x++) { bubbles1.add(getRodmBubble()); bubbles.addAll(bubbles1); } ValueAnimator animator = ValueAnimator.ofFloat(0f, 1f, 2f); animator.setDuration(3000); animator.setStartDelay(delay); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { float value = (float) animation.getAnimatedValue(); boolean isSpeed = false; if (value < 1) { value = (3.8f - 1.8f * value) * value * 0.5f; } else { value = value - 1; value = (0.4f + 1.6f * value) * value * 0.5f; isSpeed = true; } for (int x = 0; x < count; x++) { bubbles1.get(x).notifyData(value, isSpeed); } postInvalidate(); } }); animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); for (Bubble bubble : bubbles1) bubbles.remove(bubble); } }); animator.start(); if (null == animatorList) { animatorList = new CopyOnWriteArrayList<>(); } animatorList.add(animator); } private void cancelBunblesAnim() { if (null != animatorList && animatorList.size() > 0) { for (ValueAnimator animator : animatorList) { if (animator != null && animator.isRunning()) { animator.cancel(); } if (null != animator) { animator.removeAllUpdateListeners(); animator.removeAllListeners(); } } animatorList.clear(); } if (null != bubbles) { bubbles.clear(); } } private int getBitmapColor(float progress) { if (colorBitmap == null || colorBitmap.isRecycled()) { int[] colors = new int[]{getColor(R.color.colorList1), getColor(R.color.colorList2), getColor(R.color.colorList3), getColor(R.color.colorList4), getColor(R.color.colorList5)}; colorBitmap = getColorBitmap(colors); } float x, y = colorBitHeigth / 2; if (progress < 0) { progress = 0; } else if (progress > 1) { progress = 1; } x = colorBitWidth * progress * levelProgress; // 为了防止越界 int intX = (int) x; int intY = (int) y; if (intX >= colorBitmap.getWidth()) { intX = colorBitmap.getWidth() - 1; } if (intY >= colorBitmap.getHeight()) { intY = colorBitmap.getHeight() - 1; } return colorBitmap.getPixel(intX, intY); } private int getStartBitmapColor(float progress) { if (startColorBitmap == null || startColorBitmap.isRecycled()) { int[] colors = new int[]{getColor(R.color.startColorList1), getColor(R.color.startColorList2), getColor(R.color.startColorList3), getColor(R.color.startColorList4), getColor(R.color.startColorList5)}; startColorBitmap = getColorBitmap(colors); } float x, y = colorBitHeigth / 2; if (progress < 0) { progress = 0; } else if (progress > 1) { progress = 1; } x = colorBitWidth * progress * levelProgress; // 为了防止越界 int intX = (int) x; int intY = (int) y; if (intX >= startColorBitmap.getWidth()) { intX = startColorBitmap.getWidth() - 1; } if (intY >= startColorBitmap.getHeight()) { intY = startColorBitmap.getHeight() - 1; } return startColorBitmap.getPixel(intX, intY); } private Bitmap getColorBitmap(int[] colors) { Bitmap mColorAreaBmp = null; int width = colorBitWidth, height = colorBitHeigth; Paint leftPaint = new Paint(); leftPaint.setStrokeWidth(1); mColorAreaBmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(mColorAreaBmp); int bitmapWidth = mColorAreaBmp.getWidth(); int bitmapHeight = mColorAreaBmp.getHeight(); Shader leftShader = new LinearGradient(0, bitmapHeight / 2, bitmapWidth, bitmapHeight / 2, colors, null, Shader.TileMode.CLAMP); ComposeShader shader = new ComposeShader(leftShader, leftShader, PorterDuff.Mode.SCREEN); leftPaint.setShader(leftShader); canvas.drawRect(0, 0, width, height, leftPaint); return mColorAreaBmp; } private int getColor(@ColorRes int color) { return context.getResources().getColor(color); } public void destroy() { if (animator != null && animator.isRunning()) { animator.cancel(); } if (repeatAnimator != null && repeatAnimator.isRunning()) { repeatAnimator.cancel(); } if (colorBitmap != null && !colorBitmap.isRecycled()) { colorBitmap.recycle(); } if (startColorBitmap != null && !startColorBitmap.isRecycled()) { startColorBitmap.recycle(); } cancelBunblesAnim(); } }
UTF-8
Java
20,231
java
CleanNewView.java
Java
[]
null
[]
package com.loslink.myview.widget; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ValueAnimator; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ComposeShader; import android.graphics.LinearGradient; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PointF; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.RectF; import android.graphics.Shader; import android.graphics.drawable.BitmapDrawable; import androidx.annotation.ColorRes; import androidx.annotation.Nullable; import android.util.AttributeSet; import android.view.View; import android.view.animation.LinearInterpolator; import com.loslink.myview.R; import com.loslink.myview.model.Bubble; import com.loslink.myview.utils.DipToPx; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; public class CleanNewView extends View { private Paint itemPaint, circleWhitePaint, circleInnerPaint, bunblePaint; private long duration = 3000; private Context context; private float canvasWidth, canvasHeight; private float OUTER_RADIUS = 133; private float BAR_WIDTH = 18; private float BAR_HEIGHT = 5; private float INNER_OUT_RADIUS = 90; private float INNER_IN_RADIUS = 80; private float startDegree = -215, endDegree = 35f; private float currentDegree = startDegree; private float itemDegree = 5f; private ValueAnimator animator, repeatAnimator; private RectF itemRectF; private Path itemPath; private int colorBitWidth = 100, colorBitHeigth = 10; private Bitmap colorBitmap, startColorBitmap; private float levelProgress = 0f;//垃圾级别 private float junkFileSizeMax = 400f;//垃圾分界最高 private boolean isStart = false; private Runnable delayRunnable; private List<Bubble> bubbles = new ArrayList<>(); private float centerWidth = 100, centerHeight = 100; private List<ValueAnimator> animatorList; private MainCleanNewView.CleanState currentCleanState; private float junkFileSize; private int blueItemCount = 6; private Matrix shadowMatrix; private Bitmap shadowBitmap; public CleanNewView(Context context) { this(context, null); } public CleanNewView(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public CleanNewView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); this.context = context; init(); } public void init() { OUTER_RADIUS = DipToPx.dipToPx(context, OUTER_RADIUS); BAR_WIDTH = DipToPx.dipToPx(context, BAR_WIDTH); BAR_HEIGHT = DipToPx.dipToPx(context, BAR_HEIGHT); INNER_OUT_RADIUS = OUTER_RADIUS - BAR_WIDTH - DipToPx.dipToPx(context, 10); INNER_IN_RADIUS = INNER_OUT_RADIUS - DipToPx.dipToPx(context, 8); itemRectF = new RectF(OUTER_RADIUS - BAR_WIDTH, -BAR_HEIGHT / 2, OUTER_RADIUS, BAR_HEIGHT / 2); itemPath = new Path(); itemPath.addRoundRect(itemRectF, BAR_HEIGHT / 2, BAR_HEIGHT / 2, Path.Direction.CCW);//耗性能 itemPaint = new Paint(); itemPaint.setAntiAlias(true); itemPaint.setStyle(Paint.Style.FILL); itemPaint.setShadowLayer(4f, 2f, 2f, Color.parseColor("#22000000")); circleWhitePaint = new Paint(); circleWhitePaint.setAntiAlias(true); circleWhitePaint.setColor(Color.WHITE); circleWhitePaint.setStyle(Paint.Style.FILL); // circleWhitePaint.setShadowLayer(10,6f,6f,Color.parseColor("#11000000"));//需要关闭硬件加速 // setLayerType(LAYER_TYPE_SOFTWARE, null);//对单独的View在运行时阶段禁用硬件加速,阴影才有效(不要放onDraw里) circleInnerPaint = new Paint(); circleInnerPaint.setAntiAlias(true); circleInnerPaint.setColor(Color.RED); circleInnerPaint.setStyle(Paint.Style.FILL); bunblePaint = new Paint(); bunblePaint.setAntiAlias(true); bunblePaint.setColor(Color.WHITE); bunblePaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP)); shadowMatrix = new Matrix(); shadowBitmap = ((BitmapDrawable) getResources().getDrawable(R.mipmap.ic_main_clean_shadow)).getBitmap(); float resultW = (INNER_OUT_RADIUS + DipToPx.dipToPx(context, 6)) * 2f; float par = resultW / (float) shadowBitmap.getWidth(); shadowMatrix.setScale(par, par); shadowMatrix.postTranslate(-resultW / 2, -resultW / 2); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); canvasWidth = w; canvasHeight = h; } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); destroy(); } @Override protected void onDraw(Canvas canvas) { canvas.drawColor(getColor(R.color.cleanViewBgColor)); canvas.translate(canvas.getWidth() / 2, canvas.getHeight() / 2); drawOuterItems(canvas); drowCircle(canvas); } /** * 画内圈 * * @param canvas */ private void drowCircle(Canvas canvas) { float progress = (currentDegree - startDegree) / (endDegree - startDegree); if (currentCleanState == MainCleanNewView.CleanState.Checking) { progress = junkFileSize / junkFileSizeMax; if (progress > 1f) { progress = 1f; } } canvas.drawBitmap(shadowBitmap, shadowMatrix, circleWhitePaint); canvas.drawCircle(0, 0, INNER_OUT_RADIUS, circleWhitePaint); int pixel = getStartBitmapColor(progress); int a = Color.alpha(pixel); int r = Color.red(pixel); int g = Color.green(pixel); int b = Color.blue(pixel); int startColor = Color.argb(a * 2 / 3, r, g, b); LinearGradient linearGradient = new LinearGradient(-INNER_IN_RADIUS, -INNER_IN_RADIUS, INNER_IN_RADIUS - DipToPx.dipToPx(context, 80), INNER_IN_RADIUS - DipToPx.dipToPx(context, 80), pixel, getBitmapColor(progress), Shader.TileMode.CLAMP); circleInnerPaint.setShader(linearGradient); //调用saveLayer时,会生成了一个全新的bitmap,这个bitmap的大小就是我们指定的保存区域的大小,新生成的bitmap是全透明的,在调用saveLayer后所有的绘图操作都是在这个bitmap上进行的。 int layerID = canvas.saveLayer(-canvasWidth / 2, -canvasHeight / 2, canvasWidth / 2, canvasHeight / 2, circleInnerPaint, Canvas.ALL_SAVE_FLAG); canvas.drawCircle(0, 0, INNER_IN_RADIUS, circleInnerPaint); linearGradient = null; drawBunbles(canvas); } /** * 绘制小气泡 * * @param canvas */ private void drawBunbles(Canvas canvas) { canvas.save(); canvas.translate(-INNER_IN_RADIUS, -INNER_IN_RADIUS); for (Bubble bubble : bubbles) { if (bubble.pointF.x > 30) { bunblePaint.setAlpha(bubble.alph); canvas.drawCircle(bubble.pointF.x, bubble.pointF.y, bubble.radio, bunblePaint); } } canvas.restore(); } /** * 绘制外圈小块 * * @param canvas */ private void drawOuterItems(Canvas canvas) { canvas.save(); canvas.rotate(startDegree); float lastDegree = startDegree; int itemIndex = 0; while (true) { if (lastDegree > endDegree) { break; } switch (currentCleanState) { case Analysing: itemPaint.setColor(getColor(R.color.cleanItemGrayColor)); break; case AnalyseFinish: break; case Checking: int currentItem = (int) ((currentDegree - startDegree) / itemDegree); if (itemIndex >= (currentItem - blueItemCount) && itemIndex <= currentItem) { itemPaint.setColor(Color.parseColor("#3c8ef4")); } else { itemPaint.setColor(getColor(R.color.cleanItemGrayColor)); } break; case CheckFinish: if (isStart && lastDegree <= currentDegree) { float progress = (lastDegree - startDegree) / (endDegree - startDegree); itemPaint.setColor(getBitmapColor(progress)); } else { itemPaint.setColor(getColor(R.color.cleanItemGrayColor)); } break; case BestState: itemPaint.setColor(getColor(R.color.cleanItemGrayColor)); break; } canvas.drawPath(itemPath, itemPaint); canvas.rotate(itemDegree); lastDegree = lastDegree + itemDegree; itemIndex++; } canvas.restore(); } public void setCleanState(MainCleanNewView.CleanState cleanState) { currentCleanState = cleanState; switch (cleanState) { case Analysing: levelProgress = 0.5f; break; case AnalyseFinish: break; case Checking: levelProgress = 1f; break; case CheckFinish: break; case BestState: levelProgress = 0f; postInvalidate(); break; } } public void setJunkFileSize(float junkFileSize) { this.junkFileSize = junkFileSize; } /** * 开始动画 */ public void startAnimation() { if (currentCleanState == MainCleanNewView.CleanState.Checking) { startRepeatAnimation(); return; } if (animator != null && animator.isRunning()) { animator.cancel(); } cancelBunblesAnim(); if (delayRunnable != null) { removeCallbacks(delayRunnable); } animator = ValueAnimator.ofFloat(startDegree, endDegree); animator.setDuration(duration); animator.setInterpolator(new LinearInterpolator()); animator.setRepeatCount(0); animator.setRepeatMode(ValueAnimator.RESTART); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { currentDegree = (float) animation.getAnimatedValue(); postInvalidate(); } }); animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); delayRunnable = new Runnable() { @Override public void run() { cancelBunblesAnim(); } }; postDelayed(delayRunnable, 3000); } }); animator.start(); isStart = true; anima((int) (duration / 1000) * 2);//启动气泡 } public void startRepeatAnimation() { if (repeatAnimator != null && repeatAnimator.isRunning()) { repeatAnimator.cancel(); } repeatAnimator = ValueAnimator.ofFloat(startDegree, endDegree + (itemDegree * blueItemCount)); final long duration = 1500; repeatAnimator.setDuration(duration); repeatAnimator.setInterpolator(new LinearInterpolator()); repeatAnimator.setRepeatCount(ValueAnimator.INFINITE); repeatAnimator.setRepeatMode(ValueAnimator.RESTART); repeatAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { currentDegree = (float) animation.getAnimatedValue(); postInvalidate(); if (currentCleanState == MainCleanNewView.CleanState.CheckFinish) { repeatAnimator.cancel(); startAnimation(); } } }); repeatAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationRepeat(Animator animation) { super.onAnimationRepeat(animation); for (int i = 0; i < duration / 500; i++) { startBunblesAnim(i * 500); } } }); repeatAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); } }); for (int i = 0; i < duration / 500; i++) { startBunblesAnim(i * 500); } repeatAnimator.start(); isStart = true; } private Bubble getRodmBubble() { float startRadius = DipToPx.dipToPx(context, 3); float endRadius = DipToPx.dipToPx(context, 7); float radios = (float) (Math.random() * (endRadius - startRadius) + startRadius); float centerDX = (float) (Math.random() * centerWidth); float centerDY = (float) (Math.random() * centerHeight); PointF centerPointf = new PointF(INNER_IN_RADIUS + centerDX, INNER_IN_RADIUS + centerDY); float startDX = (float) (Math.random() * INNER_IN_RADIUS * 2); float startDY = INNER_IN_RADIUS * 2; PointF startPointF = new PointF(startDX, startDY); float endDX = (float) (Math.random() * INNER_IN_RADIUS * 2); float endDY = (float) (Math.random() * (INNER_IN_RADIUS - centerHeight / 2)); PointF endPointF = new PointF(endDX, endDY); return new Bubble(startPointF, centerPointf, endPointF, radios, INNER_IN_RADIUS * 2); } private void anima(int count) { bubbles.clear(); if (count == 0) count = 1; for (int i = 0; i < count; i++) startBunblesAnim(i * 500); } private void startBunblesAnim(long delay) { final List<Bubble> bubbles1 = new ArrayList<>(); final int count = 2 + (int) (Math.random() * 3); for (int x = 0; x < count; x++) { bubbles1.add(getRodmBubble()); bubbles.addAll(bubbles1); } ValueAnimator animator = ValueAnimator.ofFloat(0f, 1f, 2f); animator.setDuration(3000); animator.setStartDelay(delay); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { float value = (float) animation.getAnimatedValue(); boolean isSpeed = false; if (value < 1) { value = (3.8f - 1.8f * value) * value * 0.5f; } else { value = value - 1; value = (0.4f + 1.6f * value) * value * 0.5f; isSpeed = true; } for (int x = 0; x < count; x++) { bubbles1.get(x).notifyData(value, isSpeed); } postInvalidate(); } }); animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); for (Bubble bubble : bubbles1) bubbles.remove(bubble); } }); animator.start(); if (null == animatorList) { animatorList = new CopyOnWriteArrayList<>(); } animatorList.add(animator); } private void cancelBunblesAnim() { if (null != animatorList && animatorList.size() > 0) { for (ValueAnimator animator : animatorList) { if (animator != null && animator.isRunning()) { animator.cancel(); } if (null != animator) { animator.removeAllUpdateListeners(); animator.removeAllListeners(); } } animatorList.clear(); } if (null != bubbles) { bubbles.clear(); } } private int getBitmapColor(float progress) { if (colorBitmap == null || colorBitmap.isRecycled()) { int[] colors = new int[]{getColor(R.color.colorList1), getColor(R.color.colorList2), getColor(R.color.colorList3), getColor(R.color.colorList4), getColor(R.color.colorList5)}; colorBitmap = getColorBitmap(colors); } float x, y = colorBitHeigth / 2; if (progress < 0) { progress = 0; } else if (progress > 1) { progress = 1; } x = colorBitWidth * progress * levelProgress; // 为了防止越界 int intX = (int) x; int intY = (int) y; if (intX >= colorBitmap.getWidth()) { intX = colorBitmap.getWidth() - 1; } if (intY >= colorBitmap.getHeight()) { intY = colorBitmap.getHeight() - 1; } return colorBitmap.getPixel(intX, intY); } private int getStartBitmapColor(float progress) { if (startColorBitmap == null || startColorBitmap.isRecycled()) { int[] colors = new int[]{getColor(R.color.startColorList1), getColor(R.color.startColorList2), getColor(R.color.startColorList3), getColor(R.color.startColorList4), getColor(R.color.startColorList5)}; startColorBitmap = getColorBitmap(colors); } float x, y = colorBitHeigth / 2; if (progress < 0) { progress = 0; } else if (progress > 1) { progress = 1; } x = colorBitWidth * progress * levelProgress; // 为了防止越界 int intX = (int) x; int intY = (int) y; if (intX >= startColorBitmap.getWidth()) { intX = startColorBitmap.getWidth() - 1; } if (intY >= startColorBitmap.getHeight()) { intY = startColorBitmap.getHeight() - 1; } return startColorBitmap.getPixel(intX, intY); } private Bitmap getColorBitmap(int[] colors) { Bitmap mColorAreaBmp = null; int width = colorBitWidth, height = colorBitHeigth; Paint leftPaint = new Paint(); leftPaint.setStrokeWidth(1); mColorAreaBmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(mColorAreaBmp); int bitmapWidth = mColorAreaBmp.getWidth(); int bitmapHeight = mColorAreaBmp.getHeight(); Shader leftShader = new LinearGradient(0, bitmapHeight / 2, bitmapWidth, bitmapHeight / 2, colors, null, Shader.TileMode.CLAMP); ComposeShader shader = new ComposeShader(leftShader, leftShader, PorterDuff.Mode.SCREEN); leftPaint.setShader(leftShader); canvas.drawRect(0, 0, width, height, leftPaint); return mColorAreaBmp; } private int getColor(@ColorRes int color) { return context.getResources().getColor(color); } public void destroy() { if (animator != null && animator.isRunning()) { animator.cancel(); } if (repeatAnimator != null && repeatAnimator.isRunning()) { repeatAnimator.cancel(); } if (colorBitmap != null && !colorBitmap.isRecycled()) { colorBitmap.recycle(); } if (startColorBitmap != null && !startColorBitmap.isRecycled()) { startColorBitmap.recycle(); } cancelBunblesAnim(); } }
20,231
0.590943
0.580663
546
35.520145
26.963762
212
false
false
0
0
0
0
0
0
0.763736
false
false
0
aba6ce2dae6d0a7ccb229f735c4022bdc712b8a8
31,756,988,224,209
caf82947f79acfebc89959bf2a0d19bdefbe020b
/src/Home/Week2/Array/While/Week2Home3_9.java
3083912f4ebac9e5d4a3e06c3770d1e72b52099d
[]
no_license
AnastasiyaSeva/ABC17
https://github.com/AnastasiyaSeva/ABC17
10c21fa5a62f43eb2b10d7d03049f4fc47c6b7cd
d8a5e0164e32b5d490599989fe0b044440f6681e
refs/heads/master
2021-01-20T19:27:25.037000
2016-07-09T15:34:51
2016-07-09T15:34:51
62,956,091
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Home.Week2.Array.While; import ua.artcode.Utils.ArrayUtils; import java.util.Scanner; /** * Задать два массива случайными числами от 25 до 75. Определить у какого из массивов больше парных елементов. */ public class Week2Home3_9 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter array leght"); int size = sc.nextInt(); System.out.println("Enter array interval from a"); int a = sc.nextInt(); System.out.println("Enter array to b"); int b = sc.nextInt(); int min = a; int max = b; int cout = 0; int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = (int) (min + Math.random() * (max - min)); if (array[i] % 2 == 0) cout = cout + 1; } ArrayUtils.printArray(array); System.out.println(" Count of double elements array " + cout); System.out.println(); int cout1 = 0; int[] array1 = new int[size]; for (int i = 0; i < size; i++) { array1[i] = (int) (min + Math.random() * (max - min)); if (array[i] % 2 == 0) cout1 = cout1 + 1; } ArrayUtils.printArray(array1); System.out.println(" count double counts of array1 is " + cout1); System.out.println(" count double counts of array1 is " + cout + "; count1 double counts of array1 is " + cout1); } }
UTF-8
Java
1,601
java
Week2Home3_9.java
Java
[]
null
[]
package Home.Week2.Array.While; import ua.artcode.Utils.ArrayUtils; import java.util.Scanner; /** * Задать два массива случайными числами от 25 до 75. Определить у какого из массивов больше парных елементов. */ public class Week2Home3_9 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter array leght"); int size = sc.nextInt(); System.out.println("Enter array interval from a"); int a = sc.nextInt(); System.out.println("Enter array to b"); int b = sc.nextInt(); int min = a; int max = b; int cout = 0; int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = (int) (min + Math.random() * (max - min)); if (array[i] % 2 == 0) cout = cout + 1; } ArrayUtils.printArray(array); System.out.println(" Count of double elements array " + cout); System.out.println(); int cout1 = 0; int[] array1 = new int[size]; for (int i = 0; i < size; i++) { array1[i] = (int) (min + Math.random() * (max - min)); if (array[i] % 2 == 0) cout1 = cout1 + 1; } ArrayUtils.printArray(array1); System.out.println(" count double counts of array1 is " + cout1); System.out.println(" count double counts of array1 is " + cout + "; count1 double counts of array1 is " + cout1); } }
1,601
0.540897
0.521108
54
27.074074
27.447493
123
false
false
0
0
0
0
0
0
0.574074
false
false
0
9c9414c2979d4d227a8e082fcb43185ea2ecfb1d
35,768,487,646,730
f5a7fff33a7687a8b300a563c29c316f8d4c35c3
/src/entity/Aleatorio.java
c22b6ff1bf10e91b6febb41bb14839d874e50ccd
[]
no_license
rodrigoRolim/software-testing
https://github.com/rodrigoRolim/software-testing
087eea5b5dce0015f97ad8453dfc620b6e05260e
8cbbb057db20238f3c9fede23ff2fca93f11f7e7
refs/heads/master
2020-03-27T00:14:58.831000
2018-08-21T19:34:06
2018-08-21T19:34:06
145,607,717
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 entity; /** * * @author rod_v */ import java.util.Random; public class Aleatorio { public int gerarNumeroAleatorio (int inicio, int fim) { if (inicio < 0 || fim < 0) { return -1; } if (inicio >= fim) { return -1; } int diff = fim - inicio + 1; Random random = new Random(); int tInt = random.nextInt(diff); return inicio + tInt; } }
UTF-8
Java
644
java
Aleatorio.java
Java
[ { "context": "itor.\r\n */\r\npackage entity;\r\n\r\n/**\r\n *\r\n * @author rod_v\r\n */\r\nimport java.util.Random;\r\npublic class Alea", "end": 234, "score": 0.9996253252029419, "start": 229, "tag": "USERNAME", "value": "rod_v" } ]
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 entity; /** * * @author rod_v */ import java.util.Random; public class Aleatorio { public int gerarNumeroAleatorio (int inicio, int fim) { if (inicio < 0 || fim < 0) { return -1; } if (inicio >= fim) { return -1; } int diff = fim - inicio + 1; Random random = new Random(); int tInt = random.nextInt(diff); return inicio + tInt; } }
644
0.559006
0.551242
27
21.925926
20.368687
79
false
false
0
0
0
0
0
0
0.518519
false
false
0
977810f80f6fe469414f5e9335ade56cf20e6ff3
154,618,858,527
74ffa29b647aa0eba5288b9b67733e3185472b9f
/UI/text/User_Interface_Text.java
c01a1b31cc62f758b34aa0030afae3043c1e8c8a
[]
no_license
I3ryI3e/jubilant-umbrella
https://github.com/I3ryI3e/jubilant-umbrella
c78721839003d0661993e459ed62917697ab5bad
4b56875f6e225344c9b97388a36f54b469748777
refs/heads/master
2020-03-09T19:22:01.169000
2018-06-17T12:03:47
2018-06-17T12:03:47
128,956,308
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package UI.text; import Model.*; import State_Machine.*; import java.io.*; import java.util.Observable; import java.util.Observer; import java.util.Scanner; public class User_Interface_Text implements Constants, Observer{ private ObservableGame game; private boolean quit = false; private int opt; public User_Interface_Text(ObservableGame game){ this.game= game; game.addObserver(this); } private int read_int(){ Scanner in = new Scanner(System.in); while(!in.hasNextInt()){ in.next(); } return in.nextInt(); } private String read_Text(){ Scanner in = new Scanner(System.in); return in.nextLine(); } public void initial_text(){ System.out.println("\n9 CARD SIEGE!!\n"); System.out.println("\t1- New Game\n\t2- Load Game\n\t3- Quit"); opt=read_int(); switch(opt){ case 1: game.setup(); break; case 2: load_text(); break; case 3: quit = true; default: break; } } public void wait_action_text(){ System.out.println(game.drawBoards()); System.out.println(game.drawCardDay()); System.out.println(wait_action_text_menu()); opt=read_int(); switch(opt){ case 1: game.stateArchers(); break; case 2: game.stateBoilling(); break; case 3: game.stateCloseCombat(); break; case 4: game.coupure(); break; case 5: game.stateRally(); break; case 6: game.stateTunnel(); break; case 7: game.supplyRaid(); break; case 8: game.sabotage(); break; case 9: game.stateBuyAction(); break; case 10: game.endTurn(); break; case 11: save_text(); break; case 12: quit=true; } } public String wait_action_text_menu(){ StringBuilder str = new StringBuilder(); str.append("Player Action:\n"); str.append(game.canArchers()?"\t1- Archers Attack\n":""); str.append(game.canBoiling()?"\t2- Boilling Water Attack\n":""); str.append(game.canCloseCombat()?"\t3- Close Combat Attack\n":""); str.append(game.canCoupure()?"\t4- Coupure\n":""); str.append(game.canRally()?"\t5- Rally Troops\n":""); str.append(game.playerStillHasActionsLeft() && (!game.getSabAndRaidStateActive())?"\t6- Tunnel Action\n":""); str.append(game.canSupply()?"\t7- Supply Raid\n":""); str.append(game.canSabotage()?"\t8- Sabotage\n":""); str.append(game.canBuyAction()?"\t9- Buy Action\n":""); str.append("\t10- End Turn\n\t11- Save game\n" + "\n\t12- Quit\n"); return str.toString(); } public void draw_card_text(){ System.out.println("\n\t1- Draw card\n" + "\t2- Save game\n" + "\t3- Load game\n" + "\t4- Quit\n"); opt = read_int(); switch(opt){ case 1: game.drawCard(); break; case 2: save_text(); break; case 3: load_text(); break; case 4: quit=true; } } private void archersText() { StringBuilder str = new StringBuilder(); System.out.println(game.getEnemy()); str.append(game.ladderOnStartingPosition()?"":"\t1- Ladder\n"); str.append(game.batteringRamOnStartingPosition()?"":"\t2- Battering Ram\n"); str.append(game.siegeTowerOnStartingPosition()?"":(game.siegeTowerExists()?"\t3- Siege Tower\n":"")); str.append("\t4- return\n"); System.out.println(str.toString()); opt = read_int(); switch(opt){ case 1: game.archers(Enemy_Attack.LADDER); break; case 2: game.archers(Enemy_Attack.BATTERING_RAM); break; case 3: game.archers(Enemy_Attack.SIEGE_TOWER); break; case 4: game.returnWaitAction(); } } private void boillingText() { StringBuilder str = new StringBuilder(); System.out.println(game.getEnemy()); str.append((game.isLadderOnCircleSpace()?"\t1- Ladder\n":"")); str.append((game.isBatteringRamOnCircleSpace()?"\t2- Battering Ram\n":"")); str.append((game.isSiegeTowerOnCircleSpace()?"\t3- Siege Tower\n":"")); str.append("\t4- return\n"); System.out.println(str.toString()); opt = read_int(); switch(opt){ case 1: game.boiling(Enemy_Attack.LADDER); break; case 2: game.boiling(Enemy_Attack.BATTERING_RAM); break; case 3: game.boiling(Enemy_Attack.SIEGE_TOWER); break; case 4: game.returnWaitAction(); } } private void rallyText() { StringBuilder str = new StringBuilder(); System.out.println(game.getPlayer()); str.append((game.canDecreaseSupply()?"\t1- Spend 1 supply to get +1DRM\n":"")).append("\t2- Normal try\n").append("\t3- return\n"); System.out.println(str.toString()); opt = read_int(); switch(opt){ case 1: game.rallyPlus1DRM(); case 2: game.normalRally(); case 3: game.returnWaitAction(); } } private void tunnelText(){ StringBuilder str = new StringBuilder(); System.out.println(game.getPlayer()); str.append(game.canUseTunnelMovement()?(game.canMakeFreeMove()?"\t1- Free movement\n\t2- Fast movement":"\t2- Fast movement") :(game.onEnemyLine()||game.onCastleSpace()?"\n\t3- Get inside the Tunnel":"")).append("\n\t4- Return"); System.out.println(str.toString()); opt = read_int(); switch(opt){ case 1: game.tunnelFree(); break; case 2: game.tunnelFast(); break; case 3: game.tunnelGetInside(); break; case 4: game.returnWaitAction(); } } private void closeCombatText() { StringBuilder str = new StringBuilder(); System.out.println(game.getEnemy()); System.out.println("Still has " + game.numberOfActionsAvailable()+ " actions left"); str.append(game.isLadderOnCloseCombat()?"\t1- Attack Ladder\n":""); str.append(game.isBatteringRamOnCloseCombat()?"\t2- Attack Battering Ram\n":""); str.append(game.isSiegeTowerOnCloseCombat()?"\t1- Attack Siege Tower\n":""); str.append(game.canBuyAction()?"\t4- Buy Action\n":""); str.append(game.check2Enemy()?"":"\t5- Return\n"); str.append("\t6- End Turn\n"); System.out.println(str.toString()); opt = read_int(); switch(opt){ case 1: game.closeCombat(Enemy_Attack.LADDER); break; case 2: game.closeCombat(Enemy_Attack.BATTERING_RAM); break; case 3: game.closeCombat(Enemy_Attack.SIEGE_TOWER); break; case 4: game.stateBuyAction(); break; case 5: if(game.check2Enemy()) game.returnWaitAction(); break; case 6: game.endTurn(); } } private void buyOneActionText() { StringBuilder str = new StringBuilder(); System.out.println(game.getPlayer()); str.append(game.canDecreaseSupply()?"\t1- Use one supply to get one more action\n":"").append(game.canDecreaseMorale()?"\t2- Use one morale to get one more action":"").append("\n\t3- Return"); System.out.println(str.toString()); opt = read_int(); switch(opt){ case 1: case 2: game.buyAction(opt); break; case 3: game.returnWaitAction(); } } private void gameOver_Text() { StringBuilder str = new StringBuilder(); System.out.println(game.drawBoards()); str.append("\t1- Return to menu"); str.append("\n\t2- Quit"); System.out.println("{Your castle has been overthrown by the enemy!}"); System.out.println(str.toString()); opt = read_int(); switch(opt){ case 1: game.returnInitialState(); break; case 2: quit=true; break; } } private void winGameText() { StringBuilder str = new StringBuilder(); System.out.println(game.drawBoards()); str.append("\t1- Return to menu"); str.append("\n\t2- Quit"); System.out.println("{Congratulations!!! You have successfully repelled the enemy!}"); System.out.println(str.toString()); opt = read_int(); switch(opt){ case 1: game.returnInitialState(); break; case 2: quit=true; break; } } public void run(){ States state =null; while(!quit){ state = game.getState(); if( state instanceof Initial_State){ initial_text(); }else if (state instanceof Wait_Draw_Card){ draw_card_text(); }else if( state instanceof Wait_Action){ wait_action_text(); }else if ( state instanceof Wait_Archers) { archersText(); }else if ( state instanceof Wait_Boiling) { boillingText(); }else if ( state instanceof Rally_Troops) { rallyText(); }else if (state instanceof Game_Over){ gameOver_Text(); }else if (state instanceof Wait_Tunnel){ tunnelText(); }else if (state instanceof Close_Combat){ closeCombatText(); }else if (state instanceof Buy_One_Action){ buyOneActionText(); }else if (state instanceof Win_Game){ winGameText(); } } } @Override public void update(Observable o, Object arg) { System.out.println(game.getText()); } private void load_text() { System.out.print("\nName of the file to load: "); String filename = read_Text(); if(filename == null || filename.isEmpty()) return; game.setGame(load_game(filename)); System.out.println("\nGame loaded\n"); } private Siege_Game load_game(String filename) { ObjectInputStream oistream = null; Siege_Game sg = null; try { oistream = new ObjectInputStream(new FileInputStream(filename)); sg = (Siege_Game) oistream.readObject(); } catch (FileNotFoundException ex) { System.err.println("Error: file doesn't exists\n" + ex.getMessage()); } catch (IOException | ClassNotFoundException ex) {} finally{ if(oistream != null){ try { oistream.close(); } catch (IOException ex) {} } } return sg; } private void save_text() { System.out.println("\nName of the file to save: "); String filename = read_Text(); if(filename == null || filename.isEmpty()) return; save_game(filename); System.out.println("\nGame saved\n"); } private void save_game(String filename) { ObjectOutputStream oostream = null; try { oostream = new ObjectOutputStream(new FileOutputStream(filename)); oostream.writeObject(this.game); } catch (FileNotFoundException ex) { System.err.println("Erro: ficheiro inexistente\n" + ex.getMessage()); } catch (IOException ex) {} finally{ if(oostream != null){ try { oostream.close(); } catch (IOException ex) {} } } } }
UTF-8
Java
12,904
java
User_Interface_Text.java
Java
[]
null
[]
package UI.text; import Model.*; import State_Machine.*; import java.io.*; import java.util.Observable; import java.util.Observer; import java.util.Scanner; public class User_Interface_Text implements Constants, Observer{ private ObservableGame game; private boolean quit = false; private int opt; public User_Interface_Text(ObservableGame game){ this.game= game; game.addObserver(this); } private int read_int(){ Scanner in = new Scanner(System.in); while(!in.hasNextInt()){ in.next(); } return in.nextInt(); } private String read_Text(){ Scanner in = new Scanner(System.in); return in.nextLine(); } public void initial_text(){ System.out.println("\n9 CARD SIEGE!!\n"); System.out.println("\t1- New Game\n\t2- Load Game\n\t3- Quit"); opt=read_int(); switch(opt){ case 1: game.setup(); break; case 2: load_text(); break; case 3: quit = true; default: break; } } public void wait_action_text(){ System.out.println(game.drawBoards()); System.out.println(game.drawCardDay()); System.out.println(wait_action_text_menu()); opt=read_int(); switch(opt){ case 1: game.stateArchers(); break; case 2: game.stateBoilling(); break; case 3: game.stateCloseCombat(); break; case 4: game.coupure(); break; case 5: game.stateRally(); break; case 6: game.stateTunnel(); break; case 7: game.supplyRaid(); break; case 8: game.sabotage(); break; case 9: game.stateBuyAction(); break; case 10: game.endTurn(); break; case 11: save_text(); break; case 12: quit=true; } } public String wait_action_text_menu(){ StringBuilder str = new StringBuilder(); str.append("Player Action:\n"); str.append(game.canArchers()?"\t1- Archers Attack\n":""); str.append(game.canBoiling()?"\t2- Boilling Water Attack\n":""); str.append(game.canCloseCombat()?"\t3- Close Combat Attack\n":""); str.append(game.canCoupure()?"\t4- Coupure\n":""); str.append(game.canRally()?"\t5- Rally Troops\n":""); str.append(game.playerStillHasActionsLeft() && (!game.getSabAndRaidStateActive())?"\t6- Tunnel Action\n":""); str.append(game.canSupply()?"\t7- Supply Raid\n":""); str.append(game.canSabotage()?"\t8- Sabotage\n":""); str.append(game.canBuyAction()?"\t9- Buy Action\n":""); str.append("\t10- End Turn\n\t11- Save game\n" + "\n\t12- Quit\n"); return str.toString(); } public void draw_card_text(){ System.out.println("\n\t1- Draw card\n" + "\t2- Save game\n" + "\t3- Load game\n" + "\t4- Quit\n"); opt = read_int(); switch(opt){ case 1: game.drawCard(); break; case 2: save_text(); break; case 3: load_text(); break; case 4: quit=true; } } private void archersText() { StringBuilder str = new StringBuilder(); System.out.println(game.getEnemy()); str.append(game.ladderOnStartingPosition()?"":"\t1- Ladder\n"); str.append(game.batteringRamOnStartingPosition()?"":"\t2- Battering Ram\n"); str.append(game.siegeTowerOnStartingPosition()?"":(game.siegeTowerExists()?"\t3- Siege Tower\n":"")); str.append("\t4- return\n"); System.out.println(str.toString()); opt = read_int(); switch(opt){ case 1: game.archers(Enemy_Attack.LADDER); break; case 2: game.archers(Enemy_Attack.BATTERING_RAM); break; case 3: game.archers(Enemy_Attack.SIEGE_TOWER); break; case 4: game.returnWaitAction(); } } private void boillingText() { StringBuilder str = new StringBuilder(); System.out.println(game.getEnemy()); str.append((game.isLadderOnCircleSpace()?"\t1- Ladder\n":"")); str.append((game.isBatteringRamOnCircleSpace()?"\t2- Battering Ram\n":"")); str.append((game.isSiegeTowerOnCircleSpace()?"\t3- Siege Tower\n":"")); str.append("\t4- return\n"); System.out.println(str.toString()); opt = read_int(); switch(opt){ case 1: game.boiling(Enemy_Attack.LADDER); break; case 2: game.boiling(Enemy_Attack.BATTERING_RAM); break; case 3: game.boiling(Enemy_Attack.SIEGE_TOWER); break; case 4: game.returnWaitAction(); } } private void rallyText() { StringBuilder str = new StringBuilder(); System.out.println(game.getPlayer()); str.append((game.canDecreaseSupply()?"\t1- Spend 1 supply to get +1DRM\n":"")).append("\t2- Normal try\n").append("\t3- return\n"); System.out.println(str.toString()); opt = read_int(); switch(opt){ case 1: game.rallyPlus1DRM(); case 2: game.normalRally(); case 3: game.returnWaitAction(); } } private void tunnelText(){ StringBuilder str = new StringBuilder(); System.out.println(game.getPlayer()); str.append(game.canUseTunnelMovement()?(game.canMakeFreeMove()?"\t1- Free movement\n\t2- Fast movement":"\t2- Fast movement") :(game.onEnemyLine()||game.onCastleSpace()?"\n\t3- Get inside the Tunnel":"")).append("\n\t4- Return"); System.out.println(str.toString()); opt = read_int(); switch(opt){ case 1: game.tunnelFree(); break; case 2: game.tunnelFast(); break; case 3: game.tunnelGetInside(); break; case 4: game.returnWaitAction(); } } private void closeCombatText() { StringBuilder str = new StringBuilder(); System.out.println(game.getEnemy()); System.out.println("Still has " + game.numberOfActionsAvailable()+ " actions left"); str.append(game.isLadderOnCloseCombat()?"\t1- Attack Ladder\n":""); str.append(game.isBatteringRamOnCloseCombat()?"\t2- Attack Battering Ram\n":""); str.append(game.isSiegeTowerOnCloseCombat()?"\t1- Attack Siege Tower\n":""); str.append(game.canBuyAction()?"\t4- Buy Action\n":""); str.append(game.check2Enemy()?"":"\t5- Return\n"); str.append("\t6- End Turn\n"); System.out.println(str.toString()); opt = read_int(); switch(opt){ case 1: game.closeCombat(Enemy_Attack.LADDER); break; case 2: game.closeCombat(Enemy_Attack.BATTERING_RAM); break; case 3: game.closeCombat(Enemy_Attack.SIEGE_TOWER); break; case 4: game.stateBuyAction(); break; case 5: if(game.check2Enemy()) game.returnWaitAction(); break; case 6: game.endTurn(); } } private void buyOneActionText() { StringBuilder str = new StringBuilder(); System.out.println(game.getPlayer()); str.append(game.canDecreaseSupply()?"\t1- Use one supply to get one more action\n":"").append(game.canDecreaseMorale()?"\t2- Use one morale to get one more action":"").append("\n\t3- Return"); System.out.println(str.toString()); opt = read_int(); switch(opt){ case 1: case 2: game.buyAction(opt); break; case 3: game.returnWaitAction(); } } private void gameOver_Text() { StringBuilder str = new StringBuilder(); System.out.println(game.drawBoards()); str.append("\t1- Return to menu"); str.append("\n\t2- Quit"); System.out.println("{Your castle has been overthrown by the enemy!}"); System.out.println(str.toString()); opt = read_int(); switch(opt){ case 1: game.returnInitialState(); break; case 2: quit=true; break; } } private void winGameText() { StringBuilder str = new StringBuilder(); System.out.println(game.drawBoards()); str.append("\t1- Return to menu"); str.append("\n\t2- Quit"); System.out.println("{Congratulations!!! You have successfully repelled the enemy!}"); System.out.println(str.toString()); opt = read_int(); switch(opt){ case 1: game.returnInitialState(); break; case 2: quit=true; break; } } public void run(){ States state =null; while(!quit){ state = game.getState(); if( state instanceof Initial_State){ initial_text(); }else if (state instanceof Wait_Draw_Card){ draw_card_text(); }else if( state instanceof Wait_Action){ wait_action_text(); }else if ( state instanceof Wait_Archers) { archersText(); }else if ( state instanceof Wait_Boiling) { boillingText(); }else if ( state instanceof Rally_Troops) { rallyText(); }else if (state instanceof Game_Over){ gameOver_Text(); }else if (state instanceof Wait_Tunnel){ tunnelText(); }else if (state instanceof Close_Combat){ closeCombatText(); }else if (state instanceof Buy_One_Action){ buyOneActionText(); }else if (state instanceof Win_Game){ winGameText(); } } } @Override public void update(Observable o, Object arg) { System.out.println(game.getText()); } private void load_text() { System.out.print("\nName of the file to load: "); String filename = read_Text(); if(filename == null || filename.isEmpty()) return; game.setGame(load_game(filename)); System.out.println("\nGame loaded\n"); } private Siege_Game load_game(String filename) { ObjectInputStream oistream = null; Siege_Game sg = null; try { oistream = new ObjectInputStream(new FileInputStream(filename)); sg = (Siege_Game) oistream.readObject(); } catch (FileNotFoundException ex) { System.err.println("Error: file doesn't exists\n" + ex.getMessage()); } catch (IOException | ClassNotFoundException ex) {} finally{ if(oistream != null){ try { oistream.close(); } catch (IOException ex) {} } } return sg; } private void save_text() { System.out.println("\nName of the file to save: "); String filename = read_Text(); if(filename == null || filename.isEmpty()) return; save_game(filename); System.out.println("\nGame saved\n"); } private void save_game(String filename) { ObjectOutputStream oostream = null; try { oostream = new ObjectOutputStream(new FileOutputStream(filename)); oostream.writeObject(this.game); } catch (FileNotFoundException ex) { System.err.println("Erro: ficheiro inexistente\n" + ex.getMessage()); } catch (IOException ex) {} finally{ if(oostream != null){ try { oostream.close(); } catch (IOException ex) {} } } } }
12,904
0.50155
0.493258
388
32.260311
23.417255
200
false
false
0
0
0
0
0
0
0.572165
false
false
0
eac895a1125ab8965d4358f6bbce33228174f22f
24,326,694,784,031
f7f080ac6ba59fc062b7b9f17271b3cf139c0ac9
/src/com/company/attempt/Netease.java
287e7e8571bfc5e52fba074ed3e33d86aab3b9dd
[]
no_license
chen2013/sth
https://github.com/chen2013/sth
be6ec3e2441ad672262b2cd0fccd085fc2922f94
10a703bf176bf756dcb48885c0af65e5a9d78af2
refs/heads/master
2016-09-19T21:22:12.985000
2016-08-28T14:40:04
2016-08-28T14:40:13
65,899,873
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.company.attempt; import java.util.*; /** * Created by chen on 2016/8/19. */ public class Netease { /** * 构造最长回文,即求string和string_reverse的最大公共子串 * * @param str1 * @return */ public static int LCS(String str1) { String str2 = new StringBuffer(str1).reverse().toString(); //d(i,j) = d(i-1,j-1) + 1 str1[i] == str2[j] //d(i,j) = max{ d(i-1,j) , d(i,j-1) } int len1 = str1.length(); int len2 = str2.length(); int[][] dp = new int[len1 + 1][len2 + 1]; for (int i = 0; i <= len1; i++) { dp[i][0] = 0; } for (int j = 0; j <= len2; j++) { dp[0][j] = 0; } for (int i = 1; i <= len1; i++) { for (int j = 1; j <= len2; j++) { if (str1.charAt(i - 1) == str2.charAt(j - 1)) { dp[i][j] = dp[i - 1][j - 1] + 1; } else { dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); } } } return len1 - dp[len1][len2]; } /** * 请设计一个复杂度为O(n)的算法,计算一个未排序数组中排序后相邻元素的最大差值。 * 给定一个整数数组A和数组的大小n,请返回最大差值。保证数组元素个数大于等于2小于等于500 * * @param A * @param n * @return */ public int findMaxDivision(int[] A, int n) { // write code here int[][] bockets = new int[n][2]; int result = 0; int max = A[0], min = A[0]; //bockets[i][0]记录每个桶的最左边界、bockets[i][1]记录每个桶的最右边界 for (int i = 0; i < n; i++) { bockets[i][0] = 0; bockets[i][1] = 0; } //找到最大最小值,决定每个桶的数据边界[0/n~1/n]...[k/n,(k+1)/n]... for (int tmp : A) { if (tmp < min) min = tmp; if (tmp > max) max = tmp; } double tempBar = (max - min) * 1.0 / (n - 1); int bar = (int) Math.ceil(tempBar); int pos; for (int i = 0; i < n; i++) { pos = (A[i] - min) / bar; if (bockets[pos][0] == 0 && bockets[pos][1] == 0) bockets[pos][0] = bockets[pos][1] = A[i]; else if (A[i] < bockets[pos][0]) { bockets[pos][0] = A[i]; } else if (A[i] > bockets[pos][1]) { bockets[pos][1] = A[i]; } } for (int i = 0; i < n; i++) System.out.println(bockets[i][0] + ":" + bockets[i][1]); int tmp; int lastIndex = 0; for (int i = 1; i < n; i++) { if (bockets[i][1] == 0 && bockets[i][0] == 0) { } else { if ((tmp = bockets[i][0] - bockets[lastIndex][1]) > result) { result = tmp; } lastIndex = i; } } return result; } /** * 交叉洗牌 1,2,3,4,5,6 分两队,(1,2,3)+(4,5,6)->(1,4,2,5,3,6); * x 测试用例组数 * n 每组测试用例的其中一队的个数 * round 洗牌轮数 */ public void freshCard() { Scanner sc = new Scanner(System.in); int x = 0; if (sc.hasNext()) x = sc.nextInt(); for (int i = 0; i < x; i++) { int n = sc.nextInt(); int round = sc.nextInt(); int[] cards = new int[2 * n]; for (int j = 0; j < 2 * n; j++) { cards[j] = sc.nextInt(); } int[] cardsNew = new int[2 * n]; for (int j = 0; j < round; j++) { for (int k = 0; k < n; k++) { cardsNew[2 * k] = cards[k]; cardsNew[2 * k + 1] = cards[n + k]; } cards = cardsNew.clone(); } StringBuilder sb = new StringBuilder(); for (int j = 0; j < 2 * n; j++) { sb.append(cards[j] + " "); } System.out.println(sb.toString().trim()); } } /** * while(!Q.empty()) { int x=Q.front(); //取出当前队头的值x Q.pop(); //弹出当前队头 Q.push(x); //把x放入队尾 x = Q.front(); //取出这时候队头的值 printf("%d\n",x); //输出x Q.pop(); //弹出这时候的队头 } 输出为1,2,3,4,5,..n,求序列 */ public void makeRawQueue() { Scanner sc = new Scanner(System.in); int x = 0; if (sc.hasNext()) x = sc.nextInt(); for (int i = 0; i < x; i++) { List<Integer> queue = new ArrayList<>(); int n = sc.nextInt(); queue.add(n); while (n > 1) { n--; queue.add(0,n); int last = queue.remove(queue.size() - 1); queue.add(0,last); } StringBuilder sb = new StringBuilder(); for (int j = 0; j < queue.size(); j++) { sb.append(queue.get(j)+" "); } System.out.println(sb.toString().trim()); } } }
UTF-8
Java
5,381
java
Netease.java
Java
[ { "context": "y.attempt;\n\nimport java.util.*;\n\n/**\n * Created by chen on 2016/8/19.\n */\npublic class Netease {\n\n\n /*", "end": 73, "score": 0.9936996102333069, "start": 69, "tag": "USERNAME", "value": "chen" } ]
null
[]
package com.company.attempt; import java.util.*; /** * Created by chen on 2016/8/19. */ public class Netease { /** * 构造最长回文,即求string和string_reverse的最大公共子串 * * @param str1 * @return */ public static int LCS(String str1) { String str2 = new StringBuffer(str1).reverse().toString(); //d(i,j) = d(i-1,j-1) + 1 str1[i] == str2[j] //d(i,j) = max{ d(i-1,j) , d(i,j-1) } int len1 = str1.length(); int len2 = str2.length(); int[][] dp = new int[len1 + 1][len2 + 1]; for (int i = 0; i <= len1; i++) { dp[i][0] = 0; } for (int j = 0; j <= len2; j++) { dp[0][j] = 0; } for (int i = 1; i <= len1; i++) { for (int j = 1; j <= len2; j++) { if (str1.charAt(i - 1) == str2.charAt(j - 1)) { dp[i][j] = dp[i - 1][j - 1] + 1; } else { dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); } } } return len1 - dp[len1][len2]; } /** * 请设计一个复杂度为O(n)的算法,计算一个未排序数组中排序后相邻元素的最大差值。 * 给定一个整数数组A和数组的大小n,请返回最大差值。保证数组元素个数大于等于2小于等于500 * * @param A * @param n * @return */ public int findMaxDivision(int[] A, int n) { // write code here int[][] bockets = new int[n][2]; int result = 0; int max = A[0], min = A[0]; //bockets[i][0]记录每个桶的最左边界、bockets[i][1]记录每个桶的最右边界 for (int i = 0; i < n; i++) { bockets[i][0] = 0; bockets[i][1] = 0; } //找到最大最小值,决定每个桶的数据边界[0/n~1/n]...[k/n,(k+1)/n]... for (int tmp : A) { if (tmp < min) min = tmp; if (tmp > max) max = tmp; } double tempBar = (max - min) * 1.0 / (n - 1); int bar = (int) Math.ceil(tempBar); int pos; for (int i = 0; i < n; i++) { pos = (A[i] - min) / bar; if (bockets[pos][0] == 0 && bockets[pos][1] == 0) bockets[pos][0] = bockets[pos][1] = A[i]; else if (A[i] < bockets[pos][0]) { bockets[pos][0] = A[i]; } else if (A[i] > bockets[pos][1]) { bockets[pos][1] = A[i]; } } for (int i = 0; i < n; i++) System.out.println(bockets[i][0] + ":" + bockets[i][1]); int tmp; int lastIndex = 0; for (int i = 1; i < n; i++) { if (bockets[i][1] == 0 && bockets[i][0] == 0) { } else { if ((tmp = bockets[i][0] - bockets[lastIndex][1]) > result) { result = tmp; } lastIndex = i; } } return result; } /** * 交叉洗牌 1,2,3,4,5,6 分两队,(1,2,3)+(4,5,6)->(1,4,2,5,3,6); * x 测试用例组数 * n 每组测试用例的其中一队的个数 * round 洗牌轮数 */ public void freshCard() { Scanner sc = new Scanner(System.in); int x = 0; if (sc.hasNext()) x = sc.nextInt(); for (int i = 0; i < x; i++) { int n = sc.nextInt(); int round = sc.nextInt(); int[] cards = new int[2 * n]; for (int j = 0; j < 2 * n; j++) { cards[j] = sc.nextInt(); } int[] cardsNew = new int[2 * n]; for (int j = 0; j < round; j++) { for (int k = 0; k < n; k++) { cardsNew[2 * k] = cards[k]; cardsNew[2 * k + 1] = cards[n + k]; } cards = cardsNew.clone(); } StringBuilder sb = new StringBuilder(); for (int j = 0; j < 2 * n; j++) { sb.append(cards[j] + " "); } System.out.println(sb.toString().trim()); } } /** * while(!Q.empty()) { int x=Q.front(); //取出当前队头的值x Q.pop(); //弹出当前队头 Q.push(x); //把x放入队尾 x = Q.front(); //取出这时候队头的值 printf("%d\n",x); //输出x Q.pop(); //弹出这时候的队头 } 输出为1,2,3,4,5,..n,求序列 */ public void makeRawQueue() { Scanner sc = new Scanner(System.in); int x = 0; if (sc.hasNext()) x = sc.nextInt(); for (int i = 0; i < x; i++) { List<Integer> queue = new ArrayList<>(); int n = sc.nextInt(); queue.add(n); while (n > 1) { n--; queue.add(0,n); int last = queue.remove(queue.size() - 1); queue.add(0,last); } StringBuilder sb = new StringBuilder(); for (int j = 0; j < queue.size(); j++) { sb.append(queue.get(j)+" "); } System.out.println(sb.toString().trim()); } } }
5,381
0.382619
0.355261
179
26.77095
19.098335
77
false
false
0
0
0
0
0
0
0.726257
false
false
0
583e1f484f602b6640e252ba909c25686d5aac7d
22,376,779,617,343
514b3d25c692d63f132508c51a72ec7614bfe531
/app/models/User.java
78ba902f1fa25377af1be4fd9b7a71b5920730d3
[]
no_license
essamahmedhafez/twitterPlay
https://github.com/essamahmedhafez/twitterPlay
245ace06ea797dd28d0b0d47a007b641d119a921
8e76e69b0f2e687a6917909dd2ca53fe389d5d87
refs/heads/master
2020-06-01T11:32:27.760000
2014-05-16T21:45:19
2014-05-16T21:45:19
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package models; import javax.persistence.*; import play.db.ebean.*; import com.avaje.ebean.*; @Entity public class User extends Model{ @Id public int user_id; public String user_name; public String email; public String password; public String url; public String description; public int followers_count; public int friends_count; public int statuses_count; public User(String email, String user_name, String password) { this.email = email; this.user_name = user_name; this.password = password; this.url = "localhost:9000/"+user_name; this.description = "I've created my first twitter account"; this.followers_count = 0; this.friends_count = 0; this.statuses_count = 0; } public static User authenticate(String email, String password) { return find.where().eq("email", email) .eq("password", password).findUnique(); } public static Finder<Integer,User> find = new Finder<Integer,User>( Integer.class, User.class ); }
UTF-8
Java
1,074
java
User.java
Java
[ { "context": "{\n this.email = email;\n this.user_name = user_name;\n this.password = password;\n this.url =", "end": 531, "score": 0.9887544512748718, "start": 522, "tag": "USERNAME", "value": "user_name" }, { "context": " this.user_name = user_name;\n this.password = password;\n this.url = \"localhost:9000/\"+user_name;\n ", "end": 563, "score": 0.9990629553794861, "start": 555, "tag": "PASSWORD", "value": "password" } ]
null
[]
package models; import javax.persistence.*; import play.db.ebean.*; import com.avaje.ebean.*; @Entity public class User extends Model{ @Id public int user_id; public String user_name; public String email; public String password; public String url; public String description; public int followers_count; public int friends_count; public int statuses_count; public User(String email, String user_name, String password) { this.email = email; this.user_name = user_name; this.password = <PASSWORD>; this.url = "localhost:9000/"+user_name; this.description = "I've created my first twitter account"; this.followers_count = 0; this.friends_count = 0; this.statuses_count = 0; } public static User authenticate(String email, String password) { return find.where().eq("email", email) .eq("password", password).findUnique(); } public static Finder<Integer,User> find = new Finder<Integer,User>( Integer.class, User.class ); }
1,076
0.647114
0.640596
46
22.369566
19.827909
70
false
false
0
0
0
0
0
0
0.695652
false
false
0
45288802bc18136d5f9ec4612ec17492e1549d3a
11,519,102,297,243
44655c4ed9ce738d4b0023472b271ba8ff85ded7
/src/main/java/rover/Start.java
9a50e52c5d145984849d8a56d347965d3084c0d8
[]
no_license
syinmm/https-github.com-syinm-projekt-3-object-calisthenics-syinmm-master
https://github.com/syinmm/https-github.com-syinm-projekt-3-object-calisthenics-syinmm-master
f7fef7f91709605cf0e6c8e7cc10d32da3decfb3
b3c53686b58274fc884cced3e5c90c0f9a8f8d62
refs/heads/master
2020-05-31T12:30:56.740000
2019-06-04T21:34:31
2019-06-04T21:34:31
190,282,521
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package rover; import java.io.PrintStream; public class Start { public static void main(String[] args) { Mars mars = new Mars(); Rover rover = new Rover(); mars.createField(rover); PrintStream out = System.out; // Initial Mars mars.print(out, mars); /* .moveForward(Mars) to move */ /* .turnRight(Mars) to turn right */ /* Mars.print(out) to see mars */ rover.moveForward(mars); rover.moveForward(mars); rover.moveForward(mars); mars.print(out, mars); rover.turnRight(mars); rover.turnRight(mars); rover.turnRight(mars); rover.moveForward(mars); rover.moveForward(mars); rover.moveForward(mars); mars.print(out, mars); rover.turnRight(mars); rover.turnRight(mars); rover.turnRight(mars); rover.moveForward(mars); rover.moveForward(mars); rover.moveForward(mars); mars.print(out, mars); rover.turnRight(mars); rover.turnRight(mars); rover.turnRight(mars); rover.moveForward(mars); rover.moveForward(mars); rover.moveForward(mars); mars.print(out, mars); } }
UTF-8
Java
1,259
java
Start.java
Java
[]
null
[]
package rover; import java.io.PrintStream; public class Start { public static void main(String[] args) { Mars mars = new Mars(); Rover rover = new Rover(); mars.createField(rover); PrintStream out = System.out; // Initial Mars mars.print(out, mars); /* .moveForward(Mars) to move */ /* .turnRight(Mars) to turn right */ /* Mars.print(out) to see mars */ rover.moveForward(mars); rover.moveForward(mars); rover.moveForward(mars); mars.print(out, mars); rover.turnRight(mars); rover.turnRight(mars); rover.turnRight(mars); rover.moveForward(mars); rover.moveForward(mars); rover.moveForward(mars); mars.print(out, mars); rover.turnRight(mars); rover.turnRight(mars); rover.turnRight(mars); rover.moveForward(mars); rover.moveForward(mars); rover.moveForward(mars); mars.print(out, mars); rover.turnRight(mars); rover.turnRight(mars); rover.turnRight(mars); rover.moveForward(mars); rover.moveForward(mars); rover.moveForward(mars); mars.print(out, mars); } }
1,259
0.568705
0.568705
47
25.80851
13.475965
47
false
false
0
0
0
0
0
0
0.787234
false
false
0
c8ca173de56d4b44efafa6a6076752b5abc285d5
19,095,424,610,847
3e611373d2ff48dbffc25ca367c0f0e3e51e2f90
/AE_MQL_WS/MQLSetup/src/util/MMGenerators/QMMGenerator/QMMMetaModelBuilder/QMMMetaModelBuilder_Operators.java
9c6fa3a21bfc34635c98c081c8b234cfa2372f55
[]
no_license
Racheast/AE_MQL
https://github.com/Racheast/AE_MQL
999fbd74a15261006fe8f3a0e2fdc1323b05c0a5
3f94f6d41986ae3786ae4291736b11f0750e6091
refs/heads/master
2020-04-26T08:53:49.746000
2019-06-01T10:13:26
2019-06-01T10:13:26
173,438,094
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package util.MMGenerators.QMMGenerator.QMMMetaModelBuilder; import java.util.ArrayList; import java.util.Arrays; import org.eclipse.emf.ecore.EAnnotation; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EClassifier; import org.eclipse.emf.ecore.EOperation; import org.eclipse.emf.ecore.EReference; import org.eclipse.emf.ecore.EcorePackage; import org.eclipse.emf.ecore.util.EcoreUtil; import util.MMGenerators.QMMGenerator.CSVReader; import util.MMGenerators.QMMGenerator.EClassMethodBodies; import util.MMGenerators.QMMGenerator.EObjectHelper; public class QMMMetaModelBuilder_Operators { static ArrayList<EClass> createDefaultOperatorEClasses(){ ArrayList<EClass> eClasses = new ArrayList<EClass>(); EClass operator = EObjectHelper.createEClass("Operator", true); EClass enumerationOperator = EObjectHelper.createEClass("EnumerationOperator", true); enumerationOperator.getESuperTypes().add(operator); EClass expressionOperator = EObjectHelper.createEClass("ExpressionOperator", true); expressionOperator.getESuperTypes().add(operator); EClass bitOperator = EObjectHelper.createEClass("BitOperator", true); bitOperator.getESuperTypes().add(expressionOperator); bitOperator.getESuperTypes().add(QMMMetaModelBuilder_Collections.defaultEClasses.get("NegatableElement")); EClass functionalOperator = EObjectHelper.createEClass("FunctionalOperator", true); functionalOperator.getESuperTypes().add(expressionOperator); functionalOperator.getESuperTypes().add(QMMMetaModelBuilder_Collections.defaultEClasses.get("TypedElement")); EAnnotation genModelAnnotation = EObjectHelper.createGenModelAnnotation(EClassMethodBodies.FUNCTIONAL_OPERATOR_GETLASTOPERATOR_BODY); EOperation getLastOperator = EObjectHelper.createEOperation("getLastOperator", EcorePackage.Literals.EJAVA_OBJECT, 1, 1, new ArrayList<EAnnotation>(Arrays.asList(genModelAnnotation))); functionalOperator.getEOperations().add(getLastOperator); EClass evaluationOperator = EObjectHelper.createEClass("EvaluationOperator", true); evaluationOperator.getESuperTypes().add(operator); EClass evaluationFunctionalOperator = EObjectHelper.createEClass("EvaluationFunctionalOperator", true); evaluationFunctionalOperator.getESuperTypes().add(evaluationOperator); evaluationFunctionalOperator.getESuperTypes().add(functionalOperator); EClass evaluationBitOperator = EObjectHelper.createEClass("EvaluationBitOperator", true); evaluationBitOperator.getESuperTypes().add(evaluationOperator); evaluationBitOperator.getESuperTypes().add(bitOperator); EReference operatorERef = EObjectHelper.createEReference("connects", evaluationOperator, 2, -1, true); evaluationBitOperator.getEStructuralFeatures().add(operatorERef); EClass andOperator = EObjectHelper.createEClass("And_EvaluationBitOperator", false); andOperator.getESuperTypes().add(evaluationBitOperator); EAnnotation and_annotation = EObjectHelper.createGenModelAnnotation("return \"&&\";"); EOperation getLiteral_AND = EObjectHelper.createEOperation("getLiteral", EcorePackage.Literals.ESTRING, 1, 1, new ArrayList<EAnnotation>(Arrays.asList(and_annotation))); andOperator.getEOperations().add(getLiteral_AND); EClass orOperator = EObjectHelper.createEClass("Or_EvaluationBitOperator", false); orOperator.getESuperTypes().add(evaluationBitOperator); EAnnotation or_annotation = EObjectHelper.createGenModelAnnotation("return \"||\";"); EOperation getLiteral_OR = EObjectHelper.createEOperation("getLiteral", EcorePackage.Literals.ESTRING, 1, 1, new ArrayList<EAnnotation>(Arrays.asList(or_annotation))); orOperator.getEOperations().add(getLiteral_OR); EClass classOperator = EObjectHelper.createEClass("ClassOperator", true); classOperator.getESuperTypes().add(evaluationFunctionalOperator); eClasses.addAll(QMMMetaModelBuilder_Calculateables.updateTypedCalculateables("Integer")); EClass aggregationOperator = EObjectHelper.createEClass("AggregationOperator", true); aggregationOperator.getESuperTypes().add(evaluationFunctionalOperator); aggregationOperator.getESuperTypes().add(QMMMetaModelBuilder_Collections.typedCalculateables.get("Integer")); EClass countingOperator = EObjectHelper.createEClass("CountingAggregationOperator", true); EReference countingParamERef = EObjectHelper.createEReference("countable", QMMMetaModelBuilder_Collections.defaultEClasses.get("CountableReferenceParameter"), 1, 1, true); countingOperator.getESuperTypes().add(aggregationOperator); countingOperator.getEStructuralFeatures().add(countingParamERef); countingOperator.getEOperations().add(EObjectHelper.createGetAllParametersOperation(new ArrayList<EReference>(Arrays.asList(countingParamERef)))); EClass calculatingOperator = EObjectHelper.createEClass("CalculatingAggregationOperator", true); calculatingOperator.getESuperTypes().add(aggregationOperator); QMMMetaModelBuilder_Collections.defaultEClasses.put("Operator", operator); QMMMetaModelBuilder_Collections.defaultEClasses.put("ExpressionOperator", expressionOperator); QMMMetaModelBuilder_Collections.defaultEClasses.put("EnumerationOperator", enumerationOperator); QMMMetaModelBuilder_Collections.defaultEClasses.put("BitOperator", bitOperator); QMMMetaModelBuilder_Collections.defaultEClasses.put("FunctionalOperator", functionalOperator); QMMMetaModelBuilder_Collections.defaultEClasses.put("ClassOperator", classOperator); QMMMetaModelBuilder_Collections.defaultEClasses.put("AggregationOperator", aggregationOperator); QMMMetaModelBuilder_Collections.defaultEClasses.put("EvaluationOperator", evaluationOperator); QMMMetaModelBuilder_Collections.defaultEClasses.put("EvaluationFunctionalOperator", evaluationFunctionalOperator); QMMMetaModelBuilder_Collections.defaultEClasses.put("And_EvaluationBitOperator", andOperator); QMMMetaModelBuilder_Collections.defaultEClasses.put("Or_EvaluationBitOperator", orOperator); QMMMetaModelBuilder_Collections.defaultEClasses.put("CountingAggregationOperator", countingOperator); QMMMetaModelBuilder_Collections.defaultEClasses.put("CalculatingAggregationOperator", calculatingOperator); eClasses.add(operator); eClasses.add(expressionOperator); eClasses.add(enumerationOperator); eClasses.add(bitOperator); eClasses.add(functionalOperator); eClasses.add(classOperator); eClasses.add(evaluationOperator); eClasses.add(evaluationFunctionalOperator); eClasses.add(aggregationOperator); eClasses.add(evaluationBitOperator); eClasses.add(andOperator); eClasses.add(orOperator); eClasses.add(countingOperator); eClasses.add(calculatingOperator); return eClasses; } static ArrayList<EClass> createCountingAggregationOperators(){ ArrayList<EClass> eClasses = new ArrayList<EClass>(); ArrayList<EClass> integerList = new ArrayList<EClass>(); EClass countAggregationOperator = EObjectHelper.createEClass("Count_AggregationOperator", false); countAggregationOperator.getESuperTypes().add(QMMMetaModelBuilder_Collections.defaultEClasses.get("CountingAggregationOperator")); EAnnotation annotation = EObjectHelper.createGenModelAnnotation("return \"count\";"); EOperation getLiteral = EObjectHelper.createEOperation("getLiteral", EcorePackage.Literals.ESTRING, 1, 1, new ArrayList<EAnnotation>(Arrays.asList(annotation))); countAggregationOperator.getEOperations().add(getLiteral); countAggregationOperator.getESuperTypes().add(QMMMetaModelBuilder_Collections.typedEvaluationOperationArguments.get("Integer")); EAnnotation infoAnnotation = EObjectHelper.createEAnnotation("information"); infoAnnotation.getDetails().put("functionalType", "Integer"); infoAnnotation.getDetails().put("literal", "count"); infoAnnotation.getDetails().put("operatorXTextLiteral", "count"); countAggregationOperator.getEAnnotations().add(infoAnnotation); integerList.add(countAggregationOperator); QMMMetaModelBuilder_Collections.countingAggregationOperators.put("Integer",integerList); eClasses.add(countAggregationOperator); return eClasses; } static ArrayList<EClass> createCalculatingAggregationOperators(){ ArrayList<EClass> eClasses = new ArrayList<EClass>(); ArrayList<EClass> integerList = new ArrayList<EClass>(); ArrayList<EClass> doubleList = new ArrayList<EClass>(); EClass sumAggregationOperator_Integer = EObjectHelper.createCalculatingOperator("Sum_AggregationOperator_Integer", "sum", "Integer", "Integer"); integerList.add(sumAggregationOperator_Integer); EClass minAggregationOperator_Integer = EObjectHelper.createCalculatingOperator("Min_AggregationOperator_Integer", "min", "Integer", "Integer"); integerList.add(minAggregationOperator_Integer); EClass maxAggregationOperator_Integer = EObjectHelper.createCalculatingOperator("Max_AggregationOperator_Integer", "max", "Integer", "Integer"); integerList.add(maxAggregationOperator_Integer); EClass sumAggregationOperator_Double = EObjectHelper.createCalculatingOperator("Sum_AggregationOperator_Double", "sum", "Double", "Double"); doubleList.add(sumAggregationOperator_Double); EClass minAggregationOperator_Double = EObjectHelper.createCalculatingOperator("Min_AggregationOperator_Double", "min", "Double", "Double"); doubleList.add(minAggregationOperator_Double); EClass maxAggregationOperator_Double = EObjectHelper.createCalculatingOperator("Max_AggregationOperator_Double", "max", "Double", "Double"); doubleList.add(maxAggregationOperator_Double); QMMMetaModelBuilder_Collections.calculatingAggregationOperators.put("Integer", integerList); QMMMetaModelBuilder_Collections.calculatingAggregationOperators.put("Double", doubleList); eClasses.addAll(integerList); eClasses.addAll(doubleList); return eClasses; } static ArrayList<EClass> createConcreteClassOperators(){ ArrayList<EClass> eClasses = new ArrayList<EClass>(); ArrayList<EClass> integerList = new ArrayList<EClass>(); EClass integerParseIntOperator = EObjectHelper.createClassOperator("IntegerParseInt_ClassOperator", "Integer.parseInt", "Integer.parseInt", "Integer", "String"); integerList.add(integerParseIntOperator); QMMMetaModelBuilder_Collections.classOperators.put("Integer", integerList); eClasses.addAll(integerList); return eClasses; } static ArrayList<EClassifier> readFunctionalOperators(){ ArrayList<EClassifier> eClassifiers = new ArrayList<EClassifier>(); ArrayList<String[]> lines = CSVReader.readFunctionalOperators(); for(String[] line:lines){ eClassifiers.addAll(QMMMetaModelBuilder_Types.updateExpressionTypeSystem(line[0])); eClassifiers.addAll(QMMMetaModelBuilder_Types.updateExpressionTypeSystem(line[1])); ArrayList<EReference> paramEReferences = new ArrayList<EReference>(); int i=4; while(i < line.length){ String s = line[i]; String paramName = s.split(":")[0]; String paramType = s.split(":")[1]; eClassifiers.addAll(QMMMetaModelBuilder_Types.updateExpressionTypeSystem(paramType)); paramEReferences.add(QMMMetaModelBuilder_Parameters.createParameterReference(paramName, paramType)); i++; } eClassifiers.add(QMMMetaModelBuilder_Operators.createConcreteFunctionalOperator(line[2], line[3], line[0], QMMMetaModelBuilder_Collections.functionalTypes.get(line[1]), paramEReferences)); } return eClassifiers; } static ArrayList<EClass> updateTypedOperators(String eType){ ArrayList<EClass> eClasses = new ArrayList<EClass>(); if(QMMMetaModelBuilder_Collections.typedOperators.get(eType)==null) eClasses.add(QMMMetaModelBuilder_Operators.createTypedOperator(eType)); return eClasses; } static EClass createTypedOperator(String eType){ EClass typedOperator = EObjectHelper.createEClass(eType + "_Operator", true); typedOperator.getESuperTypes().add(QMMMetaModelBuilder_Collections.defaultEClasses.get("Operator")); QMMMetaModelBuilder_Collections.typedOperators.put(eType, typedOperator); return typedOperator; } static ArrayList<EClass> updateTypedEnumerationOperators(String eType){ ArrayList<EClass> eClasses = new ArrayList<EClass>(); if(QMMMetaModelBuilder_Collections.typedOperators.get(eType)==null) eClasses.addAll(updateTypedOperators(eType)); if(QMMMetaModelBuilder_Collections.typedEnumerationOperators.get(eType)==null) eClasses.add(QMMMetaModelBuilder_Operators.createTypedEnumerationOperator(eType)); return eClasses; } static EClass createTypedEnumerationOperator(String eType){ EClass typedEnumerationOperator = EObjectHelper.createEClass(eType + "_EnumerationOperator", false); typedEnumerationOperator.getESuperTypes().add(QMMMetaModelBuilder_Collections.defaultEClasses.get("EnumerationOperator")); typedEnumerationOperator.getESuperTypes().add(QMMMetaModelBuilder_Collections.typedOperators.get(eType)); typedEnumerationOperator.getEStructuralFeatures().add(EObjectHelper.createEAttribute("argument", QMMMetaModelBuilder_Collections.eClassifiersMap.get(eType), 1, 1, false)); typedEnumerationOperator.getEStructuralFeatures().add(EObjectHelper.createEReference("or", typedEnumerationOperator, 0, 1, true)); QMMMetaModelBuilder_Collections.typedEnumerationOperators.put(eType, typedEnumerationOperator); return typedEnumerationOperator; } static ArrayList<EClassifier> createTypedExpressionOperators(String eType){ ArrayList<EClassifier> eClassifiers = new ArrayList<EClassifier>(); EClass typedExpressionOperator = EObjectHelper.createEClass(eType + "_ExpressionOperator",true); typedExpressionOperator.getESuperTypes().add(QMMMetaModelBuilder_Collections.defaultEClasses.get("ExpressionOperator")); typedExpressionOperator.getESuperTypes().add(QMMMetaModelBuilder_Collections.typedOperators.get(eType)); EAnnotation infoAnnotation = EObjectHelper.createEAnnotation("information"); infoAnnotation.getDetails().put("type", eType); typedExpressionOperator.getEAnnotations().add(infoAnnotation); eClassifiers.add(typedExpressionOperator); //Typed_BitOperator EReference connectsERef = EObjectHelper.createEReference("connects", typedExpressionOperator, 2, -1, true); EClass typedBitOperator = EObjectHelper.createEClass(eType + "_BitOperator", true); typedBitOperator.getESuperTypes().add(typedExpressionOperator); typedBitOperator.getESuperTypes().add(QMMMetaModelBuilder_Collections.defaultEClasses.get("BitOperator")); typedBitOperator.getEStructuralFeatures().add(connectsERef); typedBitOperator.getEAnnotations().add(EcoreUtil.copy(infoAnnotation)); eClassifiers.add(typedBitOperator); EAnnotation and_annotation = EObjectHelper.createGenModelAnnotation("return \"&&\";"); EOperation and_operation = EObjectHelper.createEOperation("getLiteral", EcorePackage.Literals.ESTRING, 1, 1, new ArrayList<EAnnotation>(Arrays.asList(and_annotation))); EClass typedAndOperator = EObjectHelper.createEClass(eType + "_And_BitOperator", false); typedAndOperator.getESuperTypes().add(typedBitOperator); typedAndOperator.getEOperations().add(and_operation); typedAndOperator.getEAnnotations().add(EcoreUtil.copy(infoAnnotation)); eClassifiers.add(typedAndOperator); EAnnotation or_annotation = EObjectHelper.createGenModelAnnotation("return \"||\";"); EOperation or_operation = EObjectHelper.createEOperation("getLiteral", EcorePackage.Literals.ESTRING, 1, 1, new ArrayList<EAnnotation>(Arrays.asList(or_annotation))); EClass typedOrOperator = EObjectHelper.createEClass(eType + "_Or_BitOperator", false); typedOrOperator.getESuperTypes().add(typedBitOperator); typedOrOperator.getEOperations().add(or_operation); typedOrOperator.getEAnnotations().add(EcoreUtil.copy(infoAnnotation)); eClassifiers.add(typedOrOperator); //Typed_FunctionalOperator EClass typedFunctionalOperator = EObjectHelper.createEClass(eType + "_FunctionalOperator", true); typedFunctionalOperator.getESuperTypes().add(typedExpressionOperator); typedFunctionalOperator.getESuperTypes().add(QMMMetaModelBuilder_Collections.defaultEClasses.get("FunctionalOperator")); typedFunctionalOperator.getEAnnotations().add(EcoreUtil.copy(infoAnnotation)); EReference functionalOperatorERef = EObjectHelper.createEReference("operator", typedFunctionalOperator, 0, 1, true); QMMMetaModelBuilder_Collections.functionalTypes.get(eType).getEStructuralFeatures().add(functionalOperatorERef); if(QMMMetaModelBuilder_Collections.functionalOperators.get(eType) == null) QMMMetaModelBuilder_Collections.functionalOperators.put(eType, typedFunctionalOperator); eClassifiers.add(typedFunctionalOperator); QMMMetaModelBuilder_Collections.typedExpressionOperators.put(eType, typedExpressionOperator); return eClassifiers; } static ArrayList<EClassifier> updateTypedExpressionOperators(String eType){ ArrayList<EClassifier> eClassifiers = new ArrayList<EClassifier>(); if(QMMMetaModelBuilder_Collections.typedExpressionOperators.get(eType)==null) eClassifiers.addAll(createTypedExpressionOperators(eType)); return eClassifiers; } static EClass createConcreteFunctionalOperator(String name, String literal, String functionalOperatorType, EClass functionalType, ArrayList<EReference> parameterEReferences){ EAnnotation annotation = EObjectHelper.createGenModelAnnotation("return \"" + literal + "\";"); EOperation getLiteral = EObjectHelper.createEOperation("getLiteral", EcorePackage.Literals.ESTRING, 1, 1, new ArrayList<EAnnotation>(Arrays.asList(annotation))); EClass concreteFunctionalOperator = EObjectHelper.createEClass(name + "_FunctionalOperator", false); concreteFunctionalOperator.getESuperTypes().add(QMMMetaModelBuilder_Collections.functionalOperators.get(functionalOperatorType)); concreteFunctionalOperator.getESuperTypes().add(functionalType); concreteFunctionalOperator.getEStructuralFeatures().addAll(parameterEReferences); concreteFunctionalOperator.getEOperations().add(getLiteral); concreteFunctionalOperator.getEOperations().add(EObjectHelper.createGetAllParametersOperation(parameterEReferences)); if(QMMMetaModelBuilder_Collections.concreteFunctionalOperators.get(functionalOperatorType)==null) QMMMetaModelBuilder_Collections.concreteFunctionalOperators.put(functionalOperatorType, new ArrayList<EClass>()); QMMMetaModelBuilder_Collections.concreteFunctionalOperators.get(functionalOperatorType).add(concreteFunctionalOperator); EAnnotation infoAnnotation = EObjectHelper.createEAnnotation("information"); infoAnnotation.getDetails().put("name", name); infoAnnotation.getDetails().put("literal", literal); infoAnnotation.getDetails().put("functionalOperatorType",functionalOperatorType); infoAnnotation.getDetails().put("functionalType",functionalType.getName()); concreteFunctionalOperator.getEAnnotations().add(infoAnnotation); return concreteFunctionalOperator; } }
UTF-8
Java
18,849
java
QMMMetaModelBuilder_Operators.java
Java
[]
null
[]
package util.MMGenerators.QMMGenerator.QMMMetaModelBuilder; import java.util.ArrayList; import java.util.Arrays; import org.eclipse.emf.ecore.EAnnotation; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EClassifier; import org.eclipse.emf.ecore.EOperation; import org.eclipse.emf.ecore.EReference; import org.eclipse.emf.ecore.EcorePackage; import org.eclipse.emf.ecore.util.EcoreUtil; import util.MMGenerators.QMMGenerator.CSVReader; import util.MMGenerators.QMMGenerator.EClassMethodBodies; import util.MMGenerators.QMMGenerator.EObjectHelper; public class QMMMetaModelBuilder_Operators { static ArrayList<EClass> createDefaultOperatorEClasses(){ ArrayList<EClass> eClasses = new ArrayList<EClass>(); EClass operator = EObjectHelper.createEClass("Operator", true); EClass enumerationOperator = EObjectHelper.createEClass("EnumerationOperator", true); enumerationOperator.getESuperTypes().add(operator); EClass expressionOperator = EObjectHelper.createEClass("ExpressionOperator", true); expressionOperator.getESuperTypes().add(operator); EClass bitOperator = EObjectHelper.createEClass("BitOperator", true); bitOperator.getESuperTypes().add(expressionOperator); bitOperator.getESuperTypes().add(QMMMetaModelBuilder_Collections.defaultEClasses.get("NegatableElement")); EClass functionalOperator = EObjectHelper.createEClass("FunctionalOperator", true); functionalOperator.getESuperTypes().add(expressionOperator); functionalOperator.getESuperTypes().add(QMMMetaModelBuilder_Collections.defaultEClasses.get("TypedElement")); EAnnotation genModelAnnotation = EObjectHelper.createGenModelAnnotation(EClassMethodBodies.FUNCTIONAL_OPERATOR_GETLASTOPERATOR_BODY); EOperation getLastOperator = EObjectHelper.createEOperation("getLastOperator", EcorePackage.Literals.EJAVA_OBJECT, 1, 1, new ArrayList<EAnnotation>(Arrays.asList(genModelAnnotation))); functionalOperator.getEOperations().add(getLastOperator); EClass evaluationOperator = EObjectHelper.createEClass("EvaluationOperator", true); evaluationOperator.getESuperTypes().add(operator); EClass evaluationFunctionalOperator = EObjectHelper.createEClass("EvaluationFunctionalOperator", true); evaluationFunctionalOperator.getESuperTypes().add(evaluationOperator); evaluationFunctionalOperator.getESuperTypes().add(functionalOperator); EClass evaluationBitOperator = EObjectHelper.createEClass("EvaluationBitOperator", true); evaluationBitOperator.getESuperTypes().add(evaluationOperator); evaluationBitOperator.getESuperTypes().add(bitOperator); EReference operatorERef = EObjectHelper.createEReference("connects", evaluationOperator, 2, -1, true); evaluationBitOperator.getEStructuralFeatures().add(operatorERef); EClass andOperator = EObjectHelper.createEClass("And_EvaluationBitOperator", false); andOperator.getESuperTypes().add(evaluationBitOperator); EAnnotation and_annotation = EObjectHelper.createGenModelAnnotation("return \"&&\";"); EOperation getLiteral_AND = EObjectHelper.createEOperation("getLiteral", EcorePackage.Literals.ESTRING, 1, 1, new ArrayList<EAnnotation>(Arrays.asList(and_annotation))); andOperator.getEOperations().add(getLiteral_AND); EClass orOperator = EObjectHelper.createEClass("Or_EvaluationBitOperator", false); orOperator.getESuperTypes().add(evaluationBitOperator); EAnnotation or_annotation = EObjectHelper.createGenModelAnnotation("return \"||\";"); EOperation getLiteral_OR = EObjectHelper.createEOperation("getLiteral", EcorePackage.Literals.ESTRING, 1, 1, new ArrayList<EAnnotation>(Arrays.asList(or_annotation))); orOperator.getEOperations().add(getLiteral_OR); EClass classOperator = EObjectHelper.createEClass("ClassOperator", true); classOperator.getESuperTypes().add(evaluationFunctionalOperator); eClasses.addAll(QMMMetaModelBuilder_Calculateables.updateTypedCalculateables("Integer")); EClass aggregationOperator = EObjectHelper.createEClass("AggregationOperator", true); aggregationOperator.getESuperTypes().add(evaluationFunctionalOperator); aggregationOperator.getESuperTypes().add(QMMMetaModelBuilder_Collections.typedCalculateables.get("Integer")); EClass countingOperator = EObjectHelper.createEClass("CountingAggregationOperator", true); EReference countingParamERef = EObjectHelper.createEReference("countable", QMMMetaModelBuilder_Collections.defaultEClasses.get("CountableReferenceParameter"), 1, 1, true); countingOperator.getESuperTypes().add(aggregationOperator); countingOperator.getEStructuralFeatures().add(countingParamERef); countingOperator.getEOperations().add(EObjectHelper.createGetAllParametersOperation(new ArrayList<EReference>(Arrays.asList(countingParamERef)))); EClass calculatingOperator = EObjectHelper.createEClass("CalculatingAggregationOperator", true); calculatingOperator.getESuperTypes().add(aggregationOperator); QMMMetaModelBuilder_Collections.defaultEClasses.put("Operator", operator); QMMMetaModelBuilder_Collections.defaultEClasses.put("ExpressionOperator", expressionOperator); QMMMetaModelBuilder_Collections.defaultEClasses.put("EnumerationOperator", enumerationOperator); QMMMetaModelBuilder_Collections.defaultEClasses.put("BitOperator", bitOperator); QMMMetaModelBuilder_Collections.defaultEClasses.put("FunctionalOperator", functionalOperator); QMMMetaModelBuilder_Collections.defaultEClasses.put("ClassOperator", classOperator); QMMMetaModelBuilder_Collections.defaultEClasses.put("AggregationOperator", aggregationOperator); QMMMetaModelBuilder_Collections.defaultEClasses.put("EvaluationOperator", evaluationOperator); QMMMetaModelBuilder_Collections.defaultEClasses.put("EvaluationFunctionalOperator", evaluationFunctionalOperator); QMMMetaModelBuilder_Collections.defaultEClasses.put("And_EvaluationBitOperator", andOperator); QMMMetaModelBuilder_Collections.defaultEClasses.put("Or_EvaluationBitOperator", orOperator); QMMMetaModelBuilder_Collections.defaultEClasses.put("CountingAggregationOperator", countingOperator); QMMMetaModelBuilder_Collections.defaultEClasses.put("CalculatingAggregationOperator", calculatingOperator); eClasses.add(operator); eClasses.add(expressionOperator); eClasses.add(enumerationOperator); eClasses.add(bitOperator); eClasses.add(functionalOperator); eClasses.add(classOperator); eClasses.add(evaluationOperator); eClasses.add(evaluationFunctionalOperator); eClasses.add(aggregationOperator); eClasses.add(evaluationBitOperator); eClasses.add(andOperator); eClasses.add(orOperator); eClasses.add(countingOperator); eClasses.add(calculatingOperator); return eClasses; } static ArrayList<EClass> createCountingAggregationOperators(){ ArrayList<EClass> eClasses = new ArrayList<EClass>(); ArrayList<EClass> integerList = new ArrayList<EClass>(); EClass countAggregationOperator = EObjectHelper.createEClass("Count_AggregationOperator", false); countAggregationOperator.getESuperTypes().add(QMMMetaModelBuilder_Collections.defaultEClasses.get("CountingAggregationOperator")); EAnnotation annotation = EObjectHelper.createGenModelAnnotation("return \"count\";"); EOperation getLiteral = EObjectHelper.createEOperation("getLiteral", EcorePackage.Literals.ESTRING, 1, 1, new ArrayList<EAnnotation>(Arrays.asList(annotation))); countAggregationOperator.getEOperations().add(getLiteral); countAggregationOperator.getESuperTypes().add(QMMMetaModelBuilder_Collections.typedEvaluationOperationArguments.get("Integer")); EAnnotation infoAnnotation = EObjectHelper.createEAnnotation("information"); infoAnnotation.getDetails().put("functionalType", "Integer"); infoAnnotation.getDetails().put("literal", "count"); infoAnnotation.getDetails().put("operatorXTextLiteral", "count"); countAggregationOperator.getEAnnotations().add(infoAnnotation); integerList.add(countAggregationOperator); QMMMetaModelBuilder_Collections.countingAggregationOperators.put("Integer",integerList); eClasses.add(countAggregationOperator); return eClasses; } static ArrayList<EClass> createCalculatingAggregationOperators(){ ArrayList<EClass> eClasses = new ArrayList<EClass>(); ArrayList<EClass> integerList = new ArrayList<EClass>(); ArrayList<EClass> doubleList = new ArrayList<EClass>(); EClass sumAggregationOperator_Integer = EObjectHelper.createCalculatingOperator("Sum_AggregationOperator_Integer", "sum", "Integer", "Integer"); integerList.add(sumAggregationOperator_Integer); EClass minAggregationOperator_Integer = EObjectHelper.createCalculatingOperator("Min_AggregationOperator_Integer", "min", "Integer", "Integer"); integerList.add(minAggregationOperator_Integer); EClass maxAggregationOperator_Integer = EObjectHelper.createCalculatingOperator("Max_AggregationOperator_Integer", "max", "Integer", "Integer"); integerList.add(maxAggregationOperator_Integer); EClass sumAggregationOperator_Double = EObjectHelper.createCalculatingOperator("Sum_AggregationOperator_Double", "sum", "Double", "Double"); doubleList.add(sumAggregationOperator_Double); EClass minAggregationOperator_Double = EObjectHelper.createCalculatingOperator("Min_AggregationOperator_Double", "min", "Double", "Double"); doubleList.add(minAggregationOperator_Double); EClass maxAggregationOperator_Double = EObjectHelper.createCalculatingOperator("Max_AggregationOperator_Double", "max", "Double", "Double"); doubleList.add(maxAggregationOperator_Double); QMMMetaModelBuilder_Collections.calculatingAggregationOperators.put("Integer", integerList); QMMMetaModelBuilder_Collections.calculatingAggregationOperators.put("Double", doubleList); eClasses.addAll(integerList); eClasses.addAll(doubleList); return eClasses; } static ArrayList<EClass> createConcreteClassOperators(){ ArrayList<EClass> eClasses = new ArrayList<EClass>(); ArrayList<EClass> integerList = new ArrayList<EClass>(); EClass integerParseIntOperator = EObjectHelper.createClassOperator("IntegerParseInt_ClassOperator", "Integer.parseInt", "Integer.parseInt", "Integer", "String"); integerList.add(integerParseIntOperator); QMMMetaModelBuilder_Collections.classOperators.put("Integer", integerList); eClasses.addAll(integerList); return eClasses; } static ArrayList<EClassifier> readFunctionalOperators(){ ArrayList<EClassifier> eClassifiers = new ArrayList<EClassifier>(); ArrayList<String[]> lines = CSVReader.readFunctionalOperators(); for(String[] line:lines){ eClassifiers.addAll(QMMMetaModelBuilder_Types.updateExpressionTypeSystem(line[0])); eClassifiers.addAll(QMMMetaModelBuilder_Types.updateExpressionTypeSystem(line[1])); ArrayList<EReference> paramEReferences = new ArrayList<EReference>(); int i=4; while(i < line.length){ String s = line[i]; String paramName = s.split(":")[0]; String paramType = s.split(":")[1]; eClassifiers.addAll(QMMMetaModelBuilder_Types.updateExpressionTypeSystem(paramType)); paramEReferences.add(QMMMetaModelBuilder_Parameters.createParameterReference(paramName, paramType)); i++; } eClassifiers.add(QMMMetaModelBuilder_Operators.createConcreteFunctionalOperator(line[2], line[3], line[0], QMMMetaModelBuilder_Collections.functionalTypes.get(line[1]), paramEReferences)); } return eClassifiers; } static ArrayList<EClass> updateTypedOperators(String eType){ ArrayList<EClass> eClasses = new ArrayList<EClass>(); if(QMMMetaModelBuilder_Collections.typedOperators.get(eType)==null) eClasses.add(QMMMetaModelBuilder_Operators.createTypedOperator(eType)); return eClasses; } static EClass createTypedOperator(String eType){ EClass typedOperator = EObjectHelper.createEClass(eType + "_Operator", true); typedOperator.getESuperTypes().add(QMMMetaModelBuilder_Collections.defaultEClasses.get("Operator")); QMMMetaModelBuilder_Collections.typedOperators.put(eType, typedOperator); return typedOperator; } static ArrayList<EClass> updateTypedEnumerationOperators(String eType){ ArrayList<EClass> eClasses = new ArrayList<EClass>(); if(QMMMetaModelBuilder_Collections.typedOperators.get(eType)==null) eClasses.addAll(updateTypedOperators(eType)); if(QMMMetaModelBuilder_Collections.typedEnumerationOperators.get(eType)==null) eClasses.add(QMMMetaModelBuilder_Operators.createTypedEnumerationOperator(eType)); return eClasses; } static EClass createTypedEnumerationOperator(String eType){ EClass typedEnumerationOperator = EObjectHelper.createEClass(eType + "_EnumerationOperator", false); typedEnumerationOperator.getESuperTypes().add(QMMMetaModelBuilder_Collections.defaultEClasses.get("EnumerationOperator")); typedEnumerationOperator.getESuperTypes().add(QMMMetaModelBuilder_Collections.typedOperators.get(eType)); typedEnumerationOperator.getEStructuralFeatures().add(EObjectHelper.createEAttribute("argument", QMMMetaModelBuilder_Collections.eClassifiersMap.get(eType), 1, 1, false)); typedEnumerationOperator.getEStructuralFeatures().add(EObjectHelper.createEReference("or", typedEnumerationOperator, 0, 1, true)); QMMMetaModelBuilder_Collections.typedEnumerationOperators.put(eType, typedEnumerationOperator); return typedEnumerationOperator; } static ArrayList<EClassifier> createTypedExpressionOperators(String eType){ ArrayList<EClassifier> eClassifiers = new ArrayList<EClassifier>(); EClass typedExpressionOperator = EObjectHelper.createEClass(eType + "_ExpressionOperator",true); typedExpressionOperator.getESuperTypes().add(QMMMetaModelBuilder_Collections.defaultEClasses.get("ExpressionOperator")); typedExpressionOperator.getESuperTypes().add(QMMMetaModelBuilder_Collections.typedOperators.get(eType)); EAnnotation infoAnnotation = EObjectHelper.createEAnnotation("information"); infoAnnotation.getDetails().put("type", eType); typedExpressionOperator.getEAnnotations().add(infoAnnotation); eClassifiers.add(typedExpressionOperator); //Typed_BitOperator EReference connectsERef = EObjectHelper.createEReference("connects", typedExpressionOperator, 2, -1, true); EClass typedBitOperator = EObjectHelper.createEClass(eType + "_BitOperator", true); typedBitOperator.getESuperTypes().add(typedExpressionOperator); typedBitOperator.getESuperTypes().add(QMMMetaModelBuilder_Collections.defaultEClasses.get("BitOperator")); typedBitOperator.getEStructuralFeatures().add(connectsERef); typedBitOperator.getEAnnotations().add(EcoreUtil.copy(infoAnnotation)); eClassifiers.add(typedBitOperator); EAnnotation and_annotation = EObjectHelper.createGenModelAnnotation("return \"&&\";"); EOperation and_operation = EObjectHelper.createEOperation("getLiteral", EcorePackage.Literals.ESTRING, 1, 1, new ArrayList<EAnnotation>(Arrays.asList(and_annotation))); EClass typedAndOperator = EObjectHelper.createEClass(eType + "_And_BitOperator", false); typedAndOperator.getESuperTypes().add(typedBitOperator); typedAndOperator.getEOperations().add(and_operation); typedAndOperator.getEAnnotations().add(EcoreUtil.copy(infoAnnotation)); eClassifiers.add(typedAndOperator); EAnnotation or_annotation = EObjectHelper.createGenModelAnnotation("return \"||\";"); EOperation or_operation = EObjectHelper.createEOperation("getLiteral", EcorePackage.Literals.ESTRING, 1, 1, new ArrayList<EAnnotation>(Arrays.asList(or_annotation))); EClass typedOrOperator = EObjectHelper.createEClass(eType + "_Or_BitOperator", false); typedOrOperator.getESuperTypes().add(typedBitOperator); typedOrOperator.getEOperations().add(or_operation); typedOrOperator.getEAnnotations().add(EcoreUtil.copy(infoAnnotation)); eClassifiers.add(typedOrOperator); //Typed_FunctionalOperator EClass typedFunctionalOperator = EObjectHelper.createEClass(eType + "_FunctionalOperator", true); typedFunctionalOperator.getESuperTypes().add(typedExpressionOperator); typedFunctionalOperator.getESuperTypes().add(QMMMetaModelBuilder_Collections.defaultEClasses.get("FunctionalOperator")); typedFunctionalOperator.getEAnnotations().add(EcoreUtil.copy(infoAnnotation)); EReference functionalOperatorERef = EObjectHelper.createEReference("operator", typedFunctionalOperator, 0, 1, true); QMMMetaModelBuilder_Collections.functionalTypes.get(eType).getEStructuralFeatures().add(functionalOperatorERef); if(QMMMetaModelBuilder_Collections.functionalOperators.get(eType) == null) QMMMetaModelBuilder_Collections.functionalOperators.put(eType, typedFunctionalOperator); eClassifiers.add(typedFunctionalOperator); QMMMetaModelBuilder_Collections.typedExpressionOperators.put(eType, typedExpressionOperator); return eClassifiers; } static ArrayList<EClassifier> updateTypedExpressionOperators(String eType){ ArrayList<EClassifier> eClassifiers = new ArrayList<EClassifier>(); if(QMMMetaModelBuilder_Collections.typedExpressionOperators.get(eType)==null) eClassifiers.addAll(createTypedExpressionOperators(eType)); return eClassifiers; } static EClass createConcreteFunctionalOperator(String name, String literal, String functionalOperatorType, EClass functionalType, ArrayList<EReference> parameterEReferences){ EAnnotation annotation = EObjectHelper.createGenModelAnnotation("return \"" + literal + "\";"); EOperation getLiteral = EObjectHelper.createEOperation("getLiteral", EcorePackage.Literals.ESTRING, 1, 1, new ArrayList<EAnnotation>(Arrays.asList(annotation))); EClass concreteFunctionalOperator = EObjectHelper.createEClass(name + "_FunctionalOperator", false); concreteFunctionalOperator.getESuperTypes().add(QMMMetaModelBuilder_Collections.functionalOperators.get(functionalOperatorType)); concreteFunctionalOperator.getESuperTypes().add(functionalType); concreteFunctionalOperator.getEStructuralFeatures().addAll(parameterEReferences); concreteFunctionalOperator.getEOperations().add(getLiteral); concreteFunctionalOperator.getEOperations().add(EObjectHelper.createGetAllParametersOperation(parameterEReferences)); if(QMMMetaModelBuilder_Collections.concreteFunctionalOperators.get(functionalOperatorType)==null) QMMMetaModelBuilder_Collections.concreteFunctionalOperators.put(functionalOperatorType, new ArrayList<EClass>()); QMMMetaModelBuilder_Collections.concreteFunctionalOperators.get(functionalOperatorType).add(concreteFunctionalOperator); EAnnotation infoAnnotation = EObjectHelper.createEAnnotation("information"); infoAnnotation.getDetails().put("name", name); infoAnnotation.getDetails().put("literal", literal); infoAnnotation.getDetails().put("functionalOperatorType",functionalOperatorType); infoAnnotation.getDetails().put("functionalType",functionalType.getName()); concreteFunctionalOperator.getEAnnotations().add(infoAnnotation); return concreteFunctionalOperator; } }
18,849
0.815693
0.813836
326
56.819019
45.023319
191
false
false
0
0
0
0
0
0
2.972393
false
false
0
b1c3f6bbb3cc1c530cde665b0565b47006bbde9f
16,501,264,388,405
981c81928b1ed59aa51e2495bfc13d6d2804de02
/Strategos/src/com/visiongc/app/strategos/web/struts/planes/actions/ReportePlanesAction.java
bc3cfd45d87d1a217e56eecb4e5e15bda6625f07
[]
no_license
acaucali/Strategos
https://github.com/acaucali/Strategos
7f9b1e7ed329a4bb84379cc1db0bf95dfe7e6814
1aa41b9e0daa2f777b70160fdb6a41f50f07f628
refs/heads/master
2021-12-19T12:46:58.309000
2021-12-09T14:15:18
2021-12-09T14:15:18
146,344,252
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.visiongc.app.strategos.web.struts.planes.actions; import com.lowagie.text.Document; import com.lowagie.text.Font; import com.lowagie.text.Paragraph; import com.visiongc.app.strategos.impl.StrategosServiceFactory; import com.visiongc.app.strategos.planes.StrategosPlanesService; import com.visiongc.app.strategos.planes.model.Plan; import com.visiongc.commons.report.TablaBasicaPDF; import com.visiongc.commons.struts.action.VgcReporteBasicoAction; import com.visiongc.commons.util.PaginaLista; import com.visiongc.framework.configuracion.sistema.ConfiguracionPagina; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts.action.ActionForm; import org.apache.struts.util.MessageResources; public class ReportePlanesAction extends VgcReporteBasicoAction { protected String agregarTitulo(HttpServletRequest request, MessageResources mensajes) throws Exception { return mensajes.getMessage("action.reporteplanes.titulo"); } protected void construirReporte(ActionForm form, HttpServletRequest request, HttpServletResponse response, Document documento) throws Exception { String atributoOrden = request.getParameter("atributoOrden"); String tipoOrden = request.getParameter("tipoOrden"); String tipo = request.getParameter("tipo"); String organizacionId = (String)request.getSession().getAttribute("organizacionId"); Font font = new Font(getConfiguracionPagina(request).getCodigoFuente()); MessageResources mensajes = getResources(request); StrategosPlanesService strategosPlanesService = StrategosServiceFactory.getInstance().openStrategosPlanesService(); TablaBasicaPDF tabla = null; tabla = new TablaBasicaPDF(getConfiguracionPagina(request), request); int[] columnas = new int[4]; columnas[0] = 80; columnas[1] = 20; columnas[2] = 20; columnas[3] = 20; tabla.setAmplitudTabla(100); tabla.crearTabla(columnas); Map filtros = new HashMap(); if ((organizacionId != null) && (!organizacionId.equals(""))) { filtros.put("organizacionId", organizacionId); } filtros.put("tipo", tipo); List planes = strategosPlanesService.getPlanes(0, 0, atributoOrden, tipoOrden, false, filtros).getLista(); tabla.setFormatoFont(font.style()); tabla.setAlineacionHorizontal(TablaBasicaPDF.H_ALINEACION_CENTER); tabla.agregarCelda(mensajes.getMessage("action.reporteplanes.nombre")); tabla.agregarCelda(mensajes.getMessage("action.reporteplanes.anoinicial")); tabla.agregarCelda(mensajes.getMessage("action.reporteplanes.anofinal")); tabla.agregarCelda(mensajes.getMessage("action.reporteplanes.revision")); tabla.setDefaultAlineacionHorizontal(); if ((planes != null) && (planes.size() > 0)) { for (Iterator iter = planes.iterator(); iter.hasNext(); ) { Plan plan = (Plan)iter.next(); tabla.setDefaultAlineacionHorizontal(); tabla.agregarCelda(plan.getNombre()); tabla.setAlineacionHorizontal(TablaBasicaPDF.H_ALINEACION_CENTER); tabla.agregarCelda(plan.getAnoInicial().toString()); tabla.agregarCelda(plan.getAnoFinal().toString()); tabla.agregarCelda("[" + plan.getRevisionNombre() + "]"); } documento.add(tabla.getTabla()); } else { tabla.setColspan(4); font.setStyle(2); Paragraph texto = new Paragraph(" " + mensajes.getMessage("action.reporteplanes.noplanes"), font); texto.setAlignment(0); documento.add(texto); } documento.newPage(); strategosPlanesService.close(); } }
UTF-8
Java
3,759
java
ReportePlanesAction.java
Java
[]
null
[]
package com.visiongc.app.strategos.web.struts.planes.actions; import com.lowagie.text.Document; import com.lowagie.text.Font; import com.lowagie.text.Paragraph; import com.visiongc.app.strategos.impl.StrategosServiceFactory; import com.visiongc.app.strategos.planes.StrategosPlanesService; import com.visiongc.app.strategos.planes.model.Plan; import com.visiongc.commons.report.TablaBasicaPDF; import com.visiongc.commons.struts.action.VgcReporteBasicoAction; import com.visiongc.commons.util.PaginaLista; import com.visiongc.framework.configuracion.sistema.ConfiguracionPagina; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts.action.ActionForm; import org.apache.struts.util.MessageResources; public class ReportePlanesAction extends VgcReporteBasicoAction { protected String agregarTitulo(HttpServletRequest request, MessageResources mensajes) throws Exception { return mensajes.getMessage("action.reporteplanes.titulo"); } protected void construirReporte(ActionForm form, HttpServletRequest request, HttpServletResponse response, Document documento) throws Exception { String atributoOrden = request.getParameter("atributoOrden"); String tipoOrden = request.getParameter("tipoOrden"); String tipo = request.getParameter("tipo"); String organizacionId = (String)request.getSession().getAttribute("organizacionId"); Font font = new Font(getConfiguracionPagina(request).getCodigoFuente()); MessageResources mensajes = getResources(request); StrategosPlanesService strategosPlanesService = StrategosServiceFactory.getInstance().openStrategosPlanesService(); TablaBasicaPDF tabla = null; tabla = new TablaBasicaPDF(getConfiguracionPagina(request), request); int[] columnas = new int[4]; columnas[0] = 80; columnas[1] = 20; columnas[2] = 20; columnas[3] = 20; tabla.setAmplitudTabla(100); tabla.crearTabla(columnas); Map filtros = new HashMap(); if ((organizacionId != null) && (!organizacionId.equals(""))) { filtros.put("organizacionId", organizacionId); } filtros.put("tipo", tipo); List planes = strategosPlanesService.getPlanes(0, 0, atributoOrden, tipoOrden, false, filtros).getLista(); tabla.setFormatoFont(font.style()); tabla.setAlineacionHorizontal(TablaBasicaPDF.H_ALINEACION_CENTER); tabla.agregarCelda(mensajes.getMessage("action.reporteplanes.nombre")); tabla.agregarCelda(mensajes.getMessage("action.reporteplanes.anoinicial")); tabla.agregarCelda(mensajes.getMessage("action.reporteplanes.anofinal")); tabla.agregarCelda(mensajes.getMessage("action.reporteplanes.revision")); tabla.setDefaultAlineacionHorizontal(); if ((planes != null) && (planes.size() > 0)) { for (Iterator iter = planes.iterator(); iter.hasNext(); ) { Plan plan = (Plan)iter.next(); tabla.setDefaultAlineacionHorizontal(); tabla.agregarCelda(plan.getNombre()); tabla.setAlineacionHorizontal(TablaBasicaPDF.H_ALINEACION_CENTER); tabla.agregarCelda(plan.getAnoInicial().toString()); tabla.agregarCelda(plan.getAnoFinal().toString()); tabla.agregarCelda("[" + plan.getRevisionNombre() + "]"); } documento.add(tabla.getTabla()); } else { tabla.setColspan(4); font.setStyle(2); Paragraph texto = new Paragraph(" " + mensajes.getMessage("action.reporteplanes.noplanes"), font); texto.setAlignment(0); documento.add(texto); } documento.newPage(); strategosPlanesService.close(); } }
3,759
0.743283
0.73743
102
35.862743
30.59445
128
false
false
0
0
0
0
0
0
0.764706
false
false
0
434330e931e0e5b643a66c1d9cb63097bcfe04b1
4,226,247,853,948
70a600b6bc8551c2482fa923a266c445e290d839
/src/main/java/com/wondersgroup/framework/menu/dao/impl/MenuResourceExtdDAOImpl.java
db2841718adf1365974ed908e5d59d8ed1524c32
[]
no_license
littleqh0128/Pcf
https://github.com/littleqh0128/Pcf
aa2a5a479287dd7eafa09f94f1f2c9f3928911cb
0490c753590b375c9743e102c683c05c1f9d03e5
refs/heads/master
2021-01-13T09:11:49.359000
2016-09-30T05:55:18
2016-09-30T05:55:18
69,220,471
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.wondersgroup.framework.menu.dao.impl; import com.wondersgroup.framework.core.bo.Page; import com.wondersgroup.framework.core.bo.hibernate.HqlParameter; import com.wondersgroup.framework.core.dao.impl.AbstractHibernateExtdDAOImpl; import com.wondersgroup.framework.menu.bo.MenuResource; import com.wondersgroup.framework.menu.dao.MenuResourceExtdDAO; import com.wondersgroup.framework.security.bo.ACLOperation; import com.wondersgroup.framework.security.bo.ACLResource; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.springframework.stereotype.Repository; @Repository public class MenuResourceExtdDAOImpl extends AbstractHibernateExtdDAOImpl implements MenuResourceExtdDAO { protected Class getEntityClass() { return MenuResource.class; } public List getAllMenuResources() { return getHibernateTemplate().find("from MenuResource menu where menu.valid = 1 order by menu.parentResource, menu.displayOrder"); } public List getChildMenuResourcesByParentMenu(MenuResource parentMenuResource) { return getHibernateTemplate().find("from MenuResource menu left join fetch menu.host left join fetch menu.menuType where menu.parentResource = ? and menu.valid = 1 order by menu.displayOrder", new Object[] { parentMenuResource }); } public int getMenuResourceCount() { return super.countByHQL("select count(*) from MenuResource"); } public boolean isExistChildrenMenuResourceByParentMenu(MenuResource menuResource) { boolean isExisted = false; List result = getHibernateTemplate().find("select count(*) from MenuResource menu where menu.parentResource = ?", new Object[] { menuResource }); if (result.size() > 0) { isExisted = true; } return isExisted; } public List getTopMenuResources() { return getHibernateTemplate().find("from MenuResource menu where menu.parentResource is null order by menu.displayOrder"); } public void delMenuResourceById(MenuResource menuResource) { delete(menuResource); } public MenuResource getTopMenuInfoByName(String resourceName) { List res = getHibernateTemplate().find("from MenuResource menu where menu.parentResource is null and menu.resourceName=?", resourceName); return (res != null) && (res.size() > 0) ? (MenuResource)res.get(0) : null; } public Page getUsersByPageAndACLMenu(ACLResource aclResource, ACLOperation aclOperation, int pageNo, int pageSize) { Date dueTime = new Date(System.currentTimeMillis()); List args = new ArrayList(); args.add(new HqlParameter("aclResource", aclResource)); args.add(new HqlParameter("aclOperation", aclOperation)); args.add(new HqlParameter("dueTime", dueTime)); StringBuffer hql = new StringBuffer(); hql.append("select distinct user0 from SecurityUser user0 inner join user0.roles role1").append(" where user0.removed=0 and role1 in (select distinct role from ACLPermission permission inner join permission.roles role where ").append(" permission.aclResource = :aclResource and permission.aclOperation = :aclOperation and (permission.dueTime is null or permission.dueTime > :dueTime))").append("or user0 in (select user1 from SecurityUser user1 inner join user1.groups group1 where group1 in").append("(select distinct group0 from SecurityGroup group0 inner join group0.roles role1").append(" where role1 in (select distinct role from ACLPermission permission inner join permission.roles role where ").append(" permission.aclResource = :aclResource and permission.aclOperation = :aclOperation and (permission.dueTime is null or permission.dueTime > :dueTime)))) "); return findByHQLWithPage(hql.toString(), args, pageNo, pageSize, null); } public Page getUsersByPageAndREVMenu(ACLResource aclResource, ACLOperation aclOperation, int pageNo, int pageSize) { Date dueTime = new Date(System.currentTimeMillis()); List args = new ArrayList(); args.add(new HqlParameter("aclResource", aclResource)); args.add(new HqlParameter("aclOperation", aclOperation)); args.add(new HqlParameter("dueTime", dueTime)); StringBuffer hql = new StringBuffer(); hql.append("select distinct user0 from SecurityUser user0 inner join user0.roles role1").append(" where user0.removed=0 and role1 in (select distinct role from ACLPermission permission inner join permission.revokeRoles role where ").append(" permission.aclResource = :aclResource and permission.aclOperation = :aclOperation and (permission.dueTime is null or permission.dueTime > :dueTime))").append(" or user0 in (select user1 from SecurityUser user1 inner join user1.groups group1 where group1 in").append("(select distinct group0 from SecurityGroup group0 inner join group0.roles role1").append(" where role1 in (select distinct role from ACLPermission permission inner join permission.revokeRoles role where ").append(" permission.aclResource = :aclResource and permission.aclOperation = :aclOperation and (permission.dueTime is null or permission.dueTime > :dueTime)))) "); return findByHQLWithPage(hql.toString(), args, pageNo, pageSize, null); } public Page getGroupsByPageAndACLMenu(ACLResource aclResource, ACLOperation aclOperation, int pageNo, int pageSize) { Date dueTime = new Date(System.currentTimeMillis()); List args = new ArrayList(); args.add(new HqlParameter("aclResource", aclResource)); args.add(new HqlParameter("aclOperation", aclOperation)); args.add(new HqlParameter("dueTime", dueTime)); StringBuffer hql = new StringBuffer(); hql.append("select distinct group0 from SecurityGroup group0 inner join group0.roles role1").append(" where role1 in (select distinct role from ACLPermission permission inner join permission.roles role where ").append(" permission.aclResource = :aclResource and permission.aclOperation = :aclOperation and (permission.dueTime is null or permission.dueTime > :dueTime)) "); return findByHQLWithPage(hql.toString(), args, pageNo, pageSize, null); } public Page getGroupsByPageAndREVMenu(ACLResource aclResource, ACLOperation aclOperation, int pageNo, int pageSize) { Date dueTime = new Date(System.currentTimeMillis()); List args = new ArrayList(); args.add(new HqlParameter("aclResource", aclResource)); args.add(new HqlParameter("aclOperation", aclOperation)); args.add(new HqlParameter("dueTime", dueTime)); StringBuffer hql = new StringBuffer(); hql.append("select distinct group0 from SecurityGroup group0 inner join group0.roles role1").append(" where role1 in (select distinct role from ACLPermission permission inner join permission.revokeRoles role where ").append(" permission.aclResource = :aclResource and permission.aclOperation = :aclOperation and (permission.dueTime is null or permission.dueTime > :dueTime)) "); return findByHQLWithPage(hql.toString(), args, pageNo, pageSize, null); } public List getGroupsByREVMenu(ACLResource aclResource, ACLOperation aclOperation) { Date dueTime = new Date(System.currentTimeMillis()); List args = new ArrayList(); args.add(new HqlParameter("aclResource", aclResource)); args.add(new HqlParameter("aclOperation", aclOperation)); args.add(new HqlParameter("dueTime", dueTime)); StringBuffer hql = new StringBuffer(); hql.append("select distinct group0 from SecurityGroup group0 inner join group0.roles role1").append(" where role1 in (select distinct role from ACLPermission permission inner join permission.revokeRoles role where ").append(" permission.aclResource = :aclResource and permission.aclOperation = :aclOperation and (permission.dueTime is null or permission.dueTime > :dueTime)) "); return findByHQL(hql.toString(), args); } public List getUsersByREVMenu(ACLResource aclResource, ACLOperation aclOperation) { Date dueTime = new Date(System.currentTimeMillis()); List args = new ArrayList(); args.add(new HqlParameter("aclResource", aclResource)); args.add(new HqlParameter("aclOperation", aclOperation)); args.add(new HqlParameter("dueTime", dueTime)); StringBuffer hql = new StringBuffer(); hql.append("select distinct user0 from SecurityUser user0 inner join user0.roles role1").append(" where role1 in (select distinct role from ACLPermission permission inner join permission.revokeRoles role where ").append(" permission.aclResource = :aclResource and permission.aclOperation = :aclOperation and (permission.dueTime is null or permission.dueTime > :dueTime))").append(" or user0 in (select user1 from SecurityUser user1 inner join user1.groups group1 where group1 in").append("(select distinct group0 from SecurityGroup group0 inner join group0.roles role1").append(" where role1 in (select distinct role from ACLPermission permission inner join permission.revokeRoles role where ").append(" permission.aclResource = :aclResource and permission.aclOperation = :aclOperation and (permission.dueTime is null or permission.dueTime > :dueTime)))) "); return findByHQL(hql.toString(), args); } }
UTF-8
Java
9,102
java
MenuResourceExtdDAOImpl.java
Java
[]
null
[]
package com.wondersgroup.framework.menu.dao.impl; import com.wondersgroup.framework.core.bo.Page; import com.wondersgroup.framework.core.bo.hibernate.HqlParameter; import com.wondersgroup.framework.core.dao.impl.AbstractHibernateExtdDAOImpl; import com.wondersgroup.framework.menu.bo.MenuResource; import com.wondersgroup.framework.menu.dao.MenuResourceExtdDAO; import com.wondersgroup.framework.security.bo.ACLOperation; import com.wondersgroup.framework.security.bo.ACLResource; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.springframework.stereotype.Repository; @Repository public class MenuResourceExtdDAOImpl extends AbstractHibernateExtdDAOImpl implements MenuResourceExtdDAO { protected Class getEntityClass() { return MenuResource.class; } public List getAllMenuResources() { return getHibernateTemplate().find("from MenuResource menu where menu.valid = 1 order by menu.parentResource, menu.displayOrder"); } public List getChildMenuResourcesByParentMenu(MenuResource parentMenuResource) { return getHibernateTemplate().find("from MenuResource menu left join fetch menu.host left join fetch menu.menuType where menu.parentResource = ? and menu.valid = 1 order by menu.displayOrder", new Object[] { parentMenuResource }); } public int getMenuResourceCount() { return super.countByHQL("select count(*) from MenuResource"); } public boolean isExistChildrenMenuResourceByParentMenu(MenuResource menuResource) { boolean isExisted = false; List result = getHibernateTemplate().find("select count(*) from MenuResource menu where menu.parentResource = ?", new Object[] { menuResource }); if (result.size() > 0) { isExisted = true; } return isExisted; } public List getTopMenuResources() { return getHibernateTemplate().find("from MenuResource menu where menu.parentResource is null order by menu.displayOrder"); } public void delMenuResourceById(MenuResource menuResource) { delete(menuResource); } public MenuResource getTopMenuInfoByName(String resourceName) { List res = getHibernateTemplate().find("from MenuResource menu where menu.parentResource is null and menu.resourceName=?", resourceName); return (res != null) && (res.size() > 0) ? (MenuResource)res.get(0) : null; } public Page getUsersByPageAndACLMenu(ACLResource aclResource, ACLOperation aclOperation, int pageNo, int pageSize) { Date dueTime = new Date(System.currentTimeMillis()); List args = new ArrayList(); args.add(new HqlParameter("aclResource", aclResource)); args.add(new HqlParameter("aclOperation", aclOperation)); args.add(new HqlParameter("dueTime", dueTime)); StringBuffer hql = new StringBuffer(); hql.append("select distinct user0 from SecurityUser user0 inner join user0.roles role1").append(" where user0.removed=0 and role1 in (select distinct role from ACLPermission permission inner join permission.roles role where ").append(" permission.aclResource = :aclResource and permission.aclOperation = :aclOperation and (permission.dueTime is null or permission.dueTime > :dueTime))").append("or user0 in (select user1 from SecurityUser user1 inner join user1.groups group1 where group1 in").append("(select distinct group0 from SecurityGroup group0 inner join group0.roles role1").append(" where role1 in (select distinct role from ACLPermission permission inner join permission.roles role where ").append(" permission.aclResource = :aclResource and permission.aclOperation = :aclOperation and (permission.dueTime is null or permission.dueTime > :dueTime)))) "); return findByHQLWithPage(hql.toString(), args, pageNo, pageSize, null); } public Page getUsersByPageAndREVMenu(ACLResource aclResource, ACLOperation aclOperation, int pageNo, int pageSize) { Date dueTime = new Date(System.currentTimeMillis()); List args = new ArrayList(); args.add(new HqlParameter("aclResource", aclResource)); args.add(new HqlParameter("aclOperation", aclOperation)); args.add(new HqlParameter("dueTime", dueTime)); StringBuffer hql = new StringBuffer(); hql.append("select distinct user0 from SecurityUser user0 inner join user0.roles role1").append(" where user0.removed=0 and role1 in (select distinct role from ACLPermission permission inner join permission.revokeRoles role where ").append(" permission.aclResource = :aclResource and permission.aclOperation = :aclOperation and (permission.dueTime is null or permission.dueTime > :dueTime))").append(" or user0 in (select user1 from SecurityUser user1 inner join user1.groups group1 where group1 in").append("(select distinct group0 from SecurityGroup group0 inner join group0.roles role1").append(" where role1 in (select distinct role from ACLPermission permission inner join permission.revokeRoles role where ").append(" permission.aclResource = :aclResource and permission.aclOperation = :aclOperation and (permission.dueTime is null or permission.dueTime > :dueTime)))) "); return findByHQLWithPage(hql.toString(), args, pageNo, pageSize, null); } public Page getGroupsByPageAndACLMenu(ACLResource aclResource, ACLOperation aclOperation, int pageNo, int pageSize) { Date dueTime = new Date(System.currentTimeMillis()); List args = new ArrayList(); args.add(new HqlParameter("aclResource", aclResource)); args.add(new HqlParameter("aclOperation", aclOperation)); args.add(new HqlParameter("dueTime", dueTime)); StringBuffer hql = new StringBuffer(); hql.append("select distinct group0 from SecurityGroup group0 inner join group0.roles role1").append(" where role1 in (select distinct role from ACLPermission permission inner join permission.roles role where ").append(" permission.aclResource = :aclResource and permission.aclOperation = :aclOperation and (permission.dueTime is null or permission.dueTime > :dueTime)) "); return findByHQLWithPage(hql.toString(), args, pageNo, pageSize, null); } public Page getGroupsByPageAndREVMenu(ACLResource aclResource, ACLOperation aclOperation, int pageNo, int pageSize) { Date dueTime = new Date(System.currentTimeMillis()); List args = new ArrayList(); args.add(new HqlParameter("aclResource", aclResource)); args.add(new HqlParameter("aclOperation", aclOperation)); args.add(new HqlParameter("dueTime", dueTime)); StringBuffer hql = new StringBuffer(); hql.append("select distinct group0 from SecurityGroup group0 inner join group0.roles role1").append(" where role1 in (select distinct role from ACLPermission permission inner join permission.revokeRoles role where ").append(" permission.aclResource = :aclResource and permission.aclOperation = :aclOperation and (permission.dueTime is null or permission.dueTime > :dueTime)) "); return findByHQLWithPage(hql.toString(), args, pageNo, pageSize, null); } public List getGroupsByREVMenu(ACLResource aclResource, ACLOperation aclOperation) { Date dueTime = new Date(System.currentTimeMillis()); List args = new ArrayList(); args.add(new HqlParameter("aclResource", aclResource)); args.add(new HqlParameter("aclOperation", aclOperation)); args.add(new HqlParameter("dueTime", dueTime)); StringBuffer hql = new StringBuffer(); hql.append("select distinct group0 from SecurityGroup group0 inner join group0.roles role1").append(" where role1 in (select distinct role from ACLPermission permission inner join permission.revokeRoles role where ").append(" permission.aclResource = :aclResource and permission.aclOperation = :aclOperation and (permission.dueTime is null or permission.dueTime > :dueTime)) "); return findByHQL(hql.toString(), args); } public List getUsersByREVMenu(ACLResource aclResource, ACLOperation aclOperation) { Date dueTime = new Date(System.currentTimeMillis()); List args = new ArrayList(); args.add(new HqlParameter("aclResource", aclResource)); args.add(new HqlParameter("aclOperation", aclOperation)); args.add(new HqlParameter("dueTime", dueTime)); StringBuffer hql = new StringBuffer(); hql.append("select distinct user0 from SecurityUser user0 inner join user0.roles role1").append(" where role1 in (select distinct role from ACLPermission permission inner join permission.revokeRoles role where ").append(" permission.aclResource = :aclResource and permission.aclOperation = :aclOperation and (permission.dueTime is null or permission.dueTime > :dueTime))").append(" or user0 in (select user1 from SecurityUser user1 inner join user1.groups group1 where group1 in").append("(select distinct group0 from SecurityGroup group0 inner join group0.roles role1").append(" where role1 in (select distinct role from ACLPermission permission inner join permission.revokeRoles role where ").append(" permission.aclResource = :aclResource and permission.aclOperation = :aclOperation and (permission.dueTime is null or permission.dueTime > :dueTime)))) "); return findByHQL(hql.toString(), args); } }
9,102
0.762909
0.754999
145
61.772415
133.182159
883
false
false
0
0
0
0
0
0
0.868966
false
false
0
b3a9709662c1909aa3dc15ef0e9ed117d6f075fb
20,315,195,328,058
ed1165ee53d485e013f6340467f6d971af8ccb09
/src/main/scala/com/company/spark/recon/challenges/A.java
52d11f68f50bd778a1d6f5bbacd862c6810d243f
[]
no_license
naanimp/spark-recon
https://github.com/naanimp/spark-recon
a28483d19a203244a6c0e217fa6fe59ea27c3d61
9f0adf72000c42ac4d8d59e82256a9fa3bdd0db0
refs/heads/master
2023-01-11T17:11:34.893000
2020-11-12T12:52:19
2020-11-12T12:52:19
303,994,049
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.company.spark.recon.challenges; import java.util.HashMap; public class A { public int solution(String[] T, String[] R){ int n = T.length; HashMap<String, Boolean> wrong = new HashMap<>(); HashMap<String, Boolean> all = new HashMap<>(); for(int i = 0; i < n; i++){ int len = T[i].length(); if(T[i].charAt(len-1) >= 'a' && T[i].charAt(len-1) <= 'z'){ T[i] = T[i].substring(0, len-1); } if(R[i].equals("OK") == false){ wrong.put(T[i], true); } all.put(T[i], true); } int incorrect = wrong.size(); return (incorrect*100)/n; } }
UTF-8
Java
707
java
A.java
Java
[]
null
[]
package com.company.spark.recon.challenges; import java.util.HashMap; public class A { public int solution(String[] T, String[] R){ int n = T.length; HashMap<String, Boolean> wrong = new HashMap<>(); HashMap<String, Boolean> all = new HashMap<>(); for(int i = 0; i < n; i++){ int len = T[i].length(); if(T[i].charAt(len-1) >= 'a' && T[i].charAt(len-1) <= 'z'){ T[i] = T[i].substring(0, len-1); } if(R[i].equals("OK") == false){ wrong.put(T[i], true); } all.put(T[i], true); } int incorrect = wrong.size(); return (incorrect*100)/n; } }
707
0.472419
0.461103
24
28.458334
19.981197
71
false
false
0
0
0
0
0
0
0.791667
false
false
0
999ba9b964701530571c8221ed0be129ea88c877
10,677,288,749,153
bc4a5b2674e089a35ec7c6505690764a1cacc09e
/src/hyperledger/HyperledgerTest.java
98a94bef43bfb27836651fcc6ae6103ead3dac9a
[]
no_license
GrafW/tpm-testing
https://github.com/GrafW/tpm-testing
ae617e245d675c42664a75edbd08edc34f2259d5
e56682af4b34d02fc61180144c43ac85c376c0f9
refs/heads/master
2020-03-29T04:12:24.796000
2018-09-22T13:44:44
2018-09-22T13:44:44
149,520,505
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package hyperledger; public class HyperledgerTest { }
UTF-8
Java
56
java
HyperledgerTest.java
Java
[]
null
[]
package hyperledger; public class HyperledgerTest { }
56
0.785714
0.785714
5
10.2
12.4964
30
false
false
0
0
0
0
0
0
0.2
false
false
0
f970dddaf405f6e845ef27a5e1e58dc40a255e39
12,103,217,867,939
80a4aa9c42eb996ebe9d915e7c8bc228c3777f9c
/dxycraw/src/java/framework/org/jute/util/Strings.java
f63b4a026efdb68439670dbd08216d865d5a53a2
[]
no_license
shenbin6830/NumberOne1
https://github.com/shenbin6830/NumberOne1
410e0db176531ac416348bc475568fdeca1cc139
6937199b289c31d0048cf27f41ad00af1479dcd8
refs/heads/master
2018-02-06T22:01:15.063000
2017-06-28T13:12:47
2017-06-28T13:12:47
95,670,637
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * ---------------------------------------------------------------------------------------------------------- * $Id: Strings.java,v 1.1.1.1 2005/07/24 04:18:37 hugo Exp $ * $Source: H:/cvsroot/./dxycms/webapps/WEB-INF/src/java/org/jute/util/Strings.java,v $ * ---------------------------------------------------------------------------------------------------------- */ package org.jute.util; import java.util.Date; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.text.ParseException; import java.math.BigInteger; import java.math.BigDecimal; /** * 字符处理扩展. * 提供了从字符串到各种数据结构的转换 * * @author <a href="mailto:rainmanzhu@yahoo.com">Rainman Zhu</a> * @version $Id: Strings.java,v 1.1.1.1 2005/07/24 04:18:37 hugo Exp $ */ public class Strings { // public static String normalizeString(String str) { // if (str == null || str.length() <= 0) { // return str; // } // // StringBuffer buffer = new StringBuffer(str.length()); // boolean skipNextLF = false; // for (int i = 0; i < str.length(); i++) { // char c = str.charAt(i); // switch (c) { // case '\r': // buffer.append('\n'); // skipNextLF = true; // break; // // case '\n': // if (skipNextLF) { // skipNextLF = false; // break; // } // // default: // skipNextLF = false; // buffer.append(c); // } // } // // return buffer.toString(); // } // // public static String escapeString(String str) { // if (str == null || str.length() <= 0) { // return str; // } // // StringBuffer buffer = new StringBuffer(str.length()); // for (int i = 0; i < str.length(); i++) { // char c = str.charAt(i); // switch (c) { // case 0 : // break; // case '\b': // buffer.append("\\b"); // break; // case '\t': // buffer.append("\\t"); // break; // case '\n': // buffer.append("\\n"); // break; // case '\f': // buffer.append("\\f"); // break; // case '\r': // buffer.append("\\r"); // break; // case '\"': // buffer.append("\\\""); // break; // case '\'': // buffer.append("\\\'"); // break; // case '\\': // buffer.append("\\\\"); // break; // default: // buffer.append(c); // } // } // return buffer.toString(); // } /********************************************************************* * 将字符串转换成其它类型 * * 此处类型囊括了所有java的基本类型和BigDecimal, BigInteger类 * * *********************************************************************/ /** * 字符串转换成BigDecimal. * 如果字符串为null, 字符串不是数字, 则返回0. * * @param String 字符串 * @return BigDecimal */ public static BigDecimal asBigDecimal (String str) { return asBigDecimal(str, new BigDecimal(BigInteger.ZERO)); } /** * 字符串转换成BigDecimal. * 如果字符串为null, 字符串不是数字, 则返回指定默认值. * * @param String 字符串 * @param BigDecimal 默认值 * @return BigDecimal */ public static BigDecimal asBigDecimal (String str, BigDecimal defaultValue) { try { return new BigDecimal(str.trim()); } catch (NullPointerException e) { return defaultValue; } catch (NumberFormatException e) { return defaultValue; } catch (RuntimeException e) { // 好象是JDK的Bug, 当字符串为空串时会出现RuntimeException // 出现这种情况, 就返回默认值. return defaultValue; } } /** * 字符串转换成BigInteger. * 如果字符串为null, 字符串不是整数, 则返回0. * * @param String 字符串 * @return BigInteger */ public static BigInteger asBigInteger (String str) { return asBigInteger(str, BigInteger.ZERO); } /** * 字符串转换成BigInteger. * 如果字符串为null, 字符串不是整数, 则返回指定默认值. * * @param String 字符串 * @param BigInteger 默认值 * @return BigInteger */ public static BigInteger asBigInteger (String str, BigInteger defaultValue) { try { return new BigInteger(str.trim()); } catch (NullPointerException e) { return defaultValue; } catch (NumberFormatException e) { return defaultValue; } } // 被看作false的字符串 private static String[] FALSE_STRINGS = { "false", "null", "nul", "off", "no", "n" }; /** * 字符串转换成boolean. 转换规则如下: * 如果字符串看起来像一个整数, 且整数值等于0, 则为false, 否则true; * 如果字符串为空串或null, 则返回默认值false; * 如果字符串为下列值之一(大小写不敏感): * "false", "null", "nul", "off", "no", "n" * 则为false, 否则为true. * * @param String 字符串 * @return boolean */ public static boolean asBoolean (String str) { return asBoolean(str, false); } /** * 字符串转换成boolean. 转换规则如下: * 如果字符串看起来像一个整数, 且整数值等于0, 则为false, 否则true; * 如果字符串为空串或null, 则返回指定默认值; * 如果字符串为下列值之一(大小写不敏感): * "false", "null", "nul", "off", "no", "n" * 则为false, 否则为true. * * @param String 字符串 * @param Boolean 默认值 * @return Boolean */ public static Boolean asBoolean (String str, Boolean defaultValue) { try { str = str.trim(); return Integer.decode(str).intValue() != 0 ? Boolean.TRUE : Boolean.FALSE; } catch (NullPointerException e) { return defaultValue; } catch (NumberFormatException e) { if (str.equals("")) { return defaultValue; } for (int i = 0; i < FALSE_STRINGS.length; i++) { if (str.equalsIgnoreCase(FALSE_STRINGS[i])) { return Boolean.FALSE; } } return Boolean.TRUE; } } /** * 字符串转换成boolean. 转换规则如下: * 如果字符串看起来像一个整数, 且整数值等于0, 则为false, 否则true; * 如果字符串为空串或null, 则返回指定默认值; * 如果字符串为下列值之一(大小写不敏感): * "false", "null", "nul", "off", "no", "n" * 则为false, 否则为true. * * @param String 字符串 * @param boolean 默认值 * @return boolean */ public static boolean asBoolean (String str, boolean defaultValue) { try { str = str.trim(); return Integer.decode(str).intValue() != 0; } catch (NullPointerException e) { return defaultValue; } catch (NumberFormatException e) { if (str.equals("")) { return defaultValue; } for (int i = 0; i < FALSE_STRINGS.length; i++) { if (str.equalsIgnoreCase(FALSE_STRINGS[i])) { return false; } } return true; } } /** * 字符串转换成byte. * 如果字符串为null, 字符串不是整数或整数超过取值范围, 则返回0 * * @param String 字符串 * @return byte */ public static byte asByte (String str) { return asByte(str, (byte)0); } /** * 字符串转换成byte. * 如果字符串为null, 字符串不是整数或整数超过取值范围, 则返回指定默认值. * * @param String 字符串 * @param Byte 默认值 * @return Byte */ public static Byte asByte (String str, Byte defaultValue) { try { return Byte.decode(str.trim()); } catch (NullPointerException e) { return defaultValue; } catch (NumberFormatException e) { return defaultValue; } } /** * 字符串转换成byte. * 如果字符串为null, 字符串不是整数或整数超过取值范围, 则返回指定默认值. * * @param String 字符串 * @param byte 默认值 * @return byte */ public static byte asByte (String str, byte defaultValue) { try { return Byte.decode(str.trim()).byteValue(); } catch (NullPointerException e) { return defaultValue; } catch (NumberFormatException e) { return defaultValue; } } /** * 字符串转换成char. * 如果字符串为null, 则返回'\0' * * @param String 字符串 * @return char */ public static char asCharacter (String str) { return asCharacter(str, (char)0); } /** * 字符串转换成char. * 如果字符串为null, 则返回指定默认值. * * @param String 字符串 * @param Character 默认值 * @return Character */ public static Character asCharacter (String str, Character defaultValue) { try { return new Character(str.trim().charAt(0)); } catch (NullPointerException e) { return defaultValue; } catch (IndexOutOfBoundsException e) { return defaultValue; } } /** * 字符串转换成char. * 如果字符串为null, 则返回指定默认值. * * @param String 字符串 * @param char 默认值 * @return char */ public static char asCharacter (String str, char defaultValue) { try { return str.trim().charAt(0); } catch (NullPointerException e) { return defaultValue; } catch (IndexOutOfBoundsException e) { return defaultValue; } } /** * 字符串转换成double. * 如果字符串为null, 字符串不是浮点数或浮点数超过取值范围, 则返回0. * * @param String 字符串 * @return double */ public static double asDouble (String str) { return asDouble(str, 0.0); } /** * 字符串转换成double. * 如果字符串为null, 字符串不是浮点数或浮点数超过取值范围, 则返回指定默认值. * * @param String 字符串 * @param Double 默认值 * @return Double */ public static Double asDouble (String str, Double defaultValue) { try { return new Double(str.trim()); } catch (NullPointerException e) { return defaultValue; } catch (NumberFormatException e) { return defaultValue; } } /** * 字符串转换成double. * 如果字符串为null, 字符串不是浮点数或浮点数超过取值范围, 则返回指定默认值. * * @param String 字符串 * @param double 默认值 * @return double */ public static double asDouble (String str, double defaultValue) { try { return new Double(str.trim()).doubleValue(); } catch (NullPointerException e) { return defaultValue; } catch (NumberFormatException e) { return defaultValue; } } /** * 字符串转换成float. * 如果字符串为null, 字符串不是浮点数或浮点数超过取值范围, 则返回0. * * @param String 字符串 * @return float */ public static float asFloat (String str) { return asFloat(str, 0.0F); } /** * 字符串转换成float. * 如果字符串为null, 字符串不是浮点数或浮点数超过取值范围, 则返回指定默认值. * * @param String 字符串 * @param Float 默认值 * @return Float */ public static Float asFloat (String str, Float defaultValue) { try { return new Float(str.trim()); } catch (NullPointerException e) { return defaultValue; } catch (NumberFormatException e) { return defaultValue; } } /** * 字符串转换成float. * 如果字符串为null, 字符串不是浮点数或浮点数超过取值范围, 则返回指定默认值. * * @param String 字符串 * @param float 默认值 * @return float */ public static float asFloat (String str, float defaultValue) { try { return new Float(str.trim()).floatValue(); } catch (NullPointerException e) { return defaultValue; } catch (NumberFormatException e) { return defaultValue; } } /** * 字符串转换成int. * 如果字符串为null, 字符串不是整数或整数超过取值范围, 则返回0. * * @param String 字符串 * @return int */ public static int asInteger (String str) { return asInteger(str, 0); } /** * 字符串转换成int. * 如果字符串为null, 字符串不是整数或整数超过取值范围, 则返回指定默认值. * * @param String 字符串 * @param Integer 默认值 * @return Integer */ public static Integer asInteger (String str, Integer defaultValue) { try { return Integer.decode(str.trim()); } catch (NullPointerException e) { return defaultValue; } catch (NumberFormatException e) { return defaultValue; } } /** * 字符串转换成int. * 如果字符串为null, 字符串不是整数或整数超过取值范围, 则返回指定默认值. * * @param String 字符串 * @param int 默认值 * @return int */ public static int asInteger (String str, int defaultValue) { try { return Integer.decode(str.trim()).intValue(); } catch (NullPointerException e) { return defaultValue; } catch (NumberFormatException e) { return defaultValue; } } /** * 字符串转换成long. * 如果字符串为null, 字符串不是整数或整数超过取值范围, 则返回0. * * @param String 字符串 * @return long */ public static long asLong (String str) { return asLong(str, 0L); } /** * 字符串转换成long. * 如果字符串为null, 字符串不是整数或整数超过取值范围, 则返回指定默认值. * * @param String 字符串 * @param Long 默认值 * @return Long */ public static Long asLong (String str, Long defaultValue) { try { return Long.decode(str.trim()); } catch (NullPointerException e) { return defaultValue; } catch (NumberFormatException e) { return defaultValue; } } /** * 字符串转换成long. * 如果字符串为null, 字符串不是整数或整数超过取值范围, 则返回指定默认值. * * @param String 字符串 * @param long 默认值 * @return long */ public static long asLong (String str, long defaultValue) { try { return Long.decode(str.trim()).longValue(); } catch (NullPointerException e) { return defaultValue; } catch (NumberFormatException e) { return defaultValue; } } /** * 字符串转换成short. * 如果字符串为null, 字符串不是整数或整数超过取值范围, 则返回0. * * @param String 字符串 * @return short */ public static short asShort (String str) { return asShort(str, (short)0); } /** * 字符串转换成short. * 如果字符串为null, 字符串不是整数或整数超过取值范围, 则返回指定默认值. * * @param String 字符串 * @param Short 默认值 * @return Short */ public static Short asShort (String str, Short defaultValue) { try { return Short.decode(str.trim()); } catch (NullPointerException e) { return defaultValue; } catch (NumberFormatException e) { return defaultValue; } } /** * 字符串转换成short. * 如果字符串为null, 字符串不是整数或整数超过取值范围, 则返回指定默认值. * * @param String 字符串 * @param short 默认值 * @return short */ public static short asShort (String str, short defaultValue) { try { return Short.decode(str.trim()).shortValue(); } catch (NullPointerException e) { return defaultValue; } catch (NumberFormatException e) { return defaultValue; } } /** * 返回一个字符串. 该字符串去除了原字符串两端的空白. * 如果原字符串是null, 则返回默认值: 空字符串. * * @param String 原字符串 * @return String */ public static String asString (String str) { return asString(str, "", ""); } /** * 返回一个字符串. 该字符串去除了原字符串两端的空白. * 如果原字符串是null或空字符串, 则返回指定默认值. * * @param String 原字符串 * @param String 默认值 * @return String */ public static String asString (String str, String defaultValue) { return asString(str, defaultValue, defaultValue); } /** * 返回一个字符串. * 如果原字符串是null, 则返回指定默认值. * 如果原字符串支去除多余空白后是空串,则返回指定值. * * @param String 原字符串 * @param String 默认字符串 (原字符串为null时) * @param String 默认字符串 (原字符串为""时) * @return String */ public static String asString (String str, String defaultValue, String emptyStringValue) { try { return str.equals("") ? emptyStringValue : str; } catch (NullPointerException e) { return defaultValue; } } // 默认的日期格式 private static String DEFAULT_DATE_PATTTERN = "yyyy-M-d"; /** * 将字符串转换成日期类型. 转换使用默认模板. * 如果转换失败或字符串为null, 则返回当前日期. * * @param String 要转换的字符串 * @return Date 日期型对象 */ public static Date asDate (String str) { return asDate(str, new Date(), null); } /** * 将字符串转换成日期类型. 转换使用默认的模板. * 如果转换失败或字符串为null, 则返回指定默认值. * * @param String 要转换的字符串 * @param Date 默认值 * @return Date 日期型对象 */ public static Date asDate (String str, Date defaultValue) { return asDate(str, defaultValue, null); } /** * 将字符串转换成日期类型. * 如果转换失败或字符串为null, 则返回指定默认值. * * @param String 要转换的字符串 * @param Date 默认值 * @param String 日期格式模板 * @return Date 日期型对象 */ public static Date asDate (String str, Date defaultValue, String pattern) { DateFormat formatter = new SimpleDateFormat(pattern == null ? DEFAULT_DATE_PATTTERN : pattern); try { return formatter.parse(str); } catch (ParseException e) { return defaultValue; } catch (NullPointerException e) { return defaultValue; } } /** * 将字符串转换成指定类型. * 如果类型不支持, 则返回null. * 如果转换失败或字符串为null, 则返回默认值. * * @param Class 指定类型 * @param String 字符串 * @return Object 指定类型的对象 */ public static Object asType (Class type, String str) { if (type.isAssignableFrom(String.class)) { return asString(str, "", ""); } else if (type.isAssignableFrom(Integer.class) || type.equals(Integer.TYPE)) { return asInteger(str, new Integer(0)); } else if (type.isAssignableFrom(Double.class) || type.equals(Double.TYPE)) { return asDouble(str, new Double(0.0)); } else if (type.isAssignableFrom(Boolean.class) || type.equals(Boolean.TYPE)) { return asBoolean(str, Boolean.FALSE); } else if (type.isAssignableFrom(Float.class) || type.equals(Float.TYPE)) { return asFloat(str, new Float(0.0F)); } else if (type.isAssignableFrom(Long.class) || type.equals(Long.TYPE)) { return asLong(str, new Long(0L)); } else if (type.isAssignableFrom(Short.class) || type.equals(Short.TYPE)) { return asShort(str, new Short((short)0)); } else if (type.isAssignableFrom(Byte.class) || type.equals(Byte.TYPE)) { return asByte(str, new Byte((byte)0)); } else if (type.isAssignableFrom(Character.class) || type.equals(Character.TYPE)) { return asCharacter(str, new Character((char)0)); } else if (type.isAssignableFrom(BigDecimal.class)) { return asBigDecimal(str, new BigDecimal(BigInteger.ZERO)); } else if (type.isAssignableFrom(BigInteger.class)) { return asBigInteger(str, BigInteger.ZERO); } else if (type.isAssignableFrom(Date.class)) { return asDate(str, new Date(), null); } else { return null; } } /** * 将字符串转换成指定类型. * 如果转换失败或字符串为null, 则返回指定默认值. * 如果类型不支持, 则返回null. * 如果默认值和指定的类型不匹配, 则发生ClassCastException. * * @param Class 指定类型 * @param String 字符串 * @param Object 默认值 * @return Object 指定类型的对象 * @exception NullPointerException 当type为null时 * @exception ClassCastException 当默认值不是指定的类型时. */ public static Object asType (Class type, String str, Object defaultValue) { if (type.isAssignableFrom(String.class)) { return asString(str, (String)defaultValue); } else if (type.isAssignableFrom(Integer.class) || type.equals(Integer.TYPE)) { return asInteger(str, (Integer)defaultValue); } else if (type.isAssignableFrom(Double.class) || type.equals(Double.TYPE)) { return asDouble(str, (Double)defaultValue); } else if (type.isAssignableFrom(Boolean.class) || type.equals(Boolean.TYPE)) { return asBoolean(str, (Boolean)defaultValue); } else if (type.isAssignableFrom(Float.class) || type.equals(Float.TYPE)) { return asFloat(str, (Float)defaultValue); } else if (type.isAssignableFrom(Long.class) || type.equals(Long.TYPE)) { return asLong(str, (Long)defaultValue); } else if (type.isAssignableFrom(Short.class) || type.equals(Short.TYPE)) { return asShort(str, (Short)defaultValue); } else if (type.isAssignableFrom(Byte.class) || type.equals(Byte.TYPE)) { return asByte(str, (Byte)defaultValue); } else if (type.isAssignableFrom(Character.class) || type.equals(Character.TYPE)) { return asCharacter(str, (Character)defaultValue); } else if (type.isAssignableFrom(BigDecimal.class)) { return asBigDecimal(str, (BigDecimal)defaultValue); } else if (type.isAssignableFrom(BigInteger.class)) { return asBigInteger(str, (BigInteger)defaultValue); } else if (type.isAssignableFrom(Date.class)) { return asDate(str, (Date)defaultValue); } else { return null; } } /** * 将对象看作字符串, 并转换成指定类型. * 如果对象就是希望返回的类型, 直接返回. * 如果对象是字符串, 则结果同asType(String.class, String, Object). * 否则执行对象的toString()方法, 然后对这个字符串值调用asType(String.class, String, Object). * 如果转换失败或字符串为null, 则返回默认值. * * @param Class 指定类型 * @param Object 要转换的对象 * @return Object 指定类型的对象 * @exception NullPointerException 当type为null时 */ public static Object asType (Class type, Object obj) { if (!type.equals(String.class) && type.isInstance(obj)) { return obj; } else if (obj == null || obj instanceof String) { return Strings.asType(type, (String)obj); } else if (obj instanceof Date && String.class.isAssignableFrom(type)) { return new SimpleDateFormat(DEFAULT_DATE_PATTTERN).format((Date)obj); } else if (obj instanceof Number && Number.class.isAssignableFrom(type)) { Number num = (Number)obj; if (type.isAssignableFrom(Number.class)) { return num; } else if (type.isAssignableFrom(Integer.class)) { return new Integer(num.intValue()); } else if (type.isAssignableFrom(Double.class)) { return new Double(num.doubleValue()); } else if (type.isAssignableFrom(Float.class)) { return new Float(num.floatValue()); } else if (type.isAssignableFrom(Long.class)) { return new Long(num.longValue()); } else if (type.isAssignableFrom(Short.class)) { return new Short(num.shortValue()); } else if (type.isAssignableFrom(Byte.class)) { return new Byte(num.byteValue()); } else if (type.isAssignableFrom(BigInteger.class)) { return new BigDecimal(num.toString()).toBigInteger(); } else if (type.isAssignableFrom(BigDecimal.class)) { return new BigDecimal(num.toString()); } } return Strings.asType(type, obj.toString()); } /** * 将对象看作字符串, 并转换成指定类型. * 如果对象就是希望返回的类型, 直接返回. * 如果对象是字符串, 则结果同asType(String.class, String, Object). * 否则执行对象的toString()方法, 然后对这个字符串值调用asType(String.class, String, Object). * 如果转换失败或字符串为null, 则返回指定默认值. * 如果默认值和指定的类型不匹配, 则发生ClassCastException. * * @param Class 指定类型 * @param Object 要转换的对象 * @param Object 默认值 * @return Object 指定类型的对象 * @exception NullPointerException 当type为null时 * @exception ClassCastException 当默认值不是指定的类型时. */ public static Object asType (Class type, Object obj, Object defaultValue) { if (!type.equals(String.class) && type.isInstance(obj)) { return obj; } else if (obj == null || obj instanceof String) { return Strings.asType(type, (String)obj, defaultValue); } else if (obj instanceof Date && String.class.isAssignableFrom(type)) { return new SimpleDateFormat(DEFAULT_DATE_PATTTERN).format((Date)obj); } else if (obj instanceof Number && Number.class.isAssignableFrom(type)) { Number num = (Number)obj; if (type.isAssignableFrom(Number.class)) { return num; } else if (type.isAssignableFrom(Integer.class)) { return new Integer(num.intValue()); } else if (type.isAssignableFrom(Double.class)) { return new Double(num.doubleValue()); } else if (type.isAssignableFrom(Float.class)) { return new Float(num.floatValue()); } else if (type.isAssignableFrom(Long.class)) { return new Long(num.longValue()); } else if (type.isAssignableFrom(Short.class)) { return new Short(num.shortValue()); } else if (type.isAssignableFrom(Byte.class)) { return new Byte(num.byteValue()); } else if (type.isAssignableFrom(BigInteger.class)) { return new BigDecimal(num.toString()).toBigInteger(); } else if (type.isAssignableFrom(BigDecimal.class)) { return new BigDecimal(num.toString()); } } return Strings.asType(type, obj.toString(), defaultValue); } /** * 将类名全称改为单独类名. * * @param Class 类对象, 从中得到类名 * @return String 单独类名(无package部分) */ public static String getClassName (Class cls) { return getClassName(cls.getName()); } /** * 将类名全称改为单独类名. * * @param String 类名全称 * @return String 单独类名(无package部分) */ public static String getClassName (String fullName) { if (fullName == null) { return null; } else { fullName = fullName.trim(); } String className = fullName.substring(fullName.lastIndexOf('.') + 1).replace('$', '.').trim(); return className.equals("") ? null : className; } }
UTF-8
Java
31,424
java
Strings.java
Java
[ { "context": "提供了从字符串到各种数据结构的转换\n * \n * @author <a href=\"mailto:rainmanzhu@yahoo.com\">Rainman Zhu</a>\n * @version $Id: Strings.java,v ", "end": 682, "score": 0.9999261498451233, "start": 662, "tag": "EMAIL", "value": "rainmanzhu@yahoo.com" }, { "context": "\n * @author <a href=\"mailto:rainmanzhu@yahoo.com\">Rainman Zhu</a>\n * @version $Id: Strings.java,v 1.1.1.1 2005/", "end": 695, "score": 0.9998459219932556, "start": 684, "tag": "NAME", "value": "Rainman Zhu" } ]
null
[]
/* * ---------------------------------------------------------------------------------------------------------- * $Id: Strings.java,v 1.1.1.1 2005/07/24 04:18:37 hugo Exp $ * $Source: H:/cvsroot/./dxycms/webapps/WEB-INF/src/java/org/jute/util/Strings.java,v $ * ---------------------------------------------------------------------------------------------------------- */ package org.jute.util; import java.util.Date; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.text.ParseException; import java.math.BigInteger; import java.math.BigDecimal; /** * 字符处理扩展. * 提供了从字符串到各种数据结构的转换 * * @author <a href="mailto:<EMAIL>"><NAME></a> * @version $Id: Strings.java,v 1.1.1.1 2005/07/24 04:18:37 hugo Exp $ */ public class Strings { // public static String normalizeString(String str) { // if (str == null || str.length() <= 0) { // return str; // } // // StringBuffer buffer = new StringBuffer(str.length()); // boolean skipNextLF = false; // for (int i = 0; i < str.length(); i++) { // char c = str.charAt(i); // switch (c) { // case '\r': // buffer.append('\n'); // skipNextLF = true; // break; // // case '\n': // if (skipNextLF) { // skipNextLF = false; // break; // } // // default: // skipNextLF = false; // buffer.append(c); // } // } // // return buffer.toString(); // } // // public static String escapeString(String str) { // if (str == null || str.length() <= 0) { // return str; // } // // StringBuffer buffer = new StringBuffer(str.length()); // for (int i = 0; i < str.length(); i++) { // char c = str.charAt(i); // switch (c) { // case 0 : // break; // case '\b': // buffer.append("\\b"); // break; // case '\t': // buffer.append("\\t"); // break; // case '\n': // buffer.append("\\n"); // break; // case '\f': // buffer.append("\\f"); // break; // case '\r': // buffer.append("\\r"); // break; // case '\"': // buffer.append("\\\""); // break; // case '\'': // buffer.append("\\\'"); // break; // case '\\': // buffer.append("\\\\"); // break; // default: // buffer.append(c); // } // } // return buffer.toString(); // } /********************************************************************* * 将字符串转换成其它类型 * * 此处类型囊括了所有java的基本类型和BigDecimal, BigInteger类 * * *********************************************************************/ /** * 字符串转换成BigDecimal. * 如果字符串为null, 字符串不是数字, 则返回0. * * @param String 字符串 * @return BigDecimal */ public static BigDecimal asBigDecimal (String str) { return asBigDecimal(str, new BigDecimal(BigInteger.ZERO)); } /** * 字符串转换成BigDecimal. * 如果字符串为null, 字符串不是数字, 则返回指定默认值. * * @param String 字符串 * @param BigDecimal 默认值 * @return BigDecimal */ public static BigDecimal asBigDecimal (String str, BigDecimal defaultValue) { try { return new BigDecimal(str.trim()); } catch (NullPointerException e) { return defaultValue; } catch (NumberFormatException e) { return defaultValue; } catch (RuntimeException e) { // 好象是JDK的Bug, 当字符串为空串时会出现RuntimeException // 出现这种情况, 就返回默认值. return defaultValue; } } /** * 字符串转换成BigInteger. * 如果字符串为null, 字符串不是整数, 则返回0. * * @param String 字符串 * @return BigInteger */ public static BigInteger asBigInteger (String str) { return asBigInteger(str, BigInteger.ZERO); } /** * 字符串转换成BigInteger. * 如果字符串为null, 字符串不是整数, 则返回指定默认值. * * @param String 字符串 * @param BigInteger 默认值 * @return BigInteger */ public static BigInteger asBigInteger (String str, BigInteger defaultValue) { try { return new BigInteger(str.trim()); } catch (NullPointerException e) { return defaultValue; } catch (NumberFormatException e) { return defaultValue; } } // 被看作false的字符串 private static String[] FALSE_STRINGS = { "false", "null", "nul", "off", "no", "n" }; /** * 字符串转换成boolean. 转换规则如下: * 如果字符串看起来像一个整数, 且整数值等于0, 则为false, 否则true; * 如果字符串为空串或null, 则返回默认值false; * 如果字符串为下列值之一(大小写不敏感): * "false", "null", "nul", "off", "no", "n" * 则为false, 否则为true. * * @param String 字符串 * @return boolean */ public static boolean asBoolean (String str) { return asBoolean(str, false); } /** * 字符串转换成boolean. 转换规则如下: * 如果字符串看起来像一个整数, 且整数值等于0, 则为false, 否则true; * 如果字符串为空串或null, 则返回指定默认值; * 如果字符串为下列值之一(大小写不敏感): * "false", "null", "nul", "off", "no", "n" * 则为false, 否则为true. * * @param String 字符串 * @param Boolean 默认值 * @return Boolean */ public static Boolean asBoolean (String str, Boolean defaultValue) { try { str = str.trim(); return Integer.decode(str).intValue() != 0 ? Boolean.TRUE : Boolean.FALSE; } catch (NullPointerException e) { return defaultValue; } catch (NumberFormatException e) { if (str.equals("")) { return defaultValue; } for (int i = 0; i < FALSE_STRINGS.length; i++) { if (str.equalsIgnoreCase(FALSE_STRINGS[i])) { return Boolean.FALSE; } } return Boolean.TRUE; } } /** * 字符串转换成boolean. 转换规则如下: * 如果字符串看起来像一个整数, 且整数值等于0, 则为false, 否则true; * 如果字符串为空串或null, 则返回指定默认值; * 如果字符串为下列值之一(大小写不敏感): * "false", "null", "nul", "off", "no", "n" * 则为false, 否则为true. * * @param String 字符串 * @param boolean 默认值 * @return boolean */ public static boolean asBoolean (String str, boolean defaultValue) { try { str = str.trim(); return Integer.decode(str).intValue() != 0; } catch (NullPointerException e) { return defaultValue; } catch (NumberFormatException e) { if (str.equals("")) { return defaultValue; } for (int i = 0; i < FALSE_STRINGS.length; i++) { if (str.equalsIgnoreCase(FALSE_STRINGS[i])) { return false; } } return true; } } /** * 字符串转换成byte. * 如果字符串为null, 字符串不是整数或整数超过取值范围, 则返回0 * * @param String 字符串 * @return byte */ public static byte asByte (String str) { return asByte(str, (byte)0); } /** * 字符串转换成byte. * 如果字符串为null, 字符串不是整数或整数超过取值范围, 则返回指定默认值. * * @param String 字符串 * @param Byte 默认值 * @return Byte */ public static Byte asByte (String str, Byte defaultValue) { try { return Byte.decode(str.trim()); } catch (NullPointerException e) { return defaultValue; } catch (NumberFormatException e) { return defaultValue; } } /** * 字符串转换成byte. * 如果字符串为null, 字符串不是整数或整数超过取值范围, 则返回指定默认值. * * @param String 字符串 * @param byte 默认值 * @return byte */ public static byte asByte (String str, byte defaultValue) { try { return Byte.decode(str.trim()).byteValue(); } catch (NullPointerException e) { return defaultValue; } catch (NumberFormatException e) { return defaultValue; } } /** * 字符串转换成char. * 如果字符串为null, 则返回'\0' * * @param String 字符串 * @return char */ public static char asCharacter (String str) { return asCharacter(str, (char)0); } /** * 字符串转换成char. * 如果字符串为null, 则返回指定默认值. * * @param String 字符串 * @param Character 默认值 * @return Character */ public static Character asCharacter (String str, Character defaultValue) { try { return new Character(str.trim().charAt(0)); } catch (NullPointerException e) { return defaultValue; } catch (IndexOutOfBoundsException e) { return defaultValue; } } /** * 字符串转换成char. * 如果字符串为null, 则返回指定默认值. * * @param String 字符串 * @param char 默认值 * @return char */ public static char asCharacter (String str, char defaultValue) { try { return str.trim().charAt(0); } catch (NullPointerException e) { return defaultValue; } catch (IndexOutOfBoundsException e) { return defaultValue; } } /** * 字符串转换成double. * 如果字符串为null, 字符串不是浮点数或浮点数超过取值范围, 则返回0. * * @param String 字符串 * @return double */ public static double asDouble (String str) { return asDouble(str, 0.0); } /** * 字符串转换成double. * 如果字符串为null, 字符串不是浮点数或浮点数超过取值范围, 则返回指定默认值. * * @param String 字符串 * @param Double 默认值 * @return Double */ public static Double asDouble (String str, Double defaultValue) { try { return new Double(str.trim()); } catch (NullPointerException e) { return defaultValue; } catch (NumberFormatException e) { return defaultValue; } } /** * 字符串转换成double. * 如果字符串为null, 字符串不是浮点数或浮点数超过取值范围, 则返回指定默认值. * * @param String 字符串 * @param double 默认值 * @return double */ public static double asDouble (String str, double defaultValue) { try { return new Double(str.trim()).doubleValue(); } catch (NullPointerException e) { return defaultValue; } catch (NumberFormatException e) { return defaultValue; } } /** * 字符串转换成float. * 如果字符串为null, 字符串不是浮点数或浮点数超过取值范围, 则返回0. * * @param String 字符串 * @return float */ public static float asFloat (String str) { return asFloat(str, 0.0F); } /** * 字符串转换成float. * 如果字符串为null, 字符串不是浮点数或浮点数超过取值范围, 则返回指定默认值. * * @param String 字符串 * @param Float 默认值 * @return Float */ public static Float asFloat (String str, Float defaultValue) { try { return new Float(str.trim()); } catch (NullPointerException e) { return defaultValue; } catch (NumberFormatException e) { return defaultValue; } } /** * 字符串转换成float. * 如果字符串为null, 字符串不是浮点数或浮点数超过取值范围, 则返回指定默认值. * * @param String 字符串 * @param float 默认值 * @return float */ public static float asFloat (String str, float defaultValue) { try { return new Float(str.trim()).floatValue(); } catch (NullPointerException e) { return defaultValue; } catch (NumberFormatException e) { return defaultValue; } } /** * 字符串转换成int. * 如果字符串为null, 字符串不是整数或整数超过取值范围, 则返回0. * * @param String 字符串 * @return int */ public static int asInteger (String str) { return asInteger(str, 0); } /** * 字符串转换成int. * 如果字符串为null, 字符串不是整数或整数超过取值范围, 则返回指定默认值. * * @param String 字符串 * @param Integer 默认值 * @return Integer */ public static Integer asInteger (String str, Integer defaultValue) { try { return Integer.decode(str.trim()); } catch (NullPointerException e) { return defaultValue; } catch (NumberFormatException e) { return defaultValue; } } /** * 字符串转换成int. * 如果字符串为null, 字符串不是整数或整数超过取值范围, 则返回指定默认值. * * @param String 字符串 * @param int 默认值 * @return int */ public static int asInteger (String str, int defaultValue) { try { return Integer.decode(str.trim()).intValue(); } catch (NullPointerException e) { return defaultValue; } catch (NumberFormatException e) { return defaultValue; } } /** * 字符串转换成long. * 如果字符串为null, 字符串不是整数或整数超过取值范围, 则返回0. * * @param String 字符串 * @return long */ public static long asLong (String str) { return asLong(str, 0L); } /** * 字符串转换成long. * 如果字符串为null, 字符串不是整数或整数超过取值范围, 则返回指定默认值. * * @param String 字符串 * @param Long 默认值 * @return Long */ public static Long asLong (String str, Long defaultValue) { try { return Long.decode(str.trim()); } catch (NullPointerException e) { return defaultValue; } catch (NumberFormatException e) { return defaultValue; } } /** * 字符串转换成long. * 如果字符串为null, 字符串不是整数或整数超过取值范围, 则返回指定默认值. * * @param String 字符串 * @param long 默认值 * @return long */ public static long asLong (String str, long defaultValue) { try { return Long.decode(str.trim()).longValue(); } catch (NullPointerException e) { return defaultValue; } catch (NumberFormatException e) { return defaultValue; } } /** * 字符串转换成short. * 如果字符串为null, 字符串不是整数或整数超过取值范围, 则返回0. * * @param String 字符串 * @return short */ public static short asShort (String str) { return asShort(str, (short)0); } /** * 字符串转换成short. * 如果字符串为null, 字符串不是整数或整数超过取值范围, 则返回指定默认值. * * @param String 字符串 * @param Short 默认值 * @return Short */ public static Short asShort (String str, Short defaultValue) { try { return Short.decode(str.trim()); } catch (NullPointerException e) { return defaultValue; } catch (NumberFormatException e) { return defaultValue; } } /** * 字符串转换成short. * 如果字符串为null, 字符串不是整数或整数超过取值范围, 则返回指定默认值. * * @param String 字符串 * @param short 默认值 * @return short */ public static short asShort (String str, short defaultValue) { try { return Short.decode(str.trim()).shortValue(); } catch (NullPointerException e) { return defaultValue; } catch (NumberFormatException e) { return defaultValue; } } /** * 返回一个字符串. 该字符串去除了原字符串两端的空白. * 如果原字符串是null, 则返回默认值: 空字符串. * * @param String 原字符串 * @return String */ public static String asString (String str) { return asString(str, "", ""); } /** * 返回一个字符串. 该字符串去除了原字符串两端的空白. * 如果原字符串是null或空字符串, 则返回指定默认值. * * @param String 原字符串 * @param String 默认值 * @return String */ public static String asString (String str, String defaultValue) { return asString(str, defaultValue, defaultValue); } /** * 返回一个字符串. * 如果原字符串是null, 则返回指定默认值. * 如果原字符串支去除多余空白后是空串,则返回指定值. * * @param String 原字符串 * @param String 默认字符串 (原字符串为null时) * @param String 默认字符串 (原字符串为""时) * @return String */ public static String asString (String str, String defaultValue, String emptyStringValue) { try { return str.equals("") ? emptyStringValue : str; } catch (NullPointerException e) { return defaultValue; } } // 默认的日期格式 private static String DEFAULT_DATE_PATTTERN = "yyyy-M-d"; /** * 将字符串转换成日期类型. 转换使用默认模板. * 如果转换失败或字符串为null, 则返回当前日期. * * @param String 要转换的字符串 * @return Date 日期型对象 */ public static Date asDate (String str) { return asDate(str, new Date(), null); } /** * 将字符串转换成日期类型. 转换使用默认的模板. * 如果转换失败或字符串为null, 则返回指定默认值. * * @param String 要转换的字符串 * @param Date 默认值 * @return Date 日期型对象 */ public static Date asDate (String str, Date defaultValue) { return asDate(str, defaultValue, null); } /** * 将字符串转换成日期类型. * 如果转换失败或字符串为null, 则返回指定默认值. * * @param String 要转换的字符串 * @param Date 默认值 * @param String 日期格式模板 * @return Date 日期型对象 */ public static Date asDate (String str, Date defaultValue, String pattern) { DateFormat formatter = new SimpleDateFormat(pattern == null ? DEFAULT_DATE_PATTTERN : pattern); try { return formatter.parse(str); } catch (ParseException e) { return defaultValue; } catch (NullPointerException e) { return defaultValue; } } /** * 将字符串转换成指定类型. * 如果类型不支持, 则返回null. * 如果转换失败或字符串为null, 则返回默认值. * * @param Class 指定类型 * @param String 字符串 * @return Object 指定类型的对象 */ public static Object asType (Class type, String str) { if (type.isAssignableFrom(String.class)) { return asString(str, "", ""); } else if (type.isAssignableFrom(Integer.class) || type.equals(Integer.TYPE)) { return asInteger(str, new Integer(0)); } else if (type.isAssignableFrom(Double.class) || type.equals(Double.TYPE)) { return asDouble(str, new Double(0.0)); } else if (type.isAssignableFrom(Boolean.class) || type.equals(Boolean.TYPE)) { return asBoolean(str, Boolean.FALSE); } else if (type.isAssignableFrom(Float.class) || type.equals(Float.TYPE)) { return asFloat(str, new Float(0.0F)); } else if (type.isAssignableFrom(Long.class) || type.equals(Long.TYPE)) { return asLong(str, new Long(0L)); } else if (type.isAssignableFrom(Short.class) || type.equals(Short.TYPE)) { return asShort(str, new Short((short)0)); } else if (type.isAssignableFrom(Byte.class) || type.equals(Byte.TYPE)) { return asByte(str, new Byte((byte)0)); } else if (type.isAssignableFrom(Character.class) || type.equals(Character.TYPE)) { return asCharacter(str, new Character((char)0)); } else if (type.isAssignableFrom(BigDecimal.class)) { return asBigDecimal(str, new BigDecimal(BigInteger.ZERO)); } else if (type.isAssignableFrom(BigInteger.class)) { return asBigInteger(str, BigInteger.ZERO); } else if (type.isAssignableFrom(Date.class)) { return asDate(str, new Date(), null); } else { return null; } } /** * 将字符串转换成指定类型. * 如果转换失败或字符串为null, 则返回指定默认值. * 如果类型不支持, 则返回null. * 如果默认值和指定的类型不匹配, 则发生ClassCastException. * * @param Class 指定类型 * @param String 字符串 * @param Object 默认值 * @return Object 指定类型的对象 * @exception NullPointerException 当type为null时 * @exception ClassCastException 当默认值不是指定的类型时. */ public static Object asType (Class type, String str, Object defaultValue) { if (type.isAssignableFrom(String.class)) { return asString(str, (String)defaultValue); } else if (type.isAssignableFrom(Integer.class) || type.equals(Integer.TYPE)) { return asInteger(str, (Integer)defaultValue); } else if (type.isAssignableFrom(Double.class) || type.equals(Double.TYPE)) { return asDouble(str, (Double)defaultValue); } else if (type.isAssignableFrom(Boolean.class) || type.equals(Boolean.TYPE)) { return asBoolean(str, (Boolean)defaultValue); } else if (type.isAssignableFrom(Float.class) || type.equals(Float.TYPE)) { return asFloat(str, (Float)defaultValue); } else if (type.isAssignableFrom(Long.class) || type.equals(Long.TYPE)) { return asLong(str, (Long)defaultValue); } else if (type.isAssignableFrom(Short.class) || type.equals(Short.TYPE)) { return asShort(str, (Short)defaultValue); } else if (type.isAssignableFrom(Byte.class) || type.equals(Byte.TYPE)) { return asByte(str, (Byte)defaultValue); } else if (type.isAssignableFrom(Character.class) || type.equals(Character.TYPE)) { return asCharacter(str, (Character)defaultValue); } else if (type.isAssignableFrom(BigDecimal.class)) { return asBigDecimal(str, (BigDecimal)defaultValue); } else if (type.isAssignableFrom(BigInteger.class)) { return asBigInteger(str, (BigInteger)defaultValue); } else if (type.isAssignableFrom(Date.class)) { return asDate(str, (Date)defaultValue); } else { return null; } } /** * 将对象看作字符串, 并转换成指定类型. * 如果对象就是希望返回的类型, 直接返回. * 如果对象是字符串, 则结果同asType(String.class, String, Object). * 否则执行对象的toString()方法, 然后对这个字符串值调用asType(String.class, String, Object). * 如果转换失败或字符串为null, 则返回默认值. * * @param Class 指定类型 * @param Object 要转换的对象 * @return Object 指定类型的对象 * @exception NullPointerException 当type为null时 */ public static Object asType (Class type, Object obj) { if (!type.equals(String.class) && type.isInstance(obj)) { return obj; } else if (obj == null || obj instanceof String) { return Strings.asType(type, (String)obj); } else if (obj instanceof Date && String.class.isAssignableFrom(type)) { return new SimpleDateFormat(DEFAULT_DATE_PATTTERN).format((Date)obj); } else if (obj instanceof Number && Number.class.isAssignableFrom(type)) { Number num = (Number)obj; if (type.isAssignableFrom(Number.class)) { return num; } else if (type.isAssignableFrom(Integer.class)) { return new Integer(num.intValue()); } else if (type.isAssignableFrom(Double.class)) { return new Double(num.doubleValue()); } else if (type.isAssignableFrom(Float.class)) { return new Float(num.floatValue()); } else if (type.isAssignableFrom(Long.class)) { return new Long(num.longValue()); } else if (type.isAssignableFrom(Short.class)) { return new Short(num.shortValue()); } else if (type.isAssignableFrom(Byte.class)) { return new Byte(num.byteValue()); } else if (type.isAssignableFrom(BigInteger.class)) { return new BigDecimal(num.toString()).toBigInteger(); } else if (type.isAssignableFrom(BigDecimal.class)) { return new BigDecimal(num.toString()); } } return Strings.asType(type, obj.toString()); } /** * 将对象看作字符串, 并转换成指定类型. * 如果对象就是希望返回的类型, 直接返回. * 如果对象是字符串, 则结果同asType(String.class, String, Object). * 否则执行对象的toString()方法, 然后对这个字符串值调用asType(String.class, String, Object). * 如果转换失败或字符串为null, 则返回指定默认值. * 如果默认值和指定的类型不匹配, 则发生ClassCastException. * * @param Class 指定类型 * @param Object 要转换的对象 * @param Object 默认值 * @return Object 指定类型的对象 * @exception NullPointerException 当type为null时 * @exception ClassCastException 当默认值不是指定的类型时. */ public static Object asType (Class type, Object obj, Object defaultValue) { if (!type.equals(String.class) && type.isInstance(obj)) { return obj; } else if (obj == null || obj instanceof String) { return Strings.asType(type, (String)obj, defaultValue); } else if (obj instanceof Date && String.class.isAssignableFrom(type)) { return new SimpleDateFormat(DEFAULT_DATE_PATTTERN).format((Date)obj); } else if (obj instanceof Number && Number.class.isAssignableFrom(type)) { Number num = (Number)obj; if (type.isAssignableFrom(Number.class)) { return num; } else if (type.isAssignableFrom(Integer.class)) { return new Integer(num.intValue()); } else if (type.isAssignableFrom(Double.class)) { return new Double(num.doubleValue()); } else if (type.isAssignableFrom(Float.class)) { return new Float(num.floatValue()); } else if (type.isAssignableFrom(Long.class)) { return new Long(num.longValue()); } else if (type.isAssignableFrom(Short.class)) { return new Short(num.shortValue()); } else if (type.isAssignableFrom(Byte.class)) { return new Byte(num.byteValue()); } else if (type.isAssignableFrom(BigInteger.class)) { return new BigDecimal(num.toString()).toBigInteger(); } else if (type.isAssignableFrom(BigDecimal.class)) { return new BigDecimal(num.toString()); } } return Strings.asType(type, obj.toString(), defaultValue); } /** * 将类名全称改为单独类名. * * @param Class 类对象, 从中得到类名 * @return String 单独类名(无package部分) */ public static String getClassName (Class cls) { return getClassName(cls.getName()); } /** * 将类名全称改为单独类名. * * @param String 类名全称 * @return String 单独类名(无package部分) */ public static String getClassName (String fullName) { if (fullName == null) { return null; } else { fullName = fullName.trim(); } String className = fullName.substring(fullName.lastIndexOf('.') + 1).replace('$', '.').trim(); return className.equals("") ? null : className; } }
31,406
0.517112
0.514272
906
29.312363
22.198299
110
false
false
0
0
0
0
0
0
0.483444
false
false
0
5424f01d0a566f9ac201ef104544ee521cc1dc5b
1,511,828,557,281
b80420aa4182782883cd4c5185281d952b4b270c
/CSCI201L_FinalProject_MessagesServer/src/server/ServerThread.java
872066e732a5f762f82947d0ed4144e9280f89d8
[]
no_license
Luner/CSCI-201-FP
https://github.com/Luner/CSCI-201-FP
c8ede3775eef179edd92763552e9554eb722b1cb
8831374d29c6c5d9fdf726d8f192cd5b058d9dd3
refs/heads/master
2021-08-26T05:31:27.332000
2017-11-21T18:28:38
2017-11-21T18:28:38
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package server; import database.Database; import objects.ClientConversation; import objects.User; import objects.message.*; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.util.ArrayList; import java.util.ConcurrentModificationException; public class ServerThread extends Thread { private ObjectInputStream ois; private ObjectOutputStream oos; private Server cs; private User user; @SuppressWarnings("unused") private String username; int uid; private boolean running = true; @SuppressWarnings("unused") private Database db; public User getUser() { return user; } public ServerThread(Socket s, Server cs, Database db) { // Initialize the Object streams for the socket try { this.cs = cs; this.db = db; oos = new ObjectOutputStream(s.getOutputStream()); ois = new ObjectInputStream(s.getInputStream()); this.start(); } catch (IOException ioe) { System.out.println("ioe: " + ioe.getMessage()); } } private void login() { try { // loops until connected user is verified while (true) { Object message = ois.readObject(); if (message instanceof VerificationMessage) { // if the message is a VerificationMessage, Log the message received Log.recieved((Message) message); // Check the information sent against every user that exists for (User user : cs.getData().getUsers()) { if (user.verify(((VerificationMessage) message).getUsername(), ((VerificationMessage) message).getPassword())) { this.username = user.getUsername(); this.uid = user.getUid(); this.user = user; // Send VerificationResponseMessage VerificationResponseMessage response; // Send a verificationResponseMessage with true and the corresponding User ID response = new VerificationResponseMessage(true, uid); oos.writeObject(response); oos.flush(); // Tell Server User logged on cs.logOn(user, this); Log.sent(response); updateConversation(); updateContacts(); // Log it? return; } } // If the user was not found, send a verificationResponseMessage with false and // a User ID or -1 VerificationResponseMessage response; response = new VerificationResponseMessage(false, -1); try { oos.writeObject(response); oos.flush(); // Log the message that was sent Log.sent(response); } catch (IOException ioe) { System.out.println("ioe: " + ioe.getMessage()); } } else if (message instanceof CreateUserMessage) { String username = ((CreateUserMessage) message).getUsername(); String password = ((CreateUserMessage) message).getPassword(); System.out.println("username: " + username + " password: " + password + " nextId: " + cs.getData().getNextID()); User created = new User(username, password, cs.getData().getNextID()); boolean userCreated = cs.addUser(created, this); VerificationResponseMessage response; if (!userCreated) { response = new VerificationResponseMessage(false, -1); try { oos.writeObject(response); oos.flush(); // Log the message that was sent Log.sent(response); } catch (IOException ioe) { System.out.println("ioe: " + ioe.getMessage()); } } else { response = new VerificationResponseMessage(true, created.getUid()); try { oos.writeObject(response); oos.flush(); // Log the message that was sent Log.sent(response); } catch (IOException ioe) { System.out.println("ioe: " + ioe.getMessage()); } this.username = created.getUsername(); this.uid = created.getUid(); this.user = created; // Tell Server User logged on cs.logOn(user, this); updateConversation(); cs.updateContacts(); return; } } else if (message instanceof LogoutMessage) { running = false; break; } else { // If the Message received was not an instance of Verification Messages System.out.println("Exception: Expecting an instanceof VerificationMessage!"); } } } catch (ClassNotFoundException cnfe) { System.out.println("cnfe in run: " + cnfe.getMessage()); } catch (IOException ioe) { System.out.println("ioe in run: " + ioe.getMessage()); } } public void updateConversation() { try { ArrayList<ClientConversation> list = cs.getUserConversations(user); oos.writeObject(new ConversationsMessage(list)); oos.flush(); } catch (IOException ioe) { System.out.println("ioe: " + ioe.getMessage()); } } public void sendMessage(Message message) { try { oos.writeObject(message); oos.flush(); } catch (IOException ioe) { cs.removeServerThread(this); System.out.println("ioe: " + ioe.getMessage()); running = false; } } public void sendChatStringMessage(ChatMessage message) { // Send out a StringMessage to the user try { ChatStringMessage sMessage = new ChatStringMessage( cs.getData().findUserByUid(message.getUid()).getUsername() + ": " + message.getMessage(), message.getCid()); oos.writeObject(sMessage); oos.flush(); } catch (IOException ioe) { cs.removeServerThread(this); System.out.println("ioe: " + ioe.getMessage()); running = false; } } public void sendStringMessage(String message) { // Send out a StringMessage to the user try { StringMessage sMessage = new StringMessage(message); oos.writeObject(sMessage); oos.flush(); } catch (IOException ioe) { cs.removeServerThread(this); System.out.println("ioe: " + ioe.getMessage()); running = false; } } public void updateContacts() { ArrayList<String> contacts = new ArrayList<>(); ArrayList<User> temp = cs.getData().getUsers(); for (User u : temp) { contacts.add(u.getUsername()); } ContactsMessage cm = new ContactsMessage(contacts); try { oos.writeObject(cm); oos.flush(); } catch (IOException e) { e.printStackTrace(); } } // Handles consistently listening for chatMessages from client public void run() { login(); ArrayList<String> contacts = new ArrayList<>(); ArrayList<User> temp = cs.getData().getUsers(); for (User u : temp) { contacts.add(u.getUsername()); } try { while (running) { Message message = (Message) ois.readObject(); // Log the received Message Log.recieved(message); if (message instanceof ChatMessage) { cs.sendMessageToAllClients(message); } else if (message instanceof CommandMessage) { cs.receiveCommand((CommandMessage) message, this); } else if (message instanceof CreateConversationMessage) { cs.createConversation((CreateConversationMessage) message); } else if (message instanceof LogoutMessage) { break; } } } catch (ClassNotFoundException cnfe) { System.out.println("cnfe in run: " + cnfe.getMessage()); } catch (IOException ioe) { System.out.println("ioe in run: " + ioe.getMessage()); } catch (ConcurrentModificationException cme) { System.out.println("cme in run: " + cme.getMessage()); } cs.removeServerThread(this); } }
UTF-8
Java
7,255
java
ServerThread.java
Java
[ { "context": "println(\"username: \" + username + \" password: \" + password + \" nextId: \"\n\t\t\t\t\t\t\t+ cs.getData().getNextID())", "end": 2864, "score": 0.9922196865081787, "start": 2856, "tag": "PASSWORD", "value": "password" } ]
null
[]
package server; import database.Database; import objects.ClientConversation; import objects.User; import objects.message.*; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.util.ArrayList; import java.util.ConcurrentModificationException; public class ServerThread extends Thread { private ObjectInputStream ois; private ObjectOutputStream oos; private Server cs; private User user; @SuppressWarnings("unused") private String username; int uid; private boolean running = true; @SuppressWarnings("unused") private Database db; public User getUser() { return user; } public ServerThread(Socket s, Server cs, Database db) { // Initialize the Object streams for the socket try { this.cs = cs; this.db = db; oos = new ObjectOutputStream(s.getOutputStream()); ois = new ObjectInputStream(s.getInputStream()); this.start(); } catch (IOException ioe) { System.out.println("ioe: " + ioe.getMessage()); } } private void login() { try { // loops until connected user is verified while (true) { Object message = ois.readObject(); if (message instanceof VerificationMessage) { // if the message is a VerificationMessage, Log the message received Log.recieved((Message) message); // Check the information sent against every user that exists for (User user : cs.getData().getUsers()) { if (user.verify(((VerificationMessage) message).getUsername(), ((VerificationMessage) message).getPassword())) { this.username = user.getUsername(); this.uid = user.getUid(); this.user = user; // Send VerificationResponseMessage VerificationResponseMessage response; // Send a verificationResponseMessage with true and the corresponding User ID response = new VerificationResponseMessage(true, uid); oos.writeObject(response); oos.flush(); // Tell Server User logged on cs.logOn(user, this); Log.sent(response); updateConversation(); updateContacts(); // Log it? return; } } // If the user was not found, send a verificationResponseMessage with false and // a User ID or -1 VerificationResponseMessage response; response = new VerificationResponseMessage(false, -1); try { oos.writeObject(response); oos.flush(); // Log the message that was sent Log.sent(response); } catch (IOException ioe) { System.out.println("ioe: " + ioe.getMessage()); } } else if (message instanceof CreateUserMessage) { String username = ((CreateUserMessage) message).getUsername(); String password = ((CreateUserMessage) message).getPassword(); System.out.println("username: " + username + " password: " + <PASSWORD> + " nextId: " + cs.getData().getNextID()); User created = new User(username, password, cs.getData().getNextID()); boolean userCreated = cs.addUser(created, this); VerificationResponseMessage response; if (!userCreated) { response = new VerificationResponseMessage(false, -1); try { oos.writeObject(response); oos.flush(); // Log the message that was sent Log.sent(response); } catch (IOException ioe) { System.out.println("ioe: " + ioe.getMessage()); } } else { response = new VerificationResponseMessage(true, created.getUid()); try { oos.writeObject(response); oos.flush(); // Log the message that was sent Log.sent(response); } catch (IOException ioe) { System.out.println("ioe: " + ioe.getMessage()); } this.username = created.getUsername(); this.uid = created.getUid(); this.user = created; // Tell Server User logged on cs.logOn(user, this); updateConversation(); cs.updateContacts(); return; } } else if (message instanceof LogoutMessage) { running = false; break; } else { // If the Message received was not an instance of Verification Messages System.out.println("Exception: Expecting an instanceof VerificationMessage!"); } } } catch (ClassNotFoundException cnfe) { System.out.println("cnfe in run: " + cnfe.getMessage()); } catch (IOException ioe) { System.out.println("ioe in run: " + ioe.getMessage()); } } public void updateConversation() { try { ArrayList<ClientConversation> list = cs.getUserConversations(user); oos.writeObject(new ConversationsMessage(list)); oos.flush(); } catch (IOException ioe) { System.out.println("ioe: " + ioe.getMessage()); } } public void sendMessage(Message message) { try { oos.writeObject(message); oos.flush(); } catch (IOException ioe) { cs.removeServerThread(this); System.out.println("ioe: " + ioe.getMessage()); running = false; } } public void sendChatStringMessage(ChatMessage message) { // Send out a StringMessage to the user try { ChatStringMessage sMessage = new ChatStringMessage( cs.getData().findUserByUid(message.getUid()).getUsername() + ": " + message.getMessage(), message.getCid()); oos.writeObject(sMessage); oos.flush(); } catch (IOException ioe) { cs.removeServerThread(this); System.out.println("ioe: " + ioe.getMessage()); running = false; } } public void sendStringMessage(String message) { // Send out a StringMessage to the user try { StringMessage sMessage = new StringMessage(message); oos.writeObject(sMessage); oos.flush(); } catch (IOException ioe) { cs.removeServerThread(this); System.out.println("ioe: " + ioe.getMessage()); running = false; } } public void updateContacts() { ArrayList<String> contacts = new ArrayList<>(); ArrayList<User> temp = cs.getData().getUsers(); for (User u : temp) { contacts.add(u.getUsername()); } ContactsMessage cm = new ContactsMessage(contacts); try { oos.writeObject(cm); oos.flush(); } catch (IOException e) { e.printStackTrace(); } } // Handles consistently listening for chatMessages from client public void run() { login(); ArrayList<String> contacts = new ArrayList<>(); ArrayList<User> temp = cs.getData().getUsers(); for (User u : temp) { contacts.add(u.getUsername()); } try { while (running) { Message message = (Message) ois.readObject(); // Log the received Message Log.recieved(message); if (message instanceof ChatMessage) { cs.sendMessageToAllClients(message); } else if (message instanceof CommandMessage) { cs.receiveCommand((CommandMessage) message, this); } else if (message instanceof CreateConversationMessage) { cs.createConversation((CreateConversationMessage) message); } else if (message instanceof LogoutMessage) { break; } } } catch (ClassNotFoundException cnfe) { System.out.println("cnfe in run: " + cnfe.getMessage()); } catch (IOException ioe) { System.out.println("ioe in run: " + ioe.getMessage()); } catch (ConcurrentModificationException cme) { System.out.println("cme in run: " + cme.getMessage()); } cs.removeServerThread(this); } }
7,257
0.663542
0.663129
258
27.120155
21.92281
94
false
false
0
0
0
0
0
0
3.554264
false
false
0
2e23fee47ea211441fbca399f863d61da16a90a5
23,922,967,854,079
f6376e01b318290ba3244661002653add53af444
/src/main/java/com/mce/core/resource/Filter.java
86022675d9ff6f5d173e76f1b1e0be35ec534df4
[]
no_license
caimingqin/fruitProject
https://github.com/caimingqin/fruitProject
c0bd5d045f7923ed8f689a391ebe6bc7d15e4044
57ce9fa7b5d895a67beda0ab411e2f8b6f87999d
refs/heads/master
2020-05-19T10:42:17.561000
2014-06-16T07:48:17
2014-06-16T07:48:17
20,473,688
1
4
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mce.core.resource; public abstract interface Filter { public abstract boolean accepts(String paramString); }
UTF-8
Java
132
java
Filter.java
Java
[]
null
[]
package com.mce.core.resource; public abstract interface Filter { public abstract boolean accepts(String paramString); }
132
0.75
0.75
6
19.666666
20.499323
54
false
false
0
0
0
0
0
0
0.333333
false
false
0
bb4dd5209dc11c8a96823c89f56da1d3311b0b81
36,799,279,835,034
022384329140fc92d13c3fb23a4bf1e8296194bf
/basic-service/src/main/java/com/intest/basicservice/user/vo/LoginVO.java
3fd637779bc7959f035489bc465d22abbd43e6ac
[]
no_license
YtstIntest/fota-zt
https://github.com/YtstIntest/fota-zt
c10d881fcc2fc22d3f35105350d69c5aeb17cefc
a7c71c693f936c5ba4628d3779a8c8bd8110a69a
refs/heads/master
2023-01-22T20:38:45.127000
2020-11-10T09:12:39
2020-11-10T09:12:39
311,638,101
1
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.intest.basicservice.user.vo; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import java.util.ArrayList; import java.util.List; /** * @author zhanghui * @create 2020-08-21 9:30 */ @JsonPropertyOrder({"isCanLogin", "token", "freeNum", "menus"}) public class LoginVO { private int IsCanLogin; private String Token; private int FreeNum; private List<MenuVO> Menus; @JsonProperty("isCanLogin") public int getIsCanLogin() { return this.IsCanLogin; } @JsonProperty("token") public String getToken() { return this.Token; } @JsonProperty("freeNum") public int getFreeNum() { return this.FreeNum; } @JsonProperty("menus") public List<MenuVO> getMenus() { if (this.Menus == null) { this.Menus = new ArrayList<>(); } return this.Menus; } /** * 1-登录成功; * 2-用户名或密码错误; * 3-账户被冻结; * * @param value */ public void setIsCanLogin(int value) { this.IsCanLogin = value; } public void setToken(String value) { this.Token = value; } public void setFreeNum(int value) { this.FreeNum = value; } public void setMenus(List<MenuVO> value) { this.Menus = value; } }
UTF-8
Java
1,395
java
LoginVO.java
Java
[ { "context": ".ArrayList;\nimport java.util.List;\n\n/**\n * @author zhanghui\n * @create 2020-08-21 9:30\n */\n@JsonPropertyOrder", "end": 231, "score": 0.9993873834609985, "start": 223, "tag": "USERNAME", "value": "zhanghui" } ]
null
[]
package com.intest.basicservice.user.vo; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import java.util.ArrayList; import java.util.List; /** * @author zhanghui * @create 2020-08-21 9:30 */ @JsonPropertyOrder({"isCanLogin", "token", "freeNum", "menus"}) public class LoginVO { private int IsCanLogin; private String Token; private int FreeNum; private List<MenuVO> Menus; @JsonProperty("isCanLogin") public int getIsCanLogin() { return this.IsCanLogin; } @JsonProperty("token") public String getToken() { return this.Token; } @JsonProperty("freeNum") public int getFreeNum() { return this.FreeNum; } @JsonProperty("menus") public List<MenuVO> getMenus() { if (this.Menus == null) { this.Menus = new ArrayList<>(); } return this.Menus; } /** * 1-登录成功; * 2-用户名或密码错误; * 3-账户被冻结; * * @param value */ public void setIsCanLogin(int value) { this.IsCanLogin = value; } public void setToken(String value) { this.Token = value; } public void setFreeNum(int value) { this.FreeNum = value; } public void setMenus(List<MenuVO> value) { this.Menus = value; } }
1,395
0.605904
0.595572
69
18.637682
16.354736
63
false
false
0
0
0
0
0
0
0.304348
false
false
0
be4f665b50bdce60411003721d0dd0db64162f89
38,405,597,592,849
6c6f48632a6c2283ee50c78834e0773cec5aa5cb
/SFJava/spenefett/tmp/eqk.java
287565b43d6ea2e9474ad8f07f06aa684abcaf42
[]
no_license
kinghussien/darkfall_emu
https://github.com/kinghussien/darkfall_emu
263a9525b8c9cb62e5751163e419a3127acad7a1
3e3b76b2a892fb27c4b68fb5483664de4559bf98
refs/heads/master
2016-09-02T04:32:02.404000
2015-01-07T05:21:13
2015-01-07T05:21:13
27,749,321
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package spenefett.tmp; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import spenefett.worldbuilder.itw; class eqk implements ActionListener { eqk(itw paramitw) {} public void actionPerformed(ActionEvent paramActionEvent) { itw.a(this.fvs, paramActionEvent); } }
UTF-8
Java
324
java
eqk.java
Java
[]
null
[]
package spenefett.tmp; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import spenefett.worldbuilder.itw; class eqk implements ActionListener { eqk(itw paramitw) {} public void actionPerformed(ActionEvent paramActionEvent) { itw.a(this.fvs, paramActionEvent); } }
324
0.725309
0.725309
16
18.25
17.816776
59
false
false
0
0
0
0
0
0
0.375
false
false
0
735dbd62ade00ac22b4a44c0420a8e24dee88b19
34,797,825,087,273
dab1c76776de05c3d05da64706e87fabf7bbeef8
/Bridge/Q2/Main.java
7a171b3fd868c6858e35864d2c7fa241dda16be0
[]
no_license
seak0503/design_pattern
https://github.com/seak0503/design_pattern
b7ebf40879e26788c6fa4890024975a2503186cd
0fc5a3951bee3f4d60c43201faf64b71a385f7ac
refs/heads/master
2021-01-10T04:06:21.676000
2016-02-17T22:35:03
2016-02-17T22:35:03
45,320,400
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Main { public static void main(String[] args) { CountDisplay d = new CountDisplay(new FileDisplayImpl("start.txt")); d.multiDisplay(3); } }
UTF-8
Java
176
java
Main.java
Java
[]
null
[]
public class Main { public static void main(String[] args) { CountDisplay d = new CountDisplay(new FileDisplayImpl("start.txt")); d.multiDisplay(3); } }
176
0.642045
0.636364
6
28.5
25.5
76
false
false
0
0
0
0
0
0
0.333333
false
false
0
05d8a3fd5b0a04c332a3b4fb87f4f2a94b2d1c45
32,856,499,814,774
42fbb00a557bc41599efe6b96c35c23ab23e6179
/examSystem/src/com/wondersgroup/falcon/model/rc/base/BaseRrResource.java
efeebb9b3513cfc2e3f4892b9a8454eb165a3b27
[]
no_license
kevingekun/examSystem
https://github.com/kevingekun/examSystem
ed25d55441b927e62eba91f729bbe660a70a72d6
90594b286ca83dd3be5659bd96b7940e86190187
refs/heads/master
2020-04-06T03:55:02.674000
2017-03-30T08:48:17
2017-03-30T08:48:17
83,101,872
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.wondersgroup.falcon.model.rc.base; import java.lang.Comparable; import java.io.Serializable; import com.wondersgroup.falcon.model.citizeninfo.CompanyInfo; import com.wondersgroup.falcon.model.citizeninfo.PersonInfo; /** * This is an object that contains data related to the rr_resource table. * Do not modify this class because it will be overwritten if the configuration file * related to this class is modified. * * @hibernate.class * table="rr_resource" */ public abstract class BaseRrResource implements Comparable, Serializable { public static String REF = "RrResource"; public static String PROP_STAT = "Stat"; public static String PROP_SUBJECT_SN = "SubjectSn"; public static String PROP_USER = "User"; public static String PROP_CALLER_SN = "CallerSn"; public static String PROP_ID = "Id"; // constructors public BaseRrResource () { initialize(); } /** * Constructor for primary key */ public BaseRrResource (java.lang.String id) { this.setId(id); initialize(); } protected void initialize () {} private int hashCode = Integer.MIN_VALUE; // primary key private java.lang.String id; // fields private java.lang.String stat; // many to one private com.wondersgroup.falcon.model.rc.RrSubject subjectSn; private com.wondersgroup.falcon.model.rc.RrCaller callerSn; private com.wondersgroup.falcon.model.auth.User user; private PersonInfo personInfo; private CompanyInfo companyInfo; public CompanyInfo getCompanyInfo() { return companyInfo; } public void setCompanyInfo(CompanyInfo companyInfo) { this.companyInfo = companyInfo; } /** * Return the unique identifier of this class * @hibernate.id * generator-class="org.hibernate.id.UUIDHexGenerator" * column="resource_sn" */ public java.lang.String getId () { return id; } /** * Set the unique identifier of this class * @param id the new ID */ public void setId (java.lang.String id) { this.id = id; this.hashCode = Integer.MIN_VALUE; } /** * Return the value associated with the column: STAT */ public java.lang.String getStat () { return stat; } /** * Set the value related to the column: STAT * @param stat the STAT value */ public void setStat (java.lang.String stat) { this.stat = stat; } /** * Return the value associated with the column: subject_sn */ public com.wondersgroup.falcon.model.rc.RrSubject getSubjectSn () { return subjectSn; } /** * Set the value related to the column: subject_sn * @param subjectSn the subject_sn value */ public void setSubjectSn (com.wondersgroup.falcon.model.rc.RrSubject subjectSn) { this.subjectSn = subjectSn; } /** * Return the value associated with the column: CALLER_SN */ public com.wondersgroup.falcon.model.rc.RrCaller getCallerSn () { return callerSn; } /** * Set the value related to the column: CALLER_SN * @param callerSn the CALLER_SN value */ public void setCallerSn (com.wondersgroup.falcon.model.rc.RrCaller callerSn) { this.callerSn = callerSn; } /** * Return the value associated with the column: USER_ID */ public com.wondersgroup.falcon.model.auth.User getUser () { return user; } /** * Set the value related to the column: USER_ID * @param user the USER_ID value */ public void setUser (com.wondersgroup.falcon.model.auth.User user) { this.user = user; } public boolean equals (Object obj) { if (null == obj) return false; if (!(obj instanceof com.wondersgroup.falcon.model.rc.RrResource)) return false; else { com.wondersgroup.falcon.model.rc.RrResource rrResource = (com.wondersgroup.falcon.model.rc.RrResource) obj; if (null == this.getId() || null == rrResource.getId()) return false; else return (this.getId().equals(rrResource.getId())); } } public int hashCode () { if (Integer.MIN_VALUE == this.hashCode) { if (null == this.getId()) return super.hashCode(); else { String hashStr = this.getClass().getName() + ":" + this.getId().hashCode(); this.hashCode = hashStr.hashCode(); } } return this.hashCode; } public int compareTo (Object obj) { if (obj.hashCode() > hashCode()) return 1; else if (obj.hashCode() < hashCode()) return -1; else return 0; } public String toString () { return super.toString(); } public PersonInfo getPersonInfo() { return personInfo; } public void setPersonInfo(PersonInfo personInfo) { this.personInfo = personInfo; } }
UTF-8
Java
4,686
java
BaseRrResource.java
Java
[]
null
[]
package com.wondersgroup.falcon.model.rc.base; import java.lang.Comparable; import java.io.Serializable; import com.wondersgroup.falcon.model.citizeninfo.CompanyInfo; import com.wondersgroup.falcon.model.citizeninfo.PersonInfo; /** * This is an object that contains data related to the rr_resource table. * Do not modify this class because it will be overwritten if the configuration file * related to this class is modified. * * @hibernate.class * table="rr_resource" */ public abstract class BaseRrResource implements Comparable, Serializable { public static String REF = "RrResource"; public static String PROP_STAT = "Stat"; public static String PROP_SUBJECT_SN = "SubjectSn"; public static String PROP_USER = "User"; public static String PROP_CALLER_SN = "CallerSn"; public static String PROP_ID = "Id"; // constructors public BaseRrResource () { initialize(); } /** * Constructor for primary key */ public BaseRrResource (java.lang.String id) { this.setId(id); initialize(); } protected void initialize () {} private int hashCode = Integer.MIN_VALUE; // primary key private java.lang.String id; // fields private java.lang.String stat; // many to one private com.wondersgroup.falcon.model.rc.RrSubject subjectSn; private com.wondersgroup.falcon.model.rc.RrCaller callerSn; private com.wondersgroup.falcon.model.auth.User user; private PersonInfo personInfo; private CompanyInfo companyInfo; public CompanyInfo getCompanyInfo() { return companyInfo; } public void setCompanyInfo(CompanyInfo companyInfo) { this.companyInfo = companyInfo; } /** * Return the unique identifier of this class * @hibernate.id * generator-class="org.hibernate.id.UUIDHexGenerator" * column="resource_sn" */ public java.lang.String getId () { return id; } /** * Set the unique identifier of this class * @param id the new ID */ public void setId (java.lang.String id) { this.id = id; this.hashCode = Integer.MIN_VALUE; } /** * Return the value associated with the column: STAT */ public java.lang.String getStat () { return stat; } /** * Set the value related to the column: STAT * @param stat the STAT value */ public void setStat (java.lang.String stat) { this.stat = stat; } /** * Return the value associated with the column: subject_sn */ public com.wondersgroup.falcon.model.rc.RrSubject getSubjectSn () { return subjectSn; } /** * Set the value related to the column: subject_sn * @param subjectSn the subject_sn value */ public void setSubjectSn (com.wondersgroup.falcon.model.rc.RrSubject subjectSn) { this.subjectSn = subjectSn; } /** * Return the value associated with the column: CALLER_SN */ public com.wondersgroup.falcon.model.rc.RrCaller getCallerSn () { return callerSn; } /** * Set the value related to the column: CALLER_SN * @param callerSn the CALLER_SN value */ public void setCallerSn (com.wondersgroup.falcon.model.rc.RrCaller callerSn) { this.callerSn = callerSn; } /** * Return the value associated with the column: USER_ID */ public com.wondersgroup.falcon.model.auth.User getUser () { return user; } /** * Set the value related to the column: USER_ID * @param user the USER_ID value */ public void setUser (com.wondersgroup.falcon.model.auth.User user) { this.user = user; } public boolean equals (Object obj) { if (null == obj) return false; if (!(obj instanceof com.wondersgroup.falcon.model.rc.RrResource)) return false; else { com.wondersgroup.falcon.model.rc.RrResource rrResource = (com.wondersgroup.falcon.model.rc.RrResource) obj; if (null == this.getId() || null == rrResource.getId()) return false; else return (this.getId().equals(rrResource.getId())); } } public int hashCode () { if (Integer.MIN_VALUE == this.hashCode) { if (null == this.getId()) return super.hashCode(); else { String hashStr = this.getClass().getName() + ":" + this.getId().hashCode(); this.hashCode = hashStr.hashCode(); } } return this.hashCode; } public int compareTo (Object obj) { if (obj.hashCode() > hashCode()) return 1; else if (obj.hashCode() < hashCode()) return -1; else return 0; } public String toString () { return super.toString(); } public PersonInfo getPersonInfo() { return personInfo; } public void setPersonInfo(PersonInfo personInfo) { this.personInfo = personInfo; } }
4,686
0.667093
0.666453
205
20.868292
23.881153
110
false
false
0
0
0
0
0
0
1.156098
false
false
0
af31dbf37b63785732e3eb4e1100f4fedeb77d5a
16,698,832,867,715
4d05861f28ca84eb1eb9e4abde237c9f773b46d4
/src/main/java/io/libsoft/view/Arena.java
f62a20f856ad9cb8e5d17d111ced92c801e80d0b
[]
no_license
sixspeedchips/snake-server
https://github.com/sixspeedchips/snake-server
ca8ba83bbafd0ccd60d318a5d0e890dbbde1c468
a7e483fcd66b7e7238a4f5608514d014abab7660
refs/heads/master
2022-12-09T14:37:58.138000
2020-09-12T15:41:59
2020-09-12T15:41:59
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package io.libsoft.view; import io.libsoft.model.Drawable; import io.libsoft.model.Model; import io.libsoft.util.Props; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.paint.Color; public class Arena extends Canvas { private final GraphicsContext gc = getGraphicsContext2D(); { setWidth(Props.get().getWidth()); setHeight(Props.get().getHeight()); gc.setFill(Color.GREY); gc.fillRect(0, 0, Props.get().getHeight(), Props.get().getWidth()); } public void render(Model model) { for (Drawable drawable : model.getDrawables()) { drawable.render(gc); } } }
UTF-8
Java
651
java
Arena.java
Java
[]
null
[]
package io.libsoft.view; import io.libsoft.model.Drawable; import io.libsoft.model.Model; import io.libsoft.util.Props; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.paint.Color; public class Arena extends Canvas { private final GraphicsContext gc = getGraphicsContext2D(); { setWidth(Props.get().getWidth()); setHeight(Props.get().getHeight()); gc.setFill(Color.GREY); gc.fillRect(0, 0, Props.get().getHeight(), Props.get().getWidth()); } public void render(Model model) { for (Drawable drawable : model.getDrawables()) { drawable.render(gc); } } }
651
0.706605
0.701997
29
21.448277
20.541945
71
false
false
0
0
0
0
0
0
0.551724
false
false
0
9ec8c14e006f6e2c317d5ec2aaddb802e7e84202
16,561,393,901,171
0146acfd85c104cfc3d3c1206913894ef8d8d577
/src/main/java/com/oocl/cultivation/Ticket.java
e8c9b110f102db0dfe71daaa397b875e54cf3f36
[]
no_license
olivia-wang-code/tdd-parking-lot-cli-2020-7-15-3-23-38-755-2020-7-24-4-12-26-568
https://github.com/olivia-wang-code/tdd-parking-lot-cli-2020-7-15-3-23-38-755-2020-7-24-4-12-26-568
0fde79881a16d372f7fc3d47796eab2077daf94f
f07b94392ed10ad223290ae40f06f8f84abb1ea4
refs/heads/master
2022-11-25T01:11:19.343000
2020-07-26T12:19:14
2020-07-26T12:19:14
282,151,650
0
1
null
true
2020-07-24T07:22:25
2020-07-24T07:22:24
2020-07-24T04:12:51
2020-07-24T04:12:49
58
0
0
0
null
false
false
package com.oocl.cultivation; import java.util.Random; public class Ticket { private int id; private Car car; public Ticket(int id) { this.id = id; } public Ticket(Car car){ this.id=car.getId(); } public Ticket() { } public void setId(int id) { this.id = id; } public int getId() { return id; } public Ticket generateTicket(){ return new Ticket(new Random().nextInt(100)); } }
UTF-8
Java
480
java
Ticket.java
Java
[]
null
[]
package com.oocl.cultivation; import java.util.Random; public class Ticket { private int id; private Car car; public Ticket(int id) { this.id = id; } public Ticket(Car car){ this.id=car.getId(); } public Ticket() { } public void setId(int id) { this.id = id; } public int getId() { return id; } public Ticket generateTicket(){ return new Ticket(new Random().nextInt(100)); } }
480
0.554167
0.547917
30
15
13.515423
53
false
false
0
0
0
0
0
0
0.3
false
false
0
79a9a7cf0b4f2682f318332d797311d90ed8ac61
24,601,572,691,826
a37d03fac9513e1f3976168a05d3a5d9ace82475
/firstapp/src/main/java/ru/geekbrains/domain/Order.java
797523db757a57e8caba024faa8035c7ab52eecf
[]
no_license
artur-java-dev/javaee-homeworks
https://github.com/artur-java-dev/javaee-homeworks
07c668836fa81e8141179e42fd732b699f19824d
88ff40c0411949e272fcae4e4b1f3e3c242a62ec
refs/heads/master
2022-12-07T16:47:32.488000
2020-04-30T11:32:59
2020-04-30T11:32:59
247,463,369
0
0
null
false
2022-11-24T10:18:19
2020-03-15T12:37:26
2020-04-30T11:33:03
2022-11-24T10:18:16
780
0
0
3
Java
false
false
package ru.geekbrains.domain; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; import java.time.LocalDate; import java.util.List; import static javax.persistence.CascadeType.ALL; import static javax.persistence.GenerationType.IDENTITY; @Entity @Data @NoArgsConstructor @Table(name = "orders") public class Order { @Id @GeneratedValue(strategy = IDENTITY) private Long id; @Column(name = "number", nullable = false, unique = true) private String number; @Column(name = "delivery_date", nullable = false, columnDefinition = "DATE") private LocalDate deliveryDate; @Column(name = "delivery_country", nullable = false) private String deliveryCountry; @Column(name = "delivery_city", nullable = false) private String deliveryCity; @Column(name = "delivery_street", nullable = false) private String deliveryStreet; @Column(name = "delivery_building_num", nullable = false) private Integer deliveryBuildingNum; @Column(name = "delivery_appartments_num") private Integer deliveryAppartmentsNum; @Column(name = "delivery_method", nullable = false) private String deliveryMethod; @Column(name = "payment_method", nullable = false) private String paymentMethod; @Column(name = "username", nullable = false) private String username; @OneToMany(mappedBy = "order", cascade = ALL) private List<OrderItem> items; }
UTF-8
Java
1,400
java
Order.java
Java
[]
null
[]
package ru.geekbrains.domain; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; import java.time.LocalDate; import java.util.List; import static javax.persistence.CascadeType.ALL; import static javax.persistence.GenerationType.IDENTITY; @Entity @Data @NoArgsConstructor @Table(name = "orders") public class Order { @Id @GeneratedValue(strategy = IDENTITY) private Long id; @Column(name = "number", nullable = false, unique = true) private String number; @Column(name = "delivery_date", nullable = false, columnDefinition = "DATE") private LocalDate deliveryDate; @Column(name = "delivery_country", nullable = false) private String deliveryCountry; @Column(name = "delivery_city", nullable = false) private String deliveryCity; @Column(name = "delivery_street", nullable = false) private String deliveryStreet; @Column(name = "delivery_building_num", nullable = false) private Integer deliveryBuildingNum; @Column(name = "delivery_appartments_num") private Integer deliveryAppartmentsNum; @Column(name = "delivery_method", nullable = false) private String deliveryMethod; @Column(name = "payment_method", nullable = false) private String paymentMethod; @Column(name = "username", nullable = false) private String username; @OneToMany(mappedBy = "order", cascade = ALL) private List<OrderItem> items; }
1,400
0.740714
0.740714
59
22.745762
21.298201
78
false
false
0
0
0
0
0
0
0.542373
false
false
0
af9b07d741b117d8845e7261874a30044d2faf51
6,975,026,906,217
d3f6a23d7c96051b053f9c91d9444171402b1c53
/SistemaMatricula/src/main/java/dev/com/matricula/dto/RolUsuarioDTO.java
263547da019751cd98d940468a0f7ad38132fc45
[]
no_license
WillianYCR/SistemaMatricula
https://github.com/WillianYCR/SistemaMatricula
bfd7f116dd17242a7570ef727e029f596891b0cd
d6010e254df8ce16c00c7fb287e8196bc3a6d994
refs/heads/master
2021-04-09T16:51:09.308000
2014-12-29T05:15:07
2014-12-29T05:15:07
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dev.com.matricula.dto; import dev.com.matricula.model.RolUsuario; import dev.com.matricula.util.Consola; public class RolUsuarioDTO { private Integer id; private UsuarioDTO usuario; private RolDTO rol; private Character estado; public RolUsuarioDTO() { } public RolUsuarioDTO(RolUsuario rolUsuario) { if (rolUsuario != null) { this.id = rolUsuario.getIdRolUsuario(); this.usuario = new UsuarioDTO(rolUsuario.getUsuario()); this.rol = new RolDTO(rolUsuario.getRol()); this.estado = rolUsuario.getEstado(); } else { Consola.objetoNull(RolUsuario.class.getName()); } } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public UsuarioDTO getUsuario() { return usuario; } public void setUsuario(UsuarioDTO usuario) { this.usuario = usuario; } public RolDTO getRol() { return rol; } public void setRol(RolDTO rol) { this.rol = rol; } public Character getEstado() { return estado; } public void setEstado(Character estado) { this.estado = estado; } }
UTF-8
Java
1,063
java
RolUsuarioDTO.java
Java
[]
null
[]
package dev.com.matricula.dto; import dev.com.matricula.model.RolUsuario; import dev.com.matricula.util.Consola; public class RolUsuarioDTO { private Integer id; private UsuarioDTO usuario; private RolDTO rol; private Character estado; public RolUsuarioDTO() { } public RolUsuarioDTO(RolUsuario rolUsuario) { if (rolUsuario != null) { this.id = rolUsuario.getIdRolUsuario(); this.usuario = new UsuarioDTO(rolUsuario.getUsuario()); this.rol = new RolDTO(rolUsuario.getRol()); this.estado = rolUsuario.getEstado(); } else { Consola.objetoNull(RolUsuario.class.getName()); } } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public UsuarioDTO getUsuario() { return usuario; } public void setUsuario(UsuarioDTO usuario) { this.usuario = usuario; } public RolDTO getRol() { return rol; } public void setRol(RolDTO rol) { this.rol = rol; } public Character getEstado() { return estado; } public void setEstado(Character estado) { this.estado = estado; } }
1,063
0.703669
0.703669
59
17.016949
16.8538
58
false
false
0
0
0
0
0
0
1.372881
false
false
0
c37ef91c0eef21de09615963349e810fece806c2
28,707,561,415,043
00d28dcf71e79570f679fd7862576b68252017c5
/softwareOperacional/softwareOperacional-web/src/main/java/co/edu/eam/ingesoft/softOper/web/servicios/Consulta4.java
c3ca2804d8e1c3d3d6c8298b17974a42d08b6476
[]
no_license
Gaviria9601/Software-Operacional
https://github.com/Gaviria9601/Software-Operacional
81734691cbcaa286a7dc49ebdcd6300770dd9ebc
bcb6c8c39a7c902b7f386feec9bf128e00fdfbf4
refs/heads/master
2022-06-21T09:11:31.548000
2022-06-07T16:59:54
2022-06-07T16:59:54
105,630,986
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package co.edu.eam.ingesoft.softOper.web.servicios; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class Consulta4 { private double venta; private Date fecha; public Consulta4() { // TODO Auto-generated constructor stub } /** * @param venta * @param fecha */ public Consulta4(double venta, Date fecha) { super(); this.venta = venta; this.fecha = fecha; } /** * @return the venta */ public double getVenta() { return venta; } /** * @param venta the venta to set */ public void setVenta(double venta) { this.venta = venta; } /** * @return the fecha * @throws ParseException */ public String getFecha() throws ParseException { DateFormat outputFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); return outputFormat.format(fecha); } /** * @param fecha the fecha to set */ public void setFecha(Date fecha) { this.fecha = fecha; } }
UTF-8
Java
1,051
java
Consulta4.java
Java
[]
null
[]
package co.edu.eam.ingesoft.softOper.web.servicios; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class Consulta4 { private double venta; private Date fecha; public Consulta4() { // TODO Auto-generated constructor stub } /** * @param venta * @param fecha */ public Consulta4(double venta, Date fecha) { super(); this.venta = venta; this.fecha = fecha; } /** * @return the venta */ public double getVenta() { return venta; } /** * @param venta the venta to set */ public void setVenta(double venta) { this.venta = venta; } /** * @return the fecha * @throws ParseException */ public String getFecha() throws ParseException { DateFormat outputFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); return outputFormat.format(fecha); } /** * @param fecha the fecha to set */ public void setFecha(Date fecha) { this.fecha = fecha; } }
1,051
0.632731
0.629876
61
15.229508
16.391115
72
false
false
0
0
0
0
0
0
1.131148
false
false
0
dbf88c503f9039cb632b4f5953856ab053d354b6
5,901,285,087,836
54882634ee5ab879731501003ba86fc191d0bdfb
/Quattrocchi/src/test/it/unisa/quattrocchi/model/AcquirenteModelTest.java
00ca08681af98e05b2f1405816bdd9f5419d567f
[]
no_license
DrRek/Quattrocchi.it
https://github.com/DrRek/Quattrocchi.it
15e3192297a936e0f6a7794f5b1d805f079b72c8
d4e95af6184db4b39c0b51338268a233d36c761d
refs/heads/master
2021-03-22T04:57:21.993000
2018-01-31T09:35:15
2018-01-31T09:35:15
105,260,066
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package test.it.unisa.quattrocchi.model; import static org.junit.jupiter.api.Assertions.*; import java.sql.SQLException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import it.unisa.quattrocchi.entity.Acquirente; import it.unisa.quattrocchi.entity.ArticoloInStock; import it.unisa.quattrocchi.entity.Cart; import it.unisa.quattrocchi.model.AcquirenteModel; import it.unisa.quattrocchi.model.ArticoloInStockModel; class AcquirenteModelTest { private static AcquirenteModel acquirenteModel; private static ArticoloInStockModel articoloInStockModel; static { acquirenteModel = new AcquirenteModel(); articoloInStockModel = new ArticoloInStockModel(); } @BeforeEach public void setUp() throws Exception{ DatabaseHelper.initializeDatabase(); } @AfterEach public void tearDown() throws Exception{ DatabaseHelper.initializeDatabase(); } @Test public void TestRicercaPerId() throws SQLException { Acquirente a = acquirenteModel.doRetriveById("AntosxA"); assertNotNull(a); assertEquals(a.getNome(),"Antonio"); assertEquals(a.getCognome(),"Spera"); assertEquals(a.getUsername(),"AntosxA"); assertEquals(a.getPassword(),"Forzajuve"); } @Test public void TestCheckLogin() throws SQLException { Acquirente a = acquirenteModel.doRetriveById("AntosxA"); assertNotNull(a); String username = a.getUsername(); String password = a.getPassword(); Acquirente b = acquirenteModel.checkLogin(username, password); assertNotNull(b); assertEquals(b.getUsername(),a.getUsername()); } @Test public void TestCarreloPerUtente() throws SQLException { Acquirente a = acquirenteModel.doRetriveById("AntosxA"); assertNotNull(a); String username = a.getUsername(); Cart c = acquirenteModel.doRetrieveCartByUser(username); assertNotNull(c); } @Test public void TestAggiornaAcquirente() throws SQLException { Acquirente a = acquirenteModel.doRetriveById("Expos"); assertNotNull(a); a.setPassword("sonoivan"); a.setEmail("ivanesposito96@miao.it"); acquirenteModel.updateAcquirente(a); Acquirente b = acquirenteModel.doRetriveById("Expos"); assertNotNull(b); assertEquals(b.getPassword(),"sonoivan"); assertEquals(b.getEmail(),"ivanesposito96@miao.it"); } @Test public void TestAggiornaCarrello() throws SQLException { Acquirente a = acquirenteModel.doRetriveById("Expos"); assertNotNull(a); Cart c = acquirenteModel.doRetrieveCartByUser(a.getUsername()); assertNotNull(c); assertEquals(c.getArticoli().size(),1); ArticoloInStock ais = articoloInStockModel.doRetrieveByIdInStock(999); c.addArticle(ais); a.setCart(c); acquirenteModel.updateCart(a); Acquirente b = acquirenteModel.doRetriveById("Expos"); assertNotNull(b); Cart c1 = acquirenteModel.doRetrieveCartByUser(b.getUsername()); assertNotNull(c1); assertEquals(c1.getArticoli().size(),2); assertTrue(c1.getArticoli().containsKey(ais)); } @Test public void TestCancellaCarrello() throws SQLException { Acquirente a = acquirenteModel.doRetriveById("AntosxA"); assertNotNull(a); acquirenteModel.dropCart(a); assertEquals(a.getCart(),null); } }
UTF-8
Java
3,193
java
AcquirenteModelTest.java
Java
[ { "context": ";\n\t\tassertNotNull(a);\n\t\tassertEquals(a.getNome(),\"Antonio\");\n\t\tassertEquals(a.getCognome(),\"Spera\");\n\t\tasse", "end": 1116, "score": 0.994735062122345, "start": 1109, "tag": "NAME", "value": "Antonio" }, { "context": "Nome(),\"Antonio\");\n\t\tassertEquals(a.getCognome(),\"Spera\");\n\t\tassertEquals(a.getUsername(),\"AntosxA\");\n\t\ta", "end": 1156, "score": 0.9951281547546387, "start": 1151, "tag": "NAME", "value": "Spera" }, { "context": "gnome(),\"Spera\");\n\t\tassertEquals(a.getUsername(),\"AntosxA\");\n\t\tassertEquals(a.getPassword(),\"Forzajuve\");\n\t", "end": 1199, "score": 0.9993769526481628, "start": 1192, "tag": "USERNAME", "value": "AntosxA" }, { "context": "ame(),\"AntosxA\");\n\t\tassertEquals(a.getPassword(),\"Forzajuve\");\n\t}\n\t\n\t@Test\n\tpublic void TestCheckLogin() thro", "end": 1244, "score": 0.9992169141769409, "start": 1235, "tag": "PASSWORD", "value": "Forzajuve" }, { "context": "ng username = a.getUsername();\n\t\tString password = a.getPassword();\n\t\tAcquirente b = acquirenteModel.checkLogin(us", "end": 1461, "score": 0.9890606999397278, "start": 1448, "tag": "PASSWORD", "value": "a.getPassword" }, { "context": "Id(\"Expos\");\n\t\tassertNotNull(a);\n\t\ta.setPassword(\"sonoivan\");\n\t\ta.setEmail(\"ivanesposito96@miao.it\");\n\t\tacqu", "end": 2038, "score": 0.9992974996566772, "start": 2030, "tag": "PASSWORD", "value": "sonoivan" }, { "context": "ll(a);\n\t\ta.setPassword(\"sonoivan\");\n\t\ta.setEmail(\"ivanesposito96@miao.it\");\n\t\tacquirenteModel.updateAcquirente(a);\n\t\tAcqui", "end": 2078, "score": 0.9999291896820068, "start": 2056, "tag": "EMAIL", "value": "ivanesposito96@miao.it" }, { "context": "assertNotNull(b);\n\t\tassertEquals(b.getPassword(),\"sonoivan\");\n\t\tassertEquals(b.getEmail(),\"ivanesposito96@mi", "end": 2238, "score": 0.9993310570716858, "start": 2230, "tag": "PASSWORD", "value": "sonoivan" }, { "context": "sword(),\"sonoivan\");\n\t\tassertEquals(b.getEmail(),\"ivanesposito96@miao.it\");\n\t}\n\t\n\t\n\t@Test\n\tpublic void TestAggiornaCarrell", "end": 2293, "score": 0.9999241828918457, "start": 2271, "tag": "EMAIL", "value": "ivanesposito96@miao.it" } ]
null
[]
package test.it.unisa.quattrocchi.model; import static org.junit.jupiter.api.Assertions.*; import java.sql.SQLException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import it.unisa.quattrocchi.entity.Acquirente; import it.unisa.quattrocchi.entity.ArticoloInStock; import it.unisa.quattrocchi.entity.Cart; import it.unisa.quattrocchi.model.AcquirenteModel; import it.unisa.quattrocchi.model.ArticoloInStockModel; class AcquirenteModelTest { private static AcquirenteModel acquirenteModel; private static ArticoloInStockModel articoloInStockModel; static { acquirenteModel = new AcquirenteModel(); articoloInStockModel = new ArticoloInStockModel(); } @BeforeEach public void setUp() throws Exception{ DatabaseHelper.initializeDatabase(); } @AfterEach public void tearDown() throws Exception{ DatabaseHelper.initializeDatabase(); } @Test public void TestRicercaPerId() throws SQLException { Acquirente a = acquirenteModel.doRetriveById("AntosxA"); assertNotNull(a); assertEquals(a.getNome(),"Antonio"); assertEquals(a.getCognome(),"Spera"); assertEquals(a.getUsername(),"AntosxA"); assertEquals(a.getPassword(),"<PASSWORD>"); } @Test public void TestCheckLogin() throws SQLException { Acquirente a = acquirenteModel.doRetriveById("AntosxA"); assertNotNull(a); String username = a.getUsername(); String password = <PASSWORD>(); Acquirente b = acquirenteModel.checkLogin(username, password); assertNotNull(b); assertEquals(b.getUsername(),a.getUsername()); } @Test public void TestCarreloPerUtente() throws SQLException { Acquirente a = acquirenteModel.doRetriveById("AntosxA"); assertNotNull(a); String username = a.getUsername(); Cart c = acquirenteModel.doRetrieveCartByUser(username); assertNotNull(c); } @Test public void TestAggiornaAcquirente() throws SQLException { Acquirente a = acquirenteModel.doRetriveById("Expos"); assertNotNull(a); a.setPassword("<PASSWORD>"); a.setEmail("<EMAIL>"); acquirenteModel.updateAcquirente(a); Acquirente b = acquirenteModel.doRetriveById("Expos"); assertNotNull(b); assertEquals(b.getPassword(),"<PASSWORD>"); assertEquals(b.getEmail(),"<EMAIL>"); } @Test public void TestAggiornaCarrello() throws SQLException { Acquirente a = acquirenteModel.doRetriveById("Expos"); assertNotNull(a); Cart c = acquirenteModel.doRetrieveCartByUser(a.getUsername()); assertNotNull(c); assertEquals(c.getArticoli().size(),1); ArticoloInStock ais = articoloInStockModel.doRetrieveByIdInStock(999); c.addArticle(ais); a.setCart(c); acquirenteModel.updateCart(a); Acquirente b = acquirenteModel.doRetriveById("Expos"); assertNotNull(b); Cart c1 = acquirenteModel.doRetrieveCartByUser(b.getUsername()); assertNotNull(c1); assertEquals(c1.getArticoli().size(),2); assertTrue(c1.getArticoli().containsKey(ais)); } @Test public void TestCancellaCarrello() throws SQLException { Acquirente a = acquirenteModel.doRetriveById("AntosxA"); assertNotNull(a); acquirenteModel.dropCart(a); assertEquals(a.getCart(),null); } }
3,165
0.762293
0.758221
107
28.841122
21.795202
72
false
false
0
0
0
0
0
0
1.943925
false
false
0
59311a08e777fd348cd9ae29cb35254e7c1dff03
1,408,749,289,855
ceee21165d0a211c360ecab5b77baadb21b442e5
/core/common/src/test/java/alluxio/wire/CommandLineJobInfoTest.java
13ca875b356ab1e881b4b81c1a726fa3936c2f74
[ "LicenseRef-scancode-free-unknown", "Unlicense", "Apache-2.0", "EPL-1.0", "MIT", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause", "BSD-3-Clause", "CC-PDDC", "LicenseRef-scancode-public-domain" ]
permissive
WraithL/alluxio
https://github.com/WraithL/alluxio
d41085faf4db0215ee5bded8ab98cfff3b2e5724
baeb20b9c8f6881864722d40bb8f494525804f1a
refs/heads/master
2020-03-11T08:09:55.761000
2018-04-17T02:15:06
2018-04-17T02:15:06
129,876,394
2
0
Apache-2.0
true
2018-04-17T09:01:42
2018-04-17T09:01:42
2018-04-17T02:45:14
2018-04-17T08:19:28
87,423
0
0
0
null
false
null
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.wire; import static org.junit.Assert.assertEquals; import alluxio.util.CommonUtils; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import java.util.Random; public final class CommandLineJobInfoTest { @Test public void json() throws Exception { CommandLineJobInfo jobInfo = createRandom(); ObjectMapper mapper = new ObjectMapper(); CommandLineJobInfo other = mapper.readValue(mapper.writeValueAsBytes(jobInfo), CommandLineJobInfo.class); checkEquality(jobInfo, other); } @Test public void thrift() { CommandLineJobInfo jobInfo = createRandom(); CommandLineJobInfo other = ThriftUtils.fromThrift(ThriftUtils.toThrift(jobInfo)); checkEquality(jobInfo, other); } public void checkEquality(CommandLineJobInfo a, CommandLineJobInfo b) { assertEquals(a.getCommand(), b.getCommand()); assertEquals(a.getConf(), b.getConf()); assertEquals(a, b); } public static CommandLineJobInfo createRandom() { CommandLineJobInfo result = new CommandLineJobInfo(); Random random = new Random(); String command = CommonUtils.randomAlphaNumString(random.nextInt(10)); JobConfInfo jobConfInfo = JobConfInfoTest.createRandom(); result.setCommand(command); result.setConf(jobConfInfo); return result; } }
UTF-8
Java
1,844
java
CommandLineJobInfoTest.java
Java
[]
null
[]
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.wire; import static org.junit.Assert.assertEquals; import alluxio.util.CommonUtils; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import java.util.Random; public final class CommandLineJobInfoTest { @Test public void json() throws Exception { CommandLineJobInfo jobInfo = createRandom(); ObjectMapper mapper = new ObjectMapper(); CommandLineJobInfo other = mapper.readValue(mapper.writeValueAsBytes(jobInfo), CommandLineJobInfo.class); checkEquality(jobInfo, other); } @Test public void thrift() { CommandLineJobInfo jobInfo = createRandom(); CommandLineJobInfo other = ThriftUtils.fromThrift(ThriftUtils.toThrift(jobInfo)); checkEquality(jobInfo, other); } public void checkEquality(CommandLineJobInfo a, CommandLineJobInfo b) { assertEquals(a.getCommand(), b.getCommand()); assertEquals(a.getConf(), b.getConf()); assertEquals(a, b); } public static CommandLineJobInfo createRandom() { CommandLineJobInfo result = new CommandLineJobInfo(); Random random = new Random(); String command = CommonUtils.randomAlphaNumString(random.nextInt(10)); JobConfInfo jobConfInfo = JobConfInfoTest.createRandom(); result.setCommand(command); result.setConf(jobConfInfo); return result; } }
1,844
0.746204
0.74295
59
30.254238
29.852514
98
false
false
0
0
0
0
0
0
0.59322
false
false
0
22b8306f3c6371815c433868310db5196f566f1c
5,832,565,631,404
39f2a6e832b1542021b6659e6180e4275a0f7b6b
/app/src/main/java/com/justimaginethat/gogodriver/APIModels/DriverWorkspace/APIMarkOrderCompletedResponseModel.java
27ca1557890752169c94eebb1792e3f638d18dc7
[]
no_license
NikitaGvozdilko/PayBit
https://github.com/NikitaGvozdilko/PayBit
1eb9d1a68cb1b28566ee1d3af51753d76207ce9a
1f861f5812df8bd19d1b9c8c33a9a887fd883296
refs/heads/master
2021-07-21T22:45:12.204000
2017-10-31T19:19:42
2017-10-31T19:19:42
109,135,557
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.justimaginethat.gogodriver.APIModels.DriverWorkspace; import com.justimaginethat.gogodriver.BaseModel.BaseAPIErrorModel; import java.io.Serializable; /** * Created by Lion-1 on 3/29/2017. */ public class APIMarkOrderCompletedResponseModel extends BaseAPIErrorModel implements Serializable { public String EmailID; public APIMarkOrderCompletedResponseModel() { } }
UTF-8
Java
396
java
APIMarkOrderCompletedResponseModel.java
Java
[ { "context": ";\n\nimport java.io.Serializable;\n\n/**\n * Created by Lion-1 on 3/29/2017.\n */\n\npublic class APIMarkOrderCompl", "end": 189, "score": 0.9996048212051392, "start": 183, "tag": "USERNAME", "value": "Lion-1" } ]
null
[]
package com.justimaginethat.gogodriver.APIModels.DriverWorkspace; import com.justimaginethat.gogodriver.BaseModel.BaseAPIErrorModel; import java.io.Serializable; /** * Created by Lion-1 on 3/29/2017. */ public class APIMarkOrderCompletedResponseModel extends BaseAPIErrorModel implements Serializable { public String EmailID; public APIMarkOrderCompletedResponseModel() { } }
396
0.79798
0.777778
17
22.294117
29.698019
99
false
false
0
0
0
0
0
0
0.235294
false
false
0