hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
5
1.02k
max_stars_repo_name
stringlengths
4
126
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
list
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
5
1.02k
max_issues_repo_name
stringlengths
4
114
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
list
max_issues_count
float64
1
92.2k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
5
1.02k
max_forks_repo_name
stringlengths
4
136
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
list
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2.55
99.9
max_line_length
int64
3
1k
alphanum_fraction
float64
0.25
1
index
int64
0
1M
content
stringlengths
3
1.05M
3e1b05a34b7231f8110a8e6f8cb7d3d43be9383b
37,607
java
Java
src/integrationTest/java/uk/gov/hmcts/reform/pcqbackend/controllers/UpdatePcqRequestTest.java
uk-gov-mirror/hmcts.pcq-backend
4fb3bec547ac50d752174597bfc75aa00b922a16
[ "MIT" ]
1
2020-05-05T08:34:39.000Z
2020-05-05T08:34:39.000Z
src/integrationTest/java/uk/gov/hmcts/reform/pcqbackend/controllers/UpdatePcqRequestTest.java
uk-gov-mirror/hmcts.pcq-backend
4fb3bec547ac50d752174597bfc75aa00b922a16
[ "MIT" ]
355
2020-03-02T14:10:59.000Z
2022-03-31T13:19:11.000Z
src/integrationTest/java/uk/gov/hmcts/reform/pcqbackend/controllers/UpdatePcqRequestTest.java
uk-gov-mirror/hmcts.pcq-backend
4fb3bec547ac50d752174597bfc75aa00b922a16
[ "MIT" ]
2
2020-06-17T09:25:31.000Z
2021-04-10T22:38:29.000Z
37.308532
114
0.665328
11,444
package uk.gov.hmcts.reform.pcqbackend.controllers; import lombok.extern.slf4j.Slf4j; import net.serenitybdd.junit.spring.integration.SpringIntegrationSerenityRunner; import net.thucydides.core.annotations.WithTag; import net.thucydides.core.annotations.WithTags; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.system.OutputCaptureRule; import uk.gov.hmcts.reform.pcq.commons.model.PcqAnswerRequest; import uk.gov.hmcts.reform.pcq.commons.model.PcqAnswers; import uk.gov.hmcts.reform.pcqbackend.domain.ProtectedCharacteristics; import uk.gov.hmcts.reform.pcqbackend.util.PcqIntegrationTest; import java.io.IOException; import java.util.Map; import java.util.Optional; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static uk.gov.hmcts.reform.pcq.commons.tests.utils.TestUtils.jsonObjectFromString; import static uk.gov.hmcts.reform.pcq.commons.tests.utils.TestUtils.jsonStringFromFile; @Slf4j @RunWith(SpringIntegrationSerenityRunner.class) @WithTags({@WithTag("testType:Integration")}) @SuppressWarnings({"PMD.TooManyMethods"}) public class UpdatePcqRequestTest extends PcqIntegrationTest { public static final String RESPONSE_KEY_4 = "response_body"; public static final String HTTP_ACCEPTED = "202"; public static final String HTTP_BAD_REQUEST = "400"; public static final String RESPONSE_ACCEPTED_MSG = "Success"; public static final String RESPONSE_INVALID_MSG = "Invalid Request"; private static final String TEST_DUP_PCQ_ID = "UPDATE-DUP-INTEG-TEST"; private static final String IO_EXCEPTION_MSG = "IOException while executing test"; @Rule public OutputCaptureRule capture = new OutputCaptureRule(); @Test public void updateDobProvidedSuccess() { // Create an record first. createTestRecord(); try { String jsonStringRequest = jsonStringFromFile("JsonTestFiles/UpdateDobProvided.json"); PcqAnswerRequest answerRequest = jsonObjectFromString(jsonStringRequest); Map<String, Object> response = pcqBackEndClient.createPcqAnswer(answerRequest); assertEquals(PCQ_NOT_VALID_MSG, TEST_PCQ_ID, response.get(RESPONSE_KEY_1)); assertEquals(STATUS_CODE_INVALID_MSG, HTTP_CREATED, response.get(RESPONSE_KEY_2)); assertEquals(STATUS_INVALID_MSG, RESPONSE_CREATED_MSG, response.get(RESPONSE_KEY_3)); Optional<ProtectedCharacteristics> protectedCharacteristicsOptional = protectedCharacteristicsRepository.findById(TEST_PCQ_ID); assertFalse(protectedCharacteristicsOptional.isEmpty(), NOT_FOUND_MSG); checkAssertionsOnResponse(protectedCharacteristicsOptional.get(), answerRequest); assertLogsForKeywords(); } catch (IOException e) { log.error(IO_EXCEPTION_MSG, e); } } @Test public void updateDobProvidedSuccessOptOutNull() { // Create an record first. createTestRecord(); try { String jsonStringRequest = jsonStringFromFile("JsonTestFiles/UpdateDobProvidedOptOutNull.json"); PcqAnswerRequest answerRequest = jsonObjectFromString(jsonStringRequest); Map<String, Object> response = pcqBackEndClient.createPcqAnswer(answerRequest); assertEquals(PCQ_NOT_VALID_MSG, TEST_PCQ_ID, response.get(RESPONSE_KEY_1)); assertEquals(STATUS_CODE_INVALID_MSG, HTTP_CREATED, response.get(RESPONSE_KEY_2)); assertEquals(STATUS_INVALID_MSG, RESPONSE_CREATED_MSG, response.get(RESPONSE_KEY_3)); Optional<ProtectedCharacteristics> protectedCharacteristicsOptional = protectedCharacteristicsRepository.findById(TEST_PCQ_ID); assertFalse(protectedCharacteristicsOptional.isEmpty(), NOT_FOUND_MSG); checkAssertionsOnResponse(protectedCharacteristicsOptional.get(), answerRequest); assertLogsForKeywords(); } catch (IOException e) { log.error(IO_EXCEPTION_MSG, e); } } @Test public void dobProvidedStateDate() { // Create an record first. createTestRecord(); try { String jsonStringRequest = jsonStringFromFile("JsonTestFiles/DobProvidedStale.json"); PcqAnswerRequest answerRequest = jsonObjectFromString(jsonStringRequest); Map<String, Object> response = pcqBackEndClient.createPcqAnswer(answerRequest); assertEquals(PCQ_NOT_VALID_MSG, TEST_PCQ_ID, response.get(RESPONSE_KEY_1)); assertEquals(STATUS_CODE_INVALID_MSG, HTTP_ACCEPTED, response.get(RESPONSE_KEY_2)); assertEquals(STATUS_INVALID_MSG, RESPONSE_ACCEPTED_MSG, response.get(RESPONSE_KEY_3)); Optional<ProtectedCharacteristics> protectedCharacteristicsOptional = protectedCharacteristicsRepository.findById(TEST_PCQ_ID); assertFalse(protectedCharacteristicsOptional.isEmpty(), NOT_FOUND_MSG); assertNotEquals("DobProvided matching", protectedCharacteristicsOptional.get().getDobProvided(), answerRequest.getPcqAnswers().getDobProvided()); assertLogsForKeywords(); } catch (IOException e) { log.error(IO_EXCEPTION_MSG, e); } } @Test public void updateDobSuccess() { // Create an record first. createTestRecord(); try { String jsonStringRequest = jsonStringFromFile("JsonTestFiles/UpdateDobValid.json"); PcqAnswerRequest answerRequest = jsonObjectFromString(jsonStringRequest); Map<String, Object> response = pcqBackEndClient.createPcqAnswer(answerRequest); assertEquals(PCQ_NOT_VALID_MSG, TEST_PCQ_ID, response.get(RESPONSE_KEY_1)); assertEquals(STATUS_CODE_INVALID_MSG, HTTP_CREATED, response.get(RESPONSE_KEY_2)); assertEquals(STATUS_INVALID_MSG, RESPONSE_CREATED_MSG, response.get(RESPONSE_KEY_3)); Optional<ProtectedCharacteristics> protectedCharacteristicsOptional = protectedCharacteristicsRepository.findById(TEST_PCQ_ID); assertFalse(protectedCharacteristicsOptional.isEmpty(), NOT_FOUND_MSG); checkAssertionsOnResponse(protectedCharacteristicsOptional.get(), answerRequest); assertLogsForKeywords(); } catch (IOException e) { log.error(IO_EXCEPTION_MSG, e); } } @Test public void invalidDob() { // Create an record first. createTestRecord(); try { String jsonStringRequest = jsonStringFromFile("JsonTestFiles/invalidDob.json"); PcqAnswerRequest answerRequest = jsonObjectFromString(jsonStringRequest); Map<String, Object> response = pcqBackEndClient.createPcqAnswer(answerRequest); Map<String, Object> responseBody = jsonMapFromString((String) response.get(RESPONSE_KEY_4)); assertEquals(PCQ_NOT_VALID_MSG, TEST_PCQ_ID, responseBody.get(RESPONSE_KEY_1)); assertEquals(STATUS_CODE_INVALID_MSG, HTTP_BAD_REQUEST, responseBody.get(RESPONSE_KEY_2)); assertEquals(STATUS_INVALID_MSG, RESPONSE_INVALID_MSG, responseBody.get(RESPONSE_KEY_3)); Optional<ProtectedCharacteristics> protectedCharacteristicsOptional = protectedCharacteristicsRepository.findById(TEST_PCQ_ID); assertFalse(protectedCharacteristicsOptional.isEmpty(), NOT_FOUND_MSG); assertNotEquals("Dob not matching", protectedCharacteristicsOptional .get().getDateOfBirth(), answerRequest.getPcqAnswers().getDob()); assertLogsForKeywords(); } catch (IOException e) { log.error(IO_EXCEPTION_MSG, e); } } @Test public void updateMainLanguage() { // Create an record first. createTestRecord(); try { String jsonStringRequest = jsonStringFromFile("JsonTestFiles/MainLanguage.json"); PcqAnswerRequest answerRequest = jsonObjectFromString(jsonStringRequest); runAnswerUpdates(answerRequest); assertLogsForKeywords(); for (int i = 0; i < 3; i++) { PcqAnswers answers = answerRequest.getPcqAnswers(); answers.setLanguageMain(i); answerRequest.setPcqAnswers(answers); answerRequest.setCompletedDate(updateCompletedDate(answerRequest.getCompletedDate())); runAnswerUpdates(answerRequest); assertLogsForKeywords(); } } catch (IOException e) { log.error(IO_EXCEPTION_MSG, e); } } @Test public void updateOtherLanguage() { // Create an record first. createTestRecord(); try { String jsonStringRequest = jsonStringFromFile("JsonTestFiles/OtherLanguage.json"); PcqAnswerRequest answerRequest = jsonObjectFromString(jsonStringRequest); Map<String, Object> response = pcqBackEndClient.createPcqAnswer(answerRequest); assertEquals(PCQ_NOT_VALID_MSG, TEST_PCQ_ID, response.get(RESPONSE_KEY_1)); assertEquals(STATUS_CODE_INVALID_MSG, HTTP_CREATED, response.get(RESPONSE_KEY_2)); assertEquals(STATUS_INVALID_MSG, RESPONSE_CREATED_MSG, response.get(RESPONSE_KEY_3)); Optional<ProtectedCharacteristics> protectedCharacteristicsOptional = protectedCharacteristicsRepository.findById(TEST_PCQ_ID); assertFalse(protectedCharacteristicsOptional.isEmpty(), NOT_FOUND_MSG); checkAssertionsOnResponse(protectedCharacteristicsOptional.get(), answerRequest); assertLogsForKeywords(); } catch (IOException e) { log.error(IO_EXCEPTION_MSG, e); } } @Test public void testInjectionOtherLanguage() { // Create an record first. createMultipleTestRecords(); try { String jsonStringRequest = jsonStringFromFile("JsonTestFiles/OtherLanguageInjection.json"); PcqAnswerRequest answerRequest = jsonObjectFromString(jsonStringRequest); Map<String, Object> response = pcqBackEndClient.createPcqAnswer(answerRequest); assertEquals(PCQ_NOT_VALID_MSG, TEST_PCQ_ID, response.get(RESPONSE_KEY_1)); assertEquals(STATUS_CODE_INVALID_MSG, HTTP_CREATED, response.get(RESPONSE_KEY_2)); assertEquals(STATUS_INVALID_MSG, RESPONSE_CREATED_MSG, response.get(RESPONSE_KEY_3)); Optional<ProtectedCharacteristics> protectedCharacteristicsOptional = protectedCharacteristicsRepository.findById(TEST_PCQ_ID); assertFalse(protectedCharacteristicsOptional.isEmpty(), NOT_FOUND_MSG); checkAssertionsOnResponse(protectedCharacteristicsOptional.get(), answerRequest); assertLogsForKeywords(); protectedCharacteristicsOptional = protectedCharacteristicsRepository.findById(TEST_DUP_PCQ_ID); assertNotEquals("OtherLanguage not matching", protectedCharacteristicsOptional .get().getOtherLanguage(), answerRequest.getPcqAnswers().getLanguageOther()); } catch (IOException e) { log.error(IO_EXCEPTION_MSG, e); } } @Test public void updateEnglishLanguageLevel() { // Create an record first. createTestRecord(); try { String jsonStringRequest = jsonStringFromFile("JsonTestFiles/LanguageLevel.json"); PcqAnswerRequest answerRequest = jsonObjectFromString(jsonStringRequest); runAnswerUpdates(answerRequest); assertLogsForKeywords(); for (int i = 0; i < 5; i++) { PcqAnswers answers = answerRequest.getPcqAnswers(); answers.setEnglishLanguageLevel(i); answerRequest.setPcqAnswers(answers); answerRequest.setCompletedDate(updateCompletedDate(answerRequest.getCompletedDate())); runAnswerUpdates(answerRequest); assertLogsForKeywords(); } } catch (IOException e) { log.error(IO_EXCEPTION_MSG, e); } } @Test public void updateSex() { // Create an record first. createTestRecord(); try { String jsonStringRequest = jsonStringFromFile("JsonTestFiles/Sex.json"); PcqAnswerRequest answerRequest = jsonObjectFromString(jsonStringRequest); runAnswerUpdates(answerRequest); assertLogsForKeywords(); for (int i = 0; i < 3; i++) { PcqAnswers answers = answerRequest.getPcqAnswers(); answers.setSex(i); answerRequest.setPcqAnswers(answers); answerRequest.setCompletedDate(updateCompletedDate(answerRequest.getCompletedDate())); runAnswerUpdates(answerRequest); assertLogsForKeywords(); } } catch (IOException e) { log.error(IO_EXCEPTION_MSG, e); } } @Test public void updateGender() { // Create an record first. createTestRecord(); try { String jsonStringRequest = jsonStringFromFile("JsonTestFiles/Gender.json"); PcqAnswerRequest answerRequest = jsonObjectFromString(jsonStringRequest); runAnswerUpdates(answerRequest); assertLogsForKeywords(); for (int i = 0; i < 3; i++) { PcqAnswers answers = answerRequest.getPcqAnswers(); answers.setGenderDifferent(i); answerRequest.setPcqAnswers(answers); answerRequest.setCompletedDate(updateCompletedDate(answerRequest.getCompletedDate())); runAnswerUpdates(answerRequest); assertLogsForKeywords(); } } catch (IOException e) { log.error(IO_EXCEPTION_MSG, e); } } @Test public void updateGenderDifferent() { // Create an record first. createTestRecord(); try { String jsonStringRequest = jsonStringFromFile("JsonTestFiles/GenderOther.json"); PcqAnswerRequest answerRequest = jsonObjectFromString(jsonStringRequest); Map<String, Object> response = pcqBackEndClient.createPcqAnswer(answerRequest); assertEquals(PCQ_NOT_VALID_MSG, TEST_PCQ_ID, response.get(RESPONSE_KEY_1)); assertEquals(STATUS_CODE_INVALID_MSG, HTTP_CREATED, response.get(RESPONSE_KEY_2)); assertEquals(STATUS_INVALID_MSG, RESPONSE_CREATED_MSG, response.get(RESPONSE_KEY_3)); Optional<ProtectedCharacteristics> protectedCharacteristicsOptional = protectedCharacteristicsRepository.findById(TEST_PCQ_ID); assertFalse(protectedCharacteristicsOptional.isEmpty(), NOT_FOUND_MSG); checkAssertionsOnResponse(protectedCharacteristicsOptional.get(), answerRequest); assertLogsForKeywords(); } catch (IOException e) { log.error(IO_EXCEPTION_MSG, e); } } @Test public void updateSexuality() { // Create an record first. createTestRecord(); try { String jsonStringRequest = jsonStringFromFile("JsonTestFiles/Sexuality.json"); PcqAnswerRequest answerRequest = jsonObjectFromString(jsonStringRequest); runAnswerUpdates(answerRequest); assertLogsForKeywords(); for (int i = 0; i < 5; i++) { PcqAnswers answers = answerRequest.getPcqAnswers(); answers.setSexuality(i); answerRequest.setPcqAnswers(answers); answerRequest.setCompletedDate(updateCompletedDate(answerRequest.getCompletedDate())); runAnswerUpdates(answerRequest); assertLogsForKeywords(); } } catch (IOException e) { log.error(IO_EXCEPTION_MSG, e); } } @Test public void updateOtherSexuality() { // Create an record first. createTestRecord(); try { String jsonStringRequest = jsonStringFromFile("JsonTestFiles/SexualityOther.json"); PcqAnswerRequest answerRequest = jsonObjectFromString(jsonStringRequest); Map<String, Object> response = pcqBackEndClient.createPcqAnswer(answerRequest); assertEquals(PCQ_NOT_VALID_MSG, TEST_PCQ_ID, response.get(RESPONSE_KEY_1)); assertEquals(STATUS_CODE_INVALID_MSG, HTTP_CREATED, response.get(RESPONSE_KEY_2)); assertEquals(STATUS_INVALID_MSG, RESPONSE_CREATED_MSG, response.get(RESPONSE_KEY_3)); Optional<ProtectedCharacteristics> protectedCharacteristicsOptional = protectedCharacteristicsRepository.findById(TEST_PCQ_ID); assertFalse(protectedCharacteristicsOptional.isEmpty(), NOT_FOUND_MSG); checkAssertionsOnResponse(protectedCharacteristicsOptional.get(), answerRequest); assertLogsForKeywords(); } catch (IOException e) { log.error(IO_EXCEPTION_MSG, e); } } @Test public void testInjectionOtherSexuality() { // Create an record first. createMultipleTestRecords(); try { String jsonStringRequest = jsonStringFromFile("JsonTestFiles/SexualityOtherInjection.json"); PcqAnswerRequest answerRequest = jsonObjectFromString(jsonStringRequest); Map<String, Object> response = pcqBackEndClient.createPcqAnswer(answerRequest); assertEquals(PCQ_NOT_VALID_MSG, TEST_PCQ_ID, response.get(RESPONSE_KEY_1)); assertEquals(STATUS_CODE_INVALID_MSG, HTTP_CREATED, response.get(RESPONSE_KEY_2)); assertEquals(STATUS_INVALID_MSG, RESPONSE_CREATED_MSG, response.get(RESPONSE_KEY_3)); Optional<ProtectedCharacteristics> protectedCharacteristicsOptional = protectedCharacteristicsRepository.findById(TEST_PCQ_ID); assertFalse(protectedCharacteristicsOptional.isEmpty(), NOT_FOUND_MSG); checkAssertionsOnResponse(protectedCharacteristicsOptional.get(), answerRequest); assertLogsForKeywords(); protectedCharacteristicsOptional = protectedCharacteristicsRepository.findById(TEST_DUP_PCQ_ID); assertNotEquals("OtherSexuality not matching", protectedCharacteristicsOptional .get().getOtherSexuality(), answerRequest.getPcqAnswers().getSexualityOther()); } catch (IOException e) { log.error(IO_EXCEPTION_MSG, e); } } @Test public void updateMarried() { // Create an record first. createTestRecord(); try { String jsonStringRequest = jsonStringFromFile("JsonTestFiles/Married.json"); PcqAnswerRequest answerRequest = jsonObjectFromString(jsonStringRequest); runAnswerUpdates(answerRequest); assertLogsForKeywords(); for (int i = 0; i < 3; i++) { PcqAnswers answers = answerRequest.getPcqAnswers(); answers.setMarriage(i); answerRequest.setPcqAnswers(answers); answerRequest.setCompletedDate(updateCompletedDate(answerRequest.getCompletedDate())); runAnswerUpdates(answerRequest); assertLogsForKeywords(); } } catch (IOException e) { log.error(IO_EXCEPTION_MSG, e); } } @Test public void updateEthnicity() { // Create an record first. createTestRecord(); try { String jsonStringRequest = jsonStringFromFile("JsonTestFiles/Ethnicity.json"); PcqAnswerRequest answerRequest = jsonObjectFromString(jsonStringRequest); runAnswerUpdates(answerRequest); assertLogsForKeywords(); for (int i = 0; i < 19; i++) { PcqAnswers answers = answerRequest.getPcqAnswers(); answers.setEthnicity(i); answerRequest.setPcqAnswers(answers); answerRequest.setCompletedDate(updateCompletedDate(answerRequest.getCompletedDate())); runAnswerUpdates(answerRequest); assertLogsForKeywords(); } } catch (IOException e) { log.error(IO_EXCEPTION_MSG, e); } } @Test public void updateEthnicityOther() { // Create an record first. createTestRecord(); try { String jsonStringRequest = jsonStringFromFile("JsonTestFiles/EthnicityOther.json"); PcqAnswerRequest answerRequest = jsonObjectFromString(jsonStringRequest); Map<String, Object> response = pcqBackEndClient.createPcqAnswer(answerRequest); assertEquals(PCQ_NOT_VALID_MSG, TEST_PCQ_ID, response.get(RESPONSE_KEY_1)); assertEquals(STATUS_CODE_INVALID_MSG, HTTP_CREATED, response.get(RESPONSE_KEY_2)); assertEquals(STATUS_INVALID_MSG, RESPONSE_CREATED_MSG, response.get(RESPONSE_KEY_3)); Optional<ProtectedCharacteristics> protectedCharacteristicsOptional = protectedCharacteristicsRepository.findById(TEST_PCQ_ID); assertFalse(protectedCharacteristicsOptional.isEmpty(), NOT_FOUND_MSG); checkAssertionsOnResponse(protectedCharacteristicsOptional.get(), answerRequest); assertLogsForKeywords(); } catch (IOException e) { log.error(IO_EXCEPTION_MSG, e); } } @Test public void testInjectionOtherEthnicity() { // Create an record first. createMultipleTestRecords(); try { String jsonStringRequest = jsonStringFromFile("JsonTestFiles/EthnicityOtherInjection.json"); PcqAnswerRequest answerRequest = jsonObjectFromString(jsonStringRequest); Map<String, Object> response = pcqBackEndClient.createPcqAnswer(answerRequest); assertEquals(PCQ_NOT_VALID_MSG, TEST_PCQ_ID, response.get(RESPONSE_KEY_1)); assertEquals(STATUS_CODE_INVALID_MSG, HTTP_CREATED, response.get(RESPONSE_KEY_2)); assertEquals(STATUS_INVALID_MSG, RESPONSE_CREATED_MSG, response.get(RESPONSE_KEY_3)); Optional<ProtectedCharacteristics> protectedCharacteristicsOptional = protectedCharacteristicsRepository.findById(TEST_PCQ_ID); assertFalse(protectedCharacteristicsOptional.isEmpty(), NOT_FOUND_MSG); checkAssertionsOnResponse(protectedCharacteristicsOptional.get(), answerRequest); assertLogsForKeywords(); protectedCharacteristicsOptional = protectedCharacteristicsRepository.findById(TEST_DUP_PCQ_ID); assertNotEquals("OtherEtnicity not matching", protectedCharacteristicsOptional .get().getOtherEthnicity(), answerRequest.getPcqAnswers().getEthnicityOther()); } catch (IOException e) { log.error(IO_EXCEPTION_MSG, e); } } @Test public void updateReligion() { // Create an record first. createTestRecord(); try { String jsonStringRequest = jsonStringFromFile("JsonTestFiles/Religion.json"); PcqAnswerRequest answerRequest = jsonObjectFromString(jsonStringRequest); runAnswerUpdates(answerRequest); assertLogsForKeywords(); for (int i = 0; i < 9; i++) { PcqAnswers answers = answerRequest.getPcqAnswers(); answers.setReligion(i); answerRequest.setPcqAnswers(answers); answerRequest.setCompletedDate(updateCompletedDate(answerRequest.getCompletedDate())); runAnswerUpdates(answerRequest); assertLogsForKeywords(); } } catch (IOException e) { log.error(IO_EXCEPTION_MSG, e); } } @Test public void updateReligionOther() { // Create an record first. createTestRecord(); try { String jsonStringRequest = jsonStringFromFile("JsonTestFiles/ReligionOther.json"); PcqAnswerRequest answerRequest = jsonObjectFromString(jsonStringRequest); Map<String, Object> response = pcqBackEndClient.createPcqAnswer(answerRequest); assertEquals(PCQ_NOT_VALID_MSG, TEST_PCQ_ID, response.get(RESPONSE_KEY_1)); assertEquals(STATUS_CODE_INVALID_MSG, HTTP_CREATED, response.get(RESPONSE_KEY_2)); assertEquals(STATUS_INVALID_MSG, RESPONSE_CREATED_MSG, response.get(RESPONSE_KEY_3)); Optional<ProtectedCharacteristics> protectedCharacteristicsOptional = protectedCharacteristicsRepository.findById(TEST_PCQ_ID); assertFalse(protectedCharacteristicsOptional.isEmpty(), NOT_FOUND_MSG); checkAssertionsOnResponse(protectedCharacteristicsOptional.get(), answerRequest); assertLogsForKeywords(); } catch (IOException e) { log.error(IO_EXCEPTION_MSG, e); } } @Test public void testInjectionOtherReligion() { // Create an record first. createMultipleTestRecords(); try { String jsonStringRequest = jsonStringFromFile("JsonTestFiles/ReligionOtherInjection.json"); PcqAnswerRequest answerRequest = jsonObjectFromString(jsonStringRequest); Map<String, Object> response = pcqBackEndClient.createPcqAnswer(answerRequest); assertEquals(PCQ_NOT_VALID_MSG, TEST_PCQ_ID, response.get(RESPONSE_KEY_1)); assertEquals(STATUS_CODE_INVALID_MSG, HTTP_CREATED, response.get(RESPONSE_KEY_2)); assertEquals(STATUS_INVALID_MSG, RESPONSE_CREATED_MSG, response.get(RESPONSE_KEY_3)); Optional<ProtectedCharacteristics> protectedCharacteristicsOptional = protectedCharacteristicsRepository.findById(TEST_PCQ_ID); assertFalse(protectedCharacteristicsOptional.isEmpty(), NOT_FOUND_MSG); checkAssertionsOnResponse(protectedCharacteristicsOptional.get(), answerRequest); assertLogsForKeywords(); protectedCharacteristicsOptional = protectedCharacteristicsRepository.findById(TEST_DUP_PCQ_ID); assertNotEquals("OtherReligion not matching", protectedCharacteristicsOptional .get().getOtherReligion(), answerRequest.getPcqAnswers().getReligionOther()); } catch (IOException e) { log.error(IO_EXCEPTION_MSG, e); } } @Test public void updateDisabilityConditions() { // Create an record first. createTestRecord(); try { String jsonStringRequest = jsonStringFromFile("JsonTestFiles/DisabilityConditions.json"); PcqAnswerRequest answerRequest = jsonObjectFromString(jsonStringRequest); runAnswerUpdates(answerRequest); assertLogsForKeywords(); for (int i = 0; i < 3; i++) { PcqAnswers answers = answerRequest.getPcqAnswers(); answers.setDisabilityConditions(i); answerRequest.setPcqAnswers(answers); answerRequest.setCompletedDate(updateCompletedDate(answerRequest.getCompletedDate())); runAnswerUpdates(answerRequest); assertLogsForKeywords(); } } catch (IOException e) { log.error(IO_EXCEPTION_MSG, e); } } @Test public void updateDisabilityImpact() { // Create an record first. createTestRecord(); try { String jsonStringRequest = jsonStringFromFile("JsonTestFiles/DisabilityImpact.json"); PcqAnswerRequest answerRequest = jsonObjectFromString(jsonStringRequest); runAnswerUpdates(answerRequest); assertLogsForKeywords(); for (int i = 0; i < 4; i++) { PcqAnswers answers = answerRequest.getPcqAnswers(); answers.setDisabilityImpact(i); answerRequest.setPcqAnswers(answers); answerRequest.setCompletedDate(updateCompletedDate(answerRequest.getCompletedDate())); runAnswerUpdates(answerRequest); assertLogsForKeywords(); } } catch (IOException e) { log.error(IO_EXCEPTION_MSG, e); } } @Test public void updateDisabilityTypes() { // Create an record first. createTestRecord(); try { String jsonStringRequest = jsonStringFromFile("JsonTestFiles/DisabilityTypes.json"); PcqAnswerRequest answerRequest = jsonObjectFromString(jsonStringRequest); Map<String, Object> response = pcqBackEndClient.createPcqAnswer(answerRequest); assertEquals(PCQ_NOT_VALID_MSG, TEST_PCQ_ID, response.get(RESPONSE_KEY_1)); assertEquals(STATUS_CODE_INVALID_MSG, HTTP_CREATED, response.get(RESPONSE_KEY_2)); assertEquals(STATUS_INVALID_MSG, RESPONSE_CREATED_MSG, response.get(RESPONSE_KEY_3)); Optional<ProtectedCharacteristics> protectedCharacteristicsOptional = protectedCharacteristicsRepository.findById(TEST_PCQ_ID); assertFalse(protectedCharacteristicsOptional.isEmpty(), NOT_FOUND_MSG); checkAssertionsOnResponse(protectedCharacteristicsOptional.get(), answerRequest); assertLogsForKeywords(); } catch (IOException e) { log.error(IO_EXCEPTION_MSG, e); } } @Test public void updateOtherDisabilityDetails() { // Create an record first. createTestRecord(); try { String jsonStringRequest = jsonStringFromFile("JsonTestFiles/DisabilityOtherDetails.json"); PcqAnswerRequest answerRequest = jsonObjectFromString(jsonStringRequest); Map<String, Object> response = pcqBackEndClient.createPcqAnswer(answerRequest); assertEquals(PCQ_NOT_VALID_MSG, TEST_PCQ_ID, response.get(RESPONSE_KEY_1)); assertEquals(STATUS_CODE_INVALID_MSG, HTTP_CREATED, response.get(RESPONSE_KEY_2)); assertEquals(STATUS_INVALID_MSG, RESPONSE_CREATED_MSG, response.get(RESPONSE_KEY_3)); Optional<ProtectedCharacteristics> protectedCharacteristicsOptional = protectedCharacteristicsRepository.findById(TEST_PCQ_ID); assertFalse(protectedCharacteristicsOptional.isEmpty(), NOT_FOUND_MSG); checkAssertionsOnResponse(protectedCharacteristicsOptional.get(), answerRequest); assertLogsForKeywords(); } catch (IOException e) { log.error(IO_EXCEPTION_MSG, e); } } @Test public void testInjectionOtherDisability() { // Create an record first. createMultipleTestRecords(); try { String jsonStringRequest = jsonStringFromFile("JsonTestFiles/DisabilityOtherInjection.json"); PcqAnswerRequest answerRequest = jsonObjectFromString(jsonStringRequest); Map<String, Object> response = pcqBackEndClient.createPcqAnswer(answerRequest); assertEquals(PCQ_NOT_VALID_MSG, TEST_PCQ_ID, response.get(RESPONSE_KEY_1)); assertEquals(STATUS_CODE_INVALID_MSG, HTTP_CREATED, response.get(RESPONSE_KEY_2)); assertEquals(STATUS_INVALID_MSG, RESPONSE_CREATED_MSG, response.get(RESPONSE_KEY_3)); Optional<ProtectedCharacteristics> protectedCharacteristicsOptional = protectedCharacteristicsRepository.findById(TEST_PCQ_ID); assertFalse(protectedCharacteristicsOptional.isEmpty(), NOT_FOUND_MSG); checkAssertionsOnResponse(protectedCharacteristicsOptional.get(), answerRequest); assertLogsForKeywords(); protectedCharacteristicsOptional = protectedCharacteristicsRepository.findById(TEST_DUP_PCQ_ID); assertNotEquals("OtherDisabilityDetails not matching", protectedCharacteristicsOptional .get().getOtherDisabilityDetails(), answerRequest.getPcqAnswers().getDisabilityConditionOther()); } catch (IOException e) { log.error(IO_EXCEPTION_MSG, e); } } @Test public void updatePregnancy() { // Create an record first. createTestRecord(); try { String jsonStringRequest = jsonStringFromFile("JsonTestFiles/Pregnancy.json"); PcqAnswerRequest answerRequest = jsonObjectFromString(jsonStringRequest); runAnswerUpdates(answerRequest); assertLogsForKeywords(); for (int i = 0; i < 3; i++) { PcqAnswers answers = answerRequest.getPcqAnswers(); answers.setPregnancy(i); answerRequest.setPcqAnswers(answers); answerRequest.setCompletedDate(updateCompletedDate(answerRequest.getCompletedDate())); runAnswerUpdates(answerRequest); assertLogsForKeywords(); } } catch (IOException e) { log.error(IO_EXCEPTION_MSG, e); } } @Test public void invalidPregnancy() { // Create an record first. createTestRecord(); try { String jsonStringRequest = jsonStringFromFile("JsonTestFiles/InvalidPregnancy.json"); PcqAnswerRequest answerRequest = jsonObjectFromString(jsonStringRequest); Map<String, Object> response = pcqBackEndClient.createPcqAnswer(answerRequest); Map<String, Object> responseBody = jsonMapFromString((String) response.get(RESPONSE_KEY_4)); assertEquals(PCQ_NOT_VALID_MSG, TEST_PCQ_ID, responseBody.get(RESPONSE_KEY_1)); assertEquals(STATUS_CODE_INVALID_MSG, HTTP_BAD_REQUEST, responseBody.get(RESPONSE_KEY_2)); assertEquals(STATUS_INVALID_MSG, RESPONSE_INVALID_MSG, responseBody.get(RESPONSE_KEY_3)); Optional<ProtectedCharacteristics> protectedCharacteristicsOptional = protectedCharacteristicsRepository.findById(TEST_PCQ_ID); assertFalse(protectedCharacteristicsOptional.isEmpty(), NOT_FOUND_MSG); assertNotEquals("Pregnancy not matching", protectedCharacteristicsOptional .get().getPregnancy(), answerRequest.getPcqAnswers().getPregnancy()); assertLogsForKeywords(); } catch (IOException e) { log.error(IO_EXCEPTION_MSG, e); } } @Test public void testSqlInjection() { // Create an record first. createTestRecord(); Optional<ProtectedCharacteristics> protectedCharacteristicsOptional = protectedCharacteristicsRepository.findById(TEST_PCQ_ID + "'; DROP TABLE protected_characteristics;"); assertTrue(protectedCharacteristicsOptional.isEmpty(), NOT_FOUND_MSG); protectedCharacteristicsOptional = protectedCharacteristicsRepository.findById(TEST_PCQ_ID); assertNotNull("Answer record not found", protectedCharacteristicsOptional.get()); assertEquals("PCQ Id not matching", protectedCharacteristicsOptional.get().getPcqId(), TEST_PCQ_ID); assertLogsForKeywords(); } private void createTestRecord() { PcqAnswerRequest testRequest = createAnswerRequestForTest(TEST_PCQ_ID); pcqBackEndClient.createPcqAnswer(testRequest); } private void createMultipleTestRecords() { PcqAnswerRequest testRequest = createAnswerRequestForTest(TEST_PCQ_ID); pcqBackEndClient.createPcqAnswer(testRequest); testRequest = createAnswerRequestForTest(TEST_DUP_PCQ_ID); pcqBackEndClient.createPcqAnswer(testRequest); } public PcqAnswerRequest createAnswerRequestForTest(String pcqId) { PcqAnswerRequest answerRequest = new PcqAnswerRequest(); answerRequest.setPcqId(pcqId); answerRequest.setCaseId("CCD-Case-2"); answerRequest.setPartyId("23"); answerRequest.setChannel(1); answerRequest.setServiceId("PROBATE"); answerRequest.setCompletedDate("2020-03-05T09:13:45.000Z"); answerRequest.setActor("RESPONDENT"); answerRequest.setVersionNo(1); PcqAnswers answers = new PcqAnswers(); answers.setDobProvided(1); answerRequest.setPcqAnswers(answers); return answerRequest; } private void assertLogsForKeywords() { assertTrue(capture.getAll().contains("Co-Relation Id : " + CO_RELATION_ID_FOR_TEST), "Co-Relation Id was not logged in log files."); } }
3e1b05f430056f989d74ac7861a798ed4a1b9705
1,595
java
Java
ext/Parser_SUPPLE/prolog-impls/plcafe/gen-src/shef/nlp/supple/prolog/cafe/PRED_compile_last_grammar_1.java
TeamSPoon/logicmoo_nlu
5c3e5013a3048da7d68a8a43476ad84d3ea4bb47
[ "MIT" ]
6
2020-01-27T12:08:02.000Z
2020-02-28T19:30:28.000Z
pack/logicmoo_nlu/prolog/Parser_SUPPLE/prolog-impls/plcafe/gen-src/shef/nlp/supple/prolog/cafe/PRED_compile_last_grammar_1.java
logicmoo/old_logicmoo_workspace
44025b6e389e2f2f7d86b46c1301cab0604bba26
[ "MIT" ]
1
2020-02-02T13:12:34.000Z
2020-02-02T13:12:34.000Z
pack/logicmoo_nlu/prolog/Parser_SUPPLE/prolog-impls/plcafe/gen-src/shef/nlp/supple/prolog/cafe/PRED_compile_last_grammar_1.java
logicmoo/old_logicmoo_workspace
44025b6e389e2f2f7d86b46c1301cab0604bba26
[ "MIT" ]
null
null
null
27.586207
71
0.629375
11,445
package shef.nlp.supple.prolog.cafe; import jp.ac.kobe_u.cs.prolog.lang.*; import jp.ac.kobe_u.cs.prolog.builtin.*; /* * *** Please do not edit ! *** * @(#) PRED_compile_last_grammar_1.java * @procedure compile_last_grammar/1 in compile_grammar.pl */ /* * @version Prolog Cafe 0.8 November 2003 * @author Mutsunori Banbara (dycjh@example.com) * @author Naoyuki Tamura (dycjh@example.com) */ public class PRED_compile_last_grammar_1 extends Predicate { static SymbolTerm f1 = SymbolTerm.makeSymbol("best_parse_cats", 2); static SymbolTerm f3 = SymbolTerm.makeSymbol("best_parse_cats", 1); public Term arg1; public PRED_compile_last_grammar_1(Term a1, Predicate cont) { arg1 = a1; this.cont = cont; } public PRED_compile_last_grammar_1(){} public void setArgument(Term[] args, Predicate cont) { arg1 = args[0]; this.cont = cont; } public Predicate exec(Prolog engine) { engine.setB0(); Term a1, a2, a3, a4; Predicate p1, p2, p3; a1 = arg1.dereference(); a2 = new VariableTerm(engine); Term[] h2 = {a1, a2}; a3 = new StructureTerm(f1, h2); Term[] h4 = {new VariableTerm(engine)}; a4 = new StructureTerm(f3, h4); p1 = new PRED_retractall_1(a4, cont); p2 = new PRED_compile_grammar3_1(a1, p1); p3 = new PRED_assert_1(a3, p2); return new PRED_best_parse_cats_1(a2, p3); } public int arity() { return 1; } public String toString() { return "compile_last_grammar(" + arg1 + ")"; } }
3e1b06a8d40c78040f330de245e91abe38ba5545
2,140
java
Java
kiilin-admin/src/main/java/com/kiilin/modules/controller/SysLoginController.java
kkwwang/kiilin
e089b57300dd048b1933a87c8716d3d192da377c
[ "Apache-2.0" ]
1
2018-08-28T03:28:17.000Z
2018-08-28T03:28:17.000Z
kiilin-admin/src/main/java/com/kiilin/modules/controller/SysLoginController.java
kkwwang/kiilin
e089b57300dd048b1933a87c8716d3d192da377c
[ "Apache-2.0" ]
null
null
null
kiilin-admin/src/main/java/com/kiilin/modules/controller/SysLoginController.java
kkwwang/kiilin
e089b57300dd048b1933a87c8716d3d192da377c
[ "Apache-2.0" ]
null
null
null
27.831169
89
0.680355
11,446
package com.kiilin.modules.controller; import com.kiilin.common.abstracts.result.ServiceResult; import com.kiilin.common.annotation.SysLog; import com.kiilin.common.redis.RedisKeys; import com.kiilin.common.redis.RedisUtils; import com.kiilin.common.shiro.ShiroUtils; import lombok.extern.slf4j.Slf4j; import org.apache.shiro.authc.*; import org.apache.shiro.subject.Subject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; /** * 登录相关 * * @author chenshun * @email nnheo@example.com * @date 2016年11月10日 下午1:15:31 */ @RestController @Slf4j public class SysLoginController { @Autowired RedisUtils redisUtils; /** * 登录 */ @PostMapping(value = "/login") @SysLog("用户登录") public ServiceResult login(String loginName, String password) { try { Subject subject = ShiroUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken(loginName, password); subject.login(token); // 删除权限缓存 防止出现脏数据 String userId = ShiroUtils.getUserId(); redisUtils.delete(RedisKeys.PERMS_LIST + userId); } catch (UnknownAccountException e) { return ServiceResult.error(e.getMessage()); } catch (IncorrectCredentialsException e) { return ServiceResult.error("密码输入有误"); } catch (LockedAccountException e) { return ServiceResult.error(e.getMessage()); } catch (AuthenticationException e) { return ServiceResult.error("账户验证失败"); } return ServiceResult.success(); } /** * 退出 */ @GetMapping(value = "/logout") public ModelAndView logout() { // 删除权限缓存 防止出现脏数据 String userId = ShiroUtils.getUserId(); redisUtils.delete(RedisKeys.PERMS_LIST + userId); ShiroUtils.logout(); return new ModelAndView("redirect:/"); } }
3e1b0ab0c59732ccc4729d80db10943e0a1fc4a4
325
java
Java
spring-boot-thymeleaf/spring-boot-thymeleaf-layout/src/test/java/com/neo/TLayoutApplicationTests.java
1179175893/springBoot
dfbb9f2e741b3bd93e61d21f3aa30237546a26a7
[ "MIT" ]
5
2020-07-28T13:20:49.000Z
2022-01-17T15:34:48.000Z
spring-boot-examples/spring-boot-thymeleaf/spring-boot-thymeleaf-layout/src/test/java/com/neo/TLayoutApplicationTests.java
tinntetuki/tinntetuki.github.io
acc0b29588064f73a9ed55c29da5227a3d76344f
[ "Apache-2.0" ]
null
null
null
spring-boot-examples/spring-boot-thymeleaf/spring-boot-thymeleaf-layout/src/test/java/com/neo/TLayoutApplicationTests.java
tinntetuki/tinntetuki.github.io
acc0b29588064f73a9ed55c29da5227a3d76344f
[ "Apache-2.0" ]
null
null
null
19.117647
60
0.806154
11,447
package com.neo; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class TLayoutApplicationTests { @Test public void contextLoads() { } }
3e1b0b27836883db67be43a04b24cddb8c3c9d76
1,218
java
Java
sdk/resources/mgmt/src/main/java/com/azure/management/resources/DeploymentWhatIfProperties.java
Azure-Fluent/azure-sdk-for-java
c123e88d3e78b3d1b81a977aae0646220457f2c1
[ "MIT" ]
1
2020-10-05T18:51:27.000Z
2020-10-05T18:51:27.000Z
sdk/resources/mgmt/src/main/java/com/azure/management/resources/DeploymentWhatIfProperties.java
Azure-Fluent/azure-sdk-for-java
c123e88d3e78b3d1b81a977aae0646220457f2c1
[ "MIT" ]
24
2020-05-27T05:21:27.000Z
2021-06-25T15:37:42.000Z
sdk/resources/mgmt/src/main/java/com/azure/management/resources/DeploymentWhatIfProperties.java
Azure-Fluent/azure-sdk-for-java
c123e88d3e78b3d1b81a977aae0646220457f2c1
[ "MIT" ]
null
null
null
31.230769
99
0.728243
11,448
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.management.resources; import com.azure.core.annotation.Fluent; import com.fasterxml.jackson.annotation.JsonProperty; /** The DeploymentWhatIfProperties model. */ @Fluent public final class DeploymentWhatIfProperties extends DeploymentProperties { /* * Optional What-If operation settings. */ @JsonProperty(value = "whatIfSettings") private DeploymentWhatIfSettings whatIfSettings; /** * Get the whatIfSettings property: Optional What-If operation settings. * * @return the whatIfSettings value. */ public DeploymentWhatIfSettings whatIfSettings() { return this.whatIfSettings; } /** * Set the whatIfSettings property: Optional What-If operation settings. * * @param whatIfSettings the whatIfSettings value to set. * @return the DeploymentWhatIfProperties object itself. */ public DeploymentWhatIfProperties withWhatIfSettings(DeploymentWhatIfSettings whatIfSettings) { this.whatIfSettings = whatIfSettings; return this; } }
3e1b0b52cb76fa218ff651fc537778597feea0d9
207
java
Java
snowjena-ticket-server/src/main/java/com/github/onblog/snowjenaticketserver/token/service/TokenService.java
Mu-L/SnowJena
22f8a35e1d2709c84d4a40cc1e38062931610f3c
[ "Apache-2.0" ]
250
2020-08-05T04:32:39.000Z
2022-03-29T03:28:52.000Z
snowjena-ticket-server/src/main/java/com/github/onblog/snowjenaticketserver/token/service/TokenService.java
Mu-L/SnowJena
22f8a35e1d2709c84d4a40cc1e38062931610f3c
[ "Apache-2.0" ]
5
2020-08-07T09:52:46.000Z
2021-12-25T13:59:13.000Z
snowjena-ticket-server/src/main/java/com/github/onblog/snowjenaticketserver/token/service/TokenService.java
Mu-L/SnowJena
22f8a35e1d2709c84d4a40cc1e38062931610f3c
[ "Apache-2.0" ]
61
2020-08-03T03:28:34.000Z
2022-02-11T07:44:20.000Z
23
61
0.826087
11,449
package com.github.onblog.snowjenaticketserver.token.service; import com.github.onblog.commoon.entity.RateLimiterRule; public interface TokenService { Object token(RateLimiterRule rateLimiterRule); }
3e1b0b60d38a522e3a31c0f4d0bc393bcc4e1a8d
5,911
java
Java
src/test/java/com/dbschema/SimpleTest.java
liquibase/mongodb-jdbc-driver
15e6e9608cac8e999849fe8d760264a1e72d4b86
[ "BSD-3-Clause" ]
null
null
null
src/test/java/com/dbschema/SimpleTest.java
liquibase/mongodb-jdbc-driver
15e6e9608cac8e999849fe8d760264a1e72d4b86
[ "BSD-3-Clause" ]
null
null
null
src/test/java/com/dbschema/SimpleTest.java
liquibase/mongodb-jdbc-driver
15e6e9608cac8e999849fe8d760264a1e72d4b86
[ "BSD-3-Clause" ]
1
2020-09-02T18:17:05.000Z
2020-09-02T18:17:05.000Z
36.94375
158
0.565556
11,450
package com.dbschema; import com.dbschema.wrappers.WrappedMongoDatabase; import org.junit.Before; import org.junit.Test; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class SimpleTest extends AbstractTestCase{ private Connection con; private static final String urlWithAuth = "jdbc:mongodb://admin:fictivpwd@localhost:27017/local?authSource=local&connectTimeoutMS=1000"; private static final String urlWithoutAuth = "jdbc:mongodb://localhost"; @Before public void setUp() throws ClassNotFoundException, SQLException { Class.forName("com.dbschema.MongoJdbcDriver"); con = DriverManager.getConnection( urlWithoutAuth, null, null); /* Statement stmt=con.createStatement(); stmt.execute("local.words.drop();"); stmt.execute("local.words.insertOne({word: 'sample', qty:2});"); stmt.execute("local.words.insertOne({word: 'sample', qty:5});"); stmt.close(); */ } @Test public void testListDatabases() { MongoConnection mongoConnection = (MongoConnection) this.con; mongoConnection.client.listDatabaseNames(); WrappedMongoDatabase mongoDatabase = mongoConnection.client.getDatabase("localaaa"); for( String dbName: mongoDatabase.listCollectionNames() ){ System.out.println(dbName); } } @Test public void testFind() throws Exception { Statement stmt=con.createStatement(); printResultSet( stmt.executeQuery("local.products.find()") ); stmt.close(); } @Test public void testInsert2() throws Exception { Statement stmt=con.createStatement(); printResultSet( stmt.executeQuery("" + "local.cities3.drop();" + "local.cities3.insert(\n" + "{ \"country_id\" : \"USA\", \n" + " \"city_name\" : \"San Francisco\", \n" + " \"brother_cities\" : [\n" + " \"Urban\", \"Paris\"\n" + " ], \n" + " \"suburbs\" : [\n" + " {\n" + " \"name\" : \"Scarsdale\"\n" + " }, \n" + " {\n" + " \"name\" : \"North Hills\"\n" + " } ]\n" + " })") ); con.commit(); stmt.close(); } @Test public void testFindAnd() throws Exception { Statement stmt=con.createStatement(); printResultSet( stmt.executeQuery("local.sample.find({ $and: [ {'name':'DbSchema Free Version'}, {'name':'DbSchema Free Version'} ] } )") ); stmt.close(); } @Test public void testFindAndOr() throws Exception { Statement stmt=con.createStatement(); printResultSet( stmt.executeQuery("local.sample.find({'likes': {$gt:10}, $or: [{'by': 'tutorials point'}, {'title': 'MongoDB Overview' }]})") ); stmt.close(); } @Test public void testUpdate() throws Exception { Statement stmt=con.createStatement(); printResultSet( stmt.executeQuery("local.sample.update({'title':'MongoDB Overview'},{$set:{'title':'New MongoDB Tutorial'}})") ); stmt.close(); } @Test public void testFindId() throws Exception { /* BasicDBObject query = new BasicDBObject(); query.put("_id", new ObjectId("5dd593595f94074908de3db9")); printResultSet( new ResultSetIterator(((MongoConnection)con).client.getDatabase("local").getCollection("products").find( query), true)); */ Statement stmt=con.createStatement(); printResultSet( stmt.executeQuery("local.products.find({_id:'5f3291806abad86535411518'})" ) ); stmt.close(); } @Test public void testInsert() throws Exception { Statement stmt=con.createStatement(); printResultSet( stmt.executeQuery("local.sample2.insert({ 'firstname' : 'Anna', 'lastname' : 'Pruteanu' })") ); stmt.close(); } @Test public void testISODate() throws Exception { Statement stmt=con.createStatement(); printResultSet( stmt.executeQuery("local.sample2.insert({'shopId':'baaacd90d36e11e9adb40a8baad32c5a','date':ISODate('2019-12-25T07:23:18.408Z')})") ); stmt.close(); } @Test public void testFindGt() throws Exception { Statement stmt=con.createStatement(); printResultSet( stmt.executeQuery("local.words.find( {qty:{$gt: 4}})")); stmt.close(); } @Test public void testOID() throws Exception { Statement stmt=con.createStatement(); printResultSet( stmt.executeQuery("db.test.insert({\"_id\":ObjectId(\"5e95cfecdfa8c111a4b2a53a\"), \"name\":\"first\"})")); stmt.close(); } private static final String[] aggregateScript = new String[]{ "db.foodCool.drop();", "db.foodColl.insert([\n"+ " { category: \"cake\", type: \"chocolate\", qty: 10 },\n"+ " { category: \"cake\", type: \"ice cream\", qty: 25 },\n"+ " { category: \"pie\", type: \"boston cream\", qty: 20 },\n"+ " { category: \"pie\", type: \"blueberry\", qty: 15 }\n"+ "]);", "db.foodColl.createIndex( { qty: 1, type: 1 } );", "db.foodColl.createIndex( { qty: 1, category: 1 } );", "db.foodColl.aggregate(\n"+ " [ { $sort: { qty: 1 }}, { $match: { category: \"cake\", qty: 10 } }, { $sort: { type: -1 } } ]" + ")" }; @Test public void testAggregate() throws Exception { Statement stmt = con.createStatement(); for ( String str : aggregateScript ) { printResultSet( stmt.executeQuery(str) ); } } }
3e1b0b6cf79e115cfcea29f91b6f845f4a6ea57b
599
java
Java
jaxws-ri/tests/unit/testcases/fromjava/default_pkg/AddNumbersException.java
eheeren/metro-jax-ws
16810e6f6a3dad5c4c4ef08fd76130a68dc08fea
[ "BSD-3-Clause" ]
40
2018-10-05T10:39:25.000Z
2022-03-31T07:27:39.000Z
jaxws-ri/tests/unit/testcases/fromjava/default_pkg/AddNumbersException.java
eheeren/metro-jax-ws
16810e6f6a3dad5c4c4ef08fd76130a68dc08fea
[ "BSD-3-Clause" ]
98
2018-10-18T12:20:48.000Z
2022-03-26T13:43:10.000Z
jaxws-ri/tests/unit/testcases/fromjava/default_pkg/AddNumbersException.java
eheeren/metro-jax-ws
16810e6f6a3dad5c4c4ef08fd76130a68dc08fea
[ "BSD-3-Clause" ]
40
2018-10-17T20:43:51.000Z
2022-03-10T18:01:31.000Z
26.043478
78
0.694491
11,451
/* * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0, which is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ public class AddNumbersException extends Exception { String detail; public AddNumbersException(String message, String detail) { super(message); this.detail = detail; } public String getDetail() { return detail; } }
3e1b0c270ea9e09d8ca41a2048910bf76c7079d3
1,461
java
Java
webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/HideDataView.java
Valandur/Web-API
2fcfbe7ecbe4cc6f5d76bbb97d061076767e5b44
[ "MIT" ]
70
2016-11-08T18:41:49.000Z
2022-01-01T07:28:57.000Z
webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/HideDataView.java
Valandur/Web-API
2fcfbe7ecbe4cc6f5d76bbb97d061076767e5b44
[ "MIT" ]
139
2017-01-06T19:25:48.000Z
2022-02-20T18:13:00.000Z
webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/HideDataView.java
Valandur/Web-API
2fcfbe7ecbe4cc6f5d76bbb97d061076767e5b44
[ "MIT" ]
21
2017-03-25T16:28:09.000Z
2021-12-28T16:58:43.000Z
35.634146
80
0.738535
11,452
package valandur.webapi.serialize.view.data; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.spongepowered.api.data.manipulator.mutable.item.HideData; import valandur.webapi.serialize.BaseView; @ApiModel("HideData") public class HideDataView extends BaseView<HideData> { @ApiModelProperty("Gets the 'attributes hidden' state of the item stack") public boolean hideAttributes; @ApiModelProperty("Gets the 'can destory hidden' state of the item stack") public boolean hideCanDestroy; @ApiModelProperty("Gets the 'can place hidden' state of the item stack") public boolean hideCanPlace; @ApiModelProperty("Gets the 'enchantments hidden' state of the item stack") public boolean hideEnchantments; @ApiModelProperty("Gets the 'miscellaneous hidden' state of the item stack") public boolean hideMiscellaneous; @ApiModelProperty("Gets the 'unbreakable hidden' state of the item stack") public boolean hideUnbreakable; public HideDataView(HideData value) { super(value); this.hideAttributes = value.hideAttributes().get(); this.hideCanDestroy = value.hideCanDestroy().get(); this.hideCanPlace = value.hideCanPlace().get(); this.hideEnchantments = value.hideEnchantments().get(); this.hideMiscellaneous = value.hideMiscellaneous().get(); this.hideUnbreakable = value.hideUnbreakable().get(); } }
3e1b0c647db57a41ac65dc00811be698e7a692e2
1,599
java
Java
src/main/java/io/github/reflxction/hypixelapi/core/implementation/game/FinishedParkourImpl.java
ReflxctionDev/SimpleHypixelAPI
8eff50ed452a3f188d8cd4cce909446422dbe8ec
[ "Apache-2.0" ]
7
2019-07-31T19:32:56.000Z
2021-07-14T20:45:59.000Z
src/main/java/io/github/reflxction/hypixelapi/core/implementation/game/FinishedParkourImpl.java
Revxrsal/SimpleHypixelAPI
8eff50ed452a3f188d8cd4cce909446422dbe8ec
[ "Apache-2.0" ]
null
null
null
src/main/java/io/github/reflxction/hypixelapi/core/implementation/game/FinishedParkourImpl.java
Revxrsal/SimpleHypixelAPI
8eff50ed452a3f188d8cd4cce909446422dbe8ec
[ "Apache-2.0" ]
null
null
null
27.101695
75
0.670419
11,453
/* * * Copyright 2018-2019 github.com/ReflxctionDev * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.reflxction.hypixelapi.core.implementation.game; import io.github.reflxction.hypixelapi.game.FinishedParkour; import java.util.Date; /** * Class implementation for {@link FinishedParkour} */ public class FinishedParkourImpl implements FinishedParkour { private Date timeStart; private long timeTook; /** * Returns the time the player started this parkour * * @return The time the player started this parkour */ @Override public Date getStartingTime() { return timeStart; } /** * Returns the time this parkour took to be finished, in milliseconds. * * @return The time this parkour took to be finished */ @Override public long getTimeTook() { return timeTook; } @Override public String toString() { return "FinishedParkourImpl{" + "timeStart=" + timeStart + ", timeTook=" + timeTook + '}'; } }
3e1b0da36caa342fbc5894a4727704375cb84333
8,484
java
Java
app/src/main/java/com/tlongdev/bktf/interactor/TlongdevPriceListInteractor.java
Longi94/bptf
88f7c65941ea10ec2ab0899f01d29f1e40c7bce1
[ "Apache-2.0" ]
9
2015-07-25T04:55:37.000Z
2020-11-05T11:46:25.000Z
app/src/main/java/com/tlongdev/bktf/interactor/TlongdevPriceListInteractor.java
Sebby37/bptf
88f7c65941ea10ec2ab0899f01d29f1e40c7bce1
[ "Apache-2.0" ]
49
2015-02-24T16:23:34.000Z
2020-05-13T11:39:15.000Z
app/src/main/java/com/tlongdev/bktf/interactor/TlongdevPriceListInteractor.java
Sebby37/bptf
88f7c65941ea10ec2ab0899f01d29f1e40c7bce1
[ "Apache-2.0" ]
4
2015-07-25T04:55:39.000Z
2021-02-27T08:44:11.000Z
34.348178
118
0.61115
11,454
package com.tlongdev.bktf.interactor; import android.app.Application; import android.content.ContentValues; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.util.Log; import com.tlongdev.bktf.BptfApplication; import com.tlongdev.bktf.R; import com.tlongdev.bktf.data.DatabaseContract.PriceEntry; import com.tlongdev.bktf.flatbuffers.prices.Price; import com.tlongdev.bktf.flatbuffers.prices.Prices; import com.tlongdev.bktf.model.Item; import com.tlongdev.bktf.model.Quality; import com.tlongdev.bktf.util.HttpUtil; import com.tlongdev.bktf.util.Utility; import org.apache.commons.io.IOUtils; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.Vector; import javax.inject.Inject; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; /** * Task for fetching all data for prices database and updating it in the background. */ public class TlongdevPriceListInteractor extends AsyncTask<Void, Integer, Integer> { private static final String LOG_TAG = TlongdevPriceListInteractor.class.getSimpleName(); @Inject SharedPreferences mPrefs; @Inject SharedPreferences.Editor mEditor; @Inject Application mContext; //Whether it's an update or full database download private boolean updateDatabase; //Whether it was a user initiated update private boolean manualSync; //Error message to be displayed to the user private String errorMessage; //The listener that will be notified when the fetching finishes private Callback mCallback; //the variable that contains the birth time of the youngest price private int latestUpdate = 0; private int rowsInserted = 0; public TlongdevPriceListInteractor(BptfApplication application, boolean updateDatabase, boolean manualSync, Callback callback) { application.getInteractorComponent().inject(this); this.updateDatabase = updateDatabase; this.manualSync = manualSync; this.mCallback = callback; } /** * {@inheritDoc} */ @Override protected Integer doInBackground(Void... params) { return run(); } public Integer run() { if (System.currentTimeMillis() - mPrefs.getLong(mContext .getString(R.string.pref_last_price_list_update), 0) < 3600000L && !manualSync) { //This task ran less than an hour ago and wasn't a manual sync, nothing to do. return 0; } try { //Get the youngest price from the database. If it's an update only prices newer than this //will be updated to speed up the update and reduce data usage. if (updateDatabase) { String[] columns = {PriceEntry.COLUMN_LAST_UPDATE}; Cursor cursor = mContext.getContentResolver().query( PriceEntry.CONTENT_URI, columns, null, null, PriceEntry.COLUMN_LAST_UPDATE + " DESC LIMIT 1" ); if (cursor != null) { if (cursor.moveToFirst()) latestUpdate = cursor.getInt(0); cursor.close(); } } Uri uri = Uri.parse(mContext.getString(R.string.main_host) + "/bptf/fbs/prices").buildUpon() .appendQueryParameter("since", String.valueOf(latestUpdate)) .build(); OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(uri.toString()) .build(); Response response = client.newCall(request).execute(); if (response.body() != null) { return parseFlatBuffer(response.body().byteStream()); } else if (response.code() >= 400) { errorMessage = HttpUtil.buildErrorMessage(response); } return -1; } catch (IOException e) { //There was a network error errorMessage = e.getMessage(); Log.e(LOG_TAG, "network error", e); } return -1; } private Integer parseFlatBuffer(InputStream inputStream) throws IOException { ByteBuffer buffer = ByteBuffer.wrap(IOUtils.toByteArray(inputStream)); Prices pricesBuf = Prices.getRootAsPrices(buffer); Vector<ContentValues> cVVector = new Vector<>(); for (int i = 0; i < pricesBuf.pricesLength(); i++) { Price priceBuf = pricesBuf.prices(i); ContentValues values = buildContentValues(priceBuf); cVVector.add(values); } if (cVVector.size() > 0) { ContentValues[] cvArray = new ContentValues[cVVector.size()]; cVVector.toArray(cvArray); //Insert all the data into the database rowsInserted = mContext.getContentResolver() .bulkInsert(PriceEntry.CONTENT_URI, cvArray); Log.v(LOG_TAG, "inserted " + rowsInserted + " rows into prices table"); } return 0; } private ContentValues buildContentValues(Price priceBuf) { ContentValues values = new ContentValues(); int defindex = priceBuf.defindex(); int quality = (int) priceBuf.quality(); boolean tradable = priceBuf.tradable(); boolean craftable = priceBuf.craftable(); double value = priceBuf.price(); double high = priceBuf.priceMax(); double raw = priceBuf.raw(); Item item = new Item(); item.setDefindex(defindex); defindex = item.getFixedDefindex(); values.put(PriceEntry.COLUMN_DEFINDEX, defindex); values.put(PriceEntry.COLUMN_ITEM_QUALITY, quality); values.put(PriceEntry.COLUMN_ITEM_TRADABLE, tradable); values.put(PriceEntry.COLUMN_ITEM_CRAFTABLE, craftable); values.put(PriceEntry.COLUMN_PRICE_INDEX, priceBuf.priceIndex()); values.put(PriceEntry.COLUMN_AUSTRALIUM, priceBuf.australium()); values.put(PriceEntry.COLUMN_CURRENCY, priceBuf.currency()); values.put(PriceEntry.COLUMN_PRICE, value); values.put(PriceEntry.COLUMN_PRICE_HIGH, high); values.put(PriceEntry.COLUMN_LAST_UPDATE, priceBuf.updateTs()); values.put(PriceEntry.COLUMN_DIFFERENCE, (double) priceBuf.difference()); values.put(PriceEntry.COLUMN_WEAPON_WEAR, 0); if (quality == Quality.UNIQUE && tradable && craftable) { if (defindex == 143) { //buds Utility.putDouble(mEditor, mContext.getString(R.string.pref_buds_raw), raw); mEditor.apply(); } else if (defindex == 5002) { //metal if (high > value) { //If the metal has a high price, save the average as raw. Utility.putDouble(mEditor, mContext.getString(R.string.pref_metal_raw_usd), ((value + high) / 2)); } else { //save as raw price Utility.putDouble(mEditor, mContext.getString(R.string.pref_metal_raw_usd), value); } mEditor.apply(); } else if (defindex == 5021) { //key Utility.putDouble(mEditor, mContext.getString(R.string.pref_key_raw), raw); mEditor.apply(); } } return values; } /** * {@inheritDoc} */ @Override protected void onPostExecute(Integer integer) { if (mCallback != null) { if (integer >= 0) { //Notify the listener that the update finished mCallback.onPriceListFinished(rowsInserted, latestUpdate); } else { mCallback.onPriceListFailed(errorMessage); } } } public int getRowsInserted() { return rowsInserted; } public long getSinceParam() { return latestUpdate; } /** * Listener interface */ public interface Callback { /** * Notify the listener, that the fetching has stopped. */ void onPriceListFinished(int newItems, long sinceParam); void onPriceListFailed(String errorMessage); } }
3e1b0e0ca35b50a48bfdc166d5e50c0b1d333e8b
950
java
Java
java/java-codec/src/main/java/org/cloudburstmc/protocol/java/packet/play/serverbound/BlockEntityTagQueryPacket.java
D3ATHBRINGER13/Protocol
3bc6e1be9888736d09cd0cdeb4aff41e422e9eb4
[ "Apache-2.0" ]
null
null
null
java/java-codec/src/main/java/org/cloudburstmc/protocol/java/packet/play/serverbound/BlockEntityTagQueryPacket.java
D3ATHBRINGER13/Protocol
3bc6e1be9888736d09cd0cdeb4aff41e422e9eb4
[ "Apache-2.0" ]
null
null
null
java/java-codec/src/main/java/org/cloudburstmc/protocol/java/packet/play/serverbound/BlockEntityTagQueryPacket.java
D3ATHBRINGER13/Protocol
3bc6e1be9888736d09cd0cdeb4aff41e422e9eb4
[ "Apache-2.0" ]
null
null
null
33.928571
85
0.802105
11,455
package org.cloudburstmc.protocol.java.packet.play.serverbound; import com.nukkitx.math.vector.Vector3i; import lombok.Data; import lombok.EqualsAndHashCode; import org.cloudburstmc.protocol.common.PacketSignal; import org.cloudburstmc.protocol.java.packet.JavaPacket; import org.cloudburstmc.protocol.java.packet.handler.JavaPlayPacketHandler; import org.cloudburstmc.protocol.java.packet.type.JavaPacketType; import org.cloudburstmc.protocol.java.packet.type.JavaPlayPacketType; @Data @EqualsAndHashCode(doNotUseGetters = true, callSuper = false) public class BlockEntityTagQueryPacket implements JavaPacket<JavaPlayPacketHandler> { private int transactionId; private Vector3i position; @Override public PacketSignal handle(JavaPlayPacketHandler handler) { return handler.handle(this); } @Override public JavaPacketType getPacketType() { return JavaPlayPacketType.BLOCK_ENTITY_TAG_QUERY; } }
3e1b0e487dc44c7e61e2eecdb364e53d480b735c
12,494
java
Java
platform/lang-impl/src/com/intellij/refactoring/rename/RenameDialog.java
ekudel/intellij-community
7b79a61fbb7a949b7a55a2a60bb9ad30e82c4521
[ "Apache-2.0" ]
1
2018-10-13T19:43:36.000Z
2018-10-13T19:43:36.000Z
platform/lang-impl/src/com/intellij/refactoring/rename/RenameDialog.java
ekudel/intellij-community
7b79a61fbb7a949b7a55a2a60bb9ad30e82c4521
[ "Apache-2.0" ]
null
null
null
platform/lang-impl/src/com/intellij/refactoring/rename/RenameDialog.java
ekudel/intellij-community
7b79a61fbb7a949b7a55a2a60bb9ad30e82c4521
[ "Apache-2.0" ]
null
null
null
37.51952
143
0.761886
11,456
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.refactoring.rename; import com.intellij.lang.findUsages.DescriptiveNameUtil; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.fileTypes.FileTypes; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.codeStyle.SuggestedNameInfo; import com.intellij.psi.util.PsiUtilCore; import com.intellij.refactoring.RefactoringBundle; import com.intellij.refactoring.rename.inplace.VariableInplaceRenameHandler; import com.intellij.refactoring.rename.naming.AutomaticRenamerFactory; import com.intellij.refactoring.ui.NameSuggestionsField; import com.intellij.refactoring.ui.RefactoringDialog; import com.intellij.refactoring.util.TextOccurrencesUtil; import com.intellij.ui.NonFocusableCheckBox; import com.intellij.usageView.UsageViewUtil; import com.intellij.util.ArrayUtil; import com.intellij.util.Function; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.UIUtil; import com.intellij.xml.util.XmlStringUtil; import com.intellij.xml.util.XmlTagUtilBase; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Map; public class RenameDialog extends RefactoringDialog { private static final String REFACTORING_NAME = RefactoringBundle.message("rename.title"); private SuggestedNameInfo mySuggestedNameInfo; private JLabel myNameLabel; private NameSuggestionsField myNameSuggestionsField; private JCheckBox myCbSearchInComments; private JCheckBox myCbSearchTextOccurrences; private final JLabel myNewNamePrefix = new JLabel(""); private final String myHelpID; private final PsiElement myPsiElement; private final PsiElement myNameSuggestionContext; private final Editor myEditor; private NameSuggestionsField.DataChanged myNameChangedListener; private final Map<AutomaticRenamerFactory, JCheckBox> myAutoRenamerFactories = new HashMap<>(); private String myOldName; public RenameDialog(@NotNull Project project, @NotNull PsiElement psiElement, @Nullable PsiElement nameSuggestionContext, Editor editor) { super(project, true); PsiUtilCore.ensureValid(psiElement); myPsiElement = psiElement; myNameSuggestionContext = nameSuggestionContext; myEditor = editor; setTitle(REFACTORING_NAME); createNewNameComponent(); init(); myNameLabel.setText(XmlStringUtil.wrapInHtml(XmlTagUtilBase.escapeString(getLabelText(), false))); boolean toSearchInComments = isToSearchInCommentsForRename(); myCbSearchInComments.setSelected(toSearchInComments); if (myCbSearchTextOccurrences.isEnabled()) { boolean toSearchForTextOccurrences = isToSearchForTextOccurrencesForRename(); myCbSearchTextOccurrences.setSelected(toSearchForTextOccurrences); } if (!ApplicationManager.getApplication().isUnitTestMode()) validateButtons(); myHelpID = RenamePsiElementProcessor.forElement(psiElement).getHelpID(psiElement); } public static void showRenameDialog(DataContext dataContext, RenameDialog dialog) { if (ApplicationManager.getApplication().isUnitTestMode()) { final String name = PsiElementRenameHandler.DEFAULT_NAME.getData(dataContext); dialog.performRename(name); dialog.close(OK_EXIT_CODE); } else { dialog.show(); } } @NotNull protected String getLabelText() { return RefactoringBundle.message("rename.0.and.its.usages.to", getFullName()); } @NotNull public PsiElement getPsiElement() { return myPsiElement; } @Override protected boolean hasPreviewButton() { return RenamePsiElementProcessor.forElement(myPsiElement).showRenamePreviewButton(myPsiElement); } @Override protected void dispose() { myNameSuggestionsField.removeDataChangedListener(myNameChangedListener); super.dispose(); } protected boolean isToSearchForTextOccurrencesForRename() { return RenamePsiElementProcessor.forElement(myPsiElement).isToSearchForTextOccurrences(myPsiElement); } protected boolean isToSearchInCommentsForRename() { return RenamePsiElementProcessor.forElement(myPsiElement).isToSearchInComments(myPsiElement); } protected String getFullName() { String name = DescriptiveNameUtil.getDescriptiveName(myPsiElement); String type = UsageViewUtil.getType(myPsiElement); return StringUtil.isEmpty(name) ? type : type + " '" + name + "'"; } protected void createNewNameComponent() { String[] suggestedNames = getSuggestedNames(); myOldName = UsageViewUtil.getShortName(myPsiElement); myNameSuggestionsField = new NameSuggestionsField(suggestedNames, myProject, FileTypes.PLAIN_TEXT, myEditor) { @Override protected boolean shouldSelectAll() { return myEditor == null || myEditor.getSettings().isPreselectRename(); } }; if (myPsiElement instanceof PsiFile && myEditor == null) { myNameSuggestionsField.selectNameWithoutExtension(); } myNameChangedListener = () -> processNewNameChanged(); myNameSuggestionsField.addDataChangedListener(myNameChangedListener); } protected void preselectExtension(int start, int end) { myNameSuggestionsField.select(start, end); } protected void processNewNameChanged() { validateButtons(); } public String[] getSuggestedNames() { final LinkedHashSet<String> result = new LinkedHashSet<>(); final String initialName = VariableInplaceRenameHandler.getInitialName(); if (initialName != null) { result.add(initialName); } result.add(UsageViewUtil.getShortName(myPsiElement)); for(NameSuggestionProvider provider: NameSuggestionProvider.EP_NAME.getExtensionList()) { SuggestedNameInfo info = provider.getSuggestedNames(myPsiElement, myNameSuggestionContext, result); if (info != null) { mySuggestedNameInfo = info; if (provider instanceof PreferrableNameSuggestionProvider && !((PreferrableNameSuggestionProvider)provider).shouldCheckOthers()) break; } } return ArrayUtil.toStringArray(result); } public String getNewName() { return myNameSuggestionsField.getEnteredName().trim(); } public boolean isSearchInComments() { return myCbSearchInComments.isSelected(); } public boolean isSearchInNonJavaFiles() { return myCbSearchTextOccurrences.isSelected(); } @Override public JComponent getPreferredFocusedComponent() { return myNameSuggestionsField.getFocusableComponent(); } @Override protected JComponent createCenterPanel() { return null; } @Override protected JComponent createNorthPanel() { JPanel panel = new JPanel(new GridBagLayout()); GridBagConstraints gbConstraints = new GridBagConstraints(); gbConstraints.insets = JBUI.insetsBottom(4); gbConstraints.weighty = 0; gbConstraints.weightx = 1; gbConstraints.gridwidth = GridBagConstraints.REMAINDER; gbConstraints.fill = GridBagConstraints.BOTH; myNameLabel = new JLabel(); panel.add(myNameLabel, gbConstraints); gbConstraints.insets = JBUI.insets(0, 0, 4, StringUtil.isEmpty(myNewNamePrefix.getText()) ? 0 : 1); gbConstraints.gridwidth = 1; gbConstraints.fill = GridBagConstraints.NONE; gbConstraints.weightx = 0; gbConstraints.gridx = 0; gbConstraints.anchor = GridBagConstraints.WEST; panel.add(myNewNamePrefix, gbConstraints); gbConstraints.insets = JBUI.insetsBottom(8); gbConstraints.gridwidth = 2; gbConstraints.fill = GridBagConstraints.BOTH; gbConstraints.weightx = 1; gbConstraints.gridx = 0; gbConstraints.weighty = 1; panel.add(myNameSuggestionsField.getComponent(), gbConstraints); createCheckboxes(panel, gbConstraints); return panel; } protected void createCheckboxes(JPanel panel, GridBagConstraints gbConstraints) { gbConstraints.insets = JBUI.insetsBottom(4); gbConstraints.gridwidth = 1; gbConstraints.gridx = 0; gbConstraints.weighty = 0; gbConstraints.weightx = 1; gbConstraints.fill = GridBagConstraints.BOTH; myCbSearchInComments = new NonFocusableCheckBox(); myCbSearchInComments.setText(RefactoringBundle.getSearchInCommentsAndStringsText()); myCbSearchInComments.setSelected(true); panel.add(myCbSearchInComments, gbConstraints); gbConstraints.insets = JBUI.insets(0, UIUtil.DEFAULT_HGAP, 4, 0); gbConstraints.gridwidth = GridBagConstraints.REMAINDER; gbConstraints.gridx = 1; gbConstraints.weightx = 1; gbConstraints.fill = GridBagConstraints.BOTH; myCbSearchTextOccurrences = new NonFocusableCheckBox(); myCbSearchTextOccurrences.setText(RefactoringBundle.getSearchForTextOccurrencesText()); myCbSearchTextOccurrences.setSelected(true); panel.add(myCbSearchTextOccurrences, gbConstraints); if (!TextOccurrencesUtil.isSearchTextOccurencesEnabled(myPsiElement)) { myCbSearchTextOccurrences.setEnabled(false); myCbSearchTextOccurrences.setSelected(false); myCbSearchTextOccurrences.setVisible(false); } for(AutomaticRenamerFactory factory: AutomaticRenamerFactory.EP_NAME.getExtensionList()) { if (factory.isApplicable(myPsiElement) && factory.getOptionName() != null) { gbConstraints.gridwidth = myAutoRenamerFactories.size() % 2 == 0 ? 1 : GridBagConstraints.REMAINDER; gbConstraints.gridx = myAutoRenamerFactories.size() % 2; gbConstraints.insets = gbConstraints.gridx == 0 ? JBUI.insetsBottom(4) : JBUI.insets(0, UIUtil.DEFAULT_HGAP, 4, 0); gbConstraints.weightx = 1; gbConstraints.fill = GridBagConstraints.BOTH; JCheckBox checkBox = new NonFocusableCheckBox(); checkBox.setText(factory.getOptionName()); checkBox.setSelected(factory.isEnabled()); panel.add(checkBox, gbConstraints); myAutoRenamerFactories.put(factory, checkBox); } } } @Override protected String getHelpId() { return myHelpID; } @Override protected void doAction() { PsiUtilCore.ensureValid(myPsiElement); String newName = getNewName(); performRename(newName); } public void performRename(final String newName) { final RenamePsiElementProcessor elementProcessor = RenamePsiElementProcessor.forElement(myPsiElement); elementProcessor.setToSearchInComments(myPsiElement, isSearchInComments()); if (myCbSearchTextOccurrences.isEnabled()) { elementProcessor.setToSearchForTextOccurrences(myPsiElement, isSearchInNonJavaFiles()); } if (mySuggestedNameInfo != null) { mySuggestedNameInfo.nameChosen(newName); } final RenameProcessor processor = createRenameProcessor(newName); for(Map.Entry<AutomaticRenamerFactory, JCheckBox> e: myAutoRenamerFactories.entrySet()) { e.getKey().setEnabled(e.getValue().isSelected()); if (e.getValue().isSelected()) { processor.addRenamerFactory(e.getKey()); } } invokeRefactoring(processor); } protected RenameProcessor createRenameProcessor(String newName) { return new RenameProcessor(getProject(), myPsiElement, newName, isSearchInComments(), isSearchInNonJavaFiles()); } @Override protected void canRun() throws ConfigurationException { if (Comparing.strEqual(getNewName(), myOldName)) throw new ConfigurationException(null); if (!areButtonsValid()) { throw new ConfigurationException("\'" + getNewName() + "\' is not a valid identifier"); } final Function<String, String> inputValidator = RenameInputValidatorRegistry.getInputErrorValidator(myPsiElement); if (inputValidator != null) { setErrorText(inputValidator.fun(getNewName())); } } @Override protected boolean areButtonsValid() { final String newName = getNewName(); return RenameUtil.isValidName(myProject, myPsiElement, newName); } protected NameSuggestionsField getNameSuggestionsField() { return myNameSuggestionsField; } public JCheckBox getCbSearchInComments() { return myCbSearchInComments; } }
3e1b0fa84f8a8d35d23d56231928bab178339436
3,725
java
Java
checker/src/main/java/org/checkerframework/checker/index/OffsetDependentTypesHelper.java
fse-main-307/checker-framework
12fb7e65015015bbba541bf0cfee6270d4d25913
[ "MIT" ]
null
null
null
checker/src/main/java/org/checkerframework/checker/index/OffsetDependentTypesHelper.java
fse-main-307/checker-framework
12fb7e65015015bbba541bf0cfee6270d4d25913
[ "MIT" ]
null
null
null
checker/src/main/java/org/checkerframework/checker/index/OffsetDependentTypesHelper.java
fse-main-307/checker-framework
12fb7e65015015bbba541bf0cfee6270d4d25913
[ "MIT" ]
null
null
null
45.987654
95
0.709262
11,457
package org.checkerframework.checker.index; import com.sun.source.tree.MemberSelectTree; import com.sun.source.util.TreePath; import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.common.value.ValueAnnotatedTypeFactory; import org.checkerframework.common.value.ValueChecker; import org.checkerframework.common.value.ValueCheckerUtils; import org.checkerframework.dataflow.expression.FieldAccess; import org.checkerframework.dataflow.expression.JavaExpression; import org.checkerframework.framework.type.AnnotatedTypeFactory; import org.checkerframework.framework.type.AnnotatedTypeMirror; import org.checkerframework.framework.type.GenericAnnotatedTypeFactory; import org.checkerframework.framework.type.treeannotator.TreeAnnotator; import org.checkerframework.framework.util.JavaExpressionParseUtil; import org.checkerframework.framework.util.JavaExpressionParseUtil.JavaExpressionContext; import org.checkerframework.framework.util.dependenttypes.DependentTypesError; import org.checkerframework.framework.util.dependenttypes.DependentTypesHelper; import org.checkerframework.framework.util.dependenttypes.DependentTypesTreeAnnotator; import org.checkerframework.javacutil.TreeUtils; /** * Dependent type helper for array offset expressions. Each array offset expression may be the * addition or subtraction of several Java expressions. For example, {@code array.length - 1}. */ public class OffsetDependentTypesHelper extends DependentTypesHelper { public OffsetDependentTypesHelper(AnnotatedTypeFactory factory) { super(factory); } @Override protected String standardizeString( final String expression, JavaExpressionContext context, @Nullable TreePath localVarPath) { if (DependentTypesError.isExpressionError(expression)) { return expression; } JavaExpression result; try { result = JavaExpressionParseUtil.parse(expression, context, localVarPath); } catch (JavaExpressionParseUtil.JavaExpressionParseException e) { return new DependentTypesError(expression, e).toString(); } if (result == null) { return new DependentTypesError(expression, /*error message=*/ " ").toString(); } if (result instanceof FieldAccess && ((FieldAccess) result).isFinal()) { Object constant = ((FieldAccess) result).getField().getConstantValue(); if (constant != null && !(constant instanceof String)) { return constant.toString(); } } // TODO: Maybe move this into the superclass standardizeString, then remove this class. ValueAnnotatedTypeFactory vatf = ((GenericAnnotatedTypeFactory<?, ?, ?, ?>) factory) .getTypeFactoryOfSubchecker(ValueChecker.class); if (vatf != null) { result = ValueCheckerUtils.optimize(result, vatf); } return result.toString(); } @Override public TreeAnnotator createDependentTypesTreeAnnotator() { return new DependentTypesTreeAnnotator(factory, this) { @Override public Void visitMemberSelect(MemberSelectTree tree, AnnotatedTypeMirror type) { // UpperBoundTreeAnnotator changes the type of array.length to @LTEL("array"). // If the DependentTypesTreeAnnotator tries to viewpoint-adapt it based on the // declaration of length, it will fail. if (TreeUtils.isArrayLengthAccess(tree)) { return null; } return super.visitMemberSelect(tree, type); } }; } }
3e1b0ff37e5b984ff22b0d1de2d072ba4a813593
8,224
java
Java
aws-java-sdk-personalize/src/main/java/com/amazonaws/services/personalize/model/CreateFilterRequest.java
asellappen/aws-sdk-java
e3110498e1af384d60b608c0d12d4b3bb8dd49a6
[ "Apache-2.0" ]
3,372
2015-01-03T00:35:43.000Z
2022-03-31T15:56:24.000Z
aws-java-sdk-personalize/src/main/java/com/amazonaws/services/personalize/model/CreateFilterRequest.java
asellappen/aws-sdk-java
e3110498e1af384d60b608c0d12d4b3bb8dd49a6
[ "Apache-2.0" ]
2,391
2015-01-01T12:55:24.000Z
2022-03-31T08:01:50.000Z
aws-java-sdk-personalize/src/main/java/com/amazonaws/services/personalize/model/CreateFilterRequest.java
asellappen/aws-sdk-java
e3110498e1af384d60b608c0d12d4b3bb8dd49a6
[ "Apache-2.0" ]
2,876
2015-01-01T14:38:37.000Z
2022-03-29T19:53:10.000Z
33.567347
123
0.633268
11,458
/* * Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.personalize.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/personalize-2018-05-22/CreateFilter" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class CreateFilterRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The name of the filter to create. * </p> */ private String name; /** * <p> * The ARN of the dataset group that the filter will belong to. * </p> */ private String datasetGroupArn; /** * <p> * The filter expression defines which items are included or excluded from recommendations. Filter expression must * follow specific format rules. For information about filter expression structure and syntax, see * <a>filter-expressions</a>. * </p> */ private String filterExpression; /** * <p> * The name of the filter to create. * </p> * * @param name * The name of the filter to create. */ public void setName(String name) { this.name = name; } /** * <p> * The name of the filter to create. * </p> * * @return The name of the filter to create. */ public String getName() { return this.name; } /** * <p> * The name of the filter to create. * </p> * * @param name * The name of the filter to create. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateFilterRequest withName(String name) { setName(name); return this; } /** * <p> * The ARN of the dataset group that the filter will belong to. * </p> * * @param datasetGroupArn * The ARN of the dataset group that the filter will belong to. */ public void setDatasetGroupArn(String datasetGroupArn) { this.datasetGroupArn = datasetGroupArn; } /** * <p> * The ARN of the dataset group that the filter will belong to. * </p> * * @return The ARN of the dataset group that the filter will belong to. */ public String getDatasetGroupArn() { return this.datasetGroupArn; } /** * <p> * The ARN of the dataset group that the filter will belong to. * </p> * * @param datasetGroupArn * The ARN of the dataset group that the filter will belong to. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateFilterRequest withDatasetGroupArn(String datasetGroupArn) { setDatasetGroupArn(datasetGroupArn); return this; } /** * <p> * The filter expression defines which items are included or excluded from recommendations. Filter expression must * follow specific format rules. For information about filter expression structure and syntax, see * <a>filter-expressions</a>. * </p> * * @param filterExpression * The filter expression defines which items are included or excluded from recommendations. Filter expression * must follow specific format rules. For information about filter expression structure and syntax, see * <a>filter-expressions</a>. */ public void setFilterExpression(String filterExpression) { this.filterExpression = filterExpression; } /** * <p> * The filter expression defines which items are included or excluded from recommendations. Filter expression must * follow specific format rules. For information about filter expression structure and syntax, see * <a>filter-expressions</a>. * </p> * * @return The filter expression defines which items are included or excluded from recommendations. Filter * expression must follow specific format rules. For information about filter expression structure and * syntax, see <a>filter-expressions</a>. */ public String getFilterExpression() { return this.filterExpression; } /** * <p> * The filter expression defines which items are included or excluded from recommendations. Filter expression must * follow specific format rules. For information about filter expression structure and syntax, see * <a>filter-expressions</a>. * </p> * * @param filterExpression * The filter expression defines which items are included or excluded from recommendations. Filter expression * must follow specific format rules. For information about filter expression structure and syntax, see * <a>filter-expressions</a>. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateFilterRequest withFilterExpression(String filterExpression) { setFilterExpression(filterExpression); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getName() != null) sb.append("Name: ").append(getName()).append(","); if (getDatasetGroupArn() != null) sb.append("DatasetGroupArn: ").append(getDatasetGroupArn()).append(","); if (getFilterExpression() != null) sb.append("FilterExpression: ").append("***Sensitive Data Redacted***"); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof CreateFilterRequest == false) return false; CreateFilterRequest other = (CreateFilterRequest) obj; if (other.getName() == null ^ this.getName() == null) return false; if (other.getName() != null && other.getName().equals(this.getName()) == false) return false; if (other.getDatasetGroupArn() == null ^ this.getDatasetGroupArn() == null) return false; if (other.getDatasetGroupArn() != null && other.getDatasetGroupArn().equals(this.getDatasetGroupArn()) == false) return false; if (other.getFilterExpression() == null ^ this.getFilterExpression() == null) return false; if (other.getFilterExpression() != null && other.getFilterExpression().equals(this.getFilterExpression()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode()); hashCode = prime * hashCode + ((getDatasetGroupArn() == null) ? 0 : getDatasetGroupArn().hashCode()); hashCode = prime * hashCode + ((getFilterExpression() == null) ? 0 : getFilterExpression().hashCode()); return hashCode; } @Override public CreateFilterRequest clone() { return (CreateFilterRequest) super.clone(); } }
3e1b1075cdcc3a11052bbd713db1340e6b3385de
535
java
Java
spring-cloud-learn/stream-group/src/main/java/com/cpq/streamgroup/skin/User.java
CodingSoldier/java-learn
c480f0c26c95b65f49c082e0ffeb10706bd366b1
[ "Apache-2.0" ]
23
2018-02-11T13:28:42.000Z
2021-12-24T05:53:13.000Z
spring-cloud-learn/stream-group/src/main/java/com/cpq/streamgroup/skin/User.java
CodingSoldier/java-learn
c480f0c26c95b65f49c082e0ffeb10706bd366b1
[ "Apache-2.0" ]
5
2019-12-23T01:51:45.000Z
2021-11-30T15:12:08.000Z
spring-cloud-learn/stream-group/src/main/java/com/cpq/streamgroup/skin/User.java
CodingSoldier/java-learn
c480f0c26c95b65f49c082e0ffeb10706bd366b1
[ "Apache-2.0" ]
17
2018-02-11T13:28:03.000Z
2022-01-24T20:30:02.000Z
17.258065
40
0.48785
11,459
package com.cpq.streamgroup.skin; public class User { private String name; private Integer age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
3e1b111cf6833efc5d09f8b3252a1161cbc78630
1,882
java
Java
Util/src/main/java/io/deephaven/util/ExceptionDetails.java
mattrunyon/deephaven-core
80e3567e4647ab76a81e483d0a8ab542f9aadace
[ "MIT" ]
55
2021-05-11T16:01:59.000Z
2022-03-30T14:30:33.000Z
Util/src/main/java/io/deephaven/util/ExceptionDetails.java
mattrunyon/deephaven-core
80e3567e4647ab76a81e483d0a8ab542f9aadace
[ "MIT" ]
943
2021-05-10T14:00:02.000Z
2022-03-31T21:28:15.000Z
Util/src/main/java/io/deephaven/util/ExceptionDetails.java
mattrunyon/deephaven-core
80e3567e4647ab76a81e483d0a8ab542f9aadace
[ "MIT" ]
29
2021-05-10T11:33:16.000Z
2022-03-30T21:01:54.000Z
28.953846
118
0.716259
11,460
/* * Copyright (c) 2016-2021 Deephaven Data Labs and Patent Pending */ package io.deephaven.util; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.PrintWriter; import java.io.Serializable; import java.io.StringWriter; import java.util.function.Predicate; /** * Class to help with determining details from Throwable instances. */ public class ExceptionDetails implements Serializable { private static final long serialVersionUID = 1L; private final String errorMessage; private final String fullStackTrace; private final String shortCauses; public ExceptionDetails(final Throwable throwable) { errorMessage = throwable.toString(); final StringWriter writer = new StringWriter(); throwable.printStackTrace(new PrintWriter(writer)); fullStackTrace = writer.toString(); shortCauses = FindExceptionCause.shortCauses(throwable, "\n"); } @SuppressWarnings("UnusedDeclaration") public String getErrorMessage() { return errorMessage; } public String getFullStackTrace() { return fullStackTrace; } public String getShortCauses() { return shortCauses; } @Override public String toString() { return errorMessage; } /** * Returns true if exceptionDetails is not null and the result of applying testToApply on exceptionDetails is true * * @param exceptionDetails the exception to test * @param testToApply the test to apply * @return true if exceptionDetails is not null and testToApply returns true */ public static boolean testExceptionDetails(@Nullable final ExceptionDetails exceptionDetails, @NotNull final Predicate<ExceptionDetails> testToApply) { return exceptionDetails != null && testToApply.test(exceptionDetails); } }
3e1b11580d8f9819472a633c0975510153f92eef
3,012
java
Java
Matrix/Leetcode/ValidSudoku.java
riddhik84/DataStructuresInJava
4ba728930cb67017505e5c8d6686418ab6002164
[ "Apache-2.0" ]
null
null
null
Matrix/Leetcode/ValidSudoku.java
riddhik84/DataStructuresInJava
4ba728930cb67017505e5c8d6686418ab6002164
[ "Apache-2.0" ]
null
null
null
Matrix/Leetcode/ValidSudoku.java
riddhik84/DataStructuresInJava
4ba728930cb67017505e5c8d6686418ab6002164
[ "Apache-2.0" ]
null
null
null
41.260274
99
0.340305
11,461
//https://leetcode.com/explore/interview/card/top-interview-questions-easy/92/array/769/ public class ValidSudoku { public static void main(String[] args) { char[][] sudoku = { {'3', '5', '.', '.', '7', '.', '.', '.', '.'}, {'6', '.', '.', '1', '9', '5', '.', '.', '.'}, {'.', '9', '8', '.', '.', '.', '.', '6', '.'}, {'8', '.', '.', '.', '6', '.', '.', '.', '3'}, {'4', '.', '.', '8', '.', '3', '.', '.', '1'}, {'7', '.', '.', '.', '2', '.', '.', '.', '6'}, {'.', '6', '.', '.', '.', '.', '2', '8', '.'}, {'.', '.', '.', '4', '1', '9', '.', '5', '5'}, {'.', '.', '.', '.', '8', '.', '.', '7', '9'} }; System.out.println("Is Valid Sudoku : " + isValidSudoku(sudoku)); } public static boolean isValidSudoku(char[][] board) { if (board == null || board.length < 9 || board[0].length < 9) { return false; } //check rows for (int i = 0; i < board.length; i++) { boolean[] numbers = new boolean[10]; for (int j = 0; j < 9; j++) { if (board[i][j] != '.') { //[r][c] increase row when column needs to be printed int n = Integer.parseInt(String.valueOf(board[i][j])); //System.out.print(board[j][i] + " "); if (numbers[n] == true) { return false; } numbers[n] = true; } } //System.out.println(); } //check columns for (int i = 0; i < board.length; i++) { boolean[] numbers = new boolean[10]; for (int j = 0; j < 9; j++) { if (board[j][i] != '.') { //[r][c] increase row when column needs to be printed int n = Integer.parseInt(String.valueOf(board[j][i])); //System.out.print(board[j][i] + " "); if (numbers[n] == true) { return false; } numbers[n] = true; } } //System.out.println(); } //check 3x3 matrix for (int block = 0; block < 9; block++) { boolean[] numbers = new boolean[10]; for (int i = block / 3 * 3; i < block / 3 * 3 + 3; i++) { for (int j = block % 3 * 3; j < block % 3 * 3 + 3; j++) { if (board[j][i] != '.') { //[r][c] increase row when column needs to be printed int n = Integer.parseInt(String.valueOf(board[j][i])); //System.out.print(board[j][i] + " "); if (numbers[n] == true) { return false; } numbers[n] = true; } } } } return true; } }
3e1b12e57f247b3b50462099fe6515d6277f147d
4,609
java
Java
java/registry/src/main/java/dev/sunbirdrc/registry/util/RefResolver.java
suraj-shanbhag/sunbird-rc-core
570d64735813782edd4d61d7fbc6325d0d741788
[ "MIT" ]
7
2021-04-30T05:38:19.000Z
2021-09-07T10:55:08.000Z
java/registry/src/main/java/dev/sunbirdrc/registry/util/RefResolver.java
suraj-shanbhag/sunbird-rc-core
570d64735813782edd4d61d7fbc6325d0d741788
[ "MIT" ]
4
2021-06-28T05:16:59.000Z
2021-09-13T05:38:25.000Z
java/registry/src/main/java/dev/sunbirdrc/registry/util/RefResolver.java
suraj-shanbhag/sunbird-rc-core
570d64735813782edd4d61d7fbc6325d0d741788
[ "MIT" ]
19
2021-09-28T06:24:18.000Z
2022-03-30T13:33:42.000Z
40.429825
109
0.674767
11,462
package dev.sunbirdrc.registry.util; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import dev.sunbirdrc.registry.middleware.util.JSONUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import java.io.IOException; import java.util.Iterator; import java.util.Map; @Component public class RefResolver { private static Logger logger = LoggerFactory.getLogger(RefResolver.class); private final static String REF = "$ref"; private final DefinitionsManager definitionsManager; public RefResolver(DefinitionsManager definitionsManager) { this.definitionsManager = definitionsManager; } public JsonNode getResolvedSchema(String rootDefinitionName, String rootContext) { Definition definition = definitionsManager.getDefinition(rootDefinitionName); String content = definition.getContent(); try { JsonNode node = JSONUtil.convertStringJsonNode(content); ObjectNode jsonNode = ((ObjectNode) node); JsonNode resolvedDefinitions = resolveDefinitions(rootDefinitionName, jsonNode.get(rootContext)); logger.info(JSONUtil.convertObjectJsonString(resolvedDefinitions)); return resolvedDefinitions; } catch (IOException e) { e.printStackTrace(); } return null; } public JsonNode resolveDefinitions(String currentDefinitionName, JsonNode currentNode) { if (checkIfRefIsPresent(currentNode)) { String refPath = currentNode.get(REF).asText(); JsonNode refJsonNode = fetchDefinition(refPath, currentDefinitionName); if (refJsonNode != null && !refJsonNode.isNull()) { if (isExternalReference(refPath)) { currentDefinitionName = getDefinitionName(refPath); } currentNode = refJsonNode; } } if (currentNode.isArray()) { ArrayNode arrayNode = (ArrayNode) currentNode; ArrayNode updateArrayNodes = JsonNodeFactory.instance.arrayNode(); Iterator<JsonNode> node = arrayNode.elements(); while (node.hasNext()) { JsonNode resultantNode = resolveDefinitions(currentDefinitionName, node.next()); updateArrayNodes.add(resultantNode); } return updateArrayNodes; } else if (currentNode.isObject()) { for (Iterator<Map.Entry<String, JsonNode>> it = currentNode.fields(); it.hasNext(); ) { Map.Entry<String, JsonNode> entry = it.next(); JsonNode resultantNode = resolveDefinitions(currentDefinitionName, entry.getValue()); ((ObjectNode) currentNode).set(entry.getKey(), resultantNode); } } return currentNode; } private JsonNode fetchDefinition(String refPath, String currentDefinitionName) { try { if (isExternalReference(refPath)) { return extractDefinitionFromExternalFile(refPath); } else { return extractDefinition(refPath, currentDefinitionName); } } catch (Exception e) { logger.error("Fetching definition of $ref {} failed", refPath, e); return null; } } private boolean isExternalReference(String refPath) { return refPath.contains(".json"); } private JsonNode extractDefinition(String refPath, String currentDefinitionName) throws IOException { Definition definition = definitionsManager.getDefinition(currentDefinitionName); JsonNode referenceJson = JSONUtil.convertStringJsonNode(definition.getContent()); return referenceJson.at(extractJsonPointer(refPath)); } private JsonNode extractDefinitionFromExternalFile(String refPath) throws IOException { String fileNameWithoutExtn = getDefinitionName(refPath); return extractDefinition(refPath, fileNameWithoutExtn); } private String getDefinitionName(String refPath) { String fileName = refPath.substring(0, refPath.indexOf("/")); return fileName.substring(0, fileName.indexOf('.')); } private String extractJsonPointer(String refPath) { return refPath.substring(refPath.indexOf("/")).replace("/#", ""); } private boolean checkIfRefIsPresent(JsonNode node) { return node.has(REF); } }
3e1b137101bd80bb107b2d631a266b0979210276
119
java
Java
src/main/java/com/nosy/admin/nosyadmin/exceptions/EmailTemplateNotFoundException.java
danielj42/nosy-admin
f78df98b6b9f37c9e21c09cfd1c7c89827acb638
[ "Apache-2.0" ]
null
null
null
src/main/java/com/nosy/admin/nosyadmin/exceptions/EmailTemplateNotFoundException.java
danielj42/nosy-admin
f78df98b6b9f37c9e21c09cfd1c7c89827acb638
[ "Apache-2.0" ]
1
2022-02-16T00:57:10.000Z
2022-02-16T00:57:10.000Z
src/main/java/com/nosy/admin/nosyadmin/exceptions/EmailTemplateNotFoundException.java
danielj42/nosy-admin
f78df98b6b9f37c9e21c09cfd1c7c89827acb638
[ "Apache-2.0" ]
null
null
null
23.8
70
0.857143
11,463
package com.nosy.admin.nosyadmin.exceptions; public class EmailTemplateNotFoundException extends RuntimeException { }
3e1b1377d71e839857aa56741d4041c7d559aead
3,278
java
Java
core/src/main/java/org/adamalang/translator/tree/types/reactive/TyReactiveMaybe.java
dejenerate/adama-lang
a6d7219199581c8fff6aa7f033bf92c27d349fbc
[ "Apache-2.0" ]
null
null
null
core/src/main/java/org/adamalang/translator/tree/types/reactive/TyReactiveMaybe.java
dejenerate/adama-lang
a6d7219199581c8fff6aa7f033bf92c27d349fbc
[ "Apache-2.0" ]
null
null
null
core/src/main/java/org/adamalang/translator/tree/types/reactive/TyReactiveMaybe.java
dejenerate/adama-lang
a6d7219199581c8fff6aa7f033bf92c27d349fbc
[ "Apache-2.0" ]
null
null
null
39.493976
168
0.78432
11,464
/* The Adama Programming Language For Board Games! * See http://www.adama-lang.org/ for more information. * (c) copyright 2020 Jeffrey M. Barber (http://jeffrey.io) */ package org.adamalang.translator.tree.types.reactive; import java.util.function.Consumer; import org.adamalang.translator.env.Environment; import org.adamalang.translator.parser.token.Token; import org.adamalang.translator.tree.common.DocumentPosition; import org.adamalang.translator.tree.common.TokenizedItem; import org.adamalang.translator.tree.types.TyType; import org.adamalang.translator.tree.types.TypeBehavior; import org.adamalang.translator.tree.types.natives.TyNativeMaybe; import org.adamalang.translator.tree.types.traits.assign.AssignmentViaSetter; import org.adamalang.translator.tree.types.traits.details.DetailComputeRequiresGet; import org.adamalang.translator.tree.types.traits.details.DetailContainsAnEmbeddedType; public class TyReactiveMaybe extends TyType implements DetailContainsAnEmbeddedType, // DetailComputeRequiresGet, // AssignmentViaSetter // { public final Token maybeToken; public final TokenizedItem<TyType> tokenizedElementType; public TyReactiveMaybe(final Token maybeToken, final TokenizedItem<TyType> elementType) { super(TypeBehavior.ReadWriteWithSetGet); this.maybeToken = maybeToken; tokenizedElementType = elementType; ingest(maybeToken); ingest(elementType.item); } @Override public void emit(final Consumer<Token> yielder) { yielder.accept(maybeToken); tokenizedElementType.emitBefore(yielder); tokenizedElementType.item.emit(yielder); tokenizedElementType.emitAfter(yielder); } @Override public String getAdamaType() { return String.format("maybe<%s>", tokenizedElementType.item.getAdamaType()); } @Override public TyType getEmbeddedType(final Environment environment) { return environment.rules.Resolve(tokenizedElementType.item, false); } @Override public String getJavaBoxType(final Environment environment) { final var elementTypeFixed = getEmbeddedType(environment); return elementTypeFixed != null ? String.format("RxMaybe<%s>", elementTypeFixed.getJavaBoxType(environment)) : "RxMaybe<? /* TODO */>"; } @Override public String getJavaConcreteType(final Environment environment) { return getJavaBoxType(environment); } @Override public TyType makeCopyWithNewPosition(final DocumentPosition position, final TypeBehavior newBehavior) { return new TyReactiveMaybe(maybeToken, tokenizedElementType).withPosition(position); } @Override public TyType typeAfterGet(final Environment environment) { final var elementType = environment.rules.Resolve(tokenizedElementType.item, false); if (elementType instanceof TyReactiveRecord) { return new TyNativeMaybe(TypeBehavior.ReadWriteNative, null, maybeToken, new TokenizedItem<>(elementType)); } else { return new TyNativeMaybe(TypeBehavior.ReadWriteNative, null, maybeToken, new TokenizedItem<>(((DetailComputeRequiresGet) elementType).typeAfterGet(environment))); } } @Override public void typing(final Environment environment) { environment.rules.Resolve(tokenizedElementType.item, false); tokenizedElementType.item.typing(environment); } }
3e1b140b90e6ef629c1146a5863cc86128b00d31
301
java
Java
Design Patterns/org/algonell/trading/dp/structural/composite/PutOption.java
algonell/TradersTools
776ff7d56ca91344ae4404bafd25e8b07a45fa7b
[ "MIT" ]
3
2021-01-12T10:06:47.000Z
2021-05-18T08:02:15.000Z
Design Patterns/org/algonell/trading/dp/structural/composite/PutOption.java
algonell/TradersTools
776ff7d56ca91344ae4404bafd25e8b07a45fa7b
[ "MIT" ]
null
null
null
Design Patterns/org/algonell/trading/dp/structural/composite/PutOption.java
algonell/TradersTools
776ff7d56ca91344ae4404bafd25e8b07a45fa7b
[ "MIT" ]
1
2021-04-14T17:33:00.000Z
2021-04-14T17:33:00.000Z
16.722222
53
0.674419
11,465
package org.algonell.trading.dp.structural.composite; /** * Put Option: buy if bearish, sell if bullish. * * @author Andrew Kreimer * */ public class PutOption implements Option { @Override public double calculateDelta() { // depends on the strike, IV and etc. return -0.5; } }
3e1b146f11f6f85b73d0b510022e0caf4384ea0c
825
java
Java
net.menthor.ontouml/src/RefOntoUML/impl/subCollectionOfImpl.java
tgoprince/menthor-editor
1618b272d8976688dff46fc9e9e35eb9371cd0f4
[ "MIT" ]
28
2016-09-26T13:27:57.000Z
2022-01-19T10:01:37.000Z
net.menthor.ontouml/src/RefOntoUML/impl/subCollectionOfImpl.java
tgoprince/menthor-editor
1618b272d8976688dff46fc9e9e35eb9371cd0f4
[ "MIT" ]
16
2016-09-19T16:43:48.000Z
2021-03-10T20:47:23.000Z
net.menthor.ontouml/src/RefOntoUML/impl/subCollectionOfImpl.java
tgoprince/menthor-editor
1618b272d8976688dff46fc9e9e35eb9371cd0f4
[ "MIT" ]
6
2016-09-27T20:55:04.000Z
2022-03-20T15:52:22.000Z
18.75
84
0.6
11,466
/** * <copyright> * </copyright> * * $Id$ */ package RefOntoUML.impl; import RefOntoUML.RefOntoUMLPackage; import RefOntoUML.subCollectionOf; import org.eclipse.emf.ecore.EClass; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>sub Collection Of</b></em>'. * <!-- end-user-doc --> * <p> * </p> * * @generated */ public class subCollectionOfImpl extends MeronymicImpl implements subCollectionOf { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected subCollectionOfImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return RefOntoUMLPackage.eINSTANCE.getsubCollectionOf(); } } //subCollectionOfImpl
3e1b14d6414d3ae955f41a94a83718e504c6d727
466
java
Java
platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/CompassViewSettings.java
followtherider/mapbox-gl-native
62b56b799a7d4fcd1a8f151eed878054b862da5b
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/CompassViewSettings.java
followtherider/mapbox-gl-native
62b56b799a7d4fcd1a8f151eed878054b862da5b
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/CompassViewSettings.java
followtherider/mapbox-gl-native
62b56b799a7d4fcd1a8f151eed878054b862da5b
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
21.181818
70
0.697425
11,467
package com.mapbox.mapboxsdk.maps; /** * Settings for the overlain views of a MapboxMap. Used by UiSettings. */ class CompassViewSettings extends ViewSettings{ private boolean fadeFacingNorth = true; public CompassViewSettings() { super(); } public boolean isFadeFacingNorth() { return fadeFacingNorth; } public void setFadeFacingNorth(boolean fadeFacingNorth) { this.fadeFacingNorth = fadeFacingNorth; } }
3e1b1565079fcfd034211bf8557f01a06ff57fe2
863
java
Java
spring-rest2ts-generator/src/main/java/com/blueveery/springrest2ts/converters/ClassConverter.java
albi23/spring-rest-2-ts
9ca4e6a445e884a0039b6565b20371a1a54d9987
[ "MIT" ]
80
2019-04-25T08:49:37.000Z
2022-02-14T09:47:47.000Z
spring-rest2ts-generator/src/main/java/com/blueveery/springrest2ts/converters/ClassConverter.java
albi23/spring-rest-2-ts
9ca4e6a445e884a0039b6565b20371a1a54d9987
[ "MIT" ]
19
2020-01-09T11:22:03.000Z
2022-02-26T00:50:48.000Z
spring-rest2ts-generator/src/main/java/com/blueveery/springrest2ts/converters/ClassConverter.java
albi23/spring-rest-2-ts
9ca4e6a445e884a0039b6565b20371a1a54d9987
[ "MIT" ]
18
2019-12-04T01:48:03.000Z
2022-02-23T17:52:41.000Z
34.52
109
0.80533
11,468
package com.blueveery.springrest2ts.converters; import com.blueveery.springrest2ts.extensions.ConversionExtension; import com.blueveery.springrest2ts.implgens.ImplementationGenerator; import com.blueveery.springrest2ts.naming.ClassNameMapper; import java.util.ArrayList; import java.util.List; public abstract class ClassConverter<C extends ConversionExtension> extends ComplexTypeConverter { protected List<C> conversionExtensionList = new ArrayList<>(); protected ClassConverter(ImplementationGenerator implementationGenerator) { super(implementationGenerator); } public ClassConverter(ImplementationGenerator implementationGenerator, ClassNameMapper classNameMapper) { super(implementationGenerator, classNameMapper); } public List<C> getConversionExtensionList() { return conversionExtensionList; } }
3e1b1620bff90ad8b1980a609f1e3c2936c86dcc
23,159
java
Java
appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/AppcOam.java
arunsarat/appc
a5a04a7782fbb69621187ddc141c129554cc80ff
[ "Apache-2.0" ]
null
null
null
appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/AppcOam.java
arunsarat/appc
a5a04a7782fbb69621187ddc141c129554cc80ff
[ "Apache-2.0" ]
null
null
null
appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/AppcOam.java
arunsarat/appc
a5a04a7782fbb69621187ddc141c129554cc80ff
[ "Apache-2.0" ]
null
null
null
39.655822
178
0.624897
11,469
/*- * ============LICENSE_START======================================================= * APPC * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * Copyright (C) 2017 Amdocs * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============LICENSE_END========================================================= * ECOMP is a trademark and service mark of AT&T Intellectual Property. */ package org.openecomp.appc.oam; import org.openecomp.appc.Constants; import org.openecomp.appc.configuration.Configuration; import org.openecomp.appc.configuration.ConfigurationFactory; import org.openecomp.appc.exceptions.APPCException; import org.openecomp.appc.executor.objects.Params; import org.openecomp.appc.i18n.Msg; import org.openecomp.appc.logging.LoggingConstants; import org.openecomp.appc.logging.LoggingUtils; import org.openecomp.appc.metricservice.MetricRegistry; import org.openecomp.appc.metricservice.MetricService; import org.openecomp.appc.metricservice.metric.Metric; import org.openecomp.appc.requesthandler.LCMStateManager; import org.openecomp.appc.requesthandler.RequestHandler; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; import com.att.eelf.i18n.EELFResourceManager; import com.google.common.util.concurrent.Futures; import org.opendaylight.controller.md.sal.binding.api.DataBroker; import org.opendaylight.controller.sal.binding.api.BindingAwareBroker; import org.opendaylight.controller.sal.binding.api.NotificationProviderService; import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry; import org.opendaylight.yang.gen.v1.org.openecomp.appc.oam.rev170303.*; import org.opendaylight.yang.gen.v1.org.openecomp.appc.oam.rev170303.common.header.CommonHeader; import org.opendaylight.yang.gen.v1.org.openecomp.appc.oam.rev170303.get.metrics.output.Metrics; import org.opendaylight.yang.gen.v1.org.openecomp.appc.oam.rev170303.get.metrics.output.MetricsBuilder; import org.opendaylight.yang.gen.v1.org.openecomp.appc.oam.rev170303.get.metrics.output.metrics.KpiValues; import org.opendaylight.yang.gen.v1.org.openecomp.appc.oam.rev170303.get.metrics.output.metrics.KpiValuesBuilder; import org.opendaylight.yang.gen.v1.org.openecomp.appc.oam.rev170303.status.Status; import org.opendaylight.yang.gen.v1.org.openecomp.appc.oam.rev170303.status.StatusBuilder; import org.opendaylight.yangtools.yang.common.RpcError; import org.opendaylight.yangtools.yang.common.RpcResult; import org.opendaylight.yangtools.yang.common.RpcResultBuilder; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.FrameworkUtil; import org.osgi.framework.ServiceReference; import org.slf4j.MDC; import java.net.InetAddress; import java.util.*; import java.util.concurrent.*; import org.openecomp.appc.oam.messageadapter.*; import static com.att.eelf.configuration.Configuration.*; import org.opendaylight.yangtools.yang.common.RpcResultBuilder; import org.osgi.framework.BundleContext; import org.osgi.framework.FrameworkUtil; import org.osgi.framework.ServiceReference; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class AppcOam implements AutoCloseable, AppcOamService { private Configuration configuration = ConfigurationFactory.getConfiguration(); private final EELFLogger logger = EELFManager.getInstance().getLogger(AppcOam.class); private boolean isMetricEnabled = false; private final ScheduledExecutorService scheduledExecutorService; private volatile ScheduledFuture<?> outstandingLCMRequestMonitorSheduledFuture; private MessageAdapter messageAdapter; /** * The ODL data store broker. Provides access to a conceptual data tree store and also provides the ability to * subscribe for changes to data under a given branch of the tree. */ private DataBroker dataBroker; /** * ODL Notification Service that provides publish/subscribe capabilities for YANG modeled notifications. */ private NotificationProviderService notificationService; /** * Provides a registry for Remote Procedure Call (RPC) service implementations. The RPCs are defined in YANG models. */ private RpcProviderRegistry rpcRegistry; /** * Represents our RPC implementation registration */ private BindingAwareBroker.RpcRegistration<AppcOamService> rpcRegistration; /** * The yang rpc names */ public enum RPC { start, stop, ; } /** * @param dataBroker * @param notificationProviderService * @param rpcProviderRegistry */ @SuppressWarnings({ "javadoc", "nls" }) public AppcOam(DataBroker dataBroker, NotificationProviderService notificationProviderService, RpcProviderRegistry rpcProviderRegistry) { String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); logger.info(Msg.COMPONENT_INITIALIZING, appName, "oam"); this.dataBroker = dataBroker; this.notificationService = notificationProviderService; this.rpcRegistry = rpcProviderRegistry; if (this.rpcRegistry != null) { rpcRegistration = rpcRegistry.addRpcImplementation(AppcOamService.class, this); } Properties properties = configuration.getProperties(); if (properties != null && properties.getProperty("metric.enabled") != null) { isMetricEnabled = Boolean.valueOf(properties.getProperty("metric.enabled")); } messageAdapter = new MessageAdapter(); messageAdapter.init(); scheduledExecutorService = Executors.newSingleThreadScheduledExecutor( new ThreadFactory(){ @Override public Thread newThread(Runnable runnable) { Bundle bundle = FrameworkUtil.getBundle(AppcOam.class); return new Thread(runnable,bundle.getSymbolicName() + " scheduledExecutor"); } } ); logger.info(Msg.COMPONENT_INITIALIZED, appName, "oam"); } /** * Implements the close of the service * * @see AutoCloseable#close() */ @SuppressWarnings("nls") @Override public void close() throws Exception { String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); logger.info(Msg.COMPONENT_TERMINATING, appName, "oam"); scheduledExecutorService.shutdown(); if (rpcRegistration != null) { rpcRegistration.close(); } logger.info(Msg.COMPONENT_TERMINATED, appName, "oam"); } @Override public Future<RpcResult<GetMetricsOutput>> getMetrics() { GetMetricsOutputBuilder outputBuilder = new GetMetricsOutputBuilder(); if (!isMetricEnabled){ logger.error("Metric Service not enabled returning failure"); RpcResult<GetMetricsOutput> result = RpcResultBuilder.<GetMetricsOutput> status(false).withError(RpcError.ErrorType.APPLICATION,"Metric Service not enabled").build(); return Futures.immediateFuture(result); } MetricService metricService = null; try { metricService = getService(MetricService.class); } catch (APPCException e){ logger.error("MetricService not found",e); RpcResult<GetMetricsOutput> result = RpcResultBuilder.<GetMetricsOutput> status(false).withError(RpcError.ErrorType.APPLICATION,"Metric Service not found").build(); return Futures.immediateFuture(result); } Map<String,MetricRegistry> allMetricRegitry = metricService.getAllRegistry(); if(allMetricRegitry == null || allMetricRegitry.isEmpty()){ logger.error("No metrics registered returning failure"); RpcResult<GetMetricsOutput> result = RpcResultBuilder.<GetMetricsOutput> status(false).withError(RpcError.ErrorType.APPLICATION,"No metrics Registered").build(); return Futures.immediateFuture(result); } List<Metrics> metricsList = new ArrayList<>(); logger.debug("Iterating metric registry list"); for (MetricRegistry metricRegistry : allMetricRegitry.values() ) { logger.debug("Iterating metric registry :" + metricRegistry.toString()); Metric[] metrics = metricRegistry.metrics() ; if(metrics!= null && metrics.length >0) { logger.debug("Iterating though metrics in registry"); for (Metric metric : metrics) { logger.debug("Iterating though metrics: "+ metric.name()); MetricsBuilder metricsBuilder = new MetricsBuilder(); metricsBuilder.setKpiName(metric.name()); metricsBuilder.setLastResetTime(metric.getLastModified()); List<KpiValues> kpiList = new ArrayList<>(); Map<String, String> metricsOutput = metric.getMetricsOutput(); for (Map.Entry<String, String> kpi : metricsOutput.entrySet()) { KpiValuesBuilder kpiValuesBuilder = new KpiValuesBuilder(); kpiValuesBuilder.setName(kpi.getKey()); kpiValuesBuilder.setValue(kpi.getValue()); kpiList.add(kpiValuesBuilder.build()); } metricsBuilder.setKpiValues(kpiList); metricsList.add(metricsBuilder.build()); } } } outputBuilder.setMetrics(metricsList); RpcResult<GetMetricsOutput> result = RpcResultBuilder.<GetMetricsOutput> status(true).withResult(outputBuilder.build()).build(); return Futures.immediateFuture(result); } @Override public Future<RpcResult<StopOutput>> stop(StopInput stopInput){ logger.debug("Input received : " + stopInput); final Date startTime = new Date(); Status status = this.buildStatus(OAMCommandStatus.ACCEPTED); final CommonHeader commonHeader = stopInput.getCommonHeader(); try { setInitialLogProperties(commonHeader,RPC.stop); //Close the gate so that no more new LCM request will be excepted. LCMStateManager lcmStateManager = getService(LCMStateManager.class); lcmStateManager.disableLCMOperations(); //Begin monitoring outstanding LCM request scheduleOutstandingLCMRequestMonitor(commonHeader,startTime); } catch(Throwable t) { status = unexpectedOAMError(t,RPC.stop); } finally { LoggingUtils.auditWarn(startTime.toInstant(), new Date(System.currentTimeMillis()).toInstant(), String.valueOf(status.getCode()), status.getMessage(), this.getClass().getCanonicalName(), Msg.OAM_OPERATION_STOPPING, getAppcName() ); this.clearRequestLogProperties(); } StopOutputBuilder stopOutputBuilder = new StopOutputBuilder(); stopOutputBuilder.setStatus(status); stopOutputBuilder.setCommonHeader(commonHeader); StopOutput stopOutput = stopOutputBuilder.build(); return RpcResultBuilder.success(stopOutput).buildFuture(); } @Override public Future<RpcResult<StartOutput>> start(StartInput startInput){ logger.debug("Input received : " + startInput); final Date startTime = new Date(); Status status = this.buildStatus(OAMCommandStatus.ACCEPTED); final CommonHeader commonHeader = startInput.getCommonHeader(); try { setInitialLogProperties(commonHeader,RPC.start); this.scheduleStartingAPPC(commonHeader,startTime); } catch(Throwable t) { status = unexpectedOAMError(t,RPC.start); } finally { LoggingUtils.auditWarn(startTime.toInstant(), new Date(System.currentTimeMillis()).toInstant(), String.valueOf(status.getCode()), status.getMessage(), this.getClass().getCanonicalName(), Msg.OAM_OPERATION_STARTING, getAppcName() ); this.clearRequestLogProperties(); } StartOutputBuilder startOutputBuilder = new StartOutputBuilder(); startOutputBuilder.setStatus(status); startOutputBuilder.setCommonHeader(commonHeader); StartOutput startOutput = startOutputBuilder.build(); return RpcResultBuilder.success(startOutput).buildFuture(); } private <T> T getService(Class<T> _class) throws APPCException { BundleContext bctx = FrameworkUtil.getBundle(_class).getBundleContext(); ServiceReference sref = bctx.getServiceReference(_class.getName()); if (sref != null) { if(logger.isTraceEnabled()) { logger.debug("Using the BundleContext to fetched the service reference for " + _class.getName()); } return (T) bctx.getService(sref); } else { throw new APPCException("Using the BundleContext failed to to fetch service reference for " + _class.getName()); } } private Status buildStatus(OAMCommandStatus osmCommandStatus){ StatusBuilder status = new StatusBuilder(); status.setCode(osmCommandStatus.getResponseCode()); status.setMessage(osmCommandStatus.getResponseMessage()); return status.build(); } private Status buildStatus(OAMCommandStatus osmCommandStatus,Params params){ StatusBuilder status = new StatusBuilder(); status.setCode(osmCommandStatus.getResponseCode()); status.setMessage(osmCommandStatus.getFormattedMessage(params)); return status.build(); } private void clearRequestLogProperties() { try { MDC.remove(MDC_KEY_REQUEST_ID); MDC.remove(MDC_SERVICE_INSTANCE_ID); MDC.remove(MDC_SERVICE_NAME); MDC.remove(LoggingConstants.MDCKeys.PARTNER_NAME); MDC.remove(LoggingConstants.MDCKeys.TARGET_VIRTUAL_ENTITY); } catch (Exception e) { } } private void setInitialLogProperties(CommonHeader commonHeader,RPC action) { try { MDC.put(MDC_KEY_REQUEST_ID, commonHeader.getRequestId()); MDC.put(LoggingConstants.MDCKeys.PARTNER_NAME, commonHeader.getOriginatorId()); MDC.put(MDC_INSTANCE_UUID, ""); // value should be created in the future try { MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getCanonicalHostName()); //Don't change it to a .getHostName() again please. It's wrong! MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress()); MDC.put(LoggingConstants.MDCKeys.SERVER_NAME, InetAddress.getLocalHost().getHostName()); MDC.put(MDC_SERVICE_NAME, action.name()); } catch (Exception e) { logger.debug("MDC constant error",e); } } catch (RuntimeException e) { //ignore } } private void storeErrorMessageToLog(Status status, String additionalMessage) { LoggingUtils.logErrorMessage( String.valueOf(status.getCode()), status.getMessage(), LoggingConstants.TargetNames.APPC, LoggingConstants.TargetNames.APPC_OAM_PROVIDER, additionalMessage, this.getClass().getCanonicalName()); } private String getAppcName(){ return configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); } private Status unexpectedOAMError(Throwable t,RPC action){ final String appName = getAppcName(); String exceptionMessage = t.getMessage() != null ? t.getMessage() : t.toString(); String errorMessage = EELFResourceManager.format(Msg.OAM_OPERATION_EXCEPTION, t, appName, t.getClass().getSimpleName(), action.name(), exceptionMessage); Params params = new Params().addParam("errorMsg", exceptionMessage); Status status = buildStatus( OAMCommandStatus.UNEXPECTED_ERROR, params ); storeErrorMessageToLog(status,errorMessage); return status; } private int getInprogressLCMRequestCount() throws APPCException { RequestHandler requestHandler = getService(RequestHandler.class); if(requestHandler == null) { return 0; } int inprogressRequestCount = requestHandler.getInprogressRequestCount(); return inprogressRequestCount; } private void scheduleOutstandingLCMRequestMonitor(final CommonHeader commonHeader,final Date startTime){ class MyCommand implements Runnable{ public ScheduledFuture<?> myScheduledFuture = null; @Override public void run() { try { setInitialLogProperties(commonHeader, RPC.stop); logDebug("Executing stopping task "); ScheduledFuture<?> currentScheduledFuture = AppcOam.this.outstandingLCMRequestMonitorSheduledFuture; //cancel myself if I am not the current outstandingLCMRequestMonitor if(currentScheduledFuture != myScheduledFuture){ myScheduledFuture.cancel(false); return; } Status status = buildStatus(OAMCommandStatus.SUCCESS); try { //log status and return if there are still LCM request in progress int inprogressRequestCount = getInprogressLCMRequestCount(); if (inprogressRequestCount > 0) { logDebug("The application '%s' has '%s' outstanding LCM request to complete before coming to a complete stop. ", getAppcName(), inprogressRequestCount ); return; } } catch (Throwable t) { status = unexpectedOAMError(t, RPC.stop); myScheduledFuture.cancel(false); } try { OAMContext oamContext = new OAMContext(); oamContext.setRpcName(RPC.stop); oamContext.setCommonHeader(commonHeader); oamContext.setStatus(status); messageAdapter.post(oamContext); } catch(Throwable t) { status = unexpectedOAMError(t,RPC.stop); } LoggingUtils.auditWarn(startTime.toInstant(), new Date(System.currentTimeMillis()).toInstant(), String.valueOf(status.getCode()), status.getMessage(), this.getClass().getCanonicalName(), Msg.OAM_OPERATION_STOPPED, getAppcName() ); myScheduledFuture.cancel(false); } finally { clearRequestLogProperties(); } } }; MyCommand command = new MyCommand(); long initialDelay = 10000; long delay = initialDelay; command.myScheduledFuture = scheduledExecutorService.scheduleWithFixedDelay( command, initialDelay, delay, TimeUnit.MILLISECONDS ); this.outstandingLCMRequestMonitorSheduledFuture = command.myScheduledFuture; } private void scheduleStartingAPPC(final CommonHeader commonHeader,final Date startTime){ class MyCommand implements Runnable{ @Override public void run() { try { setInitialLogProperties(commonHeader, RPC.start); logDebug("Executing starting task "); Status status = buildStatus(OAMCommandStatus.SUCCESS); try { LCMStateManager lcmStateManager = getService(LCMStateManager.class); lcmStateManager.enableLCMOperations(); //cancel the current outstandingLCMRequestMonitor outstandingLCMRequestMonitorSheduledFuture = null; } catch(Throwable t) { status = unexpectedOAMError(t,RPC.start); } try { OAMContext oamContext = new OAMContext(); oamContext.setRpcName(RPC.start); oamContext.setCommonHeader(commonHeader); oamContext.setStatus(status); messageAdapter.post(oamContext); } catch(Throwable t) { status = unexpectedOAMError(t,RPC.start); } LoggingUtils.auditWarn(startTime.toInstant(), new Date(System.currentTimeMillis()).toInstant(), String.valueOf(status.getCode()), status.getMessage(), this.getClass().getCanonicalName(), Msg.OAM_OPERATION_STARTED, getAppcName() ); } finally { clearRequestLogProperties(); } } }; MyCommand command = new MyCommand(); long initialDelay = 1000; scheduledExecutorService.schedule( command, initialDelay, TimeUnit.MILLISECONDS ); } private void logDebug(String message,Object... args){ if (logger.isDebugEnabled()) { logger.debug(String.format(message,args)); } } }
3e1b17a7b2e765748771777c959d789a40881c19
647
java
Java
app/src/main/java/com/weique/overhaul/v2/mvp/contract/ParticipateEventContract.java
coypanglei/zongzhi
bc31d496533a342f0b6804ad6f7dc81c7314690b
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/weique/overhaul/v2/mvp/contract/ParticipateEventContract.java
coypanglei/zongzhi
bc31d496533a342f0b6804ad6f7dc81c7314690b
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/weique/overhaul/v2/mvp/contract/ParticipateEventContract.java
coypanglei/zongzhi
bc31d496533a342f0b6804ad6f7dc81c7314690b
[ "Apache-2.0" ]
1
2021-02-05T05:14:05.000Z
2021-02-05T05:14:05.000Z
21.566667
73
0.585781
11,470
package com.weique.overhaul.v2.mvp.contract; import com.jess.arms.mvp.IView; import com.jess.arms.mvp.IModel; /** * ================================================ * Description: * <p> * Created by MVPArmsTemplate on 10/17/2019 15:55 * * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a> * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a> * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a> * ================================================ */ public interface ParticipateEventContract { interface View extends IView { } interface Model extends IModel { } }
3e1b180aecbabb442e28493639fc7b4bc07056d4
57,703
java
Java
fe/fe-core/src/main/java/com/starrocks/sql/parser/AstBuilder.java
Gabriel39/starrocks
bae30ec93188bcd7db1cfe73809a0bd4d2e4d8c0
[ "ECL-2.0", "Zlib", "PSF-2.0", "Apache-2.0" ]
null
null
null
fe/fe-core/src/main/java/com/starrocks/sql/parser/AstBuilder.java
Gabriel39/starrocks
bae30ec93188bcd7db1cfe73809a0bd4d2e4d8c0
[ "ECL-2.0", "Zlib", "PSF-2.0", "Apache-2.0" ]
null
null
null
fe/fe-core/src/main/java/com/starrocks/sql/parser/AstBuilder.java
Gabriel39/starrocks
bae30ec93188bcd7db1cfe73809a0bd4d2e4d8c0
[ "ECL-2.0", "Zlib", "PSF-2.0", "Apache-2.0" ]
null
null
null
42.648189
119
0.622585
11,471
// This file is licensed under the Elastic License 2.0. Copyright 2021-present, StarRocks Limited. package com.starrocks.sql.parser; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.starrocks.analysis.AnalyticExpr; import com.starrocks.analysis.AnalyticWindow; import com.starrocks.analysis.ArithmeticExpr; import com.starrocks.analysis.ArrayElementExpr; import com.starrocks.analysis.ArrayExpr; import com.starrocks.analysis.ArrowExpr; import com.starrocks.analysis.BetweenPredicate; import com.starrocks.analysis.BinaryPredicate; import com.starrocks.analysis.BoolLiteral; import com.starrocks.analysis.CaseExpr; import com.starrocks.analysis.CaseWhenClause; import com.starrocks.analysis.CastExpr; import com.starrocks.analysis.CompoundPredicate; import com.starrocks.analysis.DateLiteral; import com.starrocks.analysis.DecimalLiteral; import com.starrocks.analysis.ExistsPredicate; import com.starrocks.analysis.Expr; import com.starrocks.analysis.FloatLiteral; import com.starrocks.analysis.FunctionCallExpr; import com.starrocks.analysis.FunctionParams; import com.starrocks.analysis.GroupByClause; import com.starrocks.analysis.GroupingFunctionCallExpr; import com.starrocks.analysis.InPredicate; import com.starrocks.analysis.InformationFunction; import com.starrocks.analysis.IntLiteral; import com.starrocks.analysis.IsNullPredicate; import com.starrocks.analysis.JoinOperator; import com.starrocks.analysis.LargeIntLiteral; import com.starrocks.analysis.LikePredicate; import com.starrocks.analysis.LimitElement; import com.starrocks.analysis.LiteralExpr; import com.starrocks.analysis.NullLiteral; import com.starrocks.analysis.OrderByElement; import com.starrocks.analysis.ParseNode; import com.starrocks.analysis.PartitionNames; import com.starrocks.analysis.SelectList; import com.starrocks.analysis.SelectListItem; import com.starrocks.analysis.SetType; import com.starrocks.analysis.ShowDbStmt; import com.starrocks.analysis.ShowTableStmt; import com.starrocks.analysis.SlotRef; import com.starrocks.analysis.StatementBase; import com.starrocks.analysis.StringLiteral; import com.starrocks.analysis.Subquery; import com.starrocks.analysis.SysVariableDesc; import com.starrocks.analysis.TableName; import com.starrocks.analysis.TimestampArithmeticExpr; import com.starrocks.analysis.TypeDef; import com.starrocks.analysis.UseStmt; import com.starrocks.analysis.ValueList; import com.starrocks.catalog.ArrayType; import com.starrocks.catalog.PrimitiveType; import com.starrocks.catalog.ScalarType; import com.starrocks.catalog.Type; import com.starrocks.common.AnalysisException; import com.starrocks.common.ErrorCode; import com.starrocks.common.ErrorReport; import com.starrocks.common.NotImplementedException; import com.starrocks.sql.analyzer.RelationId; import com.starrocks.sql.analyzer.SemanticException; import com.starrocks.sql.ast.CTERelation; import com.starrocks.sql.ast.ExceptRelation; import com.starrocks.sql.ast.Identifier; import com.starrocks.sql.ast.IntersectRelation; import com.starrocks.sql.ast.IntervalLiteral; import com.starrocks.sql.ast.JoinRelation; import com.starrocks.sql.ast.QualifiedName; import com.starrocks.sql.ast.QueryRelation; import com.starrocks.sql.ast.QueryStatement; import com.starrocks.sql.ast.Relation; import com.starrocks.sql.ast.SelectRelation; import com.starrocks.sql.ast.SubqueryRelation; import com.starrocks.sql.ast.TableFunctionRelation; import com.starrocks.sql.ast.TableRelation; import com.starrocks.sql.ast.UnionRelation; import com.starrocks.sql.ast.ValuesRelation; import com.starrocks.sql.optimizer.base.SetQualifier; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.tree.TerminalNode; import java.io.StringWriter; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import static java.util.stream.Collectors.toList; public class AstBuilder extends StarRocksBaseVisitor<ParseNode> { @Override public ParseNode visitSingleStatement(StarRocksParser.SingleStatementContext context) { return visit(context.statement()); } // -------------------------------- Statement ------------------------------ @Override public ParseNode visitShowDatabases(StarRocksParser.ShowDatabasesContext context) { if (context.pattern != null) { StringLiteral stringLiteral = (StringLiteral) visit(context.pattern); return new ShowDbStmt(stringLiteral.getValue()); } else if (context.expression() != null) { return new ShowDbStmt(null, (Expr) visit(context.expression())); } else { return new ShowDbStmt(null, null); } } @Override public ParseNode visitShowTables(StarRocksParser.ShowTablesContext context) { boolean isVerbose = context.FULL() != null; String database = null; if (context.db != null) { database = context.db.getText(); } if (context.pattern != null) { StringLiteral stringLiteral = (StringLiteral) visit(context.pattern); return new ShowTableStmt(database, isVerbose, stringLiteral.getValue()); } else if (context.expression() != null) { return new ShowTableStmt(database, isVerbose, null, (Expr) visit(context.expression())); } else { return new ShowTableStmt(database, isVerbose, null); } } @Override public ParseNode visitUse(StarRocksParser.UseContext context) { Identifier identifier = (Identifier) visit(context.identifier()); return new UseStmt(identifier.getValue()); } @Override public ParseNode visitQueryStatement(StarRocksParser.QueryStatementContext context) { QueryRelation queryRelation = (QueryRelation) visit(context.query()); return new QueryStatement(queryRelation); } @Override public ParseNode visitExplain(StarRocksParser.ExplainContext context) { QueryStatement queryStatement = (QueryStatement) visit(context.queryStatement()); StatementBase.ExplainLevel explainLevel = StatementBase.ExplainLevel.NORMAL; if (context.LOGICAL() != null) { explainLevel = StatementBase.ExplainLevel.LOGICAL; } else if (context.VERBOSE() != null) { explainLevel = StatementBase.ExplainLevel.VERBOSE; } else if (context.COSTS() != null) { explainLevel = StatementBase.ExplainLevel.COST; } queryStatement.setIsExplain(true, explainLevel); return queryStatement; } // ------------------------------------------- Query Relation ------------------------------------------- @Override public ParseNode visitQuery(StarRocksParser.QueryContext context) { QueryRelation queryRelation = (QueryRelation) visit(context.queryNoWith()); List<CTERelation> withQuery = new ArrayList<>(); if (context.withClause() != null) { withQuery = visit(context.withClause().commonTableExpression(), CTERelation.class); } withQuery.forEach(queryRelation::addCTERelation); return queryRelation; } @Override public ParseNode visitCommonTableExpression(StarRocksParser.CommonTableExpressionContext context) { List<Identifier> columns = null; if (context.columnAliases() != null) { columns = visit(context.columnAliases().identifier(), Identifier.class); } List<String> columnNames = null; if (columns != null) { columnNames = columns.stream().map(Identifier::getValue).collect(toList()); } QueryRelation queryRelation = (QueryRelation) visit(context.query()); return new CTERelation( RelationId.of(queryRelation).hashCode(), ((Identifier) visit(context.name)).getValue(), columnNames, queryRelation); } @Override public ParseNode visitQueryNoWith(StarRocksParser.QueryNoWithContext context) { List<OrderByElement> orderByElements = new ArrayList<>(); if (context.ORDER() != null) { orderByElements.addAll(visit(context.sortItem(), OrderByElement.class)); } LimitElement limitElement = null; if (context.limitElement() != null) { limitElement = (LimitElement) visit(context.limitElement()); } QueryRelation term = (QueryRelation) visit(context.queryTerm()); term.setOrderBy(orderByElements); term.setLimit(limitElement); return term; } @Override public ParseNode visitSetOperation(StarRocksParser.SetOperationContext context) { QueryRelation left = (QueryRelation) visit(context.left); QueryRelation right = (QueryRelation) visit(context.right); boolean distinct = true; if (context.setQuantifier() != null) { if (context.setQuantifier().DISTINCT() != null) { distinct = true; } else if (context.setQuantifier().ALL() != null) { distinct = false; } } SetQualifier setQualifier = distinct ? SetQualifier.DISTINCT : SetQualifier.ALL; switch (context.operator.getType()) { case StarRocksLexer.UNION: if (left instanceof UnionRelation && ((UnionRelation) left).getQualifier().equals(setQualifier)) { ((UnionRelation) left).addRelation(right); return left; } else { return new UnionRelation(Lists.newArrayList(left, right), setQualifier); } case StarRocksLexer.INTERSECT: if (left instanceof IntersectRelation && ((IntersectRelation) left).getQualifier().equals(setQualifier)) { ((IntersectRelation) left).addRelation(right); return left; } else { return new IntersectRelation(Lists.newArrayList(left, right), setQualifier); } case StarRocksLexer.EXCEPT: if (left instanceof ExceptRelation && ((ExceptRelation) left).getQualifier().equals(setQualifier)) { ((ExceptRelation) left).addRelation(right); return left; } else { return new ExceptRelation(Lists.newArrayList(left, right), setQualifier); } } throw new IllegalArgumentException("Unsupported set operation: " + context.operator.getText()); } @Override public ParseNode visitQuerySpecification(StarRocksParser.QuerySpecificationContext context) { Relation from = null; List<SelectListItem> selectItems = visit(context.selectItem(), SelectListItem.class); if (context.fromClause() instanceof StarRocksParser.DualContext) { if (selectItems.stream().anyMatch(SelectListItem::isStar)) { ErrorReport.reportSemanticException(ErrorCode.ERR_NO_TABLES_USED); } } else { StarRocksParser.FromContext fromContext = (StarRocksParser.FromContext) context.fromClause(); List<Relation> relations = visit(fromContext.relation(), Relation.class); if (!relations.isEmpty()) { Iterator<Relation> iterator = relations.iterator(); Relation relation = iterator.next(); while (iterator.hasNext()) { relation = new JoinRelation(JoinOperator.CROSS_JOIN, relation, iterator.next(), null, false); } from = relation; } } if (from == null) { ArrayList<Expr> row = new ArrayList<>(); List<String> columnNames = new ArrayList<>(); for (SelectListItem selectListItem : selectItems) { row.add(selectListItem.getExpr()); String name; if (selectListItem.getAlias() != null) { name = selectListItem.getAlias(); } else if (selectListItem.getExpr() instanceof SlotRef) { name = ((SlotRef) selectListItem.getExpr()).getColumnName(); } else { name = selectListItem.getExpr().toColumnLabel(); } columnNames.add(name); } List<ArrayList<Expr>> rows = new ArrayList<>(); rows.add(row); return new ValuesRelation(rows, columnNames); } boolean isDistinct = context.setQuantifier() != null && context.setQuantifier().DISTINCT() != null; SelectList selectList = new SelectList(selectItems, isDistinct); if (context.hint() != null) { Map<String, String> selectHints = new HashMap<>(); for (StarRocksParser.HintMapContext hintMapContext : context.hint().hintMap()) { String key = hintMapContext.k.getText(); String value = hintMapContext.v.getText(); selectHints.put(key, value); } selectList.setOptHints(selectHints); } return new SelectRelation( selectList, from, visitIfPresent(context.where, Expr.class).orElse(null), visitIfPresent(context.groupingElement(), GroupByClause.class).orElse(null), visitIfPresent(context.having, Expr.class).orElse(null)); } @Override public ParseNode visitSelectSingle(StarRocksParser.SelectSingleContext context) { String alias = null; if (context.identifier() != null) { alias = ((Identifier) visit(context.identifier())).getValue(); } else if (context.string() != null) { alias = ((StringLiteral) visit(context.string())).getStringValue(); } return new SelectListItem((Expr) visit(context.expression()), alias); } @Override public ParseNode visitSelectAll(StarRocksParser.SelectAllContext context) { if (context.qualifiedName() != null) { QualifiedName qualifiedName = getQualifiedName(context.qualifiedName()); return new SelectListItem(qualifiedNameToTableName(qualifiedName)); } return new SelectListItem(null); } @Override public ParseNode visitSingleGroupingSet(StarRocksParser.SingleGroupingSetContext context) { return new GroupByClause(new ArrayList<>(visit(context.expression(), Expr.class)), GroupByClause.GroupingType.GROUP_BY); } @Override public ParseNode visitRollup(StarRocksParser.RollupContext context) { List<Expr> groupingExprs = visit(context.expression(), Expr.class); return new GroupByClause(new ArrayList<>(groupingExprs), GroupByClause.GroupingType.ROLLUP); } @Override public ParseNode visitCube(StarRocksParser.CubeContext context) { List<Expr> groupingExprs = visit(context.expression(), Expr.class); return new GroupByClause(new ArrayList<>(groupingExprs), GroupByClause.GroupingType.CUBE); } @Override public ParseNode visitMultipleGroupingSets(StarRocksParser.MultipleGroupingSetsContext context) { List<ArrayList<Expr>> groupingSets = new ArrayList<>(); for (StarRocksParser.GroupingSetContext groupingSetContext : context.groupingSet()) { List<Expr> l = visit(groupingSetContext.expression(), Expr.class); groupingSets.add(new ArrayList<>(l)); } return new GroupByClause(groupingSets, GroupByClause.GroupingType.GROUPING_SETS); } @Override public ParseNode visitGroupingOperation(StarRocksParser.GroupingOperationContext context) { List<Expr> arguments = visit(context.expression(), Expr.class); return new GroupingFunctionCallExpr("grouping", arguments); } @Override public ParseNode visitWindowFrame(StarRocksParser.WindowFrameContext context) { if (context.end != null) { return new AnalyticWindow( getFrameType(context.frameType), (AnalyticWindow.Boundary) visit(context.start), (AnalyticWindow.Boundary) visit(context.end)); } else { return new AnalyticWindow( getFrameType(context.frameType), (AnalyticWindow.Boundary) visit(context.start)); } } private static AnalyticWindow.Type getFrameType(Token type) { switch (type.getType()) { case StarRocksLexer.RANGE: return AnalyticWindow.Type.RANGE; case StarRocksLexer.ROWS: return AnalyticWindow.Type.ROWS; } throw new IllegalArgumentException("Unsupported frame type: " + type.getText()); } @Override public ParseNode visitUnboundedFrame(StarRocksParser.UnboundedFrameContext context) { return new AnalyticWindow.Boundary(getUnboundedFrameBoundType(context.boundType), null); } @Override public ParseNode visitBoundedFrame(StarRocksParser.BoundedFrameContext context) { return new AnalyticWindow.Boundary(getBoundedFrameBoundType(context.boundType), (Expr) visit(context.expression())); } @Override public ParseNode visitCurrentRowBound(StarRocksParser.CurrentRowBoundContext context) { return new AnalyticWindow.Boundary(AnalyticWindow.BoundaryType.CURRENT_ROW, null); } private static AnalyticWindow.BoundaryType getBoundedFrameBoundType(Token token) { switch (token.getType()) { case StarRocksLexer.PRECEDING: return AnalyticWindow.BoundaryType.PRECEDING; case StarRocksLexer.FOLLOWING: return AnalyticWindow.BoundaryType.FOLLOWING; } throw new IllegalArgumentException("Unsupported bound type: " + token.getText()); } private static AnalyticWindow.BoundaryType getUnboundedFrameBoundType(Token token) { switch (token.getType()) { case StarRocksLexer.PRECEDING: return AnalyticWindow.BoundaryType.UNBOUNDED_PRECEDING; case StarRocksLexer.FOLLOWING: return AnalyticWindow.BoundaryType.UNBOUNDED_FOLLOWING; } throw new IllegalArgumentException("Unsupported bound type: " + token.getText()); } @Override public ParseNode visitSortItem(StarRocksParser.SortItemContext context) { return new OrderByElement( (Expr) visit(context.expression()), getOrderingType(context.ordering), getNullOrderingType(getOrderingType(context.ordering), context.nullOrdering)); } private static boolean getNullOrderingType(boolean isAsc, Token token) { if (token == null) { return isAsc; } switch (token.getType()) { case StarRocksLexer.FIRST: return true; case StarRocksLexer.LAST: return false; } throw new IllegalArgumentException("Unsupported ordering: " + token.getText()); } private static boolean getOrderingType(Token token) { if (token == null) { return true; } switch (token.getType()) { case StarRocksLexer.ASC: return true; case StarRocksLexer.DESC: return false; } throw new IllegalArgumentException("Unsupported ordering: " + token.getText()); } @Override public ParseNode visitLimitElement(StarRocksParser.LimitElementContext context) { long limit = Long.parseLong(context.limit.getText()); long offset = 0; if (context.offset != null) { offset = Long.parseLong(context.offset.getText()); } return new LimitElement(offset, limit); } // ------------------------------------------- Relation ------------------------------------------- @Override public ParseNode visitTableName(StarRocksParser.TableNameContext context) { QualifiedName qualifiedName = getQualifiedName(context.qualifiedName()); TableName tableName = qualifiedNameToTableName(qualifiedName); PartitionNames partitionNames = null; if (context.partitionNames() != null) { partitionNames = (PartitionNames) visit(context.partitionNames()); } TableRelation tableRelation = new TableRelation(tableName, partitionNames); if (context.hint() != null) { for (TerminalNode hint : context.hint().IDENTIFIER()) { if (hint.getText().equalsIgnoreCase("_META_")) { tableRelation.setMetaQuery(true); } } } return tableRelation; } @Override public ParseNode visitAliasedRelation(StarRocksParser.AliasedRelationContext context) { Relation child = (Relation) visit(context.relationPrimary()); if (context.identifier() == null) { return child; } Identifier identifier = (Identifier) visit(context.identifier()); child.setAlias(new TableName(null, identifier.getValue())); return child; } @Override public ParseNode visitJoinRelation(StarRocksParser.JoinRelationContext context) { Relation left = (Relation) visit(context.left); Relation right = (Relation) visit(context.rightRelation); JoinOperator joinType = JoinOperator.INNER_JOIN; if (context.joinType().CROSS() != null) { joinType = JoinOperator.CROSS_JOIN; } else if (context.joinType().LEFT() != null) { if (context.joinType().OUTER() != null) { joinType = JoinOperator.LEFT_OUTER_JOIN; } else if (context.joinType().SEMI() != null) { joinType = JoinOperator.LEFT_SEMI_JOIN; } else if (context.joinType().ANTI() != null) { joinType = JoinOperator.LEFT_ANTI_JOIN; } else { joinType = JoinOperator.LEFT_OUTER_JOIN; } } else if (context.joinType().RIGHT() != null) { if (context.joinType().OUTER() != null) { joinType = JoinOperator.RIGHT_OUTER_JOIN; } else if (context.joinType().SEMI() != null) { joinType = JoinOperator.RIGHT_SEMI_JOIN; } else if (context.joinType().ANTI() != null) { joinType = JoinOperator.RIGHT_ANTI_JOIN; } else { joinType = JoinOperator.RIGHT_OUTER_JOIN; } } else if (context.joinType().FULL() != null) { joinType = JoinOperator.FULL_OUTER_JOIN; } Expr predicate = null; List<String> usingColNames = null; if (context.joinCriteria() != null) { if (context.joinCriteria().ON() != null) { predicate = (Expr) visit(context.joinCriteria().expression()); } else if (context.joinCriteria().USING() != null) { List<Identifier> criteria = visit(context.joinCriteria().identifier(), Identifier.class); usingColNames = criteria.stream().map(Identifier::getValue).collect(Collectors.toList()); } else { throw new IllegalArgumentException("Unsupported join criteria"); } } JoinRelation joinRelation = new JoinRelation(joinType, left, right, predicate, context.LATERAL() != null); joinRelation.setUsingColNames(usingColNames); if (context.hint() != null) { joinRelation.setJoinHint(context.hint().IDENTIFIER(0).getText()); } return joinRelation; } @Override public ParseNode visitInlineTable(StarRocksParser.InlineTableContext context) { List<ValueList> rowValues = visit(context.rowConstructor(), ValueList.class); List<ArrayList<Expr>> rows = rowValues.stream().map(ValueList::getFirstRow).collect(toList()); List<String> colNames = new ArrayList<>(); for (int i = 0; i < rows.get(0).size(); ++i) { colNames.add("column_" + i); } return new ValuesRelation(rows, colNames); } @Override public ParseNode visitTableFunction(StarRocksParser.TableFunctionContext context) { return new TableFunctionRelation(getQualifiedName(context.qualifiedName()).toString(), new FunctionParams(false, visit(context.expression(), Expr.class))); } @Override public ParseNode visitRowConstructor(StarRocksParser.RowConstructorContext context) { ArrayList<Expr> row = new ArrayList<>(visit(context.expression(), Expr.class)); return new ValueList(row); } @Override public ParseNode visitPartitionNames(StarRocksParser.PartitionNamesContext context) { List<Identifier> identifierList = visit(context.identifier(), Identifier.class); return new PartitionNames(false, identifierList.stream().map(Identifier::getValue).collect(toList())); } // ------------------------------------------- SubQuery ------------------------------------------ @Override public ParseNode visitSubquery(StarRocksParser.SubqueryContext context) { return new SubqueryRelation(null, (QueryRelation) visit(context.query())); } @Override public ParseNode visitSubqueryPrimary(StarRocksParser.SubqueryPrimaryContext context) { SubqueryRelation subqueryRelation = (SubqueryRelation) visit(context.subquery()); return subqueryRelation.getQuery(); } @Override public ParseNode visitSubqueryRelation(StarRocksParser.SubqueryRelationContext context) { return visit(context.subquery()); } @Override public ParseNode visitSubqueryExpression(StarRocksParser.SubqueryExpressionContext context) { SubqueryRelation subqueryRelation = (SubqueryRelation) visit(context.subquery()); return new Subquery(subqueryRelation.getQuery()); } @Override public ParseNode visitInSubquery(StarRocksParser.InSubqueryContext context) { boolean isNotIn = context.NOT() != null; QueryRelation query = (QueryRelation) visit(context.query()); return new InPredicate((Expr) visit(context.value), new Subquery(query), isNotIn); } @Override public ParseNode visitExists(StarRocksParser.ExistsContext context) { QueryRelation query = (QueryRelation) visit(context.query()); return new ExistsPredicate(new Subquery(query), false); } @Override public ParseNode visitScalarSubquery(StarRocksParser.ScalarSubqueryContext context) { BinaryPredicate.Operator op = getComparisonOperator(((TerminalNode) context.comparisonOperator().getChild(0)) .getSymbol()); Subquery subquery = new Subquery((QueryRelation) visit(context.query())); return new BinaryPredicate(op, (Expr) visit(context.booleanExpression()), subquery); } // ------------------------------------------- Logical Expression ------------------------------------------- @Override public ParseNode visitLogicalNot(StarRocksParser.LogicalNotContext context) { return new CompoundPredicate(CompoundPredicate.Operator.NOT, (Expr) visit(context.expression()), null); } @Override public ParseNode visitLogicalBinary(StarRocksParser.LogicalBinaryContext context) { Expr left = (Expr) visit(context.left); Expr right = (Expr) visit(context.right); return new CompoundPredicate(getLogicalBinaryOperator(context.operator), left, right); } private static CompoundPredicate.Operator getLogicalBinaryOperator(Token token) { switch (token.getType()) { case StarRocksLexer.AND: return CompoundPredicate.Operator.AND; case StarRocksLexer.OR: return CompoundPredicate.Operator.OR; } throw new IllegalArgumentException("Unsupported operator: " + token.getText()); } // ------------------------------------------- Predicate Expression ------------------------------------------- @Override public ParseNode visitPredicate(StarRocksParser.PredicateContext context) { if (context.predicateOperations() != null) { return visit(context.predicateOperations()); } else { return visit(context.valueExpression()); } } @Override public ParseNode visitIsNull(StarRocksParser.IsNullContext context) { Expr child = (Expr) visit(context.booleanExpression()); if (context.NOT() == null) { return new IsNullPredicate(child, false); } else { return new IsNullPredicate(child, true); } } @Override public ParseNode visitComparison(StarRocksParser.ComparisonContext context) { BinaryPredicate.Operator op = getComparisonOperator(((TerminalNode) context.comparisonOperator().getChild(0)) .getSymbol()); return new BinaryPredicate(op, (Expr) visit(context.left), (Expr) visit(context.right)); } private static BinaryPredicate.Operator getComparisonOperator(Token symbol) { switch (symbol.getType()) { case StarRocksParser.EQ: return BinaryPredicate.Operator.EQ; case StarRocksParser.NEQ: return BinaryPredicate.Operator.NE; case StarRocksParser.LT: return BinaryPredicate.Operator.LT; case StarRocksParser.LTE: return BinaryPredicate.Operator.LE; case StarRocksParser.GT: return BinaryPredicate.Operator.GT; case StarRocksParser.GTE: return BinaryPredicate.Operator.GE; case StarRocksParser.EQ_FOR_NULL: return BinaryPredicate.Operator.EQ_FOR_NULL; } throw new IllegalArgumentException("Unsupported operator: " + symbol.getText()); } @Override public ParseNode visitInList(StarRocksParser.InListContext context) { boolean isNotIn = context.NOT() != null; return new InPredicate( (Expr) visit(context.value), visit(context.expression(), Expr.class), isNotIn); } @Override public ParseNode visitBetween(StarRocksParser.BetweenContext context) { boolean isNotBetween = context.NOT() != null; return new BetweenPredicate( (Expr) visit(context.value), (Expr) visit(context.lower), (Expr) visit(context.upper), isNotBetween); } @Override public ParseNode visitLike(StarRocksParser.LikeContext context) { LikePredicate likePredicate; if (context.REGEXP() != null) { likePredicate = new LikePredicate(LikePredicate.Operator.REGEXP, (Expr) visit(context.value), (Expr) visit(context.pattern)); } else { likePredicate = new LikePredicate( LikePredicate.Operator.LIKE, (Expr) visit(context.value), (Expr) visit(context.pattern)); } if (context.NOT() != null) { return new CompoundPredicate(CompoundPredicate.Operator.NOT, likePredicate, null); } else { return likePredicate; } } @Override public ParseNode visitSimpleCase(StarRocksParser.SimpleCaseContext context) { return new CaseExpr( (Expr) visit(context.valueExpression()), visit(context.whenClause(), CaseWhenClause.class), visitIfPresent(context.elseExpression, Expr.class).orElse(null)); } @Override public ParseNode visitSearchedCase(StarRocksParser.SearchedCaseContext context) { return new CaseExpr( null, visit(context.whenClause(), CaseWhenClause.class), visitIfPresent(context.elseExpression, Expr.class).orElse(null)); } @Override public ParseNode visitWhenClause(StarRocksParser.WhenClauseContext context) { return new CaseWhenClause((Expr) visit(context.condition), (Expr) visit(context.result)); } // ------------------------------------------- Value Expression ------------------------------------------- @Override public ParseNode visitArithmeticUnary(StarRocksParser.ArithmeticUnaryContext context) { Expr child = (Expr) visit(context.valueExpression()); switch (context.operator.getType()) { case StarRocksLexer.MINUS: if (child.isLiteral() && child.getType().isNumericType()) { try { ((LiteralExpr) child).swapSign(); } catch (NotImplementedException e) { throw new ParsingException(e.getMessage()); } return child; } else { return new ArithmeticExpr(ArithmeticExpr.Operator.MULTIPLY, new IntLiteral(-1), child); } case StarRocksLexer.PLUS: return child; case StarRocksLexer.BITNOT: return new ArithmeticExpr(ArithmeticExpr.Operator.BITNOT, child, null); default: throw new UnsupportedOperationException("Unsupported sign: " + context.operator.getText()); } } @Override public ParseNode visitArithmeticBinary(StarRocksParser.ArithmeticBinaryContext context) { Expr left = (Expr) visit(context.left); Expr right = (Expr) visit(context.right); if (left instanceof IntervalLiteral) { return new TimestampArithmeticExpr(getArithmeticBinaryOperator(context.operator), right, ((IntervalLiteral) left).getValue(), ((IntervalLiteral) left).getTimeUnitIdent(), false); } if (right instanceof IntervalLiteral) { return new TimestampArithmeticExpr(getArithmeticBinaryOperator(context.operator), left, ((IntervalLiteral) right).getValue(), ((IntervalLiteral) right).getTimeUnitIdent(), false); } return new ArithmeticExpr(getArithmeticBinaryOperator(context.operator), left, right); } private static ArithmeticExpr.Operator getArithmeticBinaryOperator(Token operator) { switch (operator.getType()) { case StarRocksLexer.PLUS: return ArithmeticExpr.Operator.ADD; case StarRocksLexer.MINUS: return ArithmeticExpr.Operator.SUBTRACT; case StarRocksLexer.ASTERISK: return ArithmeticExpr.Operator.MULTIPLY; case StarRocksLexer.SLASH: return ArithmeticExpr.Operator.DIVIDE; case StarRocksLexer.PERCENT: return ArithmeticExpr.Operator.MOD; case StarRocksLexer.INT_DIV: return ArithmeticExpr.Operator.INT_DIVIDE; case StarRocksLexer.BITAND: return ArithmeticExpr.Operator.BITAND; case StarRocksLexer.BITOR: return ArithmeticExpr.Operator.BITOR; case StarRocksLexer.BITXOR: return ArithmeticExpr.Operator.BITXOR; } throw new UnsupportedOperationException("Unsupported operator: " + operator.getText()); } @Override public ParseNode visitFunctionCall(StarRocksParser.FunctionCallContext context) { if (context.IF() != null) { return new FunctionCallExpr("if", visit(context.expression(), Expr.class)); } boolean isStar = context.ASTERISK() != null; boolean distinct = context.setQuantifier() != null && context.setQuantifier().DISTINCT() != null; String functionName = getQualifiedName(context.qualifiedName()).toString(); if (functionName.equalsIgnoreCase("DATE_ADD") || functionName.equalsIgnoreCase("ADDDATE") || functionName.equalsIgnoreCase("DATE_SUB") || functionName.equalsIgnoreCase("SUBDATE")) { if (context.expression().size() != 2) { throw new ParsingException( functionName + " must as format " + functionName + "(date,INTERVAL expr unit)"); } Expr e1 = (Expr) visit(context.expression(0)); Expr e2 = (Expr) visit(context.expression(1)); if (!(e2 instanceof IntervalLiteral)) { e2 = new IntervalLiteral(e2, "DAY"); } IntervalLiteral intervalLiteral = (IntervalLiteral) e2; return new TimestampArithmeticExpr(functionName, e1, intervalLiteral.getValue(), intervalLiteral.getTimeUnitIdent()); } if (functionName.equalsIgnoreCase("TIMESTAMPADD") || functionName.equalsIgnoreCase("TIMESTAMPDIFF")) { if (context.expression().size() != 3) { throw new ParsingException( functionName + " must as format " + functionName + "(unit,interval,datetime_expr)"); } Identifier e1 = (Identifier) visit(context.expression(0)); Expr e2 = (Expr) visit(context.expression(1)); Expr e3 = (Expr) visit(context.expression(2)); return new TimestampArithmeticExpr(functionName, e3, e2, e1.getValue()); } FunctionCallExpr functionCallExpr; if (isStar) { functionCallExpr = new FunctionCallExpr(getQualifiedName(context.qualifiedName()).toString(), FunctionParams.createStarParam()); } else { functionCallExpr = new FunctionCallExpr(getQualifiedName(context.qualifiedName()).toString(), new FunctionParams(distinct, visit(context.expression(), Expr.class))); } if (context.over() != null) { functionCallExpr.setIsAnalyticFnCall(true); List<OrderByElement> orderByElements = new ArrayList<>(); if (context.over().ORDER() != null) { orderByElements = visit(context.over().sortItem(), OrderByElement.class); } List<Expr> partitionExprs = visit(context.over().partition, Expr.class); return new AnalyticExpr(functionCallExpr, partitionExprs, orderByElements, visitIfPresent(context.over().windowFrame(), AnalyticWindow.class).orElse(null)); } return functionCallExpr; } @Override public ParseNode visitWindowFunctionCall(StarRocksParser.WindowFunctionCallContext context) { FunctionCallExpr functionCallExpr = (FunctionCallExpr) visit(context.windowFunction()); functionCallExpr.setIsAnalyticFnCall(true); List<OrderByElement> orderByElements = new ArrayList<>(); if (context.over().ORDER() != null) { orderByElements = visit(context.over().sortItem(), OrderByElement.class); } List<Expr> partitionExprs = visit(context.over().partition, Expr.class); return new AnalyticExpr(functionCallExpr, partitionExprs, orderByElements, visitIfPresent(context.over().windowFrame(), AnalyticWindow.class).orElse(null)); } public static final ImmutableSet<String> WindowFunctionSet = ImmutableSet.of( "row_number", "rank", "dense_rank", "lead", "lag", "first_value", "last_value"); @Override public ParseNode visitWindowFunction(StarRocksParser.WindowFunctionContext context) { if (WindowFunctionSet.contains(context.name.getText().toLowerCase())) { return new FunctionCallExpr(context.name.getText().toLowerCase(), new FunctionParams(false, visit(context.expression(), Expr.class))); } throw new ParsingException("Unknown window function " + context.name.getText()); } @Override public ParseNode visitConcatenation(StarRocksParser.ConcatenationContext context) { return new FunctionCallExpr("concat", new FunctionParams(Lists.newArrayList(visit(context.valueExpression(), Expr.class)))); } @Override public ParseNode visitExtract(StarRocksParser.ExtractContext context) { String fieldString = context.identifier().getText(); return new FunctionCallExpr(fieldString, new FunctionParams(Lists.newArrayList((Expr) visit(context.valueExpression())))); } @Override public ParseNode visitCast(StarRocksParser.CastContext context) { return new CastExpr(new TypeDef(getType(context.type())), (Expr) visit(context.expression())); } @Override public ParseNode visitInformationFunctionExpression(StarRocksParser.InformationFunctionExpressionContext context) { if (context.name.getText().equalsIgnoreCase("database") || context.name.getText().equalsIgnoreCase("schema") || context.name.getText().equalsIgnoreCase("user") || context.name.getText().equalsIgnoreCase("current_user") || context.name.getText().equalsIgnoreCase("connection_id")) { return new InformationFunction(context.name.getText().toUpperCase()); } throw new ParsingException("Unknown special function " + context.name.getText()); } // ------------------------------------------- Literal ------------------------------------------- @Override public ParseNode visitNullLiteral(StarRocksParser.NullLiteralContext context) { return new NullLiteral(); } @Override public ParseNode visitBooleanLiteral(StarRocksParser.BooleanLiteralContext context) { try { return new BoolLiteral(context.getText()); } catch (AnalysisException e) { throw new ParsingException("Invalid boolean literal: " + context.getText()); } } @Override public ParseNode visitNumericLiteral(StarRocksParser.NumericLiteralContext context) { return visit(context.number()); } private static final BigInteger LONG_MAX = new BigInteger("9223372036854775807"); // 2^63 - 1 private static final BigInteger LARGEINT_MAX_ABS = new BigInteger("170141183460469231731687303715884105728"); // 2^127 @Override public ParseNode visitIntegerValue(StarRocksParser.IntegerValueContext context) { try { BigInteger intLiteral = new BigInteger(context.getText()); // Note: val is positive, because we do not recognize minus charactor in 'IntegerLiteral' // -2^63 will be recognize as largeint(__int128) if (intLiteral.compareTo(LONG_MAX) <= 0) { return new IntLiteral(intLiteral.longValue()); } else if (intLiteral.compareTo(LARGEINT_MAX_ABS) <= 0) { return new LargeIntLiteral(intLiteral.toString()); } else { throw new ParsingException("Numeric overflow " + intLiteral); } } catch (NumberFormatException | AnalysisException e) { throw new ParsingException("Invalid numeric literal: " + context.getText()); } } @Override public ParseNode visitDoubleValue(StarRocksParser.DoubleValueContext context) { try { BigDecimal decimal = new BigDecimal(context.getText()); int precision = DecimalLiteral.getRealPrecision(decimal); int scale = DecimalLiteral.getRealScale(decimal); int integerPartWidth = precision - scale; if (integerPartWidth > 38) { return new FloatLiteral(context.getText()); } return new DecimalLiteral(decimal); } catch (AnalysisException | NumberFormatException e) { throw new ParsingException(e.getMessage()); } } @Override public ParseNode visitDecimalValue(StarRocksParser.DecimalValueContext context) { try { return new DecimalLiteral(context.getText()); } catch (AnalysisException e) { throw new ParsingException(e.getMessage()); } } @Override public ParseNode visitString(StarRocksParser.StringContext context) { String quotedString; if (context.SINGLE_QUOTED_TEXT() != null) { quotedString = context.SINGLE_QUOTED_TEXT().getText(); } else { quotedString = context.DOUBLE_QUOTED_TEXT().getText(); } return new StringLiteral(escapeBackSlash(quotedString.substring(1, quotedString.length() - 1))); } private static String escapeBackSlash(String str) { StringWriter writer = new StringWriter(); int strLen = str.length(); for (int i = 0; i < strLen; ++i) { char c = str.charAt(i); if (c == '\\' && (i + 1) < strLen) { switch (str.charAt(i + 1)) { case 'n': writer.append('\n'); break; case 't': writer.append('\t'); break; case 'r': writer.append('\r'); break; case 'b': writer.append('\b'); break; case '0': writer.append('\0'); // Ascii null break; case 'Z': // ^Z must be escaped on Win32 writer.append('\032'); break; case '_': case '%': writer.append('\\'); // remember prefix for wildcard /* Fall through */ default: writer.append(str.charAt(i + 1)); break; } i++; } else { writer.append(c); } } return writer.toString(); } @Override public ParseNode visitArrayConstructor(StarRocksParser.ArrayConstructorContext context) { if (context.arrayType() != null) { return new ArrayExpr( new ArrayType(getType(context.arrayType().type())), visit(context.expression(), Expr.class)); } return new ArrayExpr(null, visit(context.expression(), Expr.class)); } @Override public ParseNode visitArraySubscript(StarRocksParser.ArraySubscriptContext context) { Expr value = (Expr) visit(context.value); Expr index = (Expr) visit(context.index); return new ArrayElementExpr(value, index); } @Override public ParseNode visitInterval(StarRocksParser.IntervalContext context) { return new IntervalLiteral((Expr) visit(context.value), context.from.getText()); } @Override public ParseNode visitTypeConstructor(StarRocksParser.TypeConstructorContext context) { String value = ((StringLiteral) visit(context.string())).getValue(); try { if (context.DATE() != null) { return new DateLiteral(value, Type.DATE); } if (context.DATETIME() != null) { return new DateLiteral(value, Type.DATETIME); } } catch (AnalysisException e) { throw new ParsingException(e.getMessage()); } throw new ParsingException("Parse Error : unknown type " + context.getText()); } // ------------------------------------------- Primary Expression ------------------------------------------- @Override public ParseNode visitColumnReference(StarRocksParser.ColumnReferenceContext context) { if (context.identifier() != null) { Identifier identifier = (Identifier) visit(context.identifier()); return new SlotRef(null, identifier.getValue()); } else { QualifiedName qualifiedName = getQualifiedName(context.qualifiedName()); if (qualifiedName.getParts().size() == 3) { return new SlotRef(new TableName(qualifiedName.getParts().get(0), qualifiedName.getParts().get(1)), qualifiedName.getParts().get(2)); } else if (qualifiedName.getParts().size() == 2) { return new SlotRef(new TableName(null, qualifiedName.getParts().get(0)), qualifiedName.getParts().get(1)); } else { throw new SemanticException("Unqualified column reference " + qualifiedName); } } } @Override public ParseNode visitArrowExpression(StarRocksParser.ArrowExpressionContext context) { Expr expr = (Expr) visit(context.primaryExpression()); StringLiteral stringLiteral = (StringLiteral) visit(context.string()); return new ArrowExpr(expr, stringLiteral); } @Override public ParseNode visitVariable(StarRocksParser.VariableContext context) { SetType setType = SetType.DEFAULT; if (context.GLOBAL() != null) { setType = SetType.GLOBAL; } else if (context.LOCAL() != null || context.SESSION() != null) { setType = SetType.SESSION; } return new SysVariableDesc(context.identifier().getText(), setType); } @Override public ParseNode visitCollate(StarRocksParser.CollateContext context) { return visit(context.primaryExpression()); } @Override public ParseNode visitParenthesizedExpression(StarRocksParser.ParenthesizedExpressionContext context) { return visit(context.expression()); } @Override public ParseNode visitUnquotedIdentifier(StarRocksParser.UnquotedIdentifierContext context) { return new Identifier(context.getText()); } @Override public ParseNode visitBackQuotedIdentifier(StarRocksParser.BackQuotedIdentifierContext context) { return new Identifier(context.getText().replace("`", "")); } // ------------------------------------------- Util Functions ------------------------------------------- private <T> List<T> visit(List<? extends ParserRuleContext> contexts, Class<T> clazz) { return contexts.stream() .map(this::visit) .map(clazz::cast) .collect(toList()); } private <T> Optional<T> visitIfPresent(ParserRuleContext context, Class<T> clazz) { return Optional.ofNullable(context) .map(this::visit) .map(clazz::cast); } private QualifiedName getQualifiedName(StarRocksParser.QualifiedNameContext context) { List<String> parts = visit(context.identifier(), Identifier.class).stream() .map(Identifier::getValue) .collect(Collectors.toList()); return QualifiedName.of(parts); } private TableName qualifiedNameToTableName(QualifiedName qualifiedName) { if (qualifiedName.getParts().size() == 2) { return new TableName(qualifiedName.getParts().get(0), qualifiedName.getParts().get(1)); } else if (qualifiedName.getParts().size() == 1) { return new TableName(null, qualifiedName.getParts().get(0)); } else { throw new ParsingException("error table name "); } } private Type getType(StarRocksParser.TypeContext type) { if (type.baseType() != null) { String signature = type.baseType().getText(); if (!type.typeParameter().isEmpty()) { if (signature.equalsIgnoreCase("VARCHAR")) { if (type.typeParameter().size() > 1) { throw new SemanticException("VARCHAR can not contains multi type parameter"); } if (type.typeParameter(0).INTEGER_VALUE() != null) { return ScalarType.createVarcharType( Integer.parseInt(type.typeParameter(0).INTEGER_VALUE().toString())); } else { throw new SemanticException("VARCHAR type parameter mush be integer"); } } else if (signature.equalsIgnoreCase("CHAR")) { if (type.typeParameter().size() > 1) { throw new SemanticException("CHAR can not contains multi type parameter"); } if (type.typeParameter(0).INTEGER_VALUE() != null) { return ScalarType.createCharType( Integer.parseInt(type.typeParameter(0).INTEGER_VALUE().toString())); } else { throw new SemanticException("CHAR type parameter mush be integer"); } } else if (signature.equalsIgnoreCase("DECIMAL")) { throw new IllegalArgumentException("Unsupported type specification: " + type.getText()); } throw new IllegalArgumentException("Unsupported type specification: " + type.getText()); } if (signature.equalsIgnoreCase("BOOLEAN")) { return Type.BOOLEAN; } else if (signature.equalsIgnoreCase("TINYINT")) { return Type.TINYINT; } else if (signature.equalsIgnoreCase("SMALLINT")) { return Type.SMALLINT; } else if (signature.equalsIgnoreCase("INT") || signature.equalsIgnoreCase("INTEGER")) { return Type.INT; } else if (signature.equalsIgnoreCase("BIGINT")) { return Type.BIGINT; } else if (signature.equalsIgnoreCase("LARGEINT")) { return Type.LARGEINT; } else if (signature.equalsIgnoreCase("FLOAT")) { return Type.FLOAT; } else if (signature.equalsIgnoreCase("DOUBLE")) { return Type.DOUBLE; } else if (signature.equalsIgnoreCase("DECIMAL")) { return ScalarType.createUnifiedDecimalType(10, 0); } else if (signature.equalsIgnoreCase("DATE")) { return Type.DATE; } else if (signature.equalsIgnoreCase("DATETIME")) { return Type.DATETIME; } else if (signature.equalsIgnoreCase("TIME")) { return Type.TIME; } else if (signature.equalsIgnoreCase("VARCHAR")) { return Type.VARCHAR; } else if (signature.equalsIgnoreCase("CHAR")) { return Type.CHAR; } else if (signature.equalsIgnoreCase("STRING")) { ScalarType stringType = ScalarType.createVarcharType(ScalarType.DEFAULT_STRING_LENGTH); stringType.setAssignedStrLenInColDefinition(); return stringType; } else if (signature.equalsIgnoreCase("BITMAP")) { return Type.BITMAP; } else if (signature.equalsIgnoreCase("HLL")) { return Type.HLL; } else if (signature.equalsIgnoreCase("PERCENTILE")) { return Type.PERCENTILE; } else if (signature.equalsIgnoreCase("JSON")) { return Type.JSON; } return Type.INVALID; } else if (type.decimalType() != null) { if (type.precision == null) { if (type.decimalType().DECIMAL() != null) { return ScalarType.createUnifiedDecimalType(10, 0); } else if (type.decimalType().DECIMALV2() != null) { return ScalarType.createDecimalV2Type(); } else if (type.decimalType().DECIMAL32() != null) { return ScalarType.createDecimalV3Type(PrimitiveType.DECIMAL32); } else if (type.decimalType().DECIMAL64() != null) { return ScalarType.createDecimalV3Type(PrimitiveType.DECIMAL64); } else if (type.decimalType().DECIMAL128() != null) { return ScalarType.createDecimalV3Type(PrimitiveType.DECIMAL128); } } int precision = Integer.parseInt(type.precision.INTEGER_VALUE().toString()); int scale = ScalarType.DEFAULT_SCALE; if (type.scale != null) { scale = Integer.parseInt(type.scale.INTEGER_VALUE().toString()); } if (type.decimalType().DECIMAL() != null) { return ScalarType.createUnifiedDecimalType(precision, scale); } else if (type.decimalType().DECIMALV2() != null) { return ScalarType.createDecimalV2Type(precision, scale); } else if (type.decimalType().DECIMAL32() != null) { return ScalarType.createDecimalV3Type(PrimitiveType.DECIMAL32, precision, scale); } else if (type.decimalType().DECIMAL64() != null) { return ScalarType.createDecimalV3Type(PrimitiveType.DECIMAL64, precision, scale); } else if (type.decimalType().DECIMAL128() != null) { return ScalarType.createDecimalV3Type(PrimitiveType.DECIMAL128, precision, scale); } } else if (type.arrayType() != null) { StarRocksParser.ArrayTypeContext arrayTypeContext = type.arrayType(); return new ArrayType(getType(arrayTypeContext.type())); } throw new IllegalArgumentException("Unsupported type specification: " + type.getText()); } }
3e1b19ac039fe79adfd5e11f5002395ebd964ae0
13,436
java
Java
src/main/java/no/ssb/dapla/exploration_concept_ingest/ExplorationConceptIngestService.java
statisticsnorway/dapla-gsim-concept-ingest
3814612eba6b3aab7e29a43a81d8d69e8ef68a3e
[ "Apache-2.0" ]
null
null
null
src/main/java/no/ssb/dapla/exploration_concept_ingest/ExplorationConceptIngestService.java
statisticsnorway/dapla-gsim-concept-ingest
3814612eba6b3aab7e29a43a81d8d69e8ef68a3e
[ "Apache-2.0" ]
null
null
null
src/main/java/no/ssb/dapla/exploration_concept_ingest/ExplorationConceptIngestService.java
statisticsnorway/dapla-gsim-concept-ingest
3814612eba6b3aab7e29a43a81d8d69e8ef68a3e
[ "Apache-2.0" ]
1
2022-01-18T04:45:56.000Z
2022-01-18T04:45:56.000Z
43.482201
158
0.597499
11,472
package no.ssb.dapla.exploration_concept_ingest; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import de.huxhorn.sulky.ulid.ULID; import io.github.resilience4j.core.IntervalFunction; import io.github.resilience4j.retry.Retry; import io.github.resilience4j.retry.RetryConfig; import io.helidon.common.http.Http; import io.helidon.common.http.MediaType; import io.helidon.config.Config; import io.helidon.media.common.DefaultMediaSupport; import io.helidon.media.jackson.JacksonSupport; import io.helidon.webclient.WebClient; import io.helidon.webclient.WebClientRequestBuilder; import io.helidon.webclient.WebClientResponse; import io.helidon.webserver.Routing; import io.helidon.webserver.ServerRequest; import io.helidon.webserver.ServerResponse; import io.helidon.webserver.Service; import no.ssb.rawdata.api.RawdataClient; import no.ssb.rawdata.api.RawdataClientInitializer; import no.ssb.rawdata.api.RawdataConsumer; import no.ssb.rawdata.api.RawdataMessage; import no.ssb.service.provider.api.ProviderConfigurator; import org.msgpack.jackson.dataformat.MessagePackFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.UncheckedIOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import static java.util.Optional.ofNullable; public class ExplorationConceptIngestService implements Service { private static final Logger LOG = LoggerFactory.getLogger(ExplorationConceptIngestService.class); private final ObjectMapper msgPackMapper = new ObjectMapper(new MessagePackFactory()); private final Config config; private final AtomicBoolean waitLoopAllowed = new AtomicBoolean(false); private final Map<Class<?>, Object> instanceByType = new ConcurrentHashMap<>(); ExplorationConceptIngestService(Config config) { this.config = config; } @Override public void update(Routing.Rules rules) { rules .get("/trigger", this::getRevisionHandler) .put("/trigger", this::putRevisionHandler) .delete("/trigger", this::deleteRevisionHandler) ; } void getRevisionHandler(ServerRequest request, ServerResponse response) { Pipe pipe = (Pipe) instanceByType.get(Pipe.class); if (pipe != null) { response.headers().contentType(MediaType.APPLICATION_JSON); response.status(200).send(msgPackMapper.createObjectNode() .put("status", "RUNNING") .put("startedTime", pipe.startedAt.format(DateTimeFormatter.ISO_INSTANT)) .toPrettyString()); } else { response.headers().contentType(MediaType.APPLICATION_JSON); response.status(200).send(msgPackMapper.createObjectNode() .put("status", "STOPPED") .toPrettyString()); } } void putRevisionHandler(ServerRequest request, ServerResponse response) { triggerStart(); response.headers().contentType(MediaType.APPLICATION_JSON); response.status(200).send("[]"); } void deleteRevisionHandler(ServerRequest request, ServerResponse response) { triggerStop(); response.status(200).send(); } public void triggerStop() { waitLoopAllowed.set(false); } public void triggerStart() { instanceByType.computeIfAbsent(RawdataClient.class, k -> { String provider = config.get("pipe.source.provider.name").asString().get(); Map<String, String> providerConfig = config.get("pipe.source.provider.config").detach().asMap().get(); return ProviderConfigurator.configure(providerConfig, provider, RawdataClientInitializer.class); }); instanceByType.computeIfAbsent(WebClient.class, k -> { Config targetConfig = this.config.get("pipe.target"); String scheme = targetConfig.get("scheme").asString().get(); String host = targetConfig.get("host").asString().get(); int port = targetConfig.get("port").asInt().get(); URI ldsBaseUri; try { ldsBaseUri = new URI(scheme, null, host, port, null, null, null); } catch (URISyntaxException e) { throw new RuntimeException(e); } return WebClient.builder() .addMediaSupport(DefaultMediaSupport.create()) .addMediaSupport(JacksonSupport.create()) .baseUri(ldsBaseUri) .build(); }); Pipe pipe = (Pipe) instanceByType.computeIfAbsent(Pipe.class, k -> new Pipe()); instanceByType.computeIfAbsent(Thread.class, k -> { Thread thread = new Thread(pipe); thread.start(); return thread; }); waitLoopAllowed.set(true); } Optional<String> getLatestSourceIdFromTarget() { Config targetConfig = this.config.get("pipe.target"); String source = targetConfig.get("source").asString().get(); WebClient webClient = (WebClient) instanceByType.get(WebClient.class); WebClientRequestBuilder builder = webClient.get(); builder.headers().add("Origin", "localhost"); builder.path("source/" + source); WebClientResponse response = builder .connectTimeout(120, TimeUnit.SECONDS) .readTimeout(10, TimeUnit.SECONDS) .submit() .toCompletableFuture() .join(); if (!Http.ResponseStatus.Family.SUCCESSFUL.equals(response.status().family())) { throw new RuntimeException("Got http status code " + response.status() + " with reason: " + response.status().reasonPhrase()); } JsonNode body = response.content().as(JsonNode.class).toCompletableFuture().join(); return ofNullable(body.get("lastSourceId").textValue()); } void sendMessageToTarget(RawdataMessage message) { try { JsonNode meta = msgPackMapper.readTree(message.get("meta")); String method = meta.get("method").textValue(); String sourceNamespace = meta.get("namespace").textValue(); String entity = meta.get("entity").textValue(); String id = meta.get("id").textValue(); String versionStr = meta.get("version").textValue(); String namespace = config.get("pipe.target.namespace").asString().get(); String source = config.get("pipe.target.source").asString().get(); String sourceId = message.ulid().toString(); WebClient webClient = (WebClient) instanceByType.get(WebClient.class); String path = String.format("/%s/%s/%s", namespace, entity, id); // retry at backoff intervals for about 3 minutes before giving up Retry retry = Retry.of("write-message-to-lds", RetryConfig.custom() .intervalFunction(IntervalFunction.ofExponentialRandomBackoff(Duration.of(5, ChronoUnit.SECONDS), 2, Duration.of(30, ChronoUnit.SECONDS))) .maxAttempts(8) .failAfterMaxAttempts(true) .build()); if ("PUT".equals(method)) { JsonNode data = msgPackMapper.readTree(message.get("data")); WebClientResponse response = Retry.decorateSupplier(retry, () -> { WebClientRequestBuilder builder = webClient.put(); builder.headers().add("Origin", "localhost"); builder.path(path) .queryParam("timestamp", versionStr) .queryParam("source", source) .queryParam("sourceId", sourceId); return builder.submit(data) .toCompletableFuture() .join(); }).get(); if (!Http.ResponseStatus.Family.SUCCESSFUL.equals(response.status().family())) { LOG.warn("Unsuccessful HTTP response while attempting to perform: PUT {}?timestamp={}&source={}&sourceId={} DATA: {}", path, URLEncoder.encode(versionStr, StandardCharsets.UTF_8), URLEncoder.encode(source, StandardCharsets.UTF_8), URLEncoder.encode(sourceId, StandardCharsets.UTF_8), data.toString() ); throw new RuntimeException("Got http status code " + response.status() + " with reason: " + response.status().reasonPhrase()); } } else if ("DELETE".equals(method)) { WebClientResponse response = Retry.decorateSupplier(retry, () -> { WebClientRequestBuilder builder = webClient.delete(); builder.headers().add("Origin", "localhost"); builder.skipUriEncoding() .path(path) .queryParam("timestamp", versionStr) .queryParam("source", source) .queryParam("sourceId", sourceId); return builder.submit() .toCompletableFuture() .join(); }).get(); if (!Http.ResponseStatus.Family.SUCCESSFUL.equals(response.status().family())) { LOG.warn("Unsuccessful HTTP response while attempting to perform: DELETE {}?timestamp={}&source={}&sourceId={}", path, URLEncoder.encode(versionStr, StandardCharsets.UTF_8), URLEncoder.encode(source, StandardCharsets.UTF_8), URLEncoder.encode(sourceId, StandardCharsets.UTF_8) ); throw new RuntimeException("Got http status code " + response.status() + " with reason: " + response.status().reasonPhrase()); } } else { throw new RuntimeException("Unsupported method: " + method); } } catch (IOException e) { throw new UncheckedIOException(e); } } class Pipe implements Runnable { final ZonedDateTime startedAt; Pipe() { startedAt = ZonedDateTime.now(ZoneOffset.UTC); } @Override public void run() { try { String topic = config.get("pipe.source.topic").asString().get(); ULID.Value previousUlid = getLatestSourceIdFromTarget().map(ULID::parseULID).orElse(null); try (RawdataConsumer consumer = ((RawdataClient) instanceByType.get(RawdataClient.class)).consumer(topic, previousUlid, false)) { while (waitLoopAllowed.get()) { RawdataMessage message = consumer.receive(3, TimeUnit.SECONDS); if (message != null) { try { sendMessageToTarget(message); } catch (Throwable t) { LOG.debug("While processing/sending rawdata. RawdataMessage: {}", asJson(message)); throw t; } } } } } catch (Throwable t) { LOG.error("Unexpected error", t); } finally { instanceByType.remove(Pipe.class); instanceByType.remove(Thread.class); } } } private ObjectNode asJson(RawdataMessage message) { ObjectNode r = msgPackMapper.createObjectNode(); r.put("ulid", message.ulid().toString()); r.put("position", message.position()); r.put("orderingGroup", message.orderingGroup()); r.put("sequenceNumber", message.sequenceNumber()); r.put("timestamp", ZonedDateTime.ofInstant(Instant.ofEpochMilli(message.timestamp()), ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT)); ObjectNode data = r.putObject("data"); for (String key : message.keys()) { byte[] valueBytes = message.get(key); try { JsonNode node = msgPackMapper.readTree(valueBytes); data.set(key, node); } catch (IOException e) { data.put(key, valueBytes); } } return r; } public void close() { RawdataClient rawdataClient = (RawdataClient) instanceByType.get(RawdataClient.class); if (rawdataClient != null) { try { rawdataClient.close(); } catch (Exception e) { throw new RuntimeException(e); } } } }
3e1b1a90e8e7b7ecc7bdc9014f73e5ffce185988
378
java
Java
TraidingPlatform/src/main/java/org/devteam/view/AboutController.java
LinDevHard/traiding_platform
b1a35c95258ce4b0fc726301e5dd92f8b3c66ee7
[ "Apache-2.0" ]
null
null
null
TraidingPlatform/src/main/java/org/devteam/view/AboutController.java
LinDevHard/traiding_platform
b1a35c95258ce4b0fc726301e5dd92f8b3c66ee7
[ "Apache-2.0" ]
null
null
null
TraidingPlatform/src/main/java/org/devteam/view/AboutController.java
LinDevHard/traiding_platform
b1a35c95258ce4b0fc726301e5dd92f8b3c66ee7
[ "Apache-2.0" ]
null
null
null
21
60
0.695767
11,473
package org.devteam.view; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.stage.Stage; public class AboutController { @FXML public void onActionCloseDialog(ActionEvent event){ Node source = (Node) event.getSource(); Stage stage = (Stage) source.getScene().getWindow(); stage.close(); } }
3e1b1abc73ae53b61b1f85ad8a8f920392de9083
4,723
java
Java
nacid/src/com/nacid/web/taglib/nomenclatures/FlatNomenclatureTag.java
governmentbg/NACID-DOCTORS-TITLES
72b79b14af654573e5d23e0048adeac20d06696a
[ "MIT" ]
null
null
null
nacid/src/com/nacid/web/taglib/nomenclatures/FlatNomenclatureTag.java
governmentbg/NACID-DOCTORS-TITLES
72b79b14af654573e5d23e0048adeac20d06696a
[ "MIT" ]
null
null
null
nacid/src/com/nacid/web/taglib/nomenclatures/FlatNomenclatureTag.java
governmentbg/NACID-DOCTORS-TITLES
72b79b14af654573e5d23e0048adeac20d06696a
[ "MIT" ]
null
null
null
50.784946
154
0.648105
11,474
package com.nacid.web.taglib.nomenclatures; import com.nacid.bl.nomenclatures.NomenclaturesDataProvider; import com.nacid.web.MessagesBundle; import com.nacid.web.ValidationStrings; import com.nacid.web.WebKeys; import com.nacid.web.model.nomenclatures.FlatNomenclatureWebModel; import javax.servlet.jsp.JspException; import javax.servlet.jsp.PageContext; import javax.servlet.jsp.tagext.SimpleTagSupport; import java.io.IOException; public class FlatNomenclatureTag extends SimpleTagSupport { public void doTag() throws JspException, IOException { FlatNomenclatureWebModel webmodel = (FlatNomenclatureWebModel) getJspContext().getAttribute(WebKeys.FLAT_NOMENCLATURE, PageContext.REQUEST_SCOPE); if (webmodel != null) { getJspContext().setAttribute("id", webmodel.getId()); getJspContext().setAttribute("name", webmodel.getName()); getJspContext().setAttribute("dateFrom", webmodel.getDateFrom()); getJspContext().setAttribute("dateTo", webmodel.getDateTo()); getJspContext().setAttribute("url", webmodel.getGroupName()); getJspContext().setAttribute("nomenclatureName", webmodel.getNomenclatureName()); int nomenclatureNameLength = 80; String validationString; String validationErrorMessage; switch (webmodel.getNomenclatureType()) { case NomenclaturesDataProvider.FLAT_NOMENCLATURE_QUALIFICATION: nomenclatureNameLength = 255; break; case NomenclaturesDataProvider.FLAT_NOMENCLATURE_EDUCATION_LEVEL: nomenclatureNameLength = 100; break; case NomenclaturesDataProvider.FLAT_NOMENCLATURE_PROFESSION: nomenclatureNameLength = 600; break; case NomenclaturesDataProvider.FLAT_NOMENCLATURE_HIGHER_PROF_QUALIFICATION: nomenclatureNameLength = 150; break; case NomenclaturesDataProvider.FLAT_NOMENCLATURE_CERTIFICATE_PROF_QUALIFICATION: nomenclatureNameLength = 150; break; case NomenclaturesDataProvider.FLAT_NOMENCLATURE_EDUCATION_DOCUMENT_TYPE: nomenclatureNameLength = 255; break; case NomenclaturesDataProvider.FLAT_NOMENCLATURE_HIGHER_SPECIALITY: nomenclatureNameLength = 150; break; case NomenclaturesDataProvider.FLAT_NOMENCLATURE_PROFESSION_EXPERIENCE_DOCUMENT_TYPE: nomenclatureNameLength = 100; break; case NomenclaturesDataProvider.FLAT_NOMENCLATURE_PROFESSIONAL_INSTITUTION_TYPE: nomenclatureNameLength = 255; break; case NomenclaturesDataProvider.FLAT_NOMENCLATURE_SECONDARY_CALIBER: nomenclatureNameLength = 150; break; case NomenclaturesDataProvider.FLAT_NOMENCLATURE_QUALIFICATION_DEGREE: nomenclatureNameLength = 150; break; case NomenclaturesDataProvider.FLAT_NOMENCLATURE_ORIGINAL_SPECIALITY: nomenclatureNameLength = 255; break; case NomenclaturesDataProvider.FLAT_NOMENCLATURE_GRADUATION_DOCUMENT_TYPE: nomenclatureNameLength = 255; break; default: nomenclatureNameLength = 80; } switch (webmodel.getNomenclatureType()) { case NomenclaturesDataProvider.FLAT_NOMENCLATURE_ORIGINAL_SPECIALITY: case NomenclaturesDataProvider.FLAT_NOMENCLATURE_GRADUATION_DOCUMENT_TYPE: validationString = ValidationStrings.getValidationStrings().get("allButQuote"); validationErrorMessage = MessagesBundle.getMessagesBundle().get("err_allButQuote"); break; default: validationString = ValidationStrings.getValidationStrings().get("nomenclature_name_with_fullstop_digits"); validationErrorMessage = MessagesBundle.getMessagesBundle().get("err_nomenclature_name_with_fullstop_digits"); break; } getJspContext().setAttribute("nomenclatureNameLength", nomenclatureNameLength); getJspContext().setAttribute("validationString", validationString); getJspContext().setAttribute("validationErrorMessage", validationErrorMessage); } getJspBody().invoke(null); } }
3e1b1ac1bcfbbc993fdd2a219581ff91d7d1b907
1,566
java
Java
src/main/java/com/muyuanjin/map/CustomSerializationEnumJsonSerializer.java
muyuanjin/custom-serialization-enum
3096b3d6954f4792163917e50392c1bad9fe1738
[ "MIT" ]
null
null
null
src/main/java/com/muyuanjin/map/CustomSerializationEnumJsonSerializer.java
muyuanjin/custom-serialization-enum
3096b3d6954f4792163917e50392c1bad9fe1738
[ "MIT" ]
null
null
null
src/main/java/com/muyuanjin/map/CustomSerializationEnumJsonSerializer.java
muyuanjin/custom-serialization-enum
3096b3d6954f4792163917e50392c1bad9fe1738
[ "MIT" ]
null
null
null
40.153846
116
0.757344
11,475
package com.muyuanjin.map; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import com.muyuanjin.annotating.CustomSerializationEnum; import com.muyuanjin.annotating.EnumSerialize; import com.muyuanjin.annotating.EnumSerializeAdapter; import javafx.util.Pair; import java.io.IOException; import java.util.Set; /** * @author muyuanjin */ public class CustomSerializationEnumJsonSerializer<T extends Enum<T> & EnumSerialize<T>> extends JsonSerializer<T> { private final CustomSerializationEnum.Type type; public CustomSerializationEnumJsonSerializer(Pair<Class<Enum<?>>, Set<EnumSerialize<T>>> enumSerialize) { //noinspection unchecked,rawtypes CustomSerializationEnum annotation = EnumSerialize.getAnnotation((Class) enumSerialize.getKey()); type = annotation == null ? CustomSerializationEnum.Type.NAME : annotation.json(); } @Override public void serialize(T value, JsonGenerator gen, SerializerProvider serializers) throws IOException { Object serializedValue; //noinspection ConstantConditions if (value instanceof EnumSerialize) { serializedValue = type.getSerializedValue(value); } else { //noinspection ConstantConditions serializedValue = type.getSerializedValue(new EnumSerializeAdapter(value)); } serializers.findValueSerializer(serializedValue.getClass()).serialize(serializedValue, gen, serializers); } }
3e1b1bd6c262afd19e29806c598a5aecd2931793
290
java
Java
coco-design-patterns/src/main/java/com/coco/cloud/patterns/behavior/observer/Publisher.java
6265391/leeco-cloud
2de28d08e33736162967830a31ed36c317db7f1e
[ "Apache-2.0" ]
1
2020-01-11T10:04:03.000Z
2020-01-11T10:04:03.000Z
coco-design-patterns/src/main/java/com/coco/cloud/patterns/behavior/observer/Publisher.java
6265391/leeco-cloud
2de28d08e33736162967830a31ed36c317db7f1e
[ "Apache-2.0" ]
null
null
null
coco-design-patterns/src/main/java/com/coco/cloud/patterns/behavior/observer/Publisher.java
6265391/leeco-cloud
2de28d08e33736162967830a31ed36c317db7f1e
[ "Apache-2.0" ]
null
null
null
18.375
50
0.663265
11,476
package com.coco.cloud.patterns.behavior.observer; /** * @author anpch@example.com * @version 0.0.1 * @date 2021/4/27 22:44 */ public class Publisher extends AbstractPublisher { public void finish(){ System.out.println("被观察者发生了动作"); super.publishEvent(); } }
3e1b1c1b872cb7e5ff7a1a83e17c3ca9c47c97be
11,784
java
Java
plugins/com.github.icelyframework.activitystorming.diagram/src/com/github/icelyframework/activitystorming/diagram/edit/parts/Aggregate2EditPart.java
IcelyFramework/icely-activity-storming
60bf490ba5cae7aff619f2c6ddf9be53b86c80a4
[ "MIT" ]
2
2021-01-12T20:54:29.000Z
2021-01-18T17:10:48.000Z
plugins/com.github.icelyframework.activitystorming.diagram/src/com/github/icelyframework/activitystorming/diagram/edit/parts/Aggregate2EditPart.java
IcelyFramework/icely-activity-storming
60bf490ba5cae7aff619f2c6ddf9be53b86c80a4
[ "MIT" ]
1
2021-01-20T06:40:39.000Z
2021-01-20T06:40:39.000Z
plugins/com.github.icelyframework.activitystorming.diagram/src/com/github/icelyframework/activitystorming/diagram/edit/parts/Aggregate2EditPart.java
IcelyFramework/icely-activity-storming
60bf490ba5cae7aff619f2c6ddf9be53b86c80a4
[ "MIT" ]
null
null
null
30.138107
194
0.771809
11,477
/* * */ package com.github.icelyframework.activitystorming.diagram.edit.parts; import org.eclipse.draw2d.IFigure; import org.eclipse.draw2d.MarginBorder; import org.eclipse.draw2d.PositionConstants; import org.eclipse.draw2d.RectangleFigure; import org.eclipse.draw2d.RoundedRectangle; import org.eclipse.draw2d.Shape; import org.eclipse.draw2d.StackLayout; import org.eclipse.draw2d.geometry.Dimension; import org.eclipse.gef.EditPart; import org.eclipse.gef.EditPolicy; import org.eclipse.gef.Request; import org.eclipse.gef.commands.Command; import org.eclipse.gef.editpolicies.LayoutEditPolicy; import org.eclipse.gef.editpolicies.NonResizableEditPolicy; import org.eclipse.gef.requests.CreateRequest; import org.eclipse.gmf.runtime.diagram.core.edithelpers.CreateElementRequestAdapter; import org.eclipse.gmf.runtime.diagram.ui.editparts.AbstractBorderedShapeEditPart; import org.eclipse.gmf.runtime.diagram.ui.editparts.IBorderItemEditPart; import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; import org.eclipse.gmf.runtime.diagram.ui.editpolicies.BorderItemSelectionEditPolicy; import org.eclipse.gmf.runtime.diagram.ui.editpolicies.DragDropEditPolicy; import org.eclipse.gmf.runtime.diagram.ui.editpolicies.EditPolicyRoles; import org.eclipse.gmf.runtime.diagram.ui.figures.BorderItemLocator; import org.eclipse.gmf.runtime.diagram.ui.requests.CreateViewAndElementRequest; import org.eclipse.gmf.runtime.draw2d.ui.figures.ConstrainedToolbarLayout; import org.eclipse.gmf.runtime.draw2d.ui.figures.WrappingLabel; import org.eclipse.gmf.runtime.emf.type.core.IElementType; import org.eclipse.gmf.runtime.gef.ui.figures.DefaultSizeNodeFigure; import org.eclipse.gmf.runtime.gef.ui.figures.NodeFigure; import org.eclipse.gmf.runtime.notation.View; import org.eclipse.gmf.tooling.runtime.edit.policies.reparent.CreationEditPolicyWithCustomReparent; import org.eclipse.swt.graphics.Color; import com.github.icelyframework.activitystorming.diagram.edit.policies.Aggregate2CanonicalEditPolicy; import com.github.icelyframework.activitystorming.diagram.edit.policies.Aggregate2ItemSemanticEditPolicy; import com.github.icelyframework.activitystorming.diagram.edit.policies.OpenDiagramEditPolicy; import com.github.icelyframework.activitystorming.diagram.part.ActivitystormingVisualIDRegistry; import com.github.icelyframework.activitystorming.diagram.providers.ActivitystormingElementTypes; /** * @generated */ public class Aggregate2EditPart extends AbstractBorderedShapeEditPart { /** * @generated */ public static final int VISUAL_ID = 3006; /** * @generated */ protected IFigure contentPane; /** * @generated */ protected IFigure primaryShape; /** * @generated */ public Aggregate2EditPart(View view) { super(view); } /** * @generated */ protected void createDefaultEditPolicies() { installEditPolicy(EditPolicyRoles.CREATION_ROLE, new CreationEditPolicyWithCustomReparent(ActivitystormingVisualIDRegistry.TYPED_INSTANCE)); super.createDefaultEditPolicies(); installEditPolicy(EditPolicyRoles.SEMANTIC_ROLE, new Aggregate2ItemSemanticEditPolicy()); installEditPolicy(EditPolicyRoles.DRAG_DROP_ROLE, new DragDropEditPolicy()); installEditPolicy(EditPolicyRoles.CANONICAL_ROLE, new Aggregate2CanonicalEditPolicy()); installEditPolicy(EditPolicy.LAYOUT_ROLE, createLayoutEditPolicy()); installEditPolicy(EditPolicyRoles.OPEN_ROLE, new OpenDiagramEditPolicy()); // XXX need an SCR to runtime to have another abstract superclass that would let children add reasonable editpolicies // removeEditPolicy(org.eclipse.gmf.runtime.diagram.ui.editpolicies.EditPolicyRoles.CONNECTION_HANDLES_ROLE); } /** * @generated */ protected LayoutEditPolicy createLayoutEditPolicy() { org.eclipse.gmf.runtime.diagram.ui.editpolicies.LayoutEditPolicy lep = new org.eclipse.gmf.runtime.diagram.ui.editpolicies.LayoutEditPolicy() { protected EditPolicy createChildEditPolicy(EditPart child) { View childView = (View) child.getModel(); switch (ActivitystormingVisualIDRegistry.getVisualID(childView)) { case ConstraintPin2EditPart.VISUAL_ID: return new BorderItemSelectionEditPolicy(); } EditPolicy result = child.getEditPolicy(EditPolicy.PRIMARY_DRAG_ROLE); if (result == null) { result = new NonResizableEditPolicy(); } return result; } protected Command getMoveChildrenCommand(Request request) { return null; } protected Command getCreateCommand(CreateRequest request) { return null; } }; return lep; } /** * @generated */ protected IFigure createNodeShape() { return primaryShape = new AggregateFigure(); } /** * @generated */ public AggregateFigure getPrimaryShape() { return (AggregateFigure) primaryShape; } /** * @generated */ protected boolean addFixedChild(EditPart childEditPart) { if (childEditPart instanceof AggregateName2EditPart) { ((AggregateName2EditPart) childEditPart).setLabel(getPrimaryShape().getFigureAggregateLabelFigure()); return true; } if (childEditPart instanceof AggregateAggregateDomainobjectCompartment2EditPart) { IFigure pane = getPrimaryShape().getAggregateDomainobjectCompartmentFigure(); setupContentPane(pane); // FIXME each comparment should handle his content pane in his own way pane.add(((AggregateAggregateDomainobjectCompartment2EditPart) childEditPart).getFigure()); return true; } if (childEditPart instanceof ConstraintPin2EditPart) { BorderItemLocator locator = new BorderItemLocator(getMainFigure(), PositionConstants.NORTH); getBorderedFigure().getBorderItemContainer().add(((ConstraintPin2EditPart) childEditPart).getFigure(), locator); return true; } return false; } /** * @generated */ protected boolean removeFixedChild(EditPart childEditPart) { if (childEditPart instanceof AggregateName2EditPart) { return true; } if (childEditPart instanceof AggregateAggregateDomainobjectCompartment2EditPart) { IFigure pane = getPrimaryShape().getAggregateDomainobjectCompartmentFigure(); pane.remove(((AggregateAggregateDomainobjectCompartment2EditPart) childEditPart).getFigure()); return true; } if (childEditPart instanceof ConstraintPin2EditPart) { getBorderedFigure().getBorderItemContainer().remove(((ConstraintPin2EditPart) childEditPart).getFigure()); return true; } return false; } /** * @generated */ protected void addChildVisual(EditPart childEditPart, int index) { if (addFixedChild(childEditPart)) { return; } super.addChildVisual(childEditPart, -1); } /** * @generated */ protected void removeChildVisual(EditPart childEditPart) { if (removeFixedChild(childEditPart)) { return; } super.removeChildVisual(childEditPart); } /** * @generated */ protected IFigure getContentPaneFor(IGraphicalEditPart editPart) { if (editPart instanceof AggregateAggregateDomainobjectCompartment2EditPart) { return getPrimaryShape().getAggregateDomainobjectCompartmentFigure(); } if (editPart instanceof IBorderItemEditPart) { return getBorderedFigure().getBorderItemContainer(); } return getContentPane(); } /** * @generated */ protected NodeFigure createNodePlate() { DefaultSizeNodeFigure result = new DefaultSizeNodeFigure(40, 40); return result; } /** * Creates figure for this edit part. * * Body of this method does not depend on settings in generation model * so you may safely remove <i>generated</i> tag and modify it. * * @generated */ protected NodeFigure createMainFigure() { NodeFigure figure = createNodePlate(); figure.setLayoutManager(new StackLayout()); IFigure shape = createNodeShape(); figure.add(shape); contentPane = setupContentPane(shape); return figure; } /** * Default implementation treats passed figure as content pane. * Respects layout one may have set for generated figure. * @param nodeShape instance of generated figure class * @generated */ protected IFigure setupContentPane(IFigure nodeShape) { if (nodeShape.getLayoutManager() == null) { ConstrainedToolbarLayout layout = new ConstrainedToolbarLayout(); layout.setSpacing(5); nodeShape.setLayoutManager(layout); } return nodeShape; // use nodeShape itself as contentPane } /** * @generated */ public IFigure getContentPane() { if (contentPane != null) { return contentPane; } return super.getContentPane(); } /** * @generated */ protected void setForegroundColor(Color color) { if (primaryShape != null) { primaryShape.setForegroundColor(color); } } /** * @generated */ protected void setBackgroundColor(Color color) { if (primaryShape != null) { primaryShape.setBackgroundColor(color); } } /** * @generated */ protected void setLineWidth(int width) { if (primaryShape instanceof Shape) { ((Shape) primaryShape).setLineWidth(width); } } /** * @generated */ protected void setLineType(int style) { if (primaryShape instanceof Shape) { ((Shape) primaryShape).setLineStyle(style); } } /** * @generated */ public EditPart getPrimaryChildEditPart() { return getChildBySemanticHint(ActivitystormingVisualIDRegistry.getType(AggregateName2EditPart.VISUAL_ID)); } /** * @generated */ public EditPart getTargetEditPart(Request request) { if (request instanceof CreateViewAndElementRequest) { CreateElementRequestAdapter adapter = ((CreateViewAndElementRequest) request).getViewAndElementDescriptor() .getCreateElementRequestAdapter(); IElementType type = (IElementType) adapter.getAdapter(IElementType.class); if (type == ActivitystormingElementTypes.ValueObject_3002) { return getChildBySemanticHint(ActivitystormingVisualIDRegistry .getType(AggregateAggregateDomainobjectCompartment2EditPart.VISUAL_ID)); } if (type == ActivitystormingElementTypes.Entity_3003) { return getChildBySemanticHint(ActivitystormingVisualIDRegistry .getType(AggregateAggregateDomainobjectCompartment2EditPart.VISUAL_ID)); } if (type == ActivitystormingElementTypes.DomainObject_3004) { return getChildBySemanticHint(ActivitystormingVisualIDRegistry .getType(AggregateAggregateDomainobjectCompartment2EditPart.VISUAL_ID)); } } return super.getTargetEditPart(request); } /** * @generated */ public class AggregateFigure extends RoundedRectangle { /** * @generated */ private WrappingLabel fFigureAggregateLabelFigure; /** * @generated */ private RectangleFigure fAggregateDomainobjectCompartmentFigure; /** * @generated */ public AggregateFigure() { this.setCornerDimensions(new Dimension(getMapMode().DPtoLP(8), getMapMode().DPtoLP(8))); this.setBackgroundColor(THIS_BACK); this.setBorder(new MarginBorder(getMapMode().DPtoLP(5), getMapMode().DPtoLP(5), getMapMode().DPtoLP(5), getMapMode().DPtoLP(5))); createContents(); } /** * @generated */ private void createContents() { fFigureAggregateLabelFigure = new WrappingLabel(); fFigureAggregateLabelFigure.setText("Aggregate"); fFigureAggregateLabelFigure .setMaximumSize(new Dimension(getMapMode().DPtoLP(10000), getMapMode().DPtoLP(50))); this.add(fFigureAggregateLabelFigure); fAggregateDomainobjectCompartmentFigure = new RectangleFigure(); fAggregateDomainobjectCompartmentFigure.setOutline(false); this.add(fAggregateDomainobjectCompartmentFigure); } /** * @generated */ public WrappingLabel getFigureAggregateLabelFigure() { return fFigureAggregateLabelFigure; } /** * @generated */ public RectangleFigure getAggregateDomainobjectCompartmentFigure() { return fAggregateDomainobjectCompartmentFigure; } } /** * @generated */ static final Color THIS_BACK = new Color(null, 243, 208, 43); }
3e1b1c53fe3f3feae731574cb90609336f401799
2,181
java
Java
Microsoft/Easy/Print BST elements in given range/GFG.java
navjindervirdee/geeksforgeeks
17058549834750ff74df4d1f840af7266a31729d
[ "MIT" ]
null
null
null
Microsoft/Easy/Print BST elements in given range/GFG.java
navjindervirdee/geeksforgeeks
17058549834750ff74df4d1f840af7266a31729d
[ "MIT" ]
null
null
null
Microsoft/Easy/Print BST elements in given range/GFG.java
navjindervirdee/geeksforgeeks
17058549834750ff74df4d1f840af7266a31729d
[ "MIT" ]
null
null
null
24.233333
64
0.457588
11,478
/*Please note that it's Function problem i.e. you need to write your solution in the form of Function(s) only. Driver Code to call/invoke your function is mentioned above.*/ /* The structure of a BST node is as follows: class Node { int key; Node left, right; Node(int item) { key = item; left = right = null; } } */ class GfG { Node find(Node node, int num){ if(node==null){ return node; } if(node.key==num){ return node; } if(node.key<num){ if(node.right==null){ return node; } return find(node.right,num); } else{ if(node.left==null){ return node; } return find(node.left,num); } } Node getNext(Node node,Node root){ Node next = getLeftDescendant(node); if(next==null){ List<Node> list = new ArrayList<Node>(); getRightParent(node,root,list); for(int i =list.size()-1;i>-1;i--){ //System.out.print(list.get(i).key + " "); if(list.get(i).key>node.key){ next = list.get(i); break; } } } return next; } Node getLeftDescendant(Node node){ Node right = node.right; while(right!=null && right.left!=null){ right= right.left; } return right; } void getRightParent(Node node, Node root,List<Node> list){ if(node==root){ list.add(root); return; } list.add(root); if(node.key<root.key){ getRightParent(node,root.left,list); } else{ getRightParent(node,root.right,list); } } void Print(Node node, int k1, int k2) { Node n = find(node,k1); //System.out.println(n.key); while(n!=null && n.key<=k2){ if(n.key>=k1){ System.out.print(n.key + " "); } n = getNext(n,node); } } }
3e1b1c91c8a7efb8103759386e94cb4bdc7ff1f2
2,732
java
Java
core/logic/src/main/java/org/apache/syncope/core/logic/init/LogicInitializer.java
IsurangaPerera/syncope
3211023745b66a6571d529e0e353eac75ac2e839
[ "Apache-2.0" ]
2
2019-10-22T18:13:23.000Z
2019-10-27T16:41:35.000Z
core/logic/src/main/java/org/apache/syncope/core/logic/init/LogicInitializer.java
IsurangaPerera/syncope
3211023745b66a6571d529e0e353eac75ac2e839
[ "Apache-2.0" ]
null
null
null
core/logic/src/main/java/org/apache/syncope/core/logic/init/LogicInitializer.java
IsurangaPerera/syncope
3211023745b66a6571d529e0e353eac75ac2e839
[ "Apache-2.0" ]
null
null
null
39.028571
119
0.749268
11,479
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.syncope.core.logic.init; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import org.apache.syncope.core.spring.ApplicationContextProvider; import org.apache.syncope.core.persistence.api.SyncopeLoader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.aop.support.AopUtils; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.stereotype.Component; /** * Take care of all initializations needed by Syncope logic to run up and safe. */ @Component public class LogicInitializer implements InitializingBean, BeanFactoryAware { private static final Logger LOG = LoggerFactory.getLogger(LogicInitializer.class); private DefaultListableBeanFactory beanFactory; @Override public void setBeanFactory(final BeanFactory beanFactory) { this.beanFactory = (DefaultListableBeanFactory) beanFactory; } @Override public void afterPropertiesSet() throws Exception { Map<String, SyncopeLoader> loaderMap = beanFactory.getBeansOfType(SyncopeLoader.class); List<SyncopeLoader> loaders = new ArrayList<>(loaderMap.values()); Collections.sort(loaders, (o1, o2) -> o1.getPriority().compareTo(o2.getPriority())); ApplicationContextProvider.setBeanFactory(beanFactory); LOG.debug("Starting initialization..."); loaders.stream().map(loader -> { LOG.debug("Invoking {} with priority {}", AopUtils.getTargetClass(loader).getName(), loader.getPriority()); return loader; }).forEachOrdered(loader -> { loader.load(); }); LOG.debug("Initialization completed"); } }
3e1b1ccaa1bf3d03f2aab57ec34f9971e3a5821e
3,821
java
Java
src/main/java/edu/fiuba/algo3/ContenedorNombres.java
ivoarbanas/Algo3_TP2
8fd11f370b3650b336548a3f931d6d1599d13bbf
[ "MIT" ]
null
null
null
src/main/java/edu/fiuba/algo3/ContenedorNombres.java
ivoarbanas/Algo3_TP2
8fd11f370b3650b336548a3f931d6d1599d13bbf
[ "MIT" ]
null
null
null
src/main/java/edu/fiuba/algo3/ContenedorNombres.java
ivoarbanas/Algo3_TP2
8fd11f370b3650b336548a3f931d6d1599d13bbf
[ "MIT" ]
1
2021-10-01T20:47:08.000Z
2021-10-01T20:47:08.000Z
40.648936
168
0.718398
11,480
package edu.fiuba.algo3; import edu.fiuba.algo3.Eventos.CargarUsuarioHandler; import edu.fiuba.algo3.modelo.Kahoot; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.*; import javafx.scene.media.MediaPlayer; import javafx.scene.shape.Box; import javafx.scene.text.Font; import javafx.scene.text.FontWeight; import javafx.stage.Stage; public class ContenedorNombres extends BorderPane { BarraDeMenu menuBar; Kahoot kahoot; Stage stage; MediaPlayer mediaPlayer; public ContenedorNombres(Stage stage, Kahoot kahoot, MediaPlayer mediaPlayer){ this.kahoot = kahoot; this.stage = stage; this.mediaPlayer = mediaPlayer; this.setMenu(stage); this.setContenido(); } private void setContenido() { Image fondo = new Image("file:src/main/java/edu/fiuba/algo3/imagenes/fondo.png"); BackgroundImage imagenDeFondo = new BackgroundImage(fondo, BackgroundRepeat.REPEAT, BackgroundRepeat.REPEAT, BackgroundPosition.CENTER, BackgroundSize.DEFAULT); this.setBackground(new Background(imagenDeFondo)); ImageView aux = new ImageView("file:src/main/java/edu/fiuba/algo3/imagenes/logo_purple.png"); HBox imagen = new HBox(); imagen.getChildren().add(aux); imagen.setPrefSize(200,50); HBox cajaJugadorUno = new HBox(); HBox cajaJugadorDos = new HBox(); VBox cajaY = new VBox(); //Label labelJugadorUno = new Label("Ingrese nombre de jugador 1: "); //labelJugadorUno.getStyleClass().add("nombre"); TextField cajaNombreJugadorUno = new TextField(); cajaNombreJugadorUno.setFont(Font.font("Verdana", FontWeight.BOLD, 70)); cajaNombreJugadorUno.setFocusTraversable(false); //cajaNombreJugadorUno.setAlignment(Pos.CENTER); cajaNombreJugadorUno.setPromptText("Ingrese nombre de jugador 1: "); cajaJugadorUno.getChildren().addAll(cajaNombreJugadorUno); //Label labelJugadorDos = new Label("Ingrese nombre de jugador 2: "); //labelJugadorDos.getStyleClass().add("nombre"); TextField cajaNombreJugadorDos = new TextField(); cajaNombreJugadorDos.setFocusTraversable(false); cajaNombreJugadorUno.setFont(Font.font("Sans Serif", FontWeight.BOLD, 25)); //cajaNombreJugadorDos.setAlignment(Pos.CENTER); cajaNombreJugadorDos.setPromptText("Ingrese nombre de jugador 2: "); cajaJugadorDos.getChildren().addAll(cajaNombreJugadorDos); cajaNombreJugadorDos.setFont(Font.font("Sans Serif", FontWeight.BOLD, 25)); Button cargarJugadores = new Button("Empezar"); cajaY.getChildren().addAll(imagen,cajaJugadorUno,cajaJugadorDos,cargarJugadores); CargarUsuarioHandler cargarUsuarioHandler = new CargarUsuarioHandler(kahoot,cajaNombreJugadorUno,cajaNombreJugadorDos,stage,mediaPlayer); cargarJugadores.setOnAction(cargarUsuarioHandler); cajaNombreJugadorUno.setPrefSize(500,50); cajaJugadorUno.setPrefSize(75,75); cajaJugadorDos.setPrefSize(75,75); cargarJugadores.setPrefSize(200,30); cajaNombreJugadorDos.setPrefSize(500,50); imagen.setAlignment(Pos.TOP_CENTER); cajaJugadorDos.setAlignment(Pos.CENTER); cajaJugadorUno.setAlignment(Pos.CENTER); cajaY.setAlignment(Pos.CENTER); this.setCenter(cajaY); } private void setMenu(Stage stage) { this.menuBar = new BarraDeMenu(kahoot,stage,mediaPlayer); this.setTop(menuBar); } public BarraDeMenu getBarraDeMenu() { return menuBar; } }
3e1b1ce32cec602ebd9aa9d12abc02f7e02a3829
2,177
java
Java
mall-sys-app/mall-sys-app-goods/src/main/java/ajin/mall/sys/goods/controller/SkuController.java
xwj1024/ajin-mall
ae4771b104b5d5114e9d1cc004cc4fbe90be8069
[ "Apache-2.0" ]
null
null
null
mall-sys-app/mall-sys-app-goods/src/main/java/ajin/mall/sys/goods/controller/SkuController.java
xwj1024/ajin-mall
ae4771b104b5d5114e9d1cc004cc4fbe90be8069
[ "Apache-2.0" ]
null
null
null
mall-sys-app/mall-sys-app-goods/src/main/java/ajin/mall/sys/goods/controller/SkuController.java
xwj1024/ajin-mall
ae4771b104b5d5114e9d1cc004cc4fbe90be8069
[ "Apache-2.0" ]
1
2022-03-28T07:25:43.000Z
2022-03-28T07:25:43.000Z
28.644737
91
0.71796
11,481
package ajin.mall.sys.goods.controller; import ajin.mall.common.base.anno.RepeatSubmit; import ajin.mall.common.base.result.BaseResult; import ajin.mall.common.base.result.ResultEnum; import ajin.mall.common.base.result.ResultPage; import ajin.mall.common.data.entity.Sku; import ajin.mall.sys.goods.form.SkuAddForm; import ajin.mall.sys.goods.form.SkuListForm; import ajin.mall.sys.goods.form.SkuUpdateForm; import ajin.mall.sys.goods.service.SkuService; import ajin.mall.sys.goods.view.SkuView; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; /** * <p> * 商品sku表 前端控制器 * </p> * * @author Ajin * @since 2021-04-13 */ @RestController @RequestMapping("/sku") @Api(tags = "商品sku") @CrossOrigin public class SkuController { @Resource private SkuService skuService; @RepeatSubmit @PostMapping @ApiOperation("添加sku") public BaseResult<String> add(@Validated @RequestBody SkuAddForm skuAddForm) { skuService.add(skuAddForm); return new BaseResult<>(ResultEnum.ADD_OK); } @DeleteMapping("/{id}") @ApiOperation("删除sku") public BaseResult<String> delete(@PathVariable("id") Long id) { skuService.delete(id); return new BaseResult<>(ResultEnum.DELETE_OK); } @RepeatSubmit @PutMapping @ApiOperation("修改sku") public BaseResult<String> update(@Validated @RequestBody SkuUpdateForm skuUpdateForm) { skuService.update(skuUpdateForm); return new BaseResult<>(ResultEnum.UPDATE_OK); } @GetMapping("/{id}") @ApiOperation("根据id查询sku") public BaseResult<Sku> get(@PathVariable("id") Long id) { Sku result = skuService.get(id); return new BaseResult<>(ResultEnum.GET_OK, result); } @PostMapping("/list") @ApiOperation("根据条件查询Sku") public BaseResult<ResultPage<SkuView>> list(@RequestBody SkuListForm skuListForm) { ResultPage<SkuView> result = skuService.list(skuListForm); return new BaseResult<>(ResultEnum.GET_OK, result); } }
3e1b1d38e8e140f55e01450d4d03e39023125c91
758
java
Java
src/com/ichmed/trinketeers/util/render/light/ILight.java
Haringat/Trinketeers
47e8c8585338d8ae0844ba934223f832dd4d57f6
[ "MIT" ]
null
null
null
src/com/ichmed/trinketeers/util/render/light/ILight.java
Haringat/Trinketeers
47e8c8585338d8ae0844ba934223f832dd4d57f6
[ "MIT" ]
null
null
null
src/com/ichmed/trinketeers/util/render/light/ILight.java
Haringat/Trinketeers
47e8c8585338d8ae0844ba934223f832dd4d57f6
[ "MIT" ]
null
null
null
26.137931
91
0.726913
11,482
package com.ichmed.trinketeers.util.render.light; import org.lwjgl.util.vector.Vector2f; import org.lwjgl.util.vector.Vector4f; public interface ILight { public boolean isActive(); //RGBA Value (A = Brightness) public Vector4f getColor(); //Direction the light is pointing (doesn't matter for circular lights) public Vector2f getDirection(); //The light sources center-point public Vector2f getPosition(); //the angle of the light-cone (360 for circular light, must be <= 360) public float getAngle(); //If the light source is farther than getMaxRange from the camera it will not be rendered public float getMaxRange(); public void setPosition(Vector2f pos); public boolean shouldRender(int layer); }
3e1b1e726be3ba9c512eea8bb0e31ff4fbadc4a6
5,821
java
Java
plugin/trino-delta-lake/src/main/java/io/trino/plugin/deltalake/statistics/MetaDirStatisticsAccess.java
kbendick/trino
cf29082c8735f7d0a994c1867b1525720f7fe279
[ "Apache-2.0" ]
1,695
2019-01-19T09:05:17.000Z
2020-12-27T17:39:08.000Z
plugin/trino-delta-lake/src/main/java/io/trino/plugin/deltalake/statistics/MetaDirStatisticsAccess.java
kbendick/trino
cf29082c8735f7d0a994c1867b1525720f7fe279
[ "Apache-2.0" ]
4,549
2019-01-21T02:50:11.000Z
2020-12-27T20:38:26.000Z
plugin/trino-delta-lake/src/main/java/io/trino/plugin/deltalake/statistics/MetaDirStatisticsAccess.java
kbendick/trino
cf29082c8735f7d0a994c1867b1525720f7fe279
[ "Apache-2.0" ]
909
2019-01-19T06:51:51.000Z
2020-12-26T20:06:11.000Z
44.435115
162
0.724102
11,483
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.trino.plugin.deltalake.statistics; import com.google.inject.Inject; import io.airlift.json.JsonCodec; import io.trino.plugin.hive.HdfsEnvironment; import io.trino.spi.TrinoException; import io.trino.spi.connector.ConnectorSession; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Optional; import static io.trino.plugin.deltalake.transactionlog.TransactionLogUtil.TRANSACTION_LOG_DIRECTORY; import static io.trino.plugin.hive.util.HiveWriteUtils.createDirectory; import static io.trino.plugin.hive.util.HiveWriteUtils.pathExists; import static io.trino.spi.StandardErrorCode.GENERIC_INTERNAL_ERROR; import static java.lang.String.format; import static java.util.Objects.requireNonNull; public class MetaDirStatisticsAccess implements ExtendedStatisticsAccess { private static final String STATISTICS_META_DIR = TRANSACTION_LOG_DIRECTORY + "/_trino_meta"; // store inside TL directory so it is not deleted by VACUUM private static final String STATISTICS_FILE = "extended_stats.json"; private static final String STARBURST_META_DIR = TRANSACTION_LOG_DIRECTORY + "/_starburst_meta"; private static final String STARBURST_STATISTICS_FILE = "extendeded_stats.json"; private final HdfsEnvironment hdfsEnvironment; private final JsonCodec<ExtendedStatistics> statisticsCodec; @Inject public MetaDirStatisticsAccess( HdfsEnvironment hdfsEnvironment, JsonCodec<ExtendedStatistics> statisticsCodec) { this.hdfsEnvironment = requireNonNull(hdfsEnvironment, "hdfsEnvironment is null"); this.statisticsCodec = requireNonNull(statisticsCodec, "statisticsCodec is null"); } @Override public Optional<ExtendedStatistics> readExtendedStatistics( ConnectorSession session, String tableLocation) { return readExtendedStatistics(session, tableLocation, STATISTICS_META_DIR, STATISTICS_FILE) .or(() -> readExtendedStatistics(session, tableLocation, STARBURST_META_DIR, STARBURST_STATISTICS_FILE)); } private Optional<ExtendedStatistics> readExtendedStatistics(ConnectorSession session, String tableLocation, String statisticsDirectory, String statisticsFile) { try { Path statisticsPath = new Path(new Path(tableLocation, statisticsDirectory), statisticsFile); FileSystem fileSystem = hdfsEnvironment.getFileSystem(new HdfsEnvironment.HdfsContext(session), statisticsPath); if (!fileSystem.exists(statisticsPath)) { return Optional.empty(); } try (InputStream inputStream = fileSystem.open(statisticsPath)) { return Optional.of(statisticsCodec.fromJson(inputStream.readAllBytes())); } } catch (IOException e) { throw new TrinoException(GENERIC_INTERNAL_ERROR, format("failed to read statistics with table location %s", tableLocation), e); } } @Override public void updateExtendedStatistics( ConnectorSession session, String tableLocation, ExtendedStatistics statistics) { Path metaPath = new Path(tableLocation, STATISTICS_META_DIR); ensureDirectoryExists(session, metaPath); try { Path statisticsPath = new Path(metaPath, STATISTICS_FILE); FileSystem fileSystem = hdfsEnvironment.getFileSystem(new HdfsEnvironment.HdfsContext(session), metaPath); try (OutputStream outputStream = fileSystem.create(statisticsPath, true)) { outputStream.write(statisticsCodec.toJsonBytes(statistics)); } // Remove outdated Starburst stats file, if it exists. fileSystem.delete(new Path(new Path(tableLocation, STARBURST_META_DIR), STARBURST_STATISTICS_FILE), false); } catch (IOException e) { throw new TrinoException(GENERIC_INTERNAL_ERROR, format("failed to store statistics with table location %s", tableLocation), e); } } @Override public void deleteExtendedStatistics(ConnectorSession session, String tableLocation) { Path statisticsPath = new Path(new Path(tableLocation, STATISTICS_META_DIR), STATISTICS_FILE); try { FileSystem hdfs = hdfsEnvironment.getFileSystem(new HdfsEnvironment.HdfsContext(session), statisticsPath); if (!hdfs.delete(statisticsPath, false) && hdfs.exists(statisticsPath)) { throw new TrinoException(GENERIC_INTERNAL_ERROR, format("Failed to delete statistics file %s", statisticsPath)); } } catch (IOException e) { throw new TrinoException(GENERIC_INTERNAL_ERROR, format("Error deleting statistics file %s", statisticsPath), e); } } private void ensureDirectoryExists(ConnectorSession session, Path directoryPath) { HdfsEnvironment.HdfsContext hdfsContext = new HdfsEnvironment.HdfsContext(session); if (!pathExists(hdfsContext, hdfsEnvironment, directoryPath)) { createDirectory(hdfsContext, hdfsEnvironment, directoryPath); } } }
3e1b1e8072aa5b92e4fc95fa7eda7a31cc26b769
973
java
Java
src/main/java/uk/gov/hmcts/reform/divorce/orchestration/tasks/CaseDataToDivorceFormatterTask.java
uk-gov-mirror/hmcts.div-case-orchestration-service
a43c5d0b44f470eecea18d0f5f56b152d4230be3
[ "MIT" ]
7
2018-10-03T10:16:08.000Z
2021-12-10T16:19:21.000Z
src/main/java/uk/gov/hmcts/reform/divorce/orchestration/tasks/CaseDataToDivorceFormatterTask.java
uk-gov-mirror/hmcts.div-case-orchestration-service
a43c5d0b44f470eecea18d0f5f56b152d4230be3
[ "MIT" ]
975
2018-08-28T09:35:17.000Z
2022-03-31T17:39:57.000Z
src/main/java/uk/gov/hmcts/reform/divorce/orchestration/tasks/CaseDataToDivorceFormatterTask.java
uk-gov-mirror/hmcts.div-case-orchestration-service
a43c5d0b44f470eecea18d0f5f56b152d4230be3
[ "MIT" ]
3
2018-10-10T09:44:57.000Z
2021-04-10T22:35:46.000Z
37.423077
112
0.802672
11,484
package uk.gov.hmcts.reform.divorce.orchestration.tasks; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Component; import uk.gov.hmcts.reform.divorce.orchestration.client.CaseFormatterClient; import uk.gov.hmcts.reform.divorce.orchestration.framework.workflow.task.Task; import uk.gov.hmcts.reform.divorce.orchestration.framework.workflow.task.TaskContext; import java.util.Map; import static uk.gov.hmcts.reform.divorce.orchestration.domain.model.OrchestrationConstants.AUTH_TOKEN_JSON_KEY; @Component @RequiredArgsConstructor public class CaseDataToDivorceFormatterTask implements Task<Map<String, Object>> { private final CaseFormatterClient caseFormatterClient; @Override public Map<String, Object> execute(TaskContext context, Map<String, Object> caseData) { return caseFormatterClient.transformToDivorceFormat( context.getTransientObject(AUTH_TOKEN_JSON_KEY), caseData ); } }
3e1b1ff6ffdcc49fbed879f749197be60042e94d
264
java
Java
src/aoa/LinearTime.java
Haoyu2/java
aaa3e515889c6f1ecdd6dc3f52e6e8d9f1a4cabe
[ "MIT" ]
1
2022-01-27T19:34:44.000Z
2022-01-27T19:34:44.000Z
src/aoa/LinearTime.java
Haoyu2/java
aaa3e515889c6f1ecdd6dc3f52e6e8d9f1a4cabe
[ "MIT" ]
null
null
null
src/aoa/LinearTime.java
Haoyu2/java
aaa3e515889c6f1ecdd6dc3f52e6e8d9f1a4cabe
[ "MIT" ]
null
null
null
18.857143
48
0.469697
11,485
package aoa; public class LinearTime { public static double average(Integer[] arr){ if (arr.length == 0) return 0; int res = 0; for (int i :arr ) { res += i; } return res/arr.length; } }
3e1b21b31c4ab810be86a7ae4a2700c5a14a1200
1,760
java
Java
src/main/java/com/ne0nx3r0/quantum/receiver/PistonReceiver.java
Erumeldor/Quantum-Connectors_old
46ffe22c77e0623954174b305f09bc8412e6da73
[ "Apache-2.0" ]
null
null
null
src/main/java/com/ne0nx3r0/quantum/receiver/PistonReceiver.java
Erumeldor/Quantum-Connectors_old
46ffe22c77e0623954174b305f09bc8412e6da73
[ "Apache-2.0" ]
null
null
null
src/main/java/com/ne0nx3r0/quantum/receiver/PistonReceiver.java
Erumeldor/Quantum-Connectors_old
46ffe22c77e0623954174b305f09bc8412e6da73
[ "Apache-2.0" ]
null
null
null
33.846154
104
0.641477
11,486
package com.ne0nx3r0.quantum.receiver; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.material.PistonBaseMaterial; import org.bukkit.material.PistonExtensionMaterial; /* * Unused! * Todo: Fix it! */ public class PistonReceiver extends Receiver { public PistonReceiver(Location location, int type) { super(location, type); } public PistonReceiver(Location location, int type, int delay) { super(location, type, delay); } @Override public void setActive(boolean powerOn) { //Block b = location.getBlock(); PistonBaseMaterial pistonBase = (PistonBaseMaterial) location.getBlock().getState().getData(); //b.setData(pistonBase.getData()); /* pistonBase.setPowered(powerOn); //b.setType(Material.PISTON_EXTENSION); ((PistonBaseMaterial) location.getBlock().getState().getData()).setPowered(powerOn); location.getBlock().getState().update();*/ Block l = location.getBlock();//Basically, you are getting the block in front of the piston end. Block b = l.getRelative(pistonBase.getFacing());//Or whatever direction is to the piston if(b.getType()== Material.PISTON_BASE){ PistonBaseMaterial piston = (PistonBaseMaterial) b.getState().getData(); if(!piston.isPowered()){ piston.setPowered(true); b.setData(piston.getData()); l.setType(Material.PISTON_EXTENSION); PistonExtensionMaterial pe = (PistonExtensionMaterial) l.getState().getData(); l.setData(pe.getData()); l.getState().update(); b.getState().update(); } } } }
3e1b228c69ff6f6e50e378fb87346a1ae8db34ee
1,590
java
Java
src/main/java/io/tealight/api/oanda/v20/def/transaction/TransactionPagesResponse.java
fyanardi/tealight-api-oanda-v20
147ef7f3d1dac3d390e89f38854f76f20e3c5a08
[ "MIT" ]
null
null
null
src/main/java/io/tealight/api/oanda/v20/def/transaction/TransactionPagesResponse.java
fyanardi/tealight-api-oanda-v20
147ef7f3d1dac3d390e89f38854f76f20e3c5a08
[ "MIT" ]
null
null
null
src/main/java/io/tealight/api/oanda/v20/def/transaction/TransactionPagesResponse.java
fyanardi/tealight-api-oanda-v20
147ef7f3d1dac3d390e89f38854f76f20e3c5a08
[ "MIT" ]
null
null
null
22.083333
94
0.610692
11,487
// This Java source file was generated on 2020-09-11 14:55:02 (Malay Peninsula Standard Time) package io.tealight.api.oanda.v20.def.transaction; import java.time.ZonedDateTime; public class TransactionPagesResponse { private ZonedDateTime from; private ZonedDateTime to; private Integer pageSize; private TransactionFilter[] type; private Integer count; private String[] pages; private String lastTransactionID; public ZonedDateTime getFrom() { return from; } public void setFrom(ZonedDateTime from) { this.from = from; } public ZonedDateTime getTo() { return to; } public void setTo(ZonedDateTime to) { this.to = to; } public Integer getPageSize() { return pageSize; } public void setPageSize(Integer pageSize) { this.pageSize = pageSize; } public TransactionFilter[] getType() { return type; } public void setType(TransactionFilter[] type) { this.type = type; } public Integer getCount() { return count; } public void setCount(Integer count) { this.count = count; } public String[] getPages() { return pages; } public void setPages(String[] pages) { this.pages = pages; } public String getLastTransactionID() { return lastTransactionID; } public void setLastTransactionID(String lastTransactionID) { this.lastTransactionID = lastTransactionID; } }
3e1b22ea7b3c9c0b19d6b65582c8606d5476e35a
3,059
java
Java
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/appmanager/ApplicationManager.java
marinich135/java_ft
6554480ed894fd14123336703d0a00b6b88539ff
[ "Apache-2.0" ]
null
null
null
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/appmanager/ApplicationManager.java
marinich135/java_ft
6554480ed894fd14123336703d0a00b6b88539ff
[ "Apache-2.0" ]
null
null
null
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/appmanager/ApplicationManager.java
marinich135/java_ft
6554480ed894fd14123336703d0a00b6b88539ff
[ "Apache-2.0" ]
null
null
null
27.3125
111
0.716901
11,488
package ru.stqa.pft.addressbook.appmanager; import org.openqa.selenium.*; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.remote.BrowserType; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.net.URL; import java.util.Properties; import java.util.concurrent.TimeUnit; public class ApplicationManager { private final Properties properties; protected WebDriver wd; private ContactHelper contactHelper; private SessionHelper sessionHelper; private NavigationHelper navigationHelper; private GroupHelper groupHelper; private String browser; private DbHelper dbHelper; public ApplicationManager(String browser) { this.browser = browser; properties = new Properties(); } public void init() throws IOException { String target = System.getProperty("target", "local"); properties.load(new FileReader(new File(String.format("src/test/resources/%s.properties", target)))); dbHelper = new DbHelper(); if ("".equals(properties.getProperty("selenium.server"))) { if (browser.equals(BrowserType.CHROME)) { wd = new ChromeDriver(); } else if (browser.equals(BrowserType.FIREFOX)) { wd = new FirefoxDriver(); } else if (browser.equals(BrowserType.IE)) { wd = new InternetExplorerDriver(); } } else { DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setBrowserName(browser); capabilities.setPlatform(Platform.fromString(System.getProperty("platform", "win10"))); wd = new RemoteWebDriver(new URL(properties.getProperty("selenium.server")), capabilities); } wd.manage().timeouts().implicitlyWait(1,TimeUnit.SECONDS); wd.get(properties.getProperty("web.baseUrl")); contactHelper = new ContactHelper(wd); groupHelper = new GroupHelper(wd); navigationHelper = new NavigationHelper(wd); sessionHelper = new SessionHelper(wd); sessionHelper.login(properties.getProperty("web.adminLogin"), properties.getProperty("web.adminPassword")); } public void logOut() { wd.findElement(By.xpath("//div[@id='top']/form/a")).click(); } public void stop() { wd.quit(); } private boolean isElementPresent(By by) { try { wd.findElement(by); return true; } catch (NoSuchElementException e) { return false; } } public GroupHelper group() { return groupHelper; } public NavigationHelper goTo() { return navigationHelper; } public void gotoGroupPage() { navigationHelper.GroupPage(); } public ContactHelper Contact() { return contactHelper; } public DbHelper db() { return dbHelper; } public byte[] takeScreenshot(){ return ((TakesScreenshot)wd).getScreenshotAs(OutputType.BYTES); } }
3e1b233064bf41b8dad5f139f58de8d38b927b72
2,219
java
Java
src/main/java/com/domenicseccareccia/jpegautorotate/imaging/JpegImageReader.java
jweilhammer/jpeg-autorotate
6d390b596cae052416cfc32f1468a52a0b5709d6
[ "Apache-2.0" ]
null
null
null
src/main/java/com/domenicseccareccia/jpegautorotate/imaging/JpegImageReader.java
jweilhammer/jpeg-autorotate
6d390b596cae052416cfc32f1468a52a0b5709d6
[ "Apache-2.0" ]
null
null
null
src/main/java/com/domenicseccareccia/jpegautorotate/imaging/JpegImageReader.java
jweilhammer/jpeg-autorotate
6d390b596cae052416cfc32f1468a52a0b5709d6
[ "Apache-2.0" ]
null
null
null
33.621212
97
0.677783
11,489
/** * Copyright (c) 2019-2020 Domenic Seccareccia and contributors * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.domenicseccareccia.jpegautorotate.imaging; import com.domenicseccareccia.jpegautorotate.JpegAutorotateException; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.*; final class JpegImageReader { /** * Not intended for instantiation. */ private JpegImageReader() { throw new IllegalStateException("Not intended for instantiation."); } /** * Attempts to read JPEG file to a BufferedImage. * * @param bytes * {@code bytes} containing a JPEG image file. * @return If successful, a {@code BufferedImage} containing image data. * @throws JpegAutorotateException * In the event the {@code bytes} is unable to be read. */ protected static BufferedImage readImage(final byte[] bytes) throws JpegAutorotateException { try { File tempFile = File.createTempFile("tmp", "jpg"); FileOutputStream fos = new FileOutputStream(tempFile); fos.write(bytes); BufferedImage image = ImageIO.read(tempFile); fos.flush(); fos.close(); tempFile.deleteOnExit(); return image; } catch (IOException e) { throw new JpegAutorotateException("Unable to read JPEG image.", e); } } }
3e1b23c115e706e55f925a134b44709adbde3b2d
2,862
java
Java
modules/base/util/util-collection/src/main/java/consulo/util/collection/Sets.java
MC-JY/consulo
ebd31008fcfd03e144b46a9408d2842d0b06ffc8
[ "Apache-2.0" ]
634
2015-01-01T19:14:25.000Z
2022-03-22T11:42:50.000Z
modules/base/util/util-collection/src/main/java/consulo/util/collection/Sets.java
MC-JY/consulo
ebd31008fcfd03e144b46a9408d2842d0b06ffc8
[ "Apache-2.0" ]
410
2015-01-19T09:57:51.000Z
2022-03-22T16:24:59.000Z
modules/base/util/util-collection/src/main/java/consulo/util/collection/Sets.java
MC-JY/consulo
ebd31008fcfd03e144b46a9408d2842d0b06ffc8
[ "Apache-2.0" ]
50
2015-03-10T04:14:49.000Z
2022-03-22T07:08:45.000Z
32.157303
124
0.749126
11,490
/* * Copyright 2013-2021 consulo.io * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package consulo.util.collection; import consulo.util.collection.impl.CollectionFactory; import consulo.util.collection.impl.map.ConcurrentHashMap; import consulo.util.collection.impl.set.WeakHashSet; import org.jetbrains.annotations.Contract; import javax.annotation.Nonnull; import java.util.Collection; import java.util.Collections; import java.util.Set; /** * @author VISTALL * @since 16/01/2021 */ public final class Sets { private static CollectionFactory ourFactory = CollectionFactory.get(); @Contract(value = " -> new", pure = true) @Nonnull public static <T> Set<T> newWeakHashSet() { return new WeakHashSet<>(); } @Nonnull @Contract(pure = true) public static <T> Set<T> newHashSet(@Nonnull HashingStrategy<T> hashingStrategy) { return newHashSet(CollectionFactory.UNKNOWN_CAPACITY, hashingStrategy); } @Nonnull @Contract(pure = true) public static <T> Set<T> newHashSet(@Nonnull Collection<? extends T> items, @Nonnull HashingStrategy<T> hashingStrategy) { return ourFactory.newHashSetWithStrategy(CollectionFactory.UNKNOWN_CAPACITY, items, hashingStrategy); } @Nonnull @Contract(pure = true) public static <K> Set<K> newHashSet(int initialCapacity, @Nonnull HashingStrategy<K> hashingStrategy) { return ourFactory.newHashSetWithStrategy(initialCapacity, null, hashingStrategy); } @Nonnull @Contract(pure = true) public static <T> Set<T> newLinkedHashSet(@Nonnull HashingStrategy<T> hashingStrategy) { return Collections.newSetFromMap(Maps.newLinkedHashMap(hashingStrategy)); } @Nonnull @Contract(pure = true) public static <K> Set<K> newIdentityHashSet() { return newHashSet(CollectionFactory.UNKNOWN_CAPACITY, HashingStrategy.identity()); } @Nonnull @Contract(pure = true) public static <K> Set<K> newIdentityHashSet(int initialCapacity) { return newHashSet(initialCapacity, HashingStrategy.identity()); } @Nonnull @Contract(pure = true) public static <T> Set<T> newConcurrentHashSet() { return ConcurrentHashMap.newKeySet(); } @Nonnull @Contract(pure = true) public static <T> Set<T> newConcurrentHashSet(@Nonnull HashingStrategy<T> hashStrategy) { return Collections.newSetFromMap(Maps.newConcurrentHashMap(hashStrategy)); } }
3e1b244f3316e13b4fbcd51309a1d393de0e8ff7
8,345
java
Java
Aufgabe1-3/GroundSwarm.java
alpenraum/Tu_OOP_2018s
e3eb8a6cd04312c045c51be418abcfa31d504b20
[ "MIT" ]
null
null
null
Aufgabe1-3/GroundSwarm.java
alpenraum/Tu_OOP_2018s
e3eb8a6cd04312c045c51be418abcfa31d504b20
[ "MIT" ]
null
null
null
Aufgabe1-3/GroundSwarm.java
alpenraum/Tu_OOP_2018s
e3eb8a6cd04312c045c51be418abcfa31d504b20
[ "MIT" ]
1
2022-01-21T00:29:08.000Z
2022-01-21T00:29:08.000Z
37.254464
123
0.57855
11,491
import java.util.ArrayList; public class GroundSwarm extends Swarm { /** * Generates a GroundSwarm for Animals which are located at height = 0 * @param maxHeight max. flight altitude * @param animalCount size of the Swarm * @param swarmDrawOffset */ public GroundSwarm(int maxHeight,int animalCount, int swarmDrawOffset){ this.dependentAnimals = new ArrayList<>(); this.independentAnimals = new ArrayList<>(); this.searchRadius = 100.0f; this.borderSize = 5.0f; this.randomAnimalSpeed = 0.3f; this.safeSpace = 5.0f; this.attractionSpeed = 1.0f; // this.worldX = x; //this.worldY = y; this.maxHeight = 0; this.animalCount = animalCount; this.speed = 0.3f; this.swarmDrawOffset = swarmDrawOffset; } /** * Calculates for n different Animals random x and y directions with z = 0. Swarm must have at least n Animals. * @param n number of random Animals */ public void calcRandomAnimals(int n) { for (Animal b : independentAnimals) { b.setColor(b.getColor()); } this.dependentAnimals.addAll(independentAnimals); this.independentAnimals.clear(); for (int i = n; i > 0; i--) { //Pick random bird int r = (int) (Math.random() * (this.dependentAnimals.size())); Animal temp = this.dependentAnimals.remove(r); //Calculate random direction float rX = (float) (Math.random() * 2 - 1); float rY = (float) (Math.random() * 2 - 1); //Normalize Vector float norm = calcEuclideanNorm(rX, rY); rX /= norm; rY /= norm; //Set the new direction temp.setVelX(rX * randomAnimalSpeed); temp.setVelY(rY * randomAnimalSpeed); temp.setVelZ(0.0f); this.independentAnimals.add(temp); } } /** * Returns a new Animal with the position of Animal b and a new velocity vector. The direction of the velocity * vector points in the opposite direction of the Animal b and the Animal nearest Neighbour. * @param b Input Animal * @param nearestNeighbour Nearest neighbour of b * @return */ protected Animal collisionMode(Animal b, Animal nearestNeighbour){ float vX = 0.0f; float vY = 0.0f; float vZ = 0.0f; vX = b.getXCoor() - nearestNeighbour.getXCoor(); vY = b.getYCoor() - nearestNeighbour.getYCoor(); vZ = 0.0f; float norm = calcEuclideanNorm(vX, vY); vX /= norm; vY /= norm; Animal temp = new Animal(b.getXCoor(), b.getYCoor(), 0.0f); temp.setVelX(vX); temp.setVelY(vY); temp.setVelZ(0.0f); return temp; } /** * Returns a new Animal with the position of Animal b and a new velocity vector. The direction of the velocity * vector in x and y is the mean of all other velocity vectors of the Animals in Neighbours. * @param b Input Animal * @param Neighbours List of Animal * @return */ protected Animal alignmentMode(Animal b, ArrayList<Animal> Neighbours){ float sumX = 0; float sumY = 0; float sumZ = 0; float vX, vY, vZ = 0; for (Animal i: Neighbours) { sumX += i.getVelX(); sumY += i.getVelY(); } sumX /= Neighbours.size(); sumY /= Neighbours.size(); float norm = calcEuclideanNorm(sumX, sumY); vX = sumX / norm; vY = sumY / norm; vZ = 0.0f; Animal temp = new Animal(b.getXCoor(), b.getYCoor(), b.getZCoor()); temp.setVelX(vX); temp.setVelY(vY); temp.setVelZ(vZ); return temp; } /** * Calculates and manipulates the directions of all Birds in the swarm. Each direction of an * Animal is calculated independently, based on its position and direction of the other Animals in GroundSwarm. * The Swarm must contain at least 1 Animal. */ public void updateVelocity(){ ArrayList<Animal> NewDependetBirds = new ArrayList<>(); //Calculate direction for non-random birds for (Animal b: this.dependentAnimals) { float searchRadius = this.searchRadius; ArrayList<Animal> Neighbours = this.calculateAllNeighbours(b, searchRadius); //Check if there are enough other birds in range. When not -> make radius bigger/smaller if (Neighbours.size() < 5 || Neighbours.size() > 20) { while (Neighbours.size() < 5.0) { searchRadius *= 1.1; Neighbours = this.calculateAllNeighbours(b, searchRadius); } while (Neighbours.size() > 20.0) { searchRadius *= 0.9; Neighbours = this.calculateAllNeighbours(b, searchRadius); } } Animal newBird; /**Collision-mode: When other bird is to near and not in border-range, the bird flies in the opposite direction of the nearest neighbour **/ Animal NearestNeighbour = this.calcNearestNeighbour(b, Neighbours); if(calcDistance(b, NearestNeighbour) < this.safeSpace){ newBird = collisionMode(b, NearestNeighbour); } /**Alignment-mode: When there are more than 10 birds in range, the direction of bird b is the average direction of all neighbours **/ else if(Neighbours.size() > 18){ newBird = alignmentMode(b, Neighbours); } /**Attraction-mode: When there are only few neighbours in range, the bird b flies to the average position of its neighbours **/ else{ newBird = attractionMode(b, Neighbours); } newBird.setZCoor(0.0f); newBird.setVelZ(0.0f); NewDependetBirds.add(newBird); } this.copyValuesFrom(NewDependetBirds); } /** * FEHLER: Die Methode des Obertyps besitzt die Nachbedingung dass, die Richtungsvektoren auch die Futtersuche * unterstützen. Diese wird aber vom Untertyp abgeschwächt, indem diese Methode einfach die updateVelocity() Methode * aufruft ohne dieser Berücksichtigung. * Zu diesem Fehler kam es da nur eine Methode in Test für alle Swarms aufgerufen werden kann um die Vektoren zu * berechnen. Eine Möglichkeit wäre die updateVelocitywithFood-Methode in updateVelocity() einzubauen, so das es nur * eine Funktion gibt und die Berücksichtigung ob eine Swarm Futter sucht in eine boolean Objektvariable zu speichern. * * Same as the updateVeloctiy Method. * @param food an existing FoodSource */ public void updateVelocitywithFood(FoodSource food){ updateVelocity(); } /** * Returns a new Animal with the position of Animal b and a new velocity vector. The direction of the velocity * vector points to the mean position of all other Animals in Neighbours and sets the velocity in z-direction to 0. * @param b Input Animal * @param Neighbours List of Animal * @return the new Animal with updated velocity vectors */ protected Animal attractionMode(Animal b, ArrayList<Animal> Neighbours){ float sumX = 0.0f; float sumY = 0.0f; float vX = 0.0f; float vY = 0.0f; for (Animal i: Neighbours) { sumX += i.getXCoor(); sumY += i.getYCoor(); } sumX /= Neighbours.size(); sumY /= Neighbours.size(); vX = -b.getXCoor() + sumX; vY = -b.getYCoor() + sumY; float norm = calcEuclideanNorm(vX,vY); vX /= norm; vY /= norm; vX *= this.attractionSpeed; vY *= this.attractionSpeed; Animal temp = new Animal(b.getXCoor(), b.getYCoor(), b.getZCoor()); temp.setVelX(vX); temp.setVelY(vY); temp.setVelZ(0.0f); return temp; } }
3e1b24efeff9d411ca1986d071a193c300600926
426
java
Java
src/main/java/discojx/discogs/api/endpoints/marketplace/order/requests/edit/MarketplaceEditOrderRequestBuilder.java
drewlakee/DiscoJx
7acbfc1d41a7be0ae38a1b03a90ef57e16d72f00
[ "MIT" ]
null
null
null
src/main/java/discojx/discogs/api/endpoints/marketplace/order/requests/edit/MarketplaceEditOrderRequestBuilder.java
drewlakee/DiscoJx
7acbfc1d41a7be0ae38a1b03a90ef57e16d72f00
[ "MIT" ]
null
null
null
src/main/java/discojx/discogs/api/endpoints/marketplace/order/requests/edit/MarketplaceEditOrderRequestBuilder.java
drewlakee/DiscoJx
7acbfc1d41a7be0ae38a1b03a90ef57e16d72f00
[ "MIT" ]
null
null
null
38.727273
105
0.856808
11,492
package discojx.discogs.api.endpoints.marketplace.order.requests.edit; import discojx.discogs.api.requests.RequestBuilder; public interface MarketplaceEditOrderRequestBuilder extends RequestBuilder<MarketplaceEditOrderRequest> { MarketplaceEditOrderRequestBuilder orderId(String orderId); MarketplaceEditOrderRequestBuilder status(String status); MarketplaceEditOrderRequestBuilder shipping(double shipping); }
3e1b25d796c6c98d1fbcc3de9038ef7ae91debba
54,418
java
Java
src/main/java/edu/ucsf/rbvi/scNetViz/internal/algorithms/tSNE/MatrixOps.java
RBVI/scNetViz
49668c2202cefe836db5b661797148a5573ed46a
[ "Apache-2.0" ]
7
2019-01-29T16:46:18.000Z
2021-07-22T17:00:46.000Z
src/main/java/edu/ucsf/rbvi/scNetViz/internal/algorithms/tSNE/MatrixOps.java
RBVI/scNetViz
49668c2202cefe836db5b661797148a5573ed46a
[ "Apache-2.0" ]
40
2018-10-30T23:08:24.000Z
2022-01-12T18:18:43.000Z
src/main/java/edu/ucsf/rbvi/scNetViz/internal/algorithms/tSNE/MatrixOps.java
RBVI/scNetViz
49668c2202cefe836db5b661797148a5573ed46a
[ "Apache-2.0" ]
2
2018-10-28T19:12:37.000Z
2019-03-12T15:46:25.000Z
28.137539
151
0.593315
11,493
package edu.ucsf.rbvi.scNetViz.internal.algorithms.tSNE; import java.io.File; import java.io.FileOutputStream; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.List; import java.util.Random; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.RecursiveAction; import java.util.concurrent.ThreadLocalRandom; import Jama.Matrix; import org.ejml.data.DMatrixRMaj; public class MatrixOps { Random rnd = new Random(); static DecimalFormat mydecimalFormat = new DecimalFormat("00.###E0"); private static ForkJoinPool pool = new ForkJoinPool(); private static String DEFAULT_TITLE = "Vector"; public static int noDigits = 4; public static String arrToStr(int [] arr, String title) { String res = ""; res += title + "[" + arr.length + "]:"; for (int j = 0; j < arr.length; j++) { res += arr[j] + ", "; } res += "\n"; return res; } public static String arrToStr(List<String> labels, int [] arr) { StringBuilder builder = new StringBuilder(); for (int j = 0; j < arr.length; j++) { builder.append(labels.get(j)+": "+arr[j]+"\n"); } return builder.toString(); } public static String arrToStr(List<String> labels, double [] arr) { StringBuilder builder = new StringBuilder(); for (int j = 0; j < arr.length; j++) { builder.append(labels.get(j)+": "+formatDouble(arr[j])+"\n"); } return builder.toString(); } public static String arrToStr(double [] arr) { return arrToStr(arr, DEFAULT_TITLE, Integer.MAX_VALUE); } public static String arrToStr(double [] arr, int maxLen) { return arrToStr(arr, DEFAULT_TITLE, maxLen); } public static String arrToStr(double [] arr, String title) { return arrToStr(arr, title, Integer.MAX_VALUE); } public static String arrToStr(double [] arr, String title, int maxLen) { String res = ""; res += title + "[" + arr.length + "]:"; for (int j = 0; j < arr.length && j < maxLen; j++) { res += formatDouble(arr[j]) + ", "; } return res; } public static String doubleArrayToPrintString(List<String> labels, double[][] m, boolean transpose) { StringBuffer str = new StringBuffer(m.length * m[0].length); if (transpose) { str.append("Dim:" + m[0].length + " x " + m.length + "\n"); for (int col = 0; col < m[0].length; col++) { str.append(labels.get(col)+": "); for (int row = 0; row < m.length; row++) { String formatted = formatDouble(m[row][col]); str.append(formatted+","); } str.append("\n"); } } else { str.append("Dim:" + m.length + " x " + m[0].length + "\n"); for (int row = 0; row < m.length; row++) { str.append(labels.get(row)+": "); for (int col = 0; col < m[0].length; col++) { String formatted = formatDouble(m[row][col]); str.append(formatted+","); } str.append("\n"); } } return str.toString(); } public static String doubleArrayToPrintString(double[][] m) { return doubleArrayToPrintString(m, ", ", Integer.MAX_VALUE, m.length, Integer.MAX_VALUE, "\n"); } public static String doubleArrayToPrintString(double[][] m, int maxRows) { return doubleArrayToPrintString(m, ", ", maxRows, maxRows, Integer.MAX_VALUE, "\n"); } public static String doubleArrayToPrintString(double[][] m, String colDelimiter) { return doubleArrayToPrintString(m, colDelimiter, Integer.MAX_VALUE, -1, Integer.MAX_VALUE, "\n"); } public static String doubleArrayToPrintString(double[][] m, String colDelimiter, int toprowlim) { return doubleArrayToPrintString(m, colDelimiter, toprowlim, -1, Integer.MAX_VALUE, "\n"); } public static String doubleArrayToPrintString(double[][] m, int toprowlim, int btmrowlim) { return doubleArrayToPrintString(m, ", ", toprowlim, btmrowlim, Integer.MAX_VALUE, "\n"); } public static String doubleArrayToPrintString(double[][] m, int toprowlim, int btmrowlim, int collim) { return doubleArrayToPrintString(m, ", ", toprowlim, btmrowlim, collim, "\n"); } public static String doubleArrayToPrintString(double[][] m, String colDelimiter, int toprowlim, int btmrowlim) { return doubleArrayToPrintString(m, colDelimiter, toprowlim, btmrowlim, Integer.MAX_VALUE, "\n"); } public static String doubleArrayToPrintString(double[][] m, String colDelimiter, int toprowlim, int btmrowlim, int collim) { return doubleArrayToPrintString(m, colDelimiter, toprowlim, btmrowlim, collim, "\n"); } public static String doubleArrayToPrintString(double[][] m, String colDelimiter, int toprowlim, int btmrowlim, int collim, String sentenceDelimiter) { StringBuffer str = new StringBuffer(m.length * m[0].length); str.append("Dim:" + m.length + " x " + m[0].length + "\n"); int i = 0; for (; i < m.length && i < toprowlim; i++) { String rowPref = i < 1000 ? String.format("%03d", i) : String.format("%04d", i); str.append(rowPref+": ["); for (int j = 0; j < m[i].length - 1 && j < collim; j++) { String formatted = formatDouble(m[i][j]); str = str.append(formatted); str = str.append(colDelimiter); } str = str.append(formatDouble(m[i][m[i].length - 1])); if( collim == Integer.MAX_VALUE) { str.append("]"); } else { str.append("...]"); } if (i < m.length - 1) { str = str.append(sentenceDelimiter); } } if(btmrowlim<0) return str.toString(); while(i<(m.length-btmrowlim)) i++; if( i < m.length) str.append("\t.\n\t.\n\t.\n"); for (; i < m.length; i++) { String rowPref = i < 1000 ? String.format("%03d", i) : String.format("%04d", i); str.append(rowPref+": ["); for (int j = 0; j < m[i].length - 1 && j < collim; j++) { str = str.append(formatDouble(m[i][j])); str = str.append(colDelimiter); } str = str.append(formatDouble(m[i][m[i].length - 1])); if( collim > m[i].length ) { str.append("]"); } else { str.append(", ...]"); } if (i < m.length - 1) { str = str.append(sentenceDelimiter); } } return str.toString(); } public static String formatDouble(double d) { if ( d == 0.0 ) return "<0.0>"; if ( d<0.0001 && d>0 || d > -0.0001 && d < 0) { return mydecimalFormat.format(d); } else { String formatString = "%." + noDigits + "f"; return String.format(formatString, d); } } public static String doubleArrayToString(double[][] m) { return doubleArrayToString(m, ","); } public static String doubleArrayToString(double[][] m, String colDelimiter) { StringBuffer str = new StringBuffer(m.length * m[0].length); for (int i = 0; i < m.length; i++) { for (int j = 0; j < m[i].length - 1; j++) { str = str.append(Double.toString(m[i][j])); str = str.append(colDelimiter); } str = str.append(Double.toString(m[i][m[i].length - 1])); str = str.append("\n"); } return str.toString(); } public static double [] rep(double val, int times) { double [] res = new double[times]; for (int i = 0; i < res.length; i++) { res[i] = val; } return res; } public static double [] asVector(double [][] matrix) { boolean isCol = matrix.length != 1; int n = matrix.length == 1 ? matrix[0].length : matrix.length; if(matrix.length != 1 && matrix[0].length!=1) { throw new IllegalArgumentException("Cannot convert non-row or col matrix to vactor! Matrix dim: " + matrix.length + "x" + matrix[0].length); } double [] res = new double[n]; if(isCol) { for (int j = 0; j < matrix.length; j++) { res[j] = matrix[j][0]; } } else { for (int j = 0; j < matrix[0].length; j++) { res[j] = matrix[0][j]; } } return res; } /** * This function returns a new matrix which is centered and scaled, i.e each * the global mean is subtracted from each element in the matrix and divided * by the global matrix standard deviation * * @return new matrix which is centered (subtracted mean) and scaled (divided with stddev) */ public static double [][] centerAndScaleGlobal(double [][] matrix) { double [][] res = new double[matrix.length][matrix[0].length]; double mean = mean(matrix); double std = stdev(matrix); for (int i = 0; i < res.length; i++) { for (int j = 0; j < res[i].length; j++) { res[i][j] = (matrix[i][j]-mean) / std; } } return res; } /** * This function returns a new matrix which is centered and scaled, i.e each * the column mean is subtracted from each column element in the matrix and * divided by the respective column matrix standard deviation * * @return new matrix which is centered (subtracted mean) and scaled (divided with stddev) */ public static double [][] centerAndScale(double [][] matrix) { double [][] res = new double[matrix.length][matrix[0].length]; double [] means = rowMeans(matrix); for (int i = 0; i < res.length; i++) { for (int j = 0; j < res[i].length; j++) { res[i][j] = (matrix[i][j]-means[i]); } } double [] std = rowStddev(res); for (int i = 0; i < res.length; i++) { for (int j = 0; j < res[i].length; j++) { res[i][j] = res[i][j] / (std[i] == 0 ? 1 : std[i]); } } return res; } public static double [][] centerAndScaleSametime(double [][] matrix) { double [][] res = new double[matrix.length][matrix[0].length]; double [] means = colMeans(matrix); double [] std = colStddev(matrix); for (int i = 0; i < res.length; i++) { for (int j = 0; j < res[i].length; j++) { res[i][j] = (matrix[i][j]-means[j]) / (std[j] == 0 ? 1 : std[j]); } } return res; } /** * This function returns adds a small amount of noise to each column * * @return new matrix with added noise */ public static double [][] addNoise(double [][] matrix) { double [][] res = new double[matrix.length][matrix[0].length]; double [] std = colStddev(matrix); for (int i = 0; i < res.length; i++) { for (int j = 0; j < res[i].length; j++) { double noise = rnorm(0, std[j] == 0.0 ? 0.00001 : std[j]/5); res[i][j] = matrix[i][j] + noise; } } return res; } /** * Returns a new matrix which is the transpose of input matrix * @param matrix * @return */ public static double[][] transposeSerial(double[][] matrix) { int rows = matrix.length; int cols = matrix[0].length; double[][] transpose = new double[cols][rows]; for (int col = 0; col < cols; col++) for (int row = 0; row < rows; row++) transpose[col][row] = matrix[row][col]; return transpose; } // Unit Tested public double[][] transpose(double[][] matrix) { return transpose(matrix, 1000); } // Unit Tested /** * Returns a new matrix which is the transpose of input matrix * @param matrix * @return */ public double[][] transpose(double[][] matrix, int ll) { int cols = matrix[0].length; int rows = matrix.length; double[][] transpose = new double[cols][rows]; if(rows < 100 ) { for (int i = 0; i < cols; i++) for (int j = 0; j < rows; j++) transpose[i][j] = matrix[j][i]; } else { MatrixTransposer process = new MatrixTransposer(matrix, transpose,0,rows,ll); pool.invoke(process); } return transpose; } class MatrixTransposer extends RecursiveAction { private static final long serialVersionUID = 1L; double [][] orig; double [][] transpose; int startRow = -1; int endRow = -1; int limit = 1000; public MatrixTransposer(double [][] orig, double [][] transpose, int startRow, int endRow, int ll) { this.limit = ll; this.orig = orig; this.transpose = transpose; this.startRow = startRow; this.endRow = endRow; } public MatrixTransposer(double [][] orig, double [][] transpose, int startRow, int endRow) { this.orig = orig; this.transpose = transpose; this.startRow = startRow; this.endRow = endRow; } @Override protected void compute() { try { if ( (endRow-startRow) <= limit ) { int cols = orig[0].length; for (int i = 0; i < cols; i++) { for (int j = startRow; j < endRow; j++) { transpose[i][j] = orig[j][i]; } } } else { int range = (endRow-startRow); int startRow1 = startRow; int endRow1 = startRow + (range / 2); int startRow2 = endRow1; int endRow2 = endRow; invokeAll(new MatrixTransposer(orig, transpose, startRow1, endRow1, limit), new MatrixTransposer(orig, transpose, startRow2, endRow2, limit)); } } catch ( Exception e ) { e.printStackTrace(); } } } // Unit Tested /** * Returns a new matrix with values exponentiated * @param matrix * @return new matrix with values exponentiated */ public static double [][] exp(double [][] m1) { double[][] matrix = new double[m1.length][m1[0].length]; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { matrix[i][j] = Math.exp(m1[i][j]); } } return matrix; } // Unit Tested /** * Returns new vetcor with vals sqrt'ed * @param vector * @return new vector with values sqrt'ed */ public static double [] sqrt(double [] v1) { double [] vector = new double[v1.length]; for (int i = 0; i < vector.length; i++) { vector[i] = Math.sqrt(v1[i]); } return vector; } // Unit Tested /** * @param vector * @return mean of values in vector */ public static double mean(double [] vector) { double sum = 0.0; for (int i = 0; i < vector.length; i++) { sum +=vector[i]; } return sum/vector.length; } // Unit Tested /** * Returns a new matrix with values that are the log of the input matrix * @param matrix * @return same matrix with values log'ed */ public static double [][] log(double [][] m1) { double[][] matrix = new double[m1.length][m1[0].length]; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { matrix[i][j] = Math.log(m1[i][j]); } } return matrix; } /** * Returns a new matrix with values that are taken to the power of the input matrix * @param matrix * @param power * @return same matrix with values pow'ed */ public static double [][] pow(double [][] m1, double power) { double[][] matrix = new double[m1.length][m1[0].length]; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { matrix[i][j] = Math.pow(m1[i][j], power); } } return matrix; } /** * Returns a new matrix with values that are taken to the power of the input matrix * @param matrix * @param power * @return same matrix with values pow'ed */ public static double [] pow(double [] m1, double power) { double[] matrix = new double[m1.length]; for (int i = 0; i < matrix.length; i++) { matrix[i] = Math.pow(m1[i], power); } return matrix; } /** * Returns a new matrix with values that are the log of the input matrix * @param matrix * @param infAsZero treat +- Infinity as zero, i.e replaces Infinity with 0.0 * if set to true * @return same matrix with values log'ed */ public static double [][] log(double [][] m1, boolean infAsZero) { double[][] matrix = new double[m1.length][m1[0].length]; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { matrix[i][j] = Math.log(m1[i][j]); if(infAsZero && Double.isInfinite(matrix[i][j])) matrix[i][j] = 0.0; } } return matrix; } // Unit Tested /** * @param matrix * @return scalar inverse of matrix */ public static double [][] scalarInverse(double [][] m1) { double[][] matrix = new double[m1.length][m1[0].length]; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { matrix[i][j] = 1/m1[i][j]; } } return matrix; } // Unit Tested /** * @param vector * @return scalar inverse of vector */ public static double [] scalarInverse(double [] v1) { double [] vector = new double[v1.length]; for (int i = 0; i < vector.length; i++) { vector[i] = 1/v1[i]; } return vector; } /** * @param m * @param n * @return new 2D matrix with normal random values with mean 0 and std. dev 1 */ public static double[][] rnorm(int m, int n) { double[][] array = new double[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < array[i].length; j++) { array[i][j] = rnorm(0.0,1.0); } } return array; } public static double [] rnorm(int n, double [] mus, double [] sigmas) { double [] res = new double[n]; for (int i = 0; i < res.length; i++) { res[i] = mus[i] + (ThreadLocalRandom.current().nextGaussian() * sigmas[i]); } return res; } public static double [] rnorm(int n, double mu, double [] sigmas) { double [] res = new double[n]; for (int i = 0; i < res.length; i++) { res[i] = mu + (ThreadLocalRandom.current().nextGaussian() * sigmas[i]); } return res; } public static double rnorm() { return ThreadLocalRandom.current().nextGaussian(); } /** * A re-implementation of the Seurat LogNormalize: * "Normalize count data per cell and transform to log scale" * * The actual approach is to get the sum of each row, then for each value * replace the value with the log(1+(value/rowSum)*scaleFactor) * * NOTE: this has been validated against seurat's LogNormalize routine */ // TODO: convert to use streams and/or ojAlgo public static double[][] logNormalize(double[][] matrix, double scaleFactor) { double [] colSums = new double[matrix[0].length]; /* for (int row = 0; row < matrix.length; row++) { rowSums[row] = 0.0; for (int col = 0; col < matrix[0].length; col++) { rowSums[row] += matrix[row][col]; } } */ for (int col = 0; col < matrix[0].length; col++) { colSums[col] = 0.0; for (int row = 0; row < matrix.length; row++) { colSums[col] += matrix[row][col]; } } for (int row = 0; row < matrix.length; row++) { for (int col = 0; col < matrix[0].length; col++) { if (matrix[row][col] != 0.0) matrix[row][col] = Math.log1p(matrix[row][col] / colSums[col] * scaleFactor); } } return matrix; } /** * Reduce the matrix requiring a minimum number of detected genes in a row and the minimum number * of genes detected in a column. This is done by default as part of the "CreateSeuratObject" in * seurat. */ public static double[][] reduceMatrix(double[][] matrix, List<String> rowLabels, List<String> colLabels, int minGenes, int minAssays) { int rowCount[] = new int[matrix.length]; Arrays.fill(rowCount, 0); int colCount[] = new int[matrix[0].length]; Arrays.fill(colCount, 0); int newRows = 0; int newCols = 0; for (int row = 0; row < matrix.length; row++) { for (int col = 0; col < matrix[0].length; col++) { if (matrix[row][col] > 0.0) { rowCount[row]++; if (rowCount[row] == minGenes) { newRows++; } colCount[col]++; if (colCount[col] == minAssays) newCols++; } } } double[][] newMatrix = new double[newRows][newCols]; List<String> newRowLabels = new ArrayList<String>(newRows); List<String> newColLabels = new ArrayList<String>(newCols); int newRow = 0; for (int row = 0; row < matrix.length; row++) { if (rowCount[row] < minGenes) continue; newRowLabels.add(rowLabels.get(row)); int newCol = 0; for (int col = 0; col < matrix[0].length; col++) { if (colCount[col] < minAssays) continue; newMatrix[newRow][newCol++] = matrix[row][col]; // We only want to do this the first time if (newRow == 0) newColLabels.add(colLabels.get(col)); } newRow++; } rowLabels.clear(); rowLabels.addAll(newRowLabels); colLabels.clear(); colLabels.addAll(newColLabels); return newMatrix; } public static double[][] findVariableGenes(double[][] matrix, double xLowCutoff, double xHighCutoff, double yCutoff, int maxBins, BitSet bits, List<String> geneLabels) { int rows = matrix.length; int cols = matrix[0].length; // debug("/tmp/inputMatrix", doubleArrayToPrintString(geneLabels, matrix, false)); double[] means = new double[rows]; double[] vmr = new double[rows]; // Calculate our means; for (int row = 0; row < rows; row++) { means[row] = 0.0; for (int col = 0; col < cols; col++) { means[row] += Math.exp(matrix[row][col])-1; } means[row] = means[row] / cols; vmr[row] = 0.0; int nnZero = 0; // Count of non-zero values for (int col = 0; col < cols; col++) { if (matrix[row][col] > 0.0) { double v = Math.exp(matrix[row][col])-1; vmr[row] += Math.pow(v-means[row],2); nnZero++; } } vmr[row] = (vmr[row] + (cols - nnZero) * Math.pow(means[row], 2)) / (cols - 1); if (means[row] == 0.0) vmr[row] = 0.0; else vmr[row] = Math.log(vmr[row] / means[row]); // Convert back to log space means[row] = Math.log1p(means[row]); } // debug("/tmp/means", arrToStr(geneLabels, means)); // debug("/tmp/vmr", arrToStr(geneLabels, vmr)); double[] bins = cut(means, maxBins); // debug("/tmp/bins", arrToStr(bins)); int[] binCount = new int[bins.length]; for (int bin = 0; bin < bins.length; bin++) binCount[bin] = 0; int[] indices = indexBins(means, bins, binCount); // debug("/tmp/indices", arrToStr(geneLabels, indices)); double[][] meanSdY = tapply(vmr, indices, binCount, maxBins); double[] dispersionScaled = new double[rows]; // System.out.println("Calculating scaled dispersion"); for (int row = 0; row < rows; row++) { dispersionScaled[row] = (vmr[row] - meanSdY[indices[row]][0]) / meanSdY[indices[row]][1]; } // debug("/tmp/dispersion", arrToStr(geneLabels, dispersionScaled)); // System.out.println("Looking for variable genes"); // OK, now we have means and dispersion calculated on a per/bin basis // For each row, see if it passes our cutoffs // BitSet bits = new BitSet(cols); for (int row = 0; row < rows; row++) { if ((means[row] > xLowCutoff && means[row] < xHighCutoff) && dispersionScaled[row] > yCutoff) bits.set(row); } double[][] newMat = new double[bits.cardinality()][cols]; int newRow = 0; for (int row = 0; row < rows; row++) { if (bits.get(row)) { for (int col = 0; col < cols; col++) { newMat[newRow][col] = matrix[row][col]; } newRow++; } } return newMat; } /** * Return the bins to equally cut the range of values * into. Returns bins+1 values to get the starting and * ending bins; */ static double[] cut(double[] values, int bins) { double minValue = Double.MAX_VALUE; double maxValue = Double.MIN_VALUE; for (double v: values) { if (v < minValue) minValue = v; if (v > maxValue) maxValue = v; } double range = maxValue - minValue; double steps = range/bins; double[] b = new double[bins+1]; b[0] = minValue - range*.001; for (int i = 1; i <= bins; i++) { b[i] = minValue+i*steps; } return b; } /** * Assign values to a bin. */ static int[] indexBins(double[] values, double[] bins, int[] binCount) { int [] indices = new int[values.length]; for (int i = 0; i < values.length; i++) { for (int b = 0; b < bins.length-1; b++) { if (values[i] <= bins[b+1] && values[i] > bins[b]) { indices[i] = b; binCount[b]++; break; } } } return indices; } /** * Simplistic version of the R tapply function. Applies the proscribed * method to all of the values within the bin */ static double[][] tapply(double[] data, int[] bins, int[] binCount, int nBins) { double[][] binnedResults = new double[nBins][2]; // Calculate the means for (int d = 0; d < data.length; d++) { // if d is NaN, continue if (Double.isInfinite(data[d]) || Double.isNaN(data[d])) continue; binnedResults[bins[d]][0] += data[d]/binCount[bins[d]]; } for (int d = 0; d < data.length; d++) { if (Double.isInfinite(data[d]) || Double.isNaN(data[d])) continue; binnedResults[bins[d]][1] += Math.pow(data[d]-binnedResults[bins[d]][0], 2)/(binCount[bins[d]]-1); } for (int b = 0; b < nBins; b++) { binnedResults[b][1] = Math.sqrt(binnedResults[b][1]); } /* for (int b = 0; b < nBins; b++) { System.out.println("Mean["+b+"] = "+binnedResults[b][0]); System.out.println("Sd["+b+"] = "+binnedResults[b][1]); } */ return binnedResults; } /** * Generate random draw from Normal with mean mu and std. dev sigma * @param mu * @param sigma * @return random sample */ public static double rnorm(double mu, double sigma) { return mu + (ThreadLocalRandom.current().nextGaussian() * sigma); } // Unit Tested /** * Returns a new matrix of booleans where true is set if the values to the two matrices are * the same at that index * @param matrix1 * @param matrix2 * @return new matrix with booelans with values matrix1[i,j] == matrix2[i,j] */ public static boolean [][] equal(double [][] matrix1, double [][] matrix2) { boolean [][] equals = new boolean[matrix1.length][matrix1[0].length]; if( matrix1.length != matrix2.length) { throw new IllegalArgumentException("Dimensions does not match"); } if( matrix1[0].length != matrix2[0].length) { throw new IllegalArgumentException("Dimensions does not match"); } for (int i = 0; i < matrix1.length; i++) { for (int j = 0; j < matrix1[0].length; j++) { equals[i][j] = Double.compare(matrix1[i][j], matrix2[i][j]) == 0; } } return equals; } /** * Returns a new matrix of booleans where true is set if the values to the two matrices are * the same at that index * @param matrix1 * @param matrix2 * @return new matrix with booelans with values matrix1[i,j] == matrix2[i,j] */ public static boolean [][] equal(boolean [][] matrix1, boolean [][] matrix2) { boolean [][] equals = new boolean[matrix1.length][matrix1[0].length]; if( matrix1.length != matrix2.length) { throw new IllegalArgumentException("Dimensions does not match"); } if( matrix1[0].length != matrix2[0].length) { throw new IllegalArgumentException("Dimensions does not match"); } for (int i = 0; i < matrix1.length; i++) { for (int j = 0; j < matrix1[0].length; j++) { equals[i][j] = (matrix1[i][j] == matrix2[i][j]); } } return equals; } /** * Returns a new matrix of booleans where true is set if the value in the matrix is * bigger than value * @param matrix * @param value * @return new matrix with booelans with values matrix1[i,j] == matrix2[i,j] */ public static boolean [][] biggerThan(double [][] matrix, double value) { boolean [][] equals = new boolean[matrix.length][matrix[0].length]; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { equals[i][j] = Double.compare(matrix[i][j], value) == 1; } } return equals; } /** * @param booleans * @return new matrix with booleans which are the negations of the input */ public static boolean [][] negate(boolean [][] booleans) { boolean [][] negates = new boolean[booleans.length][booleans[0].length]; for (int i = 0; i < booleans.length; i++) { for (int j = 0; j < booleans[0].length; j++) { negates[i][j] = !booleans[i][j]; } } return negates; } /** * @param booleans * @return */ public static double [][] abs(boolean [][] booleans) { double [][] absolutes = new double[booleans.length][booleans[0].length]; for (int i = 0; i < booleans.length; i++) { for (int j = 0; j < booleans[0].length; j++) { absolutes[i][j] = booleans[i][j] ? 1 : 0; } } return absolutes; } /** * @param vals * @return */ public static double [][] abs(double [][] vals) { double [][] absolutes = new double[vals.length][vals[0].length]; for (int i = 0; i < vals.length; i++) { for (int j = 0; j < vals[0].length; j++) { absolutes[i][j] = Math.abs(vals[i][j]); } } return absolutes; } /** * @param absolutes * @return */ public static double [] abs(double [] vals) { double [] absolutes = new double[vals.length]; for (int i = 0; i < vals.length; i++) { absolutes[i] = Math.abs(vals[i]); } return absolutes; } public static double [][] sign(double [][] matrix) { double [][] signs = new double[matrix.length][matrix[0].length]; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { signs[i][j] = matrix[i][j] >= 0 ? 1 : -1; } } return signs; } public static double mean(double [][] matrix) { return mean(matrix,2)[0][0]; } // Unit Tested public static double [][] mean(double [][] matrix, int axis) { // Axis = 0 => sum columns // Axis = 1 => sum rows // Axis = 2 => global (returns a 1 element array with the result) double [][] result; if( axis == 0) { result = new double[1][matrix[0].length]; for (int j = 0; j < matrix[0].length; j++) { double colsum = 0.0; for (int i = 0; i < matrix.length; i++) { colsum += matrix[i][j]; } result[0][j] = colsum / matrix.length; } } else if (axis == 1) { result = new double[matrix.length][1]; for (int i = 0; i < matrix.length; i++) { double rowsum = 0.0; for (int j = 0; j < matrix[0].length; j++) { rowsum += matrix[i][j]; } result[i][0] = rowsum / matrix[0].length; } } else if (axis == 2) { result = new double[1][1]; for (int j = 0; j < matrix[0].length; j++) { for (int i = 0; i < matrix.length; i++) { result[0][0] += matrix[i][j]; } } result[0][0] /= (matrix[0].length * matrix.length); }else { throw new IllegalArgumentException("Axes other than 0,1,2 is unsupported"); } return result; } // Unit Tested // Should be called dim-sum! :) public static double [][] sum(double [][] matrix, int axis) { // Axis = 0 => sum columns // Axis = 1 => sum rows double [][] result; if( axis == 0) { result = new double[1][matrix[0].length]; for (int j = 0; j < matrix[0].length; j++) { double rowsum = 0.0; for (int i = 0; i < matrix.length; i++) { rowsum += matrix[i][j]; } result[0][j] = rowsum; } } else if (axis == 1) { result = new double[matrix.length][1]; for (int i = 0; i < matrix.length; i++) { double colsum = 0.0; for (int j = 0; j < matrix[0].length; j++) { colsum += matrix[i][j]; } result[i][0] = colsum; } } else { throw new IllegalArgumentException("Axes other than 0,1 is unsupported"); } return result; } // Unit Tested /** * Returns a new matrix which is the transpose of input matrix * @param matrix * @return */ public double sumPar(double[][] matrix) { int ll = 100; int cols = matrix[0].length; int rows = matrix.length; double [] sums = new double[rows]; if(rows < ll ) { for (int row = 0; row < rows; row++) for (int col = 0; col < cols; col++) sums[row] += matrix[row][col]; } else { MatrixSummer process = new MatrixSummer(matrix, sums, 0, rows, ll); pool.invoke(process); } double sum = 0.0; for (int i = 0; i < sums.length; i++) { sum += sums[i]; } return sum; } class MatrixSummer extends RecursiveAction { private static final long serialVersionUID = 1L; double [][] orig; double [] sums; int startRow = -1; int endRow = -1; int limit = 1000; public MatrixSummer(double [][] orig, double [] sums, int startRow, int endRow, int ll) { this.limit = ll; this.orig = orig; this.sums = sums; this.startRow = startRow; this.endRow = endRow; } public MatrixSummer(double [][] orig, double [] transpose, int startRow, int endRow) { this.orig = orig; this.sums = transpose; this.startRow = startRow; this.endRow = endRow; } @Override protected void compute() { try { if ( (endRow-startRow) <= limit ) { int cols = orig[0].length; for (int row = startRow; row < endRow; row++) { for (int i = 0; i < cols; i++) { sums[row] += orig[row][i]; } } } else { int range = (endRow-startRow); int startRow1 = startRow; int endRow1 = startRow + (range / 2); int startRow2 = endRow1; int endRow2 = endRow; invokeAll(new MatrixSummer(orig, sums, startRow1, endRow1, limit), new MatrixSummer(orig, sums, startRow2, endRow2, limit)); } } catch ( Exception e ) { e.printStackTrace(); } } } // Unit Tested /** * @param matrix * @return sum of all values in the matrix */ public static double sum(double [][] matrix) { double sum = 0.0; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { sum+=matrix[i][j]; } } return sum; } public static double sum(double [] vector) { double res = 0.0; for (int i = 0; i < vector.length; i++) { res += vector[i]; } return res; } /** * Return a new matrix with the max value of either the value in the matrix * or maxval otherwise * @param matrix * @param maxval * @return */ public static double [][] maximum(double [][] matrix, double maxval) { double [][] maxed = new double[matrix.length][matrix[0].length]; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { maxed[i][j] = matrix[i][j] > maxval ? matrix[i][j] : maxval; } } return maxed; } // Unit Tested /** * All values in matrix that is less than <code>lessthan</code> is assigned * the value <code>assign</code> * @param matrix * @param lessthan * @param assign * @return */ public static void assignAllLessThan(double[][] matrix, double lessthan, double assign) { for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { if( matrix[i][j] < lessthan) { matrix[i][j] = assign; } } } } // Unit Tested /** * @param matrix * @return a new matrix with the values of matrix squared */ public static double [][] square(double [][] matrix) { return scalarPow(matrix,2); } /** * Replaces NaN's with repl * @param matrix * @param repl * @return */ public static double [][] replaceNaN(double [][] matrix, double repl) { double [][] result = new double[matrix.length][matrix[0].length]; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { if(Double.isNaN(matrix[i][j])) { result[i][j] = repl; } else { result[i][j] = matrix[i][j]; } } } return result; } /** * Replaces Infinity's with repl * @param matrix * @param repl * @return */ public static double [][] replaceInf(double [][] matrix, double repl) { double [][] result = new double[matrix.length][matrix[0].length]; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { if(Double.isInfinite(matrix[i][j])) { result[i][j] = repl; } else { result[i][j] = matrix[i][j]; } } } return result; } public static double [][] scalarPow(double [][] matrix, double power) { double [][] result = new double[matrix.length][matrix[0].length]; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { result[i][j] += Math.pow(matrix[i][j],power); } } return result; } public static double [][] addColumnVector(double [][] matrix, double [][] colvector) { double [][] result = new double[matrix.length][matrix[0].length]; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { result[i][j] = matrix[i][j] + colvector[i][0]; } } return result; } public static double [][] addRowVector(double [][] matrix, double [][] rowvector) { double [][] result = new double[matrix.length][matrix[0].length]; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { result[i][j] = matrix[i][j] + rowvector[0][j]; } } return result; } public static double [][] fillWithRowOld(double [][] matrix, int row) { double [][] result = new double[matrix.length][matrix[0].length]; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { result[i][j] = matrix[row][j]; } } return result; } public static double [][] fillWithRow(double [][] matrix, int row) { int rows = matrix.length; int cols = matrix[0].length; double [][] result = new double[rows][cols]; for (int i = 0; i < rows; i++) { System.arraycopy(matrix[row], 0, result[i], 0, cols); } return result; } // Unit Tested public static double [][] tile(double [][] matrix, int rowtimes, int coltimes) { double [][] result = new double[matrix.length*rowtimes][matrix[0].length*coltimes]; for (int i = 0, resultrow = 0; i < rowtimes; i++) { for (int j = 0; j < matrix.length; j++) { for (int k = 0, resultcol = 0; k < coltimes; k++) { for (int l = 0; l < matrix[0].length; l++) { result[resultrow][resultcol++] = matrix[j][l]; } } resultrow++; } } return result; } public static double[][] normalize(double[][] x, double[] meanX, double[] stdevX) { double[][] y = new double[x.length][x[0].length]; for (int i = 0; i < y.length; i++) for (int j = 0; j < y[i].length; j++) y[i][j] = (x[i][j] - meanX[j]) / stdevX[j]; return y; } public static int [] range(int n) { int [] result = new int[n]; for (int i = 0; i < n; i++) { result[i] = i; } return result; } public static int [] range(int a, int b) { if( b < a ) { throw new IllegalArgumentException("b has to be larger than a"); } int val = a; int [] result = new int[b-a]; for (int i = 0; i < (b-a); i++) { result[i] = val++; } return result; } // Unit Tested public static int [] concatenate(int [] v1,int [] v2) { int [] result = new int[v1.length+v2.length]; int index = 0; for (int i = 0; i < v1.length; i++, index++) { result[index] = v1[index]; } for (int i = 0; i < v2.length; i++, index++) { result[index] = v2[i]; } return result; } // Unit Tested public static double [] concatenate(double [] v1,double [] v2) { double [] result = new double[v1.length+v2.length]; int index = 0; for (int i = 0; i < v1.length; i++, index++) { result[index] = v1[index]; } for (int i = 0; i < v2.length; i++, index++) { result[index] = v2[i]; } return result; } // Unit Tested public static double [][] concatenate(double [][] m1,double[][] m2) { if(m1.length!=m2.length) throw new IllegalArgumentException("m1 and m2 must have the same number of rows:" + m1.length + " != " + m2.length); double [][] result = new double[m1.length][m1[0].length+m2[0].length]; int resCol = 0; for (int i = 0; i < m1.length; i++) { resCol = 0; for (int j = 0; j < m1[i].length; j++) { result[i][resCol++] = m1[i][j]; } for (int j = 0; j < m2[i].length; j++) { result[i][resCol++] = m2[i][j]; } } return result; } // Unit Tested public static double [][] concatenate(double [][] m1,double[] v2) { if(m1.length!=v2.length) throw new IllegalArgumentException("m1 and v2 must have the same number of rows:" + m1.length + " != " + v2.length); double [][] result = new double[m1.length][m1[0].length+1]; int resCol = 0; for (int i = 0; i < m1.length; i++) { resCol = 0; for (int j = 0; j < m1[i].length; j++) { result[i][resCol++] = m1[i][j]; } result[i][resCol++] = v2[i]; } return result; } public double [][] scalarMultiply(double [][] m1,double [][] m2) { return parScalarMultiply(m1, m2); } // Unit Tested public static double [][] sMultiply(double [][] v1,double [][] v2) { if( v1.length != v2.length || v1[0].length != v2[0].length ) { throw new IllegalArgumentException("a and b has to be of equal dimensions"); } double [][] result = new double[v1.length][v1[0].length]; for (int i = 0; i < v1.length; i++) { for (int j = 0; j < v1[0].length; j++) { result[i][j] = v1[i][j] * v2[i][j]; } } return result; } public double[][] parScalarMultiply(double [][] m1,double [][] m2) { int ll = 600; double [][] result = new double[m1.length][m1[0].length]; MatrixOperator process = new MatrixOperator(m1,m2,result, multiplyop, 0, m1.length,ll); pool.invoke(process); return result; } public double[][] parScalarMinus(double [][] m1,double [][] m2) { int ll = 600; double [][] result = new double[m1.length][m1[0].length]; MatrixOperator process = new MatrixOperator(m1,m2,result, minusop, 0, m1.length,ll); pool.invoke(process); return result; } public interface MatrixOp { double compute(double op1, double op2); } MatrixOp multiplyop = new MatrixOp() { public double compute(double f1, double f2) { return f1 * f2; } }; MatrixOp minusop = new MatrixOp() { public double compute(double f1, double f2) { return f1 - f2; } }; class MatrixOperator extends RecursiveAction { final static long serialVersionUID = 1L; double [][] matrix1; double [][] matrix2; double [][] resultMatrix; int startRow = -1; int endRow = -1; int limit = 1000; MatrixOp op; public MatrixOperator(double [][] matrix1, double [][] matrix2, double [][] resultMatrix, MatrixOp op, int startRow, int endRow, int ll) { this.op = op; this.limit = ll; this.matrix1 = matrix1; this.matrix2 = matrix2; this.resultMatrix = resultMatrix; this.startRow = startRow; this.endRow = endRow; } @Override protected void compute() { try { if ( (endRow-startRow) <= limit ) { int cols = matrix1[0].length; for (int i = startRow; i < endRow; i++) { for (int j = 0; j < cols; j++) { resultMatrix[i][j] = op.compute(matrix1[i][j], matrix2[i][j]); } } } else { int range = (endRow-startRow); int startRow1 = startRow; int endRow1 = startRow + (range / 2); int startRow2 = endRow1; int endRow2 = endRow; invokeAll(new MatrixOperator(matrix1, matrix2, resultMatrix, op, startRow1, endRow1, limit), new MatrixOperator(matrix1, matrix2, resultMatrix, op, startRow2, endRow2, limit)); } } catch ( Exception e ) { e.printStackTrace(); } } } public static void assignAtIndex(double[][] num, int[] range, int[] range1, double value) { for (int j = 0; j < range.length; j++) { num[range[j]][range1[j]] = value; } } public static double [][] getValuesFromRow(double[][] matrix, int row, int[] indicies) { double [][] values = new double[1][indicies.length]; for (int j = 0; j < indicies.length; j++) { values[0][j] = matrix[row][indicies[j]]; } return values; } public static void assignValuesToRow(double[][] matrix, int row, int[] indicies, double [] values) { if( indicies.length != values.length ) { throw new IllegalArgumentException("Length of indicies and values have to be equal"); } for (int j = 0; j < indicies.length; j++) { matrix[row][indicies[j]] = values[j]; } } public static double stdev(double [][] matrix) { double m = mean(matrix); double total = 0; final int N = matrix.length * matrix[0].length; for( int i = 0; i < matrix.length; i++ ) { for (int j = 0; j < matrix[i].length; j++) { double x = matrix[i][j]; total += (x - m)*(x - m); } } return Math.sqrt(total / (N-1)); } public static double[] colStddev(double[][] v) { double[] var = variance(v); for (int i = 0; i < var.length; i++) var[i] = Math.sqrt(var[i]); return var; } public static double[] rowStddev(double[][] v) { double[] var = rowVariance(v); for (int i = 0; i < var.length; i++) var[i] = Math.sqrt(var[i]); return var; } public static double[] rowVariance(double[][] v) { int rows = v.length; int cols = v[0].length; double[] var = new double[rows]; int degrees = (cols - 1); double c; double s; for (int row = 0; row < rows; row++) { c = 0; s = 0; for (int col = 0; col < cols; col++) s += v[row][col]; s = s / cols; for (int col = 0; col < cols; col++) c += (v[row][col] - s) * (v[row][col] - s); var[row] = c / degrees; } return var; } public static double[] variance(double[][] v) { int m = v.length; int n = v[0].length; double[] var = new double[n]; int degrees = (m - 1); double c; double s; for (int j = 0; j < n; j++) { c = 0; s = 0; for (int k = 0; k < m; k++) s += v[k][j]; s = s / m; for (int k = 0; k < m; k++) c += (v[k][j] - s) * (v[k][j] - s); var[j] = c / degrees; } return var; } /** * @param matrix * @return a new vector with the column means of matrix */ public static double[] rowMeans(double[][] matrix) { int rows = matrix.length; int cols = matrix[0].length; double[] mean = new double[rows]; for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) mean[i] += matrix[i][j]; for (int i = 0; i < rows; i++) mean[i] /= (double) cols; return mean; } /** * @param matrix * @return a new vector with the column means of matrix */ public static double[] colMeans(double[][] matrix) { int rows = matrix.length; int cols = matrix[0].length; double[] mean = new double[cols]; for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) mean[j] += matrix[i][j]; for (int j = 0; j < cols; j++) mean[j] /= (double) rows; return mean; } public static double[][] copyRows(double[][] input, int... indices) { double[][] matrix = new double[indices.length][input[0].length]; for (int i = 0; i < indices.length; i++) System.arraycopy(input[indices[i]], 0, matrix[i], 0, input[indices[i]].length); return matrix; } public static double[][] copyCols(double[][] input, int... indices) { double[][] matrix = new double[indices.length][input.length]; for (int i = 0; i < indices.length; i++) for (int j = 0; j < input.length; j++) { matrix[i][j] = input[j][indices[i]]; } return matrix; } public static double[][] fillMatrix(int rows, int cols, double fillvalue) { double[][] matrix = new double[rows][cols]; for (int i = 0; i < matrix.length; i++) for (int j = 0; j < matrix[i].length; j++) matrix[i][j] = fillvalue; return matrix; } public static double[][] plus(double[][] m1, double[][] m2) { double[][] matrix = new double[m1.length][m1[0].length]; for (int i = 0; i < m1.length; i++) for (int j = 0; j < m1[0].length; j++) matrix[i][j] = m1[i][j] + m2[i][j]; return matrix; } // Unit Tested public static double[][] scalarPlus(double[][] m1, double m2) { double[][] matrix = new double[m1.length][m1[0].length]; for (int i = 0; i < m1.length; i++) for (int j = 0; j < m1[0].length; j++) matrix[i][j] = m1[i][j] + m2; return matrix; } // Unit Tested public static double [] scalarPlus(double[] m1, double m2) { double[] matrix = new double[m1.length]; for (int i = 0; i < m1.length; i++) matrix[i] = m1[i] + m2; return matrix; } public double[][] minus(double[][] m1, double[][] m2) { return parScalarMinus(m1, m2); } // Unit Tested public static double[][] sMinus(double[][] m1, double[][] m2) { double[][] matrix = new double[m1.length][m1[0].length]; for (int i = 0; i < m1.length; i++) for (int j = 0; j < m1[0].length; j++) matrix[i][j] = m1[i][j] - m2[i][j]; return matrix; } // Unit Tested public static double[][] scalarDivide(double[][] numerator, double denom) { double[][] matrix = new double[numerator.length][numerator[0].length]; for (int i = 0; i < numerator.length; i++) for (int j = 0; j < numerator[i].length; j++) matrix[i][j] = numerator[i][j] / denom; return matrix; } // Unit Tested public static double [] scalarDivide(double numerator, double[] denom) { double[] vector = new double[denom.length]; for (int i = 0; i < denom.length; i++) vector[i] = numerator / denom[i] ; return vector; } // Unit Tested public static double [] scalarDivide(double[] numerator, double denom) { double[] vector = new double[numerator.length]; for (int i = 0; i < numerator.length; i++) vector[i] = numerator[i] / denom; return vector; } // Unit Tested public static double [] scalarDivide(double [] numerator, double[] denom) { double[] vector = new double[denom.length]; for (int i = 0; i < denom.length; i++) vector[i] = numerator[i] / denom[i] ; return vector; } // Unit Tested public static double[][] scalarDivide(double[][] numerator, double[][] denom) { double[][] matrix = new double[numerator.length][numerator[0].length]; for (int i = 0; i < numerator.length; i++) for (int j = 0; j < numerator[i].length; j++) matrix[i][j] = numerator[i][j] / denom[i][j]; return matrix; } // Unit Tested public static double[][] scalarMult(double[][] m1, double mul) { double[][] matrix = new double[m1.length][m1[0].length]; for (int i = 0; i < m1.length; i++) for (int j = 0; j < m1[i].length; j++) matrix[i][j] = m1[i][j] * mul; return matrix; } // Unit Tested public static double[][] times(double[][] m1, double[][] m2) { Matrix A = Matrix.constructWithCopy(m1); Matrix B = Matrix.constructWithCopy(m2); return A.times(B).getArray(); } public static double [] scalarMultiply(double[] m1, double mul) { double[] matrix = new double[m1.length]; for (int i = 0; i < m1.length; i++) matrix[i] = m1[i] * mul; return matrix; } public static double [] scalarMultiply(double[] m1, double [] m2) { double[] matrix = new double[m1.length]; for (int i = 0; i < m1.length; i++) matrix[i] = m1[i] * m2[i]; return matrix; } public static double[][] diag(double[][] ds) { boolean isLong = ds.length > ds[0].length; int dim = Math.max(ds.length,ds[0].length); double [][] result = new double [dim][dim]; for (int i = 0; i < result.length; i++) { for (int j = 0; j < result.length; j++) { if(i==j) { if(isLong) result[i][j] = ds[i][0]; else result[i][j] = ds[0][i]; } } } return result; } public static double [][] dot(double [][] a, double [][] b) { if(a[0].length!=b.length) throw new IllegalArgumentException("Dims does not match: " + a[0].length + "!=" + b.length); double [][] res = new double[a.length][b[0].length]; for (int row = 0; row < a.length; row++) { for (int col = 0; col < b[row].length; col++) { for (int i = 0; i < a[0].length; i++) { res[row][col] = a[row][i] * b[i][col]; } } } return res; } public static double dot(double [] a, double [] b) { if(a.length!=b.length) { throw new IllegalArgumentException("Vectors are not of equal length"); } double res = 0.0; for (int i = 0; i < b.length; i++) { res += a[i] * b[i]; } return res; } public static double dot2P1(double [] a1, double [] a2, double [] b) { if((a1.length+a2.length)!=b.length) { throw new IllegalArgumentException("Vectors are not of equal length"); } double res = 0.0; int bidx = 0; for (int i = 0; i < a1.length; i++, bidx++) { res += a1[i] * b[bidx]; } for (int i = 0; i < a2.length; i++, bidx++) { res += a2[i] * b[bidx]; } return res; } public static int maxIdx(double[] probs) { int maxIdx = 0; double max = probs[maxIdx]; for (int i = 0; i < probs.length; i++) { if(probs[i]>max) { max = probs[i]; maxIdx = i; } } return maxIdx; } public static double[][] extractCol(int col, double[][] matrix) { double [][] res = new double[matrix.length][1]; for (int row = 0; row < matrix.length; row++) { res[row][0] = matrix[row][col]; } return res; } public static double[] extractColVector(int col, double[][] matrix) { double [] res = new double[matrix.length]; for (int row = 0; row < matrix.length; row++) { res[row] = matrix[row][col]; } return res; } public static double [][] extractDoubleArray(DMatrixRMaj p) { int rows = p.getNumRows(); int cols = p.getNumCols(); double [][] result = new double[rows][cols]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { result[i][j] = p.get(i, j); } } return result; } public static double [] extractDoubleVector(DMatrixRMaj p) { int rows = p.getNumRows(); int cols = p.getNumCols(); if(rows != 1 && cols != 1) { throw new IllegalArgumentException("Cannot convert a " + rows + "x" + cols + " matrix to a vector"); } double [] result; if(cols == 1) { result = new double[rows]; for (int j = 0; j < rows; j++) { result[j] = p.get(j,0); } } else { result = new double[cols]; for (int j = 0; j < cols; j++) { result[j] = p.get(0,j); } } return result; } public static double[][] extractRowCols(int col, double[][] zs2, int[] cJIdxs) { double [][] res = new double[cJIdxs.length][1]; for (int row = 0; row < cJIdxs.length; row++) { res[row][0] = zs2[cJIdxs[row]][col]; } return res; } public static Integer [] indicesOf(int classIdx, int [] ys) { List<Integer> indices = new ArrayList<>(); for (int row = 0; row < ys.length; row++) { if(ys[row]==classIdx) { indices.add(row); } } return indices.toArray(new Integer[0]); } public static double[][] makeDesignMatrix(double[][] xstmp) { double [][] xs = new double[xstmp.length][xstmp[0].length+1]; for (int row = 0; row < xs.length; row++) { for (int col = 0; col < xs[0].length; col++) { if(col==0) { xs[row][col] = 1.0; } else { xs[row][col] = xstmp[row][col-1]; } } } return xs; } public static double[][] addIntercept(double[][] xs) { double [][] result = new double [xs.length][xs[0].length+1]; for (int i = 0; i < result.length; i++) { for (int j = 0; j < result[0].length; j++) { if(j==0) { result[i][j] = 1.0; } else { result[i][j] = xs[i][j-1]; } } } return result; } public static double[] toPrimitive(Double[] ds) { double [] result = new double[ds.length]; for (int i = 0; i < ds.length; i++) { result[i] = ds[i]; } return result; } public static double [] extractRowFromFlatMatrix(double[] flatMatrix, int rowIdx, int dimension) { double [] point = new double[dimension]; int offset = rowIdx * dimension; for (int j = 0; j < dimension; j++) { point[j] = flatMatrix[offset+j]; } return point; } public static void debug(String file, String message) { try { FileOutputStream out = new FileOutputStream(file); out.write(message.getBytes()); out.close(); } catch (Exception e) { e.printStackTrace(); } } }
3e1b25e611ac5c89696871c12ce54b469addfe36
1,617
java
Java
src/main/java/sorald/Constants.java
fermadeiral/sonarqube-repair
ad227d5535816c0c7e9b7e49e94907d02570f5c9
[ "MIT" ]
null
null
null
src/main/java/sorald/Constants.java
fermadeiral/sonarqube-repair
ad227d5535816c0c7e9b7e49e94907d02570f5c9
[ "MIT" ]
null
null
null
src/main/java/sorald/Constants.java
fermadeiral/sonarqube-repair
ad227d5535816c0c7e9b7e49e94907d02570f5c9
[ "MIT" ]
null
null
null
39.439024
91
0.786642
11,494
package sorald; import java.io.File; public class Constants { public static final String ARG_SYMBOL = "--"; public static final String ARG_RULE_KEYS = "ruleKeys"; public static final String ARG_ORIGINAL_FILES_PATH = "originalFilesPath"; public static final String ARG_WORKSPACE = "workspace"; public static final String ARG_GIT_REPO_PATH = "gitRepoPath"; public static final String ARG_PRETTY_PRINTING_STRATEGY = "prettyPrintingStrategy"; public static final String ARG_FILE_OUTPUT_STRATEGY = "fileOutputStrategy"; public static final String ARG_MAX_FIXES_PER_RULE = "maxFixesPerRule"; public static final String PROCESSOR_PACKAGE = "sorald.processor"; public static final String SORALD_WORKSPACE = "sorald-workspace"; public static final String PATCHES = "SoraldGitPatches"; public static final String PATCH_FILE_PREFIX = "soraldpatch_"; public static final String PATH_TO_RESOURCES_FOLDER = "./src/test/resources/"; public static final String JAVA_EXT = ".java"; public static final String PATCH_EXT = ".patch"; public static final String SPOONED = "spooned"; public static final String INTERMEDIATE = "intermediate"; public static final String SPOONED_INTERMEDIATE = SPOONED + File.separator + INTERMEDIATE; public static final String INT = "int"; public static final String LONG = "long"; public static final String FLOAT = "float"; public static final String DOUBLE = "double"; public static final String STRING_QUALIFIED_NAME = "java.lang.String"; public static final String TOSTRING_METHOD_NAME = "toString"; public static final String HASHCODE_METHOD_NAME = "hashCode"; }
3e1b25e9a97983350cf5626336d4fc6cfc15c492
688
java
Java
app_gomocart/src/main/java/gomocart/application/com/model/grosir.java
rifkihp/kamon_app_for_customers
1ff7d6ed24b291669fc4d95a1129f8cb38ab549c
[ "MIT" ]
null
null
null
app_gomocart/src/main/java/gomocart/application/com/model/grosir.java
rifkihp/kamon_app_for_customers
1ff7d6ed24b291669fc4d95a1129f8cb38ab549c
[ "MIT" ]
null
null
null
app_gomocart/src/main/java/gomocart/application/com/model/grosir.java
rifkihp/kamon_app_for_customers
1ff7d6ed24b291669fc4d95a1129f8cb38ab549c
[ "MIT" ]
null
null
null
17.2
52
0.655523
11,495
package gomocart.application.com.model; import com.google.gson.annotations.SerializedName; import java.io.Serializable; public class grosir implements Serializable { private static final long serialVersionUID = 1L; @SerializedName("id") int id; @SerializedName("jumlah_min") int jumlah_min; @SerializedName("jumlah_max") int jumlah_max; @SerializedName("harga") double harga; public int getId() { return this.id; } public int getJumlah_min() { return this.jumlah_min; } public int getJumlah_max() { return this.jumlah_max; } public double getHarga() { return this.harga; } }
3e1b2617a9453c1bcb84a98a91908f38c1f40879
2,167
java
Java
src/main/java/com/microsoft/graph/requests/extensions/IdentityProviderCollectionWithReferencesPage.java
sbh04101989/msgraph-beta-sdk-java
c1de187b73396aa422fcfe3afc493acb92f6260c
[ "MIT" ]
null
null
null
src/main/java/com/microsoft/graph/requests/extensions/IdentityProviderCollectionWithReferencesPage.java
sbh04101989/msgraph-beta-sdk-java
c1de187b73396aa422fcfe3afc493acb92f6260c
[ "MIT" ]
null
null
null
src/main/java/com/microsoft/graph/requests/extensions/IdentityProviderCollectionWithReferencesPage.java
sbh04101989/msgraph-beta-sdk-java
c1de187b73396aa422fcfe3afc493acb92f6260c
[ "MIT" ]
null
null
null
51.595238
218
0.771112
11,496
// Template Source: BaseEntityCollectionWithReferencesPage.java.tt // ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.requests.extensions; import com.microsoft.graph.http.IRequestBuilder; import com.microsoft.graph.core.ClientException; import com.microsoft.graph.concurrency.ICallback; import com.microsoft.graph.models.extensions.B2xIdentityUserFlow; import com.microsoft.graph.models.extensions.IdentityProvider; import java.util.Arrays; import java.util.EnumSet; import com.microsoft.graph.requests.extensions.IIdentityProviderCollectionWithReferencesRequestBuilder; import com.microsoft.graph.requests.extensions.IIdentityProviderCollectionWithReferencesPage; import com.microsoft.graph.requests.extensions.IdentityProviderCollectionResponse; import com.microsoft.graph.models.extensions.IdentityProvider; import com.google.gson.JsonObject; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import com.microsoft.graph.http.BaseCollectionPage; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The class for the Identity Provider Collection With References Page. */ public class IdentityProviderCollectionWithReferencesPage extends BaseCollectionPage<IdentityProvider, IIdentityProviderCollectionWithReferencesRequestBuilder> implements IIdentityProviderCollectionWithReferencesPage { /** * A collection page for IdentityProvider * * @param response the serialized IdentityProviderCollectionResponse from the service * @param builder the request builder for the next collection page */ public IdentityProviderCollectionWithReferencesPage(final IdentityProviderCollectionResponse response, final IIdentityProviderCollectionWithReferencesRequestBuilder builder) { super(response.value, builder, response.additionalDataManager()); } }
3e1b26269503a0ccb4e4c40e6b7002cc88fcf806
978
java
Java
de.raphaelmuesseler.financer.client.javafx/src/main/java/de/raphaelmuesseler/financer/client/javafx/dialogs/FinancerConfirmDialog.java
hmallel/financer
101b9f24c81afd1610ed112d165e3b1dc5efa488
[ "BSD-3-Clause" ]
null
null
null
de.raphaelmuesseler.financer.client.javafx/src/main/java/de/raphaelmuesseler/financer/client/javafx/dialogs/FinancerConfirmDialog.java
hmallel/financer
101b9f24c81afd1610ed112d165e3b1dc5efa488
[ "BSD-3-Clause" ]
null
null
null
de.raphaelmuesseler.financer.client.javafx/src/main/java/de/raphaelmuesseler/financer/client/javafx/dialogs/FinancerConfirmDialog.java
hmallel/financer
101b9f24c81afd1610ed112d165e3b1dc5efa488
[ "BSD-3-Clause" ]
1
2019-12-07T21:09:31.000Z
2019-12-07T21:09:31.000Z
21.733333
68
0.658487
11,497
package de.raphaelmuesseler.financer.client.javafx.dialogs; import javafx.scene.control.Label; import javafx.scene.layout.Region; public class FinancerConfirmDialog extends FinancerDialog<Boolean> { private Label questionLabel; private String question; public FinancerConfirmDialog(String question) { super(false); this.question = question; this.prepareDialogContent(); } @Override protected Region getDialogContent() { this.questionLabel = new Label(); return this.questionLabel; } @Override protected void prepareDialogContent() { this.questionLabel.setText(this.question); } @Override protected boolean checkConsistency() { return true; } @Override protected void onConfirm() { this.setValue(true); super.onConfirm(); } @Override protected void onCancel() { this.setValue(false); super.onCancel(); } }
3e1b27cbb752810113381fdd66172f6ed5391b1b
1,306
java
Java
src/main/java/org/slf4j/impl/StaticLoggerBinder.java
aws-greengrass/aws-greengrass-logging-java
97ba7c54a18d4755eaa07a2c81d447491ca4de11
[ "Apache-2.0" ]
2
2020-12-15T18:24:40.000Z
2021-06-15T13:59:47.000Z
src/main/java/org/slf4j/impl/StaticLoggerBinder.java
aws-greengrass/aws-greengrass-logging-java
97ba7c54a18d4755eaa07a2c81d447491ca4de11
[ "Apache-2.0" ]
12
2021-01-21T19:37:12.000Z
2022-03-25T20:36:45.000Z
src/main/java/org/slf4j/impl/StaticLoggerBinder.java
aws-greengrass/aws-greengrass-logging-java
97ba7c54a18d4755eaa07a2c81d447491ca4de11
[ "Apache-2.0" ]
null
null
null
30.372093
114
0.745023
11,498
/* * Copyright Amazon.com Inc. or its affiliates. * SPDX-License-Identifier: Apache-2.0 */ package org.slf4j.impl; import com.aws.greengrass.logging.impl.Slf4jFactory; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.slf4j.ILoggerFactory; import org.slf4j.LoggerFactory; import org.slf4j.spi.LoggerFactoryBinder; /** * The binding of {@link LoggerFactory} class with an actual instance of {@link ILoggerFactory} is performed using * information returned by this class. * * <p>Modified from Logback's implementation */ @SuppressFBWarnings({"MS_SHOULD_BE_FINAL", "URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD"}) public class StaticLoggerBinder implements LoggerFactoryBinder { private static final StaticLoggerBinder INSTANCE = new StaticLoggerBinder(); private static final Slf4jFactory factory = new Slf4jFactory(); // to avoid constant folding by the compiler, this field must *not* be final public static String REQUESTED_API_VERSION = "1.7.16"; // !final private StaticLoggerBinder() { } public static StaticLoggerBinder getSingleton() { return INSTANCE; } public ILoggerFactory getLoggerFactory() { return factory; } public String getLoggerFactoryClassStr() { return factory.getClass().getName(); } }
3e1b2809f3b241dede3b8de432e38eb800f06f6b
5,421
java
Java
arrow/src/gen/java/org/bytedeco/arrow/AssumeTimezoneOptions.java
dministro/javacpp-presets
8e8542b0034974483caab0f73f300293a1316c1a
[ "Apache-2.0" ]
1
2022-02-10T13:03:41.000Z
2022-02-10T13:03:41.000Z
arrow/src/gen/java/org/bytedeco/arrow/AssumeTimezoneOptions.java
dministro/javacpp-presets
8e8542b0034974483caab0f73f300293a1316c1a
[ "Apache-2.0" ]
null
null
null
arrow/src/gen/java/org/bytedeco/arrow/AssumeTimezoneOptions.java
dministro/javacpp-presets
8e8542b0034974483caab0f73f300293a1316c1a
[ "Apache-2.0" ]
null
null
null
60.233333
242
0.716104
11,499
// Targeted by JavaCPP version 1.5.7-SNAPSHOT: DO NOT EDIT THIS FILE package org.bytedeco.arrow; import org.bytedeco.arrow.Function; import java.nio.*; import org.bytedeco.javacpp.*; import org.bytedeco.javacpp.annotation.*; import static org.bytedeco.javacpp.presets.javacpp.*; import static org.bytedeco.arrow.global.arrow.*; /** Used to control timestamp timezone conversion and handling ambiguous/nonexistent * times. */ @Namespace("arrow::compute") @NoOffset @Properties(inherit = org.bytedeco.arrow.presets.arrow.class) public class AssumeTimezoneOptions extends FunctionOptions { static { Loader.load(); } /** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */ public AssumeTimezoneOptions(Pointer p) { super(p); } /** Native array allocator. Access with {@link Pointer#position(long)}. */ public AssumeTimezoneOptions(long size) { super((Pointer)null); allocateArray(size); } private native void allocateArray(long size); @Override public AssumeTimezoneOptions position(long position) { return (AssumeTimezoneOptions)super.position(position); } @Override public AssumeTimezoneOptions getPointer(long i) { return new AssumeTimezoneOptions((Pointer)this).offsetAddress(i); } /** \brief How to interpret ambiguous local times that can be interpreted as * multiple instants (normally two) due to DST shifts. * * AMBIGUOUS_EARLIEST emits the earliest instant amongst possible interpretations. * AMBIGUOUS_LATEST emits the latest instant amongst possible interpretations. */ public enum Ambiguous { AMBIGUOUS_RAISE(0), AMBIGUOUS_EARLIEST(1), AMBIGUOUS_LATEST(2); public final int value; private Ambiguous(int v) { this.value = v; } private Ambiguous(Ambiguous e) { this.value = e.value; } public Ambiguous intern() { for (Ambiguous e : values()) if (e.value == value) return e; return this; } @Override public String toString() { return intern().name(); } } /** \brief How to handle local times that do not exist due to DST shifts. * * NONEXISTENT_EARLIEST emits the instant "just before" the DST shift instant * in the given timestamp precision (for example, for a nanoseconds precision * timestamp, this is one nanosecond before the DST shift instant). * NONEXISTENT_LATEST emits the DST shift instant. */ public enum Nonexistent { NONEXISTENT_RAISE(0), NONEXISTENT_EARLIEST(1), NONEXISTENT_LATEST(2); public final int value; private Nonexistent(int v) { this.value = v; } private Nonexistent(Nonexistent e) { this.value = e.value; } public Nonexistent intern() { for (Nonexistent e : values()) if (e.value == value) return e; return this; } @Override public String toString() { return intern().name(); } } public AssumeTimezoneOptions(@StdString String timezone, Ambiguous ambiguous/*=arrow::compute::AssumeTimezoneOptions::AMBIGUOUS_RAISE*/, Nonexistent nonexistent/*=arrow::compute::AssumeTimezoneOptions::NONEXISTENT_RAISE*/) { super((Pointer)null); allocate(timezone, ambiguous, nonexistent); } private native void allocate(@StdString String timezone, Ambiguous ambiguous/*=arrow::compute::AssumeTimezoneOptions::AMBIGUOUS_RAISE*/, Nonexistent nonexistent/*=arrow::compute::AssumeTimezoneOptions::NONEXISTENT_RAISE*/); public AssumeTimezoneOptions(@StdString String timezone) { super((Pointer)null); allocate(timezone); } private native void allocate(@StdString String timezone); public AssumeTimezoneOptions(@StdString BytePointer timezone, @Cast("arrow::compute::AssumeTimezoneOptions::Ambiguous") int ambiguous/*=arrow::compute::AssumeTimezoneOptions::AMBIGUOUS_RAISE*/, @Cast("arrow::compute::AssumeTimezoneOptions::Nonexistent") int nonexistent/*=arrow::compute::AssumeTimezoneOptions::NONEXISTENT_RAISE*/) { super((Pointer)null); allocate(timezone, ambiguous, nonexistent); } private native void allocate(@StdString BytePointer timezone, @Cast("arrow::compute::AssumeTimezoneOptions::Ambiguous") int ambiguous/*=arrow::compute::AssumeTimezoneOptions::AMBIGUOUS_RAISE*/, @Cast("arrow::compute::AssumeTimezoneOptions::Nonexistent") int nonexistent/*=arrow::compute::AssumeTimezoneOptions::NONEXISTENT_RAISE*/); public AssumeTimezoneOptions(@StdString BytePointer timezone) { super((Pointer)null); allocate(timezone); } private native void allocate(@StdString BytePointer timezone); public AssumeTimezoneOptions() { super((Pointer)null); allocate(); } private native void allocate(); @MemberGetter public static native byte kTypeName(int i); @MemberGetter public static native String kTypeName(); /** Timezone to convert timestamps from */ public native @StdString String timezone(); public native AssumeTimezoneOptions timezone(String setter); /** How to interpret ambiguous local times (due to DST shifts) */ public native Ambiguous ambiguous(); public native AssumeTimezoneOptions ambiguous(Ambiguous setter); /** How to interpret non-existent local times (due to DST shifts) */ public native Nonexistent nonexistent(); public native AssumeTimezoneOptions nonexistent(Nonexistent setter); }
3e1b2a998172231b190b7f98b9ea4ac591454aff
1,471
java
Java
src/main/java/com/miusaatega/batchjob/controller/BatchJobController.java
tibizy/miu-sa-batchjob-atega
4dce5f79f57c880a26a66b28a533357ba557366c
[ "MIT" ]
null
null
null
src/main/java/com/miusaatega/batchjob/controller/BatchJobController.java
tibizy/miu-sa-batchjob-atega
4dce5f79f57c880a26a66b28a533357ba557366c
[ "MIT" ]
null
null
null
src/main/java/com/miusaatega/batchjob/controller/BatchJobController.java
tibizy/miu-sa-batchjob-atega
4dce5f79f57c880a26a66b28a533357ba557366c
[ "MIT" ]
null
null
null
37.717949
85
0.826649
11,501
package com.miusaatega.batchjob.controller; import com.miusaatega.batchjob.models.Student; import com.miusaatega.batchjob.repository.StudentRepository; import com.miusaatega.batchjob.services.BatchJobService; import io.swagger.v3.oas.annotations.tags.Tag; import org.springframework.batch.core.JobParametersInvalidException; import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException; import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException; import org.springframework.batch.core.repository.JobRestartException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.security.RolesAllowed; import java.util.List; @RestController @RequestMapping("api/admin") @RolesAllowed("ADMIN") @Tag(name = "Admin") public class BatchJobController { @Autowired BatchJobService batchJobService; @Autowired StudentRepository studentRepository; @GetMapping("jobs") public ResponseEntity<List<Student>> runJob() throws Exception { batchJobService.runJob(); return ResponseEntity.ok(studentRepository.findAll()); } }
3e1b2ae28e43ce6c9d8e09bbd48c341a46d471e7
2,421
java
Java
Projects/JavaFX GUI Calculator (Simple)/Controller.java
AbdulAziz0682/Learn-to-code-java
22e12cbe35d9536345368dcb903f680cc43cefc9
[ "MIT" ]
23
2020-10-11T07:54:32.000Z
2022-03-21T21:22:34.000Z
Projects/JavaFX GUI Calculator (Simple)/Controller.java
AbdulAziz0682/Learn-to-code-java
22e12cbe35d9536345368dcb903f680cc43cefc9
[ "MIT" ]
83
2020-10-11T05:17:36.000Z
2021-10-16T09:49:12.000Z
Projects/JavaFX GUI Calculator (Simple)/Controller.java
AbdulAziz0682/Learn-to-code-java
22e12cbe35d9536345368dcb903f680cc43cefc9
[ "MIT" ]
79
2020-10-11T07:40:29.000Z
2022-03-21T21:22:36.000Z
27.511364
59
0.472532
11,502
package sample; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.Label; public class Controller { boolean checker = false; double one_int = 0; double second_int = 0; double answer = 0; String one = ""; char two; @FXML Label ans; public void pressNum(ActionEvent actionEvent) { Button btnez = (Button) actionEvent.getSource(); one = one.concat(btnez.getText()); ans.setText(one); } public void pressAct(ActionEvent actionEvent) { Button btn = (Button) actionEvent.getSource(); if(!checker){ one_int = Double.parseDouble(ans.getText()); ans.setText(""); two = btn.getText().charAt(0); checker = true; one = ""; } else{ second_int = Double.parseDouble(ans.getText()); if(two == '+'){ answer = one_int + second_int; } if(two == '-'){ answer = one_int - second_int; } if(two == '/'){ answer = one_int / second_int; } if(two == '*'){ answer = one_int * second_int; } ans.setText(String.format("%f", answer)); two = btn.getText().charAt(0); one_int = answer; one = ""; } } public void pressEqual(ActionEvent actionEvent){ if(!checker){ one_int = Double.parseDouble(ans.getText()); ans.setText(String.valueOf(one_int)); checker = false; one = ""; } else{ second_int = Double.parseDouble(ans.getText()); if(two == '+'){ answer = one_int + second_int; } if(two == '-'){ answer = one_int - second_int; } if(two == '/'){ answer = one_int / second_int; } if(two == '*'){ answer = one_int * second_int; } ans.setText(String.format("%f", answer)); checker = false; one = ""; } } public void clearAll(ActionEvent actionEvent){ checker = false; one_int = 0; second_int = 0; answer = 0; one = ""; ans.setText(""); } }
3e1b2af786984c20fe47e5a3377d1f5a178b2068
1,251
java
Java
mercadolivre/src/main/java/br/com/orange/mercadolivre/validator/CampoUnicoValidator.java
PedroArthurB99/orange-talents-08-template-ecommerce
5a74b148a235b2b3f2540d27da24511abddd4626
[ "Apache-2.0" ]
null
null
null
mercadolivre/src/main/java/br/com/orange/mercadolivre/validator/CampoUnicoValidator.java
PedroArthurB99/orange-talents-08-template-ecommerce
5a74b148a235b2b3f2540d27da24511abddd4626
[ "Apache-2.0" ]
null
null
null
mercadolivre/src/main/java/br/com/orange/mercadolivre/validator/CampoUnicoValidator.java
PedroArthurB99/orange-talents-08-template-ecommerce
5a74b148a235b2b3f2540d27da24511abddd4626
[ "Apache-2.0" ]
null
null
null
32.921053
124
0.73781
11,503
package br.com.orange.mercadolivre.validator; import br.com.orange.mercadolivre.exception.CampoUnicoException; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import java.util.List; public class CampoUnicoValidator implements ConstraintValidator<CampoUnicoConstraint, Object> { private String campo; private Class<?> modelClass; @PersistenceContext private EntityManager manager; @Override public void initialize(CampoUnicoConstraint constraintAnnotation) { // ConstraintValidator.super.initialize(constraintAnnotation); campo = constraintAnnotation.campo(); modelClass = constraintAnnotation.modelClass(); } @Override public boolean isValid(Object value, ConstraintValidatorContext context) { Query query = manager.createQuery("SELECT 1 FROM " + this.modelClass.getName() + " WHERE " + this.campo + "=:param") .setParameter("param", value); List<?> list = query.getResultList(); if (!list.isEmpty()) { throw new CampoUnicoException(this.campo); } return true; } }
3e1b2b4f4e700d50918a9bb28e4adc35ceea0548
228
java
Java
src/test/resources/single_result/while_loop_break_without_braces.java
matozoid/data_flow_analyser_with_javaparser
18b669916c3d1b9cb9f324d210bc744b45e35cc4
[ "Apache-2.0" ]
3
2021-04-27T07:55:37.000Z
2021-07-22T20:46:34.000Z
src/test/resources/single_result/while_loop_break_without_braces.java
matozoid/java_flow_analyser
18b669916c3d1b9cb9f324d210bc744b45e35cc4
[ "Apache-2.0" ]
18
2021-04-10T11:25:24.000Z
2022-03-29T04:13:39.000Z
src/test/resources/single_result/while_loop_break_without_braces.java
matozoid/data_flow_analyser_with_javaparser
18b669916c3d1b9cb9f324d210bc744b45e35cc4
[ "Apache-2.0" ]
2
2021-06-22T05:18:10.000Z
2022-02-07T08:58:16.000Z
17.538462
34
0.429825
11,504
void abc(int b) { while (b > 0) while (c > 0) break; b = 5; } /* expected: 1 START -> 2 2 CHOICE -> 5 or 3 (cond: 2:12) 5 STEP -> end 3 CHOICE -> 2 or 4 (cond: 3:16) 4 BREAK -> 2 */
3e1b2bcf18ae470cd232ce8e89784bb4d12cde3d
4,152
java
Java
servo-core/src/test/java/com/netflix/servo/monitor/DoubleCounterTest.java
brharrington/servo
6480bc4aedfd0b03dcfa16fb41ce76d46882eda0
[ "Apache-2.0" ]
993
2015-01-02T14:53:23.000Z
2022-03-27T12:03:16.000Z
servo-core/src/test/java/com/netflix/servo/monitor/DoubleCounterTest.java
brharrington/servo
6480bc4aedfd0b03dcfa16fb41ce76d46882eda0
[ "Apache-2.0" ]
113
2015-01-13T21:01:54.000Z
2021-12-19T15:38:41.000Z
servo-core/src/test/java/com/netflix/servo/monitor/DoubleCounterTest.java
brharrington/servo
6480bc4aedfd0b03dcfa16fb41ce76d46882eda0
[ "Apache-2.0" ]
271
2015-01-08T13:38:08.000Z
2022-03-24T18:49:49.000Z
27.137255
92
0.660405
11,505
/** * Copyright 2015 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.monitor; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.util.ManualClock; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; public class DoubleCounterTest { private static final double DELTA = 1e-06; final ManualClock clock = new ManualClock(Pollers.POLLING_INTERVALS[1]); public DoubleCounter newInstance(String name) { return new DoubleCounter(MonitorConfig.builder(name).build(), clock); } private long time(long t) { return t * 1000 + Pollers.POLLING_INTERVALS[1]; } @Test public void testIncrement() { assertEquals(Pollers.POLLING_INTERVALS[0], 60000L); DoubleCounter c = newInstance("c"); c.increment(1.0); assertEquals(c.getCurrentCount(0), 1.0); } @Test public void testSimpleTransition() { clock.set(time(1)); DoubleCounter c = newInstance("c"); assertEquals(c.getValue(1).doubleValue(), 0.0, DELTA); assertEquals(c.getCurrentCount(1), 0.0); clock.set(time(3)); c.increment(1); assertEquals(c.getValue(1).doubleValue(), 0.0, DELTA); assertEquals(c.getCurrentCount(1), 1.0); clock.set(time(6)); c.increment(1); assertEquals(c.getValue(1).doubleValue(), 0.0, DELTA); assertEquals(c.getCurrentCount(1), 2.0); clock.set(time(12)); c.increment(1); assertEquals(c.getCurrentCount(1), 1.0); assertEquals(c.getValue(1).doubleValue(), 2.0 / 10.0); } @Test public void testInitialPollIsZero() { clock.set(time(1)); DoubleCounter c = newInstance("foo"); assertEquals(c.getValue(1).doubleValue(), 0.0); } @Test public void testHasRightType() throws Exception { assertEquals(newInstance("foo").getConfig().getTags().getValue(DataSourceType.KEY), "NORMALIZED"); } @Test public void testBoundaryTransition() { clock.set(time(1)); DoubleCounter c = newInstance("foo"); // Should all go to one bucket c.increment(1); clock.set(time(4)); c.increment(1); clock.set(time(9)); c.increment(1); // Should cause transition clock.set(time(10)); c.increment(1); clock.set(time(19)); c.increment(1); // Check counts assertEquals(c.getValue(1).doubleValue(), 0.3); assertEquals(c.getCurrentCount(1), 2.0); } @Test public void testResetPreviousValue() { clock.set(time(1)); DoubleCounter c = newInstance("foo"); for (int i = 1; i <= 100000; ++i) { c.increment(1); clock.set(time(i * 10 + 1)); assertEquals(c.getValue(1).doubleValue(), 0.1); } } @Test public void testNonMonotonicClock() { clock.set(time(1)); DoubleCounter c = newInstance("foo"); c.getValue(1); c.increment(1); c.increment(1); clock.set(time(10)); c.increment(1); clock.set(time(9)); // Should get ignored c.increment(1); assertEquals(c.getCurrentCount(1), 2.0); c.increment(1); clock.set(time(10)); c.increment(1); c.increment(1); assertEquals(c.getCurrentCount(1), 5.0); // Check rate for previous interval assertEquals(c.getValue(1).doubleValue(), 0.2); } @Test public void testGetValueTwice() { ManualClock manualClock = new ManualClock(0L); DoubleCounter c = new DoubleCounter(MonitorConfig.builder("test").build(), manualClock); c.increment(1); for (int i = 1; i < 10; ++i) { manualClock.set(i * 60000L); c.increment(1); c.getValue(0); assertEquals(c.getValue(0).doubleValue(), 1 / 60.0); } } }
3e1b2bf35e048ab950a9e427cbe3793cc92bd852
1,724
java
Java
app/src/main/java/com/gmail/tarekmabdallah91/smooth/service/repository/network/paging/DataSourceFactory.java
tarekmabdallah91/NewsFeedapp
e154d17634344ac91446196b13fce7c80e728f51
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/gmail/tarekmabdallah91/smooth/service/repository/network/paging/DataSourceFactory.java
tarekmabdallah91/NewsFeedapp
e154d17634344ac91446196b13fce7c80e728f51
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/gmail/tarekmabdallah91/smooth/service/repository/network/paging/DataSourceFactory.java
tarekmabdallah91/NewsFeedapp
e154d17634344ac91446196b13fce7c80e728f51
[ "Apache-2.0" ]
null
null
null
30.403509
79
0.739181
11,506
/* * * Copyright 2019 hzdkv@example.com * inspired by https://github.com/EladBenDavid/TMDb * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.gmail.tarekmabdallah91.smooth.service.repository.network.paging; import android.app.Activity; import android.arch.lifecycle.MutableLiveData; import android.arch.paging.DataSource; import com.gmail.tarekmabdallah91.news.models.articles.Article; import rx.subjects.ReplaySubject; /* Responsible for creating the DataSource so we can give it to the PagedList. */ public class DataSourceFactory extends DataSource.Factory { private MutableLiveData<ItemDataSource> networkStatus; private ItemDataSource itemDataSource; public DataSourceFactory(Activity activity) { this.networkStatus = new MutableLiveData<>(); this.itemDataSource = new ItemDataSource(activity); } @Override public DataSource create() { networkStatus.postValue(itemDataSource); return itemDataSource; } public MutableLiveData<ItemDataSource> getNetworkStatus() { return networkStatus; } public ReplaySubject<Article> getArticles() { return itemDataSource.getArticles(); } }
3e1b2cb61fb50ceb2de4a8485aa3cf61def52c79
359
java
Java
cassandra/src/main/java/com/six_group/dgi/dsx/bigdata/poc/persisting/IPreTradePersister.java
rbattenfeld/bgd-term-paper
cd75e5bbe7b922eefe0cfd1c16b311a3038cb64d
[ "Apache-2.0" ]
null
null
null
cassandra/src/main/java/com/six_group/dgi/dsx/bigdata/poc/persisting/IPreTradePersister.java
rbattenfeld/bgd-term-paper
cd75e5bbe7b922eefe0cfd1c16b311a3038cb64d
[ "Apache-2.0" ]
null
null
null
cassandra/src/main/java/com/six_group/dgi/dsx/bigdata/poc/persisting/IPreTradePersister.java
rbattenfeld/bgd-term-paper
cd75e5bbe7b922eefe0cfd1c16b311a3038cb64d
[ "Apache-2.0" ]
null
null
null
29.916667
59
0.774373
11,508
package com.six_group.dgi.dsx.bigdata.poc.persisting; import java.util.List; import com.six_group.dgi.dsx.bigdata.poc.quoting.Spread; import com.six_group.dgi.dsx.bigdata.poc.quoting.Trade; public interface IPreTradePersister { void saveSpreadsCassandra(final List<Spread> spreads); void saveTradesCassandra(final List<Trade> trades); }
3e1b2cb6c73e733ec86def398e469bf9e1aa495a
6,098
java
Java
gerrit-acceptance-tests/src/test/java/com/google/gerrit/acceptance/api/plugin/PluginIT.java
balag91/gerrit
7c140198e2bc27b220aeb5ea3eecd05d1fee49b6
[ "Apache-2.0" ]
null
null
null
gerrit-acceptance-tests/src/test/java/com/google/gerrit/acceptance/api/plugin/PluginIT.java
balag91/gerrit
7c140198e2bc27b220aeb5ea3eecd05d1fee49b6
[ "Apache-2.0" ]
null
null
null
gerrit-acceptance-tests/src/test/java/com/google/gerrit/acceptance/api/plugin/PluginIT.java
balag91/gerrit
7c140198e2bc27b220aeb5ea3eecd05d1fee49b6
[ "Apache-2.0" ]
null
null
null
39.341935
99
0.711381
11,509
// Copyright (C) 2017 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.acceptance.api.plugin; import static com.google.common.truth.Truth.assertThat; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.stream.Collectors.toList; import static org.junit.Assert.fail; import com.google.common.collect.ImmutableList; import com.google.gerrit.acceptance.AbstractDaemonTest; import com.google.gerrit.acceptance.GerritConfig; import com.google.gerrit.acceptance.NoHttpd; import com.google.gerrit.common.RawInputUtil; import com.google.gerrit.extensions.api.plugins.PluginApi; import com.google.gerrit.extensions.api.plugins.Plugins.ListRequest; import com.google.gerrit.extensions.common.InstallPluginInput; import com.google.gerrit.extensions.common.PluginInfo; import com.google.gerrit.extensions.restapi.BadRequestException; import com.google.gerrit.extensions.restapi.MethodNotAllowedException; import com.google.gerrit.extensions.restapi.RawInput; import com.google.gerrit.extensions.restapi.ResourceNotFoundException; import com.google.gerrit.extensions.restapi.RestApiException; import java.util.List; import org.junit.Test; @NoHttpd public class PluginIT extends AbstractDaemonTest { private static final String JS_PLUGIN = "Gerrit.install(function(self){});\n"; private static final String HTML_PLUGIN = String.format("<dom-module id=\"test\"><script>%s</script></dom-module>", JS_PLUGIN); private static final RawInput JS_PLUGIN_CONTENT = RawInputUtil.create(JS_PLUGIN.getBytes(UTF_8)); private static final RawInput HTML_PLUGIN_CONTENT = RawInputUtil.create(HTML_PLUGIN.getBytes(UTF_8)); private static final List<String> PLUGINS = ImmutableList.of( "plugin-a.js", "plugin-b.html", "plugin-c.js", "plugin-d.html", "plugin_e.js"); @Test @GerritConfig(name = "plugins.allowRemoteAdmin", value = "true") public void pluginManagement() throws Exception { // No plugins are loaded assertThat(list().get()).isEmpty(); assertThat(list().all().get()).isEmpty(); PluginApi api; // Install all the plugins InstallPluginInput input = new InstallPluginInput(); for (String plugin : PLUGINS) { input.raw = plugin.endsWith(".js") ? JS_PLUGIN_CONTENT : HTML_PLUGIN_CONTENT; api = gApi.plugins().install(plugin, input); assertThat(api).isNotNull(); PluginInfo info = api.get(); String name = pluginName(plugin); assertThat(info.id).isEqualTo(name); assertThat(info.version).isEqualTo(pluginVersion(plugin)); assertThat(info.indexUrl).isEqualTo(String.format("plugins/%s/", name)); assertThat(info.disabled).isNull(); } assertPlugins(list().get(), PLUGINS); // With pagination assertPlugins(list().start(1).limit(2).get(), PLUGINS.subList(1, 3)); // With prefix assertPlugins(list().prefix("plugin-b").get(), ImmutableList.of("plugin-b.html")); assertPlugins(list().prefix("PLUGIN-").get(), ImmutableList.of()); // With substring assertPlugins(list().substring("lugin-").get(), PLUGINS.subList(0, PLUGINS.size() - 1)); assertPlugins(list().substring("lugin-").start(1).limit(2).get(), PLUGINS.subList(1, 3)); // With regex assertPlugins(list().regex(".*in-b").get(), ImmutableList.of("plugin-b.html")); assertPlugins(list().regex("plugin-.*").get(), PLUGINS.subList(0, PLUGINS.size() - 1)); assertPlugins(list().regex("plugin-.*").start(1).limit(2).get(), PLUGINS.subList(1, 3)); // Invalid match combinations assertBadRequest(list().regex(".*in-b").substring("a")); assertBadRequest(list().regex(".*in-b").prefix("a")); assertBadRequest(list().substring(".*in-b").prefix("a")); // Disable api = gApi.plugins().name("plugin-a"); api.disable(); api = gApi.plugins().name("plugin-a"); assertThat(api.get().disabled).isTrue(); assertPlugins(list().get(), PLUGINS.subList(1, PLUGINS.size())); assertPlugins(list().all().get(), PLUGINS); // Enable api.enable(); api = gApi.plugins().name("plugin-a"); assertThat(api.get().disabled).isNull(); assertPlugins(list().get(), PLUGINS); } @Test public void installNotAllowed() throws Exception { exception.expect(MethodNotAllowedException.class); exception.expectMessage("remote installation is disabled"); gApi.plugins().install("test.js", new InstallPluginInput()); } @Test public void getNonExistingThrowsNotFound() throws Exception { exception.expect(ResourceNotFoundException.class); gApi.plugins().name("does-not-exist"); } private ListRequest list() throws RestApiException { return gApi.plugins().list(); } private void assertPlugins(List<PluginInfo> actual, List<String> expected) { List<String> _actual = actual.stream().map(p -> p.id).collect(toList()); List<String> _expected = expected.stream().map(p -> pluginName(p)).collect(toList()); assertThat(_actual).containsExactlyElementsIn(_expected); } private String pluginName(String plugin) { int dot = plugin.indexOf("."); assertThat(dot).isGreaterThan(0); return plugin.substring(0, dot); } private String pluginVersion(String plugin) { String name = pluginName(plugin); int dash = name.lastIndexOf("-"); return dash > 0 ? name.substring(dash + 1) : ""; } private void assertBadRequest(ListRequest req) throws Exception { try { req.get(); fail("Expected BadRequestException"); } catch (BadRequestException e) { // Expected } } }
3e1b2da4cffed06745232972cffb930793f0e698
1,181
java
Java
gnd/src/main/java/com/google/android/gnd/persistence/local/room/FeatureDao.java
mmisim/ground-android
9b8059cf618e23a00bbb918241fe889c165a8522
[ "Apache-2.0" ]
1
2021-05-21T12:50:46.000Z
2021-05-21T12:50:46.000Z
gnd/src/main/java/com/google/android/gnd/persistence/local/room/FeatureDao.java
mmisim/ground-android
9b8059cf618e23a00bbb918241fe889c165a8522
[ "Apache-2.0" ]
null
null
null
gnd/src/main/java/com/google/android/gnd/persistence/local/room/FeatureDao.java
mmisim/ground-android
9b8059cf618e23a00bbb918241fe889c165a8522
[ "Apache-2.0" ]
null
null
null
34.735294
94
0.754445
11,510
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gnd.persistence.local.room; import androidx.room.Dao; import androidx.room.Query; import io.reactivex.Flowable; import io.reactivex.Maybe; import java.util.List; /** Provides low-level read/write operations of {@link FeatureEntity} to/from the local db. */ @Dao public interface FeatureDao extends BaseDao<FeatureEntity> { @Query("SELECT * FROM feature WHERE project_id = :projectId") Flowable<List<FeatureEntity>> findByProjectIdStream(String projectId); @Query("SELECT * FROM feature WHERE id = :id") Maybe<FeatureEntity> findById(String id); }
3e1b2f89ab2a54662ab442bd6b5ffda008a9ee23
3,070
java
Java
foc/src/b01/foc/gui/FGAbstractComboBox.java
FOC-framework/l3
b53600031c00f91781eba3e8c7506c8b9ce85ba7
[ "Apache-2.0" ]
null
null
null
foc/src/b01/foc/gui/FGAbstractComboBox.java
FOC-framework/l3
b53600031c00f91781eba3e8c7506c8b9ce85ba7
[ "Apache-2.0" ]
null
null
null
foc/src/b01/foc/gui/FGAbstractComboBox.java
FOC-framework/l3
b53600031c00f91781eba3e8c7506c8b9ce85ba7
[ "Apache-2.0" ]
null
null
null
24.173228
120
0.65114
11,511
/* * Created on 14 fvr. 2004 */ package b01.foc.gui; import java.awt.Color; import java.awt.event.*; import javax.swing.*; import b01.foc.property.*; import b01.foc.*; /** * @author Standard */ public abstract class FGAbstractComboBox extends JComboBox implements FocusListener, ActionListener, FPropertyListener { protected FProperty property = null; protected abstract String getPropertyStringValue(); protected abstract void setPropertyStringValue(String strValue); private FGComboAutoCompletion autoCompletion = null; boolean withAutoCompletion = false; public void dispose(){ if(property != null){ property.removeListener(this); property = null; } if(autoCompletion != null){ autoCompletion.dispose(); autoCompletion = null; } } private void updatePropertyValue() { String str = (String) getItemAt(getSelectedIndex()); //String str = (String) getSelectedItem(); setPropertyStringValue(str); //The combo box reactions in a table are not effective without this line //The combobox cell itself does not have problems, it is the other columns //That do not refresh otherwise. Globals.getDisplayManager().refresh(); } public void makeWithAutoCompletion(){ if(!withAutoCompletion){ this.autoCompletion = FGComboAutoCompletion.makeWithAutoCompletion(this); this.withAutoCompletion = true; } } public void setEnabled(boolean b) { super.setEnabled(b); StaticComponent.setEnabled(this, b); } // FocusListener // ------------- public void focusGained(FocusEvent e) { } public void focusLost(FocusEvent e) { updatePropertyValue(); } // ------------- // ActionListener // -------------- public void actionPerformed(ActionEvent e) { //Globals.logString("event id ="+e.getID()+"command " + e.getActionCommand()); updatePropertyValue(); } // -------------- /* public void setSelectedItem(Object obj){ boolean backupEditable = isEditable(); setEditable(true); super.setSelectedItem(getPropertyStringValue()); setEditable(backupEditable); } */ public void setSelectedItemWithColor(){ setSelectedItem(getPropertyStringValue()); if(getProperty() != null && getProperty().getBackground() != null){ setBackground(getProperty().getBackground()); }else{ Color c = (Color)UIManager.get("ComboBox.background"); setBackground(c); } } // PropertyListener // ---------------- public void propertyModified(FProperty property) { if (property != null) { setSelectedItemWithColor(); } } // ---------------- /** * @return Returns the property. */ public FProperty getProperty() { return property; } public void setProperty(FProperty prop) { if(property != prop){ if(property != null){ property.removeListener(this); } property = prop; //refreshList(); setSelectedItemWithColor(); if(property != null){ property.addListener(this); } } } }
3e1b2fa15f4915195a5e1f7a4dc69ca4ea080fe4
716
java
Java
aspect/testing/tests/src/com/google/idea/blaze/aspect/java/dependencies/testsrc/FooExporterExporter.java
ricebin/intellij
33f15b87476cea7b2e006f51027526d97ceffc89
[ "Apache-2.0" ]
675
2016-07-11T15:24:50.000Z
2022-03-21T20:35:53.000Z
aspect/testing/tests/src/com/google/idea/blaze/aspect/java/dependencies/testsrc/FooExporterExporter.java
ricebin/intellij
33f15b87476cea7b2e006f51027526d97ceffc89
[ "Apache-2.0" ]
1,327
2016-07-11T20:30:17.000Z
2022-03-30T18:57:25.000Z
aspect/testing/tests/src/com/google/idea/blaze/aspect/java/dependencies/testsrc/FooExporterExporter.java
ricebin/intellij
33f15b87476cea7b2e006f51027526d97ceffc89
[ "Apache-2.0" ]
262
2016-07-11T17:51:01.000Z
2022-03-21T09:05:19.000Z
37.684211
75
0.752793
11,512
/* * Copyright 2017 The Bazel Authors. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.idea.blaze.aspect.java.dependencies.testsrc; class FooExporterExporter {}
3e1b3067766c82c69805ccd99790b4128b0a1ed8
1,976
java
Java
clevertap-android-sdk/src/main/java/com/clevertap/android/sdk/DataHandler.java
faisalkhan1690/clevertap-android-sdk
a13ff851325d4500c7f5b8852dc5f87ecfec0eea
[ "MIT" ]
null
null
null
clevertap-android-sdk/src/main/java/com/clevertap/android/sdk/DataHandler.java
faisalkhan1690/clevertap-android-sdk
a13ff851325d4500c7f5b8852dc5f87ecfec0eea
[ "MIT" ]
1
2019-06-04T04:07:40.000Z
2019-06-04T04:07:40.000Z
clevertap-android-sdk/src/main/java/com/clevertap/android/sdk/DataHandler.java
faisalkhan1690/clevertap-android-sdk
a13ff851325d4500c7f5b8852dc5f87ecfec0eea
[ "MIT" ]
null
null
null
37.283019
97
0.642713
11,513
package com.clevertap.android.sdk; import java.lang.ref.WeakReference; @Deprecated public class DataHandler { private WeakReference<CleverTapAPI> weakReference; DataHandler(CleverTapAPI cleverTapAPI){ this.weakReference = new WeakReference<>(cleverTapAPI); } /** * Sends the GCM registration ID to CleverTap. * * @param gcmId The GCM registration ID * @param register Boolean indicating whether to register * or not for receiving push messages from CleverTap. * Set this to true to receive push messages from CleverTap, * and false to not receive any messages from CleverTap. * @deprecated use {@link CleverTapAPI#pushGcmRegistrationId(String gcmId, boolean register)} */ @Deprecated public void pushGcmRegistrationId(String gcmId, boolean register) { CleverTapAPI cleverTapAPI = weakReference.get(); if (cleverTapAPI == null) { Logger.d("CleverTap Instance is null."); } else { cleverTapAPI.pushGcmRegistrationId(gcmId, register); } } /** * Sends the FCM registration ID to CleverTap. * * @param fcmId The FCM registration ID * @param register Boolean indicating whether to register * or not for receiving push messages from CleverTap. * Set this to true to receive push messages from CleverTap, * and false to not receive any messages from CleverTap. * @deprecated use {@link CleverTapAPI#pushFcmRegistrationId(String gcmId, boolean register)} */ @Deprecated public void pushFcmRegistrationId(String fcmId, boolean register) { CleverTapAPI cleverTapAPI = weakReference.get(); if (cleverTapAPI == null) { Logger.d("CleverTap Instance is null."); } else { cleverTapAPI.pushFcmRegistrationId(fcmId, register); } } }
3e1b31189fe80e315ec6bbc090a4641ea40020e0
735
java
Java
basex-api/src/main/java/org/basex/query/func/request/RequestFn.java
igneus/basex
bd1451a01236983d3e302611d78f3031999b8c05
[ "BSD-3-Clause" ]
null
null
null
basex-api/src/main/java/org/basex/query/func/request/RequestFn.java
igneus/basex
bd1451a01236983d3e302611d78f3031999b8c05
[ "BSD-3-Clause" ]
null
null
null
basex-api/src/main/java/org/basex/query/func/request/RequestFn.java
igneus/basex
bd1451a01236983d3e302611d78f3031999b8c05
[ "BSD-3-Clause" ]
null
null
null
24.5
81
0.719728
11,514
package org.basex.query.func.request; import static org.basex.query.QueryError.*; import javax.servlet.http.*; import org.basex.http.*; import org.basex.query.*; import org.basex.query.func.*; /** * Request function. * * @author BaseX Team 2005-19, BSD License * @author Christian Gruen */ abstract class RequestFn extends StandardFunc { /** * Returns the current HTTP servlet request. * @param qc query context * @return HTTP request * @throws QueryException query exception */ final HttpServletRequest request(final QueryContext qc) throws QueryException { final Object req = qc.getProperty(HTTPText.REQUEST); if(req == null) throw BASEX_HTTP.get(info); return (HttpServletRequest) req; } }
3e1b319902768d5f78d27ea944e5612193e7df8e
1,038
java
Java
_plugin/jap-ids-solon-plugin/src/test/java/com/fujieid/jap/ids/solon/services/IdsIdentityServiceImpl.java
greenflute/noear_solon
9aa5eefaa080705cb337286bfd36719d11196dfc
[ "Apache-2.0" ]
1
2022-03-06T09:44:51.000Z
2022-03-06T09:44:51.000Z
_plugin/jap-ids-solon-plugin/src/test/java/com/fujieid/jap/ids/solon/services/IdsIdentityServiceImpl.java
greenflute/noear_solon
9aa5eefaa080705cb337286bfd36719d11196dfc
[ "Apache-2.0" ]
null
null
null
_plugin/jap-ids-solon-plugin/src/test/java/com/fujieid/jap/ids/solon/services/IdsIdentityServiceImpl.java
greenflute/noear_solon
9aa5eefaa080705cb337286bfd36719d11196dfc
[ "Apache-2.0" ]
null
null
null
28.833333
67
0.710019
11,515
package com.fujieid.jap.ids.solon.services; import com.fujieid.jap.ids.config.JwtConfig; import com.fujieid.jap.ids.service.IdsIdentityService; import org.noear.solon.annotation.Component; /** * @author yadong.zhang (yadong.zhang0415(a)gmail.com) * @version 1.0.0 * @date 2021-04-16 16:32 * @since 1.0.0 */ public class IdsIdentityServiceImpl implements IdsIdentityService { /** * Get the jwt token encryption key string * * @param identity User/organization/enterprise identification * @return Encryption key string in json format */ @Override public String getJwksJson(String identity) { return IdsIdentityService.super.getJwksJson(identity); } /** * Get the configuration of jwt token encryption * * @param identity User/organization/enterprise identification * @return Encryption key string in json format */ @Override public JwtConfig getJwtConfig(String identity) { return IdsIdentityService.super.getJwtConfig(identity); } }
3e1b31db3f2c9f65e6069e854b4802be4e7a7521
1,578
java
Java
src/main/java/com/visme/demo/exception/ApiExceptionHandler.java
Dadidam/visme-java
b81bcaabdb82bc2fa0e19b264b5bff97856eba52
[ "Unlicense" ]
null
null
null
src/main/java/com/visme/demo/exception/ApiExceptionHandler.java
Dadidam/visme-java
b81bcaabdb82bc2fa0e19b264b5bff97856eba52
[ "Unlicense" ]
4
2021-05-11T10:43:00.000Z
2022-02-27T03:07:24.000Z
src/main/java/com/visme/demo/exception/ApiExceptionHandler.java
Dadidam/visme-java
b81bcaabdb82bc2fa0e19b264b5bff97856eba52
[ "Unlicense" ]
null
null
null
33.574468
86
0.709759
11,516
package com.visme.demo.exception; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import java.time.ZoneId; import java.time.ZonedDateTime; @ControllerAdvice public class ApiExceptionHandler { @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(value = {ApiRequestException.class}) public ResponseEntity<Object> handleApiRequestException(ApiRequestException e) { // Create payload container HttpStatus badRequest = HttpStatus.BAD_REQUEST; ApiException apiException = new ApiException( e.getMessage(), badRequest, ZonedDateTime.now(ZoneId.of("Z")) ); // Return response entity return new ResponseEntity<>(apiException, badRequest); } @ResponseStatus(HttpStatus.NOT_FOUND) @ExceptionHandler(value = {EntityNotFoundException.class}) public ResponseEntity<Object> handleNotFoundException(EntityNotFoundException e) { // Create payload container HttpStatus badRequest = HttpStatus.NOT_FOUND; NotFoundException notFoundException = new NotFoundException( e.getMessage(), badRequest, ZonedDateTime.now(ZoneId.of("Z")) ); // Return response entity return new ResponseEntity<>(notFoundException, badRequest); } }
3e1b330378db5a086c63e8852807f394e26637ba
844
java
Java
src/main/java/com/zup/propostaservice/crypto/CryptoService.java
tales-zup/orange-talents-08-template-proposta
60dacb49a7db2ca9e66c4db4759c23eb23f47edb
[ "Apache-2.0" ]
null
null
null
src/main/java/com/zup/propostaservice/crypto/CryptoService.java
tales-zup/orange-talents-08-template-proposta
60dacb49a7db2ca9e66c4db4759c23eb23f47edb
[ "Apache-2.0" ]
null
null
null
src/main/java/com/zup/propostaservice/crypto/CryptoService.java
tales-zup/orange-talents-08-template-proposta
60dacb49a7db2ca9e66c4db4759c23eb23f47edb
[ "Apache-2.0" ]
null
null
null
24.114286
73
0.701422
11,517
package com.zup.propostaservice.crypto; import org.jasypt.util.text.BasicTextEncryptor; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; @Service public class CryptoService { @Value("${chave-criptografia-base}") private String chaveCriptografia; private BasicTextEncryptor encryptor; public CryptoService() { this.encryptor = new BasicTextEncryptor(); } @PostConstruct public void setarChave() { encryptor.setPasswordCharArray(chaveCriptografia.toCharArray()); } public String criptografar(String texto) { return encryptor.encrypt(texto); } public String descriptografar(String texto) { return encryptor.decrypt(texto); } }
3e1b33b45999f8ed5bbdae6d49d7313f4ebe6340
3,558
java
Java
modules/flowable-engine/src/main/java/org/flowable/engine/delegate/FutureJavaDelegate.java
le-shi/flowable-engine
0b610fd04b23769212f328cee330a65991fa7683
[ "Apache-2.0" ]
5,250
2016-10-13T08:15:16.000Z
2022-03-31T13:53:26.000Z
modules/flowable-engine/src/main/java/org/flowable/engine/delegate/FutureJavaDelegate.java
le-shi/flowable-engine
0b610fd04b23769212f328cee330a65991fa7683
[ "Apache-2.0" ]
1,736
2016-10-13T17:03:10.000Z
2022-03-31T19:27:39.000Z
modules/flowable-engine/src/main/java/org/flowable/engine/delegate/FutureJavaDelegate.java
le-shi/flowable-engine
0b610fd04b23769212f328cee330a65991fa7683
[ "Apache-2.0" ]
2,271
2016-10-13T08:27:26.000Z
2022-03-31T15:36:02.000Z
50.828571
199
0.741709
11,518
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.flowable.engine.delegate; import java.util.concurrent.CompletableFuture; import org.flowable.common.engine.api.async.AsyncTaskInvoker; /** * Convenience class that should be used when a Java delegation in a BPMN 2.0 process is required (for example, to call custom business logic). * When this interface is implemented then the execution of the logic can happen on a different thread then the process execution. * <p> * This class can be used only for service tasks. * <p> * This class does not allow to influence the control flow. It follows the default BPMN 2.0 behavior of taking every outgoing sequence flow (which has a condition that evaluates to true if there is a * condition defined) If you are in need of influencing the flow in your process, use the class 'org.flowable.engine.impl.pvm.delegate.ActivityBehavior' instead. * <p> * This interface allows fine grained control on how the future should be created. * It gives access to the {@link AsyncTaskInvoker} which can delegate execution to a shared task executor. * However, it doesn't have to be used. * In case you don't need custom task executor the {@link FlowableFutureJavaDelegate} can be used. * </p> * * @param <Output> the output of the execution * @author Filip Hrisafov * @see FlowableFutureJavaDelegate * @see MapBasedFlowableFutureJavaDelegate */ public interface FutureJavaDelegate<Output> { /** * Perform the execution of the delegate, potentially on another thread. * The result of the future is passed in the {@link #afterExecution(DelegateExecution, Object)} in order to store * the data on the execution on the same thread as the caller of this method. * * <b>IMPORTANT:</b> the execution should only be used to read data before creating the future. * The execution should not be used in the task that will be executed on a new thread. * <p> * The {@link AsyncTaskInvoker} is in order to schedule an execution on a different thread. * However, it is also possible to use a different scheduler, or return a future not created by the given {@code taskInvoker}. * </p> * * @param execution the execution that can be used to extract data * @param taskInvoker the task invoker that can be used to execute expensive operation on another thread * @return the output data of the execution */ CompletableFuture<Output> execute(DelegateExecution execution, AsyncTaskInvoker taskInvoker); /** * Method invoked with the result from {@link #execute(DelegateExecution, AsyncTaskInvoker)}. * This should be used to set data on the {@link DelegateExecution}. * This is on the same thread as {@link #execute(DelegateExecution, AsyncTaskInvoker)} and participates in the process transaction. * * @param execution the execution to which data can be set * @param executionData the execution data */ void afterExecution(DelegateExecution execution, Output executionData); }
3e1b34519d48634f2fd54284dedaaca031ffc68c
4,346
java
Java
src/main/java/pinacolada/characters/PCLCharacter.java
Darkon47/STS-FoolMod
85ebfd1f93edd2a1ec738a294b95a3a299564077
[ "Apache-2.0" ]
null
null
null
src/main/java/pinacolada/characters/PCLCharacter.java
Darkon47/STS-FoolMod
85ebfd1f93edd2a1ec738a294b95a3a299564077
[ "Apache-2.0" ]
null
null
null
src/main/java/pinacolada/characters/PCLCharacter.java
Darkon47/STS-FoolMod
85ebfd1f93edd2a1ec738a294b95a3a299564077
[ "Apache-2.0" ]
1
2022-03-13T23:54:43.000Z
2022-03-13T23:54:43.000Z
28.781457
107
0.695582
11,519
package pinacolada.characters; import basemod.abstracts.CustomPlayer; import basemod.animations.G3DJAnimation; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.math.MathUtils; import com.megacrit.cardcrawl.actions.AbstractGameAction; import com.megacrit.cardcrawl.cards.AbstractCard; import com.megacrit.cardcrawl.core.CardCrawlGame; import com.megacrit.cardcrawl.daily.mods.BlueCards; import com.megacrit.cardcrawl.daily.mods.GreenCards; import com.megacrit.cardcrawl.daily.mods.PurpleCards; import com.megacrit.cardcrawl.daily.mods.RedCards; import com.megacrit.cardcrawl.helpers.CardLibrary; import com.megacrit.cardcrawl.helpers.FontHelper; import com.megacrit.cardcrawl.helpers.ModHelper; import com.megacrit.cardcrawl.helpers.ScreenShake; import com.megacrit.cardcrawl.relics.AbstractRelic; import com.megacrit.cardcrawl.screens.stats.CharStat; import pinacolada.effects.SFX; import pinacolada.patches.relicLibrary.RelicLibraryPatches; import pinacolada.ui.PCLEnergyOrb; import pinacolada.ui.characterSelection.PCLBaseStatEditor; import java.util.ArrayList; public abstract class PCLCharacter extends CustomPlayer { public PCLCharacter(String name, PlayerClass playerClass, PCLEnergyOrb orb) { super(name, playerClass, orb, (new G3DJAnimation(null, null))); } @Override public ArrayList<String> getRelicNames() { final ArrayList<String> list = new ArrayList<>(); for (AbstractRelic r : relics) { RelicLibraryPatches.AddRelic(list, r); } return list; } @Override public ArrayList<AbstractCard> getCardPool(ArrayList<AbstractCard> arrayList) { arrayList = super.getCardPool(arrayList); if (ModHelper.isModEnabled(RedCards.ID)) { CardLibrary.addRedCards(arrayList); } if (ModHelper.isModEnabled(GreenCards.ID)) { CardLibrary.addGreenCards(arrayList); } if (ModHelper.isModEnabled(BlueCards.ID)) { CardLibrary.addBlueCards(arrayList); } if (ModHelper.isModEnabled(PurpleCards.ID)) { CardLibrary.addPurpleCards(arrayList); } return arrayList; } @Override public String getSpireHeartText() { return com.megacrit.cardcrawl.events.beyond.SpireHeart.DESCRIPTIONS[10]; } @Override public Color getSlashAttackColor() { return Color.SKY; } @Override public AbstractGameAction.AttackEffect[] getSpireHeartSlashEffect() { return new AbstractGameAction.AttackEffect[] { AbstractGameAction.AttackEffect.SLASH_HEAVY, AbstractGameAction.AttackEffect.FIRE, AbstractGameAction.AttackEffect.SLASH_DIAGONAL, AbstractGameAction.AttackEffect.SLASH_HEAVY, AbstractGameAction.AttackEffect.FIRE, AbstractGameAction.AttackEffect.SLASH_DIAGONAL }; } @Override public String getVampireText() { return com.megacrit.cardcrawl.events.city.Vampires.DESCRIPTIONS[5]; } @Override public int getAscensionMaxHPLoss() { return PCLBaseStatEditor.StatType.HP.BaseAmount / 10; } @Override public BitmapFont getEnergyNumFont() { return FontHelper.energyNumFontBlue; } @Override public void doCharSelectScreenSelectEffect() { CardCrawlGame.sound.playA(getCustomModeCharacterButtonSoundKey(), MathUtils.random(-0.1f, 0.2f)); CardCrawlGame.screenShake.shake(ScreenShake.ShakeIntensity.MED, ScreenShake.ShakeDur.SHORT, false); } @Override public String getCustomModeCharacterButtonSoundKey() { return SFX.TINGSHA; } @Override public String getPortraitImageName() { return null; // Updated in AnimatorCharacterSelectScreen } @Override public Texture getEnergyImage() { if (this.energyOrb instanceof PCLEnergyOrb) { return ((PCLEnergyOrb)this.energyOrb).getEnergyImage(); } else { return super.getEnergyImage(); } } @Override public CharStat getCharStat() { // yes return super.getCharStat(); } }
3e1b347ca6e553e46f1d3da0477cda788f528de4
1,276
java
Java
src/main/java/com/dsa/tree/BSTWithMinimumHeight.java
mhnvelu/DataStructures-And-Algorithms
9ac14a080ef7509d58bde8d4325f55a7c48f0491
[ "MIT" ]
null
null
null
src/main/java/com/dsa/tree/BSTWithMinimumHeight.java
mhnvelu/DataStructures-And-Algorithms
9ac14a080ef7509d58bde8d4325f55a7c48f0491
[ "MIT" ]
null
null
null
src/main/java/com/dsa/tree/BSTWithMinimumHeight.java
mhnvelu/DataStructures-And-Algorithms
9ac14a080ef7509d58bde8d4325f55a7c48f0491
[ "MIT" ]
null
null
null
31.121951
122
0.660658
11,520
package com.dsa.tree; /* Problem Description: Given a sorted array(ascending order) with unique integer elements, write an algorithm to create a BST with minimum height */ /* Solution: Using recursion 1. Insert into the tree the middle element of the array 2. Insert (into the left subtree) the left subarray elements 2. Insert (into the right subtree) the right subarray elements 4. Recurse */ public class BSTWithMinimumHeight { public static void main(String a[]) { BSTWithMinimumHeight obj = new BSTWithMinimumHeight(); int[] input = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; TreeNode treeNode = obj.createMinimalHeightBST(input, 0, input.length - 1); TreeTraversal.inOrderTraversal(treeNode); System.out.println(); TreeTraversal.preOrderTraversal(treeNode); System.out.println(); TreeTraversal.postOrderTraversal(treeNode); } TreeNode createMinimalHeightBST(int[] arr, int start, int end) { if (end < start) { return null; } int mid = (start + end) / 2; TreeNode node = new TreeNode(arr[mid]); node.left = createMinimalHeightBST(arr, start, mid - 1); node.right = createMinimalHeightBST(arr, mid + 1, end); return node; } }
3e1b350f2c2c8a648b006273e8b375687104e0c4
2,856
java
Java
flyway-core/src/main/java/org/flywaydb/core/internal/database/mysql/MySQLConnection.java
renat-sabitov/flyway
e3c9adaac18f46017ad524cbe0df26d13ab33c00
[ "ECL-2.0", "Apache-2.0" ]
1
2021-09-02T22:39:38.000Z
2021-09-02T22:39:38.000Z
flyway-core/src/main/java/org/flywaydb/core/internal/database/mysql/MySQLConnection.java
renat-sabitov/flyway
e3c9adaac18f46017ad524cbe0df26d13ab33c00
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
flyway-core/src/main/java/org/flywaydb/core/internal/database/mysql/MySQLConnection.java
renat-sabitov/flyway
e3c9adaac18f46017ad524cbe0df26d13ab33c00
[ "ECL-2.0", "Apache-2.0" ]
1
2018-11-21T19:32:59.000Z
2018-11-21T19:32:59.000Z
34.409639
104
0.691527
11,521
/* * Copyright 2010-2018 Boxfuse GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.flywaydb.core.internal.database.mysql; import org.flywaydb.core.api.configuration.Configuration; import org.flywaydb.core.api.logging.Log; import org.flywaydb.core.api.logging.LogFactory; import org.flywaydb.core.internal.database.base.Connection; import org.flywaydb.core.internal.database.base.Schema; import org.flywaydb.core.internal.database.base.Table; import org.flywaydb.core.internal.util.StringUtils; import java.sql.SQLException; import java.util.UUID; import java.util.concurrent.Callable; /** * MySQL connection. */ public class MySQLConnection extends Connection<MySQLDatabase> { private static final Log LOG = LogFactory.getLog(MySQLConnection.class); MySQLConnection(Configuration configuration, MySQLDatabase database, java.sql.Connection connection , boolean originalAutoCommit ) { super(configuration, database, connection, originalAutoCommit ); } @Override protected String getCurrentSchemaNameOrSearchPath() throws SQLException { return jdbcTemplate.queryForString("SELECT DATABASE()"); } @Override public void doChangeCurrentSchemaOrSearchPathTo(String schema) throws SQLException { if (StringUtils.hasLength(schema)) { jdbcTemplate.getConnection().setCatalog(schema); } else { try { // Weird hack to switch back to no database selected... String newDb = database.quote(UUID.randomUUID().toString()); jdbcTemplate.execute("CREATE SCHEMA " + newDb); jdbcTemplate.execute("USE " + newDb); jdbcTemplate.execute("DROP SCHEMA " + newDb); } catch (Exception e) { LOG.warn("Unable to restore connection to having no default schema: " + e.getMessage()); } } } @Override public Schema getSchema(String name) { return new MySQLSchema(jdbcTemplate, database, name); } @Override public <T> T lock(Table table, Callable<T> callable) { if (database.isPxcStrict()) { return super.lock(table, callable); } return new MySQLNamedLockTemplate(jdbcTemplate, table.toString().hashCode()).execute(callable); } }
3e1b3613c642346aeb6d9b606635677f8ed22b0b
4,759
java
Java
XiaoShiZi/src/main/java/edu/children/xiaoshizi/fragment/SafeLabFragment.java
hailongfeng/XiaoShiZi
264f94156f9fa1d85d599f10a7ff39a9796a7d9a
[ "Apache-2.0" ]
null
null
null
XiaoShiZi/src/main/java/edu/children/xiaoshizi/fragment/SafeLabFragment.java
hailongfeng/XiaoShiZi
264f94156f9fa1d85d599f10a7ff39a9796a7d9a
[ "Apache-2.0" ]
null
null
null
XiaoShiZi/src/main/java/edu/children/xiaoshizi/fragment/SafeLabFragment.java
hailongfeng/XiaoShiZi
264f94156f9fa1d85d599f10a7ff39a9796a7d9a
[ "Apache-2.0" ]
null
null
null
34.485507
132
0.696575
11,522
package edu.children.xiaoshizi.fragment; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.alibaba.fastjson.JSONArray; import com.blankj.utilcode.util.CacheUtils; import com.ogaclejapan.smarttablayout.SmartTabLayout; import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItemAdapter; import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItems; import java.util.ArrayList; import java.util.List; import java.util.TreeMap; import butterknife.BindView; import edu.children.xiaoshizi.DemoApplication; import edu.children.xiaoshizi.R; import edu.children.xiaoshizi.bean.Article; import edu.children.xiaoshizi.bean.ArticleType; import edu.children.xiaoshizi.bean.ArticleType_Table; import edu.children.xiaoshizi.bean.LoadContentCategoryResponse; import edu.children.xiaoshizi.db.DbUtils; import edu.children.xiaoshizi.logic.APIMethod; import edu.children.xiaoshizi.logic.LogicService; import edu.children.xiaoshizi.net.rxjava.ApiSubscriber; import edu.children.xiaoshizi.net.rxjava.Response; import zuo.biao.library.util.Log; public class SafeLabFragment extends XszBaseFragment { private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; @BindView(R.id.viewpagertab) SmartTabLayout viewPagerTab; @BindView(R.id.viewpager) ViewPager viewPager; private List<ArticleType> articleTypes=new ArrayList<>(); public static SafeLabFragment newInstance(String param1, String param2) { SafeLabFragment fragment = new SafeLabFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override int getLayoutId() { return R.layout.fragment_safe_lab; } @Override public void initView() { List<ArticleType> articleTypes2=DbUtils.getArticleTypeList(3); initType(articleTypes2); loadSeLabContentCategory(); } void initTabs(List<ArticleType> articleTypes){ FragmentPagerItems.Creator creator=FragmentPagerItems.with(context); Log.d(TAG,"articleTypes size==="+articleTypes.size()); for (ArticleType articleType:articleTypes){ Bundle bundle=new Bundle(); bundle.putSerializable("articleType",articleType); creator.add(articleType.getTitle(), SeLabArticleFragment.class,bundle); } FragmentManager fragmentManager=getChildFragmentManager(); FragmentPagerItemAdapter adapter = new FragmentPagerItemAdapter( fragmentManager, creator.create()); viewPager.setAdapter(adapter); viewPagerTab.setViewPager(viewPager); } private void initType(List<ArticleType> types){ if (types!=null){ this.articleTypes.clear(); this.articleTypes.addAll(types); initTabs(this.articleTypes); // multiStatusLayout_shouye.showContent(); }else { // multiStatusLayout_shouye.showEmpty(); } } @Override public void initData() { } private void loadSeLabContentCategory() { TreeMap sm = new TreeMap<String,String>(); LogicService.post(context,APIMethod.loadSeLabContentCategory,sm,new ApiSubscriber<Response<LoadContentCategoryResponse>>() { @Override protected void onSuccess(Response<LoadContentCategoryResponse> response) { DemoApplication.getInstance().setContentSeLabCategoryResponse(response.getResult()); List<ArticleType> articleTypes2=response.getResult().getCategoryResps(); for (ArticleType type:articleTypes2){ type.setBelongTo(3); } DbUtils.deleteArticleType(3); // DbUtils.deleteModel(ArticleType.class,ArticleType_Table.belongTo.eq(3)); DbUtils.saveModelList(articleTypes2); List<Article> articles=response.getResult().getContentResps(); String type3Articles= JSONArray.toJSONString(articles); print("type3Articles="+type3Articles); CacheUtils.get(context).put("type3Articles",type3Articles); initType(articleTypes2); } @Override protected void onFail(Throwable error) { error.printStackTrace(); } }); } @Override public void initEvent() { } }
3e1b36519d5bfe92a1f8af65157c5f6353392198
917
java
Java
xfire-xmpp/src/test/org/codehaus/xfire/xmpp/SoapIQProviderTest.java
eduardodaluz/xfire
e4e9723991692a0e4fab500e979bf48b8dd25caf
[ "MIT" ]
null
null
null
xfire-xmpp/src/test/org/codehaus/xfire/xmpp/SoapIQProviderTest.java
eduardodaluz/xfire
e4e9723991692a0e4fab500e979bf48b8dd25caf
[ "MIT" ]
3
2022-01-27T16:23:45.000Z
2022-01-27T16:24:10.000Z
xfire-xmpp/src/test/org/codehaus/xfire/xmpp/SoapIQProviderTest.java
eduardodaluz/xfire
e4e9723991692a0e4fab500e979bf48b8dd25caf
[ "MIT" ]
null
null
null
34.148148
93
0.665944
11,523
package org.codehaus.xfire.xmpp; import org.codehaus.xfire.soap.Soap11; import org.codehaus.xfire.soap.SoapVersion; import org.codehaus.xfire.test.AbstractXFireTest; import org.jivesoftware.smack.provider.ProviderManager; /** * @author <a href="mailto:kenaa@example.com">Dan Diephouse</a> */ public class SoapIQProviderTest extends AbstractXFireTest { public void testIQ() throws Exception { new SoapIQProvider(); SoapVersion v11 = Soap11.getInstance(); Object provider = ProviderManager.getIQProvider(v11.getEnvelope().getLocalPart(), v11.getEnvelope().getNamespaceURI()); assertNotNull("Got null provider for " + v11.getEnvelope().getLocalPart() + " in namespace " + v11.getEnvelope().getNamespaceURI(), provider); assertTrue(provider instanceof SoapIQProvider); } }
3e1b36c0423b92cf37f27ebf0e3dd5af4cd69bdf
3,804
java
Java
spring-with-mybatis/src/test/java/study/huhao/demo/adapters/inbound/rest/resources/blog/BlogResourceTest.java
howiehu/hexagonal-architecture-samples
cd69bdfa7da467e7036fa90d2b5b5b67f19dac63
[ "MIT" ]
229
2019-04-22T15:05:59.000Z
2022-03-21T02:55:53.000Z
spring-with-mybatis/src/test/java/study/huhao/demo/adapters/inbound/rest/resources/blog/BlogResourceTest.java
howiehu/hexagonal-architecture-samples
cd69bdfa7da467e7036fa90d2b5b5b67f19dac63
[ "MIT" ]
1
2019-10-22T02:34:08.000Z
2019-12-05T01:58:17.000Z
spring-with-mybatis/src/test/java/study/huhao/demo/adapters/inbound/rest/resources/blog/BlogResourceTest.java
howiehu/hexagonal-architecture-samples
cd69bdfa7da467e7036fa90d2b5b5b67f19dac63
[ "MIT" ]
86
2019-04-14T14:25:05.000Z
2022-03-09T04:01:22.000Z
36.932039
112
0.529443
11,524
package study.huhao.demo.adapters.inbound.rest.resources.blog; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import study.huhao.demo.adapters.inbound.rest.resources.ResourceTest; import java.util.UUID; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.*; import static org.hamcrest.core.IsEqual.equalTo; import static study.huhao.demo.adapters.inbound.rest.resources.BasePath.BLOG_BASE_PATH; import static study.huhao.demo.adapters.inbound.rest.resources.BaseRequestSpecification.createBlog; import static study.huhao.demo.adapters.inbound.rest.resources.BaseResponseSpecification.CREATED_SPEC; import static study.huhao.demo.adapters.inbound.rest.resources.BaseResponseSpecification.OK_SPEC; @DisplayName(BLOG_BASE_PATH) class BlogResourceTest extends ResourceTest { @Nested @DisplayName("POST /blogs") class post { @Test void should_create_blog() { UUID authorId = UUID.randomUUID(); createBlog("Test Blog", "Something...", authorId) .then() .spec(CREATED_SPEC) .body("id", notNullValue()) .body("title", is("Test Blog")) .body("body", is("Something...")) .body("authorId", is(authorId.toString())) .header("Location", response -> containsString(BLOG_BASE_PATH + "/" + response.path("id"))); } } @Nested @DisplayName("GET " + BLOG_BASE_PATH + "?limit={limit}&offset={offset}") class get { @Test void should_order_by_createdAt_desc_by_default() throws InterruptedException { createMultiBlog(); given() .when() .get(BLOG_BASE_PATH + "?limit=5&offset=0") .then() .spec(OK_SPEC) .body("results", hasSize(5)) .body("limit", equalTo(5)) .body("offset", equalTo(0)) .body("total", equalTo(5)) .body("results[0].title", is("Test Blog 1")) .body("results[1].title", is("Test Blog 2")) .body("results[2].title", is("Test Blog 3")) .body("results[3].title", is("Test Blog 4")) .body("results[4].title", is("Test Blog 5")); } @Test void should_get_second_page_blog() throws InterruptedException { createMultiBlog(); given() .when() .get(BLOG_BASE_PATH + "?limit=3&offset=3") .then() .spec(OK_SPEC) .body("results", hasSize(2)) .body("limit", equalTo(3)) .body("offset", equalTo(3)) .body("total", equalTo(5)) .body("results[0].title", is("Test Blog 4")) .body("results[1].title", is("Test Blog 5")); } @Test void should_return_empty_results_when_not_found_any_blog() { given() .when() .get(BLOG_BASE_PATH + "?limit=3&offset=4") .then() .spec(OK_SPEC) .body("results", hasSize(0)) .body("limit", equalTo(3)) .body("offset", equalTo(4)) .body("total", equalTo(0)); } private void createMultiBlog() throws InterruptedException { for (int i = 0; i < 5; i++) { Thread.sleep(10); createBlog("Test Blog " + (i + 1), "Something...", UUID.randomUUID()); } } } }
3e1b37813703d86556e3984066741fb5fabb7879
2,147
java
Java
src/main/java/seedu/address/logic/commands/DoneTodoCommand.java
whoisjustinngo/tp
ad40aa57e3f701bb1c7d0c0b2a7878ba946a938d
[ "MIT" ]
null
null
null
src/main/java/seedu/address/logic/commands/DoneTodoCommand.java
whoisjustinngo/tp
ad40aa57e3f701bb1c7d0c0b2a7878ba946a938d
[ "MIT" ]
150
2021-09-27T08:41:44.000Z
2021-11-11T10:38:19.000Z
src/main/java/seedu/address/logic/commands/DoneTodoCommand.java
whoisjustinngo/tp
ad40aa57e3f701bb1c7d0c0b2a7878ba946a938d
[ "MIT" ]
4
2021-09-13T09:37:38.000Z
2021-09-29T07:53:56.000Z
30.239437
93
0.66558
11,525
package seedu.address.logic.commands; import static java.util.Objects.requireNonNull; import java.util.List; import seedu.address.commons.core.Messages; import seedu.address.commons.core.index.Index; import seedu.address.logic.commands.exceptions.CommandException; import seedu.address.model.Model; import seedu.address.model.todo.Todo; /** * Marks an existing Todo as done. */ public class DoneTodoCommand extends Command { public static final String COMMAND_WORD = "done"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Marks the todo, identified " + "by the index number used in the displayed todo list, as done.\n" + "Parameters: INDEX (must be a positive integer)\n" + "Example: " + COMMAND_WORD + " 1"; public static final String MESSAGE_DONE_TODO_SUCCESS = "Marked this Todo as done: %1$s"; private final Index index; /** * @param index of the todo in the filtered todo list to mark as done */ public DoneTodoCommand(Index index) { requireNonNull(index); this.index = index; } @Override public CommandResult execute(Model model) throws CommandException { requireNonNull(model); List<Todo> lastShownList = model.getFilteredTodoList(); if (index.getZeroBased() >= lastShownList.size()) { throw new CommandException(Messages.MESSAGE_INVALID_TODO_DISPLAYED_INDEX); } Todo todoToMark = lastShownList.get(index.getZeroBased()); assert todoToMark != null; Todo markedTodo = todoToMark.getDoneVersion(); model.setTodo(todoToMark, markedTodo); return new CommandResult(String.format(MESSAGE_DONE_TODO_SUCCESS, markedTodo)); } @Override public boolean equals(Object other) { // short circuit if same object if (other == this) { return true; } // instanceof handles nulls if (!(other instanceof DoneTodoCommand)) { return false; } // state check DoneTodoCommand e = (DoneTodoCommand) other; return index.equals(e.index); } }
3e1b38ebe7f89bd5713bc22e369fc2ee4fae41e6
850
java
Java
src/ast/PrintNode.java
alirezasmr/Espresso
ee6ac348e5f3494436559d5ccc6ccff175149eae
[ "MIT" ]
1
2019-01-25T20:41:51.000Z
2019-01-25T20:41:51.000Z
src/ast/PrintNode.java
alirezasmr/Espresso
ee6ac348e5f3494436559d5ccc6ccff175149eae
[ "MIT" ]
null
null
null
src/ast/PrintNode.java
alirezasmr/Espresso
ee6ac348e5f3494436559d5ccc6ccff175149eae
[ "MIT" ]
1
2019-04-18T03:30:40.000Z
2019-04-18T03:30:40.000Z
18.085106
88
0.609412
11,526
package ast; import compiler.Visitor; /* Espresso Compiler - https://github.com/neevsamar/espresso.git Alireza Samar (A147053) Sepideh Sattar (A138894) */ public class PrintNode extends Node { private ExprNode value; private String type = null; //the type of the value (either int, boolean or a class) public PrintNode(ExprNode value, int lineNumber, int colNumber) { super(lineNumber, colNumber); this.value = value; } public Object accept(Visitor v) { return v.visit(this); } public Object visitValue(Visitor v) { return value.accept(v); } public String toString() { return "print(" + value + ")"; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
3e1b396c646e0b251de5d26e808564a019038c77
4,175
java
Java
clients/client/java/src/test/java/sh/ory/model/NormalizedProjectRevisionThirdPartyProviderTest.java
ory/sdks
958314d130922ad6f20f439b5230141a832231a5
[ "Apache-2.0" ]
null
null
null
clients/client/java/src/test/java/sh/ory/model/NormalizedProjectRevisionThirdPartyProviderTest.java
ory/sdks
958314d130922ad6f20f439b5230141a832231a5
[ "Apache-2.0" ]
null
null
null
clients/client/java/src/test/java/sh/ory/model/NormalizedProjectRevisionThirdPartyProviderTest.java
ory/sdks
958314d130922ad6f20f439b5230141a832231a5
[ "Apache-2.0" ]
null
null
null
20.756219
179
0.612895
11,527
/* * Ory APIs * Documentation for all public and administrative Ory APIs. Administrative APIs can only be accessed with a valid Personal Access Token. Public APIs are mostly used in browsers. * * The version of the OpenAPI document: v0.0.1-alpha.187 * Contact: nnheo@example.com * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package sh.ory.model; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.List; import java.util.UUID; import org.openapitools.jackson.nullable.JsonNullable; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; /** * Model tests for NormalizedProjectRevisionThirdPartyProvider */ public class NormalizedProjectRevisionThirdPartyProviderTest { private final NormalizedProjectRevisionThirdPartyProvider model = new NormalizedProjectRevisionThirdPartyProvider(); /** * Model tests for NormalizedProjectRevisionThirdPartyProvider */ @Test public void testNormalizedProjectRevisionThirdPartyProvider() { // TODO: test NormalizedProjectRevisionThirdPartyProvider } /** * Test the property 'applePrivateKey' */ @Test public void applePrivateKeyTest() { // TODO: test applePrivateKey } /** * Test the property 'applePrivateKeyId' */ @Test public void applePrivateKeyIdTest() { // TODO: test applePrivateKeyId } /** * Test the property 'appleTeamId' */ @Test public void appleTeamIdTest() { // TODO: test appleTeamId } /** * Test the property 'authUrl' */ @Test public void authUrlTest() { // TODO: test authUrl } /** * Test the property 'azureTenant' */ @Test public void azureTenantTest() { // TODO: test azureTenant } /** * Test the property 'clientId' */ @Test public void clientIdTest() { // TODO: test clientId } /** * Test the property 'clientSecret' */ @Test public void clientSecretTest() { // TODO: test clientSecret } /** * Test the property 'createdAt' */ @Test public void createdAtTest() { // TODO: test createdAt } /** * Test the property 'id' */ @Test public void idTest() { // TODO: test id } /** * Test the property 'issuerUrl' */ @Test public void issuerUrlTest() { // TODO: test issuerUrl } /** * Test the property 'label' */ @Test public void labelTest() { // TODO: test label } /** * Test the property 'mapperUrl' */ @Test public void mapperUrlTest() { // TODO: test mapperUrl } /** * Test the property 'projectRevisionId' */ @Test public void projectRevisionIdTest() { // TODO: test projectRevisionId } /** * Test the property 'provider' */ @Test public void providerTest() { // TODO: test provider } /** * Test the property 'providerId' */ @Test public void providerIdTest() { // TODO: test providerId } /** * Test the property 'requestedClaims' */ @Test public void requestedClaimsTest() { // TODO: test requestedClaims } /** * Test the property 'scope' */ @Test public void scopeTest() { // TODO: test scope } /** * Test the property 'tokenUrl' */ @Test public void tokenUrlTest() { // TODO: test tokenUrl } /** * Test the property 'updatedAt' */ @Test public void updatedAtTest() { // TODO: test updatedAt } }
3e1b39d2098cca5ab71357981273b9198d6b87a9
487
java
Java
src/test/java/com/qintingfm/web/RediesTest.java
glzaboy/java-qintingfm-web
b526c5b54a04eb97e47697f40898c4b0a905a148
[ "Apache-2.0" ]
null
null
null
src/test/java/com/qintingfm/web/RediesTest.java
glzaboy/java-qintingfm-web
b526c5b54a04eb97e47697f40898c4b0a905a148
[ "Apache-2.0" ]
null
null
null
src/test/java/com/qintingfm/web/RediesTest.java
glzaboy/java-qintingfm-web
b526c5b54a04eb97e47697f40898c4b0a905a148
[ "Apache-2.0" ]
null
null
null
24.35
62
0.747433
11,528
package com.qintingfm.web; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.redis.core.RedisTemplate; @SpringBootTest public class RediesTest { @Autowired RedisTemplate<String,String> template; @Test public void testRedisTemplate(){ template.opsForValue().append("abc","def"); template.delete("abc"); } }
3e1b39da0e72a9010c59f9eae01a5583e7dab620
852
java
Java
cachecloud-open-web/src/test/java/com/sohu/test/dao/AppDaoTest.java
fengkuangdestone/cachecloud
c6585490dd89f56bcc87e816b10861cd030f08ad
[ "Apache-2.0" ]
153
2018-09-27T03:34:45.000Z
2022-01-12T10:00:44.000Z
open-monitor-center/cachecloud/cachecloud-open-web/src/test/java/com/sohu/test/dao/AppDaoTest.java
marc45/open-capacity-platform-1
2edfb17e330c3a7c2cb54e2f6f652c00ef0b84a1
[ "Apache-2.0" ]
null
null
null
open-monitor-center/cachecloud/cachecloud-open-web/src/test/java/com/sohu/test/dao/AppDaoTest.java
marc45/open-capacity-platform-1
2edfb17e330c3a7c2cb54e2f6f652c00ef0b84a1
[ "Apache-2.0" ]
86
2018-09-08T14:29:00.000Z
2021-09-27T08:21:36.000Z
20.780488
58
0.644366
11,529
package com.sohu.test.dao; import java.util.List; import com.sohu.cache.dao.AppDao; import com.sohu.cache.entity.AppDesc; import com.sohu.cache.entity.AppSearch; import com.sohu.test.BaseTest; import org.junit.Test; import javax.annotation.Resource; /** * User: lingguo * Date: 14-6-10 * Time: 下午11:36 */ public class AppDaoTest extends BaseTest{ @Resource private AppDao appDao; @Test public void testAppDao() { long appId = 998L; AppDesc appDesc = appDao.getAppDescById(appId); logger.info("{}", appDesc.toString()); } @Test public void testGetAllAppDescList(){ AppSearch vo = new AppSearch(); vo.setAppName("vrspoll"); vo.setAppId(10011L); List<AppDesc> list = appDao.getAllAppDescList(vo); logger.info("list is {}", list); } }
3e1b3a20a93145a3f5acc0a08dafc6f6ccffc0dc
1,242
java
Java
src/main/java/seedu/tracker/model/calendar/AcademicYear.java
WuaaAj/tp
effde99e4404d4509cac6cb21d88a682085cb711
[ "MIT" ]
null
null
null
src/main/java/seedu/tracker/model/calendar/AcademicYear.java
WuaaAj/tp
effde99e4404d4509cac6cb21d88a682085cb711
[ "MIT" ]
null
null
null
src/main/java/seedu/tracker/model/calendar/AcademicYear.java
WuaaAj/tp
effde99e4404d4509cac6cb21d88a682085cb711
[ "MIT" ]
null
null
null
28.227273
96
0.643317
11,530
package seedu.tracker.model.calendar; import static java.util.Objects.requireNonNull; import static seedu.tracker.commons.util.AppUtil.checkArgument; public class AcademicYear { public static final String MESSAGE_CONSTRAINTS = "Academic Year should only contain numbers from 1 to 6, and it should not be blank"; public final int value; /** * Constructs an academic year. * @param year A valid academic year. */ public AcademicYear(int year) { requireNonNull(year); checkArgument(isValidAcademicYear(year), MESSAGE_CONSTRAINTS); this.value = year; } /** * Returns true if a given int is a valid Academic year. */ public static boolean isValidAcademicYear(int test) { /* Academic year should be between year 1 and year 6*/ return test >= 1 && test <= 6; } @Override public String toString() { return Integer.toString(value); } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof AcademicYear) // instanceof handles nulls && value == (((AcademicYear) other).value); // state check } }
3e1b3c8d0cbdffd0897b5f3d526db33828df499b
7,509
java
Java
sdk/src/com/kakao/authorization/accesstoken/AccessToken.java
kkung/kakao-android-sdk-standalone
63e52d2d1caf972bbfb394067464cca1017c3aef
[ "Apache-2.0" ]
9
2015-06-15T11:35:22.000Z
2018-04-18T03:52:54.000Z
sdk/src/com/kakao/authorization/accesstoken/AccessToken.java
kkung/kakao-android-sdk-standalone
63e52d2d1caf972bbfb394067464cca1017c3aef
[ "Apache-2.0" ]
null
null
null
sdk/src/com/kakao/authorization/accesstoken/AccessToken.java
kkung/kakao-android-sdk-standalone
63e52d2d1caf972bbfb394067464cca1017c3aef
[ "Apache-2.0" ]
5
2015-04-22T16:17:33.000Z
2019-04-18T05:39:04.000Z
38.92228
157
0.724175
11,531
/** * Copyright 2014 Minyoung Jeong <anpch@example.com> * Copyright 2014 Kakao Corp. * * Redistribution and modification in source or binary forms are not permitted without specific prior written permission.  * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.kakao.authorization.accesstoken; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; import android.text.TextUtils; import com.kakao.helper.ServerProtocol; import com.kakao.helper.SharedPreferencesCache; import com.kakao.helper.Utility; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; /** * refresh token에 대한 expires_at은 아직 내려오지 않는다. * @author MJ */ public class AccessToken implements Parcelable{ private static final String CACHE_ACCESS_TOKEN = "com.kakao.token.AccessToken"; private static final String CACHE_ACCESS_TOKEN_EXPIRES_AT = "com.kakao.token.AccessToken.ExpiresAt"; private static final String CACHE_REFRESH_TOKEN = "com.kakao.token.RefreshToken"; private static final String CACHE_REFRESH_TOKEN_EXPIRES_AT = "com.kakao.token.RefreshToken.ExpiresAt"; private static final Date MIN_DATE = new Date(Long.MIN_VALUE); private static final Date MAX_DATE = new Date(Long.MAX_VALUE); private static final Date DEFAULT_EXPIRATION_TIME = MAX_DATE; private static final Date ALREADY_EXPIRED_EXPIRATION_TIME = MIN_DATE; private String accessTokenString; private String refreshTokenString; private Date accessTokenExpiresAt; private Date refreshTokenExpiresAt; public static AccessToken createEmptyToken() { return new AccessToken("", "", ALREADY_EXPIRED_EXPIRATION_TIME, ALREADY_EXPIRED_EXPIRATION_TIME); } public static AccessToken createFromCache(final Bundle bundle) { Utility.notNull(bundle, "bundle"); final String accessToken = bundle.getString(CACHE_ACCESS_TOKEN); final String refreshToken = bundle.getString(CACHE_REFRESH_TOKEN); final Date accessTokenExpiresAt = SharedPreferencesCache.getDate(bundle, CACHE_ACCESS_TOKEN_EXPIRES_AT); final Date refreshTokenExpiresAt = SharedPreferencesCache.getDate(bundle, CACHE_REFRESH_TOKEN_EXPIRES_AT); return new AccessToken(accessToken, refreshToken, accessTokenExpiresAt, refreshTokenExpiresAt); } public static AccessToken createFromResponse(final Map resultObj) { String accessToken; long accessTokenExpiresAt; String refreshToken; //long refreshTokenExpiresAt =0L; accessToken = (String) resultObj.get(ServerProtocol.ACCESS_TOKEN_KEY); if(accessToken == null) return null; refreshToken = (String) resultObj.get(ServerProtocol.REFRESH_TOKEN_KEY); accessTokenExpiresAt = new Date().getTime() + (Integer)resultObj.get(ServerProtocol.EXPIRES_AT_KEY) * 1000; // 일단 refresh token의 expires_in은 나중에 return new AccessToken(accessToken, refreshToken, new Date(accessTokenExpiresAt), MAX_DATE); } private AccessToken(final String accessTokenString, final String refreshTokenString, final Date accessTokenExpiresAt, final Date refreshTokenExpiresAt) { this.accessTokenString = accessTokenString; this.refreshTokenString = refreshTokenString; this.accessTokenExpiresAt = accessTokenExpiresAt; this.refreshTokenExpiresAt = refreshTokenExpiresAt; } public static void clearAccessTokenFromCache(final SharedPreferencesCache cache) { final List<String> keysToRemove = new ArrayList<String>(); keysToRemove.add(CACHE_ACCESS_TOKEN); keysToRemove.add(CACHE_ACCESS_TOKEN_EXPIRES_AT); cache.clear(keysToRemove); } public void saveAccessTokenToCache(final SharedPreferencesCache cache) { Bundle bundle = new Bundle(); bundle.putString(CACHE_ACCESS_TOKEN, accessTokenString); bundle.putString(CACHE_REFRESH_TOKEN, refreshTokenString); SharedPreferencesCache.putDate(bundle, CACHE_ACCESS_TOKEN_EXPIRES_AT, accessTokenExpiresAt); SharedPreferencesCache.putDate(bundle, CACHE_REFRESH_TOKEN_EXPIRES_AT, refreshTokenExpiresAt); cache.save(bundle); } public static boolean hasValidAccessToken(final Bundle bundle) { if(bundle == null) return false; String token = bundle.getString(CACHE_ACCESS_TOKEN); if(((token == null) || (token.length() == 0))) return false; Date expiresAt = SharedPreferencesCache.getDate(bundle, CACHE_ACCESS_TOKEN_EXPIRES_AT); return !(expiresAt == null || expiresAt.before(new Date())); } // refresh token public static boolean hasRefreshToken(final Bundle bundle) { Utility.notNull(bundle, "bundle"); String token = bundle.getString(CACHE_REFRESH_TOKEN); return !((token == null) || (token.length() == 0)); } // access token 갱신시에는 refresh token이 내려오지 않을 수도 있다. public void updateAccessToken(final AccessToken newAccessToken){ String newRefreshToken = newAccessToken.refreshTokenString; if(TextUtils.isEmpty(newRefreshToken)){ this.accessTokenString = newAccessToken.accessTokenString; this.accessTokenExpiresAt = newAccessToken.accessTokenExpiresAt; } else { this.accessTokenString = newAccessToken.accessTokenString; this.refreshTokenString = newAccessToken.refreshTokenString; this.accessTokenExpiresAt = newAccessToken.accessTokenExpiresAt; this.refreshTokenExpiresAt = newAccessToken.refreshTokenExpiresAt; } } public String getAccessTokenString() { return accessTokenString; } public String getRefreshTokenString() { return refreshTokenString; } public boolean hasRefreshToken(){ return !Utility.isNullOrEmpty(this.refreshTokenString); } public boolean hasValidAccessToken() { return !Utility.isNullOrEmpty(this.accessTokenString) && !new Date().after(this.accessTokenExpiresAt); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(accessTokenString); dest.writeString(refreshTokenString); dest.writeLong(accessTokenExpiresAt.getTime()); dest.writeLong(refreshTokenExpiresAt.getTime()); } public AccessToken(Parcel in) { accessTokenString = in.readString(); refreshTokenString = in.readString(); accessTokenExpiresAt = new Date(in.readLong()); refreshTokenExpiresAt = new Date(in.readLong()); } public static final Parcelable.Creator<AccessToken> CREATOR = new Parcelable.Creator<AccessToken>() { public AccessToken createFromParcel(Parcel in) { return new AccessToken(in); } public AccessToken[] newArray(int size) { return new AccessToken[size]; } }; }
3e1b3c93e78a67b5f8dfcf74d22b257ee7c97205
2,721
java
Java
jbpm/rest-wih/business-application-service/src/main/java/com/company/service/Application.java
torstenwerner/mastertheboss
76e37a50c0b25990fe417ff6aa02736410bf3eae
[ "MIT" ]
146
2015-05-08T12:55:21.000Z
2022-03-24T10:15:25.000Z
jbpm/rest-wih/business-application-service/src/main/java/com/company/service/Application.java
torstenwerner/mastertheboss
76e37a50c0b25990fe417ff6aa02736410bf3eae
[ "MIT" ]
12
2016-01-11T14:40:27.000Z
2022-02-25T09:29:51.000Z
jbpm/rest-wih/business-application-service/src/main/java/com/company/service/Application.java
torstenwerner/mastertheboss
76e37a50c0b25990fe417ff6aa02736410bf3eae
[ "MIT" ]
588
2015-07-06T21:53:45.000Z
2022-03-30T07:54:59.000Z
38.323944
142
0.735759
11,532
package com.company.service; import org.jbpm.services.api.ProcessService; import org.jbpm.services.api.RuntimeDataService; import org.jbpm.services.api.UserTaskService; import org.kie.api.task.model.Status; import org.kie.api.task.model.TaskSummary; import org.kie.internal.query.QueryFilter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import java.security.Principal; import java.util.HashMap; import java.util.List; import java.util.Map; @SpringBootApplication @RestController public class Application { @Autowired private ProcessService processService; @Autowired private RuntimeDataService runtimeDataService; @Autowired private UserTaskService userTaskService; public static void main(String[] args) { SpringApplication.run(Application.class, args); } @GetMapping("/hello") public ResponseEntity<String> sayHello(@RequestParam Integer age) throws Exception { // Provided as an example. Not actually needed by our process. Map<String, Object> vars = new HashMap<>(); vars.put("name", "John Smith"); Long processInstanceId = processService.startProcess("business-application-kjar-1_0-SNAPSHOT", "com.mastertheboss.LicenseDemo", vars); Map<String, Object> params = new HashMap<String, Object>(); params.put("age", age); List<TaskSummary> taskSummaries = runtimeDataService.getTasksAssignedAsPotentialOwner("john", new QueryFilter()); taskSummaries.forEach(s->{ Status status = taskSummaries.get(0).getStatus(); if ( status == Status.Ready ) userTaskService.claim(s.getId(), "john"); userTaskService.start(s.getId(), "john"); userTaskService.complete(s.getId(), "john", params); }); return ResponseEntity.status(HttpStatus.CREATED).body("Task completed!"); } @PostMapping("/callback") public ResponseEntity<Void> datamodelCallback(Principal principal, @RequestBody String name) throws Exception { System.out.println("Hey : "+ principal); System.out.println("There is a license request from " + name); return ResponseEntity.ok().build(); } }
3e1b3cbbff06a9df3fd8ac3419eb5db0e7b7462a
6,333
java
Java
api/src/main/java/org/essencemc/essencecore/nms/packet/playout/title/Title.java
Rojoss/EssenceCore
5bd80353a7052f2735c3b86c4d67741e83e3cb87
[ "MIT" ]
null
null
null
api/src/main/java/org/essencemc/essencecore/nms/packet/playout/title/Title.java
Rojoss/EssenceCore
5bd80353a7052f2735c3b86c4d67741e83e3cb87
[ "MIT" ]
null
null
null
api/src/main/java/org/essencemc/essencecore/nms/packet/playout/title/Title.java
Rojoss/EssenceCore
5bd80353a7052f2735c3b86c4d67741e83e3cb87
[ "MIT" ]
null
null
null
46.226277
120
0.658614
11,533
/* * The MIT License (MIT) * * Copyright (c) 2015 Essence <http://essencemc.org> * Copyright (c) 2015 contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.essencemc.essencecore.nms.packet.playout.title; import org.bukkit.entity.Player; import org.essencemc.essencecore.plugin.NMSFetcher; import java.util.Collection; /** * Interface for handling Titles and Subtitles */ public interface Title { /** * Send the player only the title message * * @param titleMessage The message to be sent to the player. * It has to be a string in raw JSON format. * You can use TextParser to build one if you want. * @param fadeIn Fade in time for the title message in ticks. * @param stay Time in ticks the message stays floating on the screen * @param fadeOut Fade in time for the title message in ticks. * @param player The player the message has to be sent to. * Note that the player has to be a {@link Player} object or else it wont work. * * @return Title instance */ Title sendTitle(String titleMessage, int fadeIn, int stay, int fadeOut, Player player); /** * Send the players only the title message * * @param titleMessage The message to be sent to the player. * It has to be a string in raw JSON format. * You can use TextParser to build one if you want. * @param fadeIn Fade in time for the title message in ticks. * @param stay Time in ticks the message stays floating on the screen * @param fadeOut Fade in time for the title message in ticks. * @param players The players the message has to be sent to. * Note that the players have to be an array of {@link Player} object or else it wont work * * @return Title instance */ Title sendTitle(String titleMessage, int fadeIn, int stay, int fadeOut, Player[] players); /** * Send the players only the title message * * @param titleMessage The message to be sent to the player. * It has to be a string in raw JSON format. * You can use TextParser to build one if you want. * @param fadeIn Fade in time for the title message in ticks. * @param stay Time in ticks the message stays floating on the screen * @param fadeOut Fade in time for the title message in ticks. * @param players The players the message has to be sent to. * Note that the players have to be a collection of {@link Player} object or else it wont work * * @return Title instance */ Title sendTitle(String titleMessage, int fadeIn, int stay, int fadeOut, Collection<? extends Player> players); /** * Send the player only the subtitle message * * @param subtitleMessage The message to be sent to the player. * It has to be a string in raw JSON format. * You can use TextParser to build one if you want. * @param fadeIn Fade in time for the title message in ticks. * @param stay Time in ticks the message stays floating on the screen * @param fadeOut Fade in time for the title message in ticks. * @param player The player the message has to be sent to. * Note that the player has to be a {@link Player} object or else it wont work. * * @return Title instance */ Title sendSubtitle(String subtitleMessage, int fadeIn, int stay, int fadeOut, Player player); /** * Send the players only subtitle message * * @param subtitleMessage The message to be sent to the player. * It has to be a string in raw JSON format. * You can use TextParser to build one if you want. * @param fadeIn Fade in time for the title message in ticks. * @param stay Time in ticks the message stays floating on the screen * @param fadeOut Fade in time for the title message in ticks. * @param players The players the message has to be sent to. * Note that the players have to be an array of {@link Player} object or else it wont work * * @return Title instance */ Title sendSubtitle(String subtitleMessage, int fadeIn, int stay, int fadeOut, Player[] players); /** * Send the players only subtitle message * * @param subtitleMessage The message to be sent to the player. * It has to be a string in raw JSON format. * You can use TextParser to build one if you want. * @param fadeIn Fade in time for the title message in ticks. * @param stay Time in ticks the message stays floating on the screen * @param fadeOut Fade in time for the title message in ticks. * @param players The players the message has to be sent to. * Note that the players have to be a collection of {@link Player} object or else it wont work * * @return Title instance */ Title sendSubtitle(String subtitleMessage, int fadeIn, int stay, int fadeOut, Collection<? extends Player> players); Builder builder(NMSFetcher inmsFetcher); }
3e1b3cdd43f776aa134f63a62882c9eb7eed3de0
832
java
Java
swim-java/swim-runtime-java/swim-host-java/swim.api/src/main/java/swim/api/plane/Plane.java
swimos/swim
b403143d89d83e24a6bf842851bab57f1a1bc035
[ "Apache-2.0" ]
458
2019-02-19T14:04:55.000Z
2022-03-27T19:52:37.000Z
swim-java/swim-runtime-java/swim-host-java/swim.api/src/main/java/swim/api/plane/Plane.java
swimos/swim
b403143d89d83e24a6bf842851bab57f1a1bc035
[ "Apache-2.0" ]
57
2019-06-17T11:07:18.000Z
2021-12-21T12:47:53.000Z
swim-java/swim-runtime-java/swim-host-java/swim.api/src/main/java/swim/api/plane/Plane.java
swimos/swim
b403143d89d83e24a6bf842851bab57f1a1bc035
[ "Apache-2.0" ]
34
2019-02-21T02:47:34.000Z
2022-01-17T13:51:51.000Z
23.111111
75
0.722356
11,534
// Copyright 2015-2021 Swim Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package swim.api.plane; public interface Plane { PlaneContext planeContext(); void willStart(); void didStart(); void willStop(); void didStop(); void willClose(); void didClose(); void didFail(Throwable error); }
3e1b3d617eae6607d90163f1c3a8237d1e79359f
424
java
Java
src/main/java/com/coronaportal/services/IVaccineService.java
solvemate2018/coronaportal
bf5e2c9aad9ecad376c559325c5afaf7f2442231
[ "MIT" ]
null
null
null
src/main/java/com/coronaportal/services/IVaccineService.java
solvemate2018/coronaportal
bf5e2c9aad9ecad376c559325c5afaf7f2442231
[ "MIT" ]
null
null
null
src/main/java/com/coronaportal/services/IVaccineService.java
solvemate2018/coronaportal
bf5e2c9aad9ecad376c559325c5afaf7f2442231
[ "MIT" ]
null
null
null
22.315789
57
0.792453
11,535
package com.coronaportal.services; import com.coronaportal.models.TestResult; import com.coronaportal.models.Vaccine; import com.coronaportal.models.VaccineAppointment; import java.util.List; public interface IVaccineService { List<Vaccine> fetchVaccines(); List<Vaccine> fetchVaccines(int vaccine_center_id); void addVaccines(Vaccine vaccine); void useVaccine(String brand, int vaccine_center_id); }
3e1b3d70cc541e611d4c958b6fe7e07b3c8e907f
5,816
java
Java
aliyun-java-sdk-green/src/main/java/com/aliyuncs/green/model/v20170823/DescribeAuditContentRequest.java
cctvzd7/aliyun-openapi-java-sdk
b8e4dce2a61ca968615c9b910bedebaea71781ae
[ "Apache-2.0" ]
3
2020-04-26T09:15:45.000Z
2020-05-09T03:10:26.000Z
aliyun-java-sdk-green/src/main/java/com/aliyuncs/green/model/v20170823/DescribeAuditContentRequest.java
cctvzd7/aliyun-openapi-java-sdk
b8e4dce2a61ca968615c9b910bedebaea71781ae
[ "Apache-2.0" ]
27
2021-06-11T21:08:40.000Z
2022-03-11T21:25:09.000Z
aliyun-java-sdk-green/src/main/java/com/aliyuncs/green/model/v20170823/DescribeAuditContentRequest.java
cctvzd7/aliyun-openapi-java-sdk
b8e4dce2a61ca968615c9b910bedebaea71781ae
[ "Apache-2.0" ]
1
2020-03-05T07:30:16.000Z
2020-03-05T07:30:16.000Z
21.072464
118
0.691713
11,536
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aliyuncs.green.model.v20170823; import com.aliyuncs.RpcAcsRequest; import com.aliyuncs.http.MethodType; import com.aliyuncs.green.Endpoint; /** * @author auto create * @version */ public class DescribeAuditContentRequest extends RpcAcsRequest<DescribeAuditContentResponse> { private String imageId; private String startDate; private String scene; private String sourceIp; private String libType; private String auditResult; private Integer pageSize; private String lang; private String taskId; private Integer totalCount; private String keywordId; private String suggestion; private Integer currentPage; private String label; private String resourceType; private String bizType; private String endDate; private String dataId; public DescribeAuditContentRequest() { super("Green", "2017-08-23", "DescribeAuditContent", "green"); setMethod(MethodType.POST); try { com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointMap").set(this, Endpoint.endpointMap); com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointRegional").set(this, Endpoint.endpointRegionalType); } catch (Exception e) {} } public String getImageId() { return this.imageId; } public void setImageId(String imageId) { this.imageId = imageId; if(imageId != null){ putQueryParameter("ImageId", imageId); } } public String getStartDate() { return this.startDate; } public void setStartDate(String startDate) { this.startDate = startDate; if(startDate != null){ putQueryParameter("StartDate", startDate); } } public String getScene() { return this.scene; } public void setScene(String scene) { this.scene = scene; if(scene != null){ putQueryParameter("Scene", scene); } } public String getSourceIp() { return this.sourceIp; } public void setSourceIp(String sourceIp) { this.sourceIp = sourceIp; if(sourceIp != null){ putQueryParameter("SourceIp", sourceIp); } } public String getLibType() { return this.libType; } public void setLibType(String libType) { this.libType = libType; if(libType != null){ putQueryParameter("LibType", libType); } } public String getAuditResult() { return this.auditResult; } public void setAuditResult(String auditResult) { this.auditResult = auditResult; if(auditResult != null){ putQueryParameter("AuditResult", auditResult); } } public Integer getPageSize() { return this.pageSize; } public void setPageSize(Integer pageSize) { this.pageSize = pageSize; if(pageSize != null){ putQueryParameter("PageSize", pageSize.toString()); } } public String getLang() { return this.lang; } public void setLang(String lang) { this.lang = lang; if(lang != null){ putQueryParameter("Lang", lang); } } public String getTaskId() { return this.taskId; } public void setTaskId(String taskId) { this.taskId = taskId; if(taskId != null){ putQueryParameter("TaskId", taskId); } } public Integer getTotalCount() { return this.totalCount; } public void setTotalCount(Integer totalCount) { this.totalCount = totalCount; if(totalCount != null){ putQueryParameter("TotalCount", totalCount.toString()); } } public String getKeywordId() { return this.keywordId; } public void setKeywordId(String keywordId) { this.keywordId = keywordId; if(keywordId != null){ putQueryParameter("KeywordId", keywordId); } } public String getSuggestion() { return this.suggestion; } public void setSuggestion(String suggestion) { this.suggestion = suggestion; if(suggestion != null){ putQueryParameter("Suggestion", suggestion); } } public Integer getCurrentPage() { return this.currentPage; } public void setCurrentPage(Integer currentPage) { this.currentPage = currentPage; if(currentPage != null){ putQueryParameter("CurrentPage", currentPage.toString()); } } public String getLabel() { return this.label; } public void setLabel(String label) { this.label = label; if(label != null){ putQueryParameter("Label", label); } } public String getResourceType() { return this.resourceType; } public void setResourceType(String resourceType) { this.resourceType = resourceType; if(resourceType != null){ putQueryParameter("ResourceType", resourceType); } } public String getBizType() { return this.bizType; } public void setBizType(String bizType) { this.bizType = bizType; if(bizType != null){ putQueryParameter("BizType", bizType); } } public String getEndDate() { return this.endDate; } public void setEndDate(String endDate) { this.endDate = endDate; if(endDate != null){ putQueryParameter("EndDate", endDate); } } public String getDataId() { return this.dataId; } public void setDataId(String dataId) { this.dataId = dataId; if(dataId != null){ putQueryParameter("DataId", dataId); } } @Override public Class<DescribeAuditContentResponse> getResponseClass() { return DescribeAuditContentResponse.class; } }
3e1b3f212c1d4f220daa8fffab5b8fc89e9def5c
131
java
Java
AULA 04/checkBox/src/checkbox/testaTela.java
Ner3s/Programacao-II
9b17834a310f561247c6e528fa3ecdc7cb6d1df3
[ "MIT" ]
1
2020-12-14T03:30:34.000Z
2020-12-14T03:30:34.000Z
AULA 04/checkBox/src/checkbox/testaTela.java
Ner3s/Programacao-II
9b17834a310f561247c6e528fa3ecdc7cb6d1df3
[ "MIT" ]
null
null
null
AULA 04/checkBox/src/checkbox/testaTela.java
Ner3s/Programacao-II
9b17834a310f561247c6e528fa3ecdc7cb6d1df3
[ "MIT" ]
null
null
null
16.375
45
0.572519
11,537
package checkbox; public class testaTela { public static void main(String[] args) { new boxBoox(); } }
3e1b3fc002138e210e09c4ffaec813db1d48de9f
3,839
java
Java
components/osgi-tests/src/test/java/org/wso2/carbon/analytics/test/osgi/util/TestUtil.java
NisalaNiroshana/carbon-analytics
39667711453717f856b9cbefb363af3c0c3a9d46
[ "Apache-2.0" ]
null
null
null
components/osgi-tests/src/test/java/org/wso2/carbon/analytics/test/osgi/util/TestUtil.java
NisalaNiroshana/carbon-analytics
39667711453717f856b9cbefb363af3c0c3a9d46
[ "Apache-2.0" ]
null
null
null
components/osgi-tests/src/test/java/org/wso2/carbon/analytics/test/osgi/util/TestUtil.java
NisalaNiroshana/carbon-analytics
39667711453717f856b9cbefb363af3c0c3a9d46
[ "Apache-2.0" ]
null
null
null
39.989583
119
0.647825
11,538
/* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.carbon.analytics.test.osgi.util; import io.netty.handler.codec.http.HttpMethod; import java.io.IOException; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URI; import java.net.URL; /** * Util class for test cases. */ public class TestUtil { private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(TestUtil.class); public static HTTPResponseMessage sendHRequest(String body, URI baseURI, String path, String contentType, String methodType, Boolean auth, String userName, String password) { try { HttpURLConnection urlConn = null; try { urlConn = TestUtil.generateRequest(baseURI, path, methodType, false); } catch (IOException e) { TestUtil.handleException("IOException occurred while running the HttpsSourceTestCaseForSSL", e); } if (auth) { TestUtil.setHeader(urlConn, "Authorization", "Basic " + java.util.Base64.getEncoder(). encodeToString((userName + ":" + password).getBytes())); } if (contentType != null) { TestUtil.setHeader(urlConn, "Content-Type", contentType); } TestUtil.setHeader(urlConn, "HTTP_METHOD", methodType); if (methodType.equals(HttpMethod.POST.name()) || methodType.equals(HttpMethod.PUT.name())) { TestUtil.writeContent(urlConn, body); } assert urlConn != null; HTTPResponseMessage httpResponseMessage = new HTTPResponseMessage(urlConn.getResponseCode(), urlConn.getContentType(), urlConn.getResponseMessage()); urlConn.disconnect(); return httpResponseMessage; } catch (IOException e) { TestUtil.handleException("IOException occurred while running the HttpsSourceTestCaseForSSL", e); } return new HTTPResponseMessage(); } private static void writeContent(HttpURLConnection urlConn, String content) throws IOException { OutputStreamWriter out = new OutputStreamWriter( urlConn.getOutputStream()); out.write(content); out.close(); } private static HttpURLConnection generateRequest(URI baseURI, String path, String method, boolean keepAlive) throws IOException { URL url = baseURI.resolve(path).toURL(); HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); urlConn.setRequestMethod(method); if (method.equals(HttpMethod.POST.name()) || method.equals(HttpMethod.PUT.name())) { urlConn.setDoOutput(true); } if (keepAlive) { urlConn.setRequestProperty("Connection", "Keep-Alive"); } return urlConn; } private static void setHeader(HttpURLConnection urlConnection, String key, String value) { urlConnection.setRequestProperty(key, value); } private static void handleException(String msg, Exception ex) { logger.error(msg, ex); } }
3e1b3ff5e960f830bf8f953d158b740d7721e10c
212
java
Java
mobile_app1/module1090/src/main/java/module1090packageJava0/Foo4.java
HiWong/android-build-eval
d909ab37bc8d5d3a188ba9c9f0855f846f6f3af6
[ "Apache-2.0" ]
70
2021-01-22T16:48:06.000Z
2022-02-16T10:37:33.000Z
mobile_app1/module1090/src/main/java/module1090packageJava0/Foo4.java
HiWong/android-build-eval
d909ab37bc8d5d3a188ba9c9f0855f846f6f3af6
[ "Apache-2.0" ]
16
2021-01-22T20:52:52.000Z
2021-08-09T17:51:24.000Z
mobile_app1/module1090/src/main/java/module1090packageJava0/Foo4.java
HiWong/android-build-eval
d909ab37bc8d5d3a188ba9c9f0855f846f6f3af6
[ "Apache-2.0" ]
5
2021-01-26T13:53:49.000Z
2021-08-11T20:10:57.000Z
13.25
45
0.665094
11,539
package module1090packageJava0; import java.lang.Integer; public class Foo4 { Integer int0; public void foo0() { new module1090packageJava0.Foo3().foo1(); } public void foo1() { foo0(); } }
3e1b4012e87e2381ec253ff9c6d48106b604c7ac
804
java
Java
org.osgi.impl.bundle.annotations/src/org/osgi/impl/bundle/annotations/header/HeaderClass.java
meKokabi/osgi
063c29cb12eadaab59df75dfa967978c8052c4da
[ "Apache-2.0" ]
null
null
null
org.osgi.impl.bundle.annotations/src/org/osgi/impl/bundle/annotations/header/HeaderClass.java
meKokabi/osgi
063c29cb12eadaab59df75dfa967978c8052c4da
[ "Apache-2.0" ]
null
null
null
org.osgi.impl.bundle.annotations/src/org/osgi/impl/bundle/annotations/header/HeaderClass.java
meKokabi/osgi
063c29cb12eadaab59df75dfa967978c8052c4da
[ "Apache-2.0" ]
null
null
null
29.777778
75
0.731343
11,540
/* * Copyright (c) OSGi Alliance (2018). All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.osgi.impl.bundle.annotations.header; import org.osgi.annotation.bundle.Header; @Header(name = "FooClass", value = "bar-class") public class HeaderClass { // }
3e1b40278484e3030466c60372fbf136bbccbde3
308
java
Java
alica-plan-designer-fx-modelmanagement/src/main/java/de/unikassel/vs/alica/planDesigner/events/ModelEventType.java
alica-labs/alica-plan-designer-fx
0c8dbe1df3f3f72fc2262aebd4349dde730723d1
[ "MIT" ]
4
2019-04-02T14:42:19.000Z
2019-10-26T11:12:53.000Z
alica-plan-designer-fx-modelmanagement/src/main/java/de/unikassel/vs/alica/planDesigner/events/ModelEventType.java
alica-labs/alica-plan-designer-fx
0c8dbe1df3f3f72fc2262aebd4349dde730723d1
[ "MIT" ]
113
2018-11-26T10:39:31.000Z
2022-01-04T16:32:39.000Z
alica-plan-designer-fx-modelmanagement/src/main/java/de/unikassel/vs/alica/planDesigner/events/ModelEventType.java
alica-labs/alica-plan-designer-fx
0c8dbe1df3f3f72fc2262aebd4349dde730723d1
[ "MIT" ]
6
2019-04-08T18:33:07.000Z
2022-02-16T20:26:58.000Z
51.333333
224
0.86039
11,541
package de.unikassel.vs.alica.planDesigner.events; public enum ModelEventType { ELEMENT_FOLDER_DELETED, ELEMENT_CREATED, ELEMENT_ATTRIBUTE_CHANGED, ELEMENT_DELETED, ELEMENT_PARSED, ELEMENT_SERIALIZED, ELEMENT_ADDED, ELEMENT_REMOVED, ELEMENT_CONNECTED, ELEMENT_DISCONNECTED, ELEMENT_CHANGED_POSITION; }
3e1b40e06f62c43c3f44cc49aacda43787255971
4,823
java
Java
app/src/main/java/com/ckr/collapsingrefresh/view/TwoFragment.java
ckrgithub/CollapsingRefresh
f152a6f4a653e05448462d83b19b023f3dc15ff1
[ "Apache-2.0" ]
74
2018-03-12T15:27:13.000Z
2021-12-15T09:39:06.000Z
app/src/main/java/com/ckr/collapsingrefresh/view/TwoFragment.java
ckrgithub/CollapsingRefresh
f152a6f4a653e05448462d83b19b023f3dc15ff1
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/ckr/collapsingrefresh/view/TwoFragment.java
ckrgithub/CollapsingRefresh
f152a6f4a653e05448462d83b19b023f3dc15ff1
[ "Apache-2.0" ]
11
2018-03-14T02:29:46.000Z
2020-08-04T06:25:46.000Z
26.355191
140
0.74435
11,542
package com.ckr.collapsingrefresh.view; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.support.design.widget.AppBarLayout; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import com.ckr.collapsingrefresh.R; import com.ckr.collapsingrefresh.adapter.MyAdapter; import com.ckr.collapsingrefresh.model.AlbumList; import com.ckr.behavior.SmoothRecyclerView; import com.ckr.behavior.listener.OnSmoothScrollListener; import com.scwang.smartrefresh.SmartRefreshLayout; import com.scwang.smartrefresh.api.RefreshLayout; import com.ckr.behavior.listener.OnOffsetListener; import com.scwang.smartrefresh.listener.OnRefreshLoadmoreListener; import com.ckr.behavior.util.RefreshLog; import java.util.ArrayList; import java.util.List; import butterknife.BindDimen; import butterknife.BindView; import static com.ckr.behavior.util.RefreshLog.Logd; /** * Created by PC大佬 on 2018/2/9. */ public class TwoFragment extends BaseFragment implements OnRefreshLoadmoreListener, AppBarLayout.OnOffsetChangedListener, OnOffsetListener { private static final String TAG = "TwoFragment"; @BindView(R.id.recyclerView) SmoothRecyclerView recyclerView; @BindView(R.id.refreshLayout) SmartRefreshLayout smartRefreshLayout; @BindDimen(R.dimen.size_5) int paddingSize; private MyAdapter mAdapter; static OnSmoothScrollListener scrollListener; private boolean isVisible; private Handler handler = new Handler(Looper.myLooper()); private int verticalOffset; public static TwoFragment newInstance(OnSmoothScrollListener onScrollListener) { scrollListener = onScrollListener; Bundle args = new Bundle(); TwoFragment fragment = new TwoFragment(); fragment.setArguments(args); return fragment; } @Override protected int getContentLayoutId() { return R.layout.fragment_base; } @Override public void onDestroy() { super.onDestroy(); if (handler != null) { handler = null; } if (scrollListener != null) { scrollListener.removeOnOffsetChangedListener(this); } } @Override protected void init() { RefreshLog.Logd(TAG, "init: target:" + recyclerView); scrollListener.addOnOffsetChangedListener(this); recyclerView.setOnSmoothScrollListener(scrollListener); smartRefreshLayout.setOnRefreshLoadmoreListener(this); smartRefreshLayout.setOnCollapsingListener(this); setAdapter(); } protected void setAdapter() { mAdapter = new MyAdapter(getContext()); LinearLayoutManager layout = new LinearLayoutManager(getContext()); layout.setSmoothScrollbarEnabled(true); layout.setAutoMeasureEnabled(true); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setLayoutManager(layout); recyclerView.setAdapter(mAdapter); initData(); } private void initData() { List<AlbumList> datas = new ArrayList<>(); AlbumList albumList = new AlbumList(); albumList.setTitle("约定"); try { for (int i = 0; i < 12; i++) { AlbumList clone = (AlbumList) albumList.clone(); clone.setUserName("item " + i); if (i % 2 == 0) { clone.setDrawableId(R.mipmap.banner2); albumList.setType(0); } else { clone.setDrawableId(R.mipmap.banner); albumList.setType(1); } datas.add(clone); } } catch (CloneNotSupportedException e) { e.printStackTrace(); } mAdapter.updateAll(datas); } @Override protected void onVisible() { isVisible = true; } @Override protected void onInvisible() { isVisible = false; } @Override public void refreshFragment() { RefreshLog.Logd(TAG, "refreshFragment: isVisible:" + isVisible); } @Override public void onRefresh(RefreshLayout refreshlayout) { if (handler != null) { handler.postDelayed(new Runnable() { @Override public void run() { if (smartRefreshLayout != null) { smartRefreshLayout.finishRefresh(); } } }, 2000); } } @Override public void onLoadmore(RefreshLayout refreshlayout) { if (handler != null) { handler.postDelayed(new Runnable() { @Override public void run() { if (smartRefreshLayout != null) { smartRefreshLayout.finishLoadmore(); } } }, 2000); } } @Override public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) { this.verticalOffset = verticalOffset; Logd(TAG, "onOffsetChanged: verticalOffset:" + this.verticalOffset); if (verticalOffset != 0) { boolean enableRefresh = smartRefreshLayout.isEnableRefresh(); if (enableRefresh) { smartRefreshLayout.setEnableRefresh(false); } } else { smartRefreshLayout.setEnableRefresh(true); } } @Override public int getTotalRange() { return scrollListener == null ? 0 : scrollListener.getTotalRange(); } @Override public int getCurrentOffset() { return verticalOffset; } }
3e1b42e4fa2902d3aa3ae05981827146f1e61b2d
36,214
java
Java
src/src/sun/util/resources/cldr/ext/CurrencyNames_ja.java
HurleyWong/RTFSC-JDK
9bb72042116ff3dbb8f71c2372c8697629f4d730
[ "MIT" ]
null
null
null
src/src/sun/util/resources/cldr/ext/CurrencyNames_ja.java
HurleyWong/RTFSC-JDK
9bb72042116ff3dbb8f71c2372c8697629f4d730
[ "MIT" ]
null
null
null
src/src/sun/util/resources/cldr/ext/CurrencyNames_ja.java
HurleyWong/RTFSC-JDK
9bb72042116ff3dbb8f71c2372c8697629f4d730
[ "MIT" ]
null
null
null
54.786687
161
0.506821
11,543
/* * Copyright (c) 2012, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * COPYRIGHT AND PERMISSION NOTICE * * Copyright (C) 1991-2016 Unicode, Inc. All rights reserved. * Distributed under the Terms of Use in * http://www.unicode.org/copyright.html. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of the Unicode data files and any associated documentation * (the "Data Files") or Unicode software and any associated documentation * (the "Software") to deal in the Data Files or Software * without restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, and/or sell copies of * the Data Files or Software, and to permit persons to whom the Data Files * or Software are furnished to do so, provided that * (a) this copyright and permission notice appear with all copies * of the Data Files or Software, * (b) this copyright and permission notice appear in associated * documentation, and * (c) there is clear notice in each modified Data File or in the Software * as well as in the documentation associated with the Data File(s) or * Software that the data or software has been modified. * * THE DATA FILES AND SOFTWARE ARE 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 OF THIRD PARTY RIGHTS. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS * NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL * DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THE DATA FILES OR SOFTWARE. * * Except as contained in this notice, the name of a copyright holder * shall not be used in advertising or otherwise to promote the sale, * use or other dealings in these Data Files or Software without prior * written authorization of the copyright holder. */ package sun.util.resources.cldr.ext; import sun.util.resources.OpenListResourceBundle; public class CurrencyNames_ja extends OpenListResourceBundle { @Override protected final Object[][] getContents() { final Object[][] data = new Object[][] { { "ADP", "ADP" }, { "AED", "AED" }, { "AFA", "AFA" }, { "AFN", "AFN" }, { "ALK", "ALK" }, { "ALL", "ALL" }, { "AMD", "AMD" }, { "ANG", "ANG" }, { "AOA", "AOA" }, { "AOK", "AOK" }, { "AON", "AON" }, { "AOR", "AOR" }, { "ARA", "ARA" }, { "ARL", "ARL" }, { "ARM", "ARM" }, { "ARP", "ARP" }, { "ARS", "ARS" }, { "ATS", "ATS" }, { "AWG", "AWG" }, { "AZM", "AZM" }, { "AZN", "AZN" }, { "BAD", "BAD" }, { "BAM", "BAM" }, { "BAN", "BAN" }, { "BBD", "BBD" }, { "BDT", "BDT" }, { "BEC", "BEC" }, { "BEF", "BEF" }, { "BEL", "BEL" }, { "BGL", "BGL" }, { "BGM", "BGM" }, { "BGN", "BGN" }, { "BGO", "BGO" }, { "BHD", "BHD" }, { "BIF", "BIF" }, { "BMD", "BMD" }, { "BND", "BND" }, { "BOB", "BOB" }, { "BOL", "BOL" }, { "BOP", "BOP" }, { "BOV", "BOV" }, { "BRB", "BRB" }, { "BRC", "BRC" }, { "BRE", "BRE" }, { "BRN", "BRN" }, { "BRR", "BRR" }, { "BRZ", "BRZ" }, { "BSD", "BSD" }, { "BTN", "BTN" }, { "BUK", "BUK" }, { "BWP", "BWP" }, { "BYB", "BYB" }, { "BYN", "BYN" }, { "BYR", "BYR" }, { "BZD", "BZD" }, { "CDF", "CDF" }, { "CHE", "CHE" }, { "CHF", "CHF" }, { "CHW", "CHW" }, { "CLE", "CLE" }, { "CLF", "CLF" }, { "CLP", "CLP" }, { "CNH", "CNH" }, { "CNX", "CNX" }, { "CNY", "\u5143" }, { "COP", "COP" }, { "COU", "COU" }, { "CRC", "CRC" }, { "CSD", "CSD" }, { "CSK", "CSK" }, { "CUC", "CUC" }, { "CUP", "CUP" }, { "CVE", "CVE" }, { "CYP", "CYP" }, { "CZK", "CZK" }, { "DDM", "DDM" }, { "DEM", "DEM" }, { "DJF", "DJF" }, { "DKK", "DKK" }, { "DOP", "DOP" }, { "DZD", "DZD" }, { "ECS", "ECS" }, { "ECV", "ECV" }, { "EEK", "EEK" }, { "EGP", "EGP" }, { "ERN", "ERN" }, { "ESA", "ESA" }, { "ESB", "ESB" }, { "ESP", "ESP" }, { "ETB", "ETB" }, { "FIM", "FIM" }, { "FJD", "FJD" }, { "FKP", "FKP" }, { "FRF", "FRF" }, { "GEK", "GEK" }, { "GEL", "GEL" }, { "GHC", "GHC" }, { "GHS", "GHS" }, { "GIP", "GIP" }, { "GMD", "GMD" }, { "GNF", "GNF" }, { "GNS", "GNS" }, { "GQE", "GQE" }, { "GRD", "GRD" }, { "GTQ", "GTQ" }, { "GWE", "GWE" }, { "GWP", "GWP" }, { "GYD", "GYD" }, { "HNL", "HNL" }, { "HRD", "HRD" }, { "HRK", "HRK" }, { "HTG", "HTG" }, { "HUF", "HUF" }, { "IDR", "IDR" }, { "IEP", "IEP" }, { "ILP", "ILP" }, { "ILR", "ILR" }, { "IQD", "IQD" }, { "IRR", "IRR" }, { "ISJ", "ISJ" }, { "ISK", "ISK" }, { "ITL", "ITL" }, { "JMD", "JMD" }, { "JOD", "JOD" }, { "JPY", "\uffe5" }, { "KES", "KES" }, { "KGS", "KGS" }, { "KHR", "KHR" }, { "KMF", "KMF" }, { "KPW", "KPW" }, { "KRH", "KRH" }, { "KRO", "KRO" }, { "KWD", "KWD" }, { "KYD", "KYD" }, { "KZT", "KZT" }, { "LAK", "LAK" }, { "LBP", "LBP" }, { "LKR", "LKR" }, { "LRD", "LRD" }, { "LSL", "LSL" }, { "LTL", "LTL" }, { "LTT", "LTT" }, { "LUC", "LUC" }, { "LUF", "LUF" }, { "LUL", "LUL" }, { "LVL", "LVL" }, { "LVR", "LVR" }, { "LYD", "LYD" }, { "MAD", "MAD" }, { "MAF", "MAF" }, { "MCF", "MCF" }, { "MDC", "MDC" }, { "MDL", "MDL" }, { "MGA", "MGA" }, { "MGF", "MGF" }, { "MKD", "MKD" }, { "MKN", "MKN" }, { "MLF", "MLF" }, { "MMK", "MMK" }, { "MNT", "MNT" }, { "MOP", "MOP" }, { "MRO", "MRO" }, { "MTL", "MTL" }, { "MTP", "MTP" }, { "MUR", "MUR" }, { "MVP", "MVP" }, { "MVR", "MVR" }, { "MWK", "MWK" }, { "MXP", "MXP" }, { "MXV", "MXV" }, { "MYR", "MYR" }, { "MZE", "MZE" }, { "MZM", "MZM" }, { "MZN", "MZN" }, { "NAD", "NAD" }, { "NGN", "NGN" }, { "NIC", "NIC" }, { "NIO", "NIO" }, { "NLG", "NLG" }, { "NOK", "NOK" }, { "NPR", "NPR" }, { "OMR", "OMR" }, { "PAB", "PAB" }, { "PEI", "PEI" }, { "PEN", "PEN" }, { "PES", "PES" }, { "PGK", "PGK" }, { "PHP", "PHP" }, { "PKR", "PKR" }, { "PLN", "PLN" }, { "PLZ", "PLZ" }, { "PTE", "PTE" }, { "PYG", "PYG" }, { "QAR", "QAR" }, { "RHD", "RHD" }, { "ROL", "ROL" }, { "RON", "RON" }, { "RSD", "RSD" }, { "RUB", "RUB" }, { "RUR", "RUR" }, { "RWF", "RWF" }, { "SAR", "SAR" }, { "SBD", "SBD" }, { "SCR", "SCR" }, { "SDD", "SDD" }, { "SDG", "SDG" }, { "SDP", "SDP" }, { "SEK", "SEK" }, { "SGD", "SGD" }, { "SHP", "SHP" }, { "SIT", "SIT" }, { "SKK", "SKK" }, { "SLL", "SLL" }, { "SOS", "SOS" }, { "SRD", "SRD" }, { "SRG", "SRG" }, { "SSP", "SSP" }, { "STD", "STD" }, { "SUR", "SUR" }, { "SVC", "SVC" }, { "SYP", "SYP" }, { "SZL", "SZL" }, { "THB", "THB" }, { "TJR", "TJR" }, { "TJS", "TJS" }, { "TMM", "TMM" }, { "TMT", "TMT" }, { "TND", "TND" }, { "TOP", "TOP" }, { "TPE", "TPE" }, { "TRL", "TRL" }, { "TRY", "TRY" }, { "TTD", "TTD" }, { "TZS", "TZS" }, { "UAH", "UAH" }, { "UAK", "UAK" }, { "UGS", "UGS" }, { "UGX", "UGX" }, { "USD", "$" }, { "USN", "USN" }, { "USS", "USS" }, { "UYI", "UYI" }, { "UYP", "UYP" }, { "UYU", "UYU" }, { "UZS", "UZS" }, { "VEB", "VEB" }, { "VEF", "VEF" }, { "VNN", "VNN" }, { "VUV", "VUV" }, { "WST", "WST" }, { "XAG", "XAG" }, { "XAU", "XAU" }, { "XBA", "XBA" }, { "XBB", "XBB" }, { "XBC", "XBC" }, { "XBD", "XBD" }, { "XDR", "XDR" }, { "XEU", "XEU" }, { "XFO", "XFO" }, { "XFU", "XFU" }, { "XPD", "XPD" }, { "XPT", "XPT" }, { "XRE", "XRE" }, { "XSU", "XSU" }, { "XTS", "XTS" }, { "XUA", "XUA" }, { "XXX", "XXX" }, { "YDD", "YDD" }, { "YER", "YER" }, { "YUD", "YUD" }, { "YUM", "YUM" }, { "YUN", "YUN" }, { "YUR", "YUR" }, { "ZAL", "ZAL" }, { "ZAR", "ZAR" }, { "ZMK", "ZMK" }, { "ZMW", "ZMW" }, { "ZRN", "ZRN" }, { "ZRZ", "ZRZ" }, { "ZWD", "ZWD" }, { "ZWL", "ZWL" }, { "ZWR", "ZWR" }, { "adp", "\u30a2\u30f3\u30c9\u30e9 \u30da\u30bb\u30bf" }, { "aed", "\u30a2\u30e9\u30d6\u9996\u9577\u56fd\u9023\u90a6\u30c7\u30a3\u30eb\u30cf\u30e0" }, { "afa", "\u30a2\u30d5\u30ac\u30cb\u30b9\u30bf\u30f3 \u30a2\u30d5\u30ac\u30cb\u30fc (1927\u20132002)" }, { "afn", "\u30a2\u30d5\u30ac\u30cb\u30b9\u30bf\u30f3 \u30a2\u30d5\u30ac\u30cb\u30fc" }, { "alk", "\u30a2\u30eb\u30d0\u30cb\u30a2 \u30ec\u30af (1946\u20131965)" }, { "all", "\u30a2\u30eb\u30d0\u30cb\u30a2 \u30ec\u30af" }, { "amd", "\u30a2\u30eb\u30e1\u30cb\u30a2 \u30c9\u30e9\u30e0" }, { "ang", "\u30aa\u30e9\u30f3\u30c0\u9818\u30a2\u30f3\u30c6\u30a3\u30eb \u30ae\u30eb\u30c0\u30fc" }, { "aoa", "\u30a2\u30f3\u30b4\u30e9 \u30af\u30ef\u30f3\u30b6" }, { "aok", "\u30a2\u30f3\u30b4\u30e9 \u30af\u30ef\u30f3\u30b6 (1977\u20131991)" }, { "aon", "\u30a2\u30f3\u30b4\u30e9 \u65b0\u30af\u30ef\u30f3\u30b6 (1990\u20132000)" }, { "aor", "\u30a2\u30f3\u30b4\u30e9 \u65e7\u30af\u30ef\u30f3\u30b6 (1995\u20131999)" }, { "ara", "\u30a2\u30eb\u30bc\u30f3\u30c1\u30f3 \u30a2\u30a5\u30b9\u30c8\u30e9\u30fc\u30eb" }, { "arl", "\u30a2\u30eb\u30bc\u30f3\u30c1\u30f3\u30fb\u30da\u30bd\u30fb\u30ec\u30a4\uff081970\u20131983\uff09" }, { "arm", "\u30a2\u30eb\u30bc\u30f3\u30c1\u30f3\u30fb\u30da\u30bd\uff081881\u20131970\uff09" }, { "arp", "\u30a2\u30eb\u30bc\u30f3\u30c1\u30f3 \u30da\u30bd (1983\u20131985)" }, { "ars", "\u30a2\u30eb\u30bc\u30f3\u30c1\u30f3 \u30da\u30bd" }, { "ats", "\u30aa\u30fc\u30b9\u30c8\u30ea\u30a2 \u30b7\u30ea\u30f3\u30b0" }, { "aud", "\u30aa\u30fc\u30b9\u30c8\u30e9\u30ea\u30a2 \u30c9\u30eb" }, { "awg", "\u30a2\u30eb\u30d0 \u30ae\u30eb\u30c0\u30fc" }, { "azm", "\u30a2\u30bc\u30eb\u30d0\u30a4\u30b8\u30e3\u30f3 \u30de\u30ca\u30c8 (1993\u20132006)" }, { "azn", "\u30a2\u30bc\u30eb\u30d0\u30a4\u30b8\u30e3\u30f3 \u30de\u30ca\u30c8" }, { "bad", "\u30dc\u30b9\u30cb\u30a2\u30fb\u30d8\u30eb\u30c4\u30a7\u30b4\u30d3\u30ca \u30c7\u30a3\u30ca\u30fc\u30eb (1992\u20131994)" }, { "bam", "\u30dc\u30b9\u30cb\u30a2\u30fb\u30d8\u30eb\u30c4\u30a7\u30b4\u30d3\u30ca \u514c\u63db\u30de\u30eb\u30af (BAM)" }, { "ban", "\u30dc\u30b9\u30cb\u30a2\u30fb\u30d8\u30eb\u30c4\u30a7\u30b4\u30d3\u30ca \u65b0\u30c7\u30a3\u30ca\u30fc\u30eb\uff081994\u20131997\uff09" }, { "bbd", "\u30d0\u30eb\u30d0\u30c9\u30b9 \u30c9\u30eb" }, { "bdt", "\u30d0\u30f3\u30b0\u30e9\u30c7\u30b7\u30e5 \u30bf\u30ab" }, { "bec", "\u30d9\u30eb\u30ae\u30fc \u30d5\u30e9\u30f3 (BEC)" }, { "bef", "\u30d9\u30eb\u30ae\u30fc \u30d5\u30e9\u30f3" }, { "bel", "\u30d9\u30eb\u30ae\u30fc \u30d5\u30e9\u30f3 (BEL)" }, { "bgl", "\u30d6\u30eb\u30ac\u30ea\u30a2 \u30ec\u30d5" }, { "bgm", "\u30d6\u30eb\u30ac\u30ea\u30a2\u793e\u4f1a\u4e3b\u7fa9 \u30ec\u30d5" }, { "bgn", "\u30d6\u30eb\u30ac\u30ea\u30a2 \u65b0\u30ec\u30d5" }, { "bgo", "\u30d6\u30eb\u30ac\u30ea\u30a2 \u30ec\u30d5\uff081879\u20131952\uff09" }, { "bhd", "\u30d0\u30fc\u30ec\u30fc\u30f3 \u30c7\u30a3\u30ca\u30fc\u30eb" }, { "bif", "\u30d6\u30eb\u30f3\u30b8 \u30d5\u30e9\u30f3" }, { "bmd", "\u30d0\u30df\u30e5\u30fc\u30c0 \u30c9\u30eb" }, { "bnd", "\u30d6\u30eb\u30cd\u30a4 \u30c9\u30eb" }, { "bob", "\u30dc\u30ea\u30d3\u30a2 \u30dc\u30ea\u30d3\u30a2\u30fc\u30ce" }, { "bol", "\u30dc\u30ea\u30d3\u30a2 \u30dc\u30ea\u30d3\u30a2\u30fc\u30ce (1863\u20131963)" }, { "bop", "\u30dc\u30ea\u30d3\u30a2 \u30da\u30bd" }, { "bov", "\u30dc\u30ea\u30d3\u30a2 (Mvdol)" }, { "brb", "\u30d6\u30e9\u30b8\u30eb \u65b0\u30af\u30eb\u30bc\u30a4\u30ed (1967\u20131986)" }, { "brc", "\u30d6\u30e9\u30b8\u30eb \u30af\u30eb\u30b6\u30fc\u30c9 (1986\u20131989)" }, { "bre", "\u30d6\u30e9\u30b8\u30eb \u30af\u30eb\u30bc\u30a4\u30ed (1990\u20131993)" }, { "brl", "\u30d6\u30e9\u30b8\u30eb \u30ec\u30a2\u30eb" }, { "brn", "\u30d6\u30e9\u30b8\u30eb \u65b0\u30af\u30eb\u30b6\u30fc\u30c9 (1989\u20131990)" }, { "brr", "\u30d6\u30e9\u30b8\u30eb \u30af\u30eb\u30bc\u30a4\u30ed (1993\u20131994)" }, { "brz", "\u30d6\u30e9\u30b8\u30eb \u30af\u30eb\u30bc\u30a4\u30ed\uff081942\u20131967\uff09" }, { "bsd", "\u30d0\u30cf\u30de \u30c9\u30eb" }, { "btn", "\u30d6\u30fc\u30bf\u30f3 \u30cb\u30e5\u30eb\u30bf\u30e0" }, { "buk", "\u30d3\u30eb\u30de \u30c1\u30e3\u30c3\u30c8" }, { "bwp", "\u30dc\u30c4\u30ef\u30ca \u30d7\u30e9" }, { "byb", "\u30d9\u30e9\u30eb\u30fc\u30b7 \u65b0\u30eb\u30fc\u30d6\u30eb (1994\u20131999)" }, { "byn", "\u30d9\u30e9\u30eb\u30fc\u30b7 \u30eb\u30fc\u30d6\u30eb" }, { "byr", "\u30d9\u30e9\u30eb\u30fc\u30b7 \u30eb\u30fc\u30d6\u30eb (2000\u20132016)" }, { "bzd", "\u30d9\u30ea\u30fc\u30ba \u30c9\u30eb" }, { "cad", "\u30ab\u30ca\u30c0 \u30c9\u30eb" }, { "cdf", "\u30b3\u30f3\u30b4 \u30d5\u30e9\u30f3" }, { "che", "\u30e6\u30fc\u30ed (WIR)" }, { "chf", "\u30b9\u30a4\u30b9 \u30d5\u30e9\u30f3" }, { "chw", "\u30d5\u30e9\u30f3 (WIR)" }, { "cle", "\u30c1\u30ea \u30a8\u30b9\u30af\u30fc\u30c9" }, { "clf", "\u30c1\u30ea \u30a6\u30cb\u30c0\u30fb\u30c7\u30fb\u30d5\u30a9\u30e1\u30f3\u30c8 (UF)" }, { "clp", "\u30c1\u30ea \u30da\u30bd" }, { "cnh", "\u4e2d\u56fd\u4eba\u6c11\u5143(\u30aa\u30d5\u30b7\u30e7\u30a2)" }, { "cnx", "\u4e2d\u56fd\u4eba\u6c11\u9280\u884c\u30c9\u30eb" }, { "cny", "\u4e2d\u56fd\u4eba\u6c11\u5143" }, { "cop", "\u30b3\u30ed\u30f3\u30d3\u30a2 \u30da\u30bd" }, { "cou", "\u30b3\u30ed\u30f3\u30d3\u30a2 \u30ec\u30a2\u30eb \uff08UVR)" }, { "crc", "\u30b3\u30b9\u30bf\u30ea\u30ab \u30b3\u30ed\u30f3" }, { "csd", "\u30bb\u30eb\u30d3\u30a2 \u30c7\u30a3\u30ca\u30fc\u30eb (2002\u20132006)" }, { "csk", "\u30c1\u30a7\u30b3\u30b9\u30ed\u30d0\u30ad\u30a2 \u30b3\u30eb\u30ca" }, { "cuc", "\u30ad\u30e5\u30fc\u30d0 \u514c\u63db\u30da\u30bd" }, { "cup", "\u30ad\u30e5\u30fc\u30d0 \u30da\u30bd" }, { "cve", "\u30ab\u30fc\u30dc\u30d9\u30eb\u30c7 \u30a8\u30b9\u30af\u30fc\u30c9" }, { "cyp", "\u30ad\u30d7\u30ed\u30b9 \u30dd\u30f3\u30c9" }, { "czk", "\u30c1\u30a7\u30b3 \u30b3\u30eb\u30ca" }, { "ddm", "\u6771\u30c9\u30a4\u30c4 \u30de\u30eb\u30af" }, { "dem", "\u30c9\u30a4\u30c4 \u30de\u30eb\u30af" }, { "djf", "\u30b8\u30d6\u30c1 \u30d5\u30e9\u30f3" }, { "dkk", "\u30c7\u30f3\u30de\u30fc\u30af \u30af\u30ed\u30fc\u30cd" }, { "dop", "\u30c9\u30df\u30cb\u30ab \u30da\u30bd" }, { "dzd", "\u30a2\u30eb\u30b8\u30a7\u30ea\u30a2 \u30c7\u30a3\u30ca\u30fc\u30eb" }, { "ecs", "\u30a8\u30af\u30a2\u30c9\u30eb \u30b9\u30af\u30ec" }, { "ecv", "\u30a8\u30af\u30a2\u30c9\u30eb (UVC)" }, { "eek", "\u30a8\u30b9\u30c8\u30cb\u30a2 \u30af\u30eb\u30fc\u30f3" }, { "egp", "\u30a8\u30b8\u30d7\u30c8 \u30dd\u30f3\u30c9" }, { "ern", "\u30a8\u30ea\u30c8\u30ea\u30a2 \u30ca\u30af\u30d5\u30a1" }, { "esa", "\u30b9\u30da\u30a4\u30f3\u30da\u30bb\u30bf\uff08\u52d8\u5b9aA\uff09" }, { "esb", "\u30b9\u30da\u30a4\u30f3 \u514c\u63db\u30da\u30bb\u30bf" }, { "esp", "\u30b9\u30da\u30a4\u30f3 \u30da\u30bb\u30bf" }, { "etb", "\u30a8\u30c1\u30aa\u30d4\u30a2 \u30d6\u30eb" }, { "eur", "\u30e6\u30fc\u30ed" }, { "fim", "\u30d5\u30a3\u30f3\u30e9\u30f3\u30c9 \u30de\u30eb\u30ab" }, { "fjd", "\u30d5\u30a3\u30b8\u30fc \u30c9\u30eb" }, { "fkp", "\u30d5\u30a9\u30fc\u30af\u30e9\u30f3\u30c9\uff08\u30de\u30eb\u30d3\u30ca\u30b9\uff09\u8af8\u5cf6 \u30dd\u30f3\u30c9" }, { "frf", "\u30d5\u30e9\u30f3\u30b9 \u30d5\u30e9\u30f3" }, { "gbp", "\u82f1\u56fd\u30dd\u30f3\u30c9" }, { "gek", "\u30b8\u30e7\u30fc\u30b8\u30a2 \u30af\u30fc\u30dd\u30f3 \u30e9\u30ea" }, { "gel", "\u30b8\u30e7\u30fc\u30b8\u30a2 \u30e9\u30ea" }, { "ghc", "\u30ac\u30fc\u30ca \u30bb\u30c7\u30a3 (1979\u20132007)" }, { "ghs", "\u30ac\u30fc\u30ca \u30bb\u30c7\u30a3" }, { "gip", "\u30b8\u30d6\u30e9\u30eb\u30bf\u30eb \u30dd\u30f3\u30c9" }, { "gmd", "\u30ac\u30f3\u30d3\u30a2 \u30c0\u30e9\u30b7" }, { "gnf", "\u30ae\u30cb\u30a2 \u30d5\u30e9\u30f3" }, { "gns", "\u30ae\u30cb\u30a2 \u30b7\u30ea\u30fc" }, { "gqe", "\u8d64\u9053\u30ae\u30cb\u30a2 \u30a8\u30af\u30a6\u30a7\u30ec" }, { "grd", "\u30ae\u30ea\u30b7\u30e3 \u30c9\u30e9\u30af\u30de" }, { "gtq", "\u30b0\u30a2\u30c6\u30de\u30e9 \u30b1\u30c4\u30a1\u30eb" }, { "gwe", "\u30dd\u30eb\u30c8\u30ac\u30eb\u9818\u30ae\u30cb\u30a2 \u30a8\u30b9\u30af\u30fc\u30c9" }, { "gwp", "\u30ae\u30cb\u30a2\u30d3\u30b5\u30a6 \u30da\u30bd" }, { "gyd", "\u30ac\u30a4\u30a2\u30ca \u30c9\u30eb" }, { "hkd", "\u9999\u6e2f\u30c9\u30eb" }, { "hnl", "\u30db\u30f3\u30b8\u30e5\u30e9\u30b9 \u30ec\u30f3\u30d4\u30e9" }, { "hrd", "\u30af\u30ed\u30a2\u30c1\u30a2 \u30c7\u30a3\u30ca\u30fc\u30eb" }, { "hrk", "\u30af\u30ed\u30a2\u30c1\u30a2 \u30af\u30fc\u30ca" }, { "htg", "\u30cf\u30a4\u30c1 \u30b0\u30fc\u30eb\u30c9" }, { "huf", "\u30cf\u30f3\u30ac\u30ea\u30fc \u30d5\u30a9\u30ea\u30f3\u30c8" }, { "idr", "\u30a4\u30f3\u30c9\u30cd\u30b7\u30a2 \u30eb\u30d4\u30a2" }, { "iep", "\u30a2\u30a4\u30ea\u30c3\u30b7\u30e5 \u30dd\u30f3\u30c9" }, { "ilp", "\u30a4\u30b9\u30e9\u30a8\u30eb \u30dd\u30f3\u30c9" }, { "ilr", "\u30a4\u30b9\u30e9\u30a8\u30eb \u30b7\u30a7\u30b1\u30eb (1980\u20131985)" }, { "ils", "\u30a4\u30b9\u30e9\u30a8\u30eb\u65b0\u30b7\u30a7\u30b1\u30eb" }, { "inr", "\u30a4\u30f3\u30c9 \u30eb\u30d4\u30fc" }, { "iqd", "\u30a4\u30e9\u30af \u30c7\u30a3\u30ca\u30fc\u30eb" }, { "irr", "\u30a4\u30e9\u30f3 \u30ea\u30a2\u30eb" }, { "isj", "\u30a2\u30a4\u30b9\u30e9\u30f3\u30c9 \u30af\u30ed\u30fc\u30ca (1918\u20131981)" }, { "isk", "\u30a2\u30a4\u30b9\u30e9\u30f3\u30c9 \u30af\u30ed\u30fc\u30ca" }, { "itl", "\u30a4\u30bf\u30ea\u30a2 \u30ea\u30e9" }, { "jmd", "\u30b8\u30e3\u30de\u30a4\u30ab \u30c9\u30eb" }, { "jod", "\u30e8\u30eb\u30c0\u30f3 \u30c7\u30a3\u30ca\u30fc\u30eb" }, { "jpy", "\u65e5\u672c\u5186" }, { "kes", "\u30b1\u30cb\u30a2 \u30b7\u30ea\u30f3\u30b0" }, { "kgs", "\u30ad\u30eb\u30ae\u30b9 \u30bd\u30e0" }, { "khr", "\u30ab\u30f3\u30dc\u30b8\u30a2 \u30ea\u30a8\u30eb" }, { "kmf", "\u30b3\u30e2\u30ed \u30d5\u30e9\u30f3" }, { "kpw", "\u5317\u671d\u9bae\u30a6\u30a9\u30f3" }, { "krh", "\u97d3\u56fd \u30d5\u30a1\u30f3\uff081953\u20131962\uff09" }, { "kro", "\u97d3\u56fd \u30a6\u30a9\u30f3\uff081945\u20131953\uff09" }, { "krw", "\u97d3\u56fd\u30a6\u30a9\u30f3" }, { "kwd", "\u30af\u30a6\u30a7\u30fc\u30c8 \u30c7\u30a3\u30ca\u30fc\u30eb" }, { "kyd", "\u30b1\u30a4\u30de\u30f3\u8af8\u5cf6 \u30c9\u30eb" }, { "kzt", "\u30ab\u30b6\u30d5\u30b9\u30bf\u30f3 \u30c6\u30f3\u30b2" }, { "lak", "\u30e9\u30aa\u30b9 \u30ad\u30fc\u30d7" }, { "lbp", "\u30ec\u30d0\u30ce\u30f3 \u30dd\u30f3\u30c9" }, { "lkr", "\u30b9\u30ea\u30e9\u30f3\u30ab \u30eb\u30d4\u30fc" }, { "lrd", "\u30ea\u30d9\u30ea\u30a2 \u30c9\u30eb" }, { "lsl", "\u30ec\u30bd\u30c8 \u30ed\u30c6\u30a3" }, { "ltl", "\u30ea\u30c8\u30a2\u30cb\u30a2 \u30ea\u30bf\u30b9" }, { "ltt", "\u30ea\u30c8\u30a2\u30cb\u30a2 \u30bf\u30ed\u30ca" }, { "luc", "\u30eb\u30af\u30bb\u30f3\u30d6\u30eb\u30af \u514c\u63db\u30d5\u30e9\u30f3" }, { "luf", "\u30eb\u30af\u30bb\u30f3\u30d6\u30eb\u30b0 \u30d5\u30e9\u30f3" }, { "lul", "\u30eb\u30af\u30bb\u30f3\u30d6\u30eb\u30af \u91d1\u878d\u30d5\u30e9\u30f3" }, { "lvl", "\u30e9\u30c8\u30d3\u30a2 \u30e9\u30c3\u30c4" }, { "lvr", "\u30e9\u30c8\u30d3\u30a2 \u30eb\u30fc\u30d6\u30eb" }, { "lyd", "\u30ea\u30d3\u30a2 \u30c7\u30a3\u30ca\u30fc\u30eb" }, { "mad", "\u30e2\u30ed\u30c3\u30b3 \u30c7\u30a3\u30eb\u30cf\u30e0" }, { "maf", "\u30e2\u30ed\u30c3\u30b3 \u30d5\u30e9\u30f3" }, { "mcf", "\u30e2\u30cd\u30ac\u30b9\u30af \u30d5\u30e9\u30f3" }, { "mdc", "\u30e2\u30eb\u30c9\u30d0 \u30af\u30fc\u30dd\u30f3" }, { "mdl", "\u30e2\u30eb\u30c9\u30d0 \u30ec\u30a4" }, { "mga", "\u30de\u30c0\u30ac\u30b9\u30ab\u30eb \u30a2\u30ea\u30a2\u30ea" }, { "mgf", "\u30de\u30e9\u30ac\u30b7 \u30d5\u30e9\u30f3" }, { "mkd", "\u30de\u30b1\u30c9\u30cb\u30a2 \u30c7\u30ca\u30eb" }, { "mkn", "\u30de\u30b1\u30c9\u30cb\u30a2 \u30c7\u30a3\u30ca\u30fc\u30eb\uff081992\u20131993\uff09" }, { "mlf", "\u30de\u30ea \u30d5\u30e9\u30f3" }, { "mmk", "\u30df\u30e3\u30f3\u30de\u30fc \u30c1\u30e3\u30c3\u30c8" }, { "mnt", "\u30e2\u30f3\u30b4\u30eb \u30c8\u30b0\u30ed\u30b0" }, { "mop", "\u30de\u30ab\u30aa \u30d1\u30bf\u30ab" }, { "mro", "\u30e2\u30fc\u30ea\u30bf\u30cb\u30a2 \u30a6\u30ae\u30a2 (1973\u20132017)" }, { "mru", "\u30e2\u30fc\u30ea\u30bf\u30cb\u30a2 \u30a6\u30ae\u30a2" }, { "mtl", "\u30de\u30eb\u30bf \u30ea\u30e9" }, { "mtp", "\u30de\u30eb\u30bf \u30dd\u30f3\u30c9" }, { "mur", "\u30e2\u30fc\u30ea\u30b7\u30e3\u30b9 \u30eb\u30d4\u30fc" }, { "mvp", "\u30e2\u30eb\u30c7\u30a3\u30d6\u8af8\u5cf6 \u30eb\u30d4\u30fc" }, { "mvr", "\u30e2\u30eb\u30c7\u30a3\u30d6 \u30eb\u30d5\u30a3\u30a2" }, { "mwk", "\u30de\u30e9\u30a6\u30a3 \u30af\u30ef\u30c1\u30e3" }, { "mxn", "\u30e1\u30ad\u30b7\u30b3 \u30da\u30bd" }, { "mxp", "\u30e1\u30ad\u30b7\u30b3 \u30da\u30bd (1861\u20131992)" }, { "mxv", "\u30e1\u30ad\u30b7\u30b3 (UDI)" }, { "myr", "\u30de\u30ec\u30fc\u30b7\u30a2 \u30ea\u30f3\u30ae\u30c3\u30c8" }, { "mze", "\u30e2\u30b6\u30f3\u30d4\u30fc\u30af \u30a8\u30b9\u30af\u30fc\u30c9" }, { "mzm", "\u30e2\u30b6\u30f3\u30d3\u30fc\u30af \u30e1\u30c6\u30a3\u30ab\u30eb (1980\u20132006)" }, { "mzn", "\u30e2\u30b6\u30f3\u30d3\u30fc\u30af \u30e1\u30c6\u30a3\u30ab\u30eb" }, { "nad", "\u30ca\u30df\u30d3\u30a2 \u30c9\u30eb" }, { "ngn", "\u30ca\u30a4\u30b8\u30a7\u30ea\u30a2 \u30ca\u30a4\u30e9" }, { "nic", "\u30cb\u30ab\u30e9\u30b0\u30a2 \u30b3\u30eb\u30c9\u30d0 (1988\u20131991)" }, { "nio", "\u30cb\u30ab\u30e9\u30b0\u30a2 \u30b3\u30eb\u30c9\u30d0 \u30aa\u30ed" }, { "nlg", "\u30aa\u30e9\u30f3\u30c0 \u30ae\u30eb\u30c0\u30fc" }, { "nok", "\u30ce\u30eb\u30a6\u30a7\u30fc \u30af\u30ed\u30fc\u30cd" }, { "npr", "\u30cd\u30d1\u30fc\u30eb \u30eb\u30d4\u30fc" }, { "nzd", "\u30cb\u30e5\u30fc\u30b8\u30fc\u30e9\u30f3\u30c9 \u30c9\u30eb" }, { "omr", "\u30aa\u30de\u30fc\u30f3 \u30ea\u30a2\u30eb" }, { "pab", "\u30d1\u30ca\u30de \u30d0\u30eb\u30dc\u30a2" }, { "pei", "\u30da\u30eb\u30fc \u30a4\u30f3\u30c6\u30a3" }, { "pen", "\u30da\u30eb\u30fc \u30bd\u30eb" }, { "pes", "\u30da\u30eb\u30fc \u30bd\u30eb (1863\u20131965)" }, { "pgk", "\u30d1\u30d7\u30a2\u30cb\u30e5\u30fc\u30ae\u30cb\u30a2 \u30ad\u30ca" }, { "php", "\u30d5\u30a3\u30ea\u30d4\u30f3 \u30da\u30bd" }, { "pkr", "\u30d1\u30ad\u30b9\u30bf\u30f3 \u30eb\u30d4\u30fc" }, { "pln", "\u30dd\u30fc\u30e9\u30f3\u30c9 \u30ba\u30a6\u30a9\u30c6\u30a3" }, { "plz", "\u30dd\u30fc\u30e9\u30f3\u30c9 \u30ba\u30a6\u30a9\u30c6\u30a3 (1950\u20131995)" }, { "pte", "\u30dd\u30eb\u30c8\u30ac\u30eb \u30a8\u30b9\u30af\u30fc\u30c9" }, { "pyg", "\u30d1\u30e9\u30b0\u30a2\u30a4 \u30b0\u30a2\u30e9\u30cb" }, { "qar", "\u30ab\u30bf\u30fc\u30eb \u30ea\u30a2\u30eb" }, { "rhd", "\u30ed\u30fc\u30c7\u30b7\u30a2 \u30c9\u30eb" }, { "rol", "\u30eb\u30fc\u30de\u30cb\u30a2 \u30ec\u30a4 (1952\u20132006)" }, { "ron", "\u30eb\u30fc\u30de\u30cb\u30a2 \u30ec\u30a4" }, { "rsd", "\u30c7\u30a3\u30ca\u30fc\u30eb (\u30bb\u30eb\u30d3\u30a2)" }, { "rub", "\u30ed\u30b7\u30a2 \u30eb\u30fc\u30d6\u30eb" }, { "rur", "\u30ed\u30b7\u30a2 \u30eb\u30fc\u30d6\u30eb (1991\u20131998)" }, { "rwf", "\u30eb\u30ef\u30f3\u30c0 \u30d5\u30e9\u30f3" }, { "sar", "\u30b5\u30a6\u30b8 \u30ea\u30e4\u30eb" }, { "sbd", "\u30bd\u30ed\u30e2\u30f3\u8af8\u5cf6 \u30c9\u30eb" }, { "scr", "\u30bb\u30fc\u30b7\u30a7\u30eb \u30eb\u30d4\u30fc" }, { "sdd", "\u30b9\u30fc\u30c0\u30f3 \u30c7\u30a3\u30ca\u30fc\u30eb (1992\u20132007)" }, { "sdg", "\u30b9\u30fc\u30c0\u30f3 \u30dd\u30f3\u30c9" }, { "sdp", "\u30b9\u30fc\u30c0\u30f3 \u30dd\u30f3\u30c9 (1957\u20131998)" }, { "sek", "\u30b9\u30a6\u30a7\u30fc\u30c7\u30f3 \u30af\u30ed\u30fc\u30ca" }, { "sgd", "\u30b7\u30f3\u30ac\u30dd\u30fc\u30eb \u30c9\u30eb" }, { "shp", "\u30bb\u30f3\u30c8\u30d8\u30ec\u30ca \u30dd\u30f3\u30c9" }, { "sit", "\u30b9\u30ed\u30d9\u30cb\u30a2 \u30c8\u30e9\u30fc\u30eb" }, { "skk", "\u30b9\u30ed\u30d0\u30ad\u30a2 \u30b3\u30eb\u30ca" }, { "sll", "\u30b7\u30a8\u30e9\u30ec\u30aa\u30cd \u30ec\u30aa\u30f3" }, { "sos", "\u30bd\u30de\u30ea\u30a2 \u30b7\u30ea\u30f3\u30b0" }, { "srd", "\u30b9\u30ea\u30ca\u30e0 \u30c9\u30eb" }, { "srg", "\u30b9\u30ea\u30ca\u30e0 \u30ae\u30eb\u30c0\u30fc" }, { "ssp", "\u5357\u30b9\u30fc\u30c0\u30f3 \u30dd\u30f3\u30c9" }, { "std", "\u30b5\u30f3\u30c8\u30e1\u30fb\u30d7\u30ea\u30f3\u30b7\u30da \u30c9\u30d6\u30e9 (1977\u20132017)" }, { "stn", "\u30b5\u30f3\u30c8\u30e1\u30fb\u30d7\u30ea\u30f3\u30b7\u30da \u30c9\u30d6\u30e9" }, { "sur", "\u30bd\u9023 \u30eb\u30fc\u30d6\u30eb" }, { "svc", "\u30a8\u30eb\u30b5\u30eb\u30d0\u30c9\u30eb \u30b3\u30ed\u30f3" }, { "syp", "\u30b7\u30ea\u30a2 \u30dd\u30f3\u30c9" }, { "szl", "\u30b9\u30ef\u30b8\u30e9\u30f3\u30c9 \u30ea\u30e9\u30f3\u30b2\u30cb" }, { "thb", "\u30bf\u30a4 \u30d0\u30fc\u30c4" }, { "tjr", "\u30bf\u30b8\u30ad\u30b9\u30bf\u30f3 \u30eb\u30fc\u30d6\u30eb" }, { "tjs", "\u30bf\u30b8\u30ad\u30b9\u30bf\u30f3 \u30bd\u30e2\u30cb" }, { "tmm", "\u30c8\u30eb\u30af\u30e1\u30cb\u30b9\u30bf\u30f3 \u30de\u30ca\u30c8 (1993\u20132009)" }, { "tmt", "\u30c8\u30eb\u30af\u30e1\u30cb\u30b9\u30bf\u30f3 \u30de\u30ca\u30c8" }, { "tnd", "\u30c1\u30e5\u30cb\u30b8\u30a2 \u30c7\u30a3\u30ca\u30fc\u30eb" }, { "top", "\u30c8\u30f3\u30ac \u30d1\u30fb\u30a2\u30f3\u30ac" }, { "tpe", "\u30c6\u30a3\u30e2\u30fc\u30eb \u30a8\u30b9\u30af\u30fc\u30c9" }, { "trl", "\u30c8\u30eb\u30b3 \u30ea\u30e9 (1922\u20132005)" }, { "try", "\u65b0\u30c8\u30eb\u30b3\u30ea\u30e9" }, { "ttd", "\u30c8\u30ea\u30cb\u30c0\u30fc\u30c9\u30fb\u30c8\u30d0\u30b4 \u30c9\u30eb" }, { "twd", "\u65b0\u53f0\u6e7e\u30c9\u30eb" }, { "tzs", "\u30bf\u30f3\u30b6\u30cb\u30a2 \u30b7\u30ea\u30f3\u30b0" }, { "uah", "\u30a6\u30af\u30e9\u30a4\u30ca \u30b0\u30ea\u30d6\u30ca" }, { "uak", "\u30a6\u30af\u30e9\u30a4\u30ca \u30ab\u30eb\u30dc\u30d0\u30cd\u30c4" }, { "ugs", "\u30a6\u30ac\u30f3\u30c0 \u30b7\u30ea\u30f3\u30b0 (1966\u20131987)" }, { "ugx", "\u30a6\u30ac\u30f3\u30c0 \u30b7\u30ea\u30f3\u30b0" }, { "usd", "\u7c73\u30c9\u30eb" }, { "usn", "\u7c73\u30c9\u30eb (\u7fcc\u65e5)" }, { "uss", "\u7c73\u30c9\u30eb (\u5f53\u65e5)" }, { "uyi", "\u30a6\u30eb\u30b0\u30a2\u30a4 \u30da\u30bd\u30a8\u30f3" }, { "uyp", "\u30a6\u30eb\u30b0\u30a2\u30a4 \u30da\u30bd (1975\u20131993)" }, { "uyu", "\u30a6\u30eb\u30b0\u30a2\u30a4 \u30da\u30bd" }, { "uzs", "\u30a6\u30ba\u30d9\u30ad\u30b9\u30bf\u30f3 \u30b9\u30e0" }, { "veb", "\u30d9\u30cd\u30ba\u30a8\u30e9 \u30dc\u30ea\u30d0\u30eb (1871\u20132008)" }, { "vef", "\u30d9\u30cd\u30ba\u30a8\u30e9 \u30dc\u30ea\u30d0\u30eb" }, { "vnd", "\u30d9\u30c8\u30ca\u30e0 \u30c9\u30f3" }, { "vnn", "\u30d9\u30c8\u30ca\u30e0 \u30c9\u30f3\uff081978\u20131985\uff09" }, { "vuv", "\u30d0\u30cc\u30a2\u30c4 \u30d0\u30c4" }, { "wst", "\u30b5\u30e2\u30a2 \u30bf\u30e9" }, { "xaf", "\u4e2d\u592e\u30a2\u30d5\u30ea\u30ab CFA \u30d5\u30e9\u30f3" }, { "xag", "\u9280" }, { "xau", "\u91d1" }, { "xba", "\u30e8\u30fc\u30ed\u30c3\u30d1\u6df7\u5408\u5358\u4f4d (EURCO)" }, { "xbb", "\u30e8\u30fc\u30ed\u30c3\u30d1\u901a\u8ca8\u5358\u4f4d (EMU\u20136)" }, { "xbc", "\u30e8\u30fc\u30ed\u30c3\u30d1\u52d8\u5b9a\u5358\u4f4d (EUA\u20139)" }, { "xbd", "\u30e8\u30fc\u30ed\u30c3\u30d1\u52d8\u5b9a\u5358\u4f4d (EUA\u201317)" }, { "xcd", "\u6771\u30ab\u30ea\u30d6 \u30c9\u30eb" }, { "xdr", "\u7279\u5225\u5f15\u304d\u51fa\u3057\u6a29" }, { "xeu", "\u30e8\u30fc\u30ed\u30c3\u30d1\u901a\u8ca8\u5358\u4f4d" }, { "xfo", "\u30d5\u30e9\u30f3\u30b9\u91d1\u30d5\u30e9\u30f3" }, { "xfu", "\u30d5\u30e9\u30f3\u30b9 \u30d5\u30e9\u30f3 (UIC)" }, { "xof", "\u897f\u30a2\u30d5\u30ea\u30ab CFA \u30d5\u30e9\u30f3" }, { "xpd", "\u30d1\u30e9\u30b8\u30a6\u30e0" }, { "xpf", "CFP \u30d5\u30e9\u30f3" }, { "xpt", "\u30d7\u30e9\u30c1\u30ca" }, { "xre", "RINET\u57fa\u91d1" }, { "xsu", "\u30b9\u30af\u30ec" }, { "xts", "\u30c6\u30b9\u30c8\u7528\u901a\u8ca8\u30b3\u30fc\u30c9" }, { "xua", "UA (\u30a2\u30d5\u30ea\u30ab\u958b\u767a\u9280\u884c)" }, { "xxx", "\u4e0d\u660e\u307e\u305f\u306f\u7121\u52b9\u306a\u901a\u8ca8" }, { "ydd", "\u30a4\u30a8\u30e1\u30f3 \u30c7\u30a3\u30ca\u30fc\u30eb" }, { "yer", "\u30a4\u30a8\u30e1\u30f3 \u30ea\u30a2\u30eb" }, { "yud", "\u30e6\u30fc\u30b4\u30b9\u30e9\u30d3\u30a2 \u30cf\u30fc\u30c9\u30fb\u30c7\u30a3\u30ca\u30fc\u30eb (1966\u20131990)" }, { "yum", "\u30e6\u30fc\u30b4\u30b9\u30e9\u30d3\u30a2 \u30ce\u30d3\u30fb\u30c7\u30a3\u30ca\u30fc\u30eb (1994\u20132002)" }, { "yun", "\u30e6\u30fc\u30b4\u30b9\u30e9\u30d3\u30a2 \u514c\u63db\u30c7\u30a3\u30ca\u30fc\u30eb (1990\u20131992)" }, { "yur", "\u30e6\u30fc\u30b4\u30b9\u30e9\u30d3\u30a2 \u6539\u9769\u30c7\u30a3\u30ca\u30fc\u30eb\uff081992\u20131993\uff09" }, { "zal", "\u5357\u30a2\u30d5\u30ea\u30ab \u30e9\u30f3\u30c9 (ZAL)" }, { "zar", "\u5357\u30a2\u30d5\u30ea\u30ab \u30e9\u30f3\u30c9" }, { "zmk", "\u30b6\u30f3\u30d3\u30a2 \u30af\u30ef\u30c1\u30e3 (1968\u20132012)" }, { "zmw", "\u30b6\u30f3\u30d3\u30a2 \u30af\u30ef\u30c1\u30e3" }, { "zrn", "\u30b6\u30a4\u30fc\u30eb \u65b0\u30b6\u30a4\u30fc\u30eb (1993\u20131998)" }, { "zrz", "\u30b6\u30a4\u30fc\u30eb \u30b6\u30a4\u30fc\u30eb (1971\u20131993)" }, { "zwd", "\u30b8\u30f3\u30d0\u30d6\u30a8 \u30c9\u30eb (1980\u20132008)" }, { "zwl", "\u30b8\u30f3\u30d0\u30d6\u30a8 \u30c9\u30eb (2009)" }, { "zwr", "\u30b7\u30f3\u30d0\u30d6\u30a8 \u30c9\u30eb\uff082008\uff09" }, }; return data; } }
3e1b4337a8149a6738c5d5fac07d930327b8e1aa
703
java
Java
SootAnalysis/src/main/java/de/fraunhofer/iem/authchecker/util/ReportWebView.java
secure-software-engineering/authcheck
a2ac56b30ddbdcea7a4501f21c0f821575cfdc4f
[ "MIT" ]
14
2019-04-28T09:10:39.000Z
2022-02-21T09:23:42.000Z
SootAnalysis/src/main/java/de/fraunhofer/iem/authchecker/util/ReportWebView.java
secure-software-engineering/authcheck
a2ac56b30ddbdcea7a4501f21c0f821575cfdc4f
[ "MIT" ]
1
2022-03-31T20:07:38.000Z
2022-03-31T20:07:38.000Z
SootAnalysis/src/main/java/de/fraunhofer/iem/authchecker/util/ReportWebView.java
secure-software-engineering/authcheck
a2ac56b30ddbdcea7a4501f21c0f821575cfdc4f
[ "MIT" ]
3
2019-09-20T05:18:11.000Z
2021-05-31T09:42:05.000Z
28.12
80
0.550498
11,544
package de.fraunhofer.iem.authchecker.util; /******************************************************************************* * Copyright (c) 2019 Fraunhofer IEM, Paderborn, Germany. * ******************************************************************************/ import javafx.application.Application; import javafx.scene.Scene; import javafx.stage.Stage; public class ReportWebView extends Application { public static void showReport() { launch(); } @Override public void start(Stage stage) { Scene scene = new Scene(new WebViewBrowser("./report/report.html")); stage.setTitle("HTML Report"); stage.setScene(scene); stage.setMaximized(true); stage.show(); } }
3e1b43892b0a257ecdd6c89d6e2f9b4f9fe4ee8a
435
java
Java
src/main/java/io/resourcepool/dictionary/Dictionary.java
resourcepool/little-bob
24e540277494b0f6f62f3a978e689ed2262e6d51
[ "Apache-2.0" ]
6
2017-02-07T16:24:49.000Z
2021-11-14T17:16:04.000Z
src/main/java/io/resourcepool/dictionary/Dictionary.java
resourcepool/little-bob
24e540277494b0f6f62f3a978e689ed2262e6d51
[ "Apache-2.0" ]
null
null
null
src/main/java/io/resourcepool/dictionary/Dictionary.java
resourcepool/little-bob
24e540277494b0f6f62f3a978e689ed2262e6d51
[ "Apache-2.0" ]
null
null
null
16.111111
70
0.705747
11,545
package io.resourcepool.dictionary; import io.resourcepool.generator.Query; import io.resourcepool.model.Language; import java.util.List; /** * Represents a multi-lingual dictionary for any generic type of data. * * @author Loïc Ortola */ public interface Dictionary<T> { T pick(Language language); T pick(); List<T> pick(int count); List<T> pick(Query query); int size(Language... languages); int size(); }