blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
listlengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
131 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
32 values
content
stringlengths
3
9.45M
authors
listlengths
1
1
author_id
stringlengths
0
313
3bd564e23d2003e52435189171fd5bb2d60973c4
1cef0267f8b24cb59b5fed3d0f95030d8da4e59b
/proxy/backend/type/opengauss/src/main/java/org/apache/shardingsphere/proxy/backend/opengauss/connector/jdbc/statement/OpenGaussStatementMemoryStrictlyFetchSizeSetter.java
ee0ba5d7c182b8bf30154705f5d857dff2f78eab
[ "Apache-2.0" ]
permissive
apache/shardingsphere
4e69d07ad082ed3d1269e113d66421f67baa1f02
5ad75d38ab4fcf169a1a4704be4e671200d02e4c
refs/heads/master
2023-09-02T15:56:04.469891
2023-09-02T15:20:38
2023-09-02T15:20:38
49,876,476
9,157
3,758
Apache-2.0
2023-09-14T14:45:41
2016-01-18T12:49:26
Java
UTF-8
Java
false
false
1,760
java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.shardingsphere.proxy.backend.opengauss.connector.jdbc.statement; import org.apache.shardingsphere.proxy.backend.connector.jdbc.statement.StatementMemoryStrictlyFetchSizeSetter; import org.apache.shardingsphere.proxy.backend.postgresql.connector.jdbc.statement.PostgreSQLStatementMemoryStrictlyFetchSizeSetter; import java.sql.SQLException; import java.sql.Statement; /** * Statement memory strictly fetch size setter for openGauss. */ public final class OpenGaussStatementMemoryStrictlyFetchSizeSetter implements StatementMemoryStrictlyFetchSizeSetter { private final PostgreSQLStatementMemoryStrictlyFetchSizeSetter delegated = new PostgreSQLStatementMemoryStrictlyFetchSizeSetter(); @Override public void setFetchSize(final Statement statement) throws SQLException { delegated.setFetchSize(statement); } @Override public String getDatabaseType() { return "openGauss"; } }
d779dfa03896f1fdb66cb7ed6801a6f468619620
295ae6cbc7dee849c4ed47d9a4ad23a300be26ac
/hazelcast-jet-core/src/main/java/com/hazelcast/jet/impl/connector/ReadMapOrCacheP.java
4a63b8e9eca86e4d665049c6e00b6cf37ec42365
[ "Apache-2.0" ]
permissive
gorank/hazelcast-jet
390762736bebaf4f1487a45cab59060eeeae7a03
40f1f90662cab7c520efdaf807dc93fb729be0d3
refs/heads/master
2020-08-11T07:43:10.020465
2019-10-11T20:46:32
2019-10-11T20:46:32
214,519,591
0
0
Apache-2.0
2019-10-11T20:02:33
2019-10-11T20:02:32
null
UTF-8
Java
false
false
25,262
java
/* * Copyright (c) 2008-2019, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.jet.impl.connector; import com.hazelcast.cache.impl.CacheEntryIterationResult; import com.hazelcast.cache.impl.CacheProxy; import com.hazelcast.cache.impl.operation.CacheEntryIteratorOperation; import com.hazelcast.client.cache.impl.ClientCacheProxy; import com.hazelcast.client.impl.clientside.HazelcastClientInstanceImpl; import com.hazelcast.client.impl.clientside.HazelcastClientProxy; import com.hazelcast.client.impl.protocol.ClientMessage; import com.hazelcast.client.impl.protocol.codec.CacheIterateEntriesCodec; import com.hazelcast.client.impl.protocol.codec.MapFetchEntriesCodec; import com.hazelcast.client.impl.protocol.codec.MapFetchWithQueryCodec; import com.hazelcast.client.proxy.ClientMapProxy; import com.hazelcast.client.spi.impl.ClientInvocation; import com.hazelcast.client.spi.impl.ClientInvocationFuture; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.ICompletableFuture; import com.hazelcast.core.Partition; import com.hazelcast.instance.HazelcastInstanceImpl; import com.hazelcast.internal.serialization.InternalSerializationService; import com.hazelcast.jet.JetException; import com.hazelcast.jet.RestartableException; import com.hazelcast.jet.core.AbstractProcessor; import com.hazelcast.jet.core.Processor; import com.hazelcast.jet.core.ProcessorMetaSupplier; import com.hazelcast.jet.core.ProcessorSupplier; import com.hazelcast.jet.core.processor.SourceProcessors; import com.hazelcast.jet.function.FunctionEx; import com.hazelcast.jet.function.ToIntFunctionEx; import com.hazelcast.jet.impl.JetService; import com.hazelcast.jet.impl.MigrationWatcher; import com.hazelcast.jet.impl.util.Util; import com.hazelcast.map.impl.LazyMapEntry; import com.hazelcast.map.impl.iterator.AbstractCursor; import com.hazelcast.map.impl.iterator.MapEntriesWithCursor; import com.hazelcast.map.impl.operation.MapOperation; import com.hazelcast.map.impl.operation.MapOperationProvider; import com.hazelcast.map.impl.proxy.MapProxyImpl; import com.hazelcast.map.impl.query.Query; import com.hazelcast.map.impl.query.QueryResult; import com.hazelcast.map.impl.query.QueryResultRow; import com.hazelcast.map.impl.query.ResultSegment; import com.hazelcast.nio.Address; import com.hazelcast.nio.serialization.Data; import com.hazelcast.nio.serialization.HazelcastSerializationException; import com.hazelcast.projection.Projection; import com.hazelcast.query.Predicate; import com.hazelcast.spi.InternalCompletableFuture; import com.hazelcast.spi.Operation; import com.hazelcast.spi.OperationService; import com.hazelcast.util.IterationType; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.function.BooleanSupplier; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.IntStream; import static com.hazelcast.client.HazelcastClient.newHazelcastClient; import static com.hazelcast.jet.impl.util.ExceptionUtil.peel; import static com.hazelcast.jet.impl.util.ExceptionUtil.rethrow; import static com.hazelcast.jet.impl.util.ImdgUtil.asClientConfig; import static com.hazelcast.jet.impl.util.Util.processorToPartitions; import static java.util.stream.Collectors.groupingBy; import static java.util.stream.Collectors.mapping; import static java.util.stream.Collectors.toList; /** * Private API, see methods in {@link SourceProcessors}. * <p> * The number of Hazelcast partitions should be configured to at least * {@code localParallelism * clusterSize}, otherwise some processors will * have no partitions assigned to them. */ public final class ReadMapOrCacheP<F extends ICompletableFuture, B, R> extends AbstractProcessor { private static final int MAX_FETCH_SIZE = 16384; private final Reader<F, B, R> reader; private final int[] partitionIds; private final BooleanSupplier migrationWatcher; private final int[] readOffsets; private F[] readFutures; // currently emitted batch, its iterating position and partitionId private List<R> currentBatch = Collections.emptyList(); private int currentBatchPosition; private int currentPartitionIndex = -1; private int numCompletedPartitions; private ReadMapOrCacheP( @Nonnull Reader<F, B, R> reader, @Nonnull int[] partitionIds, @Nonnull BooleanSupplier migrationWatcher ) { this.reader = reader; this.partitionIds = partitionIds; this.migrationWatcher = migrationWatcher; readOffsets = new int[partitionIds.length]; Arrays.fill(readOffsets, Integer.MAX_VALUE); } @Override public boolean complete() { if (readFutures == null) { initialRead(); } while (emitResultSet()) { if (!tryGetNextResultSet()) { return numCompletedPartitions == partitionIds.length; } } return false; } @SuppressWarnings("unchecked") private void initialRead() { readFutures = (F[]) new ICompletableFuture[partitionIds.length]; for (int i = 0; i < readFutures.length; i++) { readFutures[i] = reader.readBatch(partitionIds[i], Integer.MAX_VALUE); } } private boolean emitResultSet() { checkMigration(); for (; currentBatchPosition < currentBatch.size(); currentBatchPosition++) { Object result = reader.toObject(currentBatch.get(currentBatchPosition)); if (result == null) { // element was filtered out by the predicate (?) continue; } if (!tryEmit(result)) { return false; } } // we're done with the current batch return true; } private boolean tryGetNextResultSet() { while (currentBatch.size() == currentBatchPosition && ++currentPartitionIndex < partitionIds.length) { if (readOffsets[currentPartitionIndex] < 0) { // partition is completed assert readFutures[currentPartitionIndex] == null : "future not null"; continue; } F future = readFutures[currentPartitionIndex]; if (!future.isDone()) { // data for partition not yet available continue; } B result = toBatchResult(future); int nextIndex = reader.toNextIndex(result); if (nextIndex < 0) { numCompletedPartitions++; } else { assert !currentBatch.isEmpty() : "empty but not terminal batch"; } currentBatch = reader.toRecordSet(result); currentBatchPosition = 0; readOffsets[currentPartitionIndex] = nextIndex; // make another read on the same partition readFutures[currentPartitionIndex] = readOffsets[currentPartitionIndex] >= 0 ? reader.readBatch(partitionIds[currentPartitionIndex], readOffsets[currentPartitionIndex]) : null; } if (currentPartitionIndex == partitionIds.length) { currentPartitionIndex = -1; return false; } return true; } private B toBatchResult(F future) { B result; try { result = reader.toBatchResult(future); } catch (ExecutionException e) { Throwable ex = peel(e); if (ex instanceof HazelcastSerializationException) { throw new JetException("Serialization error when reading the map: are the key, value, " + "predicate and projection classes visible to IMDG? You need to use User Code " + "Deployment, adding the classes to JetConfig isn't enough", e); } else { throw rethrow(ex); } } catch (InterruptedException e) { throw rethrow(e); } return result; } private void checkMigration() { if (migrationWatcher.getAsBoolean()) { throw new RestartableException("Partition migration detected"); } } static class LocalProcessorMetaSupplier<F extends ICompletableFuture, B, R> implements ProcessorMetaSupplier { private static final long serialVersionUID = 1L; private final FunctionEx<HazelcastInstance, Reader<F, B, R>> readerSupplier; private transient Map<Address, List<Integer>> addrToPartitions; LocalProcessorMetaSupplier(@Nonnull FunctionEx<HazelcastInstance, Reader<F, B, R>> readerSupplier) { this.readerSupplier = readerSupplier; } @Override public void init(@Nonnull ProcessorMetaSupplier.Context context) { Set<Partition> partitions = context.jetInstance().getHazelcastInstance().getPartitionService().getPartitions(); addrToPartitions = partitions.stream() .collect(groupingBy( p -> p.getOwner().getAddress(), mapping(Partition::getPartitionId, toList()))); } @Override @Nonnull public Function<Address, ProcessorSupplier> get(@Nonnull List<Address> addresses) { return address -> new LocalProcessorSupplier<>(readerSupplier, addrToPartitions.get(address)); } } private static final class LocalProcessorSupplier<F extends ICompletableFuture, B, R> implements ProcessorSupplier { static final long serialVersionUID = 1L; private final Function<HazelcastInstance, Reader<F, B, R>> readerSupplier; private final List<Integer> memberPartitions; private transient BooleanSupplier migrationWatcher; private transient HazelcastInstanceImpl hzInstance; private LocalProcessorSupplier(Function<HazelcastInstance, Reader<F, B, R>> readerSupplier, List<Integer> memberPartitions) { this.readerSupplier = readerSupplier; this.memberPartitions = memberPartitions; } @Override public void init(@Nonnull Context context) { hzInstance = (HazelcastInstanceImpl) context.jetInstance().getHazelcastInstance(); JetService jetService = hzInstance.node.nodeEngine.getService(JetService.SERVICE_NAME); migrationWatcher = jetService.getSharedMigrationWatcher().createWatcher(); } @Override @Nonnull public List<Processor> get(int count) { return processorToPartitions(count, memberPartitions).values().stream() .map(partitions -> partitions.stream().mapToInt(Integer::intValue).toArray()) .map(partitions -> new ReadMapOrCacheP<>(readerSupplier.apply(hzInstance), partitions, migrationWatcher)) .collect(toList()); } } static class RemoteProcessorSupplier<F extends ICompletableFuture, B, R> implements ProcessorSupplier { static final long serialVersionUID = 1L; private final String clientXml; private final FunctionEx<HazelcastInstance, Reader<F, B, R>> readerSupplier; private transient HazelcastClientProxy client; private transient MigrationWatcher migrationWatcher; private transient int totalParallelism; private transient int baseIndex; RemoteProcessorSupplier( @Nonnull String clientXml, FunctionEx<HazelcastInstance, Reader<F, B, R>> readerSupplier ) { this.clientXml = clientXml; this.readerSupplier = readerSupplier; } @Override public void init(@Nonnull Context context) { client = (HazelcastClientProxy) newHazelcastClient(asClientConfig(clientXml)); migrationWatcher = new MigrationWatcher(client); totalParallelism = context.totalParallelism(); baseIndex = context.memberIndex() * context.localParallelism(); } @Override public void close(Throwable error) { if (migrationWatcher != null) { migrationWatcher.deregister(); } if (client != null) { client.shutdown(); } } @Override @Nonnull public List<Processor> get(int count) { int remotePartitionCount = client.client.getClientPartitionService().getPartitionCount(); BooleanSupplier watcherInstance = migrationWatcher.createWatcher(); return IntStream.range(0, count) .mapToObj(i -> { int[] partitionIds = Util.roundRobinPart(remotePartitionCount, totalParallelism, baseIndex + i); return new ReadMapOrCacheP<>(readerSupplier.apply(client), partitionIds, watcherInstance); }) .collect(Collectors.toList()); } } /** * Stateless interface to read a map/cache. * * @param <F> type of the result future * @param <B> type of the batch object * @param <R> type of the record */ abstract static class Reader<F extends ICompletableFuture, B, R> { protected final String objectName; protected InternalSerializationService serializationService; private final ToIntFunctionEx<B> toNextIndexFn; private FunctionEx<B, List<R>> toRecordSetFn; Reader(@Nonnull String objectName, @Nonnull ToIntFunctionEx<B> toNextIndexFn, @Nonnull FunctionEx<B, List<R>> toRecordSetFn) { this.objectName = objectName; this.toNextIndexFn = toNextIndexFn; this.toRecordSetFn = toRecordSetFn; } @Nonnull abstract F readBatch(int partitionId, int offset); @Nonnull @SuppressWarnings("unchecked") B toBatchResult(@Nonnull F future) throws ExecutionException, InterruptedException { return (B) future.get(); } final int toNextIndex(@Nonnull B result) { return toNextIndexFn.applyAsInt(result); } @Nonnull final List<R> toRecordSet(@Nonnull B result) { return toRecordSetFn.apply(result); } @Nullable abstract Object toObject(@Nonnull R record); } static class LocalCacheReader extends Reader< InternalCompletableFuture<CacheEntryIterationResult>, CacheEntryIterationResult, Entry<Data, Data> > { private final CacheProxy cacheProxy; LocalCacheReader(HazelcastInstance hzInstance, @Nonnull String cacheName) { super(cacheName, CacheEntryIterationResult::getTableIndex, CacheEntryIterationResult::getEntries); this.cacheProxy = (CacheProxy) hzInstance.getCacheManager().getCache(cacheName); this.serializationService = (InternalSerializationService) cacheProxy.getNodeEngine().getSerializationService(); } @Nonnull @Override public InternalCompletableFuture<CacheEntryIterationResult> readBatch(int partitionId, int offset) { Operation op = new CacheEntryIteratorOperation(cacheProxy.getPrefixedName(), offset, MAX_FETCH_SIZE); //no access to CacheOperationProvider, have to be explicit OperationService operationService = cacheProxy.getOperationService(); return operationService.invokeOnPartition(cacheProxy.getServiceName(), op, partitionId); } @Nullable @Override public Object toObject(@Nonnull Entry<Data, Data> dataEntry) { return new LazyMapEntry(dataEntry.getKey(), dataEntry.getValue(), serializationService); } } static class RemoteCacheReader extends Reader< ClientInvocationFuture, CacheIterateEntriesCodec.ResponseParameters, Entry<Data, Data> > { private final ClientCacheProxy clientCacheProxy; RemoteCacheReader(HazelcastInstance hzInstance, @Nonnull String cacheName) { super(cacheName, r -> r.tableIndex, r -> r.entries ); this.clientCacheProxy = (ClientCacheProxy) hzInstance.getCacheManager().getCache(cacheName); this.serializationService = clientCacheProxy.getContext().getSerializationService(); } @Nonnull @Override public ClientInvocationFuture readBatch(int partitionId, int offset) { String name = clientCacheProxy.getPrefixedName(); ClientMessage request = CacheIterateEntriesCodec.encodeRequest(name, partitionId, offset, MAX_FETCH_SIZE); HazelcastClientInstanceImpl client = (HazelcastClientInstanceImpl) clientCacheProxy.getContext() .getHazelcastInstance(); return new ClientInvocation(client, request, name, partitionId).invoke(); } @Nonnull @Override public CacheIterateEntriesCodec.ResponseParameters toBatchResult(@Nonnull ClientInvocationFuture future) throws ExecutionException, InterruptedException { return CacheIterateEntriesCodec.decodeResponse(future.get()); } @Nullable @Override public Object toObject(@Nonnull Entry<Data, Data> dataEntry) { return new LazyMapEntry(dataEntry.getKey(), dataEntry.getValue(), serializationService); } } static class LocalMapReader extends Reader< InternalCompletableFuture<MapEntriesWithCursor>, MapEntriesWithCursor, Entry<Data, Data> > { private final MapProxyImpl mapProxyImpl; LocalMapReader(@Nonnull HazelcastInstance hzInstance, @Nonnull String mapName) { super(mapName, AbstractCursor::getNextTableIndexToReadFrom, AbstractCursor::getBatch); this.mapProxyImpl = (MapProxyImpl) hzInstance.getMap(mapName); this.serializationService = ((HazelcastInstanceImpl) hzInstance).getSerializationService(); } @Nonnull @Override public InternalCompletableFuture<MapEntriesWithCursor> readBatch(int partitionId, int offset) { MapOperationProvider operationProvider = mapProxyImpl.getOperationProvider(); Operation op = operationProvider.createFetchEntriesOperation(objectName, offset, MAX_FETCH_SIZE); return mapProxyImpl.getOperationService().invokeOnPartition(mapProxyImpl.getServiceName(), op, partitionId); } @Nullable @Override public Object toObject(@Nonnull Entry<Data, Data> dataEntry) { return new LazyMapEntry(dataEntry.getKey(), dataEntry.getValue(), serializationService); } } static class LocalMapQueryReader extends Reader< InternalCompletableFuture<ResultSegment>, ResultSegment, QueryResultRow > { private final Predicate predicate; private final Projection projection; private final MapProxyImpl mapProxyImpl; LocalMapQueryReader( @Nonnull HazelcastInstance hzInstance, @Nonnull String mapName, @Nonnull Predicate predicate, @Nonnull Projection projection ) { super(mapName, ResultSegment::getNextTableIndexToReadFrom, r -> ((QueryResult) r.getResult()).getRows() ); this.predicate = predicate; this.projection = projection; this.mapProxyImpl = (MapProxyImpl) hzInstance.getMap(mapName); this.serializationService = ((HazelcastInstanceImpl) hzInstance).getSerializationService(); } @Nonnull @Override public InternalCompletableFuture<ResultSegment> readBatch(int partitionId, int offset) { MapOperationProvider operationProvider = mapProxyImpl.getOperationProvider(); MapOperation op = operationProvider.createFetchWithQueryOperation( objectName, offset, MAX_FETCH_SIZE, Query.of() .mapName(objectName) .iterationType(IterationType.VALUE) .predicate(predicate) .projection(projection) .build() ); return mapProxyImpl.getOperationService().invokeOnPartition(mapProxyImpl.getServiceName(), op, partitionId); } @Nullable @Override public Object toObject(@Nonnull QueryResultRow record) { return serializationService.toObject(record.getValue()); } } static class RemoteMapReader extends Reader< ClientInvocationFuture, MapFetchEntriesCodec.ResponseParameters, Entry<Data, Data> > { private final ClientMapProxy clientMapProxy; RemoteMapReader(@Nonnull HazelcastInstance hzInstance, @Nonnull String mapName) { super(mapName, r -> r.tableIndex, r -> r.entries); this.clientMapProxy = (ClientMapProxy) hzInstance.getMap(mapName); this.serializationService = clientMapProxy.getContext().getSerializationService(); } @Nonnull @Override public ClientInvocationFuture readBatch(int partitionId, int offset) { ClientMessage request = MapFetchEntriesCodec.encodeRequest(objectName, partitionId, offset, MAX_FETCH_SIZE); ClientInvocation clientInvocation = new ClientInvocation( (HazelcastClientInstanceImpl) clientMapProxy.getContext().getHazelcastInstance(), request, objectName, partitionId ); return clientInvocation.invoke(); } @Nonnull @Override public MapFetchEntriesCodec.ResponseParameters toBatchResult(@Nonnull ClientInvocationFuture future) throws ExecutionException, InterruptedException { return MapFetchEntriesCodec.decodeResponse(future.get()); } @Nullable @Override public Entry<Data, Data> toObject(@Nonnull Entry<Data, Data> entry) { return new LazyMapEntry<>(entry.getKey(), entry.getValue(), serializationService); } } static class RemoteMapQueryReader extends Reader< ClientInvocationFuture, MapFetchWithQueryCodec.ResponseParameters, Data> { private final Predicate predicate; private final Projection projection; private final ClientMapProxy clientMapProxy; RemoteMapQueryReader( @Nonnull HazelcastInstance hzInstance, @Nonnull String mapName, @Nonnull Predicate predicate, @Nonnull Projection projection ) { super(mapName, r -> r.nextTableIndexToReadFrom, r -> r.results); this.predicate = predicate; this.projection = projection; this.clientMapProxy = (ClientMapProxy) hzInstance.getMap(mapName); this.serializationService = clientMapProxy.getContext().getSerializationService(); } @Nonnull @Override public ClientInvocationFuture readBatch(int partitionId, int offset) { ClientMessage request = MapFetchWithQueryCodec.encodeRequest(objectName, offset, MAX_FETCH_SIZE, serializationService.toData(projection), serializationService.toData(predicate)); ClientInvocation clientInvocation = new ClientInvocation( (HazelcastClientInstanceImpl) clientMapProxy.getContext().getHazelcastInstance(), request, objectName, partitionId ); return clientInvocation.invoke(); } @Nonnull @Override public MapFetchWithQueryCodec.ResponseParameters toBatchResult(@Nonnull ClientInvocationFuture future) throws ExecutionException, InterruptedException { return MapFetchWithQueryCodec.decodeResponse(future.get()); } @Nullable @Override public Object toObject(@Nonnull Data data) { return serializationService.toObject(data); } } }
9bbba054b8f59a38ca2ff36e663aeb29ee54497b
f3b7857ab4c29ec7b6179fa8b7e50d8001cc61c2
/mkcomapp/gen/sd/mkcom/app/R.java
b38094c285990a6a9f8edf14707dd04dac8c225a
[]
no_license
sahajdhingra26/android
23f59fcd5c1971a4a21b4f3e56d3551ff8c9fa21
089fdb89a3d32d687dbbf4987bc93578061fb81c
refs/heads/master
2021-01-12T07:19:01.328504
2016-12-20T09:38:39
2016-12-20T09:38:39
76,942,325
0
0
null
null
null
null
UTF-8
Java
false
false
16,135
java
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package sd.mkcom.app; public final class R { public static final class attr { } public static final class drawable { public static final int accessories=0x7f020000; public static final int acer=0x7f020001; public static final int acerdpc=0x7f020002; public static final int acerlp1=0x7f020003; public static final int adapter1=0x7f020004; public static final int apple=0x7f020005; public static final int bg=0x7f020006; public static final int cable1=0x7f020007; public static final int cannon=0x7f020008; public static final int cannonprnt1=0x7f020009; public static final int cannonprnt2=0x7f02000a; public static final int carcharger1=0x7f02000b; public static final int carcharger2=0x7f02000c; public static final int carcharger3=0x7f02000d; public static final int compaq=0x7f02000e; public static final int compaqdpc=0x7f02000f; public static final int computer=0x7f020010; public static final int contact=0x7f020011; public static final int cover_mkc=0x7f020012; public static final int dell=0x7f020013; public static final int delldpc=0x7f020014; public static final int delllp1=0x7f020015; public static final int delllp2=0x7f020016; public static final int developer=0x7f020017; public static final int dlinkr1=0x7f020018; public static final int dlinkr2=0x7f020019; public static final int dlinkr3=0x7f02001a; public static final int dlinkswitch1=0x7f02001b; public static final int dlinkswitch2=0x7f02001c; public static final int dlinkswitch3=0x7f02001d; public static final int epson=0x7f02001e; public static final int externalhd=0x7f02001f; public static final int fujitsu=0x7f020020; public static final int graphiccrd1=0x7f020021; public static final int hcl=0x7f020022; public static final int hcldpc=0x7f020023; public static final int hd1=0x7f020024; public static final int hd2=0x7f020025; public static final int hd3=0x7f020026; public static final int hd4=0x7f020027; public static final int hdcase1=0x7f020028; public static final int hdcase2=0x7f020029; public static final int hdlp1=0x7f02002a; public static final int hdlp2=0x7f02002b; public static final int hdlp3=0x7f02002c; public static final int hdlp4=0x7f02002d; public static final int headdphone1=0x7f02002e; public static final int headdphone2=0x7f02002f; public static final int headdphone4=0x7f020030; public static final int headphone3=0x7f020031; public static final int home_page_background=0x7f020032; public static final int hp=0x7f020033; public static final int hpdpc=0x7f020034; public static final int hplp1=0x7f020035; public static final int hplp2=0x7f020036; public static final int hplp3=0x7f020037; public static final int hppnl1=0x7f020038; public static final int hppnl2=0x7f020039; public static final int hppnl3=0x7f02003a; public static final int hppnl4=0x7f02003b; public static final int hppnl5=0x7f02003c; public static final int hppnl6=0x7f02003d; public static final int hppnl7=0x7f02003e; public static final int ibm=0x7f02003f; public static final int ic_launcher=0x7f020040; public static final int image=0x7f020041; public static final int ipad2case1=0x7f020042; public static final int ipad2case2=0x7f020043; public static final int ipad2case3=0x7f020044; public static final int ipad2case4=0x7f020045; public static final int ipad2case5=0x7f020046; public static final int ipadbackcvr1=0x7f020047; public static final int keyboardlogi=0x7f020048; public static final int keymoums1=0x7f020049; public static final int keymoums2=0x7f02004a; public static final int laptopbag1=0x7f02004b; public static final int laptopbag2=0x7f02004c; public static final int laptopbag3=0x7f02004d; public static final int laptopbag4=0x7f02004e; public static final int laptopbag5=0x7f02004f; public static final int laptopbag6=0x7f020050; public static final int laptopbag7=0x7f020051; public static final int laptopbag8=0x7f020052; public static final int lenovo=0x7f020053; public static final int lenovodpc=0x7f020054; public static final int lenovolp1=0x7f020055; public static final int logo=0x7f020056; public static final int mouseam1=0x7f020057; public static final int mouseam2=0x7f020058; public static final int mouseam3=0x7f020059; public static final int mouseam4=0x7f02005a; public static final int mouseam5=0x7f02005b; public static final int mouselogi1=0x7f02005c; public static final int mousems1=0x7f02005d; public static final int mousems2=0x7f02005e; public static final int mousetargus1=0x7f02005f; public static final int mulppt1=0x7f020060; public static final int networking=0x7f020061; public static final int norton1=0x7f020062; public static final int office1=0x7f020063; public static final int pd1=0x7f020064; public static final int pd2=0x7f020065; public static final int pd3=0x7f020066; public static final int pd4=0x7f020067; public static final int powerbar1=0x7f020068; public static final int powerstrip1=0x7f020069; public static final int powerstrip2=0x7f02006a; public static final int powerstrip3=0x7f02006b; public static final int pptremote1=0x7f02006c; public static final int quickheal1=0x7f02006d; public static final int quickheal2=0x7f02006e; public static final int quickheal3=0x7f02006f; public static final int quickheal4=0x7f020070; public static final int ram1=0x7f020071; public static final int ram2=0x7f020072; public static final int ram3=0x7f020073; public static final int ram4=0x7f020074; public static final int ram5=0x7f020075; public static final int ram6=0x7f020076; public static final int ram7=0x7f020077; public static final int ramlp1=0x7f020078; public static final int ramlp2=0x7f020079; public static final int ramlp3=0x7f02007a; public static final int ramlp4=0x7f02007b; public static final int ramlp5=0x7f02007c; public static final int ramlp6=0x7f02007d; public static final int ramlp7=0x7f02007e; public static final int samsung=0x7f02007f; public static final int softwares=0x7f020080; public static final int sonylp1=0x7f020081; public static final int speaker1=0x7f020082; public static final int speaker2=0x7f020083; public static final int tablet=0x7f020084; public static final int tally1=0x7f020085; public static final int toshiba=0x7f020086; public static final int toshibalp1=0x7f020087; public static final int toshibalp2=0x7f020088; public static final int toshibalp3=0x7f020089; public static final int toshibalp4=0x7f02008a; public static final int toshibalp5=0x7f02008b; public static final int toshibalp6=0x7f02008c; public static final int toshibalp7=0x7f02008d; public static final int ups1=0x7f02008e; public static final int usbbattery1=0x7f02008f; public static final int usbhub1=0x7f020090; public static final int usbhub2=0x7f020091; public static final int usbkeypad1=0x7f020092; public static final int vaio=0x7f020093; public static final int windows1=0x7f020094; public static final int windows2=0x7f020095; } public static final class id { public static final int RelativeLayout1=0x7f070025; public static final int button1=0x7f070001; public static final int button10=0x7f070012; public static final int button11=0x7f070013; public static final int button12=0x7f070014; public static final int button13=0x7f070015; public static final int button14=0x7f070016; public static final int button15=0x7f070017; public static final int button16=0x7f070018; public static final int button17=0x7f070026; public static final int button18=0x7f070027; public static final int button2=0x7f070002; public static final int button3=0x7f070000; public static final int button4=0x7f070005; public static final int button5=0x7f07000d; public static final int button6=0x7f07000e; public static final int button7=0x7f07000f; public static final int button8=0x7f070010; public static final int button9=0x7f070011; public static final int imageButton1=0x7f07001a; public static final int imageButton2=0x7f07001b; public static final int imageButton3=0x7f07001c; public static final int imageButton4=0x7f07001d; public static final int imageView1=0x7f070003; public static final int imageView2=0x7f070006; public static final int imageView3=0x7f070008; public static final int imageView4=0x7f07000a; public static final int imageView5=0x7f07000b; public static final int imageView6=0x7f07000c; public static final int imageView7=0x7f070020; public static final int imageView8=0x7f070022; public static final int imageView9=0x7f070023; public static final int menu_settings=0x7f070028; public static final int textView1=0x7f070004; public static final int textView2=0x7f070007; public static final int textView3=0x7f070009; public static final int textView4=0x7f070019; public static final int textView5=0x7f07001e; public static final int textView6=0x7f07001f; public static final int textView7=0x7f070021; public static final int textView8=0x7f070024; } public static final class layout { public static final int accessories=0x7f030000; public static final int acer=0x7f030001; public static final int acerlp=0x7f030002; public static final int activity_main=0x7f030003; public static final int adapter=0x7f030004; public static final int antivirus=0x7f030005; public static final int cable=0x7f030006; public static final int cableothacc=0x7f030007; public static final int cannonprnt=0x7f030008; public static final int carcharger=0x7f030009; public static final int compaq=0x7f03000a; public static final int computer=0x7f03000b; public static final int contact=0x7f03000c; public static final int dell=0x7f03000d; public static final int delllp=0x7f03000e; public static final int desktop=0x7f03000f; public static final int desktopacc=0x7f030010; public static final int developer=0x7f030011; public static final int dlinkrouter=0x7f030012; public static final int dlinkswitch=0x7f030013; public static final int externalhd=0x7f030014; public static final int graphiccard=0x7f030015; public static final int harddisk=0x7f030016; public static final int harddisklp=0x7f030017; public static final int hcl=0x7f030018; public static final int hdcasing=0x7f030019; public static final int headphone=0x7f03001a; public static final int home_page=0x7f03001b; public static final int hp=0x7f03001c; public static final int hplp=0x7f03001d; public static final int hppanel=0x7f03001e; public static final int ipad2case=0x7f03001f; public static final int ipadbackcvr=0x7f030020; public static final int keyboardlogitech=0x7f030021; public static final int keyboardmousems=0x7f030022; public static final int laptop=0x7f030023; public static final int laptopacc=0x7f030024; public static final int laptopbag=0x7f030025; public static final int lenovo=0x7f030026; public static final int lenovolp=0x7f030027; public static final int mkc=0x7f030028; public static final int mouseamkette=0x7f030029; public static final int mouselogitech=0x7f03002a; public static final int mousemicrosoft=0x7f03002b; public static final int mousetargus=0x7f03002c; public static final int msoffice=0x7f03002d; public static final int multemediappt=0x7f03002e; public static final int networking=0x7f03002f; public static final int norton=0x7f030030; public static final int operatingsystem=0x7f030031; public static final int otheracc=0x7f030032; public static final int pannel=0x7f030033; public static final int pendrive=0x7f030034; public static final int powerbar=0x7f030035; public static final int powerstrip=0x7f030036; public static final int pptremote=0x7f030037; public static final int printer=0x7f030038; public static final int quickheal=0x7f030039; public static final int ram=0x7f03003a; public static final int ramlp=0x7f03003b; public static final int router=0x7f03003c; public static final int softwares=0x7f03003d; public static final int sonylp=0x7f03003e; public static final int speaker=0x7f03003f; public static final int switch1=0x7f030040; public static final int tally=0x7f030041; public static final int toshibalp=0x7f030042; public static final int ups=0x7f030043; public static final int usbadapter=0x7f030044; public static final int usbbattery=0x7f030045; public static final int usbhub=0x7f030046; public static final int usbkeypad=0x7f030047; public static final int windows=0x7f030048; } public static final class menu { public static final int activity_main=0x7f060000; } public static final class string { public static final int app_name=0x7f040000; public static final int hello_world=0x7f040001; public static final int menu_settings=0x7f040002; } public static final class style { /** Base application theme, dependent on API level. This theme is replaced by AppBaseTheme from res/values-vXX/styles.xml on newer devices. Theme customizations available in newer API levels can go in res/values-vXX/styles.xml, while customizations related to backward-compatibility can go here. Base application theme for API 11+. This theme completely replaces AppBaseTheme from res/values/styles.xml on API 11+ devices. API 11 theme customizations can go here. Base application theme for API 14+. This theme completely replaces AppBaseTheme from BOTH res/values/styles.xml and res/values-v11/styles.xml on API 14+ devices. API 14 theme customizations can go here. */ public static final int AppBaseTheme=0x7f050000; /** Application theme. All customizations that are NOT specific to a particular API-level can go here. */ public static final int AppTheme=0x7f050001; } }
01651be42be0fb2dc32caa5a411bd3c1fd3bc3f8
bfc15119f72d4ac4baca84af74809bec3ae885fb
/Semi_KH/src/A0_cheol/Buyouu.java
21fd8e312f8edb9946ffbed3c32de45b61c9f1b2
[]
no_license
YoonMK/Semi_KH
d1e5e6d400cbb2f67dc8417e932344fe8261e148
7be7301e95f81921e6838869a685d8327d9dadf6
refs/heads/master
2020-12-24T12:34:59.552098
2016-11-08T06:35:46
2016-11-08T06:35:46
72,974,028
2
5
null
null
null
null
UHC
Java
false
false
2,150
java
package A0_cheol; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; public class Buyouu extends JFrame { JPanel GameUser = new JPanel(); JPanel GameUser2 = new JPanel(); JPanel NextView = new JPanel(); JPanel NextView2 = new JPanel(); JPanel NextPoint = new JPanel(); JPanel NextPoint2 = new JPanel(); JTextArea Conversation = new JTextArea(); JScrollPane ConScroll = new JScrollPane(Conversation); // JButton Out = new JButton(); JButton Ready = new JButton(); public Buyouu()//전체 크기의 패널. { super("♥세영이뿌네♥"); setBounds(20, 20, 920, 690); setLayout(null); /////게임창 유저1 GameUser.setBounds(5,20,280,600); GameUser.setBackground(Color.white); //게임창 유저 2 GameUser2.setBounds(620,20,280,600); GameUser2.setBackground(Color.white); //유저1 다음 나올 도형 NextView.setBounds(305,10,130,150); NextView.setBackground(Color.white); ////유저2 다음 나올 도형 NextView2.setBounds(470,10,130,150); NextView2.setBackground(Color.white); //유저1 점수 NextPoint.setBounds(305,170,200,60); NextPoint.setBackground(Color.white); //유저2 점수 NextPoint2.setBounds(400,240,200,60); NextPoint2.setBackground(Color.white); ////////////////////////////////////// //대화 ConScroll.setBounds(305,310,295,250); //////////////////////////////////// //버튼 Out.setBounds(305,570,130,50); Ready.setBounds(470,570,130,50); add(GameUser); add(GameUser2); add(NextView); add(NextView2); add(NextPoint); add(NextPoint2); add(ConScroll); add(Out); add(Ready); setVisible(true); setDefaultCloseOperation(EXIT_ON_CLOSE); } //////////////////////////////////////////////////// public static void main(String[] args) { // TODO Auto-generated method stub new Buyouu(); ////////////////////////////////////// } }
[ "Cheol@DESKTOP-QKPHBQB" ]
Cheol@DESKTOP-QKPHBQB
e62447d8cf6cd52f3b115ebef0c88717eb953273
b7c7754d582abd54e4fce7be2b2af6cc0405ac43
/src/main/java/com/alexcaranha/lib/com/musicg/math/quicksort/QuickSort.java
dd8e21bf0e97966097736be5de4d9948253d5e5b
[]
no_license
AlexCaranha/jQueryByHumming
b292cc9dd0c83927a2245b18e694e794b9fc1ef9
35bb60afdd17dfb0c0e41a43dc687fd459167f31
refs/heads/master
2021-11-29T13:56:49.923323
2014-07-16T13:16:35
2014-07-16T13:16:35
12,504,438
0
1
null
null
null
null
UTF-8
Java
false
false
135
java
package com.alexcaranha.lib.com.musicg.math.quicksort; public abstract class QuickSort{ public abstract int[] getSortIndexes(); }
[ "alexcaranha@alex-ubuntu" ]
alexcaranha@alex-ubuntu
5fd9cb1464c55685b2d49b8e06428dc1f9d7f891
034616292ef06c9ffb69f4bd2086c3541bb6ec28
/app/src/main/java/com/sglabs/medistant/elements/appointmentactivity/ApptScroll.java
ed2724f5ec2c29d4b9231c99c0b45c55382dc1fb
[]
no_license
ictsolved/medistant
e521ce2c766c48376f4755e55ef8a7a52ba705cf
3d4316301ca608962ef358b3fb364fd22a2b2f83
refs/heads/master
2021-05-14T02:46:31.700834
2018-01-17T14:00:00
2018-01-17T14:00:00
116,603,095
0
0
null
null
null
null
UTF-8
Java
false
false
557
java
package com.sglabs.medistant.elements.appointmentactivity; import android.widget.ScrollView; import android.content.Context; import android.util.AttributeSet; public class ApptScroll extends ScrollView { public ApptScroll(Context context, AttributeSet attrs) { super(context, attrs); } public ApptScroll(Context context) { super(context); } public ApptScroll(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public void onFinishInflate() { super.onFinishInflate(); } }
2162ec0e846a522e894dfebd6f08ff51e8d091a7
1a2a5accf70136d91cbc2c107524155ff3a3d69d
/FactoryPattern/src/org/mylearnings/factory/SecureConnectionFactory.java
30a1ceef21f20fa1aabd05f5856b36d71927abdf
[]
no_license
apundhir/learn_patterns
9d836fee66c72b836f15f97369abf7167935bcbc
2b3653df878225149bdc0b025dbcb9b4299c0c5b
refs/heads/master
2021-06-19T00:15:23.612569
2017-03-21T10:13:13
2017-03-21T10:13:13
22,551,963
0
0
null
null
null
null
UTF-8
Java
false
false
294
java
package org.mylearnings.factory; public class SecureConnectionFactory extends ConnectionFactory{ @Override protected Connection createConnection(String type) { if(type.equals("Oracle")){ return new OracleDbConnection(); } else return new MySqlConnectionClass(); } }
939f503e90930eee088d10d2b52e2bd94cc9a0a5
827bf064e482700d7ded2cd0a3147cb9657db883
/AndroidPOS/src/com/aadhk/restpos/d/bs.java
6a4642df7e97f7ac26d18f129b13d16765ab99c6
[]
no_license
cody0117/LearnAndroid
d30b743029f26568ccc6dda4313a9d3b70224bb6
02fd4d2829a0af8a1706507af4b626783524813e
refs/heads/master
2021-01-21T21:10:18.553646
2017-02-12T08:43:24
2017-02-12T08:43:24
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,552
java
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.aadhk.restpos.d; import android.widget.Toast; import com.aadhk.product.library.a.c; import com.aadhk.restpos.bean.POSPrinterSetting; import com.aadhk.restpos.g.u; import com.aadhk.restpos.util.f; import com.aadhk.restpos.util.q; import java.util.Map; // Referenced classes of package com.aadhk.restpos.d: // bq final class bs implements c { final bq a; private Map b; private bs(bq bq1) { a = bq1; super(); } bs(bq bq1, byte byte0) { this(bq1); } public final void a() { bq.a(a).setLogoName(""); com.aadhk.product.library.c.f.a(f.f); b = bq.b(a).b(bq.a(a).getId(), bq.a(a).getLogoName()); } public final void b() { String s = (String)b.get("serviceStatus"); if ("1".equals(s)) { com.aadhk.restpos.d.bq.f(a); Toast.makeText(bq.e(a), 0x7f0802c8, 1).show(); return; } if ("10".equals(s) || "11".equals(s)) { q.a(bq.e(a)); Toast.makeText(bq.e(a), 0x7f080246, 1).show(); return; } if ("9".equals(s)) { Toast.makeText(bq.e(a), 0x7f080248, 1).show(); return; } else { Toast.makeText(bq.e(a), 0x7f080247, 1).show(); return; } } }
071b6e59daa5c34948c75bf4a074ad77615624bc
129f58086770fc74c171e9c1edfd63b4257210f3
/src/testcases/CWE78_OS_Command_Injection/CWE78_OS_Command_Injection__PropertiesFile_09.java
1c43dea02766fa1f17a9dbd985701d522642abbb
[]
no_license
glopezGitHub/Android23
1bd0b6a6c7ce3c7439a74f1e4dcef2c4c0fac4ba
6215d0684c4fbdc7217ccfbedfccfca69824cc5e
refs/heads/master
2023-03-07T15:14:59.447795
2023-02-06T13:59:49
2023-02-06T13:59:49
6,856,387
0
3
null
2023-02-06T18:38:17
2012-11-25T22:04:23
Java
UTF-8
Java
false
false
7,070
java
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE78_OS_Command_Injection__PropertiesFile_09.java Label Definition File: CWE78_OS_Command_Injection.label.xml Template File: sources-sink-09.tmpl.java */ /* * @description * CWE: 78 OS Command Injection * BadSource: PropertiesFile Read data from a .properties file (in property named data) * GoodSource: A hardcoded string * BadSink: exec dynamic command execution with Runtime.getRuntime().exec() * Flow Variant: 09 Control flow: if(IO.static_final_t) and if(IO.static_final_f) * * */ package testcases.CWE78_OS_Command_Injection; import testcasesupport.*; import javax.servlet.http.*; import java.util.Properties; import java.io.FileInputStream; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; public class CWE78_OS_Command_Injection__PropertiesFile_09 extends AbstractTestCase { /* uses badsource and badsink */ public void bad() throws Throwable { String data; if(IO.static_final_t) { data = ""; /* Initialize data */ /* retrieve the property */ Properties props = new Properties(); FileInputStream finstr = null; try { finstr = new FileInputStream("../common/config.properties"); props.load(finstr); /* POTENTIAL FLAW: Read data from a .properties file */ data = props.getProperty("data"); } catch( IOException ioe ) { IO.logger.log(Level.WARNING, "Error with stream reading", ioe); } finally { /* Close stream reading object */ try { if( finstr != null ) { finstr.close(); } } catch( IOException ioe ) { IO.logger.log(Level.WARNING, "Error closing FileInputStream", ioe); } } } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ /* FIX: Use a hardcoded string */ data = "foo"; } String osCommand; if(System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) { /* running on Windows */ osCommand = "c:\\WINDOWS\\SYSTEM32\\cmd.exe /c dir "; } else { /* running on non-Windows */ osCommand = "/bin/ls "; } /* POTENTIAL FLAW: command injection */ Process p = Runtime.getRuntime().exec(osCommand + data); p.waitFor(); } /* goodG2B1() - use goodsource and badsink by changing IO.static_final_t to IO.static_final_f */ private void goodG2B1() throws Throwable { String data; if(IO.static_final_f) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ data = ""; /* Initialize data */ /* retrieve the property */ Properties props = new Properties(); FileInputStream finstr = null; try { finstr = new FileInputStream("../common/config.properties"); props.load(finstr); /* POTENTIAL FLAW: Read data from a .properties file */ data = props.getProperty("data"); } catch( IOException ioe ) { IO.logger.log(Level.WARNING, "Error with stream reading", ioe); } finally { /* Close stream reading object */ try { if( finstr != null ) { finstr.close(); } } catch( IOException ioe ) { IO.logger.log(Level.WARNING, "Error closing FileInputStream", ioe); } } } else { /* FIX: Use a hardcoded string */ data = "foo"; } String osCommand; if(System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) { /* running on Windows */ osCommand = "c:\\WINDOWS\\SYSTEM32\\cmd.exe /c dir "; } else { /* running on non-Windows */ osCommand = "/bin/ls "; } /* POTENTIAL FLAW: command injection */ Process p = Runtime.getRuntime().exec(osCommand + data); p.waitFor(); } /* goodG2B2() - use goodsource and badsink by reversing statements in if */ private void goodG2B2() throws Throwable { String data; if(IO.static_final_t) { /* FIX: Use a hardcoded string */ data = "foo"; } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ data = ""; /* Initialize data */ /* retrieve the property */ Properties props = new Properties(); FileInputStream finstr = null; try { finstr = new FileInputStream("../common/config.properties"); props.load(finstr); /* POTENTIAL FLAW: Read data from a .properties file */ data = props.getProperty("data"); } catch( IOException ioe ) { IO.logger.log(Level.WARNING, "Error with stream reading", ioe); } finally { /* Close stream reading object */ try { if( finstr != null ) { finstr.close(); } } catch( IOException ioe ) { IO.logger.log(Level.WARNING, "Error closing FileInputStream", ioe); } } } String osCommand; if(System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) { /* running on Windows */ osCommand = "c:\\WINDOWS\\SYSTEM32\\cmd.exe /c dir "; } else { /* running on non-Windows */ osCommand = "/bin/ls "; } /* POTENTIAL FLAW: command injection */ Process p = Runtime.getRuntime().exec(osCommand + data); p.waitFor(); } public void good() throws Throwable { goodG2B1(); goodG2B2(); } /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException { mainFromParent(args); } }
917524eb7768ea62e98448227c199d6bf33e5fe7
160d9b2b050fdc42e775bb7ab3cd0eed23edcbb0
/android/app/src/main/java/com/example/minya_flutter/MainActivity.java
8217fb2a35d0fdf3cbb58fb06a3a2f36644b99b1
[]
no_license
LCJ-MinYa/minya_flutter
5e08b4b3a322ff3912a5aea39a7a39ca05e2b197
a81d193e32cf3958e143d49d2e4230053fbaa983
refs/heads/master
2020-05-09T14:50:38.247535
2019-04-16T01:15:10
2019-04-16T01:15:10
181,210,497
0
0
null
null
null
null
UTF-8
Java
false
false
370
java
package com.example.minya_flutter; import android.os.Bundle; import io.flutter.app.FlutterActivity; import io.flutter.plugins.GeneratedPluginRegistrant; public class MainActivity extends FlutterActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); GeneratedPluginRegistrant.registerWith(this); } }
1f6ac48823d930989241e410e3e35fec270b2611
05c528b73a94f82ce702d7569d5d1999bb22a053
/src/memo/D_Font.java
30f97c4b8087dc3f07c09888537b72d11a18d893
[]
no_license
acacia0216/ppject
9c8df17b756c608e446bf212f9730df8bead6e70
ce4eda7a4a6d13becb629e99477a7a7ff3fbb8c1
refs/heads/master
2021-04-12T06:10:53.883696
2018-03-20T08:18:22
2018-03-20T08:18:22
125,983,316
0
0
null
null
null
null
UTF-8
Java
false
false
5,413
java
package memo; import java.awt.BorderLayout; import java.awt.Font; import java.awt.GraphicsEnvironment; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.SwingConstants; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; public class D_Font { class MyFrame implements ListSelectionListener, ItemListener { private JFrame frm; private JButton btn; private JLabel showFontLabel; private JList<String> fontList; private JPanel panel; private JCheckBox boldCheck; private JCheckBox italicCheck; private JList<Integer> sizeList; MyFrame() { //��� ���� frm = new JFrame(); btn = new JButton("�� ��ȯ"); showFontLabel = new JLabel("abc ABC ������ English �ȳ��ϼ��� Hi~", SwingConstants.HORIZONTAL); fontList = new JList<String>(); panel = new JPanel(); boldCheck = new JCheckBox("����"); italicCheck = new JCheckBox("����"); sizeList = new JList<Integer>(); //��Ʈ������ ����Ʈ ���� Integer[] font_size = new Integer[100]; for(int i = 0 ; i < 100 ; ++i) { font_size[i] = i+1; } sizeList.setListData(font_size); sizeList.addListSelectionListener(this); //�ý��۳� �����ϴ� ��Ʈ ��� ����Ʈ ���� GraphicsEnvironment g; g = GraphicsEnvironment.getLocalGraphicsEnvironment(); String[] font_list = g.getAvailableFontFamilyNames(); fontList.setListData(font_list); fontList.addListSelectionListener(this); //üũ�ڽ� �̺�Ʈ �ڵ鷯 ���� boldCheck.addItemListener(this); italicCheck.addItemListener(this); //�гο� ������Ʈ ���� panel.add(new JScrollPane(fontList)); panel.add(new JScrollPane(sizeList)); panel.add(boldCheck); panel.add(italicCheck); //�����ӿ� �г� ���� frm.add(showFontLabel, BorderLayout.CENTER); frm.add(panel, BorderLayout.SOUTH); //������ �⺻���� frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frm.setBounds(120, 120, 410, 300); frm.setVisible(true); } @Override public void valueChanged(ListSelectionEvent e) { if(e.getSource() == fontList) { String fontName = fontList.getSelectedValue(); String styleStr; int size = showFontLabel.getFont().getSize(); int styleNum = showFontLabel.getFont().getStyle(); if((Font.BOLD | Font.ITALIC) == styleNum) { styleStr = "BOLDITALIC"; } else if(Font.BOLD == styleNum) { styleStr = "BOLD"; } else if(Font.ITALIC == styleNum) { styleStr = "ITALIC"; } else if(Font.PLAIN == styleNum) { styleStr = "PLAIN"; } else { styleStr = "PLAIN"; } String font_style_size = fontName + "-" + styleStr + "-" + size; Font font = Font.decode(font_style_size); showFontLabel.setFont(font); } else if(e.getSource() == sizeList) { Integer fontSize = sizeList.getSelectedValue(); Font font = showFontLabel.getFont().deriveFont((float)fontSize); showFontLabel.setFont(font); } } @Override public void itemStateChanged(ItemEvent e) { if((e.getSource() == boldCheck) || (e.getSource() == italicCheck)) { //�Ѵ� üũ�Ǿ� ���� �� if(boldCheck.isSelected() && italicCheck.isSelected()) { Font font = showFontLabel.getFont().deriveFont(Font.BOLD | Font.ITALIC); showFontLabel.setFont(font); return; } //���Կ��� üũ �Ǿ� ���� �� else if(boldCheck.isSelected() == true) { Font font = showFontLabel.getFont().deriveFont(Font.BOLD); showFontLabel.setFont(font); } //���Կ��� üũ �Ǿ� ���� �� else if(italicCheck.isSelected() == true) { Font font = showFontLabel.getFont().deriveFont(Font.ITALIC); showFontLabel.setFont(font); } //�Ѵ� üũ �ȵǾ� ���� �� else { Font font = showFontLabel.getFont().deriveFont(Font.PLAIN); showFontLabel.setFont(font); } } } } }
[ "Bit@DESKTOP-0KBOIF4" ]
Bit@DESKTOP-0KBOIF4
3295635b29c89d965903678eaaf1ba2c39f708c9
77d026fbd8b4054ac114b784a33843f75514ea4a
/s-ioc/src/main/java/org/scode/sioc/context/AnnotationConfigApplicationContext.java
cfd3f3fb65b7613ac5fdf71a84e0a7fede531b3c
[]
no_license
yuanhw/source-code
28a7f3b1017271e5e926fe9b6acaf6a80fae7ce2
7d42752d60e8dffdaaa19e9f8cf93e9c81f3d8bb
refs/heads/master
2020-04-29T06:31:41.064634
2019-03-22T13:17:31
2019-03-22T13:17:31
175,918,704
0
0
null
null
null
null
UTF-8
Java
false
false
2,291
java
package org.scode.sioc.context; import org.scode.sioc.beans.AnnotatedBeanDefinitionReader; import org.scode.sioc.beans.BeanDefinition; import java.util.List; /** * @author wyh * @date 2019/3/17 2:37 PM */ public class AnnotationConfigApplicationContext extends AbstractApplicationContext { private final AnnotatedBeanDefinitionReader reader; public AnnotationConfigApplicationContext() { this.reader = new AnnotatedBeanDefinitionReader(); } public AnnotationConfigApplicationContext(String... basePackages) { this(); scan(basePackages); refresh(); } private void scan(String[] basePackages) { if (basePackages == null || basePackages.length == 0) { return; } this.reader.scan(basePackages); } /** * IOC核心实现方法 */ private void refresh() { // 加载扫描到的类路径集合 List<String> beanDefinitions = this.reader.loadBeanDefinitions(); // 进行注册BeanDefinition doRegistry(beanDefinitions); } /** * 注册BeanDefinition到Map中 * @param beanDefinitions */ private void doRegistry(List<String> beanDefinitions) { // 注册bean名称三种情况: // 1. 默认是类名首字母小写 // 2. 自定义名称 // 3. 接口名称 try { for (String className : beanDefinitions) { Class<?> cls = Class.forName(className); if(!this.reader.isCandidateComponent(cls)) { continue; } BeanDefinition beanDefinition = this.reader.registryBean(className); if (beanDefinition == null) { continue; } this.beanDefinitionMap.put(beanDefinition.getBeanFactoryName(), beanDefinition); Class<?>[] interfaces = cls.getInterfaces(); if (interfaces == null) { continue; } for (Class<?> anInterface : interfaces) { this.beanDefinitionMap.put(anInterface.getName(), beanDefinition); } } } catch (Exception e) { e.printStackTrace(); } } }
6991211a6c082fada0c1a0a73fb391b244367eaa
bd0175d8057eca01a0cf1d0785f49d4e534aa8fe
/src/main/java/com/skcc/bcsvc/Application.java
f7df08760cd36c5618d02484d69f028ecfbac843
[]
no_license
jaehoon-k/blockchain-contest
40e6fe22f9fad8cfc76a64bf499d5d952aa7422b
9188bc6842ca40ca2685c8e408858e889cb8fae9
refs/heads/master
2023-01-11T09:48:29.689173
2020-11-20T04:45:54
2020-11-20T04:45:54
310,247,314
0
0
null
null
null
null
UTF-8
Java
false
false
1,876
java
package com.skcc.bcsvc; import com.skcc.bcsvc.storage.StorageProperties; import com.skcc.bcsvc.storage.StorageService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.web3j.abi.FunctionEncoder; import org.web3j.abi.FunctionReturnDecoder; import org.web3j.abi.TypeReference; import org.web3j.abi.datatypes.*; import org.web3j.abi.datatypes.generated.Uint256; import org.web3j.crypto.Credentials; import org.web3j.crypto.WalletUtils; import org.web3j.protocol.Web3j; import org.web3j.protocol.core.DefaultBlockParameterName; import org.web3j.protocol.core.methods.request.Transaction; import org.web3j.protocol.core.methods.response.EthCall; import org.web3j.protocol.core.methods.response.TransactionReceipt; import org.web3j.protocol.http.HttpService; import org.web3j.tx.FastRawTransactionManager; import org.web3j.tx.response.PollingTransactionReceiptProcessor; import org.web3j.tx.response.TransactionReceiptProcessor; import java.math.BigInteger; import java.util.Arrays; import java.util.Collections; import java.util.List; @SpringBootApplication @EnableConfigurationProperties(StorageProperties.class) public class Application { private Logger logger = LoggerFactory.getLogger(this.getClass()); public static void main(String[] args) { // TODO Auto-generated method stub SpringApplication.run(Application.class, args); } @Bean CommandLineRunner init(StorageService storageService) { return (args) -> { storageService.deleteAll(); storageService.init(); }; } }
a8a2b5e6ef07bd1b6082ae56560fa2808c7d6a66
b11b864598a9eacb43dddf2e59e97faa6b1d3cfd
/src/servlet/Login.java
758080255d27ac09929129fce5130988bb3bb08d
[]
no_license
zy3101176/shop
47d89178cef99b36200477c254514b07b8272815
e9dd0105a2e35d9aba1e8869623102b7f2cd92c9
refs/heads/master
2021-07-11T21:52:13.610540
2017-10-15T09:33:00
2017-10-15T09:33:00
106,908,256
0
0
null
null
null
null
UTF-8
Java
false
false
976
java
package servlet; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.io.PrintWriter; /** * Created by zhuyuanhan on 2017/10/14. */ @WebServlet(name = "Login",urlPatterns = "/login") public class Login extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String email = request.getParameter("email"); String password = request.getParameter("password"); PrintWriter out = response.getWriter(); if(email.equals( "123") && password.equals("123")){ out.print("true"); }else { out.print("false"); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
f43c1e503d7907c0a9b4ac78742241835f1dda31
646193f024316e8671c02791a04f6de11a2d925d
/removeDuplicates.java
dc485add922fdb3e2bef0d10490dce38cb98510b
[]
no_license
publicwangfei/jike
fa5b170a553cca8c18fc32c731f9ca21e504603e
fed91cdb40c4ea7fbcf5bdd1e802173fe2ab1d8c
refs/heads/master
2021-03-08T10:27:27.894277
2020-03-14T06:37:08
2020-03-14T06:37:08
246,340,411
0
0
null
null
null
null
UTF-8
Java
false
false
413
java
import java.util.Set; import java.util.TreeSet; class Solution { public int removeDuplicates(int[] nums) { if(nums == null || nums.length == 0){ return 0; } int i = 0; for (int j = 1; j < nums.length; j++) { if(nums[i] != nums[j]){ nums[i + 1] = nums[j]; i++; } } return ++i; } }
c89c8d60274688dc514d59269b2c075deb747afc
a2d690729197db92fcf99000cb3f98c9d0e04a50
/ScoreStatistic/app/src/main/java/tianqiw/scorestatistic/util/Constants.java
1b9d49ecad7eb2fa30ca1b5883954ce7305c3891
[]
no_license
wentianqi7/JaveSmartphoneProjects
ebcddeaaca2fbb7322d65d5bb41bb6c31d123c54
83be3db354219bc8c4a4e59b3ad636ecdc713bc0
refs/heads/master
2020-05-31T10:04:33.435744
2016-01-27T03:57:01
2016-01-27T03:57:01
42,344,353
0
0
null
null
null
null
UTF-8
Java
false
false
460
java
package tianqiw.scorestatistic.util; /** * Created by STuotuo.Wen on 2015/11/12. */ public interface Constants { static String DATABASE = "StudentRecords"; static String[] FIELDS = {"sid", "q1", "q2", "q3", "q4", "q5"}; static String CREATE_TABLE = "CREATE TABLE records" + "(sid INTEGER PRIMARY KEY," + "q1 REAL," + "q2 REAL," + "q3 REAL," + "q4 REAL," + "q5 REAL);"; }
c5e4b95d7b0756ec9e3cfefcca5470410cf02511
cb10c2a05abae00d5dcff5a7b2324f2decfbcb4c
/Algorithm/src/com/sky/leetcode/first/_179_LargestNumber_2.java
3a11ba20743bbb066652ae2d8592fca18a2cff1e
[]
no_license
DuanSky22/LearningAlgorithm
366bd2fe874864cf8014f6c5ecb98b0e1ba1a9c3
69dc2f7047828b47a75b8ccf88525b766facfa65
refs/heads/master
2020-12-03T23:36:02.813150
2016-09-21T13:20:17
2016-09-21T13:20:17
67,912,835
0
0
null
null
null
null
UTF-8
Java
false
false
2,153
java
/** * @author DuanSky * @date 2015��10��25�� ����3:45:14 * @content * Not familiar with selection sort :( */ package com.sky.leetcode.first; import java.util.Arrays; public class _179_LargestNumber_2 { public static void main(String args[]){ //stringSortTest(); // String sa="78987"; // String sb="78987"; // System.out.println(compare(sa,sb)+":"+compare0(sa,sb)); int[] nums={1,0,0}; System.out.println(largestNumber(nums)); } public static String largestNumber(int[] nums) { if(nums.length==0) return ""; for(int i=0;i<nums.length-1;i++){ int max=nums[i]; int position=i; for(int j=i;j<nums.length;j++){ if(compare(Integer.toString(nums[j]),Integer.toString(max))>0){ position=j; max=nums[j]; } } /* * Pay attention! this method to switch two elements may get wrong answer * when the two elements are one element situation. */ // nums[i]=nums[i]^nums[position]; // nums[position]=nums[i]^nums[position]; // nums[i]=nums[i]^nums[position]; int temp=nums[i]; nums[i]=nums[position]; nums[position]=temp; } String result=""; for(int i=0;i<nums.length;i++){ result+=nums[i]; } while(result !=null && result!="" && result.charAt(0)=='0' && result.length()>1) result=result.substring(1); return result; } public static int compare0(String a,String b){ return (a+b).compareTo(b+a); } public static int compare(String sa,String sb){ int minSize=Math.min(sa.length(), sb.length()); int i=0; for(;i<minSize;i++){ if(sa.charAt(i)<sb.charAt(i)) return -1; else if(sa.charAt(i)>sb.charAt(i)) return 1; } if(sa.length()==sb.length()) return 0; else if(sa.length()<sb.length()){ return compare(sa,sb.substring(i)); } else{ return compare(sa.substring(i),sb); } } public static void stringSortTest(){ String[] list={"7","77","78","769","798"}; Arrays.sort(list); System.out.print(list); } }
d1329006be415fe1ac3e5e62a898fa48dd99498b
66781987c760172026e00bc6192a76313dce5c42
/app/src/main/java/com/safiya/obviousassignment/StringDateComparator.java
744068e9e7423f85cf7d606fb9953f7b4f8b065a
[]
no_license
safiyaAkhtarDev/ObviousAssignment
47a3ff0d9e641b37f5d4c2ffd372a08d84bf3073
1426c95e406e8949b5ecfa1e4bc07f31a70f1963
refs/heads/main
2023-02-28T06:20:34.730299
2021-02-07T08:11:29
2021-02-07T08:11:29
336,729,892
0
0
null
null
null
null
UTF-8
Java
false
false
803
java
package com.safiya.obviousassignment; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Comparator; class StringDateComparator implements Comparator<GridImages> { SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy"); public int compare(String lhs, String rhs) { try { return dateFormat.parse(lhs).compareTo(dateFormat.parse(rhs)); } catch (ParseException e) { e.printStackTrace(); return 1; } } @Override public int compare(GridImages o1, GridImages o2) { try { return dateFormat.parse(o1.getDate()).compareTo(dateFormat.parse(o2.getDate())); } catch (ParseException e) { e.printStackTrace(); return 1; } } }
e385a5b3c547f56304c8bdb204b566b5104db195
b9888e192758e8e066d5268963c202b7a3d8bd40
/src/main/java/com/sarality/dataport/file/importer/FileImportStatus.java
bce6970b9cf5588800c48b1f67a44284842a27ea
[]
no_license
sarality/blocks-dataport
3a6f09bf8b8eab3b7bc19e7b1c2d2ee87a9c5757
4c9e30ddb3aabf34abd879320515427218963236
refs/heads/devel
2023-05-30T00:51:13.342139
2021-04-08T12:31:37
2021-04-08T12:31:37
75,463,116
0
0
null
2023-04-27T15:24:56
2016-12-03T08:55:14
Java
UTF-8
Java
false
false
1,766
java
package com.sarality.dataport.file.importer; /** * Status for an Import Process * * @author abhideep@ (Abhideep Singh) */ public class FileImportStatus { private String fileName; private String filePath; private String errorFileName; private String errorFilePath; private boolean importSuccessful; private String failureReason; private int totalItemCount; private int processedCount; private int skippedCount; private int successCount; private int errorCount; FileImportStatus(String fileName, String filePath, String errorFileName, String errorFilePath, boolean importSuccessful, String failureReason, int totalItemCount, int processedCount, int skippedCount, int successCount, int errorCount) { this.fileName = fileName; this.filePath = filePath; this.errorFileName = errorFileName; this.errorFilePath = errorFilePath; this.importSuccessful = importSuccessful; this.failureReason = failureReason; this.totalItemCount = totalItemCount; this.processedCount = processedCount; this.skippedCount = skippedCount; this.successCount = successCount; this.errorCount = errorCount; } public String getErrorFileName() { return errorFileName; } public String getErrorFilePath() { return errorFilePath; } public boolean isImportSuccessful() { return importSuccessful; } public String getFailureReason() { return failureReason; } public int getTotalItemCount() { return totalItemCount; } public int getProcessedCount() { return processedCount; } public int getSkippedCount() { return skippedCount; } public int getSuccessCount() { return successCount; } public int getErrorCount() { return errorCount; } }
ec13a3516c928df7fd2cfe85ca5df600141f2c68
c312579f713d0a79cdb6d5bf54f67c7158ce1ca4
/app/src/main/java/com/br/arley/projeto2020/dao/AtividadeDao.java
698467626a638427e3dfd749e4d55d4ac45cacb2
[]
no_license
novaisarley/PalmPlay
f7790cd2f668f53078ee12b1ea5ef82b8e3c0cd5
0259d25533a110596946788ee4e6c06082a53c7a
refs/heads/master
2022-12-22T02:45:51.569322
2020-09-27T01:12:44
2020-09-27T01:12:44
258,626,165
1
0
null
null
null
null
UTF-8
Java
false
false
460
java
package com.br.arley.projeto2020.dao; import androidx.room.Dao; import androidx.room.Delete; import androidx.room.Insert; import androidx.room.Query; import com.br.arley.projeto2020.model.Atividade; import java.util.List; @Dao public interface AtividadeDao { @Query("SELECT * FROM atividade") public List<Atividade> getAllAtividades(); @Insert void insertAll(Atividade... atividades); @Delete void delete(Atividade atividade); }
a2f367600523b37bb18375bace63e3800d5b1c42
57e336ee001e59a350c919877d79886b2af8f2ef
/app/src/main/java/com/gsatechworld/spexkart/adapter/AddressAdapter.java
0f18cd72c0d74593b90ec5fbd1d90ca85d9c9e9c
[]
no_license
dprasad554/Spexkart
e3588d516cbc92aa0a2050e239c08b23612902ae
e964d0bd8d699eadd7495a8e3811da426adc9c21
refs/heads/master
2023-04-20T00:25:27.455758
2021-05-03T09:04:05
2021-05-03T09:04:05
363,872,584
0
0
null
null
null
null
UTF-8
Java
false
false
5,108
java
package com.gsatechworld.spexkart.adapter; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.LinearSmoothScroller; import androidx.recyclerview.widget.RecyclerView; import com.google.gson.Gson; import com.gsatechworld.spexkart.R; import com.gsatechworld.spexkart.activity.AddAddressActivity; import com.gsatechworld.spexkart.activity.CheckOutActivity; import com.gsatechworld.spexkart.activity.ProductDetailsActivity; import com.gsatechworld.spexkart.activity.SizeGuideActivity; import com.gsatechworld.spexkart.beans.addresslist.AddressList; import java.util.ArrayList; public class AddressAdapter extends RecyclerView.Adapter<AddressAdapter.ViewHolder> { //Variables private Context context; AddressList addressList; UserAddress userAddress; String action; private int checkedPosition = -1; public interface UserAddress { void Addresslist(String address_id,String action,String position); } public AddressAdapter(Context context,AddressList addressList,UserAddress userAddress) { this.context = context; this.addressList = addressList; this.userAddress = userAddress; } @NonNull @Override public AddressAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_addresslist,parent,false); return new AddressAdapter.ViewHolder(view); } @Override public void onBindViewHolder(@NonNull final AddressAdapter.ViewHolder holder, final int position) { holder.tv_name.setText(addressList.getAddressList().get(position).getContactName()); final String address = addressList.getAddressList().get(position).getLocality()+","+ addressList.getAddressList().get(position).getLandmark()+","+addressList.getAddressList().get(position).getCity()+ ","+addressList.getAddressList().get(position).getState()+","+addressList.getAddressList().get(position).getPincode()+","+ addressList.getAddressList().get(position).getCountry(); holder.tv_address.setText(address); holder.tv_mobile.setText(addressList.getAddressList().get(position).getMobileNumber()); holder.btnEdit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(context, AddAddressActivity.class); intent.putExtra("address_details",(String)new Gson().toJson(addressList.getAddressList().get(position))); context.startActivity(intent); } }); holder.btndelete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { action = "delete"; userAddress.Addresslist(addressList.getAddressList().get(position).getId().toString(),action, String.valueOf(position)); } }); if(addressList.getAddressList().get(position).getStatus()==0){ }else { holder.ll_address.setBackgroundResource(R.drawable.square_drawable_red); } holder.ll_address.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (checkedPosition != -1 && checkedPosition != position) { addressList.getAddressList().get(checkedPosition).setStatus(0); notifyItemChanged(checkedPosition); } addressList.getAddressList().get(position).setStatus(1); notifyItemChanged(position); checkedPosition = position; action = "select"; userAddress.Addresslist(addressList.getAddressList().get(position).getId().toString(),action, String.valueOf(position)); } }); } @Override public int getItemCount() { return addressList.getAddressList().size(); } public class ViewHolder extends RecyclerView.ViewHolder{ TextView tv_name,tv_address,tv_mobile; Button btnEdit,btndelete; LinearLayout ll_address; public ViewHolder(@NonNull View itemView) { super(itemView); tv_name = itemView.findViewById(R.id.tv_name); tv_address = itemView.findViewById(R.id.tv_address); tv_mobile = itemView.findViewById(R.id.tv_mobile); btnEdit = itemView.findViewById(R.id.btnEdit); btndelete = itemView.findViewById(R.id.btndelete); ll_address = itemView.findViewById(R.id.ll_address); } } }
c3d06e7a0bf35c7a730c57154c800eafad1ba025
dc90e66459ccaf658cd98d9dd25e250f2877b54c
/static/src/patterndemos/state/PersonState.java
d9cec7fa79ad387a73d0d203f46f30db3c59cede
[]
no_license
dlitvakb/patterns_cc2018
f593524ae5594b34e7e0bf3fdb8ed531d98776b8
4688fcd83b2ff647c57ef1e0da97b7124562bcd5
refs/heads/master
2020-03-27T23:45:47.669080
2018-09-04T12:44:15
2018-09-04T12:45:58
147,344,418
1
0
null
null
null
null
UTF-8
Java
false
false
101
java
package patterndemos.state; public interface PersonState { String walk(); String crawl(); }
30313d39b5e61ddd19aa24a6cd41f4ab9c74e304
bff127e6b8743b43549960e8b4d8adabba2cd2a7
/src/test/java/com/godeltech/camel/activemq/RpcActiveMqCamelDemo.java
87e28b5f893ec7f3dd9b62fb1932b4096cff8bf1
[]
no_license
AndrewRadkovich/rabbitmq-activemq-integration
bbfe08606328d82e708fb7b252c98432e03c989d
544974a5984c9373f975702d8d679ce6aef776bd
refs/heads/master
2021-08-30T10:50:01.850452
2017-12-17T14:55:46
2017-12-17T14:55:46
113,593,051
0
0
null
null
null
null
UTF-8
Java
false
false
1,196
java
package com.godeltech.camel.activemq; import com.godeltech.camel.activemq.rpc.RpcServer; import org.apache.activemq.camel.component.ActiveMQComponent; import org.apache.camel.CamelContext; import org.apache.camel.RoutesBuilder; import org.apache.camel.test.junit4.CamelTestSupport; import org.junit.Test; public class RpcActiveMqCamelDemo extends CamelTestSupport { @Test public void demo() throws Exception { final Integer reply = template.requestBody("activemq:queue:pow2", 3, Integer.class); System.out.println("reply = " + reply); } @Override protected RoutesBuilder[] createRouteBuilders() throws Exception { return new RoutesBuilder[]{ new RpcServer("pow2", exchange -> { final Integer in = exchange.getIn().getBody(Integer.class); exchange.getIn().setBody(in * in); }) }; } @Override protected CamelContext createCamelContext() throws Exception { final CamelContext context = super.createCamelContext(); context.addComponent("activemq", ActiveMQComponent.activeMQComponent("tcp://localhost:61616")); return context; } }
9380a5d82056ae61fa473c5416de35476175f535
be9a01223da9f18760e0569c67ed7c9b35fd95a1
/src/com/wundero/MiniGames_Core/listeners/player/SpectatorListener.java
2284d5855a61e9df0b47a8000d82fc9e4015011c
[]
no_license
Hello2/MiniGames-Core
e57b2f461ad0ca821244b43378371d075e542c45
39dd5f0fce16fe3dc09c89b9ef6f97ec4ae3098c
refs/heads/master
2021-01-18T09:22:44.199996
2014-08-16T03:27:29
2014-08-16T03:27:29
23,008,586
1
0
null
null
null
null
UTF-8
Java
false
false
1,647
java
package com.wundero.MiniGames_Core.listeners.player; import org.bukkit.entity.Arrow; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.util.Vector; import com.wundero.MiniGames_Core.Core; import com.wundero.MiniGames_Core.arena.ArenaManager; import com.wundero.MiniGames_Core.listeners.MGListener; public class SpectatorListener extends MGListener { public SpectatorListener(Core pl) { super(pl); } @EventHandler public void onPlayerHurtPlayer(EntityDamageByEntityEvent event) { Entity entityDamager = event.getDamager(); Entity entityDamaged = event.getEntity(); if(entityDamager instanceof Arrow) { if(entityDamaged instanceof Player && ((Arrow) entityDamager).getShooter() instanceof Player) { Arrow arrow = (Arrow) entityDamager; Vector velocity = arrow.getVelocity(); Player shooter = (Player) arrow.getShooter(); Player damaged = (Player) entityDamaged; if(ArenaManager.getArenaManager().isSpectator(damaged)) { damaged.teleport(entityDamaged.getLocation().add(0, 5, 0)); damaged.setFlying(true); Arrow newArrow = shooter.launchProjectile(Arrow.class); newArrow.setShooter(shooter); newArrow.setVelocity(velocity); newArrow.setBounce(false); event.setCancelled(true); arrow.remove(); } } } } }
052a50327cda9e5bcef2d6a3ad39e3636b9388c4
0e52193ca00e5c1c714abe527b44e491e339b101
/app/src/test/java/com/humolabs/excusador/ExampleUnitTest.java
f4201394246c7bca01e8b936278b5b8f797b284a
[]
no_license
humolabs/Excusador
2b3133f806f529c4ab9fe63dcc7e2430632f4163
4dc96bec994914cbd352bfd12785a9b88ac9aaa0
refs/heads/master
2021-01-20T19:26:00.940306
2016-07-12T13:29:12
2016-07-12T13:29:12
63,160,256
0
0
null
null
null
null
UTF-8
Java
false
false
315
java
package com.humolabs.excusador; import org.junit.Test; import static org.junit.Assert.*; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
644f4b9bc7b3bfe4864569fa99b07b0d70f9aa52
c3389fa9d6eb87d1754c176edc2a56587ed06db9
/moveanimator/src/test/java/whitelife/win/moveanimator/ExampleUnitTest.java
7f719b80332e49d06c4046eb1a34cd4de7fd960d
[]
no_license
earthWo/MoveAnimatorView
6e50acc9c1d2be387c02f622581c6f110f0f9ee5
f07aa696908738f51549350d013b8f885f5eccb0
refs/heads/master
2021-07-10T18:38:00.520425
2017-10-11T09:44:01
2017-10-11T09:44:01
106,533,613
0
0
null
null
null
null
UTF-8
Java
false
false
404
java
package whitelife.win.moveanimator; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
a7e2062fd57853937480ec9f81f67d38d7119cde
dc1dbb7e5a4b95bf44170d2f51fd08b3814f2ac9
/data_defect4j/preprossed_method_corpus/Lang/22/org/apache/commons/lang3/StringUtils_containsOnly_1724.java
8aa85695277190485c9d5a41343f2e0119c48172
[]
no_license
hvdthong/NetML
dca6cf4d34c5799b400d718e0a6cd2e0b167297d
9bb103da21327912e5a29cbf9be9ff4d058731a5
refs/heads/master
2021-06-30T15:03:52.618255
2020-10-07T01:58:48
2020-10-07T01:58:48
150,383,588
1
1
null
2018-09-26T07:08:45
2018-09-26T07:08:44
null
UTF-8
Java
false
false
9,563
java
org apach common lang3 oper link java lang string code code safe empti isempti blank isblank check string text trim strip remov lead trail whitespac equal compar string safe start startswith check string start prefix safe end endswith check string end suffix safe index indexof index lastindexof safe index check index indexofani index lastindexofani index indexofanybut index lastindexofanybut index set string containsonli containsnon containsani string charact substr left mid safe substr extract substr substringbefor substr substringaft substr substringbetween substr extract rel string split join split string arrai substr vice versa remov delet remov part string replac overlai search string replac string chomp chop remov part string left pad leftpad pad rightpad center repeat pad string upper case uppercas lower case lowercas swap case swapcas capit uncapit string count match countmatch count number occurr string alpha isalpha numer isnumer whitespac iswhitespac ascii printabl isasciiprint check charact string default string defaultstr protect input string revers revers delimit reversedelimit revers string abbrevi abbrevi string ellipsi differ compar string report differ levenstein distanc levensteindist number need chang string code string util stringutil code defin word relat string handl code code empti length string code code space space charact code code whitespac charact defin link charact whitespac iswhitespac trim charact link string trim code string util stringutil code handl code code input string quietli code code input code code code code code code return detail vari method side effect code code handl code null pointer except nullpointerexcept code consid bug code string util stringutil code method give sampl code explain oper symbol code code input includ code code thread safe threadsaf java lang string author apach softwar foundat author href http jakarta apach org turbin apach jakarta turbin author href mailto jon latchkei jon steven author daniel rall author href mailto gcoladonato yahoo greg coladonato author href mailto apach org korthof author href mailto rand mcneeli yahoo rand neeli mcneeli author href mailto fredrik westermarck fredrik westermarck author holger krauth author href mailto alex purpletech alexand dai chaffe author href mailto hp intermeta hen schmiedehausen author arun mammen thoma author gari gregori author phil steitz author chou author michael davei author reuben sivan author chri hyzer author scott johnson version string util stringutil check char sequenc charsequ charact code code char sequenc charsequ code code code code valid charact arrai code code empti char sequenc charsequ length return code code pre string util stringutil containsonli string util stringutil containsonli string util stringutil containsonli string util stringutil containsonli string util stringutil containsonli abab 'abc' string util stringutil containsonli ab1 'abc' string util stringutil containsonli abz 'abc' pre param string check param valid arrai valid char valid char chang signatur containsonli string containsonli char sequenc charsequ containsonli char sequenc charsequ valid pre check maintain api older version valid length valid length index indexofanybut valid index found
ae396448bba0f3314e6c11875353686a0a61a00f
3b74fbedd3001512dfe49bc0f5a18090c2e34564
/hvip-common-api/src/main/java/com/huazhu/hvip/common/vo/WxMenuVO.java
0d7b4a996280a1021c802d7935f8a1be7e239e6e
[]
no_license
xuelu520/cjiaclean-core
b148a78da67b45a0c0e5d5cf07c67b5cfc6d47dc
a96f574a8ec2b4ab7884130461671f095762995a
refs/heads/master
2020-03-27T10:19:57.138235
2017-11-16T01:41:23
2017-11-16T01:41:45
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,432
java
package com.huazhu.hvip.common.vo; import java.io.Serializable; import java.util.Date; import java.util.List; /** * @author cmy * @create 2017-08-03 10:17 **/ public class WxMenuVO implements Serializable { private Long wxMenuId; private String menuName; private String menuType; private String menuKey; private String authorize; private String url; private Long parentId; private List<WxMenuVO> children; private Date createTime; private String createUser; private Date updateTime; private String updateUser; public String getAuthorize() { return authorize; } public void setAuthorize(String authorize) { this.authorize = authorize; } public Long getWxMenuId() { return wxMenuId; } public void setWxMenuId(Long wxMenuId) { this.wxMenuId = wxMenuId; } public String getMenuName() { return menuName; } public void setMenuName(String menuName) { this.menuName = menuName; } public String getMenuType() { return menuType; } public void setMenuType(String menuType) { this.menuType = menuType; } public String getMenuKey() { return menuKey; } public void setMenuKey(String menuKey) { this.menuKey = menuKey; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public Long getParentId() { return parentId; } public void setParentId(Long parentId) { this.parentId = parentId; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getCreateUser() { return createUser; } public void setCreateUser(String createUser) { this.createUser = createUser; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public String getUpdateUser() { return updateUser; } public void setUpdateUser(String updateUser) { this.updateUser = updateUser; } public List<WxMenuVO> getChildren() { return children; } public void setChildren(List<WxMenuVO> children) { this.children = children; } }
[ "zxc,./123" ]
zxc,./123
d6d91691620f421e82af99beea10011c7331540d
c6239036b9b93cafd09f2c8aed46925abb71fd8f
/src/newtours/mercurydropdown.java
a8efd87cc18a636dbba89933d605c462a736ea73
[]
no_license
abdulrajik99/myproject
ee06cbd261403441c62861eb50dd1b2dfa6a4305
dcfa70c2be8ac329a64b3781628bc4d477c25719
refs/heads/master
2020-12-23T14:05:56.826265
2020-02-27T18:22:24
2020-02-27T18:22:24
237,175,081
0
0
null
null
null
null
UTF-8
Java
false
false
3,365
java
package newtours; import java.util.List; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.Select; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class mercurydropdown { WebDriver driver; boolean b=false; @BeforeMethod public void open() { System.setProperty("webdriver.chrome.driver", "C:\\Users\\Abdul Rajik shaik" + "\\Desktop\\eclipse\\chromedriver_win32 (1)\\chromedriver.exe"); driver=new ChromeDriver(); driver.get("https://www.mercurytravels.co.in/"); driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); driver.manage().window().maximize(); driver.findElement(By.xpath("//span[@class='white-text']")).click(); driver.findElement(By.xpath("//span[@class='white-text']")).click(); } @Test(priority=1)//links public void WorkingonMercurylinks() { List<WebElement> link=driver.findElements(By.tagName("a")); System.out.println("total links "+link.size()); System.out.println("link names "); for(WebElement web:link) { String name=web.getText(); System.out.println(name); } } @Test(priority=2) public void workingonHolidayDurationdropdown() { Select sc=new Select(driver.findElement(By.xpath("//select[@id='duration_d']"))); List<WebElement> duration=sc.getOptions(); for(WebElement web2:duration) { String s2=web2.getText(); System.out.println("durations are"+s2); if(s2.equals("1Nights+2Days")) { web2.click(); } } } @Test(priority=3)// roundtrip public void workingonFlightsradiobutton() { driver.findElement(By.xpath("//a[@id='flights']")).click(); WebElement oneway= driver.findElement(By.xpath("//label[2]//input[1]")); WebElement rountrip=driver.findElement(By.xpath("//label[@class='active']//input[@name='tripType']")); oneway.click(); boolean b=oneway.isSelected(); if(b==true) System.out.println("oneway is enable"); else System.out.println("oneway is disabled"); rountrip.click(); boolean b2=oneway.isSelected(); if(b2==true) System.out.println("roundtrip is enable"); else System.out.println("roundtrip is disabled"); } @Test(priority=4) public void FlightsdatereturnCalender() { driver.findElement(By.xpath("//a[@id='flights']")).click(); WebElement returndatetable=driver.findElement(By.xpath("//input[@id='dpf2']")); returndatetable.click(); WebElement table=driver.findElement(By.xpath("//body//div[17]")); List<WebElement> rows=table.findElements(By.tagName("tr")); for(WebElement row:rows) { List<WebElement> colu=row.findElements(By.tagName("td")); //System.out.println("dates are"); for(WebElement c:colu) { String s=c.getText(); System.out.println(s); if(s.equals("25")) { c.click(); b=true; break; } if(b==true) { break; } } } } @Test public void getimages() { List<WebElement> img=driver.findElements(By.tagName("img")); System.out.println("no of images aree "+img.size()); for(WebElement i:img) { System.out.println(i.getAttribute("src")); } } @AfterMethod public void last() { driver.close(); } }
8e128175260b44391363d213fee1a0303b79f6ed
fddcd7a8ee584df9c2ec897a32da0445be13f8a0
/src/taomp/consensus/ConsensusProtocol.java
28c5ba1bbdfdf271082114375eb398b50674fa9d
[]
no_license
Anydea/taomp
ff66919ba0eb63ed1079fa54c244724c57b78ca5
099464a83cc15355eae16f3d8f0bcd8106ab82ff
refs/heads/master
2020-05-20T11:01:49.326869
2015-08-19T16:23:12
2015-08-19T16:23:12
40,962,722
0
0
null
null
null
null
UTF-8
Java
false
false
342
java
package taomp.consensus; import taomp.util.ThreadID; public abstract class ConsensusProtocol<T> implements Consensus<T> { protected T[] proposed; void propose(T value) { proposed[ThreadID.get()] = value; } public ConsensusProtocol(int threads){ proposed = (T[]) new Object[threads]; } abstract public T decide(T value); }
73012c406819f6337d63a068f37f954bda100b09
fcdf658027735cbf61d176af3d8c00958b2b3c92
/TicTaeToeServer/src/serverPrgms/TicTaeToeServer.java
ad83571023467ad6c196a510951ed767cc28a48d
[]
no_license
svmsharma20/TicTaeToe
f7c03e9d67ea70ef371cdc11383c4be9d82fe993
dde1b5ba01a0dbfb3aa0f5d1c593fe9772888b46
refs/heads/master
2020-04-24T23:37:57.529098
2019-02-24T15:00:50
2019-02-24T15:00:50
172,350,812
0
0
null
null
null
null
UTF-8
Java
false
false
9,528
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package serverPrgms; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.Date; import java.util.logging.Level; import java.util.logging.Logger; import javafx.application.Application; import javafx.application.Platform; import javafx.scene.Scene; import javafx.scene.control.ScrollPane; import javafx.scene.control.TextArea; import javafx.stage.Stage; import static serverPrgms.TicTaeToeConstants.CONTINUE; import static serverPrgms.TicTaeToeConstants.DRAW; import static serverPrgms.TicTaeToeConstants.PLAYER1; import static serverPrgms.TicTaeToeConstants.PLAYER1_WON; import static serverPrgms.TicTaeToeConstants.PLAYER2; import static serverPrgms.TicTaeToeConstants.PLAYER2_WON; /** * * @author Shivam */ public class TicTaeToeServer extends Application implements TicTaeToeConstants { TextArea ta = new TextArea(); int sessionNo = 1; public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { Scene myScene = new Scene(new ScrollPane(ta), 450, 200); primaryStage.setTitle("Tic-Tae-Toe Server.."); primaryStage.setScene(myScene); primaryStage.show(); ta.setEditable(false); new Thread(new PlayerInitiator()).start(); } class PlayerInitiator implements Runnable { @Override public void run() { try{ ServerSocket serverSocket = new ServerSocket(8000); Platform.runLater(()-> { ta.appendText(new Date() + " : Server Started.."); }); while (true) { Platform.runLater(()-> { ta.appendText("\n\nSession"+sessionNo+" is Initiated....."); ta.appendText("\nWaiting for Player 1 to connect....."); }); Socket p1Socket = serverSocket.accept(); new DataOutputStream(p1Socket.getOutputStream()).writeInt(PLAYER1); Platform.runLater(()-> { ta.appendText("\nPlayer 1 joined session"+sessionNo); ta.appendText("\nPlayer 1 IP address : "+p1Socket.getInetAddress().getHostAddress()); ta.appendText("\nWaiting for Player 2 to connect.."); }); Socket p2Socket = serverSocket.accept(); new DataOutputStream(p2Socket.getOutputStream()).writeInt(PLAYER2); Platform.runLater(()-> { ta.appendText("\nPlayer 2 joined session"+sessionNo); ta.appendText("\nPlayer 2 IP address : "+p2Socket.getInetAddress().getHostAddress()); ta.appendText("\nStarting the game..............................."); ta.appendText("\nPlz wait..............................."); }); new Thread(new HandleASession(p1Socket,p2Socket)).start(); sessionNo++; } } catch (IOException ex) { System.out.println(ex.toString()); } } } class HandleASession implements Runnable { private Socket p1,p2; private char cell[][] = new char[3][3]; private DataInputStream fromPlayer1,fromPlayer2; private DataOutputStream toPlayer1,toPlayer2; public HandleASession(Socket p1, Socket p2) { this.p1 = p1; this.p2 = p2; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { cell[i][j]=' '; } } } @Override public void run() { try { fromPlayer1 = new DataInputStream(p1.getInputStream()); fromPlayer2 = new DataInputStream(p2.getInputStream()); toPlayer1 = new DataOutputStream(p1.getOutputStream()); toPlayer2 = new DataOutputStream(p2.getOutputStream()); toPlayer1.writeInt(1); // toPlayer2.writeInt(2); while (true) { int row = fromPlayer1.readInt(); System.out.println("line 150 row : "+row); int col = fromPlayer1.readInt(); System.out.println("line 152 col : "+col); cell[row][col] = 'X'; System.out.println("line 156"); if(isWon('X')) { toPlayer1.writeInt(PLAYER1_WON); toPlayer2.writeInt(PLAYER1_WON); sendMove(toPlayer2, row, col); break; } else if(isFull()) { toPlayer1.writeInt(DRAW); toPlayer2.writeInt(DRAW); sendMove(toPlayer2, row, col); break; } else { toPlayer2.writeInt(CONTINUE); sendMove(toPlayer2, row, col); } System.out.println("line 173"); row = fromPlayer2.readInt(); System.out.println("line 175"); col = fromPlayer2.readInt(); System.out.println("line 177"); cell[row][col] = '0'; System.out.println("line 181"); if(isWon('0')) { toPlayer1.writeInt(PLAYER2_WON); System.out.println("line 185"); toPlayer2.writeInt(PLAYER2_WON); System.out.println("line 187"); sendMove(toPlayer1, row, col); break; } else { toPlayer1.writeInt(CONTINUE); sendMove(toPlayer1, row, col); } } } catch (IOException ex) { System.out.println(ex.toString()); } } private void sendMove(DataOutputStream out, int row, int col) throws IOException { out.writeInt(row); out.writeInt(col); } private boolean isWon(char tocken) { for (int i = 0; i < 3; i++) { if( cell[i][0] == tocken && cell[i][1] == tocken && cell[i][2] == tocken) //check all rows return true; else if(cell[0][i] == tocken && cell[1][i] == tocken && cell[2][i] == tocken) //check all columns return true; } if(cell[0][0] == tocken && cell[1][1] == tocken && cell[2][2] == tocken) //check major diagonal return true; else if(cell[0][2] == tocken && cell[1][1] == tocken && cell[2][0] == tocken) //check minor diagonal return true; return false; } private boolean isFull() { for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) if(cell[i][j] == ' ') return false; return true; } } class Restarter implements Runnable { Socket player; public Restarter(Socket player) { this.player = player; } public void run() { try { int status = new DataInputStream(player.getInputStream()).readInt(); if(status == RESTART) { } else if(status == QUIT) { } } catch (IOException ex) { Logger.getLogger(TicTaeToeServer.class.getName()).log(Level.SEVERE, null, ex); } } } }
6357903c0ab8c48dacd92bcf5fc6305b3994ea03
9b9219e90dd69bbfd2bbf38a3073483deea54d85
/Gyana-master/src/com/cache/lru/Node.java
6bd9481aa604f328b244c2cf18afcb6dee2d10ac
[]
no_license
Gyanar-git/Gyana_Java_Interviews
0b7e012e9975a0d00eb88268f8683b5c32fdcbb8
b3a3f95c9e39cd6bf2d796b9c70d58c748157c4d
refs/heads/master
2023-07-17T06:51:49.265010
2021-08-20T02:39:31
2021-08-20T02:39:31
398,134,177
0
0
null
null
null
null
UTF-8
Java
false
false
192
java
package com.cache.lru; public class Node { int key; int val; Node pre; Node next; public Node(int key, int val) { this.key = key; this.val = val; } }
6d3859522bec151521f3a704fc622bb69f8d8c08
7c77ad24ba332801ea817b14d67334bbe7b4812e
/src/main/java/com/javadev/organizer/entities/Role.java
fd1785a270c3ee7f67ebaf74a8a65130951c6dbe
[]
no_license
jstanislawczyk/JavaDevOrganizer
0a4a538f4a95e39df32191bd80d03bf27dc35b6b
b1b04e7e17a9036472323819636919eb41440f6f
refs/heads/master
2021-09-15T17:52:42.107932
2018-06-07T11:19:53
2018-06-07T11:19:53
null
0
0
null
null
null
null
UTF-8
Java
false
false
89
java
package com.javadev.organizer.entities; public enum Role { ADMIN, STUDENT, LECTURER; }
96713951bb2c1021656b1a32ec10c9bf7223e3ef
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/6/6_4bb6fa9e8763d2e9094ece07b849cde9009be39f/TypesTest/6_4bb6fa9e8763d2e9094ece07b849cde9009be39f_TypesTest_s.java
81f3ef11babb1359023cbc435ee31e66da68acf6
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
3,385
java
package org.genericsystem.test; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import org.genericsystem.core.Cache; import org.genericsystem.core.Generic; import org.genericsystem.example.Example.MyVehicle; import org.genericsystem.example.Example.Vehicle; import org.genericsystem.generic.Attribute; import org.genericsystem.generic.Holder; import org.genericsystem.generic.Link; import org.genericsystem.generic.Relation; import org.genericsystem.generic.Type; import org.genericsystem.map.ConstraintsMapProvider; import org.genericsystem.myadmin.beans.GuiGenericsTreeBean; import org.genericsystem.myadmin.beans.Structural; import org.genericsystem.myadmin.beans.StructuralImpl; import org.testng.annotations.Test; @Test public class TypesTest extends AbstractTest { @Inject private Cache cache; @Inject private GuiGenericsTreeBean genericTreeBean; public void testExample() { Generic vehicle = cache.find(Vehicle.class); Generic myVehicle = cache.find(MyVehicle.class); assert myVehicle.inheritsFrom(vehicle); assert vehicle.getInheritings().contains(myVehicle); } public void testGetAttributes() { Type human = cache.setType("Human"); Generic michael = human.newInstance("Michael"); Generic quentin = human.newInstance("Quentin"); Relation isBrotherOf = human.setRelation("isBrotherOf", human); // isBrotherOf.enableMultiDirectional(); quentin.bind(isBrotherOf, michael); List<Structural> structurals = new ArrayList<>(); for (Attribute attribute : ((Type) quentin).getAttributes()) { structurals.add(new StructuralImpl(attribute, 0)); } assert structurals.size() >= 2 : structurals.size(); assert structurals.contains(new StructuralImpl(isBrotherOf, 0)); List<Structural> structurals2 = new ArrayList<>(); for (Attribute attribute : ((Type) quentin).getAttributes()) { structurals2.add(new StructuralImpl(attribute, 0)); } assert structurals2.size() >= 2 : structurals2.size(); assert structurals2.contains(new StructuralImpl(isBrotherOf, 0)); } public void testGetOtherTargets() { Type human = cache.setType("Human"); Generic michael = human.newInstance("Michael"); Generic quentin = human.newInstance("Quentin"); Relation isBrotherOf = human.setRelation("isBrotherOf", human); // isBrotherOf.enableMultiDirectional(); Link link = quentin.bind(isBrotherOf, michael); List<Generic> targetsFromQuentin = quentin.getOtherTargets(link); assert targetsFromQuentin.size() == 1 : targetsFromQuentin.size(); assert targetsFromQuentin.contains(michael); assert !targetsFromQuentin.contains(quentin); List<Generic> targetsFromMichael = michael.getOtherTargets(link); assert targetsFromMichael.size() == 1 : targetsFromMichael.size(); assert targetsFromMichael.contains(quentin); assert !targetsFromMichael.contains(michael); } public void testContraint() { Type vehicle = cache.setType("Vehicle"); Attribute vehiclePower = vehicle.setProperty("power"); Generic myVehicle = vehicle.newInstance("myVehicle"); myVehicle.getMap(ConstraintsMapProvider.class); Holder myVehicle123 = myVehicle.setValue(vehiclePower, "123"); myVehicle.cancel(myVehicle123); assert !myVehicle123.isAlive(); vehicle.cancel(vehiclePower); assert !vehiclePower.isAlive(); } }
28b4ca5b1e68397dd08ffa351bcf140a15db87bf
ee4c9bfa6483f1ec3dab4015d32cc0e9787e2ec6
/design-pattern/src/main/java/org/example/design/factory/abstractfactory/JavaNote.java
30020396a3e49995f8779af4537cc462bb8a5d71
[]
no_license
BXDylanThomas/learn-demo
c1afadf78c3fd6f88bbdbcac27327f15222cfb37
0fc6611d1dd6a8e53358ab98babdbf6822c3fbeb
refs/heads/master
2022-12-31T03:00:12.340399
2020-06-23T14:19:18
2020-06-23T14:19:18
272,760,064
0
0
null
null
null
null
UTF-8
Java
false
false
216
java
package org.example.design.factory.abstractfactory; /** * Java笔记 * Created by Tom */ public class JavaNote implements INote { public void edit() { System.out.println("编写Java笔记"); } }
0a31789cf13d69dda8cddffef88e7a5166ffdac6
ff1d1292dda5c3cf11b972b14a7c388ce73c9894
/src/main/java/allocation/projections/UsuarioProjection.java
35a80becf400cf449e66893ef7d71a86f42f0f7e
[]
no_license
robcorreia/car-allocation-java-api
b4a07c2945e0ff4419f1bfd6b1c177bb8f1bb162
614c88e976eeaebfa1b4a50930aee1e4d555756b
refs/heads/master
2020-06-14T10:20:25.060381
2019-07-03T04:34:56
2019-07-03T04:34:56
194,980,044
0
0
null
null
null
null
UTF-8
Java
false
false
116
java
package allocation.projections; public interface UsuarioProjection { String getNome(); String getEmail(); }
[ "robson" ]
robson
73f953722eed814059f9884fbde5c43b0cac2adc
6334a8716343eb3d08cc7bede3824c6568c7add5
/UdemyCourse/src/LetsCodeItUdemy/InterfaceAccessClass.java
b500bedce7b755f43953735bcecc246f5b2f8f68
[]
no_license
GANESH0080/JAVA_LetsCodeUdemy
16e4406e5f71452a4914aa5fd94c4f471d625131
f8b3f036226a7598d6ae0ca87013c4dcbd237428
refs/heads/master
2023-08-15T22:32:27.442622
2021-10-21T03:40:40
2021-10-21T03:40:40
408,760,344
0
0
null
null
null
null
UTF-8
Java
false
false
995
java
package LetsCodeItUdemy; public class InterfaceAccessClass implements InterfaceOne, InterfaceTwo { @Override public void interfactwoemethod() { System.out.println("Interface Two Method"); } @Override public void interfacemethod() { System.out.println("interface method"); } @Override public void nomodifierinterfacemethod() { System.out.println("no modifier interfacemethod"); } public static void main(String[] args) { InterfaceAccessClass c = new InterfaceAccessClass(); c.interfacemethod(); c.interfactwoemethod(); c.nomodifierinterfacemethod(); System.out.println(c.abc); System.out.println(InterfaceTwo.xyz); //using the reference of Interface we can create object of class InterfaceOne t = new InterfaceAccessClass(); t.interfacemethod(); t.nomodifierinterfacemethod(); //using the reference of Interface we can create object of class InterfaceTwo n = new InterfaceAccessClass(); n.interfactwoemethod(); } }
07753e46e1fc3d50312a7996fa13d137bfcc8a38
4dd1b99c2cd53ac97209b673c85907ca64051a32
/src/main/java/ru/netology/vk/PostSource.java
70a2ecd059a0c26b15eaa16002e6475e5217e7d1
[]
no_license
AlexeyVFrolov/Java-3.2.1
622267b306495e682125a2f63f4ddd1bbeef9d80
0708fdd0668cef36584be5eb4490348dfe7fccf8
refs/heads/master
2023-04-08T12:50:18.680113
2021-04-19T04:59:24
2021-04-19T04:59:24
356,615,607
0
0
null
2021-04-19T05:30:38
2021-04-10T15:03:42
Java
UTF-8
Java
false
false
425
java
package ru.netology.vk; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @NoArgsConstructor @AllArgsConstructor @Data public class PostSource { private String type; // тип источника private String platform; // название платформы, если оно доступно private String data; // тип действия private String url; // URL }
e0efb86370e6aa7d50d1bbbb5ad1d7fd0dd88f13
07182cb2651c3a062fbd6c4026c5e9adc991257f
/src/member/list/MemberList.java
1fdf36d630c5d48f6c877dba3be4507faf715e09
[]
no_license
Wearysome/MemberList
5db2e07749f754f6243db75ab63d6c68f3c80d85
fb64723678f2e74c1110ec21f18b199f2ecf9388
refs/heads/master
2021-05-28T22:50:42.976370
2015-04-04T15:40:55
2015-04-04T15:40:55
null
0
0
null
null
null
null
UTF-8
Java
false
false
13,251
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package member.list; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; /** * * @author Weary */ public class MemberList { static private ArrayList<ArrayList<String>> RUSU ; static private ArrayList<ArrayList<String>> AGB ; static private ArrayList<Integer> missing; static private Float threshold; static public void SetThreshold(Float t) { threshold = t; } /** * @param args the command line arguments */ static public void begin(String[] args) { //paths for the all the files //TODO Make this dynamic //TODO deal with Excel formats if (args.length < 2) { return; } String agbPath = args[0]; String rusuPath = args[1]; String missingPath = args[2]; String membersPath = args[3]; if (!missingPath.endsWith(".csv")) { missingPath += "\\missing.csv"; } //missing will hold line numbers for any name missing from the AGB list //RUSU an AGB are structures to hold the files, which presumably will not be massive missing = new ArrayList<Integer>(); ArrayList<Integer> typos = new ArrayList<Integer>(); RUSU = new ArrayList<ArrayList<String>>(); AGB = new ArrayList<ArrayList<String>>(); ArrayList<SmallStruct> members = new ArrayList<SmallStruct>(); RUSU = ReadFile(rusuPath); AGB = ReadFile(agbPath); //for every entry in RUSU (We only care if it is in RUSU and not in AGB, not vice versa for(int i = 1; i < RUSU.size(); i++ ) { try { //smallStruct will tell us if a line is present, its line number and if it contained a typo //the line number is recorded so we can delete it from the AGB list and speed up comparison SmallStruct s = IsNamePresent(RUSU.get(i).get(0), RUSU.get(i).get(1), i); //if it is not present- add it to the missing list if(!s.IsFound()) { missing.add(i); // if the name was spelt wrong then record the line number in RUSU } //if it is present- remove that name from AGB for future checks else { if (s.IsTypos()) { typos.add(i); } members.add(s); AGB.remove(s.GetLineNumber()); } } catch(Exception e) { System.out.println(e); } } //write the missing list to file WriteMissing(missingPath, typos); if (args.length == 4) { WriteMembers(membersPath, members); } } static public void WriteMembers(String path, ArrayList<SmallStruct> members) { try{ FileWriter writer = new FileWriter(path,false); for(int missingNames: missing) { writer.write("Name"); writer.write(","); writer.write("Student Number"); writer.write(","); writer.write("DOB"); writer.write("\n"); } for (int i = 0; i < members.size(); i++) { writer.write(members.toString()); } writer.close(); } catch(IOException e) { System.out.println(e); } } static public void WriteMissing(String missingPath, ArrayList<Integer> typos) { try{ FileWriter writer = new FileWriter(missingPath,false); for(int missingNames: missing) { writer.write(RUSU.get(missingNames).get(0)); writer.write(","); writer.write(RUSU.get(missingNames).get(1)); writer.write('\n'); } if (!typos.isEmpty()) { writer.write("\n"); writer.write("TYPOS"); writer.write("\n"); for (int spellingError: typos) { writer.write(RUSU.get(spellingError).get(0)); writer.write(", "); writer.write(RUSU.get(spellingError).get(1)); writer.write('\n'); } } writer.close(); } catch(IOException e) { System.out.println(e); } } //Read the file and perfrom string cleaning (case and white space) static public ArrayList<ArrayList<String>> ReadFile(String fileName) { File rusu = new File(fileName); //not sure why this is called the map, it is not a map ArrayList<ArrayList<String>> theMap = new ArrayList<ArrayList<String>>(); try{ FileInputStream inputStream = new FileInputStream(rusu); Scanner sc = new Scanner(inputStream); int lineCounter = 0; while (sc.hasNext()){ //reads each line and adds the line number + the string values to the data structure String[] line = sc.nextLine().split(","); for (int i = 0; i < line.length; i++) { //remove trailing white space and strange characters line[i] = line[i].trim().toUpperCase(); line[i] = line[i].replace("\"", ""); line[i] = line[i].replace("\\", ""); } theMap.add(lineCounter++, new ArrayList<String>(Arrays.asList(line))); } } catch(IOException e) { System.out.println(e); } return theMap; } //Retuns a SmallStruct indiciating if a name is present and weather it is spelt wrong static public SmallStruct IsNamePresent(String needle1, String needle2, int rusuIndex) { /*AGB is in the format: 0First Name, 1Surname, 2Num, 3Salutation, 4M/F,5,6,7,8,9,10,11Active,12Sen/Nov,13Club,14Due,15PaidDate,16,17DOB RUSU is in the format: 0SurName/FirstName, 1Card Nom, 2Joined, 3Expires problem names DO NASCIMENTO FERNANDES SOUZA, ESTEVAO GIOVANELLA VIVIAN, PRISCILA HAJI BAKIR, AAINAA SOFIYAH */ for (int j = 1; j < AGB.size(); j++) { //store in sympol strings for debugging String match1 = AGB.get(j).get(1); String match2 = AGB.get(j).get(0); //score of 2 is a match, 1 is a partial match and may need confirming or spell checking int score = JumbleMatch(needle1, needle2, match1, match2); if (score == 2) { SmallStruct s = new SmallStruct(j, true, AGB.get(j).get(17), RUSU.get(rusuIndex).get(2)); s.SetName(RUSU.get(rusuIndex).get(0) + "," + RUSU.get(rusuIndex).get(1)); return new SmallStruct(j, true, AGB.get(j).get(17), RUSU.get(rusuIndex).get(1)); } else if (score == 1) { SmallStruct s = new SmallStruct(j, true,true, AGB.get(j).get(17), RUSU.get(rusuIndex).get(2)); s.SetName(RUSU.get(rusuIndex).get(0) + "," + RUSU.get(rusuIndex).get(1)); return new SmallStruct(j, true, AGB.get(j).get(17), RUSU.get(rusuIndex).get(1)); } // } } return new SmallStruct(); } //Jumble match will try and match strings and return 2 - match, 1 - partial match - 0 no match. A return of 1 suggests a typo. static public int JumbleMatch(String needle1, String needle2, String Hay1, String Hay2) { //combine both parts of the name into one part String name1 = needle1 + " " + needle2; String name2 = Hay1 + " " + Hay2; //break the name into componants String name1Parts[] = name1.split(" "); String name2Parts[] = name2.split(" "); int score = 0; //depending on which array will over run first search through each array //and match the individual componants. Every match generates a score for (int i = 0; i < name1Parts.length; i++) { for(int j = 0; j < name2Parts.length; j++) { if (name1Parts[i].equals(name2Parts[j])) { score++; } } } //Threshold for matches is 2 if (score >= 2) { return 2; } else if (score >= 1) { if(TypoCheck(name1Parts, name2Parts)) { return 1; } } //later if >1 check for typos with Euclidean Distance return 0; } static boolean TypoCheck(String name1Parts[], String name2Parts[]) { //Take each name part1 and turn it into a symbol ArrayList<double[]> symbolParts1 = ToSymbols(name1Parts); ArrayList<double[]> symbolParts2 = ToSymbols(name2Parts); int score = 0; int characterCount = 0; //for every symbol in the first entry find the euclidean distance to every symbol //in the second entry. Check against a threshold to determine if this is the same person //each symbol is a count of the occurances of each letter of the alphabet //ie . A,B,C,D,E,F,G // 1,1,0,0,1,0,1 would be the symbol for GABE for(int i = 0; i < symbolParts1.size(); i++) { double[] symbol1 = symbolParts1.get(i); for (int j = 0; j < symbolParts2.size(); j++) { double[] symbol2 = symbolParts2.get(j); double distance = 0; for(int k = 0; k < 26; k++) { //Eucliedian distance distance += Math.abs(symbol1[k] - symbol2[k]); } //divide by the length of the first entry (ie. the number of characters in that part // of the name distance = distance/name1Parts[i].length(); //threshold //TODO Set this dynamically if (distance < threshold) { score++; } } } //return true if the score is high enough to be relatilvey sure of a match //2 of the words in the first entry have a close enough distance to be //be the same as two of the words in the second entry if (score >= 2) { return true; } //Do the same for part2 //Check each part against each other and calculate Euclidean Distance //If Distance > Threshold -> Score++ //if Score > 2 return true return false; } static ArrayList<double[]> ToSymbols(String nameParts[]){ char[] alpha = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'}; ArrayList<double[]> symbolParts = new ArrayList<double[]>(); ArrayList<char[]> cNameParts = new ArrayList<char[]>(); for (int i = 0; i < nameParts.length; i++) { //make char array and store cNameParts.add(nameParts[i].toCharArray()); double[] symbol = new double[26]; //for each letter of the alphabet for(int j = 0; j < alpha.length; j++) { //cout the occurances in this name part double occurance = 0; //for each character in the char array for(int k = 0; k < cNameParts.get(i).length; k++) { char c = cNameParts.get(i)[k]; //count if it matches alphabet[j] if (c == alpha[j]) { occurance++; } } symbol[j] = occurance; } symbolParts.add(symbol); } return symbolParts; } }
50ea158c37322cd518ee453f9e24ff29a2f8a54d
a21f73e135777cb22b13087d145a892ebb9aaa91
/app/src/androidTest/java/com/example/golan/calbmi/ExampleInstrumentedTest.java
15e1ae313109eff25e6bd21074d407ad75972fde
[]
no_license
golan1202/CalBMI
e57f0f93f9a702232f94183e2f864bc04701ecc2
1494686afaa3101615b30d0dd9be5c6261060af0
refs/heads/master
2020-04-14T03:24:17.417448
2018-12-30T17:56:30
2018-12-30T17:56:30
163,607,120
1
0
null
null
null
null
UTF-8
Java
false
false
732
java
package com.example.golan.calbmi; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.example.golan.calbmi", appContext.getPackageName()); } }
91c0f6a0db7f742869cb0d9ddf8768ef8f55e45c
c1bd1d1a173cb0d82df0f26b98f09246405e0256
/navigationui/src/main/java/com/loto/navigationui/MainFragment.java
f714e7f2bcbc658c7f14b8e0fb3d10499002a87a
[]
no_license
wyl123you/JetpackStudy
e4a8b7df9e40afc11112f83f9147c7647bfb75bb
91f507857927abb743e73ae1bf5fe23d29c577d9
refs/heads/master
2023-05-15T10:45:33.334760
2021-06-08T08:32:24
2021-06-08T08:32:24
null
0
0
null
null
null
null
UTF-8
Java
false
false
673
java
package com.loto.navigationui; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; /** * @Author: Wu Youliang * @CreateDate: 2021/6/7 下午2:40 * @Company LotoGram */ public class MainFragment extends Fragment { @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_main, container, false); return view; } }
fd8e742812ec4294389f78ac50751b8ce6d13f8e
13701f0d7e28ddf06bccad2f8814506efca0ee90
/SaveableDictionary.java
d7c663ef5c712f7520f261d145bb07c2e55e19b0
[]
no_license
ritish78/SaveableDictionary
c96f566aefe92adc1c809082337e03b5ed1db1fc
d590ea79cf124a6d3b49f2fbb5b4ea9f122feede
refs/heads/master
2022-09-05T12:30:31.847189
2020-05-30T05:31:02
2020-05-30T05:31:02
268,015,398
0
0
null
null
null
null
UTF-8
Java
false
false
2,756
java
import java.io.File; import java.io.PrintWriter; import java.util.HashMap; import java.util.Scanner; public class SaveableDictionary { private HashMap<String, String> englishToFinnish; //Stores English words private HashMap<String, String> finnishToEnglish; //Stores Finnish words private File file; private PrintWriter writer; public SaveableDictionary() { this.englishToFinnish = new HashMap<>(); this.finnishToEnglish = new HashMap<>(); } public SaveableDictionary(String file){ this(); this.file = new File(file); } public void add(String words, String translation) { if (!this.englishToFinnish.containsKey(translation)) { this.englishToFinnish.put(translation, words); } if (!this.finnishToEnglish.containsKey(words)){ this.finnishToEnglish.put(words, translation); } } public String translate(String word) { if (this.englishToFinnish.containsKey(word)){ return this.englishToFinnish.get(word); } if (this.finnishToEnglish.containsKey(word)){ return this.finnishToEnglish.get(word); } return null; } public void delete(String word) { if (this.englishToFinnish.containsKey(word)){ String translated = this.englishToFinnish.get(word); this.englishToFinnish.remove(word); this.finnishToEnglish.remove(translated); }else if (this.finnishToEnglish.containsKey(word)){ String translated = this.finnishToEnglish.get(word); this.finnishToEnglish.remove(word); this.englishToFinnish.remove(translated); } } public boolean load(){ try{ Scanner fileScanner = new Scanner(this.file); while (fileScanner.hasNextLine()){ String line = fileScanner.nextLine(); String[] pieces = line.split(":"); //Splitting line by ":" as we are saving translation in word:translation format this.englishToFinnish.put(pieces[1], pieces[0]); this.finnishToEnglish.put(pieces[0], pieces[1]); } return true; }catch(Exception e){ return false; } } public boolean save(){ try{ PrintWriter writer = new PrintWriter(this.file); for (String key:this.englishToFinnish.keySet()){ //Saving the words writer.append(key+":"+this.englishToFinnish.get(key)+"\n"); } writer.close(); return true; }catch (Exception e){ return false; } } }
0c4d95d40e7c18c9fde895f896f14b9a8c3e6796
e1087e5d300d9e6d5caf7eac9ce3faef78aa4d81
/services/src/main/java/org/exoplatform/samples/dao/ProduitDao.java
ff6098edb5e9c787fa8564da9b591aa300794bd6
[]
no_license
SaraBoutej/addon-example
56204027fb2ed0e0822c2dbff2239d2ce8e3364e
7ed10c61a24ffa87266dc9581b9924483cd4961c
refs/heads/master
2020-03-30T04:39:11.901974
2018-10-01T15:19:41
2018-10-01T15:19:41
150,754,968
0
0
null
null
null
null
UTF-8
Java
false
false
214
java
package org.exoplatform.samples.dao; import org.exoplatform.commons.api.persistence.GenericDAO; import org.exoplatform.samples.entity.Produit; public interface ProduitDao extends GenericDAO < Produit, Long >{ }
e9ba9bffe76cd98dd2c3591833a988cd3f726045
a3b45dc2ae35c9b5e08cffb2341a3050b7c7b8ad
/Assertions/src/test/java/com/trainings/maven/Assertions/AbstractTest.java
34088b0e49f1e3835085724430927780bd80bf03
[]
no_license
IngaCha/Selenium_WebDriver_JAVA
d21a17c13d2e442ae3b930c50cc7a0f57d861019
0af3cee1390a1ab40e2477f132fce50a5b70a6c0
refs/heads/master
2021-06-27T04:18:37.881428
2020-10-13T19:03:29
2020-10-13T19:03:29
231,249,999
0
0
null
2021-05-18T20:27:08
2020-01-01T18:28:31
HTML
UTF-8
Java
false
false
582
java
package com.trainings.maven.Assertions; import org.junit.After; import org.junit.Before; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public abstract class AbstractTest { protected static WebDriver driver; @Before public void setUp() { System.setProperty("webdriver.chrome.driver", "resources/chromedriver.exe"); driver = new ChromeDriver(); driver.manage().window().maximize(); driver.get("http://akademijait.vtmc.lt/opencartone/"); } @After public void closeBrowser() { driver.quit(); } }
46b8752e8ae8d2ab1480a31c05e6b9a38f3f69d4
20eb62855cb3962c2d36fda4377dfd47d82eb777
/IntroClassJava/dataset/grade/9c9308d4cdf5bc5dfe6efc2b1a9c9bc9a44fbff73c5367c97e3be37861bbb3ba9ac7ad3ddec74dc66e34fe8f0804e46186819b4e90e8f9a59d1b82d9cf0a6218/007/mutations/60/grade_9c9308d4_007.java
597c6741bd6238816117e4c489ff841eed6977fe
[]
no_license
ozzydong/CapGen
356746618848065cce4e253e5d3c381baa85044a
0ba0321b6b1191443276021f1997833342f02515
refs/heads/master
2023-03-18T20:12:02.923428
2020-08-21T03:08:28
2020-08-21T03:08:28
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,418
java
package introclassJava; class IntObj { public int value; public IntObj () { } public IntObj (int i) { value = i; } } class FloatObj { public float value; public FloatObj () { } public FloatObj (float i) { value = i; } } class LongObj { public long value; public LongObj () { } public LongObj (long i) { value = i; } } class DoubleObj { public double value; public DoubleObj () { } public DoubleObj (double i) { value = i; } } class CharObj { public char value; public CharObj () { } public CharObj (char i) { value = i; } } public class grade_9c9308d4_007 { public java.util.Scanner scanner; public String output = ""; public static void main (String[]args) throws Exception { grade_9c9308d4_007 mainClass = new grade_9c9308d4_007 (); String output; if (args.length > 0) { mainClass.scanner = new java.util.Scanner (args[0]); } else { mainClass.scanner = new java.util.Scanner (System.in); } mainClass.exec (); System.out.println (mainClass.output); } public void exec () throws Exception { DoubleObj A = new DoubleObj (), B = new DoubleObj (), C = new DoubleObj (), D = new DoubleObj(value) , studentscore = new DoubleObj (); CharObj lettergrade = new CharObj (); output += (String.format ("Enter thresholds for A, B, C, D \nin that order, decreasing percentages > Thank you. ")); A.value = scanner.nextDouble (); B.value = scanner.nextDouble (); C.value = scanner.nextDouble (); D.value = scanner.nextDouble (); output += (String.format ("Now enter student score (perecnt) >")); studentscore.value = scanner.nextDouble (); if (studentscore.value >= A.value) { lettergrade.value = 'A'; } else if (studentscore.value >= B.value) { lettergrade.value = 'B'; } else if (studentscore.value >= C.value) { lettergrade.value = 'C'; } else if (studentscore.value >= D.value) { lettergrade.value = 'D'; } else { lettergrade.value = 'F'; } output += (String.format ("Student has an %c grade\n", lettergrade.value)); if (true) return;; } }
c6c201870d4f68346152dc00cd3b0f522006c7ef
137e04efe91827b45d72016b8cc82c9f22e8778c
/Proiect/src/main/java/Main.java
c3c4539bac92d25e62084e0dde7f90d5ba99c1b7
[]
no_license
alex-bucevschi/Lego
492b5780f0bb3978ca210d56414edf2d3bb9db44
225d3d22d77cef47eb42ef9117b86061e5b54ead
refs/heads/master
2020-04-07T17:18:13.679912
2019-01-16T15:00:35
2019-01-16T15:00:35
158,564,059
0
0
null
null
null
null
UTF-8
Java
false
false
6,274
java
import java.io.File; import java.io.FileWriter; import java.util.HashMap; import java.util.Map; import java.util.Vector; public class Main { public static void main(String argv[]){ //generateForm(3, "form.csv"); startBKT(); } private static void probe(){ SmartMatrix<Integer> m = new SmartMatrix<>(10,10); m.initMatrixWithElem(0); for(int i=3; i< 6; i++){ for(int j=2; j< 8; j++){ m.add(i,j, 1); } } m.print(); System.out.println('\n'); Vector<Integer> column = m.getColumn(1); for(int i=0; i<10; i++){ System.out.println(column.get(i)); } } public static void startBKT(){ //generateForm(2, "form.csv"); Form form = SolutionWriter.readForm("form.csv"); //SolutionWriter.formWrite("shit", form); if(form == null) return; form.print(1); Map<Integer, Integer> formTypes = new HashMap<>(); formTypes.put(1,100); formTypes.put(2,100); formTypes.put(3,100); formTypes.put(4,100); formTypes.put(5,100); SmartBCM smartBCM = new SmartBCM(form, formTypes); smartBCM.solve(); smartBCM.fillMatrix(); Form solvedFormOne = smartBCM.getResult(); SmartBCM smartBKT_1 = new SmartBCM(solvedFormOne, formTypes); smartBKT_1.solve(); Form solvedForm = smartBKT_1.getResult(); //solvedForm.print(solvedForm.getLength() - 2); solvedForm.print(23); SolutionWriter.formWrite("input", solvedForm); } public static void generateForm(int levels, String filename){ try { FileWriter fw = new FileWriter(new File("form.csv")); }catch (Exception e){} if(levels >= 1) { //LEVEL 1 SolutionWriter.manualWrite(filename, 1, 6, 9, 28, 19, "#FF0000"); SolutionWriter.manualWrite(filename, 1, 0, 17, 0, 19, "#FFFF00"); SolutionWriter.manualWrite(filename, 1, 4, 17, 4, 19, "#FFFF00"); SolutionWriter.manualWrite(filename, 1, 30, 17, 30, 19, "#FFFF00"); SolutionWriter.manualWrite(filename, 1, 34, 17, 34, 19, "#FFFF00"); } if(levels >= 2) { //LEVEL 2 SolutionWriter.manualWrite(filename, 2, 6, 9, 28, 19, "#FF0000"); SolutionWriter.manualWrite(filename, 2, 0, 16, 5, 17, "#FFFF00"); SolutionWriter.manualWrite(filename, 2, 30, 16, 34, 17, "#FFFF00"); SolutionWriter.manualWrite(filename, 2, 0, 18, 0, 20, "#FFFF00"); SolutionWriter.manualWrite(filename, 2, 4, 18, 4, 20, "#FFFF00"); SolutionWriter.manualWrite(filename, 2, 30, 18, 30, 20, "#FFFF00"); SolutionWriter.manualWrite(filename, 2, 34, 18, 34, 20, "#FFFF00"); } if(levels >= 3) { //LEVEL 3 SolutionWriter.manualWrite(filename, 3, 6, 9, 28, 19, "#FF0000"); SolutionWriter.manualWrite(filename, 3, 1, 15, 4, 18, "#FFFF00"); SolutionWriter.manualWrite(filename, 3, 30, 15, 4, 18, "#FFFF00"); SolutionWriter.manualWrite(filename, 3, 0, 17, 0, 19, "#FFFF00"); SolutionWriter.manualWrite(filename, 3, 34, 17, 34, 19, "#FFFF00"); SolutionWriter.manualWrite(filename, 3, 2, 14, 3, 14, "#FFFF00"); SolutionWriter.manualWrite(filename, 3, 31, 14, 32, 14, "#FFFF00"); SolutionWriter.manualWrite(filename, 3, 5, 19, 5, 19, "#FFFF00"); SolutionWriter.manualWrite(filename, 3, 30, 19, 30, 19, "#FFFF00"); } } public static void manualGenerator(){ Form form = new Form(3); SmartMatrix<Piece> level1 = new SmartMatrix<Piece>(10,10); SmartMatrix<Piece> level2 = new SmartMatrix<Piece>(10,10); SmartMatrix<Piece> level3 = new SmartMatrix<Piece>(10,10); level1.add(1,1,new Piece(1,1,1)); level1.add(1,2,new Piece(1,2,1)); level1.add(1,3,new Piece(1,3,1)); level1.add(1,4,new Piece(1,4,1)); level1.add(1,7,new Piece(1,7,1)); level1.add(1,8,new Piece(1,8,1)); level1.add(2,2,new Piece(2,2,1)); level1.add(2,3,new Piece(2,3,1)); level1.add(2,4,new Piece(2,4,1)); level1.add(2,5,new Piece(2,5,1)); level1.add(2,7,new Piece(2,7,1)); level1.add(2,8,new Piece(2,8,1)); level1.add(3,4,new Piece(3,4,1)); level1.add(3,6,new Piece(3,6,1)); level1.add(4,2,new Piece(4,2,1)); level1.add(4,3,new Piece(4,3,1)); level1.add(4,4,new Piece(4,4,1)); level1.add(4,5,new Piece(4,5,1)); level1.add(5,5,new Piece(5,5,1)); level1.add(5,6,new Piece(5,6,1)); level1.add(5,7,new Piece(5,7,1)); level1.add(5,8,new Piece(5,8,1)); level1.add(6,4,new Piece(6,4,1)); level1.add(6,5,new Piece(6,5,1)); //////////////////////////////////////////////////////// level2.add(1,7, new Piece(1,7,2, "#FF0000")); level2.add(1,8, new Piece(1,8,2, "#FF0000")); level2.add(2,2, new Piece(2,2,2, "#FF0000")); level2.add(2,3, new Piece(2,3,2, "#FF0000")); level2.add(2,4, new Piece(2,4,2, "#FF0000")); level2.add(2,5, new Piece(2,5,2, "#FF0000")); level2.add(2,6, new Piece(2,6,2, "#FF0000")); level2.add(2,7, new Piece(2,7,2, "#FF0000")); level2.add(4,3, new Piece(4,3,2, "#FF0000")); level2.add(4,4, new Piece(4,4,2, "#FF0000")); level2.add(4,5, new Piece(4,5,2, "#FF0000")); level2.add(5,5, new Piece(5,5,2, "#FF0000")); level2.add(5,6, new Piece(5,6,2, "#FF0000")); level2.add(5,7, new Piece(5,7,2, "#FF0000")); level2.add(5,8, new Piece(5,8,2, "#FF0000")); //////////////////////////////////////////////////////// level3.add(1,7, new Piece(1,7,3, "#0000FF")); level3.add(2,7, new Piece(2,7,3, "#0000FF")); level3.add(4,5, new Piece(4,5,3, "#0000FF")); level3.add(5,5, new Piece(5,5,3, "#0000FF")); form.addLevel(0,level1); form.addLevel(1,level2); form.addLevel(2,level3); SolutionWriter.formWrite("input",form); } }
da3b17e9686eefd8ed749ee3d4714bfee5b3eff5
f48f2143e3b6f8a63e5de603ec7431735c8c9b68
/src/com/urgoo/domain/Data.java
720bcd499694985c94580258343f3fd904ae1b19
[ "Apache-2.0" ]
permissive
BibiNiao/urgoo_client
e906a2eba0be87e0c4323aa404978537c077b608
571aae350f64cf05e857d3d1ef5a08d5c61d78e3
refs/heads/master
2020-09-16T17:26:12.842533
2016-08-31T07:45:53
2016-08-31T07:45:53
67,017,780
0
0
null
null
null
null
UTF-8
Java
false
false
637
java
package com.urgoo.domain; import java.io.Serializable; /** * Created by lijie on 2016/4/14. */ public class Data implements Serializable { private String key; private String value; @Override public String toString() { return "Data{" + "key='" + key + '\'' + ", value='" + value + '\'' + '}'; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
eebd02c5e3f7d216f61f1724908b72c7c876844a
7cbbc908897100804fd92327ec9658fad0e292b2
/H.java
bbad14df9392826f44095577f10ab012f4fc8c0c
[]
no_license
rjsaurav13/HacKerearth
f597c70e5f8564f5b8d4b932804414dab353325a
19d01b36a0f1ed6d7fd26c1499f5df63918a8b89
refs/heads/master
2023-05-05T19:49:36.044293
2021-05-21T13:41:57
2021-05-21T13:41:57
324,346,723
4
0
null
null
null
null
UTF-8
Java
false
false
230
java
package javahe; import java.util.Scanner; public class H { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int num = scanner.nextInt(); System.out.println(num); scanner.close(); } }
ed9a2ea249734fe890e4bad232b3a62d9392b658
3bbd6dd3db7be180a24eaffe29f011546ae1d361
/modules/dcc-commons/src/main/java/org/metaeffekt/dcc/commons/mapping/ExpressionAttributeMapper.java
64b749a1584a73fd033b4c6fd782c1018c6c49b5
[ "Apache-2.0", "MIT" ]
permissive
org-metaeffekt/metaeffekt-dcc
bc2ba5c70f8ed17cac259db1f7081bdc874d2ce2
18c5fb053bf1d9814e73c5cea5e9155905e573de
refs/heads/master
2023-06-01T10:30:52.962780
2021-02-28T17:59:13
2021-02-28T17:59:13
70,954,885
0
0
Apache-2.0
2023-04-14T19:30:39
2016-10-14T23:51:04
Java
UTF-8
Java
false
false
2,523
java
/** * Copyright 2009-2017 the original author or authors. * * 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.metaeffekt.dcc.commons.mapping; import org.metaeffekt.dcc.commons.DccUtils; /** * Concrete implementation of the {@link AttributeMapper} interface using expressions to derive * a single attribute value. * * @author Karsten Klein */ public class ExpressionAttributeMapper extends AbstractSingleAttributeMapper { private final String expression; public ExpressionAttributeMapper(String attributeKey, String expression) { super(attributeKey); this.expression = expression; } public String getExpression() { return expression; } public void evaluate(PropertiesHolder propertiesHolder, Capability targetCapability, Profile profile) { final ConfigurationUnit boundUnit = targetCapability.getUnit(); final UnitScopePropertyExpression expressionEval = new UnitScopePropertyExpression(propertiesHolder, boundUnit); // FIXME: refactoring required. Implement strategy to handle overwrites centrally. final String attributeKey = getAttributeKey(); // check whether overwrite exists final String globalKey = DccUtils.deriveAttributeIdentifier(targetCapability, attributeKey); String expression = propertiesHolder.getBaseProperty(globalKey, null); // otherwise use the expression value if (expression == null) { expression = getExpression(); } final String expressionvalue = expressionEval.evaluate(expression); propertiesHolder.setProperty(targetCapability, attributeKey, expressionvalue); // NOTE: please note that defaults are not executed on this level. If an expression evaluates to null. // this result will take priority over the default. Currently the default however is not accessible // from the expression. This was however not yet required in any scenario. } }
a38b327b8958465a2124b850b1b7da05c9c51a6f
c83d0b6dabfcdcff8699a2696cc9bf5c2ea48c7f
/src/main/java/com/test/service/Greeting.java
7a6acd6aeb6086f356a3396d30f2f4884a159af7
[]
no_license
zongweiyang/WebsocketTest
e532627c8267ebfb43fc35c06efaf306b0e239b3
3152dc120e0ee2078b87ca0c3b856cdbd8106c3d
refs/heads/master
2021-01-10T01:47:25.293530
2016-08-13T00:43:13
2016-08-13T00:43:13
49,779,982
0
0
null
null
null
null
UTF-8
Java
false
false
286
java
package com.test.service; /** * Created by yzw on 2016/1/18. * message content */ public class Greeting { private String content; public Greeting(String content) { this.content = content; } public String getContent(){ return this.content; } }
1f3fe1b6f699dd6290dbc3704e476c30083e0000
8cca913b3b620524eb8f4ac37df10998570fd755
/src/cui/litang/cuimarket/bean/AppInfo.java
682db684e706a2b29710166133084d7f932b140e
[ "Apache-2.0" ]
permissive
cuilitang/CuiMarket
1c5b92ac55eaeb4a899169a2ff0cf79c9f5badae
5ef6eefea6c0c20fe8bc467fec31d6284d426316
refs/heads/master
2021-01-21T14:04:45.174778
2016-05-20T03:43:38
2016-05-20T03:43:38
50,275,263
2
0
null
null
null
null
UTF-8
Java
false
false
3,216
java
package cui.litang.cuimarket.bean; import java.util.List; /** * Created by mwqi on 2014/6/7. */ public class AppInfo { private long id;//app的id private String name;//app的软件名称 private String packageName;//app的包名 private String iconUrl;//app的icon地址 private float stars;//app的评价星级 private String downloadNum;//app的下载数量 private String version;//app的版本 private String date;//app的发布日期 private long size;//app的size private String downloadUrl;//下载地址 private String des;//简介 private String author; //作者 private List<String> screen;//截图下载地址 private List<String> safeUrl;//安全信息图片地址 private List<String> safeDesUrl;//安全信息图片勾勾地址 private List<String> safeDes;//安全信息图片勾勾后面描述信息 private List<Integer> safeDesColor;//安全信息的文字颜色 public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPackageName() { return packageName; } public void setPackageName(String packageName) { this.packageName = packageName; } public String getIconUrl() { return iconUrl; } public void setIconUrl(String iconUrl) { this.iconUrl = iconUrl; } public float getStars() { return stars; } public void setStars(float stars) { this.stars = stars; } public String getDownloadNum() { return downloadNum; } public void setDownloadNum(String downloadNum) { this.downloadNum = downloadNum; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public long getSize() { return size; } public void setSize(long size) { this.size = size; } public String getDownloadUrl() { return downloadUrl; } public void setDownloadUrl(String downloadUrl) { this.downloadUrl = downloadUrl; } public String getDes() { return des; } public void setDes(String des) { this.des = des; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public List<String> getScreen() { return screen; } public void setScreen(List<String> screen) { this.screen = screen; } public List<String> getSafeUrl() { return safeUrl; } public void setSafeUrl(List<String> safeUrl) { this.safeUrl = safeUrl; } public List<String> getSafeDesUrl() { return safeDesUrl; } public void setSafeDesUrl(List<String> safeDesUrl) { this.safeDesUrl = safeDesUrl; } public List<String> getSafeDes() { return safeDes; } public void setSafeDes(List<String> safeDes) { this.safeDes = safeDes; } public List<Integer> getSafeDesColor() { return safeDesColor; } public void setSafeDesColor(List<Integer> safeDesColor) { this.safeDesColor = safeDesColor; } }
03038f93a7a850c71c71fde9f9f1a4ee5828faac
7c20e36b535f41f86b2e21367d687ea33d0cb329
/Capricornus/src/com/gopawpaw/erp/hibernate/s/ScMstrDAO.java
957979a80b378e534eaea98e2895a7f2f2402705
[]
no_license
fazoolmail89/gopawpaw
50c95b924039fa4da8f309e2a6b2ebe063d48159
b23ccffce768a3d58d7d71833f30b85186a50cc5
refs/heads/master
2016-09-08T02:00:37.052781
2014-05-14T11:46:18
2014-05-14T11:46:18
35,091,153
1
1
null
null
null
null
UTF-8
Java
false
false
3,942
java
package com.gopawpaw.erp.hibernate.s; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.LockMode; import org.springframework.context.ApplicationContext; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; /** * A data access object (DAO) providing persistence and search support for * ScMstr entities. Transaction control of the save(), update() and delete() * operations can directly support Spring container-managed transactions or they * can be augmented to handle user-managed Spring transactions. Each of these * methods provides additional information for how to configure it for the * desired type of transaction control. * * @see com.gopawpaw.erp.hibernate.s.ScMstr * @author MyEclipse Persistence Tools */ public class ScMstrDAO extends HibernateDaoSupport { private static final Log log = LogFactory.getLog(ScMstrDAO.class); protected void initDao() { // do nothing } public void save(ScMstr transientInstance) { log.debug("saving ScMstr instance"); try { getHibernateTemplate().save(transientInstance); log.debug("save successful"); } catch (RuntimeException re) { log.error("save failed", re); throw re; } } public void delete(ScMstr persistentInstance) { log.debug("deleting ScMstr instance"); try { getHibernateTemplate().delete(persistentInstance); log.debug("delete successful"); } catch (RuntimeException re) { log.error("delete failed", re); throw re; } } public ScMstr findById(com.gopawpaw.erp.hibernate.s.ScMstrId id) { log.debug("getting ScMstr instance with id: " + id); try { ScMstr instance = (ScMstr) getHibernateTemplate().get( "com.gopawpaw.erp.hibernate.s.ScMstr", id); return instance; } catch (RuntimeException re) { log.error("get failed", re); throw re; } } public List findByExample(ScMstr instance) { log.debug("finding ScMstr instance by example"); try { List results = getHibernateTemplate().findByExample(instance); log.debug("find by example successful, result size: " + results.size()); return results; } catch (RuntimeException re) { log.error("find by example failed", re); throw re; } } public List findByProperty(String propertyName, Object value) { log.debug("finding ScMstr instance with property: " + propertyName + ", value: " + value); try { String queryString = "from ScMstr as model where model." + propertyName + "= ?"; return getHibernateTemplate().find(queryString, value); } catch (RuntimeException re) { log.error("find by property name failed", re); throw re; } } public List findAll() { log.debug("finding all ScMstr instances"); try { String queryString = "from ScMstr"; return getHibernateTemplate().find(queryString); } catch (RuntimeException re) { log.error("find all failed", re); throw re; } } public ScMstr merge(ScMstr detachedInstance) { log.debug("merging ScMstr instance"); try { ScMstr result = (ScMstr) getHibernateTemplate().merge( detachedInstance); log.debug("merge successful"); return result; } catch (RuntimeException re) { log.error("merge failed", re); throw re; } } public void attachDirty(ScMstr instance) { log.debug("attaching dirty ScMstr instance"); try { getHibernateTemplate().saveOrUpdate(instance); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } public void attachClean(ScMstr instance) { log.debug("attaching clean ScMstr instance"); try { getHibernateTemplate().lock(instance, LockMode.NONE); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } public static ScMstrDAO getFromApplicationContext(ApplicationContext ctx) { return (ScMstrDAO) ctx.getBean("ScMstrDAO"); } }
[ "ahuaness@b3021582-c689-11de-ba9a-9db95b2bc6c5" ]
ahuaness@b3021582-c689-11de-ba9a-9db95b2bc6c5
1c9d3d51c2b3a12304e9b74073e4cb8ad11c84b8
84b11976e0b4c07347aaa2a45a439b6d009650d6
/src/main/java/de/pmenke/watchflux/postgres/replication/ReplicationStatCollector.java
712405d7f716f86b98b000154a6ab2ed2c575249
[ "Apache-2.0" ]
permissive
pmenke-de/watchflux
e20020baa8ab9d223aaeef26abce37e0952dae58
3b0119a2aba80ece48d852d34f9e6502261f70f5
refs/heads/master
2020-12-03T00:35:26.854213
2017-07-02T20:28:35
2017-07-02T20:29:33
96,047,229
0
0
null
null
null
null
UTF-8
Java
false
false
2,113
java
package de.pmenke.watchflux.postgres.replication; import de.pmenke.watchflux.postgres.PostgresWatchConfig; import org.influxdb.InfluxDB; import org.influxdb.dto.Point; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Scheduled; import java.sql.*; import java.util.concurrent.TimeUnit; /** * Created by pmenke on 02.07.17. */ public class ReplicationStatCollector { private final Logger LOG = LoggerFactory.getLogger(ReplicationStatCollector.class); private final PostgresWatchConfig watchConfig; private final InfluxDB influxDB; public ReplicationStatCollector(PostgresWatchConfig watchConfig, InfluxDB influxDB) { this.watchConfig = watchConfig; this.influxDB = influxDB; LOG.info("Registered PostgreSQL replication checks: {}", watchConfig.getArchiver()); } @Scheduled(fixedDelay = 10000) public void runIteration() { for (ReplicationStatTask statTask : watchConfig.getReplication()) { try(final Connection c = DriverManager.getConnection(statTask.getUrl(), statTask.getUsername(), statTask.getPassword()); final PreparedStatement pstmt = c.prepareStatement("SELECT status FROM pglogical.show_subscription_status(?)")) { pstmt.setString(1, statTask.getSubscriptionName()); try(final ResultSet rs = pstmt.executeQuery()) { while (rs.next()) { final Point.Builder point = Point.measurement("postgres_replication") .time(System.currentTimeMillis(), TimeUnit.MILLISECONDS) .tag("label", statTask.getLabel()) .addField("subscription_name", statTask.getSubscriptionName()) .addField("status", rs.getString("status")); influxDB.write(point.build()); } } } catch (SQLException e) { LOG.error("Unable to get database connection", e); } } } }
26ca7009365e1e09509c3ed9a332e0c6cfcbe0f1
5fd25a97ca8ac0b5f4e92d5babe52add1d643703
/src/main/java/com/thinkgem/jeesite/common/utils/IdcardUtils.java
36353dbbaa3e84c82cba60ed2ec4844de41de8cd
[]
no_license
zjj-clode/xingzhengguanli2
dc2e882956c37fd63cec9c6d5212a9f045362fe0
c9f93d1d30eeef077444cc1806844d9d8f003d4a
refs/heads/master
2022-12-23T05:12:28.631780
2019-12-31T07:34:10
2019-12-31T07:34:10
231,047,853
0
0
null
2022-12-16T09:57:23
2019-12-31T07:33:33
JavaScript
UTF-8
Java
false
false
15,987
java
package com.thinkgem.jeesite.common.utils; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang3.StringUtils; /** * 身份证工具类 * * @author June * @version 1.0, 2010-06-17 */ public class IdcardUtils extends StringUtils { /** 中国公民身份证号码最小长度。 */ public static final int CHINA_ID_MIN_LENGTH = 15; /** 中国公民身份证号码最大长度。 */ public static final int CHINA_ID_MAX_LENGTH = 18; /** 省、直辖市代码表 */ public static final String cityCode[] = { "11", "12", "13", "14", "15", "21", "22", "23", "31", "32", "33", "34", "35", "36", "37", "41", "42", "43", "44", "45", "46", "50", "51", "52", "53", "54", "61", "62", "63", "64", "65", "71", "81", "82", "91" }; /** 每位加权因子 */ public static final int power[] = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 }; /** 第18位校检码 */ public static final String verifyCode[] = { "1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2" }; /** 最低年限 */ public static final int MIN = 1930; public static Map<String, String> cityCodes = new HashMap<String, String>(); /** 台湾身份首字母对应数字 */ public static Map<String, Integer> twFirstCode = new HashMap<String, Integer>(); /** 香港身份首字母对应数字 */ public static Map<String, Integer> hkFirstCode = new HashMap<String, Integer>(); static { cityCodes.put("11", "北京"); cityCodes.put("12", "天津"); cityCodes.put("13", "河北"); cityCodes.put("14", "山西"); cityCodes.put("15", "内蒙古"); cityCodes.put("21", "辽宁"); cityCodes.put("22", "吉林"); cityCodes.put("23", "黑龙江"); cityCodes.put("31", "上海"); cityCodes.put("32", "江苏"); cityCodes.put("33", "浙江"); cityCodes.put("34", "安徽"); cityCodes.put("35", "福建"); cityCodes.put("36", "江西"); cityCodes.put("37", "山东"); cityCodes.put("41", "河南"); cityCodes.put("42", "湖北"); cityCodes.put("43", "湖南"); cityCodes.put("44", "广东"); cityCodes.put("45", "广西"); cityCodes.put("46", "海南"); cityCodes.put("50", "重庆"); cityCodes.put("51", "四川"); cityCodes.put("52", "贵州"); cityCodes.put("53", "云南"); cityCodes.put("54", "西藏"); cityCodes.put("61", "陕西"); cityCodes.put("62", "甘肃"); cityCodes.put("63", "青海"); cityCodes.put("64", "宁夏"); cityCodes.put("65", "新疆"); cityCodes.put("71", "台湾"); cityCodes.put("81", "香港"); cityCodes.put("82", "澳门"); cityCodes.put("91", "国外"); twFirstCode.put("A", 10); twFirstCode.put("B", 11); twFirstCode.put("C", 12); twFirstCode.put("D", 13); twFirstCode.put("E", 14); twFirstCode.put("F", 15); twFirstCode.put("G", 16); twFirstCode.put("H", 17); twFirstCode.put("J", 18); twFirstCode.put("K", 19); twFirstCode.put("L", 20); twFirstCode.put("M", 21); twFirstCode.put("N", 22); twFirstCode.put("P", 23); twFirstCode.put("Q", 24); twFirstCode.put("R", 25); twFirstCode.put("S", 26); twFirstCode.put("T", 27); twFirstCode.put("U", 28); twFirstCode.put("V", 29); twFirstCode.put("X", 30); twFirstCode.put("Y", 31); twFirstCode.put("W", 32); twFirstCode.put("Z", 33); twFirstCode.put("I", 34); twFirstCode.put("O", 35); hkFirstCode.put("A", 1); hkFirstCode.put("B", 2); hkFirstCode.put("C", 3); hkFirstCode.put("R", 18); hkFirstCode.put("U", 21); hkFirstCode.put("Z", 26); hkFirstCode.put("X", 24); hkFirstCode.put("W", 23); hkFirstCode.put("O", 15); hkFirstCode.put("N", 14); } /** * 将15位身份证号码转换为18位 * * @param idCard * 15位身份编码 * @return 18位身份编码 */ public static String conver15CardTo18(String idCard) { String idCard18 = ""; if (idCard.length() != CHINA_ID_MIN_LENGTH) { return null; } if (isNum(idCard)) { // 获取出生年月日 String birthday = idCard.substring(6, 12); Date birthDate = null; try { birthDate = new SimpleDateFormat("yyMMdd").parse(birthday); } catch (ParseException e) { e.printStackTrace(); } Calendar cal = Calendar.getInstance(); if (birthDate != null) cal.setTime(birthDate); // 获取出生年(完全表现形式,如:2010) String sYear = String.valueOf(cal.get(Calendar.YEAR)); idCard18 = idCard.substring(0, 6) + sYear + idCard.substring(8); // 转换字符数组 char[] cArr = idCard18.toCharArray(); if (cArr != null) { int[] iCard = converCharToInt(cArr); int iSum17 = getPowerSum(iCard); // 获取校验位 String sVal = getCheckCode18(iSum17); if (sVal.length() > 0) { idCard18 += sVal; } else { return null; } } } else { return null; } return idCard18; } /** * 验证身份证是否合法 */ public static boolean validateCard(String idCard) { String card = idCard.trim(); if (validateIdCard18(card)) { return true; } if (validateIdCard15(card)) { return true; } String[] cardval = validateIdCard10(card); if (cardval != null) { if (cardval[2].equals("true")) { return true; } } return false; } /** * 验证18位身份编码是否合法 * * @param idCard * 身份编码 * @return 是否合法 */ public static boolean validateIdCard18(String idCard) { boolean bTrue = false; if (idCard.length() == CHINA_ID_MAX_LENGTH) { // 前17位 String code17 = idCard.substring(0, 17); // 第18位 String code18 = idCard.substring(17, CHINA_ID_MAX_LENGTH); if (isNum(code17)) { char[] cArr = code17.toCharArray(); if (cArr != null) { int[] iCard = converCharToInt(cArr); int iSum17 = getPowerSum(iCard); // 获取校验位 String val = getCheckCode18(iSum17); if (val.length() > 0) { if (val.equalsIgnoreCase(code18)) { bTrue = true; } } } } } return bTrue; } /** * 验证15位身份编码是否合法 * * @param idCard * 身份编码 * @return 是否合法 */ public static boolean validateIdCard15(String idCard) { if (idCard.length() != CHINA_ID_MIN_LENGTH) { return false; } if (isNum(idCard)) { String proCode = idCard.substring(0, 2); if (cityCodes.get(proCode) == null) { return false; } String birthCode = idCard.substring(6, 12); Date birthDate = null; try { birthDate = new SimpleDateFormat("yy").parse(birthCode .substring(0, 2)); } catch (ParseException e) { e.printStackTrace(); } Calendar cal = Calendar.getInstance(); if (birthDate != null) cal.setTime(birthDate); if (!valiDate(cal.get(Calendar.YEAR), Integer.valueOf(birthCode.substring(2, 4)), Integer.valueOf(birthCode.substring(4, 6)))) { return false; } } else { return false; } return true; } /** * 验证10位身份编码是否合法 * * @param idCard * 身份编码 * @return 身份证信息数组 * <p> * [0] - 台湾、澳门、香港 [1] - 性别(男M,女F,未知N) [2] - 是否合法(合法true,不合法false) * 若不是身份证件号码则返回null * </p> */ public static String[] validateIdCard10(String idCard) { String[] info = new String[3]; String card = idCard.replaceAll("[\\(|\\)]", ""); if (card.length() != 8 && card.length() != 9 && idCard.length() != 10) { return null; } if (idCard.matches("^[a-zA-Z][0-9]{9}$")) { // 台湾 info[0] = "台湾"; //System.out.println("11111"); String char2 = idCard.substring(1, 2); if (char2.equals("1")) { info[1] = "M"; //System.out.println("MMMMMMM"); } else if (char2.equals("2")) { info[1] = "F"; //System.out.println("FFFFFFF"); } else { info[1] = "N"; info[2] = "false"; //System.out.println("NNNN"); return info; } info[2] = validateTWCard(idCard) ? "true" : "false"; } else if (idCard.matches("^[1|5|7][0-9]{6}\\(?[0-9A-Z]\\)?$")) { // 澳门 info[0] = "澳门"; info[1] = "N"; } else if (idCard.matches("^[A-Z]{1,2}[0-9]{6}\\(?[0-9A]\\)?$")) { // 香港 info[0] = "香港"; info[1] = "N"; info[2] = validateHKCard(idCard) ? "true" : "false"; } else { return null; } return info; } /** * 验证台湾身份证号码 * * @param idCard * 身份证号码 * @return 验证码是否符合 */ public static boolean validateTWCard(String idCard) { String start = idCard.substring(0, 1); String mid = idCard.substring(1, 9); String end = idCard.substring(9, 10); Integer iStart = twFirstCode.get(start); Integer sum = iStart / 10 + (iStart % 10) * 9; char[] chars = mid.toCharArray(); Integer iflag = 8; for (char c : chars) { sum = sum + Integer.valueOf(c + "") * iflag; iflag--; } return (sum % 10 == 0 ? 0 : (10 - sum % 10)) == Integer.valueOf(end) ? true : false; } /** * 验证香港身份证号码(存在Bug,部份特殊身份证无法检查) * <p> * 身份证前2位为英文字符,如果只出现一个英文字符则表示第一位是空格,对应数字58 前2位英文字符A-Z分别对应数字10-35 * 最后一位校验码为0-9的数字加上字符"A","A"代表10 * </p> * <p> * 将身份证号码全部转换为数字,分别对应乘9-1相加的总和,整除11则证件号码有效 * </p> * * @param idCard * 身份证号码 * @return 验证码是否符合 */ public static boolean validateHKCard(String idCard) { String card = idCard.replaceAll("[\\(|\\)]", ""); Integer sum = 0; if (card.length() == 9) { sum = (Integer.valueOf(card.substring(0, 1).toUpperCase() .toCharArray()[0]) - 55) * 9 + (Integer.valueOf(card.substring(1, 2).toUpperCase() .toCharArray()[0]) - 55) * 8; card = card.substring(1, 9); } else { sum = 522 + (Integer.valueOf(card.substring(0, 1).toUpperCase() .toCharArray()[0]) - 55) * 8; } String mid = card.substring(1, 7); String end = card.substring(7, 8); char[] chars = mid.toCharArray(); Integer iflag = 7; for (char c : chars) { sum = sum + Integer.valueOf(c + "") * iflag; iflag--; } if (end.toUpperCase().equals("A")) { sum = sum + 10; } else { sum = sum + Integer.valueOf(end); } return (sum % 11 == 0) ? true : false; } /** * 将字符数组转换成数字数组 * * @param ca * 字符数组 * @return 数字数组 */ public static int[] converCharToInt(char[] ca) { int len = ca.length; int[] iArr = new int[len]; try { for (int i = 0; i < len; i++) { iArr[i] = Integer.parseInt(String.valueOf(ca[i])); } } catch (NumberFormatException e) { e.printStackTrace(); } return iArr; } /** * 将身份证的每位和对应位的加权因子相乘之后,再得到和值 * * @param iArr * @return 身份证编码。 */ public static int getPowerSum(int[] iArr) { int iSum = 0; if (power.length == iArr.length) { for (int i = 0; i < iArr.length; i++) { for (int j = 0; j < power.length; j++) { if (i == j) { iSum = iSum + iArr[i] * power[j]; } } } } return iSum; } /** * 将power和值与11取模获得余数进行校验码判断 * * @param iSum * @return 校验位 */ public static String getCheckCode18(int iSum) { String sCode = ""; switch (iSum % 11) { case 10: sCode = "2"; break; case 9: sCode = "3"; break; case 8: sCode = "4"; break; case 7: sCode = "5"; break; case 6: sCode = "6"; break; case 5: sCode = "7"; break; case 4: sCode = "8"; break; case 3: sCode = "9"; break; case 2: sCode = "x"; break; case 1: sCode = "0"; break; case 0: sCode = "1"; break; } return sCode; } /** * 根据身份编号获取年龄 * * @param idCard * 身份编号 * @return 年龄 */ public static int getAgeByIdCard(String idCard) { int iAge = 0; if (idCard.length() == CHINA_ID_MIN_LENGTH) { idCard = conver15CardTo18(idCard); } String year = idCard.substring(6, 10); Calendar cal = Calendar.getInstance(); int iCurrYear = cal.get(Calendar.YEAR); iAge = iCurrYear - Integer.valueOf(year); return iAge; } /** * 根据身份编号获取生日 * * @param idCard * 身份编号 * @return 生日(yyyyMMdd) */ public static String getBirthByIdCard(String idCard) { Integer len = idCard.length(); if (len < CHINA_ID_MIN_LENGTH) { return null; } else if (len == CHINA_ID_MIN_LENGTH) { idCard = conver15CardTo18(idCard); } return idCard.substring(6, 14); } /** * 根据身份编号获取生日年 * * @param idCard * 身份编号 * @return 生日(yyyy) */ public static Short getYearByIdCard(String idCard) { Integer len = idCard.length(); if (len < CHINA_ID_MIN_LENGTH) { return null; } else if (len == CHINA_ID_MIN_LENGTH) { idCard = conver15CardTo18(idCard); } return Short.valueOf(idCard.substring(6, 10)); } /** * 根据身份编号获取生日月 * * @param idCard * 身份编号 * @return 生日(MM) */ public static Short getMonthByIdCard(String idCard) { Integer len = idCard.length(); if (len < CHINA_ID_MIN_LENGTH) { return null; } else if (len == CHINA_ID_MIN_LENGTH) { idCard = conver15CardTo18(idCard); } return Short.valueOf(idCard.substring(10, 12)); } /** * 根据身份编号获取生日天 * * @param idCard * 身份编号 * @return 生日(dd) */ public static Short getDateByIdCard(String idCard) { Integer len = idCard.length(); if (len < CHINA_ID_MIN_LENGTH) { return null; } else if (len == CHINA_ID_MIN_LENGTH) { idCard = conver15CardTo18(idCard); } return Short.valueOf(idCard.substring(12, 14)); } /** * 根据身份编号获取性别 * * @param idCard * 身份编号 * @return 性别(M-男,F-女,N-未知) */ public static String getGenderByIdCard(String idCard) { String sGender = "N"; if (idCard.length() == CHINA_ID_MIN_LENGTH) { idCard = conver15CardTo18(idCard); } String sCardNum = idCard.substring(16, 17); if (Integer.parseInt(sCardNum) % 2 != 0) { sGender = "M"; } else { sGender = "F"; } return sGender; } /** * 根据身份编号获取户籍省份 * * @param idCard * 身份编码 * @return 省级编码。 */ public static String getProvinceByIdCard(String idCard) { int len = idCard.length(); String sProvince = null; String sProvinNum = ""; if (len == CHINA_ID_MIN_LENGTH || len == CHINA_ID_MAX_LENGTH) { sProvinNum = idCard.substring(0, 2); } sProvince = cityCodes.get(sProvinNum); return sProvince; } /** * 数字验证 * * @param val * @return 提取的数字。 */ public static boolean isNum(String val) { return val == null || "".equals(val) ? false : val.matches("^[0-9]*$"); } /** * 验证小于当前日期 是否有效 * * @param iYear * 待验证日期(年) * @param iMonth * 待验证日期(月 1-12) * @param iDate * 待验证日期(日) * @return 是否有效 */ public static boolean valiDate(int iYear, int iMonth, int iDate) { Calendar cal = Calendar.getInstance(); int year = cal.get(Calendar.YEAR); int datePerMonth; if (iYear < MIN || iYear >= year) { return false; } if (iMonth < 1 || iMonth > 12) { return false; } switch (iMonth) { case 4: case 6: case 9: case 11: datePerMonth = 30; break; case 2: boolean dm = ((iYear % 4 == 0 && iYear % 100 != 0) || (iYear % 400 == 0)) && (iYear > MIN && iYear < year); datePerMonth = dm ? 29 : 28; break; default: datePerMonth = 31; } return (iDate >= 1) && (iDate <= datePerMonth); } }
c11a602b1edc1b66ffbc0a8e7fd56f982966191e
fe98b0e44f2024a86a6e9e51308e9c3487f30f09
/app/src/test/java/com/example/a94004/coolweather/ExampleUnitTest.java
0825e0370a9bf3613298468ef12f8d2e69719ba1
[]
no_license
Rotlisme/CoolWeather
35df6f4b46fb8a9111ee0cee58e46233928b59bb
abb2fef665c929bebc63f57b9ae8f18ad659265d
refs/heads/master
2020-11-30T00:31:13.329159
2017-06-28T14:29:20
2017-06-28T14:29:20
95,677,903
0
0
null
null
null
null
UTF-8
Java
false
false
408
java
package com.example.a94004.coolweather; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
db5472125f2eee458bb46ec4112b154a7e9bd173
0e14687eb28c2c16adc4a12a1e03fc4b0300d606
/src/Grafo.java
29102859d32821a72330d217663ebe63928d4bb3
[]
no_license
Felipe-Cjesus/Teoria-de-Grafos-Dijkstra
03fbe1cfc53b32f3c7138b74b6a98d6d84aacb89
a758e53336f6d49a565438a192a573aa731b254c
refs/heads/master
2023-08-31T11:19:10.159952
2021-10-14T01:06:59
2021-10-14T01:06:59
416,943,388
0
0
null
null
null
null
ISO-8859-1
Java
false
false
3,855
java
import java.security.InvalidAlgorithmParameterException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; public class Grafo { private static final int INDEFINIDO = -1; private int vertices[][]; /** * Contrutor padrao. * @param numVertices * Numero total de vertices deste grafo. */ public Grafo(final int numVertices) { vertices = new int[numVertices][numVertices]; } /** * Cria uma aresta no grafo. * @param noOrigem * Nó origem * @param noDestino * Nó destino * @param peso * Distancia * @throws InvalidAlgorithmParameterException * Levanta esta excessao caso o método receber um peso negativo. */ public void criaAresta(final int noOrigem, final int noDestino, final int peso) throws InvalidAlgorithmParameterException { // // Se possuir peso ... // if (peso >= 0) { vertices[noOrigem][noDestino] = peso; vertices[noDestino][noOrigem] = peso; } else { throw new InvalidAlgorithmParameterException("O peso do no origem ["+noOrigem+"] para o no destino ["+noDestino+"] não pode ser negativo ["+peso+"]"); } } /** * @return * O custo entre os dois vertices. */ public int getCusto(final int noOrigem, final int noDestino) { int custo = 0; if (noOrigem > vertices.length) { throw new ArrayIndexOutOfBoundsException("No origem ["+noOrigem+"] não existe no grafo"); } else if (noDestino > vertices.length) { throw new ArrayIndexOutOfBoundsException("No destino ["+noDestino+"] não existe no grafo"); } else { custo = vertices[noOrigem][noDestino]; } return custo; } public List<Integer> getVizinhos(final int no) { List<Integer> vizinhos = new ArrayList<Integer>(); for (int i = 0; i < vertices[no].length; i++) { if (vertices[no][i] > 0) { vizinhos.add(i); } } return vizinhos; } public int getMaisProximo(final int listaCusto[], final Set<Integer> listaNaoVisitados) { double minDistancia = Integer.MAX_VALUE; int noProximo = 0; for (Integer i : listaNaoVisitados) { if (listaCusto[i] < minDistancia) { minDistancia = listaCusto[i]; noProximo = i; } } return noProximo; } public List<Integer> caminhoMinimo(final int noOrigem, final int noDestino) { // Variaveis de controle. int custo[] = new int[vertices.length]; int antecessor[] = new int[vertices.length]; Set<Integer> naoVisitados = new HashSet<Integer>(); // Custo inicial do noOrigem ZERO. custo[noOrigem] = 0; // Define que todos os outros vertices, diferentes do nó origem tem peso infinito. for (int v = 0; v < vertices.length; v++) { if (v != noOrigem) { custo[v] = Integer.MAX_VALUE; // Simboliza o infinito. } antecessor[v] = INDEFINIDO; naoVisitados.add(v); } while (!naoVisitados.isEmpty()) { // Busca o vertice não visitado mais peóximo. int noMaisProximo = getMaisProximo(custo, naoVisitados); // Retira da lista. naoVisitados.remove(noMaisProximo); for (Integer vizinho : getVizinhos(noMaisProximo)) { int custoTotal = custo[noMaisProximo] + getCusto(noMaisProximo, vizinho); if (custoTotal < custo[vizinho]) { custo[vizinho] = custoTotal; antecessor[vizinho] = noMaisProximo; } } if (noMaisProximo == noDestino) { return caminhoMaisProximo(antecessor, noMaisProximo); } } return Collections.emptyList(); } private List<Integer> caminhoMaisProximo(final int antecessor[], int noMaisProximo) { List<Integer> caminho = new ArrayList<Integer>(); caminho.add(noMaisProximo); while (antecessor[noMaisProximo] != INDEFINIDO) { caminho.add(antecessor[noMaisProximo]); noMaisProximo = antecessor[noMaisProximo]; } Collections.reverse(caminho); return caminho; } }
[ "faladorf10@hotmail" ]
faladorf10@hotmail
fafaa7f7eacfc6f5116bbb25af208310a72c6e62
c738966ed7ebf56f68839fb735964635d2473073
/apps/server/src/test/java/it/polimi/ingsw/server/actions/GetAtActionTest.java
29b6f9a5a6bc0940fbbb413d43650617a166a4f3
[]
no_license
MarcoSpeziali/ing-sw-2018-romano-savoldelli-speziali
4d12cc09d1e14dfd378c29eabb7d0e3b35122d78
8b81555bc28e0fba35e9f628c903fd034599494f
refs/heads/master
2021-09-17T22:17:36.405221
2018-07-05T23:17:40
2018-07-05T23:17:40
126,029,731
0
0
null
null
null
null
UTF-8
Java
false
false
846
java
package it.polimi.ingsw.server.actions; import it.polimi.ingsw.core.Context; import it.polimi.ingsw.core.GlassColor; import it.polimi.ingsw.core.locations.ChooseLocation; import it.polimi.ingsw.models.Die; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; class GetAtActionTest { @Test void testGetAt() { Die die = new Die(5, GlassColor.RED); ChooseLocation chooseLocation = mock(ChooseLocation.class); when(chooseLocation.getDie(5)).thenReturn(die); GetAtAction getAtAction = new GetAtAction(new ActionData(null, null, null), context -> chooseLocation, context -> 5); Die getDie = (Die) getAtAction.run(Context.getSharedInstance()); Assertions.assertSame(die, getDie); } }
759cea4c006acfa32707ee66cec380eafab01779
e3b8450adc3d8930297bb88def04c133f29166d1
/src/Jsp/EncapActi.java
36b17f74e1d63982067802951d358b96cdde334a
[]
no_license
Padmashree21/Automation
bec6080e231e54fe2257153ca1bf5d0da24c208d
8acd6e26ea7789bdf023ac337ea1b0ce81b0afe3
refs/heads/master
2020-04-09T07:16:46.420041
2018-12-03T07:21:44
2018-12-03T07:21:44
160,148,508
0
0
null
null
null
null
UTF-8
Java
false
false
864
java
package Jsp; import java.util.concurrent.TimeUnit; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class EncapActi { static { System.setProperty("webdriver.chrome.driver","./Drivers/chromedriver.exe"); System.setProperty("webdriver.gecko.driver", "./Drivers/geckodriver.exe"); } public static void main(String[] args) throws InterruptedException { WebDriver driver=new ChromeDriver(); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.get("https://demo.actitime.com/login.do"); LoginPage lp=new LoginPage(driver); lp.enterUserName("admin"); lp.enterPassword("damager"); lp.clickOnLogin(); Thread.sleep(3000); lp.enterUserName("admin"); lp.enterPassword("manager"); lp.clickOnLogin(); } }
[ "V Padmashree@LAPTOP-A8PHK2NI" ]
V Padmashree@LAPTOP-A8PHK2NI
386c6f8fc2072837112de99fe07827e92245bd0a
7698d4428c7da14f0caaa850fab5dab6e93df198
/src/com/jevalab/azure/persistence/CbtRecord.java
163affd47ddb7d776437fdba6db5a6366c01832d
[]
no_license
jaidadelahuya/kp
f1078ab3ac55995c16feae57798c067291311679
c7adab4e03f10cb9951a558dfb29694f97cca60a
refs/heads/master
2021-01-22T04:34:23.339649
2017-02-05T15:59:13
2017-02-10T11:56:19
81,560,745
0
0
null
null
null
null
UTF-8
Java
false
false
1,300
java
package com.jevalab.azure.persistence; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import org.datanucleus.api.jpa.annotations.Extension; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; @Entity public class CbtRecord implements Serializable { /** * */ private static final long serialVersionUID = -8296979764354266338L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Key key; @Extension(vendorName = "datanucleus", key = "gae.unindexed", value = "true") @OneToMany(cascade = CascadeType.ALL) private List<CbtTest> tests; public CbtRecord(String id) { key = KeyFactory.createKey(CbtRecord.class.getSimpleName(), id); tests = new ArrayList<CbtTest>(); } public Key getKey() { return key; } public void setKey(Key key) { this.key = key; } public List<CbtTest> getTests() { return tests; } public void setTests(List<CbtTest> tests) { this.tests = tests; } }
ae5f87a9c1d321dd2881dd5aa6465ab0d007457c
ea82e8dbf4dc635db72efce97ea64bdef5aa7103
/app/src/main/java/com/cablevision/cambaceomovil/dto/Domicilio.java
fa38ad264234600942fc76e8c4166793cc768091
[]
no_license
josmigrm/CambaceoMovilRep
81c076ae40f7bc1720a638d49aa0c0ea6896ca9d
cb9a50c2f2b379abfe46779a56a5b8799b820958
refs/heads/master
2021-01-25T04:03:15.696970
2015-07-22T23:05:21
2015-07-22T23:05:21
38,298,131
0
0
null
null
null
null
UTF-8
Java
false
false
4,468
java
package com.cablevision.cambaceomovil.dto; import java.io.Serializable; /** * Created by Mike on 6/25/15. */ public class Domicilio implements Serializable{ String Num_Ext; String Num_Int; String Edificio; String Departamento; String Orientacion; String Accont_No; String Estatus; String F_Activacion; String F_Suspension; String F_Cancelacion; String Oferta_Comercial; String Convetidor; String MTA; String CM; long Saldo_Total; long Saldo_Incobrable; public Domicilio(String num_Ext, String num_Int, String edificio, String departamento, String orientacion, String accont_No, String estatus, String f_Activacion, String f_Suspension, String f_Cancelacion, String oferta_Comercial, String convetidor, String MTA, String CM, Integer saldo_Total, Integer saldo_Incobrable) { Num_Ext = num_Ext; Num_Int = num_Int; Edificio = edificio; Departamento = departamento; Orientacion = orientacion; Accont_No = accont_No; Estatus = estatus; F_Activacion = f_Activacion; F_Suspension = f_Suspension; F_Cancelacion = f_Cancelacion; Oferta_Comercial = oferta_Comercial; Convetidor = convetidor; this.MTA = MTA; this.CM = CM; Saldo_Total = saldo_Total; Saldo_Incobrable = saldo_Incobrable; } public Domicilio(){} public String getNum_Ext() { return Num_Ext; } public void setNum_Ext(String num_Ext) { Num_Ext = num_Ext; } public String getNum_Int() { return Num_Int; } public void setNum_Int(String num_Int) { Num_Int = num_Int; } public String getEdificio() { return Edificio; } public void setEdificio(String edificio) { Edificio = edificio; } public String getDepartamento() { return Departamento; } public void setDepartamento(String departamento) { Departamento = departamento; } public String getOrientacion() { return Orientacion; } public void setOrientacion(String orientacion) { Orientacion = orientacion; } public String getAccont_No() { return Accont_No; } public void setAccont_No(String accont_No) { Accont_No = accont_No; } public String getEstatus() { return Estatus; } public void setEstatus(String estatus) { Estatus = estatus; } public String getF_Activacion() { return F_Activacion; } public void setF_Activacion(String f_Activacion) { F_Activacion = f_Activacion; } public String getF_Suspension() { return F_Suspension; } public void setF_Suspension(String f_Suspension) { F_Suspension = f_Suspension; } public String getF_Cancelacion() { return F_Cancelacion; } public void setF_Cancelacion(String f_Cancelacion) { F_Cancelacion = f_Cancelacion; } public String getOferta_Comercial() { return Oferta_Comercial; } public void setOferta_Comercial(String oferta_Comercial) { Oferta_Comercial = oferta_Comercial; } public String getConvetidor() { return Convetidor; } public void setConvetidor(String convetidor) { Convetidor = convetidor; } public String getMTA() { return MTA; } public void setMTA(String MTA) { this.MTA = MTA; } public String getCM() { return CM; } public void setCM(String CM) { this.CM = CM; } public long getSaldo_Total() { return Saldo_Total; } public void setSaldo_Total(long saldo_Total) { Saldo_Total = saldo_Total; } public long getSaldo_Incobrable() { return Saldo_Incobrable; } public void setSaldo_Incobrable(long saldo_Incobrable) { Saldo_Incobrable = saldo_Incobrable; } @Override public String toString() { return Num_Ext + " " +Num_Int + " " + Edificio + " " + Departamento + " " + Orientacion + " "+ Accont_No + " " + Estatus + " " + F_Activacion + " " + F_Suspension + " " + F_Cancelacion + " " + Oferta_Comercial + " " + Convetidor + " " + MTA + " " + CM + " " + Saldo_Total + " " + Saldo_Incobrable; } }
a4db556ac1d5e4b6fb4e2be22184f41fbf167eb4
f9fb47fa990095235215e8162b2b9588cb4f2aff
/app/src/main/java/co/krypt/kryptonite/exception/CryptoException.java
fae168cfbf450cf0671fed0f5f9dfbce81e1806d
[]
no_license
jn7163/kryptonite-android
3e3757d33564e66c29fd060411e059b7afeaed07
4f5e680d9398103bcc3732b77877ea95133d7edd
refs/heads/master
2021-08-26T06:38:57.031649
2017-11-21T21:48:33
2017-11-21T21:48:33
null
0
0
null
null
null
null
UTF-8
Java
false
false
245
java
package co.krypt.kryptonite.exception; /** * Created by Kevin King on 12/2/16. * Copyright 2016. KryptCo, Inc. */ public class CryptoException extends Exception { public CryptoException(String message) { super(message); } }
875ddcb96dfa407a2bbe610057438a7586769491
c79805e8e450e2a754b70ea4b70ecf0d43888619
/src/main/java/com/cyq/service/KafkaMangeServiceImpl.java
7354257acf97445bff6e5948aec9c9ff3ea7dcd4
[]
no_license
chendaben/KafkaDemo
0361b0122ce0d427c7def99a21ffc43c05dc2a15
f3612925ef363aadb85be8f4d6d1c5ed6be12c92
refs/heads/master
2020-03-19T03:04:24.601733
2019-03-11T15:27:16
2019-03-11T15:27:16
135,692,067
0
0
null
null
null
null
UTF-8
Java
false
false
815
java
package com.cyq.service; import kafka.utils.ZkUtils; import org.apache.kafka.common.security.JaasUtils; import scala.collection.JavaConversions; import java.util.List; /** * @author cyq * @date 2019/02/15 * @description **/ public class KafkaMangeServiceImpl { private static ZkUtils zkUtils = null; public static void main(String[] args) { getTopicList(); } /** * 获取所有的TopicList * @return */ public static List<String> getTopicList() { zkUtils = ZkUtils.apply("172.16.50.21:2181", 30000, 30000, JaasUtils.isZkSecurityEnabled()); List<String> allTopicList = JavaConversions.seqAsJavaList(zkUtils.getAllTopics()); for (String s:allTopicList){ System.out.print(s+","); } return allTopicList; } }
75fd21cbc982a1db1fb7ad8d8d3d56a11a253e66
aee1dad01ee46b955904575af04db07a8ffa33c6
/ws/src/main/java/com/fitraditya/androidwebsocket/util/HttpResponseException.java
e94f4f2d9bef37801a0300f4990b7ab9c51eda8a
[ "MIT" ]
permissive
fitraditya/android-websocket
9536c55ca1f1ed4e23d563b92e48f1f77dc14578
0455d18cfbd13a53cb5b8f4a2c1eece4d28bd1f2
refs/heads/master
2021-01-25T06:44:35.145343
2017-06-12T04:47:56
2017-06-12T04:47:56
93,598,217
1
0
null
null
null
null
UTF-8
Java
false
false
429
java
package com.fitraditya.androidwebsocket.util; /** * Created by fitra on 07/06/17. */ public class HttpResponseException extends Exception{ private int statusCode; public HttpResponseException(int statusCode, String s) { this.statusCode = statusCode; throw new RuntimeException("HTTP status code: " + statusCode + ", " + s); } public int getStatusCode() { return statusCode; } }
bf679a03951ee1361bda0d1e72f8d487318dcbf6
4709b40ca60d730deb8968198d3cbcce373c1a6f
/app/src/main/java/br/com/fcschelb/diab/InsereAlimentoHelper.java
304752ce868c15f3a84c5d096ab3b802ac36a738
[]
no_license
houspiller/diab
6c342482dda952e2d48b2431d1ab662984a5d034
0807ffee7dcdf97e697496f20064c79f0ed7cd72
refs/heads/master
2020-03-14T18:49:46.071139
2018-05-01T18:54:40
2018-05-01T18:54:40
131,749,966
0
0
null
null
null
null
UTF-8
Java
false
false
1,396
java
package br.com.fcschelb.diab; import android.widget.EditText; import br.com.fcschelb.diab.modelo.Alimento; public class InsereAlimentoHelper { private EditText campoDescricao; private EditText campoPorcao; private EditText campoCarboidrato; private EditText campoFibra; private Alimento alimento; public InsereAlimentoHelper(InsereAlimentoActivity activity) { campoDescricao = activity.findViewById(R.id.insere_alimento_descricao); campoPorcao = activity.findViewById(R.id.insere_alimento_porcao); campoCarboidrato = activity.findViewById(R.id.insere_alimento_carboidrato); campoFibra = activity.findViewById(R.id.insere_alimento_fibras); alimento = new Alimento(); } public Alimento pegaAlimento() { alimento.setDescricao(campoDescricao.getText().toString()); alimento.setPorcao(campoPorcao.getText().toString()); alimento.setCarboidratos(campoCarboidrato.getText().toString()); alimento.setFibras(campoFibra.getText().toString()); return alimento; } public void preencheCampos(Alimento alimento) { campoDescricao.setText(alimento.getDescricao()); campoPorcao.setText(alimento.getPorcao()); campoCarboidrato.setText(alimento.getCarboidratos()); campoFibra.setText(alimento.getFibras()); this.alimento = alimento; } }
1db0e335406e9fc141cc723f55cf2bf809a8684f
a81b7b3e065c909ba3af4f15c74f4bd625eb7c31
/EnglishPopKaraoke/EnglishPopKaraoke/GestionKaraoke/AudioPlugins/MinuteTest.java
917bedb1dfa3146e0769a9439085dd1447118ec3
[]
no_license
pouxl/Projet-Anglais
6e808be269344fe38738d6176ca37e67e8f69a4e
8acf4c9c8d9529d23130ed23a1314176ba11c627
refs/heads/master
2021-01-10T05:18:20.550724
2016-03-31T17:04:37
2016-03-31T17:04:37
54,777,228
0
0
null
null
null
null
UTF-8
Java
false
false
2,899
java
package EnglishPopKaraoke.GestionKaraoke.AudioPlugins; import java.io.*; import java.util.*; import EnglishPopKaraoke.GestionKaraoke.AudioPluginKaraoke; import EnglishPopKaraoke.GestionKaraoke.InformationKaraoke; import java.net.*; import java.applet.*; /** Plugin Minute Test : envoie pendant 60 secondes les paroles representant la seconde * actuellement en cours. Il permet de tester simplement les plugins Visuels */ public class MinuteTest extends AudioPluginKaraoke { private FileInputStream in; //private DataInputStream dat; private int nbLus; private long tempsInit; private boolean finLecture; /** Constructeur du plugin */ public MinuteTest () { super(); } /** Thread envoyant le temps aux differents observeurs des qu'un * nouveau mot doit faire son apparition */ private class EnvoyeurTemps extends Thread { public EnvoyeurTemps () { } public void run() { long tempsRes; int indexeActuel = 0; Vector te = getTimeEvents(); while ((finLecture == false) && (indexeActuel < te.size())){ tempsRes = System.currentTimeMillis() - tempsInit; if (tempsRes >= ((Long)te.elementAt(indexeActuel)).longValue()){ envoie(InformationKaraoke.typeTemps , new Integer(indexeActuel)); indexeActuel++; } try{ this.sleep(100); } catch (InterruptedException e ){ } } envoie(InformationKaraoke.typeStop , null); finLecture = true; } } /** est appele pour charger un fichier musical * Ce plugin ne tient pas compte du fichier passe en parametre */ public int chargeFichier(File fichier){ nomChanson ="Compteur de 61 secondes"; auteurChanson ="personne !"; textEvents.clear(); timeEvents.clear(); text.clear(); String textadd; for (int i=0;i<=60;i++){ textadd = (new Integer(i)).toString(); if (((i+1) % 5) != 0) textadd = textadd + " "; text.add(textadd); timeEvents.add(new Long(i * 1000)); if ((i % 10) == 0) textEvents.add(new Integer(AudioPluginKaraoke.NOUVEAU_PAR)); else if ((i % 5) == 0) textEvents.add(new Integer(AudioPluginKaraoke.NOUVELLE_LIGNE)); else textEvents.add(new Integer(AudioPluginKaraoke.RIEN)); } return 1; } /** Rend le nom du plugin */ public String getName() { return "Compteur (Test)"; } /** debute la lecture */ public void play() { tempsInit = System.currentTimeMillis(); finLecture = false; envoie(InformationKaraoke.typePlay , null); (new EnvoyeurTemps()).start(); } /** arrete la lecture */ public void stop() { finLecture = true; } }
4bb84f231464999048ab65736d297d9375fe72f1
cc9d3f3c7a7ff6635a3683e520b9fb67e602b609
/HomeAppliances/HomeAppliancesGUI/src/com/company/controllers/General.java
a23ce36ce4ad4a4116174b2f275905239de20e40
[]
no_license
vicras/Java
752a7538b1ae93a1056a4a3a9cdd6038d8b1e872
16677d0c79136285538242bf087491516fb29f32
refs/heads/master
2023-08-05T01:45:40.025972
2021-09-23T11:00:30
2021-09-23T11:00:30
305,134,693
0
0
null
null
null
null
UTF-8
Java
false
false
6,817
java
package com.company.controllers; import com.company.model.ParametersType; import com.company.model.Taskable; import com.company.model.homeelectricalappliances.HomeElectricalAppliances; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.*; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyCodeCombination; import javafx.scene.input.KeyCombination; import javafx.stage.Stage; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; public class General { List<HomeElectricalAppliances> appliances; Taskable model; //region field @FXML private TableColumn<?, ?> stateCol; @FXML private TableView<HomeElectricalAppliances> appliancesTable; @FXML private MenuItem voltageSortBt; @FXML private MenuItem powerSortBt; @FXML private MenuItem countrySortBt; @FXML private MenuItem dateSortBt; @FXML private MenuItem findPowerBt; @FXML private MenuItem findVoltageBt; @FXML private MenuItem findCountrybt; @FXML private MenuItem quitBt; @FXML private MenuItem undoBt; @FXML private MenuItem aboutBt; @FXML private MenuItem updateBt; @FXML private TableColumn<?, ?> nameCol; @FXML private TableColumn<?, ?> descriptionCol; @FXML private TableColumn<?, ?> powerCol; @FXML private TableColumn<?, ?> voltageCol; @FXML private TableColumn<?, ?> efficiencyCol; @FXML private TableColumn<?, ?> dateCol; @FXML private TableColumn<?, ?> sizeTypeCol; @FXML private TableColumn<?, ?> guarantyCol; @FXML private TableColumn<?, ?> countryCol; @FXML private Label infoLb; //endregion public void init(Taskable taskable) { model = taskable; initTable(); updateAction(); addKeyListener(); } @FXML void aboutAction() { AboutController.invoke((Stage) infoLb.getScene().getWindow()); } @FXML void undoAction() { updateRepresentation(appliances, "Consumed power: " + model.countConsumedPower(appliances)); } @FXML void findAction(ActionEvent event) { MenuItem source = (MenuItem) event.getSource(); TextInputDialog textInputDialog = new TextInputDialog(""); textInputDialog.setContentText("Filter"); textInputDialog.setHeaderText("Enter your filter"); Optional<String> s = textInputDialog.showAndWait(); if (s.isEmpty()) { Alert alert = new Alert(Alert.AlertType.ERROR, "You should enter your filter"); alert.show(); return; } String filter = s.get(); List<HomeElectricalAppliances> list = null; String label = ""; if (findCountrybt == source) { list = model.findWithCountry(appliances, filter); label = "Selected by country: " + filter; updateRepresentation(list, label); return; } if (!isInteger(filter)) { Alert alert = new Alert(Alert.AlertType.ERROR, "It should be a digit"); alert.show(); return; } int f = Integer.parseInt(filter); if (findPowerBt == source) { list = model.findWithPower(appliances, f); label = "Selected by power: " + filter; } if (findVoltageBt == source) { list = model.findWithVoltage(appliances, f); label = "Selected by voltage: " + filter; } updateRepresentation(list, label); } @FXML void sortAction(ActionEvent event) { MenuItem source = (MenuItem) event.getSource(); ParametersType type = null; if (countrySortBt == source) { type = ParametersType.COUNTRY; } if (dateSortBt == source) { type = ParametersType.DATE; } if (powerSortBt == source) { type = ParametersType.POWER; } if (voltageSortBt == source) { type = ParametersType.VOLTAGE; } updateTable(model.sortBy(appliances, type)); } @FXML void quitAction() { infoLb.getScene().getWindow().hide(); } @FXML void updateAction() { appliances = model.createAppliance(); updateTable(appliances); long power = model.countConsumedPower(appliances); setInfoLabelText("Consumed power: " + power); } private boolean isInteger(String string) { try { Integer.parseInt(string); } catch (NumberFormatException e) { return false; } return true; } private void updateRepresentation(List<HomeElectricalAppliances> list, String labelText) { updateTable(list); setInfoLabelText(labelText); } private void initTable() { nameCol.setCellValueFactory(new PropertyValueFactory<>("name")); descriptionCol.setCellValueFactory(new PropertyValueFactory<>("description")); powerCol.setCellValueFactory(new PropertyValueFactory<>("power")); voltageCol.setCellValueFactory(new PropertyValueFactory<>("voltage")); stateCol.setCellValueFactory(new PropertyValueFactory<>("stateProvider")); efficiencyCol.setCellValueFactory(new PropertyValueFactory<>("efficiencyClass")); dateCol.setCellValueFactory(new PropertyValueFactory<>("date")); sizeTypeCol.setCellValueFactory(new PropertyValueFactory<>("sizeType")); guarantyCol.setCellValueFactory(new PropertyValueFactory<>("guarantyPeriod")); countryCol.setCellValueFactory(new PropertyValueFactory<>("country")); } private void updateTable(List<HomeElectricalAppliances> appliances) { ObservableList<HomeElectricalAppliances> list = getTableValues(appliances); appliancesTable.setItems(list); } private ObservableList<HomeElectricalAppliances> getTableValues(List<HomeElectricalAppliances> appliances) { return appliances.stream() .collect(Collectors.toCollection(FXCollections::observableArrayList)); } private void setInfoLabelText(String text) { infoLb.setText(text); } private void addKeyListener() { KeyCombination ctrlZ = new KeyCodeCombination(KeyCode.Z, KeyCodeCombination.CONTROL_DOWN); KeyCombination ctrlU = new KeyCodeCombination(KeyCode.U, KeyCodeCombination.CONTROL_DOWN); KeyCombination f1 = new KeyCodeCombination(KeyCode.F1); updateBt.setAccelerator(ctrlU); undoBt.setAccelerator(ctrlZ); aboutBt.setAccelerator(f1); } }
7d0fc5494eeabefaf34e530931912f9822579fd1
a6900d46c4ca16587db8b6cdc13abd97124efdff
/android/app/src/main/java/com/libs/flutterfirebasestorage/MainActivity.java
3a85ca6d29407e5cf55e5a2f580ffec29ece9d86
[]
no_license
DeveloperLibs/flutter_firebase_storage
01381cf17e1365b7cb716352357bd5de65595378
b7c290674619ad3bef254d24e3dfee8520d015e8
refs/heads/master
2021-06-11T07:46:14.600812
2021-03-27T18:53:46
2021-03-27T18:53:46
163,196,108
10
7
null
null
null
null
UTF-8
Java
false
false
376
java
package com.libs.flutterfirebasestorage; import android.os.Bundle; import io.flutter.app.FlutterActivity; import io.flutter.plugins.GeneratedPluginRegistrant; public class MainActivity extends FlutterActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); GeneratedPluginRegistrant.registerWith(this); } }
95b7e93de70b869821236618386984f87b0794f8
943ac4c7d4793771a0b54b715c12c386e52dc4f5
/mvfeed/src/main/java/com/eugenefe/mvfeed/krx/KrxBondType.java
8a9b07954e3155910e72a4febf1d3457c262b052
[]
no_license
eugenefe/eugenefe
1346e6ebda49ac52e41cb46114187a2a48f0ae78
7d9553b13fd1a001864d300b8ee623610fa4d520
refs/heads/master
2022-11-28T23:23:51.634781
2019-10-21T03:37:22
2019-10-21T03:37:22
15,544,730
0
0
null
2022-11-24T03:22:03
2013-12-31T06:44:04
Java
UTF-8
Java
false
false
2,949
java
package com.eugenefe.mvfeed.krx; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Properties; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; //import com.eugenefe.mvfeed.KrxBondTypeTest; public class KrxBondType { private String type; private String typeName; private String divType; private String divTypeName; public KrxBondType() { } public KrxBondType(String type, String typeName, String divType, String divTypeName) { this.type = type; this.typeName = typeName; this.divType = divType; this.divTypeName = divTypeName; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getTypeName() { return typeName; } public void setTypeName(String typeName) { this.typeName = typeName; } public String getDivType() { return divType; } public void setDivType(String divType) { this.divType = divType; } public String getDivTypeName() { return divTypeName; } public void setDivTypeName(String divTypeName) { this.divTypeName = divTypeName; } public static String getResourceUrl(){ Properties properties = new Properties(); try { properties.load(KrxBondType.class.getResourceAsStream("/url.properties")); }catch(IOException e) { e.printStackTrace(); } return properties.getProperty("krxBondMaster"); } public static List<KrxBondType> loadDataFromUrl(){ Document doc; String type, typeName = null; String divType; KrxBondType entity ; List<KrxBondType> entityList = new ArrayList<KrxBondType>(); Properties properties = new Properties(); try { // TODO : Change to message injection properties.load(KrxBondType.class.getResourceAsStream("/url.properties")); // logger.info("Master: {}", properties.getProperty("krxBondMaster")); doc = Jsoup.connect(properties.getProperty("krxBondMaster")).get(); Elements _types = doc.select("fieldset>table>tbody>tr>td>label, fieldset>table>tbody>tr>td>span"); // logger.info("JSON: {}", _types); for( Element aa : _types){ // logger.info("JSON: {},{}", aa.tagName(), aa.text()); if(aa.tagName().equals("label")){ typeName = aa.text(); } else if(aa.tagName().equals("span")){ for(Element bb : aa.children() ){ if(bb.tagName().equals("select")){ // logger.info("JSON1111: {},{}", bb.attr("name")); type = bb.attr("name"); for( Element cc : bb.select("option")){ divType =cc.attr("value"); if(divType != ""){ // logger.info("JSON111: {},{}", cc.attr("value"), cc.text()); entity = new KrxBondType(type, typeName, divType, cc.text()); entityList.add(entity); } } } } } } return entityList; } catch (IOException e) { e.printStackTrace(); } return entityList; } }
9410fe24f08f9a2ddb1bdd060fc98d9158c3f5aa
2fca86eb109e88855b65d1b809be939c34e0a906
/src/main/java/com/rooney/james/dlgtest/service/UserService.java
4e13ad4aba795fdcb918ea593fa80831509fec02
[]
no_license
jamesvrooney/dlg-test
ca1d34a3facefef19cff5a7194692ea02108d949
1d06988a848297bea3eef3afd8f2699d6dc89255
refs/heads/main
2023-01-16T02:12:22.313114
2020-11-26T20:35:26
2020-11-26T20:35:26
313,619,358
0
0
null
null
null
null
UTF-8
Java
false
false
398
java
package com.rooney.james.dlgtest.service; import com.rooney.james.dlgtest.domain.UserDTO; import com.rooney.james.dlgtest.exception.UserNotFoundException; public interface UserService { void createUser(UserDTO newUser); UserDTO getUser(String email) throws UserNotFoundException; void updateUser(UserDTO updatedUser) throws UserNotFoundException; void deleteUser(String email); }
991a0a24b2917d5f7a0061e0c34331821b3bc8d5
59074ca50b574320557968ff5d728da3dff53de1
/JavaImageManipulations/src/imagemanipulator/Negative.java
ee03ac29de7d5821a61839e461c228c518f68b8d
[]
no_license
KoStard/JavaImageManipulations
dad63dc84e91055dd3c0023ba6c8487d35bd7949
367a18f172c56e244116faf41220ce4eb6d5c897
refs/heads/master
2020-03-23T01:49:04.984863
2018-07-15T17:09:54
2018-07-15T17:09:54
140,939,020
0
0
null
null
null
null
UTF-8
Java
false
false
336
java
package imagemanipulator; public class Negative { public static int[][][] make(int[][][] pixels){ for (int y = 0; y < pixels.length; y++) { for (int x = 0; x < pixels[0].length; x++) { int[] current = pixels[y][x]; pixels[y][x] = new int[]{255-current[0], 255-current[1], 255-current[2]}; } } return pixels; } }
51ab0875a93a0f1414e2f04caeff284735697fcd
8b3356787d18e3a28cfc8fb1d26f0c3b42fcdd10
/src/Tridion/ContentManager/CoreService/Client/DeleteTaxonomyNodeMode.java
7dc7659d7cf926a935b892ba1bac6204da9b9553
[]
no_license
Javonet-io-user/3f371929-ca97-4d2c-8d99-7483da08ce0f
0e0b75aa8df218e25eeca56d6508fdcb2c698946
36b8d7a0267ca29f1921b83ed6534a110ac42cf7
refs/heads/master
2020-07-03T23:55:37.546059
2019-08-13T07:45:15
2019-08-13T07:45:15
202,091,767
0
0
null
null
null
null
UTF-8
Java
false
false
391
java
package Tridion.ContentManager.CoreService.Client; public enum DeleteTaxonomyNodeMode { DeleteBranch(0L), DeleteBranchIncludeChildPublications(1L), RemoveParentFromChildren(2L), AssignChildrenToGrandparents(3L), ; private long numVal; DeleteTaxonomyNodeMode(long numVal) { this.numVal = numVal; } public long getNumVal() { return numVal; } }
8d84d433935e0a73ddec18019940ccc5a1db1e8e
99d06a51707bbf486ff91966bbd62631502e7e73
/src/fr/istic/proga/SpecifMatriceCarreeImpl.java
b45e7b1cab203b6d24536876291869ed5a9d3ad5
[]
no_license
anohabbah/examen-proga-2014
13ffe4d437486380353510716a6108fe75dca5a8
47a79514311a401e286c55c79f68a5be0c2fbdef
refs/heads/main
2023-03-12T23:38:51.513969
2021-03-06T14:18:41
2021-03-06T14:18:41
345,111,954
0
0
null
null
null
null
UTF-8
Java
false
false
678
java
package fr.istic.proga; public class SpecifMatriceCarreeImpl implements SpecifMatriceCarree { @Override public int getDimension() { return 0; } @Override public boolean coordCorrecte(int c) { return false; } @Override public int getCase(int ligne, int colonne) { return 0; } @Override public void setCase(int ligne, int colonne, int valeur) { coordCorrecte(ligne); coordCorrecte(colonne); assert valeur > 0; } @Override public int getTotalLigne(int ligne) { return 0; } @Override public int getTotalColonne(int colonne) { return 0; } }
e82319e634587045f769b878f8f0dfaea0148325
13970e9f6abf2be035c7703d1f071c294bd1f032
/src/com/mxgraph/smartml/control/H_EditProvider.java
d4a31bd7c42fcbc450c6aab0c436d8c4edc1dce6
[]
no_license
p2tris/SmartPMsuite
33c472c0953f55b6b4006dbfea24292efdc0b4f1
37383c96ea15390305f0cfb1c860dc44c477128a
refs/heads/master
2016-09-15T21:29:00.410551
2015-03-30T09:07:52
2015-03-30T09:07:52
26,969,444
1
0
null
null
null
null
UTF-8
Java
false
false
6,216
java
package com.mxgraph.smartml.control; import java.awt.PageAttributes.OriginType; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Vector; import javax.swing.ImageIcon; import javax.swing.JOptionPane; import com.mxgraph.smartml.model.XMLParser; import com.mxgraph.smartml.view.EditProvider; import com.mxgraph.smartml.view.ServicePerspective; public class H_EditProvider { public EditProvider _view = null; public H_EditProvider (EditProvider i_view){ _view = i_view; installListeners(); } private void installListeners() { _view.getRightButton().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { int selected_index = _view.getProviderServicesList().getSelectedIndex(); if (selected_index == -1) { //no selection JOptionPane.showMessageDialog(null, "Please select a provider's service to remove!", "ATTENTION!", JOptionPane.INFORMATION_MESSAGE, new ImageIcon("images/info_icon.png")); } else { //add after the selected item String provider_service = (String) _view.getProviderServicesListModel().getElementAt(selected_index); _view.getProviderServicesListModel().removeElementAt(selected_index); _view.getOtherServicesListModel().addElement(provider_service); } } }); _view.getLeftButton().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { int selected_index = _view.getOtherServicesList().getSelectedIndex(); if (selected_index == -1) { //no selection JOptionPane.showMessageDialog(null, "Please select a service to be associated to the provider!", "ATTENTION!", JOptionPane.INFORMATION_MESSAGE, new ImageIcon("images/info_icon.png")); } else { //add after the selected item String provider_service = (String) _view.getOtherServicesListModel().getElementAt(selected_index); _view.getOtherServicesListModel().removeElementAt(selected_index); _view.getProviderServicesListModel().addElement(provider_service); } } }); _view.getCancelButton().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { _view.dispose(); } }); _view.getOkButton().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { Vector newProviderServicesListVector = new Vector(); boolean areServicesChanged = false; for(int i=0;i<_view.getProviderServicesListModel().size();i++) { newProviderServicesListVector.addElement(_view.getProviderServicesListModel().getElementAt(i)); if(!_view.getOriginalProviderServicesVector().contains(_view.getProviderServicesListModel().getElementAt(i))) areServicesChanged = true; } if(_view.getOriginalProviderServicesVector().size() != _view.getProviderServicesListModel().size()) areServicesChanged = true; //FIRST CASE : NO CHANGE HAS BEEN MADE TO THE PROVIDER if(_view.getOriginalProvider().equalsIgnoreCase(_view.getProviderNameTextField().getText()) && areServicesChanged == false) { JOptionPane.showMessageDialog(null, "No change has been done to the provider "+ _view.getOriginalProvider(), "INFORMATION", JOptionPane.INFORMATION_MESSAGE, new ImageIcon("images/info_icon.png")); _view.dispose(); } //SECOND CASE : THE NAME OF THE PROVIDER IS ALREADY EXISTING else if(XMLParser.getProvidersNames(true).contains(_view.getProviderNameTextField().getText().toLowerCase()) && !_view.getOriginalProvider().equalsIgnoreCase(_view.getProviderNameTextField().getText())) { JOptionPane.showMessageDialog(null, "The provider '" + _view.getProviderNameTextField().getText().toLowerCase() + "' already exists. Please choose a different name for the provider!", "ATTENTION!", JOptionPane.INFORMATION_MESSAGE, new ImageIcon("images/info_icon.png")); } //THIRD CASE : THE NAME OF THE PROVIDER AND/OR ITS INTERNAL SERVICES ARE CHANGED. else { String newProvider = _view.getProviderNameTextField().getText() + " = <"; for(int j=0;j<newProviderServicesListVector.size();j++) { if(j==newProviderServicesListVector.size()-1) newProvider = newProvider + newProviderServicesListVector.elementAt(j); else newProvider = newProvider + newProviderServicesListVector.elementAt(j)+","; } newProvider = newProvider + ">"; int reply = JOptionPane.showConfirmDialog(null, "Do you want to change the original provider\n" + _view.getProviderWithAssociatedServices()+ " with\n" + newProvider + "?", "ATTENTION!", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, new ImageIcon("images/question_icon.png")); if(reply==0) { XMLParser.setProvider(_view.getOriginalProvider(), _view.getProviderNameTextField().getText(), newProviderServicesListVector); _view.getServicePerspective().loadExistingProviders(); _view.dispose(); } } } }); } }
2d54110775756c1fca3587d7be4c0ceeac291172
328cf897e83af854b74a79578f05f9e873dc9f01
/OOP3/src/org/iuea/oop/MainClass.java
d724997bbac56e0696f40bfbfb94c46e0ee7e9cb
[]
no_license
abdiazizfarahali/OOP3
4340c6f0a2927d410e3b69789ae70e9c2667e8ca
97b5bae6b01456bbf99eae9bd69497caf0129a97
refs/heads/master
2020-08-01T03:41:11.238140
2019-09-25T13:22:41
2019-09-25T13:22:41
210,849,356
0
0
null
null
null
null
UTF-8
Java
false
false
176
java
package org.iuea.oop; import view.LoginView; public class MainClass { public static void main(String[] args) { LoginView loginvw = new LoginView(); } }
5b341eb05ad48e32afb6f05283e6a5706df7873b
96c3c258ef230679c497e5c911c8877ea7bb484e
/app/src/main/java/com/app/ladies/dailymap/view/search/SearchRestaurantDetailTask.java
52ab31c1badad6dd46a5ecc95b93fbb2886973a0
[]
no_license
k-anz/tabemap
f80b70d47871e0c358da5498c7735aebab0cabfc
7101b7c8ffc5d6490aea81ea977def6b7dca66ee
refs/heads/master
2021-08-08T14:18:12.066466
2017-11-10T13:51:21
2017-11-10T13:51:21
110,251,263
0
0
null
null
null
null
UTF-8
Java
false
false
4,321
java
package com.app.ladies.dailymap.view.search; import android.net.Uri; import android.util.Log; import android.util.Pair; import android.widget.ImageView; import android.widget.TextView; import com.app.ladies.dailymap.R; import com.app.ladies.dailymap.view.detail.ImgAsyncTask; import com.app.ladies.dailymap.view.detail.ShopDetailActivity; import com.app.ladies.dailymap.view.model.ImageUrlBean; import com.app.ladies.dailymap.view.model.RestaurantBean; import com.fasterxml.jackson.databind.ObjectMapper; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.ref.WeakReference; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; /** * Created by Kyoko1 on 2016/10/27. */ public class SearchRestaurantDetailTask extends SearchRestaurantTask { WeakReference<ShopDetailActivity> mActivityWeakReference; public SearchRestaurantDetailTask(WeakReference<ShopDetailActivity> activityWeakReference) { mActivityWeakReference = activityWeakReference; } @Override protected List<RestaurantBean> doInBackground(Pair<String, String>... params) { Uri.Builder accessUrl = API_URI.buildUpon(); accessUrl.appendQueryParameter("keyid", API_KEY); // build query parameter for (Pair<String, String> queryParam : params) { accessUrl.appendQueryParameter(queryParam.first, queryParam.second); } try { java.net.URL restSearchURL = new URL(accessUrl.build().toString()); HttpURLConnection http = (HttpURLConnection)restSearchURL.openConnection(); http.setRequestMethod("GET"); Log.i("connected", accessUrl.toString()); http.connect(); InputStream in = http.getInputStream(); BufferedReader streamReader = new BufferedReader(new InputStreamReader(in, "UTF-8")); StringBuilder responseStrBuilder = new StringBuilder(); String inputStr; while ((inputStr = streamReader.readLine()) != null) { responseStrBuilder.append(inputStr); } Log.i("response", responseStrBuilder.toString()); // TODO delete JSONObject response = new JSONObject(responseStrBuilder.toString()); JSONObject rest = response.getJSONObject("rest"); ObjectMapper mapper = new ObjectMapper(); RestaurantBean bean = mapper.readValue(rest.toString(), RestaurantBean.class); String imgUrl = rest.getJSONObject("image_url").getString("shop_image1"); ImageUrlBean imgBean = new ImageUrlBean(); imgBean.setShopImage1(imgUrl); bean.setImgUrl(imgBean); List<RestaurantBean> restaurantBeanList = new ArrayList<>(); restaurantBeanList.add(bean); return restaurantBeanList; } catch (IOException | JSONException e) { // TODO Log.e("error", e.getMessage()); } return null; } @Override protected void onPostExecute(List<RestaurantBean> restaurantBeans) { super.onPostExecute(restaurantBeans); ShopDetailActivity activity = mActivityWeakReference.get(); TextView shopName = (TextView) activity.findViewById(R.id.shopName); TextView address = (TextView) activity.findViewById(R.id.address); if (restaurantBeans == null || restaurantBeans.size() == 0) { shopName.setText("お店がみつかりませんでした。"); } else { RestaurantBean rest = restaurantBeans.get(0); activity.bean = rest; // Activityに保存 shopName.setText(rest.getStoreName()); address.setText(rest.getAddress()); ImageView shopImage = (ImageView) activity.findViewById(R.id.shopImage); if (rest.getImgUrl() != null) { String url = rest.getImgUrl().getShopImage1(); if (url != null) { new ImgAsyncTask(shopImage).execute(Uri.parse(url).buildUpon()); } } else { // TODO "no image"画像つくる } } } }
5a7aec503f3714601093ccc2356292db984a67bc
46e5b636da0580a6d7eddd10538ce507f30bee6c
/cnd.fortran/src/main/java/org/netbeans/modules/fortranmodel/FVariable.java
dae163bb16403ebdf1431b7231933a1680ad2ca5
[ "Apache-2.0" ]
permissive
timboudreau/netbeans-contrib
b96c700768cca0932a0e2350362352352b3b91f6
f1e67dbd0f5c6ae596bd9754b5b1ba22cfe8cb8e
refs/heads/master
2023-01-25T00:36:37.680959
2023-01-06T06:07:09
2023-01-06T06:07:09
141,208,493
4
2
NOASSERTION
2022-09-01T22:50:24
2018-07-17T00:13:23
Java
UTF-8
Java
false
false
365
java
package org.netbeans.modules.fortranmodel; /** * Represents a variable * @author Andrey Gubichev */ public interface FVariable extends FOffsetableDeclaration{ /** Gets this variable type */ FType getType(); /** Gets this variable initial value */ FExpression getInitialValue(); String getDeclarationText(); }
bec4051a9f500789a58ebd5f12ecb16fbd6d9932
f185a4949b46620e8d9671e578bff660fc15e4c1
/ddzw/src/main/java/org/lc/com/ddzw/Bean/support/SelectionEvent.java
8b6c3615be851eb1e66c3a7923f15c98da8dc557
[]
no_license
alex0403/ziyuexs
5940a7bff008e04a2b0a184e6b60901bd4c4b9a7
867c8cfc64177c719cb5a804f2c332d7e1f52e39
refs/heads/master
2021-07-07T03:03:06.684755
2017-10-01T02:01:11
2017-10-01T02:01:30
105,413,206
0
0
null
null
null
null
UTF-8
Java
false
false
1,217
java
/** * Copyright 2016 JustWayward Team * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.lc.com.ddzw.Bean.support; import org.lc.com.ddzw.Base.Constant; /** * @author yuyh. * @date 16/9/2. */ public class SelectionEvent { public String distillate; public String type; public String sort; public SelectionEvent(@Constant.Distillate String distillate, @Constant.BookType String type, @Constant.SortType String sort) { this.distillate = distillate; this.type = type; this.sort = sort; } public SelectionEvent(@Constant.SortType String sort) { this.sort = sort; } }
[ "liucheng1986" ]
liucheng1986
69c259c218e7eca4d37cfa09e8ed51f2d18909c4
ab03b6f3855028797dc07ea6eb365f31cf0b38e2
/src/exercise/ch3/Ex3_5.java
7cad36bc619f506eb232f8a572a50c93291189d7
[]
no_license
Yaamaidie/datastructure
34df563a9102465e9bf599bb66c646d581dde9ce
e09bbb77a504ed3c5bcb80de7eecd300703883b0
refs/heads/master
2020-06-22T05:12:07.455207
2018-01-29T07:44:42
2018-01-29T07:44:42
74,753,324
0
0
null
null
null
null
UTF-8
Java
false
false
1,303
java
package exercise.ch3; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; public class Ex3_5 { public static <T extends Comparable<? super T>> void union(List<T> list1, List<T> list2, List<T> unionList) { ListIterator<T> iterL1 = list1.listIterator(); ListIterator<T> iterL2 = list2.listIterator(); T itemL1 = null, itemL2 =null; if (iterL1.hasNext() && iterL2.hasNext()) { itemL1 = iterL1.next(); itemL2 = iterL2.next(); } while (itemL1 != null && itemL2 != null) { System.out.println(itemL1 + "" + itemL2); int result = itemL1.compareTo(itemL2); if (result == 0) { unionList.add(itemL1); itemL1 = iterL1.hasNext() ? iterL1.next() : null; itemL2 = iterL2.hasNext() ? iterL2.next() : null; } else if (result < 0) { unionList.add(itemL1); itemL1 = iterL1.hasNext() ? iterL1.next() : null; } else { unionList.add(itemL2); itemL2 = iterL2.hasNext() ? iterL2.next() : null; } } } public static void main(String[] args) { List<Integer> l1 = new ArrayList<Integer>(); l1.add(1); l1.add(2); l1.add(3); List<Integer> l2 = new ArrayList<Integer>(); l2.add(2); l2.add(3); l2.add(4); List<Integer> l3 = new ArrayList<Integer>(); Ex3_5.union(l1, l2, l3); System.out.println(l3); } }
1065a2d0f35f39d4416dcbbf5f0bcea4896eb37d
a4f94f4701a59cafc7407aed2d525b2dff985c95
/core/kernel/source/jetbrains/mps/smodel/SNode.java
98a36ce64e6bfe52cc46296b2a87ac9638a3a366
[]
no_license
jamice/code-orchestra-core
ffda62860f5b117386aa6455f4fdf61661abbe9e
b2bbf8362be2e2173864c294c635badb2e27ecc6
refs/heads/master
2021-01-15T13:24:53.517854
2013-05-09T21:39:28
2013-05-09T21:39:28
null
0
0
null
null
null
null
UTF-8
Java
false
false
57,070
java
/* * Copyright 2003-2011 JetBrains s.r.o. * * 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 jetbrains.mps.smodel; import jetbrains.mps.kernel.model.SModelUtil; import jetbrains.mps.lang.smodel.generator.smodelAdapter.AttributeOperations; import jetbrains.mps.logging.Logger; import jetbrains.mps.project.GlobalScope; import jetbrains.mps.project.IModule; import jetbrains.mps.project.ModuleId; import jetbrains.mps.project.structure.modules.ModuleReference; import jetbrains.mps.smodel.language.ConceptRegistry; import jetbrains.mps.smodel.runtime.PropertyConstraintsDescriptor; import jetbrains.mps.smodel.runtime.ReferenceConstraintsDescriptor; import jetbrains.mps.smodel.runtime.illegal.IllegalReferenceConstraintsDescriptor; import jetbrains.mps.smodel.search.SModelSearchUtil; import jetbrains.mps.util.*; import jetbrains.mps.util.annotation.CodeOrchestraPatch; import jetbrains.mps.util.annotation.UseCarefully; import org.apache.commons.lang.ObjectUtils; import org.apache.commons.lang.StringUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.*; public final class SNode { private static final Logger LOG = Logger.getLogger(SNode.class); @Deprecated public static final String PACK = SNodeUtil.property_BaseConcept_virtualPackage; public static final SNode[] EMPTY_ARRAY = new SNode[0]; private static NodeMemberAccessModifier ourMemberAccessModifier = null; private static ThreadLocal<Set<Pair<SNode, String>>> ourPropertySettersInProgress = new InProgressThreadLocal(); private static ThreadLocal<Set<Pair<SNode, String>>> ourPropertyGettersInProgress = new InProgressThreadLocal(); private static ThreadLocal<Set<Pair<SNode, String>>> ourSetReferentEventHandlersInProgress = new InProgressThreadLocal(); private static final String[] EMPTY_STRING_ARRAY = new String[0]; public static void setNodeMemberAccessModifier(NodeMemberAccessModifier modifier) { ourMemberAccessModifier = modifier; } private String myRoleInParent; private SNode myParent; /** * access only in getFirstChild() */ private SNode myFirstChild; private SNode myNextSibling; // == null only for the last child in the list private SNode myPrevSibling; // notNull, myFirstChild.myPrevSibling = the last child private SReference[] myReferences = SReference.EMPTY_ARRAY; private String[] myProperties = null; private boolean myDisposed = false; private boolean myRegisteredInModelFlag; private SModel myModel; private SNodeId myId; private Object[] myUserObjects; // key,value,key,value ; !copy-on-write @NotNull private String myConceptFqName; private BaseAdapter myAdapter; public SNode(SModel model, @NotNull String conceptFqName, boolean callIntern) { myModel = model; if (callIntern) { myConceptFqName = InternUtil.intern(conceptFqName); } else { myConceptFqName = conceptFqName; } } public SNode(SModel model, String conceptFqName) { this(model, conceptFqName, true); } @CodeOrchestraPatch public IModule getSourceModule() { String sourceModuleUID = getSourceModuleUID(); if (StringUtils.isNotEmpty(sourceModuleUID)) { ModuleId moduleId = ModuleId.fromString(sourceModuleUID); IModule moduleByID = MPSModuleRepository.getInstance().getModuleById(moduleId); if (moduleByID != null) { return moduleByID; } } SModel model = getModel(); if (model != null) { SModelDescriptor modelDescriptor = model.getModelDescriptor(); if (modelDescriptor != null) { return modelDescriptor.getModule(); } } return null; } @CodeOrchestraPatch public String getSourceModuleUID() { Set<String> sourceModuleUIDs = getSourceModuleUIDs(); if (sourceModuleUIDs.isEmpty()) { return null; } return sourceModuleUIDs.iterator().next(); } @CodeOrchestraPatch public void clearSourceModuleUIDs() { setProperty(SNodeUtil.property_sourceModule, ""); } @CodeOrchestraPatch public void addSourceModuleUID(String newUID) { Set<String> uids = new HashSet<String>(); // Unserialize String uidsInOneString = getProperty(SNodeUtil.property_sourceModule); if (StringUtils.isNotEmpty(uidsInOneString)) { String[] uidsArray = StringUtils.split(uidsInOneString, ","); for (String persistentUID : uidsArray) { uids.add(persistentUID); } } // Serialize uids.add(newUID); setProperty(SNodeUtil.property_sourceModule, StringUtils.join(uids, ",")); } @CodeOrchestraPatch @NotNull public Set<String> getSourceModuleUIDs() { Set<String> uids = new HashSet<String>(); String uidsInOneString = getProperty(SNodeUtil.property_sourceModule); if (StringUtils.isNotEmpty(uidsInOneString)) { String[] uidsArray = StringUtils.split(uidsInOneString, ","); for (String uid : uidsArray) { uids.add(uid); } } return uids; } public void changeModel(SModel newModel) { if (myModel == newModel) return; LOG.assertLog(!isRegistered(), "couldn't change model of registered node " + getDebugText()); SModel wasModel = myModel; myModel = newModel; ModelChangedCaster.getInstance().fireModelChanged(this, wasModel); for (SNode child = getFirstChild(); child != null; child = child.myNextSibling) { child.changeModel(newModel); } } public boolean isRoot() { return myRegisteredInModelFlag && myParent == null && myModel.isRoot(this); } public void addNextSibling(SNode newSibling) { myParent.insertChild(this, myRoleInParent, newSibling); } public void addPrevSibling(SNode newSibling) { myParent.insertChild(this, myRoleInParent, newSibling, true); } public SModel getModel() { ModelAccess.assertLegalRead(this); fireNodeReadAccess(); return myModel; } //MUST NOT be used,except from ModelAccess SModel getModelInternal() { return myModel; } public SModel getModelInternal_() { return myModel; } public boolean isModelLoading() { return myModel.isLoading(); } public String getRoleOf(SNode node) { ModelAccess.assertLegalRead(this); fireNodeReadAccess(); fireNodeUnclassifiedReadAccess(); if (node.getParent() == this) { String role = node.getRole_(); assert role != null; return role; } if (myReferences != null) { for (SReference reference : myReferences) { if (reference.getTargetNode() == node) return reference.getRole(); } } return "<no role>"; } public Set<String> getChildRoles(boolean includeAttributeRoles) { return addChildRoles(new HashSet<String>(), includeAttributeRoles); } public Set<String> addChildRoles(final Set<String> augend, boolean includeAttributeRoles) { ModelAccess.assertLegalRead(this); fireNodeReadAccess(); fireNodeUnclassifiedReadAccess(); for (SNode child = getFirstChild(); child != null; child = child.myNextSibling) { String roleOf = child.getRole_(); assert roleOf != null; if (includeAttributeRoles || !(AttributeOperations.isAttribute(child))) { augend.add(roleOf); } } return augend; } public Set<String> getChildRoles() { return getChildRoles(false); } public Set<String> addChildRoles(final Set<String> augend) { return addChildRoles(augend, false); } public Set<String> getReferenceRoles() { ModelAccess.assertLegalRead(this); fireNodeReadAccess(); Set<String> result = new HashSet<String>(); if (myReferences != null) { for (SReference ref : myReferences) { result.add(ref.getRole()); } } result.addAll(AttributeOperations.getLinkNamesFromAttributes(this)); return result; } public boolean isAncestorOf(SNode child) { ModelAccess.assertLegalRead(this); fireNodeReadAccess(); if (child == this) return true; SNode parentOfChild = child.getParent(); if (parentOfChild == null) return false; return isAncestorOf(parentOfChild); } @NotNull public final SNode getTopmostAncestor() { SNode current = this; while (current.myParent != null) { assert current != current.myParent; current = current.myParent; } return current; } public SNode getContainingRoot() { ModelAccess.assertLegalRead(this); SNode current = this; while (true) { current.fireNodeReadAccess(); if (current.myParent == null) { if (getModel().isRoot(current)) { return current; } else { return null; } } else { current = current.myParent; } } } public List<SNode> getAncestors(boolean includeThis) { List<SNode> result = new ArrayList<SNode>(); if (includeThis) { result.add(this); } if (myParent != null) { result.addAll(myParent.getAncestors(true)); } return result; } public void replaceChild(SNode oldChild, SNode newChild) { SNode anchor = oldChild == getFirstChild() ? null : oldChild.myPrevSibling; String role = oldChild.getRole_(); assert role != null; // old and new child can have the same node Id // thus it is important to remove old child first removeChild(oldChild); insertChild(anchor, role, newChild); } public void replaceChild(SNode oldChild, List<SNode> newChildren) { assert oldChild.myParent == this; String oldChildRole = oldChild.getRole_(); assert oldChildRole != null; SNode prevChild = oldChild; for (SNode newChild : newChildren) { insertChild(prevChild, oldChildRole, newChild); prevChild = newChild; } removeChild(oldChild); } public void setName(String name) { setProperty(SNodeUtil.property_INamedConcept_name, name); } public String getName() { return getProperty(SNodeUtil.property_INamedConcept_name); } public String getResolveInfo() { String resolveInfo = SNodeUtil.getResolveInfo(this); if (resolveInfo != null) { return resolveInfo; } // tmp hack return getPersistentProperty(SNodeUtil.property_INamedConcept_name); } public String getRole_() { return myRoleInParent; } public SNode getRoleLink() { if (getRole_() == null) return null; if (getParent() == null) return null; return getParent().getLinkDeclaration(getRole_()); } public Map<String, String> getProperties() { ModelAccess.assertLegalRead(this); fireNodeReadAccess(); if (myProperties == null) return Collections.emptyMap(); return new PropertiesMap(myProperties); } public void putProperties(SNode fromNode) { ModelChange.assertLegalNodeChange(this); if (fromNode == null || fromNode.myProperties == null) return; String[] addedProps = fromNode.myProperties; String[] oldProperties = myProperties == null ? EMPTY_STRING_ARRAY : myProperties; myProperties = new String[oldProperties.length + addedProps.length]; System.arraycopy(oldProperties, 0, myProperties, 0, oldProperties.length); System.arraycopy(addedProps, 0, myProperties, oldProperties.length, addedProps.length); } public Set<String> getPropertyNames() { ModelAccess.assertLegalRead(this); fireNodeReadAccess(); Set<String> result = AttributeOperations.getPropertyNamesFromAttributes(this); if (myProperties != null) { for (int i = 0; i < myProperties.length; i += 2) { result.add(myProperties[i]); } } return result; } public boolean getBooleanProperty(String propertyName) { String value = getProperty(propertyName); return "true".equals(value); } public void setBooleanProperty(String propertyName, boolean value) { setProperty(propertyName, value ? "" + value : null); } public int getIntegerProperty(String propertyName) { String value = getProperty(propertyName); try { return Integer.parseInt(value); } catch (Exception e) { return 0; } } public void setIntegerProperty(String propertyName, int value) { setProperty(propertyName, "" + value); } public final boolean hasProperty(String propertyName) { ModelAccess.assertLegalRead(this); NodeReadAccessCasterInEditor.firePropertyReadAccessed(this, propertyName, true); String property_internal = getProperty_internal(propertyName); return !SModelUtil_new.isEmptyPropertyValue(property_internal); } public final String getProperty(String propertyName) { ModelAccess.assertLegalRead(this); NodeReadAccessCasterInEditor.firePropertyReadAccessed(this, propertyName, false); try { String propertyValue = getProperty_internal(propertyName); NodeReadEventsCaster.fireNodePropertyReadAccess(this, propertyName, propertyValue); return propertyValue; } catch (Throwable t) { LOG.error(t); return getPersistentProperty(propertyName); } } private String getProperty_internal(String propertyName) { Set<Pair<SNode, String>> getters = ourPropertyGettersInProgress.get(); Pair<SNode, String> current = new Pair<SNode, String>(this, propertyName); if (getters.contains(current)) return getPersistentProperty(propertyName); getters.add(current); try { PropertyConstraintsDescriptor descriptor = ConceptRegistry.getInstance().getConstraintsDescriptor(this.getConceptFqName()).getProperty(propertyName); Object getterValue = descriptor.getValue(this, GlobalScope.getInstance()); return getterValue == null ? null : String.valueOf(getterValue); } finally { getters.remove(current); } } public String getPersistentProperty(String propertyName) { if (myProperties == null) return null; if (ourMemberAccessModifier != null) { propertyName = ourMemberAccessModifier.getNewPropertyName(myModel, myConceptFqName, propertyName); } return getProperty_simple(propertyName); } private String getProperty_simple(String propertyName) { int index = getPropertyIndex(propertyName); if (index == -1) return null; return myProperties[index + 1]; } private int getPropertyIndex(String propertyName) { if (myProperties == null) return -1; for (int i = 0; i < myProperties.length; i += 2) { if (ObjectUtils.equals(myProperties[i], propertyName)) return i; } return -1; } void changePropertyName(String oldPropertyName, String newPropertyName) { //todo make undo? if (myProperties == null) return; int index = getPropertyIndex(oldPropertyName); if (index == -1) return; myProperties[index] = newPropertyName; } public void setProperty(final String propertyName, String propertyValue) { setProperty(propertyName, propertyValue, true); } public void setProperty(String propertyName, String propertyValue, boolean usePropertySetter) { propertyName = InternUtil.intern(propertyName); ModelChange.assertLegalNodeChange(this); propertyValue = InternUtil.intern(propertyValue); if (usePropertySetter) { Set<Pair<SNode, String>> threadSet = ourPropertySettersInProgress.get(); Pair<SNode, String> pair = new Pair<SNode, String>(this, propertyName); if (!threadSet.contains(pair) && !myModel.isLoading()) { PropertyConstraintsDescriptor descriptor = ConceptRegistry.getInstance().getConstraintsDescriptor(this.getConceptFqName()).getProperty(propertyName); threadSet.add(pair); try { descriptor.setValue(this, propertyValue, GlobalScope.getInstance()); return; } catch (Exception t) { LOG.error(t); } finally { threadSet.remove(pair); } } } if (ourMemberAccessModifier != null) { propertyName = ourMemberAccessModifier.getNewPropertyName(myModel, myConceptFqName, propertyName); } int index = getPropertyIndex(propertyName); final String oldValue = index == -1 ? null : myProperties[index + 1]; if (propertyValue == null && oldValue == null) return; if (propertyValue == null) { removeProperty(index); } else if (oldValue == null) { addProperty(propertyName, propertyValue); } else { myProperties[index + 1] = propertyValue; } if (UndoHelper.getInstance().needRegisterUndo(getModel())) { UndoHelper.getInstance().addUndoableAction(new PropertyChangeUndoableAction(this, propertyName, oldValue, propertyValue)); } if (ModelChange.needFireEvents(getModel(), this)) { getModel().firePropertyChangedEvent(this, propertyName, oldValue, propertyValue); } } private void removeProperty(int index) { String[] oldProperties = myProperties; int newLength = oldProperties.length - 2; if (newLength == 0) { myProperties = null; return; } myProperties = new String[newLength]; System.arraycopy(oldProperties, 0, myProperties, 0, index); System.arraycopy(oldProperties, index + 2, myProperties, index, newLength - index); } private void addProperty(String propertyName, String propertyValue) { String[] oldProperties = myProperties == null ? EMPTY_STRING_ARRAY : myProperties; myProperties = new String[oldProperties.length + 2]; System.arraycopy(oldProperties, 0, myProperties, 0, oldProperties.length); myProperties[myProperties.length - 2] = propertyName; myProperties[myProperties.length - 1] = propertyValue; } final public SNode getParent() { return myParent; } private void enforceModelLoad() { if (!isRoot()) return; myModel.enforceFullLoad(); } //all access to myFirstChild should be via this method private SNode getFirstChild() { enforceModelLoad(); return myFirstChild; } public void setChild(String role, SNode childNode) { SNode oldChild = getChild(role); if (oldChild != null) { removeChild(oldChild); } if (childNode != null) { addChild(role, childNode); } } public SNode getChild(String role) { ModelAccess.assertLegalRead(this); if (ourMemberAccessModifier != null) { role = ourMemberAccessModifier.getNewChildRole(myModel, myConceptFqName, role); } fireNodeReadAccess(); int count = 0; SNode foundChild = null; boolean isOldAttributeRole = AttributeOperations.isOldAttributeRole(role); for (SNode child = getFirstChild(); child != null; child = child.myNextSibling) { if (role.equals(child.getRole_())) { foundChild = child; count++; } else if (isOldAttributeRole && AttributeOperations.isOldRoleForNewAttribute(child, role)) { foundChild = child; count++; } } if (count > 1) { String errorMessage = "ERROR: " + count + " children for role " + role + " in " + NameUtil.shortNameFromLongName(getClass().getName()) + "[" + getId() + "] " + getModel().getSModelReference() + "\n"; errorMessage += "they are : " + getChildren(role); LOG.error(errorMessage, this); } NodeReadEventsCaster.fireNodeChildReadAccess(this, role, foundChild); return foundChild; } public SNode getChildAt(int index) { for (SNode child = getFirstChild(); child != null; child = child.myNextSibling) { if (index-- == 0) { return child; } } return null; } public void addChild(String role, SNode child) { SNode firstChild = getFirstChild(); insertChild(firstChild == null ? null : firstChild.myPrevSibling, role, child); } public void insertChild(SNode anchorChild, String role, SNode child, boolean insertBefore) { if (insertBefore) { insertChild(getFirstChild() == anchorChild ? null : anchorChild.myPrevSibling, role, child); } else { insertChild(anchorChild, role, child); } } public int getChildCount(String role) { if (ourMemberAccessModifier != null) { role = ourMemberAccessModifier.getNewChildRole(myModel, myConceptFqName, role); } int count = 0; boolean isOldAttributeRole = AttributeOperations.isOldAttributeRole(role); for (SNode child = getFirstChild(); child != null; child = child.myNextSibling) { if (role.equals(child.getRole_())) { count++; } else if (isOldAttributeRole && AttributeOperations.isOldRoleForNewAttribute(child, role)) { count++; } } return count; } public int getIndexOfChild(SNode child_) { ModelAccess.assertLegalRead(this); fireNodeReadAccess(); fireNodeUnclassifiedReadAccess(); String role_ = child_.getRole_(); if (role_ == null) return -1; int count = 0; for (SNode child = getFirstChild(); child != null; child = child.myNextSibling) { if (child == child_) return count; if (role_.equals(child.getRole_())) { count++; } } return -1; } public List<SNode> getChildren() { return getChildren(true); } private List<SReference> _reference() { return new MyReferencesWrapper(); } public Iterable<SNode> getChildrenIterable() { return new Iterable<SNode>() { public Iterator<SNode> iterator() { return new Iterator<SNode>() { private SNode current = getFirstChild(); public boolean hasNext() { return current != null; } public SNode next() { SNode result = current; current = current.myNextSibling; return result; } public void remove() { throw new UnsupportedOperationException(); } }; } }; } public List<SNode> getChildren(boolean includeAttributes) { ModelAccess.assertLegalRead(this); fireNodeReadAccess(); fireNodeUnclassifiedReadAccess(); SNode firstChild = getFirstChild(); if (includeAttributes) { return new ChildrenList(firstChild); } else { return new SkipAttributesChildrenList(firstChild); } } private void fireNodeUnclassifiedReadAccess() { if (myModel.isLoading()) return; NodeReadEventsCaster.fireNodeUnclassifiedReadAccess(this); } public int getChildCount() { ModelAccess.assertLegalRead(this); fireNodeReadAccess(); fireNodeUnclassifiedReadAccess(); int count = 0; for (SNode child = getFirstChild(); child != null; child = child.myNextSibling) { count++; } return count; } private void fireNodeReadAccess() { if (myModel.isLoading()) return; NodeReadAccessCasterInEditor.fireNodeReadAccessed(this); } @NotNull public List<SNode> getChildren(String role) { ModelAccess.assertLegalRead(this); if (ourMemberAccessModifier != null) { role = ourMemberAccessModifier.getNewChildRole(myModel, myConceptFqName, role); } fireNodeReadAccess(); fireNodeUnclassifiedReadAccess(); SNode firstChild = getFirstChild(); if (firstChild == null) return Collections.emptyList(); List<SNode> result = new ArrayList<SNode>(); boolean isOldAttributeRole = AttributeOperations.isOldAttributeRole(role); for (SNode child = firstChild; child != null; child = child.myNextSibling) { if (role.equals(child.getRole_())) { result.add(child); child.fireNodeReadAccess(); NodeReadEventsCaster.fireNodeChildReadAccess(this, role, child); } else if (isOldAttributeRole && AttributeOperations.isOldRoleForNewAttribute(child, role)) { result.add(child); child.fireNodeReadAccess(); NodeReadEventsCaster.fireNodeChildReadAccess(this, role, child); } } return result; } public SNode getNextChild(SNode child) { String childRole = child.getRole_(); assert childRole != null : "role must be not null"; List<SNode> children = getChildren(childRole); int index = children.indexOf(child); if (index < 0 || index >= children.size() - 1) return null; return children.get(index + 1); } public SNode getPrevChild(SNode child) { String childRole = child.getRole_(); assert childRole != null : "role must be not null"; List<SNode> children = getChildren(childRole); int index = children.indexOf(child); if (index <= 0) return null; return children.get(index - 1); } /** * Removes child from current node. This affects only link between current node and its child, but not links in * subtree of child node. * <p/> * Differs from {@link SNode#delete()}. * * @param wasChild */ public void removeChild(SNode wasChild) { if (wasChild.myParent != this) return; ModelChange.assertLegalNodeChange(this); final String wasRole = wasChild.getRole_(); SNode anchor = getFirstChild() == wasChild ? null : wasChild.myPrevSibling; assert wasRole != null; if (ModelChange.needFireEvents(getModel(), this)) { getModel().fireBeforeChildRemovedEvent(this, wasRole, wasChild, anchor); } children_remove(wasChild); wasChild.myRoleInParent = null; wasChild.unRegisterFromModel(); if (UndoHelper.getInstance().needRegisterUndo(getModel())) { UndoHelper.getInstance().addUndoableAction(new RemoveChildUndoableAction(this, anchor, wasRole, wasChild)); } if (ModelChange.needFireEvents(getModel(), this)) { getModel().fireChildRemovedEvent(this, wasRole, wasChild, anchor); } } public void insertChild(final SNode anchor, String _role, final SNode child) { enforceModelLoad(); if (ourMemberAccessModifier != null) { _role = ourMemberAccessModifier.getNewChildRole(myModel, myConceptFqName, _role); } final String role = _role; SNode parentOfChild = child.getParent(); if (parentOfChild != null) { throw new RuntimeException(child.getDebugText() + " already has parent: " + parentOfChild.getDebugText() + "\n" + "Couldn't add it to: " + this.getDebugText()); } if (child.isRoot()) { throw new RuntimeException(child.getDebugText() + " is root node. Can't add it as a child"); } if (getTopmostAncestor() == child) { throw new RuntimeException("Trying to create a cyclic tree"); } ModelChange.assertLegalNodeChange(this); children_insertAfter(anchor, child); child.myRoleInParent = InternUtil.intern(role); if (isRegistered()) { child.registerInModel(getModel()); } else { child.changeModel(getModel()); } if (UndoHelper.getInstance().needRegisterUndo(getModel())) { UndoHelper.getInstance().addUndoableAction(new InsertChildAtUndoableAction(this, anchor, _role, child)); } if (ModelChange.needFireEvents(getModel(), this)) { getModel().fireChildAddedEvent(this, role, child, anchor); } } void unRegisterFromModel() { if (!myRegisteredInModelFlag) return; UnregisteredNodes.instance().put(this); myRegisteredInModelFlag = false; if (myAdapter != null) { UnregisteredNodesWithAdapters.getInstance().add(this); } myModel.unregisterNode(this); for (SNode child = getFirstChild(); child != null; child = child.myNextSibling) { child.unRegisterFromModel(); } } void registerInModel(SModel model) { registerInModel_internal(model); // add language because typesystem needs it to invalidate/revalidate its caches //todo this is a hack SModelOperations.validateLanguages(model, this); } private void registerInModel_internal(SModel model) { if (myRegisteredInModelFlag) { if (model != myModel) { LOG.errorWithTrace("couldn't register node which is already registered in '" + myModel.getSModelReference() + "'"); } return; } SModel wasModel = myModel; myModel = model; myModel.registerNode(this); myRegisteredInModelFlag = true; UnregisteredNodes.instance().remove(this); if (myAdapter != null) { UnregisteredNodesWithAdapters.getInstance().remove(this); } if (wasModel != model) { ModelChangedCaster.getInstance().fireModelChanged(this, wasModel); } for (SNode child = getFirstChild(); child != null; child = child.myNextSibling) { child.registerInModel_internal(model); } } void dispose() { //myModel = null; //myRegisteredInModelFlag = false; //myChildren = null; //myReferences = null; //myProperties = null; myDisposed = true; myAdapter = null; myUserObjects = null; } public boolean isDisposed() { return myDisposed; } public boolean shouldHaveBeenDisposed() { return isDisposed() || myModel.isDisposed(); } public boolean isDetached() { return getContainingRoot() == null; } public boolean isRegistered() { return myRegisteredInModelFlag; } public List<SReference> getReferences() { ModelAccess.assertLegalRead(this); fireNodeReadAccess(); fireNodeUnclassifiedReadAccess(); return new ArrayList<SReference>(_reference()); } public SReference[] getReferencesArray() { SReference[] references = new SReference[myReferences.length]; System.arraycopy(myReferences, 0, references, 0, myReferences.length); return references; } public Collection<SReference> getReferencesIterable() { return new AbstractList<SReference>() { public SReference get(int index) { return myReferences[index]; } public int size() { return myReferences.length; } }; } public SReference setReferent(String role, SNode newReferent) { return setReferent(role, newReferent, true); } public SReference setReferent(String role, SNode newReferent, boolean useHandler) { if (ourMemberAccessModifier != null) { role = ourMemberAccessModifier.getNewReferentRole(myModel, myConceptFqName, role); } // remove old references List<SReference> toDelete = new ArrayList<SReference>(); if (myReferences != null) { for (SReference reference : myReferences) { if (reference.getRole().equals(role)) { toDelete.add(reference); } } } SNode oldReferent = null; if (!toDelete.isEmpty()) { oldReferent = toDelete.get(0).getTargetNode(); } if (toDelete.size() > 1) { LOG.errorWithTrace("ERROR! " + toDelete.size() + " references found for role '" + role + "' in " + this.getDebugText()); } SReference resultReference = null; boolean handlerFound = false; if (useHandler && !getModel().isLoading()) { // invoke custom referent set event handler Set<Pair<SNode, String>> threadSet = ourSetReferentEventHandlersInProgress.get(); Pair<SNode, String> pair = new Pair<SNode, String>(this, role); if (!threadSet.contains(pair)) { ReferenceConstraintsDescriptor descriptor = ConceptRegistry.getInstance().getConstraintsDescriptor(this.getConceptFqName()).getReference(role); if (!(descriptor instanceof IllegalReferenceConstraintsDescriptor)) { handlerFound = true; threadSet.add(pair); try { if (descriptor.validate(this, oldReferent, newReferent, GlobalScope.getInstance())) { resultReference = doSetReference(role, newReferent, toDelete); descriptor.onReferenceSet(this, oldReferent, newReferent, GlobalScope.getInstance()); } else { if (myReferences != null) { for (SReference reference : myReferences) { if (reference.getRole().equals(role)) { resultReference = reference; break; } } } } } finally { threadSet.remove(pair); } } else { // todo: ? } } } if (!handlerFound) { resultReference = doSetReference(role, newReferent, toDelete); } return resultReference; } private SReference doSetReference(String role, SNode newReferent, List<SReference> toDelete) { for (SReference reference : toDelete) { int index = _reference().indexOf(reference); removeReferenceAt(index); } SReference resultReference = null; if (newReferent != null) { resultReference = SReference.create(role, this, newReferent); insertReferenceAt(myReferences == null ? 0 : myReferences.length, resultReference); } return resultReference; } public SNode getReferent(String role) { SReference reference = getReference(role); SNode result = reference == null ? null : reference.getTargetNode(); if (result != null) { NodeReadEventsCaster.fireNodeReferentReadAccess(this, role, result); } return result; } public SReference getReference(String role) { ModelAccess.assertLegalRead(this); if (ourMemberAccessModifier != null) { role = ourMemberAccessModifier.getNewReferentRole(myModel, myConceptFqName, role); } fireNodeReadAccess(); SReference result = null; int count = 0; // paranoid check if (myReferences != null) { for (SReference reference : myReferences) { if (reference.getRole().equals(role)) { result = reference; count++; } } } if (count > 1) { LOG.errorWithTrace("ERROR: " + count + " referents for role '" + role + "' in " + getDebugText()); } NodeReadEventsCaster.fireNodeReferentReadAccess(this, role, null); return result; } public void addReference(SReference reference) { assert reference.getSourceNode() == this; insertReferenceAt(myReferences == null ? 0 : myReferences.length, reference); } public void removeReferent(String role) { if (ourMemberAccessModifier != null) { role = ourMemberAccessModifier.getNewReferentRole(myModel, myConceptFqName, role); } if (myReferences != null) { for (SReference reference : myReferences) { if (reference.getRole().equals(role)) { int index = _reference().indexOf(reference); removeReferenceAt(index); break; } } } } public void removeReference(SReference referenceToRemove) { if (myReferences != null) { for (SReference reference : myReferences) { if (reference.equals(referenceToRemove)) { int index = _reference().indexOf(reference); removeReferenceAt(index); break; } } } } public void replaceReference(SReference referenceToRemove, @NotNull SReference referenceToAdd) { if (myReferences != null) { for (SReference reference : myReferences) { if (reference.equals(referenceToRemove)) { int index = _reference().indexOf(reference); replaceReferenceAt(index, referenceToAdd); break; } } } } public List<SNode> getReferents() { ModelAccess.assertLegalRead(this); fireNodeReadAccess(); fireNodeUnclassifiedReadAccess(); List<SNode> result = new ArrayList<SNode>(); if (myReferences != null) { for (SReference reference : myReferences) { SNode targetNode = reference.getTargetNode(); if (targetNode != null) result.add(targetNode); } } return result; } void insertReferenceAt(final int i, final SReference reference) { ModelChange.assertLegalNodeChange(this); _reference().add(i, reference); if (UndoHelper.getInstance().needRegisterUndo(getModel())) { UndoHelper.getInstance().addUndoableAction(new InsertReferenceAtUndoableAction(this, i, reference)); } if (ModelChange.needFireEvents(getModel(), this)) { getModel().fireReferenceAddedEvent(reference); } } private void replaceReferenceAt(int index, @NotNull SReference referenceToAdd) { ModelChange.assertLegalNodeChange(this); if (UndoHelper.getInstance().needRegisterUndo(getModel()) || ModelChange.needFireEvents(getModel(), this)) { removeReferenceAt(index); insertReferenceAt(index, referenceToAdd); } else { myReferences[index] = referenceToAdd; } } void removeReferenceAt(final int i) { ModelChange.assertLegalNodeChange(this); final SReference reference = myReferences[i]; _reference().remove(reference); if (UndoHelper.getInstance().needRegisterUndo(getModel())) { UndoHelper.getInstance().addUndoableAction(new RemoveReferenceAtUndoableAction(this, i, reference)); } if (ModelChange.needFireEvents(getModel(), this)) { getModel().fireReferenceRemovedEvent(reference); } } /** * Deletes all nodes in subtree starting with current. Differs from {@link SNode#removeChild(SNode)}. */ public void delete() { delete_internal(); } private void delete_internal() { //delete all children List<SNode> children = new ArrayList<SNode>(getChildren()); for (SNode child : children) { child.delete_internal(); } //remove all references removeAllReferences(); //remove from parent SNode parent = getParent(); if (parent != null) { parent.removeChild(this); } else if (getModel().isRoot(this)) { getModel().removeRoot(this); } // really delete UnregisteredNodes.instance().remove(this); } private void removeAllReferences() { while (_reference().size() > 0) { removeReferenceAt(0); } } public boolean isDeleted() { return (_reference().size() == 0) && myParent == null && !getModel().isRoot(this); } public String getDebugText() { String roleText = ""; if (isRegistered()) { String s = getRole_(); roleText = s == null ? "[root]" : "[" + s + "]"; } String nameText; try { if ("jetbrains.mps.bootstrap.structureLanguage.structure.LinkDeclaration".equals(getConceptFqName())) { // !!! use *safe* getRole !!! String role = myProperties == null ? null : getProperty_simple("role"); nameText = (role == null) ? "<no role>" : '"' + role + '"'; } else { // !!! use *safe* getName !!! String name = myProperties == null ? null : getProperty_simple("name"); nameText = (name == null) ? "<no name>" : '"' + name + '"'; } // !!! use *safe* getId !!! nameText = nameText + "[" + myId + "]"; } catch (Exception e) { //e.printStackTrace(); nameText = "<??name??>"; } return roleText + " " + NameUtil.shortNameFromLongName(getConceptShortName()) + " " + nameText + " in " + myModel.getSModelFqName(); } public boolean hasId() { return myId != null; } public String getId() { return getSNodeId().toString(); } public SNodeId getId_() { return myId; } public SNodeId getSNodeId() { ModelAccess.assertLegalRead(this); fireNodeReadAccess(); if (myId == null && !isRegistered()) { // TODO remove id generation myId = SModel.generateUniqueId(); //LOG.error(new IllegalStateException("cannot generate id for unregistered node")); } return myId; } public void setId(@Nullable SNodeId id) { if (ObjectUtils.equals(id, myId)) return; if (!isRegistered()) { myId = id; } else { LOG.error("can't set id to registered node " + getDebugText(), new Throwable()); } } public String getPresentation() { return getPresentation(false); } public String getPresentation(boolean detailed) { if (SNodeOperations.isUnknown(this)) { String persistentName = getPersistentProperty(SNodeUtil.property_INamedConcept_name); if (persistentName == null) { return "?" + getConceptShortName() + "?"; } return "?" + persistentName + "?"; } try { /* Warning: BaseConcept_Behavior class will be loaded using platform classloader here. As a result this class will be loaded twice - once using own BundleClassLoader and one more time - here. */ if (detailed) { return "" + SNodeUtil.getDetailedPresentation(this); } else { return "" + SNodeUtil.getPresentation(this); } } catch (RuntimeException t) { LOG.error(t); return "[can't calculate presentation : " + t.getMessage() + "]"; } } public String toString() { ModelAccess.assertLegalRead(this); fireNodeReadAccess(); String s = null; try { s = getPersistentProperty(SNodeUtil.property_BaseConcept_alias); if (s == null) { s = getPresentation(); } } catch (RuntimeException t) { LOG.error(t, this); } if (s == null) { return "???"; } return s; } public List<SNode> getDescendants() { return getDescendants(null); } public Iterable<SNode> getDescendantsIterable(@Nullable final Condition<SNode> condition, final boolean includeFirst) { return new DescendantsIterable(this, includeFirst ? this : getFirstChild(), condition); } public List<SNode> getDescendants(Condition<SNode> condition) { ModelAccess.assertLegalRead(this); fireNodeReadAccess(); fireNodeUnclassifiedReadAccess(); List<SNode> list = new ArrayList<SNode>(); collectDescendants(condition, list); return list; } private void collectDescendants(Condition<SNode> condition, List<SNode> list) { // depth-first traversal for (SNode child = getFirstChild(); child != null; child = child.myNextSibling) { if (condition == null || condition == Condition.TRUE_CONDITION || condition.met(child)) { list.add(child); } child.collectDescendants(condition, list); } } public boolean isDescendantOf(SNode node, boolean includeThis) { SNode current; if (includeThis) { current = this; } else { current = getParent(); } while (current != null) { if (current == node) { return true; } current = current.getParent(); } return false; } public Language getNodeLanguage() { SNode concept = getConceptDeclarationNode(); return SModelUtil.getDeclaringLanguage(concept); } @NotNull public String getConceptFqName() { ModelAccess.assertLegalRead(this); fireNodeReadAccess(); fireNodeUnclassifiedReadAccess(); return myConceptFqName; } public ModuleReference getConceptLanguage() { return new ModuleReference(getLanguageNamespace()); } @NotNull public String getConceptShortName() { ModelAccess.assertLegalRead(this); fireNodeReadAccess(); return NameUtil.shortNameFromLongName(myConceptFqName); } @NotNull public String getLanguageNamespace() { ModelAccess.assertLegalRead(this); fireNodeReadAccess(); return InternUtil.intern(NameUtil.namespaceFromConceptFQName(myConceptFqName)); } @UseCarefully void setConceptFqName(@NotNull String conceptFQName) { myConceptFqName = InternUtil.intern(conceptFQName); myAdapter = null; SModelRepository.getInstance().markChanged(getModel()); } public boolean isInstanceOfConcept(SNode concept) { return isInstanceOfConcept(NameUtil.nodeFQName(concept)); } public boolean isInstanceOfConcept(String conceptFqName) { return SModelUtil.isAssignableConcept(myConceptFqName, conceptFqName); } public SNode getConceptDeclarationNode() { return SModelUtil.findConceptDeclaration(getConceptFqName(), GlobalScope.getInstance()); } public SNode getPropertyDeclaration(String propertyName) { return SModelSearchUtil.findPropertyDeclaration(getConceptDeclarationNode(), propertyName); } public SNode getLinkDeclaration(String role) { return SModelSearchUtil.findLinkDeclaration(getConceptDeclarationNode(), role); } public SNode findParent(Condition<SNode> condition) { SNode parent = getParent(); while (parent != null) { if (condition.met(parent)) { return parent; } parent = parent.getParent(); } return null; } public SNode findChildByPath(String path) { if (path == null) return null; String residual = path; SNode current = this; while (!residual.equals("") && current != null) { residual = residual.substring(1); int index = residual.indexOf("/"); String roleAndNumber = index == -1 ? residual : residual.substring(0, index); residual = residual.substring(roleAndNumber.length()); int numberIndex = roleAndNumber.indexOf("#"); String role = numberIndex == -1 ? roleAndNumber : roleAndNumber.substring(0, numberIndex); String numberString = numberIndex == -1 ? "-1" : roleAndNumber.substring(numberIndex + 1); int number = Integer.parseInt(numberString); if (number == -1) { current = current.getChild(role); } else { List<SNode> childrenForRole = current.getChildren(role); if (number < childrenForRole.size()) { current = childrenForRole.get(number); } else { current = null; } } } return current; } public String getNodePath(SNode child) { StringBuilder sb = new StringBuilder(); SNode current = child; while (current != this && current != null) { String role = current.getRole_(); SNode currentParent = current.getParent(); List<SNode> children = currentParent == null || role == null ? new ArrayList<SNode>() : currentParent.getChildren(role); String numberString = children.size() <= 1 ? "" : "#" + children.indexOf(current); sb.insert(0, "/" + role + numberString); current = currentParent; } return sb.toString(); } public boolean isReferentRequired(String role) { SNode conceptDeclaration = getConceptDeclarationNode(); SNode linkDeclaration = SModelSearchUtil.findLinkDeclaration(conceptDeclaration, role); if (linkDeclaration == null) { LOG.error("couldn't find link declaration for role \"" + role + "\" in hierarchy of concept " + conceptDeclaration.getDebugText()); return false; } SNode genuineLinkDeclaration = SModelUtil.getGenuineLinkDeclaration(linkDeclaration); return SNodeUtil.getLinkDeclaration_IsAtLeastOneMultiplicity(genuineLinkDeclaration); } public Language getLanguage() { String languageNamespace = getLanguageNamespace(); return MPSModuleRepository.getInstance().getLanguage(languageNamespace); } public void setRoleInParent(String newRoleInParent) {//todo add undo myRoleInParent = InternUtil.intern(newRoleInParent); } public SNode prevSibling() { if (myParent == null) return null; return myParent.getFirstChild() == this ? null : myPrevSibling; } public SNode nextSibling() { return myNextSibling; } private class MyReferencesWrapper extends ArrayWrapper<SReference> { protected SReference[] getArray() { return myReferences; } protected void setArray(SReference[] newArray) { myReferences = newArray; } protected SReference[] newArray(int size) { return new SReference[size]; } } private void children_insertAfter(SNode anchor, @NotNull SNode node) { //be sure that getFirstChild is called before any access to myFirstChild SNode firstChild = getFirstChild(); if (anchor == null) { if (firstChild != null) { node.myPrevSibling = firstChild.myPrevSibling; firstChild.myPrevSibling = node; } else { node.myPrevSibling = node; } node.myNextSibling = firstChild; myFirstChild = node; } else { node.myPrevSibling = anchor; node.myNextSibling = anchor.myNextSibling; if (anchor.myNextSibling == null) { firstChild.myPrevSibling = node; } else { anchor.myNextSibling.myPrevSibling = node; } anchor.myNextSibling = node; } node.myParent = this; } private void children_remove(@NotNull SNode node) { //be sure that getFirstChild is called before any access to myFirstChild SNode firstChild = getFirstChild(); if (firstChild == node) { myFirstChild = node.myNextSibling; if (myFirstChild != null) { myFirstChild.myPrevSibling = node.myPrevSibling; } } else { node.myPrevSibling.myNextSibling = node.myNextSibling; if (node.myNextSibling != null) { node.myNextSibling.myPrevSibling = node.myPrevSibling; } else { firstChild.myPrevSibling = node.myPrevSibling; } } node.myPrevSibling = node.myNextSibling = null; node.myParent = null; } private static class ChildrenList extends AbstractImmutableList<SNode> { public ChildrenList(SNode first) { super(first); } public ChildrenList(SNode first, int size) { super(first, size); } @Override protected SNode next(SNode node) { return node.myNextSibling; } @Override protected SNode prev(SNode node) { return node.myPrevSibling; } @Override protected AbstractImmutableList<SNode> subList(SNode elem, int size) { return new ChildrenList(elem, size); } } private static class SkipAttributesChildrenList extends AbstractImmutableList<SNode> { public SkipAttributesChildrenList(SNode first) { super(skipAttributes(first)); } public SkipAttributesChildrenList(SNode first, int size) { super(skipAttributes(first), size); } private static SNode skipAttributes(SNode node) { while (node != null && AttributeOperations.isAttribute(node)) { node = node.myNextSibling; } return node; } protected SNode next(SNode node) { return skipAttributes(node.myNextSibling); } protected SNode prev(SNode node) { SNode result = myFirst == node ? null : node.myPrevSibling; while (result != null && AttributeOperations.isAttribute(result)) { result = myFirst == result ? null : result.myPrevSibling; } return result; } protected AbstractImmutableList<SNode> subList(SNode elem, int size) { return new SkipAttributesChildrenList(elem, size); } } private static class InProgressThreadLocal extends ThreadLocal<Set<Pair<SNode, String>>> { protected Set<Pair<SNode, String>> initialValue() { return new HashSet<Pair<SNode, String>>(); } } private static class DescendantsIterable implements /* RF-758 */ TreeIterator<SNode>, Iterable<SNode> { private SNode original; private SNode current; private Condition<SNode> condition; private SNode prev; DescendantsIterable(SNode original, SNode first, @Nullable Condition<SNode> condition) { this.original = original; this.current = first; this.condition = condition; while (current != null && condition != null && !condition.met(current)) { current = nextInternal(current, false); } } public boolean hasNext() { return current != null; } public SNode next() { SNode result = current; do { current = nextInternal(current, false); } while (current != null && condition != null && !condition.met(current)); prev = result; return result; } public void skipChildren() { if(prev == null) throw new IllegalStateException("no element"); current = nextInternal(prev, true); while (current != null && condition != null && !condition.met(current)) { current = nextInternal(current, false); } } private SNode nextInternal(SNode curr, boolean skipChildren) { if (curr == null) return null; if (!skipChildren) { SNode firstChild = curr.getFirstChild(); if (firstChild != null) return firstChild; } if (curr == original) return null; do { if (curr.myNextSibling != null) { return curr.myNextSibling; } curr = curr.myParent; } while (curr != original); return null; } public void remove() { throw new UnsupportedOperationException(); } public Iterator<SNode> iterator() { return this; } } //------------adapters------------- public BaseAdapter getAdapter() { ModelAccess.assertLegalRead(this); BaseAdapter adapter = myAdapter; if (adapter != null) return adapter; Constructor c = QueryMethodGenerated.getAdapterConstructor(getConceptFqName()); if (c == null) c = QueryMethodGenerated.getAdapterConstructor(SNodeUtil.concept_BaseConcept); if (c == null) return new BaseAdapter(this) { }; synchronized (this) { adapter = myAdapter; if (adapter != null) return adapter; try { adapter = (BaseAdapter) c.newInstance(this); assert adapter.getNode() == this; if (!myRegisteredInModelFlag) { UnregisteredNodesWithAdapters.getInstance().add(this); } myAdapter = adapter; return adapter; } catch (IllegalAccessException e) { LOG.error(e); } catch (InvocationTargetException e) { LOG.error(e); } catch (InstantiationException e) { LOG.error(e); } catch (Throwable t) { LOG.error(t); } } return new BaseAdapter(this) { }; } void clearAdapter() { myAdapter = null; } //------------user objects------------- public Object getUserObject(Object key) { ModelAccess.assertLegalRead(this); fireNodeReadAccess(); if (myUserObjects == null) return null; for (int i = 0; i < myUserObjects.length; i += 2) { if (myUserObjects[i].equals(key)) { return myUserObjects[i + 1]; } } return null; } public void putUserObject(Object key, Object value) { if (value == null) { removeUserObject(key); return; } if (myUserObjects == null) { myUserObjects = new Object[]{key, value}; } else { for (int i = 0; i < myUserObjects.length; i += 2) { if (myUserObjects[i].equals(key)) { myUserObjects = Arrays.copyOf(myUserObjects, myUserObjects.length, Object[].class); myUserObjects[i + 1] = value; return; } } Object[] newarr = new Object[myUserObjects.length + 2]; System.arraycopy(myUserObjects, 0, newarr, 2, myUserObjects.length); newarr[0] = key; newarr[1] = value; myUserObjects = newarr; } } public void putUserObjects(SNode fromNode) { if (fromNode == null || fromNode.myUserObjects == null) return; if (myUserObjects == null) { myUserObjects = fromNode.myUserObjects; } else { for (int i = 0; i < fromNode.myUserObjects.length; i += 2) { putUserObject(fromNode.myUserObjects[i], fromNode.myUserObjects[i + 1]); } } } public void removeUserObject(Object key) { if (myUserObjects == null) return; for (int i = 0; i < myUserObjects.length; i += 2) { if (myUserObjects[i].equals(key)) { Object[] newarr = new Object[myUserObjects.length - 2]; if (i > 0) { System.arraycopy(myUserObjects, 0, newarr, 0, i); } if (i + 2 < myUserObjects.length) { System.arraycopy(myUserObjects, i + 2, newarr, i, newarr.length - i); } myUserObjects = newarr; break; } } if (myUserObjects.length == 0) { myUserObjects = null; } } public void removeAllUserObjects() { myUserObjects = null; } //------------concept properties------------- public boolean hasConceptProperty(String propertyName) { if ("root".equals(propertyName)) { if (SNodeUtil.isInstanceOfConceptDeclaration(this)) { return SNodeUtil.getConceptDeclaration_IsRootable(this); } else { SNode conceptDeclaration = getConceptDeclarationNode(); if (SNodeUtil.isInstanceOfConceptDeclaration(conceptDeclaration)) { return SNodeUtil.getConceptDeclaration_IsRootable(conceptDeclaration); } } return false; } return findConceptProperty(propertyName) != null; } public String getConceptProperty(String propertyName) { SNode conceptProperty = findConceptProperty(propertyName); Object o = SNodeUtil.getConceptPropertyValue(conceptProperty); return o != null ? o.toString() : null; } public SNode findConceptProperty(String propertyName) { SNode conceptDeclaration; if (myConceptFqName.equals(SNodeUtil.concept_ConceptDeclaration) || myConceptFqName.equals(SNodeUtil.concept_InterfaceConceptDeclaration)) { conceptDeclaration = this; } else { conceptDeclaration = SModelUtil.findConceptDeclaration(myConceptFqName, GlobalScope.getInstance()); } return SModelSearchUtil.findConceptProperty(conceptDeclaration, propertyName); } }
89f6e47627bf23035ed126f50236ccec4045318d
8af1164bac943cef64e41bae312223c3c0e38114
/results-java/gradle--gradle/0b643d2767ccef06763829a27fc07d642cbe4c64/after/GradlePropertiesConfigurer.java
774f6977b6d4cec790955d9b208d47215c214df0
[]
no_license
fracz/refactor-extractor
3ae45c97cc63f26d5cb8b92003b12f74cc9973a9
dd5e82bfcc376e74a99e18c2bf54c95676914272
refs/heads/master
2021-01-19T06:50:08.211003
2018-11-30T13:00:57
2018-11-30T13:00:57
87,353,478
0
0
null
null
null
null
UTF-8
Java
false
false
1,679
java
/* * Copyright 2013 the original author or authors. * * 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.gradle.launcher.daemon.configuration; import org.gradle.StartParameter; import java.io.File; import java.util.Map; /** * by Szczepan Faber, created at: 1/22/13 */ public class GradlePropertiesConfigurer { public GradleProperties prepareProperties(File projectDir, boolean searchUpwards, File gradleUserHomeDir, Map<?, ?> systemProperties) { return new GradleProperties() .configureFromBuildDir(projectDir, searchUpwards) .configureFromGradleUserHome(gradleUserHomeDir) .configureFromSystemProperties(systemProperties); } public DaemonParameters configureParameters(StartParameter startParameter) { DaemonParameters out = new DaemonParameters(); GradleProperties properties = this.prepareProperties(startParameter.getCurrentDir(), startParameter.isSearchUpwards(), startParameter.getGradleUserHomeDir(), startParameter.getMergedSystemProperties()); properties.updateStartParameter(startParameter); out.configureFrom(properties); return out; } }
3d13fc1c214511fe5b3fa79ae93796ea366c70e1
ab3fb59f90757b2cbe8338587580e67fc7886d4c
/src/controller/AddRoomServlet.java
b29aff5e0f649a698fd66f04fa8d29dbd9b2ff1c
[]
no_license
vwierenga/Kamerverhuur
cee8b30392a58499ff29c77d01f446661f98799d
12f8b6ebe68dcacc3a707ca4d0a0a138211f18a3
refs/heads/master
2020-09-13T13:48:23.760384
2016-09-09T11:07:15
2016-09-09T11:07:15
66,851,890
0
0
null
null
null
null
UTF-8
Java
false
false
2,192
java
package controller; import model.Room; import model.User; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.util.ArrayList; /** * Created by Vincent on 9/9/2016. */ @WebServlet("/AddRoomServlet") public class AddRoomServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String action = request.getParameter("action"); HttpSession session = request.getSession(false); //Checks if you're logged in. if (session != null && session.getAttribute("login") != null && (Boolean) session.getAttribute("login")) { if ("Toevoegen".equals(action)) { User currentUser = (User) session.getAttribute("currentUser"); if (currentUser.isOwner()) { //adds the room to the arraylist. int size = Integer.parseInt(request.getParameter("size")); int price = Integer.parseInt(request.getParameter("price")); String address = request.getParameter("address"); String city = request.getParameter("city"); if (address != null && city != null) { ArrayList<Room> rooms = (ArrayList<Room>) getServletContext().getAttribute("rooms"); rooms.add(new Room(size, price, address, city, currentUser)); } getServletContext().getRequestDispatcher("/showRooms").forward(request, response); } } else if("Kamer Overzicht".equals(action)) { //returns you to showRooms in case you changed your mind. getServletContext().getRequestDispatcher("/showRooms").forward(request, response); } } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
83eedddb937bfb1749066afd0da2ee5d9ca2af61
feb3890c1caf209e4b87938784c41ec4973f1ce2
/summary-service/src/main/java/com/lp/rpc/impl/ApiServiceImpl.java
6b804c338b41d7feb43b1cbaa6d3f46e5881f1b3
[]
no_license
tw0629/summary
27546daf5277275814741306624724748afe914f
3e7fd9fd3115f3c5a3a1ea4a069c0a41d5213478
refs/heads/master
2021-06-17T00:11:17.411458
2017-03-11T15:57:15
2017-03-11T15:57:15
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,987
java
package com.lp.rpc.impl; import com.lp.rpc.ApiService; import com.lp.rpc.commen.ResponseBean; import com.lp.summary.dao.UserDao; import com.lp.web.beans.UserBean; import com.migr.common.util.JsonUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * Created by Administrator on 2016/9/6. */ public class ApiServiceImpl implements ApiService { private static final Log log = LogFactory.getLog(ApiServiceImpl.class); @Autowired private UserDao userDao; private String token;//供调用rpc校验使用 public String getToken() { return token; } public ResponseBean add(String reqJson) { ResponseBean responseBean = new ResponseBean(ResponseBean.SUCCESS, "调用成功"); try { Map map = JsonUtil.g.fromJson(reqJson, HashMap.class); String username = map.get("username").toString(); String password = map.get("password").toString(); String realname = map.get("realname").toString(); Long userroleid =Double.valueOf(map.get("userroleid").toString()).longValue() ; UserBean userBean = new UserBean(); userBean.setCreatedate(new Date()); userBean.setPassword(password); userBean.setUserroleid(userroleid); userBean.setRealname(realname); userBean.setUsername(username); int count = userDao.add(userBean); responseBean.setReturnData(JsonUtil.g.toJson(count)); responseBean.setReturnCode(10); } catch (Exception e) { log.error(e.getStackTrace()); responseBean.setReturnCode(11); responseBean.setReturnMsg("服务器异常"); } return responseBean; } public void setToken(String token) { this.token = token; } }
[ "lipei@Lenovo-PC" ]
lipei@Lenovo-PC
b5f3bcf0b49441bfbc3b425db8aeefa9871ddcf8
58df55b0daff8c1892c00369f02bf4bf41804576
/src/gia.java
76d37b62a2bee0155469324af24e3b9794c0b476
[]
no_license
gafesinremedio/com.google.android.gm
0b0689f869a2a1161535b19c77b4b520af295174
278118754ea2a262fd3b5960ef9780c658b1ce7b
refs/heads/master
2020-05-04T15:52:52.660697
2016-07-21T03:39:17
2016-07-21T03:39:17
null
0
0
null
null
null
null
UTF-8
Java
false
false
501
java
import android.content.ContentResolver; import android.os.Handler; import android.os.Looper; final class gia extends Thread { gia(String paramString, ContentResolver paramContentResolver) { super(paramString); } public final void run() { Looper.prepare(); a.registerContentObserver(ghz.a, true, new gib(this, new Handler(Looper.myLooper()))); Looper.loop(); } } /* Location: * Qualified Name: gia * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
e1854eae081deeda16d4dffca3b5196381e0c764
97b361864cf3a44ec62dcc893c456ccdb6fa55a9
/src/com/yufan/pojo/TbRoleFunction.java
77b391aa5224ec24771deae94f9bf4bf9dca4d5f
[]
no_license
lirf2018/rs_store_manage
63d1aa30ebc11260f34c0408c24c8970bdc5933c
8b0f0e6618df4ce692450e25a7e693c6c53e05fe
refs/heads/master
2020-06-24T23:36:16.069642
2019-07-09T02:37:54
2019-07-09T02:38:26
195,915,502
0
0
null
null
null
null
UTF-8
Java
false
false
1,648
java
package com.yufan.pojo; import java.util.Date; /** * TbRoleFunction entity. @author MyEclipse Persistence Tools */ public class TbRoleFunction implements java.io.Serializable { // Fields private Integer roleFunctionId; private Integer roleId; private Integer functionId; private String createman; private Date createtime; // Constructors /** * default constructor */ public TbRoleFunction() { } /** * full constructor */ public TbRoleFunction(Integer roleId, Integer functionId, String createman, Date createtime) { this.roleId = roleId; this.functionId = functionId; this.createman = createman; this.createtime = createtime; } // Property accessors public Integer getRoleFunctionId() { return this.roleFunctionId; } public void setRoleFunctionId(Integer roleFunctionId) { this.roleFunctionId = roleFunctionId; } public Integer getRoleId() { return this.roleId; } public void setRoleId(Integer roleId) { this.roleId = roleId; } public Integer getFunctionId() { return this.functionId; } public void setFunctionId(Integer functionId) { this.functionId = functionId; } public String getCreateman() { return this.createman; } public void setCreateman(String createman) { this.createman = createman; } public Date getCreatetime() { return this.createtime; } public void setCreatetime(Date createtime) { this.createtime = createtime; } }
3c98cb319b2496e6a23b51f74b383b4652c0078a
7b16b8f01548780d8c69c3d0b992972f938c5163
/src/extra/SoundEffectsMachine.java
2a3a337cac7b6cf8af242437440ff4581e1c1a7a
[]
no_license
League-Level1-Student/level1-module0-sheridanliew
3d08ce77e78382928c48f33690ee99410ada0ff0
d542705caeacff1c6cfe743b89eece5e43e2a10a
refs/heads/master
2020-03-24T19:02:50.117257
2018-08-07T18:50:47
2018-08-07T18:50:47
142,907,622
0
0
null
null
null
null
UTF-8
Java
false
false
1,505
java
package extra; import java.applet.AudioClip; import java.awt.Button; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JApplet; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class SoundEffectsMachine implements ActionListener { JButton button = new JButton(); JButton button2 = new JButton(); JButton button3 = new JButton(); public static void main(String[] args) { SoundEffectsMachine sound = new SoundEffectsMachine(); sound.showButton(); } public void showButton() { JFrame frame = new JFrame(); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel(); frame.add(panel); panel.add(button); button.addActionListener(this); button.setText("service bell"); panel.add(button2); button2.addActionListener(this); button2.setText("SOS"); panel.add(button3); button3.addActionListener(this); button3.setText("Power up!"); frame.pack(); } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub JButton b = (JButton) e.getSource(); if (b == button) { playSound("service-bell_daniel_simion (1).wav"); } else if (b == button2) { playSound("sos-morse-code_daniel-simion.wav"); } else { playSound("Power-Up-KP-1879176533.wav"); } } private void playSound(String fileName) { AudioClip sound = JApplet.newAudioClip(getClass().getResource(fileName)); sound.play(); } }
411665d62f59deb4476a1e57101328b136096167
db19cc58058e4b54734b51df79c5c5b223d2a5f2
/src/test/java/com/kkMud/ShortcutTest.java
1895437907ba83830628ba78e74197e2c50e8926
[]
no_license
zachung/kkMud
999426334fad09f9081bc6b867b557c5cdddddb7
661d07ab7c161b68be72a9da30e3dfd954ac3d1a
refs/heads/master
2020-12-24T19:36:33.121111
2016-04-17T15:35:58
2016-04-17T15:35:58
56,420,924
1
0
null
null
null
null
UTF-8
Java
false
false
1,677
java
package test.java.com.kkMud; import java.awt.event.KeyEvent; import java.io.UnsupportedEncodingException; import java.util.Date; import java.util.Timer; import java.util.TimerTask; import org.junit.Ignore; import org.junit.Test; import main.java.com.kkMud.shortcut.ShortcutKey; public class ShortcutTest { private static final ShortcutKey setting = new ShortcutKey(); @Test public void colorReader() throws UnsupportedEncodingException { // zach 122 97 99 104 parse("紅"); parse("zach"); } private void parse(String msg) { byte[] bytes; try { // big5 bytes = msg.getBytes("big5"); int[] ints = new int[bytes.length]; for (int i = 0, l = bytes.length; i < l; i++) { ints[i] = bytes[i] & 0xff; System.out.println(ints[i]); } // normal bytes = msg.getBytes(); for (byte b : bytes) { System.out.println(b); } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Ignore @Test public void saveAndLoad() { String command = setting.getCommand(2, KeyEvent.VK_L); String[] commands = command.split("\\;"); for (String c : commands) { System.out.println("1"); System.out.println(c); } } @Ignore @Test public void timer() { Timer t = new Timer(); t.schedule(new TimerTask() { @Override public void run() { System.out.println(new Date()); } }, 0, 1000); try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
024ab2dbaa5539eabaa561ec45256ca78185c1ad
e682b787d0ffbe6ba470da3c6f09070b8b8da2c6
/src/main/java/com/blibli/dependencyinjection/Service/CustomerService.java
5e2ac7fb7d70ee558b1b9749bf07a641fa45709d
[]
no_license
damaimrs/dependency-injection
5cdbc8ba9fe90e3326fab63d002e436bce4110af
7e96cd03983832be7509a0f327f43a81a74ee2a4
refs/heads/master
2021-09-03T20:13:55.874270
2018-01-11T17:25:15
2018-01-11T17:25:15
117,129,894
0
0
null
null
null
null
UTF-8
Java
false
false
436
java
package com.blibli.dependencyinjection.Service; import com.blibli.dependencyinjection.Model.Customer; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; public interface CustomerService { Customer register(String name); List<Customer> getAll(); Customer findById(String idCustomer); Customer update(String idAddress, String name); void delete(String idCustomer); }
f8f8a8e091d9d709584b519dec414b95e0c52696
cca87c4ade972a682c9bf0663ffdf21232c9b857
/com/tencent/mm/plugin/setting/ui/setting/PersonalPreference.java
47e37d29f99503bed66558fd96e95113d169fbf4
[]
no_license
ZoranLi/wechat_reversing
b246d43f7c2d7beb00a339e2f825fcb127e0d1a1
36b10ef49d2c75d69e3c8fdd5b1ea3baa2bba49a
refs/heads/master
2021-07-05T01:17:20.533427
2017-09-25T09:07:33
2017-09-25T09:07:33
104,726,592
12
1
null
null
null
null
UTF-8
Java
false
false
2,462
java
package com.tencent.mm.plugin.setting.ui.setting; import android.content.Context; import android.graphics.Bitmap; import android.util.AttributeSet; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.tencent.mm.R; import com.tencent.mm.pluginsdk.ui.a.b; import com.tencent.mm.pluginsdk.ui.d.h; import com.tencent.mm.sdk.platformtools.bg; import com.tencent.mm.storage.x; import com.tencent.mm.ui.base.preference.Preference; public class PersonalPreference extends Preference { private String fSe; private String gtR; Bitmap hqW = null; private TextView jZz = null; ImageView lMX = null; private TextView piH = null; int piI = -1; String piJ = null; private OnClickListener piK; private String username; public PersonalPreference(Context context, AttributeSet attributeSet) { super(context, attributeSet); } public PersonalPreference(Context context, AttributeSet attributeSet, int i) { super(context, attributeSet, i); setLayoutResource(R.i.diC); setWidgetLayoutResource(R.i.djm); } public final View onCreateView(ViewGroup viewGroup) { View onCreateView = super.onCreateView(viewGroup); ViewGroup viewGroup2 = (ViewGroup) onCreateView.findViewById(R.h.content); viewGroup2.removeAllViews(); View.inflate(this.mContext, R.i.diQ, viewGroup2); return onCreateView; } public final void onBindView(View view) { if (this.lMX == null) { this.lMX = (ImageView) view.findViewById(R.h.bWV); } if (this.hqW != null) { this.lMX.setImageBitmap(this.hqW); } else if (this.piI > 0) { this.lMX.setImageResource(this.piI); } else if (this.piJ != null) { b.a(this.lMX, this.piJ); } this.lMX.setOnClickListener(this.piK); if (!(this.jZz == null || this.fSe == null)) { this.jZz.setText(h.b(this.mContext, this.fSe, this.jZz.getTextSize())); } if (this.piH != null) { String str = bg.mA(this.gtR) ? this.username : this.gtR; if (bg.mA(this.gtR) && x.QQ(this.username)) { this.piH.setVisibility(8); } this.piH.setText(this.mContext.getString(R.l.dHi) + str); } super.onBindView(view); } }
fe66ebbea2ceb58e505ec3f4e2bdb76ea5e5a21a
f4ad4e96b4098e9f7dd203872ba428159bff51ee
/src/main/java/br/com/cybereagle/eagledatetime/internal/gregorian/DateImpl.java
02b646d91c9194951b36dadb692093a250137508
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
CyberEagle/EagleDateTimeAPI
92d293c73e671a33bcb215353a4ef25d8178d8b5
79c764dd4ba466f5b86324b85086eb76bab23c81
refs/heads/master
2021-01-16T21:16:28.588332
2014-02-15T12:15:41
2014-02-15T12:15:41
null
0
0
null
null
null
null
UTF-8
Java
false
false
10,161
java
/* * Copyright 2013 Cyber Eagle * * 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 br.com.cybereagle.eagledatetime.internal.gregorian; import br.com.cybereagle.eagledatetime.Date; import br.com.cybereagle.eagledatetime.DayOverflow; import br.com.cybereagle.eagledatetime.exception.ItemOutOfRange; import br.com.cybereagle.eagledatetime.factory.GregorianDateTime; import br.com.cybereagle.eagledatetime.internal.format.DateTimeFormatterAdapter; import br.com.cybereagle.eagledatetime.internal.format.DateTimeFormatter; import br.com.cybereagle.eagledatetime.internal.util.DateTimeUtil; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.*; import static br.com.cybereagle.eagledatetime.internal.util.DateTimeUtil.*; public class DateImpl implements Date { private static final int EQUAL = 0; private Integer year; private Integer month; private Integer day; public DateImpl(Integer year, Integer month, Integer day) { this.year = year; this.month = month; this.day = day; validateState(); } private void validateState(){ checkRange(year, 1, 9999, "Year"); checkRange(month, 1, 12, "Month"); checkRange(day, 1, 31, "Day"); checkNumDaysInMonth(year, month, day); } private void checkNumDaysInMonth(Integer year, Integer month, Integer day) { Integer numberOfDaysInMonth = DateTimeUtil.getNumberOfDaysInMonth(year, month); if (day > numberOfDaysInMonth) { throw new ItemOutOfRange("The day-of-the-month value '" + day + "' exceeds the number of days in the month: " + numberOfDaysInMonth); } } @Override public Integer getDay() { return day; } @Override public Integer getDayOfYear() { int k = isLeapYear() ? 1 : 2; Integer result = ((275 * month) / 9) - k * ((month + 9) / 12) + day - 30; // integer division return result; } @Override public Integer getMonth() { return month; } @Override public Integer getWeekDay() { int dayNumber = calculateJulianDayNumberAtNoon() + 1; int index = dayNumber % 7; return index + 1; } @Override public Integer getYear() { return year; } @Override public Integer getWeekIndex() { Date start = GregorianDateTime.newDate(2000, 1, 2); return getWeekIndex(start); } @Override public Integer getWeekIndex(Date startingFromDate) { int diff = getModifiedJulianDayNumber() - startingFromDate.getModifiedJulianDayNumber(); return (diff / 7) + 1; // integer division } @Override public Integer getNumberOfDaysInMonth() { return DateTimeUtil.getNumberOfDaysInMonth(year, month); } @Override public Date getStartOfMonth() { return GregorianDateTime.newDate(year, month, 1); } @Override public Date getEndOfMonth() { return GregorianDateTime.newDate(year, month, getNumberOfDaysInMonth()); } @Override public Integer getModifiedJulianDayNumber() { return calculateJulianDayNumberAtNoon() - 1 - EPOCH_MODIFIED_JD; } /** * Return a the whole number, with no fraction. * The JD at noon is 1 more than the JD at midnight. */ private int calculateJulianDayNumberAtNoon() { //http://www.hermetic.ch/cal_stud/jdn.htm return (1461 * (year + 4800 + (month - 14) / 12)) / 4 + (367 * (month - 2 - 12 * ((month - 14) / 12))) / 12 - (3 * ((year + 4900 + (month - 14) / 12) / 100)) / 4 + day - 32075; } @Override public boolean isInTheFuture(TimeZone timeZone) { return GregorianDateTime.today(timeZone).compareTo(this) < 0; } @Override public boolean isInThePast(TimeZone timeZone) { return GregorianDateTime.today(timeZone).compareTo(this) > 0; } @Override public boolean isLeapYear() { return DateTimeUtil.isLeapYear(year); } @Override public boolean isSameDayAs(Date that) { return equals(that); } @Override public boolean isToday() { return false; } @Override public Date minusDays(Integer numberOfDays) { return plusDays(-1 * numberOfDays); } @Override public Date plusDays(Integer numberOfDays) { int thisJDAtNoon = getModifiedJulianDayNumber() + 1 + EPOCH_MODIFIED_JD; int resultJD = thisJDAtNoon + numberOfDays; Date datePortion = GregorianDateTime.fromJulianDayNumberAtNoon(resultJD); return GregorianDateTime.newDate(datePortion.getYear(), datePortion.getMonth(), datePortion.getDay()); } @Override public Integer numberOfDaysFrom(Date that) { return that.getModifiedJulianDayNumber() - this.getModifiedJulianDayNumber(); } @Override public Date plus(Integer year, Integer month, Integer day, DayOverflow dayOverflow) { DateTimeInterval interval = new DateTimeInterval(this, dayOverflow); interval.plus(year, month, day); return GregorianDateTime.newDate(interval.getResultYear(), interval.getResultMonth(), interval.getResultDay()); } @Override public Date minus(Integer year, Integer month, Integer day, DayOverflow dayOverflow) { DateTimeInterval interval = new DateTimeInterval(this, dayOverflow); interval.minus(year, month, day); return GregorianDateTime.newDate(interval.getResultYear(), interval.getResultMonth(), interval.getResultDay()); } @Override public String format(String format, List<String> months, List<String> weekdays) { DateTimeFormatter dateTimeFormatter = new DateTimeFormatter(format, months, weekdays, null); return dateTimeFormatter.format(new DateTimeFormatterAdapter(this)); } @Override public String format(String format) { DateTimeFormatter dateTimeFormatter = new DateTimeFormatter(format); return dateTimeFormatter.format(new DateTimeFormatterAdapter(this)); } @Override public String format(String format, Locale locale) { DateTimeFormatter dateTimeFormatter = new DateTimeFormatter(format, locale); return dateTimeFormatter.format(new DateTimeFormatterAdapter(this)); } @Override public long getMillisecondsInstant(TimeZone timeZone) { Calendar calendar = new GregorianCalendar(timeZone); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, month - 1); // 0-based calendar.set(Calendar.DAY_OF_MONTH, day); calendar.set(Calendar.HOUR_OF_DAY, 0); // 0..23 calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); return calendar.getTimeInMillis(); } @Override public long getNanosecondsInstant(TimeZone timeZone) { // these are always positive: Integer year = getYear(); Integer month = getMonth(); Integer day = getDay(); //base calculation in millis Calendar calendar = new GregorianCalendar(timeZone); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, month - 1); // 0-based calendar.set(Calendar.DAY_OF_MONTH, day); calendar.set(Calendar.HOUR_OF_DAY, 0); // 0..23 calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); return calendar.getTimeInMillis() * MILLION; } @Override public int compareTo(Date that) { if (this == that) return EQUAL; int comparison = year.compareTo(that.getYear()); if(comparison != EQUAL) return comparison; comparison = month.compareTo(that.getMonth()); if(comparison != EQUAL) return comparison; comparison = day.compareTo(that.getDay()); if(comparison != EQUAL) return comparison; return EQUAL; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Date)) return false; Date date = (Date) o; if (!day.equals(date.getDay())) return false; if (!month.equals(date.getMonth())) return false; if (!year.equals(date.getYear())) return false; return true; } @Override public int hashCode() { int result = year.hashCode(); result = 31 * result + month.hashCode(); result = 31 * result + day.hashCode(); return result; } @Override public String toString() { final StringBuilder sb = new StringBuilder("DateImpl{"); sb.append("year=").append(year); sb.append(", month=").append(month); sb.append(", day=").append(day); sb.append('}'); return sb.toString(); } /** * Always treat de-serialization as a full-blown constructor, by * validating the final state of the de-serialized object. */ private void readObject(ObjectInputStream aInputStream) throws ClassNotFoundException, IOException { //always perform the default de-serialization first aInputStream.defaultReadObject(); //no mutable fields in this case validateState(); } /** * This is the default implementation of writeObject. * Customise if necessary. */ private void writeObject(ObjectOutputStream aOutputStream) throws IOException { //perform the default serialization for all non-transient, non-static fields aOutputStream.defaultWriteObject(); } }
a45089e785220cb097996d8c8ae93c392aab1bf7
cab9809aee016d33f3c31251fc30a0d8b8e333a5
/src/main/java/main/tests/Test_Delete.java
d00dbe03390009cb71c76dc3377e18a4d2f4236f
[]
no_license
ItsRicmor/Template_Hibernate
322590b212809b9c245dcd5ea09b2937104c46d4
d052f50e9572184b27770d4203dcacd50e2b03c9
refs/heads/master
2020-04-25T06:48:35.654681
2019-02-28T18:25:48
2019-02-28T18:25:48
172,593,185
0
0
null
null
null
null
UTF-8
Java
false
false
734
java
package main.tests; import main.models.Person; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class Test_Delete { public static void main(String[] args) { SessionFactory sessionFactory = new Configuration() .configure("hibernate.cfg.xml") .addAnnotatedClass(Person.class) .buildSessionFactory(); try (Session session = sessionFactory.openSession()) { session.beginTransaction(); Person person = session.byId(Person.class).load("901110534"); session.delete(person); session.getTransaction().commit(); session.close(); } } }
7dc7eed9d17d4fc6ea37ff7832bddc462d20a34a
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/10/10_69da4442b7ef69dabc5ec4e0c74a0d1ef56995b2/HtmlThesisPrinter/10_69da4442b7ef69dabc5ec4e0c74a0d1ef56995b2_HtmlThesisPrinter_t.java
f66089ee649029490035a001dcd601f0512a0ee5
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
15,573
java
package com.arguments.functional.report.html; import static org.junit.Assert.*; import java.util.Collection; import java.util.List; import com.arguments.functional.datamodel.MPerspective; import com.arguments.functional.datamodel.OpinionatedThesis; import com.arguments.functional.datamodel.OwnedPerspective; import com.arguments.functional.datamodel.Perspective; import com.arguments.functional.datamodel.PerspectiveThesisOpinion; import com.arguments.functional.datamodel.RelatedThesis; import com.arguments.functional.datamodel.Thesis; import com.arguments.functional.datamodel.ThesisId; import com.arguments.functional.datamodel.ThesisOpinion; import com.arguments.functional.report.ListThesesData; import com.arguments.functional.report.ThesisFocusData; import com.arguments.functional.requeststate.ArgsRequestKey; import com.arguments.functional.requeststate.ProtocolMap; import com.arguments.functional.store.TheArgsStore; import com.arguments.support.Container; import com.arguments.support.IndentHtmlPrinter; import com.arguments.support.Renderer; public class HtmlThesisPrinter { private final UrlContainer theUrlContainer; private final ProtocolMap theProtocol; private MPerspective thePerspectives; private StringBuffer theText; // ------------------------------------------------------------------------ public HtmlThesisPrinter(UrlContainer aUrlContainer, ProtocolMap aProtocol) { assertNotNull(aUrlContainer); theUrlContainer = aUrlContainer; theProtocol = aProtocol; } // ------------------------------------------------------------------------ public String thesisListToInternalHtml(ListThesesData aData) { theText = new StringBuffer(); setPerspectives(aData.getPerspective()); printPerspectives(); theText.append("<h1> All theses </h1>\n"); theText.append("<table>\n"); theText.append("<tr>\n"); theText.append(" <th class=\"otherClass\"> Operations </th>\n"); for (int i = 0; i < thePerspectives.size(); i++) theText.append("<th class=\"otherClass\"> P"+(i+1)+"</th>"); theText.append(" <th class=\"otherClass\"> Thesis </th>\n"); theText.append(" <th class=\"otherClass\"> Owner </th>\n"); theText.append("</tr>\n"); for (OpinionatedThesis myThesis : aData.getTheses()) { theText.append(toTableRow(myThesis)); } theText.append("</table>\n"); return theText.toString(); } // ------------------------------------------------------------------------ public String focusPageToHtmlPage(ThesisFocusData aThesisFocusData) { StringBuffer myText1 = new StringBuffer(); myText1.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n" + "<html><head><title>Argument Viewer</title></head>"); myText1.append("<body>"); myText1.append(focusPageToInternalHtml(aThesisFocusData)); myText1.append("</body>"); return myText1.toString(); } // ------------------------------------------------------------------------ public String focusPageToInternalHtml(ThesisFocusData aThesisFocusData) { theText = new StringBuffer(); OpinionatedThesis myMainThesis = aThesisFocusData.getMainThesis(); setPerspectives(aThesisFocusData.getPerspectives()); assertEquals (myMainThesis.getPerspectives().size(), thePerspectives.size()); printPerspectives(); theText.append("<h1>Focus thesis: </h1>\n"); theText.append("<table id=\"mainfocustable\"><tr>"); theText.append(mainThesisToHtml(myMainThesis)); theText.append("</tr></table>"); if (aThesisFocusData.getMainThesisOwned()) { theText.append("<a href=\"" + theUrlContainer.getEditThesisUrl() + "\">edit</a>"); } else { theText.append("Owner: " + aThesisFocusData.getMainThesis().getOwner().getScreenName()); } if (aThesisFocusData.getFirstPerspectiveOwned()) { theText.append(", <a href=\"" + theUrlContainer.getAddPremiseUrl() + "\">add premise</a>"); theText.append(", <a href=\"" + theUrlContainer.getAddOpinionUrl() + "\">set your opinion</a>"); } theText.append("\n"); theText.append("<h1>Reasons for this to be true or not: </h1>\n"); theText.append(getRelatedThesesTable(aThesisFocusData.getPremisesSortedByStrength(), "Premise", "Relevance of premise for focus")); theText.append("<h1>Possible consequences: </h1>\n"); theText.append(getRelatedThesesTable(aThesisFocusData.getDeductions(), "Consequence", "Relevance of focus for consequence")); theText.append("<h1>Tree view: </h1>\n"); theText.append(getThesisTreeString(aThesisFocusData.getMainThesis())); theText.append("<h1>Different perspectives: </h1>\n"); theText.append(getPerspectivesTable(aThesisFocusData.getDifferentPerspectives())); return theText.toString(); } // ------------------------------------------------------------------------ private void setPerspectives(MPerspective aPerspectives) { thePerspectives = aPerspectives; } // ------------------------------------------------------------------------ private void printPerspectives() { theText.append("<ul>"); for (int i = 0; i < thePerspectives.size(); i++) { theText.append( "<li>" + "Perspective "+(i+1)+": " + thePerspectives.get(i)); if (thePerspectives.size() > 1) theText.append(toRemovePerspectiveAnchor(thePerspectives.get(i))); theText.append("</li>"); } theText.append("</ul>"); } // ------------------------------------------------------------------------ String getThesisTreeString(Thesis aThesis) { Container<Thesis> myThesisTree = TheArgsStore.i().selectPremiseTree(aThesis, 2); Renderer<Thesis> myRenderer = new Renderer<Thesis>() { @Override public String render(Thesis aThesis1) { return toFocusAnchor(aThesis1); }}; IndentHtmlPrinter<Thesis> myPrinter = new IndentHtmlPrinter<>(myRenderer); myPrinter.traverse(myThesisTree); return myPrinter.getOutput(); } // ------------------------------------------------------------------------ private String getPerspectivesTable(Collection<PerspectiveThesisOpinion> anOpinions) { StringBuffer myText = new StringBuffer(); myText.append("<table>\n"); myText.append("<tr>\n"); myText.append(" <th class=\"otherClass\">Perspective </th>\n"); myText.append(" <th class=\"otherClass\">Opinion</th>\n"); myText.append("</tr>\n"); for (PerspectiveThesisOpinion myOpinion : anOpinions) { myText.append(toTableRow(myOpinion)); } myText.append("</table>\n"); return myText.toString(); } // ------------------------------------------------------------------------ private String getRelatedThesesTable( List<RelatedThesis<OpinionatedThesis>> aTheses, String aThesisHeader, String aRelevanceHeader) { StringBuffer myText = new StringBuffer(); myText.append("<table>\n"); myText.append("<tr>\n"); myText.append(" <th class=\"otherClass\">Operations </th>\n"); for (int i=0; i<thePerspectives.size(); i++) myText.append("<th class=\"otherClass\"> P" + (i+1) + "</th>\n"); myText.append(" <th class=\"otherClass\">"+aThesisHeader+"</th>\n"); myText.append(" <th class=\"otherClass\">"+aRelevanceHeader+"</th>\n"); myText.append(" <th class=\"otherClass\"> Owner</th>\n"); myText.append("</tr>\n"); for (RelatedThesis<OpinionatedThesis> myPremise : aTheses) { assertEquals(myPremise.getThesis().getOpinions().size(), thePerspectives.size()); myText.append(toTableRow(myPremise, theUrlContainer)); } myText.append("</table>\n"); return myText.toString(); } // ------------------------------------------------------------------------ private String toSetPerspectiveAnchor(OwnedPerspective aPerspective) { return "<a href=\"focus?"+ theProtocol.get(ArgsRequestKey.SET_PERSPECTIVE_ID)+"=" + aPerspective.getIdString() + "\"> "+aPerspective+"</a>"; } // ------------------------------------------------------------------------ private String toAddPerspectiveAnchor(OwnedPerspective aPerspective) { return "<a href=\"focus?"+ theProtocol.get(ArgsRequestKey.ADD_PERSPECTIVE_ID)+"=" + aPerspective.getIdString() + "\"> "+aPerspective+"</a>"; } // ------------------------------------------------------------------------ private String toRemovePerspectiveAnchor(Perspective aPerspective) { return "<a href=\"focus?"+ theProtocol.get(ArgsRequestKey.REMOVE_PERSPECTIVE_ID)+"=" + aPerspective.getIdString() + "\"> remove from view</a>"; } // ------------------------------------------------------------------------ private String toFocusAnchor(ThesisId aThesisID) { return "<a href=\"focus?"+ theProtocol.get(ArgsRequestKey.THESIS_ID)+"=" + aThesisID + "\"> focus</a>"; } // ------------------------------------------------------------------------ private String toFocusAnchor(Thesis aThesis) { return "<a href=\"focus?"+ theProtocol.get(ArgsRequestKey.THESIS_ID)+"=" + aThesis.getID() + "\">"+aThesis.getSummary()+"</a>"; } // ------------------------------------------------------------------------ private String toRelinkAnchor(String aRelinkURL, RelatedThesis<OpinionatedThesis> aPremise) { return "<a href=\"" + aRelinkURL + "&" + theProtocol.get(ArgsRequestKey.RELATION_ID) +"=" + aPremise.getRelation().getID() + "\"> relink</a>"; } // ------------------------------------------------------------------------ private static String cssClassByOpinion(OpinionatedThesis aThesis) { assertNotNull(aThesis); return cssClassByOpinion(aThesis.getOpinion()); } // ------------------------------------------------------------------------ private static String cssClassByOpinion(ThesisOpinion aOpinion) { if (aOpinion.believe()) return "believeStyle"; if (aOpinion.neutral()) return "dontKnowStyle"; return "dontBelieveStyle"; } // ------------------------------------------------------------------------ private static StringBuffer mainThesisToHtml(OpinionatedThesis aThesis) { assertNotNull(aThesis); StringBuffer myText = new StringBuffer(); for (ThesisOpinion myOpinion : aThesis.getOpinions()) myText.append("<td><div id=\"mainfocuspers\" class=\"" + cssClassByOpinion(myOpinion) + "\">" + myOpinion.getPercentage()+"%" + "</div></td>\n"); myText.append("<td><div id=\"mainfocus\" >" + getIDWithSummary(aThesis) + "</div></td>\n"); return myText; } // ------------------------------------------------------------------------ private static String getIDWithSummary(OpinionatedThesis aThesis) { return aThesis.getID() + " -- " + aThesis.getSummary(); } // ------------------------------------------------------------------------ private StringBuffer toTableRow(RelatedThesis<OpinionatedThesis> aPremise, UrlContainer aRelinkURL) { assertNotNull(aRelinkURL); StringBuffer myText = new StringBuffer("<tr>\n"); myText.append(" <td class=\"otherClass\"> " + toFocusAnchor(aPremise.getID()) + ", " + toRelinkAnchor(aRelinkURL.getEditLinkUrl(), aPremise) + "</td>\n" ); for (ThesisOpinion myOpinion:aPremise.getThesis().getOpinions()) myText.append("<td id=\"relatedpers\" class=\"" + cssClassByOpinion(myOpinion) + "\">" + myOpinion.getPercentage()+"%" + "</td>"); myText.append(" <td>" + getIDWithSummary(aPremise.getThesis())+"</td>\n"); myText.append(" <td class=\"otherClass\">" + relevanceText(aPremise) + "</td>\n"); myText.append(" <td>" + aPremise.getOwner().getScreenName() + "</td>\n"); myText.append("</tr>\n"); return myText; } // ------------------------------------------------------------------------ private StringBuffer toTableRow(OpinionatedThesis aThesis) { StringBuffer myText = new StringBuffer("<tr>\n"); myText.append(" <td class=\"otherClass\"> " + toFocusAnchor(aThesis.getID()) + "</td>\n"); for (int i = 0; i< thePerspectives.size(); i++) { ThesisOpinion myOpinion = aThesis.getOpinions().get(i); myText.append("<td id=\"relatedpers\" class=\"" + cssClassByOpinion(myOpinion) + "\">" + myOpinion.getPercentage()+"%" + "</td>"); } myText.append(" <td>" + getIDWithSummary(aThesis) + "</td>\n"); myText.append(" <td>" + aThesis.getOwner().getScreenName() + "</td>\n"); myText.append("</tr>\n"); return myText; } // ------------------------------------------------------------------------ private StringBuffer toTableRow( PerspectiveThesisOpinion anOpinion) { StringBuffer myText = new StringBuffer("<tr>\n"); myText.append(" <td class=\"otherClass\"> " + toAddPerspectiveAnchor(anOpinion.getPerspective()) + "</td>\n"); myText.append(" <td class=\"" + cssClassByOpinion(anOpinion) + "\">" + anOpinion.toString() + "</td>\n"); myText.append("</tr>\n"); return myText; } // ------------------------------------------------------------------------ private static StringBuffer relevanceText(RelatedThesis<OpinionatedThesis> aPremise) { StringBuffer myText = new StringBuffer(); myText.append("IfTrue:"); myText.append(aPremise.getIfTrueRelevance()); myText.append(", IfFalse:"); myText.append(aPremise.getIfFalseRelevance()); myText.append(", Implied:" + RelatedThesis.getImpliedBelief( aPremise.getThesis().getOpinion(), aPremise.getRelation())); return myText; } }
23129c0bf3ef7e4424e06e39d08c6031f8371c8d
bfdfba0b0db8c756698342057b9d3ab23e8eada0
/HTN-B1/app/src/main/java/com/x10host/dhanushpatel/htn_b1/FBase.java
6cb43cdc4d416f5905bacac8ee82983b1c5b4757
[]
no_license
Ray-Ken/A.L.I.C.E.
c55ccd39a2d293eb938e533811245198fdb73bd2
95305de6efa1435603634113074fc9c83c313379
refs/heads/master
2020-03-17T18:08:06.843894
2016-09-18T18:05:11
2016-09-18T18:05:11
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,564
java
package com.x10host.dhanushpatel.htn_b1; import com.google.firebase.database.Exclude; import java.util.HashMap; import java.util.Map; /** * Created by chapatel on 9/17/16. */ public class FBase { public double accelX, accelY, accelZ, gpsLat, gpsLong, lightSensor, sonicSensor, soundSensor, tempSensor, whichButtonInt; public FBase() { // Default constructor required for calls to DataSnapshot.getValue(Post.class) } public FBase( double accelX, double accelY, double accelZ, double gpsLat, double gpsLong, double lightSensor, double sonicSensor, double soundSensor, double tempSensor, double whichButtonInt) { this.accelX = accelX; this.accelY = accelY; this.accelZ = accelZ; this.gpsLat = gpsLat; this.gpsLong = gpsLong; this.lightSensor = lightSensor; this.sonicSensor = sonicSensor; this.soundSensor = soundSensor; this.tempSensor = tempSensor; this.whichButtonInt = whichButtonInt; } // [START post_to_map] @Exclude public Map<String, Object> toMap() { HashMap<String, Object> result = new HashMap<>(); result.put("accelX",accelX); result.put("accelY", accelY); result.put("accelZ", accelZ); result.put("gpsLat",gpsLat); result.put("lightSensor",lightSensor); result.put("sonicSensor",sonicSensor); result.put("soundSensor",soundSensor); result.put("tempSensor",tempSensor); result.put("whichButtonInt",whichButtonInt); return result; } }
99c69f7b634967939162eb6d53ff02d9ecc5ce22
b06acf556b750ac1fa5b28523db7188c05ead122
/IfcModel/src/ifc2x3tc1/impl/IfcIsothermalMoistureCapacityMeasureImpl.java
19ce290fbeba6d0d1935b96240d524ecf38afa93
[]
no_license
christianharrington/MDD
3500afbe5e1b1d1a6f680254095bb8d5f63678ba
64beecdaed65ac22b0047276c616c269913afd7f
refs/heads/master
2021-01-10T21:42:53.686724
2012-12-17T03:27:05
2012-12-17T03:27:05
6,157,471
1
0
null
null
null
null
UTF-8
Java
false
false
8,120
java
/** */ package ifc2x3tc1.impl; import ifc2x3tc1.Ifc2x3tc1Package; import ifc2x3tc1.IfcIsothermalMoistureCapacityMeasure; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.impl.ENotificationImpl; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Ifc Isothermal Moisture Capacity Measure</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link ifc2x3tc1.impl.IfcIsothermalMoistureCapacityMeasureImpl#getWrappedValue <em>Wrapped Value</em>}</li> * <li>{@link ifc2x3tc1.impl.IfcIsothermalMoistureCapacityMeasureImpl#getWrappedValueAsString <em>Wrapped Value As String</em>}</li> * </ul> * </p> * * @generated */ public class IfcIsothermalMoistureCapacityMeasureImpl extends WrappedValueImpl implements IfcIsothermalMoistureCapacityMeasure { /** * The default value of the '{@link #getWrappedValue() <em>Wrapped Value</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getWrappedValue() * @generated * @ordered */ protected static final double WRAPPED_VALUE_EDEFAULT = 0.0; /** * The cached value of the '{@link #getWrappedValue() <em>Wrapped Value</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getWrappedValue() * @generated * @ordered */ protected double wrappedValue = WRAPPED_VALUE_EDEFAULT; /** * This is true if the Wrapped Value attribute has been set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ protected boolean wrappedValueESet; /** * The default value of the '{@link #getWrappedValueAsString() <em>Wrapped Value As String</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getWrappedValueAsString() * @generated * @ordered */ protected static final String WRAPPED_VALUE_AS_STRING_EDEFAULT = null; /** * The cached value of the '{@link #getWrappedValueAsString() <em>Wrapped Value As String</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getWrappedValueAsString() * @generated * @ordered */ protected String wrappedValueAsString = WRAPPED_VALUE_AS_STRING_EDEFAULT; /** * This is true if the Wrapped Value As String attribute has been set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ protected boolean wrappedValueAsStringESet; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected IfcIsothermalMoistureCapacityMeasureImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return Ifc2x3tc1Package.eINSTANCE.getIfcIsothermalMoistureCapacityMeasure(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public double getWrappedValue() { return wrappedValue; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setWrappedValue(double newWrappedValue) { double oldWrappedValue = wrappedValue; wrappedValue = newWrappedValue; boolean oldWrappedValueESet = wrappedValueESet; wrappedValueESet = true; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Ifc2x3tc1Package.IFC_ISOTHERMAL_MOISTURE_CAPACITY_MEASURE__WRAPPED_VALUE, oldWrappedValue, wrappedValue, !oldWrappedValueESet)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void unsetWrappedValue() { double oldWrappedValue = wrappedValue; boolean oldWrappedValueESet = wrappedValueESet; wrappedValue = WRAPPED_VALUE_EDEFAULT; wrappedValueESet = false; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.UNSET, Ifc2x3tc1Package.IFC_ISOTHERMAL_MOISTURE_CAPACITY_MEASURE__WRAPPED_VALUE, oldWrappedValue, WRAPPED_VALUE_EDEFAULT, oldWrappedValueESet)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public boolean isSetWrappedValue() { return wrappedValueESet; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getWrappedValueAsString() { return wrappedValueAsString; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setWrappedValueAsString(String newWrappedValueAsString) { String oldWrappedValueAsString = wrappedValueAsString; wrappedValueAsString = newWrappedValueAsString; boolean oldWrappedValueAsStringESet = wrappedValueAsStringESet; wrappedValueAsStringESet = true; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Ifc2x3tc1Package.IFC_ISOTHERMAL_MOISTURE_CAPACITY_MEASURE__WRAPPED_VALUE_AS_STRING, oldWrappedValueAsString, wrappedValueAsString, !oldWrappedValueAsStringESet)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void unsetWrappedValueAsString() { String oldWrappedValueAsString = wrappedValueAsString; boolean oldWrappedValueAsStringESet = wrappedValueAsStringESet; wrappedValueAsString = WRAPPED_VALUE_AS_STRING_EDEFAULT; wrappedValueAsStringESet = false; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.UNSET, Ifc2x3tc1Package.IFC_ISOTHERMAL_MOISTURE_CAPACITY_MEASURE__WRAPPED_VALUE_AS_STRING, oldWrappedValueAsString, WRAPPED_VALUE_AS_STRING_EDEFAULT, oldWrappedValueAsStringESet)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public boolean isSetWrappedValueAsString() { return wrappedValueAsStringESet; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case Ifc2x3tc1Package.IFC_ISOTHERMAL_MOISTURE_CAPACITY_MEASURE__WRAPPED_VALUE: return getWrappedValue(); case Ifc2x3tc1Package.IFC_ISOTHERMAL_MOISTURE_CAPACITY_MEASURE__WRAPPED_VALUE_AS_STRING: return getWrappedValueAsString(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case Ifc2x3tc1Package.IFC_ISOTHERMAL_MOISTURE_CAPACITY_MEASURE__WRAPPED_VALUE: setWrappedValue((Double)newValue); return; case Ifc2x3tc1Package.IFC_ISOTHERMAL_MOISTURE_CAPACITY_MEASURE__WRAPPED_VALUE_AS_STRING: setWrappedValueAsString((String)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case Ifc2x3tc1Package.IFC_ISOTHERMAL_MOISTURE_CAPACITY_MEASURE__WRAPPED_VALUE: unsetWrappedValue(); return; case Ifc2x3tc1Package.IFC_ISOTHERMAL_MOISTURE_CAPACITY_MEASURE__WRAPPED_VALUE_AS_STRING: unsetWrappedValueAsString(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case Ifc2x3tc1Package.IFC_ISOTHERMAL_MOISTURE_CAPACITY_MEASURE__WRAPPED_VALUE: return isSetWrappedValue(); case Ifc2x3tc1Package.IFC_ISOTHERMAL_MOISTURE_CAPACITY_MEASURE__WRAPPED_VALUE_AS_STRING: return isSetWrappedValueAsString(); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (wrappedValue: "); if (wrappedValueESet) result.append(wrappedValue); else result.append("<unset>"); result.append(", wrappedValueAsString: "); if (wrappedValueAsStringESet) result.append(wrappedValueAsString); else result.append("<unset>"); result.append(')'); return result.toString(); } } //IfcIsothermalMoistureCapacityMeasureImpl
074b0b979e3568957ea83ac95bc85b2f1712b44f
53817bad81cd57d551c0fb21c739ca80bc38e502
/USC_Projects/Artificial_Intelligence/hw2/HariHaran_Venugopal/HariHaran_Venugopal/State.java
09641013ef364eb37dc204888a483eb4d6bd1a2d
[]
no_license
hari316/Projects
6235aafe438a17b8f63a5b23dc62a0077a5e3fae
500e7d07c34c6089b9a527835cc118e3142807c6
refs/heads/master
2020-12-24T16:07:02.781415
2016-03-07T02:29:50
2016-03-07T02:29:50
22,237,603
0
0
null
null
null
null
UTF-8
Java
false
false
766
java
import java.util.LinkedHashSet; import java.util.Set; public class State{ private String current_checkpoint; public Set<String> visted_checkpoints = new LinkedHashSet<String>(); //public List<String> visted_checkpoints = new ArrayList<String>(); private double g; private double h; private double f; public String getCurrent_checkpoint() { return current_checkpoint; } public void setCurrent_checkpoint(String current_checkpoint) { this.current_checkpoint = current_checkpoint; } public double getG() { return g; } public void setG(double g) { this.g = g; } public double getH() { return h; } public void setH(double h) { this.h = h; } public double getF() { return f; } public void setF(double f) { this.f = f; } }
47c9a6f99e30bdddbfce6c5f11fa6a88134ee452
70f6fd40586fc5ae4b16e9096766dbf305d4764a
/spring-boot/spring-boot-mybatis-dynamic-datasource/src/main/java/com/zmz/app/infrastructure/dao/entity/UserEntity.java
c0509eb1c30826e20453044043ae53b3c8f68691
[]
no_license
GitHubForFrank/Spring-All-Demos
6ddc9e09ec62f5f99e780d35db768ac9560413f1
da5619d25df0d81539b16c26e1b5cffa76648c6a
refs/heads/master
2022-12-22T09:28:58.124685
2021-01-04T01:54:33
2021-01-04T01:54:33
233,199,002
0
1
null
2022-12-16T05:11:48
2020-01-11T08:17:37
Java
UTF-8
Java
false
false
447
java
package com.zmz.app.infrastructure.dao.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; /** * @author ASNPHDG * @create 2020-01-03 22:55 */ @Data @AllArgsConstructor @NoArgsConstructor @ToString public class UserEntity { private Long id; private String name; private String dept; private String phone; private String website; }
88073a3f119562d8914187cf81efbe8f11b7ddf9
f4633c46cad7875f287761a7d72281ce6ac5125f
/EAR/src/EarTankFighters/Proyectil.java
c2b83a723554e58d13fd5893fb62db2852b90d06
[]
no_license
yocuchi/cuchi-ear-pilar
b95db50f81b5639e68517c8a73edab3dc0f081a1
617868accf358428834fb9904a771afac7f28124
refs/heads/master
2021-01-18T14:14:02.405678
2013-11-18T22:48:42
2013-11-18T22:48:42
33,600,181
0
0
null
null
null
null
UTF-8
Java
false
false
2,198
java
package EarTankFighters; import java.awt.Color; import java.awt.Graphics; public class Proyectil extends ObjetoTablero { /** * @param args */ double velocidad_x, velocidad_y; TankPlayer Lanzador; public TankPlayer getLanzador() { return Lanzador; } public Proyectil(int velocidad_x, int velocidad_y, TankPlayer lanzador) { this.velocidad_x = velocidad_x; this.velocidad_y = velocidad_y; this.Ancho=TableroTankFighters.Ancho_proyectil; this.Alto=TableroTankFighters.Alto_proyectil; Lanzador = lanzador; } public Proyectil(double velocidad_x, double velocidad_y, TankPlayer lanzador) { this.velocidad_x = velocidad_x; this.velocidad_y = velocidad_y; this.Ancho=TableroTankFighters.Ancho_proyectil; this.Alto=TableroTankFighters.Alto_proyectil; Lanzador = lanzador; } public double getVelocidad_x() { return velocidad_x; } public double getVelocidad_y() { return velocidad_y; } public void mueve(int ms){ //la formula matematica es double delta_t= (double)(ms)/1000; this.x= (this.x + this.velocidad_x * delta_t); this.y= (this.y - this.velocidad_y * delta_t + 4.5 *delta_t*delta_t); this.velocidad_y = (this.velocidad_y - 9*delta_t); } @Override public void pintame(Graphics g) { // TODO Auto-generated method stub g.setColor(Lanzador.getColor()); g.fillOval((int)(x-Ancho/2), (int) (y -Alto/2), (int)Ancho,(int) Alto); g.setColor(Color.black); } @Override public boolean Colision(ObjetoTablero o) { //me aprovecho de las funciones de JAVA 2D return o.AreaImpacto().intersects(this.AreaImpacto()); } @Override public String toString() { return "Proyectil [velocidad_x=" + velocidad_x + ", velocidad_y=" + velocidad_y + ", Lanzador=" + Lanzador + ", x=" + x + ", y=" + y + ", Ancho=" + Ancho + ", Alto=" + Alto + ", Explota=" + Explota + "]"; } public void Explota(Graphics g) { //me aprovecho de las funciones de JAVA 2D g.setColor(Color.RED); g.fillOval((int)(x-Ancho/2), (int) (y -Alto/2), (int)Ancho*2,(int) Alto*2); g.setColor(Color.black); } }
[ "[email protected]@5edad677-2517-c213-a13b-7f09ccf225cb" ]
[email protected]@5edad677-2517-c213-a13b-7f09ccf225cb
0930270993f4d21d3c0bb0328bdb5b1c9d8b4603
c7bac6b1e82fc066bcf7a587f6a2999d04e6b357
/src/main/java/com/example/demo/data/repository/IProductRepository.java
c330eeff773bd2b6595356a8811838b2260dfc10
[]
no_license
jkey774/soda-machine
6bd1ad836434545fc7cb387e49035eb83755f11a
67e4f491e18a22e45dc324e96cc6877c78402119
refs/heads/main
2023-03-24T02:48:17.889905
2021-03-21T02:39:06
2021-03-21T02:39:06
330,013,917
0
0
null
null
null
null
UTF-8
Java
false
false
368
java
package com.example.demo.data.repository; import com.example.demo.model.Product; import java.util.List; import java.util.concurrent.ExecutionException; public interface IProductRepository { Product fetchProduct(String productId) throws ExecutionException, InterruptedException; List<Product> fetchProducts() throws ExecutionException, InterruptedException; }
008f747a1f8384d8bd849da08774ccc6bc64da91
30609ff57ccf1d619123ce10e4d8705aebceb30e
/src/main/java/com/aws/s3/service/StorageServiceImpl.java
029582ce177bae2732924e420f6de55a32be65bf
[]
no_license
loguvsr/aws-storage-service
b72e9792a08c6a1eafe821abd95a242c3d23b1f3
1e863f9d63e79522586b2554f9d5eab2881b9363
refs/heads/main
2023-01-19T18:21:45.282454
2020-11-24T02:23:16
2020-11-24T02:23:16
315,493,710
0
0
null
null
null
null
UTF-8
Java
false
false
1,835
java
/** * */ package com.aws.s3.service; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import com.amazonaws.AmazonServiceException; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.model.PutObjectRequest; /** * @author Logu * */ @Service public class StorageServiceImpl implements StorageService { private static final Logger LOGGER = LoggerFactory.getLogger(StorageServiceImpl.class); @Autowired private AmazonS3 amazons3; @Value("${aws.s3.bucket_name") private String bucketName; @Override @Async public void uploadFile(MultipartFile multipartFile) { try { File file = convertMultiPartFileToFile(multipartFile); uploadFileToS3Bucket(bucketName, file); LOGGER.info("File upload is completed."); file.delete(); // To remove the file locally created in the project folder. } catch (AmazonServiceException ex) { ex.getMessage(); } } private File convertMultiPartFileToFile(MultipartFile multipartFile) { File file = new File(multipartFile.getOriginalFilename()); try (FileOutputStream outputStream = new FileOutputStream(file)) { outputStream.write(multipartFile.getBytes()); } catch ( IOException ex) { } return file; } private void uploadFileToS3Bucket(String bucketName, File file) { String fileName = file.getName(); PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, file); amazons3.putObject(putObjectRequest); } }
f2b0eb1143b115561bcd40986590004a8d28d18c
5f26ead101e8cbd1948ef41dda979ab9114abaae
/little program/collection4J/src/main/java/designPatterns/visitor/MySubject.java
d361e5babdaef541639dc7819d3e13dbba2d05af
[]
no_license
computerwan/awesome-note
a874740c966b6d046c55f6e96ddf125cbe1e5d5b
b4f3a2a3d575d81d95257d1ac9879af386797075
refs/heads/master
2021-01-12T05:07:41.539032
2017-03-09T05:58:20
2017-03-09T05:58:20
77,844,988
0
0
null
null
null
null
UTF-8
Java
false
false
269
java
package designPatterns.visitor; /** * Created by pengcheng.wan on 2016/8/17. */ public class MySubject implements Subject { public void accept(Visitor visitor) { visitor.visit(this); } public String getSubject() { return "love"; } }
[ "鹏程万" ]
鹏程万
5371ebf8d805a3f4988bed52ba7cba675bb36b72
92f297583cf55fb714e7fa24efd44734d3c13a69
/springboot-redis/src/main/java/com/xf/zhang/pojo/Test.java
c466d1446386e2fdf7507ae7dbca2a55040abf8a
[]
no_license
LiarZhang/springboot-study
141f2301c2f4e62e60cee7adb06a9e10d6c74dba
055d0a9e595f8502bb1bc8f862d3c1d4875fcaae
refs/heads/master
2020-04-15T21:12:45.401464
2019-03-25T11:24:46
2019-03-25T11:24:46
165,024,917
0
0
null
null
null
null
UTF-8
Java
false
false
563
java
package com.xf.zhang.pojo; public class Test { private Integer id; private String name; private String pass; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name == null ? null : name.trim(); } public String getPass() { return pass; } public void setPass(String pass) { this.pass = pass == null ? null : pass.trim(); } }