blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
67ab1420987f2e05aeb6a909186c2305562767cd
Java
youyingke/springboot-jpa-sys
/src/main/java/com/hawk/demo/sys/dao/DeptDao.java
UTF-8
348
1.601563
2
[]
no_license
package com.hawk.demo.sys.dao; import com.hawk.demo.sys.model.DeptDO; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; /** * Created by Lenovo on 2019-06-12. */ public interface DeptDao extends JpaRepository<DeptDO,Long>,JpaSpecificationExecutor<DeptDO> { }
true
d4cc1ffb2268f45848e7cf38c9d4bcf5176c6f09
Java
COPRS/production-common
/rs-libs/obs-sdk/src/test/java/esa/s1pdgs/cpoc/obs_sdk/s3/S3ObsClientIT.java
UTF-8
28,124
1.523438
2
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
package esa.s1pdgs.cpoc.obs_sdk.s3; import static java.util.Collections.singletonList; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.Matchers.lessThan; import static org.hamcrest.number.OrderingComparison.greaterThan; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import org.apache.commons.io.IOUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.Before; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import com.amazonaws.services.s3.model.BucketLifecycleConfiguration; import com.amazonaws.services.s3.model.SetBucketLifecycleConfigurationRequest; import esa.s1pdgs.cpoc.common.ProductFamily; import esa.s1pdgs.cpoc.common.errors.AbstractCodedException; import esa.s1pdgs.cpoc.obs_sdk.FileObsUploadObject; import esa.s1pdgs.cpoc.obs_sdk.ObsConfigurationProperties; import esa.s1pdgs.cpoc.obs_sdk.ObsDownloadObject; import esa.s1pdgs.cpoc.obs_sdk.ObsEmptyFileException; import esa.s1pdgs.cpoc.obs_sdk.ObsObject; import esa.s1pdgs.cpoc.obs_sdk.ObsObjectMetadata; import esa.s1pdgs.cpoc.obs_sdk.ObsValidationException; import esa.s1pdgs.cpoc.obs_sdk.SdkClientException; import esa.s1pdgs.cpoc.obs_sdk.StreamObsUploadObject; import esa.s1pdgs.cpoc.obs_sdk.report.ReportingProductFactory; import esa.s1pdgs.cpoc.report.ReportingFactory; @Ignore @RunWith(SpringRunner.class) @TestPropertySource("classpath:obs-aws-s3.properties") @ContextConfiguration(classes = {ObsConfigurationProperties.class}) public class S3ObsClientIT { private static final Logger LOG = LogManager.getLogger(S3ObsClientIT.class); public final static ProductFamily auxiliaryFiles = ProductFamily.AUXILIARY_FILE; public final static String auxiliaryFilesBucketName = "werum-ut-auxiliary-files"; public final static String testFilePrefix1 = "abc/def/"; public final static String testFilePrefix5mb = "xyz/"; public final static String testFileName1 = "testfile1.txt"; public final static String testFileName2 = "testfile2.txt"; public final static String testFileName5mb = "random-5mb.bin"; public final static String testUnexptectedFileName = "unexpected.txt"; public final static String testDirectoryName = "testdir"; public final static File testFile1 = getResource("/" + testFileName1); public final static File testFile2 = getResource("/" + testFileName2); public final static File testFile5mb = getResource("/" + testFileName5mb); public final static File testDirectory = getResource("/" + testDirectoryName); @Rule public final ExpectedException exception = ExpectedException.none(); @Autowired private ObsConfigurationProperties configuration; private S3ObsClient uut; public static File getResource(final String fileName) { try { return new File(S3ObsClientIT.class.getResource(fileName).toURI()); } catch (final URISyntaxException e) { throw new RuntimeException("Could not get resource"); } } @Before public void setUp() throws SdkClientException { LOG.info("running with endpoint " + configuration.getEndpoint()); uut = (S3ObsClient) new S3ObsClient.Factory().newObsClient(configuration, new ReportingProductFactory()); // prepare environment if (!uut.bucketExists(auxiliaryFiles)) { uut.createBucket(auxiliaryFiles); } if (uut.exists(new ObsObject(auxiliaryFiles, testFileName1))) { uut.s3Services.s3client.deleteObject(auxiliaryFilesBucketName, testFileName1); } if (uut.exists(new ObsObject(auxiliaryFiles, testFileName2))) { uut.s3Services.s3client.deleteObject(auxiliaryFilesBucketName, testFileName2); } if (uut.exists(new ObsObject(auxiliaryFiles, testFilePrefix5mb + testFileName5mb))) { uut.s3Services.s3client.deleteObject(auxiliaryFilesBucketName, testFilePrefix5mb + testFileName5mb); } if (uut.exists(new ObsObject(auxiliaryFiles, testFilePrefix1 + testFileName1))) { uut.s3Services.s3client.deleteObject(auxiliaryFilesBucketName, testFilePrefix1 + testFileName1); } if (uut.exists(new ObsObject(auxiliaryFiles, testFilePrefix1 + testFileName2))) { uut.s3Services.s3client.deleteObject(auxiliaryFilesBucketName, testFilePrefix1 + testFileName2); } if (uut.exists(new ObsObject(auxiliaryFiles, testDirectoryName + "/" + testFileName1))) { uut.s3Services.s3client.deleteObject(auxiliaryFilesBucketName, testDirectoryName + "/" + testFileName1); } if (uut.exists(new ObsObject(auxiliaryFiles, testDirectoryName + "/" + testFileName2))) { uut.s3Services.s3client.deleteObject(auxiliaryFilesBucketName, testDirectoryName + "/" + testFileName2); } if (uut.exists(new ObsObject(auxiliaryFiles, testDirectoryName + "/" + testUnexptectedFileName))) { uut.s3Services.s3client.deleteObject(auxiliaryFilesBucketName, testDirectoryName + "/" + testUnexptectedFileName); } if (uut.exists(new ObsObject(auxiliaryFiles, testDirectoryName + ".md5sum"))) { uut.s3Services.s3client.deleteObject(auxiliaryFilesBucketName, testDirectoryName + ".md5sum"); } } @Test public void uploadWithoutPrefixTest() throws Exception { // upload assertFalse(uut.exists(new ObsObject(auxiliaryFiles, testFileName1))); uut.upload(singletonList(new FileObsUploadObject(auxiliaryFiles, testFileName1, testFile1)), ReportingFactory.NULL); assertTrue(uut.exists(new ObsObject(auxiliaryFiles, testFileName1))); } @Test public void uploadWithPrefixTest() throws Exception { // upload assertFalse(uut.exists(new ObsObject(auxiliaryFiles, testFilePrefix1 + testFileName1))); uut.upload(singletonList(new FileObsUploadObject(auxiliaryFiles, testFilePrefix1 + testFileName1, testFile1)), ReportingFactory.NULL); assertTrue(uut.exists(new ObsObject(auxiliaryFiles, testFilePrefix1 + testFileName1))); uut.validate(new FileObsUploadObject(auxiliaryFiles, testFilePrefix1 + testFileName1, testFile1)); } @Test public void uploadWithPrefixAsFileInputStreamTest() throws IOException, SdkClientException, AbstractCodedException, ObsEmptyFileException, ObsValidationException, URISyntaxException { long contentLength = testFile5mb.length(); URL res = getClass().getResource("/" + testFileName5mb); String absolutePath = Paths.get(res.toURI()).toFile().getAbsolutePath(); try(InputStream in = new FileInputStream(absolutePath)) { // upload assertFalse(uut.exists(new ObsObject(auxiliaryFiles, testFilePrefix5mb + testFileName5mb))); uut.uploadStreams(singletonList(new StreamObsUploadObject(auxiliaryFiles, testFilePrefix5mb + testFileName5mb, in, contentLength)), ReportingFactory.NULL); assertTrue(uut.exists(new ObsObject(auxiliaryFiles, testFilePrefix5mb + testFileName5mb))); uut.validate(new StreamObsUploadObject(auxiliaryFiles, testFilePrefix5mb + testFileName5mb, in, contentLength)); } } @Test public void uploadWithPrefixAsBufferedInputStreamTest() throws IOException, SdkClientException, AbstractCodedException, ObsEmptyFileException, ObsValidationException, URISyntaxException { long contentLength = testFile5mb.length(); URL res = getClass().getResource("/" + testFileName5mb); String absolutePath = Paths.get(res.toURI()).toFile().getAbsolutePath(); try(InputStream in = new BufferedInputStream(new FileInputStream(absolutePath))) { // upload assertFalse(uut.exists(new ObsObject(auxiliaryFiles, testFilePrefix5mb + testFileName5mb))); uut.uploadStreams(singletonList(new StreamObsUploadObject(auxiliaryFiles, testFilePrefix5mb + testFileName5mb, in, contentLength)), ReportingFactory.NULL); assertTrue(uut.exists(new ObsObject(auxiliaryFiles, testFilePrefix5mb + testFileName5mb))); uut.validate(new StreamObsUploadObject(auxiliaryFiles, testFilePrefix5mb + testFileName5mb, in, contentLength)); } } @Test public void uploadAndValidationOfCompleteDirectoryTest() throws SdkClientException, AbstractCodedException, ObsValidationException, ObsEmptyFileException { // upload directory assertFalse(uut.exists(new ObsObject(auxiliaryFiles, testDirectoryName + "/" + testFileName1))); assertFalse(uut.exists(new ObsObject(auxiliaryFiles, testDirectoryName + "/" + testFileName2))); assertFalse(uut.exists(new ObsObject(auxiliaryFiles, testDirectoryName + "/" + testUnexptectedFileName))); assertFalse(uut.exists(new ObsObject(auxiliaryFiles, testDirectoryName + ".md5sum"))); uut.upload(singletonList(new FileObsUploadObject(auxiliaryFiles, testDirectoryName, testDirectory)), ReportingFactory.NULL); assertTrue(uut.exists(new ObsObject(auxiliaryFiles, testDirectoryName + "/" + testFileName1))); assertTrue(uut.exists(new ObsObject(auxiliaryFiles, testDirectoryName + "/" + testFileName2))); assertTrue(uut.exists(new ObsObject(auxiliaryFiles, testDirectoryName + ".md5sum"))); // validate complete directory uut.validate(new ObsObject(auxiliaryFiles, testDirectoryName)); } @Test public void uploadAndValidationOfDirectoryWithUnexpectedObejectTest() throws SdkClientException, AbstractCodedException, ObsValidationException, ObsEmptyFileException { // upload directory assertFalse(uut.exists(new ObsObject(auxiliaryFiles, testDirectoryName + "/" + testFileName1))); assertFalse(uut.exists(new ObsObject(auxiliaryFiles, testDirectoryName + "/" + testFileName2))); assertFalse(uut.exists(new ObsObject(auxiliaryFiles, testDirectoryName + "/" + testUnexptectedFileName))); assertFalse(uut.exists(new ObsObject(auxiliaryFiles, testDirectoryName + ".md5sum"))); uut.upload(singletonList(new FileObsUploadObject(auxiliaryFiles, testDirectoryName, testDirectory)), ReportingFactory.NULL); assertTrue(uut.exists(new ObsObject(auxiliaryFiles, testDirectoryName + "/" + testFileName1))); assertTrue(uut.exists(new ObsObject(auxiliaryFiles, testDirectoryName + "/" + testFileName2))); assertTrue(uut.exists(new ObsObject(auxiliaryFiles, testDirectoryName + ".md5sum"))); // upload unexpected object uut.upload(singletonList(new FileObsUploadObject(auxiliaryFiles, testDirectoryName + "/" + testUnexptectedFileName, testFile1)), ReportingFactory.NULL); assertTrue(uut.exists(new ObsObject(auxiliaryFiles, testDirectoryName + "/" + testUnexptectedFileName))); // validate directory with unexpected object exception.expect(ObsValidationException.class); uut.validate(new ObsObject(auxiliaryFiles, testDirectoryName)); } @Test public void uploadAndValidationOfIncompleteDirectoryTest() throws SdkClientException, AbstractCodedException, ObsValidationException, ObsEmptyFileException { // upload assertFalse(uut.exists(new ObsObject(auxiliaryFiles, testDirectoryName + "/" + testFileName1))); assertFalse(uut.exists(new ObsObject(auxiliaryFiles, testDirectoryName + "/" + testFileName2))); assertFalse(uut.exists(new ObsObject(auxiliaryFiles, testDirectoryName + "/" + testUnexptectedFileName))); assertFalse(uut.exists(new ObsObject(auxiliaryFiles, testDirectoryName + ".md5sum"))); uut.upload(singletonList(new FileObsUploadObject(auxiliaryFiles, testDirectoryName, testDirectory)), ReportingFactory.NULL); assertTrue(uut.exists(new ObsObject(auxiliaryFiles, testDirectoryName + "/" + testFileName1))); assertTrue(uut.exists(new ObsObject(auxiliaryFiles, testDirectoryName + "/" + testFileName2))); assertTrue(uut.exists(new ObsObject(auxiliaryFiles, testDirectoryName + ".md5sum"))); // remove object from directory uut.s3Services.s3client.deleteObject(auxiliaryFilesBucketName, testDirectoryName + "/" + testFileName1); assertFalse(uut.exists(new ObsObject(auxiliaryFiles, testDirectoryName + "/" + testFileName1))); // validate incomplete directory exception.expect(ObsValidationException.class); exception.expectMessage("Object not found: " + testDirectoryName + "/" + testFileName1 + " of family " + auxiliaryFiles); uut.validate(new ObsObject(auxiliaryFiles, testDirectoryName)); } @Test public void uploadAndValidationOfDirectoryWithWrongChecksumTest() throws SdkClientException, AbstractCodedException, ObsValidationException, ObsEmptyFileException { // upload assertFalse(uut.exists(new ObsObject(auxiliaryFiles, testDirectoryName + "/" + testFileName1))); assertFalse(uut.exists(new ObsObject(auxiliaryFiles, testDirectoryName + "/" + testFileName2))); assertFalse(uut.exists(new ObsObject(auxiliaryFiles, testDirectoryName + "/" + testUnexptectedFileName))); assertFalse(uut.exists(new ObsObject(auxiliaryFiles, testDirectoryName + ".md5sum"))); uut.upload(singletonList(new FileObsUploadObject(auxiliaryFiles, testDirectoryName, testDirectory)), ReportingFactory.NULL); assertTrue(uut.exists(new ObsObject(auxiliaryFiles, testDirectoryName + "/" + testFileName1))); assertTrue(uut.exists(new ObsObject(auxiliaryFiles, testDirectoryName + "/" + testFileName2))); assertTrue(uut.exists(new ObsObject(auxiliaryFiles, testDirectoryName + ".md5sum"))); // replace object with bad one uut.s3Services.s3client.deleteObject(auxiliaryFilesBucketName, testDirectoryName + "/" + testFileName1); assertFalse(uut.exists(new ObsObject(auxiliaryFiles, testDirectoryName + "/" + testFileName1))); uut.s3Services.uploadFile(auxiliaryFilesBucketName, testDirectoryName + "/" + testFileName1, testFile2); assertTrue(uut.exists(new ObsObject(auxiliaryFiles, testDirectoryName + "/" + testFileName1))); // validate wrong checksum situation exception.expect(ObsValidationException.class); exception.expectMessage("Checksum is wrong for object: " + testDirectoryName + "/" + testFileName1 + " of family " + auxiliaryFiles); uut.validate(new ObsObject(auxiliaryFiles, testDirectoryName)); } @Test public void uploadAndValidationOfDirectoryWithNonexistentChecksumTest() throws SdkClientException, ObsValidationException { // validate not existing checksum file assertFalse(uut.exists(new ObsObject(auxiliaryFiles, "not-existing.md5sum"))); exception.expect(ObsValidationException.class); exception.expectMessage("Checksum file not found for: not-existing of family " + auxiliaryFiles); uut.validate(new ObsObject(auxiliaryFiles, "not-existing")); } @Test public void deleteWithoutPrefixTest() throws Exception { // upload assertFalse(uut.exists(new ObsObject(auxiliaryFiles, testFileName1))); uut.upload(singletonList(new FileObsUploadObject(auxiliaryFiles, testFileName1, testFile1)), ReportingFactory.NULL); assertTrue(uut.exists(new ObsObject(auxiliaryFiles, testFileName1))); // delete uut.s3Services.s3client.deleteObject(auxiliaryFilesBucketName, testFileName1); assertFalse(uut.exists(new ObsObject(auxiliaryFiles, testFileName1))); } @Test public void deleteWithPrefixTest() throws Exception { // upload assertFalse(uut.exists(new ObsObject(auxiliaryFiles, testFilePrefix1 + testFileName1))); uut.upload(singletonList(new FileObsUploadObject(auxiliaryFiles, testFilePrefix1 + testFileName1, testFile1)), ReportingFactory.NULL); assertTrue(uut.exists(new ObsObject(auxiliaryFiles, testFilePrefix1 + testFileName1))); // delete uut.s3Services.s3client.deleteObject(auxiliaryFilesBucketName, testFilePrefix1 + testFileName1); assertFalse(uut.exists(new ObsObject(auxiliaryFiles, testFilePrefix1 + testFileName1))); } @Test public void downloadFileWithoutPrefixTest() throws Exception { // upload assertFalse(uut.exists(new ObsObject(auxiliaryFiles, testFileName1))); uut.upload(singletonList(new FileObsUploadObject(auxiliaryFiles, testFileName1, testFile1)), ReportingFactory.NULL); assertTrue(uut.exists(new ObsObject(auxiliaryFiles, testFileName1))); // single file download final String targetDir = Files.createTempDirectory(this.getClass().getCanonicalName() + "-").toString(); uut.download(singletonList(new ObsDownloadObject(auxiliaryFiles, testFileName1, targetDir)), ReportingFactory.NULL); final String send1 = new String(Files.readAllBytes(testFile1.toPath())); final String received1 = new String(Files.readAllBytes((new File(targetDir + "/" + testFileName1)).toPath())); assertEquals(send1, received1); } @Test public void downloadFileWithPrefixTest() throws Exception { // upload assertFalse(uut.exists(new ObsObject(auxiliaryFiles, testFilePrefix1 + testFileName1))); uut.upload(singletonList(new FileObsUploadObject(auxiliaryFiles, testFilePrefix1 + testFileName1, testFile1)), ReportingFactory.NULL); assertTrue(uut.exists(new ObsObject(auxiliaryFiles, testFilePrefix1 + testFileName1))); // single file download final String targetDir = Files.createTempDirectory(this.getClass().getCanonicalName() + "-").toString(); uut.download(singletonList(new ObsDownloadObject(auxiliaryFiles, testFilePrefix1 + testFileName1, targetDir)), ReportingFactory.NULL); final String send1 = new String(Files.readAllBytes(testFile1.toPath())); final String received1 = new String(Files.readAllBytes((new File(targetDir + "/" + testFilePrefix1 + testFileName1)).toPath())); assertEquals(send1, received1); } @Test public void downloadOfDirectoryTest() throws IOException, SdkClientException, AbstractCodedException, ObsEmptyFileException { // upload assertFalse(uut.exists(new ObsObject(auxiliaryFiles, testDirectoryName + "/" + testFileName1))); assertFalse(uut.exists(new ObsObject(auxiliaryFiles, testDirectoryName + "/" + testFileName2))); assertFalse(uut.exists(new ObsObject(auxiliaryFiles, testDirectoryName + ".md5sum"))); uut.upload(singletonList(new FileObsUploadObject(auxiliaryFiles, testDirectoryName, testDirectory)), ReportingFactory.NULL); assertTrue(uut.exists(new ObsObject(auxiliaryFiles, testDirectoryName + "/" + testFileName1))); assertTrue(uut.exists(new ObsObject(auxiliaryFiles, testDirectoryName + "/" + testFileName2))); assertTrue(uut.exists(new ObsObject(auxiliaryFiles, testDirectoryName + ".md5sum"))); // multi file download final String targetDir = Files.createTempDirectory(this.getClass().getCanonicalName() + "-").toString(); uut.download(singletonList(new ObsDownloadObject(auxiliaryFiles, testDirectoryName + "/", targetDir)), ReportingFactory.NULL); final String send1 = new String(Files.readAllBytes(new File(testDirectory, testFileName1).toPath())); final String received1 = new String(Files.readAllBytes((new File(targetDir + "/" + testDirectoryName + "/" + testFileName1)).toPath())); assertEquals(send1, received1); final String send2 = new String(Files.readAllBytes(new File(testDirectory, testFileName2).toPath())); final String received2 = new String(Files.readAllBytes((new File(targetDir + "/" + testDirectoryName + "/" + testFileName2)).toPath())); assertEquals(send2, received2); assertFalse(new File(targetDir + "/" + testDirectoryName + ".md5sum").exists()); } @Test public void numberOfObjectsWithoutPrefixTest() throws Exception { // upload assertFalse(uut.exists(new ObsObject(auxiliaryFiles, testFileName1))); assertFalse(uut.exists(new ObsObject(auxiliaryFiles, testFileName2))); uut.upload(singletonList(new FileObsUploadObject(auxiliaryFiles, testFileName1, testFile1)), ReportingFactory.NULL); uut.upload(singletonList(new FileObsUploadObject(auxiliaryFiles, testFileName2, testFile2)), ReportingFactory.NULL); assertTrue(uut.exists(new ObsObject(auxiliaryFiles, testFileName1))); assertTrue(uut.exists(new ObsObject(auxiliaryFiles, testFileName2))); // count final int count = uut.s3Services.getNbObjects(auxiliaryFilesBucketName, ""); assertEquals(2, count); } @Test public void numberOfObjectsWithPrefixTest() throws Exception { // upload assertFalse(uut.exists(new ObsObject(auxiliaryFiles, testFilePrefix1 + testFileName1))); assertFalse(uut.exists(new ObsObject(auxiliaryFiles, testFilePrefix1 + testFileName2))); uut.upload(singletonList(new FileObsUploadObject(auxiliaryFiles, testFilePrefix1 + testFileName1, testFile1)), ReportingFactory.NULL); uut.upload(singletonList(new FileObsUploadObject(auxiliaryFiles, testFilePrefix1 + testFileName2, testFile2)), ReportingFactory.NULL); assertTrue(uut.exists(new ObsObject(auxiliaryFiles, testFilePrefix1 + testFileName1))); assertTrue(uut.exists(new ObsObject(auxiliaryFiles, testFilePrefix1 + testFileName2))); // count final int count = uut.s3Services.getNbObjects(auxiliaryFilesBucketName, testFilePrefix1); assertEquals(2, count); } @Test public final void list() throws Exception { assertFalse(uut.exists(new ObsObject(auxiliaryFiles, testFilePrefix1 + testFileName1))); assertFalse(uut.exists(new ObsObject(auxiliaryFiles, testFilePrefix1 + testFileName2))); uut.upload(singletonList(new FileObsUploadObject(auxiliaryFiles, testFilePrefix1 + testFileName1, testFile1)), ReportingFactory.NULL); uut.upload(singletonList(new FileObsUploadObject(auxiliaryFiles, testFilePrefix1 + testFileName2, testFile2)), ReportingFactory.NULL); assertTrue(uut.exists(new ObsObject(auxiliaryFiles, testFilePrefix1 + testFileName1))); assertTrue(uut.exists(new ObsObject(auxiliaryFiles, testFilePrefix1 + testFileName2))); final List<String> res = uut.list(auxiliaryFiles, testFilePrefix1); assertEquals(Arrays.asList("abc/def/testfile1.txt", "abc/def/testfile2.txt"), res); } @Test public final void getAsStream() throws Exception { assertFalse(uut.exists(new ObsObject(auxiliaryFiles, testFilePrefix1 + testFileName1))); assertFalse(uut.exists(new ObsObject(auxiliaryFiles, testFilePrefix1 + testFileName2))); uut.upload(singletonList(new FileObsUploadObject(auxiliaryFiles, testFilePrefix1 + testFileName1, testFile1)), ReportingFactory.NULL); uut.upload(singletonList(new FileObsUploadObject(auxiliaryFiles, testFilePrefix1 + testFileName2, testFile2)), ReportingFactory.NULL); assertTrue(uut.exists(new ObsObject(auxiliaryFiles, testFilePrefix1 + testFileName1))); assertTrue(uut.exists(new ObsObject(auxiliaryFiles, testFilePrefix1 + testFileName2))); final String retrievedTestFile1Content = IOUtils.toString(uut.getAsStream(auxiliaryFiles, "abc/def/testfile1.txt"), StandardCharsets.UTF_8); final String retrievedTestFile2Content = IOUtils.toString(uut.getAsStream(auxiliaryFiles, "abc/def/testfile2.txt"), StandardCharsets.UTF_8); assertEquals("test", retrievedTestFile1Content); assertEquals("test2", retrievedTestFile2Content); } @Test public void testSetExpirationDate() throws SdkClientException { removeAllLifecycleRules(); uut.setExpirationTime(new ObsObject(ProductFamily.AUXILIARY_FILE, "AUX-FILE.DAT"), Instant.now()); final BucketLifecycleConfiguration lifecycleConfiguration = uut.s3Services.s3client.getBucketLifecycleConfiguration(auxiliaryFilesBucketName); //two rules because Dummy rule is still present final List<BucketLifecycleConfiguration.Rule> rules = lifecycleConfiguration.getRules().stream().filter(r -> !r.getId().equals("Dummy")).collect(Collectors.toList()); assertEquals(1, rules.size()); assertEquals("AUX-FILE.DAT", rules.get(0).getId()); assertEquals("AUX-FILE.DAT", rules.get(0).getPrefix()); assertEquals("Enabled", rules.get(0).getStatus()); assertEquals(Instant.now().truncatedTo(ChronoUnit.DAYS), rules.get(0).getExpirationDate().toInstant()); } private void removeAllLifecycleRules() { //store one rule only because it is not possible to delete config with s3Client uut.s3Services.s3client.setBucketLifecycleConfiguration( new SetBucketLifecycleConfigurationRequest(auxiliaryFilesBucketName, new BucketLifecycleConfiguration().withRules( new BucketLifecycleConfiguration.Rule() .withStatus(BucketLifecycleConfiguration.DISABLED) .withPrefix("Dummy") .withId("Dummy").withExpirationInDays(365)))); final BucketLifecycleConfiguration config = uut.s3Services.s3client.getBucketLifecycleConfiguration(auxiliaryFilesBucketName); assertEquals(1, config.getRules().size()); assertEquals("Dummy", config.getRules().get(0).getId()); assertEquals("Disabled", config.getRules().get(0).getStatus()); } @Test public void testGetMetadata() throws SdkClientException, AbstractCodedException, ObsEmptyFileException { Instant justBeforeCreation = Instant.now().minus(Duration.ofMinutes(1)); final String obsKey = testFilePrefix1 + testFileName1; assertFalse(uut.exists(new ObsObject(auxiliaryFiles, obsKey))); uut.upload(singletonList(new FileObsUploadObject(auxiliaryFiles, obsKey, testFile1)), ReportingFactory.NULL); assertTrue(uut.exists(new ObsObject(auxiliaryFiles, obsKey))); Instant justAfterCreation = Instant.now().plus(Duration.ofSeconds(1)); final ObsObjectMetadata metadata = uut.getMetadata(new ObsObject(ProductFamily.AUXILIARY_FILE, obsKey)); assertEquals(obsKey, metadata.getKey()); assertThat(metadata.getLastModified(), is(greaterThan(justBeforeCreation))); assertThat(metadata.getLastModified(), is(lessThan(justAfterCreation))); } @Test public void testGetChecksum() throws SdkClientException, AbstractCodedException, ObsEmptyFileException { // upload assertFalse(uut.exists(new ObsObject(auxiliaryFiles, testFileName1))); uut.upload(singletonList(new FileObsUploadObject(auxiliaryFiles, testFileName1, testFile1)), ReportingFactory.NULL); assertTrue(uut.exists(new ObsObject(auxiliaryFiles, testFileName1))); final String md5 = uut.getChecksum(new ObsObject(auxiliaryFiles, testFileName1)); assertThat(md5, is(equalTo("098f6bcd4621d373cade4e832627b4f6"))); } }
true
85bc4bb8db70a18afd9b211064244fedc3228461
Java
StevenCode/LIP
/src/com/steven/hetero/AddNode.java
UTF-8
730
2.828125
3
[]
no_license
package com.steven.hetero; import com.steven.Homo.Token; public class AddNode extends ExprNode { ExprNode left, right; // named, node-specific, irregular children public AddNode(ExprNode left, Token addToken, ExprNode right) { super(addToken); this.left = left; this.right = right; } public String toStringTree() { if ( left==null || right==null ) return this.toString(); StringBuilder buf = new StringBuilder(); buf.append("("); buf.append(this.toString()); buf.append(' '); buf.append(left.toStringTree()); buf.append(' '); buf.append(right.toStringTree()); buf.append(")"); return buf.toString(); } }
true
cd5ef900cf684cc977e0f36eb6e7ef3ba830b050
Java
zongxingy/LifeAssistants
/lifeAssistants/src/main/java/com/yzx/lifeassistants/fragment/ChargeUpFragment.java
UTF-8
10,749
1.765625
2
[]
no_license
package com.yzx.lifeassistants.fragment; import java.util.ArrayList; import java.util.List; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.balysv.materialripple.MaterialRippleLayout; import com.baoyz.widget.PullRefreshLayout; import com.baoyz.widget.PullRefreshLayout.OnRefreshListener; import com.yzx.lifeassistants.GlobalParams; import com.yzx.lifeassistants.R; import com.yzx.lifeassistants.activity.AddExpendActivity; import com.yzx.lifeassistants.activity.ExpendPieAnalysisActivity; import com.yzx.lifeassistants.activity.SetAlimonyActivity; import com.yzx.lifeassistants.bean.ExpendByRange; import com.yzx.lifeassistants.common.CommonConstant; import com.yzx.lifeassistants.model.ISelectExpendByRange; import com.yzx.lifeassistants.model.callback.ISelectExpendByRangeCB; import com.yzx.lifeassistants.model.impl.SelectExpendByRangeImpl; import com.yzx.lifeassistants.utils.CalendarUtil; import com.yzx.lifeassistants.utils.LogcatUtils; import com.yzx.lifeassistants.utils.ToastUtils; import com.yzx.lifeassistants.view.widget.CircularLoadingDialog; import com.yzx.lifeassistants.view.widget.CircularPoints; /** * @Description: 记账能手 * @author: yzx * @time: 2015-11-27 下午2:33:16 */ public class ChargeUpFragment extends Fragment implements OnClickListener { private TextView titleTV;// 标题 private ImageButton analysisBtn;// 图表分析 private PullRefreshLayout refreshLayout;// 下拉刷新 private TextView monthTV;// 月份 private TextView yearTV;// 年份 private LinearLayout percentLL;// private RelativeLayout percentRL;// private CircularPoints circularPoints;// 百分比 private LinearLayout alimonyLL;// 设置生活费 private TextView alimonyTV;// 生活费 private LinearLayout balanceLL;// 余额 private ImageView balanceIV;// 余额图标 private TextView balanceTV;// 余额 private ImageButton addBtn;// 添加 private CircularLoadingDialog dialog;// private int alimony;// 生活费 private int balance;// 余额 private int balanceLevel;// 余额等级 private Handler handler;// private ISelectExpendByRangeCB selectCallBack;// 回调 private ISelectExpendByRange selectExpendByRange;// 查询 private List<ExpendByRange> dateList;// @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_charge_up, container, false); return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); initView(); setListenter(); initData(); initMaterialRipple(); } /** * * @Description: 初始化控件 */ private void initView() { titleTV = (TextView) getView().findViewById(R.id.top_title_tv); analysisBtn = (ImageButton) getView().findViewById( R.id.top_analysis_btn); refreshLayout = (PullRefreshLayout) getView().findViewById( R.id.charge_up_pull_refresh_layout); monthTV = (TextView) getView().findViewById(R.id.charge_up_month_tv); yearTV = (TextView) getView().findViewById(R.id.charge_up_year_tv); percentRL = (RelativeLayout) getView().findViewById( R.id.charge_up_percent_rl); percentLL = (LinearLayout) getView().findViewById( R.id.charge_up_percent_ll); alimonyLL = (LinearLayout) getView().findViewById( R.id.charge_up_alimony_ll); alimonyTV = (TextView) getView() .findViewById(R.id.charge_up_alimony_tv); balanceLL = (LinearLayout) getView().findViewById( R.id.charge_up_balance_ll); balanceIV = (ImageView) getView().findViewById( R.id.charge_up_balance_iv); balanceTV = (TextView) getView() .findViewById(R.id.charge_up_balance_tv); addBtn = (ImageButton) getView().findViewById(R.id.charge_up_add_btn); } /** * * @Description: 设置监听 */ private void setListenter() { analysisBtn.setOnClickListener(this); // 下拉刷新 refreshLayout.setOnRefreshListener(new OnRefreshListener() { @Override public void onRefresh() { getDataFromService(); } }); alimonyLL.setOnClickListener(this); addBtn.setOnClickListener(this); } /** * * @Description: 初始化数据 */ private void initData() { titleTV.setText("记账能手"); analysisBtn.setVisibility(View.VISIBLE); String time = CalendarUtil.getCurrentTime("yyyy-MM"); monthTV.setText(time.substring(time.indexOf("-") + 1, time.length())); yearTV.setText("/" + time.substring(0, time.indexOf("-"))); dialog = new CircularLoadingDialog(getActivity()); setAlimony(); dateList = new ArrayList<ExpendByRange>(); handler = new Handler(); selectCallBack = new ISelectExpendByRangeCB() { @Override public void selectSuccess(final List<ExpendByRange> expendList, String range) { handler.post(new Runnable() { @Override public void run() { LogcatUtils.i("查询本月总支出金额成功"); refreshLayout.setRefreshing(false); dialog.dismiss(); if (null == expendList || 1 > expendList.size()) { } else { dateList.clear(); dateList.add(expendList.get(0)); } setBalance(); } }); } @Override public void selectError(final int error, final String range) { handler.post(new Runnable() { @Override public void run() { LogcatUtils.e("查询本月总支出金额失败:" + error + " " + range); refreshLayout.setRefreshing(false); dialog.dismiss(); switch (error) { case ISelectExpendByRangeCB.NET_ERROR: { ToastUtils.showToast("网络超时,请检查您的手机网络~"); break; } case ISelectExpendByRangeCB.SELECT_ERROR: { ToastUtils.showToast("获取失败,请检查您的手机网络~"); break; } case ISelectExpendByRangeCB.RESULR_NULL: { LogcatUtils.e("获取本月支出为空"); dateList.clear(); setBalance();// 设置余额 break; } default: break; } } }); } }; selectExpendByRange = new SelectExpendByRangeImpl(getActivity(), selectCallBack); dialog.show(); getDataFromService(); } /** * * @Description: 设置生活费指标 */ private void setAlimony() { if (null == GlobalParams.userInfo.getAlimony()) { alimony = 1500; } else { alimony = GlobalParams.userInfo.getAlimony(); } alimonyTV.setText(alimony + "元"); } /** * * @Description: 从服务器获取数据 */ private void getDataFromService() { // 获取本月支出总额 selectExpendByRange.selectExpendByRange( GlobalParams.userInfo.getUsername(), CalendarUtil.getCurrentTime("yyyy-MM"), "month"); } /** * * @Description: 设置余额 */ private void setBalance() { balance = alimony; if (dateList.size() > 0) { balance = alimony - dateList.get(0).getMoney(); } // 先移除该百分比控件再添加 if (null != circularPoints) { percentLL.removeView(circularPoints); } balanceTV.setText(balance + "元"); if (0 == alimony) { balanceLevel = 1; balanceIV.setBackgroundResource(R.drawable.icon_balance_4); circularPoints = new CircularPoints(getActivity(), 0, CircularPoints.COLOR_RED); } else { int percent = (int) (balance * 100 / alimony); int scale = (balance * 4) / alimony; if (scale >= 3) { balanceLevel = 4; balanceIV.setBackgroundResource(R.drawable.icon_balance_1); circularPoints = new CircularPoints(getActivity(), percent, CircularPoints.COLOR_GREEN); } else if (scale >= 2) { balanceLevel = 3; balanceIV.setBackgroundResource(R.drawable.icon_balance_2); circularPoints = new CircularPoints(getActivity(), percent, CircularPoints.COLOR_YELLOW); } else if (scale >= 1) { balanceLevel = 2; balanceIV.setBackgroundResource(R.drawable.icon_balance_3); circularPoints = new CircularPoints(getActivity(), percent, CircularPoints.COLOR_ORANGE); } else { balanceLevel = 1; balanceIV.setBackgroundResource(R.drawable.icon_balance_4); circularPoints = new CircularPoints(getActivity(), percent, CircularPoints.COLOR_RED); } } percentLL.addView(circularPoints); } /** * * @Description: 瓷砖特效 */ private void initMaterialRipple() { List<View> views = new ArrayList<View>(); views.add(percentRL); views.add(alimonyLL); views.add(balanceLL); for (View view : views) { // 动态特效 MaterialRippleLayout .on(view) .rippleColor( Color.parseColor(CommonConstant.RIPPLE_COLOR_LITHT)) .rippleAlpha(CommonConstant.RIPPLE_ALPHA).rippleHover(true) .create(); } } /** * * @Description: 按键监听 */ @Override public void onClick(View v) { switch (v.getId()) { case R.id.charge_up_alimony_ll: {// 设置生活费指标 Intent intent = new Intent(getActivity(), SetAlimonyActivity.class); intent.putExtra("alimony", alimony); startActivityForResult(intent, CommonConstant.REQUESTCODE_SET_ALIMONY); break; } case R.id.charge_up_add_btn: {// 添加支出记录 Intent intent = new Intent(getActivity(), AddExpendActivity.class); intent.putExtra( CommonConstant.TO_ADD_EXPEND_ACTIVITY_BALANCE_LEVEL, balanceLevel); intent.putExtra(CommonConstant.TO_ADD_EXPEND_ACTIVITY_IS_NEW, true); startActivityForResult(intent, CommonConstant.REQUESTCODE_ADD_EXPEND); break; } case R.id.top_analysis_btn: {// 支出图表分析 Intent intent = new Intent(getActivity(), ExpendPieAnalysisActivity.class); startActivity(intent); break; } default: break; } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // 设置生活费指标 if (CommonConstant.REQUESTCODE_SET_ALIMONY == requestCode) { if (CommonConstant.RESULTCODE_SET_ALIMONY_SUCCESS == resultCode) { setAlimony(); setBalance(); ToastUtils.showToast("设置成功"); } } // 添加支出记录 if (CommonConstant.REQUESTCODE_ADD_EXPEND == requestCode) { if (CommonConstant.RESULTCODE_ADD_EXPEND_SUCCESS == resultCode) { dialog.show(); getDataFromService(); ToastUtils.showToast("添加成功"); } } } }
true
7c2b2fea2a0048c70171fee07db8dd189aaee2a4
Java
YuanChenM/xcdv1.5
/Services/msk-common/src/main/java/com/msk/product/bean/IPD141112RsPdTncResult.java
UTF-8
929
1.921875
2
[]
no_license
package com.msk.product.bean; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.msk.core.entity.PdTncStd; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; /** * 封装参数 * IPD141112RsPdTncParam. * * @author xhy */ @ApiModel(value = "IPD141112RsPdTncResult", description = "result") @JsonIgnoreProperties(value = {"delFlg", "crtId", "crtTime", "updId", "updTime", "ver", "actId"}) public class IPD141112RsPdTncResult extends PdTncStd { private static final long serialVersionUID = 1L; @ApiModelProperty(value = "分类指标名称") private String tncStdItemName; /** * 获得tncStdItemName */ public String getTncStdItemName() { return tncStdItemName; } /** * 设置tncStdItemName */ public void setTncStdItemName(String tncStdItemName) { this.tncStdItemName = tncStdItemName; } }
true
987d9e61b7a0a5239a5af66ec00f15dc90bc78f9
Java
ThNhi/BookManagement
/src/dto/Books_SE140736.java
UTF-8
1,806
2.53125
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package dto; /** * * @author DELL */ public class Books_SE140736 { private String bookID; //varchar private String bookName; //nvarchar private String author; //nvarchar private String publisher; //nvarchar private int publishedYear; //int private boolean forRent; //bit public Books_SE140736() { } public Books_SE140736(String bookID, String bookName, String author, String publisher, int publishedYear, boolean forRent) { this.bookID = bookID; this.bookName = bookName; this.author = author; this.publisher = publisher; this.publishedYear = publishedYear; this.forRent = forRent; } public String getBookID() { return bookID; } public void setBookID(String bookID) { this.bookID = bookID; } public String getBookName() { return bookName; } public void setBookName(String bookName) { this.bookName = bookName; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getPublisher() { return publisher; } public void setPublisher(String publisher) { this.publisher = publisher; } public int getPublishedYear() { return publishedYear; } public void setPublishedYear(int publishedYear) { this.publishedYear = publishedYear; } public boolean isForRent() { return forRent; } public void setForRent(boolean forRent) { this.forRent = forRent; } }
true
24dfa59a82add138bf936a83daba8611961c914a
Java
atopazio/TopSysFW
/TopSysFW/src/main/java/br/com/topsys/util/TSEmailUtil.java
WINDOWS-1252
2,174
2.671875
3
[]
no_license
package br.com.topsys.util; import java.util.Date; import java.util.Properties; import javax.mail.Message; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; /** * * @author andre.topazio * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public final class TSEmailUtil { public static final String TEXT_PLAIN = "text/plain"; private static final String FALHA_ENVIO = "No foi possvel enviar o e-mail!"; private TSEmailUtil() { } /** * Remetente � a pessoa que est� enviando o e-mail. Ex: * andre.topazio@sysdesign.com.br Assunto � o assunto do e-mail. Corpo � * a mensagem que ser� enviada. EmailTO � o destinatario do e-mail. Ex: * topazio@surf.com.br, ou seja andre.topazio@sysdesign.com.br enviou um * e-mail para topazio@surf.com.br MimeType � o tipo da mensagem, por * default ela � text/plain SmtpServer � o smtp que ir� enviar o * e-mail. Ex: "smtp.ig.com.br" ou "smtp.mail.yahoo.com.br" ou o * "IP do servidor". * * @param remetente * @param assunto * @param corpo * @param emailTO * @param mimeType * @param smtpServer * @return */ public static boolean enviar(String remetente, String assunto, String corpo, String emailTO, String mimeType, String smtpServer) { String smtp = smtpServer; String destinatario = emailTO; try { Properties propriedades = System.getProperties(); propriedades.put("mail.smtp.host", smtp); Session sessao = Session.getInstance(propriedades, null); Message mensagem = new MimeMessage(sessao); mensagem.setSentDate(new Date()); mensagem.setFrom(new InternetAddress(remetente)); mensagem.setRecipients(Message.RecipientType.TO, InternetAddress.parse(destinatario, false)); mensagem.setSubject(assunto); if (mimeType == null) { mensagem.setText(corpo); } else { mensagem.setContent(corpo, mimeType); } /** * Envia a mensagem */ Transport.send(mensagem); } catch (Exception ex) { ex.printStackTrace(); return false; } return true; } }
true
891afdc6d6882e4a6a46727738d5f111dd4b58cc
Java
vmathur/HowCheapRU
/src/com/example/howcheapru/HowCheapRUMain.java
UTF-8
10,932
2.171875
2
[]
no_license
package com.example.howcheapru; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import android.os.Bundle; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.text.Editable; import android.text.TextWatcher; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.SeekBar; import android.widget.TextView; import android.widget.SeekBar.OnSeekBarChangeListener; public class HowCheapRUMain extends Activity { private final String fileName = "textDocument"; private String fileContent=""; private static String BILL = "0.00"; private static String CUSTOM_PERCENT = "0.00"; private static String CUSTOM_TIP = "0.00"; private double meanTip = 13.00; private double Bill; private double tipPercent; private double customTip; private TextView textViewBill; private EditText editTextBill; private TextView textViewTipPercent; private EditText editTextTipPercent; private TextView textViewTip$; private EditText editTextTip$; private SeekBar seekBarTip; private TextView textViewBillTotal; private EditText editTextBillTotal; private EditText editTextComment; private Button saveButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.how_cheap_rumain); //Check to see if a saved state exists if (savedInstanceState == null) { Bill=0.00; customTip=0.0; } else { Bill= savedInstanceState.getDouble(BILL); tipPercent = savedInstanceState.getDouble(CUSTOM_PERCENT); customTip=savedInstanceState.getDouble(CUSTOM_TIP); } //Assignments textViewBill = (TextView) findViewById(R.id.textViewBill); editTextBill = (EditText) findViewById(R.id.editTextEnterBillAmount); textViewTipPercent = (TextView) findViewById(R.id.textViewTipPercent); editTextTipPercent = (EditText) findViewById(R.id.editTextTipPercent); textViewTip$ = (TextView) findViewById(R.id.textviewTip$); editTextTip$ = (EditText) findViewById(R.id.editTextTip$); seekBarTip = (SeekBar) findViewById(R.id.seekBarTip); textViewBillTotal = (TextView) findViewById(R.id.textViewBillTotal); editTextBillTotal =(EditText) findViewById(R.id.editTextBillTotal); editTextComment = (EditText) findViewById(R.id.editTextComment); Button saveButton = (Button) findViewById(R.id.saveButton); saveButton.setOnClickListener(saveButtonListener); //Listeners editTextBill.addTextChangedListener(editTextBillListener); editTextTip$.addTextChangedListener(editTextTip$Listener); editTextTipPercent.addTextChangedListener(editTextTipPercentListener); seekBarTip.setMax(1000); seekBarTip.setOnSeekBarChangeListener(seekBarTipListener); try { readFromFile(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_how_cheap_rumain, menu); return true; } @Override protected void onSaveInstanceState(Bundle outState) { // TODO Auto-generated method stub super.onSaveInstanceState(outState); outState.putDouble(BILL,Bill); outState.putDouble(CUSTOM_PERCENT,tipPercent); outState.putDouble(CUSTOM_TIP,customTip); } public void calculateBillTotal() { double billTotal = customTip + Bill; seekBarTip.setMax(seekBarMax()); editTextBillTotal.setText(String.format("%.02f", billTotal)); } public int seekBarMax() { return (int) (Bill*(meanTip*2)); } private TextWatcher editTextBillListener = new TextWatcher () { @Override public void afterTextChanged(Editable arg0) { } @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { } @Override public void onTextChanged(CharSequence s, int arg1, int arg2, int arg3) { try { Bill=Double.parseDouble(s.toString()); } catch (NumberFormatException e) { Bill = 0.00; } calculateBillTotal(); } }; private TextWatcher editTextTip$Listener = new TextWatcher () { @Override public void afterTextChanged(Editable arg0) { // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { // TODO Auto-generated method stub } @Override public void onTextChanged(CharSequence s, int arg1, int arg2, int arg3) { try { if (Bill!=0) tipPercent = 100*(customTip/Bill); else tipPercent = 0.0; editTextTipPercent.setText(String.format("%.02f", tipPercent)); //calculateBillTotal(); } catch (NumberFormatException e) { } } }; private TextWatcher editTextTipPercentListener = new TextWatcher () { @Override public void afterTextChanged(Editable arg0) { // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { // TODO Auto-generated method stub } @Override public void onTextChanged(CharSequence s, int arg1, int arg2, int arg3) { try { if (tipPercent>(meanTip+1.0)) { editTextComment.setBackgroundColor(Color.GREEN); editTextComment.setText("You are really generous!"); } else if (tipPercent<(meanTip-1.0)) { editTextComment.setBackgroundColor(Color.RED); editTextComment.setText("You are really cheap!"); } else { editTextComment.setBackgroundColor(Color.GRAY); editTextComment.setText(" "); } } catch (NumberFormatException e) { } } }; private OnSeekBarChangeListener seekBarTipListener = new OnSeekBarChangeListener () { @Override public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) { double returnedTipDouble = 0.00; int returnedTipInt = arg0.getProgress(); returnedTipDouble = ((double) returnedTipInt)/100.0; customTip = returnedTipDouble; editTextTip$.setText(""+returnedTipDouble); calculateBillTotal(); } @Override public void onStartTrackingTouch(SeekBar arg0) { // TODO Auto-generated method stub } @Override public void onStopTrackingTouch(SeekBar arg0) { // TODO Auto-generated method stub } }; public OnClickListener saveButtonListener = new OnClickListener() { @Override public void onClick(View v) { System.out.println("Going to save "+editTextTipPercent.getText()); String string = editTextTipPercent.getText().toString(); if(string!="") { try { saveToFile(string); } catch (IOException e) { e.printStackTrace(); } } else { System.out.println("the string was blank dude..."); } } }; @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.Clear: System.out.println("cleaing file..."); try { clearFile(); } catch (IOException e) { e.printStackTrace(); } return true; case R.id.showAllTips: System.out.println("Reading file..."); try { readFromFile(); } catch (IOException e) { e.printStackTrace(); } return true; case R.id.showAverage: System.out.println("Showing average..."); setAverage(); return true; default: return super.onOptionsItemSelected(item); } } private void saveToFile(String newString) throws IOException { String tempString; if (fileContent=="") { tempString=newString; } else { tempString=", "+newString; } FileOutputStream fos = openFileOutput(fileName, Context.MODE_APPEND); fos.write(tempString.getBytes()); fos.close(); setAverage(); fileContent+=tempString; System.out.println("writer) item saved: " + newString); System.out.println("writer) total fileContent: " + fileContent); } private void readFromFile() throws IOException { FileInputStream readStream = openFileInput(fileName); InputStreamReader inputStreamReader = new InputStreamReader(readStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); StringBuilder sb = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { sb.append(line); } String showFileContent = sb.toString(); fileContent=showFileContent; System.out.println("reader) it reads: " +fileContent+"."); if (fileContent=="") showPopup("All Saved Tips","No saved tips"); else showPopup("All Saved Tips",fileContent); } public void clearFile() throws IOException { fileContent = ""; FileOutputStream fos = openFileOutput(fileName, Context.MODE_PRIVATE); fos.write(fileContent.getBytes()); fos.close(); meanTip=13.00; System.out.println("clearer) all data cleared!"); } public void setAverage() { AlertDialog.Builder builder = new AlertDialog.Builder(HowCheapRUMain.this); builder.setTitle("Average"); builder.setPositiveButton("OK", null); if(fileContent!="") { double average = 0.0; double sum = 0.0; String[] valueArray = fileContent.split(", "); for (int i=0;i<valueArray.length;i++) { System.out.println("tempArray index "+i+" reads "+valueArray[i]); double tempDouble = Double.parseDouble(valueArray[i]); sum+=tempDouble; } average = sum/valueArray.length; builder.setMessage("Average is now: "+average); meanTip=average; } else { builder.setMessage("No saved tips"); } AlertDialog averageDialog = builder.create(); averageDialog.show(); } public void showPopup(String title, String message) { AlertDialog.Builder builder = new AlertDialog.Builder(HowCheapRUMain.this); builder.setTitle(title); builder.setPositiveButton("OK", null); builder.setMessage(message); AlertDialog averageDialog = builder.create(); averageDialog.show(); } }
true
133e8c91f1523308c7ed66b85e42ed673e474462
Java
Princejhabak/KissanMitr
/KissanMitr/app/src/main/java/com/example/android/myapp/ContactUsActivity.java
UTF-8
2,267
2.203125
2
[]
no_license
package com.example.android.myapp; import android.content.Intent; import android.net.Uri; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import java.util.Locale; public class ContactUsActivity extends AppCompatActivity implements OnMapReadyCallback { private GoogleMap mMap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_contact_us); ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setTitle("Contact Us"); SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); } @Override public boolean onSupportNavigateUp() { finish(); return true; } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; // Add a marker in Sydney, Australia, and move the camera. LatLng latLng = new LatLng(27.499431, 76.995634); mMap.addMarker(new MarkerOptions().position(latLng).title("Arora Krishi Kendra")); CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).zoom(17).build(); CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(cameraPosition); mMap.moveCamera(cameraUpdate); mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() { @Override public void onMapClick(LatLng latLng) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("geo:<lat>,<long>?q=<27.499431>,<76.995634>(Arora Krishi Kendra)")); startActivity(intent); } }); } }
true
740d2931b6393efe3755fe29bb864fdc48809f1b
Java
schustes/sidion-contract-examples
/books-client/src/main/java/de/sidion/books/client/adapter/BookCatalogRestService.java
UTF-8
2,087
2.21875
2
[]
no_license
package de.sidion.books.client.adapter; import de.sidion.books.client.domain.Book; import de.sidion.books.client.domain.BookCatalogService; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import java.util.Arrays; import java.util.Collections; import java.util.List; @Service @RequiredArgsConstructor public class BookCatalogRestService implements BookCatalogService { private static final String UPSTREAM_SCHEME = "http"; private static final String UPSTREAM_HOST = "localhost"; private static final String ROLE_HEADER = "X-ROLE"; private static final String CONTENT_HEADER = "Content-Type"; private static final String ROLE_HEADER_VALUE = "unprivileged use"; private static final String CONTENT_HEADER_VALUE = "application/json;charset=UTF-8"; private final RestTemplate restTemplate; @Value("${catalog.port}") private int upstreamPort; @Override public List<Book> getAllBooks() { String url = UPSTREAM_SCHEME + "://" + UPSTREAM_HOST + ":" + upstreamPort + "/books"; return Arrays.asList(restTemplate.exchange(url, HttpMethod.GET, createHeaders(), Book[].class).getBody()); } @Override public void deleteBook(String id) { String url = UPSTREAM_SCHEME + "://" + UPSTREAM_HOST + ":" + upstreamPort + "/book/" + id; restTemplate.exchange(url, HttpMethod.DELETE, createHeaders(), Void.class); } private HttpEntity<?> createHeaders() { HttpHeaders headers = new HttpHeaders(); headers.put(ROLE_HEADER, Collections.singletonList(ROLE_HEADER_VALUE)); headers.put(HttpHeaders.CONTENT_TYPE, Collections.singletonList(CONTENT_HEADER_VALUE)); headers.put(HttpHeaders.ACCEPT, Collections.singletonList("application/json")); return new HttpEntity<>(headers); } }
true
240e9db9ec014b8b5a30d16419c647d7ba864699
Java
opensourceforlife/sample-recycle-bin
/sample-recycle-bin-portlet/src/main/java/com/opensourceforlife/portlet/samplerecyclebin/SampleRecycleBinPortlet.java
UTF-8
4,612
1.875
2
[]
no_license
package com.opensourceforlife.portlet.samplerecyclebin; import java.util.Calendar; import java.util.HashMap; import java.util.Map; import javax.portlet.ActionRequest; import javax.portlet.ActionResponse; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.exception.SystemException; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.servlet.SessionMessages; import com.liferay.portal.kernel.util.Constants; import com.liferay.portal.kernel.util.ParamUtil; import com.liferay.portal.kernel.util.StringUtil; import com.liferay.portal.kernel.util.WebKeys; import com.liferay.portal.service.ServiceContext; import com.liferay.portal.service.ServiceContextFactory; import com.liferay.portal.theme.ThemeDisplay; import com.liferay.portal.util.PortalUtil; import com.liferay.portlet.trash.util.TrashUtil; import com.liferay.util.bridges.mvc.MVCPortlet; import com.opensourceforlife.portlet.samplerecyclebin.model.Event; import com.opensourceforlife.portlet.samplerecyclebin.service.EventLocalServiceUtil; import com.opensourceforlife.portlet.samplerecyclebin.service.EventServiceUtil; /** * @author Opensourceforlife */ public class SampleRecycleBinPortlet extends MVCPortlet { public void addEvent( final ActionRequest request, final ActionResponse response) throws Exception { _updateEvent(request); sendRedirect(request, response); } public void deleteEvent( final ActionRequest request, final ActionResponse response) throws Exception { long eventId = ParamUtil.getLong(request, "eventId"); String cmd = ParamUtil.getString(request, Constants.CMD); ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); if (cmd.equals(Constants.MOVE_TO_TRASH)) { Event event = EventLocalServiceUtil.moveEntryToTrash( themeDisplay.getUserId(), eventId); Map<String, String[]> data = new HashMap<String, String[]>(); data.put("deleteEntryClassName", new String[] { Event.class.getName() }); data.put("deleteEntryTitle", new String[] { TrashUtil.getOriginalTitle(event.getName()) }); data.put("restoreEntryIds", new String[] { String.valueOf(eventId) }); SessionMessages.add(request, PortalUtil.getPortletId(request) + SessionMessages.KEY_SUFFIX_DELETE_SUCCESS_DATA, data); SessionMessages.add(request, PortalUtil.getPortletId(request) + SessionMessages.KEY_SUFFIX_HIDE_DEFAULT_SUCCESS_MESSAGE); } else if (cmd.equals(Constants.DELETE)) { EventLocalServiceUtil.deleteEvent(eventId); } sendRedirect(request, response); } public void updateEvent( final ActionRequest request, final ActionResponse response) throws Exception { _updateEvent(request); sendRedirect(request, response); } private Event _updateEvent(final ActionRequest request) throws PortalException, SystemException { long eventId = ParamUtil.getLong(request, "eventId"); String name = ParamUtil.getString(request, "name"); String description = ParamUtil.getString(request, "description"); int year = ParamUtil.getInteger(request, "dateYear"); int month = ParamUtil.getInteger(request, "dateMonth"); int day = ParamUtil.getInteger(request, "dateDay"); int hour = ParamUtil.getInteger(request, "dateHour"); int minute = ParamUtil.getInteger(request, "dateMinute"); int amPm = ParamUtil.getInteger(request, "dateAmPm"); if (amPm == Calendar.PM) { hour += 12; } ServiceContext serviceContext = ServiceContextFactory.getInstance(Event.class.getName(), request); Event event = null; if (eventId <= 0) { event = EventServiceUtil.addEvent( serviceContext.getScopeGroupId(), name, description, month, day, year, hour, minute, serviceContext); } else { event = EventServiceUtil.getEvent(eventId); event = EventServiceUtil.updateEvent( serviceContext.getUserId(), eventId, name, description, month, day, year, hour, minute, serviceContext); } return event; } public void restoreEvent( final ActionRequest request, final ActionResponse response) throws Exception { ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); long[] restoreEntryIds = StringUtil.split( ParamUtil.getString(request, "restoreEntryIds"), 0L); for (long restoreEntryId : restoreEntryIds) { EventLocalServiceUtil.restoreEntryFromTrash( themeDisplay.getUserId(), restoreEntryId); } } private static Log _log = LogFactoryUtil.getLog(SampleRecycleBinPortlet.class); }
true
cd1d35f17b1125f1f20de2b43dd1751c930c5165
Java
danielferrao02/java
/Aula01/exercicios/Exercicio04.java
UTF-8
1,399
4.0625
4
[]
no_license
package exercicios; import java.util.Scanner; public class Exercicio04 { public static void main(String[] args) { //1kwatt é 1/500 avos do salario minimo Scanner entrada = new Scanner(System.in); //faça um programa que receba o valor de salario minimo System.out.println("Qual o valor do salario mínimo? "); double salmin = entrada.nextDouble(); //Receba a quantidade de kWatts consumida por uma residencia System.out.println("Qual quantidade de Kwatts consumidas? "); double kwatt = entrada.nextDouble(); //System.out.printf(FORMATO, Valor1, Valor2,...) // %f - numero com decimal, arredondando // %d - numero inteiro // %s - string // %.xf - x = numero de casas decimais // Então exiba: // o valor em reais de cada Kwatt double valor1 = salmin/500; System.out.printf(" O valor, em reais, de cada kWatt é %.2f\n", valor1); //printf utiliza valores flutuantes // O valor a ser pago por essa residencia double valor2 = valor1 * kwatt; System.out.printf("O valor a ser pago por essa residencia é %.2f\n", valor2); // o valor a ser pago com desconto de 15% System.out.printf("O valor a ser pago com 15%% de desconto é %.2f\n", valor2*0.85); entrada.close(); } }
true
67348d30862b58fa9b82c1ab916987e9ff10912e
Java
shalija/employer-service
/src/main/java/com/inpixon/interview/employers/data/EmployerRepository.java
UTF-8
460
1.851563
2
[]
no_license
package com.inpixon.interview.employers.data; import com.inpixon.interview.employers.model.Employer; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.mongodb.repository.Query; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface EmployerRepository extends MongoRepository<Employer, String> { List<Employer> findByCandidateId(String candidateId); }
true
79a33c05330c4b44565eef10dbefbf32c32611ba
Java
shrirang91/VendingMachine
/src/gui/VendingMachineFrame.java
UTF-8
2,544
2.484375
2
[]
no_license
package gui; import javax.swing.*; import java.awt.*; import java.awt.event.*; import vendsys.*; import app.*; public class VendingMachineFrame extends JFrame { private VirtualVendingMachine m_vvmMachine; private PayPanel m_ppPayPanel; private SelectorPanel m_spSelectorPanel; private OutputDisplayPanel m_odpOutputDisplayPanel; private DispenserPanel m_dpDispenserPanel; private YourMoneyFrame m_ymfYourMoney; public VendingMachineFrame(VirtualVendingMachine vvmMachine) throws java.io.IOException { m_vvmMachine = vvmMachine; m_ppPayPanel = new PayPanel(m_vvmMachine.getPayMachine()); m_spSelectorPanel = new SelectorPanel(m_vvmMachine.getProductSelector()); m_odpOutputDisplayPanel = new OutputDisplayPanel(m_vvmMachine.getOutputDisplay()); m_dpDispenserPanel = new DispenserPanel(m_vvmMachine.getProductDispenser()); JPanel jpEast = new JPanel(); JPanel jpEastCenter = new JPanel(); JPanel jpCenter = new JPanel(); Container cpPane = this.getContentPane(); cpPane.setLayout(new BorderLayout()); jpEast.setLayout(new BorderLayout()); jpEastCenter.setLayout(new BorderLayout()); jpEastCenter.add(m_spSelectorPanel, BorderLayout.WEST); jpEastCenter.add(m_ppPayPanel, BorderLayout.CENTER); jpEast.add(jpEastCenter, BorderLayout.CENTER); jpEast.add(m_odpOutputDisplayPanel, BorderLayout.NORTH); cpPane.add(jpEast, BorderLayout.EAST); ImageIcon iiVM = Utilities.readIcon("images/VENDING_MACHINE.JPG"); JLabel jlVM = new JLabel(iiVM, JLabel.CENTER); jlVM.setAlignmentX(JComponent.CENTER_ALIGNMENT); jpCenter.setLayout(new BoxLayout(jpCenter, BoxLayout.Y_AXIS)); jpCenter.add(Box.createVerticalStrut(10)); jpCenter.add(jlVM); jpCenter.add(m_dpDispenserPanel); cpPane.add(jpCenter, BorderLayout.CENTER); setSize(650, 512); setTitle("Virtual Vending Machine"); m_ymfYourMoney = new YourMoneyFrame(this); m_ymfYourMoney.setLocationRelativeTo(this); m_ymfYourMoney.setDefaultCloseOperation(EXIT_ON_CLOSE); m_ppPayPanel.setYourMoneyFrame(m_ymfYourMoney); } public void setVisible(boolean b) { super.setVisible(b); m_ymfYourMoney.setVisible(b); } public PayPanel getPayPanel() { return m_ppPayPanel; } public SelectorPanel getSelectorPanel() { return m_spSelectorPanel; } public OutputDisplayPanel getOutputDisplayPanel() { return m_odpOutputDisplayPanel; } public DispenserPanel getDispenserPanel() { return m_dpDispenserPanel; } }
true
17b7cb16df423cd8e32d36c374c304c7e56034f9
Java
khanhkd1/repo-all-subjects-in-KMA
/ThucHanhKTLT/ThucHanhKTLT/ThucHanhJava_KTLT/KeThuaDaHinhTruuTuong/Bai3/Bai3.java
UTF-8
1,294
3.078125
3
[]
no_license
package KeThuaDaHinhTruuTuong.Bai3; import java.lang.reflect.Array; import java.util.Arrays; import java.util.Scanner; public class Bai3 { public static int[] Nhap(int soDau,int n){ Scanner scan = new Scanner(System.in); int[] arr = new int[n]; arr[0] = soDau; for (int i=1; i<n; i++){ System.out.print("Nhap phan tu thu "+(i+1)+": "); arr[i] = scan.nextInt(); } return arr; } public static double[] Nhap(double soDau, int n){ Scanner scan = new Scanner(System.in); double[] arr = new double[n]; arr[0] = soDau; for (int i=1; i<n; i++){ System.out.print("Nhap phan tu thu "+(i+1)+": "); arr[i] = scan.nextDouble(); } return arr; } public static void main(String[] args) { Scanner scan = new Scanner(System.in); // Object[] arr = new Object[20]; double[] arr = new double[20]; System.out.print("Nhap so luong phan tu: "); int n = scan.nextInt(); System.out.print("Nhap phan tu thu 1: "); double sodau = scan.nextDouble(); if ((sodau - (int)sodau) == 0){ sodau = (int)sodau; // int arr = new int[20]; } arr = Nhap(sodau, n); } }
true
b0e12941fe77bac4343cb5497eceea5ee391ff69
Java
lucasko/spring-boot-stateless-env
/src/main/java/org/app/config/LoginFilter.java
UTF-8
4,177
2.28125
2
[]
no_license
package org.app.config; import java.io.BufferedReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.app.service.UserService; import org.json.JSONObject; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.User; import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; public class LoginFilter extends AbstractAuthenticationProcessingFilter { public static final String TOKEN_PREFIX = "Bearer "; public static final String HEADER_STRING = "Authorization"; public static final String SECRET = "secretkey"; public static final long EXPIRATION_TIME = 864_000_000; // 10 days private UserService userservice; public LoginFilter(String url, AuthenticationManager authManager, UserService userService ) { super(new AntPathRequestMatcher(url)); setAuthenticationManager(authManager); this.userservice = userService; } @Override public Authentication attemptAuthentication(javax.servlet.http.HttpServletRequest req, HttpServletResponse arg1) throws AuthenticationException, IOException, ServletException { BufferedReader br = req.getReader(); StringBuffer bf = new StringBuffer(); String str1; while ((str1 = br.readLine()) != null) bf.append(str1); String body = bf.toString(); JSONObject json = null; String account = null; String password = null; try { json = new JSONObject(body); account = json.getString("account"); password = json.getString("password"); } catch (Exception e) { throw new ServletException("Invalid JSON Format"); } if (account == null || password == null) { throw new ServletException("Please fill in account and password"); } org.app.model.User user = userservice.findByAccount(account); if (user == null) { throw new ServletException("Invalid Account or Password"); } if (!user.getPassword().equals(password)) { throw new ServletException("Invalid Password"); } List<Role> roles = new ArrayList<Role>(); roles.add(Role.valueOf(user.getRole())); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(account, password, roles); return this.getAuthenticationManager().authenticate(token); } @Override protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse response, FilterChain chain, Authentication auth) throws IOException, ServletException { System.out.println(">>> successfulAuthentication"); String username = ((User) auth.getPrincipal()).getUsername(); String role = userservice.findByAccount(username).getRole(); // res.addHeader(HEADER_STRING, TOKEN_PREFIX + jwttoken); if (auth != null) { List<GrantedAuthority> updatedAuthorities = new ArrayList<GrantedAuthority>(); updatedAuthorities.add(new SimpleGrantedAuthority(role)); User user = new User(auth.getName(), "", true, true, true, true, updatedAuthorities); Authentication newAuth = new UsernamePasswordAuthenticationToken(user, auth.getCredentials(), updatedAuthorities); SecurityContext securityContext = SecurityContextHolder.getContext(); securityContext.setAuthentication(newAuth); } JSONObject json = new JSONObject(); json.put("success", true); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(json.toString()); } }
true
11405edfd89a1c407f37de869c12bf0d25c4eb8e
Java
bugouzhi/workspace
/MixDB/src/misc/HCDCIDETD.java
UTF-8
10,912
2.125
2
[]
no_license
package misc; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.HashSet; import msgf.Histogram; import msutil.AminoAcidSet; import msutil.Composition; import msutil.CompositionFactory; import msutil.IonType; import msutil.Peptide; import msutil.SpectraIterator; import msutil.Spectrum; import parser.BufferedLineReader; import parser.MgfSpectrumParser; import parser.MzXMLSpectraMap; public class HCDCIDETD { public static void main(String argv[]) throws Exception { // generateAnnotatedSpectra(); // analyzeFragmentErrors(); // printParentMassErrorDist("CID"); // compositionMSGF(); // aminoAcidMSGF(); // analyzeMSGFResults(false); // findGoodAAConst(); // approxCompGraphTest(); } static class ExtComposition { int number; // public ExtComposition(int c, int h, int n, int o, int s) { // // MSB 6 (C) 13 (H) 5 (N) 5 (O) 3 (S) // number = c*0x04000000 + h*0x00002000 + n*0x00000100 + o*0x00000008 + s; // } public ExtComposition(int c, int h, int n, int o, int s) { int newC = c % 43; int newH = h + c/43*512 + n/19*264 + o/31*492 + s/7*222; int newN = n % 19; int newO = o % 31; int newS = s % 7; number = newC*0x04000000 + newH*0x00002000 + newN*0x00000100 + newO*0x00000008 + newS; } public int getC() { return (number & 0xFC000000) >>> 26; } public int getH() { return (number & 0x03FFE000) >> 13; } public int getN() { return (number & 0x00001F00) >> 8; } public int getO() { return (number & 0x000000F8) >> 3; } public int getS() { return (number & 0x00000007); } public int getNumber() { return number; } @Override public int hashCode() { return number; } @Override public boolean equals(Object obj) { if(obj instanceof ExtComposition) { ExtComposition other = (ExtComposition)obj; if(number == other.number) return true; } return false; } @Override public String toString() { return new String(getC()+" "+getH()+" "+getN()+" "+getO()+" "+getS()); } public float getMass() { return (float)(getC()*Composition.C+getH()*Composition.H+getN()*Composition.N+getO()*Composition.O+getS()*Composition.S); } } public static void approxCompGraphTest() throws Exception { int maxLength = 30; AminoAcidSet aaSet = AminoAcidSet.getStandardAminoAcidSetWithFixedCarbamidomethylatedCys(); CompositionFactory allCompositions = new CompositionFactory(aaSet, null, maxLength); HashSet<ExtComposition> approxCompSet = new HashSet<ExtComposition>(); System.out.println("Composition building done."); float maxErr = 0; Composition worstComp = Composition.NIL; for(int n : allCompositions.getData()) { Composition c = new Composition(n); int numC = c.getC(); int numH = c.getH(); int numN = c.getN(); int numO = c.getO(); int numS = c.getS(); ExtComposition newComp = new ExtComposition(numC, numH, numN, numO, numS); approxCompSet.add(newComp); float err = (newComp.getMass()-c.getMass()); if(Math.abs(err) > maxErr) { maxErr = Math.abs(err); worstComp = c; } // System.out.println(c+"\t"+err); } System.out.println("MaxErr\t"+worstComp.toString()+"\t"+worstComp.getMass()+"\t"+maxErr); System.out.println("CompositionSize\t"+allCompositions.size()); System.out.println("Size\t" + approxCompSet.size()); } public static void findGoodAAConst() throws Exception { // System.out.println(Composition.C*Constants.INTEGER_MASS_SCALER-Math.round(Composition.C)); // System.out.println(Composition.H*Constants.INTEGER_MASS_SCALER-Math.round(Composition.H)); // System.out.println(Composition.N*Constants.INTEGER_MASS_SCALER-Math.round(Composition.N)); // System.out.println(Composition.O*Constants.INTEGER_MASS_SCALER-Math.round(Composition.O)); // System.out.println(Composition.S*Constants.INTEGER_MASS_SCALER-Math.round(Composition.S)); double target = Composition.S; double base = Math.abs(target-Composition.H*Math.round(target/Composition.H)); // double base = Math.abs(target*Constants.INTEGER_MASS_SCALER-Math.round(target)); ArrayList<Integer> bestI = new ArrayList<Integer>(); ArrayList<Integer> bestJ = new ArrayList<Integer>(); ArrayList<Double> diffList = new ArrayList<Double>(); for(int i=1; i<100; i++) { for(int j=1; j<1000; j++) { double diff = Math.abs(target*i - Composition.H*j); if(diff < base) { bestI.add(i); bestJ.add(j); diffList.add(target*i - Composition.H*j); } } } System.out.println("Base: " + base); for(int i=0; i<bestI.size(); i++) System.out.println(bestI.get(i)+"\t"+bestJ.get(i)+"\t"+diffList.get(i)); } public static void analyzeMSGFResults(boolean target) throws Exception { String fileName = "/home/sangtaekim/Developments/MS_Java/bin/PNNLCompGraph.txt"; // String fileName = "/home/sangtaekim/Developments/MS_Java/bin/PNNLAAGraph.txt"; String s; BufferedLineReader in = new BufferedLineReader(fileName); // while(!(s=in.readLine()).endsWith("54220")) // continue; in.readLine(); while((s=in.readLine()) != null) { String[] token = s.split("\t"); if(token.length != 20) continue; String annotation = token[10]; String pepStr = annotation.substring(annotation.indexOf('.')+1,annotation.lastIndexOf('.')); if(pepStr.length() > 20) continue; String prot = token[8]; if(target && prot.startsWith("Reversed")) continue; if(!target && !prot.startsWith("Reversed")) continue; if(token[19].startsWith("Parent")) continue; float specProb = Float.parseFloat(token[19]); float xcorr = Float.parseFloat(token[5]); System.out.println(specProb+"\t"+xcorr); } } private static AminoAcidSet aaSet = AminoAcidSet.getStandardAminoAcidSet(); public static void analyzeFragmentErrors() throws Exception { String[] methods = {"CID", "ETD", "HCD"}; for(String method : methods) analyzeFragmentErrors(method); } public static void analyzeFragmentErrors(String method) throws Exception { IonType[] ionTypes; File dir = new File(System.getProperty("user.home")+"/Research/Data/CIDETDHCD"); File specFile = new File(dir.getPath()+File.separator+"AnnotatedSpectra/Annotated_"+method+".mgf"); double prefixMass = Composition.H; double suffixMass = Composition.H2O; SpectraIterator itr = new SpectraIterator(specFile.getPath(), new MgfSpectrumParser().aaSet(aaSet)); while(itr.hasNext()) { Spectrum spec = itr.next(); Peptide pep = spec.getAnnotation(); for(int i=0; i<pep.size()-1; i++) { prefixMass += pep.get(i).getAccurateMass(); suffixMass += pep.get(pep.size()-1-i).getAccurateMass(); } } } public static void generateAnnotatedSpectra() throws Exception { String[] methods = {"CID", "ETD", "HCD"}; for(String method : methods) generateAnnotatedSpectra(method); } public static void generateAnnotatedSpectra(String method) throws Exception { File dir = new File(System.getProperty("user.home")+"/Research/Data/CIDETDHCD"); File resultFile = new File(dir.getPath()+File.separator+"AnalysisResults/"+method+"_FDR1pct.txt"); File specFile = new File(dir.getPath()+File.separator+"HCD_CID_ETD_EBCP_LMW_1y_50ug_300rt.mzXML"); File outputFile = new File(dir.getPath()+File.separator+"AnnotatedSpectra/Annotated_"+method+".mgf"); MzXMLSpectraMap map = new MzXMLSpectraMap(specFile.getPath()); PrintStream out = new PrintStream(new BufferedOutputStream(new FileOutputStream(outputFile))); Histogram<Integer> pmErrorHist = new Histogram<Integer>(); BufferedLineReader in = new BufferedLineReader(resultFile.getPath()); in.readLine(); // header String s; int numSpecs = 0; while((s=in.readLine()) != null) { String[] token = s.split("\t"); if(token.length != 25) continue; String db = token[9]; if(db.startsWith("Reverse")) continue; int scanNum = Integer.parseInt(token[2]); Spectrum spec = map.getSpectrumBySpecIndex(scanNum); int charge = Integer.parseInt(token[4]); spec.setCharge(charge); float expMass = spec.getParentMass(); String annotation = token[11]; Peptide pep = aaSet.getPeptide(annotation.substring(annotation.indexOf('.')+1, annotation.lastIndexOf('.'))); float theoMass = pep.getParentMass(); float parentMassError = expMass - theoMass; float parentMassErrorPPM = parentMassError*1e6f/theoMass; if(parentMassErrorPPM > 50 || parentMassErrorPPM < -50) { System.out.println(annotation + " " + expMass + " " + theoMass + " " + parentMassErrorPPM); } else if(parentMassErrorPPM < 20 && parentMassErrorPPM > -20) { spec.setAnnotation(pep); spec.outputMgf(out); numSpecs++; } pmErrorHist.add(Math.round(parentMassErrorPPM)); } out.close(); System.out.println("Done: " + numSpecs + " spectra."); pmErrorHist.printSorted(); } public static void printParentMassErrorDist(String method) throws Exception { File dir = new File(System.getProperty("user.home")+"/Research/Data/CIDETDHCD"); File resultFile = new File(dir.getPath()+File.separator+"AnalysisResults/"+method+"_FDR1pct.txt"); File specFile = new File(dir.getPath()+File.separator+"HCD_CID_ETD_EBCP_LMW_1y_50ug_300rt.mzXML"); File outputFile = new File(dir.getPath()+File.separator+"AnnotatedSpectra/Annotated_"+method+".mgf"); MzXMLSpectraMap map = new MzXMLSpectraMap(specFile.getPath()); Histogram<Integer> pmErrorHistPPM = new Histogram<Integer>(); Histogram<Integer> pmErrorHistDa = new Histogram<Integer>(); BufferedLineReader in = new BufferedLineReader(resultFile.getPath()); in.readLine(); // header String s; int numSpecs = 0; while((s=in.readLine()) != null) { String[] token = s.split("\t"); if(token.length != 25) continue; String db = token[9]; if(db.startsWith("Reverse")) continue; int scanNum = Integer.parseInt(token[2]); Spectrum spec = map.getSpectrumBySpecIndex(scanNum); int charge = Integer.parseInt(token[4]); spec.setCharge(charge); float expMass = spec.getParentMass(); String annotation = token[11]; Peptide pep = aaSet.getPeptide(annotation.substring(annotation.indexOf('.')+1, annotation.lastIndexOf('.'))); float theoMass = pep.getParentMass(); float parentMassError = expMass - theoMass; float parentMassErrorPPM = parentMassError*1e6f/theoMass; if(parentMassErrorPPM > 50 || parentMassErrorPPM < -50) { System.out.println(annotation + " " + expMass + " " + theoMass + " " + parentMassErrorPPM); } numSpecs++; pmErrorHistPPM.add(Math.round(parentMassErrorPPM)); pmErrorHistDa.add(Math.round(parentMassError*1000)); } System.out.println("PPM"); pmErrorHistPPM.printSorted(); System.out.println("\tDa"); pmErrorHistDa.printSorted(); } }
true
7008f36451fbe47f9ba4a00e8d7c3f9085598ab7
Java
gautamk/RESOLVE
/src/main/java/edu/clemson/cs/r2jt/typeandpopulate/programtypes/PTGeneric.java
UTF-8
1,618
2.46875
2
[ "BSD-3-Clause", "MIT" ]
permissive
/** * PTGeneric.java * --------------------------------- * Copyright (c) 2014 * RESOLVE Software Research Group * School of Computing * Clemson University * All rights reserved. * --------------------------------- * This file is subject to the terms and conditions defined in * file 'LICENSE.txt', which is part of this source code package. */ package edu.clemson.cs.r2jt.typeandpopulate.programtypes; import edu.clemson.cs.r2jt.typeandpopulate.MTNamed; import edu.clemson.cs.r2jt.typeandpopulate.MTType; import edu.clemson.cs.r2jt.typeandpopulate.entry.FacilityEntry; import java.util.Map; import edu.clemson.cs.r2jt.typereasoning.TypeGraph; public class PTGeneric extends PTType { private final String myName; public PTGeneric(TypeGraph g, String name) { super(g); myName = name; } public String getName() { return myName; } @Override public MTType toMath() { return new MTNamed(getTypeGraph(), myName); } @Override public PTType instantiateGenerics( Map<String, PTType> genericInstantiations, FacilityEntry instantiatingFacility) { PTType result = this; if (genericInstantiations.containsKey(myName)) { result = genericInstantiations.get(myName); } return result; } @Override public boolean equals(Object o) { boolean result = (o instanceof PTGeneric); if (result) { PTGeneric oAsPTGeneric = (PTGeneric) o; result = myName.equals(oAsPTGeneric.getName()); } return result; } }
true
d1f74ac2f33de03b3b0a3d0909ed7d8c6f7d5929
Java
Giancarlo2709/programming-reactive
/rxjava2/src/main/java/com/everis/reactivex/observable/ObservableCallable.java
UTF-8
2,505
3.453125
3
[]
no_license
package com.everis.reactivex.observable; import io.reactivex.rxjava3.core.Observable; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; /* * Si necesita realizar un cálculo o acción y luego emitirlo, puede usar * Observable.just () (o Single.just () o Maybe.just (), del cual aprenderemos * luego). Pero a veces, queremos hacer esto de manera perezosa o diferida. Además, si eso * procedimiento arroja un error, queremos que se emita en la cadena Observable a través de * onError () en lugar de arrojar el error en esa ubicación de la manera tradicional de Java. por * instancia, si intenta ajustar Observable.just () alrededor de una expresión que divide 1 por * 0, se lanzará la excepción, no se emitirá hasta Observer: * */ public class ObservableCallable { public static void main(String[] args) { System.out.println(" applyOptionalOfNullable "); applyOptionalOfNullable(); System.out.println("callable"); //createFromCallableProblem(); System.out.println("createFromCallableResolveProblem"); createFromCallableResolveProblem(); } private static void applyOptionalOfNullable() { List<String> list = null; /*list.add("Giancarlo"); list.add("Elvis"); list.add("Yarleque"); list.add("Juarez");*/ List<String> list2 = Optional.ofNullable(list) .orElseGet(ArrayList::new) .stream() .map(s -> s + " xxx ") .collect(Collectors.toList()); System.out.println(list2); } private static void createFromCallableProblem() { Observable.just(1/0) .subscribe(i -> System.out.println("RECEIVED: " + i), e -> System.out.println("Error captured: " + e)); } /* * Si vamos a ser reactivos en nuestro manejo de errores, esto puede no ser deseable. Quizás tú * quisiera que el error se emitiera por la cadena hacia el observador donde estará * manejado. Si ese es el caso, use Observable.fromCallable () en su lugar, ya que acepta un * proveedor lambda <T> y emitirá cualquier error que ocurra hasta Observer: */ private static void createFromCallableResolveProblem() { Observable.fromCallable(() -> 1/0) .subscribe(i -> System.out.println("RECEIVED: " + i), e -> System.out.println("Error captured: " + e)); } }
true
b801c40ff1dcfbda7da37be04cef56c230edccb8
Java
MdAzhar123/PixoFinal
/server/Pixogram/src/main/java/com/social/imageApp/Pixogram/dao/MyMediaDao.java
UTF-8
426
1.796875
2
[]
no_license
package com.social.imageApp.Pixogram.dao; import java.util.List; import org.springframework.data.repository.CrudRepository; import com.social.imageApp.Pixogram.model.Comment; import com.social.imageApp.Pixogram.model.Media; public interface MyMediaDao extends CrudRepository<Media, Integer> { List<Media> findAllByUserId(int userId); Media findByMediaId(int mediaId); List<Comment> findAllBymediaId(int mediaId); }
true
1df1ca5fc6d3e55e9389615e3b30242e161f485c
Java
vinaysshenoy/JUnitParams
/src/main/java/junitparams/converters/Nullable.java
UTF-8
853
2.5625
3
[ "Apache-2.0" ]
permissive
package junitparams.converters; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import junitparams.Parameters; /** * Allows test null values defined as a String array in {@link Parameters} * * @author Peter Jurkovic * * <p> * Example: * <pre> * {@literal @}Test * {@literal @}Parameters({" null "}) * public void shouldBeNull({@literal @}Nullable String value) { * assertThat(value).isNull(); * } * </pre> * </p> */ @Retention(RetentionPolicy.RUNTIME) @Param(converter = NullableConverter.class) @Target({ElementType.ANNOTATION_TYPE, ElementType.PARAMETER}) public @interface Nullable { /** * Defines parameter value which will be replaced by Java null */ String nullIdentifier() default "null"; }
true
327a99f97414496566e02b2c03fc6ff557abe206
Java
BakytEshaliev/TherapiApp
/app/src/main/java/com/example/therapiapp/other/Datenschutz.java
UTF-8
713
1.773438
2
[]
no_license
package com.example.therapiapp.other; import androidx.appcompat.app.AppCompatActivity; import androidx.constraintlayout.widget.ConstraintLayout; import android.os.Bundle; import android.widget.TextView; import com.example.therapiapp.BaseActivity; import com.example.therapiapp.R; public class Datenschutz extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_datenschutz); ConstraintLayout constraintLayout = findViewById(R.id.includeDatenschutz); TextView textView = constraintLayout.findViewById(R.id.toolbar_title); textView.setText("Datenschutz"); } }
true
5a8b618266d0fada6c3f408cb34bb2a5c9b38710
Java
SplendorAnLin/paymentSystem
/account/account-core/src/main/java/com/yl/account/core/facade/impl/AccountTallyCreditFacadeImpl.java
UTF-8
9,413
1.8125
2
[]
no_license
/** * */ package com.yl.account.core.facade.impl; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import com.lefu.commons.utils.lang.AmountUtils; import com.lefu.commons.utils.lang.DateUtils; import com.lefu.commons.utils.lang.JsonUtils; import com.yl.account.api.bean.AccountBussinessInterfaceBean; import com.yl.account.bean.TallyVoucher; import com.yl.account.bean.TradeVoucher; import com.yl.account.core.ExceptionMessages; import com.yl.account.core.exception.BussinessException; import com.yl.account.core.exception.BussinessRuntimeException; import com.yl.account.core.facade.AccountTallyFacade; import com.yl.account.core.service.AccountBehaviorService; import com.yl.account.core.service.AccountChangeDetailService; import com.yl.account.core.service.AccountFreezeBalanceDetailService; import com.yl.account.core.service.AccountFreezeDetailService; import com.yl.account.core.service.AccountRecordedDetailService; import com.yl.account.core.service.AccountService; import com.yl.account.core.service.AccountTransitBalanceDetailService; import com.yl.account.core.service.AccountTransitSummaryService; import com.yl.account.core.utils.AccountFundSymbolUtils; import com.yl.account.core.utils.MQsendMessage; import com.yl.account.enums.AccountStatus; import com.yl.account.enums.FreezeHandleType; import com.yl.account.enums.FreezeStatus; import com.yl.account.model.Account; import com.yl.account.model.AccountBehavior; import com.yl.account.model.AccountFreezeDetail; import com.yl.account.model.AccountTransitBalanceDetail; import com.yl.account.model.AccountTransitSummary; import com.yl.mq.producer.client.ProducerClient; import com.yl.mq.producer.client.ProducerMessage; /** * 账务入账处理接口实现 * * @author 聚合支付有限公司 * @since 2016年4月9日 * @version V1.0.0 */ @Component("accountCreditFacade") public class AccountTallyCreditFacadeImpl implements AccountTallyFacade { private static Logger logger = LoggerFactory.getLogger(AccountTallyCreditFacadeImpl.class); @Resource private AccountService accountService; @Resource private AccountTransitBalanceDetailService accountTransitBalanceDetailService; @Resource private AccountTransitSummaryService accountTransitSummaryService; @Resource private AccountRecordedDetailService accountRecordedDetailService; @Resource private AccountBehaviorService accountBehaviorService; @Resource private AccountChangeDetailService accountChangeDetailService; @Resource private AccountFreezeDetailService accountFreezeDetailService; @Resource private AccountFreezeBalanceDetailService accountFreezeBalanceDetailService; @Resource MQsendMessage mqSendMessage; @Resource ProducerClient producerClient; /* * (non-Javadoc) * @see com.yl.account.core.facade.AccountTallyFacade#tally(com.yl.account.api.bean.AccountBussinessInterfaceBean) */ @Override public void tally(TradeVoucher tradeVoucher, AccountBussinessInterfaceBean accountBussinessInterfaceBean) { try { TallyVoucher tallyVoucher = (TallyVoucher) tradeVoucher; logger.info("账务系统接收业务系统请求[入账]指令:{}", JsonUtils.toJsonString(tallyVoucher)); Account account = accountService.findAccountByCode(tallyVoucher.getAccountNo()); if (account == null) throw new BussinessException(ExceptionMessages.ACCOUNT_NOT_EXISTS); if (account.getStatus().equals(AccountStatus.FREEZE) || account.getStatus().equals(AccountStatus.END_IN)) throw new BussinessException( ExceptionMessages.ACCOUNT_STATUS_NOT_NORMAL); if (accountRecordedDetailService.findBy(account.getCode(), tallyVoucher.getTransOrder(), accountBussinessInterfaceBean.getSystemCode(), accountBussinessInterfaceBean.getBussinessCode(), accountBussinessInterfaceBean.getSystemFlowId())) return; if (accountBussinessInterfaceBean.getBussinessCode().equals("TRANSFER") || accountBussinessInterfaceBean.getBussinessCode().equals("ADJUST")) accountChangeDetailService .create(accountBussinessInterfaceBean.getBussinessCode(), new Date(), account.getCode(), account.getType(), account.getStatus(), accountBussinessInterfaceBean.getSystemCode(), tallyVoucher.getTransOrder(), account.getUserNo(), account.getUserRole(), account.getBalance(), account.getFreezeBalance(), account.getTransitBalance(), tallyVoucher.getSymbol(), tallyVoucher.getAmount(), accountBussinessInterfaceBean.getOperator(), accountBussinessInterfaceBean.getRemark()); double creditAmount = AmountUtils.add(tallyVoucher.getAmount(), tallyVoucher.getFeeSymbol() == null || tallyVoucher.getFee() == null ? 0 : AccountFundSymbolUtils.convertToRealAmount(tallyVoucher.getFeeSymbol(), tallyVoucher.getFee())); if (creditAmount < 0) throw new BussinessException(ExceptionMessages.ACCOUNT_CREDIT_AMOUNT_NOT_NEGATIVE); Date waitAccountDate = tallyVoucher.getWaitAccountDate() == null ? tallyVoucher.getWaitAccountDate() : DateUtils.getMinTime(tallyVoucher .getWaitAccountDate()); if (waitAccountDate == null || waitAccountDate.compareTo(new Date()) > 0) { AccountTransitBalanceDetail accountTransitBalanceDetail = accountTransitBalanceDetailService.create(account.getCode(), tallyVoucher.getCurrency(), tallyVoucher.getTransOrder(), tallyVoucher.getTransDate(), accountBussinessInterfaceBean.getSystemCode(), tallyVoucher.getAmount(), tallyVoucher.getSymbol(), tallyVoucher.getFee(), tallyVoucher.getFeeSymbol(), accountBussinessInterfaceBean.getBussinessCode(), waitAccountDate); AccountTransitSummary accountTransitSummary = accountTransitSummaryService.findTransitSummaryBy(account.getCode(), waitAccountDate); if (accountTransitSummary == null) accountTransitSummaryService.create(accountTransitBalanceDetail); else { accountTransitSummary.setWaitAccountAmount(AmountUtils.add(accountTransitSummary.getWaitAccountAmount(), creditAmount)); accountTransitSummaryService.addOrSubstractWaitAccountAmount(accountTransitSummary); } accountRecordedDetailService.create(tallyVoucher.getAccountNo(), account.getUserNo(), account.getUserRole(), accountBussinessInterfaceBean.getSystemFlowId(), accountBussinessInterfaceBean.getBussinessCode(), tallyVoucher.getCurrency(), tallyVoucher.getTransOrder(), tallyVoucher.getTransDate(), accountBussinessInterfaceBean.getSystemCode(), waitAccountDate, tallyVoucher.getAmount(), tallyVoucher.getSymbol(), tallyVoucher.getFee(), tallyVoucher.getFeeSymbol(), account.getBalance()); accountService.addValueableAndTransitBalance(account, creditAmount); } else { // 实时入账 accountRecordedDetailService.create(tallyVoucher.getAccountNo(), account.getUserNo(), account.getUserRole(), accountBussinessInterfaceBean.getSystemFlowId(), accountBussinessInterfaceBean.getBussinessCode(), tallyVoucher.getCurrency(), tallyVoucher.getTransOrder(), tallyVoucher.getTransDate(), accountBussinessInterfaceBean.getSystemCode(), waitAccountDate, tallyVoucher.getAmount(), tallyVoucher.getSymbol(), tallyVoucher.getFee(), tallyVoucher.getFeeSymbol(), account.getBalance()); accountService.addOrSubtractValueableBalance(account, creditAmount); AccountBehavior accountBehavior = accountBehaviorService.findAccountBehavior(tallyVoucher.getAccountNo()); if (accountBehavior != null && accountBehavior.getPreFreezeCount() > 0) { List<AccountFreezeDetail> accountFreezeDetails = accountFreezeDetailService.findAccountFreezeDetailBy(tallyVoucher.getAccountNo(), FreezeStatus.PRE_FREEZE_ING); for (AccountFreezeDetail accountFreezeDetail : accountFreezeDetails) { // 需预冻金额 double remainPreFreezeBalance = AmountUtils.subtract(accountFreezeDetail.getPreFreezeBalance(), accountFreezeDetail.getFreezeBalance()); if (creditAmount < remainPreFreezeBalance) { accountFreezeBalanceDetailService.create(accountBussinessInterfaceBean.getSystemCode(), tallyVoucher.getAccountNo(), tallyVoucher.getTransOrder(), creditAmount, null, FreezeHandleType.PRE_FREEZE.name()); accountFreezeDetailService.addFreezeBalance(accountFreezeDetail, creditAmount); accountService.addFreezeBalance(account, creditAmount); break; } else { // 可入账户金额 double valueableCreditBalance = AmountUtils.subtract(creditAmount, remainPreFreezeBalance); accountFreezeBalanceDetailService.create(accountBussinessInterfaceBean.getSystemCode(), tallyVoucher.getAccountNo(), tallyVoucher.getTransOrder(), remainPreFreezeBalance, null, FreezeHandleType.PRE_FREEZE.name()); accountFreezeDetailService.preFreezeComplete(accountFreezeDetail, remainPreFreezeBalance); accountBehavior.setPreFreezeCount(accountBehavior.getPreFreezeCount() - 1); accountBehaviorService.addOrSubtractPreFreezeCount(accountBehavior); accountService.addFreezeBalance(account, remainPreFreezeBalance); creditAmount = valueableCreditBalance; } } } } mqSendMessage.send(tradeVoucher,account.getUserNo(),accountBussinessInterfaceBean.getBussinessCode()); } catch (Exception e) { logger.error("{}", e); throw new BussinessRuntimeException(e.getMessage()); } } }
true
bc9a047ff2e7dd3bb18a07371056319f824e477f
Java
AlexseyOstrovskiy/ClassWork
/lesson5/src/com/company/Main.java
UTF-8
1,169
3.609375
4
[]
no_license
package com.company; public class Main { /* Принципы ООП: 1. Инкапсуялция 2. Полиморфизм 3. Наследование 4. Абстракция */ public static void main(String[] args) { Animal animal = new Animal(); animal.color = "black"; animal.weight = 12.4f; animal.eat(); animal.sleep(); animal.sleep(12); animal.sleep(10,45); System.out.println(animal.color); System.out.println(animal.weight); //ссылочность Animal animal2 = animal; animal2.color = "blue"; System.out.println(animal2.color);//вывеедт blue System.out.println(animal.color);//вывеедт blue test(animal); System.out.println(animal.color); // dog dog = new dog (); dog.color = "white"; dog.weight = 10; dog.sleep(3); dog.breed = "Овчарка"; dog.bark(); dog.eat(); //полиморфизм Animal animal3 = new dog(); animal3.eat(); sleep(animal); sleep(dog); sleep(animal3); } public static void test (Animal a) { a.color = "red"; } //sleep - обобщенный метод public static void sleep (Animal a) { a.sleep(10); } }
true
860194d1e0c1ce9029bec19a28ad2291866f05f2
Java
sdahal1/JavaAugust
/spring/w2d2-springDataIPets/src/main/java/com/dahal/w2d2springDataIPets/controllers/PetController.java
UTF-8
3,079
2.640625
3
[]
no_license
package com.dahal.w2d2springDataIPets.controllers; import java.util.List; import javax.validation.Valid; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import com.dahal.w2d2springDataIPets.models.Pet; import com.dahal.w2d2springDataIPets.services.PetService; @Controller public class PetController { //tell the controller about the service private final PetService petService; public PetController(PetService petService) { this.petService= petService; } @GetMapping("/pets") public String getAllPets(Model model, @ModelAttribute("pet") Pet p){ List<Pet> allPets = this.petService.allPets(); model.addAttribute("allPets", allPets); // Pet p = new Pet(); // model.addAttribute("pet",p); return "index.jsp"; } @GetMapping("/pets/new") public String newPet(@ModelAttribute("pet") Pet pet) { return "newPet.jsp"; } @PostMapping("/pet/create") public String createPet(@Valid @ModelAttribute("pet") Pet pet, BindingResult result, Model model) { if(result.hasErrors()) { List<Pet> allPets = this.petService.allPets(); model.addAttribute("allPets", allPets); return "index.jsp"; } System.out.println(pet.getName()); //request.from[name] System.out.println(pet.getDescription()); //request.form['descrioption] System.out.println(pet.getAge()); this.petService.createPet(pet); return "redirect:/pets"; } @GetMapping("/pet/info/{id}") public String showPetInfo(@PathVariable("id") Long id, Model model) { //using the id coming from the route, we can request from the service to return to us a pet object that has that id Pet p = this.petService.findOnePet(id); model.addAttribute("petToDisplay", p); return "petinfo.jsp"; } @GetMapping("/pet/edit/{id}") public String editPet(@PathVariable("id") Long id, Model model) { //get a pet object so we can send that pet to the edit form to prepopulate with this pets info Pet p = this.petService.findOnePet(id); model.addAttribute("pett", p); return "editPet.jsp"; } @PostMapping("/pet/update/{id}") public String updatePet(@PathVariable("id") Long id, @Valid @ModelAttribute("pett") Pet pet, BindingResult result ) { if(result.hasErrors()) { return "editPet.jsp"; } //if the form doesnt have errors and is filled out properly, then update the pet object // this.petService.updatePetAnotherWay(id, pet.getName(), pet.getDescription(), pet.getAge()); System.out.println(pet.getId()); System.out.println(pet.getName()); this.petService.updatePet(pet); return "redirect:/pets"; } @GetMapping("/pet/delete/{id}") public String deletePet(@PathVariable("id") Long id) { this.petService.deletePet(id); return "redirect:/pets"; } }
true
840688e995505a7b079adc9283ba81985e8f30b5
Java
AmitSinghhub/JSP-and-Servlet
/Online Recharge/src/tingu/Valservlet.java
UTF-8
1,931
2.34375
2
[]
no_license
package tingu; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import service.Connect; import service.Login; @WebServlet("/Val") public class Valservlet extends HttpServlet{ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out=response.getWriter(); String uname=request.getParameter("uname"); String pwd=request.getParameter("pwd"); Login l=new Login(); l.setUsername(uname); l.setPassword(pwd); Connect c=new Connect(); Connection con=c.connectMe(); String query="select * from Login where uname=? and password=?"; try { PreparedStatement pstmt=con.prepareStatement(query); pstmt.setString(1, l.getUsername()); pstmt.setString(2, l.getPassword()); ResultSet rs=pstmt.executeQuery(); if(rs.next()) { //go to welcome page RequestDispatcher rd=request.getRequestDispatcher("Recharge.jsp"); rd.forward(request, response); } else { //go to login page RequestDispatcher rd=request.getRequestDispatcher("Login.jsp"); out.println("<p style='color:red'>Invalid Credentials</p>"); rd.include(request, response); } } catch (SQLException e) { e.printStackTrace(); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
true
b8afc2ddfd0f46c364e84be57dfd209b6ca086e4
Java
Tharindu-Dhananjaya/MC_BOP
/src/mc/kurunegala/bop/model/UpploadService.java
UTF-8
340
2.015625
2
[]
no_license
package mc.kurunegala.bop.model; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import mc.kurunegala.bop.dao.UploadsMapper; @Service public class UpploadService { @Autowired UploadsMapper mapper; public void add(Uploads entity) { mapper.insertSelective(entity); } }
true
769a9e2925a42b2ca6b97663a6354e96e2b46f6d
Java
mikolajgucki/ae-engine
/tools/src/main/java/com/andcreations/ae/launch/image/LaunchImageTest.java
UTF-8
486
2.125
2
[ "MIT" ]
permissive
package com.andcreations.ae.launch.image; import java.io.File; import com.andcreations.ae.color.Color; /** * @author Mikolaj Gucki */ public class LaunchImageTest { /** */ public static void main(String[] args) throws Exception { CenterLaunchImageLayout layout = new CenterLaunchImageLayout( new Color(0,0,0,255),new File("li/icon.png"),0.2); LaunchImage ios = LaunchImage.ios(layout); ios.generate(new File("li/out")); } }
true
e2f5964d46f613312799a71af0a5d22ead01aba0
Java
iay12590/ichat
/tool/socket-tool/src/main/java/com/warden/ichat/tool/core/factory/HandlerFactory.java
UTF-8
1,141
2.21875
2
[]
no_license
package com.warden.ichat.tool.core.factory; import com.warden.ichat.tool.core.handler.BusinessHandler; import com.warden.ichat.tool.core.handler.TransientModelHandler; /** * @author <a href="linjianhua@wxchina.com">JianHua.Lin</a> * @version 1.0.0 * @date 2018/10/11 */ public class HandlerFactory { private volatile static BusinessHandler businessHandler; private volatile static TransientModelHandler transientModelHandler; public static BusinessHandler getBusinessHandle() { if (businessHandler == null) { synchronized (HandlerFactory.class) { if (businessHandler == null) { businessHandler = new BusinessHandler(); } } } return businessHandler; } public static TransientModelHandler getTransientModelHandler() { if (transientModelHandler == null) { synchronized (HandlerFactory.class) { if (transientModelHandler == null) { transientModelHandler = new TransientModelHandler(); } } } return transientModelHandler; } }
true
1ce18cb38b5524e654904bbcc35c74f835c13a45
Java
rsoiffer/BeigeCraft
/src/graphics/Model.java
UTF-8
8,415
2.109375
2
[]
no_license
package graphics; import graphics.Quad.ColoredQuad; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import opengl.Camera; import opengl.ShaderProgram; import util.Resources; import static util.math.MathUtils.mod; import static util.math.MathUtils.vecMap; import util.math.Vec3d; import util.math.Vec4d; import util.rlestorage.IntConverter.IntegerConverter; import util.rlestorage.RLEArrayStorage; import util.rlestorage.RLEColumn; public class Model extends VoxelRenderer<Integer> { private static final Map<String, Model> MODEL_CACHE = new HashMap(); public static Model load(String fileName) { if (!MODEL_CACHE.containsKey(fileName)) { Model s = new Model(fileName); MODEL_CACHE.put(fileName, s); } return MODEL_CACHE.get(fileName); } public static final ShaderProgram MODEL_SHADER = Resources.loadShaderProgramGeom("model"); // Copied from the MagickaVoxel documentation private static final int[] DEFAULT_COLOR_PALETTE = { 0x00000000, 0xffffffff, 0xffccffff, 0xff99ffff, 0xff66ffff, 0xff33ffff, 0xff00ffff, 0xffffccff, 0xffccccff, 0xff99ccff, 0xff66ccff, 0xff33ccff, 0xff00ccff, 0xffff99ff, 0xffcc99ff, 0xff9999ff, 0xff6699ff, 0xff3399ff, 0xff0099ff, 0xffff66ff, 0xffcc66ff, 0xff9966ff, 0xff6666ff, 0xff3366ff, 0xff0066ff, 0xffff33ff, 0xffcc33ff, 0xff9933ff, 0xff6633ff, 0xff3333ff, 0xff0033ff, 0xffff00ff, 0xffcc00ff, 0xff9900ff, 0xff6600ff, 0xff3300ff, 0xff0000ff, 0xffffffcc, 0xffccffcc, 0xff99ffcc, 0xff66ffcc, 0xff33ffcc, 0xff00ffcc, 0xffffcccc, 0xffcccccc, 0xff99cccc, 0xff66cccc, 0xff33cccc, 0xff00cccc, 0xffff99cc, 0xffcc99cc, 0xff9999cc, 0xff6699cc, 0xff3399cc, 0xff0099cc, 0xffff66cc, 0xffcc66cc, 0xff9966cc, 0xff6666cc, 0xff3366cc, 0xff0066cc, 0xffff33cc, 0xffcc33cc, 0xff9933cc, 0xff6633cc, 0xff3333cc, 0xff0033cc, 0xffff00cc, 0xffcc00cc, 0xff9900cc, 0xff6600cc, 0xff3300cc, 0xff0000cc, 0xffffff99, 0xffccff99, 0xff99ff99, 0xff66ff99, 0xff33ff99, 0xff00ff99, 0xffffcc99, 0xffcccc99, 0xff99cc99, 0xff66cc99, 0xff33cc99, 0xff00cc99, 0xffff9999, 0xffcc9999, 0xff999999, 0xff669999, 0xff339999, 0xff009999, 0xffff6699, 0xffcc6699, 0xff996699, 0xff666699, 0xff336699, 0xff006699, 0xffff3399, 0xffcc3399, 0xff993399, 0xff663399, 0xff333399, 0xff003399, 0xffff0099, 0xffcc0099, 0xff990099, 0xff660099, 0xff330099, 0xff000099, 0xffffff66, 0xffccff66, 0xff99ff66, 0xff66ff66, 0xff33ff66, 0xff00ff66, 0xffffcc66, 0xffcccc66, 0xff99cc66, 0xff66cc66, 0xff33cc66, 0xff00cc66, 0xffff9966, 0xffcc9966, 0xff999966, 0xff669966, 0xff339966, 0xff009966, 0xffff6666, 0xffcc6666, 0xff996666, 0xff666666, 0xff336666, 0xff006666, 0xffff3366, 0xffcc3366, 0xff993366, 0xff663366, 0xff333366, 0xff003366, 0xffff0066, 0xffcc0066, 0xff990066, 0xff660066, 0xff330066, 0xff000066, 0xffffff33, 0xffccff33, 0xff99ff33, 0xff66ff33, 0xff33ff33, 0xff00ff33, 0xffffcc33, 0xffcccc33, 0xff99cc33, 0xff66cc33, 0xff33cc33, 0xff00cc33, 0xffff9933, 0xffcc9933, 0xff999933, 0xff669933, 0xff339933, 0xff009933, 0xffff6633, 0xffcc6633, 0xff996633, 0xff666633, 0xff336633, 0xff006633, 0xffff3333, 0xffcc3333, 0xff993333, 0xff663333, 0xff333333, 0xff003333, 0xffff0033, 0xffcc0033, 0xff990033, 0xff660033, 0xff330033, 0xff000033, 0xffffff00, 0xffccff00, 0xff99ff00, 0xff66ff00, 0xff33ff00, 0xff00ff00, 0xffffcc00, 0xffcccc00, 0xff99cc00, 0xff66cc00, 0xff33cc00, 0xff00cc00, 0xffff9900, 0xffcc9900, 0xff999900, 0xff669900, 0xff339900, 0xff009900, 0xffff6600, 0xffcc6600, 0xff996600, 0xff666600, 0xff336600, 0xff006600, 0xffff3300, 0xffcc3300, 0xff993300, 0xff663300, 0xff333300, 0xff003300, 0xffff0000, 0xffcc0000, 0xff990000, 0xff660000, 0xff330000, 0xff0000ee, 0xff0000dd, 0xff0000bb, 0xff0000aa, 0xff000088, 0xff000077, 0xff000055, 0xff000044, 0xff000022, 0xff000011, 0xff00ee00, 0xff00dd00, 0xff00bb00, 0xff00aa00, 0xff008800, 0xff007700, 0xff005500, 0xff004400, 0xff002200, 0xff001100, 0xffee0000, 0xffdd0000, 0xffbb0000, 0xffaa0000, 0xff880000, 0xff770000, 0xff550000, 0xff440000, 0xff220000, 0xff110000, 0xffeeeeee, 0xffdddddd, 0xffbbbbbb, 0xffaaaaaa, 0xff888888, 0xff777777, 0xff555555, 0xff444444, 0xff222222, 0xff111111 }; private Vec3d originalSize; private Vec3d max, min; private RLEArrayStorage<Integer> colors; private int[] colorPalette = DEFAULT_COLOR_PALETTE; private Model(String fileName) { colors = null; colorPalette = DEFAULT_COLOR_PALETTE; byte[] bytes = Resources.loadFileAsBytes("models/" + fileName); int pos = 8; while (pos < bytes.length) { String chunkName = new String(bytes, pos, 4); int chunkSize = readInt(bytes, pos + 4); if (chunkName.equals("SIZE")) { originalSize = new Vec3d(readInt(bytes, pos + 12), readInt(bytes, pos + 16), readInt(bytes, pos + 20)); colors = new RLEArrayStorage(Math.max((int) originalSize.x, (int) originalSize.y), new IntegerConverter()); } if (chunkName.equals("XYZI")) { int numBlocks = readInt(bytes, pos + 12); for (int i = 0; i < numBlocks; i++) { int x = mod(bytes[pos + 16 + 4 * i], 256); int y = mod(bytes[pos + 16 + 4 * i + 1], 256); int z = mod(bytes[pos + 16 + 4 * i + 2], 256); int colorID = mod(bytes[pos + 16 + 4 * i + 3], 256); colors.set(x, y, z, colorID); if (max == null) { max = new Vec3d(x + 1, y + 1, z + 1); min = new Vec3d(x, y, z); } else { max = vecMap(max, new Vec3d(x + 1, y + 1, z + 1), Math::max); min = vecMap(min, new Vec3d(x, y, z), Math::min); } } } if (chunkName.equals("RGBA")) { colorPalette = new int[256]; for (int i = 0; i < 255; i++) { colorPalette[i + 1] = readInt(bytes, pos + 12 + 4 * i); } } pos += 12 + chunkSize; } generate(); colors = null; colorPalette = null; } public Vec3d center() { return max.lerp(min, .5); } @Override protected RLEColumn<Integer> columnAt(int x, int y) { if (x < 0 || x >= originalSize.x || y < 0 || y >= originalSize.y) { return null; } return colors.columnAt(x, y); } @Override protected Quad createQuad(int x, int y, int z, Integer voxel, Vec3d dir) { ColoredQuad q = new ColoredQuad(); q.positionDir(x, y, z, dir); q.colorAmbientOcclusion(getOccludingVoxels(x, y, z, dir)); int colorHex = colorPalette[voxel]; q.r = mod(colorHex, 256) / 255.f; q.g = mod(colorHex >> 8, 256) / 255.f; q.b = mod(colorHex >> 16, 256) / 255.f; return q; } @Override protected Vec3d max() { return max; } @Override protected Vec3d min() { return min; } public Vec3d originalSize() { return originalSize; } private static int readInt(byte[] bytes, int pos) { return mod(bytes[pos], 256) + (mod(bytes[pos + 1], 256) << 8) + (mod(bytes[pos + 2], 256) << 16) + (mod(bytes[pos + 3], 256) << 24); } @Override protected void setShaderUniforms(Vec4d color) { shader().setUniform("projectionMatrix", Camera.camera3d.getProjectionMatrix()); shader().setUniform("color", color); } @Override protected ShaderProgram shader() { return MODEL_SHADER; } public Vec3d size() { return max.sub(min); } @Override protected List<Integer> vertexAttribSizes() { return Arrays.asList(3, 1, 3, 4); } @Override protected Integer voxelAt(int x, int y, int z) { if (x < 0 || x >= originalSize.x || y < 0 || y >= originalSize.y || z < 0 || z >= originalSize.z) { return null; } return colors.get(x, y, z); } }
true
e223ad2b99bd77daf13be3ab3331792cdff073a5
Java
WH2zzZ/wh-java8
/thread/src/main/java/com/oowanghan/thread/status/StateDemo.java
UTF-8
2,074
3.03125
3
[]
no_license
package com.oowanghan.thread.thread.status; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; /** * @Author WangHan * @Create 2020/5/10 6:00 下午 */ @Slf4j public class StateDemo { @Test public void testAllState() throws InterruptedException { Thread t1 = new Thread(() -> { log.info("{} run", Thread.currentThread().getName()); }); Thread t2 = new Thread(() -> { log.info("{} run", Thread.currentThread().getName()); while (true){ } }); t2.start(); Thread t3 = new Thread(() -> { log.info("{} run", Thread.currentThread().getName()); }); t3.start(); Thread t4 = new Thread(() -> { log.info("{} run", Thread.currentThread().getName()); synchronized (StateDemo.class){ try { Thread.sleep(1000000); } catch (InterruptedException e) { } } }); t4.start(); Thread t5 = new Thread(() -> { log.info("{} run", Thread.currentThread().getName()); synchronized (StateDemo.class){ try { Thread.sleep(1000000); } catch (InterruptedException e) { } } }); t5.start(); Thread t6 = new Thread(() -> { log.info("{} run", Thread.currentThread().getName()); try { t2.join(); } catch (InterruptedException e) { } }); t6.start(); Thread.sleep(1000); log.info("{} thread. state:{}", t1.getName(), t1.getState()); log.info("{} thread. state:{}", t2.getName(), t2.getState()); log.info("{} thread. state:{}", t3.getName(), t3.getState()); log.info("{} thread. state:{}", t4.getName(), t4.getState()); log.info("{} thread. state:{}", t5.getName(), t5.getState()); log.info("{} thread. state:{}", t6.getName(), t6.getState()); } }
true
17899cc85d625350528ba118503fcdaabbbeb4f4
Java
ZhangShaojun/SmartTiger
/src/com/smarttiger/demos/FitInsideCenterActivity.java
UTF-8
752
1.828125
2
[]
no_license
package com.smarttiger.demos; import android.os.Bundle; import android.util.Log; import android.view.ViewTreeObserver.OnPreDrawListener; import android.widget.ImageView; import android.widget.TextView; import com.smarttiger.demos.bean.Demo; public class FitInsideCenterActivity extends BaseActivity { public static final Demo DEMO = new Demo(); static { DEMO.setClassName(FitInsideCenterActivity.class); DEMO.setTitle("fitCenter与centerInside"); StringBuilder sb = new StringBuilder(); DEMO.setDescription(sb.toString()); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fit_inside_center); } }
true
b9ba5b5777bc115ab6d86c22147ea20b9266ddcd
Java
shutohoriesb/java-introduction
/Sample.04/src/main/java/com/handson/OperationOrderSample.java
UTF-8
602
3.734375
4
[]
no_license
package com.handson; class OperationOrderSample { public static void main(String[] args) { // 優先順位が変わる例 int sample1 = 1 + 2 * 3; int sample2 = (1 + 2) * 3; System.out.println(sample1); // 7 System.out.println(sample2); // 9 // 優先順位が変わらない例 int height = 170; int weight = 70; boolean result1 = height >= 175 && weight <= 80; boolean result2 = (height >= 175) && (weight <= 80); System.out.println(result1); // false System.out.println(result2); // false } }
true
3b2e749c1f8defd40fd08704ed840e261e0e143d
Java
johnsully83/johnsully83
/src/main/java/com/home/service/workflow/helper/country/CountryWorkflowHelperService.java
UTF-8
2,722
2.25
2
[]
no_license
package com.home.service.workflow.helper.country; import java.util.Date; import java.util.List; import com.home.AppContext; import com.home.dao.MongoDao; import com.home.model.cloud.jpa.Country; import com.home.model.cloud.mongo.MongoCountry; import com.home.model.enumeration.geoplanet.GeoPlanetPlaceType; import com.home.service.model.DtoService; import com.home.service.workflow.helper.AbstractWorkflowHelperService; import com.home.workflow.traversing.implementations.CountryTraverser; import com.jgeoplanet.GeoPlanet; import com.jgeoplanet.GeoPlanetException; import com.jgeoplanet.Place; import com.jgeoplanet.PlaceCollection; public class CountryWorkflowHelperService extends AbstractWorkflowHelperService<Country, Integer> { private final GeoPlanet geoPlanetApi; private final MongoDao<MongoCountry, Integer> countryMongoDao; @SuppressWarnings("unchecked") public CountryWorkflowHelperService() { super(AppContext.getApplicationContext().getBean("countryDtoService", DtoService.class)); this.geoPlanetApi=AppContext.getApplicationContext().getBean("geoPlanetApi", GeoPlanet.class); this.countryMongoDao=AppContext.getApplicationContext().getBean("countryMongoDao", MongoDao.class); } public void queryForCountries(CountryTraverser tasks) throws GeoPlanetException { Place earth = geoPlanetApi.getPlace(1); PlaceCollection countries = earth.getChildren().type(GeoPlanetPlaceType.COUNTRY.getName()); tasks.getWorkflowHelperWrapper().setGeoPlanetCountries(countries.get()); } public void convertCountriesAndMerge(CountryTraverser tasks) { List<Place> countries = tasks.getWorkflowHelperWrapper().getGeoPlanetCountries(); for(Place country : countries) { Country countryDto = new Country(); List<Country> countryDtos = query("name = '"+country.getName()+"'"); if(countryDtos.isEmpty()) { countryDto.setName(country.getName()); add(countryDto); tasks.getWorkflowHelperWrapper().getAllEntities().add(countryDto); continue; } countryDto = countryDtos.get(0); countryDto.setDateLastModified(new Date()); countryDto.setIsDeleted(false); countryDto = merge(countryDto); tasks.getWorkflowHelperWrapper().getAllEntities().add(countryDto); } } public void replicateToMongoDB(CountryTraverser tasks) { List<Country> countries = tasks.getWorkflowHelperWrapper().getAllEntities(); for(Country country : countries) { MongoCountry mongoCountry = new MongoCountry(); mongoCountry.setHasStates(country.getHasStates()); mongoCountry.setName(country.getName()); mongoCountry.setId(country.getPk()); mongoCountry.setId(country.getPk()); countryMongoDao.merge(mongoCountry); } } }
true
f87b568c81814fb7f625fd19dc0df94bd77e4251
Java
ashmichheda/codechef-programs
/Codigo/RenameThisCity.java
UTF-8
1,062
3.515625
4
[]
no_license
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ class Codechef { public static void main (String[] args) throws java.lang.Exception { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t--> 0){ int favourCount = 0, againstCount = 0, neutralCount = 0; int n = sc.nextInt(); int a[] = new int[n]; for(int i = 0; i<n; i++){ a[i] = sc.nextInt(); } // logic to check whether to rename this city or not for(int i = 0; i<n; i++){ if(a[i] == 1){ favourCount++; } else if(a[i] == -1) againstCount++; else{ neutralCount++; } } if(favourCount >= againstCount) System.out.println("YES"); else System.out.println("NO"); } sc.close(); } }
true
eb7092652bbfa065031b97529132c34005abc570
Java
akon1248/SkriptSecurity
/src/main/java/com/akon/skriptsecurity/PacketSecurity.java
UTF-8
1,565
2.203125
2
[ "Apache-2.0" ]
permissive
package com.akon.skriptsecurity; import com.comphenix.protocol.PacketType; import com.comphenix.protocol.events.ListenerPriority; import com.comphenix.protocol.events.PacketAdapter; import com.comphenix.protocol.events.PacketEvent; import java.util.function.Predicate; public class PacketSecurity extends PacketAdapter { public PacketSecurity(PacketType... types) { super(SkriptSecurityMain.getInstance(), ListenerPriority.MONITOR, types); } @Override public void onPacketReceiving(PacketEvent event) { this.checkMundoSK(event); } @Override public void onPacketSending(PacketEvent event) { this.checkMundoSK(event); } private void checkMundoSK(PacketEvent event) { if (!event.isCancelled()) { boolean flag = event.getPacket().getType().isServer(); Predicate<StackTraceElement> predicate; if (flag) { predicate = ste -> ste.getClassName().equals("com.pie.tlatoani.ProtocolLib.PacketManager") && ste.getMethodName().equals("sendPacket"); } else { predicate = ste -> ste.getClassName().equals("com.pie.tlatoani.ProtocolLib.EffReceivePacket") && ste.getMethodName().equals("execute"); } for (StackTraceElement ste : new Throwable().getStackTrace()) { if (predicate.test(ste)) { String message = event.getPacket().getHandle().getClass().getSimpleName() + "の" + (flag ? "送信" : "受信") + "はできません"; String warningMessage = String.format(SkriptSecurityMain.TEMPLATE, message); SkriptSecurityMain.sendSecurityMessage(warningMessage); event.setCancelled(true); } } } } }
true
7960283d45a72d4a170205ad6ace02786e5b99c9
Java
oleggye/tt
/tt-dao/src/test/java/by/bsac/timetable/dao/impl/GroupDAOImplTest.java
UTF-8
7,771
1.976563
2
[]
no_license
package by.bsac.timetable.dao.impl; import static org.assertj.core.api.Assertions.assertThat; import by.bsac.timetable.dao.IFacultyDAO; import by.bsac.timetable.dao.IFlowDAO; import by.bsac.timetable.dao.IGroupDAO; import by.bsac.timetable.dao.exception.DAOException; import by.bsac.timetable.entity.Faculty; import by.bsac.timetable.entity.Flow; import by.bsac.timetable.entity.Group; import by.bsac.timetable.entity.builder.GroupBuilder; import com.github.springtestdbunit.DbUnitTestExecutionListener; import com.github.springtestdbunit.annotation.DatabaseOperation; import com.github.springtestdbunit.annotation.DatabaseSetup; import com.github.springtestdbunit.annotation.DatabaseTearDown; import com.github.springtestdbunit.annotation.ExpectedDatabase; import com.github.springtestdbunit.assertion.DatabaseAssertionMode; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.test.context.support.DirtiesContextTestExecutionListener; import org.springframework.test.context.transaction.TransactionalTestExecutionListener; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:springDBUnitContext.xml") @TestExecutionListeners({DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class, TransactionalTestExecutionListener.class, DbUnitTestExecutionListener.class}) public class GroupDAOImplTest { @Autowired private IGroupDAO dao; @Autowired private IFacultyDAO facultyDao; @Autowired private IFlowDAO flowDao; @Test @DatabaseSetup(value = {"/data/setup/facultySetup.xml", "/data/setup/flowSetup.xml", "/data/setup/groupSetup.xml"}, type = DatabaseOperation.CLEAN_INSERT) @DatabaseTearDown(value = "classpath:data/databaseTearDown.xml", type = DatabaseOperation.CLEAN_INSERT) public void testGetGroupList() throws DAOException { final int expectedSize = 3; List<Group> groupList = dao.getAll(); assertThat(groupList).isNotNull(); assertThat(groupList.size()).isEqualTo(expectedSize); } @Test @DatabaseSetup(value = {"/data/setup/facultySetup.xml", "/data/setup/flowSetup.xml", "/data/setup/groupSetup.xml"}, type = DatabaseOperation.CLEAN_INSERT) @DatabaseTearDown(value = "classpath:data/databaseTearDown.xml", type = DatabaseOperation.CLEAN_INSERT) public void testGetGroupListByFacultyIdOne() throws DAOException { final int expectedSize = 2; final Byte idFaculty = 1; Faculty faculty = facultyDao.getById(idFaculty); List<Group> groupList = dao.getGroupListByFaculty(faculty); assertThat(groupList).isNotNull(); assertThat(groupList.size()).isEqualTo(expectedSize); } @Test @DatabaseSetup(value = {"/data/setup/facultySetup.xml", "/data/setup/flowSetup.xml", "/data/setup/groupSetup.xml"}, type = DatabaseOperation.CLEAN_INSERT) @DatabaseTearDown(value = "classpath:data/databaseTearDown.xml", type = DatabaseOperation.CLEAN_INSERT) public void testGetGroupListByFacultyIdOneAndEduLevelOne() throws DAOException { final int expectedSize = 2; final byte eduLevel = 1; final Byte idFaculty = 1; Faculty faculty = facultyDao.getById(idFaculty); List<Group> groupList = dao.getGroupListByFacultyAndEduLevel(faculty, eduLevel); assertThat(groupList).isNotNull(); assertThat(groupList.size()).isEqualTo(expectedSize); } @Test @DatabaseSetup(value = {"/data/setup/facultySetup.xml", "/data/setup/flowSetup.xml", "/data/setup/groupSetup.xml"}, type = DatabaseOperation.CLEAN_INSERT) @DatabaseTearDown(value = "classpath:data/databaseTearDown.xml", type = DatabaseOperation.CLEAN_INSERT) public void testGetGroupListByFlowOne() throws DAOException { final int expectedSize = 2; final Short idFlow = 1; Flow flow = flowDao.getById(idFlow); List<Group> groupList = dao.getGroupListByFlow(flow); assertThat(groupList).isNotNull(); assertThat(groupList.size()).isEqualTo(expectedSize); } @Test @DatabaseSetup(value = {"/data/setup/facultySetup.xml", "/data/setup/flowSetup.xml", "/data/setup/groupSetup.xml"}, type = DatabaseOperation.CLEAN_INSERT) @DatabaseTearDown(value = "classpath:data/databaseTearDown.xml", type = DatabaseOperation.CLEAN_INSERT) public void testGetGroupListWithSimilarNameByTwoLetters() throws DAOException { final int expectedSize = 2; final String groupName = "СП"; List<Group> groupList = dao.getAllWithSimilarName(groupName); assertThat(groupList).isNotNull(); assertThat(groupList.size()).isEqualTo(expectedSize); } @Test @DatabaseSetup(value = {"/data/setup/facultySetup.xml", "/data/setup/flowSetup.xml", "/data/setup/groupSetup.xml"}, type = DatabaseOperation.CLEAN_INSERT) @DatabaseTearDown(value = "classpath:data/databaseTearDown.xml", type = DatabaseOperation.CLEAN_INSERT) public void testGetGroupListWithSimilarNameByOneLetters() throws DAOException { final int expectedSize = 3; final String groupName = "С"; List<Group> groupList = dao.getAllWithSimilarName(groupName); assertThat(groupList).isNotNull(); assertThat(groupList.size()).isEqualTo(expectedSize); } @Test @DatabaseSetup(value = {"/data/setup/facultySetup.xml", "/data/setup/flowSetup.xml", "/data/setup/groupSetup.xml"}) @ExpectedDatabase(assertionMode = DatabaseAssertionMode.NON_STRICT_UNORDERED, value = "/data/expected/group/addGroup.xml") @DatabaseTearDown(value = "classpath:data/databaseTearDown.xml", type = DatabaseOperation.CLEAN_INSERT) public void testAddGroupWithIdFour() throws DAOException { final short idGroup = 4; final String nameGroup = "СО333"; final byte idFaculty = 2; final byte eduLevel = 2; Faculty faculty = facultyDao.getById(idFaculty); Group group = new GroupBuilder().id(idGroup).faculty(faculty).name(nameGroup) .eduLevel(eduLevel).build(); dao.add(group); } @Test @DatabaseSetup(value = {"/data/setup/facultySetup.xml", "/data/setup/flowSetup.xml", "/data/setup/groupSetup.xml"}) @ExpectedDatabase(assertionMode = DatabaseAssertionMode.NON_STRICT_UNORDERED, value = "/data/expected/group/updateGroup.xml") @DatabaseTearDown(value = "classpath:data/databaseTearDown.xml", type = DatabaseOperation.CLEAN_INSERT) public void testUpdateGroupWithIdTwo() throws DAOException { final short idGroup = 2; final String nameGroup = "СП777"; final byte idFaculty = 2; final short idFlow = 2; final byte eduLevel = 2; Group group = dao.getById(idGroup); Faculty faculty = facultyDao.getById(idFaculty); Flow flow = flowDao.getById(idFlow); group.setNameGroup(nameGroup); group.setFaculty(faculty); group.setFlow(flow); group.setEduLevel(eduLevel); dao.update(group); } @Test @DatabaseSetup(value = {"/data/setup/facultySetup.xml", "/data/setup/flowSetup.xml", "/data/setup/groupSetup.xml"}) @ExpectedDatabase(assertionMode = DatabaseAssertionMode.NON_STRICT_UNORDERED, value = "/data/expected/group/deleteGroup.xml") @DatabaseTearDown(value = "classpath:data/databaseTearDown.xml", type = DatabaseOperation.CLEAN_INSERT) public void testDeleteGroupWithIdOne() throws DAOException { final short idGroup = 1; Group group = dao.getById(idGroup); dao.delete(group); } }
true
cb3de728c1ca3940da15bfba747037f392f31254
Java
MSNMessinger/dat257-Grupp20
/DateIt/app/src/main/java/com/example/dateit/ui/mypage/NotificationsFragment.java
UTF-8
8,806
2.359375
2
[]
no_license
package com.example.dateit.ui.mypage; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProviders; import com.example.dateit.Company; import com.example.dateit.CustomAdapter; import com.example.dateit.MainActivity; import com.example.dateit.R; import java.util.ArrayList; import java.util.List; public class NotificationsFragment extends Fragment { private CustomAdapter customAdapterNotes = null; private CustomAdapter customAdapterFavorites = null; private ImageView heartImg; private ImageView arrowImg; private static boolean showFavorites = true; private static boolean showNotes = true; private TextView addFavoritesText; private TextView addNotesText; private NotificationsViewModel notificationsViewModel; public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { notificationsViewModel = ViewModelProviders.of(this).get(NotificationsViewModel.class); View root = inflater.inflate(R.layout.fragment_notifications, container, false); addFavoritesText = root.findViewById(R.id.addFavoritesText); addNotesText = root.findViewById(R.id.addNoteText); populateListFavorites(root); populateListNotes(root); return root; } /** * Populates the list of favorites with items marked as favorite from DB * @param root */ private void populateListFavorites(View root) { final ListView list = root.findViewById(R.id.listOfFavorites); ArrayList<Company> arrayList = new ArrayList<Company>(); arrayList.addAll(filterFavorites(MainActivity.getList())); if(!arrayList.isEmpty()) { addFavoritesText.setText(""); customAdapterFavorites = new CustomAdapter(getActivity(), arrayList, this, R.id.action_navigation_notifications_to_companyDetails); list.setAdapter(customAdapterFavorites); } //makeListHide(list, !showFavorites); if (showFavorites) { setListViewHeightBasedOnChildren(list); } else { list.setVisibility(View.INVISIBLE); } } /** * Populates the list of items with notes from DB * @param root */ private void populateListNotes(View root) { final ListView list = root.findViewById(R.id.listOfNotes); ArrayList<Company> arrayList = new ArrayList<Company>(); arrayList.addAll(filterNotes(MainActivity.getList())); if(!arrayList.isEmpty()) { addNotesText.setText(""); customAdapterNotes = new CustomAdapter(getActivity(), arrayList, this, R.id.action_navigation_notifications_to_companyDetails); list.setAdapter(customAdapterNotes); } //makeListHide(list, !showNotes); if(showNotes) { setListViewHeightBasedOnChildren(list); } else { list.setVisibility(View.INVISIBLE); } } /** * filters companies by is marked as favorite * @param companies * @return */ private List<Company> filterFavorites(List<Company> companies) { List<Company> favCompanies = new ArrayList<Company>(); for(Company c : companies) { if(c.isFavorite() == 1) { favCompanies.add(c); } } return favCompanies; } /** * filters companies by contains note * @param companies * @return */ private List<Company> filterNotes(List<Company> companies) { List<Company> noteCompanies = new ArrayList<Company>(); for(Company c : companies) { if(c.hasNote()) { noteCompanies.add(c); } } return noteCompanies; } /** * Dynamically sets height od listview based on nb of children * @param listView */ public void setListViewHeightBasedOnChildren(ListView listView) { CustomAdapter listAdapter = (CustomAdapter) listView.getAdapter(); if (listAdapter == null) { // pre-condition return; } int totalHeight = 0; for (int i = 0; i < listAdapter.getCount(); i++) { View listItem = listAdapter.getView(i, null, listView); listItem.measure(0, 0); totalHeight += listItem.getMeasuredHeight(); } ViewGroup.LayoutParams params = listView.getLayoutParams(); params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); listView.setLayoutParams(params); listView.requestLayout(); } private int getListHeight(ListView listView) { CustomAdapter listAdapter = (CustomAdapter) listView.getAdapter(); if (listAdapter == null) { // pre-condition return 0; } int totalHeight = 0; for (int i = 0; i < listAdapter.getCount(); i++) { View listItem = listAdapter.getView(i, null, listView); listItem.measure(0, 0); totalHeight += listItem.getMeasuredHeight(); } return totalHeight; } private void makeListHide(ListView listView, boolean hide){ CustomAdapter listAdapter = (CustomAdapter) listView.getAdapter(); if (listAdapter == null) { // pre-condition return; } int totalHeight = getListHeight(listView); listView.setVisibility(View.VISIBLE); if(hide){ totalHeight = 0; listView.setVisibility(View.INVISIBLE); } ViewGroup.LayoutParams params = listView.getLayoutParams(); params.height = totalHeight; listView.setLayoutParams(params); listView.requestLayout(); } public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); final ListView list = view.findViewById(R.id.listOfFavorites); final ListView notesList = view.findViewById(R.id.listOfNotes); heartImg = view.findViewById(R.id.favoriteImageHeart); if (showFavorites) { heartImg.setImageResource(R.drawable.up_arrow_key); } else { heartImg.setImageResource(R.drawable.down_arrow_key); } heartImg.callOnClick(); heartImg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(showFavorites) { heartImg.setImageResource(R.drawable.down_arrow_key); list.setVisibility(View.INVISIBLE); makeListHide(list, true); showFavorites = false; } else { heartImg.setImageResource(R.drawable.up_arrow_key); showFavorites = true; list.setVisibility(View.VISIBLE); setListViewHeightBasedOnChildren(list); } } }); arrowImg = view.findViewById(R.id.arrowImg); if(showNotes) { arrowImg.setImageResource(R.drawable.up_arrow_key); } else { arrowImg.setImageResource(R.drawable.down_arrow_key); } arrowImg.callOnClick(); arrowImg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(showNotes) { arrowImg.setImageResource(R.drawable.down_arrow_key); notesList.setVisibility(View.INVISIBLE); makeListHide(notesList, true); showNotes = false; } else { arrowImg.setImageResource(R.drawable.up_arrow_key); showNotes = true; notesList.setVisibility(View.VISIBLE); setListViewHeightBasedOnChildren(notesList); } } }); } }
true
ca8faaab950a762e8a76b54803170ca25cac3312
Java
tsmasuo/hellogit
/src/tools/Bonus.java
SHIFT_JIS
927
3.515625
4
[]
no_license
package tools; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Bonus { public static int getBonus( int basePay, String rank) { int rate = 0; if (rank.equals("A")) { rate = 4; } else if (rank.equals("B")) { rate = 3; } else if (rank.equals("C")) { rate = 2; } return basePay * rate; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); System.out.print("͂Ăi~Pʂ̐lj> "); int basePay = Integer.parseInt(br.readLine()); System.out.print("̕]N͂ĂiA|B|C) > "); String rank = br.readLine(); int bonus = Bonus.getBonus(basePay, rank); System.out.printf("{[iX%d~ł\n", bonus); br.close(); } }
true
f11bacba855964f29a8e2bfca04b352c736a89e3
Java
professorjuniel/Projetos
/Pessoal/Boletos/versoes/1.0.0/pagcontascarnes/src/main/java/br/com/pagcontascarne/dao/dados/BoletoDAO.java
UTF-8
255
1.5
2
[]
no_license
package br.com.pagcontascarne.dao.dados; import com.xpert.persistence.dao.BaseDAO; import br.com.pagcontascarne.modelo.dados.Boleto; import javax.ejb.Local; /** * * @author Juniel */ @Local public interface BoletoDAO extends BaseDAO<Boleto> { }
true
8a34880eaa0d87cbc6cf8718a12e537c4554c5ea
Java
xianqiangfu/java
/HashSet/src/HashSetTest.java
GB18030
899
3.453125
3
[]
no_license
import java.util.HashSet; import java.util.Iterator; public class HashSetTest { public static void main(String[] args) { // TODO Auto-generated method stub HashSet hashset = new HashSet(); String a = new String("A"); String b = new String("B"); String c = new String("C"); hashset.add(a); hashset.add(b); hashset.add(c); System.out.println(hashset.size()); String cz = hashset.add(c) ? "˶󲻴":"Ѿ"; System.out.println("ǷӶ: "+ cz); System.out.println(hashset.isEmpty()); System.out.println(hashset.contains("A")); Iterator ir = hashset.iterator(); while (ir.hasNext()) { System.out.println(ir.next()); } System.out.println(hashset.remove("a")); System.out.println(hashset.remove("A")); ir = hashset.iterator(); while(ir.hasNext()) { System.out.println(ir.next()); } } }
true
d006844ac129957ea0ed64af1b16fecbd281bc7a
Java
qiliangwang/Algorithm
/src/compiler/javaCompiler/PdaParser.java
UTF-8
3,079
2.953125
3
[]
no_license
package compiler.javaCompiler; import java.util.Stack; public class PdaParser { enum Grammar { STMT, EXPR, EXPR_PRIME, TERM, TERM_PRIME, FACTOR, NUM_OR_ID, PLUS, SEMI, MULTIPLE, LEFT_PARENT, RIGHT_PARENT }; private Lexer lexer; private Stack<Grammar> pdaStack = new Stack<Grammar>(); public PdaParser(Lexer lexer) { this.lexer = lexer; pdaStack.push(Grammar.STMT); } public void parse() { while (pdaStack.empty() == false) { Grammar action = pdaStack.peek(); switch (action) { case STMT: if (lexer.match(Lexer.EOI)) { pdaStack.pop(); } else { pdaStack.pop(); pdaStack.push(Grammar.STMT); pdaStack.push(Grammar.SEMI); pdaStack.push(Grammar.EXPR); } break; case EXPR: pdaStack.pop(); pdaStack.push(Grammar.EXPR_PRIME); pdaStack.push(Grammar.TERM); break; case TERM: pdaStack.pop(); pdaStack.push(Grammar.TERM_PRIME); pdaStack.push(Grammar.FACTOR); break; case TERM_PRIME: pdaStack.pop(); if (lexer.match(Lexer.TIMES)) { pdaStack.push(Grammar.TERM_PRIME); pdaStack.push(Grammar.FACTOR); pdaStack.push(Grammar.MULTIPLE); } break; case FACTOR: pdaStack.pop(); if (lexer.match(Lexer.NUM_OR_ID)) { pdaStack.push(Grammar.NUM_OR_ID); } else if (lexer.match(Lexer.LP)) { pdaStack.push(Grammar.RIGHT_PARENT); pdaStack.push(Grammar.EXPR); pdaStack.push(Grammar.LEFT_PARENT); } else { parseError(); } break; case EXPR_PRIME: pdaStack.pop(); if (lexer.match(Lexer.PLUS)) { pdaStack.push(Grammar.EXPR_PRIME); pdaStack.push(Grammar.TERM); pdaStack.push(Grammar.PLUS); } break; case NUM_OR_ID: pdaStack.pop(); if (lexer.match(Lexer.NUM_OR_ID) == false) { parseError(); } lexer.advance(); break; case PLUS: pdaStack.pop(); if (lexer.match(Lexer.PLUS) == false) { parseError(); } lexer.advance(); break; case MULTIPLE: pdaStack.pop(); if (lexer.match(Lexer.TIMES) == false) { parseError(); } lexer.advance(); break; case LEFT_PARENT: pdaStack.pop(); if (lexer.match(Lexer.LP) == false) { parseError(); } lexer.advance(); break; case RIGHT_PARENT: pdaStack.pop(); if (lexer.match(Lexer.RP) == false) { parseError(); } lexer.advance(); break; case SEMI: pdaStack.pop(); if (lexer.match(Lexer.SEMI) == false) { parseError(); } lexer.advance(); break; } } } private void parseError() { System.err.println("PDA parse error"); System.exit(1); } }
true
e7d7b3c4e02e5c1c295de3350e982112c02f797b
Java
jmagnotti/katalabaino
/Katalabaino/src/testing/PrintAnalysisOptions.java
UTF-8
1,098
2.828125
3
[]
no_license
package testing; import java.io.File; import java.util.Arrays; public class PrintAnalysisOptions { private static String prettyPrint(String s) { String result = ""; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (Character.isUpperCase(c)) { result = result + "_" + c; } else { result = result + c; } } // return result.toLowerCase().replaceAll("_map", ""); return result.toLowerCase().replaceAll("_splitter", ""); } public static void printMethod(String t, String f) { System.out.println("public void REFL_" + t + prettyPrint(f) + "() {\n\tanalysis.addSplitter(new " + f + "());\n}"); } public static void main(String[] args) { File[] files = new File("/Users/jmagnotti/Workspace/Katalabaino/src/sessions/").listFiles(); Arrays.sort(files); for (File file : files) { if (file.getName().endsWith(".java")) // printMethod("split", file.getName().substring(0, file.getName().length() - 5)); System.out.println("sessionTypes.add(\"" + file.getName().substring(0, file.getName().length()-5) + "\");"); } } }
true
e981c0b2ad12ea846df6fb08d9814feea89a9958
Java
abhijeetvaidya24/INFO-NDVaidya
/src/java/com/adcolony/sdk/aq.java
UTF-8
1,751
2.3125
2
[]
no_license
/* * Decompiled with CFR 0.0. * * Could not load the following classes: * java.io.IOException * java.io.InputStream */ package com.adcolony.sdk; import java.io.IOException; import java.io.InputStream; class aq extends InputStream { InputStream a; int b; aq(InputStream inputStream, int n2, int n3) throws IOException { this.a = inputStream; while (n2 > 0) { n2 -= (int)inputStream.skip((long)n2); } this.b = n3; } public int available() throws IOException { int n2; int n3 = this.a.available(); if (n3 <= (n2 = this.b)) { return n3; } return n2; } public void close() throws IOException { this.a.close(); } public int read() throws IOException { int n2 = this.b; if (n2 == 0) { return -1; } this.b = n2 - 1; return this.a.read(); } public int read(byte[] arrby) throws IOException { return this.read(arrby, 0, arrby.length); } public int read(byte[] arrby, int n2, int n3) throws IOException { int n4; int n5 = this.b; if (n5 == 0) { return -1; } if (n3 > n5) { n3 = n5; } if ((n4 = this.a.read(arrby, n2, n3)) == -1) { return -1; } this.b -= n4; return n4; } public long skip(long l2) throws IOException { int n2 = (int)l2; if (n2 <= 0) { return 0L; } int n3 = this.b; if (n2 > n3) { n2 = n3; } this.b -= n2; while (n2 > 0) { n2 -= (int)this.a.skip(l2); } return l2; } }
true
da6eb52e2391dc1390a9245b9ac0d948ce04d24c
Java
unsajatoi/Unsa-Java
/CopyFileToAnotherFile.java
UTF-8
376
2.796875
3
[]
no_license
//4f. Write a program to copy content of file into another file. package com.whitebox.edu; import java.io.File; public class CopyFileToAnotherFile { public static void main(String a[]){ File file = new File("/home/hduser/"); File[] files = file.listFiles(); for(File f: files){ System.out.println(f.getName()); } } }
true
e7e59872aa9a981269daf46124f789faed62577a
Java
EyeSeeTea/dhis2-android-sdk
/core/src/androidTest/java/org/hisp/dhis/android/core/event/EventCallRealIntegrationShould.java
UTF-8
1,928
1.90625
2
[ "BSD-3-Clause" ]
permissive
package org.hisp.dhis.android.core.event; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import com.google.common.truth.Truth; import org.hisp.dhis.android.core.D2; import org.hisp.dhis.android.core.common.D2Factory; import org.hisp.dhis.android.core.common.EventCallFactory; import org.hisp.dhis.android.core.data.database.AbsStoreTestCase; import org.hisp.dhis.android.core.data.server.RealServerMother; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.util.List; public class EventCallRealIntegrationShould extends AbsStoreTestCase { private D2 d2; @Override @Before public void setUp() throws IOException { super.setUp(); d2 = D2Factory.create(RealServerMother.url, databaseAdapter()); } //This test is commented because technically it is flaky. //It depends on a live server to operate and the login is hardcoded here. //Uncomment in order to quickly test changes vs a real server, but keep it uncommented after. //@Test public void download_number_of_events_according_to_default_limit() throws Exception { retrofit2.Response response = null; response = d2.logIn(RealServerMother.user, RealServerMother.password).call(); Truth.assertThat(response.isSuccessful()).isTrue(); response = d2.syncMetaData().call(); Truth.assertThat(response.isSuccessful()).isTrue(); EventCall eventCall = EventCallFactory.create( d2.retrofit(), databaseAdapter(), "DiszpKrYNg8", 0); eventCall.call(); verifyDownloadedEvents(50); } private void verifyDownloadedEvents(int numEvents) { EventStoreImpl eventStore = new EventStoreImpl(databaseAdapter()); List<Event> downloadedEvents = eventStore.querySingleEvents(); assertThat(downloadedEvents.size(), is(numEvents)); } }
true
8a52df75f8382b513e555baf685c015218b7082e
Java
Kyle1264x/PCE
/me/davejavu/pce/command/vanish.java
UTF-8
5,229
2.296875
2
[]
no_license
package me.davejavu.pce.command; import java.io.File; import java.util.ArrayList; import java.util.List; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.OfflinePlayer; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import me.davejavu.pce.CustomConfig; import me.davejavu.pce.PalCommand; import me.davejavu.pce.PalCraftListener; public class vanish extends PalCommand { public vanish(){} @Override public boolean onCommand(CommandSender sender, Command cmd, String cmdLabel, String[] args) { if (cmd.getName().equalsIgnoreCase("vanish")) { if (sender instanceof Player) { if (permissionCheck(sender, "PalCraftEssentials.command.vanish")) { Player player = (Player) sender; if (args.length > 0) { if (args[0].equalsIgnoreCase("nc") || args[0].equalsIgnoreCase("nochat")) { CustomConfig pC = getConfig(player); boolean canChat = pC.getFC().getBoolean("vanish.chat"); pC.getFC().set("vanish.chat", !canChat); pC.save(); sendMessage(sender, ChatColor.GOLD + "Chat" + ChatColor.WHITE + ": " + (!canChat ? ChatColor.GREEN + "On" : ChatColor.RED + "Off")); return true; } else if (args[0].equalsIgnoreCase("ni") || args[0].equalsIgnoreCase("nointeract")) { CustomConfig pCc = getConfig(player); boolean canInteract = pCc.getFC().getBoolean("vanish.interact"); pCc.getFC().set("vanish.interact", !canInteract); pCc.save(); sendMessage(sender, ChatColor.GOLD + "Interact" + ChatColor.WHITE + ": " + (!canInteract ? ChatColor.GREEN + "On" : ChatColor.RED + "Off")); return true; } else if (args[0].equalsIgnoreCase("check")) { sendMessage(sender, ChatColor.GOLD + "Vanish: " + ChatColor.WHITE + ": " + (isVanished(player) ? ChatColor.GREEN + "On" : ChatColor.RED + "Off")); return true; } else if (args[0].equalsIgnoreCase("fj") || args[0].equalsIgnoreCase("fakejoin")) { Bukkit.broadcastMessage(PalCraftListener.join(player)); setVanish(player, false); warnPWP(player, false); return true; } else if (args[0].equalsIgnoreCase("fq") || args[0].equalsIgnoreCase("fakequit")) { Bukkit.broadcastMessage(PalCraftListener.quit(player)); setVanish(player, true); warnPWP(player, true); return true; } else { sendMessage(sender, ChatColor.RED + "Usage: /v <nc/ni/fj/fq/check>"); return true; } } else { boolean b = toggleVanish(player); sendMessage(sender, ChatColor.GOLD + "Vanish" + ChatColor.WHITE + ": " + (b ? ChatColor.GREEN + "On" : ChatColor.RED + "Off")); return true; } } else { noPermission(cmd.getName(), sender); return true; } } else { sendMessage(sender, ChatColor.RED + "Only players in game can use this command!"); return true; } } return false; } public static void warnPWP(Player player, boolean isVanished) { for (Player p : Bukkit.getOnlinePlayers()) { if (p.hasPermission("PalCraftEssentials.command.vanish")) { p.sendMessage(ChatColor.DARK_AQUA + player.getName() + " " + ChatColor.AQUA + "is now " + (isVanished ? "hidden" : "visible")); } } } public static boolean canChat(Player player) { return getConfig(player).getFC().getBoolean("vanish.chat"); } public static boolean canInteract(Player player) { return getConfig(player).getFC().getBoolean("vanish.interact"); } public static boolean isVanished(Player player) { return getConfig(player).getFC().getBoolean("vanish.boolean"); } public static boolean toggleVanish(Player player) { CustomConfig config = getConfig(player); boolean isVanish = config.getFC().getBoolean("vanish.boolean"); setVanish(player, !isVanish); return !isVanish; } public static void setVanish(Player player, boolean tf) { CustomConfig config = getConfig(player); config.getFC().set("vanish.boolean", tf); if (tf) { config.getFC().set("vanish.interact", false); config.getFC().set("vanish.chat", false); } else { config.getFC().set("vanish.interact", true); config.getFC().set("vanish.chat", true); } config.save(); for (Player p : Bukkit.getOnlinePlayers()) { if (!p.hasPermission("PalCraftEssentials.command.vanish.see")) { if (tf) { p.hidePlayer(player); } else { p.showPlayer(player); } } } } public static List<String> listOnlineVanished() { List<String> v = new ArrayList<String>(); for (OfflinePlayer p : listVanished()) { if (p.isOnline()) { v.add(p.getName()); } } return v; } public static List<OfflinePlayer> listVanished() { List<OfflinePlayer> vanishList = new ArrayList<OfflinePlayer>(); List<String> ret = new ArrayList<String>(); File file = new File("./plugins/PalCraftEssentials/players"); for (String x : file.list()) { ret.add(x.replace(".yml", "")); } for (String r : ret) { CustomConfig config = new CustomConfig("./plugins/PalCraftEssentials/players", r); boolean van = config.getFC().getBoolean("vanish"); if (van) { vanishList.add(Bukkit.getOfflinePlayer(r.replace(".yml", ""))); } } return vanishList; } }
true
859bc029359c7a60b666b34f44cb0a406287108c
Java
982334245/spring-batch
/src/main/java/com/batch/design/patterns/bridge/DrawAPI.java
UTF-8
160
2.21875
2
[]
no_license
package com.batch.design.patterns.bridge; /** * Created by longbao on 18/7/5. */ public interface DrawAPI { void drawCircle(int radius, int x, int y); }
true
5ac9739e34106396ecfce6cd0a46d642570daf55
Java
LSL-Git/HXBlog_V2.0
/src/main/java/com/hx/blog_v2/util/ResultUtils.java
UTF-8
2,937
2.578125
3
[]
no_license
package com.hx.blog_v2.util; import com.hx.blog_v2.domain.ErrorCode; import com.hx.common.interf.common.Code2Msg; import com.hx.common.interf.common.Result; import com.hx.common.result.SimpleResult; import com.hx.common.util.InnerTools; /** * ResultUtils * * @author Jerry.X.He <970655147@qq.com> * @version 1.0 * @date 5/3/2017 8:57 PM */ public final class ResultUtils { // disable constructor private ResultUtils() { InnerTools.assert0("can't instantiate !"); } /** * 根据给定的输入封装一个成功的结果 * * @param code 响应码 * @param msg 响应消息 * @param data 响应数据 * @param extra 额外数据 * @return com.hx.common.result.SimpleResult * @author Jerry.X.He * @date 5/3/2017 9:00 PM * @since 1.0 */ public static Result success(int code, String msg, Object data, Object extra) { return new SimpleResult(true, code, msg, data, extra); } public static Result success(Code2Msg<Integer, String> code2Msg, Object data, Object extra) { return success(code2Msg.code(), code2Msg.msg(), data, extra); } public static Result success(int code, String msg, Object data) { return success(code, msg, data, null); } public static Result success(Code2Msg<Integer, String> code2Msg, Object data) { return success(code2Msg.code(), code2Msg.msg(), data); } public static Result success(Object data, Object extra) { return success(ErrorCode.SUCCESS, data, extra); } public static Result success(Object data) { return success(data, null); } public static Result success() { return success(null); } /** * 根据给定的输入封装一个失败的结果 * * @param code 响应码 * @param msg 响应消息 * @param data 响应数据 * @param extra 额外数据 * @return com.hx.common.result.SimpleResult * @author Jerry.X.He * @date 5/3/2017 9:00 PM * @since 1.0 */ public static Result failed(int code, String msg, Object data, Object extra) { return new SimpleResult(false, code, msg, data, extra); } public static Result failed(Code2Msg<Integer, String> code2Msg, Object data, Object extra) { return failed(code2Msg.code(), code2Msg.msg(), data, extra); } public static Result failed(int code, String msg, Object data) { return failed(code, msg, data, null); } public static Result failed(Code2Msg<Integer, String> code2Msg, Object data) { return failed(code2Msg.code(), code2Msg.msg(), data); } public static Result failed(Object data, Object extra) { return failed(ErrorCode.SYSTEM_ERROR, data, extra); } public static Result failed(Object data) { return failed(data, null); } public static Result failed() { return failed(null); } }
true
6f3ce892d66b39e815740de868b0ce7a75f16cf9
Java
zhuozuozhang/Weather
/weather/src/main/java/com/koterwong/weather/bean/ProvinceBean.java
UTF-8
218
1.570313
2
[]
no_license
package com.koterwong.weather.bean; /** * Author:Koterwong,Data:2016/4/25. * Description: */ public class ProvinceBean { public String ProName; public String ProShort; public String proRemeark; }
true
a794cc343b00ec8df7d0d3019ec0749c53c0cb29
Java
JB-Lee/Server-Time-Syncer
/app/src/main/java/org/cnsl/software/finalproject/contract/Main.java
UTF-8
949
1.867188
2
[]
no_license
package org.cnsl.software.finalproject.contract; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import org.cnsl.software.finalproject.board.BoardItem; import java.util.Date; import java.util.List; public interface Main { interface View { void toggleUrlHeader(); void toggleFabButton(); void boardAddItem(BoardItem item); void boardSetItem(List<BoardItem> list); void setServerTime(Date date); void setHostName(String hostname); void startPostActivity(String user); void startChangePasswordActivity(String id, String email); void scrollTop(); } interface Presenter { void onServerTimeLookup(String url); void onBoardRefresh(SwipeRefreshLayout swipe, String hostname); void onPostArticle(); void onViewCreate(); void onChangePassword(); void afterPostArticle(String category); } }
true
0c9bcb76023a5b8f3c10a17b15f651458af6647b
Java
pysior/DataMining
/GWTGUI/src/main/java/pl/edu/agh/ftj/datamining/server/impl/WekaServiceImpl.java
UTF-8
1,784
2.265625
2
[]
no_license
package pl.edu.agh.ftj.datamining.server.impl; import java.util.List; import pl.edu.agh.ftj.datamining.client.WekaService; import pl.edu.agh.ftj.datamining.server.WekaCommunication; import pl.edu.agh.ftj.datamining.server.WekaCommunicationFactory; import pl.edu.agh.ftj.datamining.server.WekaWrapper; import pl.edu.agh.ftj.datamining.weka.algorithm.WekaAnswer; import pl.edu.agh.ftj.datamining.client.shared.CommunicationType; import pl.edu.agh.ftj.datamining.client.shared.WekaAnswerDTO; import com.google.gwt.user.server.rpc.RemoteServiceServlet; /* * Klasa implementujaca interfejs {@link WekaService}. * @author Tomasz Pyszka */ public class WekaServiceImpl extends RemoteServiceServlet implements WekaService { private static final long serialVersionUID = 1L; private WekaCommunication wekaCommunication; /* * (non-Javadoc) * @see pl.edu.agh.ftj.datamining.gui.WekaService#createCommunication(pl.edu.agh.ftj.datamining.gui.impl.WekaCommunicationFactory.Type) */ @Override public void createCommunication(CommunicationType type) { wekaCommunication = WekaCommunicationFactory.create(type); } /* * (non-Javadoc) * @see pl.edu.agh.ftj.datamining.gui.WekaService#getAlgorithms() */ @Override public List<String> getAlgorithms() { return wekaCommunication.getAlgorithms(); } /* * (non-Javadoc) * @see pl.edu.agh.ftj.datamining.gui.WekaService#runAlgorithm(java.lang.Integer, java.lang.String, java.lang.String, java.lang.String) */ @Override public WekaAnswerDTO runAlgorithm(Integer algorithmType, /*String location,*/ String id, String table, String options) { WekaAnswer wekaAnswer = wekaCommunication.runAlgorithm(algorithmType, id, table, options); WekaWrapper ww = new WekaWrapper(wekaAnswer); return ww.getWekaAnswer(); } }
true
7a31a7880ae9969c9d8f14faf59beb33a098f3ba
Java
locknic/Sudokil
/sudokil/core/src/com/custardgames/sudokil/entities/ecs/components/LiftableComponent.java
UTF-8
367
2.296875
2
[]
no_license
package com.custardgames.sudokil.entities.ecs.components; import com.artemis.Component; public class LiftableComponent extends Component { private boolean lifted; public LiftableComponent() { lifted = false; } public boolean isLifted() { return lifted; } public void setLifted(boolean lifted) { this.lifted = lifted; } }
true
33acb8ed4b59f397f7222aa533e69f1dec1a560a
Java
tobega/tailspin-v0
/src/tailspin/types/Relation.java
UTF-8
4,691
2.625
3
[ "MIT" ]
permissive
package tailspin.types; import tailspin.control.ResultIterator; import tailspin.interpreter.Scope; import tailspin.literals.KeyValueExpression; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; public class Relation implements Processor, Deconstructible { private final Set<Structure> contents; private final Set<String> keys; public Relation(Iterable<Structure> lines) { contents = new HashSet<>(); Set<String> keys = null; for (Structure structure : lines) { if (keys == null) { keys = structure.keySet(); } else if (!keys.equals(structure.keySet())) { throw new IllegalArgumentException("Relation member " + structure + " does not match " + keys); } contents.add(structure); } this.keys = keys == null ? Set.of() : keys; } private Relation(Set<String> keys, Set<Structure> contents) { this.keys = keys; this.contents = contents; } @Override public String toString() { return "{|" + contents.stream().map(Objects::toString).collect(Collectors.joining(", ")) + "|}"; } public Relation union(Relation other) { // Under some conditions we cannot calculate header for empty relations if (other.keys.isEmpty() && other.contents.isEmpty()) return this; if (keys.isEmpty() && contents.isEmpty()) return other; if (!keys.equals(other.keys)) throw new IllegalArgumentException("Can't union " + keys + " with " + other.keys); return new Relation(keys, Stream.concat(contents.stream(), other.contents.stream()).collect( Collectors.toSet())); } public Relation join(Relation other) { Set<String> newKeys = new HashSet<>(keys); newKeys.addAll(other.keys); Set<String> commonKeys = new HashSet<>(keys); commonKeys.retainAll(other.keys); return new Relation(newKeys, contents.stream() .flatMap(left -> other.contents.stream() .filter(right -> commonKeys.stream().allMatch(key -> left.get(key).equals(right.get(key)))) .map(right -> Structure.value( ResultIterator.wrap(ResultIterator.appendResultValue(left.deconstruct(), right.deconstruct())))) ).collect(Collectors.toSet())); } public Relation matching(Relation other) { Set<String> commonKeys = new HashSet<>(keys); commonKeys.retainAll(other.keys); return new Relation(keys, contents.stream() .filter(left -> other.contents.stream() .anyMatch(right -> commonKeys.stream().allMatch(key -> left.get(key).equals(right.get(key)))) ).collect(Collectors.toSet())); } public Relation notMatching(Relation other) { Set<String> commonKeys = new HashSet<>(keys); commonKeys.retainAll(other.keys); return new Relation(keys, contents.stream() .filter(left -> other.contents.stream() .noneMatch(right -> commonKeys.stream().allMatch(key -> left.get(key).equals(right.get(key)))) ).collect(Collectors.toSet())); } public Relation project(List<KeyValueExpression> projections, Object it, Scope scope) { Set<String> newKeys = projections.stream().map(KeyValueExpression::getKey).collect(Collectors.toSet()); Set<Structure> tuples = contents.stream().map(tuple -> tuple.project(projections, it, scope)) .collect(Collectors.toSet()); return new Relation(newKeys, tuples); } public ResultIterator.Flat deconstruct() { if (contents.isEmpty()) { return null; } Iterator<Structure> iterator = contents.iterator(); return () -> { if (!iterator.hasNext()) return null; return iterator.next(); }; } @Override public Transform resolveMessage(String message, Map<String, Object> parameters) { if (message.equals("count")) return (it, params, callingDictionary) -> (long) contents.size(); throw new UnsupportedOperationException("Unknown relation message " + message); } public Relation minus(Relation right) { // Under some conditions we cannot calculate header for empty relations if (right.keys.isEmpty() && right.contents.isEmpty()) return this; if (keys.isEmpty() && contents.isEmpty()) return new Relation(right.keys, Set.of()); if (!keys.equals(right.keys)) throw new IllegalArgumentException("Can't subtract " + right.keys + " from " + keys); Set<Structure> result = new HashSet<>(contents); result.removeAll(right.contents); return new Relation(keys, result); } @Override public int hashCode() { return Objects.hash(keys, contents); } @Override public boolean equals(Object obj) { return (obj instanceof Relation r) && Objects.equals(keys, r.keys) && Objects.equals(contents, r.contents); } }
true
5383b5c967fbb604e3d93f08588d8a74e7964df9
Java
OEarchive/edisonAPITestTool
/src/main/java/Model/DataModels/Alarms/AlarmsHistoryQueryParams.java
UTF-8
1,104
2.40625
2
[]
no_license
package Model.DataModels.Alarms; import com.fasterxml.jackson.annotation.JsonProperty; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.List; public class AlarmsHistoryQueryParams { @JsonProperty("alarms") private List<String> alarms; @JsonProperty("start") private String start; @JsonProperty("end") private String end; public void setStart(String start) { this.start = start; } public void setEnd(String end) { this.end = end; } public void setAlarmNames(List<String> alarms) { this.alarms = alarms; } public String getQueryParamsString() throws UnsupportedEncodingException { String alarmsList = "*"; if( alarms.size() > 0 ){ alarmsList = String.join(",", alarms); } String queryString = String.format( "?alarmNames=%s&start=%s&end=%s", URLEncoder.encode(alarmsList, "UTF-8"), start, end); return queryString; } }
true
e1f0e9cdf169fa4a2b24bd99cfe553d9abaaa248
Java
gongzishuye/design-pattern
/src/main/java/com/bit/sharing/behavior/template/Main.java
UTF-8
250
2.09375
2
[]
no_license
package com.bit.sharing.behavior.template; /** * @author chen lu * @date 2017/10/11 * @time 22:29 */ public class Main { public static void main(String[] args) { Template template = new Realization(); template.flow(); } }
true
6233d4a8030d0648bc9b92a65d286d9eba7c7225
Java
gkossareva/JavaProgrammingB15Online
/src/Repl/Repl51.java
UTF-8
521
3.15625
3
[]
no_license
package Repl; import java.util.*; public class Repl51 { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n1 = s.nextInt(); int n2 = s.nextInt(); int n3 = s.nextInt(); if (n1 > n2 && n1 > n3) { System.out.println("n1 is bugger"); } if (n2 > n3 && n2 > n1) { System.out.println("n2 is bugger"); } if (n3 > n2 && n3 > n1) { System.out.println("n3 is bugger"); } } }
true
77b3cf5495c93133a1eb7ac2d36a31fc5411384d
Java
adicuco/Sem2Project
/src/GUILayer/Employee/menuPanels/dialogPanels/EditEventDialogPanel.java
UTF-8
17,390
2.265625
2
[]
no_license
package GUILayer.Employee.menuPanels.dialogPanels; import java.awt.Color; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.LayoutStyle.ComponentPlacement; import ControlLayer.EventCtr; import GUILayer.Customer.menuPanels.TimeClass; import ModelLayer.Event; public class EditEventDialogPanel extends JDialog { /** * */ private static final long serialVersionUID = 1L; private final JPanel pnlButtons = new JPanel(); private final JButton btnCancel = new JButton("Cancel"); private final JButton btnSave = new JButton("Save"); private final JLabel lblName = new JLabel("Name"); private final JLabel lblStart = new JLabel("Start Date"); private final JLabel lblDesc = new JLabel("Description"); private final JLabel lblMin = new JLabel("Min. Participants"); private final JLabel lblParts = new JLabel("Participants no."); private final JLabel lblPrice = new JLabel("Price"); private final JLabel lblStartDate = new JLabel("Registration Start Date"); private final JLabel lblEmp = new JLabel("Organizer / Instructor"); private final JTextField txtName = new JTextField(); private final JButton btnEdit = new JButton("Edit"); private final JLabel lblEmpId = new JLabel("Employee ID"); private final JLabel lblMax = new JLabel("Max. Participants"); private final JLabel lblRegEnd = new JLabel("Registration End Date"); private final JLabel lblEnd = new JLabel("End Date"); private final JTextField txtEmp = new JTextField(); private final JTextField txtEmpId = new JTextField(); private final JTextField txtRegStart = new JTextField(); private final JTextField txtRegEnd = new JTextField(); private final JTextField txtStart = new JTextField(); private final JTextField txtEnd = new JTextField(); private final JTextField txtMin = new JTextField(); private final JTextField txtMax = new JTextField(); private final JTextField txtParts = new JTextField(); private final JTextField txtPrice = new JTextField(); private final JScrollPane scrollPane = new JScrollPane(); private final JTextArea txtDesc = new JTextArea(); private Event event; public EditEventDialogPanel(Event event) { this.event = event; initialize(); initializeText(); createEvents(); getRootPane().setBorder(BorderFactory.createEtchedBorder(Color.BLACK, Color.GRAY)); setUndecorated(true); pack(); setLocationRelativeTo(null); setModal(true); setVisible(true); } private void initialize() { txtName.setEnabled(false); txtName.setEditable(false); txtName.setColumns(10); txtName.setFont(new Font("SansSerif", Font.BOLD, 15)); lblName.setFont(new Font("SansSerif", Font.BOLD, 20)); lblStart.setFont(new Font("SansSerif", Font.BOLD, 20)); lblMin.setFont(new Font("SansSerif", Font.BOLD, 20)); lblParts.setFont(new Font("SansSerif", Font.BOLD, 20)); lblPrice.setFont(new Font("SansSerif", Font.BOLD, 20)); lblDesc.setFont(new Font("SansSerif", Font.BOLD, 20)); lblStartDate.setFont(new Font("SansSerif", Font.BOLD, 20)); lblEmp.setFont(new Font("SansSerif", Font.BOLD, 20)); lblEmpId.setFont(new Font("SansSerif", Font.BOLD, 20)); lblEmpId.setVisible(false); btnSave.setFont(new Font("SansSerif", Font.BOLD, 20)); btnSave.setVisible(false); btnCancel.setFont(new Font("SansSerif", Font.BOLD, 20)); btnEdit.setFont(new Font("SansSerif", Font.BOLD, 20)); GroupLayout gl_pnlButtons = new GroupLayout(pnlButtons); gl_pnlButtons .setHorizontalGroup(gl_pnlButtons.createParallelGroup(Alignment.TRAILING).addGroup(Alignment.LEADING, gl_pnlButtons.createSequentialGroup().addGap(48).addComponent(btnCancel).addGap(262) .addComponent(btnEdit).addPreferredGap(ComponentPlacement.RELATED, 285, Short.MAX_VALUE) .addComponent(btnSave).addGap(91))); gl_pnlButtons.setVerticalGroup(gl_pnlButtons.createParallelGroup(Alignment.TRAILING) .addGroup(gl_pnlButtons.createSequentialGroup().addContainerGap(39, Short.MAX_VALUE) .addGroup(gl_pnlButtons.createParallelGroup(Alignment.LEADING) .addGroup(gl_pnlButtons.createSequentialGroup() .addGroup(gl_pnlButtons.createParallelGroup(Alignment.BASELINE) .addComponent(btnCancel).addComponent(btnEdit)) .addContainerGap()) .addGroup(Alignment.TRAILING, gl_pnlButtons.createSequentialGroup().addComponent(btnSave).addGap(14))))); pnlButtons.setLayout(gl_pnlButtons); lblMax.setFont(new Font("SansSerif", Font.BOLD, 20)); lblRegEnd.setFont(new Font("SansSerif", Font.BOLD, 20)); lblEnd.setFont(new Font("SansSerif", Font.BOLD, 20)); txtEmp.setText((String) null); txtEmp.setFont(new Font("SansSerif", Font.BOLD, 15)); txtEmp.setEnabled(false); txtEmp.setEditable(false); txtEmp.setColumns(10); txtEmpId.setText((String) null); txtEmpId.setFont(new Font("SansSerif", Font.BOLD, 15)); txtEmpId.setEnabled(false); txtEmpId.setEditable(false); txtEmpId.setVisible(false); txtEmpId.setColumns(10); txtRegStart.setText((String) null); txtRegStart.setFont(new Font("SansSerif", Font.BOLD, 15)); txtRegStart.setEnabled(false); txtRegStart.setEditable(false); txtRegStart.setColumns(10); txtRegEnd.setText((String) null); txtRegEnd.setFont(new Font("SansSerif", Font.BOLD, 15)); txtRegEnd.setEnabled(false); txtRegEnd.setEditable(false); txtRegEnd.setColumns(10); txtStart.setText((String) null); txtStart.setFont(new Font("SansSerif", Font.BOLD, 15)); txtStart.setEnabled(false); txtStart.setEditable(false); txtStart.setColumns(10); txtEnd.setText((String) null); txtEnd.setFont(new Font("SansSerif", Font.BOLD, 15)); txtEnd.setEnabled(false); txtEnd.setEditable(false); txtEnd.setColumns(10); txtMin.setText((String) null); txtMin.setFont(new Font("SansSerif", Font.BOLD, 15)); txtMin.setEnabled(false); txtMin.setEditable(false); txtMin.setColumns(10); txtMax.setText((String) null); txtMax.setFont(new Font("SansSerif", Font.BOLD, 15)); txtMax.setEnabled(false); txtMax.setEditable(false); txtMax.setColumns(10); txtParts.setText((String) null); txtParts.setFont(new Font("SansSerif", Font.BOLD, 15)); txtParts.setEnabled(false); txtParts.setEditable(false); txtParts.setColumns(10); txtPrice.setText((String) null); txtPrice.setFont(new Font("SansSerif", Font.BOLD, 15)); txtPrice.setEnabled(false); txtPrice.setEditable(false); txtPrice.setColumns(10); txtDesc.setLineWrap(true); txtDesc.setWrapStyleWord(true); txtDesc.setEnabled(false); txtDesc.setEditable(false); txtDesc.setFont(new Font("SansSerif", Font.BOLD, 15)); scrollPane.setViewportView(txtDesc); GroupLayout groupLayout = new GroupLayout(getContentPane()); groupLayout.setHorizontalGroup(groupLayout.createParallelGroup(Alignment.LEADING).addGroup(Alignment.TRAILING, groupLayout.createSequentialGroup().addContainerGap().addGroup(groupLayout .createParallelGroup(Alignment.TRAILING) .addComponent(pnlButtons, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 842, Short.MAX_VALUE) .addGroup(groupLayout.createSequentialGroup() .addComponent(lblName, GroupLayout.PREFERRED_SIZE, 102, GroupLayout.PREFERRED_SIZE) .addGap(117).addComponent(txtName, GroupLayout.DEFAULT_SIZE, 221, Short.MAX_VALUE) .addGap(12) .addGroup(groupLayout.createParallelGroup(Alignment.LEADING).addComponent(lblMin, GroupLayout.PREFERRED_SIZE, 210, GroupLayout.PREFERRED_SIZE) .addGroup(groupLayout.createSequentialGroup().addGap(169).addComponent(txtMin, GroupLayout.PREFERRED_SIZE, 221, GroupLayout.PREFERRED_SIZE)))) .addGroup(groupLayout.createSequentialGroup() .addGroup(groupLayout.createParallelGroup(Alignment.LEADING) .addComponent(lblEmp, GroupLayout.PREFERRED_SIZE, 210, GroupLayout.PREFERRED_SIZE) .addComponent(lblEmpId, GroupLayout.PREFERRED_SIZE, 135, GroupLayout.PREFERRED_SIZE)) .addGap(9) .addGroup(groupLayout.createParallelGroup(Alignment.LEADING) .addComponent(txtEmp, GroupLayout.DEFAULT_SIZE, 221, Short.MAX_VALUE) .addComponent(txtEmpId, GroupLayout.DEFAULT_SIZE, 221, Short.MAX_VALUE)) .addGap(12) .addGroup(groupLayout.createParallelGroup(Alignment.LEADING) .addComponent(lblMax, GroupLayout.PREFERRED_SIZE, 210, GroupLayout.PREFERRED_SIZE) .addGroup(groupLayout.createSequentialGroup().addGap(169).addComponent(txtMax, GroupLayout.PREFERRED_SIZE, 221, GroupLayout.PREFERRED_SIZE)) .addGroup(groupLayout.createSequentialGroup() .addComponent(lblParts, GroupLayout.PREFERRED_SIZE, 154, GroupLayout.PREFERRED_SIZE) .addGap(15).addComponent(txtParts, GroupLayout.PREFERRED_SIZE, 221, GroupLayout.PREFERRED_SIZE)))) .addGroup(Alignment.LEADING, groupLayout.createSequentialGroup().addGroup(groupLayout .createParallelGroup(Alignment.LEADING) .addComponent(lblStartDate, GroupLayout.PREFERRED_SIZE, 227, GroupLayout.PREFERRED_SIZE) .addGroup(groupLayout.createSequentialGroup().addGap(219).addComponent(txtRegStart, GroupLayout.DEFAULT_SIZE, 221, Short.MAX_VALUE)) .addGroup(groupLayout.createSequentialGroup() .addComponent(lblRegEnd, GroupLayout.PREFERRED_SIZE, 210, GroupLayout.PREFERRED_SIZE) .addGap(9) .addComponent(txtRegEnd, GroupLayout.DEFAULT_SIZE, 221, Short.MAX_VALUE)) .addGroup(groupLayout.createSequentialGroup() .addGroup(groupLayout.createParallelGroup(Alignment.LEADING) .addComponent(lblStart, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE) .addComponent(lblEnd, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE)) .addGap(119) .addGroup(groupLayout.createParallelGroup(Alignment.LEADING) .addComponent(txtEnd, GroupLayout.DEFAULT_SIZE, 221, Short.MAX_VALUE) .addComponent(txtStart, GroupLayout.DEFAULT_SIZE, 221, Short.MAX_VALUE)))) .addGap(12) .addGroup(groupLayout.createParallelGroup(Alignment.LEADING) .addGroup(Alignment.TRAILING, groupLayout.createSequentialGroup() .addComponent(lblPrice, GroupLayout.PREFERRED_SIZE, 60, GroupLayout.PREFERRED_SIZE) .addGap(109).addComponent(txtPrice, GroupLayout.PREFERRED_SIZE, 221, GroupLayout.PREFERRED_SIZE)) .addComponent(lblDesc, GroupLayout.PREFERRED_SIZE, 116, GroupLayout.PREFERRED_SIZE) .addComponent(scrollPane)))) .addGap(9))); groupLayout.setVerticalGroup(groupLayout.createParallelGroup(Alignment.LEADING) .addGroup(groupLayout.createSequentialGroup().addGap(28) .addGroup(groupLayout.createParallelGroup(Alignment.LEADING) .addGroup(groupLayout.createSequentialGroup().addGap(1).addComponent(lblName)) .addComponent(txtName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addGroup(groupLayout.createSequentialGroup().addGap(1).addComponent(lblMin)) .addComponent(txtMin, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addGap(7) .addGroup(groupLayout.createParallelGroup(Alignment.LEADING) .addGroup(groupLayout.createSequentialGroup().addGap(17).addComponent(lblEmp).addGap(5) .addComponent(lblEmpId)) .addGroup(groupLayout.createSequentialGroup().addGap(16) .addGroup(groupLayout.createParallelGroup(Alignment.LEADING) .addComponent(txtEmp, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addGroup(groupLayout.createSequentialGroup().addGap(31).addComponent(txtEmpId, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))) .addGroup(groupLayout.createSequentialGroup() .addGroup(groupLayout.createParallelGroup(Alignment.LEADING).addComponent(lblMax) .addGroup(groupLayout.createSequentialGroup().addGap(2).addComponent(txtMax, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))) .addGroup(groupLayout.createParallelGroup(Alignment.LEADING).addComponent(lblParts) .addGroup(groupLayout.createSequentialGroup().addGap(2).addComponent(txtParts, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))))) .addGap(7) .addGroup(groupLayout.createParallelGroup(Alignment.LEADING) .addGroup(groupLayout.createSequentialGroup().addGap(27) .addGroup(groupLayout.createParallelGroup(Alignment.LEADING) .addGroup(groupLayout.createSequentialGroup().addGap(1) .addComponent(lblStartDate)) .addComponent(txtRegStart, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addGap(5) .addGroup(groupLayout.createParallelGroup(Alignment.LEADING).addComponent(lblRegEnd) .addGroup(groupLayout.createSequentialGroup().addGap(2).addComponent(txtRegEnd, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))) .addGap(23) .addGroup(groupLayout.createParallelGroup(Alignment.LEADING) .addGroup(groupLayout.createSequentialGroup().addComponent(lblStart).addGap(5) .addComponent(lblEnd)) .addGroup(groupLayout.createSequentialGroup().addGap(2) .addGroup(groupLayout.createParallelGroup(Alignment.LEADING) .addGroup(groupLayout.createSequentialGroup().addGap(31).addComponent( txtEnd, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addComponent(txtStart, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))))) .addGroup(groupLayout.createSequentialGroup() .addGroup(groupLayout.createParallelGroup(Alignment.LEADING).addComponent(lblPrice) .addGroup(groupLayout.createSequentialGroup().addGap(2).addComponent(txtPrice, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))) .addGap(9).addComponent(lblDesc).addGap(9) .addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 106, GroupLayout.PREFERRED_SIZE))) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(pnlButtons, GroupLayout.PREFERRED_SIZE, 45, Short.MAX_VALUE).addGap(16))); getContentPane().setLayout(groupLayout); } private void createEvents() { btnCancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); btnEdit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { txtName.setEnabled(true); txtName.setEditable(true); txtMin.setEnabled(true); txtMin.setEditable(true); txtEmpId.setEnabled(true); txtEmpId.setEditable(true); txtEmpId.setVisible(true); txtMax.setEnabled(true); txtMax.setEditable(true); txtPrice.setEnabled(true); txtPrice.setEditable(true); txtDesc.setEnabled(true); txtDesc.setEditable(true); btnSave.setVisible(true); btnEdit.setVisible(false); } }); btnSave.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { EventCtr eventCtr = new EventCtr(); try { eventCtr.updateEvent(event.getEventId(), txtName.getText(), txtDesc.getText(), Integer.valueOf(txtMax.getText()), Integer.valueOf(txtMin.getText()), event.getRegStartDate(), event.getRegEndDate(), event.getStartDate(), event.getEndDate(), event.getActive().toString(), event.getStatus().toString(), Double.valueOf(txtPrice.getText()), Integer.valueOf(txtEmpId.getText())); JOptionPane.showMessageDialog(null, "Event successfully updated.", "Succes!", JOptionPane.INFORMATION_MESSAGE); dispose(); } catch (Exception ex) { JOptionPane.showMessageDialog(null, "Event not updated.", "Error!", JOptionPane.ERROR_MESSAGE); } } }); } private void initializeText() { txtName.setText(event.getName()); txtEmp.setText(event.getEmployee().getfName() + " " + event.getEmployee().getlName()); txtEmpId.setText(String.valueOf(event.getEmployee().getEmployeeId())); txtRegStart.setText(TimeClass.txtDate(event.getRegStartDate())); txtRegEnd.setText(TimeClass.txtDate(event.getRegEndDate())); txtStart.setText(TimeClass.txtDate(event.getStartDate())); txtEnd.setText(TimeClass.txtDate(event.getEndDate())); txtMin.setText(String.valueOf(event.getMinParticipants())); txtMax.setText(String.valueOf(event.getMaxParticipants())); txtParts.setText(String.valueOf(event.getParticipantsNr())); txtPrice.setText(String.valueOf(event.getPrice())); txtDesc.setText(event.getDescription()); } }
true
c4a2ad26906861e98200024f0f87119b76a1f565
Java
arche4/V2AppSofcoiso
/target/generated-sources/annotations/com/co/sofcoiso/modelo/Afp_.java
UTF-8
617
1.53125
2
[]
no_license
package com.co.sofcoiso.modelo; import com.co.sofcoiso.modelo.Persona; import javax.annotation.Generated; import javax.persistence.metamodel.CollectionAttribute; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(value="EclipseLink-2.5.2.v20140319-rNA", date="2020-02-22T12:36:04") @StaticMetamodel(Afp.class) public class Afp_ { public static volatile CollectionAttribute<Afp, Persona> personaCollection; public static volatile SingularAttribute<Afp, String> codigoafp; public static volatile SingularAttribute<Afp, String> nombre; }
true
a53300db14998fb50616893f72d9708ce938f4b5
Java
wang663632304/AndroidPieMenu
/PieMenuSample/src/com/example/piemenusample/PieMenuRenderer.java
UTF-8
2,289
2.609375
3
[ "MIT" ]
permissive
package com.example.piemenusample; import de.markusfisch.library.piemenu.PieMenu; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.view.MotionEvent; public class PieMenuRenderer { private static final int MAX_ICON_SIZE = 128; private static final int DRAWABLES[] = { R.drawable.icon, R.drawable.icon, R.drawable.icon, R.drawable.icon, R.drawable.icon, R.drawable.icon, R.drawable.icon, R.drawable.icon, R.drawable.icon }; private final PieMenu pieMenu = new PieMenu(); private int width = 0; private int height = 0; private float touchX = -1f; private float touchY = -1f; private float lastTouchX = -1f; private float lastTouchY = -1f; public PieMenuRenderer( Resources res ) { for( int n = DRAWABLES.length; n-- > 0; ) pieMenu.icons.add( new Icon( res.getDrawable( DRAWABLES[n] ) ) ); pieMenu.numberOfIcons = pieMenu.icons.size(); } public void setup( int w, int h ) { int radius; int min = Math.min( w, h ); if( Math.floor( min*.28f ) > MAX_ICON_SIZE ) min = Math.round( MAX_ICON_SIZE/.28f ); radius = Math.round( min*.4f ); width = w; height = h; touchX = w/2f; touchY = h/2f; pieMenu.setup( (int)touchX, (int)touchY, radius ); } public void draw( Canvas c ) { if( width < 1 ) return; c.drawColor( 0xff000000 ); if( touchX != lastTouchX || touchY != lastTouchY ) { pieMenu.calculate( touchX, touchY ); lastTouchX = touchX; lastTouchY = touchY; } for( int n = pieMenu.numberOfIcons; n-- > 0; ) ((Icon)pieMenu.icons.get( n )).draw( c ); } public void touch( MotionEvent e ) { touchX = e.getX(); touchY = e.getY(); if( e.getActionMasked() != MotionEvent.ACTION_UP ) return; if( pieMenu.selectedIcon > -1 ) ((Icon)pieMenu.icons.get( pieMenu.selectedIcon )).launch(); } private class Icon extends PieMenu.Icon { private Drawable icon; public Icon( Drawable drawable ) { icon = drawable; } public void launch() { } public void draw( Canvas c ) { int s = ((int)size)>>1<<1; if( s < 1 ) return; int half = s/2; int left = x-half; int top = y-half; icon.setBounds( left, top, left+s, top+s ); icon.draw( c ); } } }
true
ec619b07d4680f2c07b1264b391a03fe463bf5d7
Java
KrzysztofKukla/01-testing-java-junit5
/src/main/java/guru/springframework/sfgpetclinic/model/OwnerType.java
UTF-8
126
1.640625
2
[ "Apache-2.0" ]
permissive
package guru.springframework.sfgpetclinic.model; /** * @author Krzysztof Kukla */ public enum OwnerType { INDIVIDUAL, COMPANY }
true
a45a8da96ae73d110ca8ed74520349f9a5e8e04b
Java
farahmarsaouii/gestionRHPFE
/src/main/java/ch/newaccess/backendproject/service/AccountServiceImpl.java
UTF-8
3,680
2.078125
2
[]
no_license
package ch.newaccess.backendproject.service; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import ch.newaccess.backendproject.entities.AppPrivilege; import ch.newaccess.backendproject.entities.AppRole; import ch.newaccess.backendproject.entities.AppUser; import ch.newaccess.backendproject.entities.DocumentAdministratif; import ch.newaccess.backendproject.entities.Equipe; import ch.newaccess.backendproject.entities.Poste; import ch.newaccess.backendproject.repository.PrivilegeRepository; import ch.newaccess.backendproject.repository.RoleRespository; import ch.newaccess.backendproject.repository.UserRespository; @Service @Transactional public class AccountServiceImpl implements AccountService{ @Autowired private UserRespository userRespository; @Autowired private PrivilegeRepository privilegeRespository; @Autowired private RoleRespository roleRespository; @Autowired private BCryptPasswordEncoder bCryptPasswordEncoder; public AppUser saveUser(AppUser user) { String hashPW=bCryptPasswordEncoder.encode(user.getPassword()); user.setPassword(hashPW); return userRespository.save(user); } public AppRole saveRole(AppRole role) { return roleRespository.save(role); } @Override public AppPrivilege savePrivilege(AppPrivilege privilege) { // TODO Auto-generated method stub return privilegeRespository.save(privilege); } public AppUser findUserByid(Long id) { return userRespository.findById(id).get(); } public AppUser findUserByUsername(String userName) { // TODO Auto-generated method stub return userRespository.findByUserName(userName); } /*public void addRoleToUser(String userName, String roleName) { AppRole role = roleRespository.findByrole(roleName); AppUser user =userRespository.findByUserName(userName); user.getRoles().add(role); }*/ @Override public void affectRoleToUser(String userName, String roleName) { AppRole role = roleRespository.findByrole(roleName); AppUser user =userRespository.findByUserName(userName); user.setRole(role); //setRoles(role); } @Override public void addPrivilegeToRole(String privilegeName, String roleName) { AppRole role = roleRespository.findByrole(roleName); AppPrivilege privilege =privilegeRespository.findByprivilege(privilegeName); role.getprivileges().add(privilege); } @Override public List<AppUser> findByEquipeAndRole(Equipe equipe, AppRole role) { // TODO Auto-generated method stub return userRespository.findByEquipeAndRole(equipe,role) ; } public List<AppRole> findRoles() { return roleRespository.findAll(); } @Override public AppUser findByPoste(Poste poste) { return userRespository.findByPoste(poste) ; } @Override public List<AppUser> findUsers() { return userRespository.findAll(); } @Override public AppUser updateUser(AppUser user) { AppUser u= userRespository.findById(user.getId()).get(); u.setUserName(user.getUserName()); u.setCin(user.getCin()); u.setEmail(user.getEmail()); u.setEquipe(user.getEquipe()); u.setIdSuperieurhierarchique(user.getIdSuperieurhierarchique()); u.setPoste(u.getPoste()); u.setRole(u.getRole()); u.setImage(u.getImage()); u.setPassword(u.getPassword()); u.setRepassword(u.getRepassword()); return userRespository.save(u); } @Override public void deleteUser(Long idUser) { userRespository.deleteById(idUser); } public List<AppUser> findByRole(AppRole role){ return userRespository.findByRole(role); }; }
true
e0d1989885f655531dbaaba255bdc6d81befdcd5
Java
ShanzyHolm/AirportModel
/src/main/java/Flights.java
UTF-8
1,842
2.15625
2
[]
no_license
public enum Flights { GLASGOW("KL1472", Airports.GLASGOW, Airports.EDINBURGH), VANCOUVER("AF8332", Airports.GLASGOW, Airports.VANCOUVER), MALAGA("FR2609", Airports.MALAGA, Airports.GLASGOW), LONDONH("BA1487", Airports.GLASGOW, Airports.LONDONH), LONDONG("EZY811", Airports.LONDONG, Airports.EDINBURGH), AMSTERDAM("KL1476", Airports.AMSTERDAM, Airports.GLASGOW), TENERIFE("LS155", Airports.TENERIFE, Airports.GLASGOW), TENERIFERS("FR6622", Airports.TENERIFERS, Airports.EDINBURGH), DUBAI("EK028", Airports.DUBAI, Airports.GLASGOW), FRANKFURT("LH964", Airports.EDINBURGH, Airports.FRANKFURT), PARIS("AF1886", Airports.PARIS, Airports.EDINBURGH), NEWYORK("AA278", Airports.NEWYORK, Airports.EDINBURGH), TOKYO("JL407", Airports.TOKYO, Airports.EDINBURGH), MOSCOW("BA1493", Airports.GLASGOW, Airports.MOSCOW), HALIFAX("WS30", Airports.GLASGOW, Airports.HALIFAX), KEFLAVIK("FI431", Airports.KEFLAVIK, Airports.EDINBURGH), SYDNEY("QR32", Airports.SYDNEY, Airports.GLASGOW), DURBAN("BA1449", Airports.DURBAN, Airports.GLASGOW), GOTENBURG("KL1478", Airports.EDINBURGH, Airports.GOTENBURG), TORONTO("TS525", Airports.GLASGOW, Airports.TORONTO); private final String flightNumber; private final Enum departureDestination; private final Enum arrivalDestination; Flights(String flightNumber, Enum departureDestination, Enum arrivalDestination){ this.flightNumber = flightNumber; this.departureDestination = departureDestination; this.arrivalDestination = arrivalDestination; } public String getFlightNumber() { return flightNumber; } public Enum getDepartureDestination() { return departureDestination; } public Enum getArrivalDestination() { return arrivalDestination; } }
true
44f319d98f2a0e492907599bd694ab3896fc27d2
Java
fhnaumann/Challenges
/src/me/wand555/challenges/settings/challengeprofile/types/Punishable.java
UTF-8
3,960
2.234375
2
[]
no_license
package me.wand555.challenges.settings.challengeprofile.types; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.Collectors; import java.util.stream.Stream; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import me.wand555.challenges.settings.challengeprofile.ChallengeProfile; import me.wand555.challenges.settings.config.WorldUtil; import me.wand555.challenges.start.Challenges; public interface Punishable { public PunishType getPunishType(); public void setPunishType(PunishType punishType); public ChallengeType getPunishCause(); default void enforcePunishment(PunishType type, Collection<Player> affected, Player... causers) { for(Player causer : causers) { switch(type) { case HEALTH_1: causer.damage(1); break; case HEALTH_2: causer.damage(2); break; case HEALTH_3: causer.damage(3); break; case HEALTH_4: causer.damage(4); break; case HEALTH_5: causer.damage(5); break; case HEALTH_6: causer.damage(6); break; case HEALTH_7: causer.damage(7); break; case HEALTH_8: causer.damage(8); break; case HEALTH_9: causer.damage(9); break; case HEALTH_10: causer.damage(10); break; case HEALTH_ALL_1: affected.forEach(p -> p.damage(1)); break; case HEALTH_ALL_2: affected.forEach(p -> p.damage(2)); break; case HEALTH_ALL_3: affected.forEach(p -> p.damage(3)); break; case HEALTH_ALL_4: affected.forEach(p -> p.damage(4)); break; case HEALTH_ALL_5: affected.forEach(p -> p.damage(5)); break; case HEALTH_ALL_6: affected.forEach(p -> p.damage(6)); break; case HEALTH_ALL_7: affected.forEach(p -> p.damage(7)); break; case HEALTH_ALL_8: affected.forEach(p -> p.damage(8)); break; case HEALTH_ALL_9: affected.forEach(p -> p.damage(9)); break; case HEALTH_ALL_10: affected.forEach(p -> p.damage(10)); break; case DEATH: if(!causer.isDead()) { causer.setHealth(0); } break; case DEATH_ALL: if(!ChallengeProfile.getInstance().isInMLGRightNow) { affected.forEach(p -> { if(!p.isDead()) { p.setHealth(0); } }); } else { Bukkit.getScheduler().runTaskLater(Challenges.getPlugin(Challenges.class), () -> affected.forEach(p -> { if(!p.isDead()) { p.setHealth(0); } }), 35L); } break; case ONE_ITEM: { List<ItemStack> causerInv = Stream.of(causer.getInventory().getContents()) .filter(item -> item != null) .collect(Collectors.toList()); ItemStack randomItem = causerInv.get(ThreadLocalRandom.current().nextInt(0, causerInv.size())); causer.getInventory().remove(randomItem); break; } case ONE_ITEM_ALL: { affected.forEach(p -> { if(p.getWorld().equals(Bukkit.getWorld("MLGWorld"))) { WorldUtil.punishmentClearOneItem(p); } else { List<ItemStack> pInv = Stream.of(p.getInventory().getContents()).filter(item -> item != null).collect(Collectors.toList()); ItemStack randomItem = pInv.get(ThreadLocalRandom.current().nextInt(0, pInv.size())); HashMap<Integer, ItemStack> test = p.getInventory().removeItem(randomItem); WorldUtil.storeInbetweenPunishment(p); } }); break; } case ALL_ITEMS: causer.getInventory().clear(); break; case ALL_ITEMS_ALL: affected.forEach(p -> { if(p.getWorld().equals(Bukkit.getWorld("MLGWorld"))) { WorldUtil.punishmentClearAllItems(p); } else { p.getInventory().clear(); WorldUtil.storeInbetweenPunishment(p); } }); if(!ChallengeProfile.getInstance().isInMLGRightNow) { } else { } break; default: break; } } } }
true
844c9141f06e46a9c041519235b429a10f61c39b
Java
pado140/iw_wip
/src/view/User.java
UTF-8
35,807
2.15625
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package view; import connection.ConnectionDb; import connection.item; import java.awt.Font; import java.awt.event.MouseEvent; import java.sql.ResultSet; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.DefaultComboBoxModel; import javax.swing.JComboBox; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; import observateurs.Observateurs; import observateurs.Observe; /** * * @author Duvers */ public class User extends javax.swing.JInternalFrame implements Observe{ private final ConnectionDb conn = ConnectionDb.instance(); private User_rights droit=new User_rights(null,true); public static Integer id_staff = 0; public static String staff = null; Integer coddept = 0; private boolean cansave = true; //private List<Object[]> public User() { initComponents(); this.ajouterObservateur(droit); refresh(); btn_getinfo.setVisible(false); showData(); combo_dept(cmb_dept); } private void refresh(){ txt_search.setText(null); txt_pass1.setText(null); txt_pass2.setText(null); txt_staff.setText(null); txt_usu.setText(null); right.setText("User Right"); coddept = 0; } public void combo_dept(JComboBox cmb){ DefaultComboBoxModel value; try{ ResultSet rs = conn.select("select * from departement ;"); value = new DefaultComboBoxModel(); cmb.setModel(value); cmb.removeAllItems(); value.addElement(new item(0, "--")); while (rs.next()){ value.addElement(new item(rs.getInt("id_dept"), rs.getString("dept"))); } }catch (Exception ex){ System.err.println(""+ ex); } } private void saveUser(){ String query = "INSERT INTO users (idstaff, username, pass, dept, nivel, status) " + "VALUES (?,?,?,?,?,?)"; boolean wellsave = conn.Update(query, 1, id_staff,txt_usu.getText().trim(),txt_pass2.getText().trim(),coddept, cmb_nivel.getSelectedItem().toString(),cmb_statut.getSelectedItem().toString()); if(wellsave){ JOptionPane.showMessageDialog(null, "Successfully Saved"); }else{ JOptionPane.showMessageDialog(null, "ERROR"); } } private void showData(){ grid_usuario.getTableHeader().setFont( new Font( "Arial" , Font.BOLD, 13 )); DefaultTableModel tbm = (DefaultTableModel) grid_usuario.getModel(); tbm.setRowCount(0); try{ String query = "SELECT * from vw_users order by iduser DESC"; ResultSet rs = conn.select(query); while (rs.next()){ tbm.addRow(new Object[]{rs.getInt("iduser"), rs.getString("fname")+" "+rs.getString("lname"), rs.getString("username"), rs.getString("departement"), rs.getInt("nivel"), rs.getString("status"),rs.getString("pass")}); } }catch (SQLException e){ System.out.println(e); } } public void buscarDatos(String txtbox){ DefaultTableModel tbm = (DefaultTableModel) grid_usuario.getModel(); tbm.setRowCount(0); String buscar = txtbox.trim(); try{ String sql = "select * from vw_users where fname like ? or lname like ? "+ " or fname+' '+lname like ? or lname+' '+fname like ? or username like ?"; ResultSet rs = conn.select(sql,"%" + buscar + "%","%" + buscar + "%","%" + buscar + "%","%" + buscar + "%","%" + buscar + "%"); while (rs.next()){ tbm.addRow(new Object[]{rs.getInt("iduser"), rs.getString("fname")+" "+rs.getString("lname"), rs.getString("username"), rs.getString("departement"), rs.getInt("nivel"), rs.getString("status"),rs.getString("pass")}); } }catch (SQLException e){ System.out.println(e); } } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { pop = new javax.swing.JPopupMenu(); right = new javax.swing.JMenuItem(); change_password = new javax.swing.JMenuItem(); deactivate = new javax.swing.JMenuItem(); panel_station = new javax.swing.JPanel(); jPanel3 = new javax.swing.JPanel(); txt_staff = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); txt_usu = new javax.swing.JTextField(); jLabel7 = new javax.swing.JLabel(); cmb_statut = new javax.swing.JComboBox(); txt_pass1 = new javax.swing.JPasswordField(); jLabel8 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); txt_pass2 = new javax.swing.JPasswordField(); jLabel6 = new javax.swing.JLabel(); cmb_dept = new javax.swing.JComboBox(); cmb_nivel = new javax.swing.JComboBox(); jPanel1 = new javax.swing.JPanel(); btn_nouveau = new javax.swing.JButton(); btn_guardar = new javax.swing.JButton(); btn_getinfo = new javax.swing.JButton(); txt_search = new javax.swing.JTextField(); jScrollPane2 = new javax.swing.JScrollPane(); grid_usuario = new javax.swing.JTable(); right.setText("jMenuItem1"); right.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { rightActionPerformed(evt); } }); pop.add(right); change_password.setText("jMenuItem1"); pop.add(change_password); deactivate.setText("jMenuItem2"); deactivate.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { deactivateActionPerformed(evt); } }); pop.add(deactivate); setClosable(true); setTitle("USER"); addInternalFrameListener(new javax.swing.event.InternalFrameListener() { public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) { } public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) { formInternalFrameClosed(evt); } public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) { } public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) { } public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) { } public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) { } public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) { } }); panel_station.setBackground(new java.awt.Color(153, 153, 153)); panel_station.setBorder(javax.swing.BorderFactory.createEtchedBorder()); jPanel3.setBackground(new java.awt.Color(102, 102, 102)); jPanel3.setBorder(javax.swing.BorderFactory.createEtchedBorder()); jPanel3.setPreferredSize(new java.awt.Dimension(215, 34)); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 595, Short.MAX_VALUE) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 37, Short.MAX_VALUE) ); txt_staff.setEditable(false); txt_staff.setBackground(new java.awt.Color(51, 51, 51)); txt_staff.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N txt_staff.setForeground(new java.awt.Color(255, 255, 255)); txt_staff.setText("jTextField1"); txt_staff.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { txt_staffMouseClicked(evt); } }); txt_staff.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txt_staffActionPerformed(evt); } }); txt_staff.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { txt_staffKeyReleased(evt); } }); jLabel3.setFont(new java.awt.Font("Georgia", 0, 14)); // NOI18N jLabel3.setText("Staff :"); jLabel3.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jLabel3.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel3MouseClicked(evt); } }); jLabel5.setFont(new java.awt.Font("Georgia", 0, 14)); // NOI18N jLabel5.setText("Username :"); jLabel5.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jLabel5.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel5MouseClicked(evt); } }); txt_usu.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N txt_usu.setText("jTextField1"); txt_usu.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txt_usuActionPerformed(evt); } }); txt_usu.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { txt_usuKeyReleased(evt); } }); jLabel7.setFont(new java.awt.Font("Georgia", 0, 14)); // NOI18N jLabel7.setText("Statut :"); jLabel7.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jLabel7.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel7MouseClicked(evt); } }); cmb_statut.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N cmb_statut.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Actif", "Inactif" })); txt_pass1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N txt_pass1.setText("jPasswordField1"); txt_pass1.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { txt_pass1FocusLost(evt); } }); jLabel8.setFont(new java.awt.Font("Georgia", 0, 14)); // NOI18N jLabel8.setText("Password:"); jLabel8.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jLabel8.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel8MouseClicked(evt); } }); jLabel9.setFont(new java.awt.Font("Georgia", 0, 14)); // NOI18N jLabel9.setText("Confirm Password: "); jLabel9.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jLabel9.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel9MouseClicked(evt); } }); txt_pass2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N txt_pass2.setText("jPasswordField1"); txt_pass2.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { txt_pass2FocusLost(evt); } }); jLabel6.setFont(new java.awt.Font("Georgia", 0, 14)); // NOI18N jLabel6.setText("Department/Nivel:"); jLabel6.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); cmb_dept.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N cmb_dept.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmb_deptActionPerformed(evt); } }); cmb_nivel.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N cmb_nivel.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "--", "5", "4", "3", "2", "1" })); javax.swing.GroupLayout panel_stationLayout = new javax.swing.GroupLayout(panel_station); panel_station.setLayout(panel_stationLayout); panel_stationLayout.setHorizontalGroup( panel_stationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, 599, Short.MAX_VALUE) .addGroup(panel_stationLayout.createSequentialGroup() .addContainerGap() .addGroup(panel_stationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel9) .addComponent(jLabel3) .addComponent(jLabel5) .addComponent(jLabel8) .addComponent(jLabel7) .addComponent(jLabel6)) .addGap(18, 18, 18) .addGroup(panel_stationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txt_staff, javax.swing.GroupLayout.PREFERRED_SIZE, 312, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(panel_stationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(txt_pass1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 202, Short.MAX_VALUE) .addComponent(txt_usu, javax.swing.GroupLayout.Alignment.LEADING)) .addGroup(panel_stationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(txt_pass2, javax.swing.GroupLayout.PREFERRED_SIZE, 202, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(panel_stationLayout.createSequentialGroup() .addComponent(cmb_dept, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(cmb_nivel, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE))) .addComponent(cmb_statut, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(134, Short.MAX_VALUE)) ); panel_stationLayout.setVerticalGroup( panel_stationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panel_stationLayout.createSequentialGroup() .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(panel_stationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txt_staff, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(1, 1, 1) .addGroup(panel_stationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txt_usu, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(2, 2, 2) .addGroup(panel_stationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txt_pass1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(1, 1, 1) .addGroup(panel_stationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txt_pass2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(panel_stationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(cmb_dept, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6) .addComponent(cmb_nivel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(panel_stationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(cmb_statut, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel1.setBackground(new java.awt.Color(51, 51, 51)); jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder()); btn_nouveau.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N btn_nouveau.setText("NEW"); btn_nouveau.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_nouveauActionPerformed(evt); } }); btn_guardar.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N btn_guardar.setText("SAVE"); btn_guardar.setRequestFocusEnabled(false); btn_guardar.setRolloverEnabled(false); btn_guardar.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btn_guardarMouseClicked(evt); } public void mouseEntered(java.awt.event.MouseEvent evt) { btn_guardarMouseEntered(evt); } }); btn_guardar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_guardarActionPerformed(evt); } }); btn_getinfo.setText("jButton1"); btn_getinfo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_getinfoActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGap(20, 20, 20) .addComponent(btn_getinfo) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btn_guardar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btn_nouveau) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btn_guardar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btn_nouveau, javax.swing.GroupLayout.DEFAULT_SIZE, 68, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(btn_getinfo) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); txt_search.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N txt_search.setText("jTextField1"); txt_search.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { txt_searchKeyReleased(evt); } }); grid_usuario.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "id", "STAFF", "USERNAME", "DEPARTMENT", "NIVEL", "STATUT", "password" } ) { boolean[] canEdit = new boolean [] { false, false, false, false, true, true, true }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); grid_usuario.getTableHeader().setReorderingAllowed(false); grid_usuario.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { grid_usuarioMouseReleased(evt); } }); jScrollPane2.setViewportView(grid_usuario); if (grid_usuario.getColumnModel().getColumnCount() > 0) { grid_usuario.getColumnModel().getColumn(0).setMinWidth(0); grid_usuario.getColumnModel().getColumn(0).setMaxWidth(0); grid_usuario.getColumnModel().getColumn(6).setMinWidth(0); grid_usuario.getColumnModel().getColumn(6).setMaxWidth(0); } javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(10, 10, 10) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(panel_station, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txt_search, javax.swing.GroupLayout.PREFERRED_SIZE, 267, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 526, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(11, 11, 11) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addComponent(txt_search, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(1, 1, 1) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addComponent(panel_station, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(6, 6, 6) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void txt_staffMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txt_staffMouseClicked if(evt.getClickCount() == 2 ){ Staff dialog = new Staff(new javax.swing.JFrame(), true); dialog.setLocationRelativeTo(null); dialog.setVisible(true); } }//GEN-LAST:event_txt_staffMouseClicked private void txt_staffKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_staffKeyReleased }//GEN-LAST:event_txt_staffKeyReleased private void jLabel3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel3MouseClicked }//GEN-LAST:event_jLabel3MouseClicked private void jLabel5MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel5MouseClicked // TODO add your handling code here: }//GEN-LAST:event_jLabel5MouseClicked private void txt_usuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_usuActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txt_usuActionPerformed private void txt_usuKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_usuKeyReleased // TODO add your handling code here: }//GEN-LAST:event_txt_usuKeyReleased private void jLabel7MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel7MouseClicked // TODO add your handling code here: }//GEN-LAST:event_jLabel7MouseClicked private void btn_nouveauActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_nouveauActionPerformed refresh(); }//GEN-LAST:event_btn_nouveauActionPerformed private void btn_guardarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_guardarMouseClicked }//GEN-LAST:event_btn_guardarMouseClicked private void btn_guardarMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_guardarMouseEntered }//GEN-LAST:event_btn_guardarMouseEntered private void check(){ if(!txt_pass1.getText().toString().trim().equals(txt_pass2.getText().toString().trim())){ cansave = false; }else{ cansave = true; } } private void btn_guardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_guardarActionPerformed check(); String usu = txt_usu.getText().trim(); coddept=cmb_dept.getSelectedIndex(); if(!txt_staff.getText().trim().equals("")){ if(!txt_usu.getText().trim().equals("")){ if(!txt_pass1.getText().trim().equals("") && !txt_pass2.getText().trim().equals("")){ if(!cmb_nivel.getSelectedItem().equals("--") && coddept>0){ if(!cmb_statut.getSelectedItem().equals("--")){ if(!check(id_staff)){ if(cansave){ saveUser(); showData(); btn_nouveau.doClick(); }else{ JOptionPane.showMessageDialog (null, "The Passwords don't match !", "Error", JOptionPane.WARNING_MESSAGE); } }else{ JOptionPane.showMessageDialog (null, "This User has been already created ", "Error", JOptionPane.INFORMATION_MESSAGE); } }else{ JOptionPane.showMessageDialog (null, "Please fulfill all fields", "Error", JOptionPane.INFORMATION_MESSAGE); } }else{ JOptionPane.showMessageDialog (null, "Please fulfill all fields", "Error", JOptionPane.INFORMATION_MESSAGE); } }else{ JOptionPane.showMessageDialog (null, "Please fulfill all fields", "Error", JOptionPane.INFORMATION_MESSAGE); } }else{ JOptionPane.showMessageDialog (null, "Please fulfill all fields", "Error", JOptionPane.INFORMATION_MESSAGE); } }else{ JOptionPane.showMessageDialog (null, "Please fulfill all fields", "Error", JOptionPane.INFORMATION_MESSAGE); } }//GEN-LAST:event_btn_guardarActionPerformed private boolean check(int id){ boolean ch=false; String requete="select idstaff from users where idstaff=?"; ResultSet rs=conn.select(requete, id); try { while(rs.next()){ ch=true; } } catch (SQLException ex) { Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex); } return ch; } private void formInternalFrameClosed(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameClosed //Principal_iw.allow_user = true; }//GEN-LAST:event_formInternalFrameClosed private void txt_staffActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_staffActionPerformed }//GEN-LAST:event_txt_staffActionPerformed private void jLabel8MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel8MouseClicked // TODO add your handling code here: }//GEN-LAST:event_jLabel8MouseClicked private void jLabel9MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel9MouseClicked // TODO add your handling code here: }//GEN-LAST:event_jLabel9MouseClicked private void btn_getinfoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_getinfoActionPerformed txt_staff.setText(staff); }//GEN-LAST:event_btn_getinfoActionPerformed private void txt_pass2FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txt_pass2FocusLost }//GEN-LAST:event_txt_pass2FocusLost private void txt_pass1FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txt_pass1FocusLost }//GEN-LAST:event_txt_pass1FocusLost private void txt_searchKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_searchKeyReleased buscarDatos(txt_search.getText().trim()); }//GEN-LAST:event_txt_searchKeyReleased private void cmb_deptActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmb_deptActionPerformed // TODO add your handling code here: }//GEN-LAST:event_cmb_deptActionPerformed private void rightActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rightActionPerformed // TODO add your handling code here: int lin=grid_usuario.getSelectedRow(); alerter("rights",grid_usuario.getValueAt(lin, 0),grid_usuario.getValueAt(lin, 2),grid_usuario.getValueAt(lin, 1)); }//GEN-LAST:event_rightActionPerformed private void grid_usuarioMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_grid_usuarioMouseReleased // TODO add your handling code here: if(evt.getButton()==MouseEvent.BUTTON3){ if(!grid_usuario.getSelectionModel().isSelectionEmpty()){ pop.show(grid_usuario,evt.getX(),evt.getY()); }else JOptionPane.showMessageDialog(this, "Please select a row!", "Warning", JOptionPane.INFORMATION_MESSAGE); } }//GEN-LAST:event_grid_usuarioMouseReleased private void deactivateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deactivateActionPerformed // TODO add your handling code here: String requete="update users set status='inactif' where iduser=?"; int lin=grid_usuario.getSelectedRow(); conn.Update(requete, 0, grid_usuario.getValueAt(lin, 0)); showData(); }//GEN-LAST:event_deactivateActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables public static javax.swing.JButton btn_getinfo; private javax.swing.JButton btn_guardar; private javax.swing.JButton btn_nouveau; private javax.swing.JMenuItem change_password; private javax.swing.JComboBox cmb_dept; private javax.swing.JComboBox cmb_nivel; private javax.swing.JComboBox cmb_statut; private javax.swing.JMenuItem deactivate; private javax.swing.JTable grid_usuario; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel3; private javax.swing.JScrollPane jScrollPane2; public static javax.swing.JPanel panel_station; private javax.swing.JPopupMenu pop; private javax.swing.JMenuItem right; private javax.swing.JPasswordField txt_pass1; private javax.swing.JPasswordField txt_pass2; private javax.swing.JTextField txt_search; public static javax.swing.JTextField txt_staff; public static javax.swing.JTextField txt_usu; // End of variables declaration//GEN-END:variables @Override public void ajouterObservateur(Observateurs ob) { obs.add(ob); } @Override public void retirerObservateur(Observateurs ob) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void alerter(Object... ob) { for(Observateurs o:obs) o.executer(ob); } }
true
ef45f4bfad15f64f9c076d001fc7593d39b756f5
Java
szwork2013/Test
/mobile/android/tablet/src/com/kaikeba/activity/fragment/AssignmentItemFragment.java
UTF-8
5,715
2.09375
2
[]
no_license
package com.kaikeba.activity.fragment; import android.annotation.SuppressLint; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.TextView; import android.widget.Toast; import com.kaikeba.activity.ActiveAssigmentActivity; import com.kaikeba.activity.ActiveDisscussActivity; import com.kaikeba.activity.ActiveModuleActivity; import com.kaikeba.activity.ModuleActivity; import com.kaikeba.common.entity.Assignment; import com.kaikeba.common.util.DateUtils; import com.kaikeba.phone.R; import java.util.ArrayList; /** * 作业详情 * * @author Super Man */ @SuppressLint("SetJavaScriptEnabled") public class AssignmentItemFragment extends Fragment { int index = -1; private OnClickListener listener = new OnClickListener() { @Override public void onClick(View v) { int id = v.getId(); switch (id) { case R.id.btn_back_normal: if (getActivity() instanceof ModuleActivity) { getActivity().onBackPressed(); } else { if (getActivity() instanceof ActiveDisscussActivity) { ((ActiveDisscussActivity) getActivity()).clickDisscuss(); } else if (getActivity() instanceof ActiveModuleActivity) { ((ActiveModuleActivity) getActivity()).clickAnnounce(); } else if (getActivity() instanceof ActiveAssigmentActivity) { ((ActiveAssigmentActivity) getActivity()).clickAssignment(); } } break; case R.id.previous: if (index == 0) { Toast.makeText(getActivity(), "已经是第一个", Toast.LENGTH_SHORT).show(); } else { index--; setText(); } break; case R.id.next: if (index == assignments.size() - 1) { Toast.makeText(getActivity(), "已经是最后一个", Toast.LENGTH_SHORT).show(); } else { index++; setText(); } break; default: break; } } }; private TextView title; private TextView tvDueAt; private TextView tvPoint; private WebView wvMsg; private Assignment assignment; private ArrayList<Assignment> assignments; @SuppressWarnings("unchecked") @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.my_course_assignment_item, container, false); findViews(v); WebSettings setting = wvMsg.getSettings(); setting.setUseWideViewPort(true); setting.setJavaScriptEnabled(true); setting.setJavaScriptCanOpenWindowsAutomatically(true); wvMsg.setWebViewClient(new WebViewClient()); assignments = (ArrayList<Assignment>) getArguments().getSerializable("assignments"); if (getActivity() instanceof ModuleActivity) { assignment = (Assignment) getArguments().getSerializable("assignment"); index = assignments.indexOf(assignment); } else { index = getArguments().getInt("index", 0); assignment = assignments.get(index); } return v; } private void findViews(View v) { v.findViewById(R.id.btn_back_normal).setOnClickListener(listener); title = (TextView) v.findViewById(R.id.title); tvDueAt = (TextView) v.findViewById(R.id.tv_due_at); tvPoint = (TextView) v.findViewById(R.id.tv_point); wvMsg = (WebView) v.findViewById(R.id.wv_msg); v.findViewById(R.id.previous).setOnClickListener(listener); v.findViewById(R.id.next).setOnClickListener(listener); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setText(); } private void setText() { title.setText(assignments.get(index).getName()); wvMsg.loadDataWithBaseURL(null, assignments.get(index).getDescription(), "text/html", "utf-8", null); if (assignments.get(index).getDue_at() != null) { tvDueAt.setText(DateUtils.getCourseStartTime(assignments.get(index).getDue_at())); } else if (assignments.get(index).getUnlock_at() != null) { tvDueAt.setText(DateUtils.getCourseStartTime(assignments.get(index).getUnlock_at())); } // else if (assignments.get(index).getLock_info() != null && assignments.get(index).getLock_info().getLock_at() != null){ // tvDueAt.setText(DateUtils.getCourseStartTime(assignments.get(index).getLock_info().getLock_at())); // } else { tvDueAt.setText(""); } tvPoint.setText(assignments.get(index).getPoints_possible()); } // private Handler handler = new Handler(){ // public void handleMessage(android.os.Message msg) { // switch (msg.what) { // case 0: // break; // default: // break; // } // }; // }; }
true
24f24e88c74dd689d260d6ad64be00bb3001f890
Java
mazen930/Search-Engine-1
/search/src/main/java/FetchAllSuggestionsServlet.java
UTF-8
1,077
2.265625
2
[]
no_license
import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; @WebServlet("/getSuggestions") public class FetchAllSuggestionsServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Gson gson = new Gson(); IndexerDbAdapter adapter = new IndexerDbAdapter(); adapter.open(); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); ArrayList<String> result = adapter.fetchAllQueries(); HashMap<String, ArrayList<String>>res = new HashMap<>(); res.put("result", result); out.print(gson.toJson(res)); out.flush(); adapter.close(); } }
true
205fba75cad82bb68b24feb54109fcffdc5fe775
Java
Radhi13/2017fall_ooad_guitars
/src/Guitar.java
ISO-8859-1
1,712
3.765625
4
[]
no_license
/* * Purpose :This Guitar Class adds arguments of guitar and adds the functionalities * like getting the Price,Model,Type,TopWood,BackWood * *@author Radhika Hegde * @version 1.0 * @since 09-15-2017 * */ // This is the public Guitar class public class Guitar { // Guitar class has seven arguments private String serialNumber, builder, model, type, backWood, topWood; private double price; //The Guitar has one Constructor public Guitar(String serialNumber, double price, String builder, String model, String type, String backWood, String topWood) { this.serialNumber = serialNumber; this.price = price; this.builder = builder; this.model = model; this.type = type; this.backWood = backWood; this.topWood = topWood; } /* This method returns the Serialnumber of Guitar */ public String getSerialNumber() { return serialNumber; } /* This method returns the Price of Guitar */ public double getPrice() { return price; } /* This method set the newPrice of Guitar passed through arrguments * Input: Float */ public void setPrice(float newPrice) { this.price = newPrice; } /* This method returns the Builder of Guitar */ public String getBuilder() { return builder; } /* This method returns the Model of Guitar */ public String getModel() { return model; } /* This method returns the Type of Guitar */ public String getType() { return type; } /* This method returns the BackWood of Guitar */ public String getBackWood() { return backWood; } /* This method returns the TopWood of Guitar */ public String getTopWood() { return topWood; } }
true
0e403c9999791d25f0207c1e056db51231de7a09
Java
Prosta4okua/Atmosphere
/src/main/java/net/insomniakitten/atmosphere/util/dev/BlockStateFactory.java
UTF-8
2,728
2.0625
2
[]
no_license
package net.insomniakitten.atmosphere.util.dev; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import net.insomniakitten.atmosphere.Atmosphere; import net.minecraft.block.Block; import net.minecraft.block.properties.IProperty; import net.minecraft.client.Minecraft; import net.minecraftforge.fml.client.FMLClientHandler; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import javax.annotation.Nullable; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.file.Paths; import java.util.LinkedHashMap; import java.util.Map; import java.util.TreeMap; @SideOnly(Side.CLIENT) public final class BlockStateFactory { private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); private final String assets; private final String path; private BlockStateFactory(Minecraft mc, String modid) { String path = Paths.get(mc.mcDataDir.getAbsolutePath()).getParent().getParent().toString(); this.assets = path + "/src/main/resources/assets/"; this.path = modid + "/blockstates/"; } public static BlockStateFactory create(String modid) { Minecraft mc = FMLClientHandler.instance().getClient(); return new BlockStateFactory(mc, modid); } public void generateFor(Block block) { generateFor(block, null); } public void generateFor(Block block, @Nullable Object defaults) { if (!Atmosphere.DEOBF) return; Map<String, Object> json = new LinkedHashMap<>(); Map<String, Object> variants = new TreeMap<>(); String name = block.getRegistryName().getResourcePath(); File file = new File(assets + path + name + ".json"); file.getParentFile().mkdirs(); if (file.exists()) return; try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } json.put("forge_marker", 1); if (defaults != null) { json.put("defaults", defaults); } for (IProperty property : block.getDefaultState().getPropertyKeys()) { String key = property.getName(); Map<String, Object> values = new TreeMap<>(); for (Object value : property.getAllowedValues()) { String v = property.getName((Comparable) value); values.put(v, new Object()); } variants.put(key, values); } json.put("variants", variants); try (FileWriter writer = new FileWriter(file)) { GSON.toJson(json, writer); } catch (IOException e) { e.printStackTrace(); } } }
true
1b338d144249e9b06c4a1a78801f480b2174f688
Java
lichao20000/dayatang-multi-module-archetype
/src/main/resources/archetype-resources/webapp/src/main/java/webapp/action/outputvalue/ReportAction.java
UTF-8
465
1.726563
2
[]
no_license
#set( $symbol_pound = '#' ) #set( $symbol_dollar = '$' ) #set( $symbol_escape = '\' ) package ${package}.webapp.action.outputvalue; import ${package}.webapp.action.BaseAction; /** * User: zjzhai * Date: 13-4-17 * Time: 上午9:06 */ public class ReportAction extends BaseAction { /** * */ private static final long serialVersionUID = -2127243293678190255L; @Override public String execute() throws Exception { return SUCCESS; } }
true
b3c6319847a78980559664a88093b5ffe5c39b37
Java
KentinLaw/Springboot-demo
/wms-web/src/main/java/com/kt/wms/api/TestApi.java
UTF-8
1,277
2.140625
2
[ "MIT" ]
permissive
package com.kt.wms.api; import com.kt.wms.model.result.Result; import com.kt.wms.model.result.ResultFactory; import com.kt.wms.model.system.User; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.*; /** * @author kentinlaw * @version 1.0 * @date 2020/4/9 00:34 * @description 测试 */ @Api(value = "测试接口") @RestController @RequestMapping("/test") public class TestApi { @GetMapping public Result getUserList(){ return ResultFactory.buildSuccessResult("get 查询"); } @ApiOperation(value = "测试接口") @GetMapping("/{id:\\d+}") public Result getUser(@PathVariable Integer id){ return ResultFactory.buildSuccessResult("get 查询"+id); } @PostMapping public Result addTest(@RequestBody User user){ return ResultFactory.buildSuccessResult("post 新建"+user.getNickname()); } @DeleteMapping("/{username}") public Result delTest(@PathVariable String username){ return ResultFactory.buildSuccessResult("del 删除"+username); } @PutMapping("/{id:\\d+}") public Result updateTest(@RequestBody User user){ return ResultFactory.buildSuccessResult("put 修改"+user.getId()); } }
true
20f9f82ca9b6493ee1502b5a7cdc0fc322d9d5ca
Java
MichielAriens/assemassist12
/group12/src/controllers/MechanicController.java
UTF-8
4,502
3.375
3
[ "MIT" ]
permissive
package controllers; import java.util.ArrayList; import java.util.List; import logic.users.Mechanic; import logic.workstation.Task; import logic.workstation.Workstation; /** * Class used to form a link between the user interface and the Mechanic class. */ public class MechanicController extends UserController{ /** * The current mechanic. */ private Mechanic currentMechanic; /** * Sets the current mechanic to the given mechanic. * @param mechanic The new mechanic. */ public void setMechanic(Mechanic mechanic) { this.currentMechanic = mechanic; } /** * Returns the user name of the current mechanic. * @return Null if the current mechanic is null. * The user name of the current mechanic otherwise. */ @Override public String getUserName() { if(this.currentMechanic != null) return this.currentMechanic.getUserName(); return null; } /** * Returns the list of workstations from the assembly line with numbering if the current * mechanic is not null. * @return Null if the current mechanic is null. * The list of workstations from the assembly line with numbering otherwise. */ public ArrayList<String> getWorkStations(){ if(this.currentMechanic == null) return null; ArrayList<String> workstations = new ArrayList<String>(); List<Workstation> stations = this.currentMechanic.getWorkstations(); int count = 1; for(Workstation w : stations){ workstations.add(w.toString() + ": " + count); count++; } return workstations; } /** * Returns the list of tasks the current mechanic can perform with numbering. * @return Null if the mechanic is null. * The list of tasks the mechanic can perform with numbering otherwise. */ public ArrayList<String> getTasks(){ if(this.currentMechanic == null) return null; ArrayList<String> tasks = new ArrayList<String>(); int count = 1; for(Task task : this.currentMechanic.getAvailableTasks()){ tasks.add(task.toString() + ": " + count); count++; } return tasks; } /** * Returns the task information for the given task. * @param taskName The task for which the information needs to be returned. * @return Returns null if: * - the mechanic is null * - the given task name does not correspond with any of the tasks of the workstation * Returns the task information otherwise. */ public String getTaskInformation(String taskName){ if(this.currentMechanic == null) return null; for(Task task : this.currentMechanic.getAvailableTasks()){ if(task.toString().equals(taskName)) return task.getDescription(); } return null; } /** * Performs the given task if the current mechanic is not null. * @param taskName The name of the task that needs to be performed. * @param duration How long the task took to perform. */ public void doTask(String taskName, int duration){ if(this.currentMechanic == null) return; for(Task task : this.currentMechanic.getAvailableTasks()){ if(task.toString().equals(taskName)) currentMechanic.doTask(task, duration); } } /** * Sets the workstation for the current mechanic to the given workstation. * @param workstationName The new workstation for the current mechanic. */ public void setWorkStation(String workstationName){ if(this.currentMechanic == null) return; for(Workstation station : this.currentMechanic.getWorkstations()){ if(station.toString().equals(workstationName)) this.currentMechanic.setActiveWorkstation(station); } } /** * Returns the list of tasks per workstation, stating pending and completed tasks * or stating inactive if there are no tasks at the workstation. * @return The list of tasks per workstation, stating pending and completed tasks * or stating inactive if there are no tasks at the workstation. */ public List<String> getTasksPerWorkstation(){ if(this.currentMechanic == null) return null; List<Workstation> workStations = this.currentMechanic.getWorkstations(); ArrayList<String> tasks = new ArrayList<String>(); for(Workstation stat : workStations){ String temp = stat.toString() + ":\n"; if(this.currentMechanic.getAllTasks(stat).size() == 0) temp += "Inactive.\n"; else{ for(Task task : this.currentMechanic.getAllTasks(stat)){ if(task.isComplete()) temp += " -" + task.toString() + ": Completed\n"; else temp += " -" + task.toString() + ": Pending\n"; } } tasks.add(temp); } return tasks; } }
true
e71dcbcd79379827b66b95349d6dcc1e0b9f0476
Java
zhaoyu1111/graduation1
/src/main/java/com/zy/graduation1/mapper/ImageMapper.java
UTF-8
325
1.546875
2
[]
no_license
package com.zy.graduation1.mapper; import com.zy.graduation1.entity.Image; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; /** * <p> * Mapper 接口 * </p> * * @author zy * @since 2019-03-21 */ @Mapper public interface ImageMapper extends BaseMapper<Image> { }
true
bbbbfa410129b1f857192fee95960cd77c69147f
Java
rahulsajekar/Backup-Repo
/DataStructures/src/StreamAPIDemo.java
UTF-8
1,224
3.765625
4
[]
no_license
import java.util.Stack; public class StreamAPIDemo { public static void main(String[] args) { Stack<String> s1 = new Stack<>(); s1.push("rahul"); s1.push("chetan"); s1.push("ketan"); s1.push("tejas"); s1.push("rina"); // find names starts with 'r' and print them // Traditional Method // for(int i=s1.size(); i>0; i--){ // String value = s1.pop(); // if (value.startsWith("t")){ // System.out.println(value); // } // } // using stream API s1.stream() .filter(x->x.startsWith("r")) .forEach(x-> System.out.println(x)); Stack<Integer> s2 = new Stack<>(); s2.push(10); s2.push(20); s2.push(30); s2.push(40); s2.push(50); // print the total of all values in stack final int total = 0; System.out.println( s2.stream() .mapToInt(Integer::intValue) .sum() ); // find if all element in stack grater than or equal 15 System.out.println( s2.stream().allMatch(x->x>=15) ); } }
true
df1d485bfce67a0775af45b1c43d38200357ff33
Java
kssja/CoderGirlProjects-
/ThankYouMailMerge.java
UTF-8
2,618
3.125
3
[]
no_license
import static java.lang.System.out; import java.util.Scanner; import java.text.NumberFormat; public class ThankYouMailMerge{ public static void main(String[] args){ double amt= 0; String name=""; Scanner keyboard = new Scanner(System.in); name=""; out.println("Thank You Letter"); NumberFormat fmt = NumberFormat.getCurrencyInstance(); boolean keepGoing = true; while(keepGoing){ out.println("\nPlease enter your first and last name \n "); name = keyboard.nextLine(); if(name.equalsIgnoreCase("quit")){ out.println("Did you mean to enter quit?" + "\nEnter quit again to end the program or yes to continue"); name = keyboard.nextLine(); if(name.equalsIgnoreCase("quit")){ out.println("Goodbye!"); keepGoing = false; }else {keepGoing = true; } } if (keepGoing){ // out.println("\nPlease enter your first and last name \n "); //name = keyboard.nextLine(); out.println("How much would you like to contribute?"); amt = keyboard.nextDouble(); out.println( "\n\nDear " + name + "," + "\nThank you for your donation! We rely on donors like you to keep our" + "\norganization effective, and you came through for us. Your donation of " + fmt.format(amt) + "\nwill help our efforts to make a difference in the world."+ "\n\nAs you may know, we are a registered non-profit organization,"+ "\nso your dontation is tax deductible. You may use this letter" + "\nas a receipt for tax purposes. " + "\n\nThank you again for your support!"+ "\n\nSincerely," + "\nPaula Jones" + "\nYour Charity.org"); out.print("\n\nDo you have more letters to send?"+ "\nEnter Yes for more letters or quit to end the program "); name = keyboard.nextLine(); name = keyboard.nextLine(); if(name.equalsIgnoreCase("quit")){ out.println("Goodbye!"); keepGoing = false; }else keepGoing = true; } } } }
true
90bc37342dadb1c212d30642cf3b6c2c49dc3924
Java
Andiekistner95/Array_Matriz
/Array_Matriz/src/exercicio/numero17/Classe.java
ISO-8859-1
805
3.9375
4
[]
no_license
/* * Criar um array com 10 posies, com valores de 1 a 10 sequenciais. Criar um array de 5 posies. Popular o segundo array somente com os valores mpares do primeiro array utilizando for. Imprimir o segundo array para verificar se o algoritmo funcionou. */ package exercicio.numero17; public class Classe { public static void main(String[] args) { int[] a = new int[10]; int[] b = new int[5]; int posicao = 0; a[0] = 1; a[1] = 2; a[2] = 3; a[3] = 4; a[4] = 5; a[5] = 6; a[6] = 7; a[7] = 8; a[8] = 9; a[9] = 10; for (int aux = 0; aux < a.length; aux++) { if (a[aux] % 2 != 0) { b[posicao] = a[aux]; posicao++; } } for ( int aux = 0; aux < b.length; aux++ ){ System.out.println(b[aux]); } } }
true
2ccd07363e303a865b5efed6b957bb206ebcb8b6
Java
gaohe1227/othsers
/datamg/src/net/zz/sys/action/LogAction.java
UTF-8
740
1.804688
2
[]
no_license
package net.zz.sys.action; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Namespace; import org.springframework.beans.factory.annotation.Autowired; import net.zz.sys.model.Log; import net.zz.sys.service.LogService; import net.zz.utils.base.action.BaseAction; /** * * <b><code></code></b> * <p/> * Comment here * <p/> * <b>Creation Time:</b> 2014年5月23日 * @author ZhangZhen * @version 1.0 * * @since datamg 1.0 */ @SuppressWarnings("serial") @Namespace("/sys") @Action(value="logAction") public class LogAction extends BaseAction<Log> { @Autowired public void setService(LogService service){ this.service = service; this.serviceName = "日志管理"; } }
true
aaecdf17b5a8660fc4f81a20d1cea7be9c30cbd7
Java
harish02-11-1996/Area
/interface/src/hm.java
UTF-8
484
2.75
3
[]
no_license
public class hm { public static void main(String[] args) { student dref1=new student(); teacher dref2=new teacher(); school dref3=new school(); System.out.println("the details of the student is: "); dref1.getdetails(); dref1.getaddress(); System.out.println("the details of the teacher is:"); dref2.getdetails(); dref2.getaddress(); System.out.println("the details of the school is"); dref3.getdetails(); dref3.getaddress(); } }
true
f7efbff9381f4ba3609816ce3229b64f6b282426
Java
OpenMake-Software/svn-importer
/org.polarion.svnimporter.main/src/org/polarion/svnimporter/main/internal/MainConfig.java
UTF-8
13,429
1.65625
2
[]
no_license
/* * Copyright (c) 2004, 2005 Polarion Software, All rights reserved. * Email: community@polarion.org * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. Copy of the License is * located in the file LICENSE.txt in the project distribution. You may also * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * * POLARION SOFTWARE MAKES NO REPRESENTATIONS OR WARRANTIES * ABOUT THE SUITABILITY OF THE SOFTWARE, EITHER EXPRESSED OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. POLARION SOFTWARE * SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT * OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. * */ /* * $Log$ */ package org.polarion.svnimporter.main.internal; import org.polarion.svnimporter.common.ConfigUtil; import org.polarion.svnimporter.common.IProvider; import org.polarion.svnimporter.common.Log; import org.polarion.svnimporter.common.Util; import org.polarion.svnimporter.svnprovider.SvnAdmin; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.text.ParsePosition; import java.util.Date; import java.util.Properties; /** * * * @author <A HREF="mailto:svnimporter@polarion.org">Polarion Software</A> */ public class MainConfig { private static final Log LOG = Log.getLog(MainConfig.class); private static final String SVNIMPORTER_VERSION = "svnimporter 1.1-SHAPSHOT (after M8)"; /** * Command line options */ private static final String ONLY_LIST_MODE = "list"; private static final String FULL_DUMP_MODE = "full"; private static final String INCREMENTAL_DUMP_MODE = "incremental"; private static final String HELP_MODE = "help"; private static final String VERSION_MODE = "version"; /** * Config file keys */ private static final String FULL_DUMP_FILE_KEY = "full.dump.file"; private static final String INCR_DUMP_FILE_KEY = "incr.dump.file"; private static final String INCR_HISTORY_FILE_KEY = "incr.history.file"; private static final String LIST_FILES_TO_KEY = "list.files.to"; private static final String SRC_PROVIDER_KEY = "srcprovider"; private static final String DUMPFILE_SIZE_LIMIT = "dump.file.sizelimit.mb"; private static final String USAGE = "usage: command config_file [lastdate]" + "\n\nCommands:" + "\n\t" + ONLY_LIST_MODE + " - dont create dump, only list files" + "\n\t" + FULL_DUMP_MODE + " - create full dump [revisions up to lastdate]" + "\n\t" + INCREMENTAL_DUMP_MODE + " - create incremental dump [revisions up to lastdate]" + "\n\t" + HELP_MODE + " - show help" + "\n\t" + VERSION_MODE + " - show version"; private static final String AUTOPROPS_FILE_KEY = "config.autoprops"; /** * Path to full dump file. Can be a file pattern containing "%date%". */ private String fullDumpFilePattern; /** * Path to incremental dump file. Can be a file pattern containing "%date%". */ private String incrlDumpFilePattern; /** * Path to (incremental) history file */ private String incrHistoryFile; /** * Path to autoprops file */ private String autopropsFile; /** * Enable full dump mode */ private boolean fullDump; /** * Enable incemental dump mode */ private boolean incrementalDump; /** * Enable "only list files" mode */ private boolean onlyListFiles; /** * Target file for saving scm's files list */ private String listFilesTo; /** * Enable "import dump into svn" mode */ private boolean importDump; private boolean existingSvnrepos; /** * If true then do not cleanup provider's temp files */ private boolean disableCleanup; /** * Source scm provider */ private IProvider srcProvider; private boolean clearSvnParentDir; /** * SvnAdmin */ private SvnAdmin svnAdmin; private Log historyLogger; private Properties srcProperties; /** * consider only revision up to this date. */ private Date lastRevDate; /** * size limit for dump files in Megabyte. */ private int dumpFileSizeLimit; public MainConfig() { } /** * Parse command line arguments * * @param args */ public void parseArgs(String[] args) { if (args.length < 1) { usage("You must specify command"); return; } String firstArg = args[0]; if (ONLY_LIST_MODE.equals(firstArg)) { onlyListFiles = true; } else if (FULL_DUMP_MODE.equals(firstArg)) { fullDump = true; } else if (INCREMENTAL_DUMP_MODE.equals(firstArg)) { incrementalDump = true; } else if (HELP_MODE.equals(firstArg)) { usage(null); return; } else if (VERSION_MODE.equals(firstArg)) { showVersion(); return; } else { usage("Unknown command \"" + firstArg + "\""); return; } if (args.length < 2) { usage("You must specify config file as second parameter"); return; } if (args.length > 3) { StringBuffer b = new StringBuffer(); b.append("unknown command line parameters: "); for (int i = 2; i < args.length; i++) { b.append(args[i] + " "); } usage(b.toString()); return; } String configFile = args[1]; try { srcProperties = Util.loadProperties(configFile); Log.configure(srcProperties); historyLogger = Log.getLog("historyLogger"); parseConfig(); } catch (IOException e) { error("can't open config file \"" + configFile + "\"", e); } if (args.length == 3) { SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm:ss"); lastRevDate = fmt.parse(args[2], new ParsePosition(0)); // expected Day in ISO format if (lastRevDate == null) { usage("ERROR: Cannot convert " + args[2] + " to date. Expected format: \"yyyy-MM-dd'T'kk:mm:ss\""); return; } } } /** * if true - then configuration has errors */ private boolean hasErrors = false; /** * Validate configuration * * @return list of errors */ public boolean validate() { return !hasErrors; } /** * Print error * * @param message * @param e */ private void error(String message, Exception e) { LOG.error(message, e); hasErrors = true; } /** * Print error * * @param message */ private void error(String message) { LOG.error(message); hasErrors = true; } /** * Print usage instruction */ private void usage(String error) { if (error != null) System.err.println(error + "\n"); System.err.println(USAGE); hasErrors = true; } private void showVersion() { System.out.println(SVNIMPORTER_VERSION); hasErrors = true; } /** * 'Nice suffix' date format */ private final DateFormat dateStringFormat = new SimpleDateFormat("yyyyMMdd_HHmmss"); private String dateString; /** * Return date string for insert as 'nice suffix' in filenames * * @return */ private String getDateString() { if (dateString == null) dateString = dateStringFormat.format(new Date()); return dateString; } public DateFormat getDateStringFormat() { return dateStringFormat; } /** * Set incremental history file */ private void setIncrHistoryFile() { String s = getStringProperty(INCR_HISTORY_FILE_KEY); if (s == null) return; incrHistoryFile = s; } /** * Set target file for saving scm's files list */ private void setListFilesTo() { String s = getStringProperty(LIST_FILES_TO_KEY); if (s == null) return; listFilesTo = insertDate(s); } /** * Configure source scm provider */ private void setSrcProvider() { String providerName = getStringProperty(SRC_PROVIDER_KEY); if (providerName == null) return; String providerClass = getStringProperty(providerName + ".class"); if (providerClass == null) return; try { Class c = Class.forName(providerClass); Object o = c.newInstance(); if (!(o instanceof IProvider)) { error("class \"" + providerClass + "\" does not implement IProvider interface"); return; } srcProvider = (IProvider) o; if (!isFullDump()) ConfigUtil.setBooleanProperty(srcProperties, "useOnlyLastRevisionContent", false);//small hack, see ProviderConfig.configure() srcProvider.configure(srcProperties); if (!srcProvider.validateConfig()) { hasErrors = true; } } catch (Exception e) { error("can't create new instance of provider class \"" + providerClass + "\"", e); } } /** * Configure dump file, src provider, ... */ private void parseConfig() { fullDumpFilePattern = getStringProperty(FULL_DUMP_FILE_KEY); incrlDumpFilePattern = getStringProperty(INCR_DUMP_FILE_KEY); autopropsFile = getStringProperty(AUTOPROPS_FILE_KEY, false); setIncrHistoryFile(); setSrcProvider(); setListFilesTo(); disableCleanup = getBooleanProperty("disable_cleanup"); importDump = getBooleanProperty("import_dump_into_svn"); existingSvnrepos = getBooleanProperty("existing_svnrepos"); clearSvnParentDir = getBooleanProperty("clear_svn_parent_dir"); dumpFileSizeLimit = getIntProperty(DUMPFILE_SIZE_LIMIT); if (dumpFileSizeLimit < 0) error("configuration property value \"" + DUMPFILE_SIZE_LIMIT + "\" may not be negative."); if (importDump && (isFullDump() || isIncrementalDump())) { svnAdmin = new SvnAdmin(); svnAdmin.configure(srcProperties); if (!svnAdmin.validateConfig()) hasErrors = true; } } public String getFullDumpFilePattern() { return fullDumpFilePattern; } public String getIncrDumpFilePattern() { return incrlDumpFilePattern; } public String getIncrHistoryFile() { return incrHistoryFile; } public String getAutopropsFile() { return autopropsFile; } public boolean isFullDump() { return fullDump; } public boolean isIncrementalDump() { return incrementalDump; } public boolean isOnlyListFiles() { return onlyListFiles; } public String getListFilesTo() { return listFilesTo; } public boolean isImportDump() { return importDump; } public boolean isExistingSvnrepos() { return existingSvnrepos; } public boolean isDisableCleanup() { return disableCleanup; } public boolean isClearSvnParentDir() { return clearSvnParentDir; } public Log getHistoryLogger() { return historyLogger; } public IProvider getSrcProvider() { return srcProvider; } public SvnAdmin getSvnAdmin() { return svnAdmin; } public Date getLastRevisionDate() { return lastRevDate; } public int getDumpFileSizeLimit() { return dumpFileSizeLimit; } /** * Log environment information */ public void logEnvironmentInformation() { LOG.info("****************************************************************************"); LOG.info("*** Global options ***"); LOG.info("Mode = " + getMode()); LOG.info("Import dump into svn = \"" + importDump + "\""); LOG.info("Import dump only if svn repository exist = \"" + existingSvnrepos + "\""); LOG.info("Full dump path = \"" + fullDumpFilePattern + "\""); LOG.info("Incremental dump path = \"" + incrlDumpFilePattern + "\""); LOG.info("Incremental history path = \"" + incrHistoryFile + "\""); LOG.info("Save files list to = \"" + listFilesTo + "\""); LOG.info("Source provider's class = \"" + srcProvider.getClass().getName() + "\""); if (lastRevDate != null) LOG.info("Date of last revision to dump = \"" + lastRevDate.toString() + "\""); LOG.info("Size limit for dump files (in MB): " + (dumpFileSizeLimit > 0 ? Integer.toString(dumpFileSizeLimit) : "none")); srcProvider.logEnvironmentInformation(); if (svnAdmin != null) { svnAdmin.logEnvironmentInformation(); } LOG.info("****************************************************************************"); } public String getMode() { String mode = ""; if (incrementalDump) mode = "create incremental dump"; if (fullDump) mode = "create full dump"; if (onlyListFiles) mode = "list files"; return mode; } private String getStringProperty(String key, boolean mandatory) { String value = srcProperties.getProperty(key); if (value == null || value.length() < 1) { if (mandatory) error("configuration property \"" + key + "\" is not set"); value = null; } else { value = value.trim(); } return value; } private String getStringProperty(String key) { return getStringProperty(key, true); } protected boolean getBooleanProperty(String key) { return ConfigUtil.getBooleanProperty(srcProperties, key); } private int getIntProperty(String key) { String val = getStringProperty(key); if (val == null) return 0; try { return Integer.parseInt(val); } catch (NumberFormatException e) { error("configuration property value \"" + key + "\" is not a valid integer."); return 0; } } private String insertDate(String value) { int indexOfDate = value.indexOf("%date%"); if (indexOfDate != -1) { return value.replaceAll("%date%", getDateString()); } else { return value; } } }
true
e3576fb8da89d641ab1747641dc8dbb2b1c806d1
Java
LLLay/shopping
/src/test/com/tt/o2o/dao/ShopDaoTest.java
UTF-8
2,821
2.15625
2
[]
no_license
package com.tt.o2o.dao; import com.tt.o2o.BaseTest; import com.tt.o2o.entity.Area; import com.tt.o2o.entity.PersonInfo; import com.tt.o2o.entity.Shop; import com.tt.o2o.entity.ShopCategory; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import java.util.Date; import java.util.List; public class ShopDaoTest extends BaseTest { @Autowired private IShopDao iShopDao; @Test public void testQueryShopList() { Shop shopCondition = new Shop(); PersonInfo owner = new PersonInfo(); owner.setUserId(1L); shopCondition.setOwner(owner); List<Shop> list =iShopDao.queryShopList(shopCondition, 0, 5); System.out.println(list.size()); } @Test public void testQueryShopCount() { Shop shopCondition = new Shop(); ShopCategory sc = new ShopCategory(); sc.setShopCategoryId(1L); shopCondition.setShopCategory(sc); int count =iShopDao.queryShopCount(shopCondition); System.out.println(count); } @Test public void testQueryByShopId(){ long shopId = 1; Shop shop = iShopDao.queryByShopId(shopId); System.out.println(shop.getArea().getAreaName()); System.out.println(shop.getArea().getAreaId()); } @Test public void testInsertShop(){ Shop shop = new Shop(); PersonInfo owner = new PersonInfo(); Area area = new Area(); ShopCategory shopCategory = new ShopCategory(); owner.setUserId(1L); area.setAreaId(2); shopCategory.setShopCategoryId(1L); shop.setOwner(owner); shop.setArea(area); shop.setShopCategory(shopCategory); shop.setShopName("测试的店铺"); shop.setShopDesc("test"); shop.setShopAddr("test"); shop.setPhone("test"); shop.setShopImg("test"); shop.setCreateTime(new Date()); shop.setEnableStatus(1); shop.setAdvice("审核中"); shop.setOwnerId(1L); int effectedNum = iShopDao.insertShop(shop); } @Test public void testUpdateShop(){ Shop shop = new Shop(); shop.setShopId(1L); shop.setShopDesc("测试"); shop.setShopAddr("测试"); int effectedNum = iShopDao.updateShop(shop); } @Test public void testQueryShopListAndCount(){ Shop shopCondition = new Shop(); ShopCategory childCategory = new ShopCategory(); ShopCategory parentCategory = new ShopCategory(); parentCategory.setShopCategoryId(1L); childCategory.setParent(parentCategory); shopCondition.setShopCategory(childCategory); List<Shop> shopList = iShopDao.queryShopList(shopCondition,0,5); int count = iShopDao.queryShopCount(shopCondition); } }
true
2eac9e9857792cda8992543c33b04f48db5b856d
Java
kobel-sidney/nicbrainweb
/src/main/java/br/com/kolss/service/ClassificacaoOcorrenciaServiceImpl.java
UTF-8
5,596
2.28125
2
[]
no_license
package br.com.kolss.service; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.apache.commons.codec.binary.Base64; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import br.com.kolss.dto.ClassificacaoOcorrenciaDTO; import br.com.kolss.dto.TipoClassificacaoOcorrenciaDTO; import br.com.kolss.exception.ServiceException; import br.com.kolss.model.entities.ClassificacaoOcorrencia; import br.com.kolss.model.entities.Contratante; import br.com.kolss.model.entities.TipoClassificacao; import br.com.kolss.model.repository.ClassificacaoOcorrenciaRepository; @Service public class ClassificacaoOcorrenciaServiceImpl implements ClassificacaoOcorrenciaService { private Logger logger = Logger.getLogger(this.getClass()); @Autowired private ClassificacaoOcorrenciaRepository classificacaoOcorrenciaRepository; @Override public ClassificacaoOcorrencia obter(Serializable id) throws ServiceException { logger.debug("ClassificacaoOcorrenciaServiceImpl.find(Serializable)"); if(id == null){ throw new ServiceException("ID Inválido"); } return classificacaoOcorrenciaRepository.obter(id); } @Override public ClassificacaoOcorrencia obterPorNome(String nomeClassificacaoOcorrencia,Contratante contratante) throws ServiceException { logger.debug("ClassificacaoOcorrenciaServiceImpl.obterPorNome(Serializable)"); if(nomeClassificacaoOcorrencia == null || nomeClassificacaoOcorrencia.equals("")){ throw new ServiceException("Nome Inválido"); } if(contratante == null || contratante.getId()==null){ throw new ServiceException("Contratante Inválido"); } return classificacaoOcorrenciaRepository.obterPorNome(nomeClassificacaoOcorrencia,contratante); } @Override public List<ClassificacaoOcorrencia> obterTodos(Contratante contratante) { logger.debug("ClassificacaoOcorrenciaServiceImpl.getClassificacoesOcorrencias"); if(contratante == null || contratante.getId()==null){ throw new ServiceException("Contratante Inválido"); } return classificacaoOcorrenciaRepository.obterTodos(contratante); } @Override @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW) public List<ClassificacaoOcorrenciaDTO> getClassificacoesOcorrenciasDTO(Contratante contratante) { if(contratante == null || contratante.getId()==null){ throw new ServiceException("Contratante Inválido"); } List<ClassificacaoOcorrencia> listaDeClassificacaoOcorrencia = classificacaoOcorrenciaRepository.obterTodos(contratante); List<ClassificacaoOcorrenciaDTO> listaDeClassificacaoOcorrenciaDTO = new ArrayList<ClassificacaoOcorrenciaDTO>(); List<TipoClassificacaoOcorrenciaDTO> listaDeTipoDeClassificacaoDeOcorrenciaDTO = new ArrayList<TipoClassificacaoOcorrenciaDTO>(); for (ClassificacaoOcorrencia classificacaoOcorrencia : listaDeClassificacaoOcorrencia) { ClassificacaoOcorrenciaDTO classificacaoOcorrenciaDTO = new ClassificacaoOcorrenciaDTO(); classificacaoOcorrenciaDTO.setId(String.valueOf(classificacaoOcorrencia.getId())); classificacaoOcorrenciaDTO.setNome(classificacaoOcorrencia.getNome()); byte[] imgIcone = null; imgIcone = classificacaoOcorrencia.getIcone(); classificacaoOcorrenciaDTO.setBitmapImageIcone(Base64.encodeBase64String(imgIcone)); for (TipoClassificacao tipoClassificacaoOcorrencia : classificacaoOcorrencia.getTiposClassificacoes()) { TipoClassificacaoOcorrenciaDTO tipoClassificacaoOcorrenciaDTO = new TipoClassificacaoOcorrenciaDTO(); tipoClassificacaoOcorrenciaDTO.setId(tipoClassificacaoOcorrencia.getId().toString()); tipoClassificacaoOcorrenciaDTO.setNome(tipoClassificacaoOcorrencia.getNome()); tipoClassificacaoOcorrenciaDTO.setIdGravidade(tipoClassificacaoOcorrencia.getGravidadeOcorrencia().getId().toString()); tipoClassificacaoOcorrenciaDTO.setIdClassificacao(tipoClassificacaoOcorrencia.getClassificacaoOcorrencia().getId().toString()); listaDeTipoDeClassificacaoDeOcorrenciaDTO.add(tipoClassificacaoOcorrenciaDTO); } classificacaoOcorrenciaDTO.setListaDeTipoDeClassificacaoOcorrencia(listaDeTipoDeClassificacaoDeOcorrenciaDTO); classificacaoOcorrenciaDTO.setIdContratante(contratante.getId()); listaDeClassificacaoOcorrenciaDTO.add(classificacaoOcorrenciaDTO); } return listaDeClassificacaoOcorrenciaDTO; } @Override public List<TipoClassificacaoOcorrenciaDTO> obterTipoClassificacoesOcorrenciasDTO(Long idGravidade, Contratante contratante) { List<TipoClassificacao> list = classificacaoOcorrenciaRepository.obterTipoClassificacoesOcorrenciasPorIdClasContrante(idGravidade,contratante); List<TipoClassificacaoOcorrenciaDTO> tipos = new ArrayList<TipoClassificacaoOcorrenciaDTO>(); for (TipoClassificacao tipoClassificacao : list) { TipoClassificacaoOcorrenciaDTO tipoClassificacaoOcorrenciaDTO = new TipoClassificacaoOcorrenciaDTO(); tipoClassificacaoOcorrenciaDTO.setId(tipoClassificacao.getId().toString()); tipoClassificacaoOcorrenciaDTO.setNome(tipoClassificacao.getNome()); tipoClassificacaoOcorrenciaDTO.setIdClassificacao(tipoClassificacao.getClassificacaoOcorrencia().getId().toString()); tipoClassificacaoOcorrenciaDTO.setIdGravidade(tipoClassificacao.getGravidadeOcorrencia().getId().toString()); tipos.add(tipoClassificacaoOcorrenciaDTO); } return tipos; } }
true
92beba198031b2b402c218d284b8af35cab05e76
Java
zhongxingyu/Seer
/Diff-Raw-Data/2/2_1b6bc7f280073aedb27ee171b0930b61792db2e3/Method/2_1b6bc7f280073aedb27ee171b0930b61792db2e3_Method_t.java
UTF-8
924
2.171875
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.syr.bytecast.jimple.api; import edu.syr.bytecast.amd64.api.instruction.IInstruction; import edu.syr.bytecast.amd64.api.output.MemoryInstructionPair; import java.util.ArrayList; import java.util.List; /** * @author Fei Qi */ // used to combine the method content and method info public class Method { private MethodInfo methodInfo; private List<MemoryInstructionPair> l_instruction; public MethodInfo getM_info() { return m_info; } public void setM_info(MethodInfo m_info) { this.m_info = m_info; } public List<MemoryInstructionPair> getL_instruction() { return l_instruction; } public void setL_instruction(List<MemoryInstructionPair> l_instruction) { this.l_instruction = l_instruction; } }
true
31b872968044ea713936b668e5ff5364844d9527
Java
fmaylinch/translator
/src/main/java/com/codethen/translator/api/model/TranslateResponse.java
UTF-8
221
1.851563
2
[]
no_license
package com.codethen.translator.api.model; public class TranslateResponse { public String text; public TranslateResponse() { } public TranslateResponse(String text) { this.text = text; } }
true
645a793145413f435d40617dcdc7e5105727d79d
Java
keerthivrao/EduAdmin
/src/com/db/access/DBEngine.java
UTF-8
18,287
2.5625
3
[]
no_license
package com.db.access; import java.sql.Connection; import java.sql.Date; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.HashMap; import java.util.List; import javax.naming.Context; import javax.naming.InitialContext; import javax.sql.DataSource; import com.mysql.jdbc.Util; /** * @Title : DBEngine.java * @Description : DBEngine handles database related operations * @Author : Keerthi Venkateswara Rao * @Version : 1.0 * @link */ public class DBEngine implements QueryConstants { // Data Types public static final short __VARCHAR = 0; public static final short __INTEGER = 1; public static final short __DATE = 2; public static final short __TIMESTAMP = 3; public static final short __TIME = 4; public static final short __SHORT = 5; public static final short __FLOAT = 6; /** * Returns the connection to the data base configured in the properties file */ private Connection getConnection() { Connection connection = null; try { System.out.println("Getting Connection"); Context initContext = new InitialContext(); Context envContext = (Context)initContext.lookup("java:/comp/env"); DataSource ds = (DataSource)envContext.lookup("jdbc/creditusa"); connection = (Connection)ds.getConnection(); } catch (Exception e) { e.printStackTrace(); } return connection; } /** public Connection getConnection() { Connection con = null; try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://thecreditusa.virtual.vps-host.net:3306/creditusa", "creditusa", "root"); if (!con.isClosed()) System.out.println("Successfully connected to " + "MySQL server using TCP/IP..."); } catch (Exception e) { System.err.println("Exception: " + e.getMessage()); } finally { } return con; } /**/ /** private Connection getConnection() { Connection connection = null; try { System.out.println("Getting Connection"); Context initContext = new InitialContext(); Context envContext = (Context)initContext.lookup("java:/comp/env"); DataSource ds = (DataSource)envContext.lookup("jdbc/creditusa"); connection = (Connection)ds.getConnection(); /* Class.forName(driver); InitialContext context = new InitialContext(); context = (InitialContext) context.lookup("jdbc/hru"); DataSource dataSource = context.get connection = DriverManager.getConnection(url, userName, password); */ /* } catch (Exception e) { e.printStackTrace(); } return connection; } */ /** * Closes the connection associated with the resultset */ public void closeConnection(ResultSet resultSet) { //System.out.println("Closing Connection :: ResultSet "); if (resultSet != null) { try { Statement statement = resultSet.getStatement(); Connection connection = null; if(statement != null) connection = statement.getConnection(); resultSet.close(); if (statement != null) statement.close(); if (connection != null) connection.close(); resultSet = null; statement = null; connection = null; } catch (SQLException e) { e.printStackTrace(); } } } public void closeConnection(Connection connection) { //System.out.println("Closing Connection :: Connection "); try { if (connection != null) connection.close(); connection = null; } catch (SQLException e) { e.printStackTrace(); } } private void closeConnection(PreparedStatement preparedStatement) { //System.out.println("Closing Connection :: PreparedStatement"); try { if (preparedStatement != null ) { Connection connection = preparedStatement.getConnection(); if (preparedStatement != null) preparedStatement.close(); if (connection != null) connection.close(); preparedStatement = null; connection = null; } } catch (SQLException e) { e.printStackTrace(); } } /** * Executes the query string */ public QueryResults executeQuery(String query) throws Exception { Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { connection = getConnection(); statement = connection.createStatement(); resultSet = statement.executeQuery(query); } catch (SQLException e) { throw new Exception("Unexpected error occured due to :[" + e.getMessage() + "]"); } return populateResults(resultSet); } public QueryResults executeQuery(String query, String beanName) throws Exception { Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { connection = getConnection(); statement = connection.createStatement(); resultSet = statement.executeQuery(query); } catch (SQLException e) { throw new Exception("Unexpected error occured due to :[" + e.getMessage() + "]"); } if(beanName == null || "".equals(beanName)) return populateResults(resultSet); return populateResults(resultSet, beanName); } public QueryResults executeQuery(Query query, List data) throws Exception { QueryResults results = null; //boolean closeConnection = false; Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; boolean closeConnection = false; try { connection = getConnection(); preparedStatement = connection.prepareStatement(query.getQuery()); preparedStatement = populateData(preparedStatement, query .getParameters(), data); String mode = query.getMode(); int effectedRows = 0; if (mode != null) { mode = mode.toUpperCase().trim(); } if (SELECT.equals(mode)) { closeConnection = false; resultSet = preparedStatement.executeQuery(); results = populateResults(resultSet); } else if (INSERT.equals(mode)) { closeConnection = true; effectedRows = preparedStatement.executeUpdate(); resultSet = preparedStatement.getGeneratedKeys(); results = populateResults(effectedRows, resultSet); } else if (UPDATE.equals(mode)) { closeConnection = true; effectedRows = preparedStatement.executeUpdate(); results = populateResults(effectedRows, null); } else if (DELETE.equals(mode)) { closeConnection = true; effectedRows = preparedStatement.executeUpdate(); results = populateResults(effectedRows, null); } } catch (SQLException e) { throw new Exception("Unexpected error occured due to :[" + e.getMessage() + "]"); } catch (Exception e) { throw new Exception("Unexpected error occured due to :[" + e.getMessage() + "]"); } finally { if(closeConnection) { if(preparedStatement != null ) { closeConnection(preparedStatement); } else if(connection != null) { closeConnection(connection); } } } return results; } public QueryResults executeBatchUpdate(Query query,HashMap valueMap,boolean updateAll) throws Exception { QueryResults results = null; try{ int effectedRows = executeBatchUpdate(query, valueMap,query.getParameters(),updateAll); results = populateResults(effectedRows, null); } catch (SQLException e) { throw new Exception("Unexpected error occured due to :[" + e.getMessage() + "]"); } catch (Exception e) { throw new Exception("Unexpected error occured due to :[" + e.getMessage() + "]"); } return results; } public QueryResults executeBatchUpdate(Query query,HashMap valueMap) throws Exception { QueryResults results = null; try{ int effectedRows = executeBatchUpdate(query, valueMap,query.getParameters(),false); results = populateResults(effectedRows, null); } catch (SQLException e) { throw new Exception("Unexpected error occured due to :[" + e.getMessage() + "]"); } catch (Exception e) { throw new Exception("Unexpected error occured due to :[" + e.getMessage() + "]"); } return results; } public QueryResults executeQuery(Query query, List data, String beanName) throws Exception { QueryResults results = null; Connection connection = null; PreparedStatement preparedStatement= null; ResultSet resultSet = null; boolean closeConnection = false; try { connection = getConnection(); preparedStatement = connection.prepareStatement(query.getQuery()); preparedStatement = populateData(preparedStatement, query .getParameters(), data); String mode = query.getMode(); int effectedRows = 0; if (mode != null) { mode = mode.toUpperCase().trim(); } if (SELECT.equals(mode)) { resultSet = preparedStatement.executeQuery(); results = populateResults(resultSet, beanName); } else if (INSERT.equals(mode)) { closeConnection = true; effectedRows = preparedStatement.executeUpdate(); resultSet = preparedStatement.getGeneratedKeys(); results = populateResults(effectedRows, resultSet); } else if (UPDATE.equals(mode)) { closeConnection = true; effectedRows = preparedStatement.executeUpdate(); results = populateResults(effectedRows, null); } else if (DELETE.equals(mode)) { closeConnection = true; effectedRows = preparedStatement.executeUpdate(); results = populateResults(effectedRows, null); } } catch (SQLException e) { throw new Exception("Unexpected error occured due to :[" + e.getMessage() + "]"); } catch (Exception e) { throw new Exception("Unexpected error occured due to :[" + e.getMessage() + "]"); } finally { if(closeConnection) { if(preparedStatement != null) { closeConnection(preparedStatement); } else if(connection != null) { closeConnection(connection); } } } return results; } public QueryResults execute(String queryIdentifier, List values) { return null; } public Object execute(Query query, List data, String beanName) throws Exception { return executeQuery(query, data, beanName); } public QueryResults populateResults(ResultSet results, String beanName) throws SQLException { ResultSetMetaData metaData = null; QueryResults queryResults = new QueryResults(); Utils utils = new Utils(); HashMap propertyMap = null; Object dataRow = null; try { if (results != null) { metaData = results.getMetaData(); if (metaData != null) { while (results.next()) { propertyMap = new HashMap(0); String value = ""; for (int index = 1; index <= metaData.getColumnCount(); index++) { String fieldName = removeUnderScores(metaData .getColumnName(index).toLowerCase().trim()); value = results.getString(index); if (value == null) value = ""; propertyMap.put(fieldName, value); } dataRow = utils.populateProperties(beanName, propertyMap); queryResults.add(dataRow); } } } } catch (SQLException e) { e.printStackTrace(); } finally { closeConnection(results); } return queryResults; } public String removeUnderScores(String columnName) { int i = columnName.indexOf("_"); int size = columnName.length(); while (i >= 0) { columnName = columnName.substring(0, i) + columnName.substring(i + 1, size); size -= 1; i = columnName.indexOf("_"); } return columnName; } public QueryResults populateResults(ResultSet results) throws SQLException { ResultSetMetaData metaData = null; QueryResults queryResults = new QueryResults(); DataRow dataRow = null; try { if (results != null) { metaData = results.getMetaData(); if (metaData != null) { for (int index = 1; index < metaData.getColumnCount(); index++) { queryResults.addHeader(metaData.getColumnName(index)); } } while (results.next()) { dataRow = new DataRow(); for (int index = 1; index < metaData.getColumnCount(); index++) { dataRow.add(results.getString(index)); } queryResults.add(dataRow); } } } catch (SQLException e) { e.printStackTrace(); } finally { closeConnection(results); } return queryResults; } public QueryResults populateResults(int rowsAffected, ResultSet results) throws SQLException { QueryResults queryResults = new QueryResults(); queryResults.setAffectedRows(rowsAffected); try { if (results != null) { while (results.next()) { queryResults.setGeneratedNum(results.getInt(1)); } } } catch(SQLException SQLE) { SQLE.printStackTrace(); throw SQLE; } finally{ try { if(results != null) results.close(); results = null; } catch(SQLException e) { e.printStackTrace(); } } return queryResults; } private PreparedStatement populateData(PreparedStatement preparedStatement, List parameters, List data) throws SQLException { if (data != null && parameters != null && data.size() == parameters.size()) { for (int colDataIndex = 0, size = data.size(); colDataIndex < size; colDataIndex++) { Parameter param = (Parameter) parameters.get(colDataIndex); String value = (String) data.get(colDataIndex); preparedStatement = populateData(preparedStatement, param .getDataType(), value, colDataIndex + 1); } } return preparedStatement; } private PreparedStatement populateData(PreparedStatement preparedStatement, short columnDataType, String value, int parameterIndex) throws SQLException { try { switch (columnDataType) { case __DATE: if ((value != null) && (!("".equals(value))) && (!("_".equals(value)))) { preparedStatement.setDate(parameterIndex, Date .valueOf(value)); } else { preparedStatement.setDate(parameterIndex, null); } break; case __INTEGER: if ((value != null) && (!("".equals(value)))) { preparedStatement.setInt(parameterIndex, java.lang.Integer .parseInt(value)); } else { preparedStatement.setInt(parameterIndex, 0); } break; case __SHORT: preparedStatement.setShort(parameterIndex, java.lang.Short .parseShort(value)); break; case __VARCHAR: if ((value != null) && (!("".equals(value)))) { preparedStatement.setString(parameterIndex, value); } else { preparedStatement.setString(parameterIndex, null); } break; case __TIME: preparedStatement.setTime(parameterIndex, java.sql.Time .valueOf(value)); break; case __TIMESTAMP: preparedStatement.setTimestamp(parameterIndex, java.sql.Timestamp.valueOf(value)); case __FLOAT: if ((value != null) && (!("".equals(value)))) { preparedStatement.setFloat(parameterIndex,Float.parseFloat(value)); } else preparedStatement.setFloat(parameterIndex, 0.0f); break; default: //System.out.println("default"); } } catch (IllegalArgumentException IAE) { preparedStatement.setNull(parameterIndex, getSQLType(columnDataType)); } catch (SQLException SQLE) { preparedStatement.setNull(parameterIndex, getSQLType(columnDataType)); } return preparedStatement; } /** * Gets the equivalent data type in SQL */ private int getSQLType(short columnDataType) { int sqlType = -99; switch (columnDataType) { case __DATE: sqlType = java.sql.Types.DATE; break; case __INTEGER: sqlType = java.sql.Types.INTEGER; break; case __SHORT: sqlType = java.sql.Types.SMALLINT; break; case __VARCHAR: sqlType = java.sql.Types.VARCHAR; break; case __TIME: sqlType = java.sql.Types.TIME; break; case __TIMESTAMP: sqlType = java.sql.Types.TIMESTAMP; break; case __FLOAT: sqlType = java.sql.Types.FLOAT; break; } return sqlType; } public QueryResults execute(String queryString, Query query, List data, String beanName) throws Exception { Query tempQuery = new Query(); tempQuery.setQuery(queryString); tempQuery.setParameters(query.getParameters()); tempQuery.setMode(query.getMode()); System.out.println(queryString); System.out.println(data); return executeQuery(tempQuery, data, beanName); } /** * Adds multiple statements to be executed into a batch and gets the batch executed */ private int executeBatchUpdate(Query query, HashMap valueMap,List parameters,boolean updateAll) throws Exception { QueryResults results = null; Connection connection = null; PreparedStatement preparedStatement= null; ResultSet resultSet = null; boolean closeConnection = false; int parameterIndex = 0; List data = null; int effectedRows = 0; boolean rollBack = false; try { connection = getConnection(); if(updateAll) connection.setAutoCommit(false); int[] totalUpdates = null; preparedStatement = connection.prepareStatement(query.getQuery()); int valueMapSize = 0; if(valueMap != null && valueMap.size() != 0) { valueMapSize = valueMap.size(); for(int batchIndex = 0, totalBatches = valueMap.size(); batchIndex < totalBatches; batchIndex++) { parameterIndex = 1; data = (List) valueMap.get(new Integer(batchIndex)); preparedStatement = populateData(preparedStatement, parameters, data); preparedStatement.addBatch(); } totalUpdates = preparedStatement.executeBatch(); effectedRows = 0; for(int index = 0; index < totalUpdates.length; index++) { effectedRows += totalUpdates[index]; } } else { effectedRows = preparedStatement.executeUpdate(); } if(updateAll) { if(effectedRows == valueMapSize) { rollBack = false; } else { rollBack = true; connection.rollback(); } } } finally { closeConnection(connection); if(rollBack) { throw new Exception("ECP001"); } } return effectedRows; } }
true
5742c6f869a9a6b1bb90151657f2bb9ee56cccaa
Java
dmidelrey/LabsITMO
/src/ru/lab/commands/ExecuteScript.java
UTF-8
2,781
2.65625
3
[]
no_license
package ru.lab.commands; import ru.lab.client.Client; import ru.lab.client.CommandData; import ru.lab.controller.FlatController; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; public class ExecuteScript extends Command{ private CommandData commandData; private ArrayList<String> workingScripts; public ExecuteScript(ArrayList<String> workingScripts) { commandData = new CommandData(true); this.workingScripts = workingScripts; } public ExecuteScript() { commandData = new CommandData(true); this.workingScripts = new ArrayList<>(); } @Override public void execute(FlatController flatController) { } @Override public boolean commandValid() { String fileName = getValue(); try (Scanner scanner = new Scanner(new FileReader(fileName))) { workingScripts.add("execute_script " + fileName); String input = ""; while (scanner.hasNext()) { input = scanner.nextLine(); if (input.contains("execute_script")) { if (workingScripts.contains(input)) { System.out.println(input.split(" ")[1] + " is already working. Command skipped.\n"); } else { Command command = new ExecuteScript(workingScripts); System.out.println(input.split(" ")[1]); command.setValue(input.split(" ")[1]); command.setUser(getUser()); command.commandValid(); } } else { commandData.setCommand(input); Command command = commandData.getCommand(); command.setUser(getUser()); command.commandValid(); command = Client.exchangeCommands(command); System.out.println(command.getMessage()); if (command.getMessage().contains("Logging out")) { System.exit(0); } } } } catch (IOException e) { System.out.println("File not found or access denied"); } catch (Exception e) { System.out.println("Invalid input in execute_script " + fileName); e.printStackTrace(); } System.out.println("script " + fileName + " finished working"); setMessage("script"); workingScripts.remove("execute_script " + fileName); CommandsHistory.addCommand("execute_script"); return true; } }
true
4bf50d00fa9483a47caeca6de8bfbe6030ecd5e0
Java
delta-G/DiscoReefCalc
/src/dosingcomputer/Preferences.java
UTF-8
6,622
2.578125
3
[]
no_license
/** Copyright (C) 2015 David Caldwell disco47dave at gmail dot com This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package dosingcomputer; import DosingComputerGUI.ErrorDialog; import DosingComputerGUI.StartupWizard; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Dave */ public class Preferences { public static final HashMap<String, String> prefMap = new HashMap<>(); static { prefMap.put("Home Directory", "./"); prefMap.put("Tanks Directory", "./"); prefMap.put("Alkalinity Units", "dKH"); prefMap.put("Salinity Units", "S.G."); prefMap.put("Months to Keep History", "6"); prefMap.put("Tank Volume Units", VolumeUnits.GALLON.toString()); prefMap.put("Dose Volume Units", VolumeUnits.MILLILITER.toString()); } public static String getPreference(String aPref) { String retval; if (prefMap.keySet().contains(aPref)) { retval = prefMap.get(aPref); } else { retval = "ERROR"; ErrorDialog.showErrorDialog("Found Bad Preference Key"); } return retval; } // returns the old value in case you want it public static String setPreference(String aPref , String aValue){ String retval; if (prefMap.keySet().contains(aPref)) { retval = prefMap.get(aPref); prefMap.put(aPref, aValue); } else { retval = "ERROR"; ErrorDialog.showErrorDialog("Found Bad Preference Key"); } return retval; } public static File getHomeDirectory() { return new File(prefMap.get("Home Directory")); } public static void setHomeDirectory(File file) { prefMap.put("Home Directory", file.getAbsolutePath()); } public static File getTankDirectory() { return new File(prefMap.get("Tanks Directory")); } public static void setTankDirectory(File file) { prefMap.put("Tanks Directory", file.getAbsolutePath()); } public static String getAlkUnit() { return prefMap.get("Alkalinity Units"); } public static void setAlkUnit(String ustr) { if (Arrays.asList(Parameter.ALKALINITY.getUnits()).contains(ustr)) { prefMap.put("Alkalinity Units", ustr); } else { ErrorDialog.showErrorDialog("Bad Alkalinity Unit" + ustr); } } public static String getSalinityUnit() { return prefMap.get("Salinity Units"); } public static void setSalinityUnit(String ustr) { if (Arrays.asList(Parameter.SALINITY.getUnits()).contains(ustr)) { prefMap.put("Salinity Units", ustr); } else { ErrorDialog.showErrorDialog("Bad Salinity Unit" + ustr); } } public static Integer getMonthsForHistory() { return Integer.parseInt(prefMap.get("Months to Keep History")); } public static void setMonthsForHistory(Integer mon) { prefMap.put("Tanks Directory", mon.toString()); } public static VolumeUnits getTankVolumeUnit() { return VolumeUnits.parseUnit(prefMap.get("Tank Volume Units")); } public static void setTankVolumeUnit(VolumeUnits vu) { prefMap.put("Tank Volume Units", vu.toString()); } public static VolumeUnits getDoseVolumeUnit() { return VolumeUnits.parseUnit(prefMap.get("Dose Volume Units")); } public static void setDoseVolumeUnit(VolumeUnits vu) { prefMap.put("Dose Volume Units", vu.toString()); } public static void savePreferences() { try (BufferedWriter outWriter = new BufferedWriter(new FileWriter("./preferences.txt"))) { for (String s : prefMap.keySet()) { outWriter.write("<" + s + ">" + prefMap.get(s) + "\n"); } } catch (IOException ex) { Logger.getLogger(Preferences.class.getName()).log(Level.SEVERE, null, ex); } } public static void loadPreferences() { File saveFile = new File("./preferences.txt"); if(!saveFile.exists()){ try { saveFile.createNewFile(); StartupWizard.runWizard(); } catch (IOException e) { ErrorDialog.showExceptionDialog(e); } } try (BufferedReader inReader = new BufferedReader(new FileReader(saveFile))) { String line = inReader.readLine(); while (line != null) { String key; String value; if (line.startsWith("<")) { int keyindex1 = line.indexOf("<") + 1; int keyindex2 = line.indexOf(">"); key = line.substring(keyindex1, keyindex2); value = line.substring(keyindex2 + 1); if (prefMap.keySet().contains(key)) { prefMap.put(key, value); } else { ErrorDialog.showErrorDialog("Found Bad Preference Key"); } } line = inReader.readLine(); } } catch (FileNotFoundException ex){ generateDefaultPrefFile(); } catch (IOException ex) { Logger.getLogger(Preferences.class.getName()).log(Level.SEVERE, null, ex); } } private static void generateDefaultPrefFile(){ try { File file = new File("./preferences.txt"); file.createNewFile(); savePreferences(); } catch (IOException ex) { System.out.println("Error generating default pref file!"); Logger.getLogger(Preferences.class.getName()).log(Level.SEVERE, null, ex); } } }
true
df28520ce264afe17e0c1e65e59f1e6907e44b67
Java
Sophia-Okito/GAD-Project
/AndroidStudioProjects/MyGadsProject/app/src/main/java/com/funcrib/gadsapp/view/fragment/SubmitResultDialogFragment.java
UTF-8
1,919
2.234375
2
[ "Apache-2.0" ]
permissive
package com.funcrib.gadsapp.view.fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.DialogFragment; import com.funcrib.gadsapp.R; public class SubmitResultDialogFragment extends DialogFragment { private boolean success; public SubmitResultDialogFragment() { } public static SubmitResultDialogFragment newInstance() { SubmitResultDialogFragment dialog = new SubmitResultDialogFragment(); return dialog; } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { TextView view = (TextView) inflater.inflate(R.layout.dialog_submit_result, container, false); if (success) { view.setText(R.string.submission_successful); view.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_check_circle, 0, 0); } else { view.setText(R.string.submission_not_successful); view.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_error, 0, 0); } return view; } public boolean getSuccess() { return success; } public void setSuccess(boolean success) { this.success = success; TextView view = (TextView) getView(); if (view != null) { if (success) { view.setText(R.string.submission_successful); view.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_check_circle, 0, 0); } else { view.setText(R.string.submission_not_successful); view.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_error, 0, 0); } } } }
true
7604ca60c97170d28306ee44fee2eb02556590a3
Java
YobertyAlej/Code4Venezuela
/TwitterHelpHackaton/app/src/main/java/hackaton/com/twitterhelphackaton/interfaces/HTTPResponse.java
UTF-8
544
2.40625
2
[ "MIT" ]
permissive
package hackaton.com.twitterhelphackaton.interfaces; import android.util.Log; public abstract class HTTPResponse { private static boolean debug = true; public void onSuccess(String data){}; public void onForbidden(String data){ if(debug) Log.e("HTTPResponse", "FORBIDDEN"); } public void onException(Exception e){ if(debug) Log.e("HTTPResponse", String.valueOf(e)); } public void onError(String data){ if(debug) Log.e("HTTPResponse",data); } }
true
818170fb46fbf9a4df585ff9ecc9340165d8ac79
Java
MarkSmirnov13/MusicCatalog
/src/main/java/services/CollectionService.java
UTF-8
1,015
2.40625
2
[ "MIT" ]
permissive
package services; import dao.Impl.CollectionDAOImpl; import models.Collection; import java.sql.SQLException; import java.util.List; public class CollectionService { CollectionDAOImpl collectionDAOImpl = new CollectionDAOImpl(); public void saveCollection(Collection collection) { collectionDAOImpl.save(collection); } public void updateCollection(Collection collection) { collectionDAOImpl.update(collection); } public void deleteCollection(Collection collection) { collectionDAOImpl.delete(collection); } public void deleteAllCollections(List<Collection> collections) { collectionDAOImpl.deleteAll(collections); } public List<Collection> findAllCollections() { return collectionDAOImpl.findAll(); } public Collection findCollectionById(int id) { return collectionDAOImpl.findById(id); } public Collection findCollectionByName(String name) { return collectionDAOImpl.findByName(name); } }
true
a83de72cf8cfb831d69d0b2957402bd3e8eacbe0
Java
Simon199201/SSMTest
/src/main/java/com/itheima/domain/User.java
UTF-8
1,543
2.3125
2
[]
no_license
package com.itheima.domain; import com.fasterxml.jackson.annotation.JsonFormat; import org.springframework.format.annotation.DateTimeFormat; import java.util.Date; import java.util.List; public class User { private int id; private String username; private String password; @DateTimeFormat(pattern="yyyy-MM-dd") @JsonFormat(pattern="yyyy-MM-dd",timezone = "GMT+8") private String birthday; private List<Account> accountList; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } public List<Account> getAccountList() { return accountList; } public void setAccountList(List<Account> accountList) { this.accountList = accountList; } @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", password='" + password + '\'' + ", birthday=" + birthday + ", accountList=" + accountList + '}'; } }
true
6566e4e25913bb90d0c555878807942280e17746
Java
hater4u/StackCalculator
/src/main/java/OperationFactory.java
UTF-8
1,350
2.5625
3
[]
no_license
import java.io.IOException; import java.io.InputStream; import java.util.Properties; import java.util.logging.Logger; import Exception.*; import static java.util.logging.Logger.getLogger; public class OperationFactory { private volatile static OperationFactory instance; private Properties properties = new Properties(); static Logger logger = getLogger("Logger"); private OperationFactory() throws IOException{ logger.info("Start create OperationFactory"); InputStream conf = getClass().getResourceAsStream("config.properties"); properties.load(conf); conf.close(); logger.info("Successful create"); } public static OperationFactory getInstance() throws IOException { if (instance == null) synchronized (OperationFactory.class) { if (instance == null) { instance = new OperationFactory(); } } return instance; } IOperation createOperation(String operationName) throws FactoryException { IOperation operation; try { operation = (IOperation) Class.forName(properties.getProperty(operationName)).getDeclaredConstructor().newInstance(); } catch (Exception e) { throw new FactoryException(); } return operation; } }
true
f81f16aa04919fb3b9e24cd7ad24ecb7a2179664
Java
yingcanxia/RPC
/rpc-client/src/main/java/cn/shadow/discovery/ServiceDiscoveryWithZK.java
UTF-8
2,120
2.546875
3
[]
no_license
package cn.shadow.discovery; import java.util.ArrayList; import java.util.List; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.recipes.cache.PathChildrenCache; import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener; import org.apache.curator.retry.ExponentialBackoffRetry; public class ServiceDiscoveryWithZK implements IServiceDiscovery{ List<String>serviceRepos=new ArrayList<String>(); CuratorFramework curatorFramework=null; { curatorFramework=CuratorFrameworkFactory.builder() .connectString(ZKConfig.CONNECT_STRING) .sessionTimeoutMs(5000) .retryPolicy(new ExponentialBackoffRetry(1000, 3)).build();//衰减式的重试 curatorFramework.start(); } /** * 实现服务的获取与查找 * 需要设置监听 * 需要做服务地址的本地缓存 */ @Override public String discovery(String serviceName) { //完成了服务地址的查找(服务地址被删除) String path="/"+serviceName; try { serviceRepos=curatorFramework.getChildren().forPath(path); registryWatch(path); //完成了服务地址的查找 //服务地址发生变化针对已有的地址进行负载均衡 } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } LoadBalanceStrategy loadBalanceStrategy=new RandomLoadBalance(); return loadBalanceStrategy.selectHost(serviceRepos); } private void registryWatch(final String path) throws Exception { PathChildrenCache nodeCache=new PathChildrenCache(curatorFramework, "/data",true); PathChildrenCacheListener nodeListener=(curatorFramework1,pathChildrenCacheEvent)->{ //拉姆达表达式:NodeCacheListener是一个接口new一个接口需要自己实现他的方法不是应表达式的方法如下 serviceRepos=curatorFramework1.getChildren().forPath(path);//再次更新本地缓存地址 }; nodeCache.getListenable().addListener(nodeListener); nodeCache.start(PathChildrenCache.StartMode.NORMAL); } }
true
503aca79ed6e3df6e63324b4cae20bb6261e715e
Java
fighting-one-piece/j2ee-integration
/integration-core/src/main/java/org/platform/modules/abstr/web/utils/JsonReturnHandler.java
UTF-8
2,015
2.515625
3
[]
no_license
package org.platform.modules.abstr.web.utils; import java.lang.annotation.Annotation; import javax.servlet.http.HttpServletResponse; import org.platform.utils.json.CustomerJsonSerializer; import org.platform.utils.json.JSON; import org.springframework.core.MethodParameter; import org.springframework.http.MediaType; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.method.support.HandlerMethodReturnValueHandler; import org.springframework.web.method.support.ModelAndViewContainer; public class JsonReturnHandler implements HandlerMethodReturnValueHandler{ @Override public boolean supportsReturnType(MethodParameter returnType) { // 如果有我们自定义的 JSON 注解 就用我们这个Handler 来处理 boolean hasJsonAnno= returnType.getMethodAnnotation(JSON.class) != null; return hasJsonAnno; } @Override public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception { // 设置这个就是最终的处理类了,处理完不再去找下一个类进行处理 mavContainer.setRequestHandled(true); // 获得注解并执行filter方法 最后返回 HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class); Annotation[] annotations = returnType.getMethodAnnotations(); CustomerJsonSerializer jsonSerializer = new CustomerJsonSerializer(); for (int i = 0, len = annotations.length; i < len; i++) { Annotation annotation = annotations[i]; if (annotation instanceof JSON) { JSON json = (JSON) annotation; jsonSerializer.filter(json.type(), json.include(), json.filter()); } } response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE); String json = jsonSerializer.toJson(returnValue); response.getWriter().write(json); } }
true
f524aea1808646f4d7a2d90ee1f982a3068cae3d
Java
zanguixuan/MiaoHi
/app/src/main/java/com/haiqiu/miaohi/response/VideoAndImgResponse.java
UTF-8
343
1.835938
2
[]
no_license
package com.haiqiu.miaohi.response; import com.haiqiu.miaohi.bean.ImgDetail; /** * Created by ningl on 16/12/17. */ public class VideoAndImgResponse extends BaseResponse { private ImgDetail data; public ImgDetail getData() { return data; } public void setData(ImgDetail data) { this.data = data; } }
true
017f766709215e05d5d6290e4ed08b0faa9f9c27
Java
AdrianDau/Proyecto
/src/es/adrian/models/Producto.java
UTF-8
929
2.609375
3
[]
no_license
package es.adrian.models; public class Producto { private String nombreProducto; private double precio; private Categoria categoria; public Producto(String nombreProducto, double precio, Categoria categoria) { this.nombreProducto = nombreProducto; this.precio = precio; this.categoria = categoria; } public String getNombreProducto() { return nombreProducto; } public void setNombreProducto(String nombreProducto) { this.nombreProducto = nombreProducto; } public double getPrecio() { return precio; } public void setPrecio(double precio) { this.precio = precio; } public Categoria getCategoria() { return categoria; } public void setCategoria(Categoria categoria) { this.categoria = categoria; } @Override public String toString() { return nombreProducto; } }
true
dbf9afdc5ac8ac512d4b95cd82db9797bae18578
Java
JNM-2T17/SystemScape_CODE
/src/model/Project.java
UTF-8
1,218
3.328125
3
[]
no_license
package model; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; public class Project { private String name; private Date startDate; private Date endDate; private ArrayList<Employee> employees; public Project(String name, Date startDate, Date endDate){ setName(name); setStartDate(startDate); setEndDate(endDate); employees = new ArrayList<Employee>(); } public Project(){ setName(""); setStartDate(null); setEndDate(null); employees = new ArrayList<Employee>(); } public void setName(String name){ this.name = name; } public String getName(){ return name; } public void setStartDate(Date startDate){ this.startDate = startDate; } public Date getStartDate(){ return startDate; } public void setEndDate(Date endDate){ this.endDate = endDate; } public Date getEndDate(){ return endDate; } public String toString(){ return name; } public void addEmployee(Employee emp){ employees.add(emp); } public Iterator getEmployeeList(){ return employees.iterator(); } public void setEmployeeList(Iterator employee) { while(employee.hasNext()){ this.employees.add(((Employee)employee.next())); } } }
true
7659b391085f1ab5fc22b1e532248cc54efd3132
Java
liuzhengnan666/LLC_P
/app/src/main/java/com/example/administrator/llc_p/fragment/HelpFragment.java
UTF-8
6,158
1.875
2
[]
no_license
package com.example.administrator.llc_p.fragment; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.example.administrator.llc_p.R; import org.w3c.dom.Text; public class HelpFragment extends Fragment implements View.OnClickListener { private RelativeLayout about_freeze; private RelativeLayout about_mill; private RelativeLayout about_ncoordinate; private RelativeLayout about_production; private TextView explain_freeze; private TextView explain_mill; private TextView explain_ncoordinate; private TextView explain_production; private TextView connection_us; private Boolean isFreeze = false; private Boolean isMill = false; private Boolean isNcoordinate = false; private Boolean isProduction =false; private TextView tab_freeze; private TextView tab_mill; private TextView tab_production; private TextView tab_ncoordinate; private Dialog dialog; public HelpFragment() { } public static HelpFragment newInstance() { HelpFragment fragment = new HelpFragment(); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View help_view = inflater.inflate(R.layout.fragment_help, container, false); about_freeze = help_view.findViewById(R.id.about_freeze); about_mill = help_view.findViewById(R.id.about_mill); about_ncoordinate = help_view.findViewById(R.id.about_ncoordinate); about_production = help_view.findViewById(R.id.about_production); explain_freeze = help_view.findViewById(R.id.explain_freeze); explain_mill = help_view.findViewById(R.id.explain_mill); explain_ncoordinate = help_view.findViewById(R.id.explain_ncoordinate); explain_production = help_view.findViewById(R.id.explain_production); connection_us = help_view.findViewById(R.id.connection_us); tab_freeze = help_view.findViewById(R.id.tab_freeze); tab_mill = help_view.findViewById(R.id.tab_mill); tab_ncoordinate = help_view.findViewById(R.id.tab_ncoordinate); tab_production = help_view.findViewById(R.id.tab_production); about_freeze.setOnClickListener(this); about_mill.setOnClickListener(this); about_ncoordinate.setOnClickListener(this); about_production.setOnClickListener(this); connection_us.setOnClickListener(this); return help_view; } public void showDialog(){ ButtonDialogFragment buttonDialogFragment = new ButtonDialogFragment(); buttonDialogFragment.show("官方QQ:", "2666632957", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }, getFragmentManager()); } public void showDialog2(){ dialog = new Dialog(getActivity()); LayoutInflater inflater = LayoutInflater.from(getActivity()); View viewDialog = inflater.inflate(R.layout.dialog_qq, null); dialog.setContentView(viewDialog); dialog.show(); TextView ok = viewDialog.findViewById(R.id.ok); ok.setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()){ case R.id.about_freeze: if (isFreeze){ explain_freeze.setVisibility(View.GONE); tab_freeze.setBackgroundResource(R.mipmap.up); isFreeze = !isFreeze; }else { explain_freeze.setVisibility(View.VISIBLE); tab_freeze.setBackgroundResource(R.mipmap.down); isFreeze = !isFreeze; } break; case R.id.about_mill: if (isMill){ explain_mill.setVisibility(View.GONE); tab_mill.setBackgroundResource(R.mipmap.up); isMill = !isMill; }else { explain_mill.setVisibility(View.VISIBLE); tab_mill.setBackgroundResource(R.mipmap.down); isMill = !isMill; } break; case R.id.about_ncoordinate: if (isNcoordinate){ explain_ncoordinate.setVisibility(View.GONE); tab_ncoordinate.setBackgroundResource(R.mipmap.up); isNcoordinate = !isNcoordinate; }else { explain_ncoordinate.setVisibility(View.VISIBLE); tab_ncoordinate.setBackgroundResource(R.mipmap.down); isNcoordinate = !isNcoordinate; } break; case R.id.about_production: if (isProduction){ explain_production.setVisibility(View.GONE); tab_production.setBackgroundResource(R.mipmap.up); isProduction = !isProduction; }else { explain_production.setVisibility(View.VISIBLE); tab_production.setBackgroundResource(R.mipmap.down); isProduction = !isProduction; } break; case R.id.connection_us: // showDialog(); showDialog2(); break; case R.id.ok: dialog.dismiss(); break; } } }
true
e0bceb92ebac695004837f7e354a9abb36b3c230
Java
junbokim/VendingMachine
/src/test/java/R16A_Group_6_A2/ShoppingCartTest.java
UTF-8
3,035
3.015625
3
[]
no_license
package R16A_Group_6_A2; import java.util.HashMap; import java.util.List; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; public class ShoppingCartTest { private ShoppingCart cart; private ItemData itemData; public ShoppingCartTest() { this.itemData = new ItemData(false); this.cart = new ShoppingCart(this.itemData); this.cart.addItem("Coca cola", 4); this.cart.addItem("Bounty", 3); } @Test public void testConstruction() { assertNotNull(this.cart); } @Test public void testGetItems() { HashMap<Item, Integer> items = new HashMap<>(); assertEquals(0, items.size()); items = this.cart.getItems(); assertEquals(2, items.size()); assertEquals(11,cart.getPrice()); } @Test public void testGetNames() { List<String> names = this.cart.getNames(); assertTrue(names.contains("Coca cola")); assertTrue(names.contains("Bounty")); } @Test public void testGetQuantity() { assertEquals(4, this.cart.getQuantity("Coca cola")); assertEquals(3, this.cart.getQuantity("Bounty")); } @Test public void testGetEmptyCartQuantity() { ShoppingCart emptyCart = new ShoppingCart(this.itemData); assertEquals(0, emptyCart.getQuantity("Coca cola")); } @Test public void testUpdateQuantity() { assertEquals(4, this.cart.getQuantity("Coca cola")); this.cart.updateQuantity("Coca cola", 1); assertEquals(5, this.cart.getQuantity("Coca cola")); } @Test public void testLargeUpdateQuantity() { assertEquals(3, this.cart.getQuantity("Bounty")); this.cart.updateQuantity("Bounty", 20); assertEquals(7, this.cart.getQuantity("Bounty")); } @Test public void testAddItem() { assertEquals(2, this.cart.getItems().size()); this.cart.addItem("Sour Patch", 4); assertEquals(3, this.cart.getItems().size()); assertEquals(4, this.cart.getQuantity("Sour Patch")); this.cart.addItem("Sour Patch", 1); assertEquals(5, this.cart.getQuantity("Sour Patch")); } @Test public void testAddItemLargeQuantity() { assertEquals(2, this.cart.getItems().size()); this.cart.addItem("Sour Patch", 100); assertEquals(3, this.cart.getItems().size()); assertEquals(7, this.cart.getQuantity("Sour Patch")); } @Test public void testRemoveItem() { assertEquals(2, this.cart.getItems().size()); this.cart.removeItem("Bounty"); assertEquals(1, this.cart.getItems().size()); List<String> itemList = this.cart.getNames(); assert itemList.contains("Coca cola"); assertFalse(itemList.contains("Bounty")); } }
true
f6d3f349696135e6f6210ff2c30b24f6ebbc7ece
Java
broding/director
/src/nl/basroding/director/controllers/Controller.java
UTF-8
1,234
2.390625
2
[]
no_license
package nl.basroding.director.controllers; import nl.basroding.director.Director; import nl.basroding.director.models.ModelCollection; import nl.basroding.director.views.ContentView; import nl.basroding.director.views.SideMenuView; import nl.basroding.director.views.TopbarView; import nl.basroding.director.views.View; /** * * @author basroding */ public class Controller { private Director director; private ModelCollection modelCollection; private View view; public Controller() { } final public void setup(Director director, ModelCollection modelCollection) { this.director = director; this.modelCollection = modelCollection; } public void index() { } final protected void setController(Controller controller) { director.setController(controller); } final protected void setView(ContentView newView) { if(this.view != null) this.view.clear(); this.view = newView; this.view.setX(SideMenuView.WIDTH); this.director.setupView(newView); } final protected ModelCollection getModelCollection() { return this.modelCollection; } final public View getView() { return view; } }
true
a81bc9e7a7adbe60d048151be300420b16a9cdf2
Java
mdalmamuncse/CardView
/app/src/main/java/com/example/cardview/MainActivity.java
UTF-8
1,716
2.40625
2
[]
no_license
package com.example.cardview; import androidx.appcompat.app.AppCompatActivity; import androidx.cardview.widget.CardView; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Toast; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private CardView schoolcardView,resturantcardView,hospitalcardView,airportcardView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); schoolcardView = findViewById(R.id.schoolCardId); resturantcardView = findViewById(R.id.restaurantsCardId); hospitalcardView = findViewById(R.id.hospitalCardId); airportcardView = findViewById(R.id.airportCardId); schoolcardView.setOnClickListener(this); resturantcardView.setOnClickListener(this); hospitalcardView.setOnClickListener(this); airportcardView.setOnClickListener(this); } @Override public void onClick(View v) { if (v.getId() == R.id.schoolCardId){ //Toast.makeText(this, "School", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(MainActivity.this,SchoolActivity.class); startActivity(intent); }else if (v.getId() == R.id.restaurantsCardId){ Toast.makeText(this, "Restaurant", Toast.LENGTH_SHORT).show(); }else if (v.getId() == R.id.hospitalCardId){ Toast.makeText(this, "Hospital", Toast.LENGTH_SHORT).show(); }else if (v.getId() == R.id.airportCardId){ Toast.makeText(this, "Airport", Toast.LENGTH_SHORT).show(); } } }
true