blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 410 | content_id stringlengths 40 40 | detected_licenses listlengths 0 51 | license_type stringclasses 2 values | repo_name stringlengths 5 132 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 80 | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 5.85k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 131 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 3 9.45M | extension stringclasses 32 values | content stringlengths 3 9.45M | authors listlengths 1 1 | author_id stringlengths 0 313 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b850e353d32797855044ef3e83b3360fa4c34e53 | 84c471dcc39f6cefc1b9535c892101efce836655 | /projetar-web/src/main/java/br/gov/mg/fazenda/projetar/spring/security/SpringBeanIntegrator.java | 3fcc4e7fe991c4213f89e166d4c24da20865fb04 | [] | no_license | leoluzh/projetar | fd3818aee81115aeedcb58aaf6f9d4abb21cdd40 | 4d0a7ac89cba1f28657754c26ef2ad6730e31612 | refs/heads/master | 2020-05-29T15:06:23.248537 | 2016-07-11T02:16:33 | 2016-07-11T02:16:33 | 57,864,945 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 789 | java | package br.gov.mg.fazenda.projetar.spring.security;
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
//import javax.enterprise.inject.Produces;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
@ApplicationScoped
@SuppressWarnings("serial")
public class SpringBeanIntegrator implements Serializable {
private AnnotationConfigApplicationContext context;
public SpringBeanIntegrator(){
}
@PostConstruct
private void init(){
//this.context = new AnnotationConfigApplicationContext();
//this.context.register( SpringBeanIntegrator.class );
//this.context.refresh();
}
//@Produces
//public Xtpo produceXpto(){
// return this.context.getBean(Xpto.class);
//}
}
| [
"leonardo.l.fernandes@gmail.com"
] | leonardo.l.fernandes@gmail.com |
454fdc2f268a03dd7cb861905f961b4234f8cd7c | e5bf88815d214aa8170c9175c7b3e595bc1d48b9 | /src/main/java/com/exercise/services/DescendingOrderNumberGenerator.java | b464ae6542ffe5243e75fff864c6340b1611d7df | [] | no_license | kunsingh/number-generator | d6aaeba2d859f4482dc045263f0a87fd389e0482 | 637fbab943db39a06eacd28792112cad90af2888 | refs/heads/master | 2022-08-16T14:37:07.397498 | 2020-05-22T06:45:53 | 2020-05-22T06:45:53 | 266,028,274 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,782 | java | package com.exercise.services;
import com.exercise.exceptions.TaskNotFoundException;
import com.exercise.models.GenerateCriteria;
import com.exercise.task.GenerateTask;
import com.exercise.utils.Assert;
import com.exercise.utils.Constants;
import com.exercise.utils.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
@Component("descendingOrderNumberGenerator")
public class DescendingOrderNumberGenerator implements NumberGenerator {
private static final Logger LOGGER = LoggerFactory.getLogger(DescendingOrderNumberGenerator.class);
final private Map<String, Future<String>> futureByTaskId = new ConcurrentHashMap<>();
private ExecutorService executor;
@Value("${fileLocation}")
private String fileLocation;
@Value("${noOfThread}")
private int noOfThread;
@PostConstruct
public void init(){
executor = Executors.newFixedThreadPool(noOfThread);
if(!fileLocation.endsWith("/")){
fileLocation = fileLocation + "/";
}
}
@Override
public String generateNumber(final GenerateCriteria criteria) {
Assert.requireNonNull(criteria, "GenerateCriteria");
Assert.requirePositiveInteger(criteria.getGoal(), "goal");
Assert.requirePositiveInteger(criteria.getStep(), "step");
Assert.goalShouldBeGreaterThanStep(criteria.getGoal(), criteria.getStep());
LOGGER.info("File location is set to {}", fileLocation);
final String taskId = UUID.randomUUID().toString();
final GenerateTask generateTask = new GenerateTask(taskId, criteria, fileLocation);
LOGGER.info("Created a task to generate numbers with goal:{} and step:{}", criteria.getGoal(), criteria.getStep());
final Future<String> future = executor.submit(generateTask);
futureByTaskId.putIfAbsent(taskId, future);
return taskId;
}
@Override
public String getStatusForTask(final String taskId) throws TaskNotFoundException {
Assert.requireNonNull(taskId, "taskId");
if(FileUtil.isExist(fileLocation + taskId + "_output.txt")){
futureByTaskId.remove(taskId);
return Constants.SUCCESS;
}
synchronized (taskId.intern()) {
if (futureByTaskId.containsKey(taskId)) {
final Future<String> future = futureByTaskId.get(taskId);
if (future.isDone()) {
try {
future.get();
futureByTaskId.remove(taskId);
return Constants.SUCCESS;
} catch (final InterruptedException | ExecutionException ex) {
LOGGER.error("Exception occurred while generating numbers for taskId:{} Exception is: {}", taskId, ex.getMessage());
return Constants.ERROR;
}
} else {
return Constants.IN_PROGRESS;
}
}
}
LOGGER.error("No task submitted with taskId:{}", taskId);
throw new TaskNotFoundException("No task submitted with id: "+taskId);
}
@Override
public String getNumberList(final String taskId) throws IOException {
Assert.requireNonNull(taskId, "taskId");
return FileUtil.readFromFile(fileLocation + taskId + "_output.txt");
}
}
| [
"kunal.s.rathor@gmail.com"
] | kunal.s.rathor@gmail.com |
797e1079e99888408c3eb185d8c4887c51af382f | ed7fc9edbc69374cd91f431203c9b2ae57ba86af | /src/main/java/com/example/hotel/util/SensUtils.java | c7b1bc90ea804d9f9074c3a3b10d3a62c7ada505 | [] | no_license | wangtaobo0810/Hotel | b623cd31fac61cfe7284c4ed516c29d39efe528d | 0bbe1ba652f54764b72a109743a2f924f06c29d1 | refs/heads/master | 2023-08-24T11:45:35.265955 | 2021-10-13T12:42:15 | 2021-10-13T12:42:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,232 | java | package com.example.hotel.util;
import io.github.biezhi.ome.OhMyEmail;
import lombok.extern.slf4j.Slf4j;
import java.util.*;
/**
* <pre>
* 常用工具
* </pre>
*/
@Slf4j
public class SensUtils {
/**
* 配置邮件
*
* @param smtpHost smtpHost
* @param userName 邮件地址
* @param password password
*/
public static void configMail(String smtpHost, String userName, String password) {
Properties properties = OhMyEmail.defaultConfig(false);
properties.setProperty("mail.smtp.host", smtpHost);
OhMyEmail.config(properties, userName, password);
}
public static String listToStr(List<String> list) {
StringBuilder stringBuilder = new StringBuilder();
for (String str : list) {
stringBuilder.append(str).append(",");
}
String temp = stringBuilder.toString();
if (temp.length() > 0) {
return temp.substring(0, temp.length() - 1);
}
return temp;
}
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("11");
list.add("22");
list.add("13");
System.out.println(listToStr(list));
}
}
| [
"847064370@qq.com"
] | 847064370@qq.com |
dcd5fbac63fcf07b78847fb722e9e223e029299a | d3614aa7d7236df7d480951f8d1f77e3f0d2c0d0 | /src/test/java/com/example/springboot/AQSExample.java | 542c0be08eeeda070216899bb12385c698a3ef75 | [] | no_license | luhggit/selfsys | fd8d6359179571aa81fb8e5839daa4f66d201bc4 | d61bb603b9757e79612ce1a0ff8b3fb255713f35 | refs/heads/master | 2020-04-28T07:43:21.024218 | 2019-04-24T02:54:10 | 2019-04-24T02:54:10 | 175,101,370 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 159 | java | package com.example.springboot;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
public class AQSExample extends AbstractQueuedSynchronizer {
}
| [
"luhggit@github.com"
] | luhggit@github.com |
72dbd4cff176a7595cbcc2cd04e7c57142a6dc1f | 5598faaaaa6b3d1d8502cbdaca903f9037d99600 | /code_changes/Apache_projects/HDFS-6825/9b38a6ab2330117ab36862be6c2c26a716120893/~TestPipelinesFailover.java | 8274781cfcb9011a9923a346e781964f03bd7581 | [] | no_license | SPEAR-SE/LogInBugReportsEmpirical_Data | 94d1178346b4624ebe90cf515702fac86f8e2672 | ab9603c66899b48b0b86bdf63ae7f7a604212b29 | refs/heads/master | 2022-12-18T02:07:18.084659 | 2020-09-09T16:49:34 | 2020-09-09T16:49:34 | 286,338,252 | 0 | 2 | null | null | null | null | UTF-8 | Java | false | false | 21,837 | java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.server.namenode.ha;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.security.PrivilegedExceptionAction;
import java.util.concurrent.TimeoutException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.impl.Log4JLogger;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.AppendTestUtil;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.hdfs.DFSTestUtil;
import org.apache.hadoop.hdfs.DistributedFileSystem;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.hdfs.MiniDFSNNTopology;
import org.apache.hadoop.hdfs.protocol.DatanodeID;
import org.apache.hadoop.hdfs.protocol.ExtendedBlock;
import org.apache.hadoop.hdfs.protocolPB.DatanodeProtocolClientSideTranslatorPB;
import org.apache.hadoop.hdfs.server.blockmanagement.BlockInfo;
import org.apache.hadoop.hdfs.server.blockmanagement.BlockInfoUnderConstruction;
import org.apache.hadoop.hdfs.server.blockmanagement.BlockManager;
import org.apache.hadoop.hdfs.server.blockmanagement.BlockManagerTestUtil;
import org.apache.hadoop.hdfs.server.blockmanagement.DatanodeDescriptor;
import org.apache.hadoop.hdfs.server.blockmanagement.DatanodeStorageInfo;
import org.apache.hadoop.hdfs.server.datanode.DataNode;
import org.apache.hadoop.hdfs.server.datanode.DataNodeTestUtils;
import org.apache.hadoop.hdfs.server.namenode.FSNamesystem;
import org.apache.hadoop.hdfs.server.namenode.NameNode;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.test.GenericTestUtils;
import org.apache.hadoop.test.GenericTestUtils.DelayAnswer;
import org.apache.hadoop.test.MultithreadedTestUtil.RepeatingTestThread;
import org.apache.hadoop.test.MultithreadedTestUtil.TestContext;
import org.apache.log4j.Level;
import org.junit.Test;
import org.mockito.Mockito;
import com.google.common.base.Supplier;
/**
* Test cases regarding pipeline recovery during NN failover.
*/
public class TestPipelinesFailover {
static {
((Log4JLogger)LogFactory.getLog(FSNamesystem.class)).getLogger().setLevel(Level.ALL);
((Log4JLogger)LogFactory.getLog(BlockManager.class)).getLogger().setLevel(Level.ALL);
((Log4JLogger)LogFactory.getLog(
"org.apache.hadoop.io.retry.RetryInvocationHandler")).getLogger().setLevel(Level.ALL);
((Log4JLogger)NameNode.stateChangeLog).getLogger().setLevel(Level.ALL);
}
protected static final Log LOG = LogFactory.getLog(
TestPipelinesFailover.class);
private static final Path TEST_PATH =
new Path("/test-file");
private static final int BLOCK_SIZE = 4096;
private static final int BLOCK_AND_A_HALF = BLOCK_SIZE * 3 / 2;
private static final int STRESS_NUM_THREADS = 25;
private static final int STRESS_RUNTIME = 40000;
enum TestScenario {
GRACEFUL_FAILOVER {
@Override
void run(MiniDFSCluster cluster) throws IOException {
cluster.transitionToStandby(0);
cluster.transitionToActive(1);
}
},
ORIGINAL_ACTIVE_CRASHED {
@Override
void run(MiniDFSCluster cluster) throws IOException {
cluster.restartNameNode(0);
cluster.transitionToActive(1);
}
};
abstract void run(MiniDFSCluster cluster) throws IOException;
}
enum MethodToTestIdempotence {
ALLOCATE_BLOCK,
COMPLETE_FILE;
}
/**
* Tests continuing a write pipeline over a failover.
*/
@Test(timeout=30000)
public void testWriteOverGracefulFailover() throws Exception {
doWriteOverFailoverTest(TestScenario.GRACEFUL_FAILOVER,
MethodToTestIdempotence.ALLOCATE_BLOCK);
}
@Test(timeout=30000)
public void testAllocateBlockAfterCrashFailover() throws Exception {
doWriteOverFailoverTest(TestScenario.ORIGINAL_ACTIVE_CRASHED,
MethodToTestIdempotence.ALLOCATE_BLOCK);
}
@Test(timeout=30000)
public void testCompleteFileAfterCrashFailover() throws Exception {
doWriteOverFailoverTest(TestScenario.ORIGINAL_ACTIVE_CRASHED,
MethodToTestIdempotence.COMPLETE_FILE);
}
private void doWriteOverFailoverTest(TestScenario scenario,
MethodToTestIdempotence methodToTest) throws Exception {
Configuration conf = new Configuration();
conf.setInt(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, BLOCK_SIZE);
// Don't check replication periodically.
conf.setInt(DFSConfigKeys.DFS_NAMENODE_REPLICATION_INTERVAL_KEY, 1000);
FSDataOutputStream stm = null;
MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf)
.nnTopology(MiniDFSNNTopology.simpleHATopology())
.numDataNodes(3)
.build();
try {
int sizeWritten = 0;
cluster.waitActive();
cluster.transitionToActive(0);
Thread.sleep(500);
LOG.info("Starting with NN 0 active");
FileSystem fs = HATestUtil.configureFailoverFs(cluster, conf);
stm = fs.create(TEST_PATH);
// write a block and a half
AppendTestUtil.write(stm, 0, BLOCK_AND_A_HALF);
sizeWritten += BLOCK_AND_A_HALF;
// Make sure all of the blocks are written out before failover.
stm.hflush();
LOG.info("Failing over to NN 1");
scenario.run(cluster);
// NOTE: explicitly do *not* make any further metadata calls
// to the NN here. The next IPC call should be to allocate the next
// block. Any other call would notice the failover and not test
// idempotence of the operation (HDFS-3031)
FSNamesystem ns1 = cluster.getNameNode(1).getNamesystem();
BlockManagerTestUtil.updateState(ns1.getBlockManager());
assertEquals(0, ns1.getPendingReplicationBlocks());
assertEquals(0, ns1.getCorruptReplicaBlocks());
assertEquals(0, ns1.getMissingBlocksCount());
// If we're testing allocateBlock()'s idempotence, write another
// block and a half, so we have to allocate a new block.
// Otherise, don't write anything, so our next RPC will be
// completeFile() if we're testing idempotence of that operation.
if (methodToTest == MethodToTestIdempotence.ALLOCATE_BLOCK) {
// write another block and a half
AppendTestUtil.write(stm, sizeWritten, BLOCK_AND_A_HALF);
sizeWritten += BLOCK_AND_A_HALF;
}
stm.close();
stm = null;
AppendTestUtil.check(fs, TEST_PATH, sizeWritten);
} finally {
IOUtils.closeStream(stm);
cluster.shutdown();
}
}
/**
* Tests continuing a write pipeline over a failover when a DN fails
* after the failover - ensures that updating the pipeline succeeds
* even when the pipeline was constructed on a different NN.
*/
@Test(timeout=30000)
public void testWriteOverGracefulFailoverWithDnFail() throws Exception {
doTestWriteOverFailoverWithDnFail(TestScenario.GRACEFUL_FAILOVER);
}
@Test(timeout=30000)
public void testWriteOverCrashFailoverWithDnFail() throws Exception {
doTestWriteOverFailoverWithDnFail(TestScenario.ORIGINAL_ACTIVE_CRASHED);
}
private void doTestWriteOverFailoverWithDnFail(TestScenario scenario)
throws Exception {
Configuration conf = new Configuration();
conf.setInt(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, BLOCK_SIZE);
FSDataOutputStream stm = null;
MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf)
.nnTopology(MiniDFSNNTopology.simpleHATopology())
.numDataNodes(5)
.build();
try {
cluster.waitActive();
cluster.transitionToActive(0);
Thread.sleep(500);
LOG.info("Starting with NN 0 active");
FileSystem fs = HATestUtil.configureFailoverFs(cluster, conf);
stm = fs.create(TEST_PATH);
// write a block and a half
AppendTestUtil.write(stm, 0, BLOCK_AND_A_HALF);
// Make sure all the blocks are written before failover
stm.hflush();
LOG.info("Failing over to NN 1");
scenario.run(cluster);
assertTrue(fs.exists(TEST_PATH));
cluster.stopDataNode(0);
// write another block and a half
AppendTestUtil.write(stm, BLOCK_AND_A_HALF, BLOCK_AND_A_HALF);
stm.hflush();
LOG.info("Failing back to NN 0");
cluster.transitionToStandby(1);
cluster.transitionToActive(0);
cluster.stopDataNode(1);
AppendTestUtil.write(stm, BLOCK_AND_A_HALF*2, BLOCK_AND_A_HALF);
stm.hflush();
stm.close();
stm = null;
AppendTestUtil.check(fs, TEST_PATH, BLOCK_AND_A_HALF * 3);
} finally {
IOUtils.closeStream(stm);
cluster.shutdown();
}
}
/**
* Tests lease recovery if a client crashes. This approximates the
* use case of HBase WALs being recovered after a NN failover.
*/
@Test(timeout=30000)
public void testLeaseRecoveryAfterFailover() throws Exception {
final Configuration conf = new Configuration();
// Disable permissions so that another user can recover the lease.
conf.setBoolean(DFSConfigKeys.DFS_PERMISSIONS_ENABLED_KEY, false);
conf.setInt(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, BLOCK_SIZE);
FSDataOutputStream stm = null;
final MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf)
.nnTopology(MiniDFSNNTopology.simpleHATopology())
.numDataNodes(3)
.build();
try {
cluster.waitActive();
cluster.transitionToActive(0);
Thread.sleep(500);
LOG.info("Starting with NN 0 active");
FileSystem fs = HATestUtil.configureFailoverFs(cluster, conf);
stm = fs.create(TEST_PATH);
// write a block and a half
AppendTestUtil.write(stm, 0, BLOCK_AND_A_HALF);
stm.hflush();
LOG.info("Failing over to NN 1");
cluster.transitionToStandby(0);
cluster.transitionToActive(1);
assertTrue(fs.exists(TEST_PATH));
FileSystem fsOtherUser = createFsAsOtherUser(cluster, conf);
loopRecoverLease(fsOtherUser, TEST_PATH);
AppendTestUtil.check(fs, TEST_PATH, BLOCK_AND_A_HALF);
// Fail back to ensure that the block locations weren't lost on the
// original node.
cluster.transitionToStandby(1);
cluster.transitionToActive(0);
AppendTestUtil.check(fs, TEST_PATH, BLOCK_AND_A_HALF);
} finally {
IOUtils.closeStream(stm);
cluster.shutdown();
}
}
/**
* Test the scenario where the NN fails over after issuing a block
* synchronization request, but before it is committed. The
* DN running the recovery should then fail to commit the synchronization
* and a later retry will succeed.
*/
@Test(timeout=30000)
public void testFailoverRightBeforeCommitSynchronization() throws Exception {
final Configuration conf = new Configuration();
// Disable permissions so that another user can recover the lease.
conf.setBoolean(DFSConfigKeys.DFS_PERMISSIONS_ENABLED_KEY, false);
conf.setInt(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, BLOCK_SIZE);
FSDataOutputStream stm = null;
final MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf)
.nnTopology(MiniDFSNNTopology.simpleHATopology())
.numDataNodes(3)
.build();
try {
cluster.waitActive();
cluster.transitionToActive(0);
Thread.sleep(500);
LOG.info("Starting with NN 0 active");
FileSystem fs = HATestUtil.configureFailoverFs(cluster, conf);
stm = fs.create(TEST_PATH);
// write a half block
AppendTestUtil.write(stm, 0, BLOCK_SIZE / 2);
stm.hflush();
// Look into the block manager on the active node for the block
// under construction.
NameNode nn0 = cluster.getNameNode(0);
ExtendedBlock blk = DFSTestUtil.getFirstBlock(fs, TEST_PATH);
DatanodeDescriptor expectedPrimary = getExpectedPrimaryNode(nn0, blk);
LOG.info("Expecting block recovery to be triggered on DN " +
expectedPrimary);
// Find the corresponding DN daemon, and spy on its connection to the
// active.
DataNode primaryDN = cluster.getDataNode(expectedPrimary.getIpcPort());
DatanodeProtocolClientSideTranslatorPB nnSpy =
DataNodeTestUtils.spyOnBposToNN(primaryDN, nn0);
// Delay the commitBlockSynchronization call
DelayAnswer delayer = new DelayAnswer(LOG);
Mockito.doAnswer(delayer).when(nnSpy).commitBlockSynchronization(
Mockito.eq(blk),
Mockito.anyInt(), // new genstamp
Mockito.anyLong(), // new length
Mockito.eq(true), // close file
Mockito.eq(false), // delete block
(DatanodeID[]) Mockito.anyObject(), // new targets
(String[]) Mockito.anyObject()); // new target storages
DistributedFileSystem fsOtherUser = createFsAsOtherUser(cluster, conf);
assertFalse(fsOtherUser.recoverLease(TEST_PATH));
LOG.info("Waiting for commitBlockSynchronization call from primary");
delayer.waitForCall();
LOG.info("Failing over to NN 1");
cluster.transitionToStandby(0);
cluster.transitionToActive(1);
// Let the commitBlockSynchronization call go through, and check that
// it failed with the correct exception.
delayer.proceed();
delayer.waitForResult();
Throwable t = delayer.getThrown();
if (t == null) {
fail("commitBlockSynchronization call did not fail on standby");
}
GenericTestUtils.assertExceptionContains(
"Operation category WRITE is not supported",
t);
// Now, if we try again to recover the block, it should succeed on the new
// active.
loopRecoverLease(fsOtherUser, TEST_PATH);
AppendTestUtil.check(fs, TEST_PATH, BLOCK_SIZE/2);
} finally {
IOUtils.closeStream(stm);
cluster.shutdown();
}
}
/**
* Stress test for pipeline/lease recovery. Starts a number of
* threads, each of which creates a file and has another client
* break the lease. While these threads run, failover proceeds
* back and forth between two namenodes.
*/
@Test(timeout=STRESS_RUNTIME*3)
public void testPipelineRecoveryStress() throws Exception {
HAStressTestHarness harness = new HAStressTestHarness();
// Disable permissions so that another user can recover the lease.
harness.conf.setBoolean(
DFSConfigKeys.DFS_PERMISSIONS_ENABLED_KEY, false);
// This test triggers rapid NN failovers. The client retry policy uses an
// exponential backoff. This can quickly lead to long sleep times and even
// timeout the whole test. Cap the sleep time at 1s to prevent this.
harness.conf.setInt(DFSConfigKeys.DFS_CLIENT_FAILOVER_SLEEPTIME_MAX_KEY,
1000);
final MiniDFSCluster cluster = harness.startCluster();
try {
cluster.waitActive();
cluster.transitionToActive(0);
FileSystem fs = harness.getFailoverFs();
DistributedFileSystem fsAsOtherUser = createFsAsOtherUser(
cluster, harness.conf);
TestContext testers = new TestContext();
for (int i = 0; i < STRESS_NUM_THREADS; i++) {
Path p = new Path("/test-" + i);
testers.addThread(new PipelineTestThread(
testers, fs, fsAsOtherUser, p));
}
// Start a separate thread which will make sure that replication
// happens quickly by triggering deletion reports and replication
// work calculation frequently.
harness.addReplicationTriggerThread(500);
harness.addFailoverThread(5000);
harness.startThreads();
testers.startThreads();
testers.waitFor(STRESS_RUNTIME);
testers.stop();
harness.stopThreads();
} finally {
System.err.println("===========================\n\n\n\n");
harness.shutdown();
}
}
/**
* Test thread which creates a file, has another fake user recover
* the lease on the file, and then ensures that the file's contents
* are properly readable. If any of these steps fails, propagates
* an exception back to the test context, causing the test case
* to fail.
*/
private static class PipelineTestThread extends RepeatingTestThread {
private final FileSystem fs;
private final FileSystem fsOtherUser;
private final Path path;
public PipelineTestThread(TestContext ctx,
FileSystem fs, FileSystem fsOtherUser, Path p) {
super(ctx);
this.fs = fs;
this.fsOtherUser = fsOtherUser;
this.path = p;
}
@Override
public void doAnAction() throws Exception {
FSDataOutputStream stm = fs.create(path, true);
try {
AppendTestUtil.write(stm, 0, 100);
stm.hflush();
loopRecoverLease(fsOtherUser, path);
AppendTestUtil.check(fs, path, 100);
} finally {
try {
stm.close();
} catch (IOException e) {
// should expect this since we lost the lease
}
}
}
@Override
public String toString() {
return "Pipeline test thread for " + path;
}
}
/**
* @return the node which is expected to run the recovery of the
* given block, which is known to be under construction inside the
* given NameNOde.
*/
private DatanodeDescriptor getExpectedPrimaryNode(NameNode nn,
ExtendedBlock blk) {
BlockManager bm0 = nn.getNamesystem().getBlockManager();
BlockInfo storedBlock = bm0.getStoredBlock(blk.getLocalBlock());
assertTrue("Block " + blk + " should be under construction, " +
"got: " + storedBlock,
storedBlock instanceof BlockInfoUnderConstruction);
BlockInfoUnderConstruction ucBlock =
(BlockInfoUnderConstruction)storedBlock;
// We expect that the replica with the most recent heart beat will be
// the one to be in charge of the synchronization / recovery protocol.
final DatanodeStorageInfo[] storages = ucBlock.getExpectedStorageLocations();
DatanodeStorageInfo expectedPrimary = storages[0];
long mostRecentLastUpdate = expectedPrimary.getDatanodeDescriptor().getLastUpdate();
for (int i = 1; i < storages.length; i++) {
final long lastUpdate = storages[i].getDatanodeDescriptor().getLastUpdate();
if (lastUpdate > mostRecentLastUpdate) {
expectedPrimary = storages[i];
mostRecentLastUpdate = lastUpdate;
}
}
return expectedPrimary.getDatanodeDescriptor();
}
private DistributedFileSystem createFsAsOtherUser(
final MiniDFSCluster cluster, final Configuration conf)
throws IOException, InterruptedException {
return (DistributedFileSystem) UserGroupInformation.createUserForTesting(
"otheruser", new String[] { "othergroup"})
.doAs(new PrivilegedExceptionAction<FileSystem>() {
@Override
public FileSystem run() throws Exception {
return HATestUtil.configureFailoverFs(
cluster, conf);
}
});
}
/**
* Try to recover the lease on the given file for up to 60 seconds.
* @param fsOtherUser the filesystem to use for the recoverLease call
* @param testPath the path on which to run lease recovery
* @throws TimeoutException if lease recover does not succeed within 60
* seconds
* @throws InterruptedException if the thread is interrupted
*/
private static void loopRecoverLease(
final FileSystem fsOtherUser, final Path testPath)
throws TimeoutException, InterruptedException {
try {
GenericTestUtils.waitFor(new Supplier<Boolean>() {
@Override
public Boolean get() {
boolean success;
try {
success = ((DistributedFileSystem)fsOtherUser)
.recoverLease(testPath);
} catch (IOException e) {
throw new RuntimeException(e);
}
if (!success) {
LOG.info("Waiting to recover lease successfully");
}
return success;
}
}, 1000, 60000);
} catch (TimeoutException e) {
throw new TimeoutException("Timed out recovering lease for " +
testPath);
}
}
}
| [
"archen94@gmail.com"
] | archen94@gmail.com |
a264bfcf2d1305b420f566d9c06979d8ffa45483 | 774d36285e48bd429017b6901a59b8e3a51d6add | /sources/com/google/android/gms/internal/auth/zzah.java | 021486648a16c25801c6886cf9aa2b764873e790 | [] | no_license | jorge-luque/hb | 83c086851a409e7e476298ffdf6ba0c8d06911db | b467a9af24164f7561057e5bcd19cdbc8647d2e5 | refs/heads/master | 2023-08-25T09:32:18.793176 | 2020-10-02T11:02:01 | 2020-10-02T11:02:01 | 300,586,541 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,755 | java | package com.google.android.gms.internal.auth;
import android.app.PendingIntent;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.android.gms.common.internal.Preconditions;
import com.google.android.gms.common.internal.safeparcel.AbstractSafeParcelable;
import com.google.android.gms.common.internal.safeparcel.SafeParcelWriter;
import com.google.android.gms.common.internal.safeparcel.SafeParcelable;
@SafeParcelable.Class(creator = "UserChallengeRequestCreator")
public final class zzah extends AbstractSafeParcelable {
public static final Parcelable.Creator<zzah> CREATOR = new zzai();
@SafeParcelable.Field(mo15196id = 2)
private final String accountType;
@SafeParcelable.Field(mo15196id = 3)
private final PendingIntent zzbx;
@SafeParcelable.VersionField(mo15202id = 1)
private final int zzv;
public zzah(String str, PendingIntent pendingIntent) {
this(1, str, pendingIntent);
}
public final void writeToParcel(Parcel parcel, int i) {
int beginObjectHeader = SafeParcelWriter.beginObjectHeader(parcel);
SafeParcelWriter.writeInt(parcel, 1, this.zzv);
SafeParcelWriter.writeString(parcel, 2, this.accountType, false);
SafeParcelWriter.writeParcelable(parcel, 3, this.zzbx, i, false);
SafeParcelWriter.finishObjectHeader(parcel, beginObjectHeader);
}
@SafeParcelable.Constructor
zzah(@SafeParcelable.Param(mo15199id = 1) int i, @SafeParcelable.Param(mo15199id = 2) String str, @SafeParcelable.Param(mo15199id = 3) PendingIntent pendingIntent) {
this.zzv = 1;
this.accountType = (String) Preconditions.checkNotNull(str);
this.zzbx = (PendingIntent) Preconditions.checkNotNull(pendingIntent);
}
}
| [
"jorge.luque@taiger.com"
] | jorge.luque@taiger.com |
ef0235a58e8ec77a505d0f58e66fa4bc125f5cf4 | 86bafa573f14c48e752200473cf2f1c34fbfcafa | /lbs/src/main/java/com/xiaoka/lbs/service/impl/TestServiceImpl.java | 206a3e075536604372e5935c2985170ca6c8998d | [] | no_license | hekf2021/transport | 087158c99f89d2981605a80792e135278a6de8bd | 3029607ff0acf35a0bc5c4e37ea69caa4829b66e | refs/heads/master | 2020-03-20T19:59:44.652375 | 2018-06-25T07:32:41 | 2018-06-25T07:32:41 | 137,339,705 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,575 | java | package com.xiaoka.lbs.service.impl;
import com.kiaoka.common.redis.service.RedisTemplateService;
import com.xiaoka.lbs.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.Random;
import java.util.UUID;
@Service
public class TestServiceImpl implements TestService {
@Autowired
private RedisTemplateService redisTemplateService;
@Autowired
private RedisTemplate redisTemplate;
public void test(String key,String value){
redisTemplateService.stringSetString(key,value);
}
public Long getkey(){
String s = String.valueOf("abc".hashCode());
return incrementHash("order",s,1L);
}
/**
* 获取唯一Id
* @param key
* @param hashKey
* @param delta 增加量(不传采用1)
* @return
* @throws BusinessException
*/
public Long incrementHash(String key,String hashKey,Long delta){
try {
// if (null == delta) {
delta=1L;
// }
return redisTemplate.opsForHash().increment(key, hashKey, delta);
} catch (Exception e) {//redis宕机时采用uuid的方式生成唯一id
int first = new Random(10).nextInt(8) + 1;
int randNo=UUID.randomUUID().toString().hashCode();
if (randNo < 0) {
randNo=-randNo;
}
return Long.valueOf(first + String.format("%16d", randNo));
}
}
}
| [
"hekf2021@126.com"
] | hekf2021@126.com |
3c137c6cfa1f43a8dccb17cd6a7abcd0d0affb67 | 88f0cbcc410a657d5066ecbc66f5620c7f57d3af | /Foret.java | 27528bc75e2b7dbf0caf5d89460cdf8d54d77cad | [] | no_license | Laurelie/Naufrage | c7f8b36056017b3d72d1a0eb8a84400ed1f2f71f | daa23edf0dfab043ff4f458111512ad588839f82 | refs/heads/master | 2020-03-10T07:19:02.296988 | 2018-06-04T11:50:42 | 2018-06-04T11:50:42 | 129,260,407 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,827 | java | import java.util.ArrayList;
import java.util.Scanner;
public class Foret extends Lieu{
Scanner sc = new Scanner(System.in);
private ArrayList<Fruits> listeFruits = new ArrayList<Fruits>();
private ArrayList<Pechable> listePechable = new ArrayList<Pechable>();
//private ArrayList<AnimauxChassable> listeAnimaux = new ArrayList<AnimauxChassable>();
public Foret(){
super("Foret");
}
public void choixAction(Personnage p){
txt.textAffichage("1) Couper des arbres\n2) Ramasser des fruits\n");
this.interagirConstruction(2);
txt.textAffichage("\n\n\tPressez 0 pour retour.\n\n");
int str = Integer.parseInt(sc.nextLine());
while( str < 0 || str > 2+this.getConstructions().size()){
txt.textAffichage("Mauvaise selection. Recommencez.\n");
str = Integer.parseInt(sc.nextLine());
}
if(str==0) return;
if(str==1) p.couperArbre();
if(str==2) p.cueillir();
if(str>2) this.getConstructions().get(str-3).interagir(p);
}
public void genererAnimal(){
if(Math.random()<0.3){
this.changerAnimal(new Ours());
txt.textAffichage("Vous apercevez un ours derrière un buisson.\n");
}
else{
this.changerAnimal(new Lapin());
txt.textAffichage("Vous apercevez un lapin derrière un buisson.\n");
}
//LE TOP ce serait de faire comme avec les poissons, faire un tableau d'animaux chassables puis tiré au sort SEULEMENT : PB dans combattre
/*
listeAnimaux.add(new Ours());
listeAnimaux.add(new Lapin());
this.setOccupant(listeAnimaux);
*/
}
public void genererObjet(){
listeFruits.add(new Pomme());
listeFruits.add(new Baies());
listeFruits.add(new Cerise());
this.setFruits(listeFruits);
}
public void decrireLieu(){
txt.textAffichage("Vous avancer dans une foret dense.\n");
}
}
| [
"noreply@github.com"
] | Laurelie.noreply@github.com |
a7c28895df2bf52863908343a189d31e47f7977b | 8ae4152cede46c4f08c7eb2a198f14317c269842 | /shianxian-cloud/shianxian-common/src/main/java/com/shianxian/common/utils/DateUtils.java | ffbbd2ad0a8e5c12b9db464ab3508f7770fb1e6a | [] | no_license | sevenfang/spring-cloud-shianxian | 3ca72b947996e88d726fd79baa8618a92ce27e61 | 0442945026c3c1a1d14771ad6e8a0f15f1c70b0d | refs/heads/master | 2020-04-04T01:57:05.302458 | 2018-10-29T09:23:34 | 2018-10-29T09:23:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,819 | java | package com.shianxian.common.utils;
import lombok.extern.slf4j.Slf4j;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 日期Util类
*/
@Slf4j
public class DateUtils {
public static SimpleDateFormat yyyyMMddHHmmssFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static SimpleDateFormat yyyyMMddHHmmss = new SimpleDateFormat("yyyyMMddHHmmss");
public static SimpleDateFormat yyyyMMddFormat = new SimpleDateFormat("yyyy-MM-dd");
/**
* 获取时间戳
*/
public static String getTimestamp() {
return yyyyMMddHHmmss.format(new Date());
}
/**
* 获取时间字符串
*
* @param date
* @return
*/
public static String yyyyMMddHHmmssFormat(Date date) {
return yyyyMMddHHmmssFormat.format(date);
}
/**
* 获取时间字符串
*
* @return
*/
public static Date yyyyMMddHHmmssParse(String date) {
try {
return yyyyMMddHHmmssFormat.parse(date);
} catch (ParseException e) {
log.error("格式化时间失败!格式:yyyyMMddHHmmss", e);
}
return null;
}
/**
* 获取时间字符串
*
* @param date
* @return
*/
public static String yyyyMMddFormat(Date date) {
return yyyyMMddFormat.format(date);
}
/**
* 获取时间字符串
*
* @param date
* @return
*/
public static Date yyyyMMddParse(String date) {
try {
return yyyyMMddFormat.parse(date);
} catch (ParseException e) {
log.error("格式化时间失败!格式:yyyyMMdd", e);
}
return null;
}
}
| [
"damowang0322@163.com"
] | damowang0322@163.com |
c51058d4e12b7db65afb6016a7c1e12324ee7165 | a8db8bad0a9f3d80db63d4e8f1c13fa78043d610 | /8Kyu/Banjo/src/testing/SolutionTest.java | 308873cbebbf51eb825e65d04047f2277fea1e43 | [] | no_license | marcoanicosta/codewaers | 0f2ec2e32cc0cbfef1df30bdba539b92ec42fff7 | 65fd1476f27605cab72383e27e1af8902e86200e | refs/heads/master | 2023-02-13T06:07:36.902885 | 2021-01-11T23:41:10 | 2021-01-11T23:41:10 | 318,866,781 | 0 | 0 | null | 2021-01-11T23:41:11 | 2020-12-05T19:00:56 | Java | UTF-8 | Java | false | false | 379 | java | package testing;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class SolutionTest {
@Test
public void PeopleThatPlayBanjo() {
assertEquals( "Nope!", "Martin does not play banjo", Banjo.areYouPlayingBanjo("Martin"));
assertEquals( "Nope!", "Rikke plays banjo", Banjo.areYouPlayingBanjo("Rikke"));
}
}
| [
"marcolinonafafe@hotmail.co.uk"
] | marcolinonafafe@hotmail.co.uk |
f8e593740887f0ac269354e32f8fe92f454949d6 | eb34d6db083488b94bcd6c416bffcc0c412d0b1a | /src/main/java/org/app2automate/learning/web/rest/errors/BadRequestAlertException.java | 0ded0b3208ae7578eba07b6de5357c1aa58e669a | [] | no_license | jemaltech/App2AutomateApp | 53994cd7645c79a0a38af3eea618d7f356e4dc24 | b7d93b54497a808d84d8c7e83c2df180ef895167 | refs/heads/master | 2022-12-21T20:47:36.120463 | 2019-10-02T17:29:05 | 2019-10-02T17:29:05 | 212,381,713 | 0 | 0 | null | 2022-12-16T05:06:07 | 2019-10-02T15:53:03 | Java | UTF-8 | Java | false | false | 1,328 | java | package org.app2automate.learning.web.rest.errors;
import org.zalando.problem.AbstractThrowableProblem;
import org.zalando.problem.Status;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
public class BadRequestAlertException extends AbstractThrowableProblem {
private static final long serialVersionUID = 1L;
private final String entityName;
private final String errorKey;
public BadRequestAlertException(String defaultMessage, String entityName, String errorKey) {
this(ErrorConstants.DEFAULT_TYPE, defaultMessage, entityName, errorKey);
}
public BadRequestAlertException(URI type, String defaultMessage, String entityName, String errorKey) {
super(type, defaultMessage, Status.BAD_REQUEST, null, null, null, getAlertParameters(entityName, errorKey));
this.entityName = entityName;
this.errorKey = errorKey;
}
public String getEntityName() {
return entityName;
}
public String getErrorKey() {
return errorKey;
}
private static Map<String, Object> getAlertParameters(String entityName, String errorKey) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("message", "error." + errorKey);
parameters.put("params", entityName);
return parameters;
}
}
| [
"jemal@zoomdata.com"
] | jemal@zoomdata.com |
d4f4f2cf4ef0bf8696232c4d4fccbe881b3afd5f | 9807fc4902cbdefec8b9df7b948002bc41fb7165 | /server/WChat/src/com/thugkd/model/ServerConClientThread.java | c605c8cc419fd0d056fe763425b7b63877f3ad2f | [] | no_license | ThugKd/WChat | c6769417e09e19deee9b904bb9bab1ccb57fb462 | c0f710b5d75678fd0cbc97efb59c9c36bb4d0c42 | refs/heads/master | 2020-05-22T17:12:29.121886 | 2018-04-11T07:29:29 | 2018-04-11T07:29:29 | 84,707,627 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,608 | java | package com.thugkd.model;
import com.thugkd.entity.MessageType;
import com.thugkd.entity.WChatMessage;
import java.io.ObjectInputStream;
import java.net.Socket;
/**
* Created with IntelliJ IDEA
*
* @Description:
* @author: thugkd
* @date: 24/03/2017 16:50
*/
public class ServerConClientThread extends Thread {
Socket s;
public ServerConClientThread(Socket s) {
this.s = s;
}
public Socket getS(){
return s;
}
public void run() {
try {
while (true) {
ObjectInputStream ois = null;
WChatMessage m = null;
ois = new ObjectInputStream(s.getInputStream());
m = (WChatMessage) ois.readObject();
System.out.println(m.getType() + "-------" + m.getSender() + "===" + m.getReceiver());
//对从客户端取得的消息进行类型判断,做相应的处理
if (m.getType().equals(MessageType.COM_MES)) {//普通消息包
DoWhatAndSendMes.sendMes(m);
System.out.println(2222);
} else if (m.getType().equals(MessageType.GROUP_MES)) { //群消息
DoWhatAndSendMes.sendGroupMes(m);
System.out.println(3333);
} else if (m.getType().equals(MessageType.GET_ONLINE_FRIENDS)) {//请求好友列表
DoWhatAndSendMes.sendBuddyList(m);
} else if (m.getType().equals(MessageType.DEL_BUDDY)) { //删除好友
DoWhatAndSendMes.delBuddy(m);
} else if (m.getType().equals(MessageType.ADD_BUDDY)) {//添加好友
DoWhatAndSendMes.addBuddy(m);
} else if (m.getType().equals(MessageType.GET_USER_INFO)) {//获取用户信息
DoWhatAndSendMes.getUerInfo(m);
} else if (m.getType().equals(MessageType.GET_GROUP_MEMBER)) {//获取群成员
DoWhatAndSendMes.getGroupMemberInfo(m);
} else if (m.getType().equals(MessageType.ADD_GROUP)) {//添加群
System.out.println(MessageType.ADD_GROUP + "444444");
DoWhatAndSendMes.addGroup(m);
} else if (m.getType().equals(MessageType.DEL_GROUP)) {//退出群
DoWhatAndSendMes.delGroup(m);
} else if (m.getType().equals(MessageType.LOGOUT)){
DoWhatAndSendMes.logout(m);
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| [
"thugkd@gmail.com"
] | thugkd@gmail.com |
a0cbacc9dff8982dfc011a959cc907c4e41ee2ad | eac7cedec43f7ade75975a5fb73b255c216b231b | /Hw1/src/Profile/Person.java | c0150d9763dd88b61d88d4b175fee850678a7d03 | [
"MIT"
] | permissive | StarDust0415/INFO-5100-Application-Engineer-Dev | 11b36ece90cb62cf8d50e497227247d738eca235 | 0052c605922efff2e31b166a3841ecafcbc1f4cf | refs/heads/master | 2020-04-02T19:18:21.273605 | 2018-10-25T20:58:24 | 2018-10-25T20:58:24 | 154,729,814 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,850 | java | /*
* 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 Profile;
import java.awt.*;
import javax.swing.ImageIcon;
/**
*
* @author Rong gao
*/
public class Person {
private String firstName;
private String lastName;
private CreditCard creditCard;
private FinancialAcc financialAcc;
private LicenseData licenseData;
private Address address;
private ImageIcon image;
//private Person spuse;
public Person(){
}
public void setfirstName(String firstName){
this.firstName = firstName;
}
public String getFirstName(){
return this.firstName;
}
public void setlastName(String lastName){
this.lastName = lastName;
}
public String getLastName(){
return this.lastName;
}
public void setAddress(Address address){
this.address = address;
}
public Address getAddress(){
return this.address;
}
public void setCreditCard(CreditCard creditCard){
this.creditCard = creditCard;
}
public CreditCard getCreditCard(){
return this.creditCard;
}
public void setFinancialAcc(FinancialAcc financialAcc){
this.financialAcc = financialAcc;
}
public FinancialAcc getFinancialAcc(){
return this.financialAcc;
}
public void setLicenseData(LicenseData licenseData){
this.licenseData = licenseData;
}
public LicenseData getLicenseData(){
return this.licenseData;
}
public void setImage(ImageIcon image){
this.image = image;
}
public ImageIcon getImage(){
return this.image;
}
}
| [
"liu.yiz@husky.neu.edu"
] | liu.yiz@husky.neu.edu |
b54b5092ddd776cdecf022f4b6ba814720a57cb4 | 280ce9155107a41d88167818054fca9bceda796b | /jre_emul/android/platform/external/icu/android_icu4j/src/main/tests/android/icu/dev/test/collator/CollationEnglishTest.java | fc979afb4cb06115c90827c46d278c11426014e1 | [
"Apache-2.0",
"BSD-3-Clause",
"GPL-2.0-only",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"APSL-1.0",
"LGPL-2.0-or-later",
"LicenseRef-scancode-proprietary-license",
"GPL-1.0-or-later",
"LicenseRef-scancode-generic-exception",
"LicenseRef-scancode-red-hat-attribution",
"ICU",
"MIT",... | permissive | google/j2objc | bd4796cdf77459abe816ff0db6e2709c1666627c | 57b9229f5c6fb9e710609d93ca49eda9fa08c0e8 | refs/heads/master | 2023-08-28T16:26:05.842475 | 2023-08-26T03:30:58 | 2023-08-26T03:32:25 | 16,389,681 | 5,053 | 1,041 | Apache-2.0 | 2023-09-14T20:32:57 | 2014-01-30T20:19:56 | Java | UTF-8 | Java | false | false | 18,384 | java | /* GENERATED SOURCE. DO NOT MODIFY. */
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html#License
/*
*******************************************************************************
* Copyright (C) 2002-2014, International Business Machines Corporation and
* others. All Rights Reserved.
*******************************************************************************
*/
/**
* Port From: ICU4C v2.1 : Collate/CollationEnglishTest
* Source File: $ICU4CRoot/source/test/intltest/encoll.cpp
**/
package android.icu.dev.test.collator;
import java.util.Locale;
import org.junit.Before;
import org.junit.Test;
import android.icu.dev.test.TestFmwk;
import android.icu.text.CollationKey;
import android.icu.text.Collator;
public class CollationEnglishTest extends TestFmwk{
private static char[][] testSourceCases = {
{0x0061 /* 'a' */, 0x0062 /* 'b' */},
{0x0062 /* 'b' */, 0x006C /* 'l' */, 0x0061 /* 'a' */, 0x0063 /* 'c' */, 0x006B /* 'k' */, 0x002D /* '-' */, 0x0062 /* 'b' */, 0x0069 /* 'i' */, 0x0072 /* 'r' */, 0x0064 /* 'd' */},
{0x0062 /* 'b' */, 0x006C /* 'l' */, 0x0061 /* 'a' */, 0x0063 /* 'c' */, 0x006B /* 'k' */, 0x0020 /* ' ' */, 0x0062 /* 'b' */, 0x0069 /* 'i' */, 0x0072 /* 'r' */, 0x0064 /* 'd' */},
{0x0062 /* 'b' */, 0x006C /* 'l' */, 0x0061 /* 'a' */, 0x0063 /* 'c' */, 0x006B /* 'k' */, 0x002D /* '-' */, 0x0062 /* 'b' */, 0x0069 /* 'i' */, 0x0072 /* 'r' */, 0x0064 /* 'd' */},
{0x0048 /* 'H' */, 0x0065 /* 'e' */, 0x006C /* 'l' */, 0x006C /* 'l' */, 0x006F /* 'o' */},
{0x0041 /* 'A' */, 0x0042 /* 'B' */, 0x0043 /* 'C' */},
{0x0061 /* 'a' */, 0x0062 /* 'b' */, 0x0063 /* 'c' */},
{0x0062 /* 'b' */, 0x006C /* 'l' */, 0x0061 /* 'a' */, 0x0063 /* 'c' */, 0x006B /* 'k' */, 0x0062 /* 'b' */, 0x0069 /* 'i' */, 0x0072 /* 'r' */, 0x0064 /* 'd' */},
{0x0062 /* 'b' */, 0x006C /* 'l' */, 0x0061 /* 'a' */, 0x0063 /* 'c' */, 0x006B /* 'k' */, 0x002D /* '-' */, 0x0062 /* 'b' */, 0x0069 /* 'i' */, 0x0072 /* 'r' */, 0x0064 /* 'd' */},
{0x0062 /* 'b' */, 0x006C /* 'l' */, 0x0061 /* 'a' */, 0x0063 /* 'c' */, 0x006B /* 'k' */, 0x002D /* '-' */, 0x0062 /* 'b' */, 0x0069 /* 'i' */, 0x0072 /* 'r' */, 0x0064 /* 'd' */},
{0x0070 /* 'p' */, 0x00EA, 0x0063 /* 'c' */, 0x0068 /* 'h' */, 0x0065 /* 'e' */},
{0x0070 /* 'p' */, 0x00E9, 0x0063 /* 'c' */, 0x0068 /* 'h' */, 0x00E9},
{0x00C4, 0x0042 /* 'B' */, 0x0308, 0x0043 /* 'C' */, 0x0308},
{0x0061 /* 'a' */, 0x0308, 0x0062 /* 'b' */, 0x0063 /* 'c' */},
{0x0070 /* 'p' */, 0x00E9, 0x0063 /* 'c' */, 0x0068 /* 'h' */, 0x0065 /* 'e' */, 0x0072 /* 'r' */},
{0x0072 /* 'r' */, 0x006F /* 'o' */, 0x006C /* 'l' */, 0x0065 /* 'e' */, 0x0073 /* 's' */},
{0x0061 /* 'a' */, 0x0062 /* 'b' */, 0x0063 /* 'c' */},
{0x0041 /* 'A' */},
{0x0041 /* 'A' */},
{0x0061 /* 'a' */, 0x0062 /* 'b' */},
{0x0074 /* 't' */, 0x0063 /* 'c' */, 0x006F /* 'o' */, 0x006D /* 'm' */, 0x0070 /* 'p' */, 0x0061 /* 'a' */, 0x0072 /* 'r' */, 0x0065 /* 'e' */, 0x0070 /* 'p' */, 0x006C /* 'l' */, 0x0061 /* 'a' */, 0x0069 /* 'i' */, 0x006E /* 'n' */},
{0x0061 /* 'a' */, 0x0062 /* 'b' */},
{0x0061 /* 'a' */, 0x0023 /* '#' */, 0x0062 /* 'b' */},
{0x0061 /* 'a' */, 0x0023 /* '#' */, 0x0062 /* 'b' */},
{0x0061 /* 'a' */, 0x0062 /* 'b' */, 0x0063 /* 'c' */},
{0x0041 /* 'A' */, 0x0062 /* 'b' */, 0x0063 /* 'c' */, 0x0064 /* 'd' */, 0x0061 /* 'a' */},
{0x0061 /* 'a' */, 0x0062 /* 'b' */, 0x0063 /* 'c' */, 0x0064 /* 'd' */, 0x0061 /* 'a' */},
{0x0061 /* 'a' */, 0x0062 /* 'b' */, 0x0063 /* 'c' */, 0x0064 /* 'd' */, 0x0061 /* 'a' */},
{0x00E6, 0x0062 /* 'b' */, 0x0063 /* 'c' */, 0x0064 /* 'd' */, 0x0061 /* 'a' */},
{0x00E4, 0x0062 /* 'b' */, 0x0063 /* 'c' */, 0x0064 /* 'd' */, 0x0061 /* 'a' */},
{0x0061 /* 'a' */, 0x0062 /* 'b' */, 0x0063 /* 'c' */},
{0x0061 /* 'a' */, 0x0062 /* 'b' */, 0x0063 /* 'c' */},
{0x0061 /* 'a' */, 0x0062 /* 'b' */, 0x0063 /* 'c' */},
{0x0061 /* 'a' */, 0x0062 /* 'b' */, 0x0063 /* 'c' */},
{0x0061 /* 'a' */, 0x0062 /* 'b' */, 0x0063 /* 'c' */},
{0x0061 /* 'a' */, 0x0063 /* 'c' */, 0x0048 /* 'H' */, 0x0063 /* 'c' */},
{0x0061 /* 'a' */, 0x0308, 0x0062 /* 'b' */, 0x0063 /* 'c' */},
{0x0074 /* 't' */, 0x0068 /* 'h' */, 0x0069 /* 'i' */, 0x0302, 0x0073 /* 's' */},
{0x0070 /* 'p' */, 0x00EA, 0x0063 /* 'c' */, 0x0068 /* 'h' */, 0x0065 /* 'e' */},
{0x0061 /* 'a' */, 0x0062 /* 'b' */, 0x0063 /* 'c' */},
{0x0061 /* 'a' */, 0x0062 /* 'b' */, 0x0063 /* 'c' */},
{0x0061 /* 'a' */, 0x0062 /* 'b' */, 0x0063 /* 'c' */},
{0x0061 /* 'a' */, 0x00E6, 0x0063 /* 'c' */},
{0x0061 /* 'a' */, 0x0062 /* 'b' */, 0x0063 /* 'c' */},
{0x0061 /* 'a' */, 0x0062 /* 'b' */, 0x0063 /* 'c' */},
{0x0061 /* 'a' */, 0x00E6, 0x0063 /* 'c' */},
{0x0061 /* 'a' */, 0x0062 /* 'b' */, 0x0063 /* 'c' */},
{0x0061 /* 'a' */, 0x0062 /* 'b' */, 0x0063 /* 'c' */},
{0x0070 /* 'p' */, 0x00E9, 0x0063 /* 'c' */, 0x0068 /* 'h' */, 0x00E9} // 49
};
private static char[][] testTargetCases = {
{0x0061 /* 'a' */, 0x0062 /* 'b' */, 0x0063 /* 'c' */},
{0x0062 /* 'b' */, 0x006C /* 'l' */, 0x0061 /* 'a' */, 0x0063 /* 'c' */, 0x006B /* 'k' */, 0x0062 /* 'b' */, 0x0069 /* 'i' */, 0x0072 /* 'r' */, 0x0064 /* 'd' */},
{0x0062 /* 'b' */, 0x006C /* 'l' */, 0x0061 /* 'a' */, 0x0063 /* 'c' */, 0x006B /* 'k' */, 0x002D /* '-' */, 0x0062 /* 'b' */, 0x0069 /* 'i' */, 0x0072 /* 'r' */, 0x0064 /* 'd' */},
{0x0062 /* 'b' */, 0x006C /* 'l' */, 0x0061 /* 'a' */, 0x0063 /* 'c' */, 0x006B /* 'k' */},
{0x0068 /* 'h' */, 0x0065 /* 'e' */, 0x006C /* 'l' */, 0x006C /* 'l' */, 0x006F /* 'o' */},
{0x0041 /* 'A' */, 0x0042 /* 'B' */, 0x0043 /* 'C' */},
{0x0041 /* 'A' */, 0x0042 /* 'B' */, 0x0043 /* 'C' */},
{0x0062 /* 'b' */, 0x006C /* 'l' */, 0x0061 /* 'a' */, 0x0063 /* 'c' */, 0x006B /* 'k' */, 0x0062 /* 'b' */, 0x0069 /* 'i' */, 0x0072 /* 'r' */, 0x0064 /* 'd' */, 0x0073 /* 's' */},
{0x0062 /* 'b' */, 0x006C /* 'l' */, 0x0061 /* 'a' */, 0x0063 /* 'c' */, 0x006B /* 'k' */, 0x0062 /* 'b' */, 0x0069 /* 'i' */, 0x0072 /* 'r' */, 0x0064 /* 'd' */, 0x0073 /* 's' */},
{0x0062 /* 'b' */, 0x006C /* 'l' */, 0x0061 /* 'a' */, 0x0063 /* 'c' */, 0x006B /* 'k' */, 0x0062 /* 'b' */, 0x0069 /* 'i' */, 0x0072 /* 'r' */, 0x0064 /* 'd' */},
{0x0070 /* 'p' */, 0x00E9, 0x0063 /* 'c' */, 0x0068 /* 'h' */, 0x00E9},
{0x0070 /* 'p' */, 0x00E9, 0x0063 /* 'c' */, 0x0068 /* 'h' */, 0x0065 /* 'e' */, 0x0072 /* 'r' */},
{0x00C4, 0x0042 /* 'B' */, 0x0308, 0x0043 /* 'C' */, 0x0308},
{0x0041 /* 'A' */, 0x0308, 0x0062 /* 'b' */, 0x0063 /* 'c' */},
{0x0070 /* 'p' */, 0x00E9, 0x0063 /* 'c' */, 0x0068 /* 'h' */, 0x0065 /* 'e' */},
{0x0072 /* 'r' */, 0x006F /* 'o' */, 0x0302, 0x006C /* 'l' */, 0x0065 /* 'e' */},
{0x0041 /* 'A' */, 0x00E1, 0x0063 /* 'c' */, 0x0064 /* 'd' */},
{0x0041 /* 'A' */, 0x00E1, 0x0063 /* 'c' */, 0x0064 /* 'd' */},
{0x0061 /* 'a' */, 0x0062 /* 'b' */, 0x0063 /* 'c' */},
{0x0061 /* 'a' */, 0x0062 /* 'b' */, 0x0063 /* 'c' */},
{0x0054 /* 'T' */, 0x0043 /* 'C' */, 0x006F /* 'o' */, 0x006D /* 'm' */, 0x0070 /* 'p' */, 0x0061 /* 'a' */, 0x0072 /* 'r' */, 0x0065 /* 'e' */, 0x0050 /* 'P' */, 0x006C /* 'l' */, 0x0061 /* 'a' */, 0x0069 /* 'i' */, 0x006E /* 'n' */},
{0x0061 /* 'a' */, 0x0042 /* 'B' */, 0x0063 /* 'c' */},
{0x0061 /* 'a' */, 0x0023 /* '#' */, 0x0042 /* 'B' */},
{0x0061 /* 'a' */, 0x0026 /* '&' */, 0x0062 /* 'b' */},
{0x0061 /* 'a' */, 0x0023 /* '#' */, 0x0063 /* 'c' */},
{0x0061 /* 'a' */, 0x0062 /* 'b' */, 0x0063 /* 'c' */, 0x0064 /* 'd' */, 0x0061 /* 'a' */},
{0x00C4, 0x0062 /* 'b' */, 0x0063 /* 'c' */, 0x0064 /* 'd' */, 0x0061 /* 'a' */},
{0x00E4, 0x0062 /* 'b' */, 0x0063 /* 'c' */, 0x0064 /* 'd' */, 0x0061 /* 'a' */},
{0x00C4, 0x0062 /* 'b' */, 0x0063 /* 'c' */, 0x0064 /* 'd' */, 0x0061 /* 'a' */},
{0x00C4, 0x0062 /* 'b' */, 0x0063 /* 'c' */, 0x0064 /* 'd' */, 0x0061 /* 'a' */},
{0x0061 /* 'a' */, 0x0062 /* 'b' */, 0x0023 /* '#' */, 0x0063 /* 'c' */},
{0x0061 /* 'a' */, 0x0062 /* 'b' */, 0x0063 /* 'c' */},
{0x0061 /* 'a' */, 0x0062 /* 'b' */, 0x003D /* '=' */, 0x0063 /* 'c' */},
{0x0061 /* 'a' */, 0x0062 /* 'b' */, 0x0064 /* 'd' */},
{0x00E4, 0x0062 /* 'b' */, 0x0063 /* 'c' */},
{0x0061 /* 'a' */, 0x0043 /* 'C' */, 0x0048 /* 'H' */, 0x0063 /* 'c' */},
{0x00E4, 0x0062 /* 'b' */, 0x0063 /* 'c' */},
{0x0074 /* 't' */, 0x0068 /* 'h' */, 0x00EE, 0x0073 /* 's' */},
{0x0070 /* 'p' */, 0x00E9, 0x0063 /* 'c' */, 0x0068 /* 'h' */, 0x00E9},
{0x0061 /* 'a' */, 0x0042 /* 'B' */, 0x0043 /* 'C' */},
{0x0061 /* 'a' */, 0x0062 /* 'b' */, 0x0064 /* 'd' */},
{0x00E4, 0x0062 /* 'b' */, 0x0063 /* 'c' */},
{0x0061 /* 'a' */, 0x00C6, 0x0063 /* 'c' */},
{0x0061 /* 'a' */, 0x0042 /* 'B' */, 0x0064 /* 'd' */},
{0x00E4, 0x0062 /* 'b' */, 0x0063 /* 'c' */},
{0x0061 /* 'a' */, 0x00C6, 0x0063 /* 'c' */},
{0x0061 /* 'a' */, 0x0042 /* 'B' */, 0x0064 /* 'd' */},
{0x00E4, 0x0062 /* 'b' */, 0x0063 /* 'c' */},
{0x0070 /* 'p' */, 0x00EA, 0x0063 /* 'c' */, 0x0068 /* 'h' */, 0x0065 /* 'e' */}
}; // 49
private static int[] results = {
//-1:LESS; 0:EQUAL; 1:GREATER
-1,
-1, /*Collator::GREATER,*/
-1,
1,
1,
0,
-1,
-1,
-1,
-1, /*Collator::GREATER,*/ /* 10 */
1,
-1,
0,
-1,
1,
1,
1,
-1,
-1,
-1, /* 20 */
-1,
-1,
-1,
1,
1,
1,
/* Test Tertiary > 26 */
-1,
-1,
1,
-1, /* 30 */
1,
0,
1,
-1,
-1,
-1,
/* test identical > 36 */
0,
0,
/* test primary > 38 */
0,
0, /* 40 */
-1,
0,
0,
/* test secondary > 43 */
-1,
-1,
0,
-1,
-1,
-1 // 49
};
private static char [][] testBugs = {
{0x61},
{0x41},
{0x65},
{0x45},
{0x00e9},
{0x00e8},
{0x00ea},
{0x00eb},
{0x65, 0x61},
{0x78}
};
// 0x0300 is grave, 0x0301 is acute
// the order of elements in this array must be different than the order in CollationFrenchTest
private static char[][] testAcute = {
{0x65, 0x65},
{0x65, 0x65, 0x0301},
{0x65, 0x65, 0x0301, 0x0300},
{0x65, 0x65, 0x0300},
{0x65, 0x65, 0x0300, 0x0301},
{0x65, 0x0301, 0x65},
{0x65, 0x0301, 0x65, 0x0301},
{0x65, 0x0301, 0x65, 0x0301, 0x0300},
{0x65, 0x0301, 0x65, 0x0300},
{0x65, 0x0301, 0x65, 0x0300, 0x0301},
{0x65, 0x0301, 0x0300, 0x65},
{0x65, 0x0301, 0x0300, 0x65, 0x0301},
{0x65, 0x0301, 0x0300, 0x65, 0x0301, 0x0300},
{0x65, 0x0301, 0x0300, 0x65, 0x0300},
{0x65, 0x0301, 0x0300, 0x65, 0x0300, 0x0301},
{0x65, 0x0300, 0x65},
{0x65, 0x0300, 0x65, 0x0301},
{0x65, 0x0300, 0x65, 0x0301, 0x0300},
{0x65, 0x0300, 0x65, 0x0300},
{0x65, 0x0300, 0x65, 0x0300, 0x0301},
{0x65, 0x0300, 0x0301, 0x65},
{0x65, 0x0300, 0x0301, 0x65, 0x0301},
{0x65, 0x0300, 0x0301, 0x65, 0x0301, 0x0300},
{0x65, 0x0300, 0x0301, 0x65, 0x0300},
{0x65, 0x0300, 0x0301, 0x65, 0x0300, 0x0301}
};
private static char[][] testMore = {
{0x0061 /* 'a' */, 0x0065 /* 'e' */},
{ 0x00E6},
{ 0x00C6},
{0x0061 /* 'a' */, 0x0066 /* 'f' */},
{0x006F /* 'o' */, 0x0065 /* 'e' */},
{ 0x0153},
{ 0x0152},
{0x006F /* 'o' */, 0x0066 /* 'f' */},
};
private Collator myCollation = null;
public CollationEnglishTest() {
}
@Before
public void init()throws Exception {
myCollation = Collator.getInstance(Locale.ENGLISH);
}
//performs test with strength PRIMARY
@Test
public void TestPrimary() {
int i;
myCollation.setStrength(Collator.PRIMARY);
for (i = 38; i < 43 ; i++) {
doTest(testSourceCases[i], testTargetCases[i], results[i]);
}
}
//perform test with strength SECONDARY
@Test
public void TestSecondary() {
int i;
myCollation.setStrength(Collator.SECONDARY);
for (i = 43; i < 49 ; i++) {
doTest(testSourceCases[i], testTargetCases[i], results[i]);
}
//test acute and grave ordering (compare to french collation)
int j;
int expected;
for (i = 0; i < testAcute.length; i++) {
for (j = 0; j < testAcute.length; j++) {
logln("i = " + i + "; j = " + j);
if (i < j)
expected = -1;
else if (i == j)
expected = 0;
else // (i > j)
expected = 1;
doTest(testAcute[i], testAcute[j], expected );
}
}
}
//perform test with strength TERTIARY
@Test
public void TestTertiary() {
int i = 0;
myCollation.setStrength(Collator.TERTIARY);
//for (i = 0; i < 38 ; i++) //attention: there is something wrong with 36, 37.
for (i = 0; i < 38 ; i++)
{
doTest(testSourceCases[i], testTargetCases[i], results[i]);
}
int j = 0;
for (i = 0; i < 10; i++)
{
for (j = i+1; j < 10; j++)
{
doTest(testBugs[i], testBugs[j], -1);
}
}
//test more interesting cases
int expected;
for (i = 0; i < testMore.length; i++)
{
for (j = 0; j < testMore.length; j++)
{
if (i < j)
expected = -1;
else if (i == j)
expected = 0;
else // (i > j)
expected = 1;
doTest(testMore[i], testMore[j], expected );
}
}
}
// main test routine, tests rules defined by the "en" locale
private void doTest(char[] source, char[] target, int result){
String s = new String(source);
String t = new String(target);
int compareResult = myCollation.compare(s, t);
CollationKey sortKey1, sortKey2;
sortKey1 = myCollation.getCollationKey(s);
sortKey2 = myCollation.getCollationKey(t);
int keyResult = sortKey1.compareTo(sortKey2);
reportCResult(s, t, sortKey1, sortKey2, compareResult, keyResult, compareResult, result);
}
private void reportCResult( String source, String target, CollationKey sourceKey, CollationKey targetKey,
int compareResult, int keyResult, int incResult, int expectedResult ){
if (expectedResult < -1 || expectedResult > 1)
{
errln("***** invalid call to reportCResult ****");
return;
}
boolean ok1 = (compareResult == expectedResult);
boolean ok2 = (keyResult == expectedResult);
boolean ok3 = (incResult == expectedResult);
if (ok1 && ok2 && ok3 && !isVerbose()){
return;
}else{
String msg1 = ok1? "Ok: compare(\"" : "FAIL: compare(\"";
String msg2 = "\", \"";
String msg3 = "\") returned ";
String msg4 = "; expected ";
String sExpect = new String("");
String sResult = new String("");
sResult = CollationTest.appendCompareResult(compareResult, sResult);
sExpect = CollationTest.appendCompareResult(expectedResult, sExpect);
if (ok1) {
logln(msg1 + source + msg2 + target + msg3 + sResult);
} else {
errln(msg1 + source + msg2 + target + msg3 + sResult + msg4 + sExpect);
}
msg1 = ok2 ? "Ok: key(\"" : "FAIL: key(\"";
msg2 = "\").compareTo(key(\"";
msg3 = "\")) returned ";
sResult = CollationTest.appendCompareResult(keyResult, sResult);
if (ok2) {
logln(msg1 + source + msg2 + target + msg3 + sResult);
} else {
errln(msg1 + source + msg2 + target + msg3 + sResult + msg4 + sExpect);
msg1 = " ";
msg2 = " vs. ";
errln(msg1 + CollationTest.prettify(sourceKey) + msg2 + CollationTest.prettify(targetKey));
}
msg1 = ok3 ? "Ok: incCompare(\"" : "FAIL: incCompare(\"";
msg2 = "\", \"";
msg3 = "\") returned ";
sResult = CollationTest.appendCompareResult(incResult, sResult);
if (ok3) {
logln(msg1 + source + msg2 + target + msg3 + sResult);
} else {
errln(msg1 + source + msg2 + target + msg3 + sResult + msg4 + sExpect);
}
}
}
}
| [
"antoniocortes@google.com"
] | antoniocortes@google.com |
c352ebe72466153e2c4643f2ff7ee125d1d60253 | 6d0315f200e41e1c3c1970313531e5184267344d | /aJavaProgrammingMasterclassForJavaDevelopers/src/main/java/kJavaFX/cControls/Main.java | 2d8388a9b1e9c6338a862a4358431d904147d3b4 | [
"MIT"
] | permissive | Andrei-Alexandru07/JavaCourses | 6a724ff8ea35c9c64ef07d39871ce0ac2d0046fe | d5eb12a5743ca131ef0b0bc64cccb3ea563e21ac | refs/heads/master | 2023-05-16T17:34:29.403505 | 2021-04-12T16:18:40 | 2021-04-12T16:18:40 | 278,724,118 | 0 | 0 | MIT | 2021-06-04T03:12:39 | 2020-07-10T20:09:05 | Java | UTF-8 | Java | false | false | 591 | java | package kJavaFX.cControls;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("Hello World");
primaryStage.setScene(new Scene(root, 800, 500));
primaryStage.show();
}
}
| [
"andrei_alexandru707@yahoo.com"
] | andrei_alexandru707@yahoo.com |
fa62324ee419df16934d569a41187d83ba4e04e2 | 1929ebdddb3d3d7a50c8b9c22942af193b44d568 | /designpattern/src/test/java/com/designpattern/thread/t6/ExamProjectTest2.java | 9d9e6dde6121a83177ebb5c7394db58bf3fc86b9 | [] | no_license | Bergv/Java-DesignPattern | d9f2fa7da896eb41195e14f6e8858c697fcc9066 | 833498da899c888b4d055620acd8d8318a7668d9 | refs/heads/master | 2021-09-27T06:50:10.387781 | 2021-09-15T14:52:34 | 2021-09-15T14:52:34 | 188,641,267 | 0 | 0 | null | 2020-10-13T13:28:49 | 2019-05-26T04:50:04 | Java | UTF-8 | Java | false | false | 1,178 | java | package com.designpattern.thread.t6;
import static org.junit.Assert.assertFalse;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class ExamProjectTest2 {
@BeforeEach
void setUp() throws Exception {
}
@AfterEach
void tearDown() throws Exception {
}
@Test
void test() {
// fail("Not yet implemented");
List<String> list = new ArrayList<String>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
System.out.println("------1-------");
System.out.println(list.get(0));
System.out.println("------2-------");
String remove = list.remove(0);
System.out.println(remove + " ------3-------");
System.out.println(list.get(0));
}
@Test
public void testProductCreateAndconsume() {
ProductMgrImpl mgr = ProductMgrImpl.getlnstance();
Producer p = new Producer(mgr);
Consumer c = new Consumer(mgr);
try {
p.start();
c.start();
System.out.println(6666666);
mgr.shutdown();
p.join();
c.join();
System.out.println(6666666);
} catch (Exception e) {
}
assertFalse(false);
}
}
| [
"zhbo.io@aliyun.com"
] | zhbo.io@aliyun.com |
0f469e7cd74ec865891273e321179eb99d0f1203 | 911065c7428fc29bd22a440f0a5726ff4c862852 | /WEB-INF/classes/itserviceportal/controller/TimeoutController.java | 89b415518dc73e234e741c4eb3c8d92cf7535055 | [] | no_license | goldsolace/c3180044_c3281849_c3237808_FinalProject | 7aa832996034c2d422e155bd3d3fb8e1e43df58e | 93d4b6f31f6a61753a7cb20cc17033ec554f4b07 | refs/heads/master | 2020-03-15T09:18:47.697581 | 2018-09-18T11:51:34 | 2018-09-18T11:51:34 | 132,071,700 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,653 | java | package itserviceportal.controller;
import itserviceportal.model.beans.*;
import itserviceportal.model.datalayer.*;
import java.io.*;
import java.sql.SQLException;
import javax.servlet.*;
import javax.servlet.http.*;
/**
* TimeoutController
*
* @author Brice Purton, Jonothan Williams, Wajdi Yournes
* @lastModified: 18-05-2018
*/
public class TimeoutController extends HttpServlet{
/**
* Send to doPost
*
* @param request a http servlet request
* @param response a http servlet response
* @throws ServletException
* @throws IOException
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
/**
* Redirect a timed out user to login page with error message
*
* @param request a http servlet request
* @param response a http servlet response
* @throws ServletException
* @throws IOException
*/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Check to see if the user is currently already inside the session
HttpSession session = request.getSession();
User user = (User) session.getAttribute("user");
// If the user is not null then the user is already logged in, direct to the portal
if (user != null) {
response.sendRedirect("ServicePortal");
// Direct user to login page with errorMessage
} else {
String errorMessage = request.getParameter("errorMessage");
if (errorMessage != null) {
session.setAttribute("errorMessage", errorMessage);
}
response.sendRedirect(request.getContextPath() + "/");
}
}
} | [
"goldsolace@gmail.com"
] | goldsolace@gmail.com |
c446ee7b0a1de6de3ada1716ba81cc233ea4f96a | 14f41054e0ee2d96b0a164b62c2dc676c3331a5a | /app/src/main/java/com/flhs/utils/DayPickerFragment.java | ce01e9c835e5787f85460d294275fe4266137a06 | [] | no_license | DrewGregory/AndroidFLHSApp | 167e84bfdd4dbae89e6a6bf49687971aa51b60ae | bb5e6617c93e09f0375db15b4c33419de50c58f2 | refs/heads/master | 2020-04-26T00:14:35.740747 | 2017-07-18T21:13:40 | 2017-07-18T21:13:40 | 27,749,293 | 2 | 2 | null | null | null | null | UTF-8 | Java | false | false | 1,995 | java | package com.flhs.utils;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import com.flhs.R;
/**
* Created by Drew Gregory on 9/1/2014.
*/
public class DayPickerFragment extends DialogFragment {
int selectedDay;
private DayPickerListener mDayPickerListener;
public interface DayPickerListener {
public void onDayPickPositiveClick(int DayNum);
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Please Pick Your Day.");
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
mDayPickerListener.onDayPickPositiveClick(selectedDay);
}
});
builder.setSingleChoiceItems(R.array.Days, -1, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
selectedDay = which + 1;
}
});
return builder.create();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
// Instantiate the NoticeDialogListener so we can send events to the host
mDayPickerListener = (DayPickerListener) activity;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(activity.toString()
+ " must implement DayPickerListener");
}
}
}
| [
"djgregny@gmail.com"
] | djgregny@gmail.com |
c2c941f525cf71bbe46b599935b199089c649f19 | 8bc1831a5e1c222d8e90e8c544f81497a25d3b7c | /beekeeper-integration-tests/src/test/java/com/expediagroup/beekeeper/integration/utils/MySqlTestUtils.java | 614b884a80a330dabd1b6ca7adecf82f72ed8871 | [
"Apache-2.0"
] | permissive | shermosa/beekeeper | c4e3c5b6fb87360608fa2feec833be0a4e5e34f7 | 7ef48f883efc411a56d1b1493482ac5c81f0de9a | refs/heads/main | 2023-07-08T02:56:36.514621 | 2021-08-09T16:39:48 | 2021-08-09T16:39:48 | 350,742,724 | 0 | 0 | Apache-2.0 | 2021-07-15T14:57:39 | 2021-03-23T14:28:12 | Java | UTF-8 | Java | false | false | 2,835 | java | /**
* Copyright (C) 2019-2020 Expedia, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.expediagroup.beekeeper.integration.utils;
import static java.lang.String.format;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
public class MySqlTestUtils {
private static final String DROP_TABLE = "DROP TABLE IF EXISTS %s.%s;";
private static final String SELECT_TABLE = "SELECT * FROM %s.%s %s;";
private static final String INSERT_TO_TABLE = "INSERT INTO %s.%s (%s) VALUES (%s);";
private final Connection connection;
public MySqlTestUtils(String jdbcUrl, String username, String password) throws SQLException {
connection = DriverManager.getConnection(jdbcUrl, username, password);
}
public void close() throws SQLException {
connection.close();
}
public void insertToTable(String database, String table, String fields, String values) throws SQLException {
connection.createStatement().executeUpdate(format(INSERT_TO_TABLE, database, table, fields, values));
}
public int getTableRowCount(String database, String table) throws SQLException {
return getTableRowCount(format(SELECT_TABLE, database, table, ""));
}
public int getTableRowCount(String database, String table, String additionalFilters) throws SQLException {
return getTableRowCount(format(SELECT_TABLE, database, table, additionalFilters));
}
private int getTableRowCount(String statement) throws SQLException {
ResultSet resultSet = getTableRows(statement);
resultSet.last();
int rowsInTable = resultSet.getRow();
return rowsInTable;
}
public ResultSet getTableRows(String database, String table, String additionalFilters) throws SQLException {
return getTableRows(format(SELECT_TABLE, database, table, additionalFilters));
}
public ResultSet getTableRows(String database, String table) throws SQLException {
return getTableRows(format(SELECT_TABLE, database, table, ""));
}
private ResultSet getTableRows(String statement) throws SQLException {
return connection.createStatement().executeQuery(statement);
}
public void dropTable(String database, String table) throws SQLException {
connection.createStatement().executeUpdate(format(DROP_TABLE, database, table));
}
}
| [
"noreply@github.com"
] | shermosa.noreply@github.com |
60aadfcfb2634732579934db1100f4671b42c5ca | 5b3892444fb26bbd43099841ef449e58bf382b05 | /ENotify/app/src/main/java/com/example/amitpradhan/enotify/DirectorHome.java | 8beb1d7bc71d61acfce4ddbaa41e6e4a8af5ad53 | [] | no_license | amitpirdhan7/eNotify | db07c692f6f94b73896237ef688b1cecc06ce3db | 4a3d8bed69c5b8b22b9be6624bdf8d7cded612d8 | refs/heads/master | 2021-05-04T10:56:27.162776 | 2016-10-01T11:48:10 | 2016-10-01T11:48:10 | 53,519,665 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,029 | java | package com.example.amitpradhan.enotify;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class DirectorHome extends ActionBarActivity
{
public final static String BRANCH = "com.example.amitpradhan.enotify.BRANCH";
Button button1,button2,button3,button4,button5;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_director_home);
button1=(Button)findViewById(R.id.cse);
button2=(Button)findViewById(R.id.it);
button3=(Button)findViewById(R.id.ec);
button4=(Button)findViewById(R.id.ele);
button5=(Button)findViewById(R.id.mec);
button1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent i=new Intent(getApplicationContext(),DirectorPost.class);
i.putExtra(BRANCH,"CSE");
startActivity(i);
}
});
button2.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent i=new Intent(getApplicationContext(),DirectorPost.class);
i.putExtra(BRANCH,"IT");
startActivity(i);
}
});
button3.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent i=new Intent(getApplicationContext(),DirectorPost.class);
i.putExtra(BRANCH,"ECE");
startActivity(i);
}
});
button4.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent i=new Intent(getApplicationContext(),DirectorPost.class);
i.putExtra(BRANCH,"ELE");
startActivity(i);
}
});
button5.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent i=new Intent(getApplicationContext(),DirectorPost.class);
i.putExtra(BRANCH,"MECH");
startActivity(i);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_director_home, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
/* if (id == R.id.action_settings) {
return true;
}*/
switch(id)
{
case R.id.action_profile:
Intent i=new Intent(getApplicationContext(),DirectorProfile.class);
startActivity(i);
return true;
case R.id.action_logout:
SharedPreferences sharedprefrence=getSharedPreferences("Profile", Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sharedprefrence.edit();
editor.clear();
editor.commit();
Intent j=new Intent(getApplicationContext(),login.class);
j.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
j.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startActivity(j);
return true;
}
return super.onOptionsItemSelected(item);
}
}
| [
"amitpirdhan7@gmail.com"
] | amitpirdhan7@gmail.com |
22825d60f507c35ec445e9b03bbac5f410b05abc | beadb393e1a142fa3fe637017f6281110ca95655 | /src/088_merge-sorted-array/smartbber.java | 1cccdacfc3565dda15392acdc998f70f68f6f448 | [
"Apache-2.0"
] | permissive | BerBai/LeetCode | 0ea0f668aa5989843b037b17a8956a8209306901 | a28188dae39f97c27728ec66093c62f4006a6c80 | refs/heads/master | 2023-05-24T22:42:13.314424 | 2023-05-13T12:34:23 | 2023-05-13T12:34:23 | 162,692,894 | 4 | 2 | Apache-2.0 | 2023-05-13T12:34:24 | 2018-12-21T09:14:51 | Java | UTF-8 | Java | false | false | 336 | java | class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int t = m + n - 1;
m--;
n--;
while(m >= 0 && n >= 0){
nums1[t--] = nums1[m] > nums2[n] ? nums1[m--] : nums2[n--];
}
while(n >= 0) {
nums1[t--] = nums2[n--];
}
}
} | [
"bai5775@outlook.com"
] | bai5775@outlook.com |
891d8d32a63bde2cf29d9939073933464fcb26a7 | ac2c79079e3c60c9e0928a3a5a2a6545c5ecd5ad | /library/src/main/java/com/lxj/xpopup/core/FullScreenDialog.java | 919d3574cacae4d85a8609e7925eb36de3ce3f6f | [
"Apache-2.0"
] | permissive | zkvvv/XPopup | 5788eb51aba1d1ac9a0453d92061b6053da6bf4e | 230b23af5c8f754ef6001e14b21c2c004b728cef | refs/heads/master | 2023-07-08T17:12:07.960301 | 2021-08-03T02:21:22 | 2021-08-03T02:21:22 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,019 | java | package com.lxj.xpopup.core;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import androidx.annotation.NonNull;
import com.lxj.xpopup.R;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.util.FuckRomUtils;
import com.lxj.xpopup.util.XPopupUtils;
/**
* 所有弹窗的宿主
*/
public class FullScreenDialog extends Dialog {
public FullScreenDialog(@NonNull Context context) {
super(context, R.style._XPopup_TransparentDialog);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getWindow() == null || contentView==null || contentView.popupInfo==null) return;
if (contentView.popupInfo.enableShowWhenAppBackground) {
if (Build.VERSION.SDK_INT >= 26) {
getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
} else {
getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
}
}
if(contentView.popupInfo.keepScreenOn){
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
getWindow().setBackgroundDrawable(null);
getWindow().getDecorView().setPadding(0, 0, 0, 0);
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE );
//设置全屏
int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
getWindow().getDecorView().setSystemUiVisibility(option);
//处理VIVO手机8.0以上系统部分机型的状态栏问题和弹窗下移问题
getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, Math.max(XPopupUtils.getAppHeight(getContext()),
XPopupUtils.getScreenHeight(getContext())));
if(isFuckVIVORoom()){
getWindow().getDecorView().setTranslationY(-XPopupUtils.getStatusBarHeight());
}
//remove status bar shadow
if (Build.VERSION.SDK_INT >= 19 && Build.VERSION.SDK_INT < 21) {
setWindowFlag(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, true);
}
if (Build.VERSION.SDK_INT >= 21) {
setWindowFlag(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, false);
getWindow().setStatusBarColor(Color.TRANSPARENT);
int navigationBarColor = getNavigationBarColor();
if(navigationBarColor!=0)getWindow().setNavigationBarColor(navigationBarColor);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); //尝试兼容部分手机上的状态栏空白问题
}
if(Build.VERSION.SDK_INT == 19){ //解决4.4上状态栏闪烁的问题
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
//隐藏导航栏
if (!contentView.popupInfo.hasNavigationBar) {
hideNavigationBar();
}
if(!contentView.popupInfo.isRequestFocus){
//不获取焦点
int flag = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
getWindow().setFlags(flag,flag);
}
//自动设置状态色调,亮色还是暗色
autoSetStatusBarMode();
setContentView(contentView);
}
private int getNavigationBarColor(){
return contentView.popupInfo.navigationBarColor==0 ? XPopup.getNavigationBarColor()
: contentView.popupInfo.navigationBarColor;
}
public boolean isFuckVIVORoom(){
//vivo的Y开头的8.0和8.1系统特殊(y91 y85 y97):dialog无法覆盖到状态栏,并且坐标系下移了一个状态栏的距离
boolean isYModel = android.os.Build.MODEL.contains("Y") || android.os.Build.MODEL.contains("y") ;
return FuckRomUtils.isVivo() && (Build.VERSION.SDK_INT == 26 || Build.VERSION.SDK_INT == 27) && isYModel;
}
public boolean isActivityStatusBarLightMode() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
View decorView = ((Activity) contentView.getContext()).getWindow().getDecorView();
int vis = decorView.getSystemUiVisibility();
return (vis & View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR) != 0;
}
return false;
}
public void setWindowFlag(final int bits, boolean on) {
WindowManager.LayoutParams winParams = getWindow().getAttributes();
if (on) {
winParams.flags |= bits;
} else {
winParams.flags &= ~bits;
}
getWindow().setAttributes(winParams);
}
/**
* 是否是亮色调状态栏
*
* @return
*/
public void autoSetStatusBarMode() {
//隐藏状态栏
if (!contentView.popupInfo.hasStatusBar) {
final ViewGroup decorView = (ViewGroup) getWindow().getDecorView();
final int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN|
View.SYSTEM_UI_FLAG_FULLSCREEN;
getWindow().getDecorView().setSystemUiVisibility(decorView.getSystemUiVisibility() | uiOptions);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
View decorView = getWindow().getDecorView();
int vis = decorView.getSystemUiVisibility();
boolean isLightMode = isActivityStatusBarLightMode();
if (isLightMode) {
vis |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
} else {
vis &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
}
decorView.setSystemUiVisibility(vis);
}
}
public void hideNavigationBar() {
final ViewGroup decorView = (ViewGroup) getWindow().getDecorView();
for (int i = 0, count = decorView.getChildCount(); i < count; i++) {
final View child = decorView.getChildAt(i);
final int id = child.getId();
if (id != View.NO_ID) {
String resourceEntryName = getResNameById(id);
if ("navigationBarBackground".equals(resourceEntryName)) {
child.setVisibility(View.INVISIBLE);
}
}
}
final int uiOptions =
// View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|
// View.SYSTEM_UI_FLAG_IMMERSIVE |
View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
// | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
// View.SYSTEM_UI_FLAG_FULLSCREEN |
;
decorView.setSystemUiVisibility(decorView.getSystemUiVisibility() | uiOptions);
}
private String getResNameById(int id) {
try {
return getContext().getResources().getResourceEntryName(id);
} catch (Exception ignore) {
return "";
}
}
BasePopupView contentView;
public FullScreenDialog setContent(BasePopupView view) {
if(view.getParent()!=null){
((ViewGroup)view.getParent()).removeView(view);
}
this.contentView = view;
return this;
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
if(isFuckVIVORoom()){ //VIVO的部分机型需要做特殊处理,Fuck
event.setLocation(event.getX(), event.getY()+XPopupUtils.getStatusBarHeight());
}
return super.dispatchTouchEvent(event);
}
}
| [
"16167479@qq.com"
] | 16167479@qq.com |
fcee7926b7b04dd7559ff9ea2b36d4c4d8bc4e89 | 1175c288aaa0539f31201bc12b1ef6ee76f2c137 | /zuul/src/main/java/com/plumblum/zuul/Hystrix/MyZuulFallbackProvider.java | dfa584bc7c5f75427e22296439bca9a3253cd495 | [] | no_license | chenplumblum/springcloud_demo_test | 7d52789a7222ff720d35921fbd8195d7ac5f84a6 | 56246037ad1f9be44c503c1a1d6e85e11ba0e4a7 | refs/heads/master | 2020-04-16T01:52:47.030854 | 2019-12-12T12:50:25 | 2019-12-12T12:50:25 | 165,188,740 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 810 | java | package com.plumblum.zuul.Hystrix;
import org.springframework.cloud.netflix.zuul.filters.route.ZuulFallbackProvider;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;
/**
* @Auther: cpb
* @Date: 2019/1/11 15:35
* @Description:
*/
//路由熔断,降级处理
//实现方式:一个指明熔断拦截哪个服务,一个定制返回内容。
//只支持服务级别的熔断,不支持某个url的熔断。
@Component
public class MyZuulFallbackProvider implements ZuulFallbackProvider {
//定义哪个route的熔断器
@Override
public String getRoute() {
return null;
}
//发生熔断时,提供怎么样的返回值
@Override
public ClientHttpResponse fallbackResponse() {
return null;
}
}
| [
"2573350997@qq.com"
] | 2573350997@qq.com |
65192ad3519afb08b3adb8960a0f30e5e0f292ac | b308232b5f9a1acd400fe15b45780e348048fccd | /Global/src/main/java/com/param/global/dao/IStateMasterDao.java | 8836a22765dbbe2843863f6fdd09ee9da78c9eaf | [] | no_license | PravatKumarPradhan/his | 2aae12f730b7d652b9590ef976b12443fc2c2afb | afb2b3df65c0bc1b1864afc1f958ca36a2562e3f | refs/heads/master | 2022-12-22T20:43:44.895342 | 2018-07-31T17:04:26 | 2018-07-31T17:04:26 | 143,041,254 | 1 | 0 | null | 2022-12-16T03:59:53 | 2018-07-31T16:43:36 | HTML | UTF-8 | Java | false | false | 1,234 | java | package com.param.global.dao;
import com.param.global.common.Response;
import com.param.global.dto.StateMasterDto;
import com.param.global.model.StateMaster;
import in.param.common.dao.IGenericDao;
import in.param.exception.ApplicationException;
@SuppressWarnings("rawtypes")
public interface IStateMasterDao extends IGenericDao<StateMaster, Integer>{
Response getStateByName(StateMasterDto stateMasterDto)throws ApplicationException;
Response addStateMaster(StateMasterDto stateMasterDto)throws ApplicationException;
Response getStateMasterList(StateMasterDto stateMasterDto) throws ApplicationException;
Response getStateByNameNotId(StateMasterDto stateMasterDto)throws ApplicationException;
Response getStateById(StateMasterDto stateMasterDto) throws ApplicationException;
Response updateStateStatus(StateMasterDto stateMasterDto)throws ApplicationException;
Response getActiveStateList() throws ApplicationException;
Response updateStateMaster(StateMasterDto stateMasterDto)throws ApplicationException;
Response getCount(StateMasterDto stateMasterDto)throws ApplicationException;
Response getStateByCountryId(StateMasterDto stateMasterDto) throws ApplicationException;
}
| [
"pkp751989@gmail.com"
] | pkp751989@gmail.com |
d771e53a03be7314f4bca8e8d62c3345ef0a04dd | 5e9e9fe2c4eb56d00d70e08f582f8fdcee99f6fd | /rpc/RpcHelper.java | 363985a061198e5fe3d49d953cc4ea3a78085704 | [] | no_license | yux1004/Jupiter | 6356fb5634b5503db487bce7c3a166d44d8e66ee | aaf5080ab223b2669c30b4ab2402d767e66a6edf | refs/heads/master | 2021-09-09T18:33:26.212419 | 2018-03-18T22:26:24 | 2018-03-18T22:26:24 | 125,773,326 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,549 | java | package rpc;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONObject;
public class RpcHelper { // Writes a JSONObject to http response.
public static void writeJsonObject(HttpServletResponse response, JSONObject obj) {
try {
response.setContentType("application/json");
response.addHeader("Access-Control-Allow-Origin", "*");
PrintWriter out = response.getWriter();
out.print(obj);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// Parses a JSONObject from http request.
public static JSONObject readJsonObject(HttpServletRequest request) {
StringBuilder sb = new StringBuilder();
try {
BufferedReader reader = request.getReader();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
return new JSONObject(sb.toString());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
// Writes a JSONArray to http response.
public static void writeJsonArray(HttpServletResponse response, JSONArray array) {
response.setContentType("application/json");
response.addHeader("Access-Control-Allow-Origin", "*");
PrintWriter out;
try {
out = response.getWriter();
out.print(array);
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| [
"yux1004@gmail.com"
] | yux1004@gmail.com |
9418dab8aa572cf18f497bd18bfaaf41252be272 | bfc91558c498f7af7be397e6232f91bcbee12bfa | /barrage-spring/src/test/java/barrage/demo/serviceImpl/Id2LoginNameServiceImplTest.java | de3a944f163b59f675fa7ffa87dffef76aba7457 | [] | no_license | TomShiDi/barrage_website | 93291cf4e424865ac931fc98c9e0c09af0532b98 | ad63a1b4d8d8c3afbcf7ab0b4d8e7eefb4a8eede | refs/heads/master | 2022-07-19T00:08:07.589847 | 2022-07-14T10:11:04 | 2022-07-14T10:11:04 | 231,613,775 | 1 | 2 | null | 2022-07-14T10:11:04 | 2020-01-03T15:21:41 | CSS | UTF-8 | Java | false | false | 1,324 | java | package barrage.demo.serviceImpl;
import barrage.demo.entity.UseridToLoginname;
import barrage.demo.service.UseridToLoginNameService;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class Id2LoginNameServiceImplTest {
@Autowired
private UseridToLoginNameService useridToLoginNameService;
@Test
public void findByUserId() {
UseridToLoginname useridToLoginname = useridToLoginNameService.findByUserId(1);
Assert.assertNotNull(useridToLoginname);
}
@Test
public void findByLoginname() {
UseridToLoginname useridToLoginname = useridToLoginNameService.findByLoginname("TomShiDi");
Assert.assertNotNull(useridToLoginname);
}
@Test
public void save() {
UseridToLoginname useridToLoginname = new UseridToLoginname();
useridToLoginname.setLoginName("TomShiDi");
useridToLoginname.setUserId(1);
UseridToLoginname result = useridToLoginNameService.save(useridToLoginname);
Assert.assertNotNull(result);
}
} | [
"1341109792@qq.com"
] | 1341109792@qq.com |
391268d771e4d3ec3c9d3036590c99b202dcb988 | 2aaafb6c93f3317d60b6a570673b40cbabb85d75 | /src/test/DummyController.java | 838dd97da41b1d4855ce9788876990b9a7029554 | [] | no_license | brydr/loop-mania | 9857066452513b8860ad00ca6b32b42c35b75b2f | 1054107bf09cfcbc1868aa4e5928b3e86c7c3999 | refs/heads/master | 2023-08-28T21:20:55.029536 | 2021-08-01T21:38:47 | 2021-08-01T21:38:47 | 422,454,480 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 400 | java | package test;
import unsw.loopmania.Item;
import unsw.loopmania.LoopManiaWorldController;
public class DummyController extends LoopManiaWorldController {
// A dummy controller for testing, required for many things since the backend
// must interact with the front end when getting items
@Override
public void onLoad(Item item) {
// Stub for frontend processing for tests only
return;
}
}
| [
"dong.2000@hotmail.com"
] | dong.2000@hotmail.com |
abfa31510bb36d8030ae603c6fff63632b6f5496 | 00f0082f9fdd36367fa156722baf54b4015dad5a | /src/baekAlgoTest/printN/PrintN.java | 411eb6f6303c357fb833dce5876ac822e69c9c82 | [] | no_license | vltlrpdla/gather-test-algorithm | a23586245fdbf90472c0a8d431ca5c56293c0516 | f1d2208e0f6b0a822abb70a8aca1643cd9cb50ef | refs/heads/master | 2021-07-24T18:34:29.608444 | 2018-07-25T13:58:05 | 2018-07-25T13:58:05 | 133,042,599 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 307 | java | package baekAlgoTest.printN;
import java.util.*;
public class PrintN {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scn = new Scanner(System.in);
int input = scn.nextInt();
for ( int i = 0 ; i < input ; i ++){
System.out.println(i + 1);
}
}
}
| [
"vltlrpdla@hanmail.net"
] | vltlrpdla@hanmail.net |
766924be229064bdafd3eeca83ebbdb3a6279f65 | bf2966abae57885c29e70852243a22abc8ba8eb0 | /aws-java-sdk-snowball/src/main/java/com/amazonaws/services/snowball/model/transform/ShipmentMarshaller.java | 672a1949334ecf8ea402e682f619ece548ff8acc | [
"Apache-2.0"
] | permissive | kmbotts/aws-sdk-java | ae20b3244131d52b9687eb026b9c620da8b49935 | 388f6427e00fb1c2f211abda5bad3a75d29eef62 | refs/heads/master | 2021-12-23T14:39:26.369661 | 2021-07-26T20:09:07 | 2021-07-26T20:09:07 | 246,296,939 | 0 | 0 | Apache-2.0 | 2020-03-10T12:37:34 | 2020-03-10T12:37:33 | null | UTF-8 | Java | false | false | 2,204 | java | /*
* Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.snowball.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.snowball.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* ShipmentMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class ShipmentMarshaller {
private static final MarshallingInfo<String> STATUS_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("Status").build();
private static final MarshallingInfo<String> TRACKINGNUMBER_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("TrackingNumber").build();
private static final ShipmentMarshaller instance = new ShipmentMarshaller();
public static ShipmentMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(Shipment shipment, ProtocolMarshaller protocolMarshaller) {
if (shipment == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(shipment.getStatus(), STATUS_BINDING);
protocolMarshaller.marshall(shipment.getTrackingNumber(), TRACKINGNUMBER_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| [
""
] | |
1728eb91f62d9da5df92e1a8cf0f7546b9b2e843 | ab6488da74c3bcfbf3f0d47ddab69aa8a874ed9f | /OracleJDBC/src/oracle/jdbc/driver/PlsqlIndexTableAccessor.java | 99e93f7a6d2e9d04ff7640bd3002919bb25d2020 | [] | no_license | catkins10/ora-jdbc-source | ee60e9cddcb2e6a70235b50aff407e49a9bf985d | 8a8331bc7112ecd8dfcf97afe9d27cb9c30e8b0d | refs/heads/master | 2021-05-28T17:43:09.755927 | 2011-01-05T06:50:36 | 2011-01-05T06:50:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,741 | java | package oracle.jdbc.driver;
import java.math.BigDecimal;
import java.sql.SQLException;
import oracle.sql.CHAR;
import oracle.sql.CharacterSet;
import oracle.sql.Datum;
import oracle.sql.NUMBER;
class PlsqlIndexTableAccessor extends Accessor {
int elementInternalType;
int maxNumberOfElements;
int elementMaxLen;
int ibtValueIndex;
int ibtIndicatorIndex;
int ibtLengthIndex;
int ibtMetaIndex;
int ibtByteLength;
int ibtCharLength;
PlsqlIndexTableAccessor(OracleStatement stmt, int elemSqlType, int elemInternalType,
int elemMaxLen, int maxNumOfElements, short form, boolean forBind) throws SQLException {
init(stmt, 998, 998, form, forBind);
this.elementInternalType = elemInternalType;
this.maxNumberOfElements = maxNumOfElements;
this.elementMaxLen = elemMaxLen;
initForDataAccess(elemSqlType, elemMaxLen, null);
}
void initForDataAccess(int external_type, int max_len, String typeName) throws SQLException {
if (external_type != 0) {
this.externalType = external_type;
}
switch (this.elementInternalType) {
case 1:
case 96:
this.internalTypeMaxLength = 2000;
this.elementMaxLen = ((max_len == 0 ? this.internalTypeMaxLength : max_len) + 1);
this.ibtCharLength = (this.elementMaxLen * this.maxNumberOfElements);
this.elementInternalType = 9;
break;
case 6:
this.internalTypeMaxLength = 21;
this.elementMaxLen = (this.internalTypeMaxLength + 1);
this.ibtByteLength = (this.elementMaxLen * this.maxNumberOfElements);
break;
default:
DatabaseError.throwSqlException(97);
}
}
Object[] getPlsqlIndexTable(int currentRow) throws SQLException {
Object[] result = null;
short[] ibtBindIndicators = this.statement.ibtBindIndicators;
int actualElements = (ibtBindIndicators[(this.ibtMetaIndex + 4)] >> 16)
+ (ibtBindIndicators[(this.ibtMetaIndex + 5)] & 0xFFFF);
int offset = this.ibtValueIndex;
switch (this.elementInternalType) {
case 9:
result = new String[actualElements];
char[] ibtBindChars = this.statement.ibtBindChars;
for (int i = 0; i < actualElements; i++) {
if (ibtBindIndicators[(this.ibtIndicatorIndex + i)] == -1) {
result[i] = null;
} else {
result[i] = new String(ibtBindChars, offset + 1, ibtBindChars[offset] >> '\001');
}
offset += this.elementMaxLen;
}
break;
case 6:
result = new BigDecimal[actualElements];
byte[] ibtBindBytes = this.statement.ibtBindBytes;
for (int i = 0; i < actualElements; i++) {
if (ibtBindIndicators[(this.ibtIndicatorIndex + i)] == -1) {
result[i] = null;
} else {
int len = ibtBindBytes[offset];
byte[] val = new byte[len];
System.arraycopy(ibtBindBytes, offset + 1, val, 0, len);
result[i] = oracle.sql.NUMBER.toBigDecimal(val);
}
offset += this.elementMaxLen;
}
break;
default:
DatabaseError.throwSqlException(97);
}
return result;
}
Datum[] getOraclePlsqlIndexTable(int currentRow) throws SQLException {
Datum[] result = null;
short[] ibtBindIndicators = this.statement.ibtBindIndicators;
int actualElements = (ibtBindIndicators[(this.ibtMetaIndex + 4)] >> 16)
+ (ibtBindIndicators[(this.ibtMetaIndex + 5)] & 0xFFFF);
int offset = this.ibtValueIndex;
switch (this.elementInternalType) {
case 9:
result = new CHAR[actualElements];
CharacterSet charset = CharacterSet.make(2000);
char[] ibtBindChars = this.statement.ibtBindChars;
for (int i = 0; i < actualElements; i++) {
if (ibtBindIndicators[(this.ibtIndicatorIndex + i)] == -1) {
result[i] = null;
} else {
int len = ibtBindChars[offset];
byte[] b = new byte[len];
DBConversion.javaCharsToUcs2Bytes(ibtBindChars, offset + 1, b, 0, len >> 1);
result[i] = new CHAR(b, charset);
}
offset += this.elementMaxLen;
}
break;
case 6:
result = new NUMBER[actualElements];
byte[] ibtBindBytes = this.statement.ibtBindBytes;
for (int i = 0; i < actualElements; i++) {
if (ibtBindIndicators[(this.ibtIndicatorIndex + i)] == -1) {
result[i] = null;
} else {
int len = ibtBindBytes[offset];
byte[] val = new byte[len];
System.arraycopy(ibtBindBytes, offset + 1, val, 0, len);
result[i] = new NUMBER(val);
}
offset += this.elementMaxLen;
}
break;
default:
DatabaseError.throwSqlException(97);
}
return result;
}
}
/*
* Location: D:\oracle\product\10.2.0\client_1\jdbc\lib\ojdbc14_g.jar Qualified Name:
* oracle.jdbc.driver.PlsqlIndexTableAccessor JD-Core Version: 0.6.0
*/ | [
"a2903214@c4c818cb-000b-9e5c-3cc0-fab482924643"
] | a2903214@c4c818cb-000b-9e5c-3cc0-fab482924643 |
c08e5e0d3949257a7ef31e32cd457acd3103d7b8 | 043629e33d84755c527352f5c29ec62a040cfca3 | /src/multipleBlock/Algorithm.java | 65111a650fdaa545f3e50942a97a51c2fc33bd5a | [] | no_license | yzlixinyi/ggsddu | a5965268e1e761cf55233a8b58a75e4d29403355 | eb4f8c09d8b499463b0df4ab4d94f251845e3fe4 | refs/heads/master | 2023-07-18T16:29:47.855376 | 2021-09-25T12:42:11 | 2021-09-25T12:42:11 | 410,266,323 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 136 | java | package multipleBlock;
import java.util.List;
public interface Algorithm {
public List<Pick> generateRoute(WarehouseInfo info);
}
| [
"yzlixinyi@163.com"
] | yzlixinyi@163.com |
e6fbf13fd3ba04445e3bddd9c5bac3c40e94985f | 6f5bac6a37af7c88625bfc273a124682c6245ae4 | /lib_shortvideo/src/main/java/com/gh/qiniushortvideo/activity/WebDisplayActivity.java | b41044f558c273962a0d75301e2552394786c565 | [] | no_license | fangyouhui/Android_Native | 3a23b9b3957c37f8d39e8a061be5d0ca79239f69 | 3c583e376f0c08428ef9ff3a47a9b9184c56c5e2 | refs/heads/master | 2023-04-21T01:31:13.398744 | 2021-05-12T07:44:45 | 2021-05-12T07:44:45 | 309,220,375 | 4 | 4 | null | 2020-12-27T12:37:02 | 2020-11-02T00:46:42 | Java | UTF-8 | Java | false | false | 2,819 | java | package com.gh.qiniushortvideo.activity;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import com.gh.qiniushortvideo.R;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
/**
* 功能列表模块,展示七牛短视频支持的功能列表
*/
public class WebDisplayActivity extends AppCompatActivity {
public static final String URL = "web_url";
private WebView mWebView;
private ProgressBar mLoadingProgressbar;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_function_list);
mWebView = findViewById(R.id.function_list_webview);
mLoadingProgressbar = findViewById(R.id.loading_progress);
String url = getIntent().getStringExtra(URL);
WebSettings webSettings = mWebView.getSettings();
webSettings.setSupportZoom(true);
webSettings.setBuiltInZoomControls(true);
webSettings.setDisplayZoomControls(false);
webSettings.setUseWideViewPort(true); //将图片调整到适合 webview 的大小
webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
webSettings.setJavaScriptEnabled(true);
webSettings.setBlockNetworkImage(false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
webSettings.setMixedContentMode(android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
}
mWebView.setWebViewClient(new WebViewClient() {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
mLoadingProgressbar.setVisibility(View.VISIBLE);
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
mLoadingProgressbar.setVisibility(View.GONE);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url); // 强制在当前 WebView 中加载 url
return true;
}
});
mWebView.loadUrl(url);
}
@Override
protected void onResume() {
super.onResume();
mWebView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mWebView.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
mWebView.destroy();
mWebView = null;
}
}
| [
"1209342184@qq.com"
] | 1209342184@qq.com |
0d1af8ab130f74a1469fedf5851c533b5df5b9bf | 6fe987dc36c87268f2c4c717dc74fc569976be89 | /src/main/java/com/jwtsecurity/SpringBootHelloWorldApplication.java | 275d4d436309e62ba3696d064088a212e65cb6dd | [] | no_license | ShunchiZhou/Marlabs | 39c8ba934e8113170e2448484df89586e4156b6c | 2183864f6755008720b8699a4e5591fc9ce14905 | refs/heads/master | 2023-01-04T12:53:47.808339 | 2020-10-26T17:14:20 | 2020-10-26T17:14:20 | 302,079,056 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 334 | java | package com.jwtsecurity;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootHelloWorldApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootHelloWorldApplication.class, args);
}
} | [
"abc@example.com"
] | abc@example.com |
45473b3c691aa45cfe70259b900815c1d0806cab | 117a24dc265bbc965dc4f8b14ce4399b8e0f8ba6 | /src/main/java/OldAttemptLearning/shirleyisnotageek/SubsetsDuplicate.java | b29a7935acc3d27e62315c17685bdc4b8b17002b | [] | no_license | sureshrmdec/Preparation26EatSleepDrinkCode | e240393eabdc3343bb1165d5c432217f085aa353 | aa5b81907205f9d435835e2150100e8f53027212 | refs/heads/master | 2021-09-29T14:28:24.691090 | 2018-11-25T13:52:43 | 2018-11-25T13:52:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,844 | java | package OldAttemptLearning.shirleyisnotageek;
import java.util.*;
/**
* Created by hadoop on 20/1/18.
*/
/*
"Given a collection of integers S, return all possible subsets."
When it comes to problems like this, the question you should always ask yourself is: are there any duplicates?
The answer is always yes! And here comes our Subsets II.
It is defined as a backtracking problem.
Basically, given a set S with duplicates [1,2,2]
add each element into the list, then remove it after add the list to the final and add the next one.
To avoid duplicate lists, first condition is definitely num[i] != num[i - 1]. However, we still want to add i-th element if (i - 1)-th element is in the list as well as the condition where i-th element is the first element in the list.
[1] -> [1,2] -> [1,2,2] -> [1,2] -> [1] -> [1, 2], duplicates, will not add -> [1] -> [] -> [2] -> [2,2] -> [2] ->[] -> [2], duplicates -> [].
*/
public class SubsetsDuplicate {
public class Solution {
public ArrayList<List<Integer>> subsetsWithDup(int[] num) {
ArrayList<List<Integer>> rst = new ArrayList<List<Integer>>();
if (num == null || num.length == 0)
return rst;
ArrayList<Integer> list = new ArrayList<Integer>();
Arrays.sort(num);
SetHelper(rst, list, num, 0);
return rst;
}
private void SetHelper(ArrayList<List<Integer>> rst, ArrayList<Integer> list, int[] num, int start)
{
rst.add(new ArrayList(list));
for (int i = start; i < num.length; i++)
{
if (i != start && num[i] == num[i - 1])
continue;
list.add(num[i]);
SetHelper(rst, list, num, i + 1);
list.remove(list.size() - 1);
}
}
}
}
| [
"rahuja@twitter.com"
] | rahuja@twitter.com |
87680cbc6f86900cc5b45d447dad77e9c2203edd | 0435f4362c300a9a89799ecf2895a92bd89d8130 | /src/main/java/com/alucard/config/LoggingConfiguration.java | 5f391817157945047667e5dbad84bf78c0772b5e | [] | no_license | AlucardxTepes/JBlog | dff91e1c87277cdb2914ca5de27ee7c90ec61f9d | 8d53e7ace15675b5a5a9f651c558d0306b95fb94 | refs/heads/master | 2020-03-22T13:46:38.756742 | 2018-07-08T13:26:13 | 2018-07-08T13:26:13 | 140,131,144 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,574 | java | package com.alucard.config;
import java.net.InetSocketAddress;
import java.util.Iterator;
import io.github.jhipster.config.JHipsterProperties;
import ch.qos.logback.classic.AsyncAppender;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.boolex.OnMarkerEvaluator;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.LoggerContextListener;
import ch.qos.logback.core.Appender;
import ch.qos.logback.core.filter.EvaluatorFilter;
import ch.qos.logback.core.spi.ContextAwareBase;
import ch.qos.logback.core.spi.FilterReply;
import net.logstash.logback.appender.LogstashTcpSocketAppender;
import net.logstash.logback.encoder.LogstashEncoder;
import net.logstash.logback.stacktrace.ShortenedThrowableConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
@Configuration
public class LoggingConfiguration {
private static final String LOGSTASH_APPENDER_NAME = "LOGSTASH";
private static final String ASYNC_LOGSTASH_APPENDER_NAME = "ASYNC_LOGSTASH";
private final Logger log = LoggerFactory.getLogger(LoggingConfiguration.class);
private LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
private final String appName;
private final String serverPort;
private final JHipsterProperties jHipsterProperties;
public LoggingConfiguration(@Value("${spring.application.name}") String appName, @Value("${server.port}") String serverPort,
JHipsterProperties jHipsterProperties) {
this.appName = appName;
this.serverPort = serverPort;
this.jHipsterProperties = jHipsterProperties;
if (jHipsterProperties.getLogging().getLogstash().isEnabled()) {
addLogstashAppender(context);
addContextListener(context);
}
if (jHipsterProperties.getMetrics().getLogs().isEnabled()) {
setMetricsMarkerLogbackFilter(context);
}
}
private void addContextListener(LoggerContext context) {
LogbackLoggerContextListener loggerContextListener = new LogbackLoggerContextListener();
loggerContextListener.setContext(context);
context.addListener(loggerContextListener);
}
private void addLogstashAppender(LoggerContext context) {
log.info("Initializing Logstash logging");
LogstashTcpSocketAppender logstashAppender = new LogstashTcpSocketAppender();
logstashAppender.setName(LOGSTASH_APPENDER_NAME);
logstashAppender.setContext(context);
String customFields = "{\"app_name\":\"" + appName + "\",\"app_port\":\"" + serverPort + "\"}";
// More documentation is available at: https://github.com/logstash/logstash-logback-encoder
LogstashEncoder logstashEncoder = new LogstashEncoder();
// Set the Logstash appender config from JHipster properties
logstashEncoder.setCustomFields(customFields);
// Set the Logstash appender config from JHipster properties
logstashAppender.addDestinations(new InetSocketAddress(jHipsterProperties.getLogging().getLogstash().getHost(), jHipsterProperties.getLogging().getLogstash().getPort()));
ShortenedThrowableConverter throwableConverter = new ShortenedThrowableConverter();
throwableConverter.setRootCauseFirst(true);
logstashEncoder.setThrowableConverter(throwableConverter);
logstashEncoder.setCustomFields(customFields);
logstashAppender.setEncoder(logstashEncoder);
logstashAppender.start();
// Wrap the appender in an Async appender for performance
AsyncAppender asyncLogstashAppender = new AsyncAppender();
asyncLogstashAppender.setContext(context);
asyncLogstashAppender.setName(ASYNC_LOGSTASH_APPENDER_NAME);
asyncLogstashAppender.setQueueSize(jHipsterProperties.getLogging().getLogstash().getQueueSize());
asyncLogstashAppender.addAppender(logstashAppender);
asyncLogstashAppender.start();
context.getLogger("ROOT").addAppender(asyncLogstashAppender);
}
// Configure a log filter to remove "metrics" logs from all appenders except the "LOGSTASH" appender
private void setMetricsMarkerLogbackFilter(LoggerContext context) {
log.info("Filtering metrics logs from all appenders except the {} appender", LOGSTASH_APPENDER_NAME);
OnMarkerEvaluator onMarkerMetricsEvaluator = new OnMarkerEvaluator();
onMarkerMetricsEvaluator.setContext(context);
onMarkerMetricsEvaluator.addMarker("metrics");
onMarkerMetricsEvaluator.start();
EvaluatorFilter<ILoggingEvent> metricsFilter = new EvaluatorFilter<>();
metricsFilter.setContext(context);
metricsFilter.setEvaluator(onMarkerMetricsEvaluator);
metricsFilter.setOnMatch(FilterReply.DENY);
metricsFilter.start();
for (ch.qos.logback.classic.Logger logger : context.getLoggerList()) {
for (Iterator<Appender<ILoggingEvent>> it = logger.iteratorForAppenders(); it.hasNext();) {
Appender<ILoggingEvent> appender = it.next();
if (!appender.getName().equals(ASYNC_LOGSTASH_APPENDER_NAME)) {
log.debug("Filter metrics logs from the {} appender", appender.getName());
appender.setContext(context);
appender.addFilter(metricsFilter);
appender.start();
}
}
}
}
/**
* Logback configuration is achieved by configuration file and API.
* When configuration file change is detected, the configuration is reset.
* This listener ensures that the programmatic configuration is also re-applied after reset.
*/
class LogbackLoggerContextListener extends ContextAwareBase implements LoggerContextListener {
@Override
public boolean isResetResistant() {
return true;
}
@Override
public void onStart(LoggerContext context) {
addLogstashAppender(context);
}
@Override
public void onReset(LoggerContext context) {
addLogstashAppender(context);
}
@Override
public void onStop(LoggerContext context) {
// Nothing to do.
}
@Override
public void onLevelChange(ch.qos.logback.classic.Logger logger, Level level) {
// Nothing to do.
}
}
}
| [
"alucard.557@gmail.com"
] | alucard.557@gmail.com |
1e1c9c70205734b2c309c142923faa790ea33c5d | cbaeffa0cab3b8cb849dd6348aa163042b037fb5 | /Alpha/Early Code/Old Code/Processing/libraries/G4P/src/g4p_controls/GEditableTextControl.java | d7a4f061951f121877d0275239bd8ebb9087bce2 | [] | no_license | k-sheridan/HighlyAutonomousAerialReconnaissanceRobot | 208c7204db60bbe3500929cf3389cb2ba3db1d88 | 0798a73586c8191cf751f55c01a82f1e4673722e | refs/heads/master | 2022-02-22T21:49:55.408031 | 2019-09-14T21:39:14 | 2019-09-14T21:39:14 | 68,154,334 | 7 | 6 | null | null | null | null | UTF-8 | Java | false | false | 22,445 | java | /*
Part of the GUI for Processing library
http://www.lagers.org.uk/g4p/index.html
http://gui4processing.googlecode.com/svn/trunk/
Copyright (c) 2013 Peter Lager
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General
Public License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA
*/
package g4p_controls;
import g4p_controls.StyledString.TextLayoutHitInfo;
import g4p_controls.StyledString.TextLayoutInfo;
import java.awt.Font;
import java.awt.font.TextAttribute;
import java.awt.font.TextHitInfo;
import java.awt.geom.GeneralPath;
import java.util.LinkedList;
import processing.core.PApplet;
import processing.event.KeyEvent;
/**
*
* This class is the basis for the GTextField and GTextArea classes.
*
* @author Peter Lager
*
*/
public abstract class GEditableTextControl extends GTextBase {
protected static float HORZ_SCROLL_RATE = 4f;
protected static float VERT_SCROLL_RATE = 8;
GTabManager tabManager = null;
protected StyledString defaultText = null;
// The width to break a line
protected int wrapWidth = Integer.MAX_VALUE;
// The typing area
protected float tx,ty,th,tw;
// Offset to display area
protected float ptx, pty;
// Caret position
protected float caretX, caretY;
protected boolean keepCursorInView = false;
protected GeneralPath gpTextDisplayArea;
// Used for identifying selection and cursor position
protected TextLayoutHitInfo startTLHI = new TextLayoutHitInfo();
protected TextLayoutHitInfo endTLHI = new TextLayoutHitInfo();
// The scrollbars available
protected final int scrollbarPolicy;
protected boolean autoHide = false;
protected GScrollbar hsb, vsb;
protected GTimer caretFlasher;
protected boolean showCaret = false;
// Stuff to manage text selections
protected int endChar = -1, startChar = -1, pos = endChar, nbr = 0, adjust = 0;
protected boolean textChanged = false, selectionChanged = false;
/* Is the component enabled to generate mouse and keyboard events */
boolean textEditEnabled = true;
public GEditableTextControl(PApplet theApplet, float p0, float p1, float p2, float p3, int scrollbars) {
super(theApplet, p0, p1, p2, p3);
scrollbarPolicy = scrollbars;
autoHide = ((scrollbars & SCROLLBARS_AUTOHIDE) == SCROLLBARS_AUTOHIDE);
caretFlasher = new GTimer(theApplet, this, "flashCaret", 400);
caretFlasher.start();
opaque = true;
cursorOver = TEXT;
}
/**
* Give up focus but if the text is only made from spaces
* then set it to null text. <br>
* Fire focus events for the GTextField and GTextArea controls
*/
protected void loseFocus(GAbstractControl grabber){
// If this control has focus then Fire a lost focus event
if(focusIsWith == this)
fireEvent(this, GEvent.LOST_FOCUS);
// Process mouse-over cursor
if(cursorIsOver == this)
cursorIsOver = null;
focusIsWith = grabber;
// If only blank text clear it out allowing default text (if any) to be displayed
if(stext.length() > 0){
int tl = stext.getPlainText().trim().length();
if(tl == 0)
stext = new StyledString("", wrapWidth);
}
keepCursorInView = true;
bufferInvalid = true;
}
/**
* Give the focus to this component but only after allowing the
* current component with focus to release it gracefully. <br>
* Always cancel the keyFocusIsWith irrespective of the component
* type.
* Fire focus events for the GTextField and GTextArea controls
*/
protected void takeFocus(){
// If focus is not yet with this control fire a gets focus event
if(focusIsWith != this){
// If the focus is with another control then tell
// that control to lose focus
if(focusIsWith != null)
focusIsWith.loseFocus(this);
fireEvent(this, GEvent.GETS_FOCUS);
}
focusIsWith = this;
}
/**
* Determines whether this component is to have focus or not. <br>
* Fire focus events for the GTextField and GTextArea controls
* @param focus
*/
public void setFocus(boolean focus){
if(!focus){
loseFocus(null);
return;
}
// Make sure we have some text
if(focusIsWith != this){
dragging = false;
if(stext == null || stext.length() == 0)
stext = new StyledString(" ", wrapWidth);
// text = stext.getPlainText();
LinkedList<TextLayoutInfo> lines = stext.getLines(buffer.g2);
startTLHI = new TextLayoutHitInfo(lines.getFirst(), null);
startTLHI.thi = startTLHI.tli.layout.getNextLeftHit(1);
endTLHI = new TextLayoutHitInfo(lines.getLast(), null);
int lastChar = endTLHI.tli.layout.getCharacterCount();
endTLHI.thi = startTLHI.tli.layout.getNextRightHit(lastChar-1);
calculateCaretPos(endTLHI);
bufferInvalid = true;
}
keepCursorInView = true;
takeFocus();
}
/**
* Set the default text for this control. If provided this text will be
* displayed in italic whenever it is empty.
* @param dtext
*/
public void setDefaultText(String dtext){
if(dtext == null || dtext.length() == 0)
defaultText = null;
else {
defaultText = new StyledString(dtext, wrapWidth);
defaultText.addAttribute(G4P.POSTURE, G4P.POSTURE_OBLIQUE);
}
bufferInvalid = true;
}
/**
* @return the wrapWidth
*/
public int getWrapWidth() {
return wrapWidth;
}
/**
* @param wrapWidth the wrapWidth to set
*/
public void setWrapWidth(int wrapWidth) {
this.wrapWidth = wrapWidth;
}
/**
* Get the default text for this control
* @return the default text without styling
*/
public String getDefaultText(){
return defaultText.getPlainText();
}
/**
* Get the text in the control
* @return the text without styling
*/
public String getText(){
return stext.getPlainText();
}
/**
* Get the styled text in the control
* @return the text with styling
*/
public StyledString getStyledText(){
return stext;
}
/**
* Adds the text attribute to a range of characters on a particular line. If charEnd
* is past the EOL then the attribute will be applied to the end-of-line.
*
* @param attr the text attribute to add
* @param value value of the text attribute
* @param lineNo the line number (starts at 0)
* @param charStart the position of the first character to apply the attribute
* @param charEnd the position after the last character to apply the attribute
*/
public void addStyle(TextAttribute attr, Object value, int charStart, int charEnd){
if(stext != null){
stext.addAttribute(attr, value, charStart, charEnd);
bufferInvalid = true;
}
}
/**
* Adds the text attribute to a range of characters on a particular line. If charEnd
* is past the EOL then the attribute will be applied to the end-of-line.
*
* @param attr the text attribute to add
* @param value value of the text attribute
* @param lineNo the line number (starts at 0)
* @param charStart the position of the first character to apply the attribute
* @param charEnd the position after the last character to apply the attribute
*/
public void addStyle(TextAttribute attr, Object value){
if(stext != null){
stext.addAttribute(attr, value);
bufferInvalid = true;
}
}
/**
* Clears all text attribute from a range of characters starting at position
* charStart and ending with the character preceding charEnd.
*
*
* @param charStart the position of the first character to apply the attribute
* @param charEnd the position after the last character to apply the attribute
*/
public void clearStyles(int charStart, int charEnd){
if(stext != null) {
stext.clearAttributes(charStart, charEnd);
bufferInvalid = true;
}
}
/**
* Clear all styles from the entire text.
*/
public void clearStyles(){
if(stext != null){
stext.clearAttributes();
bufferInvalid = true;
}
}
/**
* Set the font for this control.
* @param font
*/
public void setFont(Font font) {
if(font != null && font != localFont && buffer != null){
localFont = font;
buffer.g2.setFont(localFont);
stext.getLines(buffer.g2);
ptx = pty = 0;
setScrollbarValues(ptx, pty);
bufferInvalid = true;
}
}
// SELECTED / HIGHLIGHTED TEXT
/**
* Get the text that has been selected (highlighted) by the user. <br>
* @return the selected text without styling
*/
public String getSelectedText(){
if(!hasSelection())
return "";
TextLayoutHitInfo startSelTLHI;
TextLayoutHitInfo endSelTLHI;
if(endTLHI.compareTo(startTLHI) == -1){
startSelTLHI = endTLHI;
endSelTLHI = startTLHI;
}
else {
startSelTLHI = startTLHI;
endSelTLHI = endTLHI;
}
int ss = startSelTLHI.tli.startCharIndex + startSelTLHI.thi.getInsertionIndex();
int ee = endSelTLHI.tli.startCharIndex + endSelTLHI.thi.getInsertionIndex();
String s = stext.getPlainText().substring(ss, ee);
return s;
}
/**
* If some text has been selected then set the style. If there is no selection then
* the text is unchanged.
*
*
* @param style
*/
public void setSelectedTextStyle(TextAttribute style, Object value){
if(!hasSelection())
return;
TextLayoutHitInfo startSelTLHI;
TextLayoutHitInfo endSelTLHI;
if(endTLHI.compareTo(startTLHI) == -1){
startSelTLHI = endTLHI;
endSelTLHI = startTLHI;
}
else {
startSelTLHI = startTLHI;
endSelTLHI = endTLHI;
}
int ss = startSelTLHI.tli.startCharIndex + startSelTLHI.thi.getInsertionIndex();
int ee = endSelTLHI.tli.startCharIndex + endSelTLHI.thi.getInsertionIndex();
stext.addAttribute(style, value, ss, ee);
// We have modified the text style so the end of the selection may have
// moved, so it needs to be recalculated. The start will be unaffected.
stext.getLines(buffer.g2);
endSelTLHI.tli = stext.getTLIforCharNo(ee);
int cn = ee - endSelTLHI.tli.startCharIndex;
if(cn == 0) // start of line
endSelTLHI.thi = endSelTLHI.tli.layout.getNextLeftHit(1);
else
endSelTLHI.thi = endSelTLHI.tli.layout.getNextRightHit(cn-1);
bufferInvalid = true;
}
/**
* Clear any styles applied to the selected text.
*/
public void clearSelectionStyle(){
if(!hasSelection())
return;
TextLayoutHitInfo startSelTLHI;
TextLayoutHitInfo endSelTLHI;
if(endTLHI.compareTo(startTLHI) == -1){
startSelTLHI = endTLHI;
endSelTLHI = startTLHI;
}
else {
startSelTLHI = startTLHI;
endSelTLHI = endTLHI;
}
int ss = startSelTLHI.tli.startCharIndex + startSelTLHI.thi.getInsertionIndex();
int ee = endSelTLHI.tli.startCharIndex + endSelTLHI.thi.getInsertionIndex();
stext.clearAttributes(ss, ee);
// We have modified the text style so the end of the selection may have
// moved, so it needs to be recalculated. The start will be unaffected.
stext.getLines(buffer.g2);
endSelTLHI.tli = stext.getTLIforCharNo(ee);
int cn = ee - endSelTLHI.tli.startCharIndex;
if(cn == 0) // start of line
endSelTLHI.thi = endSelTLHI.tli.layout.getNextLeftHit(1);
else
endSelTLHI.thi = endSelTLHI.tli.layout.getNextRightHit(cn-1);
bufferInvalid = true;
}
/**
* Used internally to set the scrollbar values as the text changes.
*
* @param sx
* @param sy
*/
void setScrollbarValues(float sx, float sy){
if(vsb != null){
float sTextHeight = stext.getTextAreaHeight();
if(sTextHeight < th)
vsb.setValue(0.0f, 1.0f);
else
vsb.setValue(sy/sTextHeight, th/sTextHeight);
}
// If needed update the horizontal scrollbar
if(hsb != null){
float sTextWidth = stext.getMaxLineLength();
if(stext.getMaxLineLength() < tw)
hsb.setValue(0,1);
else
hsb.setValue(sx/sTextWidth, tw/sTextWidth);
}
}
/**
* Move caret to home position
* @param currPos the current position of the caret
* @return true if caret moved else false
*/
protected boolean moveCaretStartOfLine(TextLayoutHitInfo currPos){
if(currPos.thi.getCharIndex() == 0)
return false; // already at start of line
currPos.thi = currPos.tli.layout.getNextLeftHit(1);
return true;
}
/**
* Move caret to the end of the line that has the current caret position
* @param currPos the current position of the caret
* @return true if caret moved else false
*/
protected boolean moveCaretEndOfLine(TextLayoutHitInfo currPos){
if(currPos.thi.getCharIndex() == currPos.tli.nbrChars - 1)
return false; // already at end of line
currPos.thi = currPos.tli.layout.getNextRightHit(currPos.tli.nbrChars - 1);
return true;
}
/**
* Move caret left by one character.
* @param currPos the current position of the caret
* @return true if caret moved else false
*/
protected boolean moveCaretLeft(TextLayoutHitInfo currPos){
TextHitInfo nthi = currPos.tli.layout.getNextLeftHit(currPos.thi);
if(nthi == null){
return false;
}
else {
// Move the caret to the left of current position
currPos.thi = nthi;
}
return true;
}
/**
* Move caret right by one character.
* @param currPos the current position of the caret
* @return true if caret moved else false
*/
protected boolean moveCaretRight(TextLayoutHitInfo currPos){
TextHitInfo nthi = currPos.tli.layout.getNextRightHit(currPos.thi);
if(nthi == null){
return false;
}
else {
currPos.thi = nthi;
}
return true;
}
public void setJustify(boolean justify){
stext.setJustify(justify);
bufferInvalid = true;
}
/**
* Sets the local colour scheme for this control
*/
public void setLocalColorScheme(int cs){
super.setLocalColorScheme(cs);
if(hsb != null)
hsb.setLocalColorScheme(localColorScheme);
if(vsb != null)
vsb.setLocalColorScheme(localColorScheme);
}
/**
* Find out if some text is selected (highlighted)
* @return true if some text is selected else false
*/
public boolean hasSelection(){
return (startTLHI.tli != null && endTLHI.tli != null && startTLHI.compareTo(endTLHI) != 0);
}
/**
* Calculate the caret (text insertion point)
*
* @param tlhi
*/
protected void calculateCaretPos(TextLayoutHitInfo tlhi){
float temp[] = tlhi.tli.layout.getCaretInfo(tlhi.thi);
caretX = temp[0];
caretY = tlhi.tli.yPosInPara;
}
/**
* Determines whether the text can be edited using the keyboard or mouse. It
* still allows the text to be modified by the sketch code. <br>
* If text editing is being disabled and the control has focus then it is forced
* to give up that focus. <br>
* This might be useful if you want to use a GTextArea control to display large
* amounts of text that needs scrolling (so cannot use a GLabel) but must not
* change e.g. a user instruction guide.
*
* @param enableTextEdit false to disable keyboard input
*/
public void setTextEditEnabled(boolean enableTextEdit){
// If we are disabling this then make sure it does not have focus
if(enableTextEdit == false && focusIsWith == this){
loseFocus(null);
}
enabled = enableTextEdit;
textEditEnabled = enableTextEdit;
}
/**
* Is this control keyboard enabled
* @return
*/
public boolean isTextEditEnabled(){
return textEditEnabled;
}
public void keyEvent(KeyEvent e) {
if(!visible || !enabled || !textEditEnabled || !available) return;
if(focusIsWith == this && endTLHI != null){
char keyChar = e.getKey();
int keyCode = e.getKeyCode();
int keyID = e.getAction();
boolean shiftDown = e.isShiftDown();
boolean ctrlDown = e.isControlDown();
textChanged = false;
keepCursorInView = true;
int startPos = pos, startNbr = nbr;
// Get selection details
endChar = endTLHI.tli.startCharIndex + endTLHI.thi.getInsertionIndex();
startChar = (startTLHI != null) ? startTLHI.tli.startCharIndex + startTLHI.thi.getInsertionIndex() : endChar;
pos = endChar;
nbr = 0;
adjust = 0;
if(endChar != startChar){ // Have we some text selected?
if(startChar < endChar){ // Forward selection
pos = startChar; nbr = endChar - pos;
}
else if(startChar > endChar){ // Backward selection
pos = endChar; nbr = startChar - pos;
}
}
if(startPos >= 0){
if(startPos != pos || startNbr != nbr)
fireEvent(this, GEvent.SELECTION_CHANGED);
}
// Select either keyPressedProcess or keyTypeProcess. These two methods are overridden in child classes
if(keyID == KeyEvent.PRESS) {
keyPressedProcess(keyCode, keyChar, shiftDown, ctrlDown);
setScrollbarValues(ptx, pty);
}
else if(keyID == KeyEvent.TYPE ){ // && e.getKey() != KeyEvent.CHAR_UNDEFINED && !ctrlDown){
keyTypedProcess(keyCode, keyChar, shiftDown, ctrlDown);
setScrollbarValues(ptx, pty);
}
if(textChanged){
changeText();
fireEvent(this, GEvent.CHANGED);
}
}
}
// Enable polymorphism.
protected void keyPressedProcess(int keyCode, char keyChar, boolean shiftDown, boolean ctrlDown) { }
protected void keyTypedProcess(int keyCode, char keyChar, boolean shiftDown, boolean ctrlDown){ }
// Only executed if text has changed
protected boolean changeText(){
TextLayoutInfo tli;
TextHitInfo thi = null, thiRight = null;
pos += adjust;
// Force layouts to be updated
stext.getLines(buffer.g2);
// Try to get text layout info for the current position
tli = stext.getTLIforCharNo(pos);
if(tli == null){
// If unable to get a layout for pos then reset everything
endTLHI = null;
startTLHI = null;
ptx = pty = 0;
caretX = caretY = 0;
return false;
}
// We have a text layout so we can do something
// First find the position in line
int posInLine = pos - tli.startCharIndex;
// Get some hit info so we can see what is happening
try{
thiRight = tli.layout.getNextRightHit(posInLine);
}
catch(Exception excp){
thiRight = null;
}
if(posInLine <= 0){ // At start of line
thi = tli.layout.getNextLeftHit(thiRight);
}
else if(posInLine >= tli.nbrChars){ // End of line
thi = tli.layout.getNextRightHit(tli.nbrChars - 1);
}
else { // Character in line;
thi = tli.layout.getNextLeftHit(thiRight);
}
endTLHI.setInfo(tli, thi);
// Cursor at end of paragraph graphic
calculateCaretPos(endTLHI);
// // Is do we have to move cursor to start of next line
// if(newline) {
// if(pos >= stext.length()){
// stext.insertCharacters(pos, " ");
// stext.getLines(buffer.g2);
// }
// moveCaretRight(endTLHI);
// calculateCaretPos(endTLHI);
// }
// // Finish off by ensuring no selection, invalidate buffer etc.
// startTLHI.copyFrom(endTLHI);
// }
bufferInvalid = true;
return true;
}
/**
* Do not call this directly. A timer calls this method as and when required.
*/
public void flashCaret(GTimer timer){
showCaret = !showCaret;
}
/**
* Do not call this method directly, G4P uses it to handle input from
* the horizontal scrollbar.
*/
public void hsbEventHandler(GScrollbar scrollbar, GEvent event){
keepCursorInView = false;
ptx = hsb.getValue() * (stext.getMaxLineLength() + 4);
bufferInvalid = true;
}
/**
* Do not call this method directly, G4P uses it to handle input from
* the vertical scrollbar.
*/
public void vsbEventHandler(GScrollbar scrollbar, GEvent event){
keepCursorInView = false;
pty = vsb.getValue() * (stext.getTextAreaHeight() + 1.5f * stext.getMaxLineHeight());
bufferInvalid = true;
}
/**
* Permanently dispose of this control.
*/
public void markForDisposal(){
if(tabManager != null)
tabManager.removeControl(this);
super.markForDisposal();
}
/**
* Save the styled text used by this control to file. <br>
* It will also save the start and end position of any text selection.
*
* @param fname the name of the file to use
* @return true if saved successfully else false
*/
public boolean saveText(String fname){
if(stext == null)
return false;
if(hasSelection()){
stext.startIdx = startTLHI.tli.startCharIndex + startTLHI.thi.getInsertionIndex();
stext.endIdx = endTLHI.tli.startCharIndex + endTLHI.thi.getInsertionIndex();
}
else {
stext.startIdx = stext.endIdx = -1;
}
StyledString.save(winApp, stext, fname);
return true;
}
/**
* Load the styled string to be used by this control. <br>
* It will also restore any text selection saved with the text.
*
* @param fname the name of the file to use
* @return true if loaded successfully else false
*/
public boolean loadText(String fname){
StyledString ss = StyledString.load(winApp, fname);
if(ss == null)
return false;
setStyledText(ss);
// Now restore any text selection
if(stext.startIdx >=0){ // we have a selection
// Selection starts at ...
startTLHI = new TextLayoutHitInfo();
startTLHI.tli = stext.getTLIforCharNo(stext.startIdx);
int pInLayout = stext.startIdx - startTLHI.tli.startCharIndex;
if(pInLayout == 0)
startTLHI.thi = startTLHI.tli.layout.getNextLeftHit(1);
else
startTLHI.thi = startTLHI.tli.layout.getNextRightHit(pInLayout - 1);
// Selection ends at ...
endTLHI = new TextLayoutHitInfo();
endTLHI.tli = stext.getTLIforCharNo(stext.endIdx);
pInLayout = stext.endIdx - endTLHI.tli.startCharIndex;
if(pInLayout == 0)
endTLHI.thi = endTLHI.tli.layout.getNextLeftHit(1);
else
endTLHI.thi = endTLHI.tli.layout.getNextRightHit(pInLayout - 1);
calculateCaretPos(endTLHI);
}
bufferInvalid = true;
return true;
}
}
| [
"sheridak@purdue.edu"
] | sheridak@purdue.edu |
21e4509cc126862f795354efffa21f6418e03235 | 447a6987a88a037375d3d43b85246dbddc706ef0 | /src/main/java/sis/report/ReportCard.java | b42b755ef94f6f1a0174f943bf1182e49fbae682 | [] | no_license | pporotoss/AgileJava | 6e7a07e629cc9eac2bcb53af7ae6adda60ac77c0 | 466e59657a83465880a3bebfa5c2767ec6326fe5 | refs/heads/master | 2021-09-05T23:13:05.162275 | 2018-01-31T15:02:06 | 2018-01-31T15:02:06 | 109,008,947 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,068 | java | package sis.report;
import sis.studentinfo.Student;
import java.util.EnumMap;
import java.util.Map;
public class ReportCard {
public static final String A_MESSAGE = "Excellent";
public static final String B_MESSAGE = "Very good";
public static final String C_MESSAGE = "Hmmm....";
public static final String D_MESSAGE = "Your not trying";
public static final String F_MESSAGE = "Loser";
private Map<Student.Grade, String> messages = null;
public String getMessage(Student.Grade grade) {
return getMessages().get(grade);
}
public Map<Student.Grade, String> getMessages() {
if (messages == null) loadMessages();
return messages;
}
private void loadMessages() {
messages = new EnumMap<>(Student.Grade.class);
messages.put(Student.Grade.A, A_MESSAGE);
messages.put(Student.Grade.B, B_MESSAGE);
messages.put(Student.Grade.C, C_MESSAGE);
messages.put(Student.Grade.D, D_MESSAGE);
messages.put(Student.Grade.F, F_MESSAGE);
}
}
| [
"pporotoss@gmail.com"
] | pporotoss@gmail.com |
e705759ce91c349cdea64415739833fc1d326849 | 941a8247d14f5a4d2dcfc944386d26822136467a | /src/modul5/Percobaan1.java | 01c7e753009cb842aa67642c34731677a5c6d6d4 | [] | no_license | wardanacoolant/modul5 | a0fa791cdfcdb14ae9762ab5349bddc1eb3c4f6b | 0d2a5d625e1013c6e6a03b198f9db3734165bafc | refs/heads/master | 2022-08-01T08:18:00.096937 | 2020-05-29T07:46:42 | 2020-05-29T07:46:42 | 267,797,907 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 277 | java | package modul5;
public class Percobaan1 {
public static void main(String[] args) {
Mahasiswa mhs = new Mahasiswa(1608561029, "I Made Wardana");
System.out.println("NIM\t: " +mhs.getNrp());
System.out.println("Nama\t: " +mhs.getNama());
}
}
| [
"made.wardana44@gmail.com"
] | made.wardana44@gmail.com |
90b9e4a6b37a6d94bcceb754c479f95501f17aee | 2c767851342c7e97ce1d19acb0201aeef174c515 | /pet-clinic-data/src/main/java/com/springcourse/petclinic/models/Vet.java | a5014f7c6d2d8b14f87df1e63ccc700d6577a9cd | [] | no_license | mariaBarczyk/pet-clinic-udemy | 0364ce8d8471ea930b14ea80753e09391dc7465f | 53b35643fcc6593f34caf561ddd6e073743b57d0 | refs/heads/master | 2020-03-28T02:01:58.082641 | 2018-10-04T10:13:14 | 2018-10-04T10:13:14 | 147,542,760 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 500 | java | package com.springcourse.petclinic.models;
import lombok.*;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Entity
public class Vet extends Person {
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "vet_specialities", joinColumns =
@JoinColumn(name = "vet_id"), inverseJoinColumns =
@JoinColumn(name = "speciality_id"))
private Set<Speciality> specialities = new HashSet<>();
}
| [
"barczyk.maria92@gmail.com"
] | barczyk.maria92@gmail.com |
37bff22c2193e3b1da42c4c4f7a74c2898d0e1f0 | 075681c084dd6449d17798e5c6b830377bb6d1cd | /剑指Offer/第一次只出现一次的字符/Solution.java | 41650223484f3848dd4543117260d09501bd79a1 | [
"ICU"
] | permissive | Q10Viking/Online-programming | 26875cf653630383795a3a269bc50d71fb62cbf7 | cf73e235e21885d89283947e3c48f2e0150e1b1a | refs/heads/master | 2020-05-01T08:21:46.919010 | 2019-04-11T02:44:32 | 2019-04-11T02:44:32 | 177,376,601 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 396 | java | public class Solution {
public int FirstNotRepeatingChar(String str) {
//模拟哈希表
int[] hashTable = new int[256];
for(int i = 0;i<str.length();i++){
hashTable[(int)str.charAt(i)] += 1;
}
for(int i=0;i<str.length();i++){
if(hashTable[(int)str.charAt(i)] == 1)
return i;
}
return -1;
}
} | [
"1193094618@qq.com"
] | 1193094618@qq.com |
755eb06b59d26d92114f9cbb13b6af6c71d9b3de | 4b4570812732e4ac7401c03460b9856dba8a8c2e | /k5/src/main/java/com/logic/GrandSlam.java | 9ea2d4618f0cbbd7a37519b83d2fdc58eee41bb9 | [] | no_license | rahulsh1010/Projects | 48f76f59c8b3ce5da44710978551f6f591f1680f | c5df2583c58dd53cd1b0ea7c4d4ffa1b9d60a3e9 | refs/heads/main | 2023-08-25T12:05:27.572047 | 2021-09-22T05:42:02 | 2021-09-22T05:42:02 | 375,407,732 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,848 | java | package com.logic;
import java.sql.*;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import com.exceptions.InvalidCourt;
import com.exceptions.InvalidSeed;
import com.model.Court;
import com.model.Match;
import com.model.Player;
import java.util.*;
import connection.Db;
public class GrandSlam {
//static Connection con=null;
/*public static void validUser(String user,String pass) {
try {
Statement st=Db.getCon().createStatement();
ResultSet rs=st.executeQuery("Select * from register1");
while(rs.next())
{
//System.out.println(rs.getString(1));
if(rs.getString(1)==user) {
RequestDispatcher rd=request.getRequestDispatcher("Options.html");
}
}
}
catch(Exception e){
}
}*/
public static void addPlayer(Player p) throws InvalidSeed {
try
{
PreparedStatement ps=Db.getCon().prepareStatement("INSERT INTO Player VALUES (?,?,?,?,?,?)");
ps.setString(1,p.getName());
ps.setInt(2,p.getAge());
ps.setInt(3,p.getSeed());
ps.setInt(4,p.getNoOfTournaments());
ps.setString(5,p.getNationality());
ps.setString(6,p.getStrength());
ps.executeUpdate();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void deletePlayer(int seed)throws InvalidSeed {
int i=0;
try { //con=new Db().getCon();
Statement st=Db.getCon().createStatement();
ResultSet rs=st.executeQuery("Select * from Player");
while(rs.next())
//try{
{//System.out.println(rs.getString(1));
if(Integer.parseInt(rs.getString(3))==seed) {
PreparedStatement ps=Db.getCon().prepareStatement("DELETE FROM Player WHERE Seed = ? ");
ps.setInt(1,seed);
ps.executeUpdate();
i++;
// break;
}
//else {
// throw new InvalidSeed("Not valid");
//}
// con.close();
}
//}
// catch (InvalidSeed e) {
// TODO Auto-generated catch block
// System.out.println("Invalid Seed");
// continue;
//System.out.println("Enter valid Player seed");
// e.printStackTrace();
// }
}
catch(Exception e){
e.printStackTrace();
}
if(i==0){
throw new InvalidSeed("Not valid");
}
}
public static void updatePlayer(Player p) throws InvalidSeed {
int i=0;
try{
Statement st=Db.getCon().createStatement();
ResultSet rs=st.executeQuery("Select * from Player");
while(rs.next())
//try{
{//System.out.println(rs.getString(1));
if(Integer.parseInt(rs.getString(3))==p.getSeed()) {
// con=Db.getCon();
PreparedStatement ps=Db.getCon().prepareStatement( "UPDATE Player SET name=?,age=?,tournaments=?,nationality=? WHERE seed=?");
ps.setString(1,p.getName());
ps.setInt(2,p.getAge());
ps.setInt(3,p.getNoOfTournaments());
ps.setString(4,p.getNationality());
ps.setInt(5,p.getSeed());
ps.executeUpdate();
i++;
//con.close();
}
}
}catch(Exception ex){
ex.printStackTrace();
}
if(i==0){
throw new InvalidSeed("Not valid");
}
}
public static Player getPlayer(int id){
Player p=new Player();
try{
PreparedStatement ps=Db.getCon().prepareStatement("select * from Player where Seed = ? ");
ps.setInt(1, id);
ResultSet rs=ps.executeQuery();
while(rs.next()){
p.setSeed(rs.getInt(3));
p.setName(rs.getString(1));
p.setAge(rs.getInt(2));
p.setNoOfTournaments(rs.getInt(4));;
p.setNationality(rs.getString(5));
ps.executeUpdate();
// con.close();
}
}catch(Exception ex){ex.printStackTrace();}
return p;
}
public static List<Player> getAllPlayers(){
List<Player> list=new ArrayList<Player>();
try{
// con=Db.getCon();
PreparedStatement ps=Db.getCon().prepareStatement("select * from Player");
ResultSet rs=ps.executeQuery();
while(rs.next()){
Player p=new Player();
p.setSeed(rs.getInt(3));
p.setName(rs.getString(1));
p.setAge(rs.getInt(2));
p.setNoOfTournaments(rs.getInt(4));;
p.setNationality(rs.getString(5));
p.setStrength(rs.getString(6));
list.add(p);
}
// con.close();
}catch(Exception e){e.printStackTrace();}
return list;
}
/* public static void addCourt(Court c) {
try {
PreparedStatement ps=Db.getCon().prepareStatement("INSERT INTO Court VALUES (?,?,?,?)");
ps.setInt(1,c.getNumber());
ps.setString(2,c.getName());
ps.setInt(3,c.getPlayer1().getSeed());
ps.setInt(4,c.getPlayer2().getSeed());
ps.executeUpdate();
}
catch(Exception e){
e.printStackTrace(); }
}*/
public static void addCourt(Court c) {
try {
PreparedStatement ps=Db.getCon().prepareStatement("INSERT INTO Court VALUES (?,?,?,?)");
ps.setInt(1,c.getNumber());
ps.setString(2, c.getName());
ps.setString(3, c.getType());
ps.setInt(4, c.getCapacity());
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
// TODO Auto-generated catch block
}
}
public static void deleteCourt(int number) throws InvalidCourt {
int i=0;
try { //con=new Db().getCon();
Statement st=Db.getCon().createStatement();
ResultSet rs=st.executeQuery("Select * from Court");
while(rs.next())
{//System.out.println(rs.getString(1));
if(Integer.parseInt(rs.getString(1))==number) {
PreparedStatement ps=Db.getCon().prepareStatement("DELETE FROM Court WHERE Number = ? ");
ps.setInt(1,number);
ps.executeUpdate();
i++;
}
// con.close();
}
}catch(Exception e){
e.printStackTrace();//System.out.println("Enter valid Player seed");
// e
}
if(i==0){
throw new InvalidCourt("Not valid");
}
}
public static void updateCourt(Court p) throws InvalidCourt{
int i=0;
try{ Statement st=Db.getCon().createStatement();
ResultSet rs=st.executeQuery("Select * from Court");
while(rs.next())
//try{
{
if(Integer.parseInt(rs.getString(1))==p.getNumber()) {
// con=Db.getCon();
PreparedStatement ps=Db.getCon().prepareStatement( "UPDATE Court SET name=?,type=?,capacity=? WHERE number=?");
ps.setString(1,p.getName());
ps.setString(2,p.getType());
ps.setInt(3,p.getCapacity());
ps.setInt(4,p.getNumber());
ps.executeUpdate();
i++;
}
}//con.close();
}catch(Exception ex){
ex.printStackTrace();
}
if(i==0){
throw new InvalidCourt("Not valid");
}
}
public static List<Court> showCourts(){
List<Court> list=new ArrayList<Court>();
try{
// con=Db.getCon();
PreparedStatement ps=Db.getCon().prepareStatement("select * from Court");
ResultSet rs=ps.executeQuery();
while(rs.next()){
Court c=new Court();
c.setNumber(rs.getInt(1));
c.setName(rs.getString(2));
c.setType(rs.getString(3));
c.setCapacity(rs.getInt(4));
list.add(c);
}
}
catch(Exception e) {
e.printStackTrace();
}
return list;
}
}
| [
"noreply@github.com"
] | rahulsh1010.noreply@github.com |
cc0e849070072ef811b5d2d8ff5c1c240cb1e705 | b00c5ee03367c2171ce091421d848a0aeb2c3af7 | /app/src/main/java/com/example/grey_hat/dineinn/Food.java | ce97923c047e6fa1683e12e4279406e04dffad99 | [] | no_license | deepaknairrpf/Dine.inn | cdf1c6f582215bcc65e79b3a64fca03feb376873 | e91ce4ee53b3fbc022b32d8d7ccf5fdcd85ea341 | refs/heads/master | 2021-01-23T07:30:11.093773 | 2017-04-05T13:56:32 | 2017-04-05T13:56:32 | 86,427,254 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 4,447 | java | package com.example.grey_hat.dineinn;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.grey_hat.signedIn;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.squareup.picasso.Picasso;
import org.w3c.dom.Text;
/**
* A simple {@link Fragment} subclass.
*/
public class Food extends Fragment {
private String food;
private RecyclerView mrecyclerView;
private DatabaseReference databaseReference;
private ProgressBar progressBar;
public Food() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
Bundle bundle = this.getArguments();
if(bundle!=null) {
food = bundle.getString("food");
}
return inflater.inflate(R.layout.fragment_food, container, false);
}
public static class FoodViewHolder extends RecyclerView.ViewHolder{
View mview;
RecyclerView.LayoutParams params ;
public FoodViewHolder(View itemView) {
super(itemView);
mview=itemView;
params=(RecyclerView.LayoutParams)itemView.getLayoutParams();
}
public void setName(String name)
{
TextView foodName = (TextView)mview.findViewById(R.id.FoodItemName);
foodName.setText(name);
}
public void setImage(Context ctx, String img) {
ImageView foodImg = (ImageView)mview.findViewById(R.id.FoodCardImg);
Picasso.with(ctx).load(img).into(foodImg);
}
public void setPrice(String price) {
TextView priceText = (TextView)mview.findViewById(R.id.FoodPrice);
priceText.setText(price);
}
public void setInVisibility() {
mview.setVisibility(View.GONE);
params.height=0;
params.width=0;
}
}
@Override
public void onStart() {
super.onStart();
progressBar = (ProgressBar)getView().findViewById(R.id.FoodpbLoading);
progressBar.setVisibility(View.VISIBLE);
databaseReference= FirebaseDatabase.getInstance().getReference().child("Food").child(food);
mrecyclerView=(RecyclerView)getView().findViewById(R.id.FoodRecylcList);
Log.e("Database",databaseReference.getKey());
mrecyclerView.setNestedScrollingEnabled(false);
mrecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
FirebaseRecyclerAdapter<FoodItem,FoodViewHolder> foodAdapter = new FirebaseRecyclerAdapter<FoodItem, FoodViewHolder>(
FoodItem.class,R.layout.food_card_view,FoodViewHolder.class,databaseReference
) {
@Override
protected void populateViewHolder(FoodViewHolder viewHolder, final FoodItem model, final int position) {
boolean availability = model.getAvailability();
if(availability) {
viewHolder.setName(model.getName());
viewHolder.setImage(getActivity().getApplicationContext(), model.getImgUrl());
viewHolder.setPrice("Price : " + Long.toString(model.getPrice()));
}
else {
viewHolder.setInVisibility();
}
viewHolder.mview.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
((signedIn)getActivity()).addToBasket(model);
Toast.makeText(getContext(),model.getName()+" added to basket",Toast.LENGTH_SHORT).show();
return true;
}
});
}
};
mrecyclerView.setAdapter(foodAdapter);
}
}
| [
"cse15b016@iiitk.ac.in"
] | cse15b016@iiitk.ac.in |
9cc0ba4dafc91d10fbd19035ad6af2232195a86e | a00505303ee78e7d3234c84f769b34627c8480e4 | /replacespace.java | 040440df0aedc5c9ef5798a1221c59c53dd96059 | [] | no_license | sukrit786/Rupee-Note-Program | d7192c95c72bf8bef0c49061df00fb1acf3e4116 | 87ab61c8dc218fb921752daea7b31b30696ec826 | refs/heads/master | 2020-04-02T23:28:55.976959 | 2019-03-19T06:47:14 | 2019-03-19T06:47:14 | 154,869,196 | 0 | 0 | null | 2018-10-26T17:20:44 | 2018-10-26T17:19:30 | C | UTF-8 | Java | false | false | 262 | java | import java.util.*;
class apples
{
public static void main(String args[])
{
String str = new String();
Scanner sc = new Scanner(System.in);
str = sc.nextLine();
System.out.println(str.trim().replaceAll("\\s+",""));
}
} | [
"sukritanand57@gmail.com"
] | sukritanand57@gmail.com |
09c3e6b69855ba83c5a388e990f264dc7b4661e1 | 50d4b171133e55d216d7cd45b204958a560cf0a7 | /ticket/src/com/interface21/web/servlet/View.java | ca0e1bf870944f28be3e8fbf31884d4c07374840 | [] | no_license | phlizik/MyStudy | 52024c8f0ec4a77a2ecf237b3a6cd3ac716d590a | 638309208e15ca3aae9925868c4842283937d78a | refs/heads/master | 2020-06-17T15:16:02.966598 | 2018-04-20T11:17:28 | 2018-04-20T11:17:28 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,496 | java | package com.interface21.web.servlet;
import java.io.IOException;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* MVC View for a web interaction. Implementations are responsible
* for rendering content, and exposing models. Multiple models can
* be exposed by a single view.<br/>
* View implementations should be threadsafe.
* <p/>View implementations may differ widely. An obvious
* implementation would be JSP based. Other implementations might be
* XSLT based, or use an HTML generation library. This interface is
* designed to avoid restricting the range of possible implementations.
* <p/>Views should be beans. They are likely to be instantiated as
* beans by a ViewResolver.
* <br/>The interface is stateless.
* @author Rod Johnson
* @version $RevisionId$
*/
public interface View {
/** Add static data to this view, exposed in each view.
* <br/>Must be invoked before any calls to render().
* <br/><b>Note that it is legal for dynamic and static attributes to
* be supplied with the same name; however, the dynamic attribute will
* always take precedence</b>, as it was supplied later. This technique
* is commonly used with titles.
* @param name name of attribute to expose
* @param o object to expose
*/
void addStaticAttribute(String name, Object o);
/**
* Renders the view given the specified model.
* The first step will be preparing the request: this commonly consists of
* setting models as request attributes.
* @param model HashMap of models (model name String mapped to model object)
* @param request HttpServletRequest request
* @param response HttpServletResponse we are building
* @throws IOException if there is an error outputing the data
* @throws ServletException if there is an unexpected error not related to IO.
*/
void render(Map model, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException;
/**
* Set the view's name. Helpful for traceability.
* Framework code must call this when constructing views.
* @param name the view's name. May not be null.
* Views should use this for log messages.
*/
void setName(String name);
/** Return the view's name. Should
* never be null, if the view was correctly configured.
* @return the view's name
*/
String getName();
}
| [
"zhaojian770627@163.com"
] | zhaojian770627@163.com |
cc7950d8b52d83aec2060a215fc5c146a0e483e3 | b67cbead02c2804cc672f425a3831db87839ac56 | /inst/ospApps/ProjectileApp.java | 4edf098056e9a627ceffd0eb4029c6cdac79f836 | [] | no_license | stanleesocca/scientific-computing-r | b7babdb03d5ae0c938748d40fc63e36ef3dee9d5 | e45f8cc4372e73fe5e5ef799bab3f40763c6a3f4 | refs/heads/master | 2022-02-13T16:41:57.442722 | 2017-06-09T21:16:23 | 2017-06-09T21:16:23 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,482 | java | /*
* Open Source Physics software is free software as described near the bottom of this code file.
*
* For additional information and documentation on Open Source Physics please see:
* <http://www.opensourcephysics.org/>
*/
// package org.opensourcephysics.sip.ch03;
import org.opensourcephysics.controls.*;
import org.opensourcephysics.frames.*;
/**
* ProjectileApp solves and displays the time evolution of a projectile by stepping a projectile model.
*
* @author Wolfgang Christian, Jan Tobochnik, Harvey Gould
* @version 1.0 05/16/05
*/
public class ProjectileApp extends AbstractSimulation {
PlotFrame plotFrame = new PlotFrame("Time", "x,y", "Position versus time");
Projectile projectile = new Projectile();
PlotFrame animationFrame = new PlotFrame("x", "y", "Trajectory");
public ProjectileApp() {
animationFrame.addDrawable(projectile);
plotFrame.setXYColumnNames(0, "t", "x");
plotFrame.setXYColumnNames(1, "t", "y");
}
/**
* Initializes the simulation.
*/
public void initialize() {
double dt = control.getDouble("dt");
double x = control.getDouble("initial x");
double vx = control.getDouble("initial vx");
double y = control.getDouble("initial y");
double vy = control.getDouble("initial vy");
projectile.setState(x, vx, y, vy);
projectile.setStepSize(dt);
double size = (vx*vx+vy*vy)/10; // estimate of size needed for display
animationFrame.setPreferredMinMax(-1, size, -1, size);
}
/**
* Does a time step.
*/
public void doStep() {
plotFrame.append(0, projectile.state[4], projectile.state[0]); // x vs time data added
plotFrame.append(1, projectile.state[4], projectile.state[2]); // y vs time data added
animationFrame.append(0, projectile.state[0], projectile.state[2]); // trajectory data added
projectile.step(); // advance the state by one time step
}
/**
* Resets the simulation.
*/
public void reset() {
control.setValue("initial x", 0);
control.setValue("initial vx", 10);
control.setValue("initial y", 0);
control.setValue("initial vy", 10);
control.setValue("dt", 0.01);
enableStepsPerDisplay(true);
}
/**
* Starts the Java application.
* @param args command line parameters
*/
public static void main(String[] args) {
SimulationControl.createApp(new ProjectileApp());
}
}
/*
* Open Source Physics software is free software; you can redistribute
* it and/or modify it under the terms of the GNU General Public License (GPL) as
* published by the Free Software Foundation; either version 2 of the License,
* or(at your option) any later version.
* Code that uses any portion of the code in the org.opensourcephysics package
* or any subpackage (subdirectory) of this package must must also be be released
* under the GNU GPL license.
*
* This software 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; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston MA 02111-1307 USA
* or view the license online at http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2007 The Open Source Physics project
* http://www.opensourcephysics.org
*/
| [
"zbook@reyesaguayo.com"
] | zbook@reyesaguayo.com |
4c5c334b7d7e3b4a2d5798ee1b7bdc2725dcea0e | 6da93393d923f180138fb53904e557a70ad3e8ec | /app/src/main/java/com/example/mfundofalteni/myweatherapp/RecyclerAdapter.java | 2359ba56229e268bd9a623d113192d455825d2d7 | [] | no_license | Karas358/MyWeatherApp | 76a6a299b618d0f5e89d4e96a33b71056f8a6956 | 5896bdddf5e4dc56d5eb8f0549cd24130a9a1ac9 | refs/heads/master | 2022-11-30T10:40:25.082044 | 2020-08-10T15:56:30 | 2020-08-10T15:56:30 | 286,184,622 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,593 | java | package com.example.mfundofalteni.myweatherapp;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder> {
private List<WeatherModel> weatherModelList;
private OnDayClickListener onDayClickListener;
public static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView txtDate, txtMin, txtMax, txtWind;
public ImageView imgView;
OnDayClickListener onDayClickListener;
public MyViewHolder(View view, OnDayClickListener onDayClickListener) {
super(view);
txtDate = view.findViewById(R.id.txtDate);
txtMin = view.findViewById(R.id.txtMin);
txtMax = view.findViewById(R.id.txtMax);
txtWind = view.findViewById(R.id.txtWindSpeed);
imgView = view.findViewById(R.id.imgWeather);
this.onDayClickListener = onDayClickListener;
view.setOnClickListener(this);
}
@Override
public void onClick(View v) {
onDayClickListener.onDayClick(getAdapterPosition());
}
}
public RecyclerAdapter(List<WeatherModel> weatherModels, OnDayClickListener onDayClickListener) {
this.weatherModelList = weatherModels;
this.onDayClickListener = onDayClickListener;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.day_layout, parent, false);
return new MyViewHolder(itemView, onDayClickListener);
}
@Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
final WeatherModel weatherModel = weatherModelList.get(position);
GetIcon getIcon = new GetIcon();
holder.txtDate.setText(weatherModel.Date);
holder.txtMin.setText(weatherModel.TempMin);
holder.txtMax.setText(weatherModel.TempMax);
holder.txtWind.setText(weatherModel.WindSpeed);
holder.imgView.setImageResource(getIcon.getWeatherIcon(weatherModel.Description));
}
@Override
public int getItemCount() {
return weatherModelList.size();
}
public interface OnDayClickListener{
void onDayClick(int position);
}
}
| [
"mfundo.falteni"
] | mfundo.falteni |
a725478dd65d5feb502ae0d150ed29d56fdf12e4 | 1eacaac77495de672692d9111e76fe8c3bccd49e | /app/src/main/java/com/example/administrator/demo_app_mua_ban_trao_doi_sach/presenter/PresenterImpRegisterTwoFragment.java | e35a39d57697c1bf86c2a51e0715ef23aa7e0338 | [] | no_license | thinhkaku/AppExchangeBook | 8ca2eb720c892d9a8089a9b19ff1514ada7126c6 | aa479596ceea0d928354aeb4fe527a7fcd1645c3 | refs/heads/master | 2020-04-05T00:12:15.972303 | 2019-04-01T20:34:30 | 2019-04-01T20:34:30 | 156,387,578 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 253 | java | package com.example.administrator.demo_app_mua_ban_trao_doi_sach.presenter;
import android.widget.EditText;
public interface PresenterImpRegisterTwoFragment {
void getRegisterTwo(EditText editText, String address, String user, String password);
}
| [
"thinhkaku.a3k51@gmail.com"
] | thinhkaku.a3k51@gmail.com |
c53e42f75016b472d16fc38a7a60bbeadcde7487 | f36f96a7f404d8a5c9bd515133cb05d7ba372ae6 | /Assignment 6/src/ques7.java | ed7ec27af3ceba987eb16ab3533c3849fd4ac91d | [] | no_license | thakurutkarsh22/Java | f79c506328ca2f003934cb735f37fdf9eac189f1 | dd17a92dc64aa6346d8bd0067cd19a07412cd15d | refs/heads/master | 2021-08-16T00:25:06.515177 | 2021-08-01T22:52:04 | 2021-08-01T22:52:04 | 162,919,306 | 5 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,355 | java | import java.util.Scanner;
public class ques7 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scn = new Scanner(System.in);
// int [] array1 = {1,2,3,18,6,4,6,7,6};
int n = scn.nextInt();
int[] array = new int[n];
for(int i=0 ;i<array.length;i++){
array[i]=scn.nextInt();
}
int k = scn.nextInt();
int ans = Mcontainedlast(array, k ,0);
System.out.println(ans);
// boolean ans = Mcontained(array, 1 ,0);
// System.out.println(ans);
}
public static boolean Mcontained (int [] arr , int n , int indx){
if (indx==arr.length-1){
return false;
}
if (arr[indx] == n)
{
return true;
}
boolean ans = Mcontained(arr, n, indx+1);
return ans;
}
public static int Mcontainedfirst (int [] arr ,int n , int indx){
if (indx==arr.length-1){
return -1;
}
if (arr[indx] == n)
{
return indx;
}
int ans = Mcontainedfirst(arr, n, indx+1);
return ans;
}
public static int Mcontainedlast (int [] arr ,int n , int indx){
// int[] k = arr;
if (indx==arr.length-1){
return -1;
}
if (arr[arr.length -indx -1 ] == n)
{
return arr.length -indx -1;
}
int ans = Mcontainedlast(arr, n, indx+1) ;
return ans;
}
}
| [
"thakurutkarsh22@gmail.com"
] | thakurutkarsh22@gmail.com |
f57f14ed87a29c3e1ec186aaf57d507dc43a6c8e | a937a242336d1e47456e8930446207a59e24c245 | /src/main/java/nz/co/reed/score/config/MetricsConfiguration.java | b37152d60e72c722f67018097da5cae6a45dea10 | [] | no_license | BulkSecurityGeneratorProject/results | 5a521f7fe340bb71a7922f35ae74bd52d1097279 | cdfe65e5fa032000817d0663562faf2cc7088153 | refs/heads/master | 2022-12-15T15:59:18.021964 | 2019-05-07T20:51:56 | 2019-05-07T20:51:56 | 296,538,092 | 0 | 0 | null | 2020-09-18T06:51:13 | 2020-09-18T06:51:12 | null | UTF-8 | Java | false | false | 5,217 | java | package nz.co.reed.score.config;
import io.github.jhipster.config.JHipsterProperties;
import com.codahale.metrics.JmxReporter;
import com.codahale.metrics.JvmAttributeGaugeSet;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Slf4jReporter;
import com.codahale.metrics.health.HealthCheckRegistry;
import com.codahale.metrics.jvm.*;
import com.ryantenney.metrics.spring.config.annotation.EnableMetrics;
import com.ryantenney.metrics.spring.config.annotation.MetricsConfigurerAdapter;
import com.zaxxer.hikari.HikariDataSource;
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.dropwizard.DropwizardExports;
import io.prometheus.client.exporter.MetricsServlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.context.annotation.*;
import javax.annotation.PostConstruct;
import javax.servlet.ServletContext;
import java.lang.management.ManagementFactory;
import java.util.concurrent.TimeUnit;
@Configuration
@EnableMetrics(proxyTargetClass = true)
public class MetricsConfiguration extends MetricsConfigurerAdapter implements ServletContextInitializer {
private static final String PROP_METRIC_REG_JVM_MEMORY = "jvm.memory";
private static final String PROP_METRIC_REG_JVM_GARBAGE = "jvm.garbage";
private static final String PROP_METRIC_REG_JVM_THREADS = "jvm.threads";
private static final String PROP_METRIC_REG_JVM_FILES = "jvm.files";
private static final String PROP_METRIC_REG_JVM_BUFFERS = "jvm.buffers";
private static final String PROP_METRIC_REG_JVM_ATTRIBUTE_SET = "jvm.attributes";
private final Logger log = LoggerFactory.getLogger(MetricsConfiguration.class);
private MetricRegistry metricRegistry = new MetricRegistry();
private HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry();
private final JHipsterProperties jHipsterProperties;
private HikariDataSource hikariDataSource;
public MetricsConfiguration(JHipsterProperties jHipsterProperties) {
this.jHipsterProperties = jHipsterProperties;
}
@Autowired(required = false)
public void setHikariDataSource(HikariDataSource hikariDataSource) {
this.hikariDataSource = hikariDataSource;
}
@Override
@Bean
public MetricRegistry getMetricRegistry() {
return metricRegistry;
}
@Override
@Bean
public HealthCheckRegistry getHealthCheckRegistry() {
return healthCheckRegistry;
}
@PostConstruct
public void init() {
log.debug("Registering JVM gauges");
metricRegistry.register(PROP_METRIC_REG_JVM_MEMORY, new MemoryUsageGaugeSet());
metricRegistry.register(PROP_METRIC_REG_JVM_GARBAGE, new GarbageCollectorMetricSet());
metricRegistry.register(PROP_METRIC_REG_JVM_THREADS, new ThreadStatesGaugeSet());
metricRegistry.register(PROP_METRIC_REG_JVM_FILES, new FileDescriptorRatioGauge());
metricRegistry.register(PROP_METRIC_REG_JVM_BUFFERS, new BufferPoolMetricSet(ManagementFactory.getPlatformMBeanServer()));
metricRegistry.register(PROP_METRIC_REG_JVM_ATTRIBUTE_SET, new JvmAttributeGaugeSet());
if (hikariDataSource != null) {
log.debug("Monitoring the datasource");
// remove the factory created by HikariDataSourceMetricsPostProcessor until JHipster migrate to Micrometer
hikariDataSource.setMetricsTrackerFactory(null);
hikariDataSource.setMetricRegistry(metricRegistry);
}
if (jHipsterProperties.getMetrics().getJmx().isEnabled()) {
log.debug("Initializing Metrics JMX reporting");
JmxReporter jmxReporter = JmxReporter.forRegistry(metricRegistry).build();
jmxReporter.start();
}
if (jHipsterProperties.getMetrics().getLogs().isEnabled()) {
log.info("Initializing Metrics Log reporting");
Marker metricsMarker = MarkerFactory.getMarker("metrics");
final Slf4jReporter reporter = Slf4jReporter.forRegistry(metricRegistry)
.outputTo(LoggerFactory.getLogger("metrics"))
.markWith(metricsMarker)
.convertRatesTo(TimeUnit.SECONDS)
.convertDurationsTo(TimeUnit.MILLISECONDS)
.build();
reporter.start(jHipsterProperties.getMetrics().getLogs().getReportFrequency(), TimeUnit.SECONDS);
}
}
@Override
public void onStartup(ServletContext servletContext) {
if (jHipsterProperties.getMetrics().getPrometheus().isEnabled()) {
String endpoint = jHipsterProperties.getMetrics().getPrometheus().getEndpoint();
log.debug("Initializing prometheus metrics exporting via {}", endpoint);
CollectorRegistry.defaultRegistry.register(new DropwizardExports(metricRegistry));
servletContext
.addServlet("prometheusMetrics", new MetricsServlet(CollectorRegistry.defaultRegistry))
.addMapping(endpoint);
}
}
}
| [
"andrew.reed@skytv.co.nz"
] | andrew.reed@skytv.co.nz |
0313b81dc215ebc7fb53f117d786ea07b780a8d1 | ad64a14fac1f0d740ccf74a59aba8d2b4e85298c | /linkwee-supermarket-admin/src/main/java/com/linkwee/xoss/util/business/ProfitCalculationUtils.java | 82ac137cb83592f6a10f8abe491b9fa99b9df232 | [] | no_license | zhangjiayin/supermarket | f7715aa3fdd2bf202a29c8683bc9322b06429b63 | 6c37c7041b5e1e32152e80564e7ea4aff7128097 | refs/heads/master | 2020-06-10T16:57:09.556486 | 2018-10-30T07:03:15 | 2018-10-30T07:03:15 | 193,682,975 | 0 | 1 | null | 2019-06-25T10:03:03 | 2019-06-25T10:03:03 | null | UTF-8 | Java | false | false | 2,626 | java | package com.linkwee.xoss.util.business;
import java.math.BigDecimal;
import org.springframework.beans.BeanUtils;
import com.linkwee.tc.fee.model.vo.InsuranceFeedetailWrapper;
import com.linkwee.web.model.CimInsuranceFeedetailExtends;
import com.linkwee.web.model.CimInsuranceNotify;
public class ProfitCalculationUtils {
/**
* 封装保险佣金明细包装类
* @param cimInsuranceFeedetail
* @param cimInsuranceNotify
* @return
*/
public static InsuranceFeedetailWrapper creatInsuranceFeedetailWrapperForFeeCalcExist(CimInsuranceFeedetailExtends cimInsuranceFeedetailExtends,CimInsuranceNotify cimInsuranceNotify) {
InsuranceFeedetailWrapper insuranceFeedetailWrapper = new InsuranceFeedetailWrapper();
BeanUtils.copyProperties(cimInsuranceFeedetailExtends, insuranceFeedetailWrapper);
//0-待审核 生成相关佣金为0的 佣金记录 便于前端页面显示
String remark = null;
if(cimInsuranceNotify.getAuditStatus() == 0){
remark = String.format("%s购买保险产品《%s》,将会在15天—45天内结算(受保险机构结算方式的影响)", cimInsuranceFeedetailExtends.getUserNameMobile(),cimInsuranceFeedetailExtends.getProductName());
insuranceFeedetailWrapper.setRemark(remark);
insuranceFeedetailWrapper.setYearpurAmount(BigDecimal.ZERO);
insuranceFeedetailWrapper.setFeeAmount(BigDecimal.ZERO);
} else if(cimInsuranceNotify.getAuditStatus() == 1 || cimInsuranceNotify.getAuditStatus() == 3){ //系统审核通过
insuranceFeedetailWrapper.setRemark(cimInsuranceFeedetailExtends.getSucceedRemark());//需具体计算展示备注
insuranceFeedetailWrapper.setSucceedRemark("");//清空SucceedRemark
insuranceFeedetailWrapper.setYearpurAmount(cimInsuranceFeedetailExtends.getProductAmount());
insuranceFeedetailWrapper.setFeeAmount(cimInsuranceFeedetailExtends.getProductAmount().multiply(cimInsuranceFeedetailExtends.getProductFeeRate()).divide(new BigDecimal(100)).multiply(cimInsuranceFeedetailExtends.getFeeRate()).divide(new BigDecimal(100)));
} else if(cimInsuranceNotify.getAuditStatus() == 2 || cimInsuranceNotify.getAuditStatus() == 4){ //系统审核失败
remark = String.format("%s购买保险产品《%s》,由于在犹豫期退保,佣金结算失败", cimInsuranceFeedetailExtends.getUserNameMobile(),cimInsuranceFeedetailExtends.getProductName());
insuranceFeedetailWrapper.setRemark(remark);
insuranceFeedetailWrapper.setYearpurAmount(BigDecimal.ZERO);
insuranceFeedetailWrapper.setFeeAmount(BigDecimal.ZERO);
}
return insuranceFeedetailWrapper;
}
}
| [
"liqimoon@qq.com"
] | liqimoon@qq.com |
1548b37b687446a9ef39a8603248570d066a2358 | 62f72f316fdfeb17e05daf94c36521bbc6b2cf8f | /hybris/bin/custom/imbibe/imbibestorefront/web/src/com/imbibe/storefront/controllers/cms/SubCategoryListComponentController.java | 238bba680dd75232c0233bf049a2a59af6e8e7fc | [] | no_license | viksin10/imbibecommerce | 1f107d615579d805f14d9c66622cd85a67247700 | 4d595136166157de4e5f4e6e54f9a5265067d5cb | refs/heads/master | 2021-06-07T01:20:40.034937 | 2020-12-18T09:26:36 | 2020-12-18T09:26:36 | 98,385,692 | 0 | 0 | null | 2023-09-06T05:20:17 | 2017-07-26T06:06:22 | Java | UTF-8 | Java | false | false | 2,338 | java | /*
* Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved.
*/
package com.imbibe.storefront.controllers.cms;
import de.hybris.platform.acceleratorcms.model.components.SubCategoryListComponentModel;
import de.hybris.platform.category.model.CategoryModel;
import de.hybris.platform.commercefacades.product.data.CategoryData;
import de.hybris.platform.commerceservices.category.CommerceCategoryService;
import de.hybris.platform.commerceservices.search.facetdata.ProductCategorySearchPageData;
import de.hybris.platform.commerceservices.search.pagedata.SearchPageData;
import de.hybris.platform.converters.Converters;
import de.hybris.platform.servicelayer.dto.converter.Converter;
import com.imbibe.storefront.controllers.ControllerConstants;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* Controller for CMS SubCategoryListComponent
*/
@Controller("SubCategoryListComponentController")
@RequestMapping(value = ControllerConstants.Actions.Cms.SubCategoryListComponent)
public class SubCategoryListComponentController extends AbstractAcceleratorCMSComponentController<SubCategoryListComponentModel>
{
@Resource(name = "commerceCategoryService")
private CommerceCategoryService commerceCategoryService;
@Resource(name = "categoryConverter")
private Converter<CategoryModel, CategoryData> categoryConverter;
@Override
protected void fillModel(final HttpServletRequest request, final Model model, final SubCategoryListComponentModel component)
{
final SearchPageData searchPageData = getRequestContextData(request).getSearch();
if (searchPageData instanceof ProductCategorySearchPageData)
{
final ProductCategorySearchPageData<?, ?, CategoryData> productCategorySearchPageData = (ProductCategorySearchPageData<?, ?, CategoryData>) searchPageData;
model.addAttribute("subCategories", productCategorySearchPageData.getSubCategories());
}
else
{
final CategoryModel categoryModel = getRequestContextData(request).getCategory();
if (categoryModel != null)
{
model.addAttribute("subCategories", Converters.convertAll(categoryModel.getAllSubcategories(), categoryConverter));
}
}
}
}
| [
"vikrantsingh200708@gmail.com"
] | vikrantsingh200708@gmail.com |
fda5db239fe790777436076c9c7e4ff87b1f9040 | ea4eb1395276c5009ac5337681099810391ba51f | /src/main/java/org/oracul/service/controller/SingletonPrognosisController.java | 7f8955c8100bd20c2512c6cbd5ec0608367db461 | [] | no_license | steplerbush/OraculService | 5a733067216698aff8f814724e396c6e5324fa2f | 9fb52818bce9c00c979adc69bf102298acde2d2d | refs/heads/master | 2021-01-15T22:24:12.237656 | 2016-01-23T08:17:22 | 2016-01-23T08:17:22 | 33,053,547 | 0 | 0 | null | 2015-03-28T23:00:35 | 2015-03-28T23:00:35 | null | UTF-8 | Java | false | false | 9,504 | java | package org.oracul.service.controller;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.oracul.service.dto.ImagePrediction;
import org.oracul.service.dto.Prediction2D;
import org.oracul.service.dto.Prediction3D;
import org.oracul.service.dto.PredictionStatus;
import org.oracul.service.executor.PredictionExecutor;
import org.oracul.service.service.Prediction2DService;
import org.oracul.service.service.Prediction3DService;
import org.oracul.service.task.PredictionTaskCreator;
import org.oracul.service.util.IntegrationFacade;
import org.oracul.service.util.PredictionsStatusesHolder;
import org.oracul.service.util.exception.PredictionNotFoundException;
import org.oracul.service.util.exception.QueueOverflowException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
@RestController
@RequestMapping("/prediction")
public class SingletonPrognosisController {
private static final Logger LOGGER = Logger.getLogger(SingletonPrognosisController.class);
@Autowired
private PredictionTaskCreator predictionTaskCreator;
@Autowired
private PredictionExecutor executor;
@Autowired
private Prediction2DService prediction2dRepository;
@Autowired
private Prediction3DService prediction3dRepository;
@Autowired
private PredictionsStatusesHolder statusHolder;
@Autowired
private IntegrationFacade facade;
@RequestMapping(value = "/order/2d", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public Object orderPrediction2D(HttpServletRequest request) throws InterruptedException {
if (facade.getQueue().size() >= facade.getQueue().getMaxSize()) {
LOGGER.debug("Queue is overloaded. Task is rejected.");
throw new QueueOverflowException();
}
Long taskID = predictionTaskCreator.createPrediction(PredictionTaskCreator.PredictionType.TASK_2D,
new String[] { "some params for 2d" });
return request.getRequestURL().substring(0, request.getRequestURL().indexOf("order")) + "2d/" + taskID;
}
@RequestMapping(value = "/order/3d", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public Object orderPrediction3D(HttpServletRequest request) throws InterruptedException {
if (facade.getQueue().size() >= facade.getQueue().getMaxSize() - facade.getProperty().getCore3d()) {
LOGGER.debug("Queue is overloaded. Task is rejected.");
throw new QueueOverflowException();
}
Long taskID = predictionTaskCreator.createPrediction(PredictionTaskCreator.PredictionType.TASK_3D,
new String[] { "some params for 3d" });
return request.getRequestURL().substring(0, request.getRequestURL().indexOf("order")) + "3d/" + taskID;
}
@RequestMapping(value = "/2d/{id}", method = RequestMethod.GET)
public Object getPrediction2D(@PathVariable("id") Long id) {
Prediction2D prediction = prediction2dRepository.findById(id);
if (prediction != null && prediction.getU() != null) {
return prediction;
} else {
return statusHolder.checkStatus(id);
}
}
@RequestMapping(value = "/3d/{id}", method = RequestMethod.GET)
public Object getPrediction3D(@PathVariable("id") Long id) {
Prediction3D prediction = prediction3dRepository.findById(id);
if (prediction != null && prediction.getLevels().size() != 0) {
return prediction;
} else {
return statusHolder.checkStatus(id);
}
}
@RequestMapping(value = "/order/image", method = RequestMethod.GET, produces = "application/json")
@ResponseStatus(HttpStatus.OK)
public @ResponseBody Map<String, Object> orderFile() throws InterruptedException {
JSONObject jsonObject = facade.getOraculHttpClient().sendGetJSONRequest(facade.getProperty().getGpuServerAddress()
+ facade.getProperty().getGpuRootSubURL() + facade.getProperty().getGpuOrderSubURL());
UUID id = UUID.fromString(jsonObject.getString("id"));
Long wait = jsonObject.getLong("wait");
LOGGER.debug("Received id=" + id + ", time to wait is = " + wait);
//ImagePrediction imagePrediction = new ImagePrediction(id,PredictionStatus.PENDING.ordinal());
//facade.getImagePredictionRepository().createPrediction(imagePrediction);
Map<String, Object> returnParams = new HashMap<>();
returnParams.put("id", id);
returnParams.put("wait", wait);
return returnParams;
}
//Возвращать на лайфрей по ордеру гуид и время ожидания. там в джаваскрипте єто отобразить и сделать таймер
//после которого автоматически виполнится дополнительний запрос на isready. и так в цикле. пока не будет результата.
// как только картинка будет готова - появится кнопка для загрузки картинки.
//разделить запрос на несколько.
@RequestMapping(value = "/get/image/{id}", method = RequestMethod.GET, produces = "image/jpg")
public @ResponseBody byte[] getFile(@PathVariable("id") UUID id) throws InterruptedException {
File image = null;
try {
JSONObject jsonObject;
boolean receivedLocal = true;
image = new File(facade.getProperty().getGpuImageResultsFolder() + id + facade.getProperty().getGpuImageResultsFormat());
if (!image.exists()) {
LOGGER.debug("Image "+ id + " does not exist on local machine. trying to request in from remote service");
image = getFileFromRemote(id);
LOGGER.debug(image.getAbsolutePath());
receivedLocal = false;
}
byte[] imageout = new byte[0];
if (image.exists()) {
imageout = sendImageToOutput(image);
} else {
LOGGER.error("Image " + id + "didnot created in filesystem");
}
//--end of third request - returned image
if (!receivedLocal) {
jsonObject = facade.getOraculHttpClient().sendGetJSONRequest(facade.getProperty().getGpuServerAddress()
+ facade.getProperty().getGpuRootSubURL()
+ facade.getProperty().getGpuReleaseSubURL()
+ id);
if (!"SUCCESS".equals(jsonObject.getString("status"))) {
LOGGER.error("Image file " + id + " was not deleted from remote service!");
}
}
return imageout;
} catch(Exception e) {
LOGGER.error("Error while processing image request", e);
if (image != null) {
Path fp = image.toPath();
try {
Files.delete(fp);
} catch (IOException e1) {
LOGGER.error("bugged image was not removed - error",e1);
}
}
throw new PredictionNotFoundException();
}
}
private byte[] sendImageToOutput(File image) {
byte[] imageout;
try (InputStream is = new FileInputStream(image);
ByteArrayOutputStream bao = new ByteArrayOutputStream()) {
BufferedImage img = ImageIO.read(is);
//ByteArrayOutputStream bao = new ByteArrayOutputStream();
ImageIO.write(img, "jpg", bao);
imageout = bao.toByteArray();
bao.flush();
bao.close();
} catch (IOException e) {
LOGGER.error("Error while making image response", e);
throw new RuntimeException(e);
}
return imageout;
}
private File getFileFromRemote(UUID id) throws InterruptedException {
JSONObject jsonObject;
File image;
Long wait;
int numberOfAttemts = 0;
while (numberOfAttemts < 3) {
jsonObject = facade.getOraculHttpClient().sendGetJSONRequest(facade.getProperty().getGpuServerAddress()
+ facade.getProperty().getGpuRootSubURL() + facade.getProperty().getGpuIsReadySubURL() + id);
String status = jsonObject.getString("status");
if ("NOT_CREATED".equals(status)) {
LOGGER.debug("NOT_CREATED: image " + id + " has not been created yet");
Thread.sleep(300);
} else if ("READY".equals(status)) {
LOGGER.debug("READY: image " + id + " has been created");
break;
} else if ("IN_PROCESSING".equals(status) || "IN_QUEUE".equals(status) || "READY_FOR_QUEUE".equals(status)) {
wait = jsonObject.getLong("wait");
LOGGER.debug(status + ": image " + id + " waiting " + wait);
Thread.sleep(wait);
}
numberOfAttemts++;
if (numberOfAttemts == 5) {
LOGGER.error("Order did not fulfilled after 5 attempts. Deleting order from db");
//imagePrediction.setStatusId(PredictionStatus.FAILED.ordinal());
//facade.getImagePredictionRepository().deletePrediction(id);
throw new RuntimeException("Order did not fulfilled after 5 attempts. Deleting order from db");
}
}
//-- end of second request
//request file from remote
image = facade.getOraculHttpClient().sendGetImageRequest(facade.getProperty().getGpuServerAddress()
+ facade.getProperty().getGpuRootSubURL()
+ facade.getProperty().getGpuGetImageSubURL()
+ id,
facade.getProperty().getGpuImageResultsFolder()
+ id
+ facade.getProperty().getGpuImageResultsFormat());
return image;
}
}
| [
"steplerbush@gmail.com"
] | steplerbush@gmail.com |
ed6caf2d7e5f0c8eb9c0d044f839525d2642e55e | fe65741c10ed154da90586cc1f4b689c621c4c02 | /src/sfinx-ekiden-gent-android-client/src/be/sfinxekidengent/ui/widget/BlockScheduleItem.java | 1fed3723e2f667c2a142e55fe13d7b5e707bb1ff | [] | no_license | chandanbenjaram/sfinx-ekiden-gent | fcd82f06a3c03727febadf781a667e687f686f88 | 3f58e016e4194c63f37455009afb441728f03bc4 | refs/heads/master | 2016-09-05T11:40:53.547951 | 2012-01-22T14:33:01 | 2012-01-22T14:33:01 | 42,661,073 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,077 | java | /*
* Copyright 2011 Google Inc.
* Copyright 2011 Peter Kuterna
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package be.sfinxekidengent.ui.widget;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import be.sfinxekidengent.R;
import be.sfinxekidengent.ui.BlockScheduleItemsFragment;
import be.sfinxekidengent.util.Maps;
import be.sfinxekidengent.util.ParserUtils;
public class BlockScheduleItem extends ScheduleItem {
public final static String TAG = "BlockScheduleItem";
public static final String BLOCK_KIND_REGISTRATION = "Registration";
public static final String BLOCK_KIND_BREAK = "Break";
public static final String BLOCK_KIND_COFFEE_BREAK = "Coffee Break";
public static final String BLOCK_KIND_LUNCH = "Lunch";
public static final String BLOCK_KIND_BREAKFAST = "Breakfast";
public static final String BLOCK_KIND_KEYNOTE = "Keynote";
public static final String BLOCK_KIND_TALK = "Talk";
public static final String BLOCK_TYPE_EKIDEN = "Ekiden";
/*
public static final String BLOCK_TYPE_UNIVERSITY = "University";
public static final String BLOCK_TYPE_CONFERENCE = "Conference";
public static final String BLOCK_TYPE_QUICKIE = "Quickie";
public static final String BLOCK_TYPE_TOOLS_IN_ACTION = "Tools in Action";
public static final String BLOCK_TYPE_BOF = "BOF";
public static final String BLOCK_TYPE_HANDS_ON_LAB = "Hands-on Labs";
*/
public static final int COLOR_REGISTRATION = 0;
public static final int COLOR_BREAK = 1;
public static final int COLOR_KEYNOTE = 2;
public static final int COLOR_UNIVERSITY = 3;
public static final int COLOR_CONFERENCE = 4;
public static final int COLOR_TOOLS_IN_ACTION = 5;
public static final int COLOR_QUICKIE = 6;
public static final int COLOR_HANDS_ON_LAB = 7;
public static final int COLOR_BOF = 8;
private static final HashMap<String, Integer> sKindMap = buildKindMap();
private static final HashMap<String, Integer> sTypeMap = buildTypeMap();
int sessionsCount;
String sessionId; // the single session id in case we only have one session
int type;
private static HashMap<String, Integer> buildKindMap() {
final HashMap<String, Integer> map = Maps.newHashMap();
map.put(BLOCK_KIND_REGISTRATION, COLOR_REGISTRATION);
map.put(BLOCK_KIND_BREAK, COLOR_BREAK);
map.put(BLOCK_KIND_COFFEE_BREAK, COLOR_BREAK);
map.put(BLOCK_KIND_BREAKFAST, COLOR_BREAK);
map.put(BLOCK_KIND_LUNCH, COLOR_BREAK);
map.put(BLOCK_KIND_KEYNOTE, COLOR_KEYNOTE);
return map;
}
private static HashMap<String, Integer> buildTypeMap() {
final HashMap<String, Integer> map = Maps.newHashMap();
map.put(BLOCK_TYPE_EKIDEN, COLOR_CONFERENCE);
map.put(BLOCK_KIND_REGISTRATION, COLOR_REGISTRATION);
map.put(BLOCK_KIND_LUNCH, COLOR_BREAK);
/*
map.put(BLOCK_TYPE_UNIVERSITY, COLOR_UNIVERSITY);
map.put(BLOCK_TYPE_CONFERENCE, COLOR_CONFERENCE);
map.put(BLOCK_TYPE_TOOLS_IN_ACTION, COLOR_TOOLS_IN_ACTION);
map.put(BLOCK_TYPE_QUICKIE, COLOR_QUICKIE);
map.put(BLOCK_TYPE_HANDS_ON_LAB, COLOR_HANDS_ON_LAB);
map.put(BLOCK_TYPE_BOF, COLOR_BOF);
*/
return map;
}
public static void loadBlocks(Context context, Cursor data,
ArrayList<BlockScheduleItem> blocksList) {
if (data == null) {
return;
}
Log.v(TAG, "loadBlocks: " + data.getCount() + ".");
do {
final String code = data
.getString(BlockScheduleItemsFragment.BlocksQuery.BLOCK_CODE);
final String kind = data
.getString(BlockScheduleItemsFragment.BlocksQuery.BLOCK_KIND);
final String type = data
.getString(BlockScheduleItemsFragment.BlocksQuery.BLOCK_TYPE);
Integer columnType = null;
if (ParserUtils.isTalk(code)) {
columnType = sTypeMap.get(type);
} else {
columnType = sKindMap.get(kind);
}
// TODO: place random blocks at bottom of entire layout
if (columnType == null) {
continue;
}
final String blockId = data
.getString(BlockScheduleItemsFragment.BlocksQuery.BLOCK_ID);
final String title = data
.getString(BlockScheduleItemsFragment.BlocksQuery.BLOCK_TITLE);
final long start = data
.getLong(BlockScheduleItemsFragment.BlocksQuery.BLOCK_START);
final long end = data.getLong(BlockScheduleItemsFragment.BlocksQuery.BLOCK_END);
final boolean containsStarred = data
.getInt(BlockScheduleItemsFragment.BlocksQuery.CONTAINS_STARRED) != 0;
final int sessionsCount = data
.getInt(BlockScheduleItemsFragment.BlocksQuery.SESSIONS_COUNT);
final BlockScheduleItem block = new BlockScheduleItem();
block.id = blockId;
block.title = title;
block.roomId = null;
block.startMillis = start;
block.endMillis = end;
block.containsStarred = containsStarred;
block.sessionsCount = sessionsCount;
block.type = columnType.intValue();
block.accentColor = getAccentColor(context, block);
blocksList.add(block);
} while (data.moveToNext());
computePositions(blocksList);
}
private static int getAccentColor(Context context, BlockScheduleItem block) {
int accentColor = -1;
if (context != null) {
switch (block.type) {
case BlockScheduleItem.COLOR_REGISTRATION:
accentColor = context.getResources().getColor(
R.color.block_registration);
break;
case BlockScheduleItem.COLOR_BREAK:
accentColor = context.getResources().getColor(
R.color.block_break);
break;
case BlockScheduleItem.COLOR_KEYNOTE:
accentColor = context.getResources().getColor(
R.color.block_keynote);
break;
case BlockScheduleItem.COLOR_UNIVERSITY:
accentColor = context.getResources().getColor(
R.color.block_university);
break;
case BlockScheduleItem.COLOR_CONFERENCE:
accentColor = context.getResources().getColor(
R.color.block_conference);
break;
case BlockScheduleItem.COLOR_TOOLS_IN_ACTION:
accentColor = context.getResources().getColor(
R.color.block_tools_in_action);
break;
case BlockScheduleItem.COLOR_QUICKIE:
accentColor = context.getResources().getColor(
R.color.block_quickie);
break;
case BlockScheduleItem.COLOR_HANDS_ON_LAB:
accentColor = context.getResources().getColor(
R.color.block_hands_on_lab);
break;
case BlockScheduleItem.COLOR_BOF:
accentColor = context.getResources()
.getColor(R.color.block_bof);
break;
}
}
return accentColor;
}
public static void updateSessionId(BlockScheduleItem block, String sessionId) {
block.sessionId = sessionId;
}
public int getSessionsCount() {
return sessionsCount;
}
}
| [
"dieter.vekeman@gmail.com"
] | dieter.vekeman@gmail.com |
78af14dcade6d82393f6e13938cc90fb65293748 | 19a7eba24d8f6272f23a633512a0924712c569e8 | /Sequence5Maven/src/insanevehicles/model/InsaneVehiclesModel.java | 841ba62c7ec90b42c0e483d0542f48107f6f8873 | [] | no_license | LAinox001/LivrableMaven | 9d1f383835b0719b9d5310167a55165657c060c6 | 0d309e8cbf7633388eb41b78c7046319e3bde0e5 | refs/heads/master | 2020-05-20T04:31:31.466071 | 2019-05-07T11:47:49 | 2019-05-07T11:47:49 | 185,385,620 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,906 | java | package fr.exia.insanevehicles.model;
import java.io.IOException;
import fr.exia.insanevehicles.model.element.mobile.IMobile;
import fr.exia.insanevehicles.model.element.mobile.MyVehicle;
/**
* <h1>The Class InsaneVehiclesModel.</h1>
*/
public class InsaneVehiclesModel implements IInsaneVehiclesModel {
/** The road. */
private IRoad road;
/** The my vehicle. */
private IMobile myVehicle;
/**
* Instantiates a new insane vehicles model.
*
* @param fileName
* the file name
* @param myVehicleStartX
* the my vehicle start X
* @param myVehicleStartY
* the my vehicle start Y
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public InsaneVehiclesModel(final String fileName, final int myVehicleStartX, final int myVehicleStartY)
throws IOException {
this.setRoad(new Road(fileName));
this.setMyVehicle(new MyVehicle(myVehicleStartX, myVehicleStartY, this.getRoad()));
}
/* (non-Javadoc)
* @see fr.exia.insanevehicles.model.IInsaneVehiclesModel#getRoad()
*/
@Override
public final IRoad getRoad() {
return this.road;
}
/**
* Sets the road.
*
* @param road
* the road to set
*/
private void setRoad(final IRoad road) {
this.road = road;
}
/* (non-Javadoc)
* @see fr.exia.insanevehicles.model.IInsaneVehiclesModel#getMyVehicle()
*/
@Override
public final IMobile getMyVehicle() {
return this.myVehicle;
}
/**
* Sets the my vehicle.
*
* @param myVehicle
* the myVehicle to set
*/
private void setMyVehicle(final IMobile myVehicle) {
this.myVehicle = myVehicle;
}
}
| [
"l.antoni@hotmail.fr"
] | l.antoni@hotmail.fr |
aa4e75ac53abcc104f47b290819539321f42eea0 | 9674479eb3ddebd5c46cd1ebceefccbe5d017d9f | /Scheduler/Scheduler/src/main/java/com/hp/scheduler/socket/LogicalClockImpl.java | 99a08bcf468590e50de62bde7fb3712723658c68 | [] | no_license | fnxcorp/SistemasDistribuidos | 1399ecb530b7db61dd82ddc66ddaeca97885d042 | 18ec4cde875bf6c1ec28c79337af8c9754ef3ecc | refs/heads/master | 2021-01-25T07:18:56.909647 | 2015-04-19T23:52:13 | 2015-04-19T23:52:13 | 30,391,766 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,071 | java | package com.hp.scheduler.socket;
/**
* Class to implement a basic logical clock.
*
* @author Omar
*/
public class LogicalClockImpl implements LogicalClock {
int c;
/**
* Starts the logical clock with 0
*/
public LogicalClockImpl() {
c = 0;
}
/**
* Get the clock value.
*
* @return the current value of the clock
*/
@Override
public int getValue() {
return c;
}
/**
* Increases the clock value by 1.
*/
@Override
public void tick() {
c = c + 1;
}
/**
* Simulates a send action, which means do a tick.
*/
@Override
public void sendAction() {
tick();
}
/**
* Updates the clock with the max value between the internal clock and the value that came from the process that
* originated the message.
*
* @param src the value of the logical clock of the process who sent a message
*/
@Override
public void receiveAction(int src) {
c = Math.max(c, src);
tick();
}
}
| [
"omar2687a@gmail.com"
] | omar2687a@gmail.com |
44b6c975d4955802aa5fa64cb929553fccae8d1c | c52dd8a66e5fc00c0f7668410b436d21caae693a | /src/com/JAVA并发编程的艺术/lockTest/ReentrantLockTest/FairAndUnfairTest.java | 7ab94063955b46a955652889b508764a6a14fc9f | [] | no_license | yang0123456789/myLeetCode2020 | 5176f2947ead70f70deb7a1327271320c31ac813 | c38d769ce786b53d978c8101018e5a42a4412294 | refs/heads/main | 2023-03-29T05:24:44.402902 | 2021-03-30T15:22:33 | 2021-03-30T15:22:33 | 308,291,030 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,419 | java | package com.JAVA并发编程的艺术.lockTest.ReentrantLockTest;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* # @author chilcyWind
* # @Time 2020/7/22 10:53
* # @version 1.0
* # @File : FairAndUnfairTest.java
* # @Software: IntelliJ IDEA
*/
public class FairAndUnfairTest {
private static Lock fairLock = new ReentrantLock2(true);
private static Lock unfairLock = new ReentrantLock2(false);
private static class ReentrantLock2 extends ReentrantLock {
public ReentrantLock2(boolean fair) {
super(fair);
}
public Collection<Thread> getQueuedThreads() {
List<Thread> arrayList = new ArrayList<Thread>(super.getQueuedThreads());
Collections.reverse(arrayList);
return arrayList;
}
}
public void fair() {
testLock(fairLock);
}
public void unfair() {
testLock(unfairLock);
}
private void testLock(Lock lock) {
// 启动5个Job(略)
}
private static class Job extends Thread {
private Lock lock;
public Job(Lock lock) {
this.lock = lock;
}
public void run() {
}
// 连续2次打印当前的Thread和等待队列中的Thread(略)
}
}
| [
"378525908@qq.com"
] | 378525908@qq.com |
6fdfd34f33d1001241920370d9c9fdc16be7d059 | 9a5133796268317e5ad4c6dc4217fa073fdf9ae2 | /src/main/java/com/online/shop/service/TestService.java | 91a6be39adb5858426a39d05f1dcbcaa4b2a94b7 | [] | no_license | p-ej/Webpro | ce29026f1b3397d8590f52703098a72b6e3594b5 | 5b686e6a90c090f88a2111aed2f221405c3956b3 | refs/heads/master | 2023-07-24T17:28:09.853178 | 2021-08-22T06:50:31 | 2021-08-22T06:50:31 | 398,735,245 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 105 | java | package com.online.shop.service;
public interface TestService {
String TestPrint() throws Exception;
}
| [
"show400035@naver.com"
] | show400035@naver.com |
137068b063aabace07902a999a614f7faace94fe | d079760c88c400276ca067ed156b84a3c8dadd57 | /mybatisdemo/src/main/java/com/mybatis/demo/utils/PubUtils.java | 1ac242b31754c4e7ce221e65acc47dde378ca8ea | [] | no_license | liwenming512/JavaDemos | f962511d7ffdc2b3a83ff0eb28e2b3c288f486b1 | 076e44eeaf1ee68071f3ad1c82fe79594c5c7f2f | refs/heads/master | 2022-05-02T22:41:22.622193 | 2022-03-26T14:28:25 | 2022-03-26T14:28:25 | 93,279,308 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,322 | java | package com.mybatis.demo.utils;/**
* Created by Administrator on 2019/11/20.
*/
import com.mybatis.demo.model.EnumVo;
import java.io.File;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @Author liwenming
* @Description 工具类,静态扫描包中所有的枚举类型
* @Date 2019/11/20 8:47
**/
public class PubUtils {
public final static String INTERFACE_NAME = "com.mybatis.demo.model.ValuedEnum";
private final static Map<Integer, ArrayList<EnumVo>> EnumVoListMap = new HashMap<>();
/**
* 扫描制定目录下所有的.class文件,得到全路径名
* @param basePack 为.java的路径
* @return
* @throws ClassNotFoundException
*/
private static List<String> searchClass(String basePack) throws ClassNotFoundException
{
List<String> classPaths = new ArrayList<String>();
// 包名转换为路径,首先得到项目的classpath
String projectClasspath = PubUtils.class.getResource("/").getPath();
// 包名basPach转换为路径名
basePack = basePack.replace(".", File.separator);
// 合并classpath和basePack
String searchPath = projectClasspath + basePack;
doPath(projectClasspath, new File(searchPath), classPaths);
return classPaths;
}
/**
* 该方法会得到所有的类,将类的绝对路径写入到classPaths中
* @param file
*/
private static void doPath(String projectClasspath, File file, List<String> classPaths)
{
if (file.isDirectory())
{// 文件夹
// 文件夹就递归
File[] files = file.listFiles();
for (File fileTemp : files)
{
doPath(projectClasspath, fileTemp, classPaths);
}
}
else
{// 标准文件
// 标准文件判断是否是class文件
if (file.getName().endsWith(".class"))
{
// 如果是class文件的绝对路径转换为全类名放入集合中。
classPaths
.add(file.getPath().replace(projectClasspath.replace("/", "\\").replaceFirst("\\\\", ""), "").replace("\\", ".").replace(".class", ""));
}
}
}
public static Map<Integer, ArrayList<EnumVo>> getAllEnumVoList(){
if (EnumVoListMap == null || EnumVoListMap.size() == 0){
List<String> classPaths = new ArrayList<>();
try {
classPaths = PubUtils.searchClass("com.mybatis.demo.model");
for(String classPath:classPaths){
Class<?> cls = null;
cls = Class.forName(classPath);
Class <?>[]iter=cls.getInterfaces();
for(Class cz:iter){
if (cz.getName().equals(INTERFACE_NAME)){
//反射获取枚举类
Class<Enum> clazz = (Class<Enum>) Class.forName(classPath);
//获取所有枚举实例
Enum[] enumConstants = clazz.getEnumConstants();
//根据方法名获取方法
try {
Method val = clazz.getMethod("getKey");
Method desc = clazz.getMethod("getValue");
ArrayList<EnumVo> enumVoList = new ArrayList<EnumVo>();
Enum enum0 = enumConstants[0];
Object obj0 = val.invoke(enum0);
Integer key = Integer.valueOf(obj0.toString()) / 100 * 100;
for (Enum enum1 : enumConstants) {
//执行枚举方法获得枚举实例对应的值
Object invoke1 = val.invoke(enum1);
Object invoke2 = desc.invoke(enum1);
// System.out.println(invoke1.toString()+":"+invoke2.toString()+":" +enum1.name());
EnumVo enumVo = new EnumVo();
enumVo.setKey(Integer.valueOf(invoke1.toString()));
enumVo.setValue(invoke2.toString());
enumVo.setName(enum1.name());
enumVoList.add(enumVo);
}
EnumVoListMap.put(key, enumVoList);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
return EnumVoListMap;
}
public static List<EnumVo> getEnumVoListByCode(Integer code){
return PubUtils.getAllEnumVoList().get(code);
}
public static void main(String[] args) {
List<EnumVo> enumVoList = PubUtils.getEnumVoListByCode(11600);
for(EnumVo enumVo: enumVoList){
System.out.println(enumVo.toString());
}
}
}
| [
"liwenming@ane56.com"
] | liwenming@ane56.com |
1c28e301308ffe7ccab6875df65147e8fd871182 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/22/22_a01cb3e95971cab21eec98eb1459a593fd41109f/Database/22_a01cb3e95971cab21eec98eb1459a593fd41109f_Database_s.java | c8f1c89c22285e4efd5a501f886cb37d24261bf2 | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 4,182 | java | package program;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
public class Database
{
private static Connection handle;
private static void connect() throws ClassNotFoundException, SQLException
{
Class.forName("com.mysql.jdbc.Driver");
handle = DriverManager.getConnection("jdbc:mysql://" + Start.getDetails().getDbServer() + ":" + Start.getDetails().getDbPort() + "/" + Start.getDetails().getDbTable(),Start.getDetails().getDbUser(),Start.getDetails().getDbpasswd());
}
private static void disconnect() throws SQLException
{
handle.close();
}
public static void updateUser(String username) throws SQLException, ClassNotFoundException
{
connect();
ResultSet exist = (handle.createStatement().executeQuery("SELECT COUNT(*) FROM User WHERE NickName =\"" + username + "\""));
int temp = 0;
while(exist.next())
temp = exist.getInt(1);
if (temp != 0)
{
String sql = "UPDATE User SET SentMsg = SentMsg + 1, LastOnline = NOW() WHERE NickName = \"" + username + "\"";
//System.out.println(sql);
handle.createStatement().executeUpdate(sql);
}
else
{
handle.createStatement().executeUpdate("INSERT INTO User(NickName, Rep, SentMsg, LastOnline) VALUES(\"" + username + "\", \"0\", \"0\", NOW())");
}
System.out.println("Updated Database");
disconnect();
}
public static void updateRep(String username,int rep) throws ClassNotFoundException, SQLException
{
connect();
ResultSet exist = (handle.createStatement().executeQuery("SELECT COUNT(*) FROM User WHERE NickName =\"" + username + "\""));
int temp = 0;
while(exist.next())
temp = exist.getInt(1);
if (temp != 0)
{
String sql = "UPDATE User SET Rep = Rep + " + rep + " WHERE NickName = \"" + username + "\"";
//System.out.println(sql);
handle.createStatement().executeUpdate(sql);
}
disconnect();
}
public static int getUserRep(String username) throws ClassNotFoundException, SQLException
{
connect();
ResultSet exist = (handle.createStatement().executeQuery("SELECT * FROM User WHERE NickName =\"" + username + "\" LIMIT 1"));
int temp = 0;
while(exist.next())
temp = exist.getInt("Rep");
disconnect();
return temp;
}
public static int getMessagesSent(String username) throws ClassNotFoundException, SQLException
{
connect();
ResultSet exist = (handle.createStatement().executeQuery("SELECT * FROM User WHERE NickName =\"" + username + "\" LIMIT 1"));
int temp = 0;
while(exist.next())
temp = exist.getInt("SentMsg");
disconnect();
return temp;
}
public static String getLastOnline(String username) throws ClassNotFoundException, SQLException
{
connect();
ResultSet exist = (handle.createStatement().executeQuery("SELECT * FROM User WHERE NickName =\"" + username + "\" LIMIT 1"));
String temp = "";
while(exist.next())
temp = exist.getString("LastOnline");
disconnect();
return temp;
}
public static void addReminder(String usernameSender,String usernameRecipicant, String message) throws SQLException, ClassNotFoundException
{
connect();
handle.createStatement().executeUpdate("INSERT INTO remind(Sender,Recipient,Message) VALUES(\"" + usernameSender + "\", \"" + usernameRecipicant +"\", \""+ message +"\")");
disconnect();
}
public static String[] getReminders(String username) throws ClassNotFoundException, SQLException
{
connect();
ResultSet exist = (handle.createStatement().executeQuery("SELECT * FROM remind WHERE Recipient =\"" + username + "\""));
ArrayList<String> temp = new ArrayList<String>();
while(exist.next())
temp.add(exist.getString("Recipient") + ": " + exist.getString("Sender") + " Said " +exist.getString("Message"));
disconnect();
return temp.toArray(new String[temp.size()]);
}
public static void delReminder(String username) throws ClassNotFoundException, SQLException
{
connect();
handle.createStatement().executeUpdate("DELETE FROM remind WHERE Recipient =\"" + username + "\"");
disconnect();
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
a960989d38e74d437bcdb21f557bba713f6e8839 | 4a03811814c988e41825c765995175c16e4ac6a1 | /OpcUaFctAddon-gateway/src/main/java/com/bouyguesenergiesservices/opcuafctaddon/gateway/fct/gan/IGatewayFctGAN.java | d60f3d15e037fb2092ab9f68fe9789d62ec5d3de | [] | no_license | IgnitionModuleDevelopmentCommunity/OpcUaFctAddon | 9e0dd6d1395fd3bd682df31b23478adf1c0421a5 | e6cbc0a8fe12042088454d9402299efcefed9f1e | refs/heads/master | 2020-12-14T09:52:54.187544 | 2017-10-10T12:49:04 | 2017-10-10T12:49:04 | 95,464,964 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 422 | java | package com.bouyguesenergiesservices.opcuafctaddon.gateway.fct.gan;
import java.util.List;
/**
* Just an interface to describe all functions available trough the GAN
*/
public interface IGatewayFctGAN {
boolean subscribe(String opcServer, List<String> lstItemPath, int rate);
void unSubscribe();
void notifyClosureGANClient();
void shutdown();
String toString();
void keepAlive();
}
| [
"r.lebohec@bouygues-es-siai.com"
] | r.lebohec@bouygues-es-siai.com |
5502a6c565fc2464e09abfbbb1e3df65e740b3f8 | 759347a5b75f088e1ba04571782e6a5d3ca69825 | /traditional_mutants/double_average(int)/ROR_232/MethodCollection2.java | 38f5b50c8be348010806d283188c4db1310af220 | [] | no_license | ps073006/testJavaMR | 218248584c64d1c239a5c428571b4cff44143484 | 3c6d9c5188c3ce4cefe0b3be5a4685503bb00f1b | refs/heads/master | 2021-01-10T04:37:47.334249 | 2016-02-02T02:22:28 | 2016-02-02T02:22:28 | 50,891,432 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 11,823 | java | // This is a mutant program.
// Author : ysma
package Test;
public class MethodCollection2
{
public static int add_values( int[] a )
{
int sum = 0;
for (int i = 0; i < a.length; i++) {
sum += a[i];
}
return sum;
}
public static double add_two_array_values( int[] a, int i, int j )
{
if (i < 0 || i >= a.length || j < 0 || j >= a.length) {
return -100000;
} else {
return a[i] + a[j] / 2.0;
}
}
public static int[] bubble( int[] a )
{
int i;
int j;
int t;
for (i = a.length - 2; i >= 0; i--) {
for (j = 0; j <= i; j++) {
if (a[j] > a[j + 1]) {
t = a[j];
a[j] = a[j + 1];
a[j + 1] = t;
}
}
}
return a;
}
public static int[] shell_sort( int[] a )
{
int j;
int i;
int k;
int m;
int mid;
for (m = a.length / 2; m > 0; m /= 2) {
for (j = m; j < a.length; j++) {
for (i = j - m; i >= 0; i -= m) {
if (a[i + m] >= a[i]) {
break;
} else {
mid = a[i];
a[i] = a[i + m];
a[i + m] = mid;
}
}
}
}
return a;
}
public static int sequential_search( int[] a, int key )
{
int i;
for (i = 0; i < a.length; i++) {
if (a[i] == key) {
return i;
}
}
return -1;
}
public static int[] selection_sort( int[] list )
{
int i;
int j;
int min;
for (i = 0; i < list.length - 1; i++) {
min = i;
for (j = i + 1; j < list.length; j++) {
if (list[j] < list[min]) {
min = j;
}
}
int tmp = list[i];
list[i] = list[min];
list[min] = tmp;
}
return list;
}
public static int add_values_in_two_arrays( int[] a, int[] b, int i )
{
if (i < 0 || i >= a.length || i >= b.length) {
return -100000;
} else {
return a[i] + b[i];
}
}
public static int dot_product( int[] a, int[] b )
{
int sum = 0;
int i;
for (i = 0; i < a.length; i++) {
sum += a[i] * b[i];
}
return sum;
}
public static int[] array_calc1( int[] a, int k )
{
int i;
int[] b = new int[a.length];
for (i = 0; i < a.length; i++) {
b[i] = a[i] / k;
}
return b;
}
public static int[] set_min_val( int[] a, int k )
{
int i;
for (i = 0; i < a.length; i++) {
if (a[i] < k) {
a[i] = k;
}
}
return a;
}
public static int get_array_value( int[] a, int k )
{
if (k - 1 >= a.length || k - 1 < 0) {
return -100000;
} else {
return a[k - 1];
}
}
public static int find_min( int[] a )
{
int min = a[0];
int i;
for (i = 0; i < a.length; i++) {
if (a[i] < min) {
min = a[i];
}
}
return min;
}
public static int[] find_diff( int[] a, int[] b )
{
int i;
int[] c = new int[a.length];
for (i = 0; i < a.length; i++) {
c[i] = a[i] - b[i];
}
return c;
}
public static int[] array_copy( int[] a )
{
int i;
int[] b = new int[a.length];
for (i = 0; i < a.length; i++) {
b[i] = a[i];
}
return b;
}
public static double find_euc_dist( int[] a, int[] b )
{
int i;
double sum = 0;
for (i = 0; i < a.length; i++) {
sum += (a[i] - b[i]) * (a[i] - b[i]);
}
double result = Math.sqrt( sum );
return result;
}
public static double find_magnitude( int[] a )
{
int i;
double sum = 0;
for (i = 0; i < a.length; i++) {
sum += a[i] * a[i];
}
double result = Math.sqrt( sum );
return result;
}
public static double manhattan_dist( int[] a, int[] b )
{
int i;
double sum = 0;
for (i = 0; i < a.length; i++) {
sum += Math.abs( a[i] - b[i] );
}
return sum;
}
public static double average( int[] a )
{
double sum = 0;
for (int i = 0; i > a.length; i++) {
sum += a[i];
}
return sum / a.length;
}
public static int[] dec_array( int[] a, int k )
{
int i;
for (i = 0; i < a.length; i++) {
a[i] -= k;
}
return a;
}
public static double expr1( double a, double b )
{
double result = (b - a) / a;
return result;
}
public static int find_max( int[] a )
{
int max = a[0];
for (int i = 0; i < a.length; i++) {
if (a[i] > max) {
max = a[i];
}
}
return max;
}
public static int find_max2( int[] a )
{
int max = a[0] + a[1];
for (int i = 0; i < a.length - 1; i++) {
if (a[i] + a[i + 1] > max) {
max = a[i] + a[i + 1];
}
}
return max;
}
public static double variance( double[] x )
{
double sum = 0;
double sum1 = 0;
double var = 0;
double avrg = 0;
for (int i = 0; i < x.length; i++) {
sum = sum + x[i];
}
avrg = sum / (double) x.length;
for (int i = 0; i < x.length; i++) {
sum1 = sum1 + (x[i] - avrg) * (x[i] - avrg);
}
var = sum1 / (double) x.length;
return var;
}
public static int[] insertion_sort( int[] array )
{
for (int i = 1; i < array.length; i++) {
int j = i;
int B = array[i];
while (j > 0 && array[j - 1] > B) {
array[j] = array[j - 1];
j--;
}
array[j] = B;
}
return array;
}
public static double geometric_mean( int[] a )
{
long product = 1;
for (int i = 0; i < a.length; i++) {
product *= a[i];
}
return Math.pow( product, (double) 1 / a.length );
}
public static double mean_absolute_error( int[] a, int[] b )
{
int sum = 0;
for (int i = 0; i < a.length; i++) {
sum += Math.abs( a[i] - b[i] );
}
return (double) sum / a.length;
}
public static double find_median( int[] a )
{
int k = a.length / 2 + 1;
int minIndex = 0;
int minValue = a[0];
for (int i = 0; i < k; i++) {
minIndex = i;
minValue = a[i];
for (int j = i + 1; j < a.length; j++) {
if (a[j] < minValue) {
minIndex = j;
minValue = a[j];
}
}
int temp = a[i];
a[i] = a[minIndex];
a[minIndex] = temp;
}
if (a.length % 2 == 0) {
return (double) (a[a.length / 2 - 1] + a[a.length / 2]) / 2;
} else {
return a[a.length / 2];
}
}
public static int[][] cartesian_product( int[] a, int[] b )
{
int[][] result = new int[a.length * b.length][2];
int cnt = 0;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < b.length; j++) {
result[cnt][0] = a[i];
result[cnt][1] = b[j];
cnt++;
}
}
return result;
}
public static int[] reverse( int[] a )
{
int[] r = new int[a.length];
int cnt = 0;
for (int i = a.length - 1; i >= 0; i--) {
r[cnt] = a[i];
cnt++;
}
return r;
}
public static boolean check_equal_tolerance( double[] a, double[] b, double tol )
{
if (a.length != b.length) {
return false;
}
for (int i = 0; i < a.length; i++) {
if (Math.abs( a[i] - b[i] ) >= tol) {
return false;
}
}
return true;
}
public static boolean check_equal( int[] a, int[] b )
{
if (a.length != b.length) {
return false;
}
for (int i = 0; i < a.length; i++) {
if (a[i] != b[i]) {
return false;
}
}
return true;
}
public static double weighted_average( double[] a, double[] b )
{
double sum1 = 0;
double sum2 = 0;
for (int i = 0; i < a.length; i++) {
sum1 += a[i] * b[i];
sum2 += b[i];
}
return sum1 / sum2;
}
public static int count_k( int[] a, int k )
{
int cnt = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] == k) {
cnt++;
}
}
return cnt;
}
public static int[] clip( int[] a, int lowerLim, int upperLim )
{
int[] r = new int[a.length];
for (int i = 0; i < a.length; i++) {
if (a[i] < lowerLim) {
r[i] = lowerLim;
} else {
if (a[i] > upperLim) {
r[i] = upperLim;
} else {
r[i] = a[i];
}
}
}
return r;
}
public static int[] elementwise_max( int[] a, int[] b )
{
int[] r = new int[a.length];
for (int i = 0; i < a.length; i++) {
if (a[i] > b[i]) {
r[i] = a[i];
} else {
r[i] = b[i];
}
}
return r;
}
public static int[] elementwise_min( int[] a, int[] b )
{
int[] r = new int[a.length];
for (int i = 0; i < a.length; i++) {
if (a[i] < b[i]) {
r[i] = a[i];
} else {
r[i] = b[i];
}
}
return r;
}
public static int count_non_zeroes( int[] a )
{
int cnt = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] != 0) {
cnt++;
}
}
return cnt;
}
public static int cnt_zeroes( int[] a )
{
int cnt = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] == 0) {
cnt++;
}
}
return cnt;
}
public static boolean[] elementwise_equal( int[] a, int[] b )
{
boolean[] r = new boolean[a.length];
for (int i = 0; i < a.length; i++) {
if (a[i] == b[i]) {
r[i] = true;
} else {
r[i] = false;
}
}
return r;
}
public static boolean[] elementwise_not_equal( int[] a, int[] b )
{
boolean[] r = new boolean[a.length];
for (int i = 0; i < a.length; i++) {
if (a[i] != b[i]) {
r[i] = true;
} else {
r[i] = false;
}
}
return r;
}
public static int hamming_dist( int[] a, int[] b )
{
int cnt = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] != b[i]) {
cnt++;
}
}
return cnt;
}
}
| [
"engr.ps07@gmail.com"
] | engr.ps07@gmail.com |
d27dccc08582dcca5c9ae3082878cf72908a4252 | 0af8b92686a58eb0b64e319b22411432aca7a8f3 | /large-multiproject/project60/src/test/java/org/gradle/test/performance60_1/Test60_1.java | 66c8571497911184bb4815c73a8e10f2e3295ce8 | [] | no_license | gradle/performance-comparisons | b0d38db37c326e0ce271abebdb3c91769b860799 | e53dc7182fafcf9fedf07920cbbea8b40ee4eef4 | refs/heads/master | 2023-08-14T19:24:39.164276 | 2022-11-24T05:18:33 | 2022-11-24T05:18:33 | 80,121,268 | 17 | 15 | null | 2022-09-30T08:04:35 | 2017-01-26T14:25:33 | null | UTF-8 | Java | false | false | 286 | java | package org.gradle.test.performance60_1;
import static org.junit.Assert.*;
public class Test60_1 {
private final Production60_1 production = new Production60_1("value");
@org.junit.Test
public void test() {
assertEquals(production.getProperty(), "value");
}
} | [
"cedric.champeau@gmail.com"
] | cedric.champeau@gmail.com |
9120800bae8f3b9a3d880dbf52897e994b36ea93 | 25ea4d858fa4748c72fdcaaa7dc29cfc957fd090 | /src/main/java/com/soapws/webservice/customerUpdate/RequestMessageKey.java | 81e4e85c44ac690bd7ae797e9faf16733d9b5b72 | [] | no_license | ChibuezePaul/soap-webservice | ed2ea2765b0504dc4b25cadf39a57ac14796c3a5 | 849bda136b21360ca11e8c97c133c1ba7aa70277 | refs/heads/master | 2023-04-13T17:39:29.356503 | 2019-07-09T12:02:38 | 2019-07-09T12:02:38 | 362,274,120 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,069 | java | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2019.07.01 at 02:28:42 PM GMT+01:00
//
package com.soapws.webservice.customerUpdate;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for RequestMessageKey complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="RequestMessageKey">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="RequestUUID" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="ServiceRequestId" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="ServiceRequestVersion" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="ChannelId" type="{http://www.w3.org/2001/XMLSchema}string"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "RequestMessageKey", propOrder = {
"requestUUID",
"serviceRequestId",
"serviceRequestVersion",
"channelId"
})
public class RequestMessageKey {
@XmlElement(name = "RequestUUID", required = true)
protected String requestUUID = "Req_1561731915070";
@XmlElement(name = "ServiceRequestId", required = true)
protected String serviceRequestId = "RetCustMod";
@XmlElement(name = "ServiceRequestVersion", required = true)
protected String serviceRequestVersion = "10.2";
@XmlElement(name = "ChannelId", required = true)
protected String channelId = "CRM";
/**
* Gets the value of the requestUUID property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRequestUUID() {
return requestUUID;
}
/**
* Sets the value of the requestUUID property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRequestUUID(String value) {
this.requestUUID = value;
}
/**
* Gets the value of the serviceRequestId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getServiceRequestId() {
return serviceRequestId;
}
/**
* Sets the value of the serviceRequestId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setServiceRequestId(String value) {
this.serviceRequestId = value;
}
/**
* Gets the value of the serviceRequestVersion property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getServiceRequestVersion() {
return serviceRequestVersion;
}
/**
* Sets the value of the serviceRequestVersion property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setServiceRequestVersion(String value) {
this.serviceRequestVersion = value;
}
/**
* Gets the value of the channelId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getChannelId() {
return channelId;
}
/**
* Sets the value of the channelId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setChannelId(String value) {
this.channelId = value;
}
}
| [
"chibueze.paul@longbridgetech.com"
] | chibueze.paul@longbridgetech.com |
e6ab2fef7a5017114bb561e920c4b067bde926c0 | ab8fd0f1ea03b102ab4054194ec4c6f3f40f15d7 | /module 4/lession_06_jpa/exercises/blog_app/src/main/java/com/example/blog/controller/BlogController.java | f3f5cdc549a5437bfd6185bc5cec6e61e9132782 | [] | no_license | honhatlong14/C1120G1-Ho-Nhat-Long | 2ec5d09d2840d617b18292afa7a8be3d44cf68ec | 11981cc0545c5e0768c942a899b36697cf5297c5 | refs/heads/main | 2023-04-29T05:01:20.047327 | 2021-05-18T17:34:16 | 2021-05-18T17:34:16 | 341,770,361 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,542 | java | package com.example.blog.controller;
import com.example.blog.model.Blog;
import com.example.blog.service.BlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
@Controller
public class BlogController {
@Autowired
private BlogService blogService;
@GetMapping
public String home(Model model){
model.addAttribute("blogs", blogService.findAll());
return "list";
}
@GetMapping("/create")
public String create(Model model){
model.addAttribute("blog",new Blog());
return "create";
}
@PostMapping("/create")
public String create(@ModelAttribute("blog") Blog blog){
blogService.create(blog);
return "redirect:/";
}
@GetMapping("/edit/{id}")
public String edit(@PathVariable("id") int id, Model model){
model.addAttribute("blog",blogService.findById(id));
return "edit";
}
@PostMapping("/edit")
public String edit(@ModelAttribute("edit") Blog blog){
blogService.update(blog);
return "redirect:/";
}
@GetMapping("/blog/delete")
public String delete(@RequestParam int id){
blogService.delete(id);
return "redirect:/";
}
@GetMapping("/view/{id}")
public String view(@PathVariable("id") int id, Model model){
model.addAttribute("blog", blogService.findById(id));
return "view";
}
}
| [
"honhatlongg@gmail.com"
] | honhatlongg@gmail.com |
7eaa09e76117df3c3be6ffffbd68b2b2cc5524a4 | 1b037becff6aa4997050bf01b350d06fe37629e4 | /src/com/papagiannis/tuberun/fetchers/RequestTask.java | c8688fecd4b6513ce5f970b50825e3e9c9b4f30a | [] | no_license | Hasanabbas/tuberun_android | 51a65ab70fb838818b33e7ef0336436a914b18b0 | d47d613235207c4fab3c845e0e4e71c16ffc8c47 | refs/heads/master | 2018-01-13T21:24:35.966098 | 2013-09-16T21:36:43 | 2013-09-16T21:36:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,856 | java | package com.papagiannis.tuberun.fetchers;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import android.os.AsyncTask;
import android.util.Log;
import com.papagiannis.tuberun.TubeRun;
public class RequestTask extends AsyncTask<String, String, String> {
protected String myUserAgent="Tuberun/"+TubeRun.VERSION+" Android";
private HttpCallback cb;
public RequestTask(HttpCallback cb) {
super();
this.cb = cb;
}
public RequestTask setDesktopUserAgent() {
myUserAgent="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.12 Safari/535.11";
return this;
}
CookieStore cookieStore ;
HttpContext localContext ;
public void setCookies(CookieStore c) {
cookieStore = c;
localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
}
@Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = "";
try {
HttpGet get=new HttpGet(uri[0]);
get.setHeader("User-Agent", myUserAgent);
if (localContext==null) response = httpclient.execute(get);
else response = httpclient.execute(get,localContext);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
String encoding="ISO-8859-1";
boolean isUTF=false;
Header[] headers=response.getAllHeaders();
for (Header header:headers) {
if (header.getName().equals("Content-Type") && header.getValue().contains("utf-8")) {
isUTF=true;
break;
}
}
if (isUTF) {
encoding="UTF-8";
}
responseString = out.toString(encoding);
} else {
// Closes the connection.
if (response!=null && response.getEntity()!=null) response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (Exception e) {
Log.e("Fetcher","Fetching", e);
}
return responseString;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (!isCancelled()) {
cb.onReturn(result);
}
}
}
| [
"jpapayan@gmail.com"
] | jpapayan@gmail.com |
7275a809f4af0750a81666bd76fe79a9a38946fb | f0d16ffac3ccd4f8c398a7494f80c6d563a1c244 | /IMe/src/com/gotye/api/listener/RoomListener.java | 0fbf39f2837367531b7f1ab368523a3cca2e5d2e | [] | no_license | Dreamflying/Android-FangDingMaster | 3571bbbf6ed52dab6629827cf936fab09175b3b7 | 877fe40f1c27fb39aef7da15787e750208839439 | refs/heads/master | 2020-05-20T07:24:23.161550 | 2015-04-07T12:50:01 | 2015-04-07T12:50:01 | 32,905,961 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,701 | java | package com.gotye.api.listener;
import java.util.List;
import com.gotye.api.GotyeMessage;
import com.gotye.api.GotyeRoom;
import com.gotye.api.GotyeStatusCode;
import com.gotye.api.GotyeUser;
public interface RoomListener extends GotyeListener{
/**
* 进入聊天室回调
* @param code 状态码 参见 {@link GotyeStatusCode}
* @param lastMsgID 该聊天室最后一条消息id
* @param room 当前聊天室对象
*/
void onEnterRoom(int code, long lastMsgID, GotyeRoom room);
/**
* 离开聊天室
* @param code 状态码 参见 {@link GotyeStatusCode}
* @param room 当前聊天室对象
*/
void onLeaveRoom(int code, GotyeRoom room);
/**
* 回去聊天室列表
* @param code 状态码 参见 {@link GotyeStatusCode}
* @param roomList 聊天室列表
*/
void onGetRoomList(int code, List<GotyeRoom> roomList);
/**
* 获取聊天室成员列表
* @param code 状态码 参见 {@link GotyeStatusCode}
* @param room 当前聊天室
* @param totalMembers 每页结果集合
* @param currentPageMembers 当前页集合
* @param pageIndex 当前页码
*/
void onGetRoomMemberList(int code, GotyeRoom room,
List<GotyeUser> totalMembers, List<GotyeUser> currentPageMembers,
int pageIndex);
/**
* 获取历史消息回调
* @deprecated
* @param code 状态码 参见 {@link GotyeStatusCode}
* @param list 历史消息列表
*/
void onGetHistoryMessageList(int code, List<GotyeMessage> list);
/**
* 获取聊天室详情
* @param code 状态码 参见 {@link GotyeStatusCode}
* @param room 聊天室对象
*/
void onRequestRoomInfo(int code,GotyeRoom room);
}
| [
"1522651962@qq.com"
] | 1522651962@qq.com |
fbbacc3ec0bd04380a1b5b3d3e577bd05615ff6c | 5efa0978fb7aa58ea73fca5d78cd5fb286fab3ac | /src/seleniumSessions/FrameHandling.java | dd1475130b1ef68c85a737863a62ba8ac83737ed | [] | no_license | TonimaGoswami/SeleniumNewTutorial | 935c21e35d71a3297cba55105a0d91896bc19a46 | 3f9b857faf0be5b613f60b18feff6022404b8df2 | refs/heads/master | 2020-09-27T01:34:24.310512 | 2019-12-06T19:04:47 | 2019-12-06T19:04:47 | 226,392,108 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,583 | java | package seleniumSessions;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class FrameHandling {
WebDriver driver;
public void setUp() {
System.setProperty("webdriver.chrome.driver", "/Users/tanu/Downloads/IMP-Drivers/chromedriver");
driver = new ChromeDriver(); // launch chrome
// driver.manage().window().maximize(); //maximize window
// driver.manage().deleteAllCookies(); //delete cookies
// dynamic waits
driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
// enter Url
driver.get("https://www.freecrm.com");
}
public void login() throws InterruptedException {
driver.findElement(By.name("username")).sendKeys("ishita");
driver.findElement(By.name("password")).sendKeys("141414");
WebElement loginBtn = driver.findElement(By.xpath("//input[@type='submit']"));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", loginBtn);
Thread.sleep(3000);
driver.switchTo().frame("mainpanel");
// Thread.sleep(2000);
driver.findElement(By.xpath("//a[contains(text(),'Contacts')]")).click();
}
public void tearDown() {
driver.quit();
}
public static void main(String[] args) throws InterruptedException {
FrameHandling handle = new FrameHandling();
handle.setUp();
handle.login();
handle.tearDown();
}
}
| [
"tonimagoswami@gmail.com"
] | tonimagoswami@gmail.com |
60729f1e2bcca89957b51ab18c0d2e5cd32dec06 | aaae74dde878ae6791f9087eac0253b1a5cf769c | /woowacrew-domain/src/test/java/woowacrew/comment/domain/CommentRepositoryTest.java | 6ea770ed83cba5e79353def26253ea2e260886a5 | [] | no_license | WoowaCrew/WoowaCrew | 8093779c88cf7ef7db94180ef16f8bff3ccc1cfd | c3d981e4b3e9e2af3c580d8f0c736f04b2e8caba | refs/heads/develop | 2022-12-13T11:11:48.056395 | 2021-03-15T12:49:57 | 2021-03-15T12:49:57 | 216,480,234 | 38 | 14 | null | 2022-12-11T18:35:42 | 2019-10-21T04:52:48 | Java | UTF-8 | Java | false | false | 1,840 | java | package woowacrew.comment.domain;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import woowacrew.JpaTestConfiguration;
import woowacrew.article.free.domain.Article;
import woowacrew.article.free.domain.ArticleRepository;
import woowacrew.degree.domain.Degree;
import woowacrew.degree.domain.DegreeRepository;
import woowacrew.user.domain.User;
import woowacrew.user.domain.UserRepository;
import woowacrew.user.domain.exception.DegreeBoundException;
import static org.assertj.core.api.Assertions.assertThat;
@ExtendWith(SpringExtension.class)
@DataJpaTest
@ContextConfiguration(classes = JpaTestConfiguration.class)
class CommentRepositoryTest {
@Autowired
private DegreeRepository degreeRepository;
@Autowired
private UserRepository userRepository;
@Autowired
private ArticleRepository articleRepository;
@Autowired
private CommentRepository commentRepository;
@Test
void Article이_삭제되면_그에따른_comment도_삭제된다() {
Degree degree = degreeRepository.findByDegreeNumber(0)
.orElseThrow(DegreeBoundException::new);
User author = userRepository.save(new User("oauthId", degree));
Article article = articleRepository.save(new Article("title", "content", author));
Comment comment = commentRepository.save(new Comment(author, "content", article));
articleRepository.deleteById(article.getId());
articleRepository.flush();
assertThat(commentRepository.existsById(comment.getId())).isFalse();
}
} | [
"noreply@github.com"
] | WoowaCrew.noreply@github.com |
50fa181a3153dc87175528e91878cfa64184896e | 7c9f40c50e5cabcb320195e3116384de139002c6 | /Plugin_Parser/src/tinyos/yeti/nesc12/parser/actions/Action646.java | 6bc485a5a6c5116e40380ffce4b92cd6489053d6 | [] | no_license | phsommer/yeti | 8e89ad89f1a4053e46693244256d03e71fe830a8 | dec8c79e75b99c2a2a43aa5425f608128b883e39 | refs/heads/master | 2021-01-10T05:33:57.285499 | 2015-05-21T19:41:02 | 2015-05-21T19:41:02 | 36,033,399 | 3 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,506 | java | /*
* Yeti 2, NesC development in Eclipse.
* Copyright (C) 2009 ETH Zurich
*
* 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/>.
*
* Web: http://tos-ide.ethz.ch
* Mail: tos-ide@tik.ee.ethz.ch
*/
package tinyos.yeti.nesc12.parser.actions;
import tinyos.yeti.nesc12.lexer.Token;
import tinyos.yeti.nesc12.lexer.Lexer;
import tinyos.yeti.nesc12.parser.ast.*;
import tinyos.yeti.nesc12.parser.ast.nodes.*;
import tinyos.yeti.nesc12.parser.ast.nodes.declaration.*;
import tinyos.yeti.nesc12.parser.ast.nodes.definition.*;
import tinyos.yeti.nesc12.parser.ast.nodes.error.*;
import tinyos.yeti.nesc12.parser.ast.nodes.expression.*;
import tinyos.yeti.nesc12.parser.ast.nodes.general.*;
import tinyos.yeti.nesc12.parser.ast.nodes.nesc.*;
import tinyos.yeti.nesc12.parser.ast.nodes.statement.*;
import tinyos.yeti.nesc12.parser.*;
public final class Action646 implements ParserAction{
public final java_cup.runtime.Symbol do_action(
int CUP$parser$act_num,
java_cup.runtime.lr_parser CUP$parser$parser,
java.util.Stack CUP$parser$stack,
int CUP$parser$top,
parser parser)
throws java.lang.Exception{
java_cup.runtime.Symbol CUP$parser$result;
// c_direct_declarator_no_typedef_name ::= c_identifier P_POINT c_identifier
{
Declarator RESULT =null;
Identifier i = (Identifier)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value;
Identifier d = (Identifier)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value;
RESULT = new NesCNameDeclarator( i, d );
CUP$parser$result = parser.getSymbolFactory().newSymbol("c_direct_declarator_no_typedef_name",104, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
}
return CUP$parser$result;
}
}
| [
"besigg@2a69fd7c-12de-fc47-e5bb-db751a41839b"
] | besigg@2a69fd7c-12de-fc47-e5bb-db751a41839b |
935e58635d49ea78dd6fe7f669cbab3196aacb91 | 4748ce2f06dc6bedb3644e8f298c8da54a9df932 | /Job-Portal-BackEnd/src/main/java/lk/ijse/jobportal/service/impl/IndustryServiceImpl.java | e93db4841cd11c239ddf3272efffe23812eece4a | [] | no_license | IshaniWijesekara/jobPortal | 581a30334b62de5787c0b2f5a54ba56288d64aa8 | f999e739f3c3b22e520494ad20f6799f02e5c3f4 | refs/heads/master | 2020-04-01T06:32:43.809612 | 2018-10-14T08:59:43 | 2018-10-14T08:59:43 | 152,952,700 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,583 | java | package lk.ijse.jobportal.service.impl;
import lk.ijse.jobportal.dto.IndustryDTO;
import lk.ijse.jobportal.entity.Industry;
import lk.ijse.jobportal.repository.IndustryRepository;
import lk.ijse.jobportal.service.IndustryService;
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 java.util.ArrayList;
import java.util.List;
@Service
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
public class IndustryServiceImpl implements IndustryService{
@Autowired
private IndustryRepository industryRepository;
@Override
@Transactional(propagation = Propagation.REQUIRED)
public boolean addIndusry(IndustryDTO industryDTO) {
Industry industry=new Industry(industryDTO.getIndustryName());
industryRepository.save(industry);
return true;
}
@Override
public ArrayList<IndustryDTO> getAllIndustry() {
ArrayList<Industry> allIndustry = industryRepository.getAllIndustry();
ArrayList<IndustryDTO> industryDTOS=new ArrayList<>();
for (Industry industry :allIndustry
) {
IndustryDTO industryDTO=new IndustryDTO();
industryDTO.setId(industry.getId());
industryDTO.setIndustryName(industry.getIndustryName());
industryDTOS.add(industryDTO);
}
return industryDTOS;
}
}
| [
"wijesekaraishani23@gmail.com"
] | wijesekaraishani23@gmail.com |
72f3213282231d58ef14558a8fa1ac1c79bd0e6c | 3563e34048e1fb2c527117dca40b30ccea0ef230 | /src/main/java/cn/ruanyun/backInterface/common/wxpay/PaymentApi.java | bb3fde8a3f95fd0dcb9c8ef279051f259bac10cd | [] | no_license | sengeiou/ruanyun | f8ce3cd11973c9b1c1610db70210b793fff14863 | 8c9f643fd33c6ae1b6c72065127d5ff83cd2bbec | refs/heads/master | 2023-08-01T10:32:24.784282 | 2020-05-14T12:49:31 | 2020-05-14T12:49:31 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 11,900 | java | package cn.ruanyun.backInterface.common.wxpay;
import cn.hutool.http.HttpUtil;
import cn.ruanyun.backInterface.common.utils.PaymentKit;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
/**
* @program: ruanyun
* @description: 微信支付api
* @author: fei
* @create: 2020-02-13 16:48
**/
public class PaymentApi {
private PaymentApi() {}
// 文档地址:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1
private static String unifiedOrderUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder";
/**
* 交易类型枚举
* WAP的文档:https://pay.weixin.qq.com/wiki/doc/api/wap.php?chapter=15_1
* @author L.cm
* <pre>
* email: 596392912@qq.com
* site: http://www.dreamlu.net
* date: 2015年10月27日 下午9:46:27
* </pre>
*/
public enum TradeType {
JSAPI, NATIVE, APP, WAP, MWEB
}
/**
* 统一下单
* @param params 参数map
* @return String
*/
public static String pushOrder(Map<String, String> params) {
return HttpUtil.post(unifiedOrderUrl, PaymentKit.toXml(params));
}
private static Map<String, String> request(String url, Map<String, String> params, String paternerKey) {
params.put("nonce_str", System.currentTimeMillis() + "");
String sign = PaymentKit.createSign(params, paternerKey);
params.put("sign", sign);
String xmlStr = HttpUtil.post(url, PaymentKit.toXml(params));
return PaymentKit.xmlToMap(xmlStr);
}
/**
* 文档说明:https://pay.weixin.qq.com/wiki/doc/api/wap.php?chapter=15_4
* <pre>
* @param appId 公众账号ID 是 String(32) wx8888888888888888 微信分配的公众账号ID
* 随机字符串 noncestr 是 String(32) 5K8264ILTKCH16CQ2502SI8ZNMTM67VS 随机字符串,不长于32位。推荐随机数生成算法
* 订单详情扩展字符串 package 是 String(32) WAP 扩展字段,固定填写WAP
* @param prepayId 预支付交易会话标识 是 String(64) wx201410272009395522657a690389285100 微信统一下单接口返回的预支付回话标识,用于后续接口调用中使用,该值有效期为2小时
* 签名 sign 是 String(32) C380BEC2BFD727A4B6845133519F3AD6 签名,详见签名生成算法
* 时间戳 timestamp 是 String(32) 1414561699 当前的时间,其他详见时间戳规则
* @param paternerKey 签名密匙
* </pre>
* @return {String}
*/
public static String getDeepLink(String appId, String prepayId, String paternerKey) {
Map<String, String> params = new HashMap<String, String>();
params.put("appid", appId);
params.put("noncestr", System.currentTimeMillis() + "");
params.put("package", "WAP");
params.put("prepayid", prepayId);
params.put("timestamp", System.currentTimeMillis() / 1000 + "");
String sign = PaymentKit.createSign(params, paternerKey);
params.put("sign", sign);
String string1 = PaymentKit.packageSign(params, true);
String string2 = "";
try { string2 = PaymentKit.urlEncode(string1); } catch (UnsupportedEncodingException e) {}
return "weixin://wap/pay?" + string2;
}
// 文档地址:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_2
private static String orderQueryUrl = "https://api.mch.weixin.qq.com/pay/orderquery";
/**
* 根据商户订单号查询信息
* @param appid 公众账号ID
* @param mch_id 商户号
* @param paternerKey 商户密钥
* @param transaction_id 微信订单号
* @return 回调信息
*/
public static Map<String, String> queryByTransactionId(String appid, String mch_id, String paternerKey, String transaction_id) {
Map<String, String> params = new HashMap<String, String>();
params.put("appid", appid);
params.put("mch_id", mch_id);
params.put("transaction_id", transaction_id);
return request(orderQueryUrl, params, paternerKey);
}
/**
* 根据商户订单号查询信息
* @param appid 公众账号ID
* @param mch_id 商户号
* @param paternerKey 商户密钥
* @param out_trade_no 商户订单号
* @return 回调信息
*/
public static Map<String, String> queryByOutTradeNo(String appid, String mch_id, String paternerKey, String out_trade_no) {
Map<String, String> params = new HashMap<String, String>();
params.put("appid", appid);
params.put("mch_id", mch_id);
params.put("out_trade_no", out_trade_no);
return request(orderQueryUrl, params, paternerKey);
}
// 文档地址:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_3
private static String closeOrderUrl = "https://api.mch.weixin.qq.com/pay/closeorder";
/**
* 关闭订单
* @param appid 公众账号ID
* @param mch_id 商户号
* @param paternerKey 商户密钥
* @param out_trade_no 商户订单号
* @return 回调信息
*/
public static Map<String, String> closeOrder(String appid, String mch_id, String paternerKey, String out_trade_no) {
Map<String, String> params = new HashMap<String, String>();
params.put("appid", appid);
params.put("mch_id", mch_id);
params.put("out_trade_no", out_trade_no);
return request(closeOrderUrl, params, paternerKey);
}
// 申请退款文档地址:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_4
public static String refundUrl = "https://api.mch.weixin.qq.com/secapi/pay/refund";
// 查询退款文档地址:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_5
private static String refundQueryUrl = "https://api.mch.weixin.qq.com/pay/refundquery";
private static Map<String, String> baseRefundQuery(Map<String, String> params, String appid, String mch_id, String paternerKey) {
params.put("appid", appid);
params.put("mch_id", mch_id);
return request(refundQueryUrl, params, paternerKey);
}
/**
* 根据微信订单号查询退款
* @param appid 公众账号ID
* @param mch_id 商户号
* @param paternerKey 商户密钥
* @param transaction_id 微信订单号
* @return map
*/
public static Map<String, String> refundQueryByTransactionId(String appid, String mch_id, String paternerKey, String transaction_id) {
Map<String, String> params = new HashMap<String, String>();
params.put("transaction_id", transaction_id);
return baseRefundQuery(params, appid, mch_id, paternerKey);
}
/**
* 根据微信订单号查询退款
* @param appid 公众账号ID
* @param mch_id 商户号
* @param paternerKey 商户密钥
* @param out_trade_no 商户订单号
* @return map
*/
public static Map<String, String> refundQueryByOutTradeNo(String appid, String mch_id, String paternerKey, String out_trade_no) {
Map<String, String> params = new HashMap<String, String>();
params.put("out_trade_no", out_trade_no);
return baseRefundQuery(params, appid, mch_id, paternerKey);
}
/**
* 根据微信订单号查询退款
* @param appid 公众账号ID
* @param mch_id 商户号
* @param paternerKey 商户密钥
* @param out_refund_no 商户退款单号
* @return map
*/
public static Map<String, String> refundQueryByOutRefundNo(String appid, String mch_id, String paternerKey, String out_refund_no) {
Map<String, String> params = new HashMap<String, String>();
params.put("out_refund_no", out_refund_no);
return baseRefundQuery(params, appid, mch_id, paternerKey);
}
/**
* 根据微信订单号查询退款
* @param appid 公众账号ID
* @param mch_id 商户号
* @param paternerKey 商户密钥
* @param refund_id 微信退款单号
* @return map
*/
public static Map<String, String> refundQueryByRefundId(String appid, String mch_id, String paternerKey, String refund_id) {
Map<String, String> params = new HashMap<String, String>();
params.put("refund_id", refund_id);
return baseRefundQuery(params, appid, mch_id, paternerKey);
}
private static String downloadBillUrl = "https://api.mch.weixin.qq.com/pay/downloadbill";
/**
* <pre>
* ALL,返回当日所有订单信息,默认值
* SUCCESS,返回当日成功支付的订单
* REFUND,返回当日退款订单
* REVOKED,已撤销的订单
* </pre>
*/
public static enum BillType {
ALL, SUCCESS, REFUND, REVOKED
}
/**
* 下载对账单
* <pre>
* 公众账号ID appid 是 String(32) wx8888888888888888 微信分配的公众账号ID(企业号corpid即为此appId)
* 商户号 mch_id 是 String(32) 1900000109 微信支付分配的商户号
* 设备号 device_info 否 String(32) 013467007045764 微信支付分配的终端设备号
* 随机字符串 nonce_str 是 String(32) 5K8264ILTKCH16CQ2502SI8ZNMTM67VS 随机字符串,不长于32位。推荐随机数生成算法
* 签名 sign 是 String(32) C380BEC2BFD727A4B6845133519F3AD6 签名,详见签名生成算法
* 对账单日期 bill_date 是 String(8) 20140603 下载对账单的日期,格式:20140603
* 账单类型 bill_type 否 String(8)
* </pre>
* @param appid 公众账号ID
* @param mch_id 商户号
* @param paternerKey 签名密匙
* @param billDate 对账单日期
* @return String
*/
public static String downloadBill(String appid, String mch_id, String paternerKey, String billDate) {
return downloadBill(appid, mch_id, paternerKey, billDate, null);
}
/**
* 下载对账单
* <pre>
* 公众账号ID appid 是 String(32) wx8888888888888888 微信分配的公众账号ID(企业号corpid即为此appId)
* 商户号 mch_id 是 String(32) 1900000109 微信支付分配的商户号
* 设备号 device_info 否 String(32) 013467007045764 微信支付分配的终端设备号
* 随机字符串 nonce_str 是 String(32) 5K8264ILTKCH16CQ2502SI8ZNMTM67VS 随机字符串,不长于32位。推荐随机数生成算法
* 签名 sign 是 String(32) C380BEC2BFD727A4B6845133519F3AD6 签名,详见签名生成算法
* 对账单日期 bill_date 是 String(8) 20140603 下载对账单的日期,格式:20140603
* 账单类型 bill_type 否 String(8)
* </pre>
* @param appid 公众账号ID
* @param mch_id 商户号
* @param paternerKey 签名密匙
* @param billDate 对账单日期
* @param billType 账单类型
* @return String
*/
public static String downloadBill(String appid, String mch_id, String paternerKey, String billDate, BillType billType) {
Map<String, String> params = new HashMap<String, String>();
params.put("appid", appid);
params.put("mch_id", mch_id);
params.put("nonce_str", System.currentTimeMillis() + "");
params.put("bill_date", billDate);
if (null != billType) {
params.put("bill_type", billType.name());
} else {
params.put("bill_type", BillType.ALL.name());
}
String sign = PaymentKit.createSign(params, paternerKey);
params.put("sign", sign);
return HttpUtil.post(downloadBillUrl, PaymentKit.toXml(params));
}
}
| [
"2240363282@qq.com"
] | 2240363282@qq.com |
d3cbdf8d7169785de4eb0155fa8830ee2967cada | 8d9c809a138f29aa3806ecca2f1a90d0e57fff86 | /AggregateStu/src/edu/hebeu/collection/CollectionInterableStu.java | 89d8d405687b5ce00a1f9b08b46d648a51c3c067 | [] | no_license | Tyong1365137828/stu-java | e9fe76586749e06e41f55edab0001d2c245fccfd | 39b452da284e0a80520359bf2dcf655c2c3d72fb | refs/heads/main | 2023-04-06T11:25:18.794632 | 2021-04-25T07:05:14 | 2021-04-25T07:05:14 | 353,631,034 | 0 | 0 | null | null | null | null | GB18030 | Java | false | false | 3,497 | java | package edu.hebeu.collection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
/**
* Collectio类型集合迭代器的学习,
* 注意:本例下讲解的迭代方式/遍历方式,对所有的Collection来说是通用的一种方式
* 但是,对Map集合不能使用,仅能在Collection以及其子类中使用
*
* 注意:在Java中,集合结构发生改变(集合内的元素增删)后,此集合的迭代器必须重新获取,
* 如果不重新获取迭代器,就会出现异常(java.util.ConcurrentModificationException);
*
* 总结:
* 1、在迭代集合元素的过程中,不能调用集合对象的remove()方法删除元素,因为调用这个方法会改变集合的结构,
* 通过上述注意点会出现java.util.ConcurrentModificationException异常;
* 2、如果一定要在迭代过程中删除元素,可以调用迭代器对象的remove()方法,此方法会将迭代器当前指向的元素删除;
* 不要使用集合自带的remove()方法删除元素!!!
* @author 13651
*
*/
public class CollectionInterableStu {
public static void main(String[] args) {
// 创建集合对象ArrayList,有序可重复;
Collection arrayC = new ArrayList();
// 添加元素至集合
arrayC.add(123);
arrayC.add(123);
arrayC.add(123);
arrayC.add("你好");
arrayC.add(2.56);
arrayC.add("???");
arrayC.add("???");
arrayC.add(true);
arrayC.add(true);
arrayC.add(true);
arrayC.add(true);
// 对集合进行遍历
// 第一步:获取集合对象的迭代器对象arrayIterator
Iterator arrayIterator = arrayC.iterator();
// 第二步:通过上面的迭代器结合迭代器工作原理进行遍历/迭代集合
System.out.print("ArrayList{");
while(arrayIterator.hasNext()) { // 判断当前元素的下面是否还有元素(判断还能否迭代)
Object obj = arrayIterator.next(); // 将迭代器指向下一个元素,并将当前指向的元素返回出去(进行迭代)
System.out.print(obj);
// arrayC.remove(obj); // 迭代过程中使用集合内的方法删除元素,改变集合结构时会出现java.util.ConcurrentModificationException异常
arrayIterator.remove(); // 使用迭代器内部的remove()方法,会将迭代器当前指向的元素删除(底层会将迭代器的参照快照内的元素和集合内的元素都删除,以保证不会出现上述的异常)
if(arrayIterator.hasNext()) {
System.out.print(", ");
}
}
System.out.println("}");
System.out.println("ArrayList内的元素:" + arrayC.size());
// 创建集合对象HashSet,无序不可重复
Collection hashC = new HashSet();
hashC.add(100);
hashC.add(200);
hashC.add("HashSet");
hashC.add(100);
hashC.add(100);
hashC.add(560);
hashC.add(2.589);
// 对集合进行遍历
// 第一步:获取集合对象的迭代器对象hashIterator
Iterator hashIterator = hashC.iterator();
// 第二步:通过上面的迭代器结合迭代器工作原理进行遍历/迭代集合
System.out.print("HashSet{");
while(hashIterator.hasNext()) { // 判断当前元素的下面是否还有元素(判断还能否迭代)
Object obj = hashIterator.next(); // 将迭代器指向下一个元素,并将当前指向的元素返回出去(进行迭代)
System.out.print(obj);
if(hashIterator.hasNext()) {
System.out.print(", ");
}
}
System.out.println("}");
}
}
| [
"1365137828@qq.com"
] | 1365137828@qq.com |
bd8a95af95e68ffd5679ad4cd487c12d0e7a9eca | 3180c5a659d5bfdbf42ab07dfcc64667f738f9b3 | /src/unk/com/zing/zalo/ui/cw.java | be4b3af20b1b0bed9e54876174a83237d7745749 | [] | no_license | tinyx3k/ZaloRE | 4b4118c789310baebaa060fc8aa68131e4786ffb | fc8d2f7117a95aea98a68ad8d5009d74e977d107 | refs/heads/master | 2023-05-03T16:21:53.296959 | 2013-05-18T14:08:34 | 2013-05-18T14:08:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,071 | java | package unk.com.zing.zalo.ui;
import com.zing.peoplepicker.views.f;
import com.zing.zalo.a.i;
import com.zing.zalo.control.w;
import java.util.HashMap;
class cw
implements f
{
cw(BroadcastSMSInviteToFriendsActivity paramBroadcastSMSInviteToFriendsActivity)
{
}
public void r(Object paramObject)
{
try
{
if ((paramObject instanceof w))
{
w localw = (w)paramObject;
if (BroadcastSMSInviteToFriendsActivity.h(this.aaB).containsKey(localw.ya))
BroadcastSMSInviteToFriendsActivity.h(this.aaB).remove(localw.ya);
BroadcastSMSInviteToFriendsActivity.k(this.aaB).a(BroadcastSMSInviteToFriendsActivity.l(this.aaB));
BroadcastSMSInviteToFriendsActivity.k(this.aaB).notifyDataSetChanged();
this.aaB.runOnUiThread(new cx(this));
}
return;
}
catch (Exception localException)
{
localException.printStackTrace();
}
}
}
/* Location: /home/danghvu/0day/Zalo/Zalo_1.0.8_dex2jar.jar
* Qualified Name: com.zing.zalo.ui.cw
* JD-Core Version: 0.6.2
*/ | [
"danghvu@gmail.com"
] | danghvu@gmail.com |
20e6cdc9c262f0d6ae010433622892cb2a172006 | b553f7b0b301be2718c559c33373aa18dd8a9b28 | /app/src/main/java/com/binaryic/beinsync/common/InternetConnectionDetector.java | 034f48c1e3a53cbd81d5d09911859b53a7ec4668 | [] | no_license | Abhis111/Beinsync | a4964e02a4564eda1c021022918f8a0ef9a73641 | ef40418442c88c21d115f81470c7da4104791036 | refs/heads/master | 2021-01-01T16:23:59.690826 | 2017-08-01T07:59:21 | 2017-08-01T07:59:21 | 97,825,112 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,549 | java | package com.binaryic.beinsync.common;
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.view.View;
import java.io.IOException;
public class InternetConnectionDetector {
public static boolean isConnectingToInternet(Activity _context, View view, boolean show_Dialogue) {
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
if (show_Dialogue) {
Utils.showSnackBar(_context, view, "No Internet Connection");
}
}
return false;
}
public static boolean isInternetWorking() {
Runtime runtime = Runtime.getRuntime();
try {
Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
int exitValue = ipProcess.waitFor();
Log.e("exit value===", "===" + exitValue);
return (exitValue == 0);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return false;
}
} | [
"minakshi.binary@gmail.com"
] | minakshi.binary@gmail.com |
e6c650ba02a31dd34d27e9d3247e94b4224b583a | 1fbd27e2d737fd6f1c65fbba31887a13617bda45 | /day1/DemoProject/src/com/hcl/java/Switch2.java | abd0dea618db2a89868362af0e130439b032108a | [] | no_license | vinodkumarr269/mode1 | 935517e1187fab24925184066b4f904095854b94 | cf8bc57cd563a993a843a078908b9bc5e9116d37 | refs/heads/master | 2022-12-27T16:08:25.551061 | 2019-10-24T06:57:43 | 2019-10-24T06:57:43 | 214,944,277 | 0 | 0 | null | 2022-12-15T23:30:25 | 2019-10-14T03:59:12 | JavaScript | UTF-8 | Java | false | false | 403 | java | package com.hcl.java;
public class Switch2 {
public void show(String op){
switch(op.toUpperCase()){
case "INSERT":
System.out.println("insert ope");
break;
case "UPDATE":
System.out.println("update ope");
break;
default:
System.out.println("invalid");
}
}
public static void main(String[] args) {
String op="update";
Switch2 o=new Switch2();
o.show(op);
}
}
| [
"vinodkumarr269@gmail.com"
] | vinodkumarr269@gmail.com |
96eeb53246557336ec96f6e2e1532e0f60c01f7a | bd10b65a74de5df3c4f8b2af57333866fdd9de0f | /WorkoutAppBoot/src/test/java/com/workoutapp/WorkoutAppBoot/ServiceTest.java | 6b214c3804fc80fcded7750022216b3028c3c19d | [] | no_license | rahulravindrangeetha/workoutapp | 64d8b52fd766d04d3f5e122681e1ab159c3612d7 | 0710be7f96c3a4ca53c5a427c18d9b2e77fc9858 | refs/heads/master | 2020-04-11T18:17:25.308844 | 2018-12-24T15:45:49 | 2018-12-24T15:45:49 | 161,992,970 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,344 | java | package com.workoutapp.WorkoutAppBoot;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import org.assertj.core.util.Lists;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.ui.ModelMap;
import com.workoutapp.dao.ReportDao;
import com.workoutapp.dao.WorkoutCategoryDao;
import com.workoutapp.dao.WorkoutDao;
import com.workoutapp.entity.WorkoutActive;
import com.workoutapp.entity.WorkoutCategory;
import com.workoutapp.entity.WorkoutCollection;
import com.workoutapp.service.ReportService;
import com.workoutapp.service.WorkoutCategoryService;
import com.workoutapp.service.WorkoutService;
import com.workoutapp.serviceimpl.ReportServiceImpl;
import com.workoutapp.serviceimpl.WorkoutCategoryServiceImpl;
import com.workoutapp.serviceimpl.WorkoutServiceImpl;
@ActiveProfiles("test")
@EnableConfigurationProperties
public class ServiceTest
{
@InjectMocks
private WorkoutService workoutService=new WorkoutServiceImpl();
@InjectMocks
private WorkoutCategoryService workoutCategoryService=new WorkoutCategoryServiceImpl();
@InjectMocks
private ReportService reportService=new ReportServiceImpl();
@Mock
private ReportDao reportDao;
@Mock
private WorkoutDao workoutDao;
@Mock
private WorkoutCategoryDao workoutCategoryDao;
private static WorkoutCategory workoutCategory1;
private static WorkoutCategory workoutCategory2;
private static WorkoutCollection workoutCollection1;
private static WorkoutCollection workoutCollection2;
private static WorkoutActive workoutActive1;
private static WorkoutActive workoutActive2;
private static WorkoutActive workoutActive3;
private static WorkoutActive workoutActive4;
@Before
public void init()
{
initMocks(this);
setData();
}
@Test
public void getWorkoutDetail()
{
List workouts = new ArrayList();
workouts.add(workoutCollection1);
workouts.add(workoutCollection2);
when(workoutDao.getAllWorkout()).thenReturn(workouts);
List returnedData=workoutService.getAllWorkout();
assertEquals(2, returnedData.size());
verify(workoutDao).getAllWorkout();
}
@Test
public void getAWorkoutDetail()
{
when(workoutDao.getWorkout(1)).thenReturn(workoutCollection1);
WorkoutCollection workout=workoutService.getWorkout(1);
assertEquals(workout.getWorkoutId(),1);
assertEquals(workout.getWorkoutCategory(),workoutCategory1);
assertEquals(workout.getWorkoutTitle(),"medium pace run");
verify(workoutDao).getWorkout(any(Integer.class));
}
@Test
public void deleteWorkout()
{
workoutService.deleteWorkout(1);
verify(workoutDao).deleteWorkout(any(Integer.class));
}
@Test
public void addWorkout()
{
workoutService.createNewWorkout(workoutCollection1);
verify(workoutDao).createNewWorkout(any(WorkoutCollection.class));
}
@Test
public void updateWorkout()
{
workoutService.editWorkout(workoutCollection1);
verify(workoutDao).editWorkout(any(WorkoutCollection.class));
}
@Test
public void getaWorkoutActiveRec()
{
when(workoutDao.getActiveWorkoutRec(1)).thenReturn(workoutActive1);
WorkoutActive activeRec=workoutService.getActiveWorkoutRec(1);
assertEquals(activeRec.getWorkout().getWorkoutId(),1);
assertEquals(activeRec.getComment(),"runn");
verify(workoutDao).getActiveWorkoutRec(any(Integer.class));
}
@Test
public void startAWorkout()
{
workoutService.startWorkout(workoutActive1, 1);
verify(workoutDao).addActiveWorkout(any(WorkoutActive.class));
}
@Test
public void updateAWorkout()
{
workoutService.updateActiveWorkout(workoutActive2, 1);
verify(workoutDao).updateActiveWorkout((any(WorkoutActive.class)), any(Integer.class));
}
@Test
public void getAllCategories()
{
List workoutCategories = new ArrayList();
workoutCategories.add(workoutCategory1);
workoutCategories.add(workoutCategory2);
when(workoutCategoryDao.getAllWorkoutCategories()).thenReturn(workoutCategories);
List returnedData=workoutCategoryService.getAllWorkoutCategories();
assertEquals(2, returnedData.size());
verify(workoutCategoryDao).getAllWorkoutCategories();
}
@Test
public void createCategoryTest()
{
workoutCategoryService.addNewWorkoutCategory(workoutCategory1);
verify(workoutCategoryDao).addNewWorkoutCategory(any(WorkoutCategory.class));
}
@Test
public void updateCategoryTest()
{
workoutCategoryService.updateWorkoutCategory(workoutCategory1);
verify(workoutCategoryDao).updateWorkoutCategory(any(WorkoutCategory.class));
}
@Test
public void deleteCategoryTest()
{
workoutCategoryService.deleteWorkoutCategory(1);
verify(workoutCategoryDao).deleteWorkoutCategory(any(Integer.class));
}
@Test
public void generateReportTest()
{
reportService.generateReport();
verify(reportDao).getCalorieBurntMonth();
verify(reportDao).getCalorieBurntWeek();
verify(reportDao).getCalorieBurntYear();
verify(reportDao).getWorkoutMinDay();
verify(reportDao).getWorkoutMinMonth();
verify(reportDao).getWorkoutMinWeek();
}
private void setData()
{
workoutCategory1= new WorkoutCategory();
workoutCategory1.setCategoryId(1);
workoutCategory1.setCategoryName("running");
workoutCategory2= new WorkoutCategory();
workoutCategory2.setCategoryId(2);
workoutCategory2.setCategoryName("cycling");
workoutCollection1= new WorkoutCollection();
workoutCollection1.setWorkoutId(1);
workoutCollection1.setCalBurnPerMin(12.11f);
workoutCollection1.setWorkoutCategory(workoutCategory1);
workoutCollection1.setWorkoutNote("good day to run");
workoutCollection1.setWorkoutTitle("medium pace run");
workoutCollection2= new WorkoutCollection();
workoutCollection2.setWorkoutId(2);
workoutCollection2.setCalBurnPerMin(7.8f);
workoutCollection2.setWorkoutCategory(workoutCategory2);
workoutCollection2.setWorkoutNote("cycling yeee");
workoutCollection2.setWorkoutTitle("cycling");
workoutActive1 = new WorkoutActive();
workoutActive1.setComment("runn");
workoutActive1.setStartDate(LocalDate.parse("11-11-2018", DateTimeFormatter.ofPattern("dd-MM-yyyy")));
workoutActive1.setStartTime(LocalTime.parse("09:45", DateTimeFormatter.ofPattern("HH:mm")));
workoutActive1.setWorkout(workoutCollection1);
workoutActive1.setStatus("TRUE");
workoutActive2 = new WorkoutActive();
workoutActive2.setComment("runn");
workoutActive2.setStartDate(LocalDate.parse("11-11-2018", DateTimeFormatter.ofPattern("dd-MM-yyyy")));
workoutActive2.setStartTime(LocalTime.parse("09:45", DateTimeFormatter.ofPattern("HH:mm")));
workoutActive2.setWorkout(workoutCollection1);
workoutActive2.setStatus("FALSE");
workoutActive2.setEndDate(LocalDate.parse("11-11-2018", DateTimeFormatter.ofPattern("dd-MM-yyyy")));
workoutActive2.setEndTime(LocalTime.parse("10:15", DateTimeFormatter.ofPattern("HH:mm")));
workoutActive3 = new WorkoutActive();
workoutActive3.setComment("cycleee");
workoutActive3.setStartDate(LocalDate.parse("14-12-2018", DateTimeFormatter.ofPattern("dd-MM-yyyy")));
workoutActive3.setStartTime(LocalTime.parse("05:15", DateTimeFormatter.ofPattern("HH:mm")));
workoutActive3.setWorkout(workoutCollection2);
workoutActive3.setStatus("TRUE");
workoutActive4 = new WorkoutActive();
workoutActive4.setComment("cycleee");
workoutActive4.setStartDate(LocalDate.parse("14-12-2018", DateTimeFormatter.ofPattern("dd-MM-yyyy")));
workoutActive4.setStartTime(LocalTime.parse("05:15", DateTimeFormatter.ofPattern("HH:mm")));
workoutActive4.setWorkout(workoutCollection2);
workoutActive4.setStatus("FALSE");
workoutActive4.setEndDate(LocalDate.parse("14-12-2018", DateTimeFormatter.ofPattern("dd-MM-yyyy")));
workoutActive4.setEndTime(LocalTime.parse("06:15", DateTimeFormatter.ofPattern("HH:mm")));
}
}
| [
"rahulrg150889@gmail.com"
] | rahulrg150889@gmail.com |
047f6135cc545c31cdcfd18c6487fac31a7b8a4f | 1edbb3239bea9e7f2bd2db890df8b97980e5544e | /src/main/java/com/fl/config/bean/JwtUserDto.java | c257043fa1ebc13fa9fdd8966b13156871cbcce7 | [] | no_license | chen2020-cyj/SliceManager | 651281c1d747cabd7932a387f9e1b901ed221cd0 | c863570f34c6168ebb8a65548ab99932019b571c | refs/heads/master | 2023-03-09T05:13:48.707142 | 2021-02-25T05:21:49 | 2021-02-25T05:21:49 | 317,431,370 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,420 | java | package com.fl.config.bean;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fl.entity.User;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@Getter
@AllArgsConstructor
public class JwtUserDto implements UserDetails {
private final User user;
@JsonIgnore
private final List<GrantedAuthority> authorities;
public Set<String> getRole(){
return authorities.stream().map(GrantedAuthority::getAuthority).collect(Collectors.toSet());
}
@JsonIgnore
@Override
public String getPassword() {
return user.getPassword();
}
@JsonIgnore
@Override
public String getUsername() {
return user.getUsername();
}
@JsonIgnore
@Override
public boolean isAccountNonExpired() {
return true;
}
@JsonIgnore
@Override
public boolean isAccountNonLocked() {
return true;
}
@JsonIgnore
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@JsonIgnore
@Override
public boolean isEnabled() {
return true;
}
// @JsonIgnore
// @Override
// public boolean isEnabled() {
// return user.getEnabled()==0;
// }
}
| [
"7653402+cyj2286886271@user.noreply.gitee.com"
] | 7653402+cyj2286886271@user.noreply.gitee.com |
07eace0658e5b8971edbf704a62bd20c58ede779 | 29b6a856a81a47ebab7bfdba7fe8a7b845123c9e | /dingtalk/java/src/main/java/com/aliyun/dingtalkdatacenter_1_0/models/QueryYydLogDayStatisticalDataRequest.java | b66409ae3a30a0f181c3f265e0630b3e90fc039d | [
"Apache-2.0"
] | permissive | aliyun/dingtalk-sdk | f2362b6963c4dbacd82a83eeebc223c21f143beb | 586874df48466d968adf0441b3086a2841892935 | refs/heads/master | 2023-08-31T08:21:14.042410 | 2023-08-30T08:18:22 | 2023-08-30T08:18:22 | 290,671,707 | 22 | 9 | null | 2021-08-12T09:55:44 | 2020-08-27T04:05:39 | PHP | UTF-8 | Java | false | false | 725 | java | // This file is auto-generated, don't edit it. Thanks.
package com.aliyun.dingtalkdatacenter_1_0.models;
import com.aliyun.tea.*;
public class QueryYydLogDayStatisticalDataRequest extends TeaModel {
@NameInMap("statDate")
public String statDate;
public static QueryYydLogDayStatisticalDataRequest build(java.util.Map<String, ?> map) throws Exception {
QueryYydLogDayStatisticalDataRequest self = new QueryYydLogDayStatisticalDataRequest();
return TeaModel.build(map, self);
}
public QueryYydLogDayStatisticalDataRequest setStatDate(String statDate) {
this.statDate = statDate;
return this;
}
public String getStatDate() {
return this.statDate;
}
}
| [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
cdecb5718558d9d7f935ebc999f5d6a5f82f7c09 | d1e340a1576d526dadfebf5e670c62da7489f8c4 | /cloud-consumer-consul-order80/src/main/java/com/ceking/springcloud/controller/OrderController.java | ad8e1b39b0aa26b64370d2e2902ef06f3c12aba8 | [] | no_license | CeKing2311/SpringCloud | a239f8e9cb155e45d959b20634246fb7a5b8a658 | 254939b567372895477910ea4362d290192d199d | refs/heads/master | 2023-02-22T01:47:08.262531 | 2021-01-27T16:05:47 | 2021-01-27T16:05:47 | 331,903,478 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 736 | java | package com.ceking.springcloud.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
/**
* @author ceking
* @desc
* @date 2021/1/24 17:46
*/
@RestController
public class OrderController {
public static final String INVOKE_URL="http://consul-provider-payment";
@Resource
private RestTemplate restTemplate;
@GetMapping("/consumer/payment/consul")
public String paymentInfo(){
String result = restTemplate.getForObject(INVOKE_URL + "/payment/consul", String.class);
System.out.println(result);
return result;
}
}
| [
"593537367@qq.com"
] | 593537367@qq.com |
50fa6e4856c9863d5f88aa6456ee14df370e2136 | cc0651a57ae4c84f4f74d24c0410b98460466a8e | /src/main/java/com/makingdevs/practica16/UserServiceProdImpl.java | 6af5450e200b0ee1f1b799c4f64b4cfef3c109b7 | [] | no_license | josdem/spring-essentials-practices | fd25fd92d277758c3bebb87d0a3acba42e721fa9 | 2ceb28546e6793a1bb12756e9500592555d0226b | refs/heads/master | 2020-12-24T21:27:32.964255 | 2016-04-28T17:56:01 | 2016-04-28T17:56:01 | 57,342,751 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 570 | java | package com.makingdevs.practica16;
import com.makingdevs.model.User;
import com.makingdevs.services.UserService;
public class UserServiceProdImpl implements UserService {
@Override
public User findUserByUsername(String username) {
// TODO Auto-generated method stub
return null;
}
@Override
public User createUser(String username) {
System.out.println("Creating user in production environment");
return null;
}
@Override
public void addToProject(String username, String codeName) {
// TODO Auto-generated method stub
}
}
| [
"neodevelop@gmail.com"
] | neodevelop@gmail.com |
cdeb34492b55c3a6e9278348fd8783c3b8d1b14a | 2bfee1d6c907d701db5c4862276894198ec9d8ae | /src/main/java/com/rest/switer/exceptions/errors/ErrorDTO.java | 8ffbb7dfbae13e09ffa7b4d6b6ffb0bf948ce4ad | [] | no_license | PolinaPerluhina/Switer | db4825f85137e52c9fa4ed66a40799e8c3616e80 | cad67386b003228fff13841d0d712fce878c9673 | refs/heads/master | 2021-08-31T18:41:41.835822 | 2017-12-22T11:50:31 | 2017-12-22T11:50:31 | 110,683,415 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 765 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.rest.switer.exceptions.errors;
/**
*
* @author Palina_Piarlukhina
*/
public class ErrorDTO {
private int code;
private String message;
public ErrorDTO() {
}
public ErrorDTO(int code, String message) {
this.code = code;
this.message = message;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
| [
"Palina_Piarlukhina@epam.com"
] | Palina_Piarlukhina@epam.com |
1fbcc370976defd001c12503d2789b0e60093636 | 901d3c66e4251b6bc1de8414eb9afa26fc7e7af7 | /src/main/java/ar/com/agtech/syros/fecae/implementations/esphora/services/FEParamGetTiposCbte.java | 49a28dc6abdc832990010c447fbe1153f6da5b3e | [] | no_license | avantgardelabs/syros_elec_invoice | 32745f89ef5f2867d776da1bbcd59f367b4f5bed | 89da95cc3173a9fbd526dcfab007fafcf07082b3 | refs/heads/master | 2020-12-30T11:15:07.505642 | 2012-07-26T19:55:53 | 2012-07-26T19:55:53 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,238 | java |
package ar.com.agtech.syros.fecae.implementations.esphora.services;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for FEParamGetTiposCbte complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="FEParamGetTiposCbte">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="cuit" type="{http://www.w3.org/2001/XMLSchema}long"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "FEParamGetTiposCbte", propOrder = {
"cuit"
})
public class FEParamGetTiposCbte {
protected long cuit;
/**
* Gets the value of the cuit property.
*
*/
public long getCuit() {
return cuit;
}
/**
* Sets the value of the cuit property.
*
*/
public void setCuit(long value) {
this.cuit = value;
}
}
| [
"jmorando@cuyum.com"
] | jmorando@cuyum.com |
29c341a9d8f98323a6b0e64d70063a31c467d7f2 | b7daf14d706b14a1998909f8e95b9aac51f3a183 | /EmptyStringsTes.java | 3c41d18af79ea011d9ddc73ff32f818066bb9ca8 | [] | no_license | Abhishekjain0112/OCA-8-Javaprograms-certification- | 7df03c3e8f4198611fc30d5fcbbd6ff3dc104055 | e6fd24198a2e354a3455f123cf7a24bfa4879586 | refs/heads/master | 2022-11-09T00:20:21.783258 | 2020-06-20T20:12:47 | 2020-06-20T20:12:47 | 273,777,321 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 317 | java | class EmptyStringsTest {
public static boolean isEmpty(String s) {
return (s == null | s.length() == 0);
}
public static void main(String args[]) {
if (isEmpty(null)) {
System.out.print("empty ");
} else {
System.out.print("not_empty ");
}
}
}
| [
"abhishekjain0112@gmail.com"
] | abhishekjain0112@gmail.com |
53c8b9a13876481afa07aa2327b9e46200c629f4 | 36698d199ce627a983225cf4d90291806c03c57f | /commons/src/main/java/yangyd/kf/commons/Instants.java | cd470daeab237246fc33fdf0d78596eacbf9dbaa | [] | no_license | yydonny/kafka-learning | 347eb76b7f3153667abfdb1aad5d1668ebc7545e | 3fa46b9313a7ccb5a0b3309e9c8b2df3a78619df | refs/heads/master | 2020-03-18T09:31:27.843439 | 2018-05-21T17:25:39 | 2018-05-21T17:25:39 | 134,567,809 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,097 | java | package yangyd.kf.commons;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
public final class Instants {
private static final DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT;
private Instants() { }
public static class Serializer extends JsonSerializer<Instant> {
@Override
public void serialize(Instant value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeString(formatter.format(value));
}
}
public static class Deserializer extends JsonDeserializer<Instant> {
@Override
public Instant deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
return Instant.parse(p.readValueAs(String.class));
}
}
}
| [
"yangyd@live.com"
] | yangyd@live.com |
097a759c7680182bb0ef25ba7c547846c46f100b | 37adc110ac0ba33ca8a878cd1ff9941a15305694 | /src/dev/java/aimprosoft.task.usermanagment.datatest/TestDataGenerator.java | 77658bede5b6bed089ab71026924d21ecb94bbba | [] | no_license | IvanPakhomov99/DepartmentManagment | 9e08cd926c51d6c763110fbaad77bc46d2a25755 | 6d217e51e7b97527e830d73dc9fe1a09c3741d17 | refs/heads/master | 2022-05-27T04:49:39.634055 | 2019-07-03T17:45:32 | 2019-07-03T17:45:32 | 183,101,603 | 0 | 0 | null | 2022-05-20T20:56:54 | 2019-04-23T21:54:44 | Java | UTF-8 | Java | false | false | 6,513 | java | package aimprosoft.task.usermanagment.datatest;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class TestDataGenerator {
private static final String JDBC_URL = "jdbc:postgresql://localhost/dep_db";
private static final String JDBC_USERNAME = "ivan";
private static final String JDBC_PASSWORD = "Vania99";
private static final String[] fullName = {"Ivan Pakhomov", "Polina Bilous", "Daniil Pilipetc", "Marina Pakhomova", "Mikhail Yuminov", "Yurii Pakhomov", "Galina Timoshenko"};
private static final String[] depName = {"first", "second", "third"};
private static final String[] CITIES = {"Kharkiv", "Kiyv", "Odessa"};
private static final Date[] birthday = {
Date.valueOf("1999-07-07"), Date.valueOf("1999-08-18"),
Date.valueOf("1998-04-17"), Date.valueOf("1966-05-15"),
Date.valueOf("1999-09-23"), Date.valueOf("1966-05-25"),
Date.valueOf("1988-07-18")
};
private static final String[] email = {
"ivan.pakhomov@nure.ua", "polina.bilous@nure.ua",
"daniil.pilipetc@nure.ua", "marina.pakhomova@gmail.com",
"mikhail.yuminov@nure.ua", "yurii.pakhomov@gmail.com",
"galina.timoshenko@gmail.com"
};
private static final Random r = new Random();
private static int idDepartment = 0;
private static Date birthDay = null;
public static void main(String[] args) throws Exception {
List<Department> departments = loadDepartments();
List<Employee> employees = loadEmployees();
try (Connection c = DriverManager.getConnection(JDBC_URL, JDBC_USERNAME, JDBC_PASSWORD)) {
c.setAutoCommit(false);
clearDb(c);
for (Department p : departments) {
createDepartment(c, p);
System.out.println("Created " + p.name + " department");
}
for (Employee e : employees) {
createEmployees(c, e);
System.out.println("Created profile for " + e.firstName + " " + e.lastName);
}
c.commit();
System.out.println("Data generated successful");
}
}
private static void clearDb(Connection c) throws SQLException {
Statement st = c.createStatement();
st.executeUpdate("delete from department");
st.executeQuery("select setval('department_seq', 1, false)");
st.executeQuery("select setval('employee_seq', 1, false)");
System.out.println("Db cleared");
}
private static class Department {
private final String name;
private final String city;
private Department(String name, String city) {
super();
this.name = name;
this.city = city;
}
@Override
public String toString() {
return String.format("Department [Name=%s, City=%s]", name, city);
}
}
private static final class Employee {
private final String firstName;
private final String lastName;
private final String email;
private final Date birthday;
private final int certificates;
private final int depId;
private Employee(String firstName, String lastName, String email, Date birthday, int certificates, int depId) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.birthday = birthday;
this.certificates = certificates;
this.depId = depId;
}
@Override
public String toString() {
return String.format("Profile [firstName=%s, lastName=%s]", firstName, lastName);
}
}
private static void createDepartment(Connection c, Department department) throws SQLException, IOException {
insertDepartmentData(c, department);
}
private static void insertDepartmentData(Connection c, Department department) throws SQLException, IOException {
PreparedStatement ps = c.prepareStatement("insert into department values (nextval('department_seq'),?,?)");
ps.setString(1, department.name);
ps.setString(2, department.city);
ps.executeUpdate();
ps.close();
idDepartment++;
}
private static List<Department> loadDepartments() {
ArrayList<Department> list = new ArrayList<>(depName.length);
int i = 0;
for (String depName : depName) {
list.add(new Department(depName, CITIES[i]));
i++;
}
Collections.sort(list, (o1, o2) -> {
int nameCompare = o1.name.compareTo(o2.name);
if (nameCompare != 0) {
return nameCompare;
} else {
return o1.city.compareTo(o2.city);
}
});
return list;
}
private static void createEmployees(Connection c, Employee e) throws IOException, SQLException {
insertEmployeesData(c, e);
}
private static void insertEmployeesData(Connection c, Employee e) throws SQLException, IOException {
PreparedStatement statement = c.prepareStatement("insert into employee values (nextval('employee_seq'), ?, ?, ?, ?, ?, ?)");
statement.setString(1, e.firstName);
statement.setString(2, e.lastName);
statement.setString(3, e.email);
statement.setDate(4, e.birthday);
statement.setInt(5, e.certificates);
statement.setInt(6, e.depId);
statement.executeUpdate();
statement.close();
}
private static List<Employee> loadEmployees() {
ArrayList<Employee> list = new ArrayList<>(fullName.length);
int first = 0;
int second = 1;
int index = 0;
for (String firstName : fullName) {
String[] names = firstName.split(" ");
list.add(new Employee(names[first], names[second], email[index], birthday[index], r.nextInt(10) + 1, r.nextInt(3) + 1));
if (index < 7) {
index++;
}
}
Collections.sort(list, (o1, o2) -> {
int firstNameCompare = o1.firstName.compareTo(o2.firstName);
if (firstNameCompare != 0) {
return firstNameCompare;
} else {
return o1.lastName.compareTo(o2.lastName);
}
});
return list;
}
}
| [
"ivan.pakhomov.nure.ua"
] | ivan.pakhomov.nure.ua |
88abccb985aec96bb93fceb7bb4f7184c552e7b9 | a6ff8c5f14b880e3dc9794b422869b0aa5c0a758 | /src/main/java/com/mrsalwater/kapteyn/decompiler/util/ClassFileUtil.java | d1fac82ba6e9b8959ed6533563d8e1b4668d4edb | [
"MIT"
] | permissive | mrsalwater/Kapteyn | 3e74f56f473480c3ecccc801b46d58ae0249c104 | 3c96a4b2e55f177d5ae6c3f9882da3bc570753f0 | refs/heads/master | 2022-11-22T12:13:21.311609 | 2020-03-20T16:31:36 | 2020-03-20T16:31:36 | 247,135,760 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,205 | java | package com.mrsalwater.kapteyn.decompiler.util;
public final class ClassFileUtil {
private ClassFileUtil() {
}
public static String getReturnType(String descriptor) {
char firstCharacter = descriptor.charAt(0);
if (firstCharacter == '[') {
return getReturnType(descriptor.substring(1)).concat("[]");
}
if (firstCharacter == 'V') {
return "void";
} else if (firstCharacter == 'L') {
return descriptor.substring(1, descriptor.length() - 1);
}
return getPrimitiveType(firstCharacter);
}
public static String getFieldType(String descriptor) {
char firstCharacter = descriptor.charAt(0);
if (firstCharacter == '[') {
return getFieldType(descriptor.substring(1)).concat("[]");
}
if (firstCharacter == 'L') {
return descriptor.substring(1, descriptor.length() - 1);
}
return getPrimitiveType(firstCharacter);
}
public static String getPrimitiveType(char c) {
switch (c) {
case 'B':
return "byte";
case 'C':
return "char";
case 'D':
return "double";
case 'F':
return "float";
case 'I':
return "int";
case 'J':
return "long";
case 'S':
return "short";
case 'Z':
return "boolean";
default:
throw new NullPointerException("");
}
}
public static String getNewArrayPrimitiveType(int atype) {
switch (atype) {
case 4:
return "T_BOOLEAN";
case 5:
return "T_CHAR";
case 6:
return "T_FLOAT";
case 7:
return "T_DOUBLE";
case 8:
return "T_BYTE";
case 9:
return "T_SHORT";
case 10:
return "T_INT";
case 11:
return "T_LONG";
default:
throw new NullPointerException();
}
}
}
| [
"mrsalwatercode@gmail.com"
] | mrsalwatercode@gmail.com |
8958e6d85fe081ae4031f24a63d7cb1f78c8ed1e | ba7d0a4ecfb02c090208b76c920d19d84ce8cd28 | /app/src/main/java/com/example/wachirawit/hearthty/LoginFragment.java | ac1ab4fbb83b45423edbd950de7e26264970fd1f | [] | no_license | 59070150/HealthyT | 9f8f82457e3d22aa72baf182a3f0d7f594c32237 | 640ec1435fad54e4fb3b91dabc1615593d210b1a | refs/heads/master | 2020-03-28T09:18:12.343139 | 2018-09-10T08:22:51 | 2018-09-10T08:22:51 | 148,027,721 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,063 | java | package com.example.wachirawit.hearthty;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LoginFragment extends Fragment {
@Nullable
@Override
public View onCreateView(
@NonNull LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
return inflater.inflate( R.layout.fragment_login, container, false);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initLoginBtn();
initRegisterBtn();
}
void initLoginBtn() {
Button _loginBtn = (Button) getView().findViewById(R.id.log_btn);
_loginBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
EditText _userId = (EditText) getView().findViewById(R.id.log_user);
EditText _password = (EditText) getView().findViewById(R.id.log_pass);
String _userIdStr = _userId.getText().toString();
String _passwordStr = _password.getText().toString();
if(_userIdStr.isEmpty() || _passwordStr.isEmpty()){
Toast.makeText(
getActivity(),
"กรุณาระบุ user or password",
Toast.LENGTH_SHORT
).show();
Log.d("USER", "USER OR PASSWORD IS EMPTY");
} else if(
_userIdStr.equals("admin") && _passwordStr.equals("admin")
) {
getActivity().getSupportFragmentManager()
.beginTransaction()
.replace(R.id.main_view, new MenuFragment())
.addToBackStack(null)
.commit();
Log.d("USER", "GOTO BMI");
} else {
Log.d("USER", "INVALID USER NAME OR PASSWORD");
}
}
});
}
void initRegisterBtn() {
TextView _registerBtn = (TextView) getView().findViewById(R.id.register_btn);
_registerBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("LOGIN", "go to register");
getActivity().getSupportFragmentManager()
.beginTransaction()
.replace(R.id.main_view, new RegisterFragment())
.addToBackStack(null)
.commit();
}
});
}
}
| [
"59070150@kmitl.ac.th"
] | 59070150@kmitl.ac.th |
70a6df27b1e6ea66325a30d13cdd3cb8cd8d3a3b | cb669faeb9d86ae7174438debcf8ed53e1f6600a | /src/employee/helloworld.java | 084745a604f38285d8a77183efcb0576000e5974 | [] | no_license | Vishavjeet2710/employee | 23621474fe1382c456059506ac193f975fe468b3 | 7647d2294a022c1d1895e9c87a29182efa518a99 | refs/heads/main | 2023-08-22T05:04:02.640018 | 2021-10-24T16:14:24 | 2021-10-24T16:14:24 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 118 | java | package employee;
public class helloworld {
public static void main(String[] args) {
helloworld2.main(args);
}
}
| [
"vishavjeet27102000@gmail.com"
] | vishavjeet27102000@gmail.com |
afb4b639de9fe6220b6c499c4e20f7bed8ef857f | aa6f74060b446a145658d598ff52dac9e349f4ca | /src/main/java/controllers/ConsoleMap.java | 689b35c2a15d9dbd073d4d6c67b279e27cfa0f30 | [] | no_license | MosesMNZ/Swingy | 599595e378164a2c3e48d044638c13e75d4ad06b | 008dd628386b0a1836322d63e5a594e020e9de0a | refs/heads/master | 2021-06-14T16:06:53.624141 | 2019-08-17T13:49:03 | 2019-08-17T13:49:03 | 202,884,862 | 0 | 0 | null | 2021-06-04T22:02:08 | 2019-08-17T13:33:15 | Java | UTF-8 | Java | false | false | 15,554 | java | package controllers;
import models.artifacts.Armor;
import models.artifacts.Helm;
import models.artifacts.Weapon;
import models.enemies.Enemy;
import models.filewriter.ReadFile;
import models.heroes.Hero;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class ConsoleMap
{
private static ArrayList<Enemy> enemyArray = new ArrayList<Enemy>();
private static ArrayList<Enemy> tempArray = new ArrayList<Enemy>();
private static int mapy;
private static int mapx;
private static int upgrade = 0;
private int[][] map;
private int heroLevel, size, enemies, xpos, ypos, oldx, oldy, level;
private Hero hero = new Hero();
private Enemy enemy = new Enemy();
private boolean set = false;
public ConsoleMap(){}
public ConsoleMap( Hero hero )
{
this.hero = hero;
}
public void setConsoleMapSize()
{
size = ( hero.getHeroStats().getLevel() - 1 ) * 5 + 10 - ( hero.getHeroStats().getLevel() % 2 );
mapx = size;
mapy = size;
map = new int[size][size];
}
public void setEnemies()
{
this.enemies = hero.getHeroStats().getLevel() * 8;
}
public void setHeroPos()
{
int x = 0, y = 0;
if ( ( size % 2 ) == 1 )
{
x = ( int )( size / 2 );
y = ( int )( size / 2 );
}
else if ( ( size % 2 ) == 0 )
{
x = ( size / 2 );
y = ( size / 2 );
}
this.xpos = x;
this.ypos = y;
}
public void updateHeroPos( int xpos, int ypos )
{
this.oldx = this.xpos;
this.oldy = this.ypos;
this.xpos += xpos;
if ( this.xpos < 0 )
{
upgradeXP( 1 );
}
else if ( this.xpos >= this.size )
{
upgradeXP( 1 );
}
this.ypos += ypos;
if ( this.ypos < 0 )
{
upgradeXP( 1 );
}
else if ( this.ypos >= this.size )
{
upgradeXP( 1 );
}
}
public int getConsoleMapSize()
{
return ( this.size );
}
public void ConsoleMap()
{
if ( set == false )
{
setConsoleMapSize();
setHeroPos();
setEnemies();
if ( tempArray.isEmpty() )
createEnemy();
else
enemyArray.addAll( tempArray );
set = true;
}
/* initialize map array to zeros */
for ( int y = 0; y < size; y++ )
{
for ( int x = 0; x < size; x++ )
{
map[y][x] = 0;
}
}
/* initialization for enemy */
for ( Enemy enemy : enemyArray )
{
map[enemy.getEnemyPosY()][enemy.getEnemyPosX()] = enemy.getTypeID();
}
/* initialization for hero */
map[this.ypos][this.xpos] = 4;
/* check if hero has crossed paths with enemy */
for ( Enemy enemy : enemyArray )
{
boolean t = crossedEnemy( this.ypos, this.xpos, enemy.getEnemyPosY(), enemy.getEnemyPosX() );
if ( t == true )
break;
}
System.out.println( "Level: " + hero.getHeroStats().getLevel() + " | " +
"Power: " + hero.getHeroStats().getPower() + " | " +
"Hitpoints: " + hero.getHeroStats().getHitPoints() + " | " +
"Experience: " + hero.getHeroStats().getXPoints() + "\n\n" );
for ( int y = 0; y < mapy; y++ )
{
for ( int x = 0; x < mapx; x++ )
{
switch ( map[y][x] )
{
case 0:
System.out.print( "|...|" );
break;
case 1:
System.out.print( "|.x.|" );
break;
case 2:
System.out.print( "|.x.|" );
break;
case 3:
System.out.print( "|.x.|" );
break;
default:
System.out.print( "|.o.|" );
break;
}
}
System.out.println();
}
}
public static void registerEnemy( Enemy enemy )
{
if ( enemyArray.contains( enemy ) )
return;
enemyArray.add( enemy );
}
// public static void removeEnemy( Enemy enemy )
// {
// if ( enemyArray.contains( enemy ) )
// enemyArray.remove( enemy );
// }
public void createEnemy()
{
for ( int i = 0; i < this.enemies; i++ )
{
Random random = new Random();
int eposx = random.nextInt( size );
int eposy = random.nextInt( size );
while ( eposy == this.ypos || eposx == this.xpos )
{
eposx = random.nextInt( size );
eposy = random.nextInt( size );
}
enemy = PlayersGenerator.newEnemy( hero );
enemy.setEnemyPos( eposx, eposy );
registerEnemy( enemy );
}
}
public Enemy getCrossedEnemy()
{
for ( int i = 0; i < enemyArray.size(); i++ )
{
if ( enemyArray.get(i).getEnemyPosY() == this.ypos && enemyArray.get(i).getEnemyPosX() == this.xpos )
return ( enemyArray.get( i ) );
}
return ( null );
}
public void upgradeXP( int type )
{
if ( type == 1 )
{
int xp;
if ( hero.getHeroStats().getXPoints() < 2450 )
{
xp = 2450;
hero.getHeroStats().setXPoints( xp );
}
else if ( hero.getHeroStats().getXPoints() < 4800 )
{
xp = 4800;
hero.getHeroStats().setXPoints( xp );
}
else if ( hero.getHeroStats().getXPoints() < 8050 )
{
xp = 8050;
hero.getHeroStats().setXPoints( xp );
}
else if ( hero.getHeroStats().getXPoints() < 12200 )
{
xp = 12200;
hero.getHeroStats().setXPoints( xp );
}
else if ( hero.getHeroStats().getXPoints() < 12201 )
{
System.out.println( "************ Game Comleted **********" );
System.out.println( "################ GOODBYE ############" );
System.exit( 0 );
}
hasWon();
}
else if ( type == 2 )
{
hero.getHeroStats().setXPoints( hero.getHeroStats().getXPoints() + enemy.getPower() );
ReadFile.updateFile( hero );
hasWon();
}
}
public void hasWon()
{
if ( hero.getHeroStats().getXPoints() < 2450 && hero.getHeroStats().getXPoints() > 1000 )
{
this.level = 1;
}
else if ( hero.getHeroStats().getXPoints() == 2450 )
{
this.level = 2;
}
else if ( hero.getHeroStats().getXPoints() > 2450 && hero.getHeroStats().getXPoints() < 4800 )
{
this.level = 2;
}
else if ( hero.getHeroStats().getXPoints() == 4800 )
{
this.level = 3;
}
else if ( hero.getHeroStats().getXPoints() > 4800 && hero.getHeroStats().getXPoints() < 8050 )
{
this.level = 3;
}
else if ( hero.getHeroStats().getXPoints() == 8050 )
{
this.level = 4;
}
else if ( hero.getHeroStats().getXPoints() > 8050 && hero.getHeroStats().getXPoints() < 12200 )
{
this.level = 4;
}
else if ( hero.getHeroStats().getXPoints() == 12200 )
{
this.level = 5;
}
if ( this.level > hero.getHeroStats().getLevel() )
{
hero.getHeroStats().setLevel( this.level );
ReadFile.updateFile ( hero );
System.out.println( "#-----------------------------------#\n" );
System.out.println( "### Congrats ###\n" );
System.out.println( "#-----------------------------------#\n" );
System.out.println( "#-----------------------------------#" );
System.out.println( "# 1. Move to next level #" );
System.out.println( "# 2. Quit game #" );
System.out.print( "--------------------------> " );
Scanner scanner = new Scanner( System.in );
while ( scanner.hasNextLine() )
{
String line = scanner.nextLine();
if ( line.matches( "\\s*[1-2]\\s*" ) )
{
int option = Integer.parseInt( line );
if ( option == 1 )
{
enemyArray.removeAll( enemyArray );
GameController.run( hero );
System.out.println( "Continue your Game." );
}
else if ( option == 2 )
{
System.out.println( "******** You quitted the game *******" );
System.out.println( "############## GOODBYE ##############\n" );
System.exit( 0 );
}
}
else
System.out.println( "Invalid input. Try again." );
}
}
else if ( this.level == hero.getHeroStats().getLevel() )
{
enemyArray.removeAll( enemyArray );
}
}
public boolean crossedEnemy( int hy, int hx, int ey, int ex )
{
if ( ( hx == ex ) && ( hy == ey ) )
{
System.out.println( "Ooops!!!" );
System.out.println( "You have crossed paths with an enemy\n" );
System.out.println( "#-----------------------------------#" );
System.out.println( "# 1. Run from the enemy #" );
System.out.println( "# 2. Fight the enemy #" );
System.out.print( "--------------------------> " );
Scanner scanner = new Scanner( System.in );
while ( scanner.hasNextLine() )
{
String line = scanner.nextLine();
if ( line.matches( "\\s*[1-2]\\s*" ) )
{
int choice = Integer.parseInt( line );
if ( choice == 1 )
{
System.out.println( "#-----------------------------------#\n" );
System.out.println( "### You have run from the enemy! ###\n" );
System.out.println( "#-----------------------------------#\n" );
GameController.run(hero);
}
else if ( choice == 2 )
{
System.out.println( "#-----------------------------------#\n" );
System.out.println( "### The battle is on ###\n" );
System.out.println( "#-----------------------------------#\n" );
Enemy crossed = getCrossedEnemy();
int won = GameController.fight( hero, crossed );
if ( won == 1 )
{
won( crossed );
return ( true );
}
else
{
lost();
break;
}
}
else
System.out.println( "Ooops! Invalid input. Try again.\n" );
}
else
System.out.println( "Ooops! Invalid input. Try again.\n" );
}
}
return ( false );
}
public void won( Enemy crossed )
{
enemyArray.remove( crossed );
upgradeXP( 2 );
System.out.println( "#-----------------------------------#\n" );
System.out.println( "### You won the battle ###\n" );
System.out.println( "#-----------------------------------#\n" );
if ( GameController.inLuck() == true )
{
System.out.println( "Available enemy artifact: " + crossed.getArtifact().getType() + "\n" );
System.out.println( "#-----------------------------------#" );
System.out.println( "# 1. Pick up enemy artifact #" );
System.out.println( "# 2. Continue your Game #" );
System.out.print( "--------------------------> " );
Scanner scanner = new Scanner( System.in );
while ( scanner.hasNextLine() )
{
String line = scanner.nextLine();
if ( line.matches( "\\s*[1-2]\\s*" ) )
{
int option = Integer.parseInt( line );
if ( option == 1 )
{
String type = enemy.getArtifact().getType();
if ( type.equals( "Weapon" ) )
{
Weapon weapon = new Weapon( "Weapon" );
hero.setArtifact( weapon );
hero.getHeroStats().setAttack( 65 );
ReadFile.updateFile( hero );
break;
}
else if ( type.equals( "Armor" ) )
{
Armor armor = new Armor( "Armor" );
hero.setArtifact( armor );
hero.getHeroStats().setDefense( 55 );
ReadFile.updateFile( hero );
break;
}
else if ( type.equals( "Helm" ) )
{
Helm helm = new Helm( "Helm" );
hero.setArtifact( helm );
hero.getHeroStats().setHitPoints( 75 );
ReadFile.updateFile( hero );
break;
}
}
else if ( option == 2 )
{
upgradeXP( 2 );
}
}
else
System.out.println( "Invalid input. Try again" );
}
}
else
{
upgradeXP( 2 );
System.out.println( "#-----------------------------------#\n" );
System.out.println( "### 500 XPoints gained ###\n" );
System.out.println( "#-----------------------------------#\n" );
try
{
Thread.sleep( 3000 );
}
catch( InterruptedException e )
{
System.exit( 0 );
}
GameController.run( hero );
}
}
public void lost()
{
System.out.println( "#-----------------------------------#\n" );
System.out.println( "### You lost the battle ###\n" );
System.out.println( "#-----------------------------------#\n" );
System.exit( 0 );
}
} | [
"mosesm@marshan.co.za"
] | mosesm@marshan.co.za |
15a7db265c652901613f32e7c6f4158a2d83fbc1 | f6492aeb1541a28929443b1059c57fec149d5030 | /ImperiusB/CustomControls/src/com/beta/UIControls/CNumberPicker.java | 8657efe16c113765bd28a84a5f595e63fcf94fac | [] | no_license | MIDIeval/MIDIeval | 9d24947b426eb379fcef91d0828b522ff6cc6d9c | 6e30a273b6d75b1bac15724242baf24276aa435a | refs/heads/master | 2020-12-24T08:15:07.033848 | 2016-08-08T20:47:50 | 2016-08-08T20:47:50 | 13,016,176 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,527 | java | package com.beta.UIControls;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TableLayout;
import android.widget.TextView;
import com.customcontrol.seekbar.R;
public class CNumberPicker extends TableLayout {
//Member of layout
private TextView previousTextView_m;
private TextView selectedTextView_m;
private TextView nextTextView_m;
private Button incrementButton_m;
private Button decrementButton_m;
private TextView selectedStringTextView_m;
private ImageView dividerImageView_m;
//Background for layout entities
private Drawable previousTextBackgroundDrawable_m;
private Drawable nextTextBackgroundDrawable_m;
private Drawable selectedTextBackgroundDrawable_m;
private Drawable selectedStringBackgroundDrawable_m;
private Drawable decrementButtonBackgroundDrawable_m;
private Drawable incrementButtonBackgroundDrawable_m;
private Drawable separatorBackgroundDrawable_m;
//List management of the view
private TreeMap<Integer, String> dictionaryListOfItems_m;
private TreeMap<Integer, String> dictionaryListOfIndex_m;
private int i_SelectedIndex_m = -1;
private int i_PreviousIndex_m = -1;
private int i_NextIndex_m = -1;
//Interface to expose methods
public interface IOnValueSelectionChanged{
public void onValueSelectionChanged(String string);
}
private IOnValueSelectionChanged valueChangedListenerRef_m;
//Constructor for instantiation
public CNumberPicker(Context context){
this(context, null);
}
public CNumberPicker(Context context, AttributeSet attributeSet){
this(context, attributeSet, 0);
}
public CNumberPicker(Context context, AttributeSet attributeSet, int defStyle){
super(context, attributeSet);
TypedArray arrAttributeSet_f = context.obtainStyledAttributes(attributeSet, R.styleable.CNumberPicker, defStyle, 0);
try{
fn_InitNumberPicker();
//Fetch all the drawable objects to fill the entities of the layout
Drawable obtainedDrawable_f = arrAttributeSet_f.getDrawable(R.styleable.CNumberPicker_decrement_button_background);
if (obtainedDrawable_f != null ){
this.decrementButtonBackgroundDrawable_m = obtainedDrawable_f;
}
obtainedDrawable_f = arrAttributeSet_f.getDrawable(R.styleable.CNumberPicker_increment_button_background);
if ( obtainedDrawable_f != null ){
this.incrementButtonBackgroundDrawable_m = obtainedDrawable_f;
}
obtainedDrawable_f = arrAttributeSet_f.getDrawable(R.styleable.CNumberPicker_previous_text_background);
if ( obtainedDrawable_f != null ){
this.previousTextBackgroundDrawable_m = obtainedDrawable_f;
}
obtainedDrawable_f = arrAttributeSet_f.getDrawable(R.styleable.CNumberPicker_next_text_background);
if ( obtainedDrawable_f != null ){
this.nextTextBackgroundDrawable_m = obtainedDrawable_f;
}
obtainedDrawable_f = arrAttributeSet_f.getDrawable(R.styleable.CNumberPicker_selected_String_text_background);
if ( obtainedDrawable_f != null){
this.selectedStringBackgroundDrawable_m = obtainedDrawable_f;
}
obtainedDrawable_f = arrAttributeSet_f.getDrawable(R.styleable.CNumberPicker_number_picker_separator);
if ( obtainedDrawable_f != null ){
this.separatorBackgroundDrawable_m = obtainedDrawable_f;
}
//Obtain context-based layout inflater to inflate the pre-defined layout
LayoutInflater layoutInflater_f = LayoutInflater.from(context);
layoutInflater_f.inflate(R.layout.spinner_layout, this);
//Get the individual view elements from the layout
this.incrementButton_m = (Button)this.findViewById(R.id.btn_increment);
this.decrementButton_m = (Button)this.findViewById(R.id.btn_decrement);
this.selectedTextView_m = (TextView)this.findViewById(R.id.text_row_02);
this.previousTextView_m = (TextView)this.findViewById(R.id.text_row_01);
this.nextTextView_m = (TextView)this.findViewById(R.id.text_row_03);
this.selectedStringTextView_m = (TextView)this.findViewById(R.id.text_row_06);
}
finally{
arrAttributeSet_f.recycle();
}
}
public void fn_InitNumberPicker(){
}
/*Function: fn_RegisterButtonClickListener
*Functionality: To register the button with an onClickListener
*@1: The button itself
*@2: The direction of change, i.e increment(1) or decrement(-1)
*/
public void fn_RegisterButtonClickListener(Button button, final int direction){
if ( button == null )
return;
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if ( dictionaryListOfItems_m == null )
return;
if ( direction == 1){
int index = fn_GetNextIndexInDictionary(i_SelectedIndex_m);
if ( index < 0 || index >= dictionaryListOfItems_m.size() )
return;
else{
i_SelectedIndex_m = index;
}
}
else if ( direction == -1 ){
int index = fn_GetPreviousIndexInDictionary(i_SelectedIndex_m);
if ( index < 0)
return;
else{
i_SelectedIndex_m = index;
}
}
fn_PopulateTextViews(i_SelectedIndex_m );
}
});
}
public int fn_GetNextIndexInDictionary(int index){
if ( index + 1 > this.getDictionaryListOfItems().size())
return -1;
else
return ++index;
}
public int fn_GetPreviousIndexInDictionary(int index){
if ( this.i_SelectedIndex_m - 1 < 0)
return -1;
else
return --index;
}
public void fn_PopulateTextViews(int selectedIndex){
if ( this.selectedStringTextView_m == null || this.previousTextView_m == null || this.nextTextView_m == null || this.selectedTextView_m == null )
return;
int index_f = selectedIndex;
String selectedItem_f = this.fn_SetTextToTextView(this.selectedTextView_m, index_f);
if ( selectedItem_f != null )
this.selectedStringTextView_m.setText(this.dictionaryListOfItems_m.get(Integer.parseInt(selectedItem_f)));
else
this.selectedStringTextView_m.setText("");
index_f = this.fn_GetPreviousIndexInDictionary(selectedIndex);
this.fn_SetTextToTextView(this.previousTextView_m, index_f);
index_f = this.fn_GetNextIndexInDictionary(selectedIndex);
this.fn_SetTextToTextView(this.nextTextView_m, index_f);
if ( this.getValueChangedListenerRef() != null )
getValueChangedListenerRef().onValueSelectionChanged(this.dictionaryListOfIndex_m.get(this.i_SelectedIndex_m));
}
public String fn_SetTextToTextView(TextView textView, int indexValue){
if ( indexValue < 0){
textView.setText("");
return null;
}
else{
String selectedItem_f= this.dictionaryListOfIndex_m.get(indexValue);
textView.setText(selectedItem_f);
return selectedItem_f;
}
}
public TreeMap<Integer, String> getDictionaryListOfItems() {
return dictionaryListOfItems_m;
}
public void setDictionaryListOfItems(TreeMap<Integer, String> dictionaryListOfItems_m) {
this.dictionaryListOfItems_m = dictionaryListOfItems_m;
if ( this.dictionaryListOfItems_m != null && this.dictionaryListOfItems_m.size() > 0){
Set<Integer> keySet_f = this.dictionaryListOfItems_m.keySet();
Iterator keySetIterator_f = keySet_f.iterator();
int iCount = 0;
this.dictionaryListOfIndex_m = new TreeMap<Integer, String>();
while(keySetIterator_f.hasNext()){
this.dictionaryListOfIndex_m.put(iCount, keySetIterator_f.next().toString());
iCount++;
}
}
this.fn_RegisterButtonClickListener(decrementButton_m, -1);
this.fn_RegisterButtonClickListener(incrementButton_m, +1);
this.i_SelectedIndex_m = 0;
this.fn_PopulateTextViews(i_SelectedIndex_m);
}
public IOnValueSelectionChanged getValueChangedListenerRef() {
return valueChangedListenerRef_m;
}
public void setValueChangedListenerRef(IOnValueSelectionChanged valueChangedListenerRef_m) {
this.valueChangedListenerRef_m = valueChangedListenerRef_m;
}
static class SavedState extends BaseSavedState {
int i_SelectedIndex_m;
/**
* Constructor called from {@link ProgressBar#onSaveInstanceState()}
*/
SavedState(Parcelable superState) {
super(superState);
}
/**
* Constructor called from {@link #CREATOR}
*/
private SavedState(Parcel in) {
super(in);
this.i_SelectedIndex_m = in.readInt();
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeInt(this.i_SelectedIndex_m);
}
public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
@Override
public Parcelable onSaveInstanceState() {
// Force our ancestor class to save its state
Parcelable superState = super.onSaveInstanceState();
SavedState ss = new SavedState(superState);
ss.i_SelectedIndex_m = this.i_SelectedIndex_m;
return ss;
}
@Override
public void onRestoreInstanceState(Parcelable state) {
SavedState ss = (SavedState) state;
super.onRestoreInstanceState(ss.getSuperState());
this.i_SelectedIndex_m = ss.i_SelectedIndex_m;
this.fn_PopulateTextViews(ss.i_SelectedIndex_m);
}
}
| [
"hrishikmishra@yahoo.com"
] | hrishikmishra@yahoo.com |
01d02d94468ed5bbbf5ffc8a8c58b1e993bc9fea | 036f8d8ae83788ff52c9e17c385fc7f57ee45a03 | /src/main/java/com/hqkj/example/entity/UserVehicle.java | 3cb0df0c4f21de83a2a9826987ea8a8aeedd4241 | [] | no_license | HayLeung/hqkjweb | 5b84061039c487e802e74ce141ebee75f0aec333 | 5f1c6c5b0c5c7dbfbe838ffec76928f1f6a0d574 | refs/heads/master | 2021-01-22T22:24:37.263857 | 2017-03-20T07:26:41 | 2017-03-20T07:26:41 | 85,542,733 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,491 | java | package com.hqkj.example.entity;
public class UserVehicle {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column uservehicle.id
*
* @mbggenerated
*/
private Integer id;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column uservehicle.user_id
*
* @mbggenerated
*/
private Integer userId;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column uservehicle.vehicle_id
*
* @mbggenerated
*/
private Integer vehicleId;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column uservehicle.id
*
* @return the value of uservehicle.id
*
* @mbggenerated
*/
public Integer getId() {
return id;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column uservehicle.id
*
* @param id the value for uservehicle.id
*
* @mbggenerated
*/
public void setId(Integer id) {
this.id = id;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column uservehicle.user_id
*
* @return the value of uservehicle.user_id
*
* @mbggenerated
*/
public Integer getUserId() {
return userId;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column uservehicle.user_id
*
* @param userId the value for uservehicle.user_id
*
* @mbggenerated
*/
public void setUserId(Integer userId) {
this.userId = userId;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column uservehicle.vehicle_id
*
* @return the value of uservehicle.vehicle_id
*
* @mbggenerated
*/
public Integer getVehicleId() {
return vehicleId;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column uservehicle.vehicle_id
*
* @param vehicleId the value for uservehicle.vehicle_id
*
* @mbggenerated
*/
public void setVehicleId(Integer vehicleId) {
this.vehicleId = vehicleId;
}
} | [
"805230761@qq.com"
] | 805230761@qq.com |
4dd32a1178ea5bcf8e45c699ec7244dc0c1a0d0c | 7c46a44f1930b7817fb6d26223a78785e1b4d779 | /store/src/java/com/zimbra/cs/dav/service/method/PropPatch.java | 4b46d053cf5dca6918bea5e109f66f35a69beb1f | [] | no_license | Zimbra/zm-mailbox | 20355a191c7174b1eb74461a6400b0329907fb02 | 8ef6538e789391813b65d3420097f43fbd2e2bf3 | refs/heads/develop | 2023-07-20T15:07:30.305312 | 2023-07-03T06:44:00 | 2023-07-06T10:09:53 | 85,609,847 | 67 | 128 | null | 2023-09-14T10:12:10 | 2017-03-20T18:07:01 | Java | UTF-8 | Java | false | false | 6,792 | java | /*
* ***** BEGIN LICENSE BLOCK *****
* Zimbra Collaboration Suite Server
* Copyright (C) 2006, 2007, 2008, 2009, 2010, 2012, 2013, 2014, 2015, 2016 Synacor, Inc.
*
* 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,
* version 2 of the License.
*
* 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 <https://www.gnu.org/licenses/>.
* ***** END LICENSE BLOCK *****
*/
package com.zimbra.cs.dav.service.method;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.QName;
import com.google.common.collect.Lists;
import com.zimbra.common.service.ServiceException;
import com.zimbra.common.util.Pair;
import com.zimbra.cs.dav.DavContext;
import com.zimbra.cs.dav.DavContext.RequestProp;
import com.zimbra.cs.dav.DavElements;
import com.zimbra.cs.dav.DavException;
import com.zimbra.cs.dav.property.ResourceProperty;
import com.zimbra.cs.dav.resource.DavResource;
import com.zimbra.cs.dav.service.DavMethod;
import com.zimbra.cs.dav.service.DavResponse;
public class PropPatch extends DavMethod {
public static final String PROPPATCH = "PROPPATCH";
@Override
public String getName() {
return PROPPATCH;
}
@Override
public void handle(DavContext ctxt) throws DavException, IOException, ServiceException {
if (!ctxt.hasRequestMessage()) {
throw new DavException("empty request", HttpServletResponse.SC_BAD_REQUEST);
}
Document req = ctxt.getRequestMessage();
Element top = req.getRootElement();
if (!top.getName().equals(DavElements.P_PROPERTYUPDATE)) {
throw new DavException("msg "+top.getName() + " not allowed in PROPPATCH",
HttpServletResponse.SC_BAD_REQUEST, null);
}
DavResource resource = ctxt.getRequestedResource();
handlePropertyUpdate(ctxt, top, resource, false, PROPPATCH);
DavResponse resp = ctxt.getDavResponse();
resp.addResource(ctxt, resource, ctxt.getResponseProp(), false);
sendResponse(ctxt);
}
/**
*
* @param top
* @param isCreate - any "remove" elements will be ignored (should they be an error?)
* @param method - used for logging to identify what HTTP method we are doing
* @return pair of lists of elements under "set" and those under "remove" in the request
* @throws DavException
* @throws IOException
*/
public static Pair<List<Element>,List<Element>> getSetsAndRemoves(Element top, boolean isCreate, String method)
throws DavException, IOException {
List<Element> set = Lists.newArrayList();
List<Element> remove = Lists.newArrayList();
if (top == null) {
return null;
}
for (Object obj : top.elements()) {
if (!(obj instanceof Element)) {
continue;
}
Element e = (Element)obj;
String nodeName = e.getName();
boolean isSet;
if (nodeName.equals(DavElements.P_SET)) {
isSet = true;
} else if (nodeName.equals(DavElements.P_REMOVE)) {
if (isCreate) {
continue;
}
isSet = false;
} else {
continue;
}
e = e.element(DavElements.E_PROP);
if (e == null) {
throw new DavException("missing <D:prop> in " + method, HttpServletResponse.SC_BAD_REQUEST, null);
}
for (Object propObj : e.elements()) {
if (propObj instanceof Element) {
Element propElem = (Element)propObj;
if (isSet) {
set.add(propElem);
} else {
remove.add(propElem);
}
}
}
}
return new Pair<List<Element>, List<Element>>(set, remove);
}
/**
* @param setElems - list of elements under "set" in the request. Must NOT be null
* @param removeElems - list of elements under "remove" in the request. Must NOT be null
* @return Pair - first is list of elements representing properties to set. second is names of
* properties to remove.
*/
public static Pair<List<Element>,List<QName>> processSetsAndRemoves(DavContext ctxt,
DavResource resource, List<Element> setElems, List<Element> removeElems, boolean isCreate)
throws DavException, IOException {
List<Element> set = Lists.newArrayList();
List<QName> remove = Lists.newArrayList();
RequestProp rp = new RequestProp(true);
ctxt.setResponseProp(rp);
for (Element propElem : setElems) {
QName propName = propElem.getQName();
ResourceProperty prop = resource.getProperty(propName);
if (prop == null || !prop.isProtected()) {
set.add(propElem);
rp.addProp(propElem);
} else if (isCreate && prop.isAllowSetOnCreate()){
set.add(propElem);
} else {
rp.addPropError(propName, new DavException.CannotModifyProtectedProperty(propName));
}
}
for (Element propElem : removeElems) {
QName propName = propElem.getQName();
ResourceProperty prop = resource.getProperty(propName);
if (prop == null || !prop.isProtected()) {
remove.add(propName);
rp.addProp(propElem);
} else {
rp.addPropError(propName, new DavException.CannotModifyProtectedProperty(propName));
}
}
return new Pair<List<Element>, List<QName>>(set, remove);
}
public static void handlePropertyUpdate(DavContext ctxt, Element top, DavResource resource, boolean isCreate,
String method)
throws DavException, IOException {
if (top == null) {
return;
}
Pair<List<Element>,List<Element>> elemPair = getSetsAndRemoves(top, isCreate, method);
Pair<List<Element>,List<QName>> pair = processSetsAndRemoves(ctxt,
resource, elemPair.getFirst(), elemPair.getSecond(), isCreate);
resource.patchProperties(ctxt, pair.getFirst(), pair.getSecond());
}
}
| [
"shriram.vishwanathan@synacor.com"
] | shriram.vishwanathan@synacor.com |
64f40d5a4214977df64a78dbbaa059e5b97ee890 | d01a381decbb6f0718d1e00c9d27b28e047fdeab | /src/com/zwavepublic/zwaveip/command/BatteryCommand.java | 1d0af42d9f90f0ac800827557f0c5ebfed04fab2 | [
"Apache-2.0"
] | permissive | zwaveiot/zwaveip-java | 87eeea189689085be34bdb29fe4d0da13e8dad01 | 1db137c5646f77b68b05f30509751aaa40975791 | refs/heads/master | 2021-04-24T22:50:46.140498 | 2018-02-06T17:11:30 | 2018-02-06T17:11:30 | 115,970,820 | 2 | 1 | null | null | null | null | UTF-8 | Java | false | false | 997 | java | package com.zwavepublic.zwaveip.command;
import java.util.HashMap;
/* Battery commands (version 1) */
public enum BatteryCommand implements Command {
GET((byte)0x02),
REPORT((byte)0x03);
private static final HashMap<Byte, BatteryCommand> _map = new HashMap<Byte, BatteryCommand>(2);
static {
for (BatteryCommand value: BatteryCommand.values()) {
_map.put(value.byteValue(), value);
}
}
private byte _byteValue;
private BatteryCommand(byte value) {
this._byteValue = value;
}
@Override
public byte byteValue() {
return this._byteValue;
}
public static BatteryCommand valueOf(byte byteValue) {
BatteryCommand result = _map.get(byteValue);
if(result == null) {
throw new IllegalArgumentException();
} else {
return result;
}
}
public static BatteryCommand valueOfIfPresent(byte byteValue) {
return _map.get(byteValue);
}
}
| [
"zwaveiot@gmail.com"
] | zwaveiot@gmail.com |
e63784e4dbde23df2e9f22160c18a8bea2d379e3 | 566d2b593ea11b940f230667ca3e1bd4ecd0875e | /shared-source/src/edu/ucar/dls/serviceclients/webclient/WebServiceClient.java | 723138922952e9a6453db3b13e00d33566017934 | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | permissive | NCAR/dls-repository-stack | a2fc4e9f2ebde2b4efce2316bc6f0099f64268c0 | 8e19d6a9a3390ce3e3e1031ea8d0f4c5db6eb7d3 | refs/heads/master | 2021-01-20T02:37:15.086260 | 2017-03-10T19:00:52 | 2017-03-10T19:00:52 | 72,246,023 | 2 | 1 | NOASSERTION | 2019-12-03T17:47:06 | 2016-10-28T22:03:11 | Java | UTF-8 | Java | false | false | 24,400 | java | /*
Copyright 2017 Digital Learning Sciences (DLS) at the
University Corporation for Atmospheric Research (UCAR),
P.O. Box 3000, Boulder, CO 80307
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package edu.ucar.dls.serviceclients.webclient;
import edu.ucar.dls.xml.*;
import edu.ucar.dls.util.*;
import edu.ucar.dls.xml.schema.DocMap;
import java.lang.*;
import java.net.*;
import java.io.*;
import java.util.*;
import java.util.regex.*;
import org.dom4j.Node;
import org.dom4j.Element;
import org.dom4j.Document;
import org.dom4j.DocumentException;
/**
* WebServiceClient provides helpers to communicate with webservices via timed
* connections (time out is adjustable).<p>
*
* NOTE: The DCS that receives the putRecord requests must be configured to
* accept requests from the client who sends the requests. To configure the
* DCS, go to "Settings -> Web Services". At the bottom of this page is a text
* input into which the IP of the client machine must be entered.<p>
*
* The helper methods do the following:
* <ol>
* <li> accept parameters,
* <li> package the parameters into a webservice request url,
* <li> submit the request URL to the service server
* <li> parse the response into either a value or exception, which are
* returned to the caller.
* </ol>
* Currently two DDS and two DCS webservices are supported:<p>
*
* The DDS helpers submit requests to the DDS Search Web Services and returns
* responses as {@link org.dom4j.Document}.
* <ol>
* <li> UrlCheck - finds resources matching a URL (possibly wildcarded), and
* </li>
* <li> GetRecord - retrieves a given record by ID </li>
* </ol>
* <p>
*
* The DCS helpers support the following repository services:
* <ol>
* <li> PutRecord - inserts a metadata record into a specified collection in
* a remote DCS repository
* <li> doGetId - returns a unique identifier for a specified collection of a
* remote DCS.
* </ol>
*
*
* @author ostwald
*/
public class WebServiceClient {
/** Description of the Field */
protected static boolean debug = true;
private static int timeOutSecs = 30;
private String baseWebServiceUrl = null;
private URL requestUrl = null;
private String requestPostData = null;
/**
* Constructor for the WebServiceClient object.<p>
*
* Example baseWebServiceUrls:
* <ul>
* <li> dds search: "http://dcs.dlese.org/roles/services/ddsws1-0"
* <li> dcs put: "http://dcs.dlese.org/roles/services/dcsws1-0"
* </ul>
*
*
* @param baseWebServiceUrl url of Web Service
*/
public WebServiceClient(String baseWebServiceUrl) {
this.baseWebServiceUrl = baseWebServiceUrl;
}
/**
* Gets the baseUrl attribute of the WebServiceClient object
*
* @return The baseUrl value
*/
public String getBaseUrl() {
return baseWebServiceUrl;
}
/**
* Sets the timeOutSecs attribute of the WebServiceClient object
*
* @param i The new timeOutSecs value
*/
public void setTimeOutSecs(int i) {
timeOutSecs = i;
}
/**
* Gets the timeOutSecs attribute of the WebServiceClient object
*
* @return The timeOutSecs value
*/
public int getTimeOutSecs() {
return timeOutSecs;
}
/**
* Submit a request (query) to the UrlCheck Web service and return the
* response as a {@link org.dom4j.Document}. The UrlCheck service returns
* items that match the query. the query is a url and may contain asterisks as
* wildcards.
*
* @param s query to be submitted to UrlCheck
* service.
* @return result from UrlCheck Service as
* Document
* @exception WebServiceClientException Description of the Exception
*/
public Document urlCheck(String s)
throws WebServiceClientException {
String verb = "UrlCheck";
String encoded = "";
try {
encoded = URLEncoder.encode(s, "UTF-8");
} catch (Exception e) {
String errorMsg = "WebServiceClient.urlCheck failed to encode: " + s;
throw new WebServiceClientException(errorMsg);
}
setRequestUrl(verb, "url=" + encoded);
Document doc = getResponseDoc();
// prtln("\n" + doc.asXML());
prtln(Dom4jUtils.prettyPrint(doc));
return doc;
}
/**
* Performs a search with provided queryStr and returns the responseDoc
*
* @param queryStr dds queryString
* @return service response
* @exception WebServiceClientException if unable to encode queryString
*/
public Document doSearch(String queryStr)
throws WebServiceClientException {
String verb = "Search";
String encodedQueryStr = "";
try {
encodedQueryStr = URLEncoder.encode(queryStr, "UTF-8");
} catch (Exception e) {
String errorMsg = "WebServiceClient.urlCheck failed to encode: " + queryStr;
throw new WebServiceClientException(errorMsg);
}
setRequestUrl(verb, queryStr);
prtln("about to sumbit request: " + getRequestUrl());
Document doc = getResponseDoc();
// prtln(Dom4jUtils.prettyPrint(doc));
return doc;
}
/**
* Place the provided ID into the provided recordXml. recordXml must be
* "delocalized" - it must contain namespace information in the rootElement.
* Currently supported xmlFormats are "adn" and "news_opps".
*
* @param recordXml Description of the Parameter
* @param id Description of the Parameter
* @param xmlFormat NOT YET DOCUMENTED
* @return Description of the Return Value
* @exception Exception Description of the Exception
*/
public static String stuffId(String recordXml, String xmlFormat, String id)
throws Exception {
// prtln ("stuffId: \n\trecordXml: " + recordXml + "\n\txmlFormat: " + xmlFormat + "\n\tid: " + id);
String idPath = (String) getIdPaths().get(xmlFormat);
if (idPath == null)
throw new Exception("unsupported metadataformat: " + xmlFormat);
// create a localized Document from the xmlString
Document doc = Dom4jUtils.getXmlDocument(recordXml);
if (doc == null)
throw new Exception("could not parse provided recordXML");
Element rootElement = doc.getRootElement();
if (rootElement == null)
throw new Exception("root element not found");
String rootElementName = rootElement.getName();
if (rootElementName == null || rootElementName.length() == 0)
throw new Exception("rootElementName not found");
String nameSpaceInfo = Dom4jUtils.getNameSpaceInfo(doc, rootElementName);
if (nameSpaceInfo == null || nameSpaceInfo.trim().length() == 0) {
throw new Exception("recordXml does not contain required name space information in the root element");
}
doc = Dom4jUtils.localizeXml(doc, rootElementName);
if (doc == null)
throw new Exception("doc could not be localized - please unsure the record's root element contains namespace information");
DocMap docMap = new DocMap(doc);
try {
docMap.smartPut(idPath, id);
} catch (Exception e) {
throw new Exception("Unable to insert ID: " + e.getMessage());
}
doc = Dom4jUtils.delocalizeXml(doc, rootElementName, nameSpaceInfo);
if (doc == null) {
throw new Exception("not able to delocalize xml");
}
// prtln (Dom4jUtils.prettyPrint(doc));
return doc.asXML();
}
/**
* Generate an ID and insert it in the recordXML before calling the PutRecord
* web service
*
* @param recordXml xml record to be put
* @param xmlFormat metadata format of xml record (e.g.,
* "adn")
* @param collection destination collection (e.g., "dcc")
* @param status status of new record
* @param statusNote statusNote for new record
* @return ID of new record
* @exception WebServiceClientException Description of the Exception
*/
public String doPutRecord(String recordXml, String xmlFormat, String collection, String status, String statusNote)
throws WebServiceClientException {
String id = null;
id = doGetId(collection);
prtln("doPutRecord got new id: " + id + " from collection " + collection);
// now stuff it into the xml record
try {
recordXml = stuffId(recordXml, xmlFormat, id);
} catch (Exception e) {
throw new WebServiceClientException("stuffId error: " + e.getMessage());
}
return doPutRecord(recordXml, xmlFormat, collection, id, status, statusNote);
}
/**
* Create a new record and insert in repository
*
* @param recordXml xml record to be put
* @param xmlFormat metadata format of xml record (e.g.,
* "adn")
* @param collection destination collection (e.g., "dcc")
* @return ID of new record
* @exception WebServiceClientException Description of the Exception
*/
public String doPutRecord(String recordXml, String xmlFormat, String collection)
throws WebServiceClientException {
return doPutRecord(recordXml, xmlFormat, collection, null, null);
}
/**
* Assumes id is already placed in the xmlRecord. Note - the ID within the
* recordXml is ultimately used by the indexer, NOT the provided id (see
* RepositoryManger.putRecord).
*
* @param recordXml xml record to be put
* @param xmlFormat metadata format of xml record (e.g.,
* "adn")
* @param collection destination collection (e.g., "dcc")
* @param id xml record id
* @param status NOT YET DOCUMENTED
* @param statusNote NOT YET DOCUMENTED
* @return ID of created record
* @exception WebServiceClientException Description of the Exception
*/
public String doPutRecord(String recordXml, String xmlFormat, String collection, String id, String status, String statusNote)
throws WebServiceClientException {
String errorMsg;
try {
String encodedRecord = URLEncoder.encode(recordXml, "UTF-8");
// package up the request URL
String postData = "recordXml=" + encodedRecord.trim();
String argString = "xmlFormat=" + xmlFormat.trim();
argString += "&collection=" + collection.trim();
argString += "&id=" + id.trim();
if (status != null)
argString += "&dcsStatus=" + status;
if (statusNote != null)
argString += "&dcsStatusNote=" + URLEncoder.encode(statusNote, "UTF-8");
String logMsg = "doPutRecord() params:";
logMsg += "\n\t" + "xmlFormat: " + xmlFormat;
logMsg += "\n\t" + "collection: " + collection;
logMsg += "\n\t" + "id: " + id;
logMsg += "\n\t" + "status: " + status;
logMsg += "\n\t" + "statusNote: " + statusNote;
prtln(logMsg);
setRequestUrl("PutRecord", argString);
setRequestPostData(postData);
Document doc = getResponseDoc();
// now we have to parse the doc looking for errors
prtln(Dom4jUtils.prettyPrint(doc));
Node errorNode = doc.selectSingleNode("/DCSWebService/error");
if (errorNode != null) {
throw new Exception(errorNode.getText());
}
} catch (UnsupportedEncodingException e) {
errorMsg = "xmlRecord encoding error: " + e.getMessage();
throw new WebServiceClientException(errorMsg);
} catch (Throwable t) {
errorMsg = t.getMessage();
throw new WebServiceClientException(errorMsg);
}
return id;
}
/**
* Requests an id from DCS getId web service. Errors are signaled by an
* exception that contains the error message. otherwise, the Id is returned as
* a string
*
* @param collection Description of the Parameter
* @return The id
* @exception WebServiceClientException If unable to generate an ID
*/
public String doGetId(String collection)
throws WebServiceClientException {
String verb = "GetId";
String encodedArg = "";
try {
encodedArg = URLEncoder.encode(collection, "UTF-8");
} catch (Exception e) {
String errorMsg = "WebServiceClient.getId failed to encode: " + collection;
throw new WebServiceClientException(errorMsg);
}
setRequestUrl(verb, "collection=" + encodedArg);
Document doc = getResponseDoc();
Node errorNode = doc.selectSingleNode("/DCSWebService/error");
if (errorNode != null) {
throw new WebServiceClientException(errorNode.getText());
}
Node idNode = doc.selectSingleNode("/DCSWebService/GetId/id");
if (idNode != null) {
return idNode.getText();
}
String errorMsg = "WebServiceClient.getId response could not be parsed" + Dom4jUtils.prettyPrint(doc);
throw new WebServiceClientException(errorMsg);
}
/**
* Submits a request to the GetRecord DDS Web Service and returns response as
* a {@link org.dom4j.Document}. The GetRecord service returns an ADN record
* wrapped in a XML response.
*
* @param id id of the record to get
* @return the response as a Document
* @exception WebServiceClientException Description of the Exception
*/
public GetRecordResponse getRecord(String id)
throws WebServiceClientException {
String verb = "GetRecord";
setRequestUrl(verb, "id=" + id);
String responseStr = getResponseStr();
return new GetRecordResponse(responseStr);
}
// ------------------------------------------------------------
// methods to construct a requestURL -- should these be rewritten (and
// renamed to be static??
/**
* Sets the requestUrl attribute of the WebServiceClient object
*
* @param url The new requestUrl value
*/
public void setRequestUrl(URL url) {
requestUrl = url;
}
/**
* Gets the requestUrl attribute of the WebServiceClient object
*
* @return The requestUrl value
*/
public String getRequestPostData() {
return requestPostData;
}
/**
* Sets the requestPostData attribute of the WebServiceClient object
*
* @param data The new requestPostData value
*/
public void setRequestPostData(String data) {
requestPostData = data;
}
/**
* Gets the requestUrl attribute of the WebServiceClient object
*
* @return The requestUrl value
*/
public URL getRequestUrl() {
return requestUrl;
}
/**
* Sets the requestUrl attribute of the WebServiceClient object
*
* @param verb The new requestUrl value
* @param argStr The new requestUrl value
*/
public void setRequestUrl(String verb, String argStr) {
String queryStr = "?verb=" + verb;
queryStr += "&" + argStr;
try {
requestUrl = new URL(baseWebServiceUrl + queryStr);
} catch (Exception e) {
prtln("setRequestUrl() " + e);
}
}
// ------ Responses as Strings ---------------------
/**
* Submits a Web Service and returns the result as a string. Throws a
* WebServiceClientException if the response contains an <b>error</b> element.
*
* @return The responseStr value
* @exception WebServiceClientException Description of the Exception
*/
protected String getResponseStr()
throws WebServiceClientException {
String response = null;
try {
prtln("getResponseStr() with url=" + requestUrl.toString());
response = getTimedURL(requestUrl, requestPostData);
// timed
} catch (Throwable e) {
throw new WebServiceClientException(e.getMessage());
}
String error = getResponseError(response);
if ((error != null) && (error.length() > 0)) {
throw new WebServiceClientException(error);
}
else {
return response;
}
}
/**
* Searches the response string for error elements and returns the contents of
* the error if one is found.
*
* @param s Web service response as string
* @return contents of error if found or empty string if not found
*/
public static String getResponseError(String s) {
Pattern p = Pattern.compile("<error>.+?</error>", Pattern.MULTILINE);
Matcher m = p.matcher(s);
if (m.find()) {
return (s.substring(m.start() + "<error>".length(), m.end() - "</error>".length()));
}
else {
return "";
}
}
// ------ Responses as Documents ---------------------
/**
* retreives the contents of the <b>requestUrl</b> field as a {@link
* org.dom4j.Document}
*
* @return dom4j Document representation of
* response
* @exception WebServiceClientException if unsuccessful retrieving url or
* parsing doc
*/
protected Document getResponseDoc()
throws WebServiceClientException {
return getResponseDoc(this.requestUrl, this.requestPostData);
}
/**
* Gets the responseDoc attribute of the WebServiceClient object
*
* @param url NOT YET DOCUMENTED
* @return The responseDoc value
* @exception WebServiceClientException NOT YET DOCUMENTED
*/
protected Document getResponseDoc(URL url)
throws WebServiceClientException {
return getResponseDoc(url, null);
}
/**
* Static version of getResponseDoc. <p>
*
* @param url Description of the Parameter
* @param postData postData in param1=val1¶m2=val2 form (vals encoded)
* @return The responseDoc value
* @exception WebServiceClientException Description of the Exception
*/
public static Document getResponseDoc(URL url, String postData)
throws WebServiceClientException {
Document responseDoc = null;
try {
responseDoc = getTimedXmlDocument(url, postData);
} catch (Throwable e) {
throw new WebServiceClientException(e.getMessage());
}
String error = getResponseError(responseDoc);
if ((error != null) && (error.length() > 0)) {
throw new WebServiceClientException(error);
}
else {
return responseDoc;
}
}
/**
* Gets the responseError attribute of the WebServiceClient class
*
* @param doc Description of the Parameter
* @return The responseError value
*/
public static String getResponseError(Document doc) {
try {
Node errorNode = doc.selectSingleNode("/DDSWebService/error");
if (errorNode != null) {
return errorNode.getText().trim();
}
} catch (Exception e) {
prtln("getResponseError() " + e);
}
return "";
}
/**
* Gets the timedURL attribute of the WebServiceClient class
*
* @param url NOT YET DOCUMENTED
* @return The timedURL value
* @exception WebServiceClientException NOT YET DOCUMENTED
*/
public static String getTimedURL(URL url)
throws WebServiceClientException {
return getTimedURL(url, null);
}
/**
* Uses a {@link edu.ucar.dls.util.TimedURLConnection} to get the repsonse
* from the web service (the request is a URL), which is returned as a String.
*
* @param url request url (possibly with queryParams)
* @param postData postData in param1=val1¶m2=val2 form (vals encoded)
* @return The timedURL value
* @exception WebServiceClientException Description of the Exception
*/
public static String getTimedURL(URL url, String postData)
throws WebServiceClientException {
String content = "";
// prtln ("getTimedURL()");
try {
content = TimedURLConnection.importURL(url.toString(), postData, "UTF-8", timeOutSecs * 1000, null);
} catch (URLConnectionTimedOutException uctoe) {
throw new WebServiceClientException(uctoe.getMessage());
} catch (Exception exc) {
String msg = "";
if (exc.getMessage().matches(".*respcode.*")) {
msg =
"The request for data resulted in an invalid response from the server." +
" The baseURL indicated may be incorrect or the service may be unavailable." +
" HTTP response: " + exc.getMessage();
}
else {
msg =
"The request for data resulted in an invalid response from the server. Error: " +
exc.getMessage();
}
throw new WebServiceClientException(msg);
}
return content;
}
/**
* Returns a mapping from xmlFormat to idPath. Compiled from dds-project
* xmlIndexerFieldsConfigs 1/23/2011.
*
* @return The idPaths value
*/
public static Map getIdPaths() {
Map idPaths = new HashMap();
idPaths.put("adn", "/itemRecord/metaMetadata/catalogEntries/catalog/@entry");
idPaths.put("assessments", "/assessment/recordID");
idPaths.put("comm_anno", "/comm_anno/recordID");
idPaths.put("comm_core", "/record/general/recordID");
idPaths.put("comm_para", "/commParadata/recordId");
idPaths.put("concepts", "/concept/recordID");
idPaths.put("dlese_anno", "/annotationRecord/service/recordID");
idPaths.put("eng_path", "/record/general/recordID");
idPaths.put("ep_collections", "/ep_collection/recordID");
idPaths.put("library_dc", "/record/recordID");
idPaths.put("mast", "/record/general/recordID");
idPaths.put("mast_demo", "/record/general/recordID");
idPaths.put("math_path", "/record/general/recordID");
idPaths.put("msp2", "/record/general/recordID");
idPaths.put("ncam_afa", "/record/general/recordID");
idPaths.put("ncs_collect", "/record/general/recordID");
idPaths.put("ncs_item", "/record/general/recordID");
idPaths.put("news_opps", "/news-oppsRecord/recordID");
idPaths.put("nsdl_anno", "/nsdl_anno/recordID");
idPaths.put("osm", "/record/general/recordID");
idPaths.put("osm_next", "/record/general/recordID");
idPaths.put("proj_prof", "/proj_profile/recordID");
idPaths.put("res_qual", "/record/general/recordID");
idPaths.put("smile_item", "/smileItem/activityBasics/recordID");
idPaths.put("teach", "/teach/recordID");
return idPaths;
}
/*
public static WebServiceClient getInstance(String baseUrl) {
return new WebServiceClient(baseUrl);
}
*/
public static Document getTimedXmlDocument(URL url)
throws WebServiceClientException, DocumentException {
String urlcontent = getTimedURL(url, null);
return Dom4jUtils.getXmlDocument(urlcontent);
}
/**
* gets the contents of a URL via {@link #getTimedURL(URL)} and then parses
* the contents into a dom4j Document, which is returned
*
* @param url url to retrieve
* @param postData postData in param1=val1¶m2=val2 form (vals encoded)
* @return contents of url as dom4j Document, or
* null if unsuccessful
* @exception WebServiceClientException Description of the Exception
* @exception DocumentException Description of the Exception
*/
public static Document getTimedXmlDocument(URL url, String postData)
throws WebServiceClientException, DocumentException {
String urlcontent = getTimedURL(url, postData);
return Dom4jUtils.getXmlDocument(urlcontent);
}
/**
* The main program for the WebServiceClient class
*
* @param args The command line arguments
*/
public static void main(String[] args) {
String serviceUrl = "http://tremor.dpc.ucar.edu:8688/dds/services/ddsws1-0";
String recId = "DLESE-000-000-004-4091";
GetRecordResponse gr = null;
WebServiceClient wsc = new WebServiceClient(serviceUrl);
try {
gr = wsc.getRecord(recId);
} catch (WebServiceClientException e) {
prtln("WebServiceClientException: " + e.getMessage());
return;
}
prtln("Response:\n" + Dom4jUtils.prettyPrint(gr.getDocument()));
Document doc = null;
try {
doc = gr.getItemRecord();
} catch (WebServiceClientException e) {
prtln(e.getMessage());
return;
}
prtln("Doc:\n" + Dom4jUtils.prettyPrint(doc));
}
/**
* Sets the debug attribute
*
* @param db The new debug value
*/
public static void setDebug(boolean db) {
debug = db;
}
/**
* Description of the Method
*
* @param s Description of the Parameter
*/
private static void prtln(String s) {
if (debug) {
System.out.println("WebServiceClient: " + s);
}
}
}
| [
"jweather@ucar.edu"
] | jweather@ucar.edu |
1cc66f0fefdd5241b0165f0d5e480094e8341ffa | 8ca8ca15c63252135e72d5cb78931a26a4c026cb | /src/main/java/com/jarsj/PBXHeadersBuildPhase.java | c9a4629408cc1f00a08e82144f3e08a8770e850a | [] | no_license | ruchitamehta090/xcodeproj-java | 19e28078a6950e4ba9cd7a4ffb010b03d38840ab | f518326e835529d2a8299868695d760d24086a98 | refs/heads/master | 2021-01-16T00:41:33.420824 | 2014-11-07T22:14:11 | 2014-11-07T22:14:11 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 189 | java | package com.jarsj;
public class PBXHeadersBuildPhase extends PBXBuildPhase {
public PBXHeadersBuildPhase() {
super("PBXHeadersBuildPhase");
}
/*No specific members of this class*/
}
| [
"ruchitamehtamehta.090@gmail.com"
] | ruchitamehtamehta.090@gmail.com |
2c22bb77776794155025ce0bdd1b40c2d8bbde79 | fdfbc429afd6d40a33a032fb206953238330dc4f | /synertone/src/main/java/com/my51c/see51/app/activity/InstallModemActivity.java | 8ccf7d31b79274f432eb12436dd4683832c07af3 | [] | no_license | liuluming/Synertone0124 | 784e379313d1ef9e7ebfc2c62fae11e7d5fc7036 | 92169921443a563acabf0ec1c8f10907bf3f4ef1 | refs/heads/master | 2020-04-18T06:17:30.389019 | 2019-01-24T06:32:24 | 2019-01-24T06:32:24 | 167,313,874 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 13,284 | java | package com.my51c.see51.app.activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.my51c.see51.BaseActivity;
import com.my51c.see51.app.bean.InstallBean;
import com.my51c.see51.app.http.XTHttpUtil;
import com.my51c.see51.app.utils.GsonUtils;
import com.my51c.see51.common.AppData;
import com.my51c.see51.widget.SharedPreferenceManager;
import com.synertone.commonutil.view.BaseNiceDialog;
import com.synertone.commonutil.view.ConfirmCancelDialog;
import com.synertone.commonutil.view.ConfirmDialog;
import com.synertone.commonutil.view.ViewConvertListener;
import com.synertone.commonutil.view.ViewHolder;
import com.synertone.netAssistant.R;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class InstallModemActivity extends BaseActivity {
private ImageView mBack;
private TextView mTittle;
private RelativeLayout rl_top_bar;
private ProgressBar mInstallProgressbar;
private TextView mProgress;
private TextView tv_next;
private TextView tvInstep;
private int messageDelay = 5*1000;
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == 1) {
getModemIp();
}else if(msg.what==2){
setCatParameter();
}
}
};
private String mCurrentIp="192.168.1.1";
private String mModemIp="192.168.1.1";
private int lastProgress=0;
private String lastStep="1";
private InstallBean installBean;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_install_modem);
initView();
getModemIp();
setCatParameter();
String step = SharedPreferenceManager.getString(mContext, "step");
tvInstep.setText("步骤"+step+"/4");
}
private void initView() {
rl_top_bar= (RelativeLayout)findViewById(R.id.rl_top_bar);
mBack= (ImageView) findViewById(R.id.iv_back);
mBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(mCurrentIp.equals(mModemIp)){
noInstallCompleteDialog();
}
}
});
mTittle= (TextView) findViewById(R.id.tv_bar_title);
mTittle.setText(R.string.modem_set);
tv_next= (TextView) findViewById(R.id.tv_next);
tv_next.setVisibility(View.GONE);
mInstallProgressbar=(ProgressBar) findViewById(R.id.pb_install_progressbar);
tvInstep= (TextView) findViewById(R.id.tv_instep);
mProgress= (TextView) findViewById(R.id.tv_progress);
}
private void installSuccessDiaLog() {
ConfirmDialog.init().setConvertListener(new ViewConvertListener() {
@Override
public void convertView(ViewHolder holder, final BaseNiceDialog dialog) {
holder.setText(R.id.tv_tip,getString(R.string.install_success));
holder.setOnClickListener(R.id.bt_ok, new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
Intent intent=new Intent(mContext,SuperSetActivity.class);
startActivity(intent);
finish();
}
});
}
}).show(getSupportFragmentManager());
}
private void doRestToStep1() {
showDia();
String getCatParameterUrl = "http://" + mModemIp + "/cgi-bin/inststep/";
RequestParams params=new RequestParams();
params.setHeader("Cookie", "loc=en");
params.addBodyParameter("step", "1");
AppData.http.send(HttpRequest.HttpMethod.POST, getCatParameterUrl, params,
new RequestCallBack<JSONObject>() {
@Override
public void onFailure(HttpException arg0, String arg1) {
dismissDia();
Intent intent=new Intent(mContext,SuperSetActivity.class);
startActivity(intent);
finish();
}
@SuppressWarnings("rawtypes")
@Override
public void onSuccess(ResponseInfo responseInfo) {
dismissDia();
Intent intent=new Intent(mContext,SuperSetActivity.class);
startActivity(intent);
finish();
}
});
}
private void installFailDiaLog() {
ConfirmDialog.init().setConvertListener(new ViewConvertListener() {
@Override
public void convertView(ViewHolder holder, final BaseNiceDialog dialog) {
holder.setText(R.id.tv_tip,getString(R.string.install_fail));
holder.setOnClickListener(R.id.bt_ok, new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
doRestToStep1();
}
});
}
}).show(getSupportFragmentManager());
}
private void noInstallCompleteDialog() {
ConfirmCancelDialog.init()
.setConvertListener(new ViewConvertListener() {
@Override
public void convertView(ViewHolder holder, final BaseNiceDialog dialog) {
holder.setText(R.id.tv_tip,getResources().getString(R.string.no_install_complete));
holder.setOnClickListener(R.id.bt_cancel, new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
holder.setOnClickListener(R.id.bt_ok, new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(mContext, SuperSetActivity.class);
startActivity(intent);
dialog.dismiss();
finish();
}
});
}
})
.show(getSupportFragmentManager());
}
private void getModemIp() {
String getModemUrl = XTHttpUtil.GET_MODEM_IP;
StringRequest stringRequest = new StringRequest(Request.Method.GET, getModemUrl, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String code = jsonObject.getString("code");
// Toast.makeText(mContext,jsonObject.optString("ip")+"======="+code,Toast.LENGTH_SHORT).show();
if (code.equals("0")) {
if(!StringUtils.isEmpty(jsonObject.getString("ip"))){
mModemIp = jsonObject.getString("ip");
}
if(!mCurrentIp.equals(mModemIp)){
handler.removeMessages(1);
handler=null;
mProgress.setText(100+"%");
mInstallProgressbar.setProgress(100);
installSuccessDiaLog();
}
}
if(handler!=null){
handler.sendEmptyMessageDelayed(1, messageDelay);
}
} catch (JSONException e) {
//installFailDiaLog();
e.printStackTrace();
if(handler!=null){
handler.sendEmptyMessageDelayed(1, messageDelay);
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//installFailDiaLog();
if(handler!=null){
handler.sendEmptyMessageDelayed(1, messageDelay);
}
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> map = new HashMap<>();
return map;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000, 0, 0f));
AppData.mRequestQueue.add(stringRequest);
}
private void setCatParameter() {
/* if(StringUtils.isEmpty(mModemIp)){
if(handler!=null){
handler.sendEmptyMessageDelayed(2,900);
}
return;
}*/
//Toast.makeText(mContext,mModemIp,Toast.LENGTH_SHORT).show();
String getCatParameterUrl = "http://" + mModemIp + "/cgi-bin/installstatus/";
RequestParams params=new RequestParams();
params.setHeader("Cookie", "loc=en");
AppData.http.send(HttpRequest.HttpMethod.GET, getCatParameterUrl, params,
new RequestCallBack<JSONObject>() {
@Override
public void onFailure(HttpException arg0, String arg1) {
if(handler!=null){
handler.sendEmptyMessageDelayed(2,900);
}
}
@SuppressWarnings("rawtypes")
@Override
public void onSuccess(ResponseInfo responseInfo) {
try{
installBean= GsonUtils.fromJson(responseInfo.result.toString(),InstallBean.class);
String err = installBean.getErr();
if(installBean!=null&&("4".equals(err)||"3".equals(err))){
installFailDiaLog();
handler=null;
return;
}
int progress= (int) Double.parseDouble(installBean.getProgress());
if(!lastStep.equals(installBean.getCurstep())&&!"0".equals(installBean.getCurstep())){
lastProgress=0;
}
/* if(!"2".equals(installBean.getCurstep())){
SharedPreferenceManager.saveString(mContext,"step",null);
}*/
if("0".equals(installBean.getCurstep())){
tvInstep.setText("步骤4/4");
}else{
tvInstep.setText("步骤"+installBean.getCurstep()+"/4");
}
if(lastProgress<=progress){
mProgress.setText(progress+"%");
mInstallProgressbar.setProgress(progress);
}
if(handler!=null){
handler.sendEmptyMessageDelayed(2,900);
}
lastStep=installBean.getCurstep();
if(!"0".equals(installBean.getCurstep())){
lastProgress=progress;
}
}catch (Exception e){
e.printStackTrace();
}
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
handler=null;
if(installBean!=null){
SharedPreferenceManager.saveString(mContext,"step",installBean.getCurstep());
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode==KeyEvent.KEYCODE_BACK&&event.getRepeatCount() == 0){
if(mCurrentIp.equals(mModemIp)){
noInstallCompleteDialog();
return false;
}
}
return super.onKeyDown(keyCode, event);
}
}
| [
"snt1206@techtone.com"
] | snt1206@techtone.com |
b3af0b86ae940ce3787e0932d3a6b59f48efc4e3 | 2a4d3219f0d470216a6ab9f04b1769808299298f | /src/test/model/RoutineCollectionTest.java | f1672786d7334f8080a4b10fd1bbd77beb5af21e | [] | no_license | terry-yoon1205/lifestyle-tracker | d679f002c83c0bb06506edcdb137ac4db1e594f5 | 202e2876c53fdc201e025143781b25ad5fecfc3c | refs/heads/main | 2023-03-04T04:17:35.362616 | 2021-02-17T00:08:37 | 2021-02-17T00:08:37 | 339,564,897 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,677 | java | package model;
import exceptions.DoesNotExistException;
import model.routine.Routine;
import model.routine.RoutineCollection;
import model.routine.Workout;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static model.routine.MuscleGroup.*;
import static org.junit.jupiter.api.Assertions.*;
public class RoutineCollectionTest extends CollectionTest<RoutineCollection, Routine, Workout> {
@BeforeEach
public void setUp() {
c = new RoutineCollection();
e1 = new Routine("TR1");
e2 = new Routine("TR2");
su1 = new Workout("W1", 10, 4, 0, BICEPS);
su2 = new Workout("W2", 6, 3, 45, CHEST);
su3 = new Workout("W3", 8, 5, 105, SHOULDERS);
su4 = new Workout("W4", 12, 2, 20, TRICEPS);
e1.add(su1);
e1.add(su2);
e2.add(su3);
e2.add(su4);
}
@Test
public void testConstructor() {
assertEquals(0, c.getEntries().size());
}
@Test
public void testGetCollectionFormatted() {
assertEquals("", c.toString());
c.add(e1);
c.add(e2);
assertEquals("TR1\nTR2\n", c.toString());
}
@Test
public void testSearchEntryDoesNotExist() {
c.add(e1);
try {
c.search("TR2");
fail();
} catch (DoesNotExistException e) {
// pass
}
}
@Test
public void testSearchEntryTypical() {
c.add(e1);
c.add(e2);
try {
assertEquals(e1, c.search("TR1"));
assertEquals(2, c.getEntries().size());
} catch (DoesNotExistException e) {
fail();
}
}
}
| [
"noreply@github.com"
] | terry-yoon1205.noreply@github.com |
9170fa24fd228a73c720baaede3122610aa0b0d0 | 035dd0a65e13b4c91e9fa9a976f21606964a2200 | /src/test/java/Dropdown/checkBox.java | 6079d901b6e83f9447f4246ba38c1f7167a316b2 | [] | no_license | nkmahesh8/Sel_proj | ff2d52523d9c27d539e6996390249154a9d28ba6 | 19fce502cd20068233386e2ab1367e6d6179d133 | refs/heads/master | 2023-04-25T13:07:23.447781 | 2021-05-14T05:19:09 | 2021-05-14T05:19:09 | 367,252,492 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 732 | java | package Dropdown;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class checkBox {
WebDriver driver;
@Test
public void selectOption() throws InterruptedException {
System.setProperty("webdriver.chrome.driver",
"D:\\workspace_eclipse_hani\\Selenium_Training\\drivers\\chromedriver.exe");
driver = new ChromeDriver();
driver.get("https://www.seleniumeasy.com/test/basic-checkbox-demo.html");
WebElement checkbox1 = driver.findElement(By.xpath("//input[@type='checkbox'])[5]"));
checkbox1.click();
Boolean c= checkbox1.isSelected();
System.out.println(c);
}
}
| [
"hanumeshnk96@gmail.com"
] | hanumeshnk96@gmail.com |
00372cd26e12fb7ef582b69c74cb65a8730724f5 | 3907806f5d0f4ec21775d5afb9574f4ea07f1dd4 | /LanMessager/src/com/lanmessager/net/message/SendFileMessage.java | c244e0cb63bb1221f7968c37f3a77d6b58031475 | [] | no_license | Leonardo-Cosmos/Tools-Java | b2c745253470ea0997970357f226751bc2128676 | e489ddbff621fb705fbba2ba8dc618673e3a36ce | refs/heads/master | 2020-06-13T04:02:13.385058 | 2016-12-17T03:45:18 | 2016-12-17T03:45:18 | 75,450,091 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,138 | java | package com.lanmessager.net.message;
public class SendFileMessage extends Message {
private static final String KEY_FILE_SIZE = "fileSize";
private static final String KEY_FILE_NAME = "fileName";
private static final String KEY_FILE_ID = "fileId";
private static final String KEY_SENDER_ADDRESS = "senderAddress";
@MessageKey(KEY_FILE_SIZE)
private long fileSize;
@MessageKey(KEY_FILE_NAME)
private String fileName;
@MessageKey(KEY_FILE_ID)
private String fileId;
@MessageKey(KEY_SENDER_ADDRESS)
private String senderAddress;
public long getFileSize() {
return fileSize;
}
public void setFileSize(long fileSize) {
this.fileSize = fileSize;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getFileId() {
return fileId;
}
public void setFileId(String fileId) {
this.fileId = fileId;
}
public String getSenderAddress() {
return senderAddress;
}
public void setSenderAddress(String senderAddress) {
this.senderAddress = senderAddress;
}
}
| [
"kylin_cl@163.com"
] | kylin_cl@163.com |
23de08102bb1e58d69238e9d3c156980682cfb1a | f52d7d9c345a7b9fe20f56b65ab474fe433c51e8 | /src/main/java/co/com/choucair/certification/Utest/task/FillAdress.java | 3e39afeb4c1622a9c00cf4641a3f1905f6af1b69 | [] | no_license | danilotros/dasd | 84b82719e05dca529ed67fbc82c80754520fece5 | 581a732f7f58ccb65c42ab8e9ae1aa64c0ba52d2 | refs/heads/main | 2023-03-20T20:30:35.300102 | 2021-03-11T14:48:18 | 2021-03-11T14:48:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,286 | java | package co.com.choucair.certification.Utest.task;
import co.com.choucair.certification.Utest.model.UtestData;
import static co.com.choucair.certification.Utest.userinterface.AddressPage.*;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.Performable;
import net.serenitybdd.screenplay.Task;
import net.serenitybdd.screenplay.Tasks;
import net.serenitybdd.screenplay.actions.Click;
import net.serenitybdd.screenplay.actions.Enter;
import org.openqa.selenium.Keys;
import java.util.List;
public class FillAdress implements Task {
private List<UtestData> data;
public FillAdress(List<UtestData> data){
this.data=data;
}
public static Performable inPageAdress(List<UtestData> data) {
return Tasks.instrumented(FillAdress.class,data);
}
@Override
public <T extends Actor> void performAs(T actor) {
actor.attemptsTo(
Enter.theValue(data.get(0).getStrCiudad()).into(INPUT_CITY),
Enter.theValue(data.get(0).getStrCode()).into(INPUT_ZIP),
Click.on(DIV_COU),
Enter.theValue(data.get(0).getStrPais()).into(INPUT_COU).thenHit(Keys.ARROW_DOWN, Keys.ENTER),
Click.on(INPUT_CITY),
Click.on(NEXT_BUTTON)
);
}
}
| [
"dgarciap@choucairtesting.com"
] | dgarciap@choucairtesting.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.