blob_id
stringlengths
40
40
__id__
int64
225
39,780B
directory_id
stringlengths
40
40
path
stringlengths
6
313
content_id
stringlengths
40
40
detected_licenses
list
license_type
stringclasses
2 values
repo_name
stringlengths
6
132
repo_url
stringlengths
25
151
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
70
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
7.28k
689M
star_events_count
int64
0
131k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
23 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
40.4M
gha_stargazers_count
int32
0
112k
gha_forks_count
int32
0
39.4k
gha_open_issues_count
int32
0
11k
gha_language
stringlengths
1
21
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
7
4.37M
src_encoding
stringlengths
3
16
language
stringclasses
1 value
length_bytes
int64
7
4.37M
extension
stringclasses
24 values
filename
stringlengths
4
174
language_id
stringclasses
1 value
entities
list
contaminating_dataset
stringclasses
0 values
malware_signatures
list
redacted_content
stringlengths
7
4.37M
redacted_length_bytes
int64
7
4.37M
alphanum_fraction
float32
0.25
0.94
alpha_fraction
float32
0.25
0.94
num_lines
int32
1
84k
avg_line_length
float32
0.76
99.9
std_line_length
float32
0
220
max_line_length
int32
5
998
is_vendor
bool
2 classes
is_generated
bool
1 class
max_hex_length
int32
0
319
hex_fraction
float32
0
0.38
max_unicode_length
int32
0
408
unicode_fraction
float32
0
0.36
max_base64_length
int32
0
506
base64_fraction
float32
0
0.5
avg_csv_sep_count
float32
0
4
is_autogen_header
bool
1 class
is_empty_html
bool
1 class
shard
stringclasses
16 values
f415e2e6e017741555cc54ba32f77b289a6f8dcb
17,179,869,217,841
b9451c54b2ff7ddb797afc029672c57181a79bf9
/core/src/main/java/org/infinispan/commands/tx/PrepareCommand.java
383a3dcc0a61b387ff77f2e1694686eabdb3f96b
[ "Apache-2.0", "LicenseRef-scancode-dco-1.1" ]
permissive
infinispan/infinispan
https://github.com/infinispan/infinispan
4c16a7f7381894e1c38c80e39cc9346b566407ad
1babc3340f2cf9bd42c84102a42c901d20feaa84
refs/heads/main
2023-08-31T19:46:06.326000
2023-06-20T08:14:50
2023-08-31T17:54:31
1,050,944
920
527
Apache-2.0
false
2023-09-14T21:00:45
2010-11-04T12:33:19
2023-09-13T11:30:16
2023-09-14T21:00:44
145,284
1,077
595
22
Java
false
false
package org.infinispan.commands.tx; import static org.infinispan.commons.marshall.MarshallUtil.marshallCollection; import static org.infinispan.commons.marshall.MarshallUtil.unmarshallCollection; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.CompletionStage; import org.infinispan.commands.VisitableCommand; import org.infinispan.commands.Visitor; import org.infinispan.commands.functional.ReadWriteKeyCommand; import org.infinispan.commands.functional.ReadWriteKeyValueCommand; import org.infinispan.commands.functional.ReadWriteManyCommand; import org.infinispan.commands.functional.ReadWriteManyEntriesCommand; import org.infinispan.commands.functional.WriteOnlyKeyCommand; import org.infinispan.commands.functional.WriteOnlyKeyValueCommand; import org.infinispan.commands.functional.WriteOnlyManyCommand; import org.infinispan.commands.functional.WriteOnlyManyEntriesCommand; import org.infinispan.commands.write.ComputeCommand; import org.infinispan.commands.write.ComputeIfAbsentCommand; import org.infinispan.commands.write.DataWriteCommand; import org.infinispan.commands.write.InvalidateCommand; import org.infinispan.commands.write.PutKeyValueCommand; import org.infinispan.commands.write.PutMapCommand; import org.infinispan.commands.write.RemoveCommand; import org.infinispan.commands.write.RemoveExpiredCommand; import org.infinispan.commands.write.ReplaceCommand; import org.infinispan.commands.write.WriteCommand; import org.infinispan.context.InvocationContext; import org.infinispan.context.InvocationContextFactory; import org.infinispan.context.impl.FlagBitSets; import org.infinispan.context.impl.RemoteTxInvocationContext; import org.infinispan.context.impl.TxInvocationContext; import org.infinispan.factories.ComponentRegistry; import org.infinispan.interceptors.AsyncInterceptorChain; import org.infinispan.notifications.cachelistener.CacheNotifier; import org.infinispan.transaction.impl.RemoteTransaction; import org.infinispan.transaction.impl.TransactionTable; import org.infinispan.transaction.xa.GlobalTransaction; import org.infinispan.transaction.xa.recovery.RecoveryManager; import org.infinispan.util.ByteString; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.infinispan.util.concurrent.CompletionStages; import org.infinispan.util.concurrent.locks.TransactionalRemoteLockCommand; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * Command corresponding to the 1st phase of 2PC. * * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik@jboss.org</a>) * @author Mircea.Markus@jboss.com * @since 4.0 */ public class PrepareCommand extends AbstractTransactionBoundaryCommand implements TransactionalRemoteLockCommand { private static final Log log = LogFactory.getLog(PrepareCommand.class); public static final byte COMMAND_ID = 12; protected List<WriteCommand> modifications; protected boolean onePhaseCommit; private transient boolean replayEntryWrapping; protected boolean retriedCommand; @SuppressWarnings("unused") private PrepareCommand() { super(null); // For command id uniqueness test } public PrepareCommand(ByteString cacheName, GlobalTransaction gtx, List<WriteCommand> commands, boolean onePhaseCommit) { super(cacheName); globalTx = gtx; modifications = commands == null ? Collections.emptyList() : Collections.unmodifiableList(commands); this.onePhaseCommit = onePhaseCommit; } public PrepareCommand(ByteString cacheName) { super(cacheName); } @Override public CompletionStage<?> invokeAsync(ComponentRegistry registry) throws Throwable { markTransactionAsRemote(true); RemoteTxInvocationContext ctx = createContext(registry); if (ctx == null) { return CompletableFutures.completedNull(); } if (log.isTraceEnabled()) log.tracef("Invoking remotely originated prepare: %s with invocation context: %s", this, ctx); CacheNotifier<?, ?> notifier = registry.getCacheNotifier().running(); CompletionStage<Void> stage = notifier.notifyTransactionRegistered(ctx.getGlobalTransaction(), false); AsyncInterceptorChain invoker = registry.getInterceptorChain().running(); for (VisitableCommand nested : modifications) nested.init(registry); if (CompletionStages.isCompletedSuccessfully(stage)) { return invoker.invokeAsync(ctx, this); } else { return stage.thenCompose(v -> invoker.invokeAsync(ctx, this)); } } @Override public RemoteTxInvocationContext createContext(ComponentRegistry componentRegistry) { RecoveryManager recoveryManager = componentRegistry.getRecoveryManager().running(); if (recoveryManager != null && recoveryManager.isTransactionPrepared(globalTx)) { log.tracef("The transaction %s is already prepared. Skipping prepare call.", globalTx); return null; } // 1. first create a remote transaction (or get the existing one) TransactionTable txTable = componentRegistry.getTransactionTableRef().running(); RemoteTransaction remoteTransaction = txTable.getOrCreateRemoteTransaction(globalTx, modifications); //set the list of modifications anyway, as the transaction might have already been created by a previous //LockControlCommand with null modifications. if (hasModifications()) { remoteTransaction.setModifications(modifications); } // 2. then set it on the invocation context InvocationContextFactory icf = componentRegistry.getInvocationContextFactory().running(); return icf.createRemoteTxInvocationContext(remoteTransaction, getOrigin()); } @Override public Collection<?> getKeysToLock() { if (modifications.isEmpty()) { return Collections.emptyList(); } final Set<Object> set = new HashSet<>(modifications.size()); for (WriteCommand writeCommand : modifications) { if (writeCommand.hasAnyFlag(FlagBitSets.SKIP_LOCKING)) { continue; } switch (writeCommand.getCommandId()) { case PutKeyValueCommand.COMMAND_ID: case RemoveCommand.COMMAND_ID: case ComputeCommand.COMMAND_ID: case ComputeIfAbsentCommand.COMMAND_ID: case RemoveExpiredCommand.COMMAND_ID: case ReplaceCommand.COMMAND_ID: case ReadWriteKeyCommand.COMMAND_ID: case ReadWriteKeyValueCommand.COMMAND_ID: case WriteOnlyKeyCommand.COMMAND_ID: case WriteOnlyKeyValueCommand.COMMAND_ID: set.add(((DataWriteCommand) writeCommand).getKey()); break; case PutMapCommand.COMMAND_ID: case InvalidateCommand.COMMAND_ID: case ReadWriteManyCommand.COMMAND_ID: case ReadWriteManyEntriesCommand.COMMAND_ID: case WriteOnlyManyCommand.COMMAND_ID: case WriteOnlyManyEntriesCommand.COMMAND_ID: set.addAll(writeCommand.getAffectedKeys()); break; default: break; } } return set; } @Override public Object getKeyLockOwner() { return globalTx; } @Override public boolean hasZeroLockAcquisition() { for (WriteCommand wc : modifications) { // If even a single command doesn't have the zero lock acquisition timeout flag, we can't use a zero timeout if (!wc.hasAnyFlag(FlagBitSets.ZERO_LOCK_ACQUISITION_TIMEOUT)) { return false; } } return true; } @Override public boolean hasSkipLocking() { return false; } @Override public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable { return visitor.visitPrepareCommand((TxInvocationContext<?>) ctx, this); } public List<WriteCommand> getModifications() { return modifications; } public boolean isOnePhaseCommit() { return onePhaseCommit; } @Override public byte getCommandId() { return COMMAND_ID; } @Override public void writeTo(ObjectOutput output) throws IOException { super.writeTo(output); //global tx output.writeBoolean(onePhaseCommit); output.writeBoolean(retriedCommand); marshallCollection(modifications, output); } @Override public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException { super.readFrom(input); onePhaseCommit = input.readBoolean(); retriedCommand = input.readBoolean(); modifications = unmarshallCollection(input, ArrayList::new); } @Override public String toString() { return "PrepareCommand {" + "modifications=" + modifications + ", onePhaseCommit=" + onePhaseCommit + ", retried=" + retriedCommand + ", " + super.toString(); } public boolean hasModifications() { return modifications != null && !modifications.isEmpty(); } public Collection<?> getAffectedKeys() { if (modifications == null || modifications.isEmpty()) return Collections.emptySet(); int size = modifications.size(); if (size == 1) return modifications.get(0).getAffectedKeys(); Set<Object> keys = new HashSet<>(size); for (WriteCommand wc : modifications) keys.addAll(wc.getAffectedKeys()); return keys; } /** * If set to true, then the keys touched by this transaction are to be wrapped again and original ones discarded. */ public boolean isReplayEntryWrapping() { return replayEntryWrapping; } /** * @see #isReplayEntryWrapping() */ public void setReplayEntryWrapping(boolean replayEntryWrapping) { this.replayEntryWrapping = replayEntryWrapping; } @Override public boolean isReturnValueExpected() { return false; } public boolean isRetriedCommand() { return retriedCommand; } public void setRetriedCommand(boolean retriedCommand) { this.retriedCommand = retriedCommand; } }
UTF-8
Java
10,329
java
PrepareCommand.java
Java
[ { "context": "rresponding to the 1st phase of 2PC.\n *\n * @author Manik Surtani (<a href=\"mailto:manik@jboss.org\">manik@jboss.org", "end": 2742, "score": 0.9998132586479187, "start": 2729, "tag": "NAME", "value": "Manik Surtani" }, { "context": "2PC.\n *\n * @author Manik Surtani (<a href=\"mailto:manik@jboss.org\">manik@jboss.org</a>)\n * @author Mircea.Markus@jb", "end": 2775, "score": 0.9999076724052429, "start": 2760, "tag": "EMAIL", "value": "manik@jboss.org" }, { "context": "r Manik Surtani (<a href=\"mailto:manik@jboss.org\">manik@jboss.org</a>)\n * @author Mircea.Markus@jboss.com\n * @since", "end": 2792, "score": 0.9998915791511536, "start": 2777, "tag": "EMAIL", "value": "manik@jboss.org" }, { "context": "o:manik@jboss.org\">manik@jboss.org</a>)\n * @author Mircea.Markus@jboss.com\n * @since 4.0\n */\npublic class PrepareCommand ext", "end": 2832, "score": 0.9992877244949341, "start": 2809, "tag": "EMAIL", "value": "Mircea.Markus@jboss.com" } ]
null
[]
package org.infinispan.commands.tx; import static org.infinispan.commons.marshall.MarshallUtil.marshallCollection; import static org.infinispan.commons.marshall.MarshallUtil.unmarshallCollection; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.CompletionStage; import org.infinispan.commands.VisitableCommand; import org.infinispan.commands.Visitor; import org.infinispan.commands.functional.ReadWriteKeyCommand; import org.infinispan.commands.functional.ReadWriteKeyValueCommand; import org.infinispan.commands.functional.ReadWriteManyCommand; import org.infinispan.commands.functional.ReadWriteManyEntriesCommand; import org.infinispan.commands.functional.WriteOnlyKeyCommand; import org.infinispan.commands.functional.WriteOnlyKeyValueCommand; import org.infinispan.commands.functional.WriteOnlyManyCommand; import org.infinispan.commands.functional.WriteOnlyManyEntriesCommand; import org.infinispan.commands.write.ComputeCommand; import org.infinispan.commands.write.ComputeIfAbsentCommand; import org.infinispan.commands.write.DataWriteCommand; import org.infinispan.commands.write.InvalidateCommand; import org.infinispan.commands.write.PutKeyValueCommand; import org.infinispan.commands.write.PutMapCommand; import org.infinispan.commands.write.RemoveCommand; import org.infinispan.commands.write.RemoveExpiredCommand; import org.infinispan.commands.write.ReplaceCommand; import org.infinispan.commands.write.WriteCommand; import org.infinispan.context.InvocationContext; import org.infinispan.context.InvocationContextFactory; import org.infinispan.context.impl.FlagBitSets; import org.infinispan.context.impl.RemoteTxInvocationContext; import org.infinispan.context.impl.TxInvocationContext; import org.infinispan.factories.ComponentRegistry; import org.infinispan.interceptors.AsyncInterceptorChain; import org.infinispan.notifications.cachelistener.CacheNotifier; import org.infinispan.transaction.impl.RemoteTransaction; import org.infinispan.transaction.impl.TransactionTable; import org.infinispan.transaction.xa.GlobalTransaction; import org.infinispan.transaction.xa.recovery.RecoveryManager; import org.infinispan.util.ByteString; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.infinispan.util.concurrent.CompletionStages; import org.infinispan.util.concurrent.locks.TransactionalRemoteLockCommand; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * Command corresponding to the 1st phase of 2PC. * * @author <NAME> (<a href="mailto:<EMAIL>"><EMAIL></a>) * @author <EMAIL> * @since 4.0 */ public class PrepareCommand extends AbstractTransactionBoundaryCommand implements TransactionalRemoteLockCommand { private static final Log log = LogFactory.getLog(PrepareCommand.class); public static final byte COMMAND_ID = 12; protected List<WriteCommand> modifications; protected boolean onePhaseCommit; private transient boolean replayEntryWrapping; protected boolean retriedCommand; @SuppressWarnings("unused") private PrepareCommand() { super(null); // For command id uniqueness test } public PrepareCommand(ByteString cacheName, GlobalTransaction gtx, List<WriteCommand> commands, boolean onePhaseCommit) { super(cacheName); globalTx = gtx; modifications = commands == null ? Collections.emptyList() : Collections.unmodifiableList(commands); this.onePhaseCommit = onePhaseCommit; } public PrepareCommand(ByteString cacheName) { super(cacheName); } @Override public CompletionStage<?> invokeAsync(ComponentRegistry registry) throws Throwable { markTransactionAsRemote(true); RemoteTxInvocationContext ctx = createContext(registry); if (ctx == null) { return CompletableFutures.completedNull(); } if (log.isTraceEnabled()) log.tracef("Invoking remotely originated prepare: %s with invocation context: %s", this, ctx); CacheNotifier<?, ?> notifier = registry.getCacheNotifier().running(); CompletionStage<Void> stage = notifier.notifyTransactionRegistered(ctx.getGlobalTransaction(), false); AsyncInterceptorChain invoker = registry.getInterceptorChain().running(); for (VisitableCommand nested : modifications) nested.init(registry); if (CompletionStages.isCompletedSuccessfully(stage)) { return invoker.invokeAsync(ctx, this); } else { return stage.thenCompose(v -> invoker.invokeAsync(ctx, this)); } } @Override public RemoteTxInvocationContext createContext(ComponentRegistry componentRegistry) { RecoveryManager recoveryManager = componentRegistry.getRecoveryManager().running(); if (recoveryManager != null && recoveryManager.isTransactionPrepared(globalTx)) { log.tracef("The transaction %s is already prepared. Skipping prepare call.", globalTx); return null; } // 1. first create a remote transaction (or get the existing one) TransactionTable txTable = componentRegistry.getTransactionTableRef().running(); RemoteTransaction remoteTransaction = txTable.getOrCreateRemoteTransaction(globalTx, modifications); //set the list of modifications anyway, as the transaction might have already been created by a previous //LockControlCommand with null modifications. if (hasModifications()) { remoteTransaction.setModifications(modifications); } // 2. then set it on the invocation context InvocationContextFactory icf = componentRegistry.getInvocationContextFactory().running(); return icf.createRemoteTxInvocationContext(remoteTransaction, getOrigin()); } @Override public Collection<?> getKeysToLock() { if (modifications.isEmpty()) { return Collections.emptyList(); } final Set<Object> set = new HashSet<>(modifications.size()); for (WriteCommand writeCommand : modifications) { if (writeCommand.hasAnyFlag(FlagBitSets.SKIP_LOCKING)) { continue; } switch (writeCommand.getCommandId()) { case PutKeyValueCommand.COMMAND_ID: case RemoveCommand.COMMAND_ID: case ComputeCommand.COMMAND_ID: case ComputeIfAbsentCommand.COMMAND_ID: case RemoveExpiredCommand.COMMAND_ID: case ReplaceCommand.COMMAND_ID: case ReadWriteKeyCommand.COMMAND_ID: case ReadWriteKeyValueCommand.COMMAND_ID: case WriteOnlyKeyCommand.COMMAND_ID: case WriteOnlyKeyValueCommand.COMMAND_ID: set.add(((DataWriteCommand) writeCommand).getKey()); break; case PutMapCommand.COMMAND_ID: case InvalidateCommand.COMMAND_ID: case ReadWriteManyCommand.COMMAND_ID: case ReadWriteManyEntriesCommand.COMMAND_ID: case WriteOnlyManyCommand.COMMAND_ID: case WriteOnlyManyEntriesCommand.COMMAND_ID: set.addAll(writeCommand.getAffectedKeys()); break; default: break; } } return set; } @Override public Object getKeyLockOwner() { return globalTx; } @Override public boolean hasZeroLockAcquisition() { for (WriteCommand wc : modifications) { // If even a single command doesn't have the zero lock acquisition timeout flag, we can't use a zero timeout if (!wc.hasAnyFlag(FlagBitSets.ZERO_LOCK_ACQUISITION_TIMEOUT)) { return false; } } return true; } @Override public boolean hasSkipLocking() { return false; } @Override public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable { return visitor.visitPrepareCommand((TxInvocationContext<?>) ctx, this); } public List<WriteCommand> getModifications() { return modifications; } public boolean isOnePhaseCommit() { return onePhaseCommit; } @Override public byte getCommandId() { return COMMAND_ID; } @Override public void writeTo(ObjectOutput output) throws IOException { super.writeTo(output); //global tx output.writeBoolean(onePhaseCommit); output.writeBoolean(retriedCommand); marshallCollection(modifications, output); } @Override public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException { super.readFrom(input); onePhaseCommit = input.readBoolean(); retriedCommand = input.readBoolean(); modifications = unmarshallCollection(input, ArrayList::new); } @Override public String toString() { return "PrepareCommand {" + "modifications=" + modifications + ", onePhaseCommit=" + onePhaseCommit + ", retried=" + retriedCommand + ", " + super.toString(); } public boolean hasModifications() { return modifications != null && !modifications.isEmpty(); } public Collection<?> getAffectedKeys() { if (modifications == null || modifications.isEmpty()) return Collections.emptySet(); int size = modifications.size(); if (size == 1) return modifications.get(0).getAffectedKeys(); Set<Object> keys = new HashSet<>(size); for (WriteCommand wc : modifications) keys.addAll(wc.getAffectedKeys()); return keys; } /** * If set to true, then the keys touched by this transaction are to be wrapped again and original ones discarded. */ public boolean isReplayEntryWrapping() { return replayEntryWrapping; } /** * @see #isReplayEntryWrapping() */ public void setReplayEntryWrapping(boolean replayEntryWrapping) { this.replayEntryWrapping = replayEntryWrapping; } @Override public boolean isReturnValueExpected() { return false; } public boolean isRetriedCommand() { return retriedCommand; } public void setRetriedCommand(boolean retriedCommand) { this.retriedCommand = retriedCommand; } }
10,290
0.727854
0.726885
278
36.154675
28.83383
124
false
false
0
0
0
0
0
0
0.517986
false
false
6
e938265f95dd95f24da49159d78cd95197a9aa13
30,434,138,316,333
61cea96c85593a4f4f54dcc74faedef9c45c7f49
/src/main/java/com/xuchi/work/service/impl/RouterServiceImpl.java
4b2aea269988697e9b46d9106639032661972db3
[]
no_license
xcnick/MvcNow
https://github.com/xcnick/MvcNow
a32d643c79be6892fd8c2ea31d3e9f935b90d9a9
ceb1ad78167ee5588ab1ff4036543d6381cd002b
refs/heads/master
2015-08-14T07:07:56.766000
2014-12-07T13:48:50
2014-12-07T13:48:50
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xuchi.work.service.impl; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.xuchi.work.dao.BaseDaoI; import com.xuchi.work.model.sys.Trouter; import com.xuchi.work.pagemodel.PageFilter; import com.xuchi.work.pagemodel.SessionInfo; import com.xuchi.work.pagemodel.sys.Router; import com.xuchi.work.service.RouterServiceI; @Service public class RouterServiceImpl implements RouterServiceI { @Autowired private BaseDaoI<Trouter> routerDao; @Override public List<Router> dataGrid(Router router, PageFilter ph) { List<Router> ul = new ArrayList<Router>(); Map<String, Object> params = new HashMap<String, Object>(); String hql = " from Trouter t "; List<Trouter> l = routerDao.find(hql + whereHql(router, params) + orderHql(ph), params, ph.getPage(), ph.getRows()); for (Trouter t : l) { Router u = new Router(); BeanUtils.copyProperties(t, u); ul.add(u); } return ul; } private String whereHql(Router router, Map<String, Object> params) { String hql = ""; if (router != null) { hql += " where 1=1 "; if (router.getMac() != null) { hql += " and t.mac like :mac"; params.put("mac", "%%" + router.getMac() + "%%"); } } return hql; } private String orderHql(PageFilter ph) { String orderString = ""; if ((ph.getSort() != null) && (ph.getOrder() != null)) { orderString = " order by t." + ph.getSort() + " " + ph.getOrder(); } return orderString; } @Override public Long count(Router router, PageFilter ph) { Map<String, Object> params = new HashMap<String, Object>(); String hql = " from Trouter t "; return routerDao.count("select count(*) " + hql + whereHql(router, params), params); } @Override public void add(Router router) { Trouter t = new Trouter(); BeanUtils.copyProperties(router, t); //t.setIsdefault(1); //t.setOrganization( organizationDao.get(Torganization.class, u.getOrganizationId())); //List<Trole> roles = new ArrayList<Trole>(); routerDao.save(t); } @Override public void delete(Long id) { Trouter t = routerDao.get(Trouter.class, id); del(t); } private void del(Trouter t) { routerDao.delete(t); } @Override public void edit(Router router) { Trouter t = routerDao.get(Trouter.class, router.getId()); t.setMac(router.getMac()); t.setLocation(router.getLocation()); t.setPassword(router.getPassword()); t.setShangjiaid(router.getShangjiaid()); t.setAuthenable(router.isAuthenable()); t.setUsercount(router.getUsercount()); routerDao.update(t); } @Override public Router get(Long id) { Map<String, Object> params = new HashMap<String, Object>(); params.put("id", id); Trouter t = routerDao.get("from Trouter t where t.id = :id", params); Router u = new Router(); BeanUtils.copyProperties(t, u); return u; } // @Override // public Router login(Router router) { // Map<String, Object> params = new HashMap<String, Object>(); // params.put("mac", router.getMac()); // params.put("password", router.getPassword()); // Trouter t = routerDao.get("from Trouter t where t.mac = :mac and t.password = :password", params); // if (t != null) { // Router u = new Router(); // BeanUtils.copyProperties(t, u); // return u; // } // return null; // } @Override public List<String> resourceList(Long id) { List<String> resourceList = new ArrayList<String>(); Map<String, Object> params = new HashMap<String, Object>(); params.put("id", id); Trouter t = routerDao.get( "from Trouter t where t.id = :id", params); // if (t != null) { // Set<Trole> roles = t.getRoles(); // if ((roles != null) && !roles.isEmpty()) { // for (Trole role : roles) { // Set<Tresource> resources = role.getResources(); // if ((resources != null) && !resources.isEmpty()) { // for (Tresource resource : resources) { // if ((resource != null) && (resource.getUrl() != null)) { // resourceList.add(resource.getUrl()); // } // } // } // } // } // } return resourceList; } // @Override // public boolean editUserPwd(SessionInfo sessionInfo, String oldPwd, // String pwd) { // Trouter u = routerDao.get(Trouter.class, sessionInfo.getId()); // if (u.getPassword().equalsIgnoreCase(oldPwd)) {// 说明原密码输入正确 // u.setPassword(pwd); // return true; // } // return false; // } @Override public Router getByName(Router router) { Trouter t = routerDao.get("from Trouter t where t.mac = '"+router.getMac()+"'"); Router u = new Router(); if(t!=null){ BeanUtils.copyProperties(t, u); }else{ return null; } return u; } }
UTF-8
Java
4,978
java
RouterServiceImpl.java
Java
[ { "context": "tLocation(router.getLocation());\r\n\t\tt.setPassword(router.getPassword());\r\n\t\tt.setShangjiaid(router.getShangjiaid());\r\n", "end": 2664, "score": 0.9299401640892029, "start": 2646, "tag": "PASSWORD", "value": "router.getPassword" }, { "context": "om Trouter t where t.mac = :mac and t.password = :password\", params);\r\n//\t\tif (t != null) {\r\n//\t\t\tRouter u =", "end": 3420, "score": 0.9732645153999329, "start": 3412, "tag": "PASSWORD", "value": "password" }, { "context": "reCase(oldPwd)) {// 说明原密码输入正确\r\n//\t\t\tu.setPassword(pwd);\r\n//\t\t\treturn true;\r\n//\t\t}\r\n//\t\treturn false;\r\n/", "end": 4623, "score": 0.9852825999259949, "start": 4620, "tag": "PASSWORD", "value": "pwd" } ]
null
[]
package com.xuchi.work.service.impl; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.xuchi.work.dao.BaseDaoI; import com.xuchi.work.model.sys.Trouter; import com.xuchi.work.pagemodel.PageFilter; import com.xuchi.work.pagemodel.SessionInfo; import com.xuchi.work.pagemodel.sys.Router; import com.xuchi.work.service.RouterServiceI; @Service public class RouterServiceImpl implements RouterServiceI { @Autowired private BaseDaoI<Trouter> routerDao; @Override public List<Router> dataGrid(Router router, PageFilter ph) { List<Router> ul = new ArrayList<Router>(); Map<String, Object> params = new HashMap<String, Object>(); String hql = " from Trouter t "; List<Trouter> l = routerDao.find(hql + whereHql(router, params) + orderHql(ph), params, ph.getPage(), ph.getRows()); for (Trouter t : l) { Router u = new Router(); BeanUtils.copyProperties(t, u); ul.add(u); } return ul; } private String whereHql(Router router, Map<String, Object> params) { String hql = ""; if (router != null) { hql += " where 1=1 "; if (router.getMac() != null) { hql += " and t.mac like :mac"; params.put("mac", "%%" + router.getMac() + "%%"); } } return hql; } private String orderHql(PageFilter ph) { String orderString = ""; if ((ph.getSort() != null) && (ph.getOrder() != null)) { orderString = " order by t." + ph.getSort() + " " + ph.getOrder(); } return orderString; } @Override public Long count(Router router, PageFilter ph) { Map<String, Object> params = new HashMap<String, Object>(); String hql = " from Trouter t "; return routerDao.count("select count(*) " + hql + whereHql(router, params), params); } @Override public void add(Router router) { Trouter t = new Trouter(); BeanUtils.copyProperties(router, t); //t.setIsdefault(1); //t.setOrganization( organizationDao.get(Torganization.class, u.getOrganizationId())); //List<Trole> roles = new ArrayList<Trole>(); routerDao.save(t); } @Override public void delete(Long id) { Trouter t = routerDao.get(Trouter.class, id); del(t); } private void del(Trouter t) { routerDao.delete(t); } @Override public void edit(Router router) { Trouter t = routerDao.get(Trouter.class, router.getId()); t.setMac(router.getMac()); t.setLocation(router.getLocation()); t.setPassword(<PASSWORD>()); t.setShangjiaid(router.getShangjiaid()); t.setAuthenable(router.isAuthenable()); t.setUsercount(router.getUsercount()); routerDao.update(t); } @Override public Router get(Long id) { Map<String, Object> params = new HashMap<String, Object>(); params.put("id", id); Trouter t = routerDao.get("from Trouter t where t.id = :id", params); Router u = new Router(); BeanUtils.copyProperties(t, u); return u; } // @Override // public Router login(Router router) { // Map<String, Object> params = new HashMap<String, Object>(); // params.put("mac", router.getMac()); // params.put("password", router.getPassword()); // Trouter t = routerDao.get("from Trouter t where t.mac = :mac and t.password = :<PASSWORD>", params); // if (t != null) { // Router u = new Router(); // BeanUtils.copyProperties(t, u); // return u; // } // return null; // } @Override public List<String> resourceList(Long id) { List<String> resourceList = new ArrayList<String>(); Map<String, Object> params = new HashMap<String, Object>(); params.put("id", id); Trouter t = routerDao.get( "from Trouter t where t.id = :id", params); // if (t != null) { // Set<Trole> roles = t.getRoles(); // if ((roles != null) && !roles.isEmpty()) { // for (Trole role : roles) { // Set<Tresource> resources = role.getResources(); // if ((resources != null) && !resources.isEmpty()) { // for (Tresource resource : resources) { // if ((resource != null) && (resource.getUrl() != null)) { // resourceList.add(resource.getUrl()); // } // } // } // } // } // } return resourceList; } // @Override // public boolean editUserPwd(SessionInfo sessionInfo, String oldPwd, // String pwd) { // Trouter u = routerDao.get(Trouter.class, sessionInfo.getId()); // if (u.getPassword().equalsIgnoreCase(oldPwd)) {// 说明原密码输入正确 // u.setPassword(pwd); // return true; // } // return false; // } @Override public Router getByName(Router router) { Trouter t = routerDao.get("from Trouter t where t.mac = '"+router.getMac()+"'"); Router u = new Router(); if(t!=null){ BeanUtils.copyProperties(t, u); }else{ return null; } return u; } }
4,972
0.634073
0.633468
173
26.670521
23.446436
118
false
false
0
0
0
0
0
0
2.479769
false
false
6
5d853ecd586c15717dbda45c8e64fe9e104cbfae
33,509,334,896,588
398774f5812a01244216f72e1fd652b49379f880
/src/main/java/com/woodtailer/emailalertplugin/model/IncommingRequest.java
b50d5e39b79ace36e29d317dc57f5aaf3dfd7a3f
[]
no_license
harald-billstein/emailAlert
https://github.com/harald-billstein/emailAlert
d22492480e76e61013ead8de01d69d6ac7a8c8f9
2d3c6c8f7b6ab55f7a39be08015fbdd7749c37c1
refs/heads/master
2020-03-27T18:04:30.153000
2018-09-13T13:37:23
2018-09-13T13:37:23
146,896,495
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.woodtailer.emailalertplugin.model; import java.util.ArrayList; import lombok.Data; @Data public class IncommingRequest { private String emailAddress; private ArrayList words; }
UTF-8
Java
198
java
IncommingRequest.java
Java
[]
null
[]
package com.woodtailer.emailalertplugin.model; import java.util.ArrayList; import lombok.Data; @Data public class IncommingRequest { private String emailAddress; private ArrayList words; }
198
0.792929
0.792929
13
14.230769
15.532368
46
false
false
0
0
0
0
0
0
0.384615
false
false
6
ab003e509ea80b89b33bd3122057a8e6017c7188
3,109,556,367,676
17aafa3c4369df27ea57cb210ac8c3309295d400
/demos/android/AppTFPNoGUIGraphicsBridgeDemo2/src/com/example/apptfpnoguigraphicsbridgedemo2/jImageView.java
c4fa96ad40227f48b680c162a183e57dbc13b2a5
[]
no_license
jmpessoa/tfpnoguigraphicsbridge
https://github.com/jmpessoa/tfpnoguigraphicsbridge
1a34243b84185c2250b4695d28f318ea67f8d6a0
d88e7892ba52c577d592eff01f694fa760ca98fd
refs/heads/master
2021-01-17T08:58:51.492000
2017-06-25T19:51:47
2017-06-25T19:51:47
34,188,563
3
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.apptfpnoguigraphicsbridgedemo2; import java.io.FileNotFoundException; import java.io.InputStream; import java.lang.reflect.Field; import javax.microedition.khronos.opengles.GL10; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.PorterDuff.Mode; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.PaintDrawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.MediaStore; import android.view.View; import android.widget.ImageView; public class jImageView extends ImageView { //Pascal Interface private long PasObj = 0; // Pascal Obj private Controls controls = null; // Control Cass for Event private jCommons LAMWCommon; // private OnClickListener onClickListener; // public Bitmap bmp = null; // Matrix mMatrix; int mRadius = 20; //Constructor public jImageView(android.content.Context context, Controls ctrls,long pasobj ) { super(context); //Connect Pascal I/F PasObj = pasobj; controls = ctrls; LAMWCommon = new jCommons(this,context,pasobj); //setAdjustViewBounds(false); setScaleType(ImageView.ScaleType.CENTER); mMatrix = new Matrix(); //Init Event onClickListener = new OnClickListener() { public void onClick(View view) { controls.pOnClick(PasObj,Const.Click_Default); } }; setOnClickListener(onClickListener); //this.setWillNotDraw(false); //false = fire OnDraw after Invalited ... true = not fire onDraw... thanks to tintinux } public void setLeftTopRightBottomWidthHeight(int _left, int _top, int _right, int _bottom, int _w, int _h) { LAMWCommon.setLeftTopRightBottomWidthHeight(_left,_top,_right,_bottom,_w,_h); } public void setParent( android.view.ViewGroup _viewgroup ) { LAMWCommon.setParent(_viewgroup); } //Free object except Self, Pascal Code Free the class. public void Free() { if (bmp != null) { bmp.recycle(); } bmp = null; setImageBitmap(null); setImageResource(0); //android.R.color.transparent; onClickListener = null; setOnClickListener(null); mMatrix = null; LAMWCommon.free(); } private Bitmap GetResizedBitmap(Bitmap _bmp, int _newWidth, int _newHeight){ float factorH = _newHeight / (float)_bmp.getHeight(); float factorW = _newWidth / (float)_bmp.getWidth(); float factorToUse = (factorH > factorW) ? factorW : factorH; Bitmap bm = Bitmap.createScaledBitmap(_bmp, (int) (_bmp.getWidth() * factorToUse), (int) (_bmp.getHeight() * factorToUse),false); return bm; } public void SetBitmapImage(Bitmap _bitmap, int _width, int _height) { this.setImageResource(android.R.color.transparent); bmp = GetResizedBitmap(_bitmap, _width, _height); this.setImageBitmap(bmp); this.invalidate(); } //http://stackoverflow.com/questions/10271020/bitmap-too-large-to-be-uploaded-into-a-texture public void SetBitmapImage(Bitmap bm) { this.setImageResource(android.R.color.transparent); //erase image ??.... if ( (bm.getHeight() > GL10.GL_MAX_TEXTURE_SIZE) || (bm.getWidth() > GL10.GL_MAX_TEXTURE_SIZE)) { //is is the case when the bitmap fails to load int nh = (int) ( bm.getHeight() * (1024.0 / bm.getWidth()) ); Bitmap scaled = Bitmap.createScaledBitmap(bm,1024, nh, true); this.setImageBitmap(scaled); bmp = scaled; } else{ // for bitmaps with dimensions that lie within the limits, load the image normally if (Build.VERSION.SDK_INT >= 16) { // why?? BitmapDrawable ob = new BitmapDrawable(this.getResources(), bm); //[ifdef_api16up] this.setBackground(ob); //[endif_api16up] //this.setImageBitmap(bm); bmp = bm; } else { this.setImageBitmap(bm); bmp = bm; } } this.invalidate(); } public void setImage(String fullPath) { //if (bmp != null) { bmp.recycle(); } this.setImageResource(android.R.color.transparent); if (fullPath.equals("null")) { this.setImageBitmap(null); return; }; bmp = BitmapFactory.decodeFile(fullPath); this.setImageBitmap(bmp); this.invalidate(); } public int GetDrawableResourceId(String _resName) { try { Class<?> res = R.drawable.class; Field field = res.getField(_resName); //"drawableName" int drawableId = field.getInt(null); return drawableId; } catch (Exception e) { //Log.e("jImageView", "Failure to get drawable id.", e); return 0; } } public Drawable GetDrawableResourceById(int _resID) { return (Drawable)( this.controls.activity.getResources().getDrawable(_resID)); } public void SetImageByResIdentifier(String _imageResIdentifier) { Drawable d = GetDrawableResourceById(GetDrawableResourceId(_imageResIdentifier)); bmp = ((BitmapDrawable)d).getBitmap(); this.setImageDrawable(d); this.invalidate(); } public void setLParamWidth(int _w) { LAMWCommon.setLParamWidth(_w); } public void setLParamHeight(int _h) { LAMWCommon.setLParamHeight(_h); } public void setLGravity(int _g) { LAMWCommon.setLGravity(_g); } public void setLWeight(float _w) { LAMWCommon.setLWeight(_w); } public int getLParamHeight() { return LAMWCommon.getLParamHeight(); } public int getLParamWidth() { return LAMWCommon.getLParamWidth(); } public int GetBitmapHeight() { if (bmp != null) { return this.bmp.getHeight(); } else return 0; } public int GetBitmapWidth() { if (bmp != null) { return this.bmp.getWidth(); } else return 0; } public void addLParamsAnchorRule(int rule) { LAMWCommon.addLParamsAnchorRule(rule); } public void addLParamsParentRule(int rule) { LAMWCommon.addLParamsParentRule(rule); } public void setLayoutAll(int idAnchor) { LAMWCommon.setLayoutAll(idAnchor); } public void ClearLayoutAll() { LAMWCommon.clearLayoutAll(); } /* * TScaleType = (scaleCenter, scaleCenterCrop, scaleCenterInside, scaleFitCenter, scaleFitEnd, scaleFitStart, scaleFitXY, scaleMatrix); ref. http://www.peachpit.com/articles/article.aspx?p=1846580&seqNum=2 hint: If you are creating a photo-viewing application, you will probably want to use the center or fitCenter scale types. */ public void SetScaleType(int _scaleType) { //TODO! switch(_scaleType) { case 0: setScaleType(ImageView.ScaleType.CENTER); break; case 1: setScaleType(ImageView.ScaleType.CENTER_CROP); break; case 2: setScaleType(ImageView.ScaleType.CENTER_INSIDE); break; case 3: setScaleType(ImageView.ScaleType.FIT_CENTER); break; case 4: setScaleType(ImageView.ScaleType.FIT_END); break; case 5: setScaleType(ImageView.ScaleType.FIT_START); break; case 6: setScaleType(ImageView.ScaleType.FIT_XY); break; case 7: setScaleType(ImageView.ScaleType.MATRIX); break; } } public void SetImageMatrixScale(float _scaleX, float _scaleY ) { if ( this.getScaleType() != ImageView.ScaleType.MATRIX) this.setScaleType(ImageView.ScaleType.MATRIX); mMatrix.setScale(_scaleX, _scaleY); this.setImageMatrix(mMatrix); this.invalidate(); } public Bitmap GetBitmapImage() { return bmp; } public void SetImageFromIntentResult(Intent _intentData) { Uri selectedImage = _intentData.getData(); String[] filePathColumn = { MediaStore.Images.Media.DATA }; Cursor cursor = controls.activity.getContentResolver().query(selectedImage, filePathColumn, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); String picturePath = cursor.getString(columnIndex); cursor.close(); bmp = BitmapFactory.decodeFile(picturePath); this.setImageBitmap(bmp); this.invalidate(); } public void SetImageThumbnailFromCamera(Intent _intentData) { Bundle extras = _intentData.getExtras(); bmp = (Bitmap) extras.get("data"); this.setImageBitmap(bmp); this.invalidate(); } //TODO Pascal public void SetImageFromURI(Uri _uri) { InputStream imageStream = null; try { imageStream = controls.activity.getContentResolver().openInputStream(_uri); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } bmp = BitmapFactory.decodeStream(imageStream); this.setImageBitmap(bmp); this.invalidate(); } public void SetImageFromByteArray(byte[] _image) { bmp = BitmapFactory.decodeByteArray(_image, 0, _image.length); this.setImageBitmap(bmp); this.invalidate(); } public Bitmap GetDrawingCache() { this.setDrawingCacheEnabled(true); Bitmap b = Bitmap.createBitmap(this.getDrawingCache()); this.setDrawingCacheEnabled(false); return b; } public void SetRoundCorner() { if (this != null) { PaintDrawable shape = new PaintDrawable(); shape.setCornerRadius(mRadius); int color = Color.TRANSPARENT; Drawable background = this.getBackground(); if (background instanceof ColorDrawable) { color = ((ColorDrawable)this.getBackground()).getColor(); shape.setColorFilter(color, Mode.SRC_ATOP); //[ifdef_api16up] if(Build.VERSION.SDK_INT >= 16) this.setBackground((Drawable)shape); //[endif_api16up] } } } public void SetRadiusRoundCorner(int _radius) { mRadius = _radius; } }
UTF-8
Java
9,603
java
jImageView.java
Java
[]
null
[]
package com.example.apptfpnoguigraphicsbridgedemo2; import java.io.FileNotFoundException; import java.io.InputStream; import java.lang.reflect.Field; import javax.microedition.khronos.opengles.GL10; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.PorterDuff.Mode; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.PaintDrawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.MediaStore; import android.view.View; import android.widget.ImageView; public class jImageView extends ImageView { //Pascal Interface private long PasObj = 0; // Pascal Obj private Controls controls = null; // Control Cass for Event private jCommons LAMWCommon; // private OnClickListener onClickListener; // public Bitmap bmp = null; // Matrix mMatrix; int mRadius = 20; //Constructor public jImageView(android.content.Context context, Controls ctrls,long pasobj ) { super(context); //Connect Pascal I/F PasObj = pasobj; controls = ctrls; LAMWCommon = new jCommons(this,context,pasobj); //setAdjustViewBounds(false); setScaleType(ImageView.ScaleType.CENTER); mMatrix = new Matrix(); //Init Event onClickListener = new OnClickListener() { public void onClick(View view) { controls.pOnClick(PasObj,Const.Click_Default); } }; setOnClickListener(onClickListener); //this.setWillNotDraw(false); //false = fire OnDraw after Invalited ... true = not fire onDraw... thanks to tintinux } public void setLeftTopRightBottomWidthHeight(int _left, int _top, int _right, int _bottom, int _w, int _h) { LAMWCommon.setLeftTopRightBottomWidthHeight(_left,_top,_right,_bottom,_w,_h); } public void setParent( android.view.ViewGroup _viewgroup ) { LAMWCommon.setParent(_viewgroup); } //Free object except Self, Pascal Code Free the class. public void Free() { if (bmp != null) { bmp.recycle(); } bmp = null; setImageBitmap(null); setImageResource(0); //android.R.color.transparent; onClickListener = null; setOnClickListener(null); mMatrix = null; LAMWCommon.free(); } private Bitmap GetResizedBitmap(Bitmap _bmp, int _newWidth, int _newHeight){ float factorH = _newHeight / (float)_bmp.getHeight(); float factorW = _newWidth / (float)_bmp.getWidth(); float factorToUse = (factorH > factorW) ? factorW : factorH; Bitmap bm = Bitmap.createScaledBitmap(_bmp, (int) (_bmp.getWidth() * factorToUse), (int) (_bmp.getHeight() * factorToUse),false); return bm; } public void SetBitmapImage(Bitmap _bitmap, int _width, int _height) { this.setImageResource(android.R.color.transparent); bmp = GetResizedBitmap(_bitmap, _width, _height); this.setImageBitmap(bmp); this.invalidate(); } //http://stackoverflow.com/questions/10271020/bitmap-too-large-to-be-uploaded-into-a-texture public void SetBitmapImage(Bitmap bm) { this.setImageResource(android.R.color.transparent); //erase image ??.... if ( (bm.getHeight() > GL10.GL_MAX_TEXTURE_SIZE) || (bm.getWidth() > GL10.GL_MAX_TEXTURE_SIZE)) { //is is the case when the bitmap fails to load int nh = (int) ( bm.getHeight() * (1024.0 / bm.getWidth()) ); Bitmap scaled = Bitmap.createScaledBitmap(bm,1024, nh, true); this.setImageBitmap(scaled); bmp = scaled; } else{ // for bitmaps with dimensions that lie within the limits, load the image normally if (Build.VERSION.SDK_INT >= 16) { // why?? BitmapDrawable ob = new BitmapDrawable(this.getResources(), bm); //[ifdef_api16up] this.setBackground(ob); //[endif_api16up] //this.setImageBitmap(bm); bmp = bm; } else { this.setImageBitmap(bm); bmp = bm; } } this.invalidate(); } public void setImage(String fullPath) { //if (bmp != null) { bmp.recycle(); } this.setImageResource(android.R.color.transparent); if (fullPath.equals("null")) { this.setImageBitmap(null); return; }; bmp = BitmapFactory.decodeFile(fullPath); this.setImageBitmap(bmp); this.invalidate(); } public int GetDrawableResourceId(String _resName) { try { Class<?> res = R.drawable.class; Field field = res.getField(_resName); //"drawableName" int drawableId = field.getInt(null); return drawableId; } catch (Exception e) { //Log.e("jImageView", "Failure to get drawable id.", e); return 0; } } public Drawable GetDrawableResourceById(int _resID) { return (Drawable)( this.controls.activity.getResources().getDrawable(_resID)); } public void SetImageByResIdentifier(String _imageResIdentifier) { Drawable d = GetDrawableResourceById(GetDrawableResourceId(_imageResIdentifier)); bmp = ((BitmapDrawable)d).getBitmap(); this.setImageDrawable(d); this.invalidate(); } public void setLParamWidth(int _w) { LAMWCommon.setLParamWidth(_w); } public void setLParamHeight(int _h) { LAMWCommon.setLParamHeight(_h); } public void setLGravity(int _g) { LAMWCommon.setLGravity(_g); } public void setLWeight(float _w) { LAMWCommon.setLWeight(_w); } public int getLParamHeight() { return LAMWCommon.getLParamHeight(); } public int getLParamWidth() { return LAMWCommon.getLParamWidth(); } public int GetBitmapHeight() { if (bmp != null) { return this.bmp.getHeight(); } else return 0; } public int GetBitmapWidth() { if (bmp != null) { return this.bmp.getWidth(); } else return 0; } public void addLParamsAnchorRule(int rule) { LAMWCommon.addLParamsAnchorRule(rule); } public void addLParamsParentRule(int rule) { LAMWCommon.addLParamsParentRule(rule); } public void setLayoutAll(int idAnchor) { LAMWCommon.setLayoutAll(idAnchor); } public void ClearLayoutAll() { LAMWCommon.clearLayoutAll(); } /* * TScaleType = (scaleCenter, scaleCenterCrop, scaleCenterInside, scaleFitCenter, scaleFitEnd, scaleFitStart, scaleFitXY, scaleMatrix); ref. http://www.peachpit.com/articles/article.aspx?p=1846580&seqNum=2 hint: If you are creating a photo-viewing application, you will probably want to use the center or fitCenter scale types. */ public void SetScaleType(int _scaleType) { //TODO! switch(_scaleType) { case 0: setScaleType(ImageView.ScaleType.CENTER); break; case 1: setScaleType(ImageView.ScaleType.CENTER_CROP); break; case 2: setScaleType(ImageView.ScaleType.CENTER_INSIDE); break; case 3: setScaleType(ImageView.ScaleType.FIT_CENTER); break; case 4: setScaleType(ImageView.ScaleType.FIT_END); break; case 5: setScaleType(ImageView.ScaleType.FIT_START); break; case 6: setScaleType(ImageView.ScaleType.FIT_XY); break; case 7: setScaleType(ImageView.ScaleType.MATRIX); break; } } public void SetImageMatrixScale(float _scaleX, float _scaleY ) { if ( this.getScaleType() != ImageView.ScaleType.MATRIX) this.setScaleType(ImageView.ScaleType.MATRIX); mMatrix.setScale(_scaleX, _scaleY); this.setImageMatrix(mMatrix); this.invalidate(); } public Bitmap GetBitmapImage() { return bmp; } public void SetImageFromIntentResult(Intent _intentData) { Uri selectedImage = _intentData.getData(); String[] filePathColumn = { MediaStore.Images.Media.DATA }; Cursor cursor = controls.activity.getContentResolver().query(selectedImage, filePathColumn, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); String picturePath = cursor.getString(columnIndex); cursor.close(); bmp = BitmapFactory.decodeFile(picturePath); this.setImageBitmap(bmp); this.invalidate(); } public void SetImageThumbnailFromCamera(Intent _intentData) { Bundle extras = _intentData.getExtras(); bmp = (Bitmap) extras.get("data"); this.setImageBitmap(bmp); this.invalidate(); } //TODO Pascal public void SetImageFromURI(Uri _uri) { InputStream imageStream = null; try { imageStream = controls.activity.getContentResolver().openInputStream(_uri); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } bmp = BitmapFactory.decodeStream(imageStream); this.setImageBitmap(bmp); this.invalidate(); } public void SetImageFromByteArray(byte[] _image) { bmp = BitmapFactory.decodeByteArray(_image, 0, _image.length); this.setImageBitmap(bmp); this.invalidate(); } public Bitmap GetDrawingCache() { this.setDrawingCacheEnabled(true); Bitmap b = Bitmap.createBitmap(this.getDrawingCache()); this.setDrawingCacheEnabled(false); return b; } public void SetRoundCorner() { if (this != null) { PaintDrawable shape = new PaintDrawable(); shape.setCornerRadius(mRadius); int color = Color.TRANSPARENT; Drawable background = this.getBackground(); if (background instanceof ColorDrawable) { color = ((ColorDrawable)this.getBackground()).getColor(); shape.setColorFilter(color, Mode.SRC_ATOP); //[ifdef_api16up] if(Build.VERSION.SDK_INT >= 16) this.setBackground((Drawable)shape); //[endif_api16up] } } } public void SetRadiusRoundCorner(int _radius) { mRadius = _radius; } }
9,603
0.69874
0.692388
314
29.579618
25.381578
118
false
false
0
0
0
0
0
0
2.232484
false
false
6
42f8268a2f8cb6b54f269d3e8a2e7495029a4934
25,211,458,062,980
7bc975c929eedca0d2254360360b7f021749ae7f
/src/main/java/com/redxun/bpm/activiti/event/TaskCompleteApplicationEvent.java
0b0a676f42f11fe369f3419f48994b8e25723a33
[]
no_license
liaosheng2018/jsaas-1
https://github.com/liaosheng2018/jsaas-1
7d6e5a10b9bf22e4e6793a4efe3c783fb4afc621
0fd2df00b4680c92500429bd800b1806b816002d
refs/heads/master
2022-03-10T12:22:51.907000
2019-11-29T07:11:11
2019-11-29T07:11:11
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.redxun.bpm.activiti.event; import org.activiti.engine.impl.persistence.entity.TaskEntity; import org.springframework.context.ApplicationEvent; /** * * * <pre> * 描述:任务完成监听器 * 作者:cjx * 邮箱:chshxuan@163.com * 日期:2016年5月7日-下午2:17:18 * @Copyright (c) 2014-2016 广州红迅软件有限公司(http://www.redxun.cn) * 本源代码受软件著作法保护,请在授权允许范围内使用。 * </pre> */ public class TaskCompleteApplicationEvent extends ApplicationEvent { public TaskCompleteApplicationEvent(final TaskEntity taskEntity) { super(taskEntity); } }
UTF-8
Java
636
java
TaskCompleteApplicationEvent.java
Java
[ { "context": "nEvent;\n\n/**\n * \n * \n * <pre>\n * 描述:任务完成监听器\n * 作者:cjx\n * 邮箱:chshxuan@163.com\n * 日期:2016年5月7日-下午2:17:18\n", "end": 201, "score": 0.9997252225875854, "start": 198, "tag": "USERNAME", "value": "cjx" }, { "context": "**\n * \n * \n * <pre>\n * 描述:任务完成监听器\n * 作者:cjx\n * 邮箱:chshxuan@163.com\n * 日期:2016年5月7日-下午2:17:18\n * @Copyright (c) 2014-", "end": 224, "score": 0.9999241828918457, "start": 208, "tag": "EMAIL", "value": "chshxuan@163.com" } ]
null
[]
package com.redxun.bpm.activiti.event; import org.activiti.engine.impl.persistence.entity.TaskEntity; import org.springframework.context.ApplicationEvent; /** * * * <pre> * 描述:任务完成监听器 * 作者:cjx * 邮箱:<EMAIL> * 日期:2016年5月7日-下午2:17:18 * @Copyright (c) 2014-2016 广州红迅软件有限公司(http://www.redxun.cn) * 本源代码受软件著作法保护,请在授权允许范围内使用。 * </pre> */ public class TaskCompleteApplicationEvent extends ApplicationEvent { public TaskCompleteApplicationEvent(final TaskEntity taskEntity) { super(taskEntity); } }
627
0.750965
0.708494
22
22.545454
23.598396
68
false
false
0
0
0
0
0
0
0.363636
false
false
6
8659a017110e38dbaea10777ef37a45da0fd21f4
29,446,295,827,276
25a4a049b236316f05d8826cd8b6f391d8bfcc9c
/dataaccess/src/main/java/wsvintsitsky/hotel/dataaccess/ApartmentClassDao.java
c08b4862aa887b82605b0aa9bcff3e1789767349
[]
no_license
vvsvintsitsky/webhotel
https://github.com/vvsvintsitsky/webhotel
942e064a4fa04232fe72c42b516504237a7b90f4
e5396a9acb242a62d9e108b346942d2bce66fb8a
refs/heads/master
2020-12-25T06:42:50.560000
2016-06-29T00:10:27
2016-06-29T00:10:27
59,880,903
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package wsvintsitsky.hotel.dataaccess; import wsvintsitsky.hotel.dataaccess.filters.ApartmentClassFilter; import wsvintsitsky.hotel.datamodel.ApartmentClass; public interface ApartmentClassDao extends AbstractDao<ApartmentClass, Long> { void multiUpdateAptClass(ApartmentClassFilter filter, String newAptClass); }
UTF-8
Java
319
java
ApartmentClassDao.java
Java
[]
null
[]
package wsvintsitsky.hotel.dataaccess; import wsvintsitsky.hotel.dataaccess.filters.ApartmentClassFilter; import wsvintsitsky.hotel.datamodel.ApartmentClass; public interface ApartmentClassDao extends AbstractDao<ApartmentClass, Long> { void multiUpdateAptClass(ApartmentClassFilter filter, String newAptClass); }
319
0.858934
0.858934
9
34.444443
32.37664
78
false
false
0
0
0
0
0
0
0.888889
false
false
6
e3b3320c45b69c11d653709c9e2dc1bb18036e15
29,446,295,828,988
116203847f66655631bb7d0de8bcf20bc88576c7
/src/main/java/org/chassot/auth/controller/HealthController.java
f5c97ce3facd1cd272535df84c60972465d538ac
[]
no_license
chassot/auth
https://github.com/chassot/auth
408e775a461cfd0ecc2f6aea313a534dd386d286
111d688db8ba2202abb26717310f618b3b50251b
refs/heads/master
2022-04-10T09:30:53.817000
2020-03-31T14:40:52
2020-03-31T14:40:52
237,776,233
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.chassot.auth.controller; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @CrossOrigin @RequestMapping("/api/health") public class HealthController { @GetMapping public String getMessage() { return "Kickstart my heart"; } }
UTF-8
Java
471
java
HealthController.java
Java
[]
null
[]
package org.chassot.auth.controller; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @CrossOrigin @RequestMapping("/api/health") public class HealthController { @GetMapping public String getMessage() { return "Kickstart my heart"; } }
471
0.791932
0.791932
17
26.705883
22.367952
62
false
false
0
0
0
0
0
0
0.352941
false
false
6
56638b1089105893349e93bd77c6af88aa66b013
970,662,668,063
7a6e97193bf4fce8a3467660f79369dc66cc9364
/tutorial1/src/test/java/net/serenitybdd/tutorials/features/navigation/WhenBrowsingProductCategories.java
e00d63cceff9b1e41510ac79e3cfd05ac3325be0
[]
no_license
YuriyPent/serenity-tutorials
https://github.com/YuriyPent/serenity-tutorials
309e9bf5fd24dfa6fcd45527aa252da3518c4c07
882a3a770669154c0ecda33ca242d3d0df7b0be8
refs/heads/master
2022-07-18T06:09:54.522000
2019-06-24T08:52:29
2019-06-24T08:52:29
177,342,874
0
0
null
false
2019-04-07T20:57:15
2019-03-23T21:41:03
2019-03-25T20:10:17
2019-04-07T20:57:09
9
0
0
1
Java
false
false
package net.serenitybdd.tutorials.features.navigation; import net.serenitybdd.junit.runners.SerenityRunner; import net.serenitybdd.screenplay.Actor; import net.serenitybdd.screenplay.abilities.BrowseTheWeb; import net.serenitybdd.screenplay.questions.page.TheWebPage; import net.serenitybdd.tutorials.steps.NavigatingUser; import net.serenitybdd.tutorials.tasks.NavigateTo; import net.thucydides.core.annotations.Managed; import net.thucydides.core.annotations.Steps; import org.junit.Test; import org.junit.runner.RunWith; import org.openqa.selenium.WebDriver; import static net.serenitybdd.screenplay.GivenWhenThen.*; import static net.serenitybdd.tutorials.model.Category.Сохраненo; import static org.hamcrest.Matchers.containsString; @RunWith(SerenityRunner.class) public class WhenBrowsingProductCategories { @Steps NavigatingUser mark; @Managed WebDriver browser; @Test public void shouldBeAbleToNavigateToTheFeedCategory() { //Given mark.isOnTheHomePage(); //When mark.navigatesToCategory(Сохраненo); //Then mark.shouldSeePageTittleContaining("Войдите или зарегистрируйтесь | eBay"); } @Test public void shouldBeAbleToViewMotoProducts() { Actor mike = Actor.named("Mike"); mike.can(BrowseTheWeb.with(browser)); when(mike).attemptsTo(NavigateTo.theCategory(Сохраненo)); then(mike).should(seeThat(TheWebPage.title(), containsString("Войдите или зарегистрируйтесь | eBay"))); } }
UTF-8
Java
1,590
java
WhenBrowsingProductCategories.java
Java
[ { "context": "toProducts() {\n\n Actor mike = Actor.named(\"Mike\");\n mike.can(BrowseTheWeb.with(browser));\n", "end": 1276, "score": 0.7954949140548706, "start": 1272, "tag": "NAME", "value": "Mike" } ]
null
[]
package net.serenitybdd.tutorials.features.navigation; import net.serenitybdd.junit.runners.SerenityRunner; import net.serenitybdd.screenplay.Actor; import net.serenitybdd.screenplay.abilities.BrowseTheWeb; import net.serenitybdd.screenplay.questions.page.TheWebPage; import net.serenitybdd.tutorials.steps.NavigatingUser; import net.serenitybdd.tutorials.tasks.NavigateTo; import net.thucydides.core.annotations.Managed; import net.thucydides.core.annotations.Steps; import org.junit.Test; import org.junit.runner.RunWith; import org.openqa.selenium.WebDriver; import static net.serenitybdd.screenplay.GivenWhenThen.*; import static net.serenitybdd.tutorials.model.Category.Сохраненo; import static org.hamcrest.Matchers.containsString; @RunWith(SerenityRunner.class) public class WhenBrowsingProductCategories { @Steps NavigatingUser mark; @Managed WebDriver browser; @Test public void shouldBeAbleToNavigateToTheFeedCategory() { //Given mark.isOnTheHomePage(); //When mark.navigatesToCategory(Сохраненo); //Then mark.shouldSeePageTittleContaining("Войдите или зарегистрируйтесь | eBay"); } @Test public void shouldBeAbleToViewMotoProducts() { Actor mike = Actor.named("Mike"); mike.can(BrowseTheWeb.with(browser)); when(mike).attemptsTo(NavigateTo.theCategory(Сохраненo)); then(mike).should(seeThat(TheWebPage.title(), containsString("Войдите или зарегистрируйтесь | eBay"))); } }
1,590
0.761905
0.761905
46
31.869566
25.934372
111
false
false
0
0
0
0
0
0
0.586957
false
false
6
8cc353a57767da402d9525ce98d3a324642ee707
39,324,720,606,850
c4623aa95fb8cdd0ee1bc68962711c33af44604e
/src/com/google/android/gms/internal/jl$d.java
e3b2416bbea5a1f1efff65cac20da2954992c2c8
[]
no_license
reverseengineeringer/com.yelp.android
https://github.com/reverseengineeringer/com.yelp.android
48f7f2c830a3a1714112649a6a0a3110f7bdc2b1
b0ac8d4f6cd5fc5543f0d8de399b6d7b3a2184c8
refs/heads/master
2021-01-19T02:07:25.997000
2016-07-19T16:37:24
2016-07-19T16:37:24
38,555,675
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.google.android.gms.internal; import com.google.android.gms.common.data.DataHolder; public abstract class jl$d<TListener> extends jl<T>.b<TListener> { private final DataHolder JG; public jl$d(TListener paramTListener, DataHolder paramDataHolder) { super(paramTListener, paramDataHolder); DataHolder localDataHolder; JG = localDataHolder; } protected abstract void b(TListener paramTListener, DataHolder paramDataHolder); protected final void g(TListener paramTListener) { b(paramTListener, JG); } protected void hx() { if (JG != null) { JG.close(); } } } /* Location: * Qualified Name: com.google.android.gms.internal.jl.d * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
UTF-8
Java
772
java
jl$d.java
Java
[]
null
[]
package com.google.android.gms.internal; import com.google.android.gms.common.data.DataHolder; public abstract class jl$d<TListener> extends jl<T>.b<TListener> { private final DataHolder JG; public jl$d(TListener paramTListener, DataHolder paramDataHolder) { super(paramTListener, paramDataHolder); DataHolder localDataHolder; JG = localDataHolder; } protected abstract void b(TListener paramTListener, DataHolder paramDataHolder); protected final void g(TListener paramTListener) { b(paramTListener, JG); } protected void hx() { if (JG != null) { JG.close(); } } } /* Location: * Qualified Name: com.google.android.gms.internal.jl.d * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
772
0.690414
0.681347
36
20.472221
21.631363
82
false
false
0
0
0
0
0
0
0.361111
false
false
6
91c5d776d5b72862e7a31f835da165bd31e7ea82
18,751,827,265,608
426ece8fcb5476070b613aa7aaceed941443f5e4
/app/src/main/java/com/atguigu/time/module_tickey/impletickbuy/MoviePager.java
6851e80d7e22d88450bafde3f43659295314e360
[]
no_license
FightingForDream/TimePro
https://github.com/FightingForDream/TimePro
0543494e05cd6cc63930c1e17433dc66c11f45da
040382dad74a8c3c04db54e49460c93d104fcb6d
refs/heads/master
2021-01-10T17:19:16.802000
2016-04-21T01:36:26
2016-04-21T01:36:26
55,791,832
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.atguigu.time.module_tickey.impletickbuy; import android.app.Activity; import android.graphics.drawable.AnimationDrawable; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.View; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.atguigu.time.MainActivity; import com.atguigu.time.R; import com.atguigu.time.module_tickey.afragment.HotMovieFragment; import com.atguigu.time.module_tickey.afragment.WillOnMovieFragment; import com.atguigu.time.pager.TicketBuyPager; import org.xutils.view.annotation.ViewInject; import org.xutils.x; /** * 作用:电影详情页面 */ public class MoviePager extends TicketBuyPager { @ViewInject(R.id.movie_indicator) private TabLayout movie_indicator; @ViewInject(R.id.vp_movie) private ViewPager vp_movie; private RelativeLayout rl_loading; private TextView tv_loading; private ImageView iv_loading_failed, iv_loading,iv_ad; //引导图片 // 1 private int[] drawableIds = {R.drawable.lead_bg1, R.drawable.lead_bg2}; /** * ViewPager中嵌套listView等 * 第一步 */ private SectionsPagerAdapter mSectionsPagerAdapter; public MoviePager(Activity activity) { super(activity); } @Override public View getView() { View view = View.inflate(mActivity, R.layout.moviepager, null); x.view().inject(this, view); //动画 iv_loading = (ImageView) view.findViewById(R.id.iv_loading); iv_loading.setBackgroundResource(R.drawable.animation_list); AnimationDrawable animationDrawable = (AnimationDrawable) iv_loading.getBackground(); animationDrawable.start(); rl_loading = (RelativeLayout) view.findViewById(R.id.rl_loading); rl_loading.setVisibility(View.GONE); tv_loading = (TextView) view.findViewById(R.id.tv_loading); iv_loading = (ImageView) view.findViewById(R.id.iv_loading); iv_loading_failed = (ImageView) view.findViewById(R.id.iv_loading_failed); iv_ad = (ImageView) view.findViewById(R.id.iv_ad);//广告图片 return view; } @Override public void initData() { super.initData(); System.out.println("影院详情页面数据被初始化了..."); /** * 第二步 */ MainActivity activity = (MainActivity) mActivity;//因为MainActivity必须继承FragmentActivity才能得到下面的方法 mSectionsPagerAdapter = new SectionsPagerAdapter(activity.getSupportFragmentManager()); //设置适配器 vp_movie.setAdapter(mSectionsPagerAdapter); //关联页签页面与ViewPager movie_indicator.setupWithViewPager(vp_movie); movie_indicator.setTabGravity(TabLayout.GRAVITY_CENTER); // vp_movie.addOnPageChangeListener(new MyPagerChangerListener()); } /** * ViewPager添加ListView的Adapter */ public class SectionsPagerAdapter extends FragmentPagerAdapter { public SectionsPagerAdapter(FragmentManager fm) { super(fm); } //切换两个ListView页面 @Override public Fragment getItem(int position) { switch (position) { case 0: { return new HotMovieFragment(); } case 1: { return new WillOnMovieFragment(); } } return null; } @Override public int getCount() { return 2; } @Override public CharSequence getPageTitle(int position) { switch (position) { case 0: return "正在热映"; case 1: return "即将上映"; } return null; } } // class MyPagerChangerListener implements ViewPager.OnPageChangeListener { // @Override // public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { // // } // // @Override // public void onPageSelected(int position) { //// if (position == drawableIds.length - 1) { //// btn_start_main.setVisibility(View.VISIBLE); //// } else { //// btn_start_main.setVisibility(View.GONE); //// } // } // // @Override // public void onPageScrollStateChanged(int state) { // // } // } /** * 填装热映和即将上映两个ListView的Adapter */ // class MoviePagerAdapter extends PagerAdapter { // @Override // public CharSequence getPageTitle(int position) { // if(position == 0) { // return "正在热映"; // }else { // return "即将上映"; // } // } // // @Override // public int getCount() { // return drawableIds.length; // } // // @Override // public boolean isViewFromObject(View view, Object object) { // return view==object; // } // // @Override // public Object instantiateItem(ViewGroup container, int position) { // ImageView imageView = new ImageView(mActivity); // imageView.setBackgroundResource(drawableIds[position]); // container.addView(imageView);//图片加入到ViewPager中 ViewPager的父类是ViewGroup // return imageView;//可以 // } // // @Override // public void destroyItem(ViewGroup container, int position, Object object) { // container.removeView((View) object); // } // } }
UTF-8
Java
5,910
java
MoviePager.java
Java
[]
null
[]
package com.atguigu.time.module_tickey.impletickbuy; import android.app.Activity; import android.graphics.drawable.AnimationDrawable; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.View; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.atguigu.time.MainActivity; import com.atguigu.time.R; import com.atguigu.time.module_tickey.afragment.HotMovieFragment; import com.atguigu.time.module_tickey.afragment.WillOnMovieFragment; import com.atguigu.time.pager.TicketBuyPager; import org.xutils.view.annotation.ViewInject; import org.xutils.x; /** * 作用:电影详情页面 */ public class MoviePager extends TicketBuyPager { @ViewInject(R.id.movie_indicator) private TabLayout movie_indicator; @ViewInject(R.id.vp_movie) private ViewPager vp_movie; private RelativeLayout rl_loading; private TextView tv_loading; private ImageView iv_loading_failed, iv_loading,iv_ad; //引导图片 // 1 private int[] drawableIds = {R.drawable.lead_bg1, R.drawable.lead_bg2}; /** * ViewPager中嵌套listView等 * 第一步 */ private SectionsPagerAdapter mSectionsPagerAdapter; public MoviePager(Activity activity) { super(activity); } @Override public View getView() { View view = View.inflate(mActivity, R.layout.moviepager, null); x.view().inject(this, view); //动画 iv_loading = (ImageView) view.findViewById(R.id.iv_loading); iv_loading.setBackgroundResource(R.drawable.animation_list); AnimationDrawable animationDrawable = (AnimationDrawable) iv_loading.getBackground(); animationDrawable.start(); rl_loading = (RelativeLayout) view.findViewById(R.id.rl_loading); rl_loading.setVisibility(View.GONE); tv_loading = (TextView) view.findViewById(R.id.tv_loading); iv_loading = (ImageView) view.findViewById(R.id.iv_loading); iv_loading_failed = (ImageView) view.findViewById(R.id.iv_loading_failed); iv_ad = (ImageView) view.findViewById(R.id.iv_ad);//广告图片 return view; } @Override public void initData() { super.initData(); System.out.println("影院详情页面数据被初始化了..."); /** * 第二步 */ MainActivity activity = (MainActivity) mActivity;//因为MainActivity必须继承FragmentActivity才能得到下面的方法 mSectionsPagerAdapter = new SectionsPagerAdapter(activity.getSupportFragmentManager()); //设置适配器 vp_movie.setAdapter(mSectionsPagerAdapter); //关联页签页面与ViewPager movie_indicator.setupWithViewPager(vp_movie); movie_indicator.setTabGravity(TabLayout.GRAVITY_CENTER); // vp_movie.addOnPageChangeListener(new MyPagerChangerListener()); } /** * ViewPager添加ListView的Adapter */ public class SectionsPagerAdapter extends FragmentPagerAdapter { public SectionsPagerAdapter(FragmentManager fm) { super(fm); } //切换两个ListView页面 @Override public Fragment getItem(int position) { switch (position) { case 0: { return new HotMovieFragment(); } case 1: { return new WillOnMovieFragment(); } } return null; } @Override public int getCount() { return 2; } @Override public CharSequence getPageTitle(int position) { switch (position) { case 0: return "正在热映"; case 1: return "即将上映"; } return null; } } // class MyPagerChangerListener implements ViewPager.OnPageChangeListener { // @Override // public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { // // } // // @Override // public void onPageSelected(int position) { //// if (position == drawableIds.length - 1) { //// btn_start_main.setVisibility(View.VISIBLE); //// } else { //// btn_start_main.setVisibility(View.GONE); //// } // } // // @Override // public void onPageScrollStateChanged(int state) { // // } // } /** * 填装热映和即将上映两个ListView的Adapter */ // class MoviePagerAdapter extends PagerAdapter { // @Override // public CharSequence getPageTitle(int position) { // if(position == 0) { // return "正在热映"; // }else { // return "即将上映"; // } // } // // @Override // public int getCount() { // return drawableIds.length; // } // // @Override // public boolean isViewFromObject(View view, Object object) { // return view==object; // } // // @Override // public Object instantiateItem(ViewGroup container, int position) { // ImageView imageView = new ImageView(mActivity); // imageView.setBackgroundResource(drawableIds[position]); // container.addView(imageView);//图片加入到ViewPager中 ViewPager的父类是ViewGroup // return imageView;//可以 // } // // @Override // public void destroyItem(ViewGroup container, int position, Object object) { // container.removeView((View) object); // } // } }
5,910
0.610857
0.608389
204
26.813726
25.215048
102
false
false
0
0
0
0
0
0
0.387255
false
false
6
9a673a28d71889be35fa5d9cb209f0f7afe758c9
16,758,962,444,962
855c25512f7cadea6b77d0ac86b1cbcb6d4fabb0
/app/src/main/java/com/example/edgu1/angleseahospital/DrugsInformation.java
a0dc1d0d65c2c79ec66db4bcb9972e2e658cfd65
[]
no_license
edgu100/Angleseahospital999
https://github.com/edgu100/Angleseahospital999
8306370ad57bd95c10eb63cab3b671f6257b89d7
aadd065bf4a0c113c6dc5bd9384b62b4b649d28d
refs/heads/master
2022-01-04T23:05:46.767000
2019-04-30T03:13:16
2019-04-30T03:13:16
107,745,888
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.edgu1.angleseahospital; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.NavigationView; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.example.edgu1.angleseahospital.DB.Drug; import com.example.edgu1.angleseahospital.DB.SQLiteHelper; import java.util.List; public class DrugsInformation extends AppCompatActivity { private DrawerLayout dl; private ActionBarDrawerToggle abdt; private SQLiteHelper dbHandler=null; private List<Drug> drugs; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.drugsinfotmation); dl = (DrawerLayout)findViewById(R.id.drug_list); abdt = new ActionBarDrawerToggle(this,dl,R.string.Open,R.string.Close); abdt.setDrawerIndicatorEnabled(true); dl.addDrawerListener(abdt); abdt.syncState(); final NavigationView nav_view = (NavigationView)findViewById(R.id.nav_view); nav_view.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { int id = item.getItemId(); switch (id){ case R.id.nav_home: Intent h = new Intent(DrugsInformation.this, Mainpage.class); startActivity(h); break; case R.id.nav_patient: Intent p = new Intent(DrugsInformation.this, PatientListPage.class); startActivity(p); break; case R.id.nav_drug: // Intent d = new Intent(DrugsInformation.this, DrugsInformation.class); // startActivity(d); break; case R.id.nav_task: Intent t = new Intent(DrugsInformation.this, CusTask.class); startActivity(t); break; } return true; } }); String msg = getIntent().getStringExtra("drug"); if(msg!=null&&!"".equals(msg)){ Toast.makeText(this,msg,Toast.LENGTH_SHORT).show(); } dbHandler = new SQLiteHelper(this); drugs = dbHandler.getDrugsByName(null); try{ ProductListAdapter productListAdapter=new ProductListAdapter(); ListView productList =(ListView) findViewById(R.id.DrugsDetails); productList.setAdapter(productListAdapter); productList.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Drug drug = drugs.get(position); Intent intent=new Intent(getApplicationContext(),drugsdetails.class); intent.putExtra("drug",drug); startActivity(intent); } }); }catch (Exception e){ e.printStackTrace(); } } ///////////////////////////// /////////Show Drugslist/////// //////////////////////////// class ProductListAdapter extends BaseAdapter { @Override public int getCount() { return drugs.size(); } @Override public Object getItem(int i) { return null; } @Override public long getItemId(int i) { return 0; } @Override public View getView(int position, View view, ViewGroup viewGroup) { view = getLayoutInflater().inflate(R.layout.simple_drugs_list, null); Drug drug = drugs.get(position); TextView drugName = (TextView) view.findViewById(R.id.DrugName); TextView drugproductionDate = (TextView) view.findViewById(R.id.DrugproductionDate); TextView drugshelfLife = (TextView) view.findViewById(R.id.DrugshelfLife); TextView drugspecification = (TextView) view.findViewById(R.id.Drugspecification); drugName.setText(drug.getName()); drugproductionDate.setText(String.valueOf(drug.getProductionDate())); drugshelfLife.setText(String.valueOf(drug.getShelfLife())); drugspecification.setText(String.valueOf(drug.getMilliliters())); return view; } } ///////////////////////////// /////////Search///////////// //////////////////////////// public void searchProduct(View v){ EditText searchText = (EditText) findViewById(R.id.searchText); drugs = dbHandler.getDrugsByName(searchText.getText().toString()); ProductListAdapter productListAdapter=new ProductListAdapter(); ListView productList =(ListView)findViewById(R.id.DrugsDetails); productList.setAdapter(productListAdapter); productList.deferNotifyDataSetChanged(); } //ADD Drugsdetail public void ADD(View view){ Intent i= new Intent(this,Add_drugs.class); startActivity(i); } @Override public boolean onOptionsItemSelected(MenuItem item) { return abdt.onOptionsItemSelected(item) || super.onOptionsItemSelected(item); } }
UTF-8
Java
5,870
java
DrugsInformation.java
Java
[]
null
[]
package com.example.edgu1.angleseahospital; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.NavigationView; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.example.edgu1.angleseahospital.DB.Drug; import com.example.edgu1.angleseahospital.DB.SQLiteHelper; import java.util.List; public class DrugsInformation extends AppCompatActivity { private DrawerLayout dl; private ActionBarDrawerToggle abdt; private SQLiteHelper dbHandler=null; private List<Drug> drugs; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.drugsinfotmation); dl = (DrawerLayout)findViewById(R.id.drug_list); abdt = new ActionBarDrawerToggle(this,dl,R.string.Open,R.string.Close); abdt.setDrawerIndicatorEnabled(true); dl.addDrawerListener(abdt); abdt.syncState(); final NavigationView nav_view = (NavigationView)findViewById(R.id.nav_view); nav_view.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { int id = item.getItemId(); switch (id){ case R.id.nav_home: Intent h = new Intent(DrugsInformation.this, Mainpage.class); startActivity(h); break; case R.id.nav_patient: Intent p = new Intent(DrugsInformation.this, PatientListPage.class); startActivity(p); break; case R.id.nav_drug: // Intent d = new Intent(DrugsInformation.this, DrugsInformation.class); // startActivity(d); break; case R.id.nav_task: Intent t = new Intent(DrugsInformation.this, CusTask.class); startActivity(t); break; } return true; } }); String msg = getIntent().getStringExtra("drug"); if(msg!=null&&!"".equals(msg)){ Toast.makeText(this,msg,Toast.LENGTH_SHORT).show(); } dbHandler = new SQLiteHelper(this); drugs = dbHandler.getDrugsByName(null); try{ ProductListAdapter productListAdapter=new ProductListAdapter(); ListView productList =(ListView) findViewById(R.id.DrugsDetails); productList.setAdapter(productListAdapter); productList.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Drug drug = drugs.get(position); Intent intent=new Intent(getApplicationContext(),drugsdetails.class); intent.putExtra("drug",drug); startActivity(intent); } }); }catch (Exception e){ e.printStackTrace(); } } ///////////////////////////// /////////Show Drugslist/////// //////////////////////////// class ProductListAdapter extends BaseAdapter { @Override public int getCount() { return drugs.size(); } @Override public Object getItem(int i) { return null; } @Override public long getItemId(int i) { return 0; } @Override public View getView(int position, View view, ViewGroup viewGroup) { view = getLayoutInflater().inflate(R.layout.simple_drugs_list, null); Drug drug = drugs.get(position); TextView drugName = (TextView) view.findViewById(R.id.DrugName); TextView drugproductionDate = (TextView) view.findViewById(R.id.DrugproductionDate); TextView drugshelfLife = (TextView) view.findViewById(R.id.DrugshelfLife); TextView drugspecification = (TextView) view.findViewById(R.id.Drugspecification); drugName.setText(drug.getName()); drugproductionDate.setText(String.valueOf(drug.getProductionDate())); drugshelfLife.setText(String.valueOf(drug.getShelfLife())); drugspecification.setText(String.valueOf(drug.getMilliliters())); return view; } } ///////////////////////////// /////////Search///////////// //////////////////////////// public void searchProduct(View v){ EditText searchText = (EditText) findViewById(R.id.searchText); drugs = dbHandler.getDrugsByName(searchText.getText().toString()); ProductListAdapter productListAdapter=new ProductListAdapter(); ListView productList =(ListView)findViewById(R.id.DrugsDetails); productList.setAdapter(productListAdapter); productList.deferNotifyDataSetChanged(); } //ADD Drugsdetail public void ADD(View view){ Intent i= new Intent(this,Add_drugs.class); startActivity(i); } @Override public boolean onOptionsItemSelected(MenuItem item) { return abdt.onOptionsItemSelected(item) || super.onOptionsItemSelected(item); } }
5,870
0.610733
0.60954
159
35.91824
27.128616
104
false
false
0
0
0
0
0
0
0.654088
false
false
6
e355a9aec9efa869e285e8982aa586a7e7ef0bc4
20,048,907,376,233
562cef37d5c1c40d0a1ad68e21ca685147fda2e7
/AlugaGames.Core/src/alugagames/core/jogos/Categoria.java
c2ce0a7763631152ed02c6e4b91cf8e49d6cdadc
[]
no_license
wllm-git/alugagames
https://github.com/wllm-git/alugagames
ba3065b2e87c6076bbda25ef4ad2c1ecc22162fd
56c8106bac8ee6f4676e00b20dcb892b01502054
refs/heads/master
2021-01-21T19:12:21.302000
2016-12-01T21:11:09
2016-12-01T21:11:09
68,386,945
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package alugagames.core.jogos; public enum Categoria { Aventura, Acao, Esporte, Corrida, Arcade, Estrategia, Guerra }
UTF-8
Java
126
java
Categoria.java
Java
[]
null
[]
package alugagames.core.jogos; public enum Categoria { Aventura, Acao, Esporte, Corrida, Arcade, Estrategia, Guerra }
126
0.738095
0.738095
11
10.454545
8.435462
30
false
false
0
0
0
0
0
0
1.272727
false
false
6
c63e51c24066d366e50e0c03428a9af7924516a6
31,344,671,372,977
36556e520378ed4a2484271955fe94f5b69d9860
/src/main/java/com/estebanposada/service/IRolService.java
a51eda2631a50c86817db2ce5be23850d94a8af7
[]
no_license
EstebanPosada/MiniBlog_EstebanPosada
https://github.com/EstebanPosada/MiniBlog_EstebanPosada
1b19c1dfe16ff770b4cea2720cf3c5fb1650a636
dd46a12e283bf1012789b5f38e86390b80e8bfe8
refs/heads/master
2020-03-28T00:46:21.620000
2018-09-25T04:07:31
2018-09-25T04:07:31
147,448,370
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.estebanposada.service; import java.util.List; import com.estebanposada.model.Rol; import com.estebanposada.model.Usuario; import com.estebanposada.model.UsuarioRol; public interface IRolService extends IService<Rol> { Integer asignar(Usuario usuario, List<Rol> roles); List<UsuarioRol> listarRolesPorUsuario(Usuario usuario); }
UTF-8
Java
362
java
IRolService.java
Java
[]
null
[]
package com.estebanposada.service; import java.util.List; import com.estebanposada.model.Rol; import com.estebanposada.model.Usuario; import com.estebanposada.model.UsuarioRol; public interface IRolService extends IService<Rol> { Integer asignar(Usuario usuario, List<Rol> roles); List<UsuarioRol> listarRolesPorUsuario(Usuario usuario); }
362
0.779006
0.779006
14
23.857143
21.937759
57
false
false
0
0
0
0
0
0
0.785714
false
false
6
b3db95f590c1e173c9c7ff13f9fc43cf1f299630
21,311,627,733,631
3fcdca1ea49c02188eb1d9e253f47cbb49380833
/fin_dev/fin.common/src/main/java/com/yqjr/fin/common/base/starter/exception/RepetitionException.java
64718b8d4188f27059de4edba5794c723e4633f6
[]
no_license
jsdelivrbot/yqjr
https://github.com/jsdelivrbot/yqjr
f13f50dc765b1c7aa7ad513ee455c9380ab3d7c6
08c7182c3d4dcc303f512b55b4405266dd3ad66c
refs/heads/master
2020-04-10T13:50:37.840000
2018-12-09T11:08:44
2018-12-09T11:08:44
161,060,607
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yqjr.fin.common.base.starter.exception; import com.yqjr.fin.common.base.starter.enums.ServiceResponseEnum; public class RepetitionException extends CommonBizzException { private String code; public RepetitionException(ServiceResponseEnum serviceResponseEnum) { super(serviceResponseEnum); this.code = serviceResponseEnum.getCode(); } public String getCode() { return code; } public void setCode(String code) { this.code = code; } }
UTF-8
Java
510
java
RepetitionException.java
Java
[]
null
[]
package com.yqjr.fin.common.base.starter.exception; import com.yqjr.fin.common.base.starter.enums.ServiceResponseEnum; public class RepetitionException extends CommonBizzException { private String code; public RepetitionException(ServiceResponseEnum serviceResponseEnum) { super(serviceResponseEnum); this.code = serviceResponseEnum.getCode(); } public String getCode() { return code; } public void setCode(String code) { this.code = code; } }
510
0.709804
0.709804
21
23.285715
24.329372
73
false
false
0
0
0
0
0
0
0.333333
false
false
6
4ab9e6565452368007fddc900c5f3a09a253987c
2,250,562,883,295
b22ce3f486a013947721c0f7936f50c6a5976a16
/ftsp_android_client/tags/ftsp_android_client_v1.3.0.52797/common_library/src/main/java/com/kungeek/android/ftsp/common/view/activity/ImMainActivity.java
af02a7dce24303aa055f04cfd61066e8fabb6b4a
[]
no_license
NeXtyin/kgcode
https://github.com/NeXtyin/kgcode
8073c3e8465b0fce91a7fad77f82cefc58c0dc7f
000f4caf87a038bc57ab01d75516b8b4355ef0d3
refs/heads/master
2018-09-10T01:52:27.219000
2018-06-05T07:02:11
2018-06-05T07:02:11
136,038,325
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright(c) Beijing Kungeek Science & Technology Ltd. */ package com.kungeek.android.ftsp.common.view.activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.res.Resources; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.FragmentTransaction; import android.telecom.ConnectionService; import android.view.KeyEvent; import android.view.View; import com.kungeek.android.ftsp.common.R; import com.kungeek.android.ftsp.common.base.UIHelper; import com.kungeek.android.ftsp.common.bean.ImNotificationBean; import com.kungeek.android.ftsp.common.service.ImNotificationService; import com.kungeek.android.ftsp.common.service.InfraUserService; import com.kungeek.android.ftsp.common.view.fragment.ImAgentContactFragment; import com.kungeek.android.ftsp.common.view.fragment.ImConversationFragment; import com.kungeek.android.ftsp.common.view.fragment.ImCustomerContactFragment; import com.kungeek.android.ftsp.utilslib.CheckCurrentActivityUtil; import com.kungeek.android.ftsp.utilslib.ImUtil; import com.kungeek.android.ftsp.utilslib.WidgetUtil; import com.kungeek.android.ftsp.utilslib.application.SysApplication; import com.kungeek.android.ftsp.utilslib.base.BaseFragmentActivity; import com.kungeek.android.ftsp.utilslib.base.FtspLog; import com.kungeek.android.ftsp.utilslib.constant.im.ImConstant; import com.kungeek.android.ftsp.utilslib.http.base.StringUtils; import com.kungeek.android.ftsp.utilslib.service.im.FtspImContactService; import com.kungeek.android.ftsp.utilslib.service.im.ImConnectionService; import org.jivesoftware.smack.tcp.XMPPTCPConnection; /** * <pre> * 沟通中心主页。 * </pre> * * @author 周家鑫 zhoujiaxin@kungeek.com * @version 1.00.00 * <pre> * 修改记录 * 修改后版本: 修改人: 修改日期: 修改内容: * </pre> */ public class ImMainActivity extends BaseFragmentActivity implements View.OnClickListener { /** * 日志。 */ private static final FtspLog log = FtspLog.getFtspLogInstance(ImMainActivity.class); /** * 消息选项卡索引。 */ private final static int INDEX_TAB_MESSAGE = 0; /** * 联系人选项卡索引。 */ private final static int INDEX_TAB_CONTACT = 1; /** * 群聊按钮索引。 */ private final static int INDEX_BUTTON_GROUPCHAT = 2; /** * 消息Fragment。 */ private ImConversationFragment conversationFragment; /** * 通讯录Fragment。 */ private ImAgentContactFragment agentContactFragment; /** * 通讯录Fragment。 */ private ImCustomerContactFragment customerContactFragment; private MessageNoticeBroadcastReceiver messageNoticeBroadcastReceiver; /** * 上级页面名 TODO 待删 */ private String fromActivityName; @Override public void onCreate(Bundle paramBundle) { super.onCreate(paramBundle); if (null != paramBundle && paramBundle.getBoolean("needLogin")) { log.info("+++++++++++++++++++++++++++RE LOGIN++++++++++++++++++++++++++"); setContentView(R.layout.layout_frame_index); } registerMessageNoticeBroadcastReceiver(); //final XMPPTCPConnection xmpptcpConnection = ImConnectionService.getInstance().getXMPPTCPConnection(); //ImUtil.queryRecentConversationList(xmpptcpConnection); } @Override public void loadViewLayout() { // 设置标题左侧区域是否可见 setHeadLeftVisibility(View.GONE); // 设置标题右侧区域是否可见 setHeadRightVisibility(View.GONE); // 设置统一title是否可见 setTitleVisibility(View.GONE); // 标题区域消息、通讯录是否可见 setHeadmessage_contractVisibility(View.VISIBLE); // 设置标题右侧区域group_chat是否可见 setHeadRight_group_chartVisibility(View.GONE); // 设置页面背景颜色 Resources res = getResources(); Drawable drawable = res.getDrawable(R.color.danju_lib_jiesuanleixing_bg); this.getWindow().setBackgroundDrawable(drawable); setContentView(R.layout.layout_frame_index); } @Override public void initViews() { Bundle bundle = getIntent().getExtras(); fromActivityName = bundle.getString("activity_name"); // 默认选中的tab if (ImAgentContactFragment.class.getSimpleName().equals(fromActivityName)) { // 联系人Tab switchTab(INDEX_TAB_CONTACT); } else { // 消息TAB switchTab(INDEX_TAB_MESSAGE); } // 初始化样式。 this.initTabStyle(); // if (!SysApplication.getInstance().isEnterpriseUser()) { // FtspZjZjxxBean zjZjxx = FtspZjZjxxDAO.getInstance().findFtspZjZjxx(); // if ("500000".equals(zjZjxx.getAreaCode()) || "440000".equals(zjZjxx.getAreaCode())) { // imagebutton04.setVisibility(View.VISIBLE); // } else { // imagebutton04.setVisibility(View.GONE); // } // } if (SysApplication.getInstance().isEnterpriseUser()) { // 查询用户所属中介机构。 InfraUserService.getInstance().findbyuseridAPI(); } } @Override public void setListener() { // 顶部tab点击 message_layout.setOnClickListener(this); contactLayout.setOnClickListener(this); // 底部Tab imagebutton01.setOnClickListener(this); imagebutton03.setOnClickListener(this); imagebutton04.setOnClickListener(this); //群聊group_chat head_right_group_chat.setOnClickListener(this); if (SysApplication.getInstance().isEnterpriseUser()) { headLeftBtn.setOnClickListener(this); } } @Override public void onClick(View v) { Bundle bundle = new Bundle(); if (v == message_layout) { // 消息 switchTab(INDEX_TAB_MESSAGE); } else if (v == contactLayout) { // 通讯录 switchTab(INDEX_TAB_CONTACT); } else if (v == imagebutton01) {// 单据选项卡 bundle.putInt("currPosi", 0); CheckCurrentActivityUtil.startComponentNameBundle(ImMainActivity.this, (String) SysApplication.objectBeanMap.get("APPLICATION_ID"), ((SysApplication) getApplicationContext()).getMainacyivity_to(), bundle); } else if (v == imagebutton03) {// “我”选项卡 bundle.putInt("currPosi", 2); CheckCurrentActivityUtil.startComponentNameBundle(ImMainActivity.this, (String) SysApplication.objectBeanMap.get("APPLICATION_ID"), ((SysApplication) getApplicationContext()).getMainacyivity_to(), bundle); } else if (v == imagebutton04) {// “进项发票”选项卡 bundle.putInt("currPosi", 3); CheckCurrentActivityUtil.startComponentNameBundle(ImMainActivity.this, (String) SysApplication.objectBeanMap.get("APPLICATION_ID"), ((SysApplication) getApplicationContext()).getMainacyivity_to(), bundle); } else if (v == head_right_group_chat) { // 群聊 switchTab(INDEX_BUTTON_GROUPCHAT); } else if (SysApplication.getInstance().isEnterpriseUser() && v == headLeftBtn) { Intent in = new Intent(); Bundle args = new Bundle(); args.putString("fromActivityName", "FuWuFragment"); in.putExtras(args); this.setResult(RESULT_FIRST_USER, in); finish(); } } /** * 初始化view视图样式。 */ private void initTabStyle() { // 将Tab背景图片还原 setTabBackground(bottom_tab01_image, R.drawable.tab01_normal); setTabBackground(bottom_tab02_image, R.drawable.tab02_pressed); setTabBackground(bottom_tab03_image, R.drawable.tab03_normal); // 将Tab文字颜色还原 setTabText(bottom_tab01_text, Color.parseColor("#a7a7a7")); if (SysApplication.getInstance().isEnterpriseUser()) { bottom_tab01_text.setText("财税状况"); bottom_tab02_text.setText("服务"); } setTabText(bottom_tab02_text, Color.parseColor("#ff7a7a")); setTabText(bottom_tab03_text, Color.parseColor("#a7a7a7")); if (SysApplication.getInstance().isEnterpriseUser()) { setbottomTabVisibility(View.GONE); headLeftBtn.setVisibility(View.VISIBLE); } } /** * 根据传入的index参数来设置选中的选项卡(消息选项卡、通讯录选项卡)。 * * @param index 每个tab页对应的下标。0消息,1通讯录。 */ private void switchTab(int index) { if (index == INDEX_BUTTON_GROUPCHAT) { // 创建群聊 if (SysApplication.getInstance().isEnterpriseUser()) { UIHelper.showCustomerContactSelectedActivity(this); } else { UIHelper.showAgentContactSelectedActivity(this); } return; } // 每次选中之前先清楚掉上次的选中状态 resetTabStatus(); // 开启一个Fragment事务 FragmentTransaction transaction = this.getSupportFragmentManager().beginTransaction(); hideFragments(transaction); switch (index) { case INDEX_TAB_MESSAGE: // 消息 if (conversationFragment == null) { conversationFragment = new ImConversationFragment(); transaction.add(R.id.content, conversationFragment); } message_layout.setEnabled(false); conversationFragment.updatePageHandler(); head_right_group_chat.setVisibility(View.GONE); transaction.show(conversationFragment); break; case INDEX_TAB_CONTACT: // 通讯录 if (SysApplication.getInstance().isEnterpriseUser()) { if (customerContactFragment == null) { customerContactFragment = new ImCustomerContactFragment(); transaction.add(R.id.content, customerContactFragment); } customerContactFragment.resetSearch(); contactLayout.setEnabled(false); transaction.show(customerContactFragment); } else { if (agentContactFragment == null) { agentContactFragment = new ImAgentContactFragment(); transaction.add(R.id.content, agentContactFragment); } agentContactFragment.resetSearch(); contactLayout.setEnabled(false); transaction.show(agentContactFragment); } break; default: break; } // 提交事务。 transaction.commit(); } /** * 清除掉所有的选中状态。 */ private void resetTabStatus() { // 还原tab点击状态。 message_layout.setEnabled(true); contactLayout.setEnabled(true); head_right_group_chat.setVisibility(View.VISIBLE); // 背景还原。 head_right_group_chat.setBackgroundResource(R.drawable.groupchat_blue_icon); WidgetUtil.hideInputPad(this); } /** * 将所有的Fragment都置为隐藏状态。 * * @param transaction 用于对Fragment执行操作的事务 */ private void hideFragments(FragmentTransaction transaction) { if (conversationFragment != null) { transaction.hide(conversationFragment); } if (agentContactFragment != null) { transaction.hide(agentContactFragment); } if (customerContactFragment != null) { transaction.hide(customerContactFragment); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // 返回显示标签页。 if (resultCode == RESULT_CANCELED) { int intExtra = ImConstant.FUNC_MESSAGE; if (data != null) { intExtra = data.getIntExtra(ImConstant.VAR_FUNC, ImConstant.FUNC_MESSAGE); } if (intExtra == ImConstant.FUNC_MESSAGE) { switchTab(INDEX_TAB_MESSAGE); } else { switchTab(INDEX_TAB_CONTACT); } } } @Override protected void onResume() { super.onResume(); //switchTab(INDEX_TAB_MESSAGE); updateMessageNotice(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { if (!SysApplication.getInstance().isEnterpriseUser()) { Bundle bundle = new Bundle(); bundle.putInt("currPosi", 0); CheckCurrentActivityUtil.startComponentNameBundle(ImMainActivity.this, (String) SysApplication.objectBeanMap.get("APPLICATION_ID"), ((SysApplication) getApplicationContext()).getMainacyivity_to(), bundle); return true; } } return super.onKeyDown(keyCode, event); } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(messageNoticeBroadcastReceiver); } private void registerMessageNoticeBroadcastReceiver() { messageNoticeBroadcastReceiver = new MessageNoticeBroadcastReceiver(); IntentFilter filter=new IntentFilter(); filter.addAction(ImConstant.ACTION_MessageNoticeBroadcastReceiver); registerReceiver(messageNoticeBroadcastReceiver, filter); } /** * 消息提醒。 */ public void updateMessageNotice() { final int count = ImConnectionService.getInstance().getUnreadMessageCount(); updateMessageNotice(count); // 更新系统消息总数。 ImNotificationService.getInstance().countmsgbyqyzidAPI(new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); int notificationCount = 0; notificationCount = (int) msg.obj; updateMessageNotice(count + notificationCount); } }, ImNotificationBean.STATUS_UNREAD); } public void updateMessageNotice(int count) { if (count == 0) { mRedPoint.setText(""); mRedPoint.setVisibility(View.GONE); } else { mRedPoint.setText(count + ""); mRedPoint.setVisibility(View.VISIBLE); } } class MessageNoticeBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { updateMessageNotice(); if(conversationFragment != null) { conversationFragment.loadSapNotificationUnreadCount(); conversationFragment.loadLastSapNotification(); } } } }
UTF-8
Java
15,711
java
ImMainActivity.java
Java
[ { "context": "\n\n/**\n * <pre>\n * 沟通中心主页。\n * </pre>\n *\n * @author 周家鑫 zhoujiaxin@kungeek.com\n * @version 1.00.00\n * <p", "end": 1878, "score": 0.9998669624328613, "start": 1875, "tag": "NAME", "value": "周家鑫" }, { "context": "*\n * <pre>\n * 沟通中心主页。\n * </pre>\n *\n * @author 周家鑫 zhoujiaxin@kungeek.com\n * @version 1.00.00\n * <pre>\n * 修改记录\n * 修改后版本: ", "end": 1902, "score": 0.9999241232872009, "start": 1880, "tag": "EMAIL", "value": "zhoujiaxin@kungeek.com" } ]
null
[]
/* * Copyright(c) Beijing Kungeek Science & Technology Ltd. */ package com.kungeek.android.ftsp.common.view.activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.res.Resources; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.FragmentTransaction; import android.telecom.ConnectionService; import android.view.KeyEvent; import android.view.View; import com.kungeek.android.ftsp.common.R; import com.kungeek.android.ftsp.common.base.UIHelper; import com.kungeek.android.ftsp.common.bean.ImNotificationBean; import com.kungeek.android.ftsp.common.service.ImNotificationService; import com.kungeek.android.ftsp.common.service.InfraUserService; import com.kungeek.android.ftsp.common.view.fragment.ImAgentContactFragment; import com.kungeek.android.ftsp.common.view.fragment.ImConversationFragment; import com.kungeek.android.ftsp.common.view.fragment.ImCustomerContactFragment; import com.kungeek.android.ftsp.utilslib.CheckCurrentActivityUtil; import com.kungeek.android.ftsp.utilslib.ImUtil; import com.kungeek.android.ftsp.utilslib.WidgetUtil; import com.kungeek.android.ftsp.utilslib.application.SysApplication; import com.kungeek.android.ftsp.utilslib.base.BaseFragmentActivity; import com.kungeek.android.ftsp.utilslib.base.FtspLog; import com.kungeek.android.ftsp.utilslib.constant.im.ImConstant; import com.kungeek.android.ftsp.utilslib.http.base.StringUtils; import com.kungeek.android.ftsp.utilslib.service.im.FtspImContactService; import com.kungeek.android.ftsp.utilslib.service.im.ImConnectionService; import org.jivesoftware.smack.tcp.XMPPTCPConnection; /** * <pre> * 沟通中心主页。 * </pre> * * @author 周家鑫 <EMAIL> * @version 1.00.00 * <pre> * 修改记录 * 修改后版本: 修改人: 修改日期: 修改内容: * </pre> */ public class ImMainActivity extends BaseFragmentActivity implements View.OnClickListener { /** * 日志。 */ private static final FtspLog log = FtspLog.getFtspLogInstance(ImMainActivity.class); /** * 消息选项卡索引。 */ private final static int INDEX_TAB_MESSAGE = 0; /** * 联系人选项卡索引。 */ private final static int INDEX_TAB_CONTACT = 1; /** * 群聊按钮索引。 */ private final static int INDEX_BUTTON_GROUPCHAT = 2; /** * 消息Fragment。 */ private ImConversationFragment conversationFragment; /** * 通讯录Fragment。 */ private ImAgentContactFragment agentContactFragment; /** * 通讯录Fragment。 */ private ImCustomerContactFragment customerContactFragment; private MessageNoticeBroadcastReceiver messageNoticeBroadcastReceiver; /** * 上级页面名 TODO 待删 */ private String fromActivityName; @Override public void onCreate(Bundle paramBundle) { super.onCreate(paramBundle); if (null != paramBundle && paramBundle.getBoolean("needLogin")) { log.info("+++++++++++++++++++++++++++RE LOGIN++++++++++++++++++++++++++"); setContentView(R.layout.layout_frame_index); } registerMessageNoticeBroadcastReceiver(); //final XMPPTCPConnection xmpptcpConnection = ImConnectionService.getInstance().getXMPPTCPConnection(); //ImUtil.queryRecentConversationList(xmpptcpConnection); } @Override public void loadViewLayout() { // 设置标题左侧区域是否可见 setHeadLeftVisibility(View.GONE); // 设置标题右侧区域是否可见 setHeadRightVisibility(View.GONE); // 设置统一title是否可见 setTitleVisibility(View.GONE); // 标题区域消息、通讯录是否可见 setHeadmessage_contractVisibility(View.VISIBLE); // 设置标题右侧区域group_chat是否可见 setHeadRight_group_chartVisibility(View.GONE); // 设置页面背景颜色 Resources res = getResources(); Drawable drawable = res.getDrawable(R.color.danju_lib_jiesuanleixing_bg); this.getWindow().setBackgroundDrawable(drawable); setContentView(R.layout.layout_frame_index); } @Override public void initViews() { Bundle bundle = getIntent().getExtras(); fromActivityName = bundle.getString("activity_name"); // 默认选中的tab if (ImAgentContactFragment.class.getSimpleName().equals(fromActivityName)) { // 联系人Tab switchTab(INDEX_TAB_CONTACT); } else { // 消息TAB switchTab(INDEX_TAB_MESSAGE); } // 初始化样式。 this.initTabStyle(); // if (!SysApplication.getInstance().isEnterpriseUser()) { // FtspZjZjxxBean zjZjxx = FtspZjZjxxDAO.getInstance().findFtspZjZjxx(); // if ("500000".equals(zjZjxx.getAreaCode()) || "440000".equals(zjZjxx.getAreaCode())) { // imagebutton04.setVisibility(View.VISIBLE); // } else { // imagebutton04.setVisibility(View.GONE); // } // } if (SysApplication.getInstance().isEnterpriseUser()) { // 查询用户所属中介机构。 InfraUserService.getInstance().findbyuseridAPI(); } } @Override public void setListener() { // 顶部tab点击 message_layout.setOnClickListener(this); contactLayout.setOnClickListener(this); // 底部Tab imagebutton01.setOnClickListener(this); imagebutton03.setOnClickListener(this); imagebutton04.setOnClickListener(this); //群聊group_chat head_right_group_chat.setOnClickListener(this); if (SysApplication.getInstance().isEnterpriseUser()) { headLeftBtn.setOnClickListener(this); } } @Override public void onClick(View v) { Bundle bundle = new Bundle(); if (v == message_layout) { // 消息 switchTab(INDEX_TAB_MESSAGE); } else if (v == contactLayout) { // 通讯录 switchTab(INDEX_TAB_CONTACT); } else if (v == imagebutton01) {// 单据选项卡 bundle.putInt("currPosi", 0); CheckCurrentActivityUtil.startComponentNameBundle(ImMainActivity.this, (String) SysApplication.objectBeanMap.get("APPLICATION_ID"), ((SysApplication) getApplicationContext()).getMainacyivity_to(), bundle); } else if (v == imagebutton03) {// “我”选项卡 bundle.putInt("currPosi", 2); CheckCurrentActivityUtil.startComponentNameBundle(ImMainActivity.this, (String) SysApplication.objectBeanMap.get("APPLICATION_ID"), ((SysApplication) getApplicationContext()).getMainacyivity_to(), bundle); } else if (v == imagebutton04) {// “进项发票”选项卡 bundle.putInt("currPosi", 3); CheckCurrentActivityUtil.startComponentNameBundle(ImMainActivity.this, (String) SysApplication.objectBeanMap.get("APPLICATION_ID"), ((SysApplication) getApplicationContext()).getMainacyivity_to(), bundle); } else if (v == head_right_group_chat) { // 群聊 switchTab(INDEX_BUTTON_GROUPCHAT); } else if (SysApplication.getInstance().isEnterpriseUser() && v == headLeftBtn) { Intent in = new Intent(); Bundle args = new Bundle(); args.putString("fromActivityName", "FuWuFragment"); in.putExtras(args); this.setResult(RESULT_FIRST_USER, in); finish(); } } /** * 初始化view视图样式。 */ private void initTabStyle() { // 将Tab背景图片还原 setTabBackground(bottom_tab01_image, R.drawable.tab01_normal); setTabBackground(bottom_tab02_image, R.drawable.tab02_pressed); setTabBackground(bottom_tab03_image, R.drawable.tab03_normal); // 将Tab文字颜色还原 setTabText(bottom_tab01_text, Color.parseColor("#a7a7a7")); if (SysApplication.getInstance().isEnterpriseUser()) { bottom_tab01_text.setText("财税状况"); bottom_tab02_text.setText("服务"); } setTabText(bottom_tab02_text, Color.parseColor("#ff7a7a")); setTabText(bottom_tab03_text, Color.parseColor("#a7a7a7")); if (SysApplication.getInstance().isEnterpriseUser()) { setbottomTabVisibility(View.GONE); headLeftBtn.setVisibility(View.VISIBLE); } } /** * 根据传入的index参数来设置选中的选项卡(消息选项卡、通讯录选项卡)。 * * @param index 每个tab页对应的下标。0消息,1通讯录。 */ private void switchTab(int index) { if (index == INDEX_BUTTON_GROUPCHAT) { // 创建群聊 if (SysApplication.getInstance().isEnterpriseUser()) { UIHelper.showCustomerContactSelectedActivity(this); } else { UIHelper.showAgentContactSelectedActivity(this); } return; } // 每次选中之前先清楚掉上次的选中状态 resetTabStatus(); // 开启一个Fragment事务 FragmentTransaction transaction = this.getSupportFragmentManager().beginTransaction(); hideFragments(transaction); switch (index) { case INDEX_TAB_MESSAGE: // 消息 if (conversationFragment == null) { conversationFragment = new ImConversationFragment(); transaction.add(R.id.content, conversationFragment); } message_layout.setEnabled(false); conversationFragment.updatePageHandler(); head_right_group_chat.setVisibility(View.GONE); transaction.show(conversationFragment); break; case INDEX_TAB_CONTACT: // 通讯录 if (SysApplication.getInstance().isEnterpriseUser()) { if (customerContactFragment == null) { customerContactFragment = new ImCustomerContactFragment(); transaction.add(R.id.content, customerContactFragment); } customerContactFragment.resetSearch(); contactLayout.setEnabled(false); transaction.show(customerContactFragment); } else { if (agentContactFragment == null) { agentContactFragment = new ImAgentContactFragment(); transaction.add(R.id.content, agentContactFragment); } agentContactFragment.resetSearch(); contactLayout.setEnabled(false); transaction.show(agentContactFragment); } break; default: break; } // 提交事务。 transaction.commit(); } /** * 清除掉所有的选中状态。 */ private void resetTabStatus() { // 还原tab点击状态。 message_layout.setEnabled(true); contactLayout.setEnabled(true); head_right_group_chat.setVisibility(View.VISIBLE); // 背景还原。 head_right_group_chat.setBackgroundResource(R.drawable.groupchat_blue_icon); WidgetUtil.hideInputPad(this); } /** * 将所有的Fragment都置为隐藏状态。 * * @param transaction 用于对Fragment执行操作的事务 */ private void hideFragments(FragmentTransaction transaction) { if (conversationFragment != null) { transaction.hide(conversationFragment); } if (agentContactFragment != null) { transaction.hide(agentContactFragment); } if (customerContactFragment != null) { transaction.hide(customerContactFragment); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // 返回显示标签页。 if (resultCode == RESULT_CANCELED) { int intExtra = ImConstant.FUNC_MESSAGE; if (data != null) { intExtra = data.getIntExtra(ImConstant.VAR_FUNC, ImConstant.FUNC_MESSAGE); } if (intExtra == ImConstant.FUNC_MESSAGE) { switchTab(INDEX_TAB_MESSAGE); } else { switchTab(INDEX_TAB_CONTACT); } } } @Override protected void onResume() { super.onResume(); //switchTab(INDEX_TAB_MESSAGE); updateMessageNotice(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { if (!SysApplication.getInstance().isEnterpriseUser()) { Bundle bundle = new Bundle(); bundle.putInt("currPosi", 0); CheckCurrentActivityUtil.startComponentNameBundle(ImMainActivity.this, (String) SysApplication.objectBeanMap.get("APPLICATION_ID"), ((SysApplication) getApplicationContext()).getMainacyivity_to(), bundle); return true; } } return super.onKeyDown(keyCode, event); } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(messageNoticeBroadcastReceiver); } private void registerMessageNoticeBroadcastReceiver() { messageNoticeBroadcastReceiver = new MessageNoticeBroadcastReceiver(); IntentFilter filter=new IntentFilter(); filter.addAction(ImConstant.ACTION_MessageNoticeBroadcastReceiver); registerReceiver(messageNoticeBroadcastReceiver, filter); } /** * 消息提醒。 */ public void updateMessageNotice() { final int count = ImConnectionService.getInstance().getUnreadMessageCount(); updateMessageNotice(count); // 更新系统消息总数。 ImNotificationService.getInstance().countmsgbyqyzidAPI(new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); int notificationCount = 0; notificationCount = (int) msg.obj; updateMessageNotice(count + notificationCount); } }, ImNotificationBean.STATUS_UNREAD); } public void updateMessageNotice(int count) { if (count == 0) { mRedPoint.setText(""); mRedPoint.setVisibility(View.GONE); } else { mRedPoint.setText(count + ""); mRedPoint.setVisibility(View.VISIBLE); } } class MessageNoticeBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { updateMessageNotice(); if(conversationFragment != null) { conversationFragment.loadSapNotificationUnreadCount(); conversationFragment.loadLastSapNotification(); } } } }
15,696
0.616193
0.611174
421
34.501186
25.852369
111
false
false
0
0
0
0
0
0
0.489311
false
false
6
6d771737fb4301775355a3314dd8e7ab9f83914f
18,305,150,683,995
5ef33b91a220c63899d73c05580f0e7fd549a18e
/HouseShelter/src/com/hiibox/houseshelter/MyApplication.java
0edb48c9ab069e4d3323682698ff8182cf9aa585
[]
no_license
magicbear/CompanyProject
https://github.com/magicbear/CompanyProject
c9a54b60294f6b0b8f829034175bcb8317055e15
9ad17f7aebbf57787f84219293f4aa6e26f4ccec
refs/heads/master
2020-12-30T16:40:26.264000
2014-03-13T15:08:05
2014-03-13T15:08:05
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hiibox.houseshelter; import java.io.IOException; import android.app.Application; import com.hiibox.houseshelter.net.TCPFileClient; import com.hiibox.houseshelter.net.TCPMainClient; import com.hiibox.houseshelter.net.TCPManager; import com.hiibox.houseshelter.net.TCPMsgClient; import com.hiibox.houseshelter.net.TCPServiceClientV2.ClientListener; public class MyApplication extends Application { public static boolean showedAds = false; public static String phone = null; public static String password = null; public static int userLevel = -1; public static TCPManager tcpManager = null; public static TCPMainClient mainClient = null; public static TCPFileClient fileClient = null; public static TCPMsgClient msgClient = null; public static ClientListener listener = null; public static String deviceCode = null; public static boolean isFirstTimeEntry = true; @Override public void onCreate() { super.onCreate(); tcpManager = new TCPManager(); listener = new ClientListener() { @Override public void onClientStop() { System.out.println("BaseApplication Client Stop................"); } @Override public void onClientStart() { System.out.println("BaseApplication Client start................"); } @Override public void onClientClose() { System.out.println("BaseApplication Client Close................"); } @Override public void onClientException(IOException ex) { ex.printStackTrace(); System.out.println("BaseApplication onClientException................"+ex.toString()); } @Override public void onLoginFail() { System.out.println("BaseApplication Login Fail................"); } }; } public static void initTcpManager() { if (null != tcpManager) { return; } tcpManager = new TCPManager(); } }
UTF-8
Java
2,648
java
MyApplication.java
Java
[ { "context": " \n public static String password = null; \n public static int userLevel = -1; ", "end": 627, "score": 0.9741740822792053, "start": 623, "tag": "PASSWORD", "value": "null" } ]
null
[]
package com.hiibox.houseshelter; import java.io.IOException; import android.app.Application; import com.hiibox.houseshelter.net.TCPFileClient; import com.hiibox.houseshelter.net.TCPMainClient; import com.hiibox.houseshelter.net.TCPManager; import com.hiibox.houseshelter.net.TCPMsgClient; import com.hiibox.houseshelter.net.TCPServiceClientV2.ClientListener; public class MyApplication extends Application { public static boolean showedAds = false; public static String phone = null; public static String password = <PASSWORD>; public static int userLevel = -1; public static TCPManager tcpManager = null; public static TCPMainClient mainClient = null; public static TCPFileClient fileClient = null; public static TCPMsgClient msgClient = null; public static ClientListener listener = null; public static String deviceCode = null; public static boolean isFirstTimeEntry = true; @Override public void onCreate() { super.onCreate(); tcpManager = new TCPManager(); listener = new ClientListener() { @Override public void onClientStop() { System.out.println("BaseApplication Client Stop................"); } @Override public void onClientStart() { System.out.println("BaseApplication Client start................"); } @Override public void onClientClose() { System.out.println("BaseApplication Client Close................"); } @Override public void onClientException(IOException ex) { ex.printStackTrace(); System.out.println("BaseApplication onClientException................"+ex.toString()); } @Override public void onLoginFail() { System.out.println("BaseApplication Login Fail................"); } }; } public static void initTcpManager() { if (null != tcpManager) { return; } tcpManager = new TCPManager(); } }
2,654
0.489426
0.488671
75
34.306667
26.961193
105
false
false
0
0
0
0
0
0
0.4
false
false
6
814a42be0d09634b447fcaa6f289d6363cb00b85
18,064,632,449,646
1073ba84fce40e2502427445b3cc22b9e5c975a4
/src/main/java/com/gloomy/impl/FoodDAOImpl.java
6897c672cece429c2334bae0302170fd36a90415
[]
no_license
Gloomy1207/FastFoodWebservice
https://github.com/Gloomy1207/FastFoodWebservice
67b303bf26ddffe6be6be7acaa3668367eac4e64
10f38f6e2ebf4899686a0bb7a4ab4758d8ee7079
refs/heads/develop
2020-12-01T02:57:12.878000
2017-05-21T01:28:46
2017-05-21T01:28:46
85,093,252
0
0
null
false
2017-04-28T14:53:10
2017-03-15T16:02:12
2017-03-18T16:30:09
2017-04-28T14:53:09
24,731
0
0
0
Java
null
null
package com.gloomy.impl; import com.gloomy.beans.Food; import com.gloomy.beans.LatLng; import com.gloomy.dao.FoodDAO; import com.gloomy.utils.GeoIPUtil; import com.sun.istack.internal.Nullable; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.List; import java.util.Set; /** * Copyright © 2017 Gloomy * Created by Gloomy on 07/04/2017. */ @Service public class FoodDAOImpl { private FoodDAO mFoodDAO; @Autowired public void setFoodDAO(FoodDAO mFoodDAO) { this.mFoodDAO = mFoodDAO; } private List<Food> getNearFood(@Nullable LatLng latLng) { if (latLng == null) { return mFoodDAO.findAll(); } List<Food> foods = new ArrayList<>(); for (Food food : mFoodDAO.findAll()) { food.getPlaceFoods().clear(); food.getPlaceFoods().addAll(food.getNearPlace(latLng)); } return foods; } public Page<Food> findAllPaginate(Pageable pageable) { return mFoodDAO.findAll(pageable); } public Page<Food> findNearFood(Double lat, Double lng, HttpServletRequest request, Pageable pageable) { Page<Food> foods; LatLng latLng = GeoIPUtil.createLatLngFromIp(lat, lng, request); List<Food> nearFoods = getNearFood(latLng); int start = pageable.getOffset(); int end = (start + pageable.getPageSize()) > nearFoods.size() ? nearFoods.size() : (start + pageable.getPageSize()); foods = new PageImpl<>(nearFoods.subList(start, end), pageable, nearFoods.size()); return foods; } public Set<Food> searchFood(String keyword) { return mFoodDAO.search(keyword); } }
UTF-8
Java
1,948
java
FoodDAOImpl.java
Java
[ { "context": "Set;\n\n/**\n * Copyright © 2017 Gloomy\n * Created by Gloomy on 07/04/2017.\n */\n@Service\npublic class Foo", "end": 615, "score": 0.6209304332733154, "start": 614, "tag": "NAME", "value": "G" }, { "context": "t;\n\n/**\n * Copyright © 2017 Gloomy\n * Created by Gloomy on 07/04/2017.\n */\n@Service\npublic class FoodDAOI", "end": 620, "score": 0.593264102935791, "start": 615, "tag": "USERNAME", "value": "loomy" } ]
null
[]
package com.gloomy.impl; import com.gloomy.beans.Food; import com.gloomy.beans.LatLng; import com.gloomy.dao.FoodDAO; import com.gloomy.utils.GeoIPUtil; import com.sun.istack.internal.Nullable; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.List; import java.util.Set; /** * Copyright © 2017 Gloomy * Created by Gloomy on 07/04/2017. */ @Service public class FoodDAOImpl { private FoodDAO mFoodDAO; @Autowired public void setFoodDAO(FoodDAO mFoodDAO) { this.mFoodDAO = mFoodDAO; } private List<Food> getNearFood(@Nullable LatLng latLng) { if (latLng == null) { return mFoodDAO.findAll(); } List<Food> foods = new ArrayList<>(); for (Food food : mFoodDAO.findAll()) { food.getPlaceFoods().clear(); food.getPlaceFoods().addAll(food.getNearPlace(latLng)); } return foods; } public Page<Food> findAllPaginate(Pageable pageable) { return mFoodDAO.findAll(pageable); } public Page<Food> findNearFood(Double lat, Double lng, HttpServletRequest request, Pageable pageable) { Page<Food> foods; LatLng latLng = GeoIPUtil.createLatLngFromIp(lat, lng, request); List<Food> nearFoods = getNearFood(latLng); int start = pageable.getOffset(); int end = (start + pageable.getPageSize()) > nearFoods.size() ? nearFoods.size() : (start + pageable.getPageSize()); foods = new PageImpl<>(nearFoods.subList(start, end), pageable, nearFoods.size()); return foods; } public Set<Food> searchFood(String keyword) { return mFoodDAO.search(keyword); } }
1,948
0.687725
0.681561
61
30.918034
26.376402
124
false
false
0
0
0
0
0
0
0.639344
false
false
6
601558f58b7b1c76f90d2656efc931883f836938
8,323,646,635,234
0f30e404703b628e711037a687d912519d3b2b89
/Uva/UVA/1244/1244.java
2341e418d7167b43f8dd7b768b614c66c505f04c
[]
no_license
willsenw/mysolution
https://github.com/willsenw/mysolution
e57b05b7ba3d04bd19d77500d69d452001bf87eb
34f87eae487e7ef6a02fc810185e0ebd73712115
refs/heads/master
2019-01-01T06:32:16.573000
2018-12-08T10:30:37
2018-12-08T10:30:37
69,456,843
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.*; import java.util.*; public class Main{ public static void main(String args[]){ InputStream inputS = System.in; OutputStream outputS = System.out; InputReader in = new InputReader(inputS); PrintWriter out = new PrintWriter(outputS); P1244 x = new P1244(); int tc = in.nextInt(); while ( tc > 0 ){ tc -= 1; x.solve(in,out); } out.close(); } public static class P1244{ int n; String[] f = new String[55]; int[][] dp = new int[55][55]; String[][] dps = new String[55][55]; String Res; int max( int a, int b ){ if ( a > b ) return a; return b; } int rek( int l, int r ){ if ( l == 0 && r == n-1 ){ return 0; } if ( l == 0 || r == n-1 ) return -10000000; if ( dp[l][r] != -1 ) return dp[l][r]; int res = -10000000; String s = ""; for ( int i = l-1; i >= 0; i-- ){ for ( int j = r+1; j < n; j++ ){ if ( f[i].charAt(l) == f[r].charAt(j) ){ int temp = rek(i,j) + 1; if ( temp < 0 ) continue; String st = dps[i][j] + f[i].charAt(l); if ( temp > res ) { res = temp; s = st; } else if ( temp == res ){ s = tmin(s,st); } } } } dps[l][r] = s; dp[l][r] = res; String temp = s; for ( int k = s.length()-1; k >= 0; k-- ) temp += s.charAt(k); Res = tmin(Res,temp); return res; } String tmin( String a, String b){ int y = a.length() - b.length(); if ( y > 0 ) return a; if ( y < 0 ) return b; int x = a.compareTo(b); if ( x < 0 ) return a; return b; } public void solve(InputReader in, PrintWriter out){ n = in.nextInt(); for ( int i = 0; i < n; i++ ) f[i] = in.next(); for ( int i = 0; i < n; i++ ) for ( int j = 0; j < n; j++ ){ dp[i][j] = -1; dps[i][j] = ""; } Res = ""; Res += f[0].charAt(n-1); dps[0][n-1] = ""; for ( int i = 1; i < n-1; i++ ){ int x = rek(i,i); } for ( int i = 1; i < n-1; i++ ){ for ( int j = i+1; j < n-1; j++ ){ int x = rek(i,j); String temp = dps[i][j] + f[i].charAt(j); for ( int k = dps[i][j].length()-1; k >= 0; k-- ) temp += dps[i][j].charAt(k); Res = tmin(Res,temp); } } out.println(Res); } } public static class InputReader{ public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream){ reader = new BufferedReader(new InputStreamReader(stream),32768); tokenizer = null; } public String next(){ while ( tokenizer == null || !tokenizer.hasMoreTokens() ){ try { tokenizer = new StringTokenizer(reader.readLine()); } catch ( IOException e ){ throw new RuntimeException(e); } } String res = tokenizer.nextToken(); //System.out.println(res); return res; } public int nextInt(){ String res = next(); int res2 = Integer.parseInt(res); //System.out.println(res2); return res2; } } }
UTF-8
Java
3,351
java
1244.java
Java
[]
null
[]
import java.io.*; import java.util.*; public class Main{ public static void main(String args[]){ InputStream inputS = System.in; OutputStream outputS = System.out; InputReader in = new InputReader(inputS); PrintWriter out = new PrintWriter(outputS); P1244 x = new P1244(); int tc = in.nextInt(); while ( tc > 0 ){ tc -= 1; x.solve(in,out); } out.close(); } public static class P1244{ int n; String[] f = new String[55]; int[][] dp = new int[55][55]; String[][] dps = new String[55][55]; String Res; int max( int a, int b ){ if ( a > b ) return a; return b; } int rek( int l, int r ){ if ( l == 0 && r == n-1 ){ return 0; } if ( l == 0 || r == n-1 ) return -10000000; if ( dp[l][r] != -1 ) return dp[l][r]; int res = -10000000; String s = ""; for ( int i = l-1; i >= 0; i-- ){ for ( int j = r+1; j < n; j++ ){ if ( f[i].charAt(l) == f[r].charAt(j) ){ int temp = rek(i,j) + 1; if ( temp < 0 ) continue; String st = dps[i][j] + f[i].charAt(l); if ( temp > res ) { res = temp; s = st; } else if ( temp == res ){ s = tmin(s,st); } } } } dps[l][r] = s; dp[l][r] = res; String temp = s; for ( int k = s.length()-1; k >= 0; k-- ) temp += s.charAt(k); Res = tmin(Res,temp); return res; } String tmin( String a, String b){ int y = a.length() - b.length(); if ( y > 0 ) return a; if ( y < 0 ) return b; int x = a.compareTo(b); if ( x < 0 ) return a; return b; } public void solve(InputReader in, PrintWriter out){ n = in.nextInt(); for ( int i = 0; i < n; i++ ) f[i] = in.next(); for ( int i = 0; i < n; i++ ) for ( int j = 0; j < n; j++ ){ dp[i][j] = -1; dps[i][j] = ""; } Res = ""; Res += f[0].charAt(n-1); dps[0][n-1] = ""; for ( int i = 1; i < n-1; i++ ){ int x = rek(i,i); } for ( int i = 1; i < n-1; i++ ){ for ( int j = i+1; j < n-1; j++ ){ int x = rek(i,j); String temp = dps[i][j] + f[i].charAt(j); for ( int k = dps[i][j].length()-1; k >= 0; k-- ) temp += dps[i][j].charAt(k); Res = tmin(Res,temp); } } out.println(Res); } } public static class InputReader{ public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream){ reader = new BufferedReader(new InputStreamReader(stream),32768); tokenizer = null; } public String next(){ while ( tokenizer == null || !tokenizer.hasMoreTokens() ){ try { tokenizer = new StringTokenizer(reader.readLine()); } catch ( IOException e ){ throw new RuntimeException(e); } } String res = tokenizer.nextToken(); //System.out.println(res); return res; } public int nextInt(){ String res = next(); int res2 = Integer.parseInt(res); //System.out.println(res2); return res2; } } }
3,351
0.448224
0.424351
133
24.203007
18.238503
83
false
false
0
0
0
0
0
0
2.323308
false
false
6
af7d0e489286a02bb72afe8278d9c5aba17bed9b
17,016,660,445,654
a0cd546101594e679544d24f92ae8fcc17013142
/refactorit-core/src/main/java/net/sf/refactorit/ui/module/apidiff/ApiDiffFilterModel.java
dd6e0d4c249b0fe141d843cf01dc85eef88a3ee5
[]
no_license
svn2github/RefactorIT
https://github.com/svn2github/RefactorIT
f65198bb64f6c11e20d35ace5f9563d781b7fe5c
4b1fc1ebd06c8e192af9ccd94eb5c2d96f79f94c
refs/heads/master
2021-01-10T03:09:28.310000
2008-09-18T10:17:56
2008-09-18T10:17:56
47,540,746
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright 2001-2008 Aqris Software AS. All rights reserved. * * This program is dual-licensed under both the Common Development * and Distribution License ("CDDL") and the GNU General Public * License ("GPL"). You may elect to use one or the other of these * licenses. */ package net.sf.refactorit.ui.module.apidiff; import net.sf.refactorit.query.usage.filters.ApiDiffFilter; import net.sf.refactorit.ui.module.IdeWindowContext; import javax.swing.table.AbstractTableModel; import java.util.ArrayList; import java.util.List; public class ApiDiffFilterModel extends AbstractTableModel { public static final String[] accessStrings = {"public", "protected", "private", "package private"}; private static final String[] columns = {" ", "public", "protected", "private", "package private"}; IdeWindowContext context; List rows = new ArrayList(); public ApiDiffFilterModel(IdeWindowContext context) { this.context = context; } public int getColumnCount() { return columns.length; } public String getColumnName(int column) { return columns[column]; } public Class getColumnClass(int columnIndex) { final Object value = getValueAt(0, columnIndex); if (value == null) { return null; } return value.getClass(); } public boolean isCellEditable(int row, int col) { return (col > 0); } public int getRowCount() { return rows.size(); } public Object getValueAt(int rowIndex, int columnIndex) { if (rowIndex >= getRowCount()) { return null; } final ApiDiffFilterNode node = findNodeForRow(rowIndex); if (node == null) { return null; } switch (columnIndex) { case 0: return node.getName(); case 1: return node.getPublic(getState()); case 2: return node.getProtected(getState()); case 3: return node.getPrivate(getState()); case 4: return node.getPackagePrivate(getState()); } return null; } public void setValueAt(Object value, int rowIndex, int columnIndex) { final ApiDiffFilterNode node = findNodeForRow(rowIndex); if (node == null) { return; } switch (columnIndex) { case 0: break; case 1: node.setPublic((Boolean) value, getState()); break; case 2: node.setProtected((Boolean) value, getState()); break; case 3: node.setPrivate((Boolean) value, getState()); break; case 4: node.setPackagePrivate((Boolean) value, getState()); break; } } public void addRow(ApiDiffFilterNode node) { rows.add(node); fireTableDataChanged(); } private ApiDiffFilterNode findNodeForRow(int rowIndex) { return (ApiDiffFilterNode) rows.get(rowIndex); } private ApiDiffFilter getState() { return (ApiDiffFilter) context.getState(); } }
UTF-8
Java
3,043
java
ApiDiffFilterModel.java
Java
[]
null
[]
/* * Copyright 2001-2008 Aqris Software AS. All rights reserved. * * This program is dual-licensed under both the Common Development * and Distribution License ("CDDL") and the GNU General Public * License ("GPL"). You may elect to use one or the other of these * licenses. */ package net.sf.refactorit.ui.module.apidiff; import net.sf.refactorit.query.usage.filters.ApiDiffFilter; import net.sf.refactorit.ui.module.IdeWindowContext; import javax.swing.table.AbstractTableModel; import java.util.ArrayList; import java.util.List; public class ApiDiffFilterModel extends AbstractTableModel { public static final String[] accessStrings = {"public", "protected", "private", "package private"}; private static final String[] columns = {" ", "public", "protected", "private", "package private"}; IdeWindowContext context; List rows = new ArrayList(); public ApiDiffFilterModel(IdeWindowContext context) { this.context = context; } public int getColumnCount() { return columns.length; } public String getColumnName(int column) { return columns[column]; } public Class getColumnClass(int columnIndex) { final Object value = getValueAt(0, columnIndex); if (value == null) { return null; } return value.getClass(); } public boolean isCellEditable(int row, int col) { return (col > 0); } public int getRowCount() { return rows.size(); } public Object getValueAt(int rowIndex, int columnIndex) { if (rowIndex >= getRowCount()) { return null; } final ApiDiffFilterNode node = findNodeForRow(rowIndex); if (node == null) { return null; } switch (columnIndex) { case 0: return node.getName(); case 1: return node.getPublic(getState()); case 2: return node.getProtected(getState()); case 3: return node.getPrivate(getState()); case 4: return node.getPackagePrivate(getState()); } return null; } public void setValueAt(Object value, int rowIndex, int columnIndex) { final ApiDiffFilterNode node = findNodeForRow(rowIndex); if (node == null) { return; } switch (columnIndex) { case 0: break; case 1: node.setPublic((Boolean) value, getState()); break; case 2: node.setProtected((Boolean) value, getState()); break; case 3: node.setPrivate((Boolean) value, getState()); break; case 4: node.setPackagePrivate((Boolean) value, getState()); break; } } public void addRow(ApiDiffFilterNode node) { rows.add(node); fireTableDataChanged(); } private ApiDiffFilterNode findNodeForRow(int rowIndex) { return (ApiDiffFilterNode) rows.get(rowIndex); } private ApiDiffFilter getState() { return (ApiDiffFilter) context.getState(); } }
3,043
0.623398
0.616826
131
21.229008
21.761568
71
false
false
0
0
0
0
0
0
0.442748
false
false
6
46594451f0cca3772d63899cb34528e05319ee0d
6,012,954,226,735
9e13bbdcd4dc16527e4ec77730673a1b3fe2c495
/app/src/main/java/com/example/subhashvaikunth/testproject2/ImgViewAndPath.java
268ae9fef8098c7afb31a9b371105a4b00b0db0f
[]
no_license
Deepz22/Test-project-magento
https://github.com/Deepz22/Test-project-magento
48d06195493499afa539617f7ec1527101b4dd40
d9510b22d2bb15e021d19aca45d7389343eca5fb
refs/heads/master
2020-12-24T20:52:45.289000
2016-04-24T12:01:30
2016-04-24T12:01:30
56,969,356
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.subhashvaikunth.testproject2; import android.widget.ImageView; import android.widget.ProgressBar; public class ImgViewAndPath { private ImageView imageView; private String path; private ProgressBar pb; public ImageView getImageView() { return imageView; } public void setImageView(ImageView imageView) { this.imageView = imageView; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public ProgressBar getPb() { return pb; } public void setPb(ProgressBar pb) { this.pb = pb; } }
UTF-8
Java
666
java
ImgViewAndPath.java
Java
[ { "context": "package com.example.subhashvaikunth.testproject2;\n\nimport android.widget.ImageView;\ni", "end": 35, "score": 0.9947347640991211, "start": 20, "tag": "USERNAME", "value": "subhashvaikunth" } ]
null
[]
package com.example.subhashvaikunth.testproject2; import android.widget.ImageView; import android.widget.ProgressBar; public class ImgViewAndPath { private ImageView imageView; private String path; private ProgressBar pb; public ImageView getImageView() { return imageView; } public void setImageView(ImageView imageView) { this.imageView = imageView; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public ProgressBar getPb() { return pb; } public void setPb(ProgressBar pb) { this.pb = pb; } }
666
0.641141
0.63964
38
16.526316
16.192488
51
false
false
0
0
0
0
0
0
0.315789
false
false
6
73accc9915ac9de67c4f1b1a16b923b10626075f
21,663,815,068,273
2305a8ab95de5737d1fac3d55fdb8106378bfaf8
/crawler/src/main/java/com/jamal/crawler/JsoupGet.java
4361ec3b4227189092db5e5ca89577dd71435d73
[]
no_license
Newjavaer1/java-base
https://github.com/Newjavaer1/java-base
4e60ffe48f864923e023bbe87af15b58e0bd346c
7bd3da5a4d17ed4044f0471f209348cdd095f00c
refs/heads/master
2022-07-19T14:03:09.379000
2019-10-25T08:57:08
2019-10-25T08:57:08
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jamal.crawler; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.util.ArrayList; import java.util.List; /** * jsoup get 方式网页采集,以 CSDN 博客为例 */ public class JsoupGet { public static void main(String[] args) throws Exception { /** *最后面的1表示页码,当我们需要采集多页时,我们需要这个地方是动态的 */ // String CSDN__HOME_URL = "https://blog.csdn.net/z694644032/article/list/1?"; String CSDN__HOME_URL = "https://blog.csdn.net/z694644032/article/list/"; for (int i=1;i<3;i++){ // 我们需要拼接url,带上页码 String url = CSDN__HOME_URL+i; List<String> links = paserListPage(url); for (String link:links){ paserDetailPage(link); } } } /** * CSDN__HOME_URL是文章列表页,获取详情页的链接 * @throws Exception */ public static List<String> paserListPage(String link) throws Exception{ Document doc = Jsoup.connect(link).get(); // 根据css选择器 Elements elements = doc.select(".article-list div h4 a"); // Elements elements = doc.select("#mainBox > main > div.article-list > div > h4 > a"); // 存放链接 List<String> links = new ArrayList<>(30); for (Element element:elements){ // 获取绝对路径 links.add(element.absUrl("href")); } return links; } /** * 处理详情页,获取如下几个字段 * 标题 title * 时间 date * 作者 author * 内容 content * @param detailUrl */ public static void paserDetailPage(String detailUrl) throws Exception{ Document document = Jsoup.connect(detailUrl).get(); // 文章标题 String title = document.select("div.article-title-box > h1.title-article").first().ownText(); // 文章发布时间 String date = document.select("span.time").first().ownText(); // 文章作者 String author = document.select("a.follow-nickName").first().ownText(); // 文章正文内容 String content = document.select("div#content_views").first().text(); System.out.println("采集文章,标题:"+title+" ,发布时间:"+date+" ,作者:"+author); // System.out.println("采集文章,标题:"+title+" ,发布时间:"+date+" ,作者:"+author+" ,正文内容:"+content); } }
UTF-8
Java
2,603
java
JsoupGet.java
Java
[ { "context": " String CSDN__HOME_URL = \"https://blog.csdn.net/z694644032/article/list/1?\";\n String CSDN__HOME_URL =", "end": 466, "score": 0.9991142153739929, "start": 456, "tag": "USERNAME", "value": "z694644032" }, { "context": " String CSDN__HOME_URL = \"https://blog.csdn.net/z694644032/article/list/\";\n for (int i=1;i<3;i++){\n ", "end": 550, "score": 0.9992182850837708, "start": 540, "tag": "USERNAME", "value": "z694644032" } ]
null
[]
package com.jamal.crawler; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.util.ArrayList; import java.util.List; /** * jsoup get 方式网页采集,以 CSDN 博客为例 */ public class JsoupGet { public static void main(String[] args) throws Exception { /** *最后面的1表示页码,当我们需要采集多页时,我们需要这个地方是动态的 */ // String CSDN__HOME_URL = "https://blog.csdn.net/z694644032/article/list/1?"; String CSDN__HOME_URL = "https://blog.csdn.net/z694644032/article/list/"; for (int i=1;i<3;i++){ // 我们需要拼接url,带上页码 String url = CSDN__HOME_URL+i; List<String> links = paserListPage(url); for (String link:links){ paserDetailPage(link); } } } /** * CSDN__HOME_URL是文章列表页,获取详情页的链接 * @throws Exception */ public static List<String> paserListPage(String link) throws Exception{ Document doc = Jsoup.connect(link).get(); // 根据css选择器 Elements elements = doc.select(".article-list div h4 a"); // Elements elements = doc.select("#mainBox > main > div.article-list > div > h4 > a"); // 存放链接 List<String> links = new ArrayList<>(30); for (Element element:elements){ // 获取绝对路径 links.add(element.absUrl("href")); } return links; } /** * 处理详情页,获取如下几个字段 * 标题 title * 时间 date * 作者 author * 内容 content * @param detailUrl */ public static void paserDetailPage(String detailUrl) throws Exception{ Document document = Jsoup.connect(detailUrl).get(); // 文章标题 String title = document.select("div.article-title-box > h1.title-article").first().ownText(); // 文章发布时间 String date = document.select("span.time").first().ownText(); // 文章作者 String author = document.select("a.follow-nickName").first().ownText(); // 文章正文内容 String content = document.select("div#content_views").first().text(); System.out.println("采集文章,标题:"+title+" ,发布时间:"+date+" ,作者:"+author); // System.out.println("采集文章,标题:"+title+" ,发布时间:"+date+" ,作者:"+author+" ,正文内容:"+content); } }
2,603
0.585055
0.573187
75
29.333334
27.272615
101
false
false
0
0
0
0
0
0
0.426667
false
false
6
72a14c71a1b6c820161fe8ad9196704b1f33181e
4,406,636,477,299
d7703769f52a27b13ff1dc83e673f0619f4afbb2
/show-member/src/main/java/com/szhengzhu/service/MatchService.java
9d7adf63db9422c1bbb4b9ccc8536afc9a3b838c
[]
no_license
zengjianhong/show-root
https://github.com/zengjianhong/show-root
1ff346c936971b3bbfa20edec75c452b285d1903
5a9db5f90ff7a60cd59fed7e4fe40fa242c1e5e8
refs/heads/master
2022-02-14T17:57:45.806000
2022-01-16T11:54:50
2022-01-16T11:54:50
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.szhengzhu.service; import com.szhengzhu.bean.member.MatchInfo; import com.szhengzhu.bean.member.param.ExchangeParam; import com.szhengzhu.core.PageGrid; import com.szhengzhu.core.PageParam; import java.util.List; import java.util.Map; /** * @author jehon */ public interface MatchService { /** * 获取竞赛活动分页列表 * * @param param * @return */ PageGrid<MatchInfo> page(PageParam<MatchInfo> param); /** * 添加竞赛活动 * * @param matchInfo */ void add(MatchInfo matchInfo); /** * 修改竞赛活动 * * @param matchInfo */ void modify(MatchInfo matchInfo); /** * 查询活动列表 * * @return */ List<Map<String, Object>> list(); /** * 竞赛活动关联队伍 * * @param teamIds * @param matchId */ void addItem(String matchId, List<String> teamIds); /** * 获取会员领券识别码 * * @param matchId * @param userId * @return */ Map<String, Object> getUserExchangeMark(String matchId, String userId); /** * 扫码获取 * * @param mark * @return */ Map<String, Object> scanCodeByMark(String mark); /** * 用户兑换券 * * @param exchangeParam */ void exchange(ExchangeParam exchangeParam); /** * 根据赠送机会类型查询竞赛活动信息 * @param type * @return */ List<MatchInfo> selectByGiveChance(Integer type); }
UTF-8
Java
1,552
java
MatchService.java
Java
[ { "context": "a.util.List;\nimport java.util.Map;\n\n/**\n * @author jehon\n */\npublic interface MatchService {\n\n /**\n ", "end": 270, "score": 0.9996596574783325, "start": 265, "tag": "USERNAME", "value": "jehon" } ]
null
[]
package com.szhengzhu.service; import com.szhengzhu.bean.member.MatchInfo; import com.szhengzhu.bean.member.param.ExchangeParam; import com.szhengzhu.core.PageGrid; import com.szhengzhu.core.PageParam; import java.util.List; import java.util.Map; /** * @author jehon */ public interface MatchService { /** * 获取竞赛活动分页列表 * * @param param * @return */ PageGrid<MatchInfo> page(PageParam<MatchInfo> param); /** * 添加竞赛活动 * * @param matchInfo */ void add(MatchInfo matchInfo); /** * 修改竞赛活动 * * @param matchInfo */ void modify(MatchInfo matchInfo); /** * 查询活动列表 * * @return */ List<Map<String, Object>> list(); /** * 竞赛活动关联队伍 * * @param teamIds * @param matchId */ void addItem(String matchId, List<String> teamIds); /** * 获取会员领券识别码 * * @param matchId * @param userId * @return */ Map<String, Object> getUserExchangeMark(String matchId, String userId); /** * 扫码获取 * * @param mark * @return */ Map<String, Object> scanCodeByMark(String mark); /** * 用户兑换券 * * @param exchangeParam */ void exchange(ExchangeParam exchangeParam); /** * 根据赠送机会类型查询竞赛活动信息 * @param type * @return */ List<MatchInfo> selectByGiveChance(Integer type); }
1,552
0.568697
0.568697
83
16.012049
15.987566
75
false
false
0
0
0
0
0
0
0.253012
false
false
6
c7c6c3388ba549ef7f3115b195a247e2eacd3bc4
506,806,193,389
b5f461a4aeb220e098a469a96dc78c2a64cf8da1
/DeteleHtmlUtil.java
2ab51e693706ef115090576dfe99dd8f0b9daaa9
[]
no_license
nxbnxb/JAVADesignPattern
https://github.com/nxbnxb/JAVADesignPattern
5ab550820084d27c6711afee0a05dfe33ff86d02
d741fe00bb59b37e68f72f6a7bca58e99a19b901
refs/heads/master
2021-01-13T06:12:44.309000
2017-06-21T05:26:12
2017-06-21T05:26:12
94,961,404
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package wy.com.write.util; import java.util.ArrayList; import java.util.HashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import wy.com.tool.MD5Util; public class DeteleHtmlUtil { private static final String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; // 定义script的正则表达式 private static final String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; // 定义style的正则表达式 private static final String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式 private static final String regEx_space = "\\s*|\t|\r|\n";// 定义空格回车换行符 private static final String regEx_w = "<w[^>]*?>[\\s\\S]*?<\\/w[^>]*?>";// 定义所有w标签 /** * 传入文本 返回取出html 空格 标点 后的 md516位 <key,字符串> * @param content * @return * 2017年5月16日 */ public static HashMap<String, String> similarity(String content){ if(content ==null){ return null; }else{ HashMap<String,String> map = new HashMap<String,String>(); //去除html标签 content = delHTMLTag(content); //句号分割 ArrayList<String> lists = splitSentence(content); int size = lists.size(); for(int i =0;i<size;i++){ String cc = lists.get(i); //去除标点符号 String cc2= delPunctuation(cc); cc2 = cc2.replaceAll("\\s*",""); //md5 16位之后 作为key 加入到map中 String md516 = MD5Util.MD516(cc2); map.put(md516, cc2.trim()); } return map; } } /** * 去除标点符号 * @param cc * @return * 2017年5月16日 */ private static String delPunctuation(String cc) { cc = cc.replaceAll("[\\pP‘’“”]",""); return cc.trim(); } /** * 句号分割 * @param content * @return * 2017年5月16日 */ private static ArrayList<String> splitSentence(String content) { ArrayList<String> lists = new ArrayList<String>(); if(content.contains(".")||content.contains("。") ){ content = content.replaceAll("。", "."); String[] split = content.split("\\."); for (String string : split) { lists.add(string); } }else if(content.contains("!") ){ content = content.replaceAll("!", "."); String[] split = content.split("\\."); for (String string : split) { lists.add(string); } }else if( content.contains("!") ){ content = content.replaceAll("!", "."); String[] split = content.split("\\."); for (String string : split) { lists.add(string); } }else{ lists.add(content); } return lists; } /** * @param htmlStr * @return 删除Html标签 * @author LongJin */ private static String delHTMLTag(String htmlStr) { //删除&nbsp之类的内容 /* htmlStr = htmlStr.replaceAll("&nbsp;", ""); htmlStr=htmlStr.replaceAll("&ldquo;", ""); htmlStr=htmlStr.replaceAll("&rdquo;", ""); htmlStr=htmlStr.replaceAll("&hellip;", "");*/ String reqAnd="\\&[a-z]{1,10};"; Pattern a_w = Pattern.compile(reqAnd, Pattern.CASE_INSENSITIVE); Matcher b_w = a_w.matcher(htmlStr); htmlStr = b_w.replaceAll(""); //删除&nbsp之类的内容 Pattern p_w = Pattern.compile(regEx_w, Pattern.CASE_INSENSITIVE); Matcher m_w = p_w.matcher(htmlStr); htmlStr = m_w.replaceAll(""); // 过滤script标签 Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE); Matcher m_script = p_script.matcher(htmlStr); htmlStr = m_script.replaceAll(""); // 过滤script标签 Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE); Matcher m_style = p_style.matcher(htmlStr); htmlStr = m_style.replaceAll(""); // 过滤style标签 Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE); Matcher m_html = p_html.matcher(htmlStr); htmlStr = m_html.replaceAll(""); // 过滤html标签 Pattern p_space = Pattern.compile(regEx_space, Pattern.CASE_INSENSITIVE); Matcher m_space = p_space.matcher(htmlStr); htmlStr = m_space.replaceAll(""); // 过滤空格回车标签 Pattern p = Pattern.compile("\\s*|\t|\r|\n"); Matcher m = p.matcher(htmlStr); htmlStr = m.replaceAll(""); return htmlStr.trim(); // 返回文本字符串 } }
UTF-8
Java
4,522
java
DeteleHtmlUtil.java
Java
[ { "context": "m htmlStr\r\n * @return 删除Html标签\r\n * @author LongJin\r\n */\r\n private static String delHTMLTag(S", "end": 2498, "score": 0.9828330874443054, "start": 2491, "tag": "NAME", "value": "LongJin" } ]
null
[]
package wy.com.write.util; import java.util.ArrayList; import java.util.HashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import wy.com.tool.MD5Util; public class DeteleHtmlUtil { private static final String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; // 定义script的正则表达式 private static final String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; // 定义style的正则表达式 private static final String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式 private static final String regEx_space = "\\s*|\t|\r|\n";// 定义空格回车换行符 private static final String regEx_w = "<w[^>]*?>[\\s\\S]*?<\\/w[^>]*?>";// 定义所有w标签 /** * 传入文本 返回取出html 空格 标点 后的 md516位 <key,字符串> * @param content * @return * 2017年5月16日 */ public static HashMap<String, String> similarity(String content){ if(content ==null){ return null; }else{ HashMap<String,String> map = new HashMap<String,String>(); //去除html标签 content = delHTMLTag(content); //句号分割 ArrayList<String> lists = splitSentence(content); int size = lists.size(); for(int i =0;i<size;i++){ String cc = lists.get(i); //去除标点符号 String cc2= delPunctuation(cc); cc2 = cc2.replaceAll("\\s*",""); //md5 16位之后 作为key 加入到map中 String md516 = MD5Util.MD516(cc2); map.put(md516, cc2.trim()); } return map; } } /** * 去除标点符号 * @param cc * @return * 2017年5月16日 */ private static String delPunctuation(String cc) { cc = cc.replaceAll("[\\pP‘’“”]",""); return cc.trim(); } /** * 句号分割 * @param content * @return * 2017年5月16日 */ private static ArrayList<String> splitSentence(String content) { ArrayList<String> lists = new ArrayList<String>(); if(content.contains(".")||content.contains("。") ){ content = content.replaceAll("。", "."); String[] split = content.split("\\."); for (String string : split) { lists.add(string); } }else if(content.contains("!") ){ content = content.replaceAll("!", "."); String[] split = content.split("\\."); for (String string : split) { lists.add(string); } }else if( content.contains("!") ){ content = content.replaceAll("!", "."); String[] split = content.split("\\."); for (String string : split) { lists.add(string); } }else{ lists.add(content); } return lists; } /** * @param htmlStr * @return 删除Html标签 * @author LongJin */ private static String delHTMLTag(String htmlStr) { //删除&nbsp之类的内容 /* htmlStr = htmlStr.replaceAll("&nbsp;", ""); htmlStr=htmlStr.replaceAll("&ldquo;", ""); htmlStr=htmlStr.replaceAll("&rdquo;", ""); htmlStr=htmlStr.replaceAll("&hellip;", "");*/ String reqAnd="\\&[a-z]{1,10};"; Pattern a_w = Pattern.compile(reqAnd, Pattern.CASE_INSENSITIVE); Matcher b_w = a_w.matcher(htmlStr); htmlStr = b_w.replaceAll(""); //删除&nbsp之类的内容 Pattern p_w = Pattern.compile(regEx_w, Pattern.CASE_INSENSITIVE); Matcher m_w = p_w.matcher(htmlStr); htmlStr = m_w.replaceAll(""); // 过滤script标签 Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE); Matcher m_script = p_script.matcher(htmlStr); htmlStr = m_script.replaceAll(""); // 过滤script标签 Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE); Matcher m_style = p_style.matcher(htmlStr); htmlStr = m_style.replaceAll(""); // 过滤style标签 Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE); Matcher m_html = p_html.matcher(htmlStr); htmlStr = m_html.replaceAll(""); // 过滤html标签 Pattern p_space = Pattern.compile(regEx_space, Pattern.CASE_INSENSITIVE); Matcher m_space = p_space.matcher(htmlStr); htmlStr = m_space.replaceAll(""); // 过滤空格回车标签 Pattern p = Pattern.compile("\\s*|\t|\r|\n"); Matcher m = p.matcher(htmlStr); htmlStr = m.replaceAll(""); return htmlStr.trim(); // 返回文本字符串 } }
4,522
0.580162
0.568982
145
26.993103
24.220396
100
false
false
0
0
0
0
0
0
1.965517
false
false
6
c3f93465b42afccfd7715e94f1df3f676614a196
146,028,910,803
a42cb3f928a4eb10751d30191e7a6d0b10b1f4b1
/src/main/java/com/raccoon/city/survivors/SurvivorsApplication.java
8fb3ac95b3f2381772d6d355a8833b4c91446a8b
[]
no_license
vladf2n/survivors
https://github.com/vladf2n/survivors
1b6f15ddec052ea8302c6ab458223c6667f17016
454844eb4aeceb8edd04089629799c25e200af09
refs/heads/main
2023-01-04T04:05:57.768000
2020-11-03T03:50:14
2020-11-03T03:50:14
308,521,194
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.raccoon.city.survivors; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SurvivorsApplication { public static void main(String[] args) { SpringApplication.run(SurvivorsApplication.class, args); } }
UTF-8
Java
325
java
SurvivorsApplication.java
Java
[]
null
[]
package com.raccoon.city.survivors; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SurvivorsApplication { public static void main(String[] args) { SpringApplication.run(SurvivorsApplication.class, args); } }
325
0.824615
0.824615
13
24
24.210615
68
false
false
0
0
0
0
0
0
0.692308
false
false
6
b307a5c5b3803e08c297fdb3e3be8c1f13e11fc7
14,577,119,034,457
c1b4d353c116ea605385ca360f884fc0f82e8bbc
/app/src/main/java/com/tupaiaer/cataloguemovie/ui/activity/MainActivity.java
1c7018a85ddc921f440aa5b685591d5b3ff8b29f
[]
no_license
sandypriyatna/Pilemku
https://github.com/sandypriyatna/Pilemku
0ffdbcd433cf13cb99c71589b33f2cfac970aa75
664124c08c41ff507f51d329111bebad113edcd5
refs/heads/master
2020-04-27T23:13:48.223000
2019-03-10T02:03:00
2019-03-10T02:03:00
174,767,191
0
1
null
false
2019-10-13T14:26:53
2019-03-10T02:03:07
2019-03-10T02:03:42
2019-03-10T02:03:40
136
0
1
1
Java
false
false
package com.tupaiaer.cataloguemovie.ui.activity; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import com.tupaiaer.cataloguemovie.R; import com.tupaiaer.cataloguemovie.adapter.ViewPagerAdapter; /** * Created by sandypriyatna on 10/03/19 * github.com/sandypriyatna */ public class MainActivity extends AppCompatActivity { TabLayout tabLayout; ViewPager viewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tabLayout = findViewById(R.id.tab_layout); viewPager = findViewById(R.id.view_pager); //viewPager ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager()); viewPager.setAdapter(viewPagerAdapter); viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout)); //tabLayout tabLayout.addTab(tabLayout.newTab().setText("NowPlaying")); tabLayout.addTab(tabLayout.newTab().setText("Upcoming")); tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { viewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); } }
UTF-8
Java
1,616
java
MainActivity.java
Java
[ { "context": "movie.adapter.ViewPagerAdapter;\n\n/**\n * Created by sandypriyatna on 10/03/19\n * github.com/sandypriyatna\n */\n\npubl", "end": 347, "score": 0.9996253848075867, "start": 334, "tag": "USERNAME", "value": "sandypriyatna" }, { "context": "reated by sandypriyatna on 10/03/19\n * github.com/sandypriyatna\n */\n\npublic class MainActivity extends AppCompatA", "end": 387, "score": 0.9996736645698547, "start": 374, "tag": "USERNAME", "value": "sandypriyatna" } ]
null
[]
package com.tupaiaer.cataloguemovie.ui.activity; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import com.tupaiaer.cataloguemovie.R; import com.tupaiaer.cataloguemovie.adapter.ViewPagerAdapter; /** * Created by sandypriyatna on 10/03/19 * github.com/sandypriyatna */ public class MainActivity extends AppCompatActivity { TabLayout tabLayout; ViewPager viewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tabLayout = findViewById(R.id.tab_layout); viewPager = findViewById(R.id.view_pager); //viewPager ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager()); viewPager.setAdapter(viewPagerAdapter); viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout)); //tabLayout tabLayout.addTab(tabLayout.newTab().setText("NowPlaying")); tabLayout.addTab(tabLayout.newTab().setText("Upcoming")); tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { viewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); } }
1,616
0.701114
0.696163
52
30.076923
27.295988
98
false
false
0
0
0
0
0
0
0.384615
false
false
6
47810cec66599f8bc3036b6863763968d392e5bf
9,311,489,129,460
0c775c6c43fa8818972bc90d7ed10f09e9ba6661
/texteriaclient/texteria/elements/container/IContainer.java
3308cf67abb9d38b119702b42826e87c9f0054ef
[]
no_license
xfrutelacode/VimeWorld-Texteria-SRC
https://github.com/xfrutelacode/VimeWorld-Texteria-SRC
f7d2e1d98a3b219c9468530d9bfbd7f511d41152
92555b646f931c015aadbdbd4054b34fb4e725cb
refs/heads/main
2023-03-06T23:10:46.640000
2021-11-11T06:49:47
2021-11-11T06:49:47
426,886,232
3
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.xtrafrancyz.mods.texteria.elements.container; import net.xtrafrancyz.mods.texteria.elements.Element2D; public interface IContainer { Element2D getElement(String var1); float getWidth(); float getHeight(); }
UTF-8
Java
235
java
IContainer.java
Java
[]
null
[]
package net.xtrafrancyz.mods.texteria.elements.container; import net.xtrafrancyz.mods.texteria.elements.Element2D; public interface IContainer { Element2D getElement(String var1); float getWidth(); float getHeight(); }
235
0.765957
0.753191
12
18.583334
21.096834
57
false
false
0
0
0
0
0
0
0.416667
false
false
6
bf225848316054b9f3e733ebd3201509fcaf8f43
6,382,321,471,242
992a73374de01f4909d735d31e4b20fa878a3775
/jgoldbox/jgoldbox/src/jia/editor/lists/pnl_ModuleList.java
20ccae4a0eb87ce213070b9fefa8b563bfc6dba2
[]
no_license
Kintar/jgoldbox
https://github.com/Kintar/jgoldbox
991951f956e36eab789479df122399c294ee5d04
786401458477d4d51c7d306ed4c92c51895bb4a6
refs/heads/master
2021-01-10T19:20:53.164000
2010-07-01T20:58:40
2010-07-01T20:58:40
32,217,577
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * ModuleList.java * * Created on October 17, 2007, 4:18 PM */ package jia.editor.lists; import jia.editor.EditorMain; import jia.editor.forms.LevelForm; import jia.editor.widgets.LevelsTable; import jia.tools.PanelSwapper; /** * * @author estell */ public class pnl_ModuleList extends javax.swing.JPanel { /** Creates new form ModuleList */ public pnl_ModuleList() { initComponents(); this.scrl_LevelList.setViewportView(new LevelsTable(this)); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents private void initComponents() { sp_MainPane = new javax.swing.JSplitPane(); scrl_Text = new javax.swing.JScrollPane(); txt_Details = new javax.swing.JTextPane(); scrl_LevelList = new javax.swing.JScrollPane(); btn_Add = new javax.swing.JButton(); btn_Edit = new javax.swing.JButton(); btn_Delete = new javax.swing.JButton(); btn_Cancel = new javax.swing.JButton(); setPreferredSize(new java.awt.Dimension(800, 580)); sp_MainPane.setBorder(javax.swing.BorderFactory.createTitledBorder(null, java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("title_Modules"), javax.swing.border.TitledBorder.LEFT, javax.swing.border.TitledBorder.BELOW_TOP)); sp_MainPane.setDividerLocation(400); sp_MainPane.setDividerSize(7); sp_MainPane.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT); sp_MainPane.setLastDividerLocation(400); sp_MainPane.setOneTouchExpandable(true); txt_Details.setBackground(new java.awt.Color(0, 0, 0)); txt_Details.setEditable(false); txt_Details.setForeground(new java.awt.Color(255, 255, 255)); scrl_Text.setViewportView(txt_Details); sp_MainPane.setRightComponent(scrl_Text); sp_MainPane.setLeftComponent(scrl_LevelList); btn_Add.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jia_ui/images/add.png"))); btn_Add.setText(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Add_lbl")); btn_Add.setToolTipText(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Add")); btn_Add.setActionCommand(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Add_lbl")); btn_Add.setLabel(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Add_lbl")); btn_Add.setName(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Add_lbl")); btn_Add.setPreferredSize(new java.awt.Dimension(125, 30)); btn_Add.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_AddActionPerformed(evt); } }); btn_Add.getAccessibleContext().setAccessibleName(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Add_lbl")); btn_Add.getAccessibleContext().setAccessibleDescription(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Add")); btn_Edit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jia_ui/images/pencil.png"))); btn_Edit.setText(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Edit_lbl")); btn_Edit.setToolTipText(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Edit")); btn_Edit.setActionCommand(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Edit_lbl")); btn_Edit.setLabel(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Edit_lbl")); btn_Edit.setName(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Edit_lbl")); btn_Edit.setPreferredSize(new java.awt.Dimension(125, 30)); btn_Edit.getAccessibleContext().setAccessibleName(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Edit_lbl")); btn_Edit.getAccessibleContext().setAccessibleDescription(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Edit")); btn_Delete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jia_ui/images/delete.png"))); btn_Delete.setText(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Delete_lbl")); btn_Delete.setToolTipText(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Delete")); btn_Delete.setActionCommand(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Delete_lbl")); btn_Delete.setLabel(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Delete_lbl")); btn_Delete.setName(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Delete_lbl")); btn_Delete.setPreferredSize(new java.awt.Dimension(125, 30)); btn_Delete.getAccessibleContext().setAccessibleName(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Delete_lbl")); btn_Delete.getAccessibleContext().setAccessibleDescription(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Delete")); btn_Cancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jia_ui/images/door_out.png"))); btn_Cancel.setText(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Cancel_lbl")); btn_Cancel.setToolTipText(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Cancel")); btn_Cancel.setActionCommand(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Cancel_lbl")); btn_Cancel.setLabel(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Cancel_lbl")); btn_Cancel.setName(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Cancel_lbl")); btn_Cancel.setPreferredSize(new java.awt.Dimension(125, 30)); btn_Cancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_CancelActionPerformed(evt); } }); btn_Cancel.getAccessibleContext().setAccessibleName(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Cancel_lbl")); btn_Cancel.getAccessibleContext().setAccessibleDescription(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Cancel")); org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .addContainerGap() .add(sp_MainPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 649, Short.MAX_VALUE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(btn_Add, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(org.jdesktop.layout.GroupLayout.TRAILING, btn_Edit, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(org.jdesktop.layout.GroupLayout.TRAILING, btn_Delete, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(org.jdesktop.layout.GroupLayout.TRAILING, btn_Cancel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .addContainerGap() .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(sp_MainPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 558, Short.MAX_VALUE) .add(layout.createSequentialGroup() .add(btn_Add, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(btn_Edit, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(btn_Delete, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 426, Short.MAX_VALUE) .add(btn_Cancel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); }// </editor-fold>//GEN-END:initComponents private void btn_AddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_AddActionPerformed PanelSwapper.swap(new LevelForm(), this); }//GEN-LAST:event_btn_AddActionPerformed private void btn_CancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_CancelActionPerformed PanelSwapper.swap(EditorMain.p_defaultAdminPanel, this); }//GEN-LAST:event_btn_CancelActionPerformed public void setConsoleText(String string) { this.txt_Details.setText(string); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btn_Add; private javax.swing.JButton btn_Cancel; private javax.swing.JButton btn_Delete; private javax.swing.JButton btn_Edit; private javax.swing.JScrollPane scrl_LevelList; private javax.swing.JScrollPane scrl_Text; private javax.swing.JSplitPane sp_MainPane; private javax.swing.JTextPane txt_Details; // End of variables declaration//GEN-END:variables }
UTF-8
Java
10,999
java
pnl_ModuleList.java
Java
[ { "context": "import jia.tools.PanelSwapper;\n\n/**\n *\n * @author estell\n */\npublic class pnl_ModuleList extends javax.swi", "end": 258, "score": 0.8716377019882202, "start": 252, "tag": "USERNAME", "value": "estell" } ]
null
[]
/* * ModuleList.java * * Created on October 17, 2007, 4:18 PM */ package jia.editor.lists; import jia.editor.EditorMain; import jia.editor.forms.LevelForm; import jia.editor.widgets.LevelsTable; import jia.tools.PanelSwapper; /** * * @author estell */ public class pnl_ModuleList extends javax.swing.JPanel { /** Creates new form ModuleList */ public pnl_ModuleList() { initComponents(); this.scrl_LevelList.setViewportView(new LevelsTable(this)); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents private void initComponents() { sp_MainPane = new javax.swing.JSplitPane(); scrl_Text = new javax.swing.JScrollPane(); txt_Details = new javax.swing.JTextPane(); scrl_LevelList = new javax.swing.JScrollPane(); btn_Add = new javax.swing.JButton(); btn_Edit = new javax.swing.JButton(); btn_Delete = new javax.swing.JButton(); btn_Cancel = new javax.swing.JButton(); setPreferredSize(new java.awt.Dimension(800, 580)); sp_MainPane.setBorder(javax.swing.BorderFactory.createTitledBorder(null, java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("title_Modules"), javax.swing.border.TitledBorder.LEFT, javax.swing.border.TitledBorder.BELOW_TOP)); sp_MainPane.setDividerLocation(400); sp_MainPane.setDividerSize(7); sp_MainPane.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT); sp_MainPane.setLastDividerLocation(400); sp_MainPane.setOneTouchExpandable(true); txt_Details.setBackground(new java.awt.Color(0, 0, 0)); txt_Details.setEditable(false); txt_Details.setForeground(new java.awt.Color(255, 255, 255)); scrl_Text.setViewportView(txt_Details); sp_MainPane.setRightComponent(scrl_Text); sp_MainPane.setLeftComponent(scrl_LevelList); btn_Add.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jia_ui/images/add.png"))); btn_Add.setText(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Add_lbl")); btn_Add.setToolTipText(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Add")); btn_Add.setActionCommand(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Add_lbl")); btn_Add.setLabel(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Add_lbl")); btn_Add.setName(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Add_lbl")); btn_Add.setPreferredSize(new java.awt.Dimension(125, 30)); btn_Add.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_AddActionPerformed(evt); } }); btn_Add.getAccessibleContext().setAccessibleName(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Add_lbl")); btn_Add.getAccessibleContext().setAccessibleDescription(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Add")); btn_Edit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jia_ui/images/pencil.png"))); btn_Edit.setText(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Edit_lbl")); btn_Edit.setToolTipText(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Edit")); btn_Edit.setActionCommand(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Edit_lbl")); btn_Edit.setLabel(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Edit_lbl")); btn_Edit.setName(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Edit_lbl")); btn_Edit.setPreferredSize(new java.awt.Dimension(125, 30)); btn_Edit.getAccessibleContext().setAccessibleName(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Edit_lbl")); btn_Edit.getAccessibleContext().setAccessibleDescription(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Edit")); btn_Delete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jia_ui/images/delete.png"))); btn_Delete.setText(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Delete_lbl")); btn_Delete.setToolTipText(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Delete")); btn_Delete.setActionCommand(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Delete_lbl")); btn_Delete.setLabel(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Delete_lbl")); btn_Delete.setName(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Delete_lbl")); btn_Delete.setPreferredSize(new java.awt.Dimension(125, 30)); btn_Delete.getAccessibleContext().setAccessibleName(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Delete_lbl")); btn_Delete.getAccessibleContext().setAccessibleDescription(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Delete")); btn_Cancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jia_ui/images/door_out.png"))); btn_Cancel.setText(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Cancel_lbl")); btn_Cancel.setToolTipText(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Cancel")); btn_Cancel.setActionCommand(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Cancel_lbl")); btn_Cancel.setLabel(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Cancel_lbl")); btn_Cancel.setName(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Cancel_lbl")); btn_Cancel.setPreferredSize(new java.awt.Dimension(125, 30)); btn_Cancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_CancelActionPerformed(evt); } }); btn_Cancel.getAccessibleContext().setAccessibleName(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Cancel_lbl")); btn_Cancel.getAccessibleContext().setAccessibleDescription(java.util.ResourceBundle.getBundle("jia_ui/images/formUI").getString("btn_Cancel")); org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .addContainerGap() .add(sp_MainPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 649, Short.MAX_VALUE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(btn_Add, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(org.jdesktop.layout.GroupLayout.TRAILING, btn_Edit, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(org.jdesktop.layout.GroupLayout.TRAILING, btn_Delete, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(org.jdesktop.layout.GroupLayout.TRAILING, btn_Cancel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .addContainerGap() .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(sp_MainPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 558, Short.MAX_VALUE) .add(layout.createSequentialGroup() .add(btn_Add, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(btn_Edit, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(btn_Delete, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 426, Short.MAX_VALUE) .add(btn_Cancel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); }// </editor-fold>//GEN-END:initComponents private void btn_AddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_AddActionPerformed PanelSwapper.swap(new LevelForm(), this); }//GEN-LAST:event_btn_AddActionPerformed private void btn_CancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_CancelActionPerformed PanelSwapper.swap(EditorMain.p_defaultAdminPanel, this); }//GEN-LAST:event_btn_CancelActionPerformed public void setConsoleText(String string) { this.txt_Details.setText(string); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btn_Add; private javax.swing.JButton btn_Cancel; private javax.swing.JButton btn_Delete; private javax.swing.JButton btn_Edit; private javax.swing.JScrollPane scrl_LevelList; private javax.swing.JScrollPane scrl_Text; private javax.swing.JSplitPane sp_MainPane; private javax.swing.JTextPane txt_Details; // End of variables declaration//GEN-END:variables }
10,999
0.707701
0.701973
170
63.700001
53.797863
250
false
false
0
0
0
0
0
0
0.794118
false
false
6
cd82615858f5a0ab7639164c8c5aaf57483cff71
24,678,882,109,292
272e15aea0eb75958d1dce13966c6bafba53d94e
/src/tw/org/iii/Home/Sample191.java
e1ce99d42f4669649c672215f76316efcb8aeffc
[]
no_license
wangFCfthxc/Home
https://github.com/wangFCfthxc/Home
8dd2e80fa4d0c283dea00b018ab931a442823a0f
343919ba3aed1543aa7959ac94f8ce13d3c28b40
refs/heads/master
2020-12-05T19:35:05.574000
2017-04-12T02:27:01
2017-04-12T02:27:01
66,151,775
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package tw.org.iii.Home; import javax.swing.JApplet; import javax.swing.JLabel; public class Sample191 extends JApplet{ private JLabel lb; public void init(){ lb = new JLabel(); // 建立元件 lb.setText("安安你好"); // 設定元件 add(lb); // 將元件新增到容器中 } }
UTF-8
Java
323
java
Sample191.java
Java
[]
null
[]
package tw.org.iii.Home; import javax.swing.JApplet; import javax.swing.JLabel; public class Sample191 extends JApplet{ private JLabel lb; public void init(){ lb = new JLabel(); // 建立元件 lb.setText("安安你好"); // 設定元件 add(lb); // 將元件新增到容器中 } }
323
0.615658
0.604982
17
14.529411
13.386199
39
false
false
0
0
0
0
0
0
1.647059
false
false
6
f521493a19278bb09be38ff01de1fb4c71a72cdf
31,945,966,756,716
fe9f4cae529b8f127cab8fc3380e86cd84ec0c4c
/library/src/main/java/com/gatebuzz/rapidapi/rx/internal/InvocationHandler.java
07b35ed537aeebbe692951d39a360cc7f12dca6b
[ "Apache-2.0" ]
permissive
waffle-iron/RxRapidApi
https://github.com/waffle-iron/RxRapidApi
1a5725825da4c2cdd9bbe4994507788d816515d2
c0f57eed3630e5f7711613b7c5fec49a68e2c4b0
refs/heads/master
2020-06-14T22:57:28.608000
2016-12-02T14:09:15
2016-12-02T14:09:15
75,401,028
0
0
null
true
2016-12-02T14:09:14
2016-12-02T14:09:13
2016-12-01T21:45:50
2016-12-02T14:01:27
162
0
0
0
null
null
null
package com.gatebuzz.rapidapi.rx.internal; import android.support.annotation.VisibleForTesting; import android.support.v4.util.Pair; import java.lang.reflect.Method; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import rx.Observable; public class InvocationHandler implements java.lang.reflect.InvocationHandler { private Map<String, CallConfiguration> callConfigurationMap; private EngineYard engineYard; public InvocationHandler(Map<String, CallConfiguration> callConfigurationMap) { this(callConfigurationMap, new DefaultEngineYard()); } @VisibleForTesting InvocationHandler(Map<String, CallConfiguration> callConfigurationMap, EngineYard engineYard) { this.callConfigurationMap = callConfigurationMap; this.engineYard = engineYard; } @Override public Object invoke(Object o, Method method, Object[] parameterValues) throws Throwable { final CallConfiguration configuration = callConfigurationMap.get(method.getName()); final Map<String, Pair<String, String>> body = new HashMap<>(); for (int i = 0; i < configuration.parameters.size(); i++) { String value = String.valueOf(parameterValues[i]); if (configuration.urlEncoded.contains(configuration.parameters.get(i))) { value = URLEncoder.encode(value, "UTF-8"); } body.put(configuration.parameters.get(i), new Pair<>("data", value)); } return Observable.create(engineYard.create(configuration, body)); } interface EngineYard { Engine create(CallConfiguration configuration, Map<String, Pair<String, String>> body); } private static class DefaultEngineYard implements EngineYard { @Override public Engine create(CallConfiguration configuration, Map<String, Pair<String, String>> body) { return new Engine(configuration, body); } } }
UTF-8
Java
1,954
java
InvocationHandler.java
Java
[]
null
[]
package com.gatebuzz.rapidapi.rx.internal; import android.support.annotation.VisibleForTesting; import android.support.v4.util.Pair; import java.lang.reflect.Method; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import rx.Observable; public class InvocationHandler implements java.lang.reflect.InvocationHandler { private Map<String, CallConfiguration> callConfigurationMap; private EngineYard engineYard; public InvocationHandler(Map<String, CallConfiguration> callConfigurationMap) { this(callConfigurationMap, new DefaultEngineYard()); } @VisibleForTesting InvocationHandler(Map<String, CallConfiguration> callConfigurationMap, EngineYard engineYard) { this.callConfigurationMap = callConfigurationMap; this.engineYard = engineYard; } @Override public Object invoke(Object o, Method method, Object[] parameterValues) throws Throwable { final CallConfiguration configuration = callConfigurationMap.get(method.getName()); final Map<String, Pair<String, String>> body = new HashMap<>(); for (int i = 0; i < configuration.parameters.size(); i++) { String value = String.valueOf(parameterValues[i]); if (configuration.urlEncoded.contains(configuration.parameters.get(i))) { value = URLEncoder.encode(value, "UTF-8"); } body.put(configuration.parameters.get(i), new Pair<>("data", value)); } return Observable.create(engineYard.create(configuration, body)); } interface EngineYard { Engine create(CallConfiguration configuration, Map<String, Pair<String, String>> body); } private static class DefaultEngineYard implements EngineYard { @Override public Engine create(CallConfiguration configuration, Map<String, Pair<String, String>> body) { return new Engine(configuration, body); } } }
1,954
0.706244
0.704708
53
35.867924
33.329708
103
false
false
0
0
0
0
0
0
0.811321
false
false
6
f7f2b426f8abeaa655a0a55da26794bd3550cc38
670,014,967,351
781def5964be9b9281d921569e028f161c82155b
/universal-application-tool-0.0.1/app/services/applicant/question/NameQuestion.java
15549c89bb0f10ae11dc18cdcf51560d508c312d
[ "Apache-2.0", "CC0-1.0" ]
permissive
armintalaie/civiform
https://github.com/armintalaie/civiform
d2a0c065a3ca2a56643c52d511ad3a0fcea7d060
a9050b77957852775bcb3d434be7e1eccd2f8ede
refs/heads/main
2023-05-05T19:19:33.672000
2021-05-22T00:13:11
2021-05-22T00:13:11
369,723,865
1
0
Apache-2.0
true
2021-05-22T05:29:51
2021-05-22T05:29:50
2021-05-22T00:13:14
2021-05-22T04:55:51
2,600
0
0
0
null
false
false
package services.applicant.question; import com.google.common.collect.ImmutableSet; import java.util.Arrays; import java.util.Optional; import java.util.stream.Collectors; import services.MessageKey; import services.Path; import services.applicant.ValidationErrorMessage; import services.question.types.NameQuestionDefinition; import services.question.types.QuestionType; public class NameQuestion implements PresentsErrors { private final ApplicantQuestion applicantQuestion; private Optional<String> firstNameValue; private Optional<String> middleNameValue; private Optional<String> lastNameValue; public NameQuestion(ApplicantQuestion applicantQuestion) { this.applicantQuestion = applicantQuestion; assertQuestionType(); } @Override public boolean hasQuestionErrors() { return !getQuestionErrors().isEmpty(); } @Override public ImmutableSet<ValidationErrorMessage> getQuestionErrors() { // TODO: Implement admin-defined validation. return ImmutableSet.of(); } @Override public boolean hasTypeSpecificErrors() { return !getAllTypeSpecificErrors().isEmpty(); } @Override public ImmutableSet<ValidationErrorMessage> getAllTypeSpecificErrors() { return ImmutableSet.<ValidationErrorMessage>builder() .addAll(getFirstNameErrors()) .addAll(getLastNameErrors()) .build(); } public ImmutableSet<ValidationErrorMessage> getFirstNameErrors() { if (isFirstNameAnswered() && getFirstNameValue().isEmpty()) { return ImmutableSet.of( ValidationErrorMessage.create(MessageKey.NAME_VALIDATION_FIRST_REQUIRED)); } return ImmutableSet.of(); } public ImmutableSet<ValidationErrorMessage> getLastNameErrors() { if (isLastNameAnswered() && getLastNameValue().isEmpty()) { return ImmutableSet.of( ValidationErrorMessage.create(MessageKey.NAME_VALIDATION_LAST_REQUIRED)); } return ImmutableSet.of(); } public Optional<String> getFirstNameValue() { if (firstNameValue != null) { return firstNameValue; } firstNameValue = applicantQuestion.getApplicantData().readString(getFirstNamePath()); return firstNameValue; } public Optional<String> getMiddleNameValue() { if (middleNameValue != null) { return middleNameValue; } middleNameValue = applicantQuestion.getApplicantData().readString(getMiddleNamePath()); return middleNameValue; } public Optional<String> getLastNameValue() { if (lastNameValue != null) { return lastNameValue; } lastNameValue = applicantQuestion.getApplicantData().readString(getLastNamePath()); return lastNameValue; } public void assertQuestionType() { if (!applicantQuestion.getType().equals(QuestionType.NAME)) { throw new RuntimeException( String.format( "Question is not a NAME question: %s (type: %s)", applicantQuestion.getQuestionDefinition().getQuestionPathSegment(), applicantQuestion.getQuestionDefinition().getQuestionType())); } } public NameQuestionDefinition getQuestionDefinition() { assertQuestionType(); return (NameQuestionDefinition) applicantQuestion.getQuestionDefinition(); } public Path getFirstNamePath() { return applicantQuestion.getContextualizedPath().join(Scalar.FIRST_NAME); } public Path getMiddleNamePath() { return applicantQuestion.getContextualizedPath().join(Scalar.MIDDLE_NAME); } public Path getLastNamePath() { return applicantQuestion.getContextualizedPath().join(Scalar.LAST_NAME); } private boolean isFirstNameAnswered() { return applicantQuestion.getApplicantData().hasPath(getFirstNamePath()); } private boolean isMiddleNameAnswered() { return applicantQuestion.getApplicantData().hasPath(getMiddleNamePath()); } private boolean isLastNameAnswered() { return applicantQuestion.getApplicantData().hasPath(getLastNamePath()); } /** * Returns true if any one of the name fields is answered. Returns false if all are not answered. */ @Override public boolean isAnswered() { return isFirstNameAnswered() || isMiddleNameAnswered() || isLastNameAnswered(); } @Override public String getAnswerString() { String[] parts = { getFirstNameValue().orElse(""), getMiddleNameValue().orElse(""), getLastNameValue().orElse("") }; return Arrays.stream(parts).filter(part -> part.length() > 0).collect(Collectors.joining(" ")); } }
UTF-8
Java
4,492
java
NameQuestion.java
Java
[]
null
[]
package services.applicant.question; import com.google.common.collect.ImmutableSet; import java.util.Arrays; import java.util.Optional; import java.util.stream.Collectors; import services.MessageKey; import services.Path; import services.applicant.ValidationErrorMessage; import services.question.types.NameQuestionDefinition; import services.question.types.QuestionType; public class NameQuestion implements PresentsErrors { private final ApplicantQuestion applicantQuestion; private Optional<String> firstNameValue; private Optional<String> middleNameValue; private Optional<String> lastNameValue; public NameQuestion(ApplicantQuestion applicantQuestion) { this.applicantQuestion = applicantQuestion; assertQuestionType(); } @Override public boolean hasQuestionErrors() { return !getQuestionErrors().isEmpty(); } @Override public ImmutableSet<ValidationErrorMessage> getQuestionErrors() { // TODO: Implement admin-defined validation. return ImmutableSet.of(); } @Override public boolean hasTypeSpecificErrors() { return !getAllTypeSpecificErrors().isEmpty(); } @Override public ImmutableSet<ValidationErrorMessage> getAllTypeSpecificErrors() { return ImmutableSet.<ValidationErrorMessage>builder() .addAll(getFirstNameErrors()) .addAll(getLastNameErrors()) .build(); } public ImmutableSet<ValidationErrorMessage> getFirstNameErrors() { if (isFirstNameAnswered() && getFirstNameValue().isEmpty()) { return ImmutableSet.of( ValidationErrorMessage.create(MessageKey.NAME_VALIDATION_FIRST_REQUIRED)); } return ImmutableSet.of(); } public ImmutableSet<ValidationErrorMessage> getLastNameErrors() { if (isLastNameAnswered() && getLastNameValue().isEmpty()) { return ImmutableSet.of( ValidationErrorMessage.create(MessageKey.NAME_VALIDATION_LAST_REQUIRED)); } return ImmutableSet.of(); } public Optional<String> getFirstNameValue() { if (firstNameValue != null) { return firstNameValue; } firstNameValue = applicantQuestion.getApplicantData().readString(getFirstNamePath()); return firstNameValue; } public Optional<String> getMiddleNameValue() { if (middleNameValue != null) { return middleNameValue; } middleNameValue = applicantQuestion.getApplicantData().readString(getMiddleNamePath()); return middleNameValue; } public Optional<String> getLastNameValue() { if (lastNameValue != null) { return lastNameValue; } lastNameValue = applicantQuestion.getApplicantData().readString(getLastNamePath()); return lastNameValue; } public void assertQuestionType() { if (!applicantQuestion.getType().equals(QuestionType.NAME)) { throw new RuntimeException( String.format( "Question is not a NAME question: %s (type: %s)", applicantQuestion.getQuestionDefinition().getQuestionPathSegment(), applicantQuestion.getQuestionDefinition().getQuestionType())); } } public NameQuestionDefinition getQuestionDefinition() { assertQuestionType(); return (NameQuestionDefinition) applicantQuestion.getQuestionDefinition(); } public Path getFirstNamePath() { return applicantQuestion.getContextualizedPath().join(Scalar.FIRST_NAME); } public Path getMiddleNamePath() { return applicantQuestion.getContextualizedPath().join(Scalar.MIDDLE_NAME); } public Path getLastNamePath() { return applicantQuestion.getContextualizedPath().join(Scalar.LAST_NAME); } private boolean isFirstNameAnswered() { return applicantQuestion.getApplicantData().hasPath(getFirstNamePath()); } private boolean isMiddleNameAnswered() { return applicantQuestion.getApplicantData().hasPath(getMiddleNamePath()); } private boolean isLastNameAnswered() { return applicantQuestion.getApplicantData().hasPath(getLastNamePath()); } /** * Returns true if any one of the name fields is answered. Returns false if all are not answered. */ @Override public boolean isAnswered() { return isFirstNameAnswered() || isMiddleNameAnswered() || isLastNameAnswered(); } @Override public String getAnswerString() { String[] parts = { getFirstNameValue().orElse(""), getMiddleNameValue().orElse(""), getLastNameValue().orElse("") }; return Arrays.stream(parts).filter(part -> part.length() > 0).collect(Collectors.joining(" ")); } }
4,492
0.729964
0.729742
152
28.552631
28.60548
100
false
false
0
0
0
0
0
0
0.348684
false
false
6
75ada06e45fb4f410056a4ab6a0298eff4c4e48d
30,270,929,561,466
d6c5174f9e974c5b324e3031b780af39e67228a2
/334-Increasing-Triplet-Subsequence/solution.java
5f62051f75ab0075afd8b233cd3d97812d7a8973
[]
no_license
JBrVJxsc/lt
https://github.com/JBrVJxsc/lt
30054b5fe6653de6e9134911afbb3d01a6172c6a
7cfe02a0a3ad63df389d2d6772fb96c8d2c67c40
refs/heads/master
2021-06-05T04:14:01.496000
2016-10-12T03:41:10
2016-10-12T03:41:10
58,743,300
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Solution { public boolean increasingTriplet(int[] nums) { int a = Integer.MAX_VALUE; int b = Integer.MAX_VALUE; for (int i : nums) { if (i <= a) { a = i; } else if (i <= b) { b = i; } else { return true; } } return false; } }
UTF-8
Java
322
java
solution.java
Java
[]
null
[]
public class Solution { public boolean increasingTriplet(int[] nums) { int a = Integer.MAX_VALUE; int b = Integer.MAX_VALUE; for (int i : nums) { if (i <= a) { a = i; } else if (i <= b) { b = i; } else { return true; } } return false; } }
322
0.453416
0.453416
18
16.833334
11.875512
48
false
false
0
0
0
0
0
0
0.333333
false
false
6
52d531dbf6124acedd39c2999eea3837ddfa50b6
21,285,857,967,480
c95ca5eeeb81f492383514d4a54e5f066d2ac08f
/xiaoyaoji-web/src/main/java/cn/com/xiaoyaoji/extension/asynctask/message/MessageNotify.java
c426da47301bc6cd3dcdb5dfaeae5b5946fe0530
[]
no_license
Jsonlu/api
https://github.com/Jsonlu/api
679bc5fa6a54f732d98cadf3c07c0a4cfbcaaa58
a6695c46c5af22be06b4cfcc95286d3181e57b81
refs/heads/master
2021-01-01T19:38:09.510000
2017-07-29T07:25:44
2017-07-29T07:25:44
98,634,690
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.com.xiaoyaoji.extension.asynctask.message; import cn.com.xiaoyaoji.extension.asynctask.ProjectMessage; import cn.com.xiaoyaoji.extension.websocket.WsUtils; /** * @author zhoujingjie * @date 2016-07-26 */ public class MessageNotify { @Message("PROJECT.INVITE") public void projectInviteUser(String projectId,String[] userIds){ System.out.println("project:{},userId:"); } @Message("PROJECT.UPDATE") public void projectUpdate(String projectId,String token){ ProjectMessage message = new ProjectMessage("PROJECT.UPDATE"); message.setProjectId(projectId); message.setToken(token); push(message); } @Message("PROJECT.DELETE") public void projectDelete(String projectId,String token){ ProjectMessage message = new ProjectMessage("PROJECT.DELETE"); message.setProjectId(projectId); message.setToken(token); push(message); } @Message("PROJECT.CREATE") public void projectCreate(String projectId,String token){ ProjectMessage message = new ProjectMessage("PROJECT.CREATE"); message.setProjectId(projectId); message.setToken(token); push(message); } @Message("MODULE.CREATE") public void moduleCreate(String projectId,String moduleId,String token){ ProjectMessage message = new ProjectMessage("MODULE.CREATE"); message.setProjectId(projectId); message.setModuleId(moduleId); message.setToken(token); push(message); } @Message("MODULE.UPDATE") public void moduleUpdate(String projectId,String moduleId,String token){ ProjectMessage message = new ProjectMessage("MODULE.UPDATE"); message.setProjectId(projectId); message.setModuleId(moduleId); message.setToken(token); push(message); } @Message("MODULE.DELETE") public void moduleDelete(String projectId,String moduleId,String token){ ProjectMessage message = new ProjectMessage("MODULE.DELETE"); message.setProjectId(projectId); message.setModuleId(moduleId); message.setToken(token); push(message); } @Message("FOLDER.DELETE") public void folderDelete(String projectId,String folderId,String token){ ProjectMessage message = new ProjectMessage("FOLDER.DELETE"); message.setProjectId(projectId); message.setFolderId(folderId); message.setToken(token); push(message); } @Message("FOLDER.CREATE") public void folderCreate(String projectId,String folderId,String token){ ProjectMessage message = new ProjectMessage("FOLDER.CREATE"); message.setProjectId(projectId); message.setFolderId(folderId); message.setToken(token); push(message); } @Message("FOLDER.UPDATE") public void folderUpdate(String projectId,String folderId,String token){ ProjectMessage message = new ProjectMessage("FOLDER.UPDATE"); message.setProjectId(projectId); message.setFolderId(folderId); message.setToken(token); push(message); } @Message("INTERFACE.CREATE") public void interfaceCreate(String projectId,String interfaceId,String token){ ProjectMessage message = new ProjectMessage("INTERFACE.CREATE"); message.setProjectId(projectId); message.setInterfaceId(interfaceId); message.setToken(token); push(message); } @Message("INTERFACE.DELETE") public void interfaceDelete(String projectId,String interfaceId,String token){ ProjectMessage message = new ProjectMessage("INTERFACE.DELETE"); message.setProjectId(projectId); message.setInterfaceId(interfaceId); message.setToken(token); push(message); } @Message("INTERFACE.UPDATE") public void interfaceUpdate(String projectId,String interfaceId,String token){ ProjectMessage message = new ProjectMessage("INTERFACE.UPDATE"); message.setProjectId(projectId); message.setInterfaceId(interfaceId); message.setToken(token); push(message); } private void push(ProjectMessage message){ WsUtils.pushMessage(message); } }
UTF-8
Java
4,228
java
MessageNotify.java
Java
[ { "context": "yaoji.extension.websocket.WsUtils;\n\n/**\n * @author zhoujingjie\n * @date 2016-07-26\n */\npublic class MessageNotif", "end": 195, "score": 0.9987854957580566, "start": 184, "tag": "USERNAME", "value": "zhoujingjie" } ]
null
[]
package cn.com.xiaoyaoji.extension.asynctask.message; import cn.com.xiaoyaoji.extension.asynctask.ProjectMessage; import cn.com.xiaoyaoji.extension.websocket.WsUtils; /** * @author zhoujingjie * @date 2016-07-26 */ public class MessageNotify { @Message("PROJECT.INVITE") public void projectInviteUser(String projectId,String[] userIds){ System.out.println("project:{},userId:"); } @Message("PROJECT.UPDATE") public void projectUpdate(String projectId,String token){ ProjectMessage message = new ProjectMessage("PROJECT.UPDATE"); message.setProjectId(projectId); message.setToken(token); push(message); } @Message("PROJECT.DELETE") public void projectDelete(String projectId,String token){ ProjectMessage message = new ProjectMessage("PROJECT.DELETE"); message.setProjectId(projectId); message.setToken(token); push(message); } @Message("PROJECT.CREATE") public void projectCreate(String projectId,String token){ ProjectMessage message = new ProjectMessage("PROJECT.CREATE"); message.setProjectId(projectId); message.setToken(token); push(message); } @Message("MODULE.CREATE") public void moduleCreate(String projectId,String moduleId,String token){ ProjectMessage message = new ProjectMessage("MODULE.CREATE"); message.setProjectId(projectId); message.setModuleId(moduleId); message.setToken(token); push(message); } @Message("MODULE.UPDATE") public void moduleUpdate(String projectId,String moduleId,String token){ ProjectMessage message = new ProjectMessage("MODULE.UPDATE"); message.setProjectId(projectId); message.setModuleId(moduleId); message.setToken(token); push(message); } @Message("MODULE.DELETE") public void moduleDelete(String projectId,String moduleId,String token){ ProjectMessage message = new ProjectMessage("MODULE.DELETE"); message.setProjectId(projectId); message.setModuleId(moduleId); message.setToken(token); push(message); } @Message("FOLDER.DELETE") public void folderDelete(String projectId,String folderId,String token){ ProjectMessage message = new ProjectMessage("FOLDER.DELETE"); message.setProjectId(projectId); message.setFolderId(folderId); message.setToken(token); push(message); } @Message("FOLDER.CREATE") public void folderCreate(String projectId,String folderId,String token){ ProjectMessage message = new ProjectMessage("FOLDER.CREATE"); message.setProjectId(projectId); message.setFolderId(folderId); message.setToken(token); push(message); } @Message("FOLDER.UPDATE") public void folderUpdate(String projectId,String folderId,String token){ ProjectMessage message = new ProjectMessage("FOLDER.UPDATE"); message.setProjectId(projectId); message.setFolderId(folderId); message.setToken(token); push(message); } @Message("INTERFACE.CREATE") public void interfaceCreate(String projectId,String interfaceId,String token){ ProjectMessage message = new ProjectMessage("INTERFACE.CREATE"); message.setProjectId(projectId); message.setInterfaceId(interfaceId); message.setToken(token); push(message); } @Message("INTERFACE.DELETE") public void interfaceDelete(String projectId,String interfaceId,String token){ ProjectMessage message = new ProjectMessage("INTERFACE.DELETE"); message.setProjectId(projectId); message.setInterfaceId(interfaceId); message.setToken(token); push(message); } @Message("INTERFACE.UPDATE") public void interfaceUpdate(String projectId,String interfaceId,String token){ ProjectMessage message = new ProjectMessage("INTERFACE.UPDATE"); message.setProjectId(projectId); message.setInterfaceId(interfaceId); message.setToken(token); push(message); } private void push(ProjectMessage message){ WsUtils.pushMessage(message); } }
4,228
0.684957
0.683065
114
36.087719
23.220741
82
false
false
0
0
0
0
0
0
0.745614
false
false
6
979739d978a55467cf21a08267889cdeb5b29a79
26,010,322,010,064
0d6118d90f48e8be6f4565416eb8a4da59f4f49c
/src/main/java/com/mak/corejava/seven/inheritancee/OverRidingDemo.java
845c486753880b096bbf899ca008ed88ca2b3386
[]
no_license
MateenKhan/corejava
https://github.com/MateenKhan/corejava
a0d44dcbe9ffe6336e301a1328c1ab7b0a07e4f2
750ad09945ea4a1aa6f4b192373c13ba383691b2
refs/heads/master
2021-01-01T06:44:16.151000
2017-07-19T17:58:29
2017-07-19T17:58:29
97,501,013
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mak.corejava.seven.inheritancee; public class OverRidingDemo { public static void main(String[] args) { // TODO Auto-generated method stub Machine machine = new Machine(); System.out.println("Machine color:"+machine.color); machine.consumpEclectricity(); Machine refrigirator = new Refrigirator(); System.out.println("Refrigirator color:"+refrigirator.color); refrigirator.consumpEclectricity(); // Refrigirator refrigirator = new Refrigirator(); // refrigirator.consumpEclectricity(); } } class Machine{ String color="black"; int units=20; public void consumpEclectricity(){ System.out.println("Machine Consumption electricity:"+units); } } class Refrigirator extends Machine{ int units=50; @Override public void consumpEclectricity(){ System.out.println("Refrigirator Consumption electricity:"+units); } }
UTF-8
Java
861
java
OverRidingDemo.java
Java
[]
null
[]
package com.mak.corejava.seven.inheritancee; public class OverRidingDemo { public static void main(String[] args) { // TODO Auto-generated method stub Machine machine = new Machine(); System.out.println("Machine color:"+machine.color); machine.consumpEclectricity(); Machine refrigirator = new Refrigirator(); System.out.println("Refrigirator color:"+refrigirator.color); refrigirator.consumpEclectricity(); // Refrigirator refrigirator = new Refrigirator(); // refrigirator.consumpEclectricity(); } } class Machine{ String color="black"; int units=20; public void consumpEclectricity(){ System.out.println("Machine Consumption electricity:"+units); } } class Refrigirator extends Machine{ int units=50; @Override public void consumpEclectricity(){ System.out.println("Refrigirator Consumption electricity:"+units); } }
861
0.749129
0.744483
36
22.944445
21.50445
68
false
false
0
0
0
0
0
0
1.388889
false
false
6
93c26e2ba28bd7a8ed9e91a6397f0e5a76db0a7d
24,472,723,706,213
ee731d0acfb6dc9465d6842245ba91a02ef93fcc
/jdbc/src/com/sample/bookstore/dao/OrderDAO.java
479582a4e94624a7fc869b44e105e5b1a9690203
[]
no_license
siwolsmu89/J_HTA_java_workspace
https://github.com/siwolsmu89/J_HTA_java_workspace
6a668c421c5ada7b792be0ee0a94b3232bd109ca
43b0bae8e5b7cb68513d8670b136f098d7b8a4e1
refs/heads/master
2022-11-18T17:23:29.458000
2020-07-20T08:57:02
2020-07-20T08:57:02
258,408,262
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sample.bookstore.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import com.sample.bookstore.util.ConnectionUtil; import com.sample.bookstore.util.QueryUtil; import com.sample.bookstore.vo.Book; import com.sample.bookstore.vo.Order; import com.sample.bookstore.vo.User; public class OrderDAO { private Order resultSetToOrder(ResultSet rs) throws Exception { Order order = new Order(); User user = new User(); Book book = new Book(); user.setId(rs.getString("user_id")); user.setPassword(rs.getString("user_password")); user.setName(rs.getString("user_name")); user.setEmail(rs.getString("user_email")); user.setPoint(rs.getInt("user_point")); user.setRegisterdDate(rs.getDate("user_registered_date")); book.setNo(rs.getInt("book_no")); book.setTitle(rs.getString("book_title")); book.setWriter(rs.getString("book_writer")); book.setGenre(rs.getString("book_genre")); book.setPublisher(rs.getString("book_publisher")); book.setPrice(rs.getInt("book_price")); book.setDiscountPrice(rs.getInt("book_discount_price")); book.setStock(rs.getInt("book_stock")); book.setRegisteredDate(rs.getDate("book_registered_date")); order.setOrderNo(rs.getInt("order_no")); order.setUser(user); order.setBook(book); order.setPrice(rs.getInt("order_price")); order.setAmount(rs.getInt("order_amount")); order.setRegistredDate(rs.getDate("order_registered_date")); return order; } public void addOrder(Order order) throws Exception { Connection connection = ConnectionUtil.getConnection(); PreparedStatement pstmt = connection.prepareStatement(QueryUtil.getSQL("order.addOrder")); User user = order.getUser(); Book book = order.getBook(); pstmt.setString(1, user.getId()); pstmt.setInt(2, book.getNo()); pstmt.setInt(3, order.getPrice()); pstmt.setInt(4, order.getAmount()); pstmt.executeUpdate(); pstmt.close(); connection.close(); } public List<Order> getOrdersByUserId(String userId) throws Exception { List<Order> orders = new ArrayList<Order>(); Connection connection = ConnectionUtil.getConnection(); PreparedStatement pstmt = connection.prepareStatement(QueryUtil.getSQL("order.getOrdersByUserId")); pstmt.setString(1, userId); ResultSet rs = pstmt.executeQuery(); while(rs.next()) { orders.add(resultSetToOrder(rs)); } return orders; } public Order getOrderByNo(int orderNo) throws Exception { Order order = null; Connection connection = ConnectionUtil.getConnection(); PreparedStatement pstmt = connection.prepareStatement(QueryUtil.getSQL("order.getOrderByNo")); pstmt.setInt(1, orderNo); ResultSet rs = pstmt.executeQuery(); if (rs.next()) { order = resultSetToOrder(rs); } return order; } }
UTF-8
Java
2,870
java
OrderDAO.java
Java
[]
null
[]
package com.sample.bookstore.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import com.sample.bookstore.util.ConnectionUtil; import com.sample.bookstore.util.QueryUtil; import com.sample.bookstore.vo.Book; import com.sample.bookstore.vo.Order; import com.sample.bookstore.vo.User; public class OrderDAO { private Order resultSetToOrder(ResultSet rs) throws Exception { Order order = new Order(); User user = new User(); Book book = new Book(); user.setId(rs.getString("user_id")); user.setPassword(rs.getString("user_password")); user.setName(rs.getString("user_name")); user.setEmail(rs.getString("user_email")); user.setPoint(rs.getInt("user_point")); user.setRegisterdDate(rs.getDate("user_registered_date")); book.setNo(rs.getInt("book_no")); book.setTitle(rs.getString("book_title")); book.setWriter(rs.getString("book_writer")); book.setGenre(rs.getString("book_genre")); book.setPublisher(rs.getString("book_publisher")); book.setPrice(rs.getInt("book_price")); book.setDiscountPrice(rs.getInt("book_discount_price")); book.setStock(rs.getInt("book_stock")); book.setRegisteredDate(rs.getDate("book_registered_date")); order.setOrderNo(rs.getInt("order_no")); order.setUser(user); order.setBook(book); order.setPrice(rs.getInt("order_price")); order.setAmount(rs.getInt("order_amount")); order.setRegistredDate(rs.getDate("order_registered_date")); return order; } public void addOrder(Order order) throws Exception { Connection connection = ConnectionUtil.getConnection(); PreparedStatement pstmt = connection.prepareStatement(QueryUtil.getSQL("order.addOrder")); User user = order.getUser(); Book book = order.getBook(); pstmt.setString(1, user.getId()); pstmt.setInt(2, book.getNo()); pstmt.setInt(3, order.getPrice()); pstmt.setInt(4, order.getAmount()); pstmt.executeUpdate(); pstmt.close(); connection.close(); } public List<Order> getOrdersByUserId(String userId) throws Exception { List<Order> orders = new ArrayList<Order>(); Connection connection = ConnectionUtil.getConnection(); PreparedStatement pstmt = connection.prepareStatement(QueryUtil.getSQL("order.getOrdersByUserId")); pstmt.setString(1, userId); ResultSet rs = pstmt.executeQuery(); while(rs.next()) { orders.add(resultSetToOrder(rs)); } return orders; } public Order getOrderByNo(int orderNo) throws Exception { Order order = null; Connection connection = ConnectionUtil.getConnection(); PreparedStatement pstmt = connection.prepareStatement(QueryUtil.getSQL("order.getOrderByNo")); pstmt.setInt(1, orderNo); ResultSet rs = pstmt.executeQuery(); if (rs.next()) { order = resultSetToOrder(rs); } return order; } }
2,870
0.724739
0.722648
99
27.989899
23.248545
101
false
false
0
0
0
0
0
0
2.222222
false
false
6
59c838f4c51354eade8ebf876902d67045bf598b
12,360,915,931,805
a80b6708361fe152425874cc9694a17ebd28bd05
/src/main/java/com/ast/airlinesystem/controller/reservationServlet.java
70e2a0ea5c3ae79210e1af9b5049095599947e53
[]
no_license
Gairaud/LAB-01-Moviles
https://github.com/Gairaud/LAB-01-Moviles
c2e010a43bfaab66061804826d7b9e56457150f7
8f8a1753030d6474c3eac300c3e8080c5455798f
refs/heads/main
2023-06-08T02:19:57.424000
2021-07-02T10:07:36
2021-07-02T10:07:36
353,820,764
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ast.airlinesystem.controller; import java.io.*; import java.sql.SQLException; import java.util.List; import com.ast.airlinesystem.logic.Model; import com.ast.airlinesystem.logic.Reservation; import com.ast.airlinesystem.logic.User; import jakarta.servlet.http.*; import com.google.gson.*; public class reservationServlet extends HttpServlet{ private String message; private final Gson gsonObject = new Gson(); protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { //String action = request.getParameter("action"); switch (request.getServletPath()) { case "/get-reservations":{ try { BufferedReader reader = request.getReader(); User user = gsonObject.fromJson(reader, User.class); List<Reservation> reservationsList = Model.instance().getReservationsByUser(String.valueOf(user.getId())); String reservations = gsonObject.toJson(reservationsList); PrintWriter out = response.getWriter(); out.print(reservations); out.flush(); } catch (Exception e) { e.printStackTrace(); break; } break; } case "/add-reservation":{ try{ Reservation res = new Reservation(); res.setId(Integer.parseInt(request.getParameter("id"))); res.setSeatQuantity(Integer.parseInt(request.getParameter("seatQuantity"))); res.setTotalPrice(Float.parseFloat(request.getParameter("totalPrice"))); res.setUser(Model.instance().getUserById(request.getParameter("userid"))); Model.instance().addReservation(res); }catch (Exception e){ e.printStackTrace(); } break; } } } }
UTF-8
Java
2,063
java
reservationServlet.java
Java
[]
null
[]
package com.ast.airlinesystem.controller; import java.io.*; import java.sql.SQLException; import java.util.List; import com.ast.airlinesystem.logic.Model; import com.ast.airlinesystem.logic.Reservation; import com.ast.airlinesystem.logic.User; import jakarta.servlet.http.*; import com.google.gson.*; public class reservationServlet extends HttpServlet{ private String message; private final Gson gsonObject = new Gson(); protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { //String action = request.getParameter("action"); switch (request.getServletPath()) { case "/get-reservations":{ try { BufferedReader reader = request.getReader(); User user = gsonObject.fromJson(reader, User.class); List<Reservation> reservationsList = Model.instance().getReservationsByUser(String.valueOf(user.getId())); String reservations = gsonObject.toJson(reservationsList); PrintWriter out = response.getWriter(); out.print(reservations); out.flush(); } catch (Exception e) { e.printStackTrace(); break; } break; } case "/add-reservation":{ try{ Reservation res = new Reservation(); res.setId(Integer.parseInt(request.getParameter("id"))); res.setSeatQuantity(Integer.parseInt(request.getParameter("seatQuantity"))); res.setTotalPrice(Float.parseFloat(request.getParameter("totalPrice"))); res.setUser(Model.instance().getUserById(request.getParameter("userid"))); Model.instance().addReservation(res); }catch (Exception e){ e.printStackTrace(); } break; } } } }
2,063
0.569074
0.569074
63
31.746031
30.157244
126
false
false
0
0
0
0
0
0
0.507937
false
false
6
f20bd775a2540f782b2f706713c592ec245a0203
26,285,199,917,681
dfdcfcdc688f14585079991d7be7ffe74eb5648b
/src/project9.java
0f53063aa6a10f1f08d2d9fe2d1f6ccfd8fc00f7
[]
no_license
chaoxing0910/project2
https://github.com/chaoxing0910/project2
70f652036aab067c7c8cccc9cdd4d235e2c8d8f2
25c5b1eacc8294334b648dad2dfe774c50334102
refs/heads/master
2022-12-26T20:09:18.816000
2020-10-04T14:12:25
2020-10-04T14:12:25
301,146,034
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Scanner; public class project9 { public static void main(String[] args) { // 3.25¼¸ºÎ£º½»µã double x1, y1, x2, y2, x3, y3, x4, y4; double a, b, c, d, e, f, x, y, fenmu; System.out.print("Enter x1, y1, x2, y2, x3, y3, x4, y4: "); Scanner input = new Scanner(System.in); x1=input.nextDouble(); y1=input.nextDouble();x2=input.nextDouble(); y2=input.nextDouble(); x3=input.nextDouble(); y3=input.nextDouble();x4=input.nextDouble(); y4=input.nextDouble(); a=y1-y2; b =x2-x1; c=y3-y4; d =x4-x3; e=(y1-y2)*x1-(x1-x2)*y1; f=(y3-y4)*x3-(x3-x4)*y3; fenmu=a*d-b*c; if(fenmu != 0) { x=(e*d-b*f)/fenmu; y=(a*f-e*c)/fenmu; System.out.println("The intersecting point is at(" +x+", "+y+")"); } else System.out.println("The two lines are parallel"); } }
WINDOWS-1252
Java
857
java
project9.java
Java
[]
null
[]
import java.util.Scanner; public class project9 { public static void main(String[] args) { // 3.25¼¸ºÎ£º½»µã double x1, y1, x2, y2, x3, y3, x4, y4; double a, b, c, d, e, f, x, y, fenmu; System.out.print("Enter x1, y1, x2, y2, x3, y3, x4, y4: "); Scanner input = new Scanner(System.in); x1=input.nextDouble(); y1=input.nextDouble();x2=input.nextDouble(); y2=input.nextDouble(); x3=input.nextDouble(); y3=input.nextDouble();x4=input.nextDouble(); y4=input.nextDouble(); a=y1-y2; b =x2-x1; c=y3-y4; d =x4-x3; e=(y1-y2)*x1-(x1-x2)*y1; f=(y3-y4)*x3-(x3-x4)*y3; fenmu=a*d-b*c; if(fenmu != 0) { x=(e*d-b*f)/fenmu; y=(a*f-e*c)/fenmu; System.out.println("The intersecting point is at(" +x+", "+y+")"); } else System.out.println("The two lines are parallel"); } }
857
0.577332
0.517119
32
24.46875
25.356194
92
false
false
0
0
0
0
0
0
3.15625
false
false
6
3542daf4e4223c644eae6a39ce309df165046639
19,842,748,971,197
e9c68e4a460d5506fa6c5c4adf294843c47bda9b
/src/main/java/nz/co/example/admin-app/domain/logic/CircuitSubComponentSorter.java
53e74fc27ba02c2fe89d15d0a29a0a1cb15f61f5
[ "Apache-2.0" ]
permissive
nick-manasys/admin-webapp
https://github.com/nick-manasys/admin-webapp
dc66e5a7d0f13d6a34f1605fe1a2a22ce2b022bf
bc5ed3ba7edf41667ae22460ac81e264883181a6
refs/heads/master
2021-01-01T04:52:02.415000
2016-05-22T22:46:00
2016-05-22T22:46:00
59,436,971
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package nz.co.example.dev.domain.logic; import java.util.List; import nz.co.example.dev.domain.model.Circuit; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * Capable of sorting all of the circuit subcomponents to match them up into circuits. * * Is injected with a list of actual @see {@link CircuitSubcomponentMatcher} implementations * which do the actual matching of the various subcomponents into full circuits. * * The function of this class is to facilitate the matching and produce one single list of all circuits * and the left over subcomponents that could not be matched. * * @author nivanov */ @Service public class CircuitSubComponentSorter { @Autowired private List<CircuitSubcomponentMatcher<Circuit>> circuitSubcomponentMatchers; public SortedCircuitResult<Circuit> getSortedCircuits(CircuitSubComponents circuitSubComponents) { SortedCircuitResult<Circuit> matchedSubComponents = null; for (CircuitSubcomponentMatcher<Circuit> subcomponentMatcher : circuitSubcomponentMatchers) { if (matchedSubComponents == null) { matchedSubComponents = subcomponentMatcher.matchSubComponents(circuitSubComponents); } else { SortedCircuitResult<Circuit> typedMatchedSubComponents = subcomponentMatcher.matchSubComponents(matchedSubComponents.getUnsortedSubComponents()); matchedSubComponents.addSortedCircuits(typedMatchedSubComponents.getSortedCircuits()); matchedSubComponents.setUnsortedSubComponents(typedMatchedSubComponents.getUnsortedSubComponents()); } } return matchedSubComponents; } }
UTF-8
Java
1,802
java
CircuitSubComponentSorter.java
Java
[ { "context": "mponents that could not be matched.\n * \n * @author nivanov\n */\n@Service\npublic class CircuitSubComponentSort", "end": 697, "score": 0.9991922378540039, "start": 690, "tag": "USERNAME", "value": "nivanov" } ]
null
[]
/** * */ package nz.co.example.dev.domain.logic; import java.util.List; import nz.co.example.dev.domain.model.Circuit; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * Capable of sorting all of the circuit subcomponents to match them up into circuits. * * Is injected with a list of actual @see {@link CircuitSubcomponentMatcher} implementations * which do the actual matching of the various subcomponents into full circuits. * * The function of this class is to facilitate the matching and produce one single list of all circuits * and the left over subcomponents that could not be matched. * * @author nivanov */ @Service public class CircuitSubComponentSorter { @Autowired private List<CircuitSubcomponentMatcher<Circuit>> circuitSubcomponentMatchers; public SortedCircuitResult<Circuit> getSortedCircuits(CircuitSubComponents circuitSubComponents) { SortedCircuitResult<Circuit> matchedSubComponents = null; for (CircuitSubcomponentMatcher<Circuit> subcomponentMatcher : circuitSubcomponentMatchers) { if (matchedSubComponents == null) { matchedSubComponents = subcomponentMatcher.matchSubComponents(circuitSubComponents); } else { SortedCircuitResult<Circuit> typedMatchedSubComponents = subcomponentMatcher.matchSubComponents(matchedSubComponents.getUnsortedSubComponents()); matchedSubComponents.addSortedCircuits(typedMatchedSubComponents.getSortedCircuits()); matchedSubComponents.setUnsortedSubComponents(typedMatchedSubComponents.getUnsortedSubComponents()); } } return matchedSubComponents; } }
1,802
0.73141
0.73141
48
36.541668
41.112629
161
false
false
0
0
0
0
0
0
0.25
false
false
6
49699e1f24f00a57d8db4285146bc3209abce7db
19,842,748,971,567
2b570d248063c1f54aef12cc97c7cab66bc15523
/src/boxes/GameUtils.java
3826daea948f89537cafc5d9938659d9fbfe27ed
[]
no_license
HugoRattovski/j2Dge
https://github.com/HugoRattovski/j2Dge
de7f126f1235852db62eb3e794c66e5f16d65c76
2a71eea29d9c950ec2ad4147fcf8cb64496636f6
refs/heads/master
2020-06-02T10:34:29.956000
2014-01-28T20:11:11
2014-01-28T20:11:11
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package boxes; import com.thoughtworks.xstream.XStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import static org.lwjgl.opengl.GL11.*; import org.newdawn.slick.opengl.Texture; import org.newdawn.slick.opengl.TextureLoader; public class GameUtils { public static <T> T loadObjectFromXmlFile(T object, String filename) { XStream xstream = new XStream(); // do NOT serialize these attributes xstream.omitField(FrameSequence.class, "singleFrameFraction"); try (FileInputStream fs = new FileInputStream(filename)) { return (T) xstream.fromXML(fs); } catch (FileNotFoundException ex) { System.out.println("Error while loading '" + filename + "'. " + ex.toString()); return null; } catch (IOException ex) { System.out.println("Error while loading '" + filename + "'. " + ex.toString()); return null; } } public static <T> void writeObjectToXmlFile(T object, String filename) { XStream xstream = new XStream(); // do NOT serialize these attributes xstream.omitField(FrameSequence.class, "singleFrameFraction"); try (FileOutputStream fs = new FileOutputStream(filename)) { xstream.toXML(object, fs); } catch (FileNotFoundException ex) { System.out.println("Error while writing '" + filename + "'. " + ex.toString()); } catch (IOException ex) { System.out.println("Error while writing '" + filename + "'. " + ex.toString()); } } public static Texture loadTexturePng(String filename) { try (FileInputStream fs = new FileInputStream(filename)) { return TextureLoader.getTexture("PNG", fs, GL_LINEAR); } catch (FileNotFoundException ex) { System.out.println("Error while loading texture '" + filename + "'. " + ex.toString()); return null; } catch (IOException ex) { System.out.println("Error while loading texture '" + filename + "'. " + ex.toString()); return null; } } }
UTF-8
Java
2,296
java
GameUtils.java
Java
[]
null
[]
package boxes; import com.thoughtworks.xstream.XStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import static org.lwjgl.opengl.GL11.*; import org.newdawn.slick.opengl.Texture; import org.newdawn.slick.opengl.TextureLoader; public class GameUtils { public static <T> T loadObjectFromXmlFile(T object, String filename) { XStream xstream = new XStream(); // do NOT serialize these attributes xstream.omitField(FrameSequence.class, "singleFrameFraction"); try (FileInputStream fs = new FileInputStream(filename)) { return (T) xstream.fromXML(fs); } catch (FileNotFoundException ex) { System.out.println("Error while loading '" + filename + "'. " + ex.toString()); return null; } catch (IOException ex) { System.out.println("Error while loading '" + filename + "'. " + ex.toString()); return null; } } public static <T> void writeObjectToXmlFile(T object, String filename) { XStream xstream = new XStream(); // do NOT serialize these attributes xstream.omitField(FrameSequence.class, "singleFrameFraction"); try (FileOutputStream fs = new FileOutputStream(filename)) { xstream.toXML(object, fs); } catch (FileNotFoundException ex) { System.out.println("Error while writing '" + filename + "'. " + ex.toString()); } catch (IOException ex) { System.out.println("Error while writing '" + filename + "'. " + ex.toString()); } } public static Texture loadTexturePng(String filename) { try (FileInputStream fs = new FileInputStream(filename)) { return TextureLoader.getTexture("PNG", fs, GL_LINEAR); } catch (FileNotFoundException ex) { System.out.println("Error while loading texture '" + filename + "'. " + ex.toString()); return null; } catch (IOException ex) { System.out.println("Error while loading texture '" + filename + "'. " + ex.toString()); return null; } } }
2,296
0.600174
0.599303
63
34.444443
29.184566
99
false
false
0
0
0
0
0
0
0.52381
false
false
6
d4c1a27fafc279120e603b231a13f50bfefe8569
27,401,891,403,714
71f55c3abda19a5c0356fd87a7d9b22583bcfa1c
/bundles/scripting/sightly/engine/src/main/java/org/apache/sling/scripting/sightly/impl/engine/compiled/SourceIdentifier.java
62a3a4be8337cebba6f82493b7ce65afde9d4599
[ "MIT", "Apache-2.0", "JSON" ]
permissive
chetanmeh/sling
https://github.com/chetanmeh/sling
4a7dcccd4eb75eeefa3ca8d7798107f8508fbf69
c738beabb6eb0d49c9bcfccaf277f4b52290ba44
refs/heads/trunk
2020-04-05T22:54:22.955000
2016-10-08T10:22:02
2016-10-08T10:22:02
4,012,092
0
1
null
true
2014-02-04T07:33:07
2012-04-13T04:00:31
2013-09-27T13:15:29
2013-09-27T13:15:05
26,497
3
1
1
Java
null
null
/******************************************************************************* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. ******************************************************************************/ package org.apache.sling.scripting.sightly.impl.engine.compiled; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; import org.apache.sling.api.resource.Resource; import org.apache.sling.scripting.sightly.impl.engine.SightlyEngineConfiguration; import org.apache.sling.scripting.sightly.java.compiler.ClassInfo; import org.apache.sling.scripting.sightly.java.compiler.JavaEscapeUtils; /** * Identifies a Java source file based on a {@link Resource}. Depending on the used constructor this class might provide the abstraction * for either a Java source file generated for a HTL script or for a HTL {@link Resource}-based Java Use-API Object. */ public class SourceIdentifier implements ClassInfo { public static final Pattern MANGLED_CHAR_PATTER = Pattern.compile("(.*)(__[0-9a-f]{4}__)(.*)"); private SightlyEngineConfiguration engineConfiguration; private String scriptName; private String simpleClassName; private String packageName; private String fullyQualifiedClassName; public SourceIdentifier(SightlyEngineConfiguration engineConfiguration, String scriptName) { this.engineConfiguration = engineConfiguration; this.scriptName = scriptName; } @Override public String getSimpleClassName() { if (simpleClassName == null) { int lastSlashIndex = scriptName.lastIndexOf("/"); String processingScriptName = scriptName; if (scriptName.endsWith(".java")) { processingScriptName = scriptName.substring(0, scriptName.length() - 5); } if (lastSlashIndex != -1) { simpleClassName = JavaEscapeUtils.makeJavaPackage(processingScriptName.substring(lastSlashIndex)); } else { simpleClassName = JavaEscapeUtils.makeJavaPackage(processingScriptName); } } return simpleClassName; } @Override public String getPackageName() { if (packageName == null) { int lastSlashIndex = scriptName.lastIndexOf("/"); String processingScriptName = scriptName; boolean javaFile = scriptName.endsWith(".java"); if (javaFile) { processingScriptName = scriptName.substring(0, scriptName.length() - 5); } if (lastSlashIndex != -1) { packageName = JavaEscapeUtils.makeJavaPackage(processingScriptName.substring(0, lastSlashIndex)); } else { packageName = JavaEscapeUtils.makeJavaPackage(processingScriptName); } if (!javaFile) { packageName = engineConfiguration.getBundleSymbolicName() + "." + packageName; } } return packageName; } @Override public String getFullyQualifiedClassName() { if (fullyQualifiedClassName == null) { fullyQualifiedClassName = getPackageName() + "." + getSimpleClassName(); } return fullyQualifiedClassName; } public static String getScriptName(String slashSubpackage, String fullyQualifiedClassName) { String className = fullyQualifiedClassName; StringBuilder pathElements = new StringBuilder("/"); if (StringUtils.isNotEmpty(slashSubpackage) && className.contains(slashSubpackage)) { className = className.replaceAll(slashSubpackage + "\\.", ""); } String[] classElements = StringUtils.split(className, '.'); for (int i = 0; i < classElements.length; i++) { String classElem = classElements[i]; Matcher matcher = MANGLED_CHAR_PATTER.matcher(classElem); if (matcher.matches()) { String group = matcher.group(2); char unmangled = JavaEscapeUtils.unmangle(group); classElem = classElem.replaceAll(group, Character.toString(unmangled)); while (matcher.find()) { group = matcher.group(2); unmangled = JavaEscapeUtils.unmangle(group); classElem = classElem.replaceAll(group, Character.toString(unmangled)); } } else { int underscoreIndex = classElem.indexOf('_'); if (underscoreIndex > -1) { if (underscoreIndex == classElem.length() - 1) { classElem = classElem.substring(0, classElem.length() -1); } else { classElem = classElem.replaceAll("_", "."); } } } pathElements.append(classElem); if (i < classElements.length - 1) { pathElements.append("/"); } } return pathElements.toString(); } }
UTF-8
Java
5,791
java
SourceIdentifier.java
Java
[]
null
[]
/******************************************************************************* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. ******************************************************************************/ package org.apache.sling.scripting.sightly.impl.engine.compiled; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; import org.apache.sling.api.resource.Resource; import org.apache.sling.scripting.sightly.impl.engine.SightlyEngineConfiguration; import org.apache.sling.scripting.sightly.java.compiler.ClassInfo; import org.apache.sling.scripting.sightly.java.compiler.JavaEscapeUtils; /** * Identifies a Java source file based on a {@link Resource}. Depending on the used constructor this class might provide the abstraction * for either a Java source file generated for a HTL script or for a HTL {@link Resource}-based Java Use-API Object. */ public class SourceIdentifier implements ClassInfo { public static final Pattern MANGLED_CHAR_PATTER = Pattern.compile("(.*)(__[0-9a-f]{4}__)(.*)"); private SightlyEngineConfiguration engineConfiguration; private String scriptName; private String simpleClassName; private String packageName; private String fullyQualifiedClassName; public SourceIdentifier(SightlyEngineConfiguration engineConfiguration, String scriptName) { this.engineConfiguration = engineConfiguration; this.scriptName = scriptName; } @Override public String getSimpleClassName() { if (simpleClassName == null) { int lastSlashIndex = scriptName.lastIndexOf("/"); String processingScriptName = scriptName; if (scriptName.endsWith(".java")) { processingScriptName = scriptName.substring(0, scriptName.length() - 5); } if (lastSlashIndex != -1) { simpleClassName = JavaEscapeUtils.makeJavaPackage(processingScriptName.substring(lastSlashIndex)); } else { simpleClassName = JavaEscapeUtils.makeJavaPackage(processingScriptName); } } return simpleClassName; } @Override public String getPackageName() { if (packageName == null) { int lastSlashIndex = scriptName.lastIndexOf("/"); String processingScriptName = scriptName; boolean javaFile = scriptName.endsWith(".java"); if (javaFile) { processingScriptName = scriptName.substring(0, scriptName.length() - 5); } if (lastSlashIndex != -1) { packageName = JavaEscapeUtils.makeJavaPackage(processingScriptName.substring(0, lastSlashIndex)); } else { packageName = JavaEscapeUtils.makeJavaPackage(processingScriptName); } if (!javaFile) { packageName = engineConfiguration.getBundleSymbolicName() + "." + packageName; } } return packageName; } @Override public String getFullyQualifiedClassName() { if (fullyQualifiedClassName == null) { fullyQualifiedClassName = getPackageName() + "." + getSimpleClassName(); } return fullyQualifiedClassName; } public static String getScriptName(String slashSubpackage, String fullyQualifiedClassName) { String className = fullyQualifiedClassName; StringBuilder pathElements = new StringBuilder("/"); if (StringUtils.isNotEmpty(slashSubpackage) && className.contains(slashSubpackage)) { className = className.replaceAll(slashSubpackage + "\\.", ""); } String[] classElements = StringUtils.split(className, '.'); for (int i = 0; i < classElements.length; i++) { String classElem = classElements[i]; Matcher matcher = MANGLED_CHAR_PATTER.matcher(classElem); if (matcher.matches()) { String group = matcher.group(2); char unmangled = JavaEscapeUtils.unmangle(group); classElem = classElem.replaceAll(group, Character.toString(unmangled)); while (matcher.find()) { group = matcher.group(2); unmangled = JavaEscapeUtils.unmangle(group); classElem = classElem.replaceAll(group, Character.toString(unmangled)); } } else { int underscoreIndex = classElem.indexOf('_'); if (underscoreIndex > -1) { if (underscoreIndex == classElem.length() - 1) { classElem = classElem.substring(0, classElem.length() -1); } else { classElem = classElem.replaceAll("_", "."); } } } pathElements.append(classElem); if (i < classElements.length - 1) { pathElements.append("/"); } } return pathElements.toString(); } }
5,791
0.621827
0.618028
132
42.871212
30.886009
136
false
false
0
0
0
0
0
0
0.515152
false
false
6
b5b5f6a75e5bbacc4a8f855576a2b36c4f33cc5b
1,778,116,521,298
9fc5f55af715c4901408a71c2333deaf83825941
/src/Audit.java
6b0fb6072e5127566582c87d0306c9de82048cba
[]
no_license
hellodrf/MoralMachine
https://github.com/hellodrf/MoralMachine
0bb28cf4c37e7fea33555502dc96df6caf95f7df
a6991a8d77a064e4bd5b8a6a97be5dc8a06a3306
refs/heads/master
2022-11-28T18:03:56.221000
2020-08-07T03:12:37
2020-08-07T03:12:37
282,394,300
3
2
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Moral Machine: Audit.java * manages audit sessions. * * ©Runfeng Du */ import ethicalengine.*; import ethicalengine.Character; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintWriter; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.Scanner; public class Audit { private String auditType = "Unspecified"; private final HashMap<String, int[]> statisticsDatabase = new HashMap<>(); private int runCount = 0; private int surviveCount = 0; private double ageSum = 0.0; private ArrayList<Scenario> scenarioBuffer; // a public scanner public static Scanner scannerObject = new Scanner(System.in); /** * Empty constructor */ public Audit() {} /** * Constructor with scenarios specified * @param scenarioSet set of scenarios to be run */ public Audit(ArrayList<Scenario> scenarioSet) { scenarioBuffer = scenarioSet; } /** * Manually load scenarios into audit * @param scenarioSet set of scenarios to be run */ public void loadScenarios (ArrayList<Scenario> scenarioSet) { scenarioBuffer = scenarioSet; } /** * run audit by randomly generated scenarios. * @param runs number of audit to be run */ public void run(int runs) { ScenarioGenerator generator = new ScenarioGenerator(); for (int i = 0; i < runs ; i++) { Scenario scenario = generator.generate(); EthicalEngine.Decision result = EthicalEngine.decide(scenario); this.updateStatistics(scenario, result); runCount += 1; } } /** * Run audit by imported scenarios. */ public void run() { for (Scenario s: scenarioBuffer) { EthicalEngine.Decision result = EthicalEngine.decide(s); this.updateStatistics(s, result); runCount += 1; } } /** * Run audit in interactive mode */ public void interactiveRun() { for (Scenario s: scenarioBuffer) { EthicalEngine.Decision decision = EthicalEngine.Decision.PASSENGERS; boolean decisionMade = false; System.out.print(s.toString()); while (!decisionMade){ System.out.println(); System.out.println("Who should be saved? (passenger(s) [1] or pedestrian(s) [2])"); switch (scannerObject.nextLine()) { case "passenger", "passengers", "1" -> { decision = EthicalEngine.Decision.PASSENGERS; decisionMade = true; } case "pedestrian", "pedestrians", "2" -> { decision = EthicalEngine.Decision.PEDESTRIANS; decisionMade = true; } default -> System.out.print("Invalid response. "); } } this.updateStatistics(s, decision); runCount += 1; } // clear buffer scenarioBuffer = new ArrayList<>(); } /** * get audit type * @return the audit type */ public String getAuditType() { return auditType; } /** * Set audit type * @param auditType the audit type */ public void setAuditType(String auditType) { this.auditType = auditType; } private void updateStatistics(Scenario scenario, EthicalEngine.Decision decision) { ArrayList<Character> survivors = (decision == EthicalEngine.Decision.PASSENGERS) ? scenario.getPassengersList() : scenario.getPedestriansList(); ArrayList<Character> sacrifices = (decision == EthicalEngine.Decision.PASSENGERS) ? scenario.getPedestriansList() : scenario.getPassengersList(); //survivors for (Character c: survivors) { characterUpdate(c, 1, scenario.isLegalCrossing()); } //sacrifices for (Character c: sacrifices) { characterUpdate(c,0, scenario.isLegalCrossing()); } } private void entryUpdate(String key, int modifier) { if (!key.equals("UNKNOWN") && !key.equals("NONE") && !key.equals("UNSPECIFIED")){ statisticsDatabase.putIfAbsent(key, new int[]{0, 0}); int[] entry = statisticsDatabase.get(key); statisticsDatabase.replace(key, new int[]{entry[0]+1, entry[1]+modifier}); } } private void characterUpdate(Character c, int modifier, boolean isLegalCrossing) { entryUpdate(isLegalCrossing? "green": "red", modifier); if (c instanceof Person) { if (modifier == 1){ ageSum += c.getAge(); surviveCount += 1; } entryUpdate(c.getBodyType().name(), modifier); entryUpdate(c.getGender().name(), modifier); entryUpdate(((Person) c).getProfession().name(), modifier); entryUpdate(((Person) c).getAgeCategory().name(), modifier); entryUpdate("person", modifier); if ((c).isYou()){ entryUpdate("you", modifier); } if (((Person) c).isPregnant()){ entryUpdate("pregnant", modifier); } } else if (c instanceof Animal) { entryUpdate(((Animal) c).getSpecies(), modifier); entryUpdate("animal", modifier); if (((Animal) c).isPet()){ entryUpdate("pet", modifier); } } } /** * Convert audit statistics to string * @return string representing an audit */ @Override public String toString() { StringBuilder string = new StringBuilder(); string.append("======================================\n"); string.append("# ").append(getAuditType()).append(" Audit\n"); string.append("======================================\n"); string.append("- % SAVED AFTER ").append(runCount).append(" RUNS\n"); // sort database by survival rate. ArrayList <String[]> sortedDatabase = new ArrayList<>(); for (String key:statisticsDatabase.keySet()) { int[] entry = statisticsDatabase.get(key); double survivalRate = (double)entry[1]/(double) entry[0]; sortedDatabase.add(new String[]{key, String.valueOf(survivalRate)}); } //sortedDatabase.sort(Comparator.comparingDouble(o -> -1 * Double.parseDouble(o[1]))); sortedDatabase.sort(Comparator.comparing((String[] o) -> -1 * Double.parseDouble(o[1])) .thenComparing(o -> o[0])); for (String[] s: sortedDatabase) { string.append(s[0].toLowerCase()).append(": ") .append(String.format("%.1f", Double.parseDouble(s[1]))) .append("\n"); } string.append("--\n"); string.append("average age: ").append(new DecimalFormat("#.#") .format(ageSum/surviveCount)).append("\n"); return string.toString(); } /** * Print statistics out */ public void printStatistic() { System.out.println(toString()); } /** * Print statistics to file * @param path path of file output */ public void printToFile(String path) { try { PrintWriter outputStream = new PrintWriter(new FileOutputStream(path, true)); outputStream.println(toString()); outputStream.close(); } catch (FileNotFoundException e) { System.out.println( "ERROR: could not print results. Target directory does not exist."); } } }
UTF-8
Java
7,848
java
Audit.java
Java
[ { "context": "ine: Audit.java\n * manages audit sessions.\n *\n * ©Runfeng Du\n */\n\nimport ethicalengine.*;\nimport ethicalengine", "end": 76, "score": 0.9998400807380676, "start": 66, "tag": "NAME", "value": "Runfeng Du" } ]
null
[]
/* * Moral Machine: Audit.java * manages audit sessions. * * ©<NAME> */ import ethicalengine.*; import ethicalengine.Character; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintWriter; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.Scanner; public class Audit { private String auditType = "Unspecified"; private final HashMap<String, int[]> statisticsDatabase = new HashMap<>(); private int runCount = 0; private int surviveCount = 0; private double ageSum = 0.0; private ArrayList<Scenario> scenarioBuffer; // a public scanner public static Scanner scannerObject = new Scanner(System.in); /** * Empty constructor */ public Audit() {} /** * Constructor with scenarios specified * @param scenarioSet set of scenarios to be run */ public Audit(ArrayList<Scenario> scenarioSet) { scenarioBuffer = scenarioSet; } /** * Manually load scenarios into audit * @param scenarioSet set of scenarios to be run */ public void loadScenarios (ArrayList<Scenario> scenarioSet) { scenarioBuffer = scenarioSet; } /** * run audit by randomly generated scenarios. * @param runs number of audit to be run */ public void run(int runs) { ScenarioGenerator generator = new ScenarioGenerator(); for (int i = 0; i < runs ; i++) { Scenario scenario = generator.generate(); EthicalEngine.Decision result = EthicalEngine.decide(scenario); this.updateStatistics(scenario, result); runCount += 1; } } /** * Run audit by imported scenarios. */ public void run() { for (Scenario s: scenarioBuffer) { EthicalEngine.Decision result = EthicalEngine.decide(s); this.updateStatistics(s, result); runCount += 1; } } /** * Run audit in interactive mode */ public void interactiveRun() { for (Scenario s: scenarioBuffer) { EthicalEngine.Decision decision = EthicalEngine.Decision.PASSENGERS; boolean decisionMade = false; System.out.print(s.toString()); while (!decisionMade){ System.out.println(); System.out.println("Who should be saved? (passenger(s) [1] or pedestrian(s) [2])"); switch (scannerObject.nextLine()) { case "passenger", "passengers", "1" -> { decision = EthicalEngine.Decision.PASSENGERS; decisionMade = true; } case "pedestrian", "pedestrians", "2" -> { decision = EthicalEngine.Decision.PEDESTRIANS; decisionMade = true; } default -> System.out.print("Invalid response. "); } } this.updateStatistics(s, decision); runCount += 1; } // clear buffer scenarioBuffer = new ArrayList<>(); } /** * get audit type * @return the audit type */ public String getAuditType() { return auditType; } /** * Set audit type * @param auditType the audit type */ public void setAuditType(String auditType) { this.auditType = auditType; } private void updateStatistics(Scenario scenario, EthicalEngine.Decision decision) { ArrayList<Character> survivors = (decision == EthicalEngine.Decision.PASSENGERS) ? scenario.getPassengersList() : scenario.getPedestriansList(); ArrayList<Character> sacrifices = (decision == EthicalEngine.Decision.PASSENGERS) ? scenario.getPedestriansList() : scenario.getPassengersList(); //survivors for (Character c: survivors) { characterUpdate(c, 1, scenario.isLegalCrossing()); } //sacrifices for (Character c: sacrifices) { characterUpdate(c,0, scenario.isLegalCrossing()); } } private void entryUpdate(String key, int modifier) { if (!key.equals("UNKNOWN") && !key.equals("NONE") && !key.equals("UNSPECIFIED")){ statisticsDatabase.putIfAbsent(key, new int[]{0, 0}); int[] entry = statisticsDatabase.get(key); statisticsDatabase.replace(key, new int[]{entry[0]+1, entry[1]+modifier}); } } private void characterUpdate(Character c, int modifier, boolean isLegalCrossing) { entryUpdate(isLegalCrossing? "green": "red", modifier); if (c instanceof Person) { if (modifier == 1){ ageSum += c.getAge(); surviveCount += 1; } entryUpdate(c.getBodyType().name(), modifier); entryUpdate(c.getGender().name(), modifier); entryUpdate(((Person) c).getProfession().name(), modifier); entryUpdate(((Person) c).getAgeCategory().name(), modifier); entryUpdate("person", modifier); if ((c).isYou()){ entryUpdate("you", modifier); } if (((Person) c).isPregnant()){ entryUpdate("pregnant", modifier); } } else if (c instanceof Animal) { entryUpdate(((Animal) c).getSpecies(), modifier); entryUpdate("animal", modifier); if (((Animal) c).isPet()){ entryUpdate("pet", modifier); } } } /** * Convert audit statistics to string * @return string representing an audit */ @Override public String toString() { StringBuilder string = new StringBuilder(); string.append("======================================\n"); string.append("# ").append(getAuditType()).append(" Audit\n"); string.append("======================================\n"); string.append("- % SAVED AFTER ").append(runCount).append(" RUNS\n"); // sort database by survival rate. ArrayList <String[]> sortedDatabase = new ArrayList<>(); for (String key:statisticsDatabase.keySet()) { int[] entry = statisticsDatabase.get(key); double survivalRate = (double)entry[1]/(double) entry[0]; sortedDatabase.add(new String[]{key, String.valueOf(survivalRate)}); } //sortedDatabase.sort(Comparator.comparingDouble(o -> -1 * Double.parseDouble(o[1]))); sortedDatabase.sort(Comparator.comparing((String[] o) -> -1 * Double.parseDouble(o[1])) .thenComparing(o -> o[0])); for (String[] s: sortedDatabase) { string.append(s[0].toLowerCase()).append(": ") .append(String.format("%.1f", Double.parseDouble(s[1]))) .append("\n"); } string.append("--\n"); string.append("average age: ").append(new DecimalFormat("#.#") .format(ageSum/surviveCount)).append("\n"); return string.toString(); } /** * Print statistics out */ public void printStatistic() { System.out.println(toString()); } /** * Print statistics to file * @param path path of file output */ public void printToFile(String path) { try { PrintWriter outputStream = new PrintWriter(new FileOutputStream(path, true)); outputStream.println(toString()); outputStream.close(); } catch (FileNotFoundException e) { System.out.println( "ERROR: could not print results. Target directory does not exist."); } } }
7,844
0.563018
0.559067
232
32.827587
25.057787
99
false
false
0
0
0
0
0
0
0.508621
false
false
6
b5d1b2ca15ae00431907c40caf374a510cfda7e0
32,555,852,121,760
5b1ccc3382f0bd73525f15da26a28b96e5576d35
/daily/src/main/java/com/btmf/business/service/slaver/impl/UserServiceImpl.java
09e94e0179b43bb9b683a7519b93fc91dcc0cf1d
[]
no_license
crazy-yyh/intelligentrecommendation
https://github.com/crazy-yyh/intelligentrecommendation
be9a3ea1cdcf6a1dd3d97570e2fa845480f8138c
ae1bea205cf31e1c69539a8be5ac9b6544c0189a
refs/heads/master
2023-07-19T02:49:36.785000
2021-09-30T13:43:38
2021-09-30T13:43:38
410,312,542
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.btmf.business.service.slaver.impl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.btmf.business.dao.slaver.UserDao; import com.btmf.business.entity.slaver.UserEntity; import com.btmf.business.service.slaver.UserService; import org.springframework.stereotype.Service; @Service("userService") public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService { }
UTF-8
Java
437
java
UserServiceImpl.java
Java
[]
null
[]
package com.btmf.business.service.slaver.impl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.btmf.business.dao.slaver.UserDao; import com.btmf.business.entity.slaver.UserEntity; import com.btmf.business.service.slaver.UserService; import org.springframework.stereotype.Service; @Service("userService") public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService { }
437
0.832952
0.832952
15
28.200001
29.775158
94
false
false
0
0
0
0
0
0
0.466667
false
false
6
fc778c2f179147926d334fbc39353bd8982ba2b3
1,657,857,394,535
d428f82b02d1aa8ca13c9aff9bbe719f52ca8c67
/src/main/java/com/bharuwa/haritkranti/repositories/FinancialDetailRepo.java
4dbde11cf28ab5917d7a50a64caf00cccf36973f
[]
no_license
PatanjaliAyurveda/HaritkrantiApiV1
https://github.com/PatanjaliAyurveda/HaritkrantiApiV1
ce10cb95b91a7da23b4b5095edbe222940cfa2b3
e4c71419a164ca3360f43ca8252b6d1a0a05291c
refs/heads/master
2023-02-01T02:57:21.602000
2020-12-16T06:22:20
2020-12-16T06:22:20
321,889,522
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bharuwa.haritkranti.repositories; import com.bharuwa.haritkranti.models.FinancialDetails; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository; /** * @author harman */ @Repository public interface FinancialDetailRepo extends MongoRepository<FinancialDetails,String> { }
UTF-8
Java
350
java
FinancialDetailRepo.java
Java
[ { "context": "ngframework.stereotype.Repository;\n\n/**\n * @author harman\n */\n@Repository\npublic interface FinancialDetailR", "end": 243, "score": 0.9632084369659424, "start": 237, "tag": "USERNAME", "value": "harman" } ]
null
[]
package com.bharuwa.haritkranti.repositories; import com.bharuwa.haritkranti.models.FinancialDetails; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository; /** * @author harman */ @Repository public interface FinancialDetailRepo extends MongoRepository<FinancialDetails,String> { }
350
0.837143
0.837143
12
28.166666
29.464197
87
false
false
0
0
0
0
0
0
0.416667
false
false
6
9aa00e5c73ef6f196c16a7307b73f8a1d899d3da
3,075,196,634,113
24b0712c0a59ba77ae20cdb77de9fc9d1aeb108c
/src/cn/littleround/ASTnode/ParenthesisOpNode.java
1902ea103f3526fed612b07f217be319032b8244
[]
no_license
djrmlrfs/MxStaro
https://github.com/djrmlrfs/MxStaro
8c8bebf86474dab54590259d681c926651c5a828
3f237b0ae721c3a609394cd2ccbdcec62e53d6fb
refs/heads/master
2020-03-13T07:13:03.872000
2018-04-24T15:42:51
2018-04-24T15:42:51
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.littleround.ASTnode; import cn.littleround.symbol.VariableSymbol; import cn.littleround.type.FuncType; import cn.littleround.type.TypeList; public class ParenthesisOpNode extends BinaryOpNode { @Override public void updateType() { super.updateType(); if (!(op1().type instanceof FuncType)) { if (op1() instanceof IdentifierNode) { ((IdentifierNode) op1()).updateTypeToFunc(); } if (op1() instanceof DotOpNode) { // WTF, tired to solve } } if (!(op1().type instanceof FuncType)) { reportError("Semantic Error", "op1 should be Func type in parenthesis operation."); } TypeList tl = new TypeList(); for (ASTBaseNode i:op2().getSons()) { tl.add(i.type); } type = ((FuncType) op1().type).getRetType(tl); if (type == null) reportError("Semantic", "Cannot find coresponding function form."); } }
UTF-8
Java
1,011
java
ParenthesisOpNode.java
Java
[]
null
[]
package cn.littleround.ASTnode; import cn.littleround.symbol.VariableSymbol; import cn.littleround.type.FuncType; import cn.littleround.type.TypeList; public class ParenthesisOpNode extends BinaryOpNode { @Override public void updateType() { super.updateType(); if (!(op1().type instanceof FuncType)) { if (op1() instanceof IdentifierNode) { ((IdentifierNode) op1()).updateTypeToFunc(); } if (op1() instanceof DotOpNode) { // WTF, tired to solve } } if (!(op1().type instanceof FuncType)) { reportError("Semantic Error", "op1 should be Func type in parenthesis operation."); } TypeList tl = new TypeList(); for (ASTBaseNode i:op2().getSons()) { tl.add(i.type); } type = ((FuncType) op1().type).getRetType(tl); if (type == null) reportError("Semantic", "Cannot find coresponding function form."); } }
1,011
0.581602
0.573689
31
31.612904
23.299837
95
false
false
0
0
0
0
0
0
0.451613
false
false
6
2b3c9a1cfa0cbeb92f3e6757a97d8d56be98e8a7
4,063,039,123,614
03821dbcd5b1fad16f6ff2dd222dac0dbc0502fd
/source/src/main/java/co/weeby/chat/Room.java
4faf36ab61beb0776b86e045e2ad20c23ad11518
[ "Apache-2.0" ]
permissive
jiangzhen1984/ChatServer
https://github.com/jiangzhen1984/ChatServer
2f45e87857c8f70bc7364fdc7aa45429f71cf124
bb064ae3bd500529e7c4de91e6dd9c573dcdb6c2
refs/heads/master
2021-01-10T09:07:58.314000
2016-02-24T04:55:17
2016-02-24T04:55:17
52,133,775
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package co.weeby.chat; import java.util.ArrayList; import java.util.List; public class Room { private String name; private List<Telnet> users; public Room(String name) { super(); this.name = name; users = new ArrayList<Telnet>(); } public Room() { users = new ArrayList<Telnet>(); } public void addUser(Telnet terminal) { users.add(terminal); } public void removeUser(Telnet ter) { users.remove(ter); } public int getUserCount() { return users.size(); } public String getName() { return name; } public List<Telnet> getUsers() { return users; } }
UTF-8
Java
618
java
Room.java
Java
[]
null
[]
package co.weeby.chat; import java.util.ArrayList; import java.util.List; public class Room { private String name; private List<Telnet> users; public Room(String name) { super(); this.name = name; users = new ArrayList<Telnet>(); } public Room() { users = new ArrayList<Telnet>(); } public void addUser(Telnet terminal) { users.add(terminal); } public void removeUser(Telnet ter) { users.remove(ter); } public int getUserCount() { return users.size(); } public String getName() { return name; } public List<Telnet> getUsers() { return users; } }
618
0.640777
0.640777
52
10.884615
12.625758
39
false
false
0
0
0
0
0
0
1.192308
false
false
6
f9799dbee6633d419a4f612fad9428f558524a52
27,565,100,170,545
341a1b65e15c551a93a013c234b5b31febed4d8b
/data_structure_1/src/eg/edu/alexu/csd/filestructure/sort/Node.java
1f2bdfe51c93b77931c58cb4e53a28d88cef81d6
[]
no_license
islammostafa99/heapsort
https://github.com/islammostafa99/heapsort
512e2936694452e8d9d441336af59ad98d2232ee
022a3cc300abc9e37e2c40606c606fea357dd4d4
refs/heads/master
2021-03-17T04:06:10.888000
2020-03-13T00:37:51
2020-03-13T00:37:51
246,957,462
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package eg.edu.alexu.csd.filestructure.sort; import java.util.Vector; public class Node implements INode { private Object node; private int index; private int f; public Node(Object object){ for (int i=0;i<Controller.arr.size();i++){ if(Controller.arr.elementAt(i).getValue().equals(object)){ index = i; } } } public Node(){ node=null; } @Override public INode getLeftChild() { if(index*2+1>Controller.arr.size()){ return null; } return (INode) Controller.arr.elementAt(index*2+1); } @Override public INode getRightChild() { if(index*2+2>Controller.arr.size()){ return null; } return Controller.arr.elementAt(index*2+2); } @Override public INode getParent() { if(index==0){ return null; } return Controller.arr.elementAt((index-1)/2); } @Override public Comparable getValue() { return (Comparable) node; } @Override public void setValue(Comparable value) { node=value; } }
UTF-8
Java
1,192
java
Node.java
Java
[]
null
[]
package eg.edu.alexu.csd.filestructure.sort; import java.util.Vector; public class Node implements INode { private Object node; private int index; private int f; public Node(Object object){ for (int i=0;i<Controller.arr.size();i++){ if(Controller.arr.elementAt(i).getValue().equals(object)){ index = i; } } } public Node(){ node=null; } @Override public INode getLeftChild() { if(index*2+1>Controller.arr.size()){ return null; } return (INode) Controller.arr.elementAt(index*2+1); } @Override public INode getRightChild() { if(index*2+2>Controller.arr.size()){ return null; } return Controller.arr.elementAt(index*2+2); } @Override public INode getParent() { if(index==0){ return null; } return Controller.arr.elementAt((index-1)/2); } @Override public Comparable getValue() { return (Comparable) node; } @Override public void setValue(Comparable value) { node=value; } }
1,192
0.537752
0.527685
46
23.956522
16.556828
70
false
false
0
0
0
0
0
0
0.369565
false
false
6
dcbeafe2ae9d7abb3ca36621201f92cb64ec794a
36,215,164,273,239
944c10b47d046601f0c41527937147c338d18859
/app/src/main/java/zjj/com/dribbbledemoapp/activities/UserActivity.java
9c68a29a1fed9b167f6e3a1f9e0c233d86277fd3
[ "Apache-2.0" ]
permissive
jz233/DribbbleDemoApp
https://github.com/jz233/DribbbleDemoApp
8c77ebaf8223799cd083e5e8ebbac9759da7d28c
9ea3eaeebb5cb536278a19e49c271cb953f550b1
refs/heads/master
2021-01-11T04:41:55.773000
2016-11-22T13:35:36
2016-11-22T13:35:36
71,110,898
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package zjj.com.dribbbledemoapp.activities; import android.content.Context; import android.content.Intent; import android.support.v7.app.ActionBar; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.google.gson.Gson; import com.squareup.picasso.Picasso; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import de.hdodenhof.circleimageview.CircleImageView; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; import zjj.com.dribbbledemoapp.R; import zjj.com.dribbbledemoapp.adapters.base.CommonAdapter; import zjj.com.dribbbledemoapp.adapters.base.CommonViewHolder; import zjj.com.dribbbledemoapp.applications.AppController; import zjj.com.dribbbledemoapp.base.BaseActivity; import zjj.com.dribbbledemoapp.domains.Shot; import zjj.com.dribbbledemoapp.domains.User; import zjj.com.dribbbledemoapp.listeners.OnLoadMoreListener; import zjj.com.dribbbledemoapp.utils.Constants; public class UserActivity extends BaseActivity { private Toolbar toolbar; private CircleImageView iv_user_avatar; private User user; private boolean loadSuccess; private TextView tv_name; private TextView tv_user_location; private TextView tv_user_bio; private RecyclerView rv_shots_list; private String userId; private Shot[] shots; private ArrayList<Shot> shotsList; private String name; private ActionBar actionBar; private GridLayoutManager layoutManager; private int itemCount; private static int threshold = 2; private int firstVisibleItemPosition; private int previousItemCount = 0; private boolean isLoading; private int childCount; private int currentPage = 1; private CommonAdapter<Shot> adapter; private HashMap<String, String> params; @Override public void initView() { setContentView(R.layout.activity_user); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); iv_user_avatar = (CircleImageView) findViewById(R.id.iv_user_avatar); tv_name = (TextView) findViewById(R.id.tv_name); tv_user_location = (TextView) findViewById(R.id.tv_user_location); tv_user_bio = (TextView) findViewById(R.id.tv_user_bio); rv_shots_list = (RecyclerView) findViewById(R.id.rv_shots_list); params = new HashMap<>(); } @Override public void initListener() { } @Override public void initData() { Intent intent = getIntent(); if (intent != null) { userId = String.valueOf(intent.getIntExtra("userId", 0)); name = intent.getStringExtra("name"); actionBar.setTitle(name); AppController.getInstance().enqueueGetRequest( new String[]{Constants.USERS, userId}, "users", new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { String body = response.body().string(); user = new Gson().fromJson(body, User.class); runOnUiThread(new Runnable() { @Override public void run() { displayData(); } }); } }); } } private void displayData() { loadImage(); loadInfo(); loadShots(currentPage); } private void loadImage() { if (!loadSuccess) { Picasso.with(this).load(user.getAvatar_url()) .error(R.drawable.default_avatar).tag("image") .into(iv_user_avatar, new com.squareup.picasso.Callback() { @Override public void onSuccess() { loadSuccess = true; Toast.makeText(context, "load success", Toast.LENGTH_SHORT).show(); } @Override public void onError() { loadSuccess = false; Picasso.with(context).cancelRequest(iv_user_avatar); Toast.makeText(context, "load error", Toast.LENGTH_SHORT).show(); } }); } } private void loadInfo() { tv_name.setText(user.getName()); tv_user_location.setText(user.getLocation()); tv_user_bio.setText(user.getBio()); } private void loadShots(final int currentPage) { params.put("page", String.valueOf(currentPage)); AppController.getInstance().enqueueGetRequest( new String[]{Constants.USERS, userId, Constants.SHOTS}, params, Constants.USERS_SHOTS, new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { String body = response.body().string(); shots = new Gson().fromJson(body, Shot[].class); if (currentPage == 1) { // first page shotsList = new ArrayList<>(Arrays.asList(shots)); displayUserShotsList(); }else{ // load more shotsList.addAll(Arrays.asList(shots)); isLoading = false; runOnUiThread(new Runnable() { @Override public void run() { adapter.notifyItemRangeInserted(itemCount+1, shots.length); } }); } } } ); } private void displayUserShotsList() { layoutManager = new GridLayoutManager(UserActivity.this, 2); // load more implementation rv_shots_list.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition(); childCount = recyclerView.getChildCount(); itemCount = layoutManager.getItemCount(); if (!isLoading && (firstVisibleItemPosition + childCount + threshold) > itemCount) { isLoading = true; previousItemCount = itemCount; loadShots(++currentPage); } if (itemCount > previousItemCount) { isLoading = false; } } }); runOnUiThread(new Runnable() { @Override public void run() { rv_shots_list.setLayoutManager(layoutManager); adapter = new CommonAdapter<Shot>(context, R.layout.item_users_shot_cardview, shotsList) { @Override protected void convert(CommonViewHolder holder, final Shot shot) { holder.setImageUrl(R.id.shots_thumb, shot.getImages().getTeaser()); holder.setText(R.id.shots_title, shot.getTitle()); holder.setText(R.id.shots_views_count, String.valueOf(shot.getViews_count())); holder.setText(R.id.shots_comments_count, String.valueOf(shot.getComments_count())); holder.setText(R.id.shots_likes_count, String.valueOf(shot.getLikes_count())); holder.setOnViewClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Context context = v.getContext(); Intent intent = new Intent(context, DetailsActivity.class); intent.putExtra("id", shot.getId()); context.startActivity(intent); } }); } }; rv_shots_list.setAdapter(adapter); } }); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; } return super.onOptionsItemSelected(item); } @Override protected void cancelRequestsOnStop() { } }
UTF-8
Java
9,459
java
UserActivity.java
Java
[]
null
[]
package zjj.com.dribbbledemoapp.activities; import android.content.Context; import android.content.Intent; import android.support.v7.app.ActionBar; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.google.gson.Gson; import com.squareup.picasso.Picasso; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import de.hdodenhof.circleimageview.CircleImageView; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; import zjj.com.dribbbledemoapp.R; import zjj.com.dribbbledemoapp.adapters.base.CommonAdapter; import zjj.com.dribbbledemoapp.adapters.base.CommonViewHolder; import zjj.com.dribbbledemoapp.applications.AppController; import zjj.com.dribbbledemoapp.base.BaseActivity; import zjj.com.dribbbledemoapp.domains.Shot; import zjj.com.dribbbledemoapp.domains.User; import zjj.com.dribbbledemoapp.listeners.OnLoadMoreListener; import zjj.com.dribbbledemoapp.utils.Constants; public class UserActivity extends BaseActivity { private Toolbar toolbar; private CircleImageView iv_user_avatar; private User user; private boolean loadSuccess; private TextView tv_name; private TextView tv_user_location; private TextView tv_user_bio; private RecyclerView rv_shots_list; private String userId; private Shot[] shots; private ArrayList<Shot> shotsList; private String name; private ActionBar actionBar; private GridLayoutManager layoutManager; private int itemCount; private static int threshold = 2; private int firstVisibleItemPosition; private int previousItemCount = 0; private boolean isLoading; private int childCount; private int currentPage = 1; private CommonAdapter<Shot> adapter; private HashMap<String, String> params; @Override public void initView() { setContentView(R.layout.activity_user); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); iv_user_avatar = (CircleImageView) findViewById(R.id.iv_user_avatar); tv_name = (TextView) findViewById(R.id.tv_name); tv_user_location = (TextView) findViewById(R.id.tv_user_location); tv_user_bio = (TextView) findViewById(R.id.tv_user_bio); rv_shots_list = (RecyclerView) findViewById(R.id.rv_shots_list); params = new HashMap<>(); } @Override public void initListener() { } @Override public void initData() { Intent intent = getIntent(); if (intent != null) { userId = String.valueOf(intent.getIntExtra("userId", 0)); name = intent.getStringExtra("name"); actionBar.setTitle(name); AppController.getInstance().enqueueGetRequest( new String[]{Constants.USERS, userId}, "users", new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { String body = response.body().string(); user = new Gson().fromJson(body, User.class); runOnUiThread(new Runnable() { @Override public void run() { displayData(); } }); } }); } } private void displayData() { loadImage(); loadInfo(); loadShots(currentPage); } private void loadImage() { if (!loadSuccess) { Picasso.with(this).load(user.getAvatar_url()) .error(R.drawable.default_avatar).tag("image") .into(iv_user_avatar, new com.squareup.picasso.Callback() { @Override public void onSuccess() { loadSuccess = true; Toast.makeText(context, "load success", Toast.LENGTH_SHORT).show(); } @Override public void onError() { loadSuccess = false; Picasso.with(context).cancelRequest(iv_user_avatar); Toast.makeText(context, "load error", Toast.LENGTH_SHORT).show(); } }); } } private void loadInfo() { tv_name.setText(user.getName()); tv_user_location.setText(user.getLocation()); tv_user_bio.setText(user.getBio()); } private void loadShots(final int currentPage) { params.put("page", String.valueOf(currentPage)); AppController.getInstance().enqueueGetRequest( new String[]{Constants.USERS, userId, Constants.SHOTS}, params, Constants.USERS_SHOTS, new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { String body = response.body().string(); shots = new Gson().fromJson(body, Shot[].class); if (currentPage == 1) { // first page shotsList = new ArrayList<>(Arrays.asList(shots)); displayUserShotsList(); }else{ // load more shotsList.addAll(Arrays.asList(shots)); isLoading = false; runOnUiThread(new Runnable() { @Override public void run() { adapter.notifyItemRangeInserted(itemCount+1, shots.length); } }); } } } ); } private void displayUserShotsList() { layoutManager = new GridLayoutManager(UserActivity.this, 2); // load more implementation rv_shots_list.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition(); childCount = recyclerView.getChildCount(); itemCount = layoutManager.getItemCount(); if (!isLoading && (firstVisibleItemPosition + childCount + threshold) > itemCount) { isLoading = true; previousItemCount = itemCount; loadShots(++currentPage); } if (itemCount > previousItemCount) { isLoading = false; } } }); runOnUiThread(new Runnable() { @Override public void run() { rv_shots_list.setLayoutManager(layoutManager); adapter = new CommonAdapter<Shot>(context, R.layout.item_users_shot_cardview, shotsList) { @Override protected void convert(CommonViewHolder holder, final Shot shot) { holder.setImageUrl(R.id.shots_thumb, shot.getImages().getTeaser()); holder.setText(R.id.shots_title, shot.getTitle()); holder.setText(R.id.shots_views_count, String.valueOf(shot.getViews_count())); holder.setText(R.id.shots_comments_count, String.valueOf(shot.getComments_count())); holder.setText(R.id.shots_likes_count, String.valueOf(shot.getLikes_count())); holder.setOnViewClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Context context = v.getContext(); Intent intent = new Intent(context, DetailsActivity.class); intent.putExtra("id", shot.getId()); context.startActivity(intent); } }); } }; rv_shots_list.setAdapter(adapter); } }); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; } return super.onOptionsItemSelected(item); } @Override protected void cancelRequestsOnStop() { } }
9,459
0.547204
0.545724
251
36.685261
25.690165
108
false
false
0
0
0
0
0
0
0.641434
false
false
6
f9dfac70f229b09d150173ef898bbddc255ae176
38,173,669,340,254
8b518a1192a427a8abe9fd0c37f7c33c8f2924cc
/web-server/metaScience/src/som/metascience/elements/Author.java
7948aa966a91720b84903d4eed720889c7a2c4ed
[]
no_license
SOM-Research/metaScience
https://github.com/SOM-Research/metaScience
8f070d1312f8a86b7f5cadcb23e8ca46493f0b28
84b2fb53b8624791399b1a3342ffddca8c86a9af
refs/heads/master
2023-05-23T04:28:46.604000
2022-10-28T14:14:26
2022-10-28T14:14:26
20,441,319
9
1
null
false
2016-07-27T13:46:13
2014-06-03T12:12:50
2016-07-25T12:12:05
2016-07-27T13:46:13
9,919
5
1
4
Python
null
null
package som.metascience.elements; public class Author { private String name; private int numberPublications; public Author(String name, int numberPublications) { this.name = name; this.numberPublications = numberPublications; } public int getNumberPublications() { return this.numberPublications; } public String getName() { return this.name; } }
UTF-8
Java
375
java
Author.java
Java
[]
null
[]
package som.metascience.elements; public class Author { private String name; private int numberPublications; public Author(String name, int numberPublications) { this.name = name; this.numberPublications = numberPublications; } public int getNumberPublications() { return this.numberPublications; } public String getName() { return this.name; } }
375
0.738667
0.738667
22
16.045454
16.818489
53
false
false
0
0
0
0
0
0
1.318182
false
false
6
8e97583e69f2c62ddd1e88aebd230db63be93632
35,639,638,657,456
57637ab52d00fe0524aa1a5f74857bdaf6bec16e
/googlemaptest/app/src/main/java/com/termproject/user/googlemaptest/Map.java
9bde720247dc9e5fd13bbe4afcafe3c1aff56b28
[]
no_license
skins346/BluetoothTracker
https://github.com/skins346/BluetoothTracker
cac19af26cbf3d1bd45553bec632b4b861693ce2
66780e6eda5ed5b0b93aafd2166233f7c069e0bf
refs/heads/master
2020-07-15T11:11:14.115000
2016-08-22T23:19:05
2016-08-22T23:19:05
66,314,634
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.termproject.user.googlemaptest; import android.content.Context; import android.location.Address; import android.os.Bundle; 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.location.Location; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import android.location.Geocoder; import java.util.*; public class Map extends Fragment { public static double longitude; public static double latitude; private GoogleMap map; public static Map newInstance() { Map fragment = new Map(); return fragment; } private void drawMarker(Location location) { //기존 마커 지우기 map.clear(); LatLng currentPosition = new LatLng(location.getLatitude(), location.getLongitude()); //currentPosition 위치로 카메라 중심을 옮기고 화면 줌을 조정한다. 줌범위는 2~21, 숫자클수록 확대 map.moveCamera(CameraUpdateFactory.newLatLngZoom( currentPosition, 17)); map.animateCamera(CameraUpdateFactory.zoomTo(17), 2000, null); //마커 추가 map.addMarker(new MarkerOptions() .position(currentPosition) .snippet("Lat:" + location.getLatitude() + "Lng:" + location.getLongitude()) .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)) .title("현재위치")); } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.activity_map, container, false); map = ((MapFragment) MainActivity.fragmentManager.findFragmentById(R.id.map)).getMap(); //현재 위치로 가는 버튼 표시 map.setMyLocationEnabled(true); //map.moveCamera(CameraUpdateFactory.newLatLngZoom(SEOUL, 15));//초기 위치...수정필요 MyLocation.LocationResult locationResult = new MyLocation.LocationResult() { @Override public void gotLocation(Location location) { longitude = location.getLongitude(); latitude = location.getLatitude(); drawMarker(location); } }; MyLocation myLocation = new MyLocation(); myLocation.getLocation(getContext(), locationResult); return rootView; } public static String getAddress(Context context){ String address = null; //위치정보를 활용하기 위한 구글 API 객체 Geocoder geocoder = new Geocoder(context, Locale.getDefault()); //주소 목록을 담기 위한 HashMap java.util.List<Address> list = null; try{ list = geocoder.getFromLocation(latitude, longitude, 1); } catch(Exception e){ e.printStackTrace(); } if(list == null){ Log.e("getAddress", "주소 데이터 얻기 실패"); return null; } if(list.size() > 0){ Address addr = list.get(0); address = addr.getCountryName() + " " + addr.getPostalCode() + " " + addr.getLocality() + " " + addr.getThoroughfare() + " " + addr.getFeatureName(); } return address; } }
UTF-8
Java
3,764
java
Map.java
Java
[]
null
[]
package com.termproject.user.googlemaptest; import android.content.Context; import android.location.Address; import android.os.Bundle; 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.location.Location; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import android.location.Geocoder; import java.util.*; public class Map extends Fragment { public static double longitude; public static double latitude; private GoogleMap map; public static Map newInstance() { Map fragment = new Map(); return fragment; } private void drawMarker(Location location) { //기존 마커 지우기 map.clear(); LatLng currentPosition = new LatLng(location.getLatitude(), location.getLongitude()); //currentPosition 위치로 카메라 중심을 옮기고 화면 줌을 조정한다. 줌범위는 2~21, 숫자클수록 확대 map.moveCamera(CameraUpdateFactory.newLatLngZoom( currentPosition, 17)); map.animateCamera(CameraUpdateFactory.zoomTo(17), 2000, null); //마커 추가 map.addMarker(new MarkerOptions() .position(currentPosition) .snippet("Lat:" + location.getLatitude() + "Lng:" + location.getLongitude()) .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)) .title("현재위치")); } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.activity_map, container, false); map = ((MapFragment) MainActivity.fragmentManager.findFragmentById(R.id.map)).getMap(); //현재 위치로 가는 버튼 표시 map.setMyLocationEnabled(true); //map.moveCamera(CameraUpdateFactory.newLatLngZoom(SEOUL, 15));//초기 위치...수정필요 MyLocation.LocationResult locationResult = new MyLocation.LocationResult() { @Override public void gotLocation(Location location) { longitude = location.getLongitude(); latitude = location.getLatitude(); drawMarker(location); } }; MyLocation myLocation = new MyLocation(); myLocation.getLocation(getContext(), locationResult); return rootView; } public static String getAddress(Context context){ String address = null; //위치정보를 활용하기 위한 구글 API 객체 Geocoder geocoder = new Geocoder(context, Locale.getDefault()); //주소 목록을 담기 위한 HashMap java.util.List<Address> list = null; try{ list = geocoder.getFromLocation(latitude, longitude, 1); } catch(Exception e){ e.printStackTrace(); } if(list == null){ Log.e("getAddress", "주소 데이터 얻기 실패"); return null; } if(list.size() > 0){ Address addr = list.get(0); address = addr.getCountryName() + " " + addr.getPostalCode() + " " + addr.getLocality() + " " + addr.getThoroughfare() + " " + addr.getFeatureName(); } return address; } }
3,764
0.640695
0.63593
111
31.126125
26.53134
103
false
false
0
0
0
0
0
0
0.585586
false
false
6
163089798fcbf2c2c944ac0a04e941a985963ff7
1,357,209,735,519
d58493ae0309e87796792172e33b7e979e8a0b63
/src/main/java/com/damani/service/PaymentService.java
86300d5edd696ac10d2729010f623ecdc81a0efa
[]
no_license
nehaaghara/GruhUdhyog
https://github.com/nehaaghara/GruhUdhyog
b34d03ea61dfa6603150b4f2cb576267ff7ceb7c
29fbf09ae526d1114d89ecc32de07fd1722f26ed
refs/heads/master
2020-04-26T23:16:58.522000
2019-04-09T11:04:48
2019-04-09T11:04:48
173,897,499
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.damani.service; import com.damani.model.TblPayment; import com.damani.model.TblShipping; import com.damani.model.TblUserTable; import org.springframework.stereotype.Service; /** * * @author ITMCS */ @Service public interface PaymentService { public void saveShippingInformation(TblShipping tblShipping,TblUserTable tblUserTable); public void savePayment(TblPayment tblPayment,TblUserTable tblUserTable); }
UTF-8
Java
621
java
PaymentService.java
Java
[ { "context": "ngframework.stereotype.Service;\n\n/**\n *\n * @author ITMCS\n */\n@Service\npublic interface PaymentService {\n ", "end": 396, "score": 0.9995606541633606, "start": 391, "tag": "USERNAME", "value": "ITMCS" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.damani.service; import com.damani.model.TblPayment; import com.damani.model.TblShipping; import com.damani.model.TblUserTable; import org.springframework.stereotype.Service; /** * * @author ITMCS */ @Service public interface PaymentService { public void saveShippingInformation(TblShipping tblShipping,TblUserTable tblUserTable); public void savePayment(TblPayment tblPayment,TblUserTable tblUserTable); }
621
0.780998
0.780998
22
27.227272
27.886021
91
false
false
0
0
0
0
0
0
0.545455
false
false
6
83a42cc7c92a7022020ffe43eb635de381ea9d0c
38,594,576,137,345
b6ee1c1a394ed7be00f616060a8f75faa03d5dd8
/Decorator/Decorator/src/LiderEquipe.java
029f770c142b2df0c00cf5c829d8d53c23116e35
[]
no_license
leandroscramos/Disciplina_POO_2019_1
https://github.com/leandroscramos/Disciplina_POO_2019_1
587a1f24bdb81f1025e42ac6b12c77b188063057
3f7a45077ae2facf2b105e25d77d005e40a160b8
refs/heads/master
2020-04-28T02:13:24.072000
2019-05-15T14:19:19
2019-05-15T14:19:19
173,816,105
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class LiderEquipe extends FuncionarioDecorator{ public LiderEquipe(Funcionario f) { this.funcionario = f; } public String descricao(){ return funcionario.descricao() + " e Lider de equipe"; } public double getSalario(){ return funcionario.getSalario() + 300.00; } }
UTF-8
Java
324
java
LiderEquipe.java
Java
[]
null
[]
public class LiderEquipe extends FuncionarioDecorator{ public LiderEquipe(Funcionario f) { this.funcionario = f; } public String descricao(){ return funcionario.descricao() + " e Lider de equipe"; } public double getSalario(){ return funcionario.getSalario() + 300.00; } }
324
0.645062
0.62963
14
22.142857
21.705355
62
false
false
0
0
0
0
0
0
0.214286
false
false
6
1979a860731d41bb2148e79406422bc16e1b6025
4,758,823,831,785
18d92bf091b985f09936162725341c2f151c9d7d
/treegen-core/src/main/java/pl/mj/treegen/core/math/RandomGenerator.java
775eebf1fc8e2f9de5337393fab0f3e94a1402fc
[]
no_license
mateuszjaszewski/TreeGenWebApp
https://github.com/mateuszjaszewski/TreeGenWebApp
ceb3d556943e135d31b4d4cf4d3b1508cbaa46bd
3bf4787fc147ef1f5c314f63e862f1d6db48ea77
refs/heads/master
2021-01-10T07:21:44.480000
2016-11-11T20:04:24
2016-11-11T20:04:24
49,782,299
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pl.mj.treegen.core.math; import java.util.Random; public class RandomGenerator { private int globalSeed; private int lastSeed; private Random globalRandom; private Random currentRandom; public RandomGenerator(int globalSeed) { this.globalSeed = globalSeed; this.globalRandom = new Random(globalSeed); lastSeed = globalRandom.nextInt(); currentRandom = new Random(lastSeed); } public RandomGenerator() { globalSeed = 0; } public void setGlobalSeed(int seed) { globalSeed = seed; } public int getGlobalSeed() { return globalSeed; } public int randomInt(int min, int max, int seed) { if(seed != lastSeed) { currentRandom = new Random(seed); } max++; if (min == max) { return min; } int rand = globalRandom.nextInt() + currentRandom.nextInt(); if (rand < 0) { rand = -rand; } return (rand % (max - min)) + min; } public double randomDouble(double min, double max, int seed) { double rand = randomInt(0, Integer.MAX_VALUE, seed) / (double)Integer.MAX_VALUE; return (rand * (max - min) + min); } private int hash(int a, int b) { return a * 31 + b; } }
UTF-8
Java
1,329
java
RandomGenerator.java
Java
[]
null
[]
package pl.mj.treegen.core.math; import java.util.Random; public class RandomGenerator { private int globalSeed; private int lastSeed; private Random globalRandom; private Random currentRandom; public RandomGenerator(int globalSeed) { this.globalSeed = globalSeed; this.globalRandom = new Random(globalSeed); lastSeed = globalRandom.nextInt(); currentRandom = new Random(lastSeed); } public RandomGenerator() { globalSeed = 0; } public void setGlobalSeed(int seed) { globalSeed = seed; } public int getGlobalSeed() { return globalSeed; } public int randomInt(int min, int max, int seed) { if(seed != lastSeed) { currentRandom = new Random(seed); } max++; if (min == max) { return min; } int rand = globalRandom.nextInt() + currentRandom.nextInt(); if (rand < 0) { rand = -rand; } return (rand % (max - min)) + min; } public double randomDouble(double min, double max, int seed) { double rand = randomInt(0, Integer.MAX_VALUE, seed) / (double)Integer.MAX_VALUE; return (rand * (max - min) + min); } private int hash(int a, int b) { return a * 31 + b; } }
1,329
0.573363
0.569601
59
21.525423
20.501638
88
false
false
0
0
0
0
0
0
0.491525
false
false
6
6f10b061ad6e05ec9e8f75681c68dbf5d171c000
37,709,812,876,639
3693ef74c30522887e0d9dcd6cfff71cfdc38204
/LayeredArc/src/com/cg/service/CustomerServiceImpl.java
7d4dc0c17ae450ee24f83745f03d22c3f091b083
[]
no_license
shivamsingh361/la
https://github.com/shivamsingh361/la
545cc426bceaa202a7551bc02d36a2d93260273c
1cd42dedd7c8847724244f33ad247acf40888b9e
refs/heads/master
2020-12-29T12:18:44.907000
2020-02-06T04:06:13
2020-02-06T04:06:13
238,605,331
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cg.service; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.log4j.PropertyConfigurator; import com.cg.dao.CustomerDaoImpl; import com.cg.dto.CustomerDTO; import com.cg.exception.CustomException; public class CustomerServiceImpl implements CustomerService{ static Logger myLogger = Logger.getLogger(CustomerDaoImpl.class.getName()); CustomerDaoImpl obj = new CustomerDaoImpl(); Logger log; public CustomerServiceImpl(){ PropertyConfigurator.configure("resources/customerlog.properties"); //log = Logger.getLogger("Logy"); myLogger.setLevel((Level)Level.WARNING); myLogger.info("Constuctor created"); } public boolean addNew(long id, String name, String email, String phone, String address) { try{ new ValidateID(id); new ValidateName(name); new ValidateEmail(email); new ValidatePhone(Long.parseLong(phone)); obj.addNew(id, name, email, phone, address); } catch(CustomException e){ myLogger.log(Level.WARNING, "Custom Exception Handled: Invalid Details inputed by User"); System.out.println(e); } return true; } public boolean modifyDetails(String id, String name, String email, String phone, String address) { try{ new ValidateID(Long.parseLong(id)); if(!name.equalsIgnoreCase("null")) new ValidateName(name); if(!email.equalsIgnoreCase("null")) new ValidateEmail(email); if(!phone.equalsIgnoreCase("null")) new ValidatePhone(Long.parseLong(phone)); obj.modifyDetails(id, name, email, phone, address); System.out.println("Returning "); } catch(CustomException e){ myLogger.log(Level.WARNING, "Custom Exception Handled: Invalid Details inputed by User"); System.out.println("In ServiceImpl>> "+e); } return true; } public boolean deleteAll() { return obj.deleteAll(); } public boolean delete(String id) { obj.delete(id); return true; } public List<CustomerDTO> fetchAll() { /* String all = null; for(CustomerDTO itr:obj.fetchAll() ) all += (itr +"\n"); obj.fetchAll().forEach((custStr)-> all+=custStr);*/ return obj.fetchAll(); } public String fetchName(String name) { return obj.fetchName(name); } }
UTF-8
Java
2,285
java
CustomerServiceImpl.java
Java
[]
null
[]
package com.cg.service; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.log4j.PropertyConfigurator; import com.cg.dao.CustomerDaoImpl; import com.cg.dto.CustomerDTO; import com.cg.exception.CustomException; public class CustomerServiceImpl implements CustomerService{ static Logger myLogger = Logger.getLogger(CustomerDaoImpl.class.getName()); CustomerDaoImpl obj = new CustomerDaoImpl(); Logger log; public CustomerServiceImpl(){ PropertyConfigurator.configure("resources/customerlog.properties"); //log = Logger.getLogger("Logy"); myLogger.setLevel((Level)Level.WARNING); myLogger.info("Constuctor created"); } public boolean addNew(long id, String name, String email, String phone, String address) { try{ new ValidateID(id); new ValidateName(name); new ValidateEmail(email); new ValidatePhone(Long.parseLong(phone)); obj.addNew(id, name, email, phone, address); } catch(CustomException e){ myLogger.log(Level.WARNING, "Custom Exception Handled: Invalid Details inputed by User"); System.out.println(e); } return true; } public boolean modifyDetails(String id, String name, String email, String phone, String address) { try{ new ValidateID(Long.parseLong(id)); if(!name.equalsIgnoreCase("null")) new ValidateName(name); if(!email.equalsIgnoreCase("null")) new ValidateEmail(email); if(!phone.equalsIgnoreCase("null")) new ValidatePhone(Long.parseLong(phone)); obj.modifyDetails(id, name, email, phone, address); System.out.println("Returning "); } catch(CustomException e){ myLogger.log(Level.WARNING, "Custom Exception Handled: Invalid Details inputed by User"); System.out.println("In ServiceImpl>> "+e); } return true; } public boolean deleteAll() { return obj.deleteAll(); } public boolean delete(String id) { obj.delete(id); return true; } public List<CustomerDTO> fetchAll() { /* String all = null; for(CustomerDTO itr:obj.fetchAll() ) all += (itr +"\n"); obj.fetchAll().forEach((custStr)-> all+=custStr);*/ return obj.fetchAll(); } public String fetchName(String name) { return obj.fetchName(name); } }
2,285
0.697593
0.697155
77
27.675325
23.746738
99
false
false
0
0
0
0
0
0
2.38961
false
false
6
4aab44dc49fc56e3ceb9f0ee2f2f6ba3394aadb2
11,879,879,594,576
ceb9286bc2eb870c553acc0ca3fd97f252d6f8af
/Sem12/EurekaApp/src/pe/egcc/eurekaapp/view/ClienteView.java
526f4de79d205d2d545a6ad5f93494cf4359b679
[]
no_license
gcoronelc/UCH_PROG-I_2017-1
https://github.com/gcoronelc/UCH_PROG-I_2017-1
2c38a76bddad4680cd40433e79d93251e36a09df
1e6e2e118957954b79d6098d4fc9b0187c0207cd
refs/heads/master
2020-05-21T06:20:31.440000
2017-07-14T17:34:03
2017-07-14T17:34:03
84,587,319
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package pe.egcc.eurekaapp.view; import java.util.Map; import javax.swing.JOptionPane; import pe.egcc.eurekaapp.controller.ClienteController; /** * * @author docente */ public class ClienteView extends javax.swing.JFrame { private ClienteController control; /** * Creates new form ClienteView */ public ClienteView() { initComponents(); control = new ClienteController(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); txtCodigo = new javax.swing.JTextField(); btnConsultar = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); txtRepo = new javax.swing.JTextArea(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("CONSULTAR CLIENTE"); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel1.setText("Código:"); txtCodigo.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N btnConsultar.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N btnConsultar.setText("Consultar"); btnConsultar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnConsultarActionPerformed(evt); } }); txtRepo.setColumns(20); txtRepo.setRows(5); jScrollPane1.setViewportView(txtRepo); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(44, 44, 44) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jScrollPane1) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(28, 28, 28) .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(28, 28, 28) .addComponent(btnConsultar, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(41, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnConsultar, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 294, Short.MAX_VALUE) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btnConsultarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConsultarActionPerformed try { txtRepo.setText(""); // Dato String codigo = txtCodigo.getText(); // Proceso Map<String,Object> row = control.getcliente(codigo); if(row == null){ throw new Exception("Código no existe."); } // Reporte for(String key: row.keySet()){ txtRepo.append(key + ": " + row.get(key) + "\n"); } } catch (Exception e) { JOptionPane.showMessageDialog(rootPane, e.getMessage(), "ERROR", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_btnConsultarActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(ClienteView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ClienteView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ClienteView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ClienteView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new ClienteView().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnConsultar; private javax.swing.JLabel jLabel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextField txtCodigo; private javax.swing.JTextArea txtRepo; // End of variables declaration//GEN-END:variables }
UTF-8
Java
7,092
java
ClienteView.java
Java
[ { "context": "p.controller.ClienteController;\n\n/**\n *\n * @author docente\n */\npublic class ClienteView extends javax.swing.", "end": 353, "score": 0.9987956285476685, "start": 346, "tag": "USERNAME", "value": "docente" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package pe.egcc.eurekaapp.view; import java.util.Map; import javax.swing.JOptionPane; import pe.egcc.eurekaapp.controller.ClienteController; /** * * @author docente */ public class ClienteView extends javax.swing.JFrame { private ClienteController control; /** * Creates new form ClienteView */ public ClienteView() { initComponents(); control = new ClienteController(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); txtCodigo = new javax.swing.JTextField(); btnConsultar = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); txtRepo = new javax.swing.JTextArea(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("CONSULTAR CLIENTE"); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel1.setText("Código:"); txtCodigo.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N btnConsultar.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N btnConsultar.setText("Consultar"); btnConsultar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnConsultarActionPerformed(evt); } }); txtRepo.setColumns(20); txtRepo.setRows(5); jScrollPane1.setViewportView(txtRepo); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(44, 44, 44) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jScrollPane1) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(28, 28, 28) .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(28, 28, 28) .addComponent(btnConsultar, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(41, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnConsultar, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 294, Short.MAX_VALUE) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btnConsultarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConsultarActionPerformed try { txtRepo.setText(""); // Dato String codigo = txtCodigo.getText(); // Proceso Map<String,Object> row = control.getcliente(codigo); if(row == null){ throw new Exception("Código no existe."); } // Reporte for(String key: row.keySet()){ txtRepo.append(key + ": " + row.get(key) + "\n"); } } catch (Exception e) { JOptionPane.showMessageDialog(rootPane, e.getMessage(), "ERROR", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_btnConsultarActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(ClienteView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ClienteView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ClienteView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ClienteView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new ClienteView().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnConsultar; private javax.swing.JLabel jLabel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextField txtCodigo; private javax.swing.JTextArea txtRepo; // End of variables declaration//GEN-END:variables }
7,092
0.63512
0.625952
158
43.873417
36.177433
138
false
false
0
0
0
0
0
0
0.632911
false
false
6
09030c7a1cb16eab08ff7ee6a6354fd2de79881b
24,481,313,619,511
d0b5a38740ba4a47ec0c416c2f2032cd7ef7f356
/app/src/main/java/com/darkdeymon/ceub_potosi/clases/CentrosSalud.java
ab9629ef7b3bd50cba4236b68bac77dd1a67f219
[]
no_license
DARKDEYMON/CEUB-Potosi-Coregido
https://github.com/DARKDEYMON/CEUB-Potosi-Coregido
0b3bf4fcb24afe3dddcb3135570e6a69d62a3fb0
cbc564fc1a44b8130a64b034dd91a474ac89bb85
refs/heads/master
2020-03-17T22:14:07.853000
2018-05-21T16:19:52
2018-05-21T16:19:52
133,995,015
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.darkdeymon.ceub_potosi.clases; import com.google.android.gms.maps.model.LatLng; public class CentrosSalud { private String nombre; private String zona; private String telefono; private LatLng ubicacion; public CentrosSalud(String nombre, String zona, String telefono, float Lat, float Lng) { this.nombre = nombre; this.zona = zona; this.telefono = telefono; this.ubicacion = new LatLng(Lat,Lng); } public String getNombre() { return nombre.toUpperCase(); } public void setNombre(String nombre) { this.nombre = nombre; } public String getZona() { return zona; } public void setZona(String zona) { this.zona = zona; } public String getTelefono() { return telefono; } public void setTelefono(String telefono) { this.telefono = telefono; } public LatLng getUbicacion() { return ubicacion; } public void setUbicacion(LatLng ubicacion) { this.ubicacion = ubicacion; } }
UTF-8
Java
1,071
java
CentrosSalud.java
Java
[]
null
[]
package com.darkdeymon.ceub_potosi.clases; import com.google.android.gms.maps.model.LatLng; public class CentrosSalud { private String nombre; private String zona; private String telefono; private LatLng ubicacion; public CentrosSalud(String nombre, String zona, String telefono, float Lat, float Lng) { this.nombre = nombre; this.zona = zona; this.telefono = telefono; this.ubicacion = new LatLng(Lat,Lng); } public String getNombre() { return nombre.toUpperCase(); } public void setNombre(String nombre) { this.nombre = nombre; } public String getZona() { return zona; } public void setZona(String zona) { this.zona = zona; } public String getTelefono() { return telefono; } public void setTelefono(String telefono) { this.telefono = telefono; } public LatLng getUbicacion() { return ubicacion; } public void setUbicacion(LatLng ubicacion) { this.ubicacion = ubicacion; } }
1,071
0.628385
0.628385
49
20.857143
19.155645
92
false
false
0
0
0
0
0
0
0.469388
false
false
6
8137f61675fe5ef4df8f9cccd195e234bfbad406
16,673,063,088,080
8e48dee8aec288f6e5789751228b5181c9373a3d
/src/main/java/com/webservice/controller/UserController.java
ad7cbd66425c5951443dcda4b6f9f31792f10814
[]
no_license
palakchaurasia27/ecomm-9
https://github.com/palakchaurasia27/ecomm-9
7ae84967b933d840e7b9a256a0c5e2210d53cca0
3917349d7714a8922247da94eba890e294b57321
refs/heads/main
2023-08-29T06:24:38.552000
2021-11-16T08:32:53
2021-11-16T08:32:53
427,837,642
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.webservice.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.webservice.entity.User; import com.webservice.exceptions.InvalidUserException; import com.webservice.exceptions.UserNotFoundException; import com.webservice.repository.UserRepository; @RestController @RequestMapping("/api/admin") public class UserController { @Autowired UserRepository uRepo; // list all users @GetMapping("/users") public List<User> getUsers() { List<User> list = uRepo.findAll(); if (!list.isEmpty()) { return list; } throw new UserNotFoundException("User list is empty !"); } // get one user @GetMapping("/users/{id}") public User getUsers(@PathVariable("id") long id) { User fetchedUser = uRepo.findById(id).orElseThrow(() -> { throw new UserNotFoundException("User does not exist with id " + id); }); return fetchedUser; } // create user @PostMapping("/users") public User addUser(@RequestBody(required=false) User userObj) { if(userObj !=null) { return uRepo.save(userObj); } throw new InvalidUserException("User creation failed ! missing user object !"); } // update user @PutMapping("/users") public User updateUser(@RequestBody User userObj) { // step 1: find product User fetchedUser = uRepo.findById(userObj.getUserId()).orElseThrow(() -> { throw new UserNotFoundException("User does not exist with id " + userObj.getUserId()); }); // step 2: Map updating fields fetchedUser.setUserName(userObj.getUserName()); fetchedUser.setUserEmail(userObj.getUserEmail()); fetchedUser.setUserPwd(userObj.getUserPwd()); fetchedUser.setUserRole(userObj.getUserRole()); // step 3: update return uRepo.save(fetchedUser); } // delete one user @DeleteMapping("/users/{id}") public void deleteUser(@PathVariable("id") long id) { // step 1: find product User fetchedUser = uRepo.findById(id).orElseThrow(() -> { throw new UserNotFoundException("User does not exist with id " + id); }); // step 2: delete uRepo.delete(fetchedUser); } }
UTF-8
Java
2,559
java
UserController.java
Java
[]
null
[]
package com.webservice.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.webservice.entity.User; import com.webservice.exceptions.InvalidUserException; import com.webservice.exceptions.UserNotFoundException; import com.webservice.repository.UserRepository; @RestController @RequestMapping("/api/admin") public class UserController { @Autowired UserRepository uRepo; // list all users @GetMapping("/users") public List<User> getUsers() { List<User> list = uRepo.findAll(); if (!list.isEmpty()) { return list; } throw new UserNotFoundException("User list is empty !"); } // get one user @GetMapping("/users/{id}") public User getUsers(@PathVariable("id") long id) { User fetchedUser = uRepo.findById(id).orElseThrow(() -> { throw new UserNotFoundException("User does not exist with id " + id); }); return fetchedUser; } // create user @PostMapping("/users") public User addUser(@RequestBody(required=false) User userObj) { if(userObj !=null) { return uRepo.save(userObj); } throw new InvalidUserException("User creation failed ! missing user object !"); } // update user @PutMapping("/users") public User updateUser(@RequestBody User userObj) { // step 1: find product User fetchedUser = uRepo.findById(userObj.getUserId()).orElseThrow(() -> { throw new UserNotFoundException("User does not exist with id " + userObj.getUserId()); }); // step 2: Map updating fields fetchedUser.setUserName(userObj.getUserName()); fetchedUser.setUserEmail(userObj.getUserEmail()); fetchedUser.setUserPwd(userObj.getUserPwd()); fetchedUser.setUserRole(userObj.getUserRole()); // step 3: update return uRepo.save(fetchedUser); } // delete one user @DeleteMapping("/users/{id}") public void deleteUser(@PathVariable("id") long id) { // step 1: find product User fetchedUser = uRepo.findById(id).orElseThrow(() -> { throw new UserNotFoundException("User does not exist with id " + id); }); // step 2: delete uRepo.delete(fetchedUser); } }
2,559
0.749512
0.747558
82
30.219513
24.372128
89
false
false
0
0
0
0
0
0
1.47561
false
false
6
269043dfaa7872cdece533de563b4b42ffc7419e
20,340,965,157,764
84f9964ce782e5a0138e616f2588d0c12bc76c3b
/src/main/java/com/lsx/study/ProducerAndConsumer/Producer.java
dfb31b395f8fd9cbd8dde1660e1251b5b8fb9058
[]
no_license
liushuangxiao/DesignPatterns
https://github.com/liushuangxiao/DesignPatterns
6848fef82c743123fb3c71b5c9071abda9d9d30d
30ebcb975554710db184e6dd6b12c7e4af87e5f5
refs/heads/master
2020-05-20T21:03:47.145000
2018-03-14T12:22:32
2018-03-14T12:22:32
84,524,028
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lsx.study.ProducerAndConsumer; /** * @author kebi on 2017/3/14. */ public class Producer { }
UTF-8
Java
111
java
Producer.java
Java
[ { "context": "com.lsx.study.ProducerAndConsumer;\n\n/**\n * @author kebi on 2017/3/14.\n */\npublic class Producer {\n\n\n\n}\n", "end": 63, "score": 0.9994975924491882, "start": 59, "tag": "USERNAME", "value": "kebi" } ]
null
[]
package com.lsx.study.ProducerAndConsumer; /** * @author kebi on 2017/3/14. */ public class Producer { }
111
0.675676
0.612613
10
10.1
14.604451
42
false
false
0
0
0
0
0
0
0.1
false
false
6
9171f7814b2b508c40d01ab2f92e891cb61e4337
18,476,949,357,590
87b45223cb6b4e25bc3ed9ee737d385a913b7f3c
/action-executor/src/main/java/at/ac/tuwien/infosys/viepepc/actionexecutor/ProcessStepExecutorController.java
994a05a9feff338370d71bc0ada1475582536137
[]
no_license
piwa/ViePEP-C
https://github.com/piwa/ViePEP-C
3f87dd3d6a6c4fe4f4e56c2d6a63f8465ca12de6
45e1891145a5b27b3013bef008fbb297af7bbee1
refs/heads/master
2022-05-16T08:30:01.360000
2019-09-09T15:08:02
2019-09-09T15:08:02
71,267,556
0
0
null
false
2018-02-07T14:51:04
2016-10-18T16:18:33
2016-10-18T16:22:21
2018-02-07T14:51:04
894
0
0
0
Java
false
null
package at.ac.tuwien.infosys.viepepc.actionexecutor; import at.ac.tuwien.infosys.viepepc.library.entities.workflow.ProcessStep; import at.ac.tuwien.infosys.viepepc.library.entities.workflow.ProcessStepStatus; import at.ac.tuwien.infosys.viepepc.serviceexecutor.ServiceExecution; import at.ac.tuwien.infosys.viepepc.serviceexecutor.invoker.ServiceInvokeException; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; import java.util.List; @Component @Slf4j public class ProcessStepExecutorController { @Autowired private ServiceExecution serviceExecution; @Async public void startProcessStepExecution(ProcessStep processStep) { processStep.setProcessStepStatus(ProcessStepStatus.DEPLOYING); try { serviceExecution.startExecution(processStep, processStep.getContainer()); } catch (ServiceInvokeException e) { log.error("Exception while invoking service. Stop VM and reset.", e); reset(processStep); } } private void reset(ProcessStep processStep) { // TODO // cacheProcessStepService.getProcessStepsWaitingForExecution().remove(processStep); // cacheProcessStepService.getProcessStepsWaitingForServiceDone().remove(processStep.getName()); processStep.reset(); } }
UTF-8
Java
1,444
java
ProcessStepExecutorController.java
Java
[]
null
[]
package at.ac.tuwien.infosys.viepepc.actionexecutor; import at.ac.tuwien.infosys.viepepc.library.entities.workflow.ProcessStep; import at.ac.tuwien.infosys.viepepc.library.entities.workflow.ProcessStepStatus; import at.ac.tuwien.infosys.viepepc.serviceexecutor.ServiceExecution; import at.ac.tuwien.infosys.viepepc.serviceexecutor.invoker.ServiceInvokeException; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; import java.util.List; @Component @Slf4j public class ProcessStepExecutorController { @Autowired private ServiceExecution serviceExecution; @Async public void startProcessStepExecution(ProcessStep processStep) { processStep.setProcessStepStatus(ProcessStepStatus.DEPLOYING); try { serviceExecution.startExecution(processStep, processStep.getContainer()); } catch (ServiceInvokeException e) { log.error("Exception while invoking service. Stop VM and reset.", e); reset(processStep); } } private void reset(ProcessStep processStep) { // TODO // cacheProcessStepService.getProcessStepsWaitingForExecution().remove(processStep); // cacheProcessStepService.getProcessStepsWaitingForServiceDone().remove(processStep.getName()); processStep.reset(); } }
1,444
0.765928
0.76385
42
33.380951
31.885176
101
false
false
0
0
0
0
0
0
0.47619
false
false
6
087b21c635259288238eac18f483b4a6f21c25c5
18,476,949,355,129
c8ddd884cc3fd84420cd5fa699fe6989804841a8
/teht_18/src/prototype/Clock.java
b4f4dfa5cc8b6f7eeaa6eb3aa7f21863f01a2382
[]
no_license
qqmss/Suunnittelumallit-2020
https://github.com/qqmss/Suunnittelumallit-2020
6d7f4901ce62a3ef48c557fd63a317a438b96d6e
684873e5f4e5a2bd3121984dc0d4a9cff7f29c25
refs/heads/master
2021-04-07T20:19:50.459000
2020-05-05T09:12:45
2020-05-05T09:12:45
248,705,935
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package prototype; public class Clock implements Cloneable{ private Second second; private Minute minute; private Hour hour; public Clock(Second second, Minute minute, Hour hour) { this.second = second; this.minute = minute; this.hour = hour; } public Second getSecond() { return second; } public Minute getMinute() { return minute; } public Hour getHour() { return hour; } public void setSecond(Second second) { this.second = second; } public void setMinute(Minute minute) { this.minute = minute; } public void setHour(Hour hour) { this.hour = hour; } @Override public String toString() { return hour.getH() + ":" + minute.getM() + ":" +second.getS(); } @Override public Object clone() throws CloneNotSupportedException { Clock clock = (Clock) super.clone(); clock.setHour((Hour) hour.clone()); clock.setMinute((Minute) minute.clone()); clock.second = (Second) second.clone(); return clock; } }
UTF-8
Java
1,120
java
Clock.java
Java
[]
null
[]
package prototype; public class Clock implements Cloneable{ private Second second; private Minute minute; private Hour hour; public Clock(Second second, Minute minute, Hour hour) { this.second = second; this.minute = minute; this.hour = hour; } public Second getSecond() { return second; } public Minute getMinute() { return minute; } public Hour getHour() { return hour; } public void setSecond(Second second) { this.second = second; } public void setMinute(Minute minute) { this.minute = minute; } public void setHour(Hour hour) { this.hour = hour; } @Override public String toString() { return hour.getH() + ":" + minute.getM() + ":" +second.getS(); } @Override public Object clone() throws CloneNotSupportedException { Clock clock = (Clock) super.clone(); clock.setHour((Hour) hour.clone()); clock.setMinute((Minute) minute.clone()); clock.second = (Second) second.clone(); return clock; } }
1,120
0.583929
0.583929
53
20.132076
18.499401
70
false
false
0
0
0
0
0
0
0.396226
false
false
6
efc834e787392da97b5aa4319a2ef440ff0b1d37
32,736,240,781,490
f62396e8d8f2f130f660a9e12c3e91a05414a79d
/pasticceria-unicorno/src/main/java/it/dstech/models/Ricetta.java
7081bc2a7f4056d53dcf3f30ac20a6a5ad29f6cf
[]
no_license
marco-12/PasticceriaUnicorno
https://github.com/marco-12/PasticceriaUnicorno
619de056d23b15add56af00ee2b8311f29a08c6f
67b28f2794110407a8d1fec0038e7886bad63c8f
refs/heads/master
2022-11-07T04:02:37.058000
2020-07-01T11:03:46
2020-07-01T11:03:46
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package it.dstech.models; import java.util.List; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; @Entity public class Ricetta { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String nome; private String tempoDiRealizzazione; private int difficoltà; @OneToMany(fetch = FetchType.EAGER) private List<Ingrediente> ingrediente; private String descrizione; private double costoRicetta10; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getTempoDiRealizzazione() { return tempoDiRealizzazione; } public void setTempoDiRealizzazione(String tempoDiRealizzazione) { this.tempoDiRealizzazione = tempoDiRealizzazione; } public int getDifficoltà() { return difficoltà; } public void setDifficoltà(int difficoltà) { this.difficoltà = difficoltà; } public List<Ingrediente> getIngrediente() { return ingrediente; } public void setIngrediente(List<Ingrediente> ingrediente) { this.ingrediente = ingrediente; } public String getDescrizione() { return descrizione; } public void setDescrizione(String descrizione) { this.descrizione = descrizione; } public double getCostoRicetta10() { return costoRicetta10; } public void setCostoRicetta10(double costoRicetta10) { this.costoRicetta10 = costoRicetta10; } }
UTF-8
Java
1,683
java
Ricetta.java
Java
[]
null
[]
package it.dstech.models; import java.util.List; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; @Entity public class Ricetta { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String nome; private String tempoDiRealizzazione; private int difficoltà; @OneToMany(fetch = FetchType.EAGER) private List<Ingrediente> ingrediente; private String descrizione; private double costoRicetta10; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getTempoDiRealizzazione() { return tempoDiRealizzazione; } public void setTempoDiRealizzazione(String tempoDiRealizzazione) { this.tempoDiRealizzazione = tempoDiRealizzazione; } public int getDifficoltà() { return difficoltà; } public void setDifficoltà(int difficoltà) { this.difficoltà = difficoltà; } public List<Ingrediente> getIngrediente() { return ingrediente; } public void setIngrediente(List<Ingrediente> ingrediente) { this.ingrediente = ingrediente; } public String getDescrizione() { return descrizione; } public void setDescrizione(String descrizione) { this.descrizione = descrizione; } public double getCostoRicetta10() { return costoRicetta10; } public void setCostoRicetta10(double costoRicetta10) { this.costoRicetta10 = costoRicetta10; } }
1,683
0.754773
0.74642
96
16.458334
17.822573
67
false
false
0
0
0
0
0
0
1.114583
false
false
6
c78367304b4c8a248a48d22c79a149ab929abe49
12,077,448,097,491
b55caaf5548f06ef525ebdc2254955a643d3d5bb
/gs1-pds/gs1-pds-client/src/main/java/org/gs1us/sgg/gbservice/api/BillingTransaction.java
0e0b944620f91e8d05472275817920dbec68b885
[]
no_license
GS1-APPS/Siddharth-582017
https://github.com/GS1-APPS/Siddharth-582017
d0dbf9300dcf2c3b8680546b50fc1af1a273f377
7aeca4191e95cae276a5be22e6058f24e7b89fe3
refs/heads/master
2021-01-20T14:53:33.660000
2017-06-30T02:26:31
2017-06-30T02:26:31
90,685,142
1
1
null
false
2017-06-30T02:26:32
2017-05-09T00:36:50
2017-06-01T21:26:32
2017-06-30T02:26:31
56,408
1
1
0
Java
null
null
package org.gs1us.sgg.gbservice.api; import java.util.Date; public interface BillingTransaction { BillingTransactionType getType(); Date getDate(); String getReference(); String getDescription(); Amount getAmount(); Amount getBalance(); }
UTF-8
Java
265
java
BillingTransaction.java
Java
[]
null
[]
package org.gs1us.sgg.gbservice.api; import java.util.Date; public interface BillingTransaction { BillingTransactionType getType(); Date getDate(); String getReference(); String getDescription(); Amount getAmount(); Amount getBalance(); }
265
0.716981
0.713208
13
19.384615
13.635578
37
false
false
0
0
0
0
0
0
0.615385
false
false
6
7c45cbe6f658a57de0be5241df063acf69882fee
936,302,883,468
68b801a185c1e9a9f29e1c9850c644183e26ca0d
/src/main/java/tree/binarysearch/problems/Problem009.java
b614147b4801c97c98ce248670646c34f29f02c0
[]
no_license
avishekgurung/algo
https://github.com/avishekgurung/algo
c081f8fbd11d22eed87d17a6db7e6f5aa52c0706
c63f86634d94bb4b74dbb17f4b51129bcc7b7e17
refs/heads/master
2021-08-03T00:08:25.868000
2021-07-27T05:43:07
2021-07-27T05:43:07
155,651,748
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package tree.binarysearch.problems; import tree.binarysearch.util.BinarySearchTree; import tree.binarysearch.util.Node; public class Problem009 { private static Node prev = null; /** * The BT can now be used as a DLL as where left pointer is same prev and right * pointer is same as next in DLL. * @param root */ public static void convertBstToDll(Node root) { if(root == null) return; convertBstToDll(root.left); if(prev != null) { prev.right = root; root.left = prev; } prev = root; convertBstToDll(root.right); } private static void displayDll(Node head) { while(head != null) { System.out.print(head.data + " --> "); head = head.right; } System.out.println(); } private static Node getLeftMostNode(Node root) { while(root.left != null) root = root.left; return root; } public static void main(String[] args) { Node root = BinarySearchTree.getTree(); Node head = getLeftMostNode(root); BinarySearchTree.display(root); convertBstToDll(root); displayDll(head); } }
UTF-8
Java
1,093
java
Problem009.java
Java
[]
null
[]
package tree.binarysearch.problems; import tree.binarysearch.util.BinarySearchTree; import tree.binarysearch.util.Node; public class Problem009 { private static Node prev = null; /** * The BT can now be used as a DLL as where left pointer is same prev and right * pointer is same as next in DLL. * @param root */ public static void convertBstToDll(Node root) { if(root == null) return; convertBstToDll(root.left); if(prev != null) { prev.right = root; root.left = prev; } prev = root; convertBstToDll(root.right); } private static void displayDll(Node head) { while(head != null) { System.out.print(head.data + " --> "); head = head.right; } System.out.println(); } private static Node getLeftMostNode(Node root) { while(root.left != null) root = root.left; return root; } public static void main(String[] args) { Node root = BinarySearchTree.getTree(); Node head = getLeftMostNode(root); BinarySearchTree.display(root); convertBstToDll(root); displayDll(head); } }
1,093
0.651418
0.648673
46
22.76087
18.610638
81
false
false
0
0
0
0
0
0
0.434783
false
false
6
41af2ec438d10ff7164132a340401e304008ffb5
1,374,389,546,354
b659613c10ac2ab3b8664d9c7781823a4553572d
/src/main/java/org/infosystema/peakcoin/conversation/ConversationUser.java
6321d81e1af12ccf0f3afb5de5e9e6f48c7fd3dd
[]
no_license
beksay/peakcoin
https://github.com/beksay/peakcoin
72315f986e3d5f07ad9aa38f1e8fd90110ec1ee2
8d4f80835f07fd49d6ac0a094458a641b1595a33
refs/heads/master
2022-12-11T20:26:29.528000
2020-09-18T04:25:12
2020-09-18T04:25:12
296,512,685
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.infosystema.peakcoin.conversation; import javax.enterprise.context.ConversationScoped; import javax.inject.Named; import org.infosystema.peakcoin.annotation.Logged; import org.infosystema.peakcoin.controller.base.Conversational; import org.infosystema.peakcoin.domain.Company; import org.infosystema.peakcoin.domain.Person; import org.infosystema.peakcoin.domain.Role; import org.infosystema.peakcoin.domain.User; /** * * @author Kuttubek Aidaraliev * */ @Logged @Named @ConversationScoped public class ConversationUser extends Conversational { private static final long serialVersionUID = -6100072166946495229L; private User user; private Person person; private Role role; private Company company; public User getUser() { return user; } public void setUser(User user) { this.user = user; } public Role getRole() { return role; } public void setRole(Role role) { this.role = role; } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } public Company getCompany() { return company; } public void setCompany(Company company) { this.company = company; } }
UTF-8
Java
1,180
java
ConversationUser.java
Java
[ { "context": "osystema.peakcoin.domain.User;\n\n/**\n * \n * @author Kuttubek Aidaraliev\n *\n */\n@Logged\n@Named\n@ConversationScoped\npublic ", "end": 467, "score": 0.9998725056648254, "start": 448, "tag": "NAME", "value": "Kuttubek Aidaraliev" } ]
null
[]
package org.infosystema.peakcoin.conversation; import javax.enterprise.context.ConversationScoped; import javax.inject.Named; import org.infosystema.peakcoin.annotation.Logged; import org.infosystema.peakcoin.controller.base.Conversational; import org.infosystema.peakcoin.domain.Company; import org.infosystema.peakcoin.domain.Person; import org.infosystema.peakcoin.domain.Role; import org.infosystema.peakcoin.domain.User; /** * * @author <NAME> * */ @Logged @Named @ConversationScoped public class ConversationUser extends Conversational { private static final long serialVersionUID = -6100072166946495229L; private User user; private Person person; private Role role; private Company company; public User getUser() { return user; } public void setUser(User user) { this.user = user; } public Role getRole() { return role; } public void setRole(Role role) { this.role = role; } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } public Company getCompany() { return company; } public void setCompany(Company company) { this.company = company; } }
1,167
0.755085
0.738983
61
18.344263
18.762436
68
false
false
0
0
0
0
0
0
1.032787
false
false
6
76524215272c7a54c1a76e80f5143a58416c061f
26,345,329,457,319
1240264c572125ba7975e79ef80a49ab26637776
/commons/src/main/java/io/wcm/sling/commons/caservice/impl/ContextAwareServiceTracker.java
b7f4fd9c89bf347cdf74f233714bcaa69e9bbdc3
[ "Apache-2.0" ]
permissive
wcm-io/wcm-io-sling
https://github.com/wcm-io/wcm-io-sling
3dc4d0bd610f2638b00b27491e5360b0ea593696
a4ca9d32ad7e0b0d252e61fb9486671c6e99fe04
refs/heads/master
2023-08-15T00:51:28.694000
2021-01-17T13:03:04
2021-01-17T13:03:04
39,159,871
3
4
null
false
2016-11-17T19:13:12
2015-07-15T20:35:26
2016-04-14T14:22:45
2016-11-17T19:13:11
253
2
2
0
Java
null
null
/* * #%L * wcm.io * %% * Copyright (C) 2017 wcm.io * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package io.wcm.sling.commons.caservice.impl; import java.util.stream.Stream; import org.apache.sling.api.resource.Resource; import org.apache.sling.commons.osgi.Order; import org.apache.sling.commons.osgi.RankedServices; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.osgi.util.tracker.ServiceTracker; import org.osgi.util.tracker.ServiceTrackerCustomizer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.wcm.sling.commons.caservice.ContextAwareService; import io.wcm.sling.commons.caservice.PathPreprocessor; class ContextAwareServiceTracker implements ServiceTrackerCustomizer<ContextAwareService, ServiceInfo> { private final BundleContext bundleContext; private final PathPreprocessor pathPreprocessor; private final ServiceTracker<ContextAwareService, ServiceInfo> serviceTracker; private volatile RankedServices<ServiceInfo> rankedServices; private volatile long lastServiceChange; private static final Logger log = LoggerFactory.getLogger(ContextAwareServiceTracker.class); ContextAwareServiceTracker(String serviceClassName, BundleContext bundleContext, PathPreprocessor pathPreprocessor) { this.bundleContext = bundleContext; this.pathPreprocessor = pathPreprocessor; this.rankedServices = new RankedServices<ServiceInfo>(Order.DESCENDING); this.serviceTracker = new ServiceTracker<ContextAwareService, ServiceInfo>(bundleContext, serviceClassName, this); this.serviceTracker.open(); } public void dispose() { serviceTracker.close(); rankedServices = null; } @Override public ServiceInfo addingService(ServiceReference<ContextAwareService> reference) { ServiceInfo serviceInfo = new ServiceInfo(reference, bundleContext); if (log.isDebugEnabled()) { log.debug("Add service {}", serviceInfo.getService().getClass().getName()); } if (rankedServices != null) { rankedServices.bind(serviceInfo, serviceInfo.getServiceProperties()); } lastServiceChange = System.currentTimeMillis(); return serviceInfo; } @Override public void modifiedService(ServiceReference<ContextAwareService> reference, ServiceInfo serviceInfo) { // nothing to do } @Override public void removedService(ServiceReference<ContextAwareService> reference, ServiceInfo serviceInfo) { if (log.isDebugEnabled()) { log.debug("Remove service {}", serviceInfo.getService().getClass().getName()); } if (rankedServices != null) { rankedServices.unbind(serviceInfo, serviceInfo.getServiceProperties()); } lastServiceChange = System.currentTimeMillis(); bundleContext.ungetService(reference); } public Stream<ServiceInfo> resolve(Resource resource) { if (rankedServices == null) { return Stream.empty(); } return rankedServices.getList().stream() .filter(serviceInfo -> matchesResource(serviceInfo, resource)); } private boolean matchesResource(ServiceInfo serviceInfo, Resource resource) { String path = null; if (resource != null) { path = resource.getPath(); if (pathPreprocessor != null) { // apply path preprocessor path = pathPreprocessor.apply(path, resource.getResourceResolver()); } } return serviceInfo.matches(path); } public long getLastServiceChangeTimestamp() { return this.lastServiceChange; } public Iterable<ServiceInfo> getServiceInfos() { return rankedServices; } }
UTF-8
Java
4,105
java
ContextAwareServiceTracker.java
Java
[]
null
[]
/* * #%L * wcm.io * %% * Copyright (C) 2017 wcm.io * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package io.wcm.sling.commons.caservice.impl; import java.util.stream.Stream; import org.apache.sling.api.resource.Resource; import org.apache.sling.commons.osgi.Order; import org.apache.sling.commons.osgi.RankedServices; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.osgi.util.tracker.ServiceTracker; import org.osgi.util.tracker.ServiceTrackerCustomizer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.wcm.sling.commons.caservice.ContextAwareService; import io.wcm.sling.commons.caservice.PathPreprocessor; class ContextAwareServiceTracker implements ServiceTrackerCustomizer<ContextAwareService, ServiceInfo> { private final BundleContext bundleContext; private final PathPreprocessor pathPreprocessor; private final ServiceTracker<ContextAwareService, ServiceInfo> serviceTracker; private volatile RankedServices<ServiceInfo> rankedServices; private volatile long lastServiceChange; private static final Logger log = LoggerFactory.getLogger(ContextAwareServiceTracker.class); ContextAwareServiceTracker(String serviceClassName, BundleContext bundleContext, PathPreprocessor pathPreprocessor) { this.bundleContext = bundleContext; this.pathPreprocessor = pathPreprocessor; this.rankedServices = new RankedServices<ServiceInfo>(Order.DESCENDING); this.serviceTracker = new ServiceTracker<ContextAwareService, ServiceInfo>(bundleContext, serviceClassName, this); this.serviceTracker.open(); } public void dispose() { serviceTracker.close(); rankedServices = null; } @Override public ServiceInfo addingService(ServiceReference<ContextAwareService> reference) { ServiceInfo serviceInfo = new ServiceInfo(reference, bundleContext); if (log.isDebugEnabled()) { log.debug("Add service {}", serviceInfo.getService().getClass().getName()); } if (rankedServices != null) { rankedServices.bind(serviceInfo, serviceInfo.getServiceProperties()); } lastServiceChange = System.currentTimeMillis(); return serviceInfo; } @Override public void modifiedService(ServiceReference<ContextAwareService> reference, ServiceInfo serviceInfo) { // nothing to do } @Override public void removedService(ServiceReference<ContextAwareService> reference, ServiceInfo serviceInfo) { if (log.isDebugEnabled()) { log.debug("Remove service {}", serviceInfo.getService().getClass().getName()); } if (rankedServices != null) { rankedServices.unbind(serviceInfo, serviceInfo.getServiceProperties()); } lastServiceChange = System.currentTimeMillis(); bundleContext.ungetService(reference); } public Stream<ServiceInfo> resolve(Resource resource) { if (rankedServices == null) { return Stream.empty(); } return rankedServices.getList().stream() .filter(serviceInfo -> matchesResource(serviceInfo, resource)); } private boolean matchesResource(ServiceInfo serviceInfo, Resource resource) { String path = null; if (resource != null) { path = resource.getPath(); if (pathPreprocessor != null) { // apply path preprocessor path = pathPreprocessor.apply(path, resource.getResourceResolver()); } } return serviceInfo.matches(path); } public long getLastServiceChangeTimestamp() { return this.lastServiceChange; } public Iterable<ServiceInfo> getServiceInfos() { return rankedServices; } }
4,105
0.749817
0.747381
118
33.788136
30.77002
119
false
false
0
0
0
0
0
0
0.550847
false
false
6
fe0fceb0fa2740ddfafa47ca9077088c4a7055b9
11,132,555,231,935
2ba747a642e5f012d9783a4f3c3b7dc2188466e0
/menu/src/main/java/com/miso/menu/MenuActivity.java
4ec7b633058280ddd29e4dc1a6edf465caeb42d7
[]
no_license
M187/TheGame
https://github.com/M187/TheGame
55f38c27513661bce7ec38d0e24b7ca7ae45f1fe
3a8e5a42ca5137b29c4ae6c460fb060fe37c3a29
refs/heads/master
2020-04-12T08:55:07.691000
2018-01-26T14:07:42
2018-01-26T14:07:42
53,611,562
0
0
null
false
2016-05-30T07:43:30
2016-03-10T19:36:27
2016-03-10T19:38:28
2016-05-29T17:19:04
23,849
0
0
1
Java
null
null
package com.miso.menu; import android.appwidget.AppWidgetManager; import android.content.ComponentName; import android.content.Intent; import android.content.Loader; import android.database.Cursor; import android.media.AudioManager; import android.media.MediaPlayer; import android.os.Bundle; import android.view.View; import android.view.WindowManager; import android.widget.RemoteViews; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; import com.miso.persistence.player.StatsActivityLoaderCallbackImpl; import com.miso.thegame.gameMechanics.map.levels.NewLevelActivity; public class MenuActivity extends StatsActivityLoaderCallbackImpl { public static String KILL_COUNT = "0"; private Intent gameIntent = null; private MediaPlayer mMediaPlayer; private AdView mAdView; private final int PLAYER_STATS_LIST_ID = 1110; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); this.setContentView(R.layout.activity_menu); mMediaPlayer = new MediaPlayer(); mMediaPlayer = MediaPlayer.create(this, R.raw.intro); mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mMediaPlayer.setLooping(false); //mMediaPlayer.start(); mAdView = (AdView) findViewById(R.id.adView); AdRequest adRequest = new AdRequest.Builder().build(); mAdView.loadAd(adRequest); ((TheGameApplication)getApplication()).startTracking(); getLoaderManager().initLoader(PLAYER_STATS_LIST_ID, null, this); } public void onResume(){ this.setContentView(R.layout.activity_menu); super.onResume(); if (mAdView != null) { mAdView.resume(); } } public void newGameClickGround(View view) { setContentView(R.layout.loading_game); this.gameIntent = new Intent(this, NewLevelActivity.class); this.gameIntent.putExtra("Level", "Ground"); startActivity(this.gameIntent); } public void newMultiplayerGame(View view){ this.gameIntent = new Intent(this, MultiplayerLobby.class); this.gameIntent.putExtra("Level", "Default"); startActivity(this.gameIntent); } @Override public void onPause() { if (mAdView != null) { mAdView.pause(); } super.onPause(); } public void onDestroy(){ if (mAdView != null) { mAdView.destroy(); } mMediaPlayer.stop(); super.onDestroy(); } public void playerOptionClick(View view){ Intent intent = new Intent(this, PlayerStats.class); startActivity(intent); } public void quitClick(View viev){ this.finish(); System.exit(0); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { data.moveToFirst(); KILL_COUNT = data.getString(0); AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this); RemoteViews remoteViews = new RemoteViews(this.getPackageName(), R.layout.game_widget_layout); remoteViews.setTextViewText(R.id.widget_player_kills, getResources().getString(R.string.options_kill_count) + data.getString(0)); remoteViews.setTextViewText(R.id.widget_player_level_points, getResources().getString(R.string.options_level_points) + data.getString(2)); appWidgetManager.updateAppWidget(appWidgetManager.getAppWidgetIds(new ComponentName(this, TheGameWidgetProvider.class)), remoteViews); } }
UTF-8
Java
3,680
java
MenuActivity.java
Java
[]
null
[]
package com.miso.menu; import android.appwidget.AppWidgetManager; import android.content.ComponentName; import android.content.Intent; import android.content.Loader; import android.database.Cursor; import android.media.AudioManager; import android.media.MediaPlayer; import android.os.Bundle; import android.view.View; import android.view.WindowManager; import android.widget.RemoteViews; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; import com.miso.persistence.player.StatsActivityLoaderCallbackImpl; import com.miso.thegame.gameMechanics.map.levels.NewLevelActivity; public class MenuActivity extends StatsActivityLoaderCallbackImpl { public static String KILL_COUNT = "0"; private Intent gameIntent = null; private MediaPlayer mMediaPlayer; private AdView mAdView; private final int PLAYER_STATS_LIST_ID = 1110; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); this.setContentView(R.layout.activity_menu); mMediaPlayer = new MediaPlayer(); mMediaPlayer = MediaPlayer.create(this, R.raw.intro); mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mMediaPlayer.setLooping(false); //mMediaPlayer.start(); mAdView = (AdView) findViewById(R.id.adView); AdRequest adRequest = new AdRequest.Builder().build(); mAdView.loadAd(adRequest); ((TheGameApplication)getApplication()).startTracking(); getLoaderManager().initLoader(PLAYER_STATS_LIST_ID, null, this); } public void onResume(){ this.setContentView(R.layout.activity_menu); super.onResume(); if (mAdView != null) { mAdView.resume(); } } public void newGameClickGround(View view) { setContentView(R.layout.loading_game); this.gameIntent = new Intent(this, NewLevelActivity.class); this.gameIntent.putExtra("Level", "Ground"); startActivity(this.gameIntent); } public void newMultiplayerGame(View view){ this.gameIntent = new Intent(this, MultiplayerLobby.class); this.gameIntent.putExtra("Level", "Default"); startActivity(this.gameIntent); } @Override public void onPause() { if (mAdView != null) { mAdView.pause(); } super.onPause(); } public void onDestroy(){ if (mAdView != null) { mAdView.destroy(); } mMediaPlayer.stop(); super.onDestroy(); } public void playerOptionClick(View view){ Intent intent = new Intent(this, PlayerStats.class); startActivity(intent); } public void quitClick(View viev){ this.finish(); System.exit(0); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { data.moveToFirst(); KILL_COUNT = data.getString(0); AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this); RemoteViews remoteViews = new RemoteViews(this.getPackageName(), R.layout.game_widget_layout); remoteViews.setTextViewText(R.id.widget_player_kills, getResources().getString(R.string.options_kill_count) + data.getString(0)); remoteViews.setTextViewText(R.id.widget_player_level_points, getResources().getString(R.string.options_level_points) + data.getString(2)); appWidgetManager.updateAppWidget(appWidgetManager.getAppWidgetIds(new ComponentName(this, TheGameWidgetProvider.class)), remoteViews); } }
3,680
0.694022
0.691576
111
32.153152
30.430307
146
false
false
0
0
0
0
0
0
0.675676
false
false
6
0cdf3d199c4c0905453c4fad94bb32e2c2074063
20,048,907,390,849
2a6ce6d5ad9f5f6cc743629d096d6f7fdfc47305
/ColdFusion-core/src/main/java/com/freifeld/coldfusion/priority/PriorityTuple.java
c153b1b71c55d88ce5252a8fa19ecc48b12d860b
[ "Apache-2.0" ]
permissive
FreifeldRoyi/ColdFusion
https://github.com/FreifeldRoyi/ColdFusion
db2417026d4d057c9850e860b3c9506d796f00b9
78db6afef0be6522d30f85961d146d19d66d390f
refs/heads/master
2018-07-16T15:49:11.590000
2018-07-02T11:11:57
2018-07-02T11:11:57
135,738,745
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.freifeld.coldfusion.priority; import com.freifeld.coldfusion.FuseClassMetaData; import java.util.Comparator; public class PriorityTuple<S> { public static final Comparator<PriorityTuple<?>> PRIORITY_TUPLE_COMPARATOR = Comparator.comparingDouble(PriorityTuple::getPriority); private final S source; private final String targetPropertyName; private final FuseClassMetaData<S> sourceMetaData; private final Object sourceValue; private final double priority; public PriorityTuple(S source, String targetPropertyName, FuseClassMetaData<S> sourceMetaData, Object sourceValue, double priority) { this.source = source; this.targetPropertyName = targetPropertyName; this.sourceMetaData = sourceMetaData; this.sourceValue = sourceValue; this.priority = priority; } public S getSource() { return source; } public String getTargetPropertyName() { return this.targetPropertyName; } public FuseClassMetaData<S> getSourceMetaData() { return this.sourceMetaData; } public Object getSourceValue() { return this.sourceValue; } public boolean hasValue() { return this.sourceValue != null; } public double getPriority() { return this.priority; } }
UTF-8
Java
1,200
java
PriorityTuple.java
Java
[]
null
[]
package com.freifeld.coldfusion.priority; import com.freifeld.coldfusion.FuseClassMetaData; import java.util.Comparator; public class PriorityTuple<S> { public static final Comparator<PriorityTuple<?>> PRIORITY_TUPLE_COMPARATOR = Comparator.comparingDouble(PriorityTuple::getPriority); private final S source; private final String targetPropertyName; private final FuseClassMetaData<S> sourceMetaData; private final Object sourceValue; private final double priority; public PriorityTuple(S source, String targetPropertyName, FuseClassMetaData<S> sourceMetaData, Object sourceValue, double priority) { this.source = source; this.targetPropertyName = targetPropertyName; this.sourceMetaData = sourceMetaData; this.sourceValue = sourceValue; this.priority = priority; } public S getSource() { return source; } public String getTargetPropertyName() { return this.targetPropertyName; } public FuseClassMetaData<S> getSourceMetaData() { return this.sourceMetaData; } public Object getSourceValue() { return this.sourceValue; } public boolean hasValue() { return this.sourceValue != null; } public double getPriority() { return this.priority; } }
1,200
0.775
0.775
55
20.818182
27.386189
133
false
false
0
0
0
0
0
0
1.327273
false
false
6
8dd916ebfb7ca3f7db31db18f4cb8fed47c6137a
13,374,528,202,894
a770502571649f4d7622221f8e18583999950813
/wrapper/src/main/java/io/mywish/wrapper/service/WrapperTransactionService.java
1583a358d6bc91beed67644283d8e2169a8e3273
[]
no_license
mickeystone/event_scanner
https://github.com/mickeystone/event_scanner
cb5a0c8563326107d45dc893d7ec772ae4c7d1c8
599baecace89765ad7c2f3d04e1ec926614ca35c
refs/heads/master
2020-03-20T13:58:37.845000
2018-06-14T14:42:44
2018-06-14T14:42:44
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package io.mywish.wrapper.service; import io.mywish.wrapper.WrapperTransaction; public interface WrapperTransactionService<T> { WrapperTransaction build(T source); }
UTF-8
Java
172
java
WrapperTransactionService.java
Java
[]
null
[]
package io.mywish.wrapper.service; import io.mywish.wrapper.WrapperTransaction; public interface WrapperTransactionService<T> { WrapperTransaction build(T source); }
172
0.80814
0.80814
7
23.571428
20.471981
47
false
false
0
0
0
0
0
0
0.428571
false
false
6
f5f803790a41160dec14dce85360070261e6288f
326,417,534,015
cb8ff9177c9a2e581a6d6367899130d0d0f3a97b
/8_Paintings/src/main/java/edu/kea/paintings/controllers/Paintings.java
c31c306926a41dd1c9ef3406ae682b04d6c91e3b
[]
no_license
dwaGithub/KEA_3.Semester-main
https://github.com/dwaGithub/KEA_3.Semester-main
4178caea8ffe97792adf07821ee7b9566d007a26
323409b6b3560fac314736ce9363c5a9155488f9
refs/heads/master
2023-08-16T20:11:34.471000
2021-10-05T08:43:02
2021-10-05T08:43:02
400,079,255
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.kea.paintings.controllers; import edu.kea.paintings.models.Painting; import edu.kea.paintings.repositories.PaintingRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @RestController public class Paintings { @Autowired PaintingRepository paintings; //Getting all Paintings @GetMapping("/paintings") Iterable<Painting> getPaintings() { return paintings.findAll(); } //Getting a painting by id @GetMapping("/paintings/{id}") public Painting getPaintingById(@PathVariable Long id) { return paintings.findById(id).get(); } //Add's a painting using post @PostMapping("/paintings") public Painting addPainting(@RequestBody Painting newPainting) { return paintings.save(newPainting); } @PutMapping("/paintings/{id}") public String updatePaintingById(@PathVariable Long id, @RequestBody Painting paintingToUpdateWith){ if(paintings.existsById(id)){ paintingToUpdateWith.setId(id); paintings.save(paintingToUpdateWith); return "Painting was created"; } else { return "Painting not found"; } } //Updates a painting by id @PatchMapping("/paintings/{id}") public String patchPaintingById(@PathVariable Long id, @RequestBody Painting paintingToUpdateWith){ return paintings.findById(id).map(foundPainting -> { if(paintingToUpdateWith.getArtist() != null) foundPainting.setArtist(paintingToUpdateWith.getArtist()); if(paintingToUpdateWith.getPrice() != 0) foundPainting.setPrice(paintingToUpdateWith.getPrice()); if(paintingToUpdateWith.getTitle() != null) foundPainting.setTitle(paintingToUpdateWith.getTitle()); if(paintingToUpdateWith.getGenre() != null) foundPainting.setGenre(paintingToUpdateWith.getGenre()); if(paintingToUpdateWith.getPrice() != 0) foundPainting.setPrice(paintingToUpdateWith.getPrice()); paintings.save(foundPainting); return "Painting updated"; }).orElse("Painting not found"); } //Delete an artists by id. @DeleteMapping("/paintings/{id}") public void deletePaintingById(@PathVariable Long id){ paintings.deleteById(id); } }
UTF-8
Java
2,336
java
Paintings.java
Java
[]
null
[]
package edu.kea.paintings.controllers; import edu.kea.paintings.models.Painting; import edu.kea.paintings.repositories.PaintingRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @RestController public class Paintings { @Autowired PaintingRepository paintings; //Getting all Paintings @GetMapping("/paintings") Iterable<Painting> getPaintings() { return paintings.findAll(); } //Getting a painting by id @GetMapping("/paintings/{id}") public Painting getPaintingById(@PathVariable Long id) { return paintings.findById(id).get(); } //Add's a painting using post @PostMapping("/paintings") public Painting addPainting(@RequestBody Painting newPainting) { return paintings.save(newPainting); } @PutMapping("/paintings/{id}") public String updatePaintingById(@PathVariable Long id, @RequestBody Painting paintingToUpdateWith){ if(paintings.existsById(id)){ paintingToUpdateWith.setId(id); paintings.save(paintingToUpdateWith); return "Painting was created"; } else { return "Painting not found"; } } //Updates a painting by id @PatchMapping("/paintings/{id}") public String patchPaintingById(@PathVariable Long id, @RequestBody Painting paintingToUpdateWith){ return paintings.findById(id).map(foundPainting -> { if(paintingToUpdateWith.getArtist() != null) foundPainting.setArtist(paintingToUpdateWith.getArtist()); if(paintingToUpdateWith.getPrice() != 0) foundPainting.setPrice(paintingToUpdateWith.getPrice()); if(paintingToUpdateWith.getTitle() != null) foundPainting.setTitle(paintingToUpdateWith.getTitle()); if(paintingToUpdateWith.getGenre() != null) foundPainting.setGenre(paintingToUpdateWith.getGenre()); if(paintingToUpdateWith.getPrice() != 0) foundPainting.setPrice(paintingToUpdateWith.getPrice()); paintings.save(foundPainting); return "Painting updated"; }).orElse("Painting not found"); } //Delete an artists by id. @DeleteMapping("/paintings/{id}") public void deletePaintingById(@PathVariable Long id){ paintings.deleteById(id); } }
2,336
0.692637
0.691781
62
36.677418
31.90802
115
false
false
0
0
0
0
0
0
0.387097
false
false
6
ad25a0b6896769a22235c5eb6da75eee1d98cdc8
326,417,532,672
8191bea395f0e97835735d1ab6e859db3a7f8a99
/com.antutu.ABenchMark_source_from_JADX/com/google/android/gms/signin/internal/CheckServerAuthResult.java
a48c34082211ca30837b218884e5dec7f734bcc0
[]
no_license
msmtmsmt123/jadx-1
https://github.com/msmtmsmt123/jadx-1
5e5aea319e094b5d09c66e0fdb31f10a3238346c
b9458bb1a49a8a7fba8b9f9a6fb6f54438ce03a2
refs/heads/master
2021-05-08T19:21:27.870000
2017-01-28T04:19:54
2017-01-28T04:19:54
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.google.android.gms.signin.internal; import android.os.Parcel; import android.os.Parcelable.Creator; import com.google.android.gms.common.api.Scope; import com.google.android.gms.common.internal.safeparcel.SafeParcelable; import java.util.List; public class CheckServerAuthResult implements SafeParcelable { public static final Creator<CheckServerAuthResult> CREATOR; final int f12249a; final boolean f12250b; final List<Scope> f12251c; static { CREATOR = new C3547c(); } CheckServerAuthResult(int i, boolean z, List<Scope> list) { this.f12249a = i; this.f12250b = z; this.f12251c = list; } public int describeContents() { return 0; } public void writeToParcel(Parcel parcel, int i) { C3547c.m14766a(this, parcel, i); } }
UTF-8
Java
835
java
CheckServerAuthResult.java
Java
[]
null
[]
package com.google.android.gms.signin.internal; import android.os.Parcel; import android.os.Parcelable.Creator; import com.google.android.gms.common.api.Scope; import com.google.android.gms.common.internal.safeparcel.SafeParcelable; import java.util.List; public class CheckServerAuthResult implements SafeParcelable { public static final Creator<CheckServerAuthResult> CREATOR; final int f12249a; final boolean f12250b; final List<Scope> f12251c; static { CREATOR = new C3547c(); } CheckServerAuthResult(int i, boolean z, List<Scope> list) { this.f12249a = i; this.f12250b = z; this.f12251c = list; } public int describeContents() { return 0; } public void writeToParcel(Parcel parcel, int i) { C3547c.m14766a(this, parcel, i); } }
835
0.692216
0.639521
32
25.09375
21.603472
72
false
false
0
0
0
0
0
0
0.65625
false
false
6
392b674e264742a601b924f67451172d01885a81
8,040,178,832,477
47fd9e562c3483983ea1144a87fc095931ec486b
/crud-swagger/src/main/java/com/example/demo/NameValidator.java
13f4d491965622e752f3728c4fafe1218243683e
[]
no_license
binimbabu/Springboot-CRUD-Swagger-custom-validation
https://github.com/binimbabu/Springboot-CRUD-Swagger-custom-validation
a93f43b94cd2c58b28dbf8b2fb2df9c7077836bd
f3699d23713fc4ed7e249710f3182307176f7ded
refs/heads/master
2022-12-01T12:59:12.261000
2020-08-21T08:45:13
2020-08-21T08:45:13
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.demo; import com.example.demo.Entity.User; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; public class NameValidator implements ConstraintValidator<NameConstraint, User> { @Override public void initialize(NameConstraint constraintAnnotation) { } @Override public boolean isValid(User user, ConstraintValidatorContext constraintValidatorContext) { User user1 = (User) user; String firstname = user1.getFirstName(); String lastname = user1.getLastName(); if (firstname.length() == lastname.length()) { return true; } return false; } }
UTF-8
Java
705
java
NameValidator.java
Java
[]
null
[]
package com.example.demo; import com.example.demo.Entity.User; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; public class NameValidator implements ConstraintValidator<NameConstraint, User> { @Override public void initialize(NameConstraint constraintAnnotation) { } @Override public boolean isValid(User user, ConstraintValidatorContext constraintValidatorContext) { User user1 = (User) user; String firstname = user1.getFirstName(); String lastname = user1.getLastName(); if (firstname.length() == lastname.length()) { return true; } return false; } }
705
0.695035
0.69078
29
23.310345
26.361027
94
false
false
0
0
0
0
0
0
0.37931
false
false
6
4b6fdcec8084ab17086ffab87a0f0b3d69458878
29,042,568,912,936
028cbe18b4e5c347f664c592cbc7f56729b74060
/v2/appserv-core-ee/http-session-persistence-ha/src/java/com/sun/enterprise/ee/web/sessmgmt/ConnectionUtil.java
090513bb35dbc8057e0b4154fd817cefb34b3a00
[]
no_license
dmatej/Glassfish-SVN-Patched
https://github.com/dmatej/Glassfish-SVN-Patched
8d355ff753b23a9a1bd9d7475fa4b2cfd3b40f9e
269e29ba90db6d9c38271f7acd2affcacf2416f1
refs/heads/master
2021-05-28T12:55:06.267000
2014-11-11T04:21:44
2014-11-11T04:21:44
23,610,469
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You * may not use this file except in compliance with the License. You can obtain * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html * or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt. * Sun designates this particular file as subject to the "Classpath" exception * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * Header, with the fields enclosed by brackets [] replaced by your own * identifying information: "Portions Copyrighted [year] * [name of copyright owner]" * * Contributor(s): * * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. */ /* * Copyright 2006 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ /* * ConnectionUtil.java * * Created on February 14, 2003, 11:32 AM */ package com.sun.enterprise.ee.web.sessmgmt; import java.io.*; import javax.naming.*; import java.sql.*; import javax.sql.*; import java.util.*; import java.util.logging.Logger; import java.util.logging.Level; import com.sun.logging.LogDomains; import org.apache.catalina.*; import com.sun.enterprise.web.ServerConfigLookup; import com.sun.enterprise.web.ShutdownCleanupCapable; import com.sun.enterprise.ComponentInvocation; import com.sun.enterprise.Switch; import com.sun.enterprise.InvocationManager; //FIXME: move this later to com.sun.appserv.jdbc.DataSource //import com.sun.appserv.DataSource; import com.sun.enterprise.resource.ResourceInstaller; /** * * @author lwhite */ public class ConnectionUtil { /** * The cached DataSource */ private static DataSource _dataSource = null; /** * The logger to use for logging ALL web container related messages. */ private static Logger _logger = null; /** * The helper class used to manage retryable errors from the HA store */ protected HAErrorManager haErr = null; /** * The name of the HA store JDBC driver */ protected String driverName = "com.sun.hadb.jdbc.Driver"; /** * The number of seconds to wait before timing out a transaction * Default is 5 minutes. */ protected String timeoutSecs = new Long(5 * 60).toString(); //protected String timeoutSecs = new Long(2).toString(); //protected Container container = null; protected Object container = null; //protected Manager manager = null; protected Object manager = null; protected Valve valve = null; /** * The database connection. */ protected Connection conn = null; /** * Name to register for the background thread. */ protected String threadName = "ConnectionUtil"; /** Creates a new instance of ConnectionUtil */ public ConnectionUtil(Object cont) { //manager = mgr; container = cont; threadName = "ConnectionUtil"; long timeout = new Long(timeoutSecs).longValue(); haErr = new HAErrorManager(timeout, threadName); if (_logger == null) { //FIXME use LogDomains.WEB_EE_LOGGER later _logger = LogDomains.getLogger(LogDomains.WEB_LOGGER); } } /** Creates a new instance of ConnectionUtil */ public ConnectionUtil(Container cont) { //manager = mgr; container = cont; threadName = "ConnectionUtil"; long timeout = new Long(timeoutSecs).longValue(); haErr = new HAErrorManager(timeout, threadName); if (_logger == null) { //FIXME use LogDomains.WEB_EE_LOGGER later _logger = LogDomains.getLogger(LogDomains.WEB_LOGGER); } } /** Creates a new instance of ConnectionUtil */ public ConnectionUtil(Container cont, Manager mgr) { this(cont); manager = mgr; } /** Creates a new instance of ConnectionUtil */ public ConnectionUtil(Container cont, Valve aValve) { this(cont); valve = aValve; } /** * User for the connection */ protected String user = null; protected String getConnUser() { if (user == null) { ServerConfigLookup lookup = new ServerConfigLookup(); user = lookup.getConnectionUserFromConfig(); } return user; } /** * Password for the connection */ protected String password = null; protected String getConnPassword() { if (password == null) { ServerConfigLookup lookup = new ServerConfigLookup(); password = lookup.getConnectionPasswordFromConfig(); } return password; } protected boolean configErrorFlag = false; protected boolean hasConfigErrorBeenReported() { return configErrorFlag; } protected void setConfigErrorFlag(boolean value) { configErrorFlag = value; } /** * connection url string for the connection */ protected String connString = null; protected String getConnString() { if (connString == null) { ServerConfigLookup lookup = new ServerConfigLookup(); connString = lookup.getConnectionURLFromConfig(); } return connString; } /** * connection data source string for the connection */ protected String dataSourceString = null; protected String getDataSourceNameFromConfig() { if (dataSourceString == null) { ServerConfigLookup configLookup = new ServerConfigLookup(); dataSourceString = configLookup.getHaStorePoolJndiNameFromConfig(); } return dataSourceString; } /** * connection data source for the connection */ protected DataSource dataSource = null; public DataSource privateGetDataSource() throws javax.naming.NamingException { return this.getDataSource(); } /** * connection data source for the connection */ protected DataSource getDataSource() throws javax.naming.NamingException { if(dataSource != null) { return dataSource; } if(_dataSource != null) { dataSource = _dataSource; return _dataSource; } final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); //System.out.println("ConnectionUtil>>getDataSource: originalClassLoader=" + originalClassLoader); //_logger.finest("Getting initial context..."); java.security.AccessController.doPrivileged( new java.security.PrivilegedAction() { public java.lang.Object run() { Thread.currentThread().setContextClassLoader(ConnectionUtil.class.getClassLoader()); return null; } } ); InitialContext ctx = null; try { ctx = new InitialContext(); if(_logger.isLoggable(Level.FINEST)) { _logger.finest("- Got initial context for pool successfully"); _logger.finest("Getting datasource..."); } String dsName = this.getDataSourceNameFromConfig(); //DataSource ds = (javax.sql.DataSource)ctx.lookup(dsName); String systemDataSourceName = ResourceInstaller.getPMJndiName(dsName); DataSource ds = (javax.sql.DataSource)ctx.lookup(systemDataSourceName); //DataSource ds = (javax.sql.DataSource)ctx.lookup(dsName + "__pm"); if(_logger.isLoggable(Level.FINEST)) { _logger.finest("- Got datasource for pool successfully"); } dataSource = ds; setDataSource(ds); return ds; } catch (Exception e) { if(_logger.isLoggable(Level.FINEST)) { _logger.finest("ERROR CREATING INITCTX+++++++++"); } e.printStackTrace(); throw new javax.naming.NamingException(e.getMessage()); } finally { java.security.AccessController.doPrivileged( new java.security.PrivilegedAction() { public java.lang.Object run() { Thread.currentThread().setContextClassLoader(originalClassLoader); return null; } } ); } } private static synchronized void setDataSource(DataSource ds) { _dataSource = ds; } /** * return a connection from the pool * can return null if non-retryable exception * is thrown during effort to get a connection * else will keep retrying until a connection is obtained */ protected Connection getConnectionFromPool() throws IOException { Connection conn = null; InvocationManager invmgr = null; ComponentInvocation ci = null; try { /*( invmgr = Switch.getSwitch().getInvocationManager(); ci = new ComponentInvocation(this, container); invmgr.preInvoke(ci); */ DataSource ds = this.getDataSource(); conn = this.getConnectionRetry(ds); //_logger.finest("Getting connection..."); //conn = ds.getConnection(); // _logger.finest("GOT CONNECTION: class= " + conn.getClass().getName()); //conn.setAutoCommit(false); //_logger.finest("- Got connection from pool successfully"); } catch (Exception ex) { //ex.printStackTrace(); //throw new IOException("Unable to obtain connection from pool"); IOException ex1 = (IOException) new IOException("Unable to obtain connection from pool").initCause(ex); throw ex1; } finally { /* invmgr.postInvoke(ci); */ } return conn; } /** * return a connection from the pool * can return null if non-retryable exception * is thrown during effort to get a connection * else will keep retrying until a connection is obtained */ protected Connection getConnectionFromPool(boolean autoCommit) throws IOException { Connection conn = null; InvocationManager invmgr = null; ComponentInvocation ci = null; try { /* invmgr = Switch.getSwitch().getInvocationManager(); ci = new ComponentInvocation(this, container); invmgr.preInvoke(ci); */ DataSource ds = this.getDataSource(); conn = this.getConnectionRetry(ds, autoCommit); //_logger.finest("Getting connection..."); //conn = ds.getConnection(); // _logger.finest("GOT CONNECTION: class= " + conn.getClass().getName()); //conn.setAutoCommit(false); //_logger.finest("- Got connection from pool successfully"); } catch (Exception ex) { //ex.printStackTrace(); //throw new IOException("Unable to obtain connection from pool"); IOException ex1 = (IOException) new IOException("Unable to obtain connection from pool").initCause(ex); throw ex1; } finally { /* invmgr.postInvoke(ci); */ } return conn; } /** * this method is temporary until HADB fixes bug relating * to the length of the thread name - see callers of this * method in this class * this method calls getConnection on the data source after * insuring the thread name is short enough and then restores * the original thread name after the call */ private Connection doGetConnection(DataSource ds) throws SQLException { //System.out.println("IN NEW doGetConnection"); Connection resultConn = null; String threadName = Thread.currentThread().getName(); String shortString = this.truncateString(threadName, 63); Thread.currentThread().setName(shortString); //start 6468099 final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); if(originalClassLoader == null) { java.security.AccessController.doPrivileged( new java.security.PrivilegedAction() { public java.lang.Object run() { Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader()); return null; } } ); } //end 6468099 com.sun.appserv.jdbc.DataSource castDS = (com.sun.appserv.jdbc.DataSource) ds; try { //begin 6374243 //resultConn = castDS.getNonTxConnection(); //bail out and return null if thread is interrupted if(Thread.currentThread().isInterrupted()) { resultConn = null; } else { resultConn = castDS.getNonTxConnection(); //resultConn = ds.getConnection(); } //end 6374243 } finally { Thread.currentThread().setName(threadName); //start 6468099 java.security.AccessController.doPrivileged( new java.security.PrivilegedAction() { public java.lang.Object run() { Thread.currentThread().setContextClassLoader(originalClassLoader); return null; } } ); //end 6468099 } return resultConn; } /** * this method is temporary until HADB fixes bug relating * to the length of the thread name - see callers of this * method in this class * this method truncates the inputStr to the newLength * after doing some safety checks on the newLength */ private String truncateString(String inputStr, int newLength) { int strLength = inputStr.length(); String result = inputStr; if(newLength < strLength && newLength > 0) { result = inputStr.substring((strLength - newLength), strLength); } return result; } private Connection getConnectionRetry(DataSource ds) throws IOException { Connection resultConn = null; try { haErr.txStart(); while ( ! haErr.isTxCompleted() ) { try { //_logger.finest("Getting connection..."); //FIXME: this call is a work-around for HADB bug //when it is fixed can go back to following line resultConn = this.doGetConnection(ds); //resultConn = ds.getConnection(); // _logger.finest("GOT CONNECTION: class= " + conn.getClass().getName()); resultConn.setAutoCommit(false); //_logger.finest("- Got connection from pool successfully"); haErr.txEnd(); } catch ( SQLException e ) { //haErr.checkError(e, null); haErr.checkError(e, resultConn); if (resultConn != null) { //put resultConn back in pool try { resultConn.close(); } catch (Exception ex) {} } if(_logger.isLoggable(Level.FINEST)) { _logger.finest("Got a retryable exception from ConnectionUtil: " + e.getMessage()); } } } } catch(SQLException e) { IOException ex1 = (IOException) new IOException("Error from ConnectionUtil: " + e.getMessage()).initCause(e); throw ex1; } catch ( HATimeoutException e ) { IOException ex1 = (IOException) new IOException("Timeout from ConnectionUtil").initCause(e); throw ex1; } if(resultConn == null) { _logger.warning("ConnectionUtil>>getConnectionRetry failed: returning null"); } return resultConn; } private Connection getConnectionRetry(DataSource ds, boolean autoCommit) throws IOException { Connection resultConn = null; try { haErr.txStart(); while ( ! haErr.isTxCompleted() ) { try { //_logger.finest("Getting connection..."); //FIXME: this call is a work-around for HADB bug //when it is fixed can go back to following line resultConn = this.doGetConnection(ds); //resultConn = ds.getConnection(); // _logger.finest("GOT CONNECTION: class= " + conn.getClass().getName()); resultConn.setAutoCommit(autoCommit); /* above line replaces following 3 lines if(!autoCommit) { resultConn.setAutoCommit(false); } */ //_logger.finest("- Got connection from pool successfully"); haErr.txEnd(); } catch ( SQLException e ) { //haErr.checkError(e, null); haErr.checkError(e, resultConn); if (resultConn != null) { //put resultConn back in pool try { resultConn.close(); } catch (Exception ex) {} } if(_logger.isLoggable(Level.FINEST)) { _logger.finest("Got a retryable exception from ConnectionUtil: " + e.getMessage()); } } } } catch(SQLException e) { IOException ex1 = (IOException) new IOException("Error from ConnectionUtil: " + e.getMessage()).initCause(e); throw ex1; } catch ( HATimeoutException e ) { IOException ex1 = (IOException) new IOException("Timeout from ConnectionUtil").initCause(e); throw ex1; } if(resultConn == null) { _logger.warning("ConnectionUtil>>getConnectionRetry failed: returning null"); } return resultConn; } /** * return a HADBConnectionGroup from the pool */ public HADBConnectionGroup getConnectionsFromPool() throws IOException { Connection conn = this.getConnectionFromPool(); //if conn is null this is a failure to get a connection //even after repeated retries if(conn == null) { _logger.warning("ConnectionUtil>>getConnectionsFromPool failed: returning null"); return null; } Connection internalConn = this.getInternalConnection(conn); HADBConnectionGroup connections = new HADBConnectionGroup(internalConn, conn); //FIXME wrong to manage pool connections this way - remove after testing //System.out.println("ConnectionUtil:about to putConnection"); //this.putConnection(internalConn); return connections; } /** * return a HADBConnectionGroup from the pool */ public HADBConnectionGroup getConnectionsFromPool(boolean autoCommit) throws IOException { Connection conn = this.getConnectionFromPool(autoCommit); //if conn is null this is a failure to get a connection //even after repeated retries if(conn == null) { _logger.warning("ConnectionUtil>>getConnectionsFromPool failed: returning null"); return null; } Connection internalConn = this.getInternalConnection(conn); HADBConnectionGroup connections = new HADBConnectionGroup(internalConn, conn); //FIXME wrong to manage pool connections this way - remove after testing //System.out.println("ConnectionUtil:about to putConnection"); //this.putConnection(internalConn); return connections; } /** * return the internal connection from the JDBC external wrapper */ private Connection getInternalConnection(Connection connection) throws IOException { Connection internalConn = null; //FIXME: this will change to com.sun.appserv.jdbc.DataSource com.sun.appserv.jdbc.DataSource ds = null; try { ds = (com.sun.appserv.jdbc.DataSource) (this.getDataSource()); } catch (Exception ex) {} try { internalConn = ds.getConnection(connection); } catch (Exception ex) { //just warn and continue processing //_logger.log(Level.SEVERE, "webcontainer.hadbConnectionPoolNotReached"); //ex.printStackTrace(); //throw new IOException("Unable to obtain connection from pool"); IOException ex1 = (IOException) new IOException("Unable to obtain connection from pool").initCause(ex); throw ex1; } return internalConn; } /** * Check the connection associated with this store, if it's * <code>null</code> or closed try to reopen it. * Returns <code>null</code> if the connection could not be established. * * @return <code>Connection</code> if the connection succeeded */ public Connection getConnection() throws IOException { return getConnection(true); } /** * Check the connection associated with this store, if it's * <code>null</code> or closed try to reopen it. * set autoCommit to autoCommit * Returns <code>null</code> if the connection could not be established. * * @return <code>Connection</code> if the connection succeeded */ public Connection getConnectionNew(boolean autoCommit) throws IOException { //FIXME: this method is wrong //for now is getting from the pool Connection internalConn = null; try { Connection externalConn = this.getConnectionFromPool(); internalConn = this.getInternalConnection(externalConn); if(internalConn != null) { internalConn.setAutoCommit(autoCommit); this.putConnection(internalConn); } } catch ( SQLException e ) { //e.printStackTrace(); _logger.log(Level.SEVERE, "connectionutil.unableToOpenConnection", e.getMessage()); _logger.log(Level.SEVERE, "connectionutil.failedToPersist"); IOException ex1 = (IOException) new IOException("Unable to open connection to HA Store: " + e.getMessage()).initCause(e); throw ex1; } return internalConn; } /** * Check the connection associated with this store, if it's * <code>null</code> or closed try to reopen it. * set autoCommit to autoCommit * Returns <code>null</code> if the connection could not be established. * * @return <code>Connection</code> if the connection succeeded */ public Connection getConnection(boolean autoCommit) throws IOException { if(this.hasConfigErrorBeenReported()) { return null; } haErr.txStart(); while ( ! haErr.isTxCompleted() ) { try { if ( conn != null && (! conn.isClosed()) ) { if(conn.getAutoCommit()) { conn.setAutoCommit(autoCommit); } //return conn; } if(_logger.isLoggable(Level.FINEST)) { _logger.finest("VALUE-OF-CONN-STRING= " + getConnString()); _logger.finest("cached conn= " + conn); } } catch (Exception e1) { conn = null; } if(conn != null) { if(_logger.isLoggable(Level.FINEST)) { _logger.finest("getConnection-near begin return conn from cache"); } haErr.txEnd(); break; } try { try { Class.forName(driverName); } catch ( ClassNotFoundException ex ) { IOException ex1 = (IOException) new IOException("Unable to find JDBC driver class " + driverName + ": " + ex.getMessage()).initCause(ex); throw ex1; } try { Properties props = new Properties(); String theUser = this.getConnUser(); String thePassword = this.getConnPassword(); if(theUser == null || thePassword == null || getConnString() == null) { _logger.log(Level.WARNING, "connectionutil.configError"); this.setConfigErrorFlag(true); } else { this.setConfigErrorFlag(false); //use these lines to get log of JDBC driver activity //props.setProperty("loglevel", "FINEST"); //props.setProperty("logfile", "/tmp/mylogfile"); props.setProperty("user", user); props.setProperty("password", password); //FIXME: these lines relating to the thread name // are a work-around until HADB bug is fixed String threadName = Thread.currentThread().getName(); String shortString = this.truncateString(threadName, 63); Thread.currentThread().setName(shortString); conn = DriverManager.getConnection(getConnString(), props); Thread.currentThread().setName(threadName); conn.setAutoCommit(autoCommit); //Bug 4836431 conn.setTransactionIsolation(java.sql.Connection.TRANSACTION_REPEATABLE_READ); } haErr.txEnd(); if(_logger.isLoggable(Level.FINEST)) { _logger.finest("getConnection at middle - return created conn: " + conn); } //debug("Connected to " + connString); } catch ( SQLException ex ) { haErr.checkError(ex, conn); //debug("Got a retryable exception from HA Store: " + ex.getMessage()) if(_logger.isLoggable(Level.FINEST)) { _logger.finest("Got a retryable exception from HA Store: " + ex.getMessage()); } System.out.println("Got a retryable exception from HA Store: " + ex.getMessage()); ex.printStackTrace(); } } catch ( SQLException e ) { //e.printStackTrace(); _logger.log(Level.SEVERE, "connectionutil.unableToOpenConnection", e.getMessage()); _logger.log(Level.SEVERE, "connectionutil.failedToPersist"); //throw new IOException("Unable to open connection to HA Store: " + e.getMessage()); IOException ex1 = (IOException) new IOException("Unable to open connection to HA Store: " + e.getMessage()).initCause(e); throw ex1; } catch ( HATimeoutException e ) { //throw new IOException("Timed out attempting to open connection to HA Store"); IOException ex2 = (IOException) new IOException("Timed out attempting to open connection to HA Store").initCause(e); throw ex2; } } if(_logger.isLoggable(Level.FINEST)) { _logger.finest("getConnection at end - return conn: " + conn); } if(conn != null) this.putConnection(conn); return conn; } protected void putConnection(Connection conn) { if(manager instanceof ShutdownCleanupCapable) { ((ShutdownCleanupCapable)manager).putConnection(conn); } //for SSO case if(valve instanceof ShutdownCleanupCapable) { ((ShutdownCleanupCapable)valve).putConnection(conn); } } public void clearCachedConnection() { conn = null; } }
UTF-8
Java
30,888
java
ConnectionUtil.java
Java
[ { "context": "se.resource.ResourceInstaller;\n\n/**\n *\n * @author lwhite\n */\npublic class ConnectionUtil {\n \n /**\n ", "end": 2809, "score": 0.9996505379676819, "start": 2803, "tag": "USERNAME", "value": "lwhite" }, { "context": " props.setProperty(\"password\", password);\n\n //FIXME: these lines r", "end": 27706, "score": 0.9922213554382324, "start": 27698, "tag": "PASSWORD", "value": "password" } ]
null
[]
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You * may not use this file except in compliance with the License. You can obtain * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html * or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt. * Sun designates this particular file as subject to the "Classpath" exception * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * Header, with the fields enclosed by brackets [] replaced by your own * identifying information: "Portions Copyrighted [year] * [name of copyright owner]" * * Contributor(s): * * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. */ /* * Copyright 2006 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ /* * ConnectionUtil.java * * Created on February 14, 2003, 11:32 AM */ package com.sun.enterprise.ee.web.sessmgmt; import java.io.*; import javax.naming.*; import java.sql.*; import javax.sql.*; import java.util.*; import java.util.logging.Logger; import java.util.logging.Level; import com.sun.logging.LogDomains; import org.apache.catalina.*; import com.sun.enterprise.web.ServerConfigLookup; import com.sun.enterprise.web.ShutdownCleanupCapable; import com.sun.enterprise.ComponentInvocation; import com.sun.enterprise.Switch; import com.sun.enterprise.InvocationManager; //FIXME: move this later to com.sun.appserv.jdbc.DataSource //import com.sun.appserv.DataSource; import com.sun.enterprise.resource.ResourceInstaller; /** * * @author lwhite */ public class ConnectionUtil { /** * The cached DataSource */ private static DataSource _dataSource = null; /** * The logger to use for logging ALL web container related messages. */ private static Logger _logger = null; /** * The helper class used to manage retryable errors from the HA store */ protected HAErrorManager haErr = null; /** * The name of the HA store JDBC driver */ protected String driverName = "com.sun.hadb.jdbc.Driver"; /** * The number of seconds to wait before timing out a transaction * Default is 5 minutes. */ protected String timeoutSecs = new Long(5 * 60).toString(); //protected String timeoutSecs = new Long(2).toString(); //protected Container container = null; protected Object container = null; //protected Manager manager = null; protected Object manager = null; protected Valve valve = null; /** * The database connection. */ protected Connection conn = null; /** * Name to register for the background thread. */ protected String threadName = "ConnectionUtil"; /** Creates a new instance of ConnectionUtil */ public ConnectionUtil(Object cont) { //manager = mgr; container = cont; threadName = "ConnectionUtil"; long timeout = new Long(timeoutSecs).longValue(); haErr = new HAErrorManager(timeout, threadName); if (_logger == null) { //FIXME use LogDomains.WEB_EE_LOGGER later _logger = LogDomains.getLogger(LogDomains.WEB_LOGGER); } } /** Creates a new instance of ConnectionUtil */ public ConnectionUtil(Container cont) { //manager = mgr; container = cont; threadName = "ConnectionUtil"; long timeout = new Long(timeoutSecs).longValue(); haErr = new HAErrorManager(timeout, threadName); if (_logger == null) { //FIXME use LogDomains.WEB_EE_LOGGER later _logger = LogDomains.getLogger(LogDomains.WEB_LOGGER); } } /** Creates a new instance of ConnectionUtil */ public ConnectionUtil(Container cont, Manager mgr) { this(cont); manager = mgr; } /** Creates a new instance of ConnectionUtil */ public ConnectionUtil(Container cont, Valve aValve) { this(cont); valve = aValve; } /** * User for the connection */ protected String user = null; protected String getConnUser() { if (user == null) { ServerConfigLookup lookup = new ServerConfigLookup(); user = lookup.getConnectionUserFromConfig(); } return user; } /** * Password for the connection */ protected String password = null; protected String getConnPassword() { if (password == null) { ServerConfigLookup lookup = new ServerConfigLookup(); password = lookup.getConnectionPasswordFromConfig(); } return password; } protected boolean configErrorFlag = false; protected boolean hasConfigErrorBeenReported() { return configErrorFlag; } protected void setConfigErrorFlag(boolean value) { configErrorFlag = value; } /** * connection url string for the connection */ protected String connString = null; protected String getConnString() { if (connString == null) { ServerConfigLookup lookup = new ServerConfigLookup(); connString = lookup.getConnectionURLFromConfig(); } return connString; } /** * connection data source string for the connection */ protected String dataSourceString = null; protected String getDataSourceNameFromConfig() { if (dataSourceString == null) { ServerConfigLookup configLookup = new ServerConfigLookup(); dataSourceString = configLookup.getHaStorePoolJndiNameFromConfig(); } return dataSourceString; } /** * connection data source for the connection */ protected DataSource dataSource = null; public DataSource privateGetDataSource() throws javax.naming.NamingException { return this.getDataSource(); } /** * connection data source for the connection */ protected DataSource getDataSource() throws javax.naming.NamingException { if(dataSource != null) { return dataSource; } if(_dataSource != null) { dataSource = _dataSource; return _dataSource; } final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); //System.out.println("ConnectionUtil>>getDataSource: originalClassLoader=" + originalClassLoader); //_logger.finest("Getting initial context..."); java.security.AccessController.doPrivileged( new java.security.PrivilegedAction() { public java.lang.Object run() { Thread.currentThread().setContextClassLoader(ConnectionUtil.class.getClassLoader()); return null; } } ); InitialContext ctx = null; try { ctx = new InitialContext(); if(_logger.isLoggable(Level.FINEST)) { _logger.finest("- Got initial context for pool successfully"); _logger.finest("Getting datasource..."); } String dsName = this.getDataSourceNameFromConfig(); //DataSource ds = (javax.sql.DataSource)ctx.lookup(dsName); String systemDataSourceName = ResourceInstaller.getPMJndiName(dsName); DataSource ds = (javax.sql.DataSource)ctx.lookup(systemDataSourceName); //DataSource ds = (javax.sql.DataSource)ctx.lookup(dsName + "__pm"); if(_logger.isLoggable(Level.FINEST)) { _logger.finest("- Got datasource for pool successfully"); } dataSource = ds; setDataSource(ds); return ds; } catch (Exception e) { if(_logger.isLoggable(Level.FINEST)) { _logger.finest("ERROR CREATING INITCTX+++++++++"); } e.printStackTrace(); throw new javax.naming.NamingException(e.getMessage()); } finally { java.security.AccessController.doPrivileged( new java.security.PrivilegedAction() { public java.lang.Object run() { Thread.currentThread().setContextClassLoader(originalClassLoader); return null; } } ); } } private static synchronized void setDataSource(DataSource ds) { _dataSource = ds; } /** * return a connection from the pool * can return null if non-retryable exception * is thrown during effort to get a connection * else will keep retrying until a connection is obtained */ protected Connection getConnectionFromPool() throws IOException { Connection conn = null; InvocationManager invmgr = null; ComponentInvocation ci = null; try { /*( invmgr = Switch.getSwitch().getInvocationManager(); ci = new ComponentInvocation(this, container); invmgr.preInvoke(ci); */ DataSource ds = this.getDataSource(); conn = this.getConnectionRetry(ds); //_logger.finest("Getting connection..."); //conn = ds.getConnection(); // _logger.finest("GOT CONNECTION: class= " + conn.getClass().getName()); //conn.setAutoCommit(false); //_logger.finest("- Got connection from pool successfully"); } catch (Exception ex) { //ex.printStackTrace(); //throw new IOException("Unable to obtain connection from pool"); IOException ex1 = (IOException) new IOException("Unable to obtain connection from pool").initCause(ex); throw ex1; } finally { /* invmgr.postInvoke(ci); */ } return conn; } /** * return a connection from the pool * can return null if non-retryable exception * is thrown during effort to get a connection * else will keep retrying until a connection is obtained */ protected Connection getConnectionFromPool(boolean autoCommit) throws IOException { Connection conn = null; InvocationManager invmgr = null; ComponentInvocation ci = null; try { /* invmgr = Switch.getSwitch().getInvocationManager(); ci = new ComponentInvocation(this, container); invmgr.preInvoke(ci); */ DataSource ds = this.getDataSource(); conn = this.getConnectionRetry(ds, autoCommit); //_logger.finest("Getting connection..."); //conn = ds.getConnection(); // _logger.finest("GOT CONNECTION: class= " + conn.getClass().getName()); //conn.setAutoCommit(false); //_logger.finest("- Got connection from pool successfully"); } catch (Exception ex) { //ex.printStackTrace(); //throw new IOException("Unable to obtain connection from pool"); IOException ex1 = (IOException) new IOException("Unable to obtain connection from pool").initCause(ex); throw ex1; } finally { /* invmgr.postInvoke(ci); */ } return conn; } /** * this method is temporary until HADB fixes bug relating * to the length of the thread name - see callers of this * method in this class * this method calls getConnection on the data source after * insuring the thread name is short enough and then restores * the original thread name after the call */ private Connection doGetConnection(DataSource ds) throws SQLException { //System.out.println("IN NEW doGetConnection"); Connection resultConn = null; String threadName = Thread.currentThread().getName(); String shortString = this.truncateString(threadName, 63); Thread.currentThread().setName(shortString); //start 6468099 final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); if(originalClassLoader == null) { java.security.AccessController.doPrivileged( new java.security.PrivilegedAction() { public java.lang.Object run() { Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader()); return null; } } ); } //end 6468099 com.sun.appserv.jdbc.DataSource castDS = (com.sun.appserv.jdbc.DataSource) ds; try { //begin 6374243 //resultConn = castDS.getNonTxConnection(); //bail out and return null if thread is interrupted if(Thread.currentThread().isInterrupted()) { resultConn = null; } else { resultConn = castDS.getNonTxConnection(); //resultConn = ds.getConnection(); } //end 6374243 } finally { Thread.currentThread().setName(threadName); //start 6468099 java.security.AccessController.doPrivileged( new java.security.PrivilegedAction() { public java.lang.Object run() { Thread.currentThread().setContextClassLoader(originalClassLoader); return null; } } ); //end 6468099 } return resultConn; } /** * this method is temporary until HADB fixes bug relating * to the length of the thread name - see callers of this * method in this class * this method truncates the inputStr to the newLength * after doing some safety checks on the newLength */ private String truncateString(String inputStr, int newLength) { int strLength = inputStr.length(); String result = inputStr; if(newLength < strLength && newLength > 0) { result = inputStr.substring((strLength - newLength), strLength); } return result; } private Connection getConnectionRetry(DataSource ds) throws IOException { Connection resultConn = null; try { haErr.txStart(); while ( ! haErr.isTxCompleted() ) { try { //_logger.finest("Getting connection..."); //FIXME: this call is a work-around for HADB bug //when it is fixed can go back to following line resultConn = this.doGetConnection(ds); //resultConn = ds.getConnection(); // _logger.finest("GOT CONNECTION: class= " + conn.getClass().getName()); resultConn.setAutoCommit(false); //_logger.finest("- Got connection from pool successfully"); haErr.txEnd(); } catch ( SQLException e ) { //haErr.checkError(e, null); haErr.checkError(e, resultConn); if (resultConn != null) { //put resultConn back in pool try { resultConn.close(); } catch (Exception ex) {} } if(_logger.isLoggable(Level.FINEST)) { _logger.finest("Got a retryable exception from ConnectionUtil: " + e.getMessage()); } } } } catch(SQLException e) { IOException ex1 = (IOException) new IOException("Error from ConnectionUtil: " + e.getMessage()).initCause(e); throw ex1; } catch ( HATimeoutException e ) { IOException ex1 = (IOException) new IOException("Timeout from ConnectionUtil").initCause(e); throw ex1; } if(resultConn == null) { _logger.warning("ConnectionUtil>>getConnectionRetry failed: returning null"); } return resultConn; } private Connection getConnectionRetry(DataSource ds, boolean autoCommit) throws IOException { Connection resultConn = null; try { haErr.txStart(); while ( ! haErr.isTxCompleted() ) { try { //_logger.finest("Getting connection..."); //FIXME: this call is a work-around for HADB bug //when it is fixed can go back to following line resultConn = this.doGetConnection(ds); //resultConn = ds.getConnection(); // _logger.finest("GOT CONNECTION: class= " + conn.getClass().getName()); resultConn.setAutoCommit(autoCommit); /* above line replaces following 3 lines if(!autoCommit) { resultConn.setAutoCommit(false); } */ //_logger.finest("- Got connection from pool successfully"); haErr.txEnd(); } catch ( SQLException e ) { //haErr.checkError(e, null); haErr.checkError(e, resultConn); if (resultConn != null) { //put resultConn back in pool try { resultConn.close(); } catch (Exception ex) {} } if(_logger.isLoggable(Level.FINEST)) { _logger.finest("Got a retryable exception from ConnectionUtil: " + e.getMessage()); } } } } catch(SQLException e) { IOException ex1 = (IOException) new IOException("Error from ConnectionUtil: " + e.getMessage()).initCause(e); throw ex1; } catch ( HATimeoutException e ) { IOException ex1 = (IOException) new IOException("Timeout from ConnectionUtil").initCause(e); throw ex1; } if(resultConn == null) { _logger.warning("ConnectionUtil>>getConnectionRetry failed: returning null"); } return resultConn; } /** * return a HADBConnectionGroup from the pool */ public HADBConnectionGroup getConnectionsFromPool() throws IOException { Connection conn = this.getConnectionFromPool(); //if conn is null this is a failure to get a connection //even after repeated retries if(conn == null) { _logger.warning("ConnectionUtil>>getConnectionsFromPool failed: returning null"); return null; } Connection internalConn = this.getInternalConnection(conn); HADBConnectionGroup connections = new HADBConnectionGroup(internalConn, conn); //FIXME wrong to manage pool connections this way - remove after testing //System.out.println("ConnectionUtil:about to putConnection"); //this.putConnection(internalConn); return connections; } /** * return a HADBConnectionGroup from the pool */ public HADBConnectionGroup getConnectionsFromPool(boolean autoCommit) throws IOException { Connection conn = this.getConnectionFromPool(autoCommit); //if conn is null this is a failure to get a connection //even after repeated retries if(conn == null) { _logger.warning("ConnectionUtil>>getConnectionsFromPool failed: returning null"); return null; } Connection internalConn = this.getInternalConnection(conn); HADBConnectionGroup connections = new HADBConnectionGroup(internalConn, conn); //FIXME wrong to manage pool connections this way - remove after testing //System.out.println("ConnectionUtil:about to putConnection"); //this.putConnection(internalConn); return connections; } /** * return the internal connection from the JDBC external wrapper */ private Connection getInternalConnection(Connection connection) throws IOException { Connection internalConn = null; //FIXME: this will change to com.sun.appserv.jdbc.DataSource com.sun.appserv.jdbc.DataSource ds = null; try { ds = (com.sun.appserv.jdbc.DataSource) (this.getDataSource()); } catch (Exception ex) {} try { internalConn = ds.getConnection(connection); } catch (Exception ex) { //just warn and continue processing //_logger.log(Level.SEVERE, "webcontainer.hadbConnectionPoolNotReached"); //ex.printStackTrace(); //throw new IOException("Unable to obtain connection from pool"); IOException ex1 = (IOException) new IOException("Unable to obtain connection from pool").initCause(ex); throw ex1; } return internalConn; } /** * Check the connection associated with this store, if it's * <code>null</code> or closed try to reopen it. * Returns <code>null</code> if the connection could not be established. * * @return <code>Connection</code> if the connection succeeded */ public Connection getConnection() throws IOException { return getConnection(true); } /** * Check the connection associated with this store, if it's * <code>null</code> or closed try to reopen it. * set autoCommit to autoCommit * Returns <code>null</code> if the connection could not be established. * * @return <code>Connection</code> if the connection succeeded */ public Connection getConnectionNew(boolean autoCommit) throws IOException { //FIXME: this method is wrong //for now is getting from the pool Connection internalConn = null; try { Connection externalConn = this.getConnectionFromPool(); internalConn = this.getInternalConnection(externalConn); if(internalConn != null) { internalConn.setAutoCommit(autoCommit); this.putConnection(internalConn); } } catch ( SQLException e ) { //e.printStackTrace(); _logger.log(Level.SEVERE, "connectionutil.unableToOpenConnection", e.getMessage()); _logger.log(Level.SEVERE, "connectionutil.failedToPersist"); IOException ex1 = (IOException) new IOException("Unable to open connection to HA Store: " + e.getMessage()).initCause(e); throw ex1; } return internalConn; } /** * Check the connection associated with this store, if it's * <code>null</code> or closed try to reopen it. * set autoCommit to autoCommit * Returns <code>null</code> if the connection could not be established. * * @return <code>Connection</code> if the connection succeeded */ public Connection getConnection(boolean autoCommit) throws IOException { if(this.hasConfigErrorBeenReported()) { return null; } haErr.txStart(); while ( ! haErr.isTxCompleted() ) { try { if ( conn != null && (! conn.isClosed()) ) { if(conn.getAutoCommit()) { conn.setAutoCommit(autoCommit); } //return conn; } if(_logger.isLoggable(Level.FINEST)) { _logger.finest("VALUE-OF-CONN-STRING= " + getConnString()); _logger.finest("cached conn= " + conn); } } catch (Exception e1) { conn = null; } if(conn != null) { if(_logger.isLoggable(Level.FINEST)) { _logger.finest("getConnection-near begin return conn from cache"); } haErr.txEnd(); break; } try { try { Class.forName(driverName); } catch ( ClassNotFoundException ex ) { IOException ex1 = (IOException) new IOException("Unable to find JDBC driver class " + driverName + ": " + ex.getMessage()).initCause(ex); throw ex1; } try { Properties props = new Properties(); String theUser = this.getConnUser(); String thePassword = this.getConnPassword(); if(theUser == null || thePassword == null || getConnString() == null) { _logger.log(Level.WARNING, "connectionutil.configError"); this.setConfigErrorFlag(true); } else { this.setConfigErrorFlag(false); //use these lines to get log of JDBC driver activity //props.setProperty("loglevel", "FINEST"); //props.setProperty("logfile", "/tmp/mylogfile"); props.setProperty("user", user); props.setProperty("password", <PASSWORD>); //FIXME: these lines relating to the thread name // are a work-around until HADB bug is fixed String threadName = Thread.currentThread().getName(); String shortString = this.truncateString(threadName, 63); Thread.currentThread().setName(shortString); conn = DriverManager.getConnection(getConnString(), props); Thread.currentThread().setName(threadName); conn.setAutoCommit(autoCommit); //Bug 4836431 conn.setTransactionIsolation(java.sql.Connection.TRANSACTION_REPEATABLE_READ); } haErr.txEnd(); if(_logger.isLoggable(Level.FINEST)) { _logger.finest("getConnection at middle - return created conn: " + conn); } //debug("Connected to " + connString); } catch ( SQLException ex ) { haErr.checkError(ex, conn); //debug("Got a retryable exception from HA Store: " + ex.getMessage()) if(_logger.isLoggable(Level.FINEST)) { _logger.finest("Got a retryable exception from HA Store: " + ex.getMessage()); } System.out.println("Got a retryable exception from HA Store: " + ex.getMessage()); ex.printStackTrace(); } } catch ( SQLException e ) { //e.printStackTrace(); _logger.log(Level.SEVERE, "connectionutil.unableToOpenConnection", e.getMessage()); _logger.log(Level.SEVERE, "connectionutil.failedToPersist"); //throw new IOException("Unable to open connection to HA Store: " + e.getMessage()); IOException ex1 = (IOException) new IOException("Unable to open connection to HA Store: " + e.getMessage()).initCause(e); throw ex1; } catch ( HATimeoutException e ) { //throw new IOException("Timed out attempting to open connection to HA Store"); IOException ex2 = (IOException) new IOException("Timed out attempting to open connection to HA Store").initCause(e); throw ex2; } } if(_logger.isLoggable(Level.FINEST)) { _logger.finest("getConnection at end - return conn: " + conn); } if(conn != null) this.putConnection(conn); return conn; } protected void putConnection(Connection conn) { if(manager instanceof ShutdownCleanupCapable) { ((ShutdownCleanupCapable)manager).putConnection(conn); } //for SSO case if(valve instanceof ShutdownCleanupCapable) { ((ShutdownCleanupCapable)valve).putConnection(conn); } } public void clearCachedConnection() { conn = null; } }
30,890
0.558016
0.55439
787
38.247776
26.902542
123
false
false
0
0
0
0
0
0
0.43202
false
false
6
5a2856bbc349898d384be7a6749be6b3d0f31c46
29,437,705,915,140
bb6bdb777d9732c5ff8125d1cf849b1495575081
/PrimerosPasos/src/Adivina_numero.java
52053d18d2a6f43c2f4ad37c7a91624d021b2b35
[]
no_license
jgfeliz/java
https://github.com/jgfeliz/java
8c91bab712ad01f76ed433691f1534b36e45cbfc
e354b6f60269785a8e892637cb600cb055e420d6
refs/heads/master
2021-09-09T19:04:41.213000
2018-03-19T03:21:00
2018-03-19T03:21:00
116,167,193
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.*; public class Adivina_numero { public static void main(String[] args) { // TODO Auto-generated method stub int aleatorio; int intentos=1; aleatorio =(int)(Math.random() * 100); //aqui se realiza una refunsicion, pasar un numero decimal creado con random a entero Scanner entrada=new Scanner(System.in); System.out.println("Ingrese un numero, por favor"); int compara=entrada.nextInt(); while (aleatorio!=compara) { intentos++; if (aleatorio>compara){ System.out.println("El numero aleatorio es mayor que " + compara); } else if (aleatorio<compara){ System.out.println("El numero aleatorio es menor que " + compara); } compara=entrada.nextInt(); } //entrada.close(); System.out.println("El numero aleatorio es " + aleatorio + " lo intento " + intentos + " Veces"); } }
UTF-8
Java
901
java
Adivina_numero.java
Java
[]
null
[]
import java.util.*; public class Adivina_numero { public static void main(String[] args) { // TODO Auto-generated method stub int aleatorio; int intentos=1; aleatorio =(int)(Math.random() * 100); //aqui se realiza una refunsicion, pasar un numero decimal creado con random a entero Scanner entrada=new Scanner(System.in); System.out.println("Ingrese un numero, por favor"); int compara=entrada.nextInt(); while (aleatorio!=compara) { intentos++; if (aleatorio>compara){ System.out.println("El numero aleatorio es mayor que " + compara); } else if (aleatorio<compara){ System.out.println("El numero aleatorio es menor que " + compara); } compara=entrada.nextInt(); } //entrada.close(); System.out.println("El numero aleatorio es " + aleatorio + " lo intento " + intentos + " Veces"); } }
901
0.63929
0.63485
43
19.976744
27.753473
126
false
false
0
0
0
0
0
0
2.581395
false
false
6
8e206d09f3e3cce36ad92502c75bdb389c87f5dc
4,629,974,756,031
7359a1c779a17afcda8b5da4edefb8f93a100b90
/app/src/main/java/com/beebeom/a17_cursoradapter/MyCursorAdapter.java
3ebd668ea6f144d87db367440b2efc38f5911d30
[]
no_license
leebeebeom/Study_17_CursorAdapter
https://github.com/leebeebeom/Study_17_CursorAdapter
c56a37b1ad1248dc283b2bfcd50b23a041a49b68
3bc1bdb4a399f6ecdba1a0dee1dde509228d2825
refs/heads/master
2023-01-15T23:18:23.049000
2020-11-28T01:12:11
2020-11-28T01:12:11
316,631,934
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.beebeom.a17_cursoradapter; import android.content.Context; import android.database.Cursor; import android.provider.MediaStore; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import androidx.cursoradapter.widget.CursorAdapter; import com.bumptech.glide.Glide; public class MyCursorAdapter extends CursorAdapter { public MyCursorAdapter(Context context, Cursor c, boolean autoRequery) { super(context, c, autoRequery); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return LayoutInflater.from(context).inflate(R.layout.item_photo, parent, false); } @Override public void bindView(View view, Context context, Cursor cursor) { ImageView imageView = view.findViewById(R.id.item_image); //각 이미지의 URI 가져오기 String url = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)); Glide.with(context).load(url).into(imageView); } }
UTF-8
Java
1,076
java
MyCursorAdapter.java
Java
[]
null
[]
package com.beebeom.a17_cursoradapter; import android.content.Context; import android.database.Cursor; import android.provider.MediaStore; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import androidx.cursoradapter.widget.CursorAdapter; import com.bumptech.glide.Glide; public class MyCursorAdapter extends CursorAdapter { public MyCursorAdapter(Context context, Cursor c, boolean autoRequery) { super(context, c, autoRequery); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return LayoutInflater.from(context).inflate(R.layout.item_photo, parent, false); } @Override public void bindView(View view, Context context, Cursor cursor) { ImageView imageView = view.findViewById(R.id.item_image); //각 이미지의 URI 가져오기 String url = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)); Glide.with(context).load(url).into(imageView); } }
1,076
0.744802
0.742911
35
29.228571
28.286379
98
false
false
0
0
0
0
0
0
0.714286
false
false
6
63463da70a30a9a82c649ea1db9ac17c45dc22d8
21,715,354,712,334
6f28ba66909fa293d9058eb033e1694b4ec97eb0
/smartenv-system/smartenv-system-service/src/main/java/com/ai/apac/smartenv/system/service/impl/RegionServiceImpl.java
05e5707c40874433f22d98bf05712372057e27b0
[]
no_license
fangxunqing/smart-env
https://github.com/fangxunqing/smart-env
01870c01ceb8141787652585b7bf3738a3498641
99665cb17c8f7b96f1f6d29223d26a08b5b05d8a
refs/heads/main
2023-04-26T17:55:03.072000
2021-05-25T03:29:15
2021-05-25T03:29:15
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright (c) 2018-2028, Chill Zhuang All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * Neither the name of the dreamlu.net developer nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * Author: Chill 庄骞 (smallchill@163.com) */ package com.ai.apac.smartenv.system.service.impl; import com.ai.apac.smartenv.address.util.CoordsTypeConvertUtil; import com.ai.apac.smartenv.alarm.constant.AlarmConstant; import com.ai.apac.smartenv.alarm.dto.AlarmInfoCountDTO; import com.ai.apac.smartenv.alarm.feign.IAlarmInfoClient; import com.ai.apac.smartenv.arrange.feign.IScheduleClient; import com.ai.apac.smartenv.common.constant.ArrangeConstant; import com.ai.apac.smartenv.event.dto.EventQueryDTO; import com.ai.apac.smartenv.event.entity.EventInfo; import com.ai.apac.smartenv.event.feign.IEventInfoClient; import com.ai.apac.smartenv.event.vo.EventInfoVO; import com.ai.apac.smartenv.person.dto.BasicPersonDTO; import com.ai.apac.smartenv.person.entity.Person; import com.ai.apac.smartenv.person.feign.IPersonClient; import com.ai.apac.smartenv.system.constant.RegionConstant; import com.ai.apac.smartenv.system.entity.Region; import com.ai.apac.smartenv.system.vo.BigScreenInfoVO; import com.ai.apac.smartenv.system.vo.BusiRegionTreeVO; import com.ai.apac.smartenv.system.vo.BusiRegionVO; import com.ai.apac.smartenv.system.vo.RegionVO; import com.ai.apac.smartenv.system.mapper.RegionMapper; import com.ai.apac.smartenv.system.service.IRegionService; import com.ai.apac.smartenv.vehicle.dto.BasicVehicleInfoDTO; import com.ai.apac.smartenv.vehicle.entity.VehicleInfo; import com.ai.apac.smartenv.workarea.entity.WorkareaInfo; import com.ai.apac.smartenv.workarea.entity.WorkareaNode; import com.ai.apac.smartenv.workarea.entity.WorkareaRel; import com.ai.apac.smartenv.workarea.feign.IWorkareaClient; import com.ai.apac.smartenv.workarea.feign.IWorkareaNodeClient; import com.ai.apac.smartenv.workarea.feign.IWorkareaRelClient; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import lombok.AllArgsConstructor; import org.apache.commons.lang.StringUtils; import org.springblade.core.log.exception.ServiceException; import org.springblade.core.mp.base.BaseServiceImpl; import org.springblade.core.secure.utils.AuthUtil; import org.springblade.core.tool.api.R; import org.springblade.core.tool.utils.Func; import org.springblade.core.tool.utils.ObjectUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.stereotype.Service; import com.baomidou.mybatisplus.core.metadata.IPage; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * 服务实现类 * * @author Blade * @since 2020-01-16 */ @Service @AllArgsConstructor @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, rollbackFor = {ServiceException.class, Exception.class}) public class RegionServiceImpl extends BaseServiceImpl<RegionMapper, Region> implements IRegionService { private IWorkareaNodeClient workareaNodeClient; private IWorkareaClient workareaClient; private IPersonClient personClient; private CoordsTypeConvertUtil coordsTypeConvertUtil; private MongoTemplate mongoTemplate; private IEventInfoClient eventInfoClient; private IAlarmInfoClient alarmInfoClient; @Override public IPage<RegionVO> selectRegionPage(IPage<RegionVO> page, RegionVO region) { return page.setRecords(baseMapper.selectRegionPage(page, region)); } /** * 删除区域 * * @param regionIds * @return */ @Override @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, rollbackFor = {ServiceException.class, Exception.class}) public boolean removeRegion(String regionIds) { if(StringUtils.isBlank(regionIds)){ throw new ServiceException("请选择需要删除的区域"); } List<Long> regionIdList = Func.toLongList(regionIds); LambdaQueryWrapper<Region> queryWrapper = Wrappers.<Region>query().lambda() .in(Region::getParentRegionId, regionIdList); Integer cnt = baseMapper.selectCount(queryWrapper); if (cnt > 0) { throw new ServiceException("请先删除下级区域!"); } for (Long aLong : regionIdList) { // 删除业务区域网格坐标 //删除区域时校验该区域是否规划了作业区域 List<WorkareaInfo> workareaInfoList = workareaClient.getWorkareaInfoByRegion(aLong).getData(); if (workareaInfoList != null && workareaInfoList.size() > 0) { throw new ServiceException("请先删除下级工作区域或路线!"); } workareaNodeClient.deleteWorkAreaNodes(aLong); } boolean result = removeByIds(regionIdList); return result; } @Override @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, rollbackFor = {ServiceException.class, Exception.class}) public boolean savaOrUpdateRegionNew(BusiRegionVO busiRegionVO) { boolean result = false; //保存区域对象 Region region = busiRegionVO.getRegion(); if(StringUtils.isNotBlank(region.getRegionManager())) { region.setRegionManagerName(personClient.getPerson(Long.valueOf(region.getRegionManager())).getData().getPersonName()); } if(region.getId() != null && region.getId() != 0L){ //edit this.updateById(region); //同步更新事件中对应片区主管 EventQueryDTO eventQueryDTO = new EventQueryDTO(); eventQueryDTO.setTenantId(AuthUtil.getTenantId()); eventQueryDTO.setBelongArea(region.getId()); List<EventInfoVO> eventInfos = eventInfoClient.listEventInfoByParam(eventQueryDTO).getData(); if (eventInfos != null && eventInfos.size() > 0 && eventInfos.get(0).getId() != null) { for (EventInfoVO eventInfo : eventInfos) { eventInfo.setHandlePersonId(region.getRegionManager()); eventInfo.setHandlePersonName(region.getRegionManagerName()); eventInfoClient.updateEventInfo(eventInfo); } } // 同步更新区域、路线中对应的片区主管 List<WorkareaInfo> workareaInfoList = workareaClient.getWorkareaInfoByRegion(region.getId()).getData(); if (workareaInfoList != null && workareaInfoList.size() > 0 && workareaInfoList.get(0).getId() != null) { for (WorkareaInfo workareaInfo : workareaInfoList) { workareaInfo.setAreaHead(Long.valueOf(region.getRegionManager())); workareaClient.updateWorkareaInfo(workareaInfo); } } // 每次编辑调用前先删除原有的坐标点 if(region.getRegionType().intValue() == RegionConstant.REGION_TYPE.BUSI_REGION) { workareaNodeClient.deleteWorkAreaNodes(region.getId()); } }else { this.save(region); } WorkareaNode[] workareaNodes = busiRegionVO.getWorkareaNodes(); if (workareaNodes != null && workareaNodes.length > 0) { for (WorkareaNode workareaNode: workareaNodes ) { workareaNode.setRegionId(region.getId()); } if (workareaNodes.length > 0) { coordsTypeConvertUtil.fromWebConvert(Arrays.asList(workareaNodes)); for (WorkareaNode workareaNode : workareaNodes) { workareaNodeClient.saveWorkAreaNode(workareaNode).getData(); } } } result = true; return result; } @Override @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, rollbackFor = {ServiceException.class, Exception.class}) public BusiRegionVO queryBusiRegionList(Long regionId) { BusiRegionVO busiRegionVO = new BusiRegionVO(); Region region = this.getById(regionId); busiRegionVO.setRegion(region); R<List<WorkareaNode>> listR = workareaNodeClient.queryRegionNodesList(regionId); if (listR.getData() != null && listR.getData().size() > 0) { coordsTypeConvertUtil.toWebConvert(listR.getData()); busiRegionVO.setWorkareaNodes(listR.getData().toArray(new WorkareaNode[listR.getData().size()])); } return busiRegionVO; } @Override @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, rollbackFor = {ServiceException.class, Exception.class}) public BigScreenInfoVO queryBigScreenInfoCountByRegion(Long regionId,String tenantId) { BigScreenInfoVO bigScreenInfoVO = new BigScreenInfoVO(); Region region = this.getById(regionId); bigScreenInfoVO.setRegionName(region.getRegionName()); //人员数量、过滤休假数据 Query query = Query.query(Criteria.where("tenantId").is(tenantId).and("personBelongRegion").is(regionId).and("watchDeviceCode").ne(null)); List<BasicPersonDTO> basicPersonDTOList = mongoTemplate.find(query, BasicPersonDTO.class); bigScreenInfoVO.setPersonCount(basicPersonDTOList.size()); //车辆数量 过滤休假数据 Query query1 = Query.query(Criteria.where("tenantId").is(tenantId).and("vehicleBelongRegion").is(regionId).and("gpsDeviceCode").ne(null)); List<BasicVehicleInfoDTO> basicVehicleInfoDTOS = mongoTemplate.find(query1, BasicVehicleInfoDTO.class); bigScreenInfoVO.setVehicleCount(basicVehicleInfoDTOS.size()); //事件数量 Integer eventCount = eventInfoClient.countEventDailyByParam(tenantId,regionId).getData(); bigScreenInfoVO.setEventCount(eventCount); //告警数量 // 1-人员告警数量 Integer personAlarmCount = 0; if (basicPersonDTOList.size() > 0) { List<Long> entityIds = new ArrayList<>(); for (BasicPersonDTO basicPersonDTO : basicPersonDTOList) { entityIds.add(basicPersonDTO.getId()); } AlarmInfoCountDTO alarmInfoCountDTO = new AlarmInfoCountDTO(); alarmInfoCountDTO.setTenantId(tenantId); alarmInfoCountDTO.setEntityIds(entityIds); alarmInfoCountDTO.setIsHandle(AlarmConstant.IsHandle.HANDLED_NO); personAlarmCount = alarmInfoClient.countAlarmInfoAmountByEntityIds(alarmInfoCountDTO).getData(); } // 1-车辆告警数量 Integer vehicleAlarmCount = 0; if (basicVehicleInfoDTOS.size() > 0) { List<Long> entityIds = new ArrayList<>(); for (BasicVehicleInfoDTO basicVehicleInfoDTO : basicVehicleInfoDTOS) { entityIds.add(basicVehicleInfoDTO.getId()); } AlarmInfoCountDTO alarmInfoCountDTO = new AlarmInfoCountDTO(); alarmInfoCountDTO.setTenantId(tenantId); alarmInfoCountDTO.setEntityIds(entityIds); alarmInfoCountDTO.setIsHandle(AlarmConstant.IsHandle.HANDLED_NO); vehicleAlarmCount = alarmInfoClient.countAlarmInfoAmountByEntityIds(alarmInfoCountDTO).getData(); } bigScreenInfoVO.setAlarmCount(personAlarmCount + vehicleAlarmCount); return bigScreenInfoVO; } @Override @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, rollbackFor = {ServiceException.class, Exception.class}) public BigScreenInfoVO queryBigScreenInfoCountByAllRegion(String tenantId) { BigScreenInfoVO bigScreenInfoVO = new BigScreenInfoVO(); bigScreenInfoVO.setRegionName("全部"); //人员数量、过滤休假人员 Query query = Query.query(Criteria.where("tenantId").is(tenantId).and("personBelongRegion").ne(null).and("watchDeviceCode").ne(null)); List<BasicPersonDTO> basicPersonDTOList = mongoTemplate.find(query, BasicPersonDTO.class); bigScreenInfoVO.setPersonCount(basicPersonDTOList.size()); //车辆数量 ,过滤休假车辆 Query query1 = Query.query(Criteria.where("tenantId").is(tenantId).and("vehicleBelongRegion").ne(null).and("gpsDeviceCode").ne(null)); List<BasicVehicleInfoDTO> basicVehicleInfoDTOS = mongoTemplate.find(query1, BasicVehicleInfoDTO.class); bigScreenInfoVO.setVehicleCount(basicVehicleInfoDTOS.size()); //事件数量 Integer eventCount = eventInfoClient.countEventDaily(tenantId).getData(); bigScreenInfoVO.setEventCount(eventCount); //告警数量 // 1-人员告警数量 Integer personAlarmCount = 0; AlarmInfoCountDTO alarmInfoCountDTO = new AlarmInfoCountDTO(); alarmInfoCountDTO.setTenantId(tenantId); alarmInfoCountDTO.setIsHandle(AlarmConstant.IsHandle.HANDLED_NO); personAlarmCount = alarmInfoClient.countAlarmInfoAmountByEntityIds(alarmInfoCountDTO).getData(); bigScreenInfoVO.setAlarmCount(personAlarmCount); return bigScreenInfoVO; } @Override public BusiRegionTreeVO queryChildBusiRegionList(Long regionId) { BusiRegionTreeVO treeVO = new BusiRegionTreeVO(); List<BusiRegionVO> busiRegionVOS = new ArrayList<>(); //当前区域 BusiRegionVO regionVO = queryBusiRegionList(regionId); if (regionVO != null && regionVO.getRegion() != null) { treeVO.setBusiRegionVO(regionVO); } List<Region> regions = this.list(new QueryWrapper<Region>().eq("parent_region_id",regionId)); if (regions != null && regions.size() > 0) { for (Region region : regions) { BusiRegionVO busiRegionVO = new BusiRegionVO(); busiRegionVO.setRegion(region); R<List<WorkareaNode>> listR = workareaNodeClient.queryRegionNodesList(region.getId()); if (listR.getData() != null && listR.getData().size() > 0) { coordsTypeConvertUtil.toWebConvert(listR.getData()); busiRegionVO.setWorkareaNodes(listR.getData().toArray(new WorkareaNode[listR.getData().size()])); } busiRegionVOS.add(busiRegionVO); } } treeVO.setChildBusiRegionVOList(busiRegionVOS); return treeVO; } @Override public List<BusiRegionVO> queryAllBusiRegionAndNodes(String regionType,String tenantId) { List<BusiRegionVO> busiRegionVOList = new ArrayList<>(); String regionType_ = RegionConstant.REGION_TYPE.BUSI_REGION +","+ RegionConstant.REGION_TYPE.GREEN_REGION; // 两个都是业务区域 if(ObjectUtil.isNotEmpty(regionType)){ regionType_ = regionType; } List<Region> regionList = this.list(new QueryWrapper<Region>().in("region_type",Func.toIntList(regionType_)).eq("tenant_id",tenantId)); if (regionList != null && regionList.size() > 0) { for (Region region : regionList) { BusiRegionVO busiRegionVO = new BusiRegionVO(); if (region.getRegionManager() != null && !"".equals(region.getRegionManager())) { Person persion = personClient.getPerson(Long.valueOf(region.getRegionManager())).getData(); String name = region.getRegionName() + "("+persion.getPersonName()+")"; region.setExt1(name); } busiRegionVO.setRegion(region); R<List<WorkareaNode>> listR = workareaNodeClient.queryRegionNodesList(region.getId()); if (listR.getData() != null && listR.getData().size() > 0) { coordsTypeConvertUtil.toWebConvert(listR.getData()); busiRegionVO.setWorkareaNodes(listR.getData().toArray(new WorkareaNode[listR.getData().size()])); } busiRegionVOList.add(busiRegionVO); } } return busiRegionVOList; } /** * 查询所有上级是行政区域的业务区域 */ @Override public List<Region> queryAllBusiRegionList(String regionType,String tenantId) { String regionType_ = RegionConstant.REGION_TYPE.BUSI_REGION +","+ RegionConstant.REGION_TYPE.GREEN_REGION; // 两个都是业务区域 if(ObjectUtil.isNotEmpty(regionType)){ regionType_ = regionType; } List<Region> regionList = this.list(new QueryWrapper<Region>().in("region_type",Func.toIntList(regionType_)).eq("tenant_id",tenantId)); if (regionList != null && regionList.size() > 0) { for (Region region : regionList) { if (region.getRegionManager() != null && !"".equals(region.getRegionManager())) { Person persion = personClient.getPerson(Long.valueOf(region.getRegionManager())).getData(); String name = region.getRegionName() + "("+persion.getPersonName()+")"; region.setExt1(name); } } } return regionList; } @Override public List<Region> queryBusiRegionListForBS(String regionType,String tenantId) { QueryWrapper<VehicleInfo> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("a.region_type", regionType); queryWrapper.eq("a.tenant_Id", tenantId); List<Region> regionList = baseMapper.selectRegionListForBS(queryWrapper); return regionList; } }
UTF-8
Java
18,531
java
RegionServiceImpl.java
Java
[ { "context": "/*\n * Copyright (c) 2018-2028, Chill Zhuang All rights reserved.\n *\n * Redistribution and us", "end": 48, "score": 0.9998546838760376, "start": 36, "tag": "NAME", "value": "Chill Zhuang" }, { "context": "out specific prior written permission.\n * Author: Chill 庄骞 (smallchill@163.com)\n */\npackage com.ai.apac.smar", "end": 800, "score": 0.9998694658279419, "start": 792, "tag": "NAME", "value": "Chill 庄骞" }, { "context": "c prior written permission.\n * Author: Chill 庄骞 (smallchill@163.com)\n */\npackage com.ai.apac.smartenv.system.service.", "end": 820, "score": 0.9999258518218994, "start": 802, "tag": "EMAIL", "value": "smallchill@163.com" }, { "context": "import java.util.List;\n\n/**\n * 服务实现类\n *\n * @author Blade\n * @since 2020-01-16\n */\n@Service\n@AllArgsConstru", "end": 3737, "score": 0.9984115362167358, "start": 3732, "tag": "USERNAME", "value": "Blade" } ]
null
[]
/* * Copyright (c) 2018-2028, <NAME> All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * Neither the name of the dreamlu.net developer nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * Author: <NAME> (<EMAIL>) */ package com.ai.apac.smartenv.system.service.impl; import com.ai.apac.smartenv.address.util.CoordsTypeConvertUtil; import com.ai.apac.smartenv.alarm.constant.AlarmConstant; import com.ai.apac.smartenv.alarm.dto.AlarmInfoCountDTO; import com.ai.apac.smartenv.alarm.feign.IAlarmInfoClient; import com.ai.apac.smartenv.arrange.feign.IScheduleClient; import com.ai.apac.smartenv.common.constant.ArrangeConstant; import com.ai.apac.smartenv.event.dto.EventQueryDTO; import com.ai.apac.smartenv.event.entity.EventInfo; import com.ai.apac.smartenv.event.feign.IEventInfoClient; import com.ai.apac.smartenv.event.vo.EventInfoVO; import com.ai.apac.smartenv.person.dto.BasicPersonDTO; import com.ai.apac.smartenv.person.entity.Person; import com.ai.apac.smartenv.person.feign.IPersonClient; import com.ai.apac.smartenv.system.constant.RegionConstant; import com.ai.apac.smartenv.system.entity.Region; import com.ai.apac.smartenv.system.vo.BigScreenInfoVO; import com.ai.apac.smartenv.system.vo.BusiRegionTreeVO; import com.ai.apac.smartenv.system.vo.BusiRegionVO; import com.ai.apac.smartenv.system.vo.RegionVO; import com.ai.apac.smartenv.system.mapper.RegionMapper; import com.ai.apac.smartenv.system.service.IRegionService; import com.ai.apac.smartenv.vehicle.dto.BasicVehicleInfoDTO; import com.ai.apac.smartenv.vehicle.entity.VehicleInfo; import com.ai.apac.smartenv.workarea.entity.WorkareaInfo; import com.ai.apac.smartenv.workarea.entity.WorkareaNode; import com.ai.apac.smartenv.workarea.entity.WorkareaRel; import com.ai.apac.smartenv.workarea.feign.IWorkareaClient; import com.ai.apac.smartenv.workarea.feign.IWorkareaNodeClient; import com.ai.apac.smartenv.workarea.feign.IWorkareaRelClient; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import lombok.AllArgsConstructor; import org.apache.commons.lang.StringUtils; import org.springblade.core.log.exception.ServiceException; import org.springblade.core.mp.base.BaseServiceImpl; import org.springblade.core.secure.utils.AuthUtil; import org.springblade.core.tool.api.R; import org.springblade.core.tool.utils.Func; import org.springblade.core.tool.utils.ObjectUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.stereotype.Service; import com.baomidou.mybatisplus.core.metadata.IPage; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * 服务实现类 * * @author Blade * @since 2020-01-16 */ @Service @AllArgsConstructor @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, rollbackFor = {ServiceException.class, Exception.class}) public class RegionServiceImpl extends BaseServiceImpl<RegionMapper, Region> implements IRegionService { private IWorkareaNodeClient workareaNodeClient; private IWorkareaClient workareaClient; private IPersonClient personClient; private CoordsTypeConvertUtil coordsTypeConvertUtil; private MongoTemplate mongoTemplate; private IEventInfoClient eventInfoClient; private IAlarmInfoClient alarmInfoClient; @Override public IPage<RegionVO> selectRegionPage(IPage<RegionVO> page, RegionVO region) { return page.setRecords(baseMapper.selectRegionPage(page, region)); } /** * 删除区域 * * @param regionIds * @return */ @Override @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, rollbackFor = {ServiceException.class, Exception.class}) public boolean removeRegion(String regionIds) { if(StringUtils.isBlank(regionIds)){ throw new ServiceException("请选择需要删除的区域"); } List<Long> regionIdList = Func.toLongList(regionIds); LambdaQueryWrapper<Region> queryWrapper = Wrappers.<Region>query().lambda() .in(Region::getParentRegionId, regionIdList); Integer cnt = baseMapper.selectCount(queryWrapper); if (cnt > 0) { throw new ServiceException("请先删除下级区域!"); } for (Long aLong : regionIdList) { // 删除业务区域网格坐标 //删除区域时校验该区域是否规划了作业区域 List<WorkareaInfo> workareaInfoList = workareaClient.getWorkareaInfoByRegion(aLong).getData(); if (workareaInfoList != null && workareaInfoList.size() > 0) { throw new ServiceException("请先删除下级工作区域或路线!"); } workareaNodeClient.deleteWorkAreaNodes(aLong); } boolean result = removeByIds(regionIdList); return result; } @Override @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, rollbackFor = {ServiceException.class, Exception.class}) public boolean savaOrUpdateRegionNew(BusiRegionVO busiRegionVO) { boolean result = false; //保存区域对象 Region region = busiRegionVO.getRegion(); if(StringUtils.isNotBlank(region.getRegionManager())) { region.setRegionManagerName(personClient.getPerson(Long.valueOf(region.getRegionManager())).getData().getPersonName()); } if(region.getId() != null && region.getId() != 0L){ //edit this.updateById(region); //同步更新事件中对应片区主管 EventQueryDTO eventQueryDTO = new EventQueryDTO(); eventQueryDTO.setTenantId(AuthUtil.getTenantId()); eventQueryDTO.setBelongArea(region.getId()); List<EventInfoVO> eventInfos = eventInfoClient.listEventInfoByParam(eventQueryDTO).getData(); if (eventInfos != null && eventInfos.size() > 0 && eventInfos.get(0).getId() != null) { for (EventInfoVO eventInfo : eventInfos) { eventInfo.setHandlePersonId(region.getRegionManager()); eventInfo.setHandlePersonName(region.getRegionManagerName()); eventInfoClient.updateEventInfo(eventInfo); } } // 同步更新区域、路线中对应的片区主管 List<WorkareaInfo> workareaInfoList = workareaClient.getWorkareaInfoByRegion(region.getId()).getData(); if (workareaInfoList != null && workareaInfoList.size() > 0 && workareaInfoList.get(0).getId() != null) { for (WorkareaInfo workareaInfo : workareaInfoList) { workareaInfo.setAreaHead(Long.valueOf(region.getRegionManager())); workareaClient.updateWorkareaInfo(workareaInfo); } } // 每次编辑调用前先删除原有的坐标点 if(region.getRegionType().intValue() == RegionConstant.REGION_TYPE.BUSI_REGION) { workareaNodeClient.deleteWorkAreaNodes(region.getId()); } }else { this.save(region); } WorkareaNode[] workareaNodes = busiRegionVO.getWorkareaNodes(); if (workareaNodes != null && workareaNodes.length > 0) { for (WorkareaNode workareaNode: workareaNodes ) { workareaNode.setRegionId(region.getId()); } if (workareaNodes.length > 0) { coordsTypeConvertUtil.fromWebConvert(Arrays.asList(workareaNodes)); for (WorkareaNode workareaNode : workareaNodes) { workareaNodeClient.saveWorkAreaNode(workareaNode).getData(); } } } result = true; return result; } @Override @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, rollbackFor = {ServiceException.class, Exception.class}) public BusiRegionVO queryBusiRegionList(Long regionId) { BusiRegionVO busiRegionVO = new BusiRegionVO(); Region region = this.getById(regionId); busiRegionVO.setRegion(region); R<List<WorkareaNode>> listR = workareaNodeClient.queryRegionNodesList(regionId); if (listR.getData() != null && listR.getData().size() > 0) { coordsTypeConvertUtil.toWebConvert(listR.getData()); busiRegionVO.setWorkareaNodes(listR.getData().toArray(new WorkareaNode[listR.getData().size()])); } return busiRegionVO; } @Override @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, rollbackFor = {ServiceException.class, Exception.class}) public BigScreenInfoVO queryBigScreenInfoCountByRegion(Long regionId,String tenantId) { BigScreenInfoVO bigScreenInfoVO = new BigScreenInfoVO(); Region region = this.getById(regionId); bigScreenInfoVO.setRegionName(region.getRegionName()); //人员数量、过滤休假数据 Query query = Query.query(Criteria.where("tenantId").is(tenantId).and("personBelongRegion").is(regionId).and("watchDeviceCode").ne(null)); List<BasicPersonDTO> basicPersonDTOList = mongoTemplate.find(query, BasicPersonDTO.class); bigScreenInfoVO.setPersonCount(basicPersonDTOList.size()); //车辆数量 过滤休假数据 Query query1 = Query.query(Criteria.where("tenantId").is(tenantId).and("vehicleBelongRegion").is(regionId).and("gpsDeviceCode").ne(null)); List<BasicVehicleInfoDTO> basicVehicleInfoDTOS = mongoTemplate.find(query1, BasicVehicleInfoDTO.class); bigScreenInfoVO.setVehicleCount(basicVehicleInfoDTOS.size()); //事件数量 Integer eventCount = eventInfoClient.countEventDailyByParam(tenantId,regionId).getData(); bigScreenInfoVO.setEventCount(eventCount); //告警数量 // 1-人员告警数量 Integer personAlarmCount = 0; if (basicPersonDTOList.size() > 0) { List<Long> entityIds = new ArrayList<>(); for (BasicPersonDTO basicPersonDTO : basicPersonDTOList) { entityIds.add(basicPersonDTO.getId()); } AlarmInfoCountDTO alarmInfoCountDTO = new AlarmInfoCountDTO(); alarmInfoCountDTO.setTenantId(tenantId); alarmInfoCountDTO.setEntityIds(entityIds); alarmInfoCountDTO.setIsHandle(AlarmConstant.IsHandle.HANDLED_NO); personAlarmCount = alarmInfoClient.countAlarmInfoAmountByEntityIds(alarmInfoCountDTO).getData(); } // 1-车辆告警数量 Integer vehicleAlarmCount = 0; if (basicVehicleInfoDTOS.size() > 0) { List<Long> entityIds = new ArrayList<>(); for (BasicVehicleInfoDTO basicVehicleInfoDTO : basicVehicleInfoDTOS) { entityIds.add(basicVehicleInfoDTO.getId()); } AlarmInfoCountDTO alarmInfoCountDTO = new AlarmInfoCountDTO(); alarmInfoCountDTO.setTenantId(tenantId); alarmInfoCountDTO.setEntityIds(entityIds); alarmInfoCountDTO.setIsHandle(AlarmConstant.IsHandle.HANDLED_NO); vehicleAlarmCount = alarmInfoClient.countAlarmInfoAmountByEntityIds(alarmInfoCountDTO).getData(); } bigScreenInfoVO.setAlarmCount(personAlarmCount + vehicleAlarmCount); return bigScreenInfoVO; } @Override @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, rollbackFor = {ServiceException.class, Exception.class}) public BigScreenInfoVO queryBigScreenInfoCountByAllRegion(String tenantId) { BigScreenInfoVO bigScreenInfoVO = new BigScreenInfoVO(); bigScreenInfoVO.setRegionName("全部"); //人员数量、过滤休假人员 Query query = Query.query(Criteria.where("tenantId").is(tenantId).and("personBelongRegion").ne(null).and("watchDeviceCode").ne(null)); List<BasicPersonDTO> basicPersonDTOList = mongoTemplate.find(query, BasicPersonDTO.class); bigScreenInfoVO.setPersonCount(basicPersonDTOList.size()); //车辆数量 ,过滤休假车辆 Query query1 = Query.query(Criteria.where("tenantId").is(tenantId).and("vehicleBelongRegion").ne(null).and("gpsDeviceCode").ne(null)); List<BasicVehicleInfoDTO> basicVehicleInfoDTOS = mongoTemplate.find(query1, BasicVehicleInfoDTO.class); bigScreenInfoVO.setVehicleCount(basicVehicleInfoDTOS.size()); //事件数量 Integer eventCount = eventInfoClient.countEventDaily(tenantId).getData(); bigScreenInfoVO.setEventCount(eventCount); //告警数量 // 1-人员告警数量 Integer personAlarmCount = 0; AlarmInfoCountDTO alarmInfoCountDTO = new AlarmInfoCountDTO(); alarmInfoCountDTO.setTenantId(tenantId); alarmInfoCountDTO.setIsHandle(AlarmConstant.IsHandle.HANDLED_NO); personAlarmCount = alarmInfoClient.countAlarmInfoAmountByEntityIds(alarmInfoCountDTO).getData(); bigScreenInfoVO.setAlarmCount(personAlarmCount); return bigScreenInfoVO; } @Override public BusiRegionTreeVO queryChildBusiRegionList(Long regionId) { BusiRegionTreeVO treeVO = new BusiRegionTreeVO(); List<BusiRegionVO> busiRegionVOS = new ArrayList<>(); //当前区域 BusiRegionVO regionVO = queryBusiRegionList(regionId); if (regionVO != null && regionVO.getRegion() != null) { treeVO.setBusiRegionVO(regionVO); } List<Region> regions = this.list(new QueryWrapper<Region>().eq("parent_region_id",regionId)); if (regions != null && regions.size() > 0) { for (Region region : regions) { BusiRegionVO busiRegionVO = new BusiRegionVO(); busiRegionVO.setRegion(region); R<List<WorkareaNode>> listR = workareaNodeClient.queryRegionNodesList(region.getId()); if (listR.getData() != null && listR.getData().size() > 0) { coordsTypeConvertUtil.toWebConvert(listR.getData()); busiRegionVO.setWorkareaNodes(listR.getData().toArray(new WorkareaNode[listR.getData().size()])); } busiRegionVOS.add(busiRegionVO); } } treeVO.setChildBusiRegionVOList(busiRegionVOS); return treeVO; } @Override public List<BusiRegionVO> queryAllBusiRegionAndNodes(String regionType,String tenantId) { List<BusiRegionVO> busiRegionVOList = new ArrayList<>(); String regionType_ = RegionConstant.REGION_TYPE.BUSI_REGION +","+ RegionConstant.REGION_TYPE.GREEN_REGION; // 两个都是业务区域 if(ObjectUtil.isNotEmpty(regionType)){ regionType_ = regionType; } List<Region> regionList = this.list(new QueryWrapper<Region>().in("region_type",Func.toIntList(regionType_)).eq("tenant_id",tenantId)); if (regionList != null && regionList.size() > 0) { for (Region region : regionList) { BusiRegionVO busiRegionVO = new BusiRegionVO(); if (region.getRegionManager() != null && !"".equals(region.getRegionManager())) { Person persion = personClient.getPerson(Long.valueOf(region.getRegionManager())).getData(); String name = region.getRegionName() + "("+persion.getPersonName()+")"; region.setExt1(name); } busiRegionVO.setRegion(region); R<List<WorkareaNode>> listR = workareaNodeClient.queryRegionNodesList(region.getId()); if (listR.getData() != null && listR.getData().size() > 0) { coordsTypeConvertUtil.toWebConvert(listR.getData()); busiRegionVO.setWorkareaNodes(listR.getData().toArray(new WorkareaNode[listR.getData().size()])); } busiRegionVOList.add(busiRegionVO); } } return busiRegionVOList; } /** * 查询所有上级是行政区域的业务区域 */ @Override public List<Region> queryAllBusiRegionList(String regionType,String tenantId) { String regionType_ = RegionConstant.REGION_TYPE.BUSI_REGION +","+ RegionConstant.REGION_TYPE.GREEN_REGION; // 两个都是业务区域 if(ObjectUtil.isNotEmpty(regionType)){ regionType_ = regionType; } List<Region> regionList = this.list(new QueryWrapper<Region>().in("region_type",Func.toIntList(regionType_)).eq("tenant_id",tenantId)); if (regionList != null && regionList.size() > 0) { for (Region region : regionList) { if (region.getRegionManager() != null && !"".equals(region.getRegionManager())) { Person persion = personClient.getPerson(Long.valueOf(region.getRegionManager())).getData(); String name = region.getRegionName() + "("+persion.getPersonName()+")"; region.setExt1(name); } } } return regionList; } @Override public List<Region> queryBusiRegionListForBS(String regionType,String tenantId) { QueryWrapper<VehicleInfo> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("a.region_type", regionType); queryWrapper.eq("a.tenant_Id", tenantId); List<Region> regionList = baseMapper.selectRegionListForBS(queryWrapper); return regionList; } }
18,508
0.690536
0.687877
377
46.896553
35.731499
146
false
false
0
0
0
0
0
0
0.639257
false
false
6
2c7bde653f23e265b0caf96562a97fb2807eb2bc
12,893,491,843,052
234041d5e6f4c01d46ffb1964f268692e4893f72
/GGeasyLoL/app/src/main/java/com/antika/berk/ggeasylol/fragment/VideoFragment.java
a26a3d9c3443a74709355c4e990c0b52f7d8c9aa
[]
no_license
BerkEmre/GGEasy
https://github.com/BerkEmre/GGEasy
c858e76c2bef02bbf8658f9415f2982ee939f9ec
491e0c33abeb52d9af6bd420ec43bc16b88b20a8
refs/heads/master
2020-06-12T20:20:56.377000
2017-11-24T09:21:13
2017-11-24T09:21:13
75,754,683
3
1
null
false
2016-12-10T17:46:57
2016-12-06T17:26:18
2016-12-07T14:13:44
2016-12-10T17:46:57
20,996
2
0
0
Java
null
null
package com.antika.berk.ggeasylol.fragment; import android.media.MediaPlayer; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.VideoView; import com.antika.berk.ggeasylol.R; public class VideoFragment extends DialogFragment { VideoView videoView; String a; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE); View view= inflater.inflate(R.layout.fragment_video, container, false); videoView=(VideoView)view.findViewById(R.id.videoView); Bundle mArgs = getArguments(); String []array = mArgs.getStringArray("array"); if (array[1].equals("0")) videoView.setVideoPath("http://ggeasylol.com/api/videos/"+array[0]+"P.mp4"); else if (array[1].equals("1")) videoView.setVideoPath("http://ggeasylol.com/api/videos/"+array[0]+"Q.mp4"); else if (array[1].equals("2")) videoView.setVideoPath("http://ggeasylol.com/api/videos/"+array[0]+"W.mp4"); else if (array[1].equals("3")) videoView.setVideoPath("http://ggeasylol.com/api/videos/"+array[0]+"E.mp4"); else if (array[1].equals("4")) videoView.setVideoPath("http://ggeasylol.com/api/videos/"+array[0]+"R.mp4"); videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { videoView.start(); } }); return view; } }
UTF-8
Java
1,812
java
VideoFragment.java
Java
[]
null
[]
package com.antika.berk.ggeasylol.fragment; import android.media.MediaPlayer; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.VideoView; import com.antika.berk.ggeasylol.R; public class VideoFragment extends DialogFragment { VideoView videoView; String a; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE); View view= inflater.inflate(R.layout.fragment_video, container, false); videoView=(VideoView)view.findViewById(R.id.videoView); Bundle mArgs = getArguments(); String []array = mArgs.getStringArray("array"); if (array[1].equals("0")) videoView.setVideoPath("http://ggeasylol.com/api/videos/"+array[0]+"P.mp4"); else if (array[1].equals("1")) videoView.setVideoPath("http://ggeasylol.com/api/videos/"+array[0]+"Q.mp4"); else if (array[1].equals("2")) videoView.setVideoPath("http://ggeasylol.com/api/videos/"+array[0]+"W.mp4"); else if (array[1].equals("3")) videoView.setVideoPath("http://ggeasylol.com/api/videos/"+array[0]+"E.mp4"); else if (array[1].equals("4")) videoView.setVideoPath("http://ggeasylol.com/api/videos/"+array[0]+"R.mp4"); videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { videoView.start(); } }); return view; } }
1,812
0.65287
0.64128
55
31.945454
28.527765
88
false
false
0
0
0
0
0
0
0.545455
false
false
6
36623b14714e2d1e8c9d98b2fb78f32e8b4fbb02
16,149,077,057,609
8f755e5600ef02dacce310603f52d275e066017d
/src/java/controllers/korisnik/KorisnikGradskeViewController.java
f71128ea7478ccb62d5b047551044eb304b07dfc
[]
no_license
mladjanmih/public-transport-management-system
https://github.com/mladjanmih/public-transport-management-system
bfe9cd3b8f72b4adbc5cfc52bddaddd59a2e4c6d
d2cf93d46b46cd95bfa9531c1596db8c7959e959
refs/heads/master
2020-03-26T09:59:33.295000
2019-03-03T14:31:50
2019-03-03T14:31:50
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Mladjan Mihajlovic * Programiranje internet aplikacija | Elektrotehnicki fakultet | Avgust 2018 */ package controllers.korisnik; import beans.GradskaLinija; import beans.Stanica; import beans.managers.BeanManager; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import static java.util.stream.Collectors.toList; import javax.annotation.PostConstruct; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import utils.ApplicationUtils; /** * * @author Mlađan */ @ManagedBean(name = "korisnikGradskeView") @ViewScoped public class KorisnikGradskeViewController implements Serializable { private List<GradskaLinija> linije; private List<GradskaLinija> filtriraneLinije; private List<GradskaLinija> pretragaLinija; private String nazivOdredista; public KorisnikGradskeViewController() { linije = new ArrayList<>(); filtriraneLinije = new ArrayList<>(); } @PostConstruct public void init() { Date d = Calendar.getInstance().getTime(); SimpleDateFormat sdt = new SimpleDateFormat("yyyy-MM-dd"); String date = sdt.format(d); BeanManager.executeUpdate("update gradske_linije set aktivna=true where CAST(otkazana_do as date) < '" + date + "'", null); linije = BeanManager.getList("from gradske_linije where aktivna = true order by broj_linije"); } public List<GradskaLinija> getLinije() { return linije; } public void setLinije(List<GradskaLinija> linije) { this.linije = linije; } public List<GradskaLinija> getFiltriraneLinije() { return filtriraneLinije; } public void setFiltriraneLinije(List<GradskaLinija> filtriraneLinije) { this.filtriraneLinije = filtriraneLinije; } public String getNazivOdredista() { return nazivOdredista; } public void setNazivOdredista(String nazivOdredista) { this.nazivOdredista = nazivOdredista; } public void pretragaPoOdredistu() { //linije = BeanManager.getList("from gradske_linije where aktivna = true order by broj_linije"); if (ApplicationUtils.isNullOrEmpty(nazivOdredista)) { this.pretragaLinija = new ArrayList<>(); this.pretragaLinija.addAll(this.linije); return; } String nazivLower = nazivOdredista.toLowerCase(); this.pretragaLinija = linije.stream() .filter((l) -> { String lower = l.getOdredisnaStanica().getNaziv().toLowerCase(); if (!ApplicationUtils.isNullOrEmpty(lower) && (nazivLower.equals(lower) || lower.contains(nazivLower.subSequence(0, nazivLower.length())))) { return true; } if (ApplicationUtils.isNullOrEmpty(l.getMedjustanice())) { return false; } boolean found = false; for (Stanica m : l.getMedjustanice()) { lower = m.getNaziv().toLowerCase(); if (!ApplicationUtils.isNullOrEmpty(lower) && (lower.equals(nazivLower) || lower.contains(nazivLower.subSequence(0, nazivLower.length())))) { found = true; break; } } return found; }) .collect(toList()); } public List<GradskaLinija> getPretragaLinija() { return pretragaLinija; } public void setPretragaLinija(List<GradskaLinija> pretragaLinija) { this.pretragaLinija = pretragaLinija; } }
UTF-8
Java
3,927
java
KorisnikGradskeViewController.java
Java
[ { "context": "/*\r\n * Mladjan Mihajlovic \r\n * Programiranje internet aplikacija | Elektrot", "end": 25, "score": 0.9998919367790222, "start": 7, "tag": "NAME", "value": "Mladjan Mihajlovic" }, { "context": "ort utils.ApplicationUtils;\r\n\r\n/**\r\n *\r\n * @author Mlađan\r\n */\r\n@ManagedBean(name = \"korisnikGradskeView\")\r", "end": 630, "score": 0.9997262358665466, "start": 624, "tag": "NAME", "value": "Mlađan" } ]
null
[]
/* * <NAME> * Programiranje internet aplikacija | Elektrotehnicki fakultet | Avgust 2018 */ package controllers.korisnik; import beans.GradskaLinija; import beans.Stanica; import beans.managers.BeanManager; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import static java.util.stream.Collectors.toList; import javax.annotation.PostConstruct; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import utils.ApplicationUtils; /** * * @author Mlađan */ @ManagedBean(name = "korisnikGradskeView") @ViewScoped public class KorisnikGradskeViewController implements Serializable { private List<GradskaLinija> linije; private List<GradskaLinija> filtriraneLinije; private List<GradskaLinija> pretragaLinija; private String nazivOdredista; public KorisnikGradskeViewController() { linije = new ArrayList<>(); filtriraneLinije = new ArrayList<>(); } @PostConstruct public void init() { Date d = Calendar.getInstance().getTime(); SimpleDateFormat sdt = new SimpleDateFormat("yyyy-MM-dd"); String date = sdt.format(d); BeanManager.executeUpdate("update gradske_linije set aktivna=true where CAST(otkazana_do as date) < '" + date + "'", null); linije = BeanManager.getList("from gradske_linije where aktivna = true order by broj_linije"); } public List<GradskaLinija> getLinije() { return linije; } public void setLinije(List<GradskaLinija> linije) { this.linije = linije; } public List<GradskaLinija> getFiltriraneLinije() { return filtriraneLinije; } public void setFiltriraneLinije(List<GradskaLinija> filtriraneLinije) { this.filtriraneLinije = filtriraneLinije; } public String getNazivOdredista() { return nazivOdredista; } public void setNazivOdredista(String nazivOdredista) { this.nazivOdredista = nazivOdredista; } public void pretragaPoOdredistu() { //linije = BeanManager.getList("from gradske_linije where aktivna = true order by broj_linije"); if (ApplicationUtils.isNullOrEmpty(nazivOdredista)) { this.pretragaLinija = new ArrayList<>(); this.pretragaLinija.addAll(this.linije); return; } String nazivLower = nazivOdredista.toLowerCase(); this.pretragaLinija = linije.stream() .filter((l) -> { String lower = l.getOdredisnaStanica().getNaziv().toLowerCase(); if (!ApplicationUtils.isNullOrEmpty(lower) && (nazivLower.equals(lower) || lower.contains(nazivLower.subSequence(0, nazivLower.length())))) { return true; } if (ApplicationUtils.isNullOrEmpty(l.getMedjustanice())) { return false; } boolean found = false; for (Stanica m : l.getMedjustanice()) { lower = m.getNaziv().toLowerCase(); if (!ApplicationUtils.isNullOrEmpty(lower) && (lower.equals(nazivLower) || lower.contains(nazivLower.subSequence(0, nazivLower.length())))) { found = true; break; } } return found; }) .collect(toList()); } public List<GradskaLinija> getPretragaLinija() { return pretragaLinija; } public void setPretragaLinija(List<GradskaLinija> pretragaLinija) { this.pretragaLinija = pretragaLinija; } }
3,915
0.60596
0.604432
122
30.180328
30.072866
165
false
false
0
0
0
0
0
0
0.467213
false
false
6
101841c45f3d45a57c09b450eaacc4ef77af891d
26,749,056,343,462
bc8adf80a4e4842ee08ce72b76af10d9ecad7aa3
/src/server/Operation.java
5f7d032d67a73ba64260cb93ee9431e83d82b8f9
[]
no_license
Marcusx11/TrabalhoSistemasDistribuidos
https://github.com/Marcusx11/TrabalhoSistemasDistribuidos
4089ed9b5a4eebd66dfb2a002d2efeb82c91531f
b9b3331f62f3d274ffdaec9c09a582ea772e5bfe
refs/heads/main
2023-07-07T07:54:00.953000
2021-08-03T18:44:37
2021-08-03T18:44:37
381,514,260
1
0
null
false
2021-07-21T14:20:48
2021-06-29T22:40:22
2021-07-21T00:46:25
2021-07-21T14:20:48
9,816
1
0
0
Java
false
false
package server; import core.Response; import core.ResponseCode; import core.models.transfer.Transfer; import core.models.transfer.TransferDAO; import core.models.user.User; import core.models.user.UserDAO; import java.util.List; public class Operation { private float userBalance(User user) { TransferDAO transferDAO = new TransferDAO(); List<Transfer> transfersOut = transferDAO.selectBy("from_user_id", String.valueOf(user.getId())); List<Transfer> transfersIn = transferDAO.selectBy("to_user_id", String.valueOf(user.getId())); float transfersOutTotal = 0; for (Transfer transfer:transfersOut) { transfersOutTotal += transfer.getAmount(); } float transfersInTotal = 0; for (Transfer transfer:transfersIn) { transfersInTotal += transfer.getAmount(); } return transfersInTotal - transfersOutTotal; } public Response transfer(Transfer transfer) { try { UserDAO userDAO = new UserDAO(); User userTo = userDAO.findBy("id", String.valueOf(transfer.getToUserId())); User userFrom = userDAO.findBy("id", String.valueOf(transfer.getFromUserId())); if (userTo == null) { return new Response(ResponseCode.ERROR, "Destination account not found."); } if (userFrom == null) { return new Response(ResponseCode.ERROR, "Invalid source account."); } if (this.userBalance(userFrom) < transfer.getAmount()) { return new Response(ResponseCode.ERROR, "Transfer amount exceeds balance."); } TransferDAO transferDAO = new TransferDAO(); transferDAO.create(transfer); return new Response(ResponseCode.OK, "The transfer was successfully created."); } catch (Exception e) { return new Response(ResponseCode.ERROR, "There was a problem creating this transfer. Please try again."); } } public Response balance(User user) { try { return new Response(ResponseCode.OK, this.userBalance(user)); } catch (Exception e) { return new Response(ResponseCode.ERROR, "There was a problem. Please try again."); } } public Response listAllUsers() { try { UserDAO userDAO = new UserDAO(); List<User> users = userDAO.selectAll(); return new Response(ResponseCode.OK, users); } catch (Exception e) { return new Response(ResponseCode.ERROR, "There was a problem. Please try again."); } } public Response statementOfAccount(User user) { TransferDAO transferDAO = new TransferDAO(); List<Transfer> transfers = transferDAO.fromUser(String.valueOf(user.getId())); return new Response(ResponseCode.OK, transfers); } public Response bankAmount() { UserDAO userDAO = new UserDAO(); List<User> users = userDAO.selectAll(); float total = 0; for (User user: users) { total += this.userBalance(user); } return new Response(ResponseCode.OK, total); } }
UTF-8
Java
3,204
java
Operation.java
Java
[]
null
[]
package server; import core.Response; import core.ResponseCode; import core.models.transfer.Transfer; import core.models.transfer.TransferDAO; import core.models.user.User; import core.models.user.UserDAO; import java.util.List; public class Operation { private float userBalance(User user) { TransferDAO transferDAO = new TransferDAO(); List<Transfer> transfersOut = transferDAO.selectBy("from_user_id", String.valueOf(user.getId())); List<Transfer> transfersIn = transferDAO.selectBy("to_user_id", String.valueOf(user.getId())); float transfersOutTotal = 0; for (Transfer transfer:transfersOut) { transfersOutTotal += transfer.getAmount(); } float transfersInTotal = 0; for (Transfer transfer:transfersIn) { transfersInTotal += transfer.getAmount(); } return transfersInTotal - transfersOutTotal; } public Response transfer(Transfer transfer) { try { UserDAO userDAO = new UserDAO(); User userTo = userDAO.findBy("id", String.valueOf(transfer.getToUserId())); User userFrom = userDAO.findBy("id", String.valueOf(transfer.getFromUserId())); if (userTo == null) { return new Response(ResponseCode.ERROR, "Destination account not found."); } if (userFrom == null) { return new Response(ResponseCode.ERROR, "Invalid source account."); } if (this.userBalance(userFrom) < transfer.getAmount()) { return new Response(ResponseCode.ERROR, "Transfer amount exceeds balance."); } TransferDAO transferDAO = new TransferDAO(); transferDAO.create(transfer); return new Response(ResponseCode.OK, "The transfer was successfully created."); } catch (Exception e) { return new Response(ResponseCode.ERROR, "There was a problem creating this transfer. Please try again."); } } public Response balance(User user) { try { return new Response(ResponseCode.OK, this.userBalance(user)); } catch (Exception e) { return new Response(ResponseCode.ERROR, "There was a problem. Please try again."); } } public Response listAllUsers() { try { UserDAO userDAO = new UserDAO(); List<User> users = userDAO.selectAll(); return new Response(ResponseCode.OK, users); } catch (Exception e) { return new Response(ResponseCode.ERROR, "There was a problem. Please try again."); } } public Response statementOfAccount(User user) { TransferDAO transferDAO = new TransferDAO(); List<Transfer> transfers = transferDAO.fromUser(String.valueOf(user.getId())); return new Response(ResponseCode.OK, transfers); } public Response bankAmount() { UserDAO userDAO = new UserDAO(); List<User> users = userDAO.selectAll(); float total = 0; for (User user: users) { total += this.userBalance(user); } return new Response(ResponseCode.OK, total); } }
3,204
0.61985
0.618914
98
31.693878
30.67985
117
false
false
0
0
0
0
0
0
0.561224
false
false
6
7672600ee5ba197906f0f356db84fc4a7d65a262
16,939,351,041,307
fb2db831430b0831b314c25a437b6b1b5fccf200
/XToolOutAndroid/src/main/java/ulric/li/xout/core/communication/CommunicationImpl.java
64d25e97107b27179e1dfc0a67dad1bc167b32b9
[]
no_license
LiuZhiDaa/PeriodAndroid
https://github.com/LiuZhiDaa/PeriodAndroid
8795840c6ca1e923bf87a2afdfdd2775ed7e5d98
aa6cfab846ec82ad322d53df87e8e43dbda93568
refs/heads/master
2020-04-22T15:38:46.178000
2019-02-13T09:57:27
2019-02-13T09:57:27
170,483,783
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package ulric.li.xout.core.communication; import android.content.Intent; import android.support.v4.content.LocalBroadcastManager; import ulric.li.utils.UtilsLog; import ulric.li.xout.core.XOutFactory; /** * Created by WangYu on 2018/9/5. */ public class CommunicationImpl implements IOutComponent { private static IOutComponent mIOutComponent=null; public void setComponentInstance(IOutComponent i) { mIOutComponent=i; } @Override public String getConfigUrl() { if (mIOutComponent != null) { return mIOutComponent.getConfigUrl(); } sendBroadCastReceiver(); return ""; } @Override public String getNativeAdKey(String strScene) { if (mIOutComponent != null) { return mIOutComponent.getNativeAdKey(strScene); } sendBroadCastReceiver(); return ""; } @Override public String getBannerAdKey(String strScene) { if (mIOutComponent != null) { return mIOutComponent.getBannerAdKey(strScene); } sendBroadCastReceiver(); return ""; } @Override public String getInterstitialAdKey(String strScene) { if (mIOutComponent != null) { return mIOutComponent.getInterstitialAdKey(strScene); } sendBroadCastReceiver(); return ""; } @Override public String getSceneName(String adKey) { if (mIOutComponent != null) { return mIOutComponent.getSceneName(adKey); } sendBroadCastReceiver(); return ""; } @Override public Class<?> getOutPageClass(String strScene) { if (mIOutComponent != null) { return mIOutComponent.getOutPageClass(strScene); } sendBroadCastReceiver(); return null; } private void sendBroadCastReceiver() { try { UtilsLog.statisticsLog("out", "IOutComponent is null", null); LocalBroadcastManager manager = LocalBroadcastManager.getInstance(XOutFactory.getApplication()); Intent intent = new Intent(); intent.setAction(BROADCAST_ACTION); manager.sendBroadcast(intent); } catch (Exception e) { e.printStackTrace(); } } }
UTF-8
Java
2,284
java
CommunicationImpl.java
Java
[ { "context": "ulric.li.xout.core.XOutFactory;\n\n/**\n * Created by WangYu on 2018/9/5.\n */\npublic class CommunicationImpl i", "end": 228, "score": 0.8211160898208618, "start": 222, "tag": "USERNAME", "value": "WangYu" } ]
null
[]
package ulric.li.xout.core.communication; import android.content.Intent; import android.support.v4.content.LocalBroadcastManager; import ulric.li.utils.UtilsLog; import ulric.li.xout.core.XOutFactory; /** * Created by WangYu on 2018/9/5. */ public class CommunicationImpl implements IOutComponent { private static IOutComponent mIOutComponent=null; public void setComponentInstance(IOutComponent i) { mIOutComponent=i; } @Override public String getConfigUrl() { if (mIOutComponent != null) { return mIOutComponent.getConfigUrl(); } sendBroadCastReceiver(); return ""; } @Override public String getNativeAdKey(String strScene) { if (mIOutComponent != null) { return mIOutComponent.getNativeAdKey(strScene); } sendBroadCastReceiver(); return ""; } @Override public String getBannerAdKey(String strScene) { if (mIOutComponent != null) { return mIOutComponent.getBannerAdKey(strScene); } sendBroadCastReceiver(); return ""; } @Override public String getInterstitialAdKey(String strScene) { if (mIOutComponent != null) { return mIOutComponent.getInterstitialAdKey(strScene); } sendBroadCastReceiver(); return ""; } @Override public String getSceneName(String adKey) { if (mIOutComponent != null) { return mIOutComponent.getSceneName(adKey); } sendBroadCastReceiver(); return ""; } @Override public Class<?> getOutPageClass(String strScene) { if (mIOutComponent != null) { return mIOutComponent.getOutPageClass(strScene); } sendBroadCastReceiver(); return null; } private void sendBroadCastReceiver() { try { UtilsLog.statisticsLog("out", "IOutComponent is null", null); LocalBroadcastManager manager = LocalBroadcastManager.getInstance(XOutFactory.getApplication()); Intent intent = new Intent(); intent.setAction(BROADCAST_ACTION); manager.sendBroadcast(intent); } catch (Exception e) { e.printStackTrace(); } } }
2,284
0.623468
0.620403
86
25.55814
22.133635
108
false
false
0
0
0
0
0
0
0.383721
false
false
6
bd52cca66529e709711d5263b45c1dd111aa2165
24,962,349,951,636
ed80d330815b18862d587d71a12897cd261947d3
/src/main/java/com/frlz/mapper/PrePlanMapper.java
21a9e7c7290ea63311f725346773c45245e2190a
[]
no_license
a02241/frlzGitHub
https://github.com/a02241/frlzGitHub
e3e8d31d2a4c468341b0567e308b4b1b698da871
c785fd6ed0ba616648b869ea42be3622f739465d
refs/heads/master
2020-04-27T10:33:00.427000
2019-04-26T01:18:00
2019-04-26T01:18:00
174,258,940
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.frlz.mapper; import com.frlz.pojo.PrePlan; import org.apache.ibatis.annotations.*; import java.util.Date; import java.util.List; /** * @author cz */ public interface PrePlanMapper { @SelectKey(keyProperty = "prePlanId",resultType = String.class, before = true, statement = "select replace(uuid(), '-', '')") @Options(keyProperty = "prePlanId", useGeneratedKeys = true) @Insert("insert into prePlan values(#{prePlanId},#{message},now(),#{uid})") void insertIntoPrePlan(PrePlan prePlan); @Select("select * from prePlan where uid = #{uid} and DATEDIFF(time,#{time}) =0") PrePlan selectPrePlanByUid(String uid, String time); @Select("select count(*) from prePlan where prePlanId = #{prePlanId}") int checkPrePlan(String prePlanId); @Select("select count(*) from prePlan where uid = #{uid}") int checkPrePlanByUid(String uid); @Select("select time from prePlan where DATE_FORMAT(time, '%Y-%m') = #{time} and uid = #{uid}") List<Date> selectTimeByMonthUid(String time , String uid); @Update("update prePlan set message = #{message} where prePlanId = #{prePlanId}") void updatePrePlanMessage(String message,String prePlanId); @Delete("delete from prePlan where prePlanId = #{prePlanId}") void deletePrePlanByprePlanId(String prePlanId); }
UTF-8
Java
1,332
java
PrePlanMapper.java
Java
[ { "context": "a.util.Date;\nimport java.util.List;\n/**\n * @author cz\n */\npublic interface PrePlanMapper {\n\n @Select", "end": 160, "score": 0.990892767906189, "start": 158, "tag": "USERNAME", "value": "cz" } ]
null
[]
package com.frlz.mapper; import com.frlz.pojo.PrePlan; import org.apache.ibatis.annotations.*; import java.util.Date; import java.util.List; /** * @author cz */ public interface PrePlanMapper { @SelectKey(keyProperty = "prePlanId",resultType = String.class, before = true, statement = "select replace(uuid(), '-', '')") @Options(keyProperty = "prePlanId", useGeneratedKeys = true) @Insert("insert into prePlan values(#{prePlanId},#{message},now(),#{uid})") void insertIntoPrePlan(PrePlan prePlan); @Select("select * from prePlan where uid = #{uid} and DATEDIFF(time,#{time}) =0") PrePlan selectPrePlanByUid(String uid, String time); @Select("select count(*) from prePlan where prePlanId = #{prePlanId}") int checkPrePlan(String prePlanId); @Select("select count(*) from prePlan where uid = #{uid}") int checkPrePlanByUid(String uid); @Select("select time from prePlan where DATE_FORMAT(time, '%Y-%m') = #{time} and uid = #{uid}") List<Date> selectTimeByMonthUid(String time , String uid); @Update("update prePlan set message = #{message} where prePlanId = #{prePlanId}") void updatePrePlanMessage(String message,String prePlanId); @Delete("delete from prePlan where prePlanId = #{prePlanId}") void deletePrePlanByprePlanId(String prePlanId); }
1,332
0.692192
0.691441
36
36
31.361689
99
false
false
0
0
0
0
0
0
0.722222
false
false
6
a57f24c6f4a5a64bb15369ab38ba2a71806a2301
3,178,275,834,965
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/2/2_8ab11cd3fca47be804782f3a028761c77bc60afb/JumpCommand/2_8ab11cd3fca47be804782f3a028761c77bc60afb_JumpCommand_s.java
1d07fea49f30749c84d9c36e2ae5ee2946b11876
[]
no_license
zhongxingyu/Seer
https://github.com/zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516000
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
false
2023-06-22T07:55:57
2020-04-28T11:07:49
2023-06-21T00:53:27
2023-06-22T07:55:57
2,849,868
2
2
0
null
false
false
package no.runsafe.creativetoolbox.command; import no.runsafe.creativetoolbox.PlotFilter; import no.runsafe.creativetoolbox.PlotList; import no.runsafe.creativetoolbox.database.ApprovedPlotRepository; import no.runsafe.framework.api.IScheduler; import no.runsafe.framework.api.command.argument.EnumArgument; import no.runsafe.framework.api.command.player.PlayerAsyncCallbackCommand; import no.runsafe.framework.api.player.IPlayer; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Random; public class JumpCommand extends PlayerAsyncCallbackCommand<JumpCommand.Sudo> { public enum JumpKinds { Approved, Unapproved } public JumpCommand(IScheduler scheduler, PlotFilter plotFilter, ApprovedPlotRepository approval, PlotList plotList) { super("jump", "Find a random plot of a given kind", "runsafe.creative.teleport.random", scheduler, new EnumArgument("kind", JumpKinds.values(), true)); this.plotFilter = plotFilter; this.approval = approval; this.plotList = plotList; } @Override public Sudo OnAsyncExecute(IPlayer executor, Map<String, String> params) { console.debugFine("Jumping to an %s plot", params.get("kind")); List<String> approved = approval.getApprovedPlots(); Sudo target = new Sudo(); target.player = executor; if (params.get("kind").equals(JumpKinds.Approved.name().toLowerCase())) { int r = rng.nextInt(approved.size()); plotList.set(executor, approved); plotList.wind(executor, approved.get(r)); target.command = String.format("creativetoolbox teleport %s", approved.get(r)); return target; } List<String> plots = plotFilter.getFiltered(); ArrayList<String> result = new ArrayList<String>(); for (String value : plots) if (!approved.contains(value)) result.add(value); int r = rng.nextInt(result.size()); plotList.set(executor, result); plotList.wind(executor, result.get(r)); target.command = String.format("creativetoolbox teleport %s", result.get(r)); return target; } @Override public void SyncPostExecute(Sudo result) { if (result != null) result.player.performCommand(result.command); } class Sudo { public IPlayer player; public String command; } private final PlotFilter plotFilter; private final ApprovedPlotRepository approval; private final Random rng = new Random(); private final PlotList plotList; }
UTF-8
Java
2,523
java
2_8ab11cd3fca47be804782f3a028761c77bc60afb_JumpCommand_s.java
Java
[]
null
[]
package no.runsafe.creativetoolbox.command; import no.runsafe.creativetoolbox.PlotFilter; import no.runsafe.creativetoolbox.PlotList; import no.runsafe.creativetoolbox.database.ApprovedPlotRepository; import no.runsafe.framework.api.IScheduler; import no.runsafe.framework.api.command.argument.EnumArgument; import no.runsafe.framework.api.command.player.PlayerAsyncCallbackCommand; import no.runsafe.framework.api.player.IPlayer; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Random; public class JumpCommand extends PlayerAsyncCallbackCommand<JumpCommand.Sudo> { public enum JumpKinds { Approved, Unapproved } public JumpCommand(IScheduler scheduler, PlotFilter plotFilter, ApprovedPlotRepository approval, PlotList plotList) { super("jump", "Find a random plot of a given kind", "runsafe.creative.teleport.random", scheduler, new EnumArgument("kind", JumpKinds.values(), true)); this.plotFilter = plotFilter; this.approval = approval; this.plotList = plotList; } @Override public Sudo OnAsyncExecute(IPlayer executor, Map<String, String> params) { console.debugFine("Jumping to an %s plot", params.get("kind")); List<String> approved = approval.getApprovedPlots(); Sudo target = new Sudo(); target.player = executor; if (params.get("kind").equals(JumpKinds.Approved.name().toLowerCase())) { int r = rng.nextInt(approved.size()); plotList.set(executor, approved); plotList.wind(executor, approved.get(r)); target.command = String.format("creativetoolbox teleport %s", approved.get(r)); return target; } List<String> plots = plotFilter.getFiltered(); ArrayList<String> result = new ArrayList<String>(); for (String value : plots) if (!approved.contains(value)) result.add(value); int r = rng.nextInt(result.size()); plotList.set(executor, result); plotList.wind(executor, result.get(r)); target.command = String.format("creativetoolbox teleport %s", result.get(r)); return target; } @Override public void SyncPostExecute(Sudo result) { if (result != null) result.player.performCommand(result.command); } class Sudo { public IPlayer player; public String command; } private final PlotFilter plotFilter; private final ApprovedPlotRepository approval; private final Random rng = new Random(); private final PlotList plotList; }
2,523
0.710662
0.710662
76
31.18421
28.949007
154
false
false
0
0
0
0
0
0
2.013158
false
false
6
e09ebc97283a5ce6a5652b123b9241284b236729
20,607,253,128,991
cd53388a4b1922598dd7f3dc25592b59b7c85c1f
/Javadir/java_train/src/main/java/tenthChapter/anonymousClasses/StringCorrector.java
8b2d4e367b7fa9ac8ee0272c7aa20812743f5f1e
[]
no_license
IgorPystovit/Java
https://github.com/IgorPystovit/Java
fe3654e7f69cd3adbbc011e32d3314b2a0fee176
4dd3b18ed775a943f7b32a2062cb1eb65e7413ec
refs/heads/master
2020-04-30T02:01:45.076000
2019-05-19T11:14:06
2019-05-19T11:14:06
176,546,848
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package tenthChapter.anonymousClasses; public class StringCorrector { private String string; public StringCorrector(String string){ this.string = string; } public String getString() { return string; } }
UTF-8
Java
243
java
StringCorrector.java
Java
[]
null
[]
package tenthChapter.anonymousClasses; public class StringCorrector { private String string; public StringCorrector(String string){ this.string = string; } public String getString() { return string; } }
243
0.666667
0.666667
13
17.692308
15.454074
42
false
false
0
0
0
0
0
0
0.307692
false
false
6
5ca092c216508f0a95a379d93090720fdd46781a
20,607,253,126,624
3ed62214bc614f8bf58672664714fbf4950a2085
/cn.yuanwill.bufferedStream/BufferedInputStreamTest.java
c622c22104a7a33c78a8bfb652586f2a48c2d87f
[]
no_license
shenyWill/javaSE
https://github.com/shenyWill/javaSE
f2091a4c55c79706a1d7b1d6bc6fab899d773d12
1fff69b781576b3321ecce81b50153434902fefd
refs/heads/master
2020-03-28T11:45:06.813000
2018-11-25T08:29:05
2018-11-25T08:29:05
148,243,916
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.yuanwill.bufferedStream; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class BufferedInputStreamTest { public static void main(String[] args) throws IOException { File file = new File("C:\\Users\\shenyuan\\Desktop\\test\\test1.txt"); FileInputStream fis = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(fis); byte[] b = new byte[(int) file.length()]; bis.read(b); System.out.println(new String(b)); bis.close(); } }
UTF-8
Java
602
java
BufferedInputStreamTest.java
Java
[ { "context": " IOException {\n\t\tFile file = new File(\"C:\\\\Users\\\\shenyuan\\\\Desktop\\\\test\\\\test1.txt\");\n\t\tFileInputStream fi", "end": 337, "score": 0.9240242838859558, "start": 329, "tag": "USERNAME", "value": "shenyuan" } ]
null
[]
package cn.yuanwill.bufferedStream; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class BufferedInputStreamTest { public static void main(String[] args) throws IOException { File file = new File("C:\\Users\\shenyuan\\Desktop\\test\\test1.txt"); FileInputStream fis = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(fis); byte[] b = new byte[(int) file.length()]; bis.read(b); System.out.println(new String(b)); bis.close(); } }
602
0.737542
0.73588
24
24.083334
21.908743
72
false
false
0
0
0
0
0
0
1.458333
false
false
6
6ac48c32d799b9e7fe78c14f159717a6c28bc76d
2,628,520,039,882
2f441b2ab0c2e149c8935b4ca9d29077513aafbf
/app/src/main/java/aca/com/hris/Database/SetVar.java
d60fdb844ac36ea10e11cd605eae7deecaed144e
[]
no_license
AcaInsurance/hris
https://github.com/AcaInsurance/hris
00ce002bb7e11bd112714c98b3cf1a321d8d53be
408d168662808554f5662546092b2917d1583023
refs/heads/master
2021-01-11T05:47:58.369000
2016-10-24T02:20:34
2016-10-24T02:20:47
71,743,363
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package aca.com.hris.Database; import com.raizlabs.android.dbflow.annotation.Column; import com.raizlabs.android.dbflow.annotation.PrimaryKey; import com.raizlabs.android.dbflow.annotation.Table; import com.raizlabs.android.dbflow.sql.language.Select; import com.raizlabs.android.dbflow.structure.BaseModel; /** * Created by Marsel on 17/11/2015. */ @Table(databaseName = DBMaster.NAME) public class SetVar extends BaseModel { @Column @PrimaryKey(autoincrement = true) public int _id; @Column public String ParameterCode, ParameterName, Value; }
UTF-8
Java
615
java
SetVar.java
Java
[ { "context": "oid.dbflow.structure.BaseModel;\n\n/**\n * Created by Marsel on 17/11/2015.\n */\n@Table(databaseName = DBMaster", "end": 334, "score": 0.9316977858543396, "start": 328, "tag": "USERNAME", "value": "Marsel" } ]
null
[]
package aca.com.hris.Database; import com.raizlabs.android.dbflow.annotation.Column; import com.raizlabs.android.dbflow.annotation.PrimaryKey; import com.raizlabs.android.dbflow.annotation.Table; import com.raizlabs.android.dbflow.sql.language.Select; import com.raizlabs.android.dbflow.structure.BaseModel; /** * Created by Marsel on 17/11/2015. */ @Table(databaseName = DBMaster.NAME) public class SetVar extends BaseModel { @Column @PrimaryKey(autoincrement = true) public int _id; @Column public String ParameterCode, ParameterName, Value; }
615
0.717073
0.704065
24
24.625
20.594927
57
false
false
0
0
0
0
0
0
0.416667
false
false
6
e44c4d8fb640361fac75c5b413408d7c615a34ae
19,593,640,870,911
f03ecea84afd14ab2793f9f413697f47ee0fab60
/app/src/main/java/com/sinapsissoft/rizoma/fragment/CropFragment.java
0fd5d9f9b7853e27be7e4fcc5f9c1644ed700fd3
[]
no_license
sinapsisSoft/Rizoma
https://github.com/sinapsisSoft/Rizoma
c999c1543d7004e31f16b44c62fd65fd9805b590
c5b6b46969aa8b8a753766d0ad2656d2605af08f
refs/heads/master
2020-04-04T03:44:45.457000
2018-12-03T17:34:58
2018-12-03T17:34:58
155,724,094
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sinapsissoft.rizoma.fragment; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.sinapsissoft.rizoma.R; import com.sinapsissoft.rizoma.dto.Crops; import com.sinapsissoft.rizoma.my_class.FirebaseReferences; import com.squareup.picasso.Picasso; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link CropFragment.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link CropFragment#newInstance} factory method to * create an instance of this fragment. */ public class CropFragment extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; private static final int MAX_WIDTH = 250; private static final int MAX_HEIGHT = 250; private OnFragmentInteractionListener mListener; public CropFragment() { // Required empty public constructor } public static CropFragment newInstance(String param1, String param2) { CropFragment fragment = new CropFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onActivityCreated(Bundle state){ super.onActivityCreated(state); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment // Please note the third parameter should be false, otherwise a java.lang.IllegalStateException maybe thrown. View retView = inflater.inflate(R.layout.fragment_view_crop, container, false); loadDataDetail(retView); return retView; } public void loadDataDetail(View view){ Crops crops=FirebaseReferences.CROP; ImageView imgViewCrop=view.findViewById(R.id.image_crop); TextView tViewCropName=view.findViewById(R.id.name_crops); TextView tViewCropNameScientific=view.findViewById(R.id.name_crops_scientific); TextView tVCropDescription=view.findViewById(R.id.description_product); Picasso.with(getContext()).load(crops.getCropImg()).fit().into(imgViewCrop); tViewCropName.setText(crops.getCropName()); tViewCropNameScientific.setText(crops.getCropNameScientific()); tVCropDescription.setText(crops.getCropDescription()); } // TODO: Rename method, update argument and hook method into UI event public void onButtonPressed(Uri uri) { if (mListener != null) { mListener.onFragmentInteraction(uri); } } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } public interface OnFragmentInteractionListener { // TODO: Update argument type and name void onFragmentInteraction(Uri uri); } }
UTF-8
Java
4,109
java
CropFragment.java
Java
[]
null
[]
package com.sinapsissoft.rizoma.fragment; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.sinapsissoft.rizoma.R; import com.sinapsissoft.rizoma.dto.Crops; import com.sinapsissoft.rizoma.my_class.FirebaseReferences; import com.squareup.picasso.Picasso; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link CropFragment.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link CropFragment#newInstance} factory method to * create an instance of this fragment. */ public class CropFragment extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; private static final int MAX_WIDTH = 250; private static final int MAX_HEIGHT = 250; private OnFragmentInteractionListener mListener; public CropFragment() { // Required empty public constructor } public static CropFragment newInstance(String param1, String param2) { CropFragment fragment = new CropFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onActivityCreated(Bundle state){ super.onActivityCreated(state); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment // Please note the third parameter should be false, otherwise a java.lang.IllegalStateException maybe thrown. View retView = inflater.inflate(R.layout.fragment_view_crop, container, false); loadDataDetail(retView); return retView; } public void loadDataDetail(View view){ Crops crops=FirebaseReferences.CROP; ImageView imgViewCrop=view.findViewById(R.id.image_crop); TextView tViewCropName=view.findViewById(R.id.name_crops); TextView tViewCropNameScientific=view.findViewById(R.id.name_crops_scientific); TextView tVCropDescription=view.findViewById(R.id.description_product); Picasso.with(getContext()).load(crops.getCropImg()).fit().into(imgViewCrop); tViewCropName.setText(crops.getCropName()); tViewCropNameScientific.setText(crops.getCropNameScientific()); tVCropDescription.setText(crops.getCropDescription()); } // TODO: Rename method, update argument and hook method into UI event public void onButtonPressed(Uri uri) { if (mListener != null) { mListener.onFragmentInteraction(uri); } } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } public interface OnFragmentInteractionListener { // TODO: Update argument type and name void onFragmentInteraction(Uri uri); } }
4,109
0.70017
0.694573
120
33.241665
26.152756
117
false
false
0
0
0
0
0
0
0.508333
false
false
6
8ec24f873646222b6616d4d0d26233e570dafe1a
12,859,132,143,048
ab2c88ccfdef270530b2299685655318339217a6
/Semana 4/Lab/pyLab04/src/e03/EjecutableV2.java
61374c601f7cadb539e5ada429d500a79710361e
[]
no_license
FranMZA/DiploIntroJava
https://github.com/FranMZA/DiploIntroJava
eab44c2042379292e57c5fd0ae494b89f1f32383
d0ca2a17f01dd90905294efbb24fcf7ee9a3f47b
refs/heads/master
2022-12-17T11:29:44.910000
2020-09-26T02:19:12
2020-09-26T02:19:12
290,071,146
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package e03; import java.util.Scanner; /** * * @author Franco J. Mulé <franjmule@gmail.com> */ public class EjecutableV2 { /** * @param args the command line arguments */ public static void main(String[] args) { /* Se necesita desarrollar un programa que permita cargar los tiempos obtenidos por los 20 participantes de una competencia de ciclismo. Con los tiempos registrados en minutos el programa debe:  Determinar el tiempo promedio de la carrera  Determinar la cantidad de abandonos (se considera abandono cuando el tiempo ingresado es 0)  Determinar y mostrar el tiempo del ganador  Mostrar el listado completo de tiempos ordenado en forma ascendente (Tener presente que los abandonos no debería figurar en el listado). */ Scanner entrada = new Scanner(System.in); // Variables int numParticipantes = 20; int[] tiemposEntrada = new int[numParticipantes]; boolean abandono[] = new boolean[numParticipantes]; int tiempos[]; int contAbandonos = 0; float promedio = 0; // Entrada for (int i = 0; i < tiemposEntrada.length; i++) { do { System.out.println("Introduzca el tiempo del participante " + (i + 1) + ":"); tiemposEntrada[i] = entrada.nextInt(); if (tiemposEntrada[i] < 0) { System.out.println("Error de carga!"); } } while (tiemposEntrada[i] < 0); if (tiemposEntrada[i] != 0) { abandono[i] = false; promedio += (float) tiemposEntrada[i]; } else { abandono[i] = true; contAbandonos++; } } if (contAbandonos != numParticipantes) { promedio /= (float) (numParticipantes - contAbandonos); } else { promedio = 0; } tiempos = new int[(numParticipantes - contAbandonos)]; for (int i = 0, j = i; i < tiemposEntrada.length && j < tiempos.length; i++) { if (abandono[i] == false) { tiempos[j] = tiemposEntrada[i]; j++; } } // Ordenando lote int aux; for (int i = 0; i < tiempos.length - 1; i++) { for (int j = i + 1; j < tiempos.length; j++) { if (tiempos[i] > tiempos[j]) { aux = tiempos[i]; tiempos[i] = tiempos[j]; tiempos[j] = aux; } } } // Salida System.out.println("--------------------"); System.out.println("El promedio de la carrera es de " + String.format("%.2f", promedio) + " minutos."); if (contAbandonos == 0) { System.out.println("No hubo abandonos."); } else { System.out.println("Hubieron " + contAbandonos + " abandonos."); } if (tiempos.length > 0) { System.out.println("El tiempo del ganador fue de " + tiempos[0] + " minutos."); } else { System.out.println("No hubo ganador."); } System.out.println("--------------------"); System.out.println("Lista de tiempos:"); System.out.print("["); if (tiempos.length > 0) { System.out.print(tiempos[0]); for (int i = 1; i < tiempos.length; i++) { System.out.print(", "); System.out.print(tiempos[i]); } } System.out.println("]"); } }
UTF-8
Java
3,894
java
EjecutableV2.java
Java
[ { "context": "e03;\n\nimport java.util.Scanner;\n\n/**\n *\n * @author Franco J. Mulé <franjmule@gmail.com>\n */\npublic class Ejecutable", "end": 258, "score": 0.9998540282249451, "start": 244, "tag": "NAME", "value": "Franco J. Mulé" }, { "context": ".util.Scanner;\n\n/**\n *\n * @author Franco J. Mulé <franjmule@gmail.com>\n */\npublic class EjecutableV2 {\n\n /**\n * ", "end": 279, "score": 0.9999316334724426, "start": 260, "tag": "EMAIL", "value": "franjmule@gmail.com" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package e03; import java.util.Scanner; /** * * @author <NAME> <<EMAIL>> */ public class EjecutableV2 { /** * @param args the command line arguments */ public static void main(String[] args) { /* Se necesita desarrollar un programa que permita cargar los tiempos obtenidos por los 20 participantes de una competencia de ciclismo. Con los tiempos registrados en minutos el programa debe:  Determinar el tiempo promedio de la carrera  Determinar la cantidad de abandonos (se considera abandono cuando el tiempo ingresado es 0)  Determinar y mostrar el tiempo del ganador  Mostrar el listado completo de tiempos ordenado en forma ascendente (Tener presente que los abandonos no debería figurar en el listado). */ Scanner entrada = new Scanner(System.in); // Variables int numParticipantes = 20; int[] tiemposEntrada = new int[numParticipantes]; boolean abandono[] = new boolean[numParticipantes]; int tiempos[]; int contAbandonos = 0; float promedio = 0; // Entrada for (int i = 0; i < tiemposEntrada.length; i++) { do { System.out.println("Introduzca el tiempo del participante " + (i + 1) + ":"); tiemposEntrada[i] = entrada.nextInt(); if (tiemposEntrada[i] < 0) { System.out.println("Error de carga!"); } } while (tiemposEntrada[i] < 0); if (tiemposEntrada[i] != 0) { abandono[i] = false; promedio += (float) tiemposEntrada[i]; } else { abandono[i] = true; contAbandonos++; } } if (contAbandonos != numParticipantes) { promedio /= (float) (numParticipantes - contAbandonos); } else { promedio = 0; } tiempos = new int[(numParticipantes - contAbandonos)]; for (int i = 0, j = i; i < tiemposEntrada.length && j < tiempos.length; i++) { if (abandono[i] == false) { tiempos[j] = tiemposEntrada[i]; j++; } } // Ordenando lote int aux; for (int i = 0; i < tiempos.length - 1; i++) { for (int j = i + 1; j < tiempos.length; j++) { if (tiempos[i] > tiempos[j]) { aux = tiempos[i]; tiempos[i] = tiempos[j]; tiempos[j] = aux; } } } // Salida System.out.println("--------------------"); System.out.println("El promedio de la carrera es de " + String.format("%.2f", promedio) + " minutos."); if (contAbandonos == 0) { System.out.println("No hubo abandonos."); } else { System.out.println("Hubieron " + contAbandonos + " abandonos."); } if (tiempos.length > 0) { System.out.println("El tiempo del ganador fue de " + tiempos[0] + " minutos."); } else { System.out.println("No hubo ganador."); } System.out.println("--------------------"); System.out.println("Lista de tiempos:"); System.out.print("["); if (tiempos.length > 0) { System.out.print(tiempos[0]); for (int i = 1; i < tiempos.length; i++) { System.out.print(", "); System.out.print(tiempos[i]); } } System.out.println("]"); } }
3,873
0.507209
0.500257
116
32.482758
25.499657
111
false
false
0
0
0
0
0
0
0.474138
false
false
6
aed06a6afbd222659835ff64ad9633e18cc3cad6
29,927,332,132,043
d465ae58a2a3b195c70fb67d0d35f90a291eda72
/app/src/main/java/com/liurui/mydemo/widget/web/CustomChromeClient.java
fd0af67f25488414fef08adf88da8adbd18a55cd
[]
no_license
RichardLiuRui/MyDemo
https://github.com/RichardLiuRui/MyDemo
47beb70c53e47d07e711d7282bb78fc9b5de75a8
c68b39fb509fe4deb5b154d73140a2144d94772d
refs/heads/master
2020-03-11T23:20:06.183000
2019-02-22T09:43:06
2019-02-22T09:43:09
130,318,708
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.liurui.mydemo.widget.web; import android.webkit.JsResult; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.widget.ProgressBar; /** * WebChromeClient主要辅助WebView处理Javascript的对话框、网站图标、网站title、加载进度等 * Created by LiuRui on 2018/12/13 */ public class CustomChromeClient extends WebChromeClient { private ProgressBar progressBar; private OnChromClientListener onChromClientListener; public CustomChromeClient(ProgressBar progressBar, OnChromClientListener onChromClientListener) { this.onChromClientListener = onChromClientListener; this.progressBar = progressBar; } //不支持js的alert弹窗,需要自己监听然后通过dialog弹窗 @Override public boolean onJsAlert(WebView webView, String url, String message, JsResult result) { // AlertDialog.Builder localBuilder = new AlertDialog.Builder(webView.getContext()); // localBuilder.setMessage(message).setPositiveButton("确定",null); // localBuilder.setCancelable(false); // localBuilder.create().show(); //注意: //必须要这一句代码:result.confirm()表示: //处理结果为确定状态同时唤醒WebCore线程 //否则不能继续点击按钮 result.confirm(); return true; } //获取网页标题 @Override public void onReceivedTitle(WebView view, String title) { super.onReceivedTitle(view, title); if (onChromClientListener != null){ onChromClientListener.onUpdateTitle(title); } } //加载进度回调 @Override public void onProgressChanged(WebView view, int newProgress) { progressBar.setProgress(newProgress); } public interface OnChromClientListener{ void onUpdateTitle(String title); } }
UTF-8
Java
1,885
java
CustomChromeClient.java
Java
[ { "context": "w处理Javascript的对话框、网站图标、网站title、加载进度等\n * Created by LiuRui on 2018/12/13\n */\npublic class CustomChromeClient", "end": 266, "score": 0.960792601108551, "start": 260, "tag": "USERNAME", "value": "LiuRui" } ]
null
[]
package com.liurui.mydemo.widget.web; import android.webkit.JsResult; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.widget.ProgressBar; /** * WebChromeClient主要辅助WebView处理Javascript的对话框、网站图标、网站title、加载进度等 * Created by LiuRui on 2018/12/13 */ public class CustomChromeClient extends WebChromeClient { private ProgressBar progressBar; private OnChromClientListener onChromClientListener; public CustomChromeClient(ProgressBar progressBar, OnChromClientListener onChromClientListener) { this.onChromClientListener = onChromClientListener; this.progressBar = progressBar; } //不支持js的alert弹窗,需要自己监听然后通过dialog弹窗 @Override public boolean onJsAlert(WebView webView, String url, String message, JsResult result) { // AlertDialog.Builder localBuilder = new AlertDialog.Builder(webView.getContext()); // localBuilder.setMessage(message).setPositiveButton("确定",null); // localBuilder.setCancelable(false); // localBuilder.create().show(); //注意: //必须要这一句代码:result.confirm()表示: //处理结果为确定状态同时唤醒WebCore线程 //否则不能继续点击按钮 result.confirm(); return true; } //获取网页标题 @Override public void onReceivedTitle(WebView view, String title) { super.onReceivedTitle(view, title); if (onChromClientListener != null){ onChromClientListener.onUpdateTitle(title); } } //加载进度回调 @Override public void onProgressChanged(WebView view, int newProgress) { progressBar.setProgress(newProgress); } public interface OnChromClientListener{ void onUpdateTitle(String title); } }
1,885
0.708309
0.703595
56
29.303572
26.099342
101
false
false
0
0
0
0
0
0
0.482143
false
false
6
2f998ca2724564d1adaf4570732513e0f491f3bc
3,702,261,861,226
1931c95e6308b8cb9b13c4077db16e95cb7c041b
/module_class/src/main/java/com/mingpinmall/classz/ui/vm/ClassificationItemHolder.java
72fce67bdeb4ff586f11800d7ec837693891b5e9
[]
no_license
965310001/MPS
https://github.com/965310001/MPS
73f766ed29b4d0db080723607f432ef50f438d95
406a261b3bf7a4b3e97c404a55559cd769f9eb5f
refs/heads/master
2020-04-30T21:04:05.171000
2019-06-21T10:28:14
2019-06-21T10:28:14
177,085,675
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
//package com.mingpinmall.classz.ui.vm; // //import android.content.Context; //import android.databinding.BindingAdapter; //import android.databinding.DataBindingUtil; //import android.support.annotation.NonNull; //import android.view.LayoutInflater; //import android.view.View; //import android.widget.ImageView; // //import com.goldze.common.dmvvm.utils.ImageUtils; //import com.mingpinmall.classz.R; //import com.mingpinmall.classz.databinding.ClassifyItemOfListBinding; //import com.mingpinmall.classz.ui.vm.bean.ClassificationBean; //import com.trecyclerview.holder.AbsHolder; //import com.trecyclerview.holder.AbsItemHolder; // //public class ClassificationItemHolder extends AbsItemHolder<ClassificationBean.DatasBean.ClassListBean, // ClassificationItemHolder.ViewHolder> { // // public ClassificationItemHolder(Context context) { // super(context); // } // // @Override // public int getLayoutResId() { // return R.layout.classify_item_of_list; // } // // ClassifyItemOfListBinding binding; // // @Override // public ViewHolder createViewHolder(View view) { // binding= DataBindingUtil.bind(view); // return new ViewHolder(binding.getRoot()); // } // // @Override // protected void onBindViewHolder(@NonNull ViewHolder holder, @NonNull ClassificationBean.DatasBean.ClassListBean dataBean) { // binding = DataBindingUtil.getBinding(holder.itemView); // binding.setData(dataBean); // binding.executePendingBindings(); // } // // @Override // protected long getItemId(@NonNull ClassificationBean.DatasBean.ClassListBean data) { // return Long.parseLong(data.getGc_id()); // } // // static class ViewHolder extends AbsHolder { // private ViewHolder(View itemView) { // super(itemView); // } // } //}
UTF-8
Java
1,844
java
ClassificationItemHolder.java
Java
[]
null
[]
//package com.mingpinmall.classz.ui.vm; // //import android.content.Context; //import android.databinding.BindingAdapter; //import android.databinding.DataBindingUtil; //import android.support.annotation.NonNull; //import android.view.LayoutInflater; //import android.view.View; //import android.widget.ImageView; // //import com.goldze.common.dmvvm.utils.ImageUtils; //import com.mingpinmall.classz.R; //import com.mingpinmall.classz.databinding.ClassifyItemOfListBinding; //import com.mingpinmall.classz.ui.vm.bean.ClassificationBean; //import com.trecyclerview.holder.AbsHolder; //import com.trecyclerview.holder.AbsItemHolder; // //public class ClassificationItemHolder extends AbsItemHolder<ClassificationBean.DatasBean.ClassListBean, // ClassificationItemHolder.ViewHolder> { // // public ClassificationItemHolder(Context context) { // super(context); // } // // @Override // public int getLayoutResId() { // return R.layout.classify_item_of_list; // } // // ClassifyItemOfListBinding binding; // // @Override // public ViewHolder createViewHolder(View view) { // binding= DataBindingUtil.bind(view); // return new ViewHolder(binding.getRoot()); // } // // @Override // protected void onBindViewHolder(@NonNull ViewHolder holder, @NonNull ClassificationBean.DatasBean.ClassListBean dataBean) { // binding = DataBindingUtil.getBinding(holder.itemView); // binding.setData(dataBean); // binding.executePendingBindings(); // } // // @Override // protected long getItemId(@NonNull ClassificationBean.DatasBean.ClassListBean data) { // return Long.parseLong(data.getGc_id()); // } // // static class ViewHolder extends AbsHolder { // private ViewHolder(View itemView) { // super(itemView); // } // } //}
1,844
0.707158
0.707158
55
32.527271
27.312239
129
false
false
0
0
0
0
0
0
0.472727
false
false
6
df6929665c437ec0a2798ad39ac63748f08a3019
6,408,091,275,884
fa39070496ed0f2a62faa54fb1fe462548f08b01
/src/main/java/com/github/xibalba/zhorse/commands/CommandRez.java
4eb06ffe5a1f54cf3762bc8bff4253611c492724
[]
no_license
EvroxFR/ZHorse
https://github.com/EvroxFR/ZHorse
04390527bc4d6a7536141f41d176696e297d01b5
27209727ce6a6e19623fe45dd09d16aa3bdcf644
refs/heads/master
2020-03-19T05:35:14.004000
2018-04-23T13:29:43
2018-04-23T13:29:43
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.github.xibalba.zhorse.commands; import java.util.UUID; import org.bukkit.Location; import org.bukkit.attribute.Attribute; import org.bukkit.block.Block; import org.bukkit.command.CommandSender; import com.github.xibalba.zhorse.ZHorse; import com.github.xibalba.zhorse.database.HorseInventoryRecord; import com.github.xibalba.zhorse.database.HorseStatsRecord; import com.github.xibalba.zhorse.enums.LocaleEnum; import com.github.xibalba.zhorse.utils.MessageConfig; public class CommandRez extends AbstractCommand { public CommandRez(ZHorse zh, CommandSender s, String[] a) { super(zh, s, a); if (isPlayer() && zh.getEM().canAffordCommand(p, command) && parseArguments() && hasPermission() && isCooldownElapsed() && isWorldEnabled()) { if (!idMode) { if (!targetMode || isRegistered(targetUUID)) { execute(); } } else { sendCommandUsage(); } } } private void execute() { if (ownsDeadHorse(targetUUID) && !hasReachedClaimsLimit(true)) { UUID horseUUID = zh.getDM().getLatestHorseDeathUUID(targetUUID); int horseID = zh.getDM().getNextHorseID(targetUUID); boolean success = true; HorseInventoryRecord inventoryRecord = zh.getDM().getHorseInventoryRecord(horseUUID); HorseStatsRecord statsRecord = zh.getDM().getHorseStatsRecord(horseUUID); success &= zh.getDM().removeHorseDeath(horseUUID); success &= zh.getDM().updateHorseID(horseUUID, horseID); success &= craftHorseName(true, horseUUID); if (success) { Location destination = p.getLocation(); if (p.isFlying()) { Block block = destination.getWorld().getHighestBlockAt(destination); destination = new Location(destination.getWorld(), block.getX(), block.getY(), block.getZ()); } horse = zh.getHM().spawnHorse(destination, inventoryRecord, statsRecord, horseUUID, true); if (horse != null) { applyHorseName(targetUUID); zh.getDM().updateHorseName(horse.getUniqueId(), horseName); horse.setHealth(horse.getAttribute(Attribute.GENERIC_MAX_HEALTH).getBaseValue()); zh.getMM().sendMessage(s, new MessageConfig(LocaleEnum.HORSE_RESURRECTED) {{ setHorseName(horseName); }}); zh.getCmdM().updateCommandHistory(s, command); zh.getEM().payCommand(p, command); } } } } }
UTF-8
Java
2,325
java
CommandRez.java
Java
[ { "context": "package com.github.xibalba.zhorse.commands;\r\n\r\nimport java.util.UUID;\r\n\r\nimp", "end": 26, "score": 0.8694736957550049, "start": 19, "tag": "USERNAME", "value": "xibalba" }, { "context": "ukkit.command.CommandSender;\r\n\r\nimport com.github.xibalba.zhorse.ZHorse;\r\nimport com.github.xibalba.zhorse.", "end": 243, "score": 0.9561415910720825, "start": 236, "tag": "USERNAME", "value": "xibalba" }, { "context": ".github.xibalba.zhorse.ZHorse;\r\nimport com.github.xibalba.zhorse.database.HorseInventoryRecord;\r\nimport com", "end": 285, "score": 0.8523534536361694, "start": 278, "tag": "USERNAME", "value": "xibalba" }, { "context": "database.HorseInventoryRecord;\r\nimport com.github.xibalba.zhorse.database.HorseStatsRecord;\r\nimport com.git", "end": 350, "score": 0.9014186859130859, "start": 343, "tag": "USERNAME", "value": "xibalba" }, { "context": "se.database.HorseStatsRecord;\r\nimport com.github.xibalba.zhorse.enums.LocaleEnum;\r\nimport com.github.xibal", "end": 411, "score": 0.9326704144477844, "start": 405, "tag": "USERNAME", "value": "ibalba" }, { "context": "alba.zhorse.enums.LocaleEnum;\r\nimport com.github.xibalba.zhorse.utils.MessageConfig;\r\n\r\npublic class Comma", "end": 463, "score": 0.8847926259040833, "start": 457, "tag": "USERNAME", "value": "ibalba" } ]
null
[]
package com.github.xibalba.zhorse.commands; import java.util.UUID; import org.bukkit.Location; import org.bukkit.attribute.Attribute; import org.bukkit.block.Block; import org.bukkit.command.CommandSender; import com.github.xibalba.zhorse.ZHorse; import com.github.xibalba.zhorse.database.HorseInventoryRecord; import com.github.xibalba.zhorse.database.HorseStatsRecord; import com.github.xibalba.zhorse.enums.LocaleEnum; import com.github.xibalba.zhorse.utils.MessageConfig; public class CommandRez extends AbstractCommand { public CommandRez(ZHorse zh, CommandSender s, String[] a) { super(zh, s, a); if (isPlayer() && zh.getEM().canAffordCommand(p, command) && parseArguments() && hasPermission() && isCooldownElapsed() && isWorldEnabled()) { if (!idMode) { if (!targetMode || isRegistered(targetUUID)) { execute(); } } else { sendCommandUsage(); } } } private void execute() { if (ownsDeadHorse(targetUUID) && !hasReachedClaimsLimit(true)) { UUID horseUUID = zh.getDM().getLatestHorseDeathUUID(targetUUID); int horseID = zh.getDM().getNextHorseID(targetUUID); boolean success = true; HorseInventoryRecord inventoryRecord = zh.getDM().getHorseInventoryRecord(horseUUID); HorseStatsRecord statsRecord = zh.getDM().getHorseStatsRecord(horseUUID); success &= zh.getDM().removeHorseDeath(horseUUID); success &= zh.getDM().updateHorseID(horseUUID, horseID); success &= craftHorseName(true, horseUUID); if (success) { Location destination = p.getLocation(); if (p.isFlying()) { Block block = destination.getWorld().getHighestBlockAt(destination); destination = new Location(destination.getWorld(), block.getX(), block.getY(), block.getZ()); } horse = zh.getHM().spawnHorse(destination, inventoryRecord, statsRecord, horseUUID, true); if (horse != null) { applyHorseName(targetUUID); zh.getDM().updateHorseName(horse.getUniqueId(), horseName); horse.setHealth(horse.getAttribute(Attribute.GENERIC_MAX_HEALTH).getBaseValue()); zh.getMM().sendMessage(s, new MessageConfig(LocaleEnum.HORSE_RESURRECTED) {{ setHorseName(horseName); }}); zh.getCmdM().updateCommandHistory(s, command); zh.getEM().payCommand(p, command); } } } } }
2,325
0.705806
0.705806
61
36.147541
32.280449
144
false
false
0
0
0
0
0
0
3.131148
false
false
6
308d8a36cb23466b4bfeb2ebea63e4634e45c0db
14,482,629,737,469
7834b193fb9a82dc4739cd62f0536172181b1dd2
/spring-test/leecode/src/main/java/org/leecode/result/impl/Result_463.java
5b19b1d9765cbe7204b5c286d9197f820d8df3b0
[]
no_license
CHForDream/jm-spring-boot
https://github.com/CHForDream/jm-spring-boot
995afbefe9a6921caac81cea358d6d80310d9f10
231f467b88645907ec9d3cc99a30b0efdbae1e09
refs/heads/master
2023-01-12T14:33:35.752000
2020-11-06T07:16:29
2020-11-06T07:16:29
278,351,524
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.leecode.result.impl; import org.leecode.result.IResult; import org.springframework.stereotype.Service; import com.alibaba.fastjson.JSON; @Service public class Result_463 implements IResult { /** * 给定两个大小为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。 * 请你找出这两个正序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。 * 你可以假设 nums1 和 nums2 不会同时为空。 * * 示例 1: * nums1 = [1, 3] * nums2 = [2] * 则中位数是 2.0 * 示例 2: * nums1 = [1, 2] * nums2 = [3, 4] * 则中位数是 (2 + 3)/2 = 2.5 */ @Override public String process() { int[] nums1 = { 1, 3 }; int[] nums2 = { 2, 4 }; return JSON.toJSONString(findMedianSortedArrays(nums1, nums2)); } @Override public String gerneral() { // TODO Auto-generated method stub return null; } public double findMedianSortedArrays(int[] nums1, int[] nums2) { int nSize1 = nums1.length; int nSize2 = nums2.length; boolean flag = (nSize1 + nSize2) % 2 == 1; int pos0 = flag ? (nSize1 + nSize2) / 2 + 1 : (nSize1 + nSize2) / 2; int pos1 = (nSize1 + nSize2) / 2 + 1; int n1 = 0; int n1Start = 0; int n2Start = 0; int count = 0; while (true) { int tmp = 0; if (n1Start == nSize1) { tmp = nums2[n2Start]; n2Start++; } else if (n2Start == nSize2) { tmp = nums1[n1Start]; n1Start++; } else if (nums1[n1Start] <= nums2[n2Start]) { tmp = nums1[n1Start]; n1Start++; } else { tmp = nums2[n2Start]; n2Start++; } count++; if (flag) { if (count == pos0) { return tmp; } } else { if (count == pos0) { n1 = tmp; } if (count == pos1) { return (n1 + tmp) / 2.0; } } } } }
UTF-8
Java
1,787
java
Result_463.java
Java
[]
null
[]
package org.leecode.result.impl; import org.leecode.result.IResult; import org.springframework.stereotype.Service; import com.alibaba.fastjson.JSON; @Service public class Result_463 implements IResult { /** * 给定两个大小为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。 * 请你找出这两个正序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。 * 你可以假设 nums1 和 nums2 不会同时为空。 * * 示例 1: * nums1 = [1, 3] * nums2 = [2] * 则中位数是 2.0 * 示例 2: * nums1 = [1, 2] * nums2 = [3, 4] * 则中位数是 (2 + 3)/2 = 2.5 */ @Override public String process() { int[] nums1 = { 1, 3 }; int[] nums2 = { 2, 4 }; return JSON.toJSONString(findMedianSortedArrays(nums1, nums2)); } @Override public String gerneral() { // TODO Auto-generated method stub return null; } public double findMedianSortedArrays(int[] nums1, int[] nums2) { int nSize1 = nums1.length; int nSize2 = nums2.length; boolean flag = (nSize1 + nSize2) % 2 == 1; int pos0 = flag ? (nSize1 + nSize2) / 2 + 1 : (nSize1 + nSize2) / 2; int pos1 = (nSize1 + nSize2) / 2 + 1; int n1 = 0; int n1Start = 0; int n2Start = 0; int count = 0; while (true) { int tmp = 0; if (n1Start == nSize1) { tmp = nums2[n2Start]; n2Start++; } else if (n2Start == nSize2) { tmp = nums1[n1Start]; n1Start++; } else if (nums1[n1Start] <= nums2[n2Start]) { tmp = nums1[n1Start]; n1Start++; } else { tmp = nums2[n2Start]; n2Start++; } count++; if (flag) { if (count == pos0) { return tmp; } } else { if (count == pos0) { n1 = tmp; } if (count == pos1) { return (n1 + tmp) / 2.0; } } } } }
1,787
0.572044
0.514778
82
18.804878
16.133921
70
false
false
0
0
0
0
0
0
2.341463
false
false
6
d72c1314ed401e60305a017356bf2f476b744a30
17,660,905,538,753
9008c0d68f2ced89970c57f201624f6cd014e30a
/plugins/ru.runa.gpd/src/ru/runa/gpd/property/StartImagePropertyDescriptor.java
a14ca1c817c5a4414f5febfdd427a317aa83517c
[]
no_license
MaximCheb/runawfe-free-devstudio
https://github.com/MaximCheb/runawfe-free-devstudio
fa9cabc442280123b5eb5469416054b056838bb2
7a9546e4a5a5e8c2573e26d62af1248b9cc6238f
refs/heads/master
2023-05-31T10:26:07.838000
2021-06-14T21:36:32
2021-06-14T21:36:32
366,336,621
0
0
null
true
2021-06-05T21:51:17
2021-05-11T10:04:50
2021-05-11T10:04:51
2021-06-05T21:51:17
57,456
0
0
0
null
false
false
package ru.runa.gpd.property; import org.eclipse.core.resources.IFile; import org.eclipse.jface.viewers.CellEditor; import org.eclipse.jface.viewers.DialogCellEditor; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.ui.views.properties.PropertyDescriptor; import ru.runa.gpd.PluginLogger; import ru.runa.gpd.lang.par.ParContentProvider; import ru.runa.gpd.util.IOUtils; public class StartImagePropertyDescriptor extends PropertyDescriptor { public StartImagePropertyDescriptor(Object id, String label) { super(id, label); } @Override public CellEditor createPropertyEditor(Composite parent) { return new ImageCellEditor(parent); } private IFile getImageFile() { return IOUtils.getFile(ParContentProvider.PROCESS_INSTANCE_START_IMAGE_FILE_NAME); } class ImageCellEditor extends DialogCellEditor { private Image image; private Label colorLabel; public ImageCellEditor(Composite parent) { super(parent); } @Override protected Object openDialogBox(Control cellEditorWindow) { FileDialog dialog = new FileDialog(cellEditorWindow.getShell(), SWT.OPEN); dialog.setFilterExtensions(new String[] { "*.png" }); String path = dialog.open(); if (path == null) { return null; } IOUtils.copyFile(path, getImageFile()); return getImageFile(); } @Override protected Control createContents(Composite cell) { Color bg = cell.getBackground(); colorLabel = new Label(cell, SWT.LEFT); colorLabel.setBackground(bg); return colorLabel; } @Override protected void updateContents(Object value) { try { IFile imageFile = getImageFile(); if (imageFile == null || !imageFile.exists()) { return; } ImageData data = new ImageData(imageFile.getContents()).scaledTo(16, 16); image = new Image(colorLabel.getDisplay(), data, data.getTransparencyMask()); colorLabel.setImage(image); } catch (Exception e) { PluginLogger.logErrorWithoutDialog("start image", e); } } @Override public void dispose() { if (image != null) { image.dispose(); image = null; } super.dispose(); } } }
UTF-8
Java
2,819
java
StartImagePropertyDescriptor.java
Java
[]
null
[]
package ru.runa.gpd.property; import org.eclipse.core.resources.IFile; import org.eclipse.jface.viewers.CellEditor; import org.eclipse.jface.viewers.DialogCellEditor; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.ui.views.properties.PropertyDescriptor; import ru.runa.gpd.PluginLogger; import ru.runa.gpd.lang.par.ParContentProvider; import ru.runa.gpd.util.IOUtils; public class StartImagePropertyDescriptor extends PropertyDescriptor { public StartImagePropertyDescriptor(Object id, String label) { super(id, label); } @Override public CellEditor createPropertyEditor(Composite parent) { return new ImageCellEditor(parent); } private IFile getImageFile() { return IOUtils.getFile(ParContentProvider.PROCESS_INSTANCE_START_IMAGE_FILE_NAME); } class ImageCellEditor extends DialogCellEditor { private Image image; private Label colorLabel; public ImageCellEditor(Composite parent) { super(parent); } @Override protected Object openDialogBox(Control cellEditorWindow) { FileDialog dialog = new FileDialog(cellEditorWindow.getShell(), SWT.OPEN); dialog.setFilterExtensions(new String[] { "*.png" }); String path = dialog.open(); if (path == null) { return null; } IOUtils.copyFile(path, getImageFile()); return getImageFile(); } @Override protected Control createContents(Composite cell) { Color bg = cell.getBackground(); colorLabel = new Label(cell, SWT.LEFT); colorLabel.setBackground(bg); return colorLabel; } @Override protected void updateContents(Object value) { try { IFile imageFile = getImageFile(); if (imageFile == null || !imageFile.exists()) { return; } ImageData data = new ImageData(imageFile.getContents()).scaledTo(16, 16); image = new Image(colorLabel.getDisplay(), data, data.getTransparencyMask()); colorLabel.setImage(image); } catch (Exception e) { PluginLogger.logErrorWithoutDialog("start image", e); } } @Override public void dispose() { if (image != null) { image.dispose(); image = null; } super.dispose(); } } }
2,819
0.621497
0.620078
86
31.77907
23.46913
93
false
false
0
0
0
0
0
0
0.604651
false
false
6
6f9be21e958c4fe3dc1365bc8d55bf5c8c32f1d0
28,896,539,984,423
f6701e05530e88982f17da25f49d9920ee2caaa9
/src/main/java/ws/TemaUris.java
d5783de8dadfdad1bc5e93be0767d0979535af59
[]
no_license
franciscomaestre/JEE_ECP
https://github.com/franciscomaestre/JEE_ECP
7b2c775c361fb77b90724a44ea0d8ffdd3a38f3e
6905f5786e9be504a42568151830f7b20146d8c2
refs/heads/master
2015-08-21T05:36:56.358000
2015-04-03T21:54:06
2015-04-03T21:54:06
31,808,826
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package ws; public interface TemaUris { public String PATH_TEMAS = "/temas"; public String PATH_ID_PARAM = "{id}"; }
UTF-8
Java
137
java
TemaUris.java
Java
[]
null
[]
package ws; public interface TemaUris { public String PATH_TEMAS = "/temas"; public String PATH_ID_PARAM = "{id}"; }
137
0.605839
0.605839
9
13.444445
16.760477
41
false
false
0
0
0
0
0
0
0.333333
false
false
6
6bffdd5a06d3adba86032731e49340c36b489d63
9,955,734,217,917
ed19bc01866d227a5d7f3b5d7326842af90cd63d
/src/cs3500/animator/view/MyPanel.java
ede6b8bcc2186e2109d5f93ca29125b5b53b36bc
[]
no_license
GCranton/HW5-ExCellence
https://github.com/GCranton/HW5-ExCellence
2bd9baa5c2dfd0efb1a272bffa216ddcdba08996
ab47225619b3c2e4762a0b6334577f7935fb2266
refs/heads/master
2022-04-12T10:05:27.968000
2020-04-07T05:06:23
2020-04-07T05:06:23
246,434,087
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cs3500.animator.view; import cs3500.animator.model.Animator; import cs3500.animator.shapes.IShape; import javax.swing.JPanel; import java.awt.Graphics; import java.awt.Color; /** * Specialized JPanel class used to animate Animators in VideoAnimatorView. * currTick keeps track of the tick that is being animated. */ @SuppressWarnings("serial") public class MyPanel extends JPanel { Animator model; int currTick = 0; /** * Constructor for MyPanel, takes in a model so it can run paintComponent. * @param model is the Animator this panel animates */ public MyPanel(Animator model) { this.model = model; } /** * This code checks to see if a shape exists at the current tick. * @param g is the Graphics that needs to be there */ @Override public void paintComponent(Graphics g) { super.paintComponent(g); for (IShape shape : model.getShapes()) { int firstTickOfShape = model.getInstructions(shape).get(0).getDescription()[0]; if (currTick >= firstTickOfShape) { int[] currDescription = model.getDescriptionAt(shape, currTick); g.setColor(new Color(currDescription[5], currDescription[6], currDescription[7])); if (shape.getType().equals("Rectangle")) { g.fillRect(currDescription[1], currDescription[2], currDescription[3], currDescription[4]); } else if (shape.getType().equals("Ellipse")) { g.fillOval(currDescription[1] - model.getRight(), currDescription[2] - model.getTop(), currDescription[3], currDescription[4]); } } } } }
UTF-8
Java
1,698
java
MyPanel.java
Java
[]
null
[]
package cs3500.animator.view; import cs3500.animator.model.Animator; import cs3500.animator.shapes.IShape; import javax.swing.JPanel; import java.awt.Graphics; import java.awt.Color; /** * Specialized JPanel class used to animate Animators in VideoAnimatorView. * currTick keeps track of the tick that is being animated. */ @SuppressWarnings("serial") public class MyPanel extends JPanel { Animator model; int currTick = 0; /** * Constructor for MyPanel, takes in a model so it can run paintComponent. * @param model is the Animator this panel animates */ public MyPanel(Animator model) { this.model = model; } /** * This code checks to see if a shape exists at the current tick. * @param g is the Graphics that needs to be there */ @Override public void paintComponent(Graphics g) { super.paintComponent(g); for (IShape shape : model.getShapes()) { int firstTickOfShape = model.getInstructions(shape).get(0).getDescription()[0]; if (currTick >= firstTickOfShape) { int[] currDescription = model.getDescriptionAt(shape, currTick); g.setColor(new Color(currDescription[5], currDescription[6], currDescription[7])); if (shape.getType().equals("Rectangle")) { g.fillRect(currDescription[1], currDescription[2], currDescription[3], currDescription[4]); } else if (shape.getType().equals("Ellipse")) { g.fillOval(currDescription[1] - model.getRight(), currDescription[2] - model.getTop(), currDescription[3], currDescription[4]); } } } } }
1,698
0.640165
0.624853
57
27.789474
26.470598
90
false
false
0
0
0
0
0
0
0.438596
false
false
6
f8582cee5d2dca3a80da06a7cddd317bd1d82562
9,852,654,980,912
3c3dfa68b464610dc560b953a935d363396cc197
/Code/Day17/src/cn/yykjc/self/Map_Demo1.java
d073e680283993380f4d301c05fcebc2f87d8d3a
[]
no_license
zhuangsuzheng/JavaStrudy
https://github.com/zhuangsuzheng/JavaStrudy
04fa9ac68de3ef0d1982e047d4b509a6cac8ea9d
a436d64cfa4d35ed24b0ce2b893d1df9d98ee307
refs/heads/master
2020-06-03T01:48:47.197000
2019-06-25T13:47:40
2019-06-25T13:47:40
191,381,016
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.yykjc.self; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; public class Map_Demo1 { public static void main(String[] args) { // TODO Auto-generated method stub //demo1(); //demo2(); //demo3(); // demo4(); } public static void demo4() { Map<String, Integer> map = new HashMap<>(); Integer aInteger = map.put("庄宿正", 12); Integer bInteger = map.put("张三", 13); Integer cInteger = map.put("李四", 14); Set<Map.Entry<String, Integer>> entries = map.entrySet(); Iterator<Map.Entry<String, Integer>> iterator = entries.iterator(); while(iterator.hasNext()) { Map.Entry<String,Integer> entry = iterator.next(); System.out.println(entry.getKey() + "===" + entry.getValue()); //System.out.println(iterator.next()); } for (Map.Entry<String, Integer> entry : map.entrySet()) { System.out.println(entry.getKey() + "----" + entry.getValue()); } } public static void demo3() { Map<String, Integer> map = new HashMap<>(); Integer aInteger = map.put("庄宿正", 12); Integer bInteger = map.put("张三", 13); Integer cInteger = map.put("李四", 14); System.out.println(map.size()); map.clear(); // 数据没有了,集合依然在 System.out.println(map.size()); } public static void demo2() { Map<String, Integer> map = new HashMap<>(); Integer aInteger = map.put("庄宿正", 12); Integer bInteger = map.put("张三", 13); Integer cInteger = map.put("李四", 14); Integer value = map.remove("李四"); System.out.println(map.containsKey("张三")); // 是否包含张三这个键 System.out.println(map.containsValue(12)); // 是否包含12这个值 System.out.println(value); System.out.println(map); } public static void demo1() { Map<String, Integer> map = new HashMap<>(); Integer aInteger = map.put("庄宿正", 12); Integer bInteger = map.put("张三", 13); Integer cInteger = map.put("李四", 14); System.out.println(map + "---" +aInteger + bInteger + cInteger ); } }
GB18030
Java
2,053
java
Map_Demo1.java
Java
[ { "context": " = new HashMap<>();\n\t\tInteger aInteger = map.put(\"庄宿正\", 12);\n\t\tInteger bInteger = map.put(\"张三\", 13);\n\t\t", "end": 401, "score": 0.9982293844223022, "start": 398, "tag": "NAME", "value": "庄宿正" }, { "context": "map.put(\"庄宿正\", 12);\n\t\tInteger bInteger = map.put(\"张三\", 13);\n\t\tInteger cInteger = map.put(\"李四\", 14);\n\t\t", "end": 441, "score": 0.9541717767715454, "start": 439, "tag": "NAME", "value": "张三" }, { "context": " map.put(\"张三\", 13);\n\t\tInteger cInteger = map.put(\"李四\", 14);\n\t\tSet<Map.Entry<String, Integer>> entries ", "end": 481, "score": 0.9507418870925903, "start": 479, "tag": "NAME", "value": "李四" }, { "context": " = new HashMap<>();\n\t\tInteger aInteger = map.put(\"庄宿正\", 12);\n\t\tInteger bInteger = map.put(\"张三\", 13);\n\t\t", "end": 1062, "score": 0.9988023042678833, "start": 1059, "tag": "NAME", "value": "庄宿正" }, { "context": "map.put(\"庄宿正\", 12);\n\t\tInteger bInteger = map.put(\"张三\", 13);\n\t\tInteger cInteger = map.put(\"李四\", 14);\n\t\t", "end": 1102, "score": 0.9762409329414368, "start": 1100, "tag": "NAME", "value": "张三" }, { "context": " map.put(\"张三\", 13);\n\t\tInteger cInteger = map.put(\"李四\", 14);\n\t\tSystem.out.println(map.size());\n\t\tmap.cl", "end": 1142, "score": 0.9837359189987183, "start": 1140, "tag": "NAME", "value": "李四" }, { "context": " = new HashMap<>();\n\t\tInteger aInteger = map.put(\"庄宿正\", 12);\n\t\tInteger bInteger = map.put(\"张三\", 13);\n\t\t", "end": 1361, "score": 0.9982334971427917, "start": 1358, "tag": "NAME", "value": "庄宿正" }, { "context": "map.put(\"庄宿正\", 12);\n\t\tInteger bInteger = map.put(\"张三\", 13);\n\t\tInteger cInteger = map.put(\"李四\", 14);\n\t\t", "end": 1401, "score": 0.9384150505065918, "start": 1399, "tag": "NAME", "value": "张三" }, { "context": " map.put(\"张三\", 13);\n\t\tInteger cInteger = map.put(\"李四\", 14);\n\t\tInteger value = map.remove(\"李四\");\n\t\tSyst", "end": 1441, "score": 0.7915284633636475, "start": 1439, "tag": "NAME", "value": "李四" }, { "context": " map.put(\"李四\", 14);\n\t\tInteger value = map.remove(\"李四\");\n\t\tSystem.out.println(map.containsKey(\"张三\")); ", "end": 1481, "score": 0.9873945713043213, "start": 1479, "tag": "NAME", "value": "李四" }, { "context": "move(\"李四\");\n\t\tSystem.out.println(map.containsKey(\"张三\")); // 是否包含张三这个键\n\t\tSystem.out.println(map.contai", "end": 1525, "score": 0.9266313314437866, "start": 1523, "tag": "NAME", "value": "张三" }, { "context": " = new HashMap<>();\n\t\tInteger aInteger = map.put(\"庄宿正\", 12);\n\t\tInteger bInteger = map.put(\"张三\", 13);\n\t\t", "end": 1773, "score": 0.9991804957389832, "start": 1770, "tag": "NAME", "value": "庄宿正" }, { "context": "map.put(\"庄宿正\", 12);\n\t\tInteger bInteger = map.put(\"张三\", 13);\n\t\tInteger cInteger = map.put(\"李四\", 14);\n\t\t", "end": 1813, "score": 0.9957129955291748, "start": 1811, "tag": "NAME", "value": "张三" }, { "context": " map.put(\"张三\", 13);\n\t\tInteger cInteger = map.put(\"李四\", 14);\n\t\tSystem.out.println(map + \"---\" +aInteger", "end": 1853, "score": 0.9970289468765259, "start": 1851, "tag": "NAME", "value": "李四" } ]
null
[]
package cn.yykjc.self; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; public class Map_Demo1 { public static void main(String[] args) { // TODO Auto-generated method stub //demo1(); //demo2(); //demo3(); // demo4(); } public static void demo4() { Map<String, Integer> map = new HashMap<>(); Integer aInteger = map.put("庄宿正", 12); Integer bInteger = map.put("张三", 13); Integer cInteger = map.put("李四", 14); Set<Map.Entry<String, Integer>> entries = map.entrySet(); Iterator<Map.Entry<String, Integer>> iterator = entries.iterator(); while(iterator.hasNext()) { Map.Entry<String,Integer> entry = iterator.next(); System.out.println(entry.getKey() + "===" + entry.getValue()); //System.out.println(iterator.next()); } for (Map.Entry<String, Integer> entry : map.entrySet()) { System.out.println(entry.getKey() + "----" + entry.getValue()); } } public static void demo3() { Map<String, Integer> map = new HashMap<>(); Integer aInteger = map.put("庄宿正", 12); Integer bInteger = map.put("张三", 13); Integer cInteger = map.put("李四", 14); System.out.println(map.size()); map.clear(); // 数据没有了,集合依然在 System.out.println(map.size()); } public static void demo2() { Map<String, Integer> map = new HashMap<>(); Integer aInteger = map.put("庄宿正", 12); Integer bInteger = map.put("张三", 13); Integer cInteger = map.put("李四", 14); Integer value = map.remove("李四"); System.out.println(map.containsKey("张三")); // 是否包含张三这个键 System.out.println(map.containsValue(12)); // 是否包含12这个值 System.out.println(value); System.out.println(map); } public static void demo1() { Map<String, Integer> map = new HashMap<>(); Integer aInteger = map.put("庄宿正", 12); Integer bInteger = map.put("张三", 13); Integer cInteger = map.put("李四", 14); System.out.println(map + "---" +aInteger + bInteger + cInteger ); } }
2,053
0.645478
0.626357
69
27.043478
20.533772
69
false
false
0
0
0
0
0
0
2.347826
false
false
6
08359764f851fce89e8188727708616c4312876a
15,685,220,570,884
0ee973dced51a7c5ae49efe41abe886e458df1df
/GasInformationApp/src/com/gasinforapp/bean/User.java
74f0dcec0498447dc22582c9562aaf645ea6a046
[]
no_license
c317/AndroidApp
https://github.com/c317/AndroidApp
89145cdf6bd37c9cd125cf411b9b58971efb75c4
42373aa705e6d4ba694bc95dd38ff927ea423f24
refs/heads/master
2016-08-11T18:56:44.019000
2016-03-27T08:37:02
2016-03-27T08:37:02
49,556,153
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.gasinforapp.bean; public class User { private int userID; private String account; private String userName; private String password; private String department; private String job; public int getUserID() { return userID; } public void setUserID(int userID) { this.userID = userID; } public String getUserName() { return userName; } public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public String getJob() { return job; } public void setJob(String job) { this.job = job; } }
UTF-8
Java
998
java
User.java
Java
[ { "context": "userID;\r\n\tprivate String account;\r\n\tprivate String userName;\r\n\tprivate String password;\r\n\tprivate String depa", "end": 126, "score": 0.9728181958198547, "start": 118, "tag": "USERNAME", "value": "userName" }, { "context": "D;\r\n\t}\r\n\r\n\tpublic String getUserName() {\r\n\t\treturn userName;\r\n\t}\r\n\r\n\tpublic String getAccount() {\r\n\t\treturn a", "end": 378, "score": 0.976352870464325, "start": 370, "tag": "USERNAME", "value": "userName" }, { "context": " = account;\r\n\t}\r\n\r\n\tpublic void setUserName(String userName) {\r\n\t\tthis.userName = userName;\r\n\t}\r\n\r\n\tpublic St", "end": 559, "score": 0.8687847852706909, "start": 551, "tag": "USERNAME", "value": "userName" }, { "context": " setUserName(String userName) {\r\n\t\tthis.userName = userName;\r\n\t}\r\n\r\n\tpublic String getPassword() {\r\n\t\treturn ", "end": 590, "score": 0.9934430122375488, "start": 582, "tag": "USERNAME", "value": "userName" } ]
null
[]
package com.gasinforapp.bean; public class User { private int userID; private String account; private String userName; private String password; private String department; private String job; public int getUserID() { return userID; } public void setUserID(int userID) { this.userID = userID; } public String getUserName() { return userName; } public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public String getJob() { return job; } public void setJob(String job) { this.job = job; } }
998
0.668337
0.668337
59
14.915255
14.257069
47
false
false
0
0
0
0
0
0
1.237288
false
false
6
ecd5ebe9c8f421eb6e29bd234b57431587e609ae
4,045,859,200,690
a4a32e489baa6cb4af80651a8e19a57d086ad8ae
/src/main/java/com/cupcakes/logic/DTO/Invoice.java
b0b0dd7281ef8312d0cd74bf06ca8bd9e05c93ba
[]
no_license
cph-mn521/Cup_Cake
https://github.com/cph-mn521/Cup_Cake
2aae6eb131613aac4dd1f3d602bc6d4285c059da
2f4526dd8130a264de85c0ac11c476d82ae1753d
refs/heads/master
2020-04-25T16:35:02.403000
2019-03-15T12:14:34
2019-03-15T12:14:34
172,917,853
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cupcakes.logic.DTO; import java.sql.Date; /** * * @author martin bøgh */ public class Invoice { private int invoice_id; private int user_id; private int cart_id; private Date invoice_date; private String username; private String email; private String balance; public Invoice(int invoice_id, int user_id, int cart_id, Date invoice_date, String username, String email, String balance) { this.invoice_id = invoice_id; this.user_id = user_id; this.cart_id = cart_id; this.invoice_date = invoice_date; this.username = username; this.email = email; this.balance = balance; } public int getInvoice_id() { return invoice_id; } public int getUser_id() { return user_id; } public int getCart_id() { return cart_id; } public Date getInvoice_date() { return invoice_date; } public String getUsername() { return username; } public String getEmail() { return email; } public String getBalance() { return balance; } }
UTF-8
Java
1,172
java
Invoice.java
Java
[ { "context": "gic.DTO;\n\nimport java.sql.Date;\n\n/**\n *\n * @author martin bøgh\n */\npublic class Invoice {\n private int invoic", "end": 85, "score": 0.9998663067817688, "start": 74, "tag": "NAME", "value": "martin bøgh" }, { "context": "voice_date = invoice_date;\n this.username = username;\n this.email = email;\n this.balance", "end": 615, "score": 0.9745870232582092, "start": 607, "tag": "USERNAME", "value": "username" } ]
null
[]
package com.cupcakes.logic.DTO; import java.sql.Date; /** * * @author <NAME> */ public class Invoice { private int invoice_id; private int user_id; private int cart_id; private Date invoice_date; private String username; private String email; private String balance; public Invoice(int invoice_id, int user_id, int cart_id, Date invoice_date, String username, String email, String balance) { this.invoice_id = invoice_id; this.user_id = user_id; this.cart_id = cart_id; this.invoice_date = invoice_date; this.username = username; this.email = email; this.balance = balance; } public int getInvoice_id() { return invoice_id; } public int getUser_id() { return user_id; } public int getCart_id() { return cart_id; } public Date getInvoice_date() { return invoice_date; } public String getUsername() { return username; } public String getEmail() { return email; } public String getBalance() { return balance; } }
1,166
0.578138
0.578138
66
16.742424
18.672058
126
false
false
0
0
0
0
0
0
0.439394
false
false
6
514ec3795d29f8519937f344244ccfd30efbe942
32,366,873,543,808
fa3c41529cf3590a50c09d11260c02c7a9fba277
/src/main/java/cn/edu/hfut/backend/dao/UserMapper.java
0fd8ba6183a43e8193132d55a422526f3a3deda4
[]
no_license
xuewenG/online-chat-backend
https://github.com/xuewenG/online-chat-backend
d6f33b1a1bdf5028abc1aa546254977f27eed145
a883884b559dc7ab6c3124da88f6514e348e21c4
refs/heads/master
2022-11-12T08:37:59.076000
2020-07-06T17:53:20
2020-07-06T17:53:20
274,790,204
0
0
null
false
2020-07-05T13:02:27
2020-06-24T23:35:16
2020-07-05T12:48:37
2020-07-05T13:02:26
506
0
0
0
Java
false
false
package cn.edu.hfut.backend.dao; import cn.edu.hfut.backend.dao.provider.UserProvider; import cn.edu.hfut.backend.entity.User; import org.apache.ibatis.annotations.*; import java.sql.Timestamp; @Mapper public interface UserMapper { @Select("SELECT * FROM " + "user " + "WHERE user.account = #{account}") User getUserByAccount(String account); @Select("SELECT * FROM " + "user " + "WHERE user.email = #{email}") User getUserByEmail(String email); @Insert("INSERT INTO `user`(account,`password`,nickname,gender,birthday,avatar,email,state) " + "VALUES(#{account},#{password},#{nickname},#{gender}," + "#{birthday},#{avatar},#{email},1)") void enroll(String account, String password, String email, String nickname, String avatar, Timestamp birthday, Integer gender); @Select("SELECT ID FROM " + "user " + "WHERE user.email= #{email}") Integer getIdByEmail(String email); @Select("SELECT ID FROM " + "user " + "WHERE user.account= #{account}") Integer getIdByAccount(String account); @Select("SELECT * FROM " + "user " + "WHERE user.account= #{account}") User getByAccount(String account); @Select("SELECT * FROM " + "user " + "WHERE user.email= #{email}") User getByEmail(String email); @Select("SELECT * FROM " + "user " + "WHERE user.ID= #{Id}") User getUserById(Integer id); @UpdateProvider(type = UserProvider.class, method = "updateById") void updateById(Integer id, String nickname, Integer gender, Timestamp birthday); @Update("update user set password = #{password} where id = #{userId}") void updatePasswordById(Integer userId, String password); @Update("update user set avatar = #{avatar} where id = #{userId}") void editAvatar(Integer userId, String avatar); }
UTF-8
Java
1,980
java
UserMapper.java
Java
[]
null
[]
package cn.edu.hfut.backend.dao; import cn.edu.hfut.backend.dao.provider.UserProvider; import cn.edu.hfut.backend.entity.User; import org.apache.ibatis.annotations.*; import java.sql.Timestamp; @Mapper public interface UserMapper { @Select("SELECT * FROM " + "user " + "WHERE user.account = #{account}") User getUserByAccount(String account); @Select("SELECT * FROM " + "user " + "WHERE user.email = #{email}") User getUserByEmail(String email); @Insert("INSERT INTO `user`(account,`password`,nickname,gender,birthday,avatar,email,state) " + "VALUES(#{account},#{password},#{nickname},#{gender}," + "#{birthday},#{avatar},#{email},1)") void enroll(String account, String password, String email, String nickname, String avatar, Timestamp birthday, Integer gender); @Select("SELECT ID FROM " + "user " + "WHERE user.email= #{email}") Integer getIdByEmail(String email); @Select("SELECT ID FROM " + "user " + "WHERE user.account= #{account}") Integer getIdByAccount(String account); @Select("SELECT * FROM " + "user " + "WHERE user.account= #{account}") User getByAccount(String account); @Select("SELECT * FROM " + "user " + "WHERE user.email= #{email}") User getByEmail(String email); @Select("SELECT * FROM " + "user " + "WHERE user.ID= #{Id}") User getUserById(Integer id); @UpdateProvider(type = UserProvider.class, method = "updateById") void updateById(Integer id, String nickname, Integer gender, Timestamp birthday); @Update("update user set password = #{password} where id = #{userId}") void updatePasswordById(Integer userId, String password); @Update("update user set avatar = #{avatar} where id = #{userId}") void editAvatar(Integer userId, String avatar); }
1,980
0.608586
0.608081
61
31.442623
24.542051
99
false
false
0
0
0
0
0
0
0.688525
false
false
6
e53d0685122863bfaee864b08b2b46258a602593
3,599,182,602,980
a0e8253aa7002586929520d94c15ec1c51ec0789
/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/events/EventsListenerProvider.java
87606ca984be66fe739ccfe9f2170e99b73f72ee
[ "Apache-2.0" ]
permissive
vmuzikar/keycloak
https://github.com/vmuzikar/keycloak
1c6f9fdc2e51b3aa7887c23bdb4c64de9a6db512
115efcf34aeb116a692ede6d30bf25b1147ca1a2
refs/heads/master
2023-08-03T03:01:49.979000
2016-05-20T08:17:17
2016-05-20T08:17:17
43,059,184
4
0
Apache-2.0
true
2022-10-12T13:27:17
2015-09-24T10:02:07
2022-08-16T08:21:04
2022-10-12T13:27:16
177,567
2
0
0
Java
false
false
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.keycloak.testsuite.events; import org.keycloak.events.Event; import org.keycloak.events.EventListenerProvider; import org.keycloak.events.admin.AdminEvent; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; /** * @author <a href="mailto:mstrukel@redhat.com">Marko Strukelj</a> */ public class EventsListenerProvider implements EventListenerProvider { private static final BlockingQueue<Event> events = new LinkedBlockingQueue<Event>(); private static final BlockingQueue<AdminEvent> adminEvents = new LinkedBlockingQueue<>(); @Override public void onEvent(Event event) { events.add(event); } @Override public void onEvent(AdminEvent event, boolean includeRepresentation) { // Save the copy for case when same AdminEventBuilder is used more times during same transaction to avoid overwriting previously referenced event adminEvents.add(copy(event)); } @Override public void close() { } public static Event poll() { return events.poll(); } public static AdminEvent pollAdminEvent() { return adminEvents.poll(); } public static void clear() { events.clear(); } public static void clearAdminEvents() { adminEvents.clear(); } private AdminEvent copy(AdminEvent adminEvent) { AdminEvent newEvent = new AdminEvent(); newEvent.setAuthDetails(adminEvent.getAuthDetails()); newEvent.setError(adminEvent.getError()); newEvent.setOperationType(adminEvent.getOperationType()); newEvent.setRealmId(adminEvent.getRealmId()); newEvent.setRepresentation(adminEvent.getRepresentation()); newEvent.setResourcePath(adminEvent.getResourcePath()); newEvent.setTime(adminEvent.getTime()); return newEvent; } }
UTF-8
Java
2,543
java
EventsListenerProvider.java
Java
[ { "context": "kedBlockingQueue;\n\n/**\n * @author <a href=\"mailto:mstrukel@redhat.com\">Marko Strukelj</a>\n */\npublic class EventsListen", "end": 989, "score": 0.9999254941940308, "start": 970, "tag": "EMAIL", "value": "mstrukel@redhat.com" }, { "context": "*\n * @author <a href=\"mailto:mstrukel@redhat.com\">Marko Strukelj</a>\n */\npublic class EventsListenerProvider imple", "end": 1005, "score": 0.999891459941864, "start": 991, "tag": "NAME", "value": "Marko Strukelj" } ]
null
[]
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.keycloak.testsuite.events; import org.keycloak.events.Event; import org.keycloak.events.EventListenerProvider; import org.keycloak.events.admin.AdminEvent; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; /** * @author <a href="mailto:<EMAIL>"><NAME></a> */ public class EventsListenerProvider implements EventListenerProvider { private static final BlockingQueue<Event> events = new LinkedBlockingQueue<Event>(); private static final BlockingQueue<AdminEvent> adminEvents = new LinkedBlockingQueue<>(); @Override public void onEvent(Event event) { events.add(event); } @Override public void onEvent(AdminEvent event, boolean includeRepresentation) { // Save the copy for case when same AdminEventBuilder is used more times during same transaction to avoid overwriting previously referenced event adminEvents.add(copy(event)); } @Override public void close() { } public static Event poll() { return events.poll(); } public static AdminEvent pollAdminEvent() { return adminEvents.poll(); } public static void clear() { events.clear(); } public static void clearAdminEvents() { adminEvents.clear(); } private AdminEvent copy(AdminEvent adminEvent) { AdminEvent newEvent = new AdminEvent(); newEvent.setAuthDetails(adminEvent.getAuthDetails()); newEvent.setError(adminEvent.getError()); newEvent.setOperationType(adminEvent.getOperationType()); newEvent.setRealmId(adminEvent.getRealmId()); newEvent.setRepresentation(adminEvent.getRepresentation()); newEvent.setResourcePath(adminEvent.getResourcePath()); newEvent.setTime(adminEvent.getTime()); return newEvent; } }
2,523
0.717656
0.71451
78
31.602564
30.21858
153
false
false
0
0
0
0
0
0
0.384615
false
false
6
2e3b34d722feb52fe100fd9ad2a2ab48adb71f98
8,744,553,414,723
9a23070b18dce92bb428647fb6baf5680126eed7
/MapGraph/MapNode.java
268119f6a5ebd274fded2c7b7041b1683b898aea
[]
no_license
Snafkin547/InfluencerAnalysis
https://github.com/Snafkin547/InfluencerAnalysis
ab9c37c2b35528c76b29aa505abacfddb6ddced2
32ab0ffb3e33895b0d93ebbcfdc2f9e9a15bb939
refs/heads/master
2023-07-15T16:51:02.063000
2021-08-24T15:33:53
2021-08-24T15:33:53
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package roadgraph; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import geography.GeographicPoint; public class MapNode implements Comparable<MapNode>{ private GeographicPoint location; private List<MapEdge> edges; private LinkedList<MapNode> neighbors; private double distance; public MapNode(GeographicPoint location) { this.location = location; edges = new ArrayList<>(); neighbors = new LinkedList<MapNode>(); distance = Double.MAX_VALUE; } public void addEdge(MapEdge edge) { edges.add(edge); } public GeographicPoint getLocation() { return location; } /** Returns whether two nodes are equal. * Nodes are considered equal if their locations are the same, * even if their street list is different. * @param o the node to compare to * @return true if these nodes are at the same location, false otherwise */ public boolean equals(Object o) { if (!(o instanceof MapNode) || (o == null)) { return false; } MapNode node = (MapNode)o; return node.location.equals(this.location); } public void addNeighbor(MapNode neighbor) { neighbors.add(neighbor); } /** * @return the neighbors */ public Set<MapNode> getNeighbors() { Set<MapNode> neighbors = new HashSet<MapNode>(); for(MapEdge edge : edges) { neighbors.add(edge.getNeighborsOf(this)); } return neighbors; } @SuppressWarnings("null") public double getEdge(MapNode start,MapNode end){ Double edgeWeight = null; for(MapEdge edge: edges){ if(edge.getOtherNode(start).equals(end)){ edgeWeight = edge.getWeight(); return edgeWeight; } } return edgeWeight; } public double getDistance() { return distance; } public void setDistance(double distance) { this.distance = distance; } public int compareTo(MapNode o) { if(this.distance < o.distance){ return -1; }else if(this.distance > o.distance){ return 1; }else{ return 0; } } }
UTF-8
Java
2,157
java
MapNode.java
Java
[]
null
[]
package roadgraph; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import geography.GeographicPoint; public class MapNode implements Comparable<MapNode>{ private GeographicPoint location; private List<MapEdge> edges; private LinkedList<MapNode> neighbors; private double distance; public MapNode(GeographicPoint location) { this.location = location; edges = new ArrayList<>(); neighbors = new LinkedList<MapNode>(); distance = Double.MAX_VALUE; } public void addEdge(MapEdge edge) { edges.add(edge); } public GeographicPoint getLocation() { return location; } /** Returns whether two nodes are equal. * Nodes are considered equal if their locations are the same, * even if their street list is different. * @param o the node to compare to * @return true if these nodes are at the same location, false otherwise */ public boolean equals(Object o) { if (!(o instanceof MapNode) || (o == null)) { return false; } MapNode node = (MapNode)o; return node.location.equals(this.location); } public void addNeighbor(MapNode neighbor) { neighbors.add(neighbor); } /** * @return the neighbors */ public Set<MapNode> getNeighbors() { Set<MapNode> neighbors = new HashSet<MapNode>(); for(MapEdge edge : edges) { neighbors.add(edge.getNeighborsOf(this)); } return neighbors; } @SuppressWarnings("null") public double getEdge(MapNode start,MapNode end){ Double edgeWeight = null; for(MapEdge edge: edges){ if(edge.getOtherNode(start).equals(end)){ edgeWeight = edge.getWeight(); return edgeWeight; } } return edgeWeight; } public double getDistance() { return distance; } public void setDistance(double distance) { this.distance = distance; } public int compareTo(MapNode o) { if(this.distance < o.distance){ return -1; }else if(this.distance > o.distance){ return 1; }else{ return 0; } } }
2,157
0.651368
0.649977
96
21.46875
18.050249
73
false
false
0
0
0
0
0
0
1.25
false
false
6
e50cd0412f8006d3b50039c30f2a885472a12420
28,321,014,369,183
8103c9ec42a0566fa613bf290828e1851a122e90
/web-service/src/main/java/com/mohress/training/service/course/CourseBizImpl.java
3739901039e9cb8da2ef6c4d4e8a77366f135beb
[]
no_license
telen/hrproject
https://github.com/telen/hrproject
058a81ed8f87762045161fa3e0dbb160a009bac4
f99a7c2cfff4963bffbe80945aeb349b120846eb
refs/heads/master
2021-01-15T17:29:13.587000
2017-09-04T07:40:20
2017-09-04T07:40:20
99,756,073
0
2
null
false
2017-09-04T07:40:21
2017-08-09T02:21:38
2017-08-11T03:21:12
2017-09-04T07:40:21
520
0
2
0
Java
null
null
package com.mohress.training.service.course; import com.google.common.base.Preconditions; import com.mohress.training.dto.QueryDto; import com.mohress.training.dto.course.CourseItemDto; import com.mohress.training.dto.course.CourseRequestDto; import com.mohress.training.entity.TblCourse; import com.mohress.training.entity.TblTeacher; import com.mohress.training.service.BaseManageService; import com.mohress.training.service.ModuleBiz; import com.mohress.training.service.teacher.TeacherQuery; import com.mohress.training.service.teacher.TeacherServiceImpl; import com.mohress.training.util.Checker; import com.mohress.training.util.Convert; import com.mohress.training.util.JsonUtil; import com.mohress.training.util.SequenceCreator; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeanUtils; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import javax.annotation.Resource; import java.util.List; /** * 课程服务 * Created by qx.wang on 2017/8/18. */ @Slf4j @Service public class CourseBizImpl implements ModuleBiz { @Resource private BaseManageService courseServiceImpl; @Resource private TeacherServiceImpl teacherServiceImpl; @Override public void newModule(String o, String agencyId) { Preconditions.checkArgument(o != null); CourseRequestDto courseRequestDto; try { courseRequestDto = JsonUtil.getInstance().convertToBean(CourseRequestDto.class, String.valueOf(o)); } catch (Exception e) { throw new RuntimeException("反序列化课程失败"); } Checker.checkNewCourse(courseRequestDto); //todo 校验教师合理性 courseServiceImpl.newModule(buildInsertTblCourse(courseRequestDto, agencyId)); } @Override public void delete(List<String> ids) { Preconditions.checkArgument(!CollectionUtils.isEmpty(ids)); courseServiceImpl.delete(ids); } @Override public void update(String o) { Preconditions.checkArgument(o != null); CourseRequestDto courseRequestDto = null; try { courseRequestDto = JsonUtil.getInstance().convertToBean(CourseRequestDto.class, String.valueOf(o)); } catch (Exception e) { log.error("教师新增反序列化失败 {}", o, e); } courseServiceImpl.update(buildUpdateTblCourse(courseRequestDto)); } @Override public Object query(QueryDto pageDto) { Preconditions.checkNotNull(pageDto); Preconditions.checkArgument(pageDto.getPage() >= 0); Preconditions.checkArgument(pageDto.getPageSize() > 0); List<TblCourse> tblCourses = courseServiceImpl.query(buildCourseQuery(pageDto)); List<CourseItemDto> courseItemDtos = Convert.convertCourse(tblCourses); if (CollectionUtils.isEmpty(courseItemDtos)) { return courseItemDtos; } for (CourseItemDto dto : courseItemDtos) { TeacherQuery query = new TeacherQuery(); query.setTeacherId(dto.getTeacherId()); List<TblTeacher> teachers = teacherServiceImpl.query(query); if (!CollectionUtils.isEmpty(teachers)) { dto.setTeacherName(teachers.get(0).getName()); } } return courseItemDtos; } @Override public void checkDelete(String agencyId, List<String> ids) { } private CourseQuery buildCourseQuery(QueryDto dto) { CourseQuery query = new CourseQuery(); query.setAgencyId(dto.getAgencyId()); query.setPageIndex(dto.getPage()); query.setPageSize(dto.getPageSize()); return query; } private TblCourse buildInsertTblCourse(CourseRequestDto courseRequestDto, String agencyId) { TblCourse course = new TblCourse(); BeanUtils.copyProperties(courseRequestDto, course); course.setCourseId(SequenceCreator.getCourseId()); course.setAgencyId(agencyId); return course; } private TblCourse buildUpdateTblCourse(CourseRequestDto courseRequestDto) { TblCourse course = new TblCourse(); BeanUtils.copyProperties(courseRequestDto, course); return course; } }
UTF-8
Java
4,244
java
CourseBizImpl.java
Java
[ { "context": "\nimport java.util.List;\n\n/**\n * 课程服务\n * Created by qx.wang on 2017/8/18.\n */\n@Slf4j\n@Service\npublic class Co", "end": 1004, "score": 0.9564076066017151, "start": 997, "tag": "USERNAME", "value": "qx.wang" } ]
null
[]
package com.mohress.training.service.course; import com.google.common.base.Preconditions; import com.mohress.training.dto.QueryDto; import com.mohress.training.dto.course.CourseItemDto; import com.mohress.training.dto.course.CourseRequestDto; import com.mohress.training.entity.TblCourse; import com.mohress.training.entity.TblTeacher; import com.mohress.training.service.BaseManageService; import com.mohress.training.service.ModuleBiz; import com.mohress.training.service.teacher.TeacherQuery; import com.mohress.training.service.teacher.TeacherServiceImpl; import com.mohress.training.util.Checker; import com.mohress.training.util.Convert; import com.mohress.training.util.JsonUtil; import com.mohress.training.util.SequenceCreator; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeanUtils; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import javax.annotation.Resource; import java.util.List; /** * 课程服务 * Created by qx.wang on 2017/8/18. */ @Slf4j @Service public class CourseBizImpl implements ModuleBiz { @Resource private BaseManageService courseServiceImpl; @Resource private TeacherServiceImpl teacherServiceImpl; @Override public void newModule(String o, String agencyId) { Preconditions.checkArgument(o != null); CourseRequestDto courseRequestDto; try { courseRequestDto = JsonUtil.getInstance().convertToBean(CourseRequestDto.class, String.valueOf(o)); } catch (Exception e) { throw new RuntimeException("反序列化课程失败"); } Checker.checkNewCourse(courseRequestDto); //todo 校验教师合理性 courseServiceImpl.newModule(buildInsertTblCourse(courseRequestDto, agencyId)); } @Override public void delete(List<String> ids) { Preconditions.checkArgument(!CollectionUtils.isEmpty(ids)); courseServiceImpl.delete(ids); } @Override public void update(String o) { Preconditions.checkArgument(o != null); CourseRequestDto courseRequestDto = null; try { courseRequestDto = JsonUtil.getInstance().convertToBean(CourseRequestDto.class, String.valueOf(o)); } catch (Exception e) { log.error("教师新增反序列化失败 {}", o, e); } courseServiceImpl.update(buildUpdateTblCourse(courseRequestDto)); } @Override public Object query(QueryDto pageDto) { Preconditions.checkNotNull(pageDto); Preconditions.checkArgument(pageDto.getPage() >= 0); Preconditions.checkArgument(pageDto.getPageSize() > 0); List<TblCourse> tblCourses = courseServiceImpl.query(buildCourseQuery(pageDto)); List<CourseItemDto> courseItemDtos = Convert.convertCourse(tblCourses); if (CollectionUtils.isEmpty(courseItemDtos)) { return courseItemDtos; } for (CourseItemDto dto : courseItemDtos) { TeacherQuery query = new TeacherQuery(); query.setTeacherId(dto.getTeacherId()); List<TblTeacher> teachers = teacherServiceImpl.query(query); if (!CollectionUtils.isEmpty(teachers)) { dto.setTeacherName(teachers.get(0).getName()); } } return courseItemDtos; } @Override public void checkDelete(String agencyId, List<String> ids) { } private CourseQuery buildCourseQuery(QueryDto dto) { CourseQuery query = new CourseQuery(); query.setAgencyId(dto.getAgencyId()); query.setPageIndex(dto.getPage()); query.setPageSize(dto.getPageSize()); return query; } private TblCourse buildInsertTblCourse(CourseRequestDto courseRequestDto, String agencyId) { TblCourse course = new TblCourse(); BeanUtils.copyProperties(courseRequestDto, course); course.setCourseId(SequenceCreator.getCourseId()); course.setAgencyId(agencyId); return course; } private TblCourse buildUpdateTblCourse(CourseRequestDto courseRequestDto) { TblCourse course = new TblCourse(); BeanUtils.copyProperties(courseRequestDto, course); return course; } }
4,244
0.706402
0.703297
121
33.595043
26.209764
111
false
false
0
0
0
0
0
0
0.578512
false
false
6
e83529a1675e36b66db36777226002fa41339f7e
11,089,605,582,756
9d1a6356e638fe225f87c2a64cd731c878f24dce
/compress.java
a06c38978654534c03fd4d942c3eebfdae63c383
[]
no_license
sunsui/leetcode
https://github.com/sunsui/leetcode
5d7d1108640246df854ab25cf6ea11a8b9bc1691
ceee740c2f8d1ecb080e8d98bbc3f251dd8c949c
refs/heads/master
2021-09-03T00:10:08.190000
2018-01-04T07:42:35
2018-01-04T07:42:35
113,028,750
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package leetcode; import java.util.Arrays; class Solution { public int compress(char[] chars) { // int tmp = 1; // StringBuilder sb = new StringBuilder(); // if(chars.length == 1) // return 1; // for(int i=1;i<chars.length;i++){ // if(chars[i] != chars[i-1] ){ // sb.append(chars[i-1]).append(tmp); // tmp = 1; // } // else{ // tmp += 1; // if( i == chars.length-1) // sb.append(chars[i-1]).append(tmp); // } // } // return sb.length(); int start = 0; for(int end = 0, count = 0; end < chars.length; end++) { count++; if(end == chars.length-1 || chars[end] != chars[end + 1] ) { //We have found a difference or we are at the end of array chars[start] = chars[end]; // Update the character at start pointer start++; if(count != 1) { // Copy over the character count to the array char[] arr = String.valueOf(count).toCharArray(); for(int i=0;i<arr.length;i++, start++) chars[start] = arr[i]; } // Reset the counter count = 0; } } return start; } }
UTF-8
Java
1,349
java
compress.java
Java
[]
null
[]
package leetcode; import java.util.Arrays; class Solution { public int compress(char[] chars) { // int tmp = 1; // StringBuilder sb = new StringBuilder(); // if(chars.length == 1) // return 1; // for(int i=1;i<chars.length;i++){ // if(chars[i] != chars[i-1] ){ // sb.append(chars[i-1]).append(tmp); // tmp = 1; // } // else{ // tmp += 1; // if( i == chars.length-1) // sb.append(chars[i-1]).append(tmp); // } // } // return sb.length(); int start = 0; for(int end = 0, count = 0; end < chars.length; end++) { count++; if(end == chars.length-1 || chars[end] != chars[end + 1] ) { //We have found a difference or we are at the end of array chars[start] = chars[end]; // Update the character at start pointer start++; if(count != 1) { // Copy over the character count to the array char[] arr = String.valueOf(count).toCharArray(); for(int i=0;i<arr.length;i++, start++) chars[start] = arr[i]; } // Reset the counter count = 0; } } return start; } }
1,349
0.435137
0.421794
43
30.372093
21.395525
83
false
false
0
0
0
0
0
0
1.116279
false
false
6
85eab188a22314904fb0e2a64f637a9d3366afc7
33,320,356,313,552
00fa5bc1ef75a14fccff68f62bd0c855604cf22c
/src/main/java/com/bank/controller/AccountController.java
413202b89d2f5b7a75599f4c0f5ea1e4dfb82ad9
[]
no_license
boschma2702/F4U-Bank
https://github.com/boschma2702/F4U-Bank
e47544dc79d62aab62c9480b5abd5b2d3b087009
64080b8b9399585d2df3ba691f5ca46778633856
refs/heads/master
2021-01-01T03:59:24.567000
2017-09-09T09:08:18
2017-09-09T09:08:18
97,100,353
0
1
null
false
2017-09-09T09:08:18
2017-07-13T08:42:44
2017-07-13T08:48:58
2017-09-09T09:08:18
455
0
1
0
Java
null
null
package com.bank.controller; import com.bank.exception.*; import com.bank.projection.account.AccountAmountProjection; import com.bank.projection.account.AccountOpenProjection; import com.bank.projection.account.AccountOverdraftLimitProjection; import com.bank.service.AuthenticationService; import com.bank.service.account.*; import com.bank.service.account.accountsaving.AccountSavingCloseService; import com.bank.service.creditcard.CreditCardCloseService; import com.bank.service.customer.CustomerService; import com.bank.service.overdraft.OverdraftLimitService; import com.bank.util.AccountType; import com.bank.util.Constants; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.math.BigDecimal; import java.sql.Date; @Service public class AccountController { @Autowired private AccountService accountService; @Autowired private AccountOpenService accountOpenService; @Autowired private AccountCloseService accountCloseService; @Autowired private AccountSavingCloseService accountSavingCloseService; @Autowired private CreditCardCloseService creditCardCloseService; @Autowired private AccountAmountService accountAmountService; @Autowired private OverdraftLimitService overdraftLimitService; @Autowired private AccountFreezeService accountFreezeService; @Autowired private AccountTransferLimitService accountTransferLimitService; @Autowired private CustomerService customerService; public AccountOpenProjection openAccount(String name, String surname, String initials, Date date, String ssn, String address, String telephoneNumber, String email, String username, String password) throws InvalidParamValueException, NotAuthorizedException { try { return openAccount(name, surname, initials, date, ssn, address, telephoneNumber, email, username, password, Constants.ACCOUNT_TYPE_REGULAR, new String[]{}); } catch (AccountFrozenException e) { //new accounts without guardians can not throw accountFrozenException } throw new IllegalStateException("FrozenAccountException during opening new account"); } public AccountOpenProjection openAdditionalAccount(String authToken) throws NotAuthorizedException, AccountFrozenException, NotAllowedException { if (AuthenticationService.instance.isCustomer(authToken)) { int customerId = (Integer) AuthenticationService.instance.getObject(authToken, AuthenticationService.USER_ID); if ((Boolean) AuthenticationService.instance.getObject(authToken, AuthenticationService.IS_MINOR)) { throw new NotAllowedException("Not Authorized"); } return accountOpenService.openAdditionalAccount(customerId); } else { throw new NotAuthorizedException("Not Authorized"); } } public void closeAccount(String authToken, String IBAN) throws InvalidParamValueException, NotAuthorizedException, AccountFrozenException { int customerId = (Integer) AuthenticationService.instance.getObject(authToken, AuthenticationService.USER_ID); String normalizedAccountNumber = AccountType.getNormalizedAccount(IBAN); if (accountService.checkIfIsMainAccountHolderCheckFrozen(normalizedAccountNumber, customerId)) { switch (AccountType.getAccountType(IBAN)) { case CREDIT: creditCardCloseService.closeCreditCard(accountService.getAccountBeanByAccountNumber(normalizedAccountNumber).getAccountId()); break; case SAVING: accountSavingCloseService.closeAccount(normalizedAccountNumber); break; default: accountCloseService.closeAccount(IBAN, customerId); break; } } else { throw new NotAuthorizedException("Not Authorized"); } } public AccountAmountProjection getBalance(String authToken, String IBAN) throws NotAuthorizedException, InvalidParamValueException { if (AuthenticationService.instance.isCustomer(authToken)) { int customerId = (Integer) AuthenticationService.instance.getObject(authToken, AuthenticationService.USER_ID); if (accountService.checkIfAccountHolder(IBAN, customerId)) { return accountAmountService.getBalance(accountService.getAccountBeanByAccountNumber(IBAN).getAccountId()); } } else { boolean isAdministrativeEmployee = (Boolean) AuthenticationService.instance.getObject(authToken, AuthenticationService.HAS_ADMINISTRATIVE_ACCESS); if (isAdministrativeEmployee) { return accountAmountService.getBalance(accountService.getAccountBeanByAccountNumber(IBAN).getAccountId()); } } throw new NotAuthorizedException("Not Authorized"); } public void setOverdraftLimit(String authToken, String iBAN, double overdraftLimit) throws NotAuthorizedException, InvalidParamValueException, AccountFrozenException, NotAllowedException { int customerId = (Integer) AuthenticationService.instance.getObject(authToken, AuthenticationService.USER_ID); if (accountService.checkIfIsMainAccountHolderCheckFrozen(iBAN, customerId)) { accountService.checkMinor(iBAN); overdraftLimitService.setOverdraft(iBAN, overdraftLimit); } else { throw new NotAuthorizedException("Not Authorized"); } } public AccountOverdraftLimitProjection getOverdraftLimit(String authToken, String iBAN) throws NotAuthorizedException, InvalidParamValueException { if (AuthenticationService.instance.isCustomer(authToken)) { int customerId = (Integer) AuthenticationService.instance.getObject(authToken, AuthenticationService.USER_ID); if (accountService.checkIfIsMainAccountHolder(iBAN, customerId)) { return overdraftLimitService.getOverdraft(iBAN); } } else { boolean isAdministrativeEmployee = (Boolean) AuthenticationService.instance.getObject(authToken, AuthenticationService.HAS_ADMINISTRATIVE_ACCESS); if (isAdministrativeEmployee) { return overdraftLimitService.getOverdraft(iBAN); } } throw new NotAuthorizedException("Not Authorized"); } public void setFreezeUserAccount(String authToken, String username, boolean freeze) throws NotAuthorizedException, InvalidParamValueException, NoEffectException { boolean isAdmin = (Boolean) AuthenticationService.instance.getObject(authToken, AuthenticationService.HAS_ADMINISTRATIVE_ACCESS); if (isAdmin) { accountFreezeService.freezeAccount(customerService.getCustomerBeanByUsername(username).getCustomerId(), freeze); } else { throw new NotAuthorizedException("Not Authorized"); } } public void setTransferLimit(String authToken, String iBAN, BigDecimal transferLimit) throws InvalidParamValueException, AccountFrozenException, NotAuthorizedException { int customerId = (Integer) AuthenticationService.instance.getObject(authToken, AuthenticationService.USER_ID); if (accountService.checkIfIsMainAccountHolderCheckFrozen(iBAN, customerId)) { accountTransferLimitService.setTransferLimit(accountService.getAccountBeanByAccountNumberCheckFrozen(iBAN).getAccountId(), transferLimit); } else { throw new NotAuthorizedException("Not Authorized"); } } public AccountOpenProjection openAccount(String name, String surname, String initials, Date date, String ssn, String address, String telephoneNumber, String email, String username, String password, String type, String[] guardians) throws NotAuthorizedException, InvalidParamValueException, AccountFrozenException { return accountOpenService.openAccount(name, surname, initials, date, ssn, address, telephoneNumber, email, username, password, type, guardians); } }
UTF-8
Java
9,042
java
AccountController.java
Java
[]
null
[]
package com.bank.controller; import com.bank.exception.*; import com.bank.projection.account.AccountAmountProjection; import com.bank.projection.account.AccountOpenProjection; import com.bank.projection.account.AccountOverdraftLimitProjection; import com.bank.service.AuthenticationService; import com.bank.service.account.*; import com.bank.service.account.accountsaving.AccountSavingCloseService; import com.bank.service.creditcard.CreditCardCloseService; import com.bank.service.customer.CustomerService; import com.bank.service.overdraft.OverdraftLimitService; import com.bank.util.AccountType; import com.bank.util.Constants; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.math.BigDecimal; import java.sql.Date; @Service public class AccountController { @Autowired private AccountService accountService; @Autowired private AccountOpenService accountOpenService; @Autowired private AccountCloseService accountCloseService; @Autowired private AccountSavingCloseService accountSavingCloseService; @Autowired private CreditCardCloseService creditCardCloseService; @Autowired private AccountAmountService accountAmountService; @Autowired private OverdraftLimitService overdraftLimitService; @Autowired private AccountFreezeService accountFreezeService; @Autowired private AccountTransferLimitService accountTransferLimitService; @Autowired private CustomerService customerService; public AccountOpenProjection openAccount(String name, String surname, String initials, Date date, String ssn, String address, String telephoneNumber, String email, String username, String password) throws InvalidParamValueException, NotAuthorizedException { try { return openAccount(name, surname, initials, date, ssn, address, telephoneNumber, email, username, password, Constants.ACCOUNT_TYPE_REGULAR, new String[]{}); } catch (AccountFrozenException e) { //new accounts without guardians can not throw accountFrozenException } throw new IllegalStateException("FrozenAccountException during opening new account"); } public AccountOpenProjection openAdditionalAccount(String authToken) throws NotAuthorizedException, AccountFrozenException, NotAllowedException { if (AuthenticationService.instance.isCustomer(authToken)) { int customerId = (Integer) AuthenticationService.instance.getObject(authToken, AuthenticationService.USER_ID); if ((Boolean) AuthenticationService.instance.getObject(authToken, AuthenticationService.IS_MINOR)) { throw new NotAllowedException("Not Authorized"); } return accountOpenService.openAdditionalAccount(customerId); } else { throw new NotAuthorizedException("Not Authorized"); } } public void closeAccount(String authToken, String IBAN) throws InvalidParamValueException, NotAuthorizedException, AccountFrozenException { int customerId = (Integer) AuthenticationService.instance.getObject(authToken, AuthenticationService.USER_ID); String normalizedAccountNumber = AccountType.getNormalizedAccount(IBAN); if (accountService.checkIfIsMainAccountHolderCheckFrozen(normalizedAccountNumber, customerId)) { switch (AccountType.getAccountType(IBAN)) { case CREDIT: creditCardCloseService.closeCreditCard(accountService.getAccountBeanByAccountNumber(normalizedAccountNumber).getAccountId()); break; case SAVING: accountSavingCloseService.closeAccount(normalizedAccountNumber); break; default: accountCloseService.closeAccount(IBAN, customerId); break; } } else { throw new NotAuthorizedException("Not Authorized"); } } public AccountAmountProjection getBalance(String authToken, String IBAN) throws NotAuthorizedException, InvalidParamValueException { if (AuthenticationService.instance.isCustomer(authToken)) { int customerId = (Integer) AuthenticationService.instance.getObject(authToken, AuthenticationService.USER_ID); if (accountService.checkIfAccountHolder(IBAN, customerId)) { return accountAmountService.getBalance(accountService.getAccountBeanByAccountNumber(IBAN).getAccountId()); } } else { boolean isAdministrativeEmployee = (Boolean) AuthenticationService.instance.getObject(authToken, AuthenticationService.HAS_ADMINISTRATIVE_ACCESS); if (isAdministrativeEmployee) { return accountAmountService.getBalance(accountService.getAccountBeanByAccountNumber(IBAN).getAccountId()); } } throw new NotAuthorizedException("Not Authorized"); } public void setOverdraftLimit(String authToken, String iBAN, double overdraftLimit) throws NotAuthorizedException, InvalidParamValueException, AccountFrozenException, NotAllowedException { int customerId = (Integer) AuthenticationService.instance.getObject(authToken, AuthenticationService.USER_ID); if (accountService.checkIfIsMainAccountHolderCheckFrozen(iBAN, customerId)) { accountService.checkMinor(iBAN); overdraftLimitService.setOverdraft(iBAN, overdraftLimit); } else { throw new NotAuthorizedException("Not Authorized"); } } public AccountOverdraftLimitProjection getOverdraftLimit(String authToken, String iBAN) throws NotAuthorizedException, InvalidParamValueException { if (AuthenticationService.instance.isCustomer(authToken)) { int customerId = (Integer) AuthenticationService.instance.getObject(authToken, AuthenticationService.USER_ID); if (accountService.checkIfIsMainAccountHolder(iBAN, customerId)) { return overdraftLimitService.getOverdraft(iBAN); } } else { boolean isAdministrativeEmployee = (Boolean) AuthenticationService.instance.getObject(authToken, AuthenticationService.HAS_ADMINISTRATIVE_ACCESS); if (isAdministrativeEmployee) { return overdraftLimitService.getOverdraft(iBAN); } } throw new NotAuthorizedException("Not Authorized"); } public void setFreezeUserAccount(String authToken, String username, boolean freeze) throws NotAuthorizedException, InvalidParamValueException, NoEffectException { boolean isAdmin = (Boolean) AuthenticationService.instance.getObject(authToken, AuthenticationService.HAS_ADMINISTRATIVE_ACCESS); if (isAdmin) { accountFreezeService.freezeAccount(customerService.getCustomerBeanByUsername(username).getCustomerId(), freeze); } else { throw new NotAuthorizedException("Not Authorized"); } } public void setTransferLimit(String authToken, String iBAN, BigDecimal transferLimit) throws InvalidParamValueException, AccountFrozenException, NotAuthorizedException { int customerId = (Integer) AuthenticationService.instance.getObject(authToken, AuthenticationService.USER_ID); if (accountService.checkIfIsMainAccountHolderCheckFrozen(iBAN, customerId)) { accountTransferLimitService.setTransferLimit(accountService.getAccountBeanByAccountNumberCheckFrozen(iBAN).getAccountId(), transferLimit); } else { throw new NotAuthorizedException("Not Authorized"); } } public AccountOpenProjection openAccount(String name, String surname, String initials, Date date, String ssn, String address, String telephoneNumber, String email, String username, String password, String type, String[] guardians) throws NotAuthorizedException, InvalidParamValueException, AccountFrozenException { return accountOpenService.openAccount(name, surname, initials, date, ssn, address, telephoneNumber, email, username, password, type, guardians); } }
9,042
0.669432
0.669432
178
49.797752
45.983433
192
false
false
0
0
0
0
0
0
0.837079
false
false
6