hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
e9809b006a24c9d196254508e7a363bbea8b2491
402
package com.dataiku.dctc.command.grep; import com.dataiku.dctc.file.GFile; class ColorFileGrepPrinter implements GrepPrinter { public void print(String line) { match = true; } public void end(GFile file) { if (match) { System.out.println("\u001B[1;35m" + file.givenName() + "\u001B[0m"); } } // Attributes private boolean match = false; }
22.333333
80
0.619403
6ef26357b14562c124d6501b6beb0a518e905fd9
5,755
package GameOfLifeModel; import org.junit.Test; import static org.junit.Assert.assertEquals; public class GameOfLifeModelTest { @Test //Any live cell with fewer than two live neighbors dies, as if by under population. public void cellAlive_fewerThanTwoLiveNeighborsDies_oneNeighbor() { GameOfLifeModel gameOfLifeModel = new GameOfLifeModel(3, false); gameOfLifeModel.currentGeneration[0][0] = true; gameOfLifeModel.currentGeneration[2][2] = true; gameOfLifeModel.nextGeneration(); assertEquals(gameOfLifeModel.currentGeneration[1][1], false); } @Test //Any live cell with fewer than two live neighbors dies, as if by under population. public void cellAlive_fewerThanTwoLiveNeighborsDies_zeroNeighbor() { GameOfLifeModel gameOfLifeModel = new GameOfLifeModel(3, false); gameOfLifeModel.currentGeneration[2][2] = true; gameOfLifeModel.nextGeneration(); assertEquals(gameOfLifeModel.currentGeneration[1][1], false); } @Test //Any live cell with two or three live neighbors lives on to the next generation. public void cellAlive_twoOrThreeLiveNeighborsLivesOn_twoNeighbors() { GameOfLifeModel gameOfLifeModel = new GameOfLifeModel(3, false); gameOfLifeModel.currentGeneration[0][0] = true; gameOfLifeModel.currentGeneration[1][1] = true; gameOfLifeModel.currentGeneration[2][1] = true; gameOfLifeModel.nextGeneration(); assertEquals(gameOfLifeModel.currentGeneration[1][1], true); } @Test //Any live cell with two or three live neighbors lives on to the next generation. public void cellAlive_twoOrThreeLiveNeighborsLivesOn_threeNeighbors() { GameOfLifeModel gameOfLifeModel = new GameOfLifeModel(3, false); gameOfLifeModel.currentGeneration[0][0] = true; gameOfLifeModel.currentGeneration[1][1] = true; gameOfLifeModel.currentGeneration[1][2] = true; gameOfLifeModel.currentGeneration[2][1] = true; gameOfLifeModel.nextGeneration(); assertEquals(gameOfLifeModel.currentGeneration[1][1], true); } @Test //Any live cell with more than three live neighbors dies, as if by overpopulation. public void cellAlive_moreThanThreeLiveNeighborsDies_fourNeighbors() { GameOfLifeModel gameOfLifeModel = new GameOfLifeModel(3, false); gameOfLifeModel.currentGeneration[0][0] = true; gameOfLifeModel.currentGeneration[0][1] = true; gameOfLifeModel.currentGeneration[1][1] = true; gameOfLifeModel.currentGeneration[1][2] = true; gameOfLifeModel.currentGeneration[2][1] = true; gameOfLifeModel.nextGeneration(); assertEquals(gameOfLifeModel.currentGeneration[1][1], false); } @Test //Any live cell with more than three live neighbors dies, as if by overpopulation. public void cellAlive_moreThanThreeLiveNeighborsDies_sevenNeighbors() { GameOfLifeModel gameOfLifeModel = new GameOfLifeModel(3, false); gameOfLifeModel.currentGeneration[0][0] = true; gameOfLifeModel.currentGeneration[0][1] = true; gameOfLifeModel.currentGeneration[0][2] = true; gameOfLifeModel.currentGeneration[1][0] = true; gameOfLifeModel.currentGeneration[1][1] = true; gameOfLifeModel.currentGeneration[1][2] = true; gameOfLifeModel.currentGeneration[2][0] = true; gameOfLifeModel.currentGeneration[2][1] = true; gameOfLifeModel.nextGeneration(); assertEquals(gameOfLifeModel.currentGeneration[1][1], false); } @Test //Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction. public void cellDead_exactlyThreeLiveNeighborsBecomesAlive() { GameOfLifeModel gameOfLifeModel = new GameOfLifeModel(3, false); gameOfLifeModel.currentGeneration[1][1] = false; gameOfLifeModel.currentGeneration[1][2] = true; gameOfLifeModel.currentGeneration[2][0] = true; gameOfLifeModel.currentGeneration[2][1] = true; gameOfLifeModel.nextGeneration(); assertEquals(gameOfLifeModel.currentGeneration[1][1], true); } @Test public void countNeighbors_zeroNeighbors() { GameOfLifeModel gameOfLifeModel = new GameOfLifeModel(3, false); assertEquals(gameOfLifeModel.countNeighbors(0,0), 0); } @Test public void countNeighbors_threeNeighbors() { GameOfLifeModel gameOfLifeModel = new GameOfLifeModel(3, false); gameOfLifeModel.currentGeneration[0][1] = true; gameOfLifeModel.currentGeneration[1][1] = true; gameOfLifeModel.currentGeneration[1][0] = true; assertEquals(gameOfLifeModel.countNeighbors(0,0), 3); } @Test public void countNeighbors_eightNeighbors() { GameOfLifeModel gameOfLifeModel = new GameOfLifeModel(4, false); gameOfLifeModel.currentGeneration[0][0] = true; gameOfLifeModel.currentGeneration[0][1] = true; gameOfLifeModel.currentGeneration[0][2] = true; gameOfLifeModel.currentGeneration[1][0] = true; gameOfLifeModel.currentGeneration[1][1] = true; gameOfLifeModel.currentGeneration[1][2] = true; gameOfLifeModel.currentGeneration[2][0] = true; gameOfLifeModel.currentGeneration[2][1] = true; gameOfLifeModel.currentGeneration[2][2] = true; gameOfLifeModel.currentGeneration[3][0] = true; gameOfLifeModel.currentGeneration[3][1] = true; gameOfLifeModel.currentGeneration[3][2] = true; assertEquals(gameOfLifeModel.countNeighbors(1,1), 8); } }
44.612403
104
0.692963
06cd655ace24378396f22d90a390f675a0b08928
1,633
/* Annot8 (annot8.io) - Licensed under Apache-2.0. */ package io.annot8.implementations.support.registries; import io.annot8.api.capabilities.Capabilities; import io.annot8.api.capabilities.Capability; import io.annot8.api.components.Processor; import io.annot8.api.components.ProcessorDescriptor; import io.annot8.api.components.responses.ProcessorResponse; import io.annot8.api.context.Context; import io.annot8.api.data.Item; import io.annot8.api.settings.NoSettings; import java.util.stream.Stream; public class TestProcessorDescriptor implements ProcessorDescriptor<TestProcessorDescriptor.TestProcessor, NoSettings> { private String name; @Override public void setName(String name) { this.name = name; } @Override public String getName() { return name; } @Override public void setSettings(NoSettings settings) { // Do nothing } @Override public NoSettings getSettings() { return NoSettings.getInstance(); } @Override public Capabilities capabilities() { return new Capabilities() { @Override public Stream<Capability> creates() { return Stream.empty(); } @Override public Stream<Capability> processes() { return Stream.empty(); } @Override public Stream<Capability> deletes() { return Stream.empty(); } }; } @Override public TestProcessor create(Context context) { return new TestProcessor(); } public static class TestProcessor implements Processor { @Override public ProcessorResponse process(Item item) { return ProcessorResponse.ok(); } } }
23
87
0.706675
2f6a2f8782d08577b2d536a7ee7d732d18a4c32c
124,592
/* * Copyright (C) 2012-2015 DataStax Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.datastax.driver.core; import java.io.Closeable; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.*; import java.util.Map.Entry; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Functions; import com.google.common.base.Objects; import com.google.common.base.Predicates; import com.google.common.collect.*; import com.google.common.util.concurrent.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.datastax.driver.core.exceptions.AuthenticationException; import com.datastax.driver.core.exceptions.DriverInternalError; import com.datastax.driver.core.exceptions.InvalidQueryException; import com.datastax.driver.core.exceptions.NoHostAvailableException; import com.datastax.driver.core.policies.*; import com.datastax.driver.core.utils.MoreFutures; /** * Information and known state of a Cassandra cluster. * <p> * This is the main entry point of the driver. A simple example of access to a * Cassandra cluster would be: * <pre> * Cluster cluster = Cluster.builder().addContactPoint("192.168.0.1").build(); * Session session = cluster.connect("db1"); * * for (Row row : session.execute("SELECT * FROM table1")) * // do something ... * </pre> * <p> * A cluster object maintains a permanent connection to one of the cluster nodes * which it uses solely to maintain information on the state and current * topology of the cluster. Using the connection, the driver will discover all * the nodes currently in the cluster as well as new nodes joining the cluster * subsequently. */ public class Cluster implements Closeable { private static final Logger logger = LoggerFactory.getLogger(Cluster.class); @VisibleForTesting static final int NEW_NODE_DELAY_SECONDS = SystemProperties.getInt("com.datastax.driver.NEW_NODE_DELAY_SECONDS", 1); private static final int NON_BLOCKING_EXECUTOR_SIZE = SystemProperties.getInt("com.datastax.driver.NON_BLOCKING_EXECUTOR_SIZE", Runtime.getRuntime().availableProcessors()); private static final ResourceBundle driverProperties = ResourceBundle.getBundle("com.datastax.driver.core.Driver"); // Some per-JVM number that allows to generate unique cluster names when // multiple Cluster instance are created in the same JVM. private static final AtomicInteger CLUSTER_ID = new AtomicInteger(0); private static final int DEFAULT_THREAD_KEEP_ALIVE = 30; private static final int NOTIF_LOCK_TIMEOUT_SECONDS = SystemProperties.getInt("com.datastax.driver.NOTIF_LOCK_TIMEOUT_SECONDS", 60); final Manager manager; /** * Constructs a new Cluster instance. * <p> * This constructor is mainly exposed so Cluster can be sub-classed as a means to make testing/mocking * easier or to "intercept" its method call. Most users shouldn't extend this class however and * should prefer either using the {@link #builder} or calling {@link #buildFrom} with a custom * Initializer. * * @param name the name to use for the cluster (this is not the Cassandra cluster name, see {@link #getClusterName}). * @param contactPoints the list of contact points to use for the new cluster. * @param configuration the configuration for the new cluster. */ protected Cluster(String name, List<InetSocketAddress> contactPoints, Configuration configuration) { this(name, contactPoints, configuration, Collections.<Host.StateListener>emptySet()); } /** * Constructs a new Cluster instance. * <p> * This constructor is mainly exposed so Cluster can be sub-classed as a means to make testing/mocking * easier or to "intercept" its method call. Most users shouldn't extend this class however and * should prefer using the {@link #builder}. * * @param initializer the initializer to use. * @see #buildFrom */ protected Cluster(Initializer initializer) { this(initializer.getClusterName(), checkNotEmpty(initializer.getContactPoints()), initializer.getConfiguration(), initializer.getInitialListeners()); } private static List<InetSocketAddress> checkNotEmpty(List<InetSocketAddress> contactPoints) { if (contactPoints.isEmpty()) throw new IllegalArgumentException("Cannot build a cluster without contact points"); return contactPoints; } private Cluster(String name, List<InetSocketAddress> contactPoints, Configuration configuration, Collection<Host.StateListener> listeners) { this.manager = new Manager(name, contactPoints, configuration, listeners); } /** * Initialize this Cluster instance. * * This method creates an initial connection to one of the contact points * used to construct the {@code Cluster} instance. That connection is then * used to populate the cluster {@link Metadata}. * <p> * Calling this method is optional in the sense that any call to one of the * {@code connect} methods of this object will automatically trigger a call * to this method beforehand. It is thus only useful to call this method if * for some reason you want to populate the metadata (or test that at least * one contact point can be reached) without creating a first {@code * Session}. * <p> * Please note that this method only creates one control connection for * gathering cluster metadata. In particular, it doesn't create any connection pools. * Those are created when a new {@code Session} is created through * {@code connect}. * <p> * This method has no effect if the cluster is already initialized. * * @return this {@code Cluster} object. * * @throws NoHostAvailableException if no host amongst the contact points * can be reached. * @throws AuthenticationException if an authentication error occurs * while contacting the initial contact points. * @throws IllegalStateException if the Cluster was closed prior to calling * this method. This can occur either directly (through {@link #close()} or * {@link #closeAsync()}), or as a result of an error while initializing the * Cluster. */ public Cluster init() { this.manager.init(); return this; } /** * Build a new cluster based on the provided initializer. * <p> * Note that for building a cluster pragmatically, Cluster.Builder * provides a slightly less verbose shortcut with {@link Builder#build}. * <p> * Also note that that all the contact points provided by {@code * initializer} must share the same port. * * @param initializer the Cluster.Initializer to use * @return the newly created Cluster instance * * @throws IllegalArgumentException if the list of contact points provided * by {@code initializer} is empty or if not all those contact points have the same port. */ public static Cluster buildFrom(Initializer initializer) { return new Cluster(initializer); } /** * Creates a new {@link Cluster.Builder} instance. * <p> * This is a convenience method for {@code new Cluster.Builder()}. * * @return the new cluster builder. */ public static Cluster.Builder builder() { return new Cluster.Builder(); } /** * Returns the current version of the driver. * <p> * This is intended for products that wrap or extend the driver, as a way to check * compatibility if end-users override the driver version in their application. * * @return the version. */ public static String getDriverVersion() { return driverProperties.getString("driver.version"); } /** * Creates a new session on this cluster but does not initialize it. * <p> * Because this method does not perform any initialization, it cannot fail. * The initialization of the session (the connection of the Session to the * Cassandra nodes) will occur if either the {@link Session#init} method is * called explicitly, or whenever the returned session object is used. * <p> * Once a session returned by this method gets initialized (see above), it * will be set to no keyspace. If you want to set such session to a * keyspace, you will have to explicitly execute a 'USE mykeyspace' query. * <p> * Note that if you do not particularly need to defer initialization, it is * simpler to use one of the {@code connect()} method of this class. * * @return a new, non-initialized session on this cluster. */ public Session newSession() { checkNotClosed(manager); return manager.newSession(); } /** * Creates a new session on this cluster and initialize it. * <p> * Note that this method will initialize the newly created session, trying * to connect to the Cassandra nodes before returning. If you only want to * create a Session object without initializing it right away, see * {@link #newSession}. * * @return a new session on this cluster sets to no keyspace. * * @throws NoHostAvailableException if the Cluster has not been initialized * yet ({@link #init} has not be called and this is the first connect call) * and no host amongst the contact points can be reached. * @throws AuthenticationException if an authentication error occurs while * contacting the initial contact points. * @throws IllegalStateException if the Cluster was closed prior to calling * this method. This can occur either directly (through {@link #close()} or * {@link #closeAsync()}), or as a result of an error while initializing the * Cluster. */ public Session connect() { try { return Uninterruptibles.getUninterruptibly(connectAsync()); } catch (ExecutionException e) { throw DriverThrowables.propagateCause(e); } } /** * Creates a new session on this cluster, initialize it and sets the * keyspace to the provided one. * <p> * Note that this method will initialize the newly created session, trying * to connect to the Cassandra nodes before returning. If you only want to * create a Session object without initializing it right away, see * {@link #newSession}. * * @param keyspace The name of the keyspace to use for the created * {@code Session}. * @return a new session on this cluster sets to keyspace * {@code keyspaceName}. * * @throws NoHostAvailableException if the Cluster has not been initialized * yet ({@link #init} has not be called and this is the first connect call) * and no host amongst the contact points can be reached, or if no host can * be contacted to set the {@code keyspace}. * @throws AuthenticationException if an authentication error occurs while * contacting the initial contact points. * @throws InvalidQueryException if the keyspace does not exists. * @throws IllegalStateException if the Cluster was closed prior to calling * this method. This can occur either directly (through {@link #close()} or * {@link #closeAsync()}), or as a result of an error while initializing the * Cluster. */ public Session connect(String keyspace) { try { return Uninterruptibles.getUninterruptibly(connectAsync(keyspace)); } catch (ExecutionException e) { throw DriverThrowables.propagateCause(e); } } /** * Creates a new session on this cluster and initializes it asynchronously. * * This will also initialize the {@code Cluster} if needed; note that cluster * initialization happens synchronously on the thread that called this method. * Therefore it is recommended to initialize the cluster at application * startup, and not rely on this method to do it. * * @return a future that will complete when the session is fully initialized. * * @throws NoHostAvailableException if the Cluster has not been initialized * yet ({@link #init} has not been called and this is the first connect call) * and no host amongst the contact points can be reached. * * @throws IllegalStateException if the Cluster was closed prior to calling * this method. This can occur either directly (through {@link #close()} or * {@link #closeAsync()}), or as a result of an error while initializing the * Cluster. * * @see #connect() */ public ListenableFuture<Session> connectAsync() { return connectAsync(null); } /** * Creates a new session on this cluster, and initializes it to the given * keyspace asynchronously. * * This will also initialize the {@code Cluster} if needed; note that cluster * initialization happens synchronously on the thread that called this method. * Therefore it is recommended to initialize the cluster at application * startup, and not rely on this method to do it. * * @param keyspace The name of the keyspace to use for the created * {@code Session}. * @return a future that will complete when the session is fully initialized. * * @throws NoHostAvailableException if the Cluster has not been initialized * yet ({@link #init} has not been called and this is the first connect call) * and no host amongst the contact points can be reached. * * @throws IllegalStateException if the Cluster was closed prior to calling * this method. This can occur either directly (through {@link #close()} or * {@link #closeAsync()}), or as a result of an error while initializing the * Cluster. */ public ListenableFuture<Session> connectAsync(final String keyspace) { checkNotClosed(manager); init(); final AsyncInitSession session = manager.newSession(); ListenableFuture<Session> sessionInitialized = session.initAsync(); if (keyspace == null) { return sessionInitialized; } else { ListenableFuture<ResultSet> keyspaceSet = Futures.transform(sessionInitialized, new AsyncFunction<Session, ResultSet>() { @Override public ListenableFuture<ResultSet> apply(Session session) throws Exception { return session.executeAsync("USE " + keyspace); } }); Futures.addCallback(keyspaceSet, new MoreFutures.FailureCallback<ResultSet>() { @Override public void onFailure(Throwable t) { session.closeAsync(); } }); return Futures.transform(keyspaceSet, Functions.<Session>constant(session)); } } /** * The name of this cluster object. * <p> * Note that this is not the Cassandra cluster name, but rather a name * assigned to this Cluster object. Currently, that name is only used * for one purpose: to distinguish exposed JMX metrics when multiple * Cluster instances live in the same JVM (which should be rare in the first * place). That name can be set at Cluster building time (through * {@link Builder#withClusterName} for instance) but will default to a * name like {@code cluster1} where each Cluster instance in the same JVM * will have a different number. * * @return the name for this cluster instance. */ public String getClusterName() { return manager.clusterName; } /** * Returns read-only metadata on the connected cluster. * <p> * This includes the known nodes with their status as seen by the driver, * as well as the schema definitions. Since this return metadata on the * connected cluster, this method may trigger the creation of a connection * if none has been established yet (neither {@code init()} nor {@code connect()} * has been called yet). * * @return the cluster metadata. * * @throws NoHostAvailableException if the Cluster has not been initialized yet * and no host amongst the contact points can be reached. * @throws AuthenticationException if an authentication error occurs * while contacting the initial contact points. * @throws IllegalStateException if the Cluster was closed prior to calling * this method. This can occur either directly (through {@link #close()} or * {@link #closeAsync()}), or as a result of an error while initializing the * Cluster. */ public Metadata getMetadata() { manager.init(); return manager.metadata; } /** * The cluster configuration. * * @return the cluster configuration. */ public Configuration getConfiguration() { return manager.configuration; } /** * The cluster metrics. * * @return the cluster metrics, or {@code null} if metrics collection has * been disabled (that is if {@link Configuration#getMetricsOptions} * returns {@code null}). */ public Metrics getMetrics() { checkNotClosed(manager); return manager.metrics; } /** * Registers the provided listener to be notified on hosts * up/down/added/removed events. * <p> * Registering the same listener multiple times is a no-op. * <p> * Note that while {@link LoadBalancingPolicy} implements * {@code Host.StateListener}, the configured load balancing does not * need to (and should not) be registered through this method to * received host related events. * * @param listener the new {@link Host.StateListener} to register. * @return this {@code Cluster} object; */ public Cluster register(Host.StateListener listener) { checkNotClosed(manager); manager.listeners.add(listener); return this; } /** * Unregisters the provided listener from being notified on hosts events. * <p> * This method is a no-op if {@code listener} hadn't previously be * registered against this Cluster. * * @param listener the {@link Host.StateListener} to unregister. * @return this {@code Cluster} object; */ public Cluster unregister(Host.StateListener listener) { checkNotClosed(manager); manager.listeners.remove(listener); return this; } /** * Registers the provided tracker to be updated with hosts read * latencies. * <p> * Registering the same listener multiple times is a no-op. * <p> * Be wary that the registered tracker {@code update} method will be call * very frequently (at the end of every query to a Cassandra host) and * should thus not be costly. * <p> * The main use case for a {@code LatencyTracker} is so * {@link LoadBalancingPolicy} can implement latency awareness * Typically, {@link LatencyAwarePolicy} registers it's own internal * {@code LatencyTracker} (automatically, you don't have to call this * method directly). * * @param tracker the new {@link LatencyTracker} to register. * @return this {@code Cluster} object; */ public Cluster register(LatencyTracker tracker) { checkNotClosed(manager); manager.trackers.add(tracker); return this; } /** * Unregisters the provided latency tracking from being updated * with host read latencies. * <p> * This method is a no-op if {@code tracker} hadn't previously be * registered against this Cluster. * * @param tracker the {@link LatencyTracker} to unregister. * @return this {@code Cluster} object; */ public Cluster unregister(LatencyTracker tracker) { checkNotClosed(manager); manager.trackers.remove(tracker); return this; } /** * Registers the provided listener to be updated with schema change events. * <p> * Registering the same listener multiple times is a no-op. * * @param listener the new {@link SchemaChangeListener} to register. * @return this {@code Cluster} object; */ public Cluster register(SchemaChangeListener listener) { checkNotClosed(manager); listener.onRegister(this); manager.schemaChangeListeners.add(listener); return this; } /** * Unregisters the provided schema change listener from being updated * with schema change events. * <p> * This method is a no-op if {@code listener} hadn't previously be * registered against this Cluster. * * @param listener the {@link SchemaChangeListener} to unregister. * @return this {@code Cluster} object; */ public Cluster unregister(SchemaChangeListener listener) { checkNotClosed(manager); listener.onUnregister(this); manager.schemaChangeListeners.remove(listener); return this; } /** * Initiates a shutdown of this cluster instance. * <p> * This method is asynchronous and return a future on the completion * of the shutdown process. As soon a the cluster is shutdown, no * new request will be accepted, but already submitted queries are * allowed to complete. This method closes all connections from all * sessions and reclaims all resources used by this Cluster * instance. * <p> * If for some reason you wish to expedite this process, the * {@link CloseFuture#force} can be called on the result future. * <p> * This method has no particular effect if the cluster was already closed * (in which case the returned future will return immediately). * * @return a future on the completion of the shutdown process. */ public CloseFuture closeAsync() { return manager.close(); } /** * Initiates a shutdown of this cluster instance and blocks until * that shutdown completes. * <p> * This method is a shortcut for {@code closeAsync().get()}. */ public void close() { try { closeAsync().get(); } catch (ExecutionException e) { throw DriverThrowables.propagateCause(e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } /** * Whether this Cluster instance has been closed. * <p> * Note that this method returns true as soon as one of the close methods * ({@link #closeAsync} or {@link #close}) has been called, it does not guarantee * that the closing is done. If you want to guarantee that the closing is done, * you can call {@code close()} and wait until it returns (or call the get method * on {@code closeAsync()} with a very short timeout and check this doesn't timeout). * * @return {@code true} if this Cluster instance has been closed, {@code false} * otherwise. */ public boolean isClosed() { return manager.closeFuture.get() != null; } private static void checkNotClosed(Manager manager) { if (manager.isClosed()) throw new IllegalStateException("Can't use this cluster instance because it was previously closed"); } /** * Initializer for {@link Cluster} instances. * <p> * If you want to create a new {@code Cluster} instance programmatically, * then it is advised to use {@link Cluster.Builder} which can be obtained from the * {@link Cluster#builder} method. * <p> * But it is also possible to implement a custom {@code Initializer} that * retrieves initialization from a web-service or from a configuration file. */ public interface Initializer { /** * An optional name for the created cluster. * <p> * Such name is optional (a default name will be created otherwise) and is currently * only use for JMX reporting of metrics. See {@link Cluster#getClusterName} for more * information. * * @return the name for the created cluster or {@code null} to use an automatically * generated name. */ public String getClusterName(); /** * Returns the initial Cassandra hosts to connect to. * * @return the initial Cassandra contact points. See {@link Builder#addContactPoint} * for more details on contact points. */ public List<InetSocketAddress> getContactPoints(); /** * The configuration to use for the new cluster. * <p> * Note that some configuration can be modified after the cluster * initialization but some others cannot. In particular, the ones that * cannot be changed afterwards includes: * <ul> * <li>the port use to connect to Cassandra nodes (see {@link ProtocolOptions}).</li> * <li>the policies used (see {@link Policies}).</li> * <li>the authentication info provided (see {@link Configuration}).</li> * <li>whether metrics are enabled (see {@link Configuration}).</li> * </ul> * * @return the configuration to use for the new cluster. */ public Configuration getConfiguration(); /** * Optional listeners to register against the newly created cluster. * <p> * Note that contrary to listeners registered post Cluster creation, * the listeners returned by this method will see {@link Host.StateListener#onAdd} * events for the initial contact points. * * @return a possibly empty collection of {@code Host.StateListener} to register * against the newly created cluster. */ public Collection<Host.StateListener> getInitialListeners(); } /** * Helper class to build {@link Cluster} instances. */ public static class Builder implements Initializer { private String clusterName; private final List<InetSocketAddress> addresses = new ArrayList<InetSocketAddress>(); private final List<InetAddress> rawAddresses = new ArrayList<InetAddress>(); private int port = ProtocolOptions.DEFAULT_PORT; private int maxSchemaAgreementWaitSeconds = ProtocolOptions.DEFAULT_MAX_SCHEMA_AGREEMENT_WAIT_SECONDS; private int protocolVersion = -1; private AuthProvider authProvider = AuthProvider.NONE; private LoadBalancingPolicy loadBalancingPolicy; private ReconnectionPolicy reconnectionPolicy; private RetryPolicy retryPolicy; private AddressTranslater addressTranslater; private SpeculativeExecutionPolicy speculativeExecutionPolicy; private ProtocolOptions.Compression compression = ProtocolOptions.Compression.NONE; private SSLOptions sslOptions = null; private boolean metricsEnabled = true; private boolean jmxEnabled = true; private PoolingOptions poolingOptions; private SocketOptions socketOptions; private QueryOptions queryOptions; private NettyOptions nettyOptions = NettyOptions.DEFAULT_INSTANCE; private Collection<Host.StateListener> listeners; @Override public String getClusterName() { return clusterName; } @Override public List<InetSocketAddress> getContactPoints() { if (rawAddresses.isEmpty()) return addresses; List<InetSocketAddress> allAddresses = new ArrayList<InetSocketAddress>(addresses); for (InetAddress address : rawAddresses) allAddresses.add(new InetSocketAddress(address, port)); return allAddresses; } /** * An optional name for the create cluster. * <p> * Note: this is not related to the Cassandra cluster name (though you * are free to provide the same name). See {@link Cluster#getClusterName} for * details. * <p> * If you use this method and create more than one Cluster instance in the * same JVM (which should be avoided unless you need to connect to multiple * Cassandra clusters), you should make sure each Cluster instance get a * unique name or you may have a problem with JMX reporting. * * @param name the cluster name to use for the created Cluster instance. * @return this Builder. */ public Builder withClusterName(String name) { this.clusterName = name; return this; } /** * The port to use to connect to the Cassandra host. * <p> * If not set through this method, the default port (9042) will be used * instead. * * @param port the port to set. * @return this Builder. */ public Builder withPort(int port) { this.port = port; return this; } /** * Sets the maximum time to wait for schema agreement before returning from a DDL query. * <p> * If not set through this method, the default value (10 seconds) will be used. * * @param maxSchemaAgreementWaitSeconds the new value to set. * @return this Builder. * * @throws IllegalStateException if the provided value is zero or less. */ public Builder withMaxSchemaAgreementWaitSeconds(int maxSchemaAgreementWaitSeconds) { if (maxSchemaAgreementWaitSeconds <= 0) throw new IllegalArgumentException("Max schema agreement wait must be greater than zero"); this.maxSchemaAgreementWaitSeconds = maxSchemaAgreementWaitSeconds; return this; } /** * The native protocol version to use. * <p> * The driver supports both version 1 and 2 of the native protocol. Version 2 * of the protocol has more features and should be preferred, but it is only * supported by Cassandra 2.0 and above, so you will have to use version 1 with * Cassandra 1.2 nodes. * <p> * By default, the driver will "auto-detect" which protocol version it can use * when connecting to the first node. More precisely, it will try the version * 2 first and will fallback to version 1 if it is not supported by that first * node it connects to. Please note that once the version is "auto-detected", * it won't change: if the first node the driver connects to is a Cassandra 1.2 * node and auto-detection is used (the default), then the native protocol * version 1 will be use for the lifetime of the Cluster instance. * <p> * This method allows to force the use of a particular protocol version. Forcing * version 1 is always fine since all Cassandra version (at least all those * supporting the native protocol in the first place) so far supports it. However, * please note that a number of features of the driver won't be available if that * version of thr protocol is in use, including result set paging, * {@link BatchStatement}, executing a non-prepared query with binary values * ({@link Session#execute(String, Object...)}), ... (those methods will throw * an UnsupportedFeatureException). Using the protocol version 1 should thus * only be considered when using Cassandra 1.2, until nodes have been upgraded * to Cassandra 2.0. * <p> * If version 2 of the protocol is used, then Cassandra 1.2 nodes will be ignored * (the driver won't connect to them). * <p> * The default behavior (auto-detection) is fine in almost all case, but you may * want to force a particular version if you have a Cassandra cluster with mixed * 1.2/2.0 nodes (i.e. during a Cassandra upgrade). * * @param version the native protocol version to use. The versions supported by * this driver are version 1 and 2. Negative values are also supported to trigger * auto-detection (see above) but this is the default (so you don't have to call * this method for that behavior). * @return this Builder. * * @throws IllegalArgumentException if {@code version} is neither 1, 2 or a * negative value. */ public Builder withProtocolVersion(int version) { if (version >= 0 && version != 1 && version != 2) throw new IllegalArgumentException(String.format("Unsupported protocol version %d; valid values are 1, 2 or negative (for auto-detect).", version)); this.protocolVersion = version; return this; } /** * Adds a contact point. * <p> * Contact points are addresses of Cassandra nodes that the driver uses * to discover the cluster topology. Only one contact point is required * (the driver will retrieve the address of the other nodes * automatically), but it is usually a good idea to provide more than * one contact point, because if that single contact point is unavailable, * the driver cannot initialize itself correctly. * <p> * Note that by default (that is, unless you use the {@link #withLoadBalancingPolicy}) * method of this builder), the first succesfully contacted host will be use * to define the local data-center for the client. If follows that if you are * running Cassandra in a multiple data-center setting, it is a good idea to * only provided contact points that are in the same datacenter than the client, * or to provide manually the load balancing policy that suits your need. * * @param address the address of the node to connect to * @return this Builder. * * @throws IllegalArgumentException if no IP address for {@code address} * could be found * @throws SecurityException if a security manager is present and * permission to resolve the host name is denied. */ public Builder addContactPoint(String address) { // We explicitely check for nulls because InetAdress.getByName() will happily // accept it and use localhost (while a null here almost likely mean a user error, // not "connect to localhost") if (address == null) throw new NullPointerException(); try { this.rawAddresses.add(InetAddress.getByName(address)); return this; } catch (UnknownHostException e) { throw new IllegalArgumentException(e.getMessage()); } } /** * Adds contact points. * <p> * See {@link Builder#addContactPoint} for more details on contact * points. * * @param addresses addresses of the nodes to add as contact point. * @return this Builder. * * @throws IllegalArgumentException if no IP address for at least one * of {@code addresses} could be found * @throws SecurityException if a security manager is present and * permission to resolve the host name is denied. * * @see Builder#addContactPoint */ public Builder addContactPoints(String... addresses) { for (String address : addresses) addContactPoint(address); return this; } /** * Adds a contact point - or many if it host resolves to multiple <code>InetAddress</code>s (A records). * <p> * * If the host name points to a dns records with multiple a-records, all InetAddresses * returned will be used. Make sure that all resulting <code>InetAddress</code>s returned * points to the same cluster and datacenter. * <p> * See {@link Builder#addContactPoint} for more details on contact * points and thrown exceptions * * @param address address of the nodes to look up InetAddresses from to add as contact points. * @return this Builder. * * * @see Builder#addContactPoint */ public Builder addContactPoints(String address) { // We explicitely check for nulls because InetAdress.getByName() will happily // accept it and use localhost (while a null here almost likely mean a user error, // not "connect to localhost") if (address == null) throw new NullPointerException(); try { addContactPoints(InetAddress.getAllByName(address)); } catch (UnknownHostException e) { throw new IllegalArgumentException(e.getMessage()); } return this; } /** * Adds contact points. * <p> * See {@link Builder#addContactPoint} for more details on contact * points. * * @param addresses addresses of the nodes to add as contact point. * @return this Builder. * * @see Builder#addContactPoint */ public Builder addContactPoints(InetAddress... addresses) { Collections.addAll(this.rawAddresses, addresses); return this; } /** * Adds contact points. * * See {@link Builder#addContactPoint} for more details on contact * points. * * @param addresses addresses of the nodes to add as contact point * @return this Builder * * @see Builder#addContactPoint */ public Builder addContactPoints(Collection<InetAddress> addresses) { this.rawAddresses.addAll(addresses); return this; } /** * Adds contact points. * <p> * See {@link Builder#addContactPoint} for more details on contact * points. Contrarily to other {@code addContactPoints} methods, this method * allow to provide a different port for each contact points. Since Cassandra * nodes must always all listen on the same port, this is rarelly what you * want and most use should prefer other {@code addContactPoints} methods to * this one. However, this can be useful if the Cassandra nodes are behind * a router and are not accessed directly. Note that if you are in this * situtation (Cassandra nodes are behind a router, not directly accessible), * you almost surely want to provide a specific {@code AddressTranslater} * (through {@link #withAddressTranslater}) to translate actual Cassandra node * addresses to the addresses the driver should use, otherwise the driver * will not be able to auto-detect new nodes (and will generally not function * optimally). * * @param addresses addresses of the nodes to add as contact point * @return this Builder * * @see Builder#addContactPoint */ public Builder addContactPointsWithPorts(Collection<InetSocketAddress> addresses) { this.addresses.addAll(addresses); return this; } /** * Configures the load balancing policy to use for the new cluster. * <p> * If no load balancing policy is set through this method, * {@link Policies#defaultLoadBalancingPolicy} will be used instead. * * @param policy the load balancing policy to use. * @return this Builder. */ public Builder withLoadBalancingPolicy(LoadBalancingPolicy policy) { this.loadBalancingPolicy = policy; return this; } /** * Configures the reconnection policy to use for the new cluster. * <p> * If no reconnection policy is set through this method, * {@link Policies#DEFAULT_RECONNECTION_POLICY} will be used instead. * * @param policy the reconnection policy to use. * @return this Builder. */ public Builder withReconnectionPolicy(ReconnectionPolicy policy) { this.reconnectionPolicy = policy; return this; } /** * Configures the retry policy to use for the new cluster. * <p> * If no retry policy is set through this method, * {@link Policies#DEFAULT_RETRY_POLICY} will be used instead. * * @param policy the retry policy to use. * @return this Builder. */ public Builder withRetryPolicy(RetryPolicy policy) { this.retryPolicy = policy; return this; } /** * Configures the address translater to use for the new cluster. * <p> * See {@link AddressTranslater} for more detail on address translation, * but the default translater, {@link IdentityTranslater}, should be * correct in most cases. If unsure, stick to the default. * * @param translater the translater to use. * @return this Builder. */ public Builder withAddressTranslater(AddressTranslater translater) { this.addressTranslater = translater; return this; } /** * Configures the speculative execution policy to use for the new cluster. * <p> * If no policy is set through this method, {@link Policies#defaultSpeculativeExecutionPolicy()} * will be used instead. * * @param policy the policy to use. * @return this Builder. */ public Builder withSpeculativeExecutionPolicy(SpeculativeExecutionPolicy policy) { this.speculativeExecutionPolicy = policy; return this; } /** * Uses the provided credentials when connecting to Cassandra hosts. * <p> * This should be used if the Cassandra cluster has been configured to * use the {@code PasswordAuthenticator}. If the the default {@code * AllowAllAuthenticator} is used instead, using this method has no * effect. * * @param username the username to use to login to Cassandra hosts. * @param password the password corresponding to {@code username}. * @return this Builder. */ public Builder withCredentials(String username, String password) { this.authProvider = new PlainTextAuthProvider(username, password); return this; } /** * Use the specified AuthProvider when connecting to Cassandra * hosts. * <p> * Use this method when a custom authentication scheme is in place. * You shouldn't call both this method and {@code withCredentials} * on the same {@code Builder} instance as one will supersede the * other * * @param authProvider the {@link AuthProvider} to use to login to * Cassandra hosts. * @return this Builder */ public Builder withAuthProvider(AuthProvider authProvider) { this.authProvider = authProvider; return this; } /** * Sets the compression to use for the transport. * * @param compression the compression to set. * @return this Builder. * * @see ProtocolOptions.Compression */ public Builder withCompression(ProtocolOptions.Compression compression) { this.compression = compression; return this; } /** * Disables metrics collection for the created cluster (metrics are * enabled by default otherwise). * * @return this builder. */ public Builder withoutMetrics() { this.metricsEnabled = false; return this; } /** * Enables the use of SSL for the created {@code Cluster}. * <p> * Calling this method will use default SSL options (see {@link SSLOptions#SSLOptions()}). * This is thus a shortcut for {@code withSSL(new SSLOptions())}. * <p> * Note that if SSL is enabled, the driver will not connect to any * Cassandra nodes that doesn't have SSL enabled and it is strongly * advised to enable SSL on every Cassandra node if you plan on using * SSL in the driver. * * @return this builder. */ public Builder withSSL() { this.sslOptions = new SSLOptions(); return this; } /** * Enable the use of SSL for the created {@code Cluster} using the provided options. * * @param sslOptions the SSL options to use. * * @return this builder. */ public Builder withSSL(SSLOptions sslOptions) { this.sslOptions = sslOptions; return this; } /** * Register the provided listeners in the newly created cluster. * <p> * Note: repeated calls to this method will override the previous ones. * * @param listeners the listeners to register. * @return this builder. */ public Builder withInitialListeners(Collection<Host.StateListener> listeners) { this.listeners = listeners; return this; } /** * Disables JMX reporting of the metrics. * <p> * JMX reporting is enabled by default (see {@link Metrics}) but can be * disabled using this option. If metrics are disabled, this is a * no-op. * * @return this builder. */ public Builder withoutJMXReporting() { this.jmxEnabled = false; return this; } /** * Sets the PoolingOptions to use for the newly created Cluster. * <p> * If no pooling options are set through this method, default pooling * options will be used. * * @param options the pooling options to use. * @return this builder. */ public Builder withPoolingOptions(PoolingOptions options) { this.poolingOptions = options; return this; } /** * Sets the SocketOptions to use for the newly created Cluster. * <p> * If no socket options are set through this method, default socket * options will be used. * * @param options the socket options to use. * @return this builder. */ public Builder withSocketOptions(SocketOptions options) { this.socketOptions = options; return this; } /** * Sets the QueryOptions to use for the newly created Cluster. * <p> * If no query options are set through this method, default query * options will be used. * * @param options the query options to use. * @return this builder. */ public Builder withQueryOptions(QueryOptions options) { this.queryOptions = options; return this; } /** * Set the {@link NettyOptions} to use for the newly created Cluster. * <p> * If no Netty options are set through this method, {@link NettyOptions#DEFAULT_INSTANCE} * will be used as a default value, which means that no customization will be applied. * * @param nettyOptions the {@link NettyOptions} to use. * @return this builder. */ public Builder withNettyOptions(NettyOptions nettyOptions) { this.nettyOptions = nettyOptions; return this; } /** * The configuration that will be used for the new cluster. * <p> * You <b>should not</b> modify this object directly because changes made * to the returned object may not be used by the cluster build. * Instead, you should use the other methods of this {@code Builder}. * * @return the configuration to use for the new cluster. */ @Override public Configuration getConfiguration() { Policies policies = new Policies( loadBalancingPolicy == null ? Policies.defaultLoadBalancingPolicy() : loadBalancingPolicy, Objects.firstNonNull(reconnectionPolicy, Policies.defaultReconnectionPolicy()), Objects.firstNonNull(retryPolicy, Policies.defaultRetryPolicy()), Objects.firstNonNull(addressTranslater, Policies.defaultAddressTranslater()), Objects.firstNonNull(speculativeExecutionPolicy, Policies.defaultSpeculativeExecutionPolicy()) ); return new Configuration(policies, new ProtocolOptions(port, protocolVersion, maxSchemaAgreementWaitSeconds, sslOptions, authProvider).setCompression(compression), poolingOptions == null ? new PoolingOptions() : poolingOptions, socketOptions == null ? new SocketOptions() : socketOptions, metricsEnabled ? new MetricsOptions(jmxEnabled) : null, queryOptions == null ? new QueryOptions() : queryOptions, nettyOptions); } @Override public Collection<Host.StateListener> getInitialListeners() { return listeners == null ? Collections.<Host.StateListener>emptySet() : listeners; } /** * Builds the cluster with the configured set of initial contact points * and policies. * <p> * This is a convenience method for {@code Cluster.buildFrom(this)}. * * @return the newly built Cluster instance. */ public Cluster build() { return Cluster.buildFrom(this); } } static long timeSince(long startNanos, TimeUnit destUnit) { return destUnit.convert(System.nanoTime() - startNanos, TimeUnit.NANOSECONDS); } private static String generateClusterName() { return "cluster" + CLUSTER_ID.incrementAndGet(); } /** * The sessions and hosts managed by this a Cluster instance. * <p> * Note: the reason we create a Manager object separate from Cluster is * that Manager is not publicly visible. For instance, we wouldn't want * user to be able to call the {@link #onUp} and {@link #onDown} methods. */ class Manager implements Connection.DefaultResponseHandler { final String clusterName; private boolean isInit; private volatile boolean isFullyInit; // Initial contacts point final List<InetSocketAddress> contactPoints; final Set<SessionManager> sessions = new CopyOnWriteArraySet<SessionManager>(); Metadata metadata; final Configuration configuration; Metrics metrics; Connection.Factory connectionFactory; ControlConnection controlConnection; final ConvictionPolicy.Factory convictionPolicyFactory = new ConvictionPolicy.DefaultConvictionPolicy.Factory(); ScheduledThreadPoolExecutor reconnectionExecutor; ScheduledThreadPoolExecutor scheduledTasksExecutor; // Executor used for tasks that shouldn't be executed on an IO thread. Used for short-lived, generally non-blocking tasks ListeningExecutorService executor; // Work Queue used by executor. LinkedBlockingQueue<Runnable> executorQueue; // An executor for tasks that might block some time, like creating new connection, but are generally not too critical. ListeningExecutorService blockingExecutor; // Work Queue used by blockingExecutor. LinkedBlockingQueue<Runnable> blockingExecutorQueue; ConnectionReaper reaper; final AtomicReference<CloseFuture> closeFuture = new AtomicReference<CloseFuture>(); // All the queries that have been prepared (we keep them so we can re-prepared them when a node fail or a // new one join the cluster). // Note: we could move this down to the session level, but since prepared statement are global to a node, // this would yield a slightly less clear behavior. ConcurrentMap<MD5Digest, PreparedStatement> preparedQueries; final Set<Host.StateListener> listeners; final Set<LatencyTracker> trackers = new CopyOnWriteArraySet<LatencyTracker>(); final Set<SchemaChangeListener> schemaChangeListeners = new CopyOnWriteArraySet<SchemaChangeListener>(); EventDebouncer<NodeListRefreshRequest> nodeListRefreshRequestDebouncer; EventDebouncer<NodeRefreshRequest> nodeRefreshRequestDebouncer; EventDebouncer<SchemaRefreshRequest> schemaRefreshRequestDebouncer; private Manager(String clusterName, List<InetSocketAddress> contactPoints, Configuration configuration, Collection<Host.StateListener> listeners) { this.clusterName = clusterName == null ? generateClusterName() : clusterName; this.configuration = configuration; this.contactPoints = contactPoints; this.listeners = new CopyOnWriteArraySet<Host.StateListener>(listeners); } // Initialization is not too performance intensive and in practice there shouldn't be contention // on it so synchronized is good enough. synchronized void init() { checkNotClosed(this); if (isInit) return; isInit = true; logger.debug("Starting new cluster with contact points " + contactPoints); this.configuration.register(this); this.executorQueue = new LinkedBlockingQueue<Runnable>(); this.executor = makeExecutor(NON_BLOCKING_EXECUTOR_SIZE, "worker", executorQueue); this.blockingExecutorQueue = new LinkedBlockingQueue<Runnable>(); this.blockingExecutor = makeExecutor(2, "blocking-task-worker", blockingExecutorQueue); this.reconnectionExecutor = new ScheduledThreadPoolExecutor(2, threadFactory("reconnection")); // scheduledTasksExecutor is used to process C* notifications. So having it mono-threaded ensures notifications are // applied in the order received. this.scheduledTasksExecutor = new ScheduledThreadPoolExecutor(1, threadFactory("scheduled-task-worker")); this.reaper = new ConnectionReaper(this); this.metadata = new Metadata(this); this.connectionFactory = new Connection.Factory(this, configuration); this.controlConnection = new ControlConnection(this); this.metrics = configuration.getMetricsOptions() == null ? null : new Metrics(this); this.preparedQueries = new MapMaker().weakValues().makeMap(); // create debouncers - at this stage, they are not running yet QueryOptions queryOptions = configuration.getQueryOptions(); this.nodeListRefreshRequestDebouncer = new EventDebouncer<NodeListRefreshRequest>( "Node list refresh", scheduledTasksExecutor, new NodeListRefreshRequestDeliveryCallback(), queryOptions.getRefreshNodeListIntervalMillis(), queryOptions.getMaxPendingRefreshNodeListRequests()); this.nodeRefreshRequestDebouncer = new EventDebouncer<NodeRefreshRequest>( "Node refresh", scheduledTasksExecutor, new NodeRefreshRequestDeliveryCallback(), queryOptions.getRefreshNodeIntervalMillis(), queryOptions.getMaxPendingRefreshNodeRequests()); this.schemaRefreshRequestDebouncer = new EventDebouncer<SchemaRefreshRequest>( "Schema refresh", scheduledTasksExecutor, new SchemaRefreshRequestDeliveryCallback(), queryOptions.getRefreshSchemaIntervalMillis(), queryOptions.getMaxPendingRefreshSchemaRequests()); this.scheduledTasksExecutor.scheduleWithFixedDelay(new CleanupIdleConnectionsTask(), 10, 10, TimeUnit.SECONDS); for (InetSocketAddress address : contactPoints) { // We don't want to signal -- call onAdd() -- because nothing is ready // yet (loadbalancing policy, control connection, ...). All we want is // create the Host object so we can initialize the control connection. metadata.add(address); } try { while (true) { try { Collection<Host> allHosts = metadata.allHosts(); // At this stage, metadata.allHosts() only contains the contact points, that's what we want to pass to LBP.init(). // But the control connection will initialize first and discover more hosts, so make a copy. Set<Host> contactPointHosts = Sets.newHashSet(allHosts); controlConnection.connect(); if (connectionFactory.protocolVersion < 0) connectionFactory.protocolVersion = 2; // The control connection can mark hosts down if it failed to connect to them, or remove them if they weren't found // in the control host's system.peers. Separate them: Set<Host> downContactPointHosts = Sets.newHashSet(); Set<Host> removedContactPointHosts = Sets.newHashSet(); for (Host host : contactPointHosts) { if (!allHosts.contains(host)) removedContactPointHosts.add(host); else if (host.state == Host.State.DOWN) downContactPointHosts.add(host); } contactPointHosts.removeAll(removedContactPointHosts); contactPointHosts.removeAll(downContactPointHosts); // Now that the control connection is ready, we have all the information we need about the nodes (datacenter, // rack...) to initialize the load balancing policy loadBalancingPolicy().init(Cluster.this, contactPointHosts); speculativeRetryPolicy().init(Cluster.this); for (Host host : removedContactPointHosts) { loadBalancingPolicy().onRemove(host); for (Host.StateListener listener : listeners) listener.onRemove(host); } for (Host host : downContactPointHosts) { loadBalancingPolicy().onDown(host); for (Host.StateListener listener : listeners) listener.onDown(host); startPeriodicReconnectionAttempt(host, true); } for (Host host : allHosts) { // If the host is down at this stage, it's a contact point that the control connection failed to reach. // Reconnection attempts are already scheduled, and the LBP and listeners have been notified above. if (host.state == Host.State.DOWN) continue; // Otherwise, we want to do the equivalent of onAdd(). But since we know for sure that no sessions or prepared // statements exist at this point, we can skip some of the steps (plus this avoids scheduling concurrent pool // creations if a session is created right after this method returns). logger.info("New Cassandra host {} added", host); if (connectionFactory.protocolVersion == 2 && !supportsProtocolV2(host)) { logUnsupportedVersionProtocol(host); continue; } if (!contactPointHosts.contains(host)) loadBalancingPolicy().onAdd(host); host.setUp(); for (Host.StateListener listener : listeners) listener.onAdd(host); } // start debouncers this.nodeListRefreshRequestDebouncer.start(); this.schemaRefreshRequestDebouncer.start(); this.nodeRefreshRequestDebouncer.start(); isFullyInit = true; return; } catch (UnsupportedProtocolVersionException e) { assert connectionFactory.protocolVersion < 1; // For now, all C* version supports the protocol version 1 if (e.versionUnsupported <= 1) throw new DriverInternalError("Got a node that don't even support the protocol version 1, this makes no sense", e); logger.debug("{}: retrying with version {}", e.getMessage(), e.versionUnsupported - 1); connectionFactory.protocolVersion = e.versionUnsupported - 1; } } } catch (NoHostAvailableException e) { close(); throw e; } } int protocolVersion() { return connectionFactory.protocolVersion; } ThreadFactory threadFactory(String name) { return new ThreadFactoryBuilder().setNameFormat(clusterName + "-" + name + "-%d").build(); } private ListeningExecutorService makeExecutor(int threads, String name, LinkedBlockingQueue<Runnable> workQueue) { ThreadPoolExecutor executor = new ThreadPoolExecutor(threads, threads, DEFAULT_THREAD_KEEP_ALIVE, TimeUnit.SECONDS, workQueue, threadFactory(name)); executor.allowCoreThreadTimeOut(true); return MoreExecutors.listeningDecorator(executor); } Cluster getCluster() { return Cluster.this; } LoadBalancingPolicy loadBalancingPolicy() { return configuration.getPolicies().getLoadBalancingPolicy(); } SpeculativeExecutionPolicy speculativeRetryPolicy() { return configuration.getPolicies().getSpeculativeExecutionPolicy(); } ReconnectionPolicy reconnectionPolicy() { return configuration.getPolicies().getReconnectionPolicy(); } InetSocketAddress translateAddress(InetAddress address) { InetSocketAddress sa = new InetSocketAddress(address, connectionFactory.getPort()); InetSocketAddress translated = configuration.getPolicies().getAddressTranslater().translate(sa); return translated == null ? sa : translated; } private AsyncInitSession newSession() { SessionManager session = new SessionManager(Cluster.this); sessions.add(session); return session; } boolean removeSession(Session session) { return sessions.remove(session); } void reportLatency(Host host, Statement statement, Exception exception, long latencyNanos) { for (LatencyTracker tracker : trackers) { tracker.update(host, statement, exception, latencyNanos); } } boolean isClosed() { return closeFuture.get() != null; } private CloseFuture close() { CloseFuture future = closeFuture.get(); if (future != null) return future; if (isInit) { logger.debug("Shutting down"); // stop debouncers nodeListRefreshRequestDebouncer.stop(); nodeRefreshRequestDebouncer.stop(); schemaRefreshRequestDebouncer.stop(); // If we're shutting down, there is no point in waiting on scheduled reconnections, nor on notifications // delivery or blocking tasks so we use shutdownNow shutdownNow(reconnectionExecutor); shutdownNow(scheduledTasksExecutor); shutdownNow(blockingExecutor); // but for the worker executor, we want to let submitted tasks finish unless the shutdown is forced. executor.shutdown(); // We also close the metrics if (metrics != null) metrics.shutdown(); // And the load balancing policy LoadBalancingPolicy loadBalancingPolicy = loadBalancingPolicy(); if (loadBalancingPolicy instanceof CloseableLoadBalancingPolicy) ((CloseableLoadBalancingPolicy)loadBalancingPolicy).close(); speculativeRetryPolicy().close(); AddressTranslater translater = configuration.getPolicies().getAddressTranslater(); if (translater instanceof CloseableAddressTranslater) ((CloseableAddressTranslater)translater).close(); for (SchemaChangeListener listener : schemaChangeListeners) { listener.onUnregister(Cluster.this); } // Then we shutdown all connections List<CloseFuture> futures = new ArrayList<CloseFuture>(sessions.size() + 1); futures.add(controlConnection.closeAsync()); for (Session session : sessions) futures.add(session.closeAsync()); future = new ClusterCloseFuture(futures); // The rest will happen asynchronously, when all connections are successfully closed } else { future = CloseFuture.immediateFuture(); } return closeFuture.compareAndSet(null, future) ? future : closeFuture.get(); // We raced, it's ok, return the future that was actually set } private void shutdownNow(ExecutorService executor) { List<Runnable> pendingTasks = executor.shutdownNow(); // If some tasks were submitted to this executor but not yet commenced, make sure the corresponding futures complete for (Runnable pendingTask : pendingTasks) { if (pendingTask instanceof FutureTask<?>) ((FutureTask<?>)pendingTask).cancel(false); } } void logUnsupportedVersionProtocol(Host host) { logger.warn("Detected added or restarted Cassandra host {} but ignoring it since it does not support the version 2 of the native " + "protocol which is currently in use. If you want to force the use of the version 1 of the native protocol, use " + "Cluster.Builder#usingProtocolVersion() when creating the Cluster instance.", host); } void logClusterNameMismatch(Host host, String expectedClusterName, String actualClusterName) { logger.warn("Detected added or restarted Cassandra host {} but ignoring it since its cluster name '{}' does not match the one " + "currently known ({})", host, actualClusterName, expectedClusterName); } public ListenableFuture<?> triggerOnUp(final Host host) { return executor.submit(new ExceptionCatchingRunnable() { @Override public void runMayThrow() throws InterruptedException, ExecutionException { onUp(host, null); } }); } // Use triggerOnUp unless you're sure you want to run this on the current thread. private void onUp(final Host host, Connection reusedConnection) throws InterruptedException, ExecutionException { if (isClosed()) return; if (connectionFactory.protocolVersion == 2 && !supportsProtocolV2(host)) { logUnsupportedVersionProtocol(host); return; } try { boolean locked = host.notificationsLock.tryLock(NOTIF_LOCK_TIMEOUT_SECONDS, TimeUnit.SECONDS); if (!locked) { logger.warn("Could not acquire notifications lock within {} seconds, ignoring UP notification for {}", NOTIF_LOCK_TIMEOUT_SECONDS, host); return; } try { // We don't want to use the public Host.isUp() as this would make us skip the rest for suspected hosts if (host.state == Host.State.UP) return; Host.statesLogger.debug("[{}] marking host UP", host); // If there is a reconnection attempt scheduled for that node, cancel it Future<?> scheduledAttempt = host.reconnectionAttempt.getAndSet(null); if (scheduledAttempt != null) { logger.debug("Cancelling reconnection attempt since node is UP"); scheduledAttempt.cancel(false); } try { if (getCluster().getConfiguration().getQueryOptions().isReprepareOnUp()) reusedConnection = prepareAllQueries(host, reusedConnection); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // Don't propagate because we don't want to prevent other listener to run } catch (UnsupportedProtocolVersionException e) { logUnsupportedVersionProtocol(host); return; } catch (ClusterNameMismatchException e) { logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName); return; } // Session#onUp() expects the load balancing policy to have been updated first, so that // Host distances are up to date. This mean the policy could return the node before the // new pool have been created. This is harmless if there is no prior pool since RequestHandler // will ignore the node, but we do want to make sure there is no prior pool so we don't // query from a pool we will shutdown right away. for (SessionManager s : sessions) s.removePool(host); loadBalancingPolicy().onUp(host); controlConnection.onUp(host); logger.trace("Adding/renewing host pools for newly UP host {}", host); List<ListenableFuture<Boolean>> futures = Lists.newArrayListWithCapacity(sessions.size()); for (SessionManager s : sessions) futures.add(s.forceRenewPool(host, reusedConnection)); try { // Only mark the node up once all session have re-added their pool (if the load-balancing // policy says it should), so that Host.isUp() don't return true before we're reconnected // to the node. List<Boolean> poolCreationResults = Futures.allAsList(futures).get(); // If any of the creation failed, they will have signaled a connection failure // which will trigger a reconnection to the node. So don't bother marking UP. if (Iterables.any(poolCreationResults, Predicates.equalTo(false))) { logger.debug("Connection pool cannot be created, not marking {} UP", host); return; } host.setUp(); for (Host.StateListener listener : listeners) listener.onUp(host); } catch (ExecutionException e) { Throwable t = e.getCause(); // That future is not really supposed to throw unexpected exceptions if (!(t instanceof InterruptedException) && !(t instanceof CancellationException)) logger.error("Unexpected error while marking node UP: while this shouldn't happen, this shouldn't be critical", t); } // Now, check if there isn't pools to create/remove following the addition. // We do that now only so that it's not called before we've set the node up. for (SessionManager s : sessions) s.updateCreatedPools().get(); } finally { host.notificationsLock.unlock(); } } finally { if (reusedConnection != null && !reusedConnection.hasOwner()) reusedConnection.closeAsync(); } } public ListenableFuture<?> triggerOnDown(final Host host, boolean startReconnection) { return triggerOnDown(host, false, startReconnection); } public ListenableFuture<?> triggerOnDown(final Host host, final boolean isHostAddition, final boolean startReconnection) { return executor.submit(new ExceptionCatchingRunnable() { @Override public void runMayThrow() throws InterruptedException, ExecutionException { onDown(host, isHostAddition, startReconnection); } }); } // Use triggerOnDown unless you're sure you want to run this on the current thread. private void onDown(final Host host, final boolean isHostAddition, boolean startReconnection) throws InterruptedException, ExecutionException { if (isClosed()) return; boolean locked = host.notificationsLock.tryLock(NOTIF_LOCK_TIMEOUT_SECONDS, TimeUnit.SECONDS); if (!locked) { logger.warn("Could not acquire notifications lock within {} seconds, ignoring DOWN notification for {}", NOTIF_LOCK_TIMEOUT_SECONDS, host); return; } try { // Note: we don't want to skip that method if !host.isUp() because we set isUp // late in onUp, and so we can rely on isUp if there is an error during onUp. // But if there is a reconnection attempt in progress already, then we know // we've already gone through that method since the last successful onUp(), so // we're good skipping it. if (host.reconnectionAttempt.get() != null) { logger.debug("Aborting onDown because a reconnection is running on DOWN host {}", host); return; } Host.statesLogger.debug("[{}] marking host DOWN", host); // Remember if we care about this node at all. We must call this before // we've signalled the load balancing policy, since most policy will always // IGNORE down nodes anyway. HostDistance distance = loadBalancingPolicy().distance(host); boolean wasUp = host.isUp(); host.setDown(); loadBalancingPolicy().onDown(host); controlConnection.onDown(host); for (SessionManager s : sessions) s.onDown(host); // Contrarily to other actions of that method, there is no reason to notify listeners // unless the host was UP at the beginning of this function since even if a onUp fail // mid-method, listeners won't have been notified of the UP. if (wasUp) { for (Host.StateListener listener : listeners) listener.onDown(host); } // Don't start a reconnection if we ignore the node anyway (JAVA-314) if (distance == HostDistance.IGNORED || !startReconnection) return; startPeriodicReconnectionAttempt(host, isHostAddition); } finally { host.notificationsLock.unlock(); } } void startPeriodicReconnectionAttempt(final Host host, final boolean isHostAddition) { new AbstractReconnectionHandler(host.toString(), reconnectionExecutor, reconnectionPolicy().newSchedule(), host.reconnectionAttempt) { protected Connection tryReconnect() throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException { return connectionFactory.open(host); } protected void onReconnection(Connection connection) { // Make sure we have up-to-date infos on that host before adding it (so we typically // catch that an upgraded node uses a new cassandra version). if (controlConnection.refreshNodeInfo(host)) { logger.debug("Successful reconnection to {}, setting host UP", host); try { if (isHostAddition) onAdd(host, connection); else onUp(host, connection); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (Exception e) { logger.error("Unexpected error while setting node up", e); } } else { logger.debug("Not enough info for {}, ignoring host", host); connection.closeAsync(); } } protected boolean onConnectionException(ConnectionException e, long nextDelayMs) { if (logger.isDebugEnabled()) logger.debug("Failed reconnection to {} ({}), scheduling retry in {} milliseconds", host, e.getMessage(), nextDelayMs); return true; } protected boolean onUnknownException(Exception e, long nextDelayMs) { logger.error(String.format("Unknown error during reconnection to %s, scheduling retry in %d milliseconds", host, nextDelayMs), e); return true; } protected boolean onAuthenticationException(AuthenticationException e, long nextDelayMs) { logger.error(String.format("Authentication error during reconnection to %s, scheduling retry in %d milliseconds", host, nextDelayMs), e); return true; } }.start(); } void startSingleReconnectionAttempt(final Host host) { if (isClosed() || host.isUp()) return; logger.debug("Scheduling one-time reconnection to {}", host); // Setting an initial delay of 0 to start immediately, and all the exception handlers return false to prevent further attempts new AbstractReconnectionHandler(host.toString(), reconnectionExecutor, reconnectionPolicy().newSchedule(), host.reconnectionAttempt, 0) { protected Connection tryReconnect() throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException { return connectionFactory.open(host); } protected void onReconnection(Connection connection) { // Make sure we have up-to-date infos on that host before adding it (so we typically // catch that an upgraded node uses a new cassandra version). if (controlConnection.refreshNodeInfo(host)) { logger.debug("Successful reconnection to {}, setting host UP", host); try { onUp(host, connection); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (Exception e) { logger.error("Unexpected error while setting node up", e); } } else { logger.debug("Not enough info for {}, ignoring host", host); connection.closeAsync(); } } protected boolean onConnectionException(ConnectionException e, long nextDelayMs) { if (logger.isDebugEnabled()) logger.debug("Failed one-time reconnection to {} ({})", host, e.getMessage()); return false; } protected boolean onUnknownException(Exception e, long nextDelayMs) { logger.error(String.format("Unknown error during one-time reconnection to %s", host), e); return false; } protected boolean onAuthenticationException(AuthenticationException e, long nextDelayMs) { logger.error(String.format("Authentication error during one-time reconnection to %s", host), e); return false; } }.start(); } public ListenableFuture<?> triggerOnAdd(final Host host) { return executor.submit(new ExceptionCatchingRunnable() { @Override public void runMayThrow() throws InterruptedException, ExecutionException { onAdd(host, null); } }); } // Use triggerOnAdd unless you're sure you want to run this on the current thread. private void onAdd(final Host host, Connection reusedConnection) throws InterruptedException, ExecutionException { if (isClosed()) return; if (connectionFactory.protocolVersion == 2 && !supportsProtocolV2(host)) { logUnsupportedVersionProtocol(host); return; } try { boolean locked = host.notificationsLock.tryLock(NOTIF_LOCK_TIMEOUT_SECONDS, TimeUnit.SECONDS); if (!locked) { logger.warn("Could not acquire notifications lock within {} seconds, ignoring ADD notification for {}", NOTIF_LOCK_TIMEOUT_SECONDS, host); return; } try { Host.statesLogger.debug("[{}] adding host", host); // Adds to the load balancing first and foremost, as doing so might change the decision // it will make for distance() on that node (not likely but we leave that possibility). // This does mean the policy may start returning that node for query plan, but as long // as no pools have been created (below) this will be ignored by RequestHandler so it's fine. loadBalancingPolicy().onAdd(host); // Next, if the host should be ignored, well, ignore it. if (loadBalancingPolicy().distance(host) == HostDistance.IGNORED) { // We still mark the node UP though as it should be (and notifiy the listeners). // We'll mark it down if we have a notification anyway and we've documented that especially // for IGNORED hosts, the isUp() method was a best effort guess host.setUp(); for (Host.StateListener listener : listeners) listener.onAdd(host); return; } try { reusedConnection = prepareAllQueries(host, reusedConnection); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // Don't propagate because we don't want to prevent other listener to run } catch (UnsupportedProtocolVersionException e) { logUnsupportedVersionProtocol(host); return; } catch (ClusterNameMismatchException e) { logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName); return; } controlConnection.onAdd(host); List<ListenableFuture<Boolean>> futures = Lists.newArrayListWithCapacity(sessions.size()); for (SessionManager s : sessions) futures.add(s.maybeAddPool(host, reusedConnection)); try { // Only mark the node up once all session have added their pool (if the load-balancing // policy says it should), so that Host.isUp() don't return true before we're reconnected // to the node. List<Boolean> poolCreationResults = Futures.allAsList(futures).get(); // If any of the creation failed, they will have signaled a connection failure // which will trigger a reconnection to the node. So don't bother marking UP. if (Iterables.any(poolCreationResults, Predicates.equalTo(false))) { logger.debug("Connection pool cannot be created, not marking {} UP", host); return; } host.setUp(); for (Host.StateListener listener : listeners) listener.onAdd(host); } catch (ExecutionException e) { Throwable t = e.getCause(); // That future is not really supposed to throw unexpected exceptions if (!(t instanceof InterruptedException) && !(t instanceof CancellationException)) logger.error("Unexpected error while adding node: while this shouldn't happen, this shouldn't be critical", t); } // Now, check if there isn't pools to create/remove following the addition. // We do that now only so that it's not called before we've set the node up. for (SessionManager s : sessions) s.updateCreatedPools().get(); } finally { host.notificationsLock.unlock(); } } finally { if (reusedConnection != null && !reusedConnection.hasOwner()) reusedConnection.closeAsync(); } } public ListenableFuture<?> triggerOnRemove(final Host host) { return executor.submit(new ExceptionCatchingRunnable() { @Override public void runMayThrow() throws InterruptedException, ExecutionException { onRemove(host); } }); } // Use triggerOnRemove unless you're sure you want to run this on the current thread. private void onRemove(Host host) throws InterruptedException, ExecutionException { if (isClosed()) return; boolean locked = host.notificationsLock.tryLock(NOTIF_LOCK_TIMEOUT_SECONDS, TimeUnit.SECONDS); if (!locked) { logger.warn("Could not acquire notifications lock within {} seconds, ignoring REMOVE notification for {}", NOTIF_LOCK_TIMEOUT_SECONDS, host); return; } try { host.setDown(); Host.statesLogger.debug("[{}] removing host", host); loadBalancingPolicy().onRemove(host); controlConnection.onRemove(host); for (SessionManager s : sessions) s.onRemove(host); for (Host.StateListener listener : listeners) listener.onRemove(host); } finally { host.notificationsLock.unlock(); } } public boolean signalConnectionFailure(Host host, Connection connection, boolean isHostAddition) { boolean isDown = host.convictionPolicy.signalConnectionFailure(connection); // Don't mark the node down until we've fully initialized the controlConnection as this might mess up with // the protocol detection if (!isFullyInit || isClosed()) return true; if (isDown) triggerOnDown(host, isHostAddition, true); return isDown; } private boolean supportsProtocolV2(Host newHost) { return newHost.getCassandraVersion() == null || newHost.getCassandraVersion().getMajor() >= 2; } public void removeHost(Host host, boolean isInitialConnection) { if (host == null) return; if (metadata.remove(host)) { if (isInitialConnection) { logger.warn("You listed {} in your contact points, but it wasn't found in the control host's system.peers at startup", host); } else { logger.info("Cassandra host {} removed", host); triggerOnRemove(host); } } } public void ensurePoolsSizing() { for (SessionManager session : sessions) { for (HostConnectionPool pool : session.pools.values()) pool.ensureCoreConnections(); } } public PreparedStatement addPrepared(PreparedStatement stmt) { PreparedStatement previous = preparedQueries.putIfAbsent(stmt.getPreparedId().id, stmt); if (previous != null) { logger.warn("Re-preparing already prepared query {}. Please note that preparing the same query more than once is " + "generally an anti-pattern and will likely affect performance. Consider preparing the statement only once.", stmt.getQueryString()); // The one object in the cache will get GCed once it's not referenced by the client anymore since we use a weak reference. // So we need to make sure that the instance we do return to the user is the one that is in the cache. return previous; } return stmt; } /** * @param reusedConnection an existing connection (from a reconnection attempt) that we want to * reuse to prepare the statements (might be null). * @return a connection that the rest of the initialization process can use (it will be made part * of a connection pool). Can be reusedConnection, or one that was open in the method. */ private Connection prepareAllQueries(Host host, Connection reusedConnection) throws InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException { if (preparedQueries.isEmpty()) return reusedConnection; logger.debug("Preparing {} prepared queries on newly up node {}", preparedQueries.size(), host); Connection connection = null; try { connection = (reusedConnection == null) ? connectionFactory.open(host) : reusedConnection; try { controlConnection.waitForSchemaAgreement(); } catch (ExecutionException e) { // As below, just move on } // Furthermore, along with each prepared query we keep the current keyspace at the time of preparation // as we need to make it is the same when we re-prepare on new/restarted nodes. Most query will use the // same keyspace so keeping it each time is slightly wasteful, but this doesn't really matter and is // simpler. Besides, we do avoid in prepareAllQueries to not set the current keyspace more than needed. // We need to make sure we prepared every query with the right current keyspace, i.e. the one originally // used for preparing it. However, since we are likely that all prepared query belong to only a handful // of different keyspace (possibly only one), and to avoid setting the current keyspace more than needed, // we first sort the query per keyspace. SetMultimap<String, String> perKeyspace = HashMultimap.create(); for (PreparedStatement ps : preparedQueries.values()) { // It's possible for a query to not have a current keyspace. But since null doesn't work well as // map keys, we use the empty string instead (that is not a valid keyspace name). String keyspace = ps.getQueryKeyspace() == null ? "" : ps.getQueryKeyspace(); perKeyspace.put(keyspace, ps.getQueryString()); } for (String keyspace : perKeyspace.keySet()) { // Empty string mean no particular keyspace to set if (!keyspace.isEmpty()) connection.setKeyspace(keyspace); List<Connection.Future> futures = new ArrayList<Connection.Future>(preparedQueries.size()); for (String query : perKeyspace.get(keyspace)) { futures.add(connection.write(new Requests.Prepare(query))); } for (Connection.Future future : futures) { try { future.get(); } catch (ExecutionException e) { // This "might" happen if we drop a CF but haven't removed it's prepared queries (which we don't do // currently). It's not a big deal however as if it's a more serious problem it'll show up later when // the query is tried for execution. logger.debug("Unexpected error while preparing queries on new/newly up host", e); } } } return connection; } catch (ConnectionException e) { // Ignore, not a big deal if (connection != null) connection.closeAsync(); return null; } catch (AuthenticationException e) { // That's a bad news, but ignore at this point if (connection != null) connection.closeAsync(); return null; } catch (BusyConnectionException e) { // Ignore, not a big deal // In theory the problem is transient so the connection could be reused later, but if the core pool size is 1 // it's better to close this one so that we start with a fresh connection. if (connection != null) connection.closeAsync(); return null; } } ListenableFuture<Void> submitSchemaRefresh(String keyspace, String table) { SchemaRefreshRequest request = new SchemaRefreshRequest(keyspace, table); logger.trace("Submitting schema refresh: {}", request); return schemaRefreshRequestDebouncer.eventReceived(request); } void submitNodeListRefresh() { logger.trace("Submitting node list and token map refresh"); nodeListRefreshRequestDebouncer.eventReceived(new NodeListRefreshRequest()); } void submitNodeRefresh(InetSocketAddress address, HostEvent eventType) { NodeRefreshRequest request = new NodeRefreshRequest(address, eventType); logger.trace("Submitting node refresh: {}", request); nodeRefreshRequestDebouncer.eventReceived(request); } // refresh the schema using the provided connection, and notice the future with the provided resultset once done public void refreshSchemaAndSignal(final Connection connection, final DefaultResultSetFuture future, final ResultSet rs, final String keyspace, final String table) { if (logger.isDebugEnabled()) logger.debug("Refreshing schema for {}{}", keyspace == null ? "" : keyspace, table == null ? "" : '.' + table); maybeRefreshSchemaAndSignal(connection, future, rs, keyspace, table); } public void waitForSchemaAgreementAndSignal(final Connection connection, final DefaultResultSetFuture future, final ResultSet rs) { maybeRefreshSchemaAndSignal(connection, future, rs, null, null); } private void maybeRefreshSchemaAndSignal(final Connection connection, final DefaultResultSetFuture future, final ResultSet rs, final String keyspace, final String table) { final boolean refreshSchema = (keyspace != null); // if false, only wait for schema agreement executor.submit(new Runnable() { @Override public void run() { boolean schemaInAgreement = false; try { // Before refreshing the schema, wait for schema agreement so // that querying a table just after having created it don't fail. schemaInAgreement = controlConnection.waitForSchemaAgreement(); if (!schemaInAgreement) logger.warn("No schema agreement from live replicas after {} s. The schema may not be up to date on some nodes.", configuration.getProtocolOptions().getMaxSchemaAgreementWaitSeconds()); ListenableFuture<Void> schemaReady = refreshSchema ? submitSchemaRefresh(keyspace, table) : MoreFutures.VOID_SUCCESS; final boolean finalSchemaInAgreement = schemaInAgreement; schemaReady.addListener(new Runnable() { @Override public void run() { rs.getExecutionInfo().setSchemaInAgreement(finalSchemaInAgreement); future.setResult(rs); } }, MoreExecutors.sameThreadExecutor()); } catch (Exception e) { logger.warn("Error while waiting for schema agreement", e); // This is not fatal, complete the future anyway rs.getExecutionInfo().setSchemaInAgreement(schemaInAgreement); future.setResult(rs); } } }); } // Called when some message has been received but has been initiated from the server (streamId < 0). // This is called on an I/O thread, so all blocking operation must be done on an executor. @Override public void handle(Message.Response response) { if (!(response instanceof Responses.Event)) { logger.error("Received an unexpected message from the server: {}", response); return; } final ProtocolEvent event = ((Responses.Event)response).event; logger.debug("Received event {}, scheduling delivery", response); switch (event.type) { case TOPOLOGY_CHANGE: ProtocolEvent.TopologyChange tpc = (ProtocolEvent.TopologyChange)event; InetSocketAddress tpAddr = translateAddress(tpc.node.getAddress()); Host.statesLogger.debug("[{}] received event {}", tpAddr, tpc.change); switch (tpc.change) { case NEW_NODE: submitNodeRefresh(tpAddr, HostEvent.ADDED); break; case REMOVED_NODE: submitNodeRefresh(tpAddr, HostEvent.REMOVED); break; case MOVED_NODE: submitNodeListRefresh(); break; } break; case STATUS_CHANGE: ProtocolEvent.StatusChange stc = (ProtocolEvent.StatusChange)event; InetSocketAddress stAddr = translateAddress(stc.node.getAddress()); Host.statesLogger.debug("[{}] received event {}", stAddr, stc.status); switch (stc.status) { case UP: submitNodeRefresh(stAddr, HostEvent.UP); break; case DOWN: submitNodeRefresh(stAddr, HostEvent.DOWN); break; } break; case SCHEMA_CHANGE: if (!configuration.getQueryOptions().isMetadataEnabled()) return; ProtocolEvent.SchemaChange scc = (ProtocolEvent.SchemaChange)event; switch (scc.change) { case CREATED: if (scc.table.isEmpty()) submitSchemaRefresh(scc.keyspace, null); else submitSchemaRefresh(scc.keyspace, scc.table); break; case DROPPED: if (scc.table.isEmpty()) { final KeyspaceMetadata removed = manager.metadata.removeKeyspace(scc.keyspace); if(removed != null) { executor.submit(new Runnable() { @Override public void run() { manager.metadata.triggerOnKeyspaceRemoved(removed); } }); } } else { KeyspaceMetadata keyspace = manager.metadata.getKeyspaceInternal(scc.keyspace); if (keyspace == null) logger.warn("Received a DROPPED notification for {}.{}, but this keyspace is unknown in our metadata", scc.keyspace, scc.table); else { final TableMetadata removed = keyspace.removeTable(scc.table); if (removed != null) { executor.submit(new Runnable() { @Override public void run() { manager.metadata.triggerOnTableRemoved(removed); } }); } } } break; case UPDATED: if (scc.table.isEmpty()) submitSchemaRefresh(scc.keyspace, null); else submitSchemaRefresh(scc.keyspace, scc.table); break; } break; } } void refreshConnectedHosts() { // Deal first with the control connection: if it's connected to a node that is not LOCAL, try // reconnecting (thus letting the loadBalancingPolicy pick a better node) Host ccHost = controlConnection.connectedHost(); if (ccHost == null || loadBalancingPolicy().distance(ccHost) != HostDistance.LOCAL) controlConnection.triggerReconnect(); try { for (SessionManager s : sessions) Uninterruptibles.getUninterruptibly(s.updateCreatedPools()); } catch (ExecutionException e) { throw DriverThrowables.propagateCause(e); } } void refreshConnectedHost(Host host) { // Deal with the control connection if it was using this host Host ccHost = controlConnection.connectedHost(); if (ccHost == null || ccHost.equals(host) && loadBalancingPolicy().distance(ccHost) != HostDistance.LOCAL) controlConnection.triggerReconnect(); for (SessionManager s : sessions) s.updateCreatedPools(host); } private class ClusterCloseFuture extends CloseFuture.Forwarding { ClusterCloseFuture(List<CloseFuture> futures) { super(futures); } @Override public CloseFuture force() { // The only ExecutorService we haven't forced yet is executor shutdownNow(executor); return super.force(); } @Override protected void onFuturesDone() { /* * When we reach this, all sessions should be shutdown. We've also started a shutdown * of the thread pools used by this object. Remains 2 things before marking the shutdown * as done: * 1) we need to wait for the completion of the shutdown of the Cluster threads pools. * 2) we need to shutdown the Connection.Factory, i.e. the executors used by Netty. * But at least for 2), we must not do it on the current thread because that could be * a netty worker, which we're going to shutdown. So creates some thread for that. */ (new Thread("Shutdown-checker") { public void run() { // Just wait indefinitely on the the completion of the thread pools. Provided the user // call force(), we'll never really block forever. try { reconnectionExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS); scheduledTasksExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS); executor.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS); blockingExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS); // Some of the jobs on the executors can be doing query stuff, so close the // connectionFactory at the very last connectionFactory.shutdown(); reaper.shutdown(); set(null); } catch (InterruptedException e) { Thread.currentThread().interrupt(); setException(e); } } }).start(); } } private class CleanupIdleConnectionsTask implements Runnable { @Override public void run() { try { long now = System.currentTimeMillis(); for (SessionManager session : sessions) { session.cleanupIdleConnections(now); } } catch (Exception e) { logger.warn("Error while trashing idle connections", e); } } } private class SchemaRefreshRequest { private final String keyspace; private final String table; SchemaRefreshRequest(String keyspace, String table) { this.keyspace = keyspace; this.table = table; } /** * Coalesce schema refresh requests. * The algorithm is simple: if more than 2 keyspaces * need refresh, then refresh the entire schema; * otherwise if more than 2 tables in the same keyspace * need refresh, then refresh the entire keyspace. * * @param that the other request to merge with the current one. * @return A coalesced request */ SchemaRefreshRequest coalesce(SchemaRefreshRequest that) { if(this.keyspace == null || that.keyspace == null) return new SchemaRefreshRequest(null, null); if(!this.keyspace.equals(that.keyspace)) return new SchemaRefreshRequest(null, null); if(this.table == null || that.table == null) return new SchemaRefreshRequest(keyspace, null); if(!this.table.equals(that.table)) return new SchemaRefreshRequest(keyspace, null); return this; } @Override public String toString() { if(this.keyspace == null) return "Refresh ALL"; if(this.table == null) return "Refresh keyspace " + keyspace; return "Refresh keyspace " + keyspace + " table " + table; } } private class SchemaRefreshRequestDeliveryCallback implements EventDebouncer.DeliveryCallback<SchemaRefreshRequest> { @Override public ListenableFuture<?> deliver(final List<SchemaRefreshRequest> events) { return executor.submit(new ExceptionCatchingRunnable() { @Override public void runMayThrow() throws InterruptedException, ExecutionException { SchemaRefreshRequest coalesced = null; for (SchemaRefreshRequest request : events) { coalesced = coalesced == null ? request : coalesced.coalesce(request); } assert coalesced != null; logger.trace("Coalesced schema refresh request: {}", coalesced); controlConnection.refreshSchema(coalesced.keyspace, coalesced.table); } }); } } private class NodeRefreshRequest { private final InetSocketAddress address; private final HostEvent eventType; private NodeRefreshRequest(InetSocketAddress address, HostEvent eventType) { this.address = address; this.eventType = eventType; } @Override public String toString() { return address + " " + eventType; } } private class NodeRefreshRequestDeliveryCallback implements EventDebouncer.DeliveryCallback<NodeRefreshRequest> { @Override public ListenableFuture<?> deliver(List<NodeRefreshRequest> events) { Map<InetSocketAddress, HostEvent> hosts = new HashMap<InetSocketAddress, HostEvent>(); // only keep the last event for each host for (NodeRefreshRequest req : events) { hosts.put(req.address, req.eventType); } List<ListenableFuture<?>> futures = new ArrayList<ListenableFuture<?>>(hosts.size()); for (final Entry<InetSocketAddress, HostEvent> entry : hosts.entrySet()) { InetSocketAddress address = entry.getKey(); HostEvent eventType = entry.getValue(); switch (eventType) { case UP: Host upHost = metadata.getHost(address); if (upHost == null) { upHost = metadata.add(address); // If upHost is still null, it means we didn't know about it the line before but // got beaten at adding it to the metadata by another thread. In that case, it's // fine to let the other thread win and ignore the notification here if (upHost == null) continue; futures.add(schedule(hostAdded(upHost))); } else { futures.add(schedule(hostUp(upHost))); } break; case ADDED: Host newHost = metadata.add(address); if (newHost != null) { futures.add(schedule(hostAdded(newHost))); } else { // If host already existed, retrieve it and check its state, if it's not up schedule a // hostUp event. Host existingHost = metadata.getHost(address); if(!existingHost.isUp()) futures.add(schedule(hostUp(existingHost))); } break; case DOWN: // Note that there is a slight risk we can receive the event late and thus // mark the host down even though we already had reconnected successfully. // But it is unlikely, and don't have too much consequence since we'll try reconnecting // right away, so we favor the detection to make the Host.isUp method more reliable. Host downHost = metadata.getHost(address); if (downHost != null) futures.add(execute(hostDown(downHost))); break; case REMOVED: Host removedHost = metadata.getHost(address); if (removedHost != null) futures.add(execute(hostRemoved(removedHost))); break; } } return Futures.allAsList(futures); } private ListenableFuture<?> execute(ExceptionCatchingRunnable task) { return executor.submit(task); } private ListenableFuture<?> schedule(final ExceptionCatchingRunnable task) { // Cassandra tends to send notifications for new/up nodes a bit early (it is triggered once // gossip is up, but that is before the client-side server is up), so we add a delay // (otherwise the connection will likely fail and have to be retry which is wasteful). This // probably should be fixed C* side, after which we'll be able to remove this. final SettableFuture<?> future = SettableFuture.create(); scheduledTasksExecutor.schedule(new ExceptionCatchingRunnable() { public void runMayThrow() throws Exception { ListenableFuture<?> f = execute(task); Futures.addCallback(f, new FutureCallback<Object>() { @Override public void onSuccess(Object result) { future.set(null); } @Override public void onFailure(Throwable t) { future.setException(t); } }); } }, NEW_NODE_DELAY_SECONDS, TimeUnit.SECONDS); return future; } // Make sure we call controlConnection.refreshNodeInfo(host) // so that we have up-to-date infos on that host before adding it (so we typically // catch that an upgraded node uses a new cassandra version). private ExceptionCatchingRunnable hostAdded(final Host host) { return new ExceptionCatchingRunnable() { @Override public void runMayThrow() throws Exception { if (controlConnection.refreshNodeInfo(host)) { onAdd(host, null); } else { logger.debug("Not enough info for {}, ignoring host", host); } } }; } private ExceptionCatchingRunnable hostUp(final Host host) { return new ExceptionCatchingRunnable() { @Override public void runMayThrow() throws Exception { if (controlConnection.refreshNodeInfo(host)) { onUp(host, null); } else { logger.debug("Not enough info for {}, ignoring host", host); } } }; } private ExceptionCatchingRunnable hostDown(final Host host) { return new ExceptionCatchingRunnable() { @Override public void runMayThrow() throws Exception { if (controlConnection.refreshNodeInfo(host)) { onDown(host, false, true); } else { logger.debug("Not enough info for {}, ignoring host", host); } } }; } private ExceptionCatchingRunnable hostRemoved(final Host host) { return new ExceptionCatchingRunnable() { @Override public void runMayThrow() throws Exception { if (metadata.remove(host)) { logger.info("Cassandra host {} removed", host); onRemove(host); } } }; } } private class NodeListRefreshRequest { @Override public String toString() { return "Refresh node list and token map"; } } private class NodeListRefreshRequestDeliveryCallback implements EventDebouncer.DeliveryCallback<NodeListRefreshRequest> { @Override public ListenableFuture<?> deliver(List<NodeListRefreshRequest> events) { // The number of received requests does not matter // as long as one request is made, refresh the entire node list return executor.submit(new ExceptionCatchingRunnable() { @Override public void runMayThrow() throws InterruptedException, ExecutionException { controlConnection.refreshNodeListAndTokenMap(); } }); } } } private enum HostEvent { UP, DOWN, ADDED, REMOVED } /** * Periodically ensures that closed connections are properly terminated once they have no more pending requests. * * This is normally done when the connection errors out, or when the last request is processed; this class acts as * a last-effort protection since unterminated connections can lead to deadlocks. If it terminates a connection, * this indicates a bug; warnings are logged so that this can be reported. * * @see Connection#tryTerminate(boolean) */ static class ConnectionReaper { private static final int INTERVAL_MS = 15000; private final ScheduledExecutorService executor; @VisibleForTesting final Map<Connection, Long> connections = new ConcurrentHashMap<Connection, Long>(); private volatile boolean shutdown; private final Runnable reaperTask = new Runnable() { @Override public void run() { long now = System.currentTimeMillis(); Iterator<Entry<Connection, Long>> iterator = connections.entrySet().iterator(); while (iterator.hasNext()) { Entry<Connection, Long> entry = iterator.next(); Connection connection = entry.getKey(); Long terminateTime = entry.getValue(); if (terminateTime <= now) { boolean terminated = connection.tryTerminate(true); if (terminated) iterator.remove(); } } } }; ConnectionReaper(Cluster.Manager manager) { executor = Executors.newScheduledThreadPool(1, manager.threadFactory("connection-reaper")); executor.scheduleWithFixedDelay(reaperTask, INTERVAL_MS, INTERVAL_MS, TimeUnit.MILLISECONDS); } void register(Connection connection, long terminateTime) { if (shutdown) { // This should not happen since the reaper is shut down after all sessions. logger.warn("Connection registered after reaper shutdown: {}", connection); connection.tryTerminate(true); } else { connections.put(connection, terminateTime); } } void shutdown() { shutdown = true; // Force shutdown to avoid waiting for the interval, and run the task manually one last time executor.shutdownNow(); reaperTask.run(); } } }
45.789048
213
0.583424
882f9712d5afba155f865e27e1ec384a268de152
3,065
package com.workflowconversion.knime2grid.utils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.Validate; import com.workflowconversion.knime2grid.resource.Application; import com.workflowconversion.knime2grid.resource.Queue; import com.workflowconversion.knime2grid.resource.Resource; /** * Convenience methods to generate system-wide keys for applications, queues. * * @author delagarza * */ public class KeyUtils { /** * Generates a key for the given application. * * @param application * the application. * @return A key, not necessarily system-wide, that represents the given application. */ public static String generate(final Application application) { Validate.notNull(application, "application cannot be null, this seems to be a coding problem and should be reported."); return generateApplicationKey(application.getName(), application.getVersion(), application.getPath()); } /** * Generates a key for an application. * * @param name * the name. * @param version * the version. * @param path * the path. * @return A key, not necessarily system-wide, for an application represented by the given fields. */ public static String generateApplicationKey(final String name, final String version, final String path) { return "application:name=" + StringUtils.trimToEmpty(name) + "_version=" + StringUtils.trimToEmpty(version) + "_path=" + StringUtils.trimToEmpty(path); } /** * Generates a key for the given resource. * * @param resource * the resource. * @return A system-wide key that represents the given resource. */ public static String generate(final Resource resource) { Validate.notNull(resource, "resource cannot be null, this seems to be a coding problem and should be reported."); return generateResourceKey(resource.getName(), resource.getType()); } /** * Generates a system-wide key for the given resource fields. * * @param name * the resource name. * @param type * the resource type. * @return a system-wide key for a resource represented by the given fields. */ public static String generateResourceKey(final String name, final String type) { return "resource:name=" + StringUtils.trimToEmpty(name) + "_type=" + StringUtils.trimToEmpty(type); } /** * Generates a key for the given queue. * * @param queue * the queue. * @return a key, not necessarily system-wide, for the given queue. */ public static String generate(final Queue queue) { Validate.notNull(queue, "queue cannot be null, this seems to be a coding problem and should be reported."); return generateQueueKey(queue.getName()); } /** * Generates a queue for a queue represented by the given fields. * * @param name * the name. * @return a key, not necessarily system-wide, for a queue. */ public static String generateQueueKey(final String name) { return "queue:name=" + StringUtils.trimToEmpty(name); } }
31.927083
109
0.700489
ed26c89881a5d22d4a34dbf3cc05df13fe89b675
3,771
/* * Copyright 2014-2021 JKOOL, LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.jkoolcloud.tnt4j.sink.impl; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import com.jkoolcloud.tnt4j.config.ConfigException; import com.jkoolcloud.tnt4j.config.Configurable; import com.jkoolcloud.tnt4j.utils.Utils; /** * <p> * A pooled logger factory manages access to {@link PooledLogger} instances. * </p> * * @see PooledLogger * * @version $Revision: 1 $ * */ public class PooledLoggerFactoryImpl implements PooledLoggerFactory, Configurable { public static final String DEFAULT_POOL_NAME = "default"; private static final int MAX_POOL_SIZE = Integer.getInteger("tnt4j.pooled.logger.pool", 4); private static final int MAX_CAPACITY = Integer.getInteger("tnt4j.pooled.logger.capacity", 10000); private static final long RETRY_INTERVAL = Long.getLong("tnt4j.pooled.logger.retry.interval", TimeUnit.SECONDS.toMillis(5)); private static final boolean DROP_ON_EXCEPTION = Boolean.getBoolean("tnt4j.pooled.logger.drop.on.error"); private static final ConcurrentMap<String, PooledLogger> POOLED_LOGGERS = new ConcurrentHashMap<>(); int poolSize = MAX_POOL_SIZE; int capacity = MAX_CAPACITY; long retryInterval = RETRY_INTERVAL; boolean dropOnError = DROP_ON_EXCEPTION; String poolName = DEFAULT_POOL_NAME; protected Map<String, ?> props; /** * Create a default pooled logger factory. */ public PooledLoggerFactoryImpl() { } /** * Obtain an instance of pooled logger, which allows logging of events asynchronously by a thread pool. * * @param pName * pool name * @return pooled logger instance * @see PooledLogger */ public static PooledLogger getPooledLogger(String pName) { return POOLED_LOGGERS.get(pName); } @Override public PooledLogger getPooledLogger() { return POOLED_LOGGERS.get(poolName); } @Override public Map<String, PooledLogger> getPooledLoggers() { Map<String, PooledLogger> copy = new HashMap<>(POOLED_LOGGERS); return copy; } @Override public Map<String, ?> getConfiguration() { return props; } @Override public void setConfiguration(Map<String, ?> settings) throws ConfigException { this.props = settings; // obtain all optional attributes poolName = Utils.getString("Name", settings, DEFAULT_POOL_NAME); poolSize = Utils.getInt("Size", settings, MAX_POOL_SIZE); capacity = Utils.getInt("Capacity", settings, MAX_CAPACITY); retryInterval = Utils.getLong("RetryInterval", settings, RETRY_INTERVAL); dropOnError = Utils.getBoolean("DropOnError", settings, DROP_ON_EXCEPTION); // create and register pooled logger instance if not yet available PooledLogger pooledLogger = new PooledLogger(poolName, poolSize, capacity); pooledLogger.dropOnError(dropOnError); pooledLogger.setRetryInterval(retryInterval); if (POOLED_LOGGERS.putIfAbsent(poolName, pooledLogger) == null) { pooledLogger.start(); } } /** * Shuts down all pooled loggers. */ public static void shutdownAllLoggers() { for (PooledLogger pl : POOLED_LOGGERS.values()) { pl.shutdown(null); } POOLED_LOGGERS.clear(); } }
31.689076
106
0.750994
0672a8c1682bf4b144df63d76e9db87e54390e5f
1,280
package com.ffmpeg.common; import com.ffmpeg.common.audio.AudioOperation; import com.ffmpeg.common.response.Result; import com.ffmpeg.common.video.VideoOperation; import org.junit.Test; /** * @auther alan.chen * @time 2019/9/17 5:40 PM */ public class AudioTest { private static final String ffmpegEXE = "/Users/alan.chen/Documents/notes/ffmpeg"; @Test public void audioScaleTest() { String inputPath = "/Users/alan.chen/Documents/notes/VideoTest/2222.mp4"; String outPutPath = "/Users/alan.chen/Documents/notes/VideoTest/1/out.mp4"; VideoOperation ffmpeg = VideoOperation.builder(ffmpegEXE); Result result = ffmpeg.videoScale(inputPath,"1080","1920", outPutPath); System.out.println(result.getCode()); System.out.println(result.getErrMessage()); } @Test public void audioFormatTest() { String inputPath = "/Users/alan.chen/Documents/notes/VideoTest/amr.amr"; String outPutPath = "/Users/alan.chen/Documents/notes/VideoTest/mp3.mp3"; AudioOperation ffmpeg = AudioOperation.builder(ffmpegEXE); Result result = ffmpeg.transFormatToMp3Audio(inputPath, outPutPath); System.out.println(result.getCode()); System.out.println(result.getErrMessage()); } }
35.555556
86
0.703906
a6e817a5ec20fc3f586c8cba8ef85fb297fa9241
1,924
package com.local.problem; import com.local.core.Problem; import org.apache.commons.math3.linear.Array2DRowRealMatrix; import org.apache.commons.math3.linear.ArrayRealVector; import org.apache.commons.math3.linear.RealMatrix; import org.apache.commons.math3.linear.RealVector; public class VoidFormationProblem implements Problem { private final double densityScale = 1.e-3; private final double delta = 1.e-3; @Override public RealVector computeFlux(RealVector value) { final double density = value.getEntry(0); final double velocity = value.getEntry(1); ArrayRealVector result = new ArrayRealVector(2); result.setEntry(0, density * velocity); result.setEntry(1, delta * Math.log(density)); return result; } @Override public RealMatrix computeJacobian(RealVector value) { final double density = value.getEntry(0); final double velocity = value.getEntry(1); Array2DRowRealMatrix result = new Array2DRowRealMatrix(2, 2); result.setEntry(0, 0, density); result.setEntry(0, 1, velocity); result.setEntry(1, 0, delta / density); result.setEntry(1, 1, 0.); return result; } @Override public RealVector getInitialValue(Double position) { RealVector value = new ArrayRealVector(2); double initialValue = densityScale + densityScale * 10. * getInitialStepDistribution(position); value.setEntry(0, initialValue); value.setEntry(1, 0.); return value; } private double getInitialStepDistribution(double position) { if (position < 0.5) return 1.; return 0.; } @Override public Double getLeftBoundary() { return 0.; } @Override public Double getRightBoundary() { return 4.; } @Override public Integer getResolution() { return 200; } }
29.151515
103
0.660083
a8ea530ec1b7bd22afe846bc07442c8c7f4fe6d7
1,123
package io.cloudevents.v03; import java.util.Collection; import java.util.Objects; import io.cloudevents.Attributes; import io.cloudevents.CloudEvent; import io.cloudevents.extensions.ExtensionFormat; import io.cloudevents.fun.ExtensionFormatAccessor; /** * * @author fabiojose * */ public class Accessor { private Accessor() {} /** * To get access the set of {@link ExtensionFormat} inside the * event. * * <br> * <br> * This method follow the signature of * {@link ExtensionFormatAccessor#extensionsOf(CloudEvent)} * * @param cloudEvent * @throws IllegalArgumentException When argument is not an instance * of {@link CloudEventImpl} */ @SuppressWarnings({"unchecked", "rawtypes"}) public static <A extends Attributes, T> Collection<ExtensionFormat> extensionsOf(CloudEvent<A, T> cloudEvent) { Objects.requireNonNull(cloudEvent); if(cloudEvent instanceof CloudEventImpl) { CloudEventImpl impl = (CloudEventImpl)cloudEvent; return impl.getExtensionsFormats(); } throw new IllegalArgumentException("Invalid instance type: " + cloudEvent.getClass()); } }
24.413043
69
0.731968
ca897dda3a3c7899e9d88398d894cd50e018fe53
284
package decorator.decorator1; import decorator.decorator1.abstracts.Beverage; public class Esspresso extends Beverage { public static final double COST = 1.99; public Esspresso() { super("Esspresso"); } public double cost() { return COST; } }
16.705882
47
0.661972
26e177458c6e145a610f52d93bed9930a31d8c88
337
package net.gegy1000.psf.server.api; import javax.annotation.ParametersAreNonnullByDefault; import net.minecraft.block.Block; import net.minecraft.item.ItemBlock; @ParametersAreNonnullByDefault public interface RegisterItemBlock { default ItemBlock createItemBlock(Block block) { return new ItemBlock(block); } }
22.466667
54
0.783383
9d69cee4d0cda1092de5f9e6ceecaafc0f389850
305
package com.example.springboot.demospringbootn11.dao; import com.example.springboot.demospringbootn11.entity.Urun; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface UrunDao extends CrudRepository<Urun,Long> { }
21.785714
60
0.842623
aa4826441afa3b60ecf6a64903a6422d159a5666
8,369
package com.db.chart.renderer; import android.graphics.Canvas; import com.db.chart.model.ChartEntry; import com.db.chart.model.ChartSet; import com.db.chart.view.ChartView.Style; import com.google.android.flexbox.FlexItem; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Iterator; public abstract class AxisRenderer { private static final float DEFAULT_STEPS_NUMBER = 3.0f; float axisPosition; boolean handleValues; ArrayList<String> labels; ArrayList<Float> labelsPos; float labelsStaticPos; ArrayList<Float> labelsValues; float mInnerChartBottom; float mInnerChartLeft; float mInnerChartRight; float mInnerChartTop; float mandatoryBorderSpacing; private float maxLabelValue; float minLabelValue; float screenStep; private float step; Style style; public enum LabelPosition { NONE, OUTSIDE, INSIDE } protected abstract float defineAxisPosition(); protected abstract float defineStaticLabelsPosition(float f, int i); protected abstract void draw(Canvas canvas); protected abstract float measureInnerChartBottom(int i); protected abstract float measureInnerChartLeft(int i); protected abstract float measureInnerChartRight(int i); protected abstract float measureInnerChartTop(int i); public abstract float parsePos(int i, double d); AxisRenderer() { reset(); } public void init(ArrayList<ChartSet> data, Style style) { if (this.handleValues) { if (this.minLabelValue == 0.0f && this.maxLabelValue == 0.0f) { float[] borders; if (hasStep()) { borders = findBorders(data, this.step); } else { borders = findBorders(data); } this.minLabelValue = borders[0]; this.maxLabelValue = borders[1]; } if (!hasStep()) { setBorderValues(this.minLabelValue, this.maxLabelValue); } this.labelsValues = calculateValues(this.minLabelValue, this.maxLabelValue, this.step); this.labels = convertToLabelsFormat(this.labelsValues, style.getLabelsFormat()); } else { this.labels = extractLabels(data); } this.style = style; } void dispose() { this.axisPosition = defineAxisPosition(); this.labelsStaticPos = defineStaticLabelsPosition(this.axisPosition, this.style.getAxisLabelsSpacing()); } public void measure(int left, int top, int right, int bottom) { this.mInnerChartLeft = measureInnerChartLeft(left); this.mInnerChartTop = measureInnerChartTop(top); this.mInnerChartRight = measureInnerChartRight(right); this.mInnerChartBottom = measureInnerChartBottom(bottom); } public void reset() { this.mandatoryBorderSpacing = 0.0f; this.step = FlexItem.FLEX_BASIS_PERCENT_DEFAULT; this.labelsStaticPos = 0.0f; this.axisPosition = 0.0f; this.minLabelValue = 0.0f; this.maxLabelValue = 0.0f; this.handleValues = false; } void defineMandatoryBorderSpacing(float innerStart, float innerEnd) { if (this.mandatoryBorderSpacing == FlexItem.FLEX_SHRINK_DEFAULT) { this.mandatoryBorderSpacing = (((innerEnd - innerStart) - ((float) (this.style.getAxisBorderSpacing() * 2))) / ((float) this.labels.size())) / 2.0f; } } void defineLabelsPosition(float innerStart, float innerEnd) { int nLabels = this.labels.size(); this.screenStep = ((((innerEnd - innerStart) - ((float) this.style.getAxisTopSpacing())) - ((float) (this.style.getAxisBorderSpacing() * 2))) - (this.mandatoryBorderSpacing * 2.0f)) / ((float) (nLabels - 1)); this.labelsPos = new ArrayList(nLabels); float currPos = (((float) this.style.getAxisBorderSpacing()) + innerStart) + this.mandatoryBorderSpacing; for (int i = 0; i < nLabels; i++) { this.labelsPos.add(Float.valueOf(currPos)); currPos += this.screenStep; } } ArrayList<String> convertToLabelsFormat(ArrayList<Float> values, DecimalFormat format) { int size = values.size(); ArrayList<String> result = new ArrayList(size); for (int i = 0; i < size; i++) { result.add(format.format(values.get(i))); } return result; } ArrayList<String> extractLabels(ArrayList<ChartSet> sets) { int size = ((ChartSet) sets.get(0)).size(); ArrayList<String> result = new ArrayList(size); for (int i = 0; i < size; i++) { result.add(((ChartSet) sets.get(0)).getLabel(i)); } return result; } float[] findBorders(ArrayList<ChartSet> sets) { float max = -2.14748365E9f; float min = 2.14748365E9f; Iterator it = sets.iterator(); while (it.hasNext()) { Iterator it2 = ((ChartSet) it.next()).getEntries().iterator(); while (it2.hasNext()) { ChartEntry e = (ChartEntry) it2.next(); if (e.getValue() >= max) { max = e.getValue(); } if (e.getValue() <= min) { min = e.getValue(); } } } if (max < 0.0f) { max = 0.0f; } if (min > 0.0f) { min = 0.0f; } if (min == max) { max += FlexItem.FLEX_SHRINK_DEFAULT; } return new float[]{min, max}; } float[] findBorders(ArrayList<ChartSet> sets, float step) { float[] borders = findBorders(sets); while ((borders[1] - borders[0]) % step != 0.0f) { borders[1] = borders[1] + FlexItem.FLEX_SHRINK_DEFAULT; } return borders; } ArrayList<Float> calculateValues(float min, float max, float step) { ArrayList<Float> result = new ArrayList(); float pos = min; while (pos <= max) { result.add(Float.valueOf(pos)); pos += step; } if (((Float) result.get(result.size() - 1)).floatValue() < max) { result.add(Float.valueOf(pos)); } return result; } public float getInnerChartLeft() { return this.mInnerChartLeft; } public float getInnerChartTop() { return this.mInnerChartTop; } public float getInnerChartRight() { return this.mInnerChartRight; } public float getInnerChartBottom() { return this.mInnerChartBottom; } public float[] getInnerChartBounds() { return new float[]{this.mInnerChartLeft, this.mInnerChartTop, this.mInnerChartRight, this.mInnerChartBottom}; } public float getStep() { return this.step; } public void setStep(int step) { this.step = (float) step; } public float getBorderMaximumValue() { return this.maxLabelValue; } public float getBorderMinimumValue() { return this.minLabelValue; } public boolean hasMandatoryBorderSpacing() { return this.mandatoryBorderSpacing == FlexItem.FLEX_SHRINK_DEFAULT; } boolean hasStep() { return this.step != FlexItem.FLEX_BASIS_PERCENT_DEFAULT; } public void setHandleValues(boolean bool) { this.handleValues = bool; } public void setMandatoryBorderSpacing(boolean bool) { this.mandatoryBorderSpacing = bool ? FlexItem.FLEX_SHRINK_DEFAULT : 0.0f; } public void setInnerChartBounds(float left, float top, float right, float bottom) { this.mInnerChartLeft = left; this.mInnerChartTop = top; this.mInnerChartRight = right; this.mInnerChartBottom = bottom; } public void setBorderValues(float min, float max, float step) { if (min >= max) { throw new IllegalArgumentException("Minimum border value must be greater than maximum values"); } this.step = step; this.maxLabelValue = max; this.minLabelValue = min; } public void setBorderValues(float min, float max) { if (!hasStep()) { this.step = (max - min) / DEFAULT_STEPS_NUMBER; } setBorderValues(min, max, this.step); } }
32.065134
216
0.608555
950e02775fd15f49017900699c1098a900a06706
476
package br.com.desafiotecnico.model; import java.util.StringTokenizer; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Getter @Setter @NoArgsConstructor public class Item { int itemId; int itemQuant; double itemPrice; public Item(StringTokenizer st) { this.itemId = Integer.valueOf((String) st.nextElement()); this.itemQuant = Integer.valueOf((String)st.nextElement()); this.itemPrice = new Double((String) st.nextElement()); } }
20.695652
61
0.760504
10cb72b981ba2942e236a1554ab8d38da560594c
1,582
package ca.uhn.fhir.jpa.subscription.resthook; /*- * #%L * HAPI FHIR JPA Server * %% * Copyright (C) 2014 - 2018 University Health Network * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import ca.uhn.fhir.jpa.subscription.BaseSubscriptionInterceptor; public class SubscriptionRestHookInterceptor extends BaseSubscriptionInterceptor { private SubscriptionDeliveringRestHookSubscriber mySubscriptionDeliverySubscriber; @Override protected void registerDeliverySubscriber() { if (mySubscriptionDeliverySubscriber == null) { mySubscriptionDeliverySubscriber = new SubscriptionDeliveringRestHookSubscriber(getSubscriptionDao(), getChannelType(), this); } getDeliveryChannel().subscribe(mySubscriptionDeliverySubscriber); } @Override public org.hl7.fhir.r4.model.Subscription.SubscriptionChannelType getChannelType() { return org.hl7.fhir.r4.model.Subscription.SubscriptionChannelType.RESTHOOK; } @Override protected void unregisterDeliverySubscriber() { getDeliveryChannel().unsubscribe(mySubscriptionDeliverySubscriber); } }
34.391304
129
0.782554
e3e090b0784e28a1ac88516d8fc1731df134091d
706
package com.github.cc3002.citricliquid.phases.states; import com.github.cc3002.citricjuice.model.Player; import com.github.cc3002.citricjuice.model.board.IPanel; import com.github.cc3002.citricliquid.phases.State; /** * Class that represents a state in the game. * * @author Ignacio Diaz Lara. */ public class ActivatingPanelEffect extends State { /** * The panel effects activates. Then goes to * next phase CheckingAWinner. */ @Override public void panelEffectActivates(IPanel panel, Player player) { panel.activatedBy(player); this.changeState(new CheckingAWinner()); } @Override public boolean isActivatingPanelEffect() { return true; } }
26.148148
67
0.719547
bb60896e7677f5a254632654a3a07cf3bc5476d3
732
/* * * * ***************************************************************************** * * Copyright (C) 2020 Testsigma Technologies Inc. * * All rights reserved. * * **************************************************************************** * */ package com.testsigma.dto; import com.testsigma.model.ScheduleStatus; import com.testsigma.model.ScheduleType; import lombok.Data; import java.sql.Timestamp; @Data public class ScheduleTestPlanDTO { private Long id; private Long testPlanId; private String name; private String comments; private ScheduleType scheduleType; private String scheduleTime; private Timestamp createdDate; private Timestamp updatedDate; private ScheduleStatus status; }
23.612903
83
0.587432
be7cd92bc522f4a6e8b85e6fb4aea6e198a83d1e
6,818
/* * Copyright 2012 The Netty Project * * The Netty Project 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.jboss.netty.channel.local; import static org.jboss.netty.channel.Channels.*; import java.nio.channels.ClosedChannelException; import java.nio.channels.NotYetConnectedException; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicInteger; import org.jboss.netty.channel.AbstractChannel; import org.jboss.netty.channel.ChannelConfig; import org.jboss.netty.channel.ChannelException; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelFutureListener; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelSink; import org.jboss.netty.channel.DefaultChannelConfig; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.util.internal.ThreadLocalBoolean; /** */ final class DefaultLocalChannel extends AbstractChannel implements LocalChannel { // TODO Move the state management up to AbstractChannel to remove duplication. private static final int ST_OPEN = 0; private static final int ST_BOUND = 1; private static final int ST_CONNECTED = 2; private static final int ST_CLOSED = -1; final AtomicInteger state = new AtomicInteger(ST_OPEN); private final ChannelConfig config; private final ThreadLocalBoolean delivering = new ThreadLocalBoolean(); final Queue<MessageEvent> writeBuffer = new ConcurrentLinkedQueue<MessageEvent>(); volatile DefaultLocalChannel pairedChannel; volatile LocalAddress localAddress; volatile LocalAddress remoteAddress; DefaultLocalChannel( LocalServerChannel parent, ChannelFactory factory, ChannelPipeline pipeline, ChannelSink sink, DefaultLocalChannel pairedChannel) { super(parent, factory, pipeline, sink); this.pairedChannel = pairedChannel; config = new DefaultChannelConfig(); // TODO Move the state variable to AbstractChannel so that we don't need // to add many listeners. getCloseFuture().addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { state.set(ST_CLOSED); } }); fireChannelOpen(this); } public ChannelConfig getConfig() { return config; } @Override public boolean isOpen() { return state.get() >= ST_OPEN; } public boolean isBound() { return state.get() >= ST_BOUND; } public boolean isConnected() { return state.get() == ST_CONNECTED; } void setBound() throws ClosedChannelException { if (!state.compareAndSet(ST_OPEN, ST_BOUND)) { switch (state.get()) { case ST_CLOSED: throw new ClosedChannelException(); default: throw new ChannelException("already bound"); } } } void setConnected() { if (state.get() != ST_CLOSED) { state.set(ST_CONNECTED); } } @Override protected boolean setClosed() { return super.setClosed(); } public LocalAddress getLocalAddress() { return localAddress; } public LocalAddress getRemoteAddress() { return remoteAddress; } void closeNow(ChannelFuture future) { LocalAddress localAddress = this.localAddress; try { // Close the self. if (!setClosed()) { return; } DefaultLocalChannel pairedChannel = this.pairedChannel; if (pairedChannel != null) { this.pairedChannel = null; fireChannelDisconnected(this); fireChannelUnbound(this); } fireChannelClosed(this); // Close the peer. if (pairedChannel == null || !pairedChannel.setClosed()) { return; } DefaultLocalChannel me = pairedChannel.pairedChannel; if (me != null) { pairedChannel.pairedChannel = null; fireChannelDisconnected(pairedChannel); fireChannelUnbound(pairedChannel); } fireChannelClosed(pairedChannel); } finally { future.setSuccess(); if (localAddress != null && getParent() == null) { LocalChannelRegistry.unregister(localAddress); } } } void flushWriteBuffer() { DefaultLocalChannel pairedChannel = this.pairedChannel; if (pairedChannel != null) { if (pairedChannel.isConnected()) { // Channel is open and connected and channelConnected event has // been fired. if (!delivering.get()) { delivering.set(true); try { for (;;) { MessageEvent e = writeBuffer.poll(); if (e == null) { break; } fireMessageReceived(pairedChannel, e.getMessage()); e.getFuture().setSuccess(); fireWriteComplete(this, 1); } } finally { delivering.set(false); } } } else { // Channel is open and connected but channelConnected event has // not been fired yet. } } else { // Channel is closed or not connected yet - notify as failures. Exception cause; if (isOpen()) { cause = new NotYetConnectedException(); } else { cause = new ClosedChannelException(); } for (;;) { MessageEvent e = writeBuffer.poll(); if (e == null) { break; } e.getFuture().setFailure(cause); fireExceptionCaught(this, cause); } } } }
32.937198
88
0.594163
926ea60865839b40afe754afcd8ed130ff6004d3
10,596
/* * Copyright (C) 2018 The Dagger 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 dagger.internal.codegen; import static com.google.common.base.Verify.verify; import static com.google.common.collect.Iterables.getOnlyElement; import static com.google.common.collect.Maps.filterValues; import static com.google.common.collect.Maps.transformValues; import static dagger.internal.codegen.DaggerStreams.toImmutableSet; import static dagger.internal.codegen.DaggerStreams.toImmutableSetMultimap; import static dagger.internal.codegen.Formatter.INDENT; import static dagger.internal.codegen.Optionals.emptiesLast; import static java.util.Comparator.comparing; import static javax.tools.Diagnostic.Kind.ERROR; import com.google.auto.value.AutoValue; import com.google.common.base.Equivalence; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSetMultimap; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; import dagger.model.Binding; import dagger.model.BindingGraph; import dagger.model.BindingGraph.Node; import dagger.model.DependencyRequest; import dagger.model.Key; import dagger.spi.BindingGraphPlugin; import dagger.spi.DiagnosticReporter; import java.util.Comparator; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Set; import javax.inject.Inject; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; /** Reports errors for conflicting bindings with the same key. */ final class DuplicateBindingsValidator implements BindingGraphPlugin { // 1. contributing module or enclosing type // 2. binding element's simple name // 3. binding element's type private static final Comparator<BindingDeclaration> BINDING_DECLARATION_COMPARATOR = comparing( (BindingDeclaration declaration) -> declaration.contributingModule().isPresent() ? declaration.contributingModule() : declaration.bindingTypeElement(), emptiesLast(comparing((TypeElement type) -> type.getQualifiedName().toString()))) .thenComparing( (BindingDeclaration declaration) -> declaration.bindingElement(), emptiesLast( comparing((Element element) -> element.getSimpleName().toString()) .thenComparing((Element element) -> element.asType().toString()))); /** * An {@link Equivalence} between {@link Binding}s that ignores the {@link * Binding#componentPath()}. (All other properties are essentially derived from the {@link * Binding#bindingElement()} and {@link Binding#contributingModule()}, so only those two are * compared.) */ // TODO(dpb): Move to dagger.model? private static final Equivalence<Binding> IGNORING_COMPONENT_PATH = new Equivalence<Binding>() { @Override protected boolean doEquivalent(Binding a, Binding b) { return a.bindingElement().equals(b.bindingElement()) && a.contributingModule().equals(b.contributingModule()); } @Override protected int doHash(Binding binding) { return Objects.hash(binding.bindingElement(), binding.contributingModule()); } }; private final BindingDeclarationFormatter bindingDeclarationFormatter; @Inject DuplicateBindingsValidator(BindingDeclarationFormatter bindingDeclarationFormatter) { this.bindingDeclarationFormatter = bindingDeclarationFormatter; } @Override public String pluginName() { return "Dagger/DuplicateBindings"; } @Override public void visitGraph(BindingGraph bindingGraph, DiagnosticReporter diagnosticReporter) { // If two unrelated subcomponents have the same duplicate bindings only because they install the // same two modules, then fixing the error in one subcomponent will uncover the second // subcomponent to fix. // TODO(ronshapiro): Explore ways to address such underreporting without overreporting. Set<ImmutableSet<Equivalence.Wrapper<Binding>>> reportedDuplicateBindingSets = new HashSet<>(); duplicateBindings(bindingGraph) .forEach( (sourceAndRequest, resolvedBindings) -> { // Only report each set of duplicate bindings once, ignoring the installed component. if (reportedDuplicateBindingSets.add( equivalentSetIgnoringComponentPath(resolvedBindings))) { reportDuplicateBindings(resolvedBindings, bindingGraph, diagnosticReporter); } }); } /** * Returns duplicate bindings for each dependency request, counting the same dependency request * separately when coming from separate source nodes. */ private Map<SourceAndRequest, ImmutableSet<Binding>> duplicateBindings( BindingGraph bindingGraph) { ImmutableSetMultimap<SourceAndRequest, Binding> bindingsByDependencyRequest = bindingGraph.dependencyEdges().stream() .filter(edge -> bindingGraph.network().incidentNodes(edge).target() instanceof Binding) .collect( toImmutableSetMultimap( edge -> SourceAndRequest.create( bindingGraph.network().incidentNodes(edge).source(), edge.dependencyRequest()), edge -> ((Binding) bindingGraph.network().incidentNodes(edge).target()))); return transformValues( filterValues(bindingsByDependencyRequest.asMap(), bindings -> bindings.size() > 1), ImmutableSet::copyOf); } private void reportDuplicateBindings( ImmutableSet<Binding> duplicateBindings, BindingGraph bindingGraph, DiagnosticReporter diagnosticReporter) { Binding oneBinding = duplicateBindings.asList().get(0); diagnosticReporter.reportBinding( ERROR, oneBinding, Iterables.any(duplicateBindings, binding -> binding.kind().isMultibinding()) ? incompatibleBindingsMessage(oneBinding.key(), duplicateBindings, bindingGraph) : duplicateBindingMessage(oneBinding.key(), duplicateBindings, bindingGraph)); } private String duplicateBindingMessage( Key key, ImmutableSet<Binding> duplicateBindings, BindingGraph graph) { StringBuilder message = new StringBuilder().append(key).append(" is bound multiple times:"); formatDeclarations(message, 1, declarations(graph, duplicateBindings)); return message.toString(); } private String incompatibleBindingsMessage( Key key, ImmutableSet<Binding> duplicateBindings, BindingGraph graph) { ImmutableSet<dagger.model.Binding> multibindings = duplicateBindings.stream() .filter(binding -> binding.kind().isMultibinding()) .collect(toImmutableSet()); verify( multibindings.size() == 1, "expected only one multibinding for %s: %s", key, multibindings); StringBuilder message = new StringBuilder(); java.util.Formatter messageFormatter = new java.util.Formatter(message); messageFormatter.format("%s has incompatible bindings or declarations:\n", key); message.append(INDENT); dagger.model.Binding multibinding = getOnlyElement(multibindings); messageFormatter.format("%s bindings and declarations:", multibindingTypeString(multibinding)); formatDeclarations(message, 2, declarations(graph, multibindings)); Set<dagger.model.Binding> uniqueBindings = Sets.filter(duplicateBindings, binding -> !binding.equals(multibinding)); message.append('\n').append(INDENT).append("Unique bindings and declarations:"); formatDeclarations( message, 2, Sets.filter( declarations(graph, uniqueBindings), declaration -> !(declaration instanceof MultibindingDeclaration))); return message.toString(); } private void formatDeclarations( StringBuilder builder, int indentLevel, Iterable<? extends BindingDeclaration> bindingDeclarations) { bindingDeclarationFormatter.formatIndentedList( builder, ImmutableList.copyOf(bindingDeclarations), indentLevel); } private ImmutableSet<BindingDeclaration> declarations( BindingGraph graph, Set<dagger.model.Binding> bindings) { return bindings.stream() .flatMap(binding -> declarations(graph, binding).stream()) .distinct() .sorted(BINDING_DECLARATION_COMPARATOR) .collect(toImmutableSet()); } private ImmutableSet<BindingDeclaration> declarations( BindingGraph graph, dagger.model.Binding binding) { ImmutableSet.Builder<BindingDeclaration> declarations = ImmutableSet.builder(); BindingNode bindingNode = (BindingNode) binding; bindingNode.associatedDeclarations().forEach(declarations::add); if (bindingDeclarationFormatter.canFormat(bindingNode.delegate())) { declarations.add(bindingNode.delegate()); } else { graph.requestedBindings(binding).stream() .flatMap(requestedBinding -> declarations(graph, requestedBinding).stream()) .forEach(declarations::add); } return declarations.build(); } private String multibindingTypeString(dagger.model.Binding multibinding) { switch (multibinding.kind()) { case MULTIBOUND_MAP: return "Map"; case MULTIBOUND_SET: return "Set"; default: throw new AssertionError(multibinding); } } private static ImmutableSet<Equivalence.Wrapper<Binding>> equivalentSetIgnoringComponentPath( ImmutableSet<Binding> resolvedBindings) { return resolvedBindings.stream().map(IGNORING_COMPONENT_PATH::wrap).collect(toImmutableSet()); } @AutoValue abstract static class SourceAndRequest { abstract Node source(); abstract DependencyRequest request(); static SourceAndRequest create(Node source, DependencyRequest request) { return new AutoValue_DuplicateBindingsValidator_SourceAndRequest(source, request); } } }
42.047619
100
0.720272
43eedbf293e2f6a459afac83d526dceef674bd24
859
package io.micronaut.rabbitmq.docs.properties; import io.micronaut.context.annotation.Requires; // tag::imports[] import io.micronaut.rabbitmq.annotation.Binding; import io.micronaut.rabbitmq.annotation.RabbitClient; import io.micronaut.rabbitmq.annotation.RabbitProperty; // end::imports[] @Requires(property = "spec.name", value = "PropertiesSpec") // tag::clazz[] @RabbitClient @RabbitProperty(name = "appId", value = "myApp") // <1> @RabbitProperty(name = "userId", value = "admin") public interface ProductClient { @Binding("product") @RabbitProperty(name = "contentType", value = "application/json") // <2> @RabbitProperty(name = "userId", value = "guest") void send(byte[] data); @Binding("product") void send(@RabbitProperty("userId") String user, @RabbitProperty String contentType, byte[] data); // <3> } // end::clazz[]
33.038462
109
0.71362
0e90078d64be4438f3b8dd411c6dcd7800f302e6
8,198
package by.gdev.component; import java.awt.GraphicsEnvironment; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.ResourceBundle; import org.apache.http.client.config.RequestConfig; import com.google.common.eventbus.EventBus; import by.gdev.Main; import by.gdev.handler.Localise; import by.gdev.handler.ValidateEnvironment; import by.gdev.handler.ValidateFont; import by.gdev.handler.ValidateTempDir; import by.gdev.handler.ValidateTempNull; import by.gdev.handler.ValidateUpdate; import by.gdev.handler.ValidateWorkDir; import by.gdev.handler.ValidatedPartionSize; import by.gdev.http.head.cache.config.HttpClientConfig; import by.gdev.http.head.cache.handler.AccesHandler; import by.gdev.http.head.cache.handler.PostHandlerImpl; import by.gdev.http.head.cache.handler.SimvolicLinkHandler; import by.gdev.http.head.cache.impl.DownloaderImpl; import by.gdev.http.head.cache.impl.FileCacheServiceImpl; import by.gdev.http.head.cache.impl.GsonServiceImpl; import by.gdev.http.head.cache.impl.HttpServiceImpl; import by.gdev.http.head.cache.model.downloader.DownloaderContainer; import by.gdev.http.head.cache.service.Downloader; import by.gdev.http.head.cache.service.FileCacheService; import by.gdev.http.head.cache.service.GsonService; import by.gdev.http.head.cache.service.HttpService; import by.gdev.model.AppConfig; import by.gdev.model.JVMConfig; import by.gdev.model.StarterAppConfig; import by.gdev.process.JavaProcess; import by.gdev.process.JavaProcessHelper; import by.gdev.ui.StarterStatusFrame; import by.gdev.ui.ValidatorMessageSubscriber; import by.gdev.util.DesktopUtil; import by.gdev.util.OSInfo; import by.gdev.util.OSInfo.Arch; import by.gdev.util.OSInfo.OSType; import by.gdev.util.model.download.Repo; import lombok.extern.slf4j.Slf4j; /** * I want to see all possible implementations and idea. So we can implement * upper abstraction with system.out messages! */ @Slf4j public class Starter { private EventBus eventBus; private StarterAppConfig starterConfig; private OSType osType; private Arch osArc; private AppConfig all; private Repo java; private Repo fileRepo; private Repo dependencis; JavaProcess procces; private StarterStatusFrame starterStatusFrame; public Starter(EventBus eventBus, StarterAppConfig starterConfig) { this.eventBus = eventBus; this.starterConfig = starterConfig; } /** * Get information about current OS */ public void collectOSInfo() { osType = OSInfo.getOSType(); osArc = OSInfo.getJavaBit(); if (!GraphicsEnvironment.isHeadless()) { starterStatusFrame = new StarterStatusFrame(osType, "get installed app name", true, ResourceBundle.getBundle("application", new Localise().getLocal())); eventBus.register(starterStatusFrame); eventBus.register(new ValidatorMessageSubscriber(starterStatusFrame)); starterStatusFrame.setVisible(true); } } // TODO aleksandr to delete public void checkCommonProblems() { log.info("call method {}", "checkCommonProblems"); } /** * Validate files,java and return what we need to download */ public void validateEnvironmentAndAppRequirements() throws Exception { ResourceBundle bundle = ResourceBundle.getBundle("application", new Localise().getLocal()); List<ValidateEnvironment> validateEnvironment = new ArrayList<ValidateEnvironment>(); validateEnvironment.add(new ValidatedPartionSize(starterConfig.getMinMemorySize(), new File(starterConfig.workDir(starterConfig.getWorkDirectory())), bundle)); validateEnvironment.add(new ValidateWorkDir(starterConfig.workDir(starterConfig.getWorkDirectory()), bundle)); validateEnvironment.add(new ValidateTempNull(bundle)); validateEnvironment.add(new ValidateTempDir(bundle)); validateEnvironment.add(new ValidateFont(bundle)); validateEnvironment.add(new ValidateUpdate(bundle)); for (ValidateEnvironment val : validateEnvironment) { if (!val.validate()) { log.error(bundle.getString("validate.error") + " " + val.getClass().getName()); eventBus.post(val.getExceptionMessage()); } else { log.debug(bundle.getString("validate.successful") + " " + val.getClass().getName()); } } } /** * Download resources(java,files,.jar) and and prepare them to use, after this * we need revalidate again */ public void prepareResources() throws Exception { log.info("Start loading"); log.info(String.valueOf(osType)); log.info(String.valueOf(osArc)); DesktopUtil desktopUtil = new DesktopUtil(); desktopUtil.activeDoubleDownloadingResourcesLock(starterConfig.getWorkDirectory()); HttpClientConfig httpConfig = new HttpClientConfig(); RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(60000).build(); int maxAttepmts = DesktopUtil.numberOfAttempts(starterConfig.getUrlConnection(), 4, requestConfig, httpConfig.getInstanceHttpClient()); HttpService httpService = new HttpServiceImpl(null, httpConfig.getInstanceHttpClient(), requestConfig, maxAttepmts); FileCacheService fileService = new FileCacheServiceImpl(httpService, Main.GSON, Main.charset, Paths.get("target/out", "config"), 600000); GsonService gsonService = new GsonServiceImpl(Main.GSON, fileService); Downloader downloader = new DownloaderImpl(eventBus, httpConfig.getInstanceHttpClient(), requestConfig); DownloaderContainer container = new DownloaderContainer(); all = gsonService.getObject(starterConfig.getServerFileConifg(starterConfig), AppConfig.class, false); fileRepo = all.getAppFileRepo(); dependencis = gsonService.getObject(all.getAppDependencies().getRepositories().get(0)+ all.getAppDependencies().getResources().get(0).getRelativeUrl(), Repo.class, false); Repo resources = gsonService.getObject(all.getAppResources().getRepositories().get(0)+ all.getAppResources().getResources().get(0).getRelativeUrl(), Repo.class, false); JVMConfig jvm = gsonService.getObject(all.getJavaRepo().getRepositories().get(0) + all.getJavaRepo().getResources().get(0).getRelativeUrl(),JVMConfig.class, false); String jvmPath = jvm.getJvms().get(osType).get(osArc).get("jre_default").getResources().get(0).getRelativeUrl(); String jvmDomain = jvm.getJvms().get(osType).get(osArc).get("jre_default").getRepositories().get(0); java = gsonService.getObject(jvmDomain + jvmPath, Repo.class, false); List<Repo> list = new ArrayList<Repo>(); list.add(fileRepo); list.add(dependencis); list.add(resources); list.add(java); PostHandlerImpl postHandler = new PostHandlerImpl(); AccesHandler accesHandler = new AccesHandler(); SimvolicLinkHandler linkHandler = new SimvolicLinkHandler(); for (Repo repo : list) { container.conteinerAllSize(repo); container.filterNotExistResoursesAndSetRepo(repo, starterConfig.getWorkDirectory()); container.setDestinationRepositories(starterConfig.getWorkDirectory()); container.setHandlers(Arrays.asList(postHandler, accesHandler, linkHandler)); downloader.addContainer(container); } downloader.startDownload(true); desktopUtil.diactivateDoubleDownloadingResourcesLock(); log.info("loading is complete"); } /** * Run app and wait some command to switch off , cas we run in new process * switch off command 'Starter run app' * * @throws IOException * @throws InterruptedException */ public void runApp() throws IOException, InterruptedException { log.info("Start application"); Path jre = Paths.get(starterConfig.getWorkDirectory() + DesktopUtil.getJavaRun(java)).toAbsolutePath(); JavaProcessHelper javaProcess = new JavaProcessHelper(String.valueOf(jre),new File(starterConfig.getWorkDirectory()), eventBus); String classPath = DesktopUtil.convertListToString(File.pathSeparator,javaProcess.librariesForRunning(starterConfig.getWorkDirectory(), fileRepo, dependencis)); javaProcess.addCommands(all.getJvmArguments()); javaProcess.addCommand("-cp", classPath); javaProcess.addCommand(all.getMainClass()); procces = javaProcess.start(); if (starterConfig.isStop()) { Thread.sleep(600); procces.getProcess().destroy(); } } }
43.375661
173
0.781898
b5766220bf0650594d60dccb31640cc6d7ae37d1
3,249
public abstract class AbstractClassOrInterfaceMethodMustUseJavadocA { public String getName(String firstName, String secondName) throws XPathException, IOException { return "lalalala"; } } public abstract class AbstractClassOrInterfaceMethodMustUseJavadocB { public abstract String getName(String firstName, String secondName) throws XPathException, IOException; // Noncompliant } public abstract class AbstractClassOrInterfaceMethodMustUseJavadocC{ // hahahaha //sss /** */ public abstract String getName(String firstName, String secondName) throws XPathException, IOException; // Noncompliant } public interface AbstractClassOrInterfaceMethodMustUseJavadocJ { /** * get user name * * @param firstName first name * @return full name * @throws xpath exception */ String getName(String firstName, String secondName) throws XPathException, IOException; // Noncompliant } public abstract class AbstractClassOrInterfaceMethodMustUseJavadocD { /** * only function comment. */ public abstract void getFistName(); /** * function comment * * @param firstName first name * @param secondName second name * @return full name * @throws xpath exception * @throws IO exceptioin */ public abstract String getName(String firstName, String secondName) throws XPathException, IOException; } public interface AbstractClassOrInterfaceMethodMustUseJavadocE { String getName(String firstName, String secondName) throws XPathException, IOException; // Noncompliant } public interface AbstractClassOrInterfaceMethodMustUseJavadocF { /** */ void getName(); // Noncompliant } public interface AbstractClassOrInterfaceMethodMustUseJavadocG { /** */ String getName(String firstName, String secondName) throws XPathException, IOException; // Noncompliant } public interface AbstractClassOrInterfaceMethodMustUseJavadocH { /** * get user name * * @param firstName first name * @param secondName second name * @return full name * @throws xpath exception * @throws io exception */ String getName(String firstName, String secondName) throws XPathException, IOException; } public interface InterfaceTest { int test(); // Noncompliant int test2(); // Noncompliant public enum CmdbAttributeName { schema("schema"), planId("planId"); private String prototype; CmdbAttributeName(String prototype){ this.prototype = prototype; } public String getPrototype() { return this.prototype; } } public class InnerClass { public void classTest() { } } String getName(String username); // Noncompliant } public interface Stage { /** * test */ void test(); // 注释没问题 /** * Process Stage * * @param context context of responsibility chain */ void process(PipeLineContext context); /** * whether this stage can be skipped, true by default. * @return boolean can skip or not. */ default boolean isCanSkip() { return true; } }
25.186047
125
0.674054
bb7b03b537b5b56b29c52b09cb1043ccef6ffe0b
1,806
package com.neva.oycland.game.screen; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener; import com.neva.oycland.game.OyclandGame; import com.neva.oycland.game.ui.Hud; import static com.neva.oycland.core.gfx.GfxUtils.loadSprite; public class SummaryScreen extends StageScreen { public SummaryScreen(final OyclandGame game) { super(game); ui.setBackground(loadSprite("images/main-menu.jpg")); ui.center(); { Label label = new Label("Game over", skin); label.setFontScale(2f); ui.add(label).row(); } { Label label = new Label(Hud.formatScore(game.getProgress().getScore()), skin); ui.add(label).padBottom(5f).row(); } { Label label = new Label(Hud.formatTime(game.getProgress().getTimeElapsed()), skin); ui.add(label).padBottom(5f).row(); } { TextButton btn = new TextButton("Try again", skin); btn.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { game.start(game.getProgress().getLastLevel()); } }); ui.add(btn).row(); } { TextButton btn = new TextButton("Back to main menu", skin); btn.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { game.setScreen(MainMenuScreen.class); } }); ui.add(btn).row(); } } }
28.21875
95
0.570321
6f7053c7d6fa87bc86a553ce4e4243731b46e0a9
2,493
package io.simpleframework.sms; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; import java.io.Serializable; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; /** * @author loyayz (loyayz@foxmail.com) */ @Data @Accessors(chain = true) @NoArgsConstructor public class SmsRequest implements Serializable { private static final long serialVersionUID = 1L; /** * 短信应用 * 为空时取 SimpleSmsProperties.defaultAppId */ private String appId; /** * 短信签名 * 为空时取 SimpleSmsProperties.defaultSignName */ private String signName; /** * 短信模板 */ private String templateId; /** * 参数列表 */ private final Map<String, String> params = new LinkedHashMap<>(8); /** * 手机号码列表 */ private final Set<String> phoneNumbers = new HashSet<>(); public SmsRequest(String templateId) { this.templateId = templateId; } /** * 添加参数 * * @param key 参数编码 * @param val 参数值 * @return this */ public SmsRequest addParam(String key, String val) { this.params.put(key, val); return this; } /** * 添加参数 * * @param params 参数 * @return this */ public SmsRequest addParams(Map<String, String> params) { if (params != null) { this.params.putAll(params); } return this; } /** * 添加手机号码 * * @param phoneNumbers 手机号码。多值用逗号隔开 * @return this */ public SmsRequest addPhoneNumbers(String... phoneNumbers) { if (phoneNumbers == null) { return this; } String sep = ","; for (String phoneNumber : phoneNumbers) { if (phoneNumber == null) { continue; } for (String num : phoneNumber.split(sep)) { num = num.trim(); if (!num.isEmpty()) { this.phoneNumbers.add(num); } } } return this; } public String[] getPhoneNumberArray(boolean nationPrefix) { return this.phoneNumbers.stream() .map(number -> { if (nationPrefix && !number.startsWith("+")) { number = "+86" + number; } return number; }) .toArray(value -> new String[0]); } }
22.459459
70
0.533093
daaa62898a4e814c19f13854defbacb1424675b2
490
package singleton; /** * 懒汉-线程安全-内部静态类 * * @author mayuefeng * @date 2020-07-13 */ public class StaticSingleton { private static class Instance { private static final StaticSingleton instance = new StaticSingleton(); } private StaticSingleton() { System.out.println("instantiation"); } public void print() { System.out.println("print"); } public static StaticSingleton getInstance() { return Instance.instance; } }
17.5
78
0.636735
c7794bfaeb398e41823a1c9720ceee2884f59140
25,955
/* * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * The contents of this file are subject to the terms of either the Universal Permissive License * v 1.0 as shown at http://oss.oracle.com/licenses/upl * * or the following license: * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions * and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials provided with * the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to * endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.openjdk.jmc.common.unit; import static org.openjdk.jmc.common.item.Attribute.attr; import static org.openjdk.jmc.common.unit.BinaryPrefix.GIBI; import static org.openjdk.jmc.common.unit.BinaryPrefix.NOBI; import static org.openjdk.jmc.common.unit.BinaryPrefix.PEBI; import static org.openjdk.jmc.common.unit.BinaryPrefix.YOBI; import static org.openjdk.jmc.common.unit.DecimalPrefix.MICRO; import static org.openjdk.jmc.common.unit.DecimalPrefix.MILLI; import static org.openjdk.jmc.common.unit.DecimalPrefix.NANO; import static org.openjdk.jmc.common.unit.DecimalPrefix.NONE; import static org.openjdk.jmc.common.unit.DecimalPrefix.PICO; import static org.openjdk.jmc.common.unit.DecimalPrefix.YOCTO; import static org.openjdk.jmc.common.unit.DecimalPrefix.YOTTA; import java.text.DateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; import java.util.logging.Level; import java.util.logging.Logger; import org.openjdk.jmc.common.IDisplayable; import org.openjdk.jmc.common.IMCClassLoader; import org.openjdk.jmc.common.IMCFrame; import org.openjdk.jmc.common.IMCMethod; import org.openjdk.jmc.common.IMCModule; import org.openjdk.jmc.common.IMCOldObject; import org.openjdk.jmc.common.IMCOldObjectArray; import org.openjdk.jmc.common.IMCOldObjectField; import org.openjdk.jmc.common.IMCOldObjectGcRoot; import org.openjdk.jmc.common.IMCPackage; import org.openjdk.jmc.common.IMCStackTrace; import org.openjdk.jmc.common.IMCThread; import org.openjdk.jmc.common.IMCThreadGroup; import org.openjdk.jmc.common.IMCType; import org.openjdk.jmc.common.item.IAttribute; import org.openjdk.jmc.common.item.IType; import org.openjdk.jmc.common.messages.internal.Messages; import org.openjdk.jmc.common.util.LabeledIdentifier; import org.openjdk.jmc.common.util.MethodToolkit; /** * This class is responsible for configuring the different units that are available in Mission * Control. */ @SuppressWarnings("nls") final public class UnitLookup { private static final String UNIT_ID_SEPARATOR = ":"; public static final LinearKindOfQuantity MEMORY = createMemory(); public static final LinearKindOfQuantity TIMESPAN = createTimespan(); /* * NOTE: These 3 (count, index, and identifier) cannot be persisted/restored due to Long(1) and * Integer(1) not being equal or comparable. We either need to split into concrete wrappers, * support a custom Comparator, or wrap into a (simple) IQuantity. */ public static final ContentType<Number> COUNT = createCount(); public static final ContentType<Number> INDEX = createIndex(); public static final ContentType<Number> IDENTIFIER = createIdentifier(); public static final KindOfQuantity<TimestampUnit> TIMESTAMP = createTimestamp(TIMESPAN); public static final LinearKindOfQuantity PERCENTAGE = createPercentage(); public static final LinearKindOfQuantity NUMBER = createNumber(); /** * NOTE: Temporary placeholder for raw numerical values, primitive wrappers. Use sparingly. */ public static final ContentType<Number> RAW_NUMBER = createRawNumber(); /** * NOTE: Temporary placeholder for raw long values to allow for comparable uses. */ public static final ContentType<Long> RAW_LONG = createRawLong(); public static final ContentType<IUnit> UNIT = createSyntheticContentType("unit"); public static final ContentType<Object> UNKNOWN = createSyntheticContentType("unknown"); public static final ContentType<String> PLAIN_TEXT = createStringContentType("text"); public static final ContentType<IMCOldObject> OLD_OBJECT = createSyntheticContentType("oldObject"); public static final ContentType<IMCOldObjectArray> OLD_OBJECT_ARRAY = createSyntheticContentType("oldObjectArray"); public static final ContentType<IMCOldObjectField> OLD_OBJECT_FIELD = createSyntheticContentType("oldObjectField"); public static final ContentType<IMCOldObjectGcRoot> OLD_OBJECT_GC_ROOT = createSyntheticContentType( "oldObjectGcRoot"); public static final ContentType<IMCMethod> METHOD = createSyntheticContentType("method"); public static final ContentType<IMCType> CLASS = createJavaTypeContentType("class"); public static final ContentType<IMCClassLoader> CLASS_LOADER = createSyntheticContentType("classLoader"); public static final ContentType<IMCPackage> PACKAGE = createSyntheticContentType("package"); public static final ContentType<IMCModule> MODULE = createSyntheticContentType("module"); public static final ContentType<IMCStackTrace> STACKTRACE = createSyntheticContentType("stacktrace"); public static final ContentType<IMCFrame> STACKTRACE_FRAME = createSyntheticContentType("frame"); public static final ContentType<IMCThread> THREAD = createSyntheticContentType("thread"); public static final ContentType<IMCThreadGroup> THREAD_GROUP = createSyntheticContentType("threadGroup"); public static final ContentType<LabeledIdentifier> LABELED_IDENTIFIER = createSyntheticContentType( "labeledIdentifier"); public static final LinearKindOfQuantity ADDRESS = createAddress(); public static final ContentType<Boolean> FLAG = createFlag("boolean"); public static final ContentType<IType<?>> TYPE = createSyntheticContentType("type"); public static final TimestampUnit EPOCH_MS = TIMESTAMP.getUnit("epochms"); public static final TimestampUnit EPOCH_NS = TIMESTAMP.getUnit("epochns"); public static final TimestampUnit EPOCH_S = TIMESTAMP.getUnit("epochs"); public static final LinearUnit NUMBER_UNITY = NUMBER.getUnit(NONE); public static final LinearUnit ADDRESS_UNITY = ADDRESS.getUnit(NONE); public static final LinearUnit PERCENT_UNITY = PERCENTAGE.getUnit(""); public static final LinearUnit PERCENT = PERCENTAGE.getUnit("%"); public static final LinearUnit BYTE = MEMORY.getUnit(NOBI); public static final LinearUnit GIBIBYTE = MEMORY.getUnit(GIBI); public static final LinearUnit NANOSECOND = TIMESPAN.getUnit(NANO); public static final LinearUnit MICROSECOND = TIMESPAN.getUnit(MICRO); public static final LinearUnit MILLISECOND = TIMESPAN.getUnit(MILLI); public static final LinearUnit SECOND = TIMESPAN.getUnit(NONE); public static final LinearUnit MINUTE = TIMESPAN.getUnit("min"); public static final LinearUnit HOUR = TIMESPAN.getUnit("h"); public static final LinearUnit DAY = TIMESPAN.getUnit("d"); public static final LinearUnit YEAR = TIMESPAN.getUnit("a"); // Attributes matching RAW_NUMBER and UNIT content types. Use sparingly. public static final IAttribute<Number> NUMERICAL_ATTRIBUTE = attr("numerical", "Numerical", //$NON-NLS-1$ //$NON-NLS-2$ "The numerical value of a quantity", RAW_NUMBER); public static final IAttribute<IUnit> UNIT_ATTRIBUTE = attr("unit", "Unit", "The unit of a quantity", UNIT); //$NON-NLS-1$ //$NON-NLS-2$ private static final List<ContentType<?>> CONTENT_TYPES; private static final Map<String, RangeContentType<?>> RANGE_CONTENT_TYPES; static { List<KindOfQuantity<?>> quantityKinds = new ArrayList<>(); quantityKinds.add(MEMORY); quantityKinds.add(TIMESPAN); quantityKinds.add(TIMESTAMP); quantityKinds.add(PERCENTAGE); quantityKinds.add(NUMBER); quantityKinds.add(ADDRESS); Map<String, RangeContentType<?>> rangeTypes = new HashMap<>(); for (KindOfQuantity<?> kind : quantityKinds) { rangeTypes.put(kind.getIdentifier(), RangeContentType.create(kind)); } RANGE_CONTENT_TYPES = Collections.unmodifiableMap(rangeTypes); List<ContentType<?>> types = new ArrayList<ContentType<?>>(quantityKinds); types.add(COUNT); types.add(INDEX); types.add(IDENTIFIER); types.add(LABELED_IDENTIFIER); types.add(PLAIN_TEXT); types.add(STACKTRACE); types.add(STACKTRACE_FRAME); types.add(METHOD); types.add(CLASS); types.add(CLASS_LOADER); types.add(PACKAGE); types.add(MODULE); types.add(THREAD); types.add(THREAD_GROUP); types.add(FLAG); types.add(TYPE); types.add(OLD_OBJECT); // FIXME: Should we add the OLD_OBJECT_* subtypes? types.add(UNKNOWN); CONTENT_TYPES = Collections.unmodifiableList(types); } public static final ContentType<IRange<IQuantity>> TIMERANGE = getRangeType(TIMESTAMP); @SuppressWarnings("unchecked") public static <M extends Comparable<? super M>> RangeContentType<M> getRangeType(ContentType<M> endPointType) { return (RangeContentType<M>) RANGE_CONTENT_TYPES.get(endPointType.getIdentifier()); } private static abstract class LeafContentType<T> extends ContentType<T> implements IPersister<T> { private LeafContentType(String identifier) { super(identifier); } protected final void checkNull(Object value) { if (value == null) { throw new NullPointerException(); } } @Override public IConstraint<T> combine(IConstraint<?> other) { return (this == other) ? this : null; } @Override public IPersister<T> getPersister() { return this; } } public static List<KindOfQuantity<?>> getKindsOfQuantity() { return Arrays.<KindOfQuantity<?>> asList(MEMORY, TIMESPAN, TIMESTAMP, NUMBER, PERCENTAGE); } public static List<ContentType<?>> getAllContentTypes() { return CONTENT_TYPES; } /** * Convert a {@link Date} instance to a {@link IQuantity}, preserving {@code null}. * * @param timestamp * a {@link Date} instance, or {@code null} * @return an {@link IQuantity} implementation instance, or {@code null} */ public static IQuantity fromDate(Date timestamp) { return (timestamp != null) ? EPOCH_MS.quantity(timestamp.getTime()) : null; } /** * Convert an {@link IQuantity} representing a timestamp to a {@link Date}, preserving * {@code null}. * * @param timestamp * a timestamp {@link IQuantity}, or {@code null} * @return a {@link Date} instance, or {@code null} * @throws IllegalArgumentException * if {@code timestamp} is not of the timestamp kind */ public static Date toDate(IQuantity timestamp) { return (timestamp != null) ? new Date(timestamp.clampedLongValueIn(EPOCH_MS)) : null; } // FIXME: Doesn't really belong here. For now, make sure to not expose more. static Logger getLogger() { return Logger.getLogger("org.openjdk.jmc.common.unit"); } private static <T> ContentType<T> createSyntheticContentType(String id) { ContentType<T> contentType = new ContentType<>(id); contentType.addFormatter(new DisplayFormatter<>(contentType, IDisplayable.AUTO, "Default")); return contentType; } private static ContentType<Boolean> createFlag(String id) { ContentType<Boolean> contentType = new LeafContentType<Boolean>(id) { @Override public boolean validate(Boolean value) { // Overriding this method seems sufficient and simplest to check that the class is correct. checkNull(value); return false; } @Override public String persistableString(Boolean value) { return value.toString(); } @Override public Boolean parsePersisted(String persistedValue) throws QuantityConversionException { if (persistedValue.equals("true")) { return Boolean.TRUE; } if (persistedValue.equals("false")) { return Boolean.FALSE; } throw QuantityConversionException.unparsable(persistedValue, Boolean.TRUE, this); } @Override public String interactiveFormat(Boolean content) { // FIXME: Define better localized strings return content.toString(); } @Override public Boolean parseInteractive(String interactiveValue) throws QuantityConversionException { checkNull(interactiveValue); // FIXME: Define better localized strings return Boolean.valueOf(interactiveValue); } }; contentType.addFormatter(new DisplayFormatter<>(contentType, IDisplayable.AUTO, "Default")); return contentType; } private static ContentType<String> createStringContentType(String id) { ContentType<String> contentType = new LeafContentType<String>(id) { @Override public boolean validate(String value) { // Overriding this method seems sufficient and simplest to check that the class is correct. checkNull(value); return false; } @Override public String persistableString(String value) { validate(value); return value; } @Override public String parsePersisted(String persistedValue) { checkNull(persistedValue); return persistedValue; } @Override public String interactiveFormat(String value) { validate(value); return value; } @Override public String parseInteractive(String interactiveValue) { checkNull(interactiveValue); return interactiveValue; } }; contentType.addFormatter(new DisplayFormatter<>(contentType, IDisplayable.AUTO, "Default")); return contentType; } private static ContentType<IMCType> createJavaTypeContentType(String id) { ContentType<IMCType> contentType = new LeafContentType<IMCType>(id) { @Override public boolean validate(IMCType value) { // Overriding this method seems sufficient and simplest to check that the class is correct. checkNull(value); return false; } @Override public String persistableString(IMCType value) { return value.getFullName(); } @Override public IMCType parsePersisted(String persistedValue) { checkNull(persistedValue); return MethodToolkit.typeFromBinaryJLS(persistedValue); } @Override public String interactiveFormat(IMCType value) { return value.getFullName(); } @Override public IMCType parseInteractive(String interactiveValue) { checkNull(interactiveValue); return MethodToolkit.typeFromBinaryJLS(interactiveValue); } }; contentType.addFormatter(new DisplayFormatter<>(contentType, IDisplayable.AUTO, "Default")); return contentType; } private static LinearKindOfQuantity createNumber() { LinearKindOfQuantity number = new LinearKindOfQuantity("number", "", EnumSet.range(NONE, NONE)); number.addFormatter(new LinearKindOfQuantity.AutoFormatter(number, "Dynamic", 0.001, 1000000)); number.addFormatter(new KindOfQuantity.ExactFormatter<>(number)); number.addFormatter(new KindOfQuantity.VerboseFormatter<>(number)); // FIXME: Verify that scientific and engineering notation formatting works properly. number.addFormatter(new LinearKindOfQuantity.AutoFormatter(number, DisplayFormatter.SCIENTIFIC_NOTATION_IDENTIFIER, "Scientific Notation", 1.0, 10, 3)); number.addFormatter(new LinearKindOfQuantity.AutoFormatter(number, DisplayFormatter.ENGINEERING_NOTATION_IDENTIFIER, "Engineering Notation", 1.0, 1000, 3)); return number; } private static LinearKindOfQuantity createAddress() { LinearKindOfQuantity address = new LinearKindOfQuantity("address", "", EnumSet.range(NONE, NONE)) { // NOTE: Only overriding the interactive format. Persisted value can still be decimal. @Override public String interactiveFormat(IQuantity quantity) { return formatHexNumber(quantity); } }; address.addFormatter(new DisplayFormatter<IQuantity>(address, IDisplayable.AUTO, "Dynamic") { @Override public String format(IQuantity quantity) { return formatHexNumber(quantity); } }); return address; } private static String formatHexNumber(IQuantity quantity) { return String.format("0x%08X", quantity.longValue()); } // FIXME: Rename to createPrimitiveNumber? Remove? private static ContentType<Number> createRawNumber() { ContentType<Number> contentType = new ContentType<>("raw number"); contentType.addFormatter(new DisplayFormatter<>(contentType, IDisplayable.AUTO, "Value")); return contentType; } private static ContentType<Long> createRawLong() { ContentType<Long> contentType = new ContentType<>("raw long"); contentType.addFormatter(new DisplayFormatter<>(contentType, IDisplayable.AUTO, "Value")); return contentType; } private static LinearKindOfQuantity createMemory() { LinearKindOfQuantity memory = new LinearKindOfQuantity("memory", "B", EnumSet.range(NOBI, PEBI), EnumSet.range(NOBI, YOBI)); memory.addFormatter(new LinearKindOfQuantity.AutoFormatter(memory, "Dynamic", 1.0, 1024)); memory.addFormatter(new KindOfQuantity.ExactFormatter<>(memory)); memory.addFormatter(new KindOfQuantity.VerboseFormatter<>(memory)); return memory; } private static void addQuantities( Collection<ITypedQuantity<LinearUnit>> result, LinearUnit unit, Number ... numbers) { for (Number number : numbers) { result.add(unit.quantity(number)); } } private static LinearKindOfQuantity createTimespan() { EnumSet<DecimalPrefix> commonPrefixes = EnumSet.range(PICO, MILLI); commonPrefixes.add(NONE); LinearKindOfQuantity timeSpan = new LinearKindOfQuantity("timespan", "s", commonPrefixes, EnumSet.range(YOCTO, YOTTA)); LinearUnit second = timeSpan.atomUnit; LinearUnit minute = timeSpan.makeUnit("min", second.quantity(60)); LinearUnit hour = timeSpan.makeUnit("h", minute.quantity(60)); LinearUnit day = timeSpan.makeUnit("d", hour.quantity(24)); // UCUM defines the symbol "wk" for the week. LinearUnit week = timeSpan.makeUnit("wk", day.quantity(7)); // The Julian year (annum, symbol "a") is defined by UCUM for use with SI, since it is the basis for the light year (so this is exact). LinearUnit year = timeSpan.makeUnit("a", hour.quantity(8766)); // A mean Julian month is 1/12 of a Julian year = 365.25*24/12 h = 730.5 h = 43 830 min (exactly). // LinearUnit month = timeSpan.makeUnit("mo", minute.quantity(43830)); LinearUnit[] units = {minute, hour, day, week, year}; for (LinearUnit unit : units) { timeSpan.addUnit(unit); } // Tick marks and bucket sizes, also used for timestamps. SortedSet<ITypedQuantity<LinearUnit>> ticks = new TreeSet<>(); addQuantities(ticks, second, 1, 2, 4, 5, 10, 15, 30); addQuantities(ticks, minute, 1, 2, 4, 5, 10, 15, 30); addQuantities(ticks, hour, 1, 2, 4, 6, 12); addQuantities(ticks, day, 1, 2, 4); addQuantities(ticks, week, 1, 2, 4, 5, 10); addQuantities(ticks, year, 0.25, 0.5, 1); DecimalUnitSelector yearSelector = new DecimalUnitSelector(timeSpan, year); CustomUnitSelector selector; selector = new CustomUnitSelector(timeSpan, timeSpan.unitSelector, Arrays.asList(units), yearSelector, ticks); timeSpan.setDefaultSelector(selector); timeSpan.addFormatter(new LinearKindOfQuantity.DualUnitFormatter(timeSpan, IDisplayable.AUTO, "Human readable", timeSpan.getUnit(NANO))); // FIXME: LKOQ.AutoFormatter uses IDisplayable.AUTO id which collides with the DualUnitFormatter above. Sync with FLR behavior? timeSpan.addFormatter(new LinearKindOfQuantity.AutoFormatter(timeSpan, "Dynamic")); timeSpan.addFormatter(new KindOfQuantity.ExactFormatter<>(timeSpan)); timeSpan.addFormatter(new KindOfQuantity.VerboseFormatter<>(timeSpan)); return timeSpan; } private static TimestampKind createTimestamp(LinearKindOfQuantity timespan) { TimestampKind timestampContentType = TimestampKind.buildContentType(timespan); timestampContentType .addFormatter(new DisplayFormatter<IQuantity>(timestampContentType, IDisplayable.AUTO, "Dynamic") { @Override public String format(IQuantity quantity) { try { // NOTE: This used to return the floor value. Date date = new Date(quantity.longValueIn(TimestampKind.MILLIS_UNIT)); return DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM).format(date); } catch (QuantityConversionException e) { return Messages.getString(Messages.UnitLookup_TIMESTAMP_OUT_OF_RANGE); } } }); timestampContentType.addFormatter(new KindOfQuantity.ExactFormatter<>(timestampContentType)); timestampContentType.addFormatter(new KindOfQuantity.VerboseFormatter<>(timestampContentType)); // contentType.addDisplayUnit(new DisplayUnit(contentType, "nanos", "D:HH:MM:SS ns")); // contentType.addDisplayUnit(new DisplayUnit(contentType, "micros", "D:HH:MM:SS us")); // contentType.addDisplayUnit(new DisplayUnit(contentType, "seconds", "D:HH:MM:SS")); return timestampContentType; } private static LinearKindOfQuantity createPercentage() { LinearKindOfQuantity percentage = new LinearKindOfQuantity("percentage", "%", EnumSet.range(NONE, NONE)); LinearUnit percentUnit = percentage.atomUnit; // Use identifier "", like Number. Relying on externalization to get symbol like "x100 %". LinearUnit unity = percentage.makeUnit("", percentUnit.quantity(100)); percentage.addUnit(unity); percentage.addFormatter(new LinearKindOfQuantity.AutoFormatter(percentage, "Dynamic", 0.001, 1000000)); percentage.addFormatter(new KindOfQuantity.ExactFormatter<>(percentage)); percentage.addFormatter(new KindOfQuantity.VerboseFormatter<>(percentage)); percentage.addFormatter(new DisplayFormatter<>(percentage, "accuracy2digits", "Accuracy 2 digits)")); percentage.addFormatter(new DisplayFormatter<>(percentage, "accuracy0digits", "Accuracy 0 digits)")); percentage.addFormatter(new DisplayFormatter<>(percentage, "accuracy1digit", "Accuracy 1 digit)")); percentage.addFormatter(new DisplayFormatter<>(percentage, "accuracy3digits", "Accuracy 3 digits)")); return percentage; } private static ContentType<Number> createCount() { ContentType<Number> contentType = new ContentType<>("count"); // contentType.addDisplayUnit( // new DisplayUnit(contentType, DisplayUnit.ENGINEERING_NOTATION_IDENTIFIER, "Engineering Notation")); contentType.addFormatter(new DisplayFormatter<>(contentType, IDisplayable.AUTO, "Value")); // contentType.addDisplayUnit( // new DisplayUnit(contentType, DisplayUnit.SCIENTIFIC_NOTATION_IDENTIFIER, "Scientific Notation")); return contentType; } private static ContentType<Number> createIdentifier() { ContentType<Number> contentType = new ContentType<>("identifier"); contentType.addFormatter(new DisplayFormatter<>(contentType, IDisplayable.AUTO, "Value")); return contentType; } private static ContentType<Number> createIndex() { ContentType<Number> contentType = new ContentType<>("index"); contentType.addFormatter(new DisplayFormatter<>(contentType, IDisplayable.AUTO, "Value")); return contentType; } public static String getUnitIdentifier(IUnit unit) { if (unit.getIdentifier() == null) { throw new IllegalArgumentException("Cannot get identifier for impersistable unit :" + unit); } KindOfQuantity<?> ct = unit.getContentType(); return ct.getIdentifier() + UNIT_ID_SEPARATOR + unit.getIdentifier(); } public static IUnit getUnitOrDefault(String unitIdentifier) { IUnit unit = getUnitOrNull(unitIdentifier); return unit == null ? NUMBER.getUnit(NONE) : unit; } public static IUnit getUnitOrNull(String unitIdentifier) { if (unitIdentifier != null) { String[] parts = unitIdentifier.split(UNIT_ID_SEPARATOR, 2); if (parts.length == 2) { ContentType<?> ct = getContentType(parts[0]); if (ct instanceof KindOfQuantity) { IUnit unit = ((KindOfQuantity<?>) ct).getUnit(parts[1]); if (unit != null) { return unit; } else if (ct instanceof LinearKindOfQuantity) { LinearKindOfQuantity kindOfQuantity = (LinearKindOfQuantity) ct; String id = parts[1]; LinearUnit linUnit = kindOfQuantity.getCachedUnit(id); if (linUnit != null) { return linUnit; } try { // FIXME: Parse using UCUM (Unified Code for Units of Measure) syntax instead? Or by only allowing integers? ITypedQuantity<LinearUnit> quantity = kindOfQuantity.parsePersisted(id); return kindOfQuantity.makeCustomUnit(quantity); } catch (QuantityConversionException e) { getLogger().log(Level.WARNING, e.getMessage(), e); } } } } } return null; } public static ContentType<?> getContentType(String identifier) { String[] parts = identifier.split(UNIT_ID_SEPARATOR, 2); if (parts.length > 2) { return UNKNOWN; } else if (parts.length == 2) { identifier = parts[0]; } for (ContentType<?> type : CONTENT_TYPES) { if (identifier.equals(type.getIdentifier())) { return type; } } return UNKNOWN; } }
41.594551
137
0.756579
ceb1ba088d639c42a7f56c7e002df41873383cf8
1,144
package com.hw.Network.Handlers; import com.hw.Network.Protocol.Request; import com.hw.Network.Protocol.Response; import com.hw.Network.Protocol.ResponseCode; import com.hw.DataStorage.StorageHandler; import java.util.ArrayList; /** * Created by Pasha on 5/29/2016. */ public class GetMethodHandler implements MethodHandler { @Override public String[] handledRequests() { return new String[]{"get"}; } @Override public MethodHandler getNewInstance() { return new GetMethodHandler(); } @Override public Response process(Request req) { String key = req.getParams().containsKey("key") ? (String) req.getParams().get("key") : null; if(key == null || key.isEmpty()) return new Response(ResponseCode.ERROR, "key is not provided", null); ArrayList<String> values = StorageHandler.getInstance().get(key); // TODO: Add response on error to set value if(values.isEmpty()) return new Response(ResponseCode.OK, "No data found", null); return new Response(ResponseCode.OK, "", values); } }
28.6
118
0.646853
75dc39722bcf70b1c4ab8061955006aa59d969d8
29,965
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.systemui.power; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.database.ContentObserver; import android.os.BatteryManager; import android.os.Handler; import android.os.IThermalEventListener; import android.os.IThermalService; import android.os.PowerManager; import android.os.RemoteException; import android.os.ServiceManager; import android.os.SystemClock; import android.os.Temperature; import android.os.UserHandle; import android.provider.Settings; import android.text.format.DateUtils; import android.util.Log; import android.util.Slog; import com.android.internal.annotations.VisibleForTesting; import com.android.settingslib.fuelgauge.Estimate; import com.android.settingslib.utils.ThreadUtils; import com.android.systemui.Dependency; import com.android.systemui.R; import com.android.systemui.SystemUI; import com.android.systemui.statusbar.phone.StatusBar; import java.io.FileDescriptor; import java.io.PrintWriter; import java.time.Duration; import java.util.Arrays; import java.util.concurrent.Future; public class PowerUI extends SystemUI { static final String TAG = "PowerUI"; static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG); private static final long TEMPERATURE_INTERVAL = 30 * DateUtils.SECOND_IN_MILLIS; private static final long TEMPERATURE_LOGGING_INTERVAL = DateUtils.HOUR_IN_MILLIS; private static final int MAX_RECENT_TEMPS = 125; // TEMPERATURE_LOGGING_INTERVAL plus a buffer static final long THREE_HOURS_IN_MILLIS = DateUtils.HOUR_IN_MILLIS * 3; private static final int CHARGE_CYCLE_PERCENT_RESET = 45; private static final long SIX_HOURS_MILLIS = Duration.ofHours(6).toMillis(); public static final int NO_ESTIMATE_AVAILABLE = -1; private static final String BOOT_COUNT_KEY = "boot_count"; private static final String PREFS = "powerui_prefs"; private final Handler mHandler = new Handler(); @VisibleForTesting final Receiver mReceiver = new Receiver(); private PowerManager mPowerManager; private WarningsUI mWarnings; private final Configuration mLastConfiguration = new Configuration(); private int mPlugType = 0; private int mInvalidCharger = 0; private EnhancedEstimates mEnhancedEstimates; private Future mLastShowWarningTask; private boolean mEnableSkinTemperatureWarning; private boolean mEnableUsbTemperatureAlarm; private int mLowBatteryAlertCloseLevel; private final int[] mLowBatteryReminderLevels = new int[2]; private long mScreenOffTime = -1; @VisibleForTesting boolean mLowWarningShownThisChargeCycle; @VisibleForTesting boolean mSevereWarningShownThisChargeCycle; @VisibleForTesting BatteryStateSnapshot mCurrentBatteryStateSnapshot; @VisibleForTesting BatteryStateSnapshot mLastBatteryStateSnapshot; @VisibleForTesting IThermalService mThermalService; @VisibleForTesting int mBatteryLevel = 100; @VisibleForTesting int mBatteryStatus = BatteryManager.BATTERY_STATUS_UNKNOWN; private IThermalEventListener mSkinThermalEventListener; private IThermalEventListener mUsbThermalEventListener; public void start() { mPowerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE); mScreenOffTime = mPowerManager.isScreenOn() ? -1 : SystemClock.elapsedRealtime(); mWarnings = Dependency.get(WarningsUI.class); mEnhancedEstimates = Dependency.get(EnhancedEstimates.class); mLastConfiguration.setTo(mContext.getResources().getConfiguration()); ContentObserver obs = new ContentObserver(mHandler) { @Override public void onChange(boolean selfChange) { updateBatteryWarningLevels(); } }; final ContentResolver resolver = mContext.getContentResolver(); resolver.registerContentObserver(Settings.Global.getUriFor( Settings.Global.LOW_POWER_MODE_TRIGGER_LEVEL), false, obs, UserHandle.USER_ALL); updateBatteryWarningLevels(); mReceiver.init(); // Check to see if we need to let the user know that the phone previously shut down due // to the temperature being too high. showWarnOnThermalShutdown(); // Register an observer to configure mEnableSkinTemperatureWarning and perform the // registration of skin thermal event listener upon Settings change. resolver.registerContentObserver( Settings.Global.getUriFor(Settings.Global.SHOW_TEMPERATURE_WARNING), false /*notifyForDescendants*/, new ContentObserver(mHandler) { @Override public void onChange(boolean selfChange) { doSkinThermalEventListenerRegistration(); } }); // Register an observer to configure mEnableUsbTemperatureAlarm and perform the // registration of usb thermal event listener upon Settings change. resolver.registerContentObserver( Settings.Global.getUriFor(Settings.Global.SHOW_USB_TEMPERATURE_ALARM), false /*notifyForDescendants*/, new ContentObserver(mHandler) { @Override public void onChange(boolean selfChange) { doUsbThermalEventListenerRegistration(); } }); initThermalEventListeners(); } @Override protected void onConfigurationChanged(Configuration newConfig) { final int mask = ActivityInfo.CONFIG_MCC | ActivityInfo.CONFIG_MNC; // Safe to modify mLastConfiguration here as it's only updated by the main thread (here). if ((mLastConfiguration.updateFrom(newConfig) & mask) != 0) { mHandler.post(this::initThermalEventListeners); } } void updateBatteryWarningLevels() { int critLevel = mContext.getResources().getInteger( com.android.internal.R.integer.config_criticalBatteryWarningLevel); int warnLevel = mContext.getResources().getInteger( com.android.internal.R.integer.config_lowBatteryWarningLevel); if (warnLevel < critLevel) { warnLevel = critLevel; } mLowBatteryReminderLevels[0] = warnLevel; mLowBatteryReminderLevels[1] = critLevel; mLowBatteryAlertCloseLevel = mLowBatteryReminderLevels[0] + mContext.getResources().getInteger( com.android.internal.R.integer.config_lowBatteryCloseWarningBump); } /** * Buckets the battery level. * * The code in this function is a little weird because I couldn't comprehend * the bucket going up when the battery level was going down. --joeo * * 1 means that the battery is "ok" * 0 means that the battery is between "ok" and what we should warn about. * less than 0 means that the battery is low */ private int findBatteryLevelBucket(int level) { if (level >= mLowBatteryAlertCloseLevel) { return 1; } if (level > mLowBatteryReminderLevels[0]) { return 0; } final int N = mLowBatteryReminderLevels.length; for (int i=N-1; i>=0; i--) { if (level <= mLowBatteryReminderLevels[i]) { return -1-i; } } throw new RuntimeException("not possible!"); } @VisibleForTesting final class Receiver extends BroadcastReceiver { public void init() { // Register for Intent broadcasts for... IntentFilter filter = new IntentFilter(); filter.addAction(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED); filter.addAction(Intent.ACTION_BATTERY_CHANGED); filter.addAction(Intent.ACTION_SCREEN_OFF); filter.addAction(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_USER_SWITCHED); mContext.registerReceiver(this, filter, null, mHandler); } @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (PowerManager.ACTION_POWER_SAVE_MODE_CHANGED.equals(action)) { ThreadUtils.postOnBackgroundThread(() -> { if (mPowerManager.isPowerSaveMode()) { mWarnings.dismissLowBatteryWarning(); } }); } else if (Intent.ACTION_BATTERY_CHANGED.equals(action)) { final int oldBatteryLevel = mBatteryLevel; mBatteryLevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 100); final int oldBatteryStatus = mBatteryStatus; mBatteryStatus = intent.getIntExtra(BatteryManager.EXTRA_STATUS, BatteryManager.BATTERY_STATUS_UNKNOWN); final int oldPlugType = mPlugType; mPlugType = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 1); final int oldInvalidCharger = mInvalidCharger; mInvalidCharger = intent.getIntExtra(BatteryManager.EXTRA_INVALID_CHARGER, 0); mLastBatteryStateSnapshot = mCurrentBatteryStateSnapshot; final boolean plugged = mPlugType != 0; final boolean oldPlugged = oldPlugType != 0; int oldBucket = findBatteryLevelBucket(oldBatteryLevel); int bucket = findBatteryLevelBucket(mBatteryLevel); if (DEBUG) { Slog.d(TAG, "buckets ....." + mLowBatteryAlertCloseLevel + " .. " + mLowBatteryReminderLevels[0] + " .. " + mLowBatteryReminderLevels[1]); Slog.d(TAG, "level " + oldBatteryLevel + " --> " + mBatteryLevel); Slog.d(TAG, "status " + oldBatteryStatus + " --> " + mBatteryStatus); Slog.d(TAG, "plugType " + oldPlugType + " --> " + mPlugType); Slog.d(TAG, "invalidCharger " + oldInvalidCharger + " --> " + mInvalidCharger); Slog.d(TAG, "bucket " + oldBucket + " --> " + bucket); Slog.d(TAG, "plugged " + oldPlugged + " --> " + plugged); } mWarnings.update(mBatteryLevel, bucket, mScreenOffTime); if (oldInvalidCharger == 0 && mInvalidCharger != 0) { Slog.d(TAG, "showing invalid charger warning"); mWarnings.showInvalidChargerWarning(); return; } else if (oldInvalidCharger != 0 && mInvalidCharger == 0) { mWarnings.dismissInvalidChargerWarning(); } else if (mWarnings.isInvalidChargerWarningShowing()) { // if invalid charger is showing, don't show low battery if (DEBUG) { Slog.d(TAG, "Bad Charger"); } return; } // Show the correct version of low battery warning if needed if (mLastShowWarningTask != null) { mLastShowWarningTask.cancel(true); if (DEBUG) { Slog.d(TAG, "cancelled task"); } } mLastShowWarningTask = ThreadUtils.postOnBackgroundThread(() -> { maybeShowBatteryWarningV2( plugged, bucket); }); } else if (Intent.ACTION_SCREEN_OFF.equals(action)) { mScreenOffTime = SystemClock.elapsedRealtime(); } else if (Intent.ACTION_SCREEN_ON.equals(action)) { mScreenOffTime = -1; } else if (Intent.ACTION_USER_SWITCHED.equals(action)) { mWarnings.userSwitched(); } else { Slog.w(TAG, "unknown intent: " + intent); } } } protected void maybeShowBatteryWarningV2(boolean plugged, int bucket) { final boolean hybridEnabled = mEnhancedEstimates.isHybridNotificationEnabled(); final boolean isPowerSaverMode = mPowerManager.isPowerSaveMode(); // Stick current battery state into an immutable container to determine if we should show // a warning. if (DEBUG) { Slog.d(TAG, "evaluating which notification to show"); } if (hybridEnabled) { if (DEBUG) { Slog.d(TAG, "using hybrid"); } Estimate estimate = refreshEstimateIfNeeded(); mCurrentBatteryStateSnapshot = new BatteryStateSnapshot(mBatteryLevel, isPowerSaverMode, plugged, bucket, mBatteryStatus, mLowBatteryReminderLevels[1], mLowBatteryReminderLevels[0], estimate.getEstimateMillis(), estimate.getAverageDischargeTime(), mEnhancedEstimates.getSevereWarningThreshold(), mEnhancedEstimates.getLowWarningThreshold(), estimate.isBasedOnUsage(), mEnhancedEstimates.getLowWarningEnabled()); } else { if (DEBUG) { Slog.d(TAG, "using standard"); } mCurrentBatteryStateSnapshot = new BatteryStateSnapshot(mBatteryLevel, isPowerSaverMode, plugged, bucket, mBatteryStatus, mLowBatteryReminderLevels[1], mLowBatteryReminderLevels[0]); } mWarnings.updateSnapshot(mCurrentBatteryStateSnapshot); if (mCurrentBatteryStateSnapshot.isHybrid()) { maybeShowHybridWarning(mCurrentBatteryStateSnapshot, mLastBatteryStateSnapshot); } else { maybeShowBatteryWarning(mCurrentBatteryStateSnapshot, mLastBatteryStateSnapshot); } } // updates the time estimate if we don't have one or battery level has changed. @VisibleForTesting Estimate refreshEstimateIfNeeded() { if (mLastBatteryStateSnapshot == null || mLastBatteryStateSnapshot.getTimeRemainingMillis() == NO_ESTIMATE_AVAILABLE || mBatteryLevel != mLastBatteryStateSnapshot.getBatteryLevel()) { final Estimate estimate = mEnhancedEstimates.getEstimate(); if (DEBUG) { Slog.d(TAG, "updated estimate: " + estimate.getEstimateMillis()); } return estimate; } return new Estimate(mLastBatteryStateSnapshot.getTimeRemainingMillis(), mLastBatteryStateSnapshot.isBasedOnUsage(), mLastBatteryStateSnapshot.getAverageTimeToDischargeMillis()); } @VisibleForTesting void maybeShowHybridWarning(BatteryStateSnapshot currentSnapshot, BatteryStateSnapshot lastSnapshot) { // if we are now over 45% battery & 6 hours remaining so we can trigger hybrid // notification again if (currentSnapshot.getBatteryLevel() >= CHARGE_CYCLE_PERCENT_RESET && currentSnapshot.getTimeRemainingMillis() > SIX_HOURS_MILLIS) { mLowWarningShownThisChargeCycle = false; mSevereWarningShownThisChargeCycle = false; if (DEBUG) { Slog.d(TAG, "Charge cycle reset! Can show warnings again"); } } final boolean playSound = currentSnapshot.getBucket() != lastSnapshot.getBucket() || lastSnapshot.getPlugged(); if (shouldShowHybridWarning(currentSnapshot)) { mWarnings.showLowBatteryWarning(playSound); // mark if we've already shown a warning this cycle. This will prevent the notification // trigger from spamming users by only showing low/critical warnings once per cycle if (currentSnapshot.getTimeRemainingMillis() <= currentSnapshot.getSevereThresholdMillis() || currentSnapshot.getBatteryLevel() <= currentSnapshot.getSevereLevelThreshold()) { mSevereWarningShownThisChargeCycle = true; mLowWarningShownThisChargeCycle = true; if (DEBUG) { Slog.d(TAG, "Severe warning marked as shown this cycle"); } } else { Slog.d(TAG, "Low warning marked as shown this cycle"); mLowWarningShownThisChargeCycle = true; } } else if (shouldDismissHybridWarning(currentSnapshot)) { if (DEBUG) { Slog.d(TAG, "Dismissing warning"); } mWarnings.dismissLowBatteryWarning(); } else { if (DEBUG) { Slog.d(TAG, "Updating warning"); } mWarnings.updateLowBatteryWarning(); } } @VisibleForTesting boolean shouldShowHybridWarning(BatteryStateSnapshot snapshot) { if (snapshot.getPlugged() || snapshot.getBatteryStatus() == BatteryManager.BATTERY_STATUS_UNKNOWN) { Slog.d(TAG, "can't show warning due to - plugged: " + snapshot.getPlugged() + " status unknown: " + (snapshot.getBatteryStatus() == BatteryManager.BATTERY_STATUS_UNKNOWN)); return false; } // Only show the low warning if enabled once per charge cycle & no battery saver final boolean canShowWarning = snapshot.isLowWarningEnabled() && !mLowWarningShownThisChargeCycle && !snapshot.isPowerSaver() && (snapshot.getTimeRemainingMillis() < snapshot.getLowThresholdMillis() || snapshot.getBatteryLevel() <= snapshot.getLowLevelThreshold()); // Only show the severe warning once per charge cycle final boolean canShowSevereWarning = !mSevereWarningShownThisChargeCycle && (snapshot.getTimeRemainingMillis() < snapshot.getSevereThresholdMillis() || snapshot.getBatteryLevel() <= snapshot.getSevereLevelThreshold()); final boolean canShow = canShowWarning || canShowSevereWarning; if (DEBUG) { Slog.d(TAG, "Enhanced trigger is: " + canShow + "\nwith battery snapshot:" + " mLowWarningShownThisChargeCycle: " + mLowWarningShownThisChargeCycle + " mSevereWarningShownThisChargeCycle: " + mSevereWarningShownThisChargeCycle + "\n" + snapshot.toString()); } return canShow; } @VisibleForTesting boolean shouldDismissHybridWarning(BatteryStateSnapshot snapshot) { return snapshot.getPlugged() || snapshot.getTimeRemainingMillis() > snapshot.getLowThresholdMillis(); } protected void maybeShowBatteryWarning( BatteryStateSnapshot currentSnapshot, BatteryStateSnapshot lastSnapshot) { final boolean playSound = currentSnapshot.getBucket() != lastSnapshot.getBucket() || lastSnapshot.getPlugged(); if (shouldShowLowBatteryWarning(currentSnapshot, lastSnapshot)) { mWarnings.showLowBatteryWarning(playSound); } else if (shouldDismissLowBatteryWarning(currentSnapshot, lastSnapshot)) { mWarnings.dismissLowBatteryWarning(); } else { mWarnings.updateLowBatteryWarning(); } } @VisibleForTesting boolean shouldShowLowBatteryWarning( BatteryStateSnapshot currentSnapshot, BatteryStateSnapshot lastSnapshot) { return !currentSnapshot.getPlugged() && !currentSnapshot.isPowerSaver() && (((currentSnapshot.getBucket() < lastSnapshot.getBucket() || lastSnapshot.getPlugged()) && currentSnapshot.getBucket() < 0)) && currentSnapshot.getBatteryStatus() != BatteryManager.BATTERY_STATUS_UNKNOWN; } @VisibleForTesting boolean shouldDismissLowBatteryWarning( BatteryStateSnapshot currentSnapshot, BatteryStateSnapshot lastSnapshot) { return currentSnapshot.isPowerSaver() || currentSnapshot.getPlugged() || (currentSnapshot.getBucket() > lastSnapshot.getBucket() && currentSnapshot.getBucket() > 0); } private void initThermalEventListeners() { doSkinThermalEventListenerRegistration(); doUsbThermalEventListenerRegistration(); } @VisibleForTesting synchronized void doSkinThermalEventListenerRegistration() { final boolean oldEnableSkinTemperatureWarning = mEnableSkinTemperatureWarning; boolean ret = false; mEnableSkinTemperatureWarning = Settings.Global.getInt(mContext.getContentResolver(), Settings.Global.SHOW_TEMPERATURE_WARNING, mContext.getResources().getInteger(R.integer.config_showTemperatureWarning)) != 0; if (mEnableSkinTemperatureWarning != oldEnableSkinTemperatureWarning) { try { if (mSkinThermalEventListener == null) { mSkinThermalEventListener = new SkinThermalEventListener(); } if (mThermalService == null) { mThermalService = IThermalService.Stub.asInterface( ServiceManager.getService(Context.THERMAL_SERVICE)); } if (mEnableSkinTemperatureWarning) { ret = mThermalService.registerThermalEventListenerWithType( mSkinThermalEventListener, Temperature.TYPE_SKIN); } else { ret = mThermalService.unregisterThermalEventListener(mSkinThermalEventListener); } } catch (RemoteException e) { Slog.e(TAG, "Exception while (un)registering skin thermal event listener.", e); } if (!ret) { mEnableSkinTemperatureWarning = !mEnableSkinTemperatureWarning; Slog.e(TAG, "Failed to register or unregister skin thermal event listener."); } } } @VisibleForTesting synchronized void doUsbThermalEventListenerRegistration() { final boolean oldEnableUsbTemperatureAlarm = mEnableUsbTemperatureAlarm; boolean ret = false; mEnableUsbTemperatureAlarm = Settings.Global.getInt(mContext.getContentResolver(), Settings.Global.SHOW_USB_TEMPERATURE_ALARM, mContext.getResources().getInteger(R.integer.config_showUsbPortAlarm)) != 0; if (mEnableUsbTemperatureAlarm != oldEnableUsbTemperatureAlarm) { try { if (mUsbThermalEventListener == null) { mUsbThermalEventListener = new UsbThermalEventListener(); } if (mThermalService == null) { mThermalService = IThermalService.Stub.asInterface( ServiceManager.getService(Context.THERMAL_SERVICE)); } if (mEnableUsbTemperatureAlarm) { ret = mThermalService.registerThermalEventListenerWithType( mUsbThermalEventListener, Temperature.TYPE_USB_PORT); } else { ret = mThermalService.unregisterThermalEventListener(mUsbThermalEventListener); } } catch (RemoteException e) { Slog.e(TAG, "Exception while (un)registering usb thermal event listener.", e); } if (!ret) { mEnableUsbTemperatureAlarm = !mEnableUsbTemperatureAlarm; Slog.e(TAG, "Failed to register or unregister usb thermal event listener."); } } } private void showWarnOnThermalShutdown() { int bootCount = -1; int lastReboot = mContext.getSharedPreferences(PREFS, 0).getInt(BOOT_COUNT_KEY, -1); try { bootCount = Settings.Global.getInt(mContext.getContentResolver(), Settings.Global.BOOT_COUNT); } catch (Settings.SettingNotFoundException e) { Slog.e(TAG, "Failed to read system boot count from Settings.Global.BOOT_COUNT"); } // Only show the thermal shutdown warning when there is a thermal reboot. if (bootCount > lastReboot) { mContext.getSharedPreferences(PREFS, 0).edit().putInt(BOOT_COUNT_KEY, bootCount).apply(); if (mPowerManager.getLastShutdownReason() == PowerManager.SHUTDOWN_REASON_THERMAL_SHUTDOWN) { mWarnings.showThermalShutdownWarning(); } } } public void dump(FileDescriptor fd, PrintWriter pw, String[] args) { pw.print("mLowBatteryAlertCloseLevel="); pw.println(mLowBatteryAlertCloseLevel); pw.print("mLowBatteryReminderLevels="); pw.println(Arrays.toString(mLowBatteryReminderLevels)); pw.print("mBatteryLevel="); pw.println(Integer.toString(mBatteryLevel)); pw.print("mBatteryStatus="); pw.println(Integer.toString(mBatteryStatus)); pw.print("mPlugType="); pw.println(Integer.toString(mPlugType)); pw.print("mInvalidCharger="); pw.println(Integer.toString(mInvalidCharger)); pw.print("mScreenOffTime="); pw.print(mScreenOffTime); if (mScreenOffTime >= 0) { pw.print(" ("); pw.print(SystemClock.elapsedRealtime() - mScreenOffTime); pw.print(" ago)"); } pw.println(); pw.print("soundTimeout="); pw.println(Settings.Global.getInt(mContext.getContentResolver(), Settings.Global.LOW_BATTERY_SOUND_TIMEOUT, 0)); pw.print("bucket: "); pw.println(Integer.toString(findBatteryLevelBucket(mBatteryLevel))); pw.print("mEnableSkinTemperatureWarning="); pw.println(mEnableSkinTemperatureWarning); pw.print("mEnableUsbTemperatureAlarm="); pw.println(mEnableUsbTemperatureAlarm); mWarnings.dump(pw); } /** * The interface to allow PowerUI to communicate with whatever implementation of WarningsUI * is being used by the system. */ public interface WarningsUI { /** * Updates battery and screen info for determining whether to trigger battery warnings or * not. * @param batteryLevel The current battery level * @param bucket The current battery bucket * @param screenOffTime How long the screen has been off in millis */ void update(int batteryLevel, int bucket, long screenOffTime); void dismissLowBatteryWarning(); void showLowBatteryWarning(boolean playSound); void dismissInvalidChargerWarning(); void showInvalidChargerWarning(); void updateLowBatteryWarning(); boolean isInvalidChargerWarningShowing(); void dismissHighTemperatureWarning(); void showHighTemperatureWarning(); /** * Display USB port overheat alarm */ void showUsbHighTemperatureAlarm(); void showThermalShutdownWarning(); void dump(PrintWriter pw); void userSwitched(); /** * Updates the snapshot of battery state used for evaluating battery warnings * @param snapshot object containing relevant values for making battery warning decisions. */ void updateSnapshot(BatteryStateSnapshot snapshot); } // Skin thermal event received from thermal service manager subsystem @VisibleForTesting final class SkinThermalEventListener extends IThermalEventListener.Stub { @Override public void notifyThrottling(Temperature temp) { int status = temp.getStatus(); if (status >= Temperature.THROTTLING_EMERGENCY) { StatusBar statusBar = getComponent(StatusBar.class); if (statusBar != null && !statusBar.isDeviceInVrMode()) { mWarnings.showHighTemperatureWarning(); Slog.d(TAG, "SkinThermalEventListener: notifyThrottling was called " + ", current skin status = " + status + ", temperature = " + temp.getValue()); } } else { mWarnings.dismissHighTemperatureWarning(); } } } // Usb thermal event received from thermal service manager subsystem @VisibleForTesting final class UsbThermalEventListener extends IThermalEventListener.Stub { @Override public void notifyThrottling(Temperature temp) { int status = temp.getStatus(); if (status >= Temperature.THROTTLING_EMERGENCY) { mWarnings.showUsbHighTemperatureAlarm(); Slog.d(TAG, "UsbThermalEventListener: notifyThrottling was called " + ", current usb port status = " + status + ", temperature = " + temp.getValue()); } } } }
43.80848
100
0.632772
52e5d4083737d42a08a5ad3208797ff8645a3c96
4,040
// Copyright (C) 2013 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.client.changes; import com.google.gerrit.client.account.AccountInfo; import com.google.gerrit.client.diff.CommentRange; import com.google.gerrit.extensions.client.Side; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwtjsonrpc.client.impl.ser.JavaSqlTimestamp_JsonSerializer; import java.sql.Timestamp; public class CommentInfo extends JavaScriptObject { public static CommentInfo create(String path, Side side, int line, CommentRange range) { CommentInfo n = createObject().cast(); n.path(path); n.side(side); if (range != null) { n.line(range.end_line()); n.range(range); } else if (line > 0) { n.line(line); } return n; } public static CommentInfo createReply(CommentInfo r) { CommentInfo n = createObject().cast(); n.path(r.path()); n.side(r.side()); n.in_reply_to(r.id()); if (r.has_range()) { n.line(r.range().end_line()); n.range(r.range()); } else if (r.has_line()) { n.line(r.line()); } return n; } public static CommentInfo copy(CommentInfo s) { CommentInfo n = createObject().cast(); n.path(s.path()); n.side(s.side()); n.id(s.id()); n.in_reply_to(s.in_reply_to()); n.message(s.message()); if (s.has_range()) { n.line(s.range().end_line()); n.range(s.range()); } else if (s.has_line()) { n.line(s.line()); } return n; } public final native void path(String p) /*-{ this.path = p }-*/; public final native void id(String i) /*-{ this.id = i }-*/; public final native void line(int n) /*-{ this.line = n }-*/; public final native void range(CommentRange r) /*-{ this.range = r }-*/; public final native void in_reply_to(String i) /*-{ this.in_reply_to = i }-*/; public final native void message(String m) /*-{ this.message = m }-*/; public final void side(Side side) { sideRaw(side.toString()); } private final native void sideRaw(String s) /*-{ this.side = s }-*/; public final native String path() /*-{ return this.path }-*/; public final native String id() /*-{ return this.id }-*/; public final native String in_reply_to() /*-{ return this.in_reply_to }-*/; public final Side side() { String s = sideRaw(); return s != null ? Side.valueOf(s) : Side.REVISION; } private final native String sideRaw() /*-{ return this.side }-*/; public final Timestamp updated() { Timestamp r = updatedTimestamp(); if (r == null) { String s = updatedRaw(); if (s != null) { r = JavaSqlTimestamp_JsonSerializer.parseTimestamp(s); updatedTimestamp(r); } } return r; } private final native String updatedRaw() /*-{ return this.updated }-*/; private final native Timestamp updatedTimestamp() /*-{ return this._ts }-*/; private final native void updatedTimestamp(Timestamp t) /*-{ this._ts = t }-*/; public final native AccountInfo author() /*-{ return this.author }-*/; public final native int line() /*-{ return this.line || 0 }-*/; public final native boolean has_line() /*-{ return this.hasOwnProperty('line') }-*/; public final native boolean has_range() /*-{ return this.hasOwnProperty('range') }-*/; public final native CommentRange range() /*-{ return this.range }-*/; public final native String message() /*-{ return this.message }-*/; protected CommentInfo() { } }
33.94958
88
0.65
2342226717b7b142a8c11ae527c0e6e5042ab13b
546
/* * @lc app=leetcode id=470 lang=java * * [470] Implement Rand10() Using Rand7() * 方法一:拒绝采样 */ // @lc code=start /** * The rand7() API is already defined in the parent class SolBase. * public int rand7(); * @return a random integer in the range 1 to 7 */ class Solution extends SolBase { public int rand10() { int row, col, idx; do { row = rand7(); col = rand7(); idx = col + (row - 1) * 7; } while (idx > 40); return 1 + (idx - 1) % 10; } } // @lc code=end
20.222222
66
0.521978
d15b1ddbb413de4cfc53ffb43a6858777cb15621
2,067
package net.kunmc.lab.fastmob; import dev.kotx.flylib.command.Command; import dev.kotx.flylib.command.CommandContext; public class MainCommand extends Command { public MainCommand() { super("fastmob"); children(new Command("enderDragonSpeed") { { usage(builder -> { builder.doubleArgument("speed") .executes(ctx -> { Config.enderDragonSpeed = ((Double) ctx.getTypedArgs().get(0)); ctx.success("enderDragonSpeedを" + Config.enderDragonSpeed + "に変更しました."); }); }); } }); children(new Command("otherMobsSpeed") { { usage(builder -> { builder.doubleArgument("speed") .executes(ctx -> { Config.otherMobsSpeed = ((Double) ctx.getTypedArgs().get(0)); ctx.success("otherMobsSpeedを" + Config.otherMobsSpeed + "に変更しました."); }); }); } }); children(new Command("check") { @Override public void execute(CommandContext ctx) { ctx.success("enderDragonSpeed: " + Config.enderDragonSpeed); ctx.success("otherMobsSpeed: " + Config.otherMobsSpeed); ctx.success("maxEnderDragonDistance: " + FastMob.maxEnderDragonDistance); } }); children(new Command("maxEnderDragonDistance") { { usage(builder -> { builder.doubleArgument("distance") .executes(ctx -> { FastMob.maxEnderDragonDistance = ((Double) ctx.getTypedArgs().get(0)); ctx.success("maxEnderDragonDistanceの値を" + FastMob.maxEnderDragonDistance + "に変更しました."); }); }); } }); } }
36.910714
119
0.465409
8b5195cc66c786a9be69294ade830a364b6ee013
460
package models; import io.ebean.Finder; import io.ebean.Model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.ManyToOne; import java.util.Date; @Entity public class Vote extends Model { @ManyToOne public Person person; @ManyToOne public Review review; @Column(name = "created_at") public Date createdAt; public static final Finder<Long, Vote> find = new Finder<>(Vote.class); }
16.428571
75
0.726087
c15f91dc5b2a4517aeacbdb3115e2335ee914f3e
292
package com.kristijangeorgiev.softdelete.service; import org.springframework.stereotype.Service; import com.kristijangeorgiev.softdelete.model.entity.pk.PermissionRolePK; @Service public interface PermissionRoleService extends BaseService { public void softDelete(PermissionRolePK id); }
26.545455
73
0.85274
ecbeccb374d197858e732cd350464272a39455ee
2,561
package com.psychic_engine.cmput301w17t10.feelsappman.Controllers; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import com.psychic_engine.cmput301w17t10.feelsappman.Enums.MoodState; import com.psychic_engine.cmput301w17t10.feelsappman.Enums.SocialSetting; import com.psychic_engine.cmput301w17t10.feelsappman.Models.Mood; abstract class MoodController { static Mood selectMood(String moodString) { Mood mood; switch (moodString) { case "Sad": mood = new Mood(MoodState.SAD); break; case "Happy": mood = new Mood(MoodState.HAPPY); break; case "Shame": mood = new Mood(MoodState.SHAME); break; case "Fear": mood = new Mood(MoodState.FEAR); break; case "Anger": mood = new Mood(MoodState.ANGER); break; case "Surprised": mood = new Mood(MoodState.SURPRISED); break; case "Disgust": mood = new Mood(MoodState.DISGUST); break; case "Confused": mood = new Mood(MoodState.CONFUSED); break; default: mood = null; } return mood; } static SocialSetting selectSocialSetting(String settingString) { SocialSetting socialSetting; switch (settingString) { case "Alone": socialSetting = SocialSetting.ALONE; break; case "One Other": socialSetting = SocialSetting.ONEOTHER; break; case "Two To Several": socialSetting = SocialSetting.TWOTOSEVERAL; break; case "Crowd": socialSetting = SocialSetting.CROWD; break; default: socialSetting = null; } return socialSetting; } //http://www.ssaurel.com/blog/how-to-check-if-internet-connection-is-enabled-in-android/ // - S.Saurel //obtained April 1, 2017 public static boolean isConnected(Context context) { ConnectivityManager cm = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); return activeNetwork != null && activeNetwork.isConnectedOrConnecting(); } }
32.417722
92
0.565795
d1a08e57e7fe70a358bc2ae13f1248f6de89690c
39,855
package lejos.pc.charting; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Shape; import java.awt.event.MouseEvent; import javax.swing.JFrame; import lejos.pc.charting.data.XYZDataItem; import lejos.pc.charting.data.XYZSeriesCollection; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.AxisLocation; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.labels.StandardXYToolTipGenerator; import org.jfree.chart.plot.DefaultDrawingSupplier; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.AbstractRenderer; import org.jfree.chart.renderer.xy.XYBubbleRenderer; import org.jfree.chart.renderer.xy.XYItemRenderer; import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYSeries; import org.jfree.ui.RectangleEdge; import org.jfree.ui.RectangleInsets; /** * Base XY ChartPanel implementation. Use this to create XYZSeriesCollection-based JFreeChart GUIs * * @author kirk * */ abstract class BaseXYChart extends ChartPanel { // final String THISCLASS; /** * The maximum number of axes you should support */ static final int RANGE_AXIS_COUNT = 4; /** * The suggested refresh frequency in milliseconds for updater threads */ static final int REFRESH_FREQUENCY_MS = 500; private static final float NORMAL_SERIES_LINE_WEIGHT = 0.5f; /** * No domain range limiting */ protected static final int DAL_UNLIMITED = 0; /** * Domain range limiting by Time (in ms) */ protected static final int DAL_TIME = 1; /** * Domain range limiting by Count (# of domain items in dataset(s)) */ protected static final int DAL_COUNT = 2; /** * Used to indicate the chart data has been changed and needs a redraw */ volatile boolean chartDirty = false; /** * metadata of each series added to chart via setSeries() * * @author kirk * */ private class SeriesDef { String seriesLabel; int axisIndex; // Corresponds to dataset(index) for axis 1-4. could be sparse meaning we can have non-consecutive axis indexes int seriesIndex; // Corresponds to series(index) in a dataset. is not sparse. } /** * each seriesdef is series definition of a series with label, axis idx (1-4), and * series idx */ private SeriesDef[] seriesDefs; /** * use solely for synchronization across this and subclasses. Mainly for paint/graphics/render because we * don't want to be adding data in one thread and have the chart do a paint/render in another (null pointer * exceptions based empirical experience) */ Object lockObj1 = new Object(); boolean emptyChart = true; boolean scrollDomain = true; MarkerManager markerManager = null; MouseManager mouseManager = null; private int chartType; Shape[] seriesShapes = new Shape[10]; /** * Used to track series collection (i.e dataset and one collection of series per chart axis). Maximum # of axes * is RANGE_AXIS_COUNT (4). used in setSeries() * * @author kirk * */ private class DatasetAndAxis { XYZSeriesCollection datasetObj = null; //XYItemRenderer axisRenderer; // TODO to hold a renderer ref NumberAxis numberAxisObj = null; } /** * Used to track series collection (one per chart axis) and axes (up to 4 (RANGE_AXIS_COUNT)) */ private DatasetAndAxis[] datasetsAndAxes = null; // set in constructor and // in setSeries() protected BaseXYChart(JFreeChart chart) { super(chart); // init the instance datasets and axes holding object this.datasetsAndAxes = initDatasetAndAxisArray(); // Effectively disable font scaling/skewing // JFreeChart forum: Graphics context and custom shapes // http://www.jfree.org/forum/viewtopic.php?f=3&t=24499&hilit=font+scaling this.setMaximumDrawWidth(1800); this.setMaximumDrawHeight(1280); } /** * @return a new DatasetAndAxis array of RANGE_AXIS_COUNT length */ private DatasetAndAxis[] initDatasetAndAxisArray() { DatasetAndAxis[] dAndDaArray = new DatasetAndAxis[RANGE_AXIS_COUNT]; for (int i = 0; i < dAndDaArray.length; i++) { dAndDaArray[i] = new DatasetAndAxis(); } return dAndDaArray; } // /** // * Return a new or cached/pooled NumberAxis. If a cached one doesn't exist // * for index, create one for index and return it. // * // * @param index // * The Axis index (1-4 as per RANGE_AXIS_COUNT) // * @param dAnda // * the // * @return the axis ref // */ // private NumberAxis getTheRangeAxis(int index, DatasetAndAxis[] dAnda) { //// String axisLabel; //// if (this.chartType == LoggerProtocolManager.CT_XY_TIMEDOMAIN) { //// axisLabel = "Range"; //// } else { //// axisLabel = "Y"; //// } // // if (dAnda[index].numberAxisObj != null) { //// dAnda[index].numberAxisObj.setLabel(axisLabel); // return dAnda[index].numberAxisObj; // } // // Color axisColor = getAxisColor(index); // //// if (index > 0) { //// axisLabel += "-" + (index + 1); //// } // // NumberAxis rangeAxis = this.getAxisInstance("undefined", axisColor); // dAnda[index].numberAxisObj = rangeAxis; // // return rangeAxis; // } /** * helper method to Get a single XYZSeriesCollection based on axis metadata * in passed DatasetAndAxis[] array. Return from pool if exists otherwise it * creates one, and adds it to pool, and returns it. * <p> * One renderer per axis/dataset(XYZSeriesCollection) * * @param axisIndex The axis index value 0-(RANGE_AXIS_COUNT-1) * @param chart The target JFreeChart to get plot info from * @param dAnda the metadata to manage single XYZSeriesCollection (comprised of series) per axis * @return a XYZSeriesCollection to use for a graph XY series per axis */ private XYZSeriesCollection getAxisDataset(int axisIndex, JFreeChart chart, DatasetAndAxis[] dAnda) { String axisLabel; if (this.chartType == LoggerProtocolManager.CT_XY_TIMEDOMAIN) { axisLabel = "Range"; } else { axisLabel = "Y"; } if (axisIndex > 0) { axisLabel += "-" + (axisIndex + 1); } if (dAnda[axisIndex].datasetObj != null) { dAnda[axisIndex].numberAxisObj.setLabel(axisLabel); chart.getXYPlot().getRangeAxis(axisIndex).setLabel(axisLabel); return dAnda[axisIndex].datasetObj; } XYZSeriesCollection dataset = new XYZSeriesCollection(); chart.getXYPlot().setDataset(axisIndex, dataset); // get the axis def // NumberAxis rangeAxis = getTheRangeAxis(axisIndex, dAnda); Color axisColor = getAxisColor(axisIndex); NumberAxis rangeAxis = this.getAxisInstance(axisLabel, axisColor); dAnda[axisIndex].numberAxisObj = rangeAxis; chart.getXYPlot().setRangeAxis(axisIndex, rangeAxis); AxisLocation axloc; if (axisIndex % 2 == 0) { // even on left axloc = AxisLocation.BOTTOM_OR_LEFT; } else { axloc = AxisLocation.BOTTOM_OR_RIGHT; } chart.getXYPlot().setRangeAxisLocation(axisIndex, axloc); chart.getXYPlot().mapDatasetToRangeAxis(axisIndex, axisIndex); chart.getXYPlot().setRangeCrosshairVisible(true); // assign back into the passed array dAnda[axisIndex].datasetObj = dataset; return dataset; } /** * adds XYSeries and maps axis/dataseries from datasetsAndAxes[] as per * pre-defined this.seriesDefs[] set in the setSeries() method. setSeries() does the creation of the * seriesDefs[]. Creates the datasets per axisID one-to-one using defs in seriesDefs[] * * addDataSets(getChart(), false); * * @param chart * the JFreeChart * @param spawnable * true to reassign axis labels (use if a spawn) */ private void addDataSets(JFreeChart chart, boolean spawnable) { DatasetAndAxis[] tempDandA; String[] axisLabels = null; // if flagged as a copy, make new DatasetAndAxis[] if (spawnable) { tempDandA = initDatasetAndAxisArray(); // track existing [possible custom] axis labels axisLabels = new String[tempDandA.length]; for (int i = 0; i < tempDandA.length; i++) { if (getChart().getXYPlot().getRangeAxis(i) != null) { axisLabels[i] = getChart().getXYPlot().getRangeAxis(i).getLabel(); } } } else { // otherwise, use the established instance var // set the ref to the instance var to use in in getAxisDataset() // method call below tempDandA = this.datasetsAndAxes; } // create a set of renderers for [potential] axes // TODO fix inefficiency by only creating per needed axisIndex based on seriesDefs[] XYItemRenderer[] rendererSet = new XYItemRenderer[RANGE_AXIS_COUNT]; for (int i=0;i<rendererSet.length;i++){ switch (this.chartType) { case LoggerProtocolManager.CT_XY_TIMEDOMAIN: rendererSet[i] = getTimeSeriesRenderer(i); break; case LoggerProtocolManager.CT_XY_SCATTER: rendererSet[i] = getScatterRenderer(i); break; case LoggerProtocolManager.CT_XYZ_BUBBLE: rendererSet[i] = getBubbleRenderer(i); break; default: // TODO do we need this? rendererSet[i] = getTimeSeriesRenderer(i); } } // create the datasets per axisID one-one. this.seriesDefs[] set in setSeries() for (int i = 0; i < this.seriesDefs.length; i++) { XYZSeriesCollection xysc = getAxisDataset(this.seriesDefs[i].axisIndex, chart, tempDandA); // set the renderer per axisIndex chart.getXYPlot().setRenderer(this.seriesDefs[i].axisIndex, rendererSet[this.seriesDefs[i].axisIndex]); // change alpha of bubble plot to show transparency if (this.chartType == LoggerProtocolManager.CT_XYZ_BUBBLE) { chart.getXYPlot().setForegroundAlpha(0.65f); } else { chart.getXYPlot().setForegroundAlpha(1.0f); } // change autosort=true for XY timeseries. No sorting screws up performance in mouseManager XYSeries xys; if (this.chartType == LoggerProtocolManager.CT_XY_TIMEDOMAIN) { xys = new XYSeries(this.seriesDefs[i].seriesLabel, true, true); } else { xys = new XYSeries(this.seriesDefs[i].seriesLabel, false, true); } xysc.addSeries(xys); // assign tooltip generators to each series chart.getXYPlot() .getRenderer(this.seriesDefs[i].axisIndex) .setSeriesToolTipGenerator(this.seriesDefs[i].seriesIndex, new StandardXYToolTipGenerator()); } // reassign axis labels if a spawn if (spawnable) { for (int i = 0; i < tempDandA.length; i++) { if (chart.getXYPlot().getRangeAxis(i) != null) { chart.getXYPlot().getRangeAxis(i).setLabel(axisLabels[i]); } } } // set colors for series int colorIndex = 0; for (int i = 0; i < chart.getXYPlot().getDatasetCount(); i++) { if (chart.getXYPlot().getDataset(i) == null) continue; for (int ii = 0; ii < chart.getXYPlot().getDataset(i).getSeriesCount(); ii++) { chart.getXYPlot().getRenderer(i).setSeriesPaint(ii, getSeriesColor(colorIndex)); // getSeriesShape chart.getXYPlot().getRenderer(i).setSeriesShape(ii, getSeriesShape(ii)); colorIndex++; chart.getXYPlot().getRenderer(i).setSeriesStroke(ii, new BasicStroke(NORMAL_SERIES_LINE_WEIGHT, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL)); } } } /** * Return a baseline, initialized chart object as per desired type * @return a chart */ //abstract JFreeChart getBaselineChart(); JFreeChart getBaselineChart(){ // create the plot object to pass to the chart XYPlot plot = new XYPlot(); //this.dataset[0], domainAxis, getRangeAxis(1), renderer); plot.setBackgroundPaint(Color.lightGray); plot.setDomainGridlinePaint(Color.white); plot.setRangeGridlinePaint(Color.white); plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0)); // set the domain axis NumberAxis domainAxis = getAxisInstance("Time (ms)", Color.black); plot.setDomainAxis(domainAxis); plot.setDomainPannable(true); plot.setDomainCrosshairVisible(true); plot.setRangePannable(true); plot.setDataset(new XYZSeriesCollection()); // create and return the chart JFreeChart chart = new JFreeChart("", new Font("Arial", Font.BOLD, 14), plot, true); chart.setNotify(false); chart.setBackgroundPaint(Color.white); chart.getLegend().setPosition(RectangleEdge.RIGHT); chart.getLegend().setItemFont(new Font("Arial", Font.PLAIN, 10)); return chart; } /** * Spawn a copy of the current chart in a new window. * * @return true for success * @throws OutOfMemoryError */ boolean spawnChartCopy() throws OutOfMemoryError { if (this.emptyChart) return false; dbg("Constructing chart clone: \"" + getChart().getTitle().getText() + "\".."); JFreeChart chartClone=getBaselineChart(); int pointCounter=0; //adds XYSeries and maps axis/dataseries as per seriesDefs[] addDataSets(chartClone, true); XYSeries seriesClone=null; XYItemRenderer ir; for (int i=0;i<chartClone.getXYPlot().getDatasetCount();i++) { if (chartClone.getXYPlot().getDataset(i)==null) continue; ir=getChart().getXYPlot().getRenderer(i); int seriesCount=chartClone.getXYPlot().getDataset(i).getSeriesCount(); for (int j=0;j<seriesCount;j++) { // hide the series if "hidden" by user through GUI and is a timeseries chart if (this.chartType != LoggerProtocolManager.CT_XYZ_BUBBLE) { // TODO cleanup handling of bubble chart XYLineAndShapeRenderer temp_ir = (XYLineAndShapeRenderer) ir; if (temp_ir.getSeriesLinesVisible(j)==null) temp_ir.setSeriesLinesVisible(j,true); // because will return null if never defined through API if (!temp_ir.getSeriesLinesVisible(j).booleanValue()) { chartClone.getXYPlot().getRenderer(i).setSeriesVisible(j, new Boolean(false)); dbg("Excluding series \"" + ir.getLegendItem(i,j).getLabel() + "\""); if (!(i==0 && j==0)) continue; //and don't add data if not base dataset (we need it for marker calcs) } } // dupe the data seriesClone=((XYZSeriesCollection)getChart().getXYPlot().getDataset(i)).getSeries(j); int seriesLength = seriesClone.getItemCount(); for (int k=0;k<seriesLength;k++){ XYZDataItem xyzCloneItem = (XYZDataItem)seriesClone.getDataItem(k); ((XYZSeriesCollection)chartClone.getXYPlot().getDataset(i)).getSeries(j).add (new XYZDataItem(xyzCloneItem), false); pointCounter++; if (pointCounter%1000==0) { chartClone.setNotify(true); chartClone.setNotify(false); } } } } // hide unused axes for (int i = 0; i < chartClone.getXYPlot().getDatasetCount(); i++) { if (chartClone.getXYPlot().getDataset(i) == null) { continue; } boolean hasData=false; for (int j=0;j<chartClone.getXYPlot().getDataset(i).getSeriesCount();j++) { if (((XYZSeriesCollection)chartClone.getXYPlot().getDataset(i)).getSeries(j).getItemCount()>0) { hasData=true; break; // we can break I think because of the assumption of consecutive series IDs? } } if (!hasData) { chartClone.getXYPlot().getRangeAxis(i).setVisible(false); dbg("Removing unused axis \"" + chartClone.getXYPlot().getRangeAxis(i).getLabel() + "\""); } } SpawnChartPanel spawnpanel = new SpawnChartPanel(chartClone, this.chartType); // chartClone.setNotify(false); SpawnChartFrame frame = new SpawnChartFrame(spawnpanel); frame.setIconImage(((JFrame)this.getTopLevelAncestor()).getIconImage()); // SpawnChartPanel spawnpanel = new SpawnChartPanel(chartClone); if (markerManager.isCommentsVisible()) { // add comment markers spawnpanel.importMarkers(markerManager.cloneMarkers()); } // copy the current title chartClone.getTitle().setText(getChart().getTitle().getText()); frame.setTitle("Chart: " + getChart().getTitle().getText()); chartClone.getXYPlot().getDomainAxis().setLabel(getChart().getXYPlot().getDomainAxis().getLabel()); dbg("Cloning complete"); return true; } /* * public BaseXYChart(JFreeChart chart, boolean useBuffer) { super(chart, * useBuffer); } * * public BaseXYChart(JFreeChart chart, boolean properties, boolean save, * boolean print, boolean zoom, boolean tooltips) { super(chart, properties, * save, print, zoom, tooltips); } * * public BaseXYChart(JFreeChart chart, int width, int height, int * minimumDrawWidth, int minimumDrawHeight, int maximumDrawWidth, int * maximumDrawHeight, boolean useBuffer, boolean properties, boolean save, * boolean print, boolean zoom, boolean tooltips) { super(chart, width, * height, minimumDrawWidth, minimumDrawHeight, maximumDrawWidth, * maximumDrawHeight, useBuffer, properties, save, print, zoom, tooltips); } * * public BaseXYChart(JFreeChart chart, int width, int height, int * minimumDrawWidth, int minimumDrawHeight, int maximumDrawWidth, int * maximumDrawHeight, boolean useBuffer, boolean properties, boolean copy, * boolean save, boolean print, boolean zoom, boolean tooltips) { * super(chart, width, height, minimumDrawWidth, minimumDrawHeight, * maximumDrawWidth, maximumDrawHeight, useBuffer, properties, copy, save, * print, zoom, tooltips); } */ void setDomainScrolling(boolean scrollDomain) { this.scrollDomain = scrollDomain; } void setChartDirty() { getChart().setNotify(true); this.chartDirty = true; } boolean isEmptyChart() { return this.emptyChart; } /** * * @return If any data has been added to the data series (using [timestamp] series 0) */ boolean hasData() { boolean retval = false; if (getChart().getXYPlot().getDataset() != null) { try { // dbg("series 0 item count=" + getChart().getXYPlot().getDataset().getItemCount(0)); retval = (getChart().getXYPlot().getDataset().getItemCount(0) > 0); } catch (IllegalArgumentException e) { // do nothing } } return retval; } @Override public void mouseMoved(MouseEvent e) { if (mouseManager.doMouseMoved(e)) { super.mouseMoved(e); } } @Override public void mouseDragged(MouseEvent e) { if (mouseManager.doMouseDragged(e)) { super.mouseDragged(e); } } @Override public void mouseClicked(MouseEvent e) { if (mouseManager.doMouseClicked(e)) { super.mouseClicked(e); } } @Override public void paintComponent(Graphics g) { synchronized (lockObj1) { try { super.paintComponent(g); } catch (NullPointerException e) { // ignore } } } void doWait(long milliseconds) { try { Thread.sleep(milliseconds); } catch (InterruptedException e) { // Thread.currentThread().interrupt(); } } /** * Set the passed series/header definitions as new XYseries in the dataset. * Existing series are wiped. Must be at least two items in the array or any * existing series is left intact and method exits with 0. First item * (series 0) is set as domain label and should always be system [relative] time in * milliseconds, and is always axis 0 for multi-axis charts. * <p> * For X-Y scatter, 2 seriesNames for each dataset, first is X, second is Y. Timestamp (column 0, series Names[0]) * is not displayed but TODO may be used in series DataItem comment. NXT-side client appends "-X" and "-Y" to * seriesNames from setColumns() call which should be stripped here to set the series name [taken from the * X column name for the series] (see {@link LoggerProtocolManager#CT_XY_TIMEDOMAIN}, etc.) * * <p> * The string format/structure of each string field is:<br> * <code>[name]:[axis ID 1-4]</code> <br> * i.e. * * <pre> * &quot;MySeries:1&quot; * </pre> * * @param seriesNames Array of series names * @param chartType The chart type. * @return The number of series created * @see LoggerProtocolManager#CT_XY_POLAR * @see LoggerProtocolManager#CT_XY_SCATTER * @see LoggerProtocolManager#CT_XY_TIMEDOMAIN * @see LoggerProtocolManager#CT_XYZ_BUBBLE */ int setSeries(String[] seriesNames, int chartType) { // don't allow empty range (length==1 means only domain series // (timestamp) defined) // System.out.println("*** Chart type=" + chartType); if (seriesNames.length < 2) { return 0; } // set the chart type to use for setting data points correctly in seriesCollections, etc. this.chartType = chartType; mouseManager.setChartType(chartType); // ************* Clear/init any series, etc. // init a new instance datasets and axes holding object of length RANGE_AXIS_COUNT this.datasetsAndAxes = initDatasetAndAxisArray(); // clear all series in all datasets (i.e. axes) and set all axes to axis 0 int dsCount = getChart().getXYPlot().getDatasetCount(); // should always be 4 or less as per RANGE_AXIS_COUNT for (int i = 0; i < dsCount; i++) { getChart().getXYPlot().mapDatasetToRangeAxis(i, 0); getChart().getXYPlot().setRangeAxis(i, null); // delete all series in the dataset if exists (clear the chart) XYDataset ds = getChart().getXYPlot().getDataset(i); if (ds != null) { ((XYZSeriesCollection)ds).removeAllSeries(); } } // used to disable zoom extent calc when there is no data this.emptyChart = true; // remove any measuring markers and clear any comments this.markerManager.measureToolsOff(); this.markerManager.clearComments(); // int yExtents so extents will be calculated for new data //resetYExtents(); // remove domain def (series 0 => milliseconds) from series def string array String[] fields; String[] theSeries; // create series as per chartType int seriesOffset = 1; String domainTimeseriesAxisLabel = "X"; switch (this.chartType) { case LoggerProtocolManager.CT_XY_SCATTER: seriesOffset = 2; break; case LoggerProtocolManager.CT_XYZ_BUBBLE: seriesOffset = 3; break; case LoggerProtocolManager.CT_XY_TIMEDOMAIN: default: // Parse and set the domain (X => milliseconds) label fields = seriesNames[0].split(":"); domainTimeseriesAxisLabel = fields[0]; } // set length of series name array based on chart type theSeries = new String[(seriesNames.length - 1) / seriesOffset]; int tempIndex = 0; // skip element 0 (timestamp) for (int i=1;i<seriesNames.length;i=i+seriesOffset){ try { theSeries[tempIndex++] = seriesNames[i]; } catch (ArrayIndexOutOfBoundsException e) { // dbg("setSeries(): ArrayIndexOutOfBoundsException caught. Most likely " + // "a column count mismatch per chartType (" + this.chartType +"). " + // "Columns after index " + i + " are ignored."); break; } } // System.arraycopy(seriesNames, 1, theSeries, 0, theSeries.length); getChart().getXYPlot().getDomainAxis().setLabel(domainTimeseriesAxisLabel); // ************ End of clear/init // create seriesDefs. This is metadata used to construct the chart object specifics in addDataSets() this.seriesDefs = new SeriesDef[theSeries.length]; // used as a consecutive series counter contextual for each axis id int[] axisSeriesIndex = new int[RANGE_AXIS_COUNT]; for (int i = 0; i < RANGE_AXIS_COUNT; i++) { axisSeriesIndex[i] = 0; } // fill the seriesDefs array int minAxisId = RANGE_AXIS_COUNT; for (int i = 0; i < theSeries.length; i++) { this.seriesDefs[i] = new SeriesDef(); fields = theSeries[i].split(":"); // dbg("fields[0]=" + fields[0]); this.seriesDefs[i].seriesLabel = parseOutXYZ(fields[0]); // TODO may need to process by 2 to get both X and Y labels depending on chart type // if no axis and chartable attributes defined in series def string, and not a timeseries charttype, // use default axis index if (fields.length == 1 || this.chartType != LoggerProtocolManager.CT_XY_TIMEDOMAIN) { this.seriesDefs[i].axisIndex = 0; } else { try { this.seriesDefs[i].axisIndex = Integer.valueOf(fields[1]) .intValue() - 1; // 1-based label [from datalogger // header] to zero-based internal // / check and force if violated if (this.seriesDefs[i].axisIndex < 0 || seriesDefs[i].axisIndex > 3) { this.seriesDefs[i].axisIndex = 0; } } catch (Exception e) { this.seriesDefs[i].axisIndex = 0; } } // need to ensure that dataset(0) is always created (TODO JFreeChart is unhappy if not? KPT 9.14.13) // shift all series defs to ensure zero-based dataset if (this.seriesDefs[i].axisIndex < minAxisId) minAxisId = this.seriesDefs[i].axisIndex; // bump series index per axis (contiguous) this.seriesDefs[i].seriesIndex = axisSeriesIndex[this.seriesDefs[i].axisIndex]++; } // We need to ensure that dataset(0) is always created so a shift offset is used for (int i = 0; i < this.seriesDefs.length; i++) { this.seriesDefs[i].axisIndex -= (minAxisId); // [potentially] shift all // axisIDs down to ensure we // have a axisID=0 } // create the datasets (XYZSeriesCollections) per axisID one-to-one using defs in seriesDefs[] addDataSets(getChart(), false); chartDirty = true; return getChart().getXYPlot().getSeriesCount(); } private String parseOutXYZ(String fieldName){ if (fieldName.substring(fieldName.length()-2).matches("-([xX]|[yY]|[zZ])")){ return fieldName.substring(0, fieldName.length()-2); } return fieldName; } void dbg(String msg) { System.out.println("BaseXYChart" + "-" + msg); } /**Add series data to the dataset. Pass a double array of series values that all share the same domain value (element 0). * The number of values must match the header count in setSeries(). * <p> * Element 0 is the timestamp and should be the domain (X) series for {@link LoggerProtocolManager#CT_XY_TIMEDOMAIN} * @param seriesData the series data as <code>double</code>s * @see #setDomainLimiting */ void addDataPoints(double[] seriesData) { if (seriesData.length<2) { dbg("!** addDataPoints: Not enough data. length=" + seriesData.length); return; } // seriesData[0]: first element should always be timestamp from NXT // add the datapoint series by series in correct axis ID XYPlot plot= getChart().getXYPlot(); XYSeries tempSeries=null; int seriesOffset = 1; switch (this.chartType) { case LoggerProtocolManager.CT_XY_SCATTER: seriesOffset = 2; break; case LoggerProtocolManager.CT_XYZ_BUBBLE: seriesOffset = 3; break; case LoggerProtocolManager.CT_XY_TIMEDOMAIN: default: } synchronized (lockObj1) { int tempIndex = 0; for (int i=1;i<seriesData.length;i=i+seriesOffset) { // 1-based to ignore the ms value that is the first element/column sent XYZDataItem dataItem; try {tempSeries=((XYZSeriesCollection)plot.getDataset(this.seriesDefs[tempIndex].axisIndex)) .getSeries(this.seriesDefs[tempIndex].seriesIndex); } catch (ArrayIndexOutOfBoundsException e) { // ignore the rest of the data. This state will happen when the same thing happens in setSeries() // dbg("addDataPoints(): ArrayIndexOutOfBoundsException caught. Most likely " + // "a column count mismatch per chartType (" + this.chartType +"). " + // "Columns after index " + i + " are ignored."); break; } tempIndex++; switch (this.chartType) { case LoggerProtocolManager.CT_XY_SCATTER: dataItem = new XYZDataItem(seriesData[i], seriesData[i+1], 0); break; case LoggerProtocolManager.CT_XYZ_BUBBLE: dataItem = new XYZDataItem(seriesData[i], seriesData[i+1], seriesData[i+2]); break; case LoggerProtocolManager.CT_XY_TIMEDOMAIN: default: dataItem = new XYZDataItem(seriesData[0], seriesData[i], 0); } // tempSeries=((XYZSeriesCollection)plot.getDataset(this.seriesDefs[i-1].axisIndex)).getSeries(this.seriesDefs[i-1].seriesIndex); // TODO change below for Time series , XY Scatter, etc. // XYZDataItem dataItem = new XYZDataItem(seriesData[0], seriesData[i], -99.8); // TODO use real Z tempSeries.add(dataItem, false); } } // the updater thread picks this up every xxx ms and has the JFreeChart do it's notifications for rendering, // etc. The domain axis is also scrolled for incoming data in this thread this.chartDirty=true; if (this.emptyChart) this.emptyChart=false; } private NumberAxis getAxisInstance(String axisLabel, Color axisColor) { NumberAxis workingAxis; workingAxis = new NumberAxis(axisLabel); workingAxis.setTickLabelFont(new Font("Arial", Font.PLAIN, 9)); workingAxis.setLabelFont(new Font("Arial", Font.PLAIN, 12)); workingAxis.setStandardTickUnits(NumberAxis.createStandardTickUnits()); workingAxis.setTickLabelsVisible(true); workingAxis.setLowerMargin(.01); workingAxis.setUpperMargin(.01); workingAxis.setAutoRange(false); workingAxis.setAutoRangeIncludesZero(false); // set colors workingAxis.setLabelPaint(axisColor); workingAxis.setAxisLinePaint(axisColor); workingAxis.setLabelPaint(axisColor); workingAxis.setTickLabelPaint(axisColor); workingAxis.setTickMarkPaint(axisColor); return workingAxis; } /** * Instantiate a XYLineAndShapeRenderer. One per axis is the intended use. Color is determined by axisIndex * with getAxisColor(). * * @param axisIndex * @return the renderer */ private XYLineAndShapeRenderer getTimeSeriesRenderer(int axisIndex) { Color seriesColor = getAxisColor(axisIndex); XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(); setBaseRenderer(renderer, seriesColor); renderer.setBaseShapesVisible(false); return renderer; } private XYLineAndShapeRenderer getScatterRenderer(int axisIndex){ XYLineAndShapeRenderer renderer = getTimeSeriesRenderer(axisIndex); renderer.setUseOutlinePaint(true); renderer.setBaseShapesVisible(true); renderer.setBaseLinesVisible(false); return renderer; } private XYBubbleRenderer getBubbleRenderer(int axisIndex) { Color seriesColor = getAxisColor(axisIndex); XYBubbleRenderer renderer = new XYBubbleRenderer(XYBubbleRenderer.SCALE_ON_DOMAIN_AXIS); setBaseRenderer(renderer, seriesColor); renderer.setBaseOutlinePaint(Color.DARK_GRAY); return renderer; } private void setBaseRenderer(AbstractRenderer renderer, Color seriesColor) { // set the renderer renderer.setBaseStroke(new BasicStroke(NORMAL_SERIES_LINE_WEIGHT, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL)); renderer.clearSeriesPaints(true); renderer.setAutoPopulateSeriesPaint(false); renderer.setAutoPopulateSeriesShape(false); if (seriesColor == null) { seriesColor = Color.black; } renderer.setSeriesOutlinePaint(0, seriesColor); // renderer.setSeriesOutlinePaint(1, seriesColor); renderer.setBaseLegendTextPaint(seriesColor); } void addCommentMarker(double xVal, String comment) { if (this.markerManager == null) return; this.markerManager.addCommentMarker(xVal, comment); } void setCommentsVisible(boolean visible) { if (this.markerManager == null) return; this.markerManager.setCommentsVisible(visible); } Color getAxisColor(int index) { switch (index) { case 0: return Color.BLACK; case 1: return Color.MAGENTA.darker(); case 2: return Color.BLUE; case 3: return Color.RED; } return Color.BLACK; } Color getSeriesColor(int index) { if (index > 10) index = index % 11; switch (index) { case 0: return Color.BLUE.brighter().brighter(); case 1: return Color.RED.brighter(); case 2: return Color.GREEN.darker(); case 3: return Color.CYAN.darker(); case 4: return Color.BLUE.darker().darker(); case 5: return Color.DARK_GRAY; case 6: return Color.MAGENTA; case 7: return Color.ORANGE.darker(); case 8: return Color.CYAN.darker().darker(); case 9: return Color.BLACK.brighter(); case 10: return Color.RED.darker(); } return Color.LIGHT_GRAY; } private Shape getSeriesShape(int index) { if (!CheckChartAndPlotRef()) return null; // init cache array of shapes to use if (this.seriesShapes[0] == null) { DefaultDrawingSupplier ds = new DefaultDrawingSupplier(); for (int i=0;i<10;i++) { seriesShapes[i] = ds.getNextShape(); } } if (index > 10) index = index % 11; return seriesShapes[index]; } /** * TODO define axis meaning and how many per chart type. * * @param axisIndex The axis index you want the label from * @return The label for given index. null if not exist. */ String getAxisLabel(int axisIndex){ if (!CheckChartAndPlotRef()) return null; ValueAxis v3; v3 = getChart().getXYPlot().getRangeAxis(axisIndex); if (v3==null) return null; return v3.getLabel(); } /** * @param axisIndex The axis index to set the label for * @param axisLabel The label */ void setAxisLabel(int axisIndex, String axisLabel){ if (!CheckChartAndPlotRef()) return; ValueAxis v3; v3 = getChart().getXYPlot().getRangeAxis(axisIndex); if (v3==null) return; v3.setLabel(axisLabel); getChart().setNotify(true); } /** * Set the chart title. * * @param title */ void setChartTitle(String title) { getChart().setTitle(title); getChart().setNotify(true); } /** * @return The chart's main title */ String getChartTitle() { return getChart().getTitle().getText(); } boolean axisExists(int axisIndex){ if (!CheckChartAndPlotRef()) return false; return getChart().getXYPlot().getRangeAxis(axisIndex)!=null; } void registerListeners(ChartModel customChartPanel){ // if (!CheckChartAndPlotRef()) { //// throw new ; // return; // } getChart().getXYPlot().getDomainAxis().addChangeListener(customChartPanel); getChart().addProgressListener(customChartPanel); getChart().addChangeListener(customChartPanel); // to capture dataset changes to populate row count } /** * @return True if chart and xyplot are valid refs (not null) */ private boolean CheckChartAndPlotRef(){ JFreeChart c = getChart(); if (c==null) return false; if (c.getXYPlot()==null) return false; return true; } }
39.188791
159
0.596211
bf5b0e821a157dfdda377f7e5c850f90c59610ea
825
package com.aspose.words.examples.linq; import java.util.List; //ExStart:Manager public class Manager { private String Name; public final String getName() { return Name; } public final void setName(String value) { Name = value; } private int Age; public final int getAge() { return Age; } public final void setAge(int value) { Age = value; } private byte[] Photo; public final byte[] getPhoto() { return Photo; } public final void setPhoto(byte[] value) { Photo = value; } private List<Contract> Contracts; public final List<Contract> getContracts() { return Contracts; } public final void setContracts(List<Contract> value) { Contracts = value; } } //ExEnd:Manager
16.5
58
0.6
3ade101928a970d9f8fca3222330e049f286f52a
5,020
package net.smackem.ylang.lang; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public final class Preprocessor { private static final Logger log = LoggerFactory.getLogger(Preprocessor.class); private static final Pattern includePattern = Pattern.compile("^#include \"(.+)\"$"); private final String source; private final FileProvider fileProvider; private final StringBuilder acc; private final Set<String> visitedIncludes = new HashSet<>(); private final List<Segment> segments = new ArrayList<>(); private final Deque<Segment> segmentStack = new ArrayDeque<>(); private int accLineNumber; private Segment currentSegment; public Preprocessor(String source, FileProvider fileProvider) { this.source = Objects.requireNonNull(source); this.fileProvider = fileProvider; this.acc = new StringBuilder(); this.accLineNumber = 1; } public CodeMap preprocess() throws IOException { pushSegment("*"); try (final BufferedReader reader = new BufferedReader(new StringReader(this.source))) { walk(reader); } return new SegmentedCodeMap(this.acc.toString(), this.segments); } public static CodeMap stripDirectives(String source) { // TODO: fix this to not strip #option, which is not a preprocessor directive final StringBuilder buffer = new StringBuilder(); source.lines() .map(line -> line.startsWith("#") ? "" : line) .forEach(line -> { buffer.append(line); buffer.append(System.lineSeparator()); }); return CodeMap.oneToOne(buffer.toString()); } private void walk(BufferedReader reader) throws IOException { String line; while ((line = reader.readLine()) != null) { if (line.startsWith("#")) { if (processDirective(line)) { continue; } } appendLine(line); this.currentSegment.lineCount++; } } private void pushSegment(String fileName) { if (this.currentSegment != null) { this.segmentStack.push(this.currentSegment); } this.currentSegment = new Segment(fileName, this.accLineNumber, 1); this.segments.add(this.currentSegment); } private void popSegment() { final Segment topSegment = this.segmentStack.pop(); this.currentSegment = new Segment(topSegment.fileName, this.accLineNumber, topSegment.lineNumberOffsetInFile + topSegment.lineCount + 1); this.segments.add(this.currentSegment); } private boolean processDirective(String line) throws IOException { final Matcher matcher = includePattern.matcher(line); if (matcher.matches()) { includeFile(matcher.group(1)); return true; } if (line.startsWith("#option")) { // ignore option statement return false; } log.warn("unknown preprocessor directive '{}'", line); return false; } private void includeFile(String fileName) throws IOException { if (this.visitedIncludes.add(fileName) == false) { log.warn("file %s is included multiple times - only including it once".formatted(fileName)); return; } pushSegment(fileName); try (final BufferedReader nestedReader = this.fileProvider.open(fileName)) { walk(nestedReader); } popSegment(); } private void appendLine(String line) { this.acc.append(line).append(System.lineSeparator()); this.accLineNumber++; } private static class Segment { final String fileName; final int lineNumber; final int lineNumberOffsetInFile; int lineCount; Segment(String fileName, int lineNumber, int lineNumberOffsetInFile) { this.fileName = fileName; this.lineNumber = lineNumber; this.lineNumberOffsetInFile = lineNumberOffsetInFile; } } private static class SegmentedCodeMap extends CodeMap { final Collection<Segment> segments; SegmentedCodeMap(String source, Collection<Segment> segments) { super(source); this.segments = segments; } @Override public Location translate(int lineNumber) { for (final Segment segment : this.segments) { if (segment.lineNumber <= lineNumber && lineNumber < segment.lineNumber + segment.lineCount) { return new Location(lineNumber - segment.lineNumber + segment.lineNumberOffsetInFile, segment.fileName); } } return null; } } }
34.62069
124
0.620518
9f7e42f34bed2d637cbafd81b793e6a015d3da61
1,238
package s2u2msdk.spring.service.account.service; import s2u2msdk.spring.test.AbS2u2mSpringTest; import s2u2msdk.spring.service.account.dao.UserDAO; import s2u2msdk.spring.service.account.entity.UserEntity; import s2u2msdk.spring.service.account.enums.GenderEnum; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.mock.mockito.MockBean; import static org.junit.Assert.*; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doReturn; public class UserServiceTest extends AbS2u2mSpringTest { @Autowired private UserService userService; @MockBean private UserDAO userDAO; @Test public void create_success() { String nickName = "test"; GenderEnum gender = GenderEnum.Female; doReturn(1).when(userDAO).insert(any(UserEntity.class)); UserEntity input = new UserEntity() .setNickName(nickName) .setGender(gender); UserEntity entity = userService.create(input); assertNotNull(entity.getId()); assertNotEquals("", entity.getId()); assertNotNull(entity.getCreateTime()); assertFalse(entity.getDeleteFlag()); } }
29.47619
64
0.724556
ffd85926f33b659aba3dcc25a156ff9d9ac078e7
5,756
import java.sql.DriverManager; import com.mysql.jdbc.Connection; import com.mysql.jdbc.Statement; import java.sql.ResultSet; import javax.swing.DefaultComboBoxModel; import javax.swing.JOptionPane; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * KnowMorePeople.java * * Created on 12 Nov, 2019, 1:48:52 PM */ /** * * @author India */ public class KnowMorePeople extends javax.swing.JFrame { public static String SelectedPerson; public KnowMorePeople() { initComponents(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jComboBox1 = new javax.swing.JComboBox(); jButton1 = new javax.swing.JButton(); jLabel4 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel1.setFont(new java.awt.Font("Arial", 3, 14)); jLabel1.setText("Enter City"); getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 50, -1, -1)); getContentPane().add(jTextField1, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 50, 340, -1)); jButton2.setText("Know more people"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); getContentPane().add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 100, -1, -1)); jButton3.setText("Go back to Dash Board"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); getContentPane().add(jButton3, new org.netbeans.lib.awtextra.AbsoluteConstraints(340, 250, -1, -1)); jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Zeaan" })); getContentPane().add(jComboBox1, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 170, 330, -1)); jButton1.setText("Chat"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 250, 140, -1)); jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/IMG-20191111-WA0071.jpg"))); // NOI18N getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 610, -1)); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed String City=jTextField1.getText(); DefaultComboBoxModel model=(DefaultComboBoxModel)jComboBox1.getModel(); jComboBox1.removeAllItems(); try { //For establishing connection between program and database Class.forName("java.sql.DriverManager"); Connection con=(Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/LabChat","root","zeaan"); Statement stmt=(Statement)con.createStatement(); //To get all the usernames along with their location String q="Select * from Userinfo;"; ResultSet r=stmt.executeQuery(q); while(r.next()) { if(City.equals(r.getString("City"))) { String a=r.getString("User"); jComboBox1.addItem(a); } } } catch(Exception o) { JOptionPane.showMessageDialog(null,o.getMessage()); } }//GEN-LAST:event_jButton2ActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed //For moving to Dash Board window DashBoard m=new DashBoard(); m.setVisible(true); this.dispose(); }//GEN-LAST:event_jButton3ActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed SelectedPerson=jComboBox1.getSelectedItem().toString(); Chat d=new Chat(); d.setVisible(true); this.dispose(); }//GEN-LAST:event_jButton1ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new KnowMorePeople().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JComboBox jComboBox1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel4; private javax.swing.JTextField jTextField1; // End of variables declaration//GEN-END:variables }
39.424658
121
0.664003
975421955e8581c9fee0876ab2610f0a309eed28
3,576
package com.wythe.mall.ui; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.wythe.mall.R; import com.wythe.mall.activity.LoginActivity; import com.wythe.mall.activity.MessageCenterActivity; import com.wythe.mall.activity.MoreSettingActivity; import com.wythe.mall.activity.PocketActivity; import com.wythe.mall.activity.ServiceFeedbackActivity; import com.wythe.mall.utils.GotoActivity; import com.wythe.mall.utils.UserManager; public class PersonalFragment extends Fragment implements View.OnClickListener{ private View view; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_personal, container, false); initView(); return view; } private void initView(){ view.findViewById(R.id.personal_click_for_login).setOnClickListener(this); view.findViewById(R.id.more_setting).setOnClickListener(this); view.findViewById(R.id.messages).setOnClickListener(this); view.findViewById(R.id.personal_guanzhu).setOnClickListener(this); view.findViewById(R.id.personal_zuji).setOnClickListener(this); view.findViewById(R.id.personal_hongbao).setOnClickListener(this); view.findViewById(R.id.personal_feedback).setOnClickListener(this); view.findViewById(R.id.personal_pocket_title).setOnClickListener(this); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override public void onResume() { super.onResume(); //登录未登录界面切换 if (UserManager.getInstance().isLogin()){ view.findViewById(R.id.personal_for_not_login).setVisibility(View.GONE); view.findViewById(R.id.personal_for_login_info).setVisibility(View.VISIBLE); view.findViewById(R.id.personal_recommend_layout).setVisibility(View.VISIBLE); } else { view.findViewById(R.id.personal_for_not_login).setVisibility(View.VISIBLE); view.findViewById(R.id.personal_for_login_info).setVisibility(View.GONE); view.findViewById(R.id.personal_recommend_layout).setVisibility(View.GONE); } } @Override public void onClick(View v) { switch (v.getId()){ case R.id.personal_click_for_login:{ GotoActivity.gotoActiviy(getActivity(), LoginActivity.class); break; } case R.id.more_setting:{ GotoActivity.gotoActiviy(getActivity(), MoreSettingActivity.class); break; } case R.id.messages:{ GotoActivity.gotoActiviy(getActivity(), MessageCenterActivity.class); break; } case R.id.personal_guanzhu:{ break; } case R.id.personal_zuji:{ break; } case R.id.personal_hongbao:{ break; } case R.id.personal_feedback:{ GotoActivity.gotoActiviy(getActivity(), ServiceFeedbackActivity.class); break; } case R.id.personal_pocket_title:{ GotoActivity.gotoActiviy(getActivity(), PocketActivity.class); break; } } } }
35.058824
103
0.661633
50dee381da1f5f35e2cc4f870c5c33e5d52bf81f
2,904
/** * Copyright (C) 2010 Asterios Raptis * * 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 de.alpharogroup.wicket.components.menu.suckerfish; import java.util.ArrayList; import java.util.List; import org.apache.wicket.behavior.AttributeAppender; import org.apache.wicket.markup.head.IHeaderResponse; import org.apache.wicket.model.Model; import org.apache.wicket.model.PropertyModel; import de.alpharogroup.io.annotations.ImportResource; import de.alpharogroup.io.annotations.ImportResources; import de.alpharogroup.wicket.base.BasePanel; import de.alpharogroup.wicket.header.contributors.HeaderResponseExtensions; import lombok.Getter; /** * The Class {@link MenuPanel}. */ @ImportResources(resources = { @ImportResource(resourceName = "MenuPanel.js", resourceType = "js") }) public class MenuPanel extends BasePanel<Object> { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 0L; /** The Constant LINK_ID. */ public static final String LINK_ID = "linkid"; /** The Constant LINK_TEXT_ID. */ public static final String LINK_TEXT_ID = "linktext"; /** * This appender is used to add a down or right arrow icon if there are children. */ public static final AttributeAppender menuHasSubmenuAppender = new AttributeAppender("class", Model.of("menu-has-submenu"), " "); /** The top menu items. */ @Getter private final List<MenuItem> topMenuItems = new ArrayList<>(); /** * Instantiates a new {@link MenuPanel}. * * @param id * the id */ public MenuPanel(final String id) { super(id); // Add the top menus add(new SubMenuListView("topmenuitems", new PropertyModel<>(this, "topMenuItems"), this)); } /** * Add one menu item. * * @param menu * the menu */ public void addMenu(final MenuItem menu) { topMenuItems.add(menu); } /** * {@inheritDoc} */ @Override public void renderHead(final IHeaderResponse response) { super.renderHead(response); HeaderResponseExtensions.renderHeaderResponse(response, this.getClass()); } /** * Add all menus at once. * * @param menuItems * the new menu items */ public void setMenuItems(final List<MenuItem> menuItems) { topMenuItems.clear(); topMenuItems.addAll(menuItems); } }
26.888889
95
0.691804
61ceebfcbf391f49454dc92abdce40736121dca1
1,217
package com.etri.sl.models; public class Gateway { private int gid; private String gpid; private String productCode; private String serialNumber; private String iblid; private String ip; private String tcpPort; public Gateway() { gid = 0; } public Gateway(int gid, String ip, String port) { this.gid = gid; this.ip = ip; this.tcpPort = port; } public int getGid() { return gid; } public void setGid(int gid) { this.gid = gid; } public String getGpid() { return gpid; } public void setGpid(String gpid) { this.gpid = gpid; } public String getProductCode() { return productCode; } public void setProductCode(String productCode) { this.productCode = productCode; } public String getSerialNumber() { return serialNumber; } public void setSerialNumber(String serialNumber) { this.serialNumber = serialNumber; } public String getIblid() { return iblid; } public void setIblid(String iblid) { this.iblid = iblid; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public String getTcpPort() { return tcpPort; } public void setTcpPort(String tcpPort) { this.tcpPort = tcpPort; } }
14.151163
51
0.677896
75a5ee66f405318671d9493a1aad375960555688
417
/* * 文 件 名: LaRouJiaMo.java * 版 权: 深圳市钱眼金融控股有限公司 * 描 述: <描述> * 修 改 人: sun * 修改时间: 2018年7月3日 */ package com.research.designPattern.factoryModel.SimpleFactoryMode; /** * 辣味肉夹馍 * <功能详细描述> * * @author sun * @version [版本号, 2018年7月3日] */ public class LaRouJiaMo extends RouJiaMo { public LaRouJiaMo() { this.name = "辣味肉夹馍"; System.out.println("开始生产辣味肉夹馍"); } }
16.038462
66
0.585132
c34ec5f72bb901771b28028b45cec8ef5ce63fd3
379
package com.example.service; import com.alibaba.fastjson.JSONObject; /** * Created by merit on 2018/2/7. */ public interface IExampleService { /** * 增加节点 * * @return */ JSONObject addNode(); /** * 根据labels查询数据节点 * * @param label * @return */ JSONObject queryNodesByLabel(String label); }
15.16
48
0.540897
56b28a0ac19a7243a3f309feed3f56f4247d2c89
153
package net.collaud.fablab.manager.service.impl; /** * * @author Gaetan Collaud <gaetancollaud@gmail.com> */ public class AbstractServiceImpl { }
12.75
51
0.72549
7e8384c0b118ad957a9e766d9f45b96acb56d39f
2,967
public class Solution { List<List<String>> results; List<String> list; Map<String,List<String>> map; public List<List<String>> findLadders(String start, String end, Set<String> dict) { results= new ArrayList<List<String>>(); if (dict.size() == 0) return results; int curr=1,next=0; boolean found=false; list = new LinkedList<String>(); map = new HashMap<String,List<String>>(); Queue<String> queue= new ArrayDeque<String>(); Set<String> unvisited = new HashSet<String>(dict); Set<String> visited = new HashSet<String>(); queue.add(start); unvisited.add(end); unvisited.remove(start); //BFS while (!queue.isEmpty()) { String word = queue.poll(); curr--; for (int i = 0; i < word.length(); i++){ StringBuilder builder = new StringBuilder(word); for (char ch='a'; ch <= 'z'; ch++){ builder.setCharAt(i,ch); String new_word=builder.toString(); if (unvisited.contains(new_word)){ //Handle queue if (visited.add(new_word)){//Key statement,Avoid Duplicate queue insertion next++; queue.add(new_word); } if (map.containsKey(new_word))//Build Adjacent Graph map.get(new_word).add(word); else{ List<String> l= new LinkedList<String>(); l.add(word); map.put(new_word, l); } if (new_word.equals(end)&&!found) found=true; } }//End:Iteration from 'a' to 'z' }//End:Iteration from the first to the last if (curr==0){ if (found) break; curr=next; next=0; unvisited.removeAll(visited); visited.clear(); } }//End While backTrace(end,start); return results; } private void backTrace(String word,String start){ if (word.equals(start)){ list.add(0,start); results.add(new ArrayList<String>(list)); list.remove(0); return; } list.add(0,word); if (map.get(word)!=null) for (String s:map.get(word)) backTrace(s,start); list.remove(0); } }
37.0875
102
0.410853
1cb1b1f28464c900f14f89155e5e6d87437fae5e
1,103
package org.arkecosystem.crypto.transactions.builder; import java.util.List; import org.arkecosystem.crypto.enums.Fees; import org.arkecosystem.crypto.identities.Address; import org.arkecosystem.crypto.transactions.types.Transaction; import org.arkecosystem.crypto.transactions.types.Vote; public class VoteBuilder extends AbstractTransactionBuilder<VoteBuilder> { public VoteBuilder() { super(); this.transaction.fee = Fees.VOTE.getValue(); } public VoteBuilder addVotes(List votes) { this.transaction.asset.votes = votes; return this; } public VoteBuilder addVote(String vote) { this.transaction.asset.votes.add(vote); return this; } public VoteBuilder sign(String passphrase) { this.transaction.recipientId = Address.fromPassphrase(passphrase, this.transaction.network); super.sign(passphrase); return this; } @Override public Transaction getTransactionInstance() { return new Vote(); } @Override public VoteBuilder instance() { return this; } }
25.068182
100
0.696283
697f449be42c0c6849349d6ec8a8adeb244a0146
946
package fr.openwide.core.basicapp.core.business.notification.service; import java.util.Date; import fr.openwide.core.basicapp.core.business.user.model.User; import fr.openwide.core.spring.notification.model.INotificationContentDescriptor; import fr.openwide.core.spring.notification.util.NotificationContentDescriptors; /** * Implémentation bouche-trou, uniquement pour combler la dépendance. */ public class EmptyNotificationContentDescriptorFactoryImpl implements IBasicApplicationNotificationContentDescriptorFactory { private static final INotificationContentDescriptor DEFAULT_DESCRIPTOR = NotificationContentDescriptors.explicit("defaultSubject", "defaultTextBody", "defaultHtmlBody"); @Override public INotificationContentDescriptor example(User user, Date date) { return DEFAULT_DESCRIPTOR; } @Override public INotificationContentDescriptor userPasswordRecoveryRequest(User user) { return DEFAULT_DESCRIPTOR; } }
32.62069
125
0.839323
6dbb53079b2e39b663d9b62ff3abc65a2acf6656
219
package org.tanc.inner; /** * * Created by tanc on 2017/4/17. */ public abstract class AbstractClass { protected int x; public AbstractClass(int x) { this.x = x; } abstract void show(); }
12.882353
37
0.598174
a4a4c101959df4907d18f9dd8b0d4e18fbfe3aee
2,600
/* * Copyright 2010-2015 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 org.jetbrains.kotlin.resolve.diagnostics; import com.intellij.openapi.util.AtomicNotNullLazyValue; import com.intellij.psi.PsiElement; import com.intellij.util.containers.ConcurrentMultiMap; import com.intellij.util.containers.MultiMap; import kotlin.collections.CollectionsKt; import kotlin.jvm.functions.Function1; import org.jetbrains.annotations.NotNull; import org.jetbrains.kotlin.diagnostics.Diagnostic; import java.util.Collection; public class DiagnosticsElementsCache { private final Diagnostics diagnostics; private final Function1<Diagnostic, Boolean> filter; private final AtomicNotNullLazyValue<MultiMap<PsiElement, Diagnostic>> elementToDiagnostic = new AtomicNotNullLazyValue<MultiMap<PsiElement, Diagnostic>>() { @NotNull @Override protected MultiMap<PsiElement, Diagnostic> compute() { return buildElementToDiagnosticCache(diagnostics, filter); } }; public DiagnosticsElementsCache(Diagnostics diagnostics, Function1<Diagnostic, Boolean> filter) { this.diagnostics = diagnostics; this.filter = filter; } @NotNull public Collection<Diagnostic> getDiagnostics(@NotNull PsiElement psiElement) { return elementToDiagnostic.getValue().get(psiElement); } private static MultiMap<PsiElement, Diagnostic> buildElementToDiagnosticCache(Diagnostics diagnostics, Function1<Diagnostic, Boolean> filter) { MultiMap<PsiElement, Diagnostic> elementToDiagnostic = new ConcurrentMultiMap<>(); for (Diagnostic diagnostic : diagnostics) { if (diagnostic == null) { throw new IllegalStateException( "There shouldn't be null diagnostics in the collection: " + CollectionsKt.toList(diagnostics)); } if (filter.invoke(diagnostic)) { elementToDiagnostic.putValue(diagnostic.getPsiElement(), diagnostic); } } return elementToDiagnostic; } }
38.80597
161
0.726538
a464f76ab7d299ef7d47dfaf7722dc764e1f4b22
552
package uk.co.cwspencer.ideagdb.debug.breakpoints; import org.jetbrains.annotations.NotNull; import com.intellij.xdebugger.breakpoints.XLineBreakpointTypeBase; import uk.co.cwspencer.ideagdb.debug.GdbDebuggerEditorsProvider; public class GdbBreakpointType extends XLineBreakpointTypeBase { @NotNull public static GdbBreakpointType getInstance() { return EXTENSION_POINT_NAME.findExtension(GdbBreakpointType.class); } public GdbBreakpointType() { super("gdb-line-breakpoint", "GDB Line Breakpoints", new GdbDebuggerEditorsProvider()); } }
27.6
89
0.822464
b8967c638e53be3b02e47b80e36257613668b59e
937
package cn.iocoder.yudao.adminserver.modules.infra.service.file.impl; import cn.iocoder.yudao.adminserver.modules.infra.dal.mysql.file.InfFileMapper; import cn.iocoder.yudao.adminserver.modules.infra.service.file.InfFileService; import cn.iocoder.yudao.adminserver.modules.infra.controller.file.vo.InfFilePageReqVO; import cn.iocoder.yudao.coreservice.modules.infra.dal.dataobject.file.InfFileDO; import cn.iocoder.yudao.coreservice.modules.infra.service.file.InfFileCoreService; import cn.iocoder.yudao.framework.common.pojo.PageResult; import org.springframework.stereotype.Service; import javax.annotation.Resource; /** * 文件 Service 实现类 * * @author 芋道源码 */ @Service public class InfFileServiceImpl implements InfFileService { @Resource private InfFileMapper fileMapper; @Override public PageResult<InfFileDO> getFilePage(InfFilePageReqVO pageReqVO) { return fileMapper.selectPage(pageReqVO); } }
31.233333
86
0.804696
224f4ca266f43ca289d6c26cc88c8e70c2be58c2
470
package com.heaven7.java.pc; /** * @author heaven7 */ public final class Transformers { private static final Transformer<Object, Object> UNCHANGED = new Transformer<Object, Object>() { @Override public Object transform(ProductContext context, Object t) { return t; } }; @SuppressWarnings("unchecked") public static <T> Transformer<T,T> unchangeTransformer(){ return (Transformer<T, T>) UNCHANGED; } }
23.5
100
0.642553
d1e0ef7778242990cab6d35c2afd3b0eafa313d3
514
package br.com.mindsy.api.gateway.dto.evaluation; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class EvaluationResponseDto implements Serializable { private static final long serialVersionUID = 1L; private List<EvaluationDto> evaluations = new ArrayList<>(); public List<EvaluationDto> getEvaluations() { return evaluations; } public void setEvaluations(List<EvaluationDto> evaluations) { this.evaluations = evaluations; } }
23.363636
65
0.737354
fb37c3ac4e734604092a84662647facb1d5fced5
14,551
// Import Statements. import java.util.*; // Node Class to represent each vertex of a graph. class Node { private String name; private HashMap<Node, Integer> adjascMap; Node(String name) { // Initializes the instances of the node class. this.name = name; adjascMap = new HashMap<Node, Integer>(); } String getName() { // Returns the name of the node. return(this.name); } HashMap<Node, Integer> getAdjascentMap() { // Returns a list of all the adjascent vertices to the present vertex. return(this.adjascMap); } void addAdjascentNode(Node nodeB, int w) { // Adds a vertex as adjascent to this current vertex. String othName = nodeB.getName(); boolean flag = false; for(Map.Entry<Node, Integer> itr : this.adjascMap.entrySet()) { if(othName.equals(itr.getKey().getName())) { flag = true; break; } } if(flag == false) { this.adjascMap.put(nodeB, w); } } } // A Graph class that represents a graph or a collection of vertices that are linked with each other in numerous ways. class Graph { private String name; private ArrayList<Node> vertices; Graph(String name) { // Initializes the instance of the graph class. this.name = name; vertices = new ArrayList<Node>(); } String getName() { // Returns the name of the graph. return(this.name); } ArrayList<Node> getVertices() { // Returns all the vertices of the graph. return(this.vertices); } boolean checkVertices(String nameToSearch) { // It checks if a vertex with the provided name exists in the graph or not. Iterator<Node> itr = vertices.iterator(); String itrName; while(itr.hasNext()) { itrName = itr.next().getName(); if(itrName.equals(nameToSearch)) { return(true); } } return(false); } Node getNode(String nameToSearch) { // Returns the node with the provided name if present in the graph. Iterator<Node> itr = vertices.iterator(); String itrName; Node curNode; while(itr.hasNext()) { curNode = itr.next(); itrName = curNode.getName(); if(itrName.equals(nameToSearch)) { return(curNode); } } return(null); } void getInputByEdges(Scanner sc) { // It take input in the form of edges for the graph. System.out.println("Enter the number of edges : "); int numEdges = Integer.parseInt(sc.nextLine()); if(numEdges > 0) { System.out.println("Enter 1 if the edges are uni-directional.\nEnter 2 if the edges are bidirectional."); System.out.print("Enter your choice : "); int cho = Integer.parseInt(sc.nextLine()); if(cho == 1 || cho == 2) { if(cho == 1) { System.out.println("The format for entering the edges is : Source-Vertex Destination-Vertex Weight"); } else if(cho == 2) { System.out.println("The format for entering the edges is : Vertex-1 Vertex-2 Weight"); } System.out.println("Enter the edges one by one : "); String str[]; int weight; Node nodeA, nodeB; for(int i=0;i<numEdges;i++) { str = new String[3]; str = sc.nextLine().split(" "); weight = Integer.parseInt(str[2]); if(checkVertices(str[0]) == false) { nodeA = new Node(str[0]); this.vertices.add(nodeA); } else { nodeA = this.getNode(str[0]); } if(checkVertices(str[1]) == false) { nodeB = new Node(str[1]); this.vertices.add(nodeB); } else { nodeB = this.getNode(str[1]); } nodeA.addAdjascentNode(nodeB, weight); if(cho == 2) { // If the edges are stated to be bidirectional. nodeB.addAdjascentNode(nodeA, weight); } } } else { // Invalid choice is entered for the type of edges. System.out.println("Invalid Input."); sc.close(); System.exit(0); } } } void getInputByVertices(Scanner sc) { // To get the input in the form of vertices and their adjascent vertices to form the graph. System.out.println("Enter the number of vertices : "); int numVertices = Integer.parseInt(sc.nextLine()); String nameA; String str[]; int numAdj, i, j, w; Node nodeA, nodeB; for(i=0;i<numVertices;i++) { System.out.println("Enter the name of the vertex : "); nameA = sc.nextLine(); if(this.checkVertices(nameA) == true) { nodeA = this.getNode(nameA); } else { nodeA = new Node(nameA); this.vertices.add(nodeA); } System.out.println("Enter the number of adjascent vertices : "); numAdj = Integer.parseInt(sc.nextLine()); if(numAdj > 0) { System.out.println("The format for the input is : Destination-Vertex Weight"); System.out.println("Enter all the edges leading fron the vertex '" + nameA + "' : "); for(j=0;j<numAdj;j++) { // For each adjascent vertex do the following. str = sc.nextLine().split(" "); w = Integer.parseInt(str[1]); if(checkVertices(str[0]) == false) { nodeB = new Node(str[0]); this.vertices.add(nodeB); } else { nodeB = this.getNode(str[0]); } nodeA.addAdjascentNode(nodeB, w); // For the case of bidirectional edges we have to state it twice one from source to destination and vice versa in this form of representation. } } } } } // A class to maipulate the above classes and implement the dijkstra algorithm. public class Dijkstra { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter the name of the graph : "); Graph graph = new Graph(sc.nextLine()); int cho; System.out.println("Enter 1 to make the graph by specfying the details of the edges.\nEnter 2 to make the graph by specfying the details of vertices."); System.out.print("Enter your choice : "); cho = Integer.parseInt(sc.nextLine()); switch(cho) { case 1 : graph.getInputByEdges(sc); break; case 2 : graph.getInputByVertices(sc); break; default : System.out.println("Invalid Input."); sc.close(); System.exit(0); } if(graph.getVertices().size() > 0) { // If the graph entered is not an emptyof null graph. System.out.println("Enter the name of the source vertex : "); String src = sc.nextLine(); if(graph.checkVertices(src) == true) { // If the entered source node name is present in the graph. HashMap<Node, Integer> distance = new HashMap<Node, Integer>(); // Distance data structure holds the shortest distance of the node from the source node. HashMap<Node, ArrayList<Node>> path = new HashMap<Node, ArrayList<Node>>(); // Path data structure holds the entire path from the source node till that node for the most optimal path. Iterator<Node> itr1 = graph.getVertices().iterator(); Iterator<Node> itr2; final int inf = (int)Double.POSITIVE_INFINITY; Node curNode; while(itr1.hasNext()) { // To perform default initialization for the path and distance data structures. curNode = itr1.next(); distance.put(curNode, inf); path.put(curNode, new ArrayList<Node>()); } ArrayList<Node> notVisited = new ArrayList<Node>(graph.getVertices()); // notVisited holds a list of all the vertices that have not yet been visited. Node nodeVisit = graph.getNode(src); int curDist = 0, w = 0, minDist; distance.put(nodeVisit, curDist); // To finish visiting the source node. ArrayList<Node> curPath; while(notVisited.size() > 0) { // Until we have not yet visited all the nodes. notVisited.remove(nodeVisit); curDist = distance.get(nodeVisit); for(Map.Entry<Node, Integer> entry : nodeVisit.getAdjascentMap().entrySet()) { // To check every node that is adjscent to the currently visiting node. w = entry.getValue(); curNode = entry.getKey(); if(distance.get(curNode) > (w + curDist) && notVisited.contains(curNode)) { // If there is a shorter path to reach here from the source node. distance.put(curNode, w+curDist); path.remove(curNode); curPath = new ArrayList<Node>(path.get(nodeVisit)); curPath.add(nodeVisit); path.put(curNode, curPath); // Modify the path and the distance data structures based on the shorter path found. } } curPath = new ArrayList<Node>(path.get(nodeVisit)); curPath.add(nodeVisit); path.put(nodeVisit, curPath); // Adds the currently visiting node to its path thereby completing its path. minDist = inf; nodeVisit = null; for(Map.Entry<Node, Integer> entry : distance.entrySet()) { if(entry.getValue() < minDist && notVisited.contains(entry.getKey())) { // To find a node that has not yet been visited and has minimum weight. minDist = entry.getValue(); nodeVisit = entry.getKey(); } } // It finds the node that dhould be visited next based on the weights. } // To print the results of the algorithm to the console. System.out.println("The vertices of the graph '" + graph.getName() + "' and their shortest distances from the source vertex '" + src + "' are : "); itr1 = graph.getVertices().iterator(); while(itr1.hasNext()) { // Prints the details of every node, namely its shortest distance and the path followed from the source node. curNode = itr1.next(); System.out.println("Node : " + curNode.getName()); System.out.println("Distance from source : " + distance.get(curNode)); curPath = new ArrayList<Node>(path.get(curNode)); if(curPath.size() == 0 || distance.get(curNode) == inf) { System.out.println("The node is not reachable from the source."); // If the node cannot be reached from the entered source. } else { // If the current node can be reached from the source and we have found an optimal path. System.out.print("Path from source : "); itr2 = curPath.iterator(); while(itr2.hasNext()) { System.out.print(itr2.next().getName()); if(itr2.hasNext()) { System.out.print(" -> "); } } System.out.println(); // Prints the optimal path of the current node from the source node. } System.out.println("---------------------------------------------------------------------------------"); } } else { // If the entered name for the source node is invalid or dosent exist in the entered graph. System.out.println("Invalid Source Vertex."); sc.close(); System.exit(0); } } else { // If the entered graph has no vertices. System.out.println("The entered graph is a null graph."); } System.out.println("End of Program."); System.out.println("---------------------------------------------------------------------------------"); // Closing the scanner class object. sc.close(); // Program has ended. } }
39.327027
164
0.470552
75c00b931293054c1dd391dfa62da0239b250c76
2,084
package com.fitmgr.common.data.mybatis; import org.apache.commons.lang3.StringUtils; import org.apache.ibatis.executor.keygen.Jdbc3KeyGenerator; import org.apache.ibatis.executor.keygen.KeyGenerator; import org.apache.ibatis.executor.keygen.NoKeyGenerator; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.mapping.SqlSource; import com.baomidou.mybatisplus.core.enums.SqlMethod; import com.baomidou.mybatisplus.core.injector.AbstractMethod; import com.baomidou.mybatisplus.core.metadata.TableInfo; import com.baomidou.mybatisplus.core.toolkit.sql.SqlScriptUtils; public class Insert extends AbstractMethod { @Override public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) { KeyGenerator keyGenerator = new NoKeyGenerator(); SqlMethod sqlMethod = SqlMethod.INSERT_ONE; String columnScript = SqlScriptUtils.convertTrim(tableInfo.getAllInsertSqlColumnMaybeIf(), LEFT_BRACKET, RIGHT_BRACKET, null, COMMA); String valuesScript = SqlScriptUtils.convertTrim(tableInfo.getAllInsertSqlPropertyMaybeIf(null), LEFT_BRACKET, RIGHT_BRACKET, null, COMMA); String keyProperty = null; String keyColumn = null; // 表包含主键处理逻辑,如果不包含主键当普通字段处理 if (StringUtils.isNotBlank(tableInfo.getKeyProperty())) { if (Integer.class.getName().equals(tableInfo.getKeyType().getName()) || Long.class.getName().equals(tableInfo.getKeyType().getName())) { keyGenerator = new Jdbc3KeyGenerator(); } } keyProperty = tableInfo.getKeyProperty(); keyColumn = tableInfo.getKeyColumn(); String sql = String.format(sqlMethod.getSql(), tableInfo.getTableName(), columnScript, valuesScript); SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass); return this.addInsertMappedStatement(mapperClass, modelClass, getMethod(sqlMethod), sqlSource, keyGenerator, keyProperty, keyColumn); } }
49.619048
118
0.732726
58f8a1d7973fa90a01e300ec94c65d75cfd4a4d5
14,730
/* * JPPF. * Copyright (C) 2005-2019 JPPF Team. * http://www.jppf.org * * 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.jppf.management; import java.util.*; import org.jppf.utils.*; import org.jppf.utils.concurrent.ThreadUtils; import org.jppf.utils.stats.*; /** * This class encapsulates the system information for a node.<br> * It includes: * <ul> * <li>System properties, including -D flags</li> * <li>Runtime information such as available processors and memory usage</li> * <li>Environment variables</li> * <li>JPPF configuration properties</li> * <li>IPV4 and IPV6 addresses assigned to the JVM host</li> * <li>Disk space information</li> * <li>Server statistics (server-side only)</li> * </ul> * @author Laurent Cohen */ public class JPPFSystemInformation implements PropertiesCollection<String> { /** * Explicit serialVersionUID. */ private static final long serialVersionUID = 1L; /** * Mapping of all properties containers. */ private Map<String, TypedProperties> map = new HashMap<>(); /** * {@code true} if the JPPF component is local (local node or local client executor), {@code false} otherwise. */ private boolean local; /** * If {@code true}, then the name resolution for {@code InetAddress}es should occur immediately, */ private boolean resolveInetAddressesNow; /** * */ private transient TypedProperties[] propertiesArray; /** * An optional statistics object from which events can be received so the corresponding properties can be kept up to date. */ private transient JPPFStatistics stats; /** * The JPPF configuration. */ private transient TypedProperties jppfConfig; /** * Initialize this system information object with the specified uuid. * @param jppfConfig the JPPF configuration. * @param uuid the uuid of the corresponding JPPF component. * @param local {@code true} if the JPPF component is local (local node or local client executor), {@code false} otherwise. * @param resolveInetAddressesNow if {@code true}, then name resolution for {@code InetAddress}es should occur immediately, * otherwise it is different and executed in a separate thread. * @exclude */ public JPPFSystemInformation(final TypedProperties jppfConfig, final String uuid, final boolean local, final boolean resolveInetAddressesNow) { this(jppfConfig, uuid, local, resolveInetAddressesNow, null); } /** * Initialize this system information object with the specified uuid. * @param jppfConfig the JPPF configuration. * @param uuid the uuid of the corresponding JPPF component. * @param local {@code true} if the JPPF component is local (local node or local client executor), {@code false} otherwise. * @param resolveInetAddressesNow if {@code true}, then name resolution for {@code InetAddress}es should occur immediately, * otherwise it is different and executed in a separate thread. * @param stats an optional statistics object from which events can be received so the corresponding properties can be kept up to date. * @exclude */ public JPPFSystemInformation(final TypedProperties jppfConfig, final String uuid, final boolean local, final boolean resolveInetAddressesNow, final JPPFStatistics stats) { this.local = local; this.resolveInetAddressesNow = resolveInetAddressesNow; this.stats = stats; this.jppfConfig = jppfConfig; final TypedProperties uuidProps = new TypedProperties(); uuidProps.setProperty("jppf.uuid", (uuid == null) ? "" : uuid); uuidProps.setInt("jppf.pid", SystemUtils.getPID()); final VersionUtils.Version v = VersionUtils.getVersion(); uuidProps.setProperty("jppf.version.number", v.getVersionNumber()); uuidProps.setProperty("jppf.build.number", v.getBuildNumber()); uuidProps.setProperty("jppf.build.date", v.getBuildDate()); addProperties("uuid", uuidProps); populate(); } /** * Get the map holding the system properties. * @return a {@code TypedProperties} instance. * @see org.jppf.utils.SystemUtils#getSystemProperties() */ public TypedProperties getSystem() { return getProperties("system"); } /** * Get the map holding the runtime information. * <p>The resulting map will contain the following properties: * <ul> * <li>availableProcessors = <i>number of processors available to the JVM</i></li> * <li>freeMemory = <i>current free heap size in bytes</i></li> * <li>totalMemory = <i>current total heap size in bytes</i></li> * <li>maxMemory = <i>maximum heap size in bytes (i.e. as specified by -Xmx JVM option)</i></li> * <li>usedMemory = <i>currently used heap memory in bytes</i></li> * <li>availableMemory = <i>the currently available heap memory in bytes; equal to: </i>{@code maxMemory - usedMemory}</li> * <li>startTime = <i>the approximate timestamp in millis of when the JVM started</i></li> * <li>upTime = <i>how long the JVM has been up in millis</i></li> * <li>inputArgs = <i>arguments given to the 'java' command, excluding those passed to the main method. * Arguments are given as a list of strings separated by the ", " delimiter (a comma followed by a space)</i></li> * </ul> * <p>Some or all of these properties may be missing if a security manager is installed * that does not grant access to the related {@link java.lang.Runtime} APIs. * @return a {@code TypedProperties} instance. * @see org.jppf.utils.SystemUtils#getRuntimeInformation() */ public TypedProperties getRuntime() { return getProperties("runtime"); } /** * Get the map holding the environment variables. * @return a {@code TypedProperties} instance. * @see org.jppf.utils.SystemUtils#getEnvironment() */ public TypedProperties getEnv() { return getProperties("env"); } /** * Get the map of the network configuration. * <p>The resulting map will contain the following properties: * <ul> * <li>ipv4.addresses = <i>hostname_1</i>|<i>ipv4_address_1</i> ... <i>hostname_n</i>|<i>ipv4_address_n</i></li> * <li>ipv6.addresses = <i>hostname_1</i>|<i>ipv6_address_1</i> ... <i>hostname_p</i>|<i>ipv6_address_p</i></li> * </ul> * <p>Each property is a space-separated list of <i>hostname</i>|<i>ip_address</i> pairs, * the hostname and ip address being separated by a pipe symbol &quot;|&quot;. * @return a {@code TypedProperties} instance. * @see org.jppf.utils.SystemUtils#getNetwork() */ public TypedProperties getNetwork() { return getProperties("network"); } /** * Get the map holding the JPPF configuration properties. * @return a {@code TypedProperties} instance. * @see org.jppf.utils.JPPFConfiguration#getProperties() */ public TypedProperties getJppf() { return getProperties("jppf"); } /** * Get the map holding the host storage information. * <p>The map will contain the following information: * <ul> * <li>host.roots.names = <i>root_name_0</i> ... <i>root_name_n-1</i> : the names of all accessible file system roots</li> * <li>host.roots.number = <i>n</i> : the number of accessible file system roots</li> * <li><b>For each root <i>i</i>:</b></li> * <li>root.<i>i</i>.name = <i>root_name</i> : for instance &quot;C:\&quot; on Windows or &quot;/&quot; on Unix</li> * <li>root.<i>i</i>.space.free = <i>space_in_bytes</i> : current free space for the root</li> * <li>root.<i>i</i>.space.total = <i>space_in_bytes</i> : total space for the root</li> * <li>root.<i>i</i>.space.usable = <i>space_in_bytes</i> : space available to the user the JVM is running under</li> * </ul> * If the JVM version is prior to 1.6, the space information will not be available. * @return a {@code TypedProperties} instance. * @see org.jppf.utils.SystemUtils#getStorageInformation() */ public TypedProperties getStorage() { return getProperties("storage"); } /** * Get the properties object holding the JPPF uuid and version information. * The following properties are provided: * <ul> * <li>"jppf.uuid" : the uuid of the node or driver</li> * <li>"jppf.pid" : the process id of the JVM running the JPPF driver or node</li> * <li>"jppf.version.number" : the current JPPF version number</li> * <li>"jppf.build.number" : the current build number</li> * <li>"jppf.build.date" : the build date, including the time zone, in the format "yyyy-MM-dd hh:mm z" </li> * </ul> * @return a {@code TypedProperties} wrapper for the uuid and version information of the corresponding JPPF component. */ public TypedProperties getUuid() { return getProperties("uuid"); } /** * Get the properties object holding the JPPF server statistics, listed as constants in {@link JPPFStatisticsHelper}. * @return a {@code TypedProperties} wrapper for the server statistics; for a node this will return an empty set of properties. */ public TypedProperties getStats() { return getProperties("stats"); } /** * Get the properties object holding the operating system information. * The following properties are provided: * <ul> * <li>"os.TotalPhysicalMemorySize" : total physical RAM (long value)</li> * <li>"os.FreePhysicalMemorySize" : available physical RAM (long value)</li> * <li>"os.TotalSwapSpaceSize" : total swap space (long value)</li> * <li>"os.FreeSwapSpaceSize" : available swap space (long value)</li> * <li>"os.CommittedVirtualMemorySize" : total committed virtual memory of the process (long value)</li> * <li>"os.ProcessCpuLoad" : process CPU load (double value in range [0 ... 1])</li> * <li>"os.ProcessCpuTime" : process CPU time (long value)</li> * <li>"os.SystemCpuLoad" : system total CPU load (double value in range [0 ... 1])</li> * <li>"os.Name" : the name of the OS (string value, ex: "Windows 7")</li> * <li>"os.Version" : the OS version (string value, ex: "6.1")</li> * <li>"os.Arch" : the OS architecture (string value, ex: "amd64")</li> * <li>"os.AvailableProcessors" : number of processors available to the OS (int value)</li> * <li>"os.SystemLoadAverage" : average system CPU load over the last minute (double value in the range [0 ... 1], always returns -1 on Windows)</li> * </ul> * @return a {@code TypedProperties} wrapper for the operating system information of the corresponding JPPF component. */ public TypedProperties getOS() { return getProperties("os"); } /** * Get all the properties as an array. * @return an array of all the sets of properties. */ @Override public TypedProperties[] getPropertiesArray() { synchronized(map) { if (propertiesArray == null) propertiesArray = map.values().toArray(new TypedProperties[map.size()]); return propertiesArray; } } @Override public void addProperties(final String key, final TypedProperties properties) { synchronized(map) { map.put(key, properties); propertiesArray = map.values().toArray(new TypedProperties[map.size()]); } } @Override public TypedProperties getProperties(final String key) { synchronized(map) { return map.get(key); } } /** * Populate this system information object. * @return this {@code JPPFSystemInformation} object. */ public JPPFSystemInformation populate() { addProperties("system", SystemUtils.getSystemProperties()); addProperties("runtime", SystemUtils.getRuntimeInformation()); addProperties("env", SystemUtils.getEnvironment()); addProperties("jppf", new TypedProperties((jppfConfig == null) ? JPPFConfiguration.getProperties() : jppfConfig)); //addProperties("jppf", (jppfConfig == null) ? JPPFConfiguration.getProperties() : jppfConfig); getJppf().setProperty("jppf.channel.local", String.valueOf(local)); final Runnable r = new Runnable() { @Override public void run() { addProperties("network", SystemUtils.getNetwork()); } }; if (resolveInetAddressesNow) r.run(); else ThreadUtils.startThread(r, "InetAddressResolver"); addProperties("storage", SystemUtils.getStorageInformation()); if (getProperties("uuid") == null) addProperties("uuid", new TypedProperties()); addProperties("os", SystemUtils.getOS()); final TypedProperties statsProperties = new TypedProperties(); addProperties("stats", statsProperties); if (stats != null) { for (JPPFSnapshot snapshot: stats) JPPFStatisticsHelper.toProperties(statsProperties, snapshot); stats = null; } return this; } /** * Parse the list of IP v4 addresses contained in this JPPFSystemInformation instance.<br> * This method is provided as a convenience so developers don't have to do the parsing themselves. * @return an array of {@code HostIP} instances. * @exclude */ public HostIP[] parseIPV4Addresses() { return NetworkUtils.parseAddresses(getNetwork().getString("ipv4.addresses")); } /** * Parse the list of IP v6 addresses contained in this JPPFSystemInformation instance.<br> * This method is provided as a convenience so developers don't have to do the parsing themselves. * @return an array of {@code HostIP} instances. * @exclude */ public HostIP[] parseIPV6Addresses() { return NetworkUtils.parseAddresses(getNetwork().getString("ipv6.addresses")); } @Override public String toString() { final StringBuilder sb = new StringBuilder(getClass().getSimpleName()).append('['); sb.append("uuid=").append(getUuid().getString("jppf.uuid")); sb.append(", local=").append(local); sb.append(", resolveInetAddressesNow=").append(resolveInetAddressesNow); //sb.append(", map=").append(map); return sb.append(']').toString(); } @Override public String getProperty(final String name) { for (TypedProperties props: getPropertiesArray()) { if (props == null) continue; if (props.containsKey(name)) return props.getProperty(name); } return null; } @Override public boolean containsKey(final String name) { for (TypedProperties props: getPropertiesArray()) { if (props == null) continue; if (props.containsKey(name)) return true; } return false; } }
41.965812
173
0.693754
4112a73a7f0d3a0df14be35521765fd8b7b06a8e
4,736
package eu.nimble.service.model.solr.owl; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; import org.springframework.data.solr.core.mapping.Indexed; import org.springframework.data.solr.core.mapping.SolrDocument; import com.fasterxml.jackson.annotation.JsonIgnore; /** * SOLR Document holding the properties out of * any ontologies including label, range and * the usage in distinct classes * * @author dglachs * */ @SolrDocument(collection=IPropertyType.COLLECTION) public class PropertyType extends Concept implements IPropertyType { /** * The uri of the property including namespace */ @Indexed(defaultValue=TYPE_VALUE, name=TYPE_FIELD) private String type = TYPE_VALUE; @Indexed(required=false, name=RANGE_FIELD) private String range; @Indexed(required=false, type="string", name=VALUE_QUALIFIER_FIELD) private ValueQualifier valueQualifier; @Indexed(required=false, name=USED_WITH_FIELD) private Collection<String> product; @Indexed(required=false, name=USED_BY_FIELD) private Collection<String> items; @Indexed(required=false, name=IDX_FIELD_NAME_FIELD) private Collection<String> itemFieldNames; @Indexed(required=false, name=IS_FACET_FIELD) private boolean facet = true; @Indexed(required=false, name=IS_VISIBLE_FIELD) private boolean visible = true; @Indexed(required=false, name=IS_REQUIRED_FIELD) private boolean required = false; @Indexed(required=false, name=BOOST_FIELD, type="pdouble") private Double boost; @Indexed(required=false, name=PROPERTY_TYPE_FIELD) private String propertyType; // @Indexed(required=false, name=PEFERRED_VALUE_CODE_FIELD) // private String valueCode; @Indexed(required=false, name= CODE_LIST_FIELD) private Collection<String> codeList; @Indexed(required=false, name=CODE_LIST_ID_FIELD) private String codeListId; public String getPropertyType() { return propertyType; } public void setPropertyType(String propertyType) { this.propertyType = propertyType; } @JsonIgnore public Collection<String> getUnits() { return codeList; } public void setUnits(Collection<String> unitsTypeList) { this.codeList = unitsTypeList; } public Collection<String> getCodeList() { if ( codeList == null) { codeList = new HashSet<String>(); } return codeList; } public void setCodeList(Collection<String> valueCodesList) { this.codeList = valueCodesList; } public String getRange() { return range; } public void setRange(String range) { this.range = range; } public Collection<String> getProduct() { if (product == null ) { product = new HashSet<String>(); } return product; } public void addProduct(String className) { if ( this.product == null ) { this.product = new HashSet<>(); } } public void setProduct(Collection<String> className) { this.product = className; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Collection<String> getItemFieldNames() { return itemFieldNames; } public void setItemFieldNames(Collection<String> idxFieldNames) { this.itemFieldNames = idxFieldNames; } public void addItemFieldName(String idxField) { if (itemFieldNames==null) { itemFieldNames=new HashSet<>(); } else if (! (itemFieldNames instanceof Set)) { // ensure to have a new set (to avoid duplicates) itemFieldNames = itemFieldNames.stream().collect(Collectors.toSet()); } this.itemFieldNames.add(idxField); } public ValueQualifier getValueQualifier() { return valueQualifier; } public void setValueQualifier(ValueQualifier valueQualifier) { this.valueQualifier = valueQualifier; } @JsonIgnore public boolean isFacet() { return facet; } public void setFacet(boolean facet) { this.facet = facet; } @JsonIgnore public Double getBoost() { return boost; } public void setBoost(Double boost) { this.boost = boost; } public Collection<String> getItems() { return items; } public void setItems(Collection<String> items) { this.items = items; } public void addItem(String uri) { if ( items == null ) { items = new HashSet<>(); } items.add(uri); } public boolean removeItem(String item) { if ( items == null ) { return false; } return items.remove(item); } public boolean isVisible() { return visible; } public void setVisible(boolean visible) { this.visible = visible; } public boolean isRequired() { return required; } public void setRequired(boolean required) { this.required = required; } public String getCodeListId() { return codeListId; } public void setCodeListId(String codeListUri) { this.codeListId = codeListUri; } }
22.339623
72
0.732475
296abc3a65553a22362a6d30f2d1332f7505084e
3,936
package main.java.CustomUtils; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Stats { private static final int MIN = 0, MAX = 1; public static double computeSkewness(List<List<double[]>> trajSet){ double[] meanPoint = new double[TrajUtil.getDim()]; double skewNominator = 0; double skewDenominator = 0; int nPoint = 0; for(List<double[]> traj:trajSet){ for (double[] p : traj) { for (int k = 0; k < TrajUtil.getDim(); k++) meanPoint[k] = meanPoint[k] + p[k]; nPoint++; } } for(int k=0;k<TrajUtil.getDim();k++) meanPoint[k] = meanPoint[k]/nPoint; //skewness for (List<double[]> traj : trajSet) { for (double[] p : traj) { double dist = Util.computeDistance(meanPoint, p); skewNominator += Math.pow(dist, 3); skewDenominator += Math.pow(dist, 2); } } skewNominator/=nPoint; skewDenominator/=nPoint; skewDenominator= Math.pow(skewDenominator,3.0/2); double skewness = skewNominator/skewDenominator; System.out.println("Point distribution skewness: " +skewness); return skewness; } public static double[] computeConsecutiveDistPercentiles(List<List<double[]>> trajSet){ double[] percentilesDistConsecutivePoints = new double[101]; List<Double> consecutiveDistances = new ArrayList<>(); for(List<double[]> traj:trajSet) { for (int i = 1; i < traj.size(); i++) { double consecutiveDist = Util.computeDistance(traj.get(i), traj.get(i-1)); consecutiveDistances.add(consecutiveDist); } } extractXiles(consecutiveDistances,percentilesDistConsecutivePoints); return percentilesDistConsecutivePoints; } private static void extractXiles(List<Double> distances, double[] iles) { Collections.sort(distances); for(int i=0;i<iles.length;i++) { if(i==iles.length-1) iles[i] = distances.get(distances.size() - 1); else iles[i] = distances.get((int)((double)distances.size() / iles.length * i )); } } public static double[] computeMbrDiagonal(List<List<double[]>> trajSet){ double[] quartilesDistMbr = new double[5]; List<Double> distances = new ArrayList<>(); for(List<double[]> traj:trajSet) { double[][] mbr = TrajUtil.findMBR(traj); double[] range = new double[mbr[0].length]; double dist = Util.computeDistance(mbr[MIN],mbr[MAX]); distances.add(dist); } extractXiles(distances, quartilesDistMbr); return quartilesDistMbr; } public static double[][] computeBoundary(List<List<double[]>> trajSet){ double[][] boundary = new double[2][]; boundary[MIN] = new double[TrajUtil.getDim()]; boundary[MAX] = new double[TrajUtil.getDim()]; for(int i=0;i<TrajUtil.getDim();i++){ boundary[MIN][i] = Double.MAX_VALUE; boundary[MAX][i] = -Double.MAX_VALUE; } for(List<double[]> traj:trajSet) { for(int d=0;d<TrajUtil.getDim();d++){ double[][] mbr = TrajUtil.findMBR(traj); if (boundary[MIN][d] > mbr[MIN][d])//min boundary[MIN][d] = mbr[MIN][d]; if (boundary[MAX][d] < mbr[MAX][d])//max boundary[MAX][d] = mbr[MAX][d]; } } return boundary; } public static double computeAverageLength(List<List<double[]>> trajSet){ double sumLength = 0; for(List<double[]> traj:trajSet) { sumLength+=traj.size(); } return sumLength/trajSet.size(); } }
34.526316
92
0.560722
13b03110229f0f4d63fa01e1a63667f9231259e9
388
package bg.bulsi.egov.eauth.metadata.config.model; import java.io.Serializable; import lombok.Data; @Data public class ContactData implements Serializable { private static final long serialVersionUID = -8327458792336659441L; private String email; private String company; private String givenName; private String surName; private String phone; }
20.421053
69
0.737113
24eb220f8e68f6df44a2820f8518cc63783dc19c
3,402
package com.aliyuncs.ft.model; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.util.HashMap; import java.util.Map; import com.aliyuncs.RpcAcsRequest; import com.aliyuncs.auth.AlibabaCloudCredentials; import com.aliyuncs.auth.BasicSessionCredentials; import com.aliyuncs.auth.HmacSHA1Signer; import com.aliyuncs.auth.Signer; import com.aliyuncs.http.FormatType; import com.aliyuncs.http.HttpRequest; import com.aliyuncs.regions.ProductDomain; import com.aliyuncs.utils.ParameterHelper; public class RpcDubboApiRequest extends RpcAcsRequest<RpcDubboApiResponse> { private String requiredValue = "testSignatureV2ForSDK"; private String success = "true"; public RpcDubboApiRequest() { super("Ft", "2015-01-01", "RpcDubboApi"); putQueryParameter("RequiredValue", this.requiredValue); putQueryParameter("Success", this.success); } public String getRequiredValue() { return requiredValue; } public void setRequiredValue(String requiredValue) { this.requiredValue = requiredValue; putQueryParameter("RequiredValue", this.requiredValue); } public String getSuccess() { return this.success; } public void setSuccess(String success) { this.success = success; putQueryParameter("Success", this.success); } @Override public HttpRequest signRequest(Signer signer, AlibabaCloudCredentials credentials, FormatType format, ProductDomain domain) throws InvalidKeyException, IllegalStateException, UnsupportedEncodingException { signer = new HmacSHA1Signer(); Map<String, String> imutableMap = new HashMap<String, String>(this.getQueryParameters()); if (null != signer && null != credentials) { String accessKeyId = credentials.getAccessKeyId(); if (credentials instanceof BasicSessionCredentials) { BasicSessionCredentials basicSessionCredentials = (BasicSessionCredentials)credentials; if (basicSessionCredentials.getSessionToken() != null) { this.putQueryParameter("SecurityToken", basicSessionCredentials.getSessionToken()); } } imutableMap = this.composer.refreshSignParameters(this.getQueryParameters(), signer, accessKeyId, format); imutableMap.put("RegionId", getRegionId()); Map<String, String> paramsToSign = new HashMap<String, String>(imutableMap); Map<String, String> formParams = this.getBodyParameters(); if (formParams != null && !formParams.isEmpty()) { byte[] data = ParameterHelper.getFormData(formParams); this.setHttpContent(data, "UTF-8", FormatType.FORM); paramsToSign.putAll(formParams); } String strToSign = this.composer.composeStringToSign(this.getMethod(), null, signer, paramsToSign, null, null); String signature = signer.signString(strToSign, credentials.getAccessKeySecret()); imutableMap.put("Signature", signature); } setUrl(this.composeUrl(domain.getDomianName(), imutableMap)); return this; } @Override public Class<RpcDubboApiResponse> getResponseClass() { return RpcDubboApiResponse.class; } }
39.103448
127
0.683128
b3896408247e0792fe470f9166e9bd27b95b2033
551
package br.com.solstice.notecommerce.entity.domain.stock; import br.com.solstice.notecommerce.entity.domain.DomainEntity; import br.com.solstice.notecommerce.entity.domain.product.Product; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.ToString; import lombok.NoArgsConstructor; import lombok.Setter; @Getter @Setter @NoArgsConstructor @AllArgsConstructor @ToString(callSuper = true) public class Stock extends DomainEntity { private Product product; private Integer quantity; public Stock(Long id) { super(id); } }
21.192308
66
0.809437
14cafecfb0a2155d3e1e5943ff06aa32418bc992
743
import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.regex.*; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int numInputs = sc.nextInt(); for(int i = 1; i <= numInputs; i++){ // rows int j = numInputs; // loop to print (size - i) spaces while(j-- > i) { System.out.print(" "); } // loop to print (i) #s while(j-- >= 0) { System.out.print("#"); } System.out.println(); } } }
21.852941
48
0.45895
bde3400b02fb208df6f34d903ebfa72132d56e84
333
package cc.zkteam.zkinfocollectpro.fragment.problem.mvp; import cc.zkteam.zkinfocollectpro.base.mvp.BaseMVPView; /** * Created by Administrator on 2017/12/15. */ public interface PRView extends BaseMVPView { void setLocationInfo(String location); void cleanInput(); void showLoading(); void hideLoading(); }
17.526316
56
0.735736
3c044dc3b7b1a1c923b1cb7fe88cab5a353912ab
1,720
package com.example.insta; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.parse.ParseFile; import java.util.List; public class ProfileAdapter extends RecyclerView.Adapter<ProfileAdapter.ViewHolder> { private Context context; private List<Post> posts; public ProfileAdapter (Context context, List<Post> posts) { this.context = context; this.posts = posts; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.item_profile, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) { Post post = posts.get(i); viewHolder.bind(post); } @Override public int getItemCount() { return posts.size(); } class ViewHolder extends RecyclerView.ViewHolder{ private ImageView ivProfileSquareImage; public ViewHolder(View itemView){ super(itemView); ivProfileSquareImage = itemView.findViewById(R.id.ivProfileSquareImage); } public void bind(Post post) { ParseFile image = post.getImage(); if(image != null) { Glide.with(context) .load(image.getUrl()) .into(ivProfileSquareImage); } } } }
27.301587
95
0.662209
34380cfd65c1af9b9bd6fa632b5d6a2743d94584
3,038
package gin; import com.github.javaparser.JavaParser; import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.stmt.BlockStmt; import com.github.javaparser.ast.stmt.Statement; import java.io.File; import java.io.IOException; import java.util.List; public class SourceFile { private CompilationUnit compilationUnit; private int statementCount; private int numberOfBlocks; private int[] numberOfInsertionPointsInBlock; private String filename; public SourceFile(String filename) { this.filename = filename; try { this.compilationUnit = JavaParser.parse(new File(filename)); } catch (IOException e) { System.err.println("Exception reading program source: " + e); System.exit(-1); } countStatements(); countBlocks(); } public SourceFile(CompilationUnit compilationUnit) { this.compilationUnit = compilationUnit; countStatements(); countBlocks(); } public String getSource() { return this.compilationUnit.toString(); } public String getFilename() { return this.filename; } public CompilationUnit getCompilationUnit() { return compilationUnit; } public int getStatementCount() { return statementCount; } public int getNumberOfBlocks() { return numberOfBlocks; } public int getNumberOfInsertionPointsInBlock(int block) { return numberOfInsertionPointsInBlock[block]; } private void countStatements() { List<Statement> list = compilationUnit.getChildNodesByType(Statement.class); statementCount = list.size(); } private void countBlocks() { List<BlockStmt> list = compilationUnit.getChildNodesByType(BlockStmt.class); numberOfBlocks = list.size(); numberOfInsertionPointsInBlock = new int[numberOfBlocks]; int counter = 0; for (BlockStmt b: list) { numberOfInsertionPointsInBlock[counter] = b.getStatements().size(); counter++; } } public String statementList() { List<Statement> list = compilationUnit.getChildNodesByType(Statement.class); statementCount = list.size(); int counter = 0; String output = ""; for (Statement statement: list) { output += "[" + counter + "] " + statement.toString() + "\n"; // can't use indexof as may appear > once counter++; } return output; } public String blockList() { List<BlockStmt> list = compilationUnit.getChildNodesByType(BlockStmt.class); numberOfBlocks = list.size(); int counter = 0; String output = ""; for (BlockStmt block: list) { output += "[" + counter + "] " + block.toString() + "\n"; // can't use indexof as may appear > once counter++; } return output; } public String toString() { return this.getSource(); } }
28.392523
116
0.627716
525cccd78521c7c771ff4f7e4236df0c475cddc5
1,775
/** fun_endless@163.com 2018年11月26日 */ package org.aimbin.commons.javas; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /**Tools for date. * @author aimbin * @verison 1.0.0 2018年11月26日 */ public class TimeUtils { /** yyyy-MM-dd HH:mm:ss SSS */ private static final DateFormat _full = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS"); private static final String _TightPattern = "yyyyMMddHHmmssSSS"; /** yyyyMMddHHmmssSSS */ private static final DateFormat _fullTight = new SimpleDateFormat(_TightPattern); /**To yyyy-MM-dd HH:mm:ss SSS. */ public static String toStrFull(Date date) { return _full.format(date); } /**To yyyyMMddHHmmssSSS. */ public static String toStrFullTight(Date date) { return _fullTight.format(date); } /**To date for yyyy-MM-dd HH:mm:ss SSS. */ public static Date toDateAsFull(String full) { try { return _full.parse(full); } catch (ParseException e) { throw new IllegalArgumentException(e); } } /**To date for yyyyMMddHHmmssSSS. */ public static Date toDateFullTight(String fullTight) { try { return _fullTight.parse(fullTight); } catch (ParseException e) { throw new IllegalArgumentException(e); } } /** Eliminate the tail value of last digits as format of yyyyMMddHHmmssSSS. */ public static Date eliminateTail(Date date, int tailLength) { if(tailLength > _TightPattern.length()) { throw new IllegalArgumentException("tailLength must less than lenth of yyyyMMddHHmmssSSS"); } String full = toStrFullTight(date); full = full.substring(0, _TightPattern.length() - tailLength) + StrUtils.repeat("0", tailLength); return toDateFullTight(full); } }
30.603448
100
0.704225
60ed344e041bea500971920081502a6dd825d0b1
2,441
package com.amazonaws.stepfunctions.cloudformation.statemachine; import com.amazonaws.services.stepfunctions.model.DescribeStateMachineResult; import com.amazonaws.services.stepfunctions.model.Tag; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; public class ResourceModelUtilsTest extends HandlerTestBase { @Test public void testGetUpdatedResourceModelFromReadResults_returnsUpdatedModelWithAllProperties() { final DescribeStateMachineResult describeStateMachineResult = new DescribeStateMachineResult(); describeStateMachineResult.setStateMachineArn(STATE_MACHINE_ARN); describeStateMachineResult.setName(STATE_MACHINE_NAME); describeStateMachineResult.setDefinition(DEFINITION); describeStateMachineResult.setRoleArn(ROLE_ARN); describeStateMachineResult.setType(EXPRESS_TYPE); final LoggingConfiguration loggingConfiguration = createLoggingConfiguration(); describeStateMachineResult.setLoggingConfiguration(Translator.getLoggingConfiguration(loggingConfiguration)); final TracingConfiguration tracingConfiguration = createTracingConfiguration(true); describeStateMachineResult.setTracingConfiguration(Translator.getTracingConfiguration(tracingConfiguration)); final List<Tag> stateMachineTags = new ArrayList<>(); stateMachineTags.add(new Tag().withKey("Key1").withValue("Value1")); stateMachineTags.add(new Tag().withKey("Key2").withValue("Value2")); final ResourceModel outputModel = ResourceModelUtils.getUpdatedResourceModelFromReadResults( describeStateMachineResult, stateMachineTags); final List<TagsEntry> expectedTagEntries = new ArrayList<>(); expectedTagEntries.add(new TagsEntry("Key1", "Value1")); expectedTagEntries.add(new TagsEntry("Key2", "Value2")); final ResourceModel expectedModel = new ResourceModel( STATE_MACHINE_ARN, STATE_MACHINE_NAME, DEFINITION, ROLE_ARN, STATE_MACHINE_NAME, EXPRESS_TYPE, loggingConfiguration, tracingConfiguration, null, null, null, expectedTagEntries); assertThat(outputModel).isEqualTo(expectedModel); } }
42.086207
117
0.726342
f48092a81932e37db94f05277592a15f30e3ee23
2,366
package oriedita.editor.action; import javax.inject.Inject; import javax.inject.Singleton; import org.tinylog.Logger; import origami.crease_pattern.element.Point; import oriedita.editor.canvas.MouseMode; import origami.folding.FoldedFigure; import oriedita.editor.canvas.CreasePattern_Worker; import oriedita.editor.databinding.FoldedFiguresList; import oriedita.editor.drawing.FoldedFigure_Drawer; @Singleton public class MouseHandlerChangeStandardFace extends BaseMouseHandler { private final CreasePattern_Worker d; private final FoldedFiguresList foldedFiguresList; @Inject public MouseHandlerChangeStandardFace(FoldedFiguresList foldedFiguresList, CreasePattern_Worker d) { this.foldedFiguresList = foldedFiguresList; this.d = d; } @Override public MouseMode getMouseMode() { return MouseMode.CHANGE_STANDARD_FACE_103; } @Override public void mouseMoved(Point p0) { } @Override public void mousePressed(Point p0) { } @Override public void mouseDragged(Point p0) { } @Override public void mouseReleased(Point p0) { FoldedFigure_Drawer selectedFigure = (FoldedFigure_Drawer) foldedFiguresList.getSelectedItem(); if (selectedFigure != null) { Point p = new Point(); p.set(d.camera.TV2object(p0)); int oldStartingFaceId = selectedFigure.getStartingFaceId(); int newStartingFaceId = selectedFigure.foldedFigure.cp_worker1.get().inside(p); if (newStartingFaceId < 1) return; selectedFigure.setStartingFaceId(newStartingFaceId); Logger.info("kijyunmen_id = " + newStartingFaceId); if (selectedFigure.foldedFigure.ct_worker.face_rating != null) {//20180227追加 int index = selectedFigure.foldedFigure.ct_worker.nbox.getSequence(newStartingFaceId); Logger.info( "OZ.js.nbox.get_jyunjyo = " + index + " , rating = " + selectedFigure.foldedFigure.ct_worker.nbox.getWeight(index) ); } if ((newStartingFaceId != oldStartingFaceId) && (selectedFigure.foldedFigure.estimationStep != FoldedFigure.EstimationStep.STEP_0)) { selectedFigure.foldedFigure.estimationStep = FoldedFigure.EstimationStep.STEP_1; } } } }
31.546667
145
0.692308
429951819e1bfec4617f8542781c61219d997299
2,908
/* * Copyright (c) 2016-2018 Evolveum and contributors * * This work is dual-licensed under the Apache License 2.0 * and European Union Public License. See LICENSE file for details. */ package com.evolveum.midpoint.model.impl; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import java.io.File; import java.util.List; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; import org.testng.annotations.Test; import com.evolveum.midpoint.prism.PrismContainer; import com.evolveum.midpoint.prism.PrismContainerValue; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; @ContextConfiguration(locations = { "classpath:ctx-model-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestFilterResolverQueryDsl extends AbstractInternalModelIntegrationTest { protected static final File TEST_DIR = new File("src/test/resources/common"); private static final String RESOURCE_DUMMY_DEPENDENCY_FILTER_OID = "10000000-0000-0000-dep0-000000000004"; private static final File RESOURCE_DUMMY_DEPENDENCY_FILTER_FILE = new File(TEST_DIR, "resource-dummy-dependency-filter-querydsl.xml"); @Test public void test001resolveDependencyFilter() throws Exception { // WHEN importObjectFromFile(RESOURCE_DUMMY_DEPENDENCY_FILTER_FILE); // THEN PrismObject<ResourceType> resourceDummyResolvedFilter = getObject(ResourceType.class, RESOURCE_DUMMY_DEPENDENCY_FILTER_OID); assertNotNull(resourceDummyResolvedFilter, "Something unexpected happened. No resource found"); PrismContainer<ResourceObjectTypeDefinitionType> objectType = resourceDummyResolvedFilter.findContainer( ItemPath.create(ResourceType.F_SCHEMA_HANDLING, SchemaHandlingType.F_OBJECT_TYPE)); assertEquals(objectType.size(), 1, "Unexpected object type definitions in resource."); PrismContainerValue<ResourceObjectTypeDefinitionType> objectTypeDef = objectType.getValues().iterator().next(); List<ResourceObjectTypeDependencyType> resourceDependencies = objectTypeDef.asContainerable().getDependency(); assertEquals(resourceDependencies.size(), 1, "Unexpected dependency definitions in resource."); ResourceObjectTypeDependencyType resourceDependency = resourceDependencies.iterator().next(); ObjectReferenceType dependencyRef = resourceDependency.getResourceRef(); assertNotNull(dependencyRef, "No dependency reference found in the resource, something is wrong"); assertEquals(dependencyRef.getOid(), RESOURCE_DUMMY_OID, "Unexpected oid in resolved reference."); } }
49.288136
138
0.788514
6b480ce8ae3a87495ecb025ffe775511cf66d27b
3,644
package org.motechproject.security.service.authentication; import org.motechproject.security.domain.MotechRole; import org.motechproject.security.domain.MotechUser; import org.motechproject.security.domain.UserStatus; import org.motechproject.security.repository.AllMotechRoles; import org.motechproject.security.repository.AllMotechUsers; import org.motechproject.security.service.AuthoritiesService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.AuthenticationUserDetailsService; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.openid.OpenIDAttribute; import org.springframework.security.openid.OpenIDAuthenticationToken; import java.util.ArrayList; import java.util.List; import java.util.Locale; /** * Implementation class for @AuthenticationUserDetailsService. Retrieves user details given OpenId * authentication */ public class MotechOpenIdUserDetailsService implements AuthenticationUserDetailsService<OpenIDAuthenticationToken> { private AllMotechRoles allMotechRoles; private AllMotechUsers allMotechUsers; private AuthoritiesService authoritiesService; /** * Adds user for given OpenId to {@link org.motechproject.security.repository.AllMotechUsers} * and return his {@link org.springframework.security.core.userdetails.UserDetails} * * @param token for OpenId * @return details of added user */ @Override public UserDetails loadUserDetails(OpenIDAuthenticationToken token) { MotechUser user = allMotechUsers.findUserByOpenId(token.getName()); if (user == null) { List<String> roles = new ArrayList<String>(); if (allMotechUsers.getOpenIdUsers().isEmpty()) { for (MotechRole role : allMotechRoles.getRoles()) { roles.add(role.getRoleName()); } } user = new MotechUser(getAttribute(token.getAttributes(), "Email"), "", getAttribute(token.getAttributes(), "Email"), "", roles, token.getName(), Locale.getDefault()); allMotechUsers.addOpenIdUser(user); } return new User(user.getUserName(), user.getPassword(), user.isActive(), true, true, !UserStatus.BLOCKED.equals(user.getUserStatus()), authoritiesService.authoritiesFor(user)); } /** * Looks for attribute with given name in given list * * @param attributes list of OpenId attributes * @param attributeName of attribute we're looking for * @return string with attribute value if attribute with given * name exists, otherwise return empty string */ private String getAttribute(List<OpenIDAttribute> attributes, String attributeName) { String attributeValue = ""; for (OpenIDAttribute attribute : attributes) { if (attribute.getName() != null && (attribute.getName().equals("ax" + attributeName) || attribute.getName().equals("ae" + attributeName))) { attributeValue = attribute.getValues().get(0); } } return attributeValue; } @Autowired public void setAllMotechRoles(AllMotechRoles allMotechRoles) { this.allMotechRoles = allMotechRoles; } @Autowired public void setAllMotechUsers(AllMotechUsers allMotechUsers) { this.allMotechUsers = allMotechUsers; } @Autowired public void setAuthoritiesService(AuthoritiesService authoritiesService) { this.authoritiesService = authoritiesService; } }
41.885057
179
0.723106
817ee432b3c70d19d0e8501d35be05b4cecd05f4
805
package com.metaui.core.util.group; import java.util.HashMap; import java.util.Map; /** * 分组模型 * * @author wei_jc * @since 1.0.0 */ public class GroupModel { private String[] groupCols; private Map<String, GroupFunction> computeColMap = new HashMap<String, GroupFunction>(); public void addComputeCol(String colName, GroupFunction function) { computeColMap.put(colName, function); } public String[] getGroupCols() { return groupCols; } public Map<String, GroupFunction> getComputeColMap() { return computeColMap; } public void setGroupCols(String[] groupCols) { this.groupCols = groupCols; } public void setComputeColMap(Map<String, GroupFunction> computeColMap) { this.computeColMap = computeColMap; } }
22.361111
92
0.677019
780ce2b7eddaf42879ad6b2240abff1965a4b6ef
14,023
package com.hello.holaApp.activity; import android.content.Intent; import android.graphics.Color; import android.graphics.Typeface; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageButton; import android.widget.TextView; import com.crashlytics.android.Crashlytics; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.hello.holaApp.R; import com.hello.holaApp.common.CommonFunction; import com.hello.holaApp.fragment.GroupChatFragment; import com.sendbird.android.GroupChannel; import com.sendbird.android.SendBird; import com.sendbird.android.SendBirdException; import com.sendbird.android.User; import java.util.ArrayList; import java.util.List; /** * Created by lji5317 on 11/12/2017. */ public class ChatRoomActivity extends AppCompatActivity { private FirebaseAuth mAuth; private FirebaseUser fUser; public static final String EXTRA_NEW_CHANNEL_URL = "EXTRA_NEW_CHANNEL_URL"; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_group_channel); CommonFunction.sendMsg(getApplicationContext()); /*Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_group_channel); setSupportActionBar(toolbar); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_back_arrow); } */ this.mAuth = FirebaseAuth.getInstance(); this.fUser = mAuth.getCurrentUser(); ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayShowCustomEnabled(true); //true설정을 해주셔야 합니다. actionBar.setDisplayHomeAsUpEnabled(false); //액션바 아이콘을 업 네비게이션 형태로 표시합니다. actionBar.setDisplayShowTitleEnabled(false); //액션바에 표시되는 제목의 표시유무를 설정합니다. actionBar.setDisplayShowHomeEnabled(false); //홈 아이콘을 숨김처리합니다. actionBar.setBackgroundDrawable(new ColorDrawable(Color.argb(255,255,255,255))); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); View actionView = getLayoutInflater().inflate(R.layout.new_say_action_bar, null); TextView title = (TextView) actionView.findViewById(R.id.actionBarTitle); title.setText(getIntent().getStringExtra("")); Typeface typeface = Typeface.createFromAsset(this.getAssets(), "fonts/NotoSans-Medium.ttf"); title.setTypeface(typeface); actionBar.setCustomView(actionView); Button saveBtn = (Button) findViewById(R.id.saveBtn); saveBtn.setVisibility(View.GONE); ImageButton backBtn = (ImageButton) actionView.findViewById(R.id.backBtn); backBtn.setOnClickListener(view1 -> { boolean userInfoYn = getIntent().getBooleanExtra("userInfoYn", false); if(!userInfoYn) { MainActivity.tabIndex = 2; startActivity(new Intent(this, MainActivity.class)); } finish(); }); /*if (savedInstanceState == null) { // If started from launcher, load list of Open Channels Fragment fragment = GroupChannelListFragment.newInstance(); FragmentManager manager = getSupportFragmentManager(); manager.popBackStack(); manager.beginTransaction() .replace(R.id.container_group_channel, fragment) .commit(); }*/ String channelUrl = getIntent().getStringExtra("channelUrl"); String uid = getIntent().getStringExtra("uid"); SendBird.connect(this.fUser.getUid(), new SendBird.ConnectHandler() { @Override public void onConnected(User user, SendBirdException e) { if (e != null) { e.printStackTrace(); return; } title.setText(getIntent().getStringExtra("senderName")); if(channelUrl != null) { // If started from notification Fragment fragment = GroupChatFragment.newInstance(channelUrl); FragmentManager manager = getSupportFragmentManager(); manager.beginTransaction() .replace(R.id.container_group_channel, fragment) .addToBackStack(null) .commit(); } else { /*GroupChannel.getChannel(channelUrl, new GroupChannel.GroupChannelGetHandler() { @Override public void onResult(GroupChannel groupChannel, SendBirdException e) { if (e != null) { // Error! e.printStackTrace(); return; } List<Member> memberList = groupChannel.getMembers(); for (Member member : memberList) { if(member.getUserId().equals(uid)) { title.setText(member.getNickname()); break; } } } });*/ List<String> userList = new ArrayList<>(); userList.add(uid); userList.add(fUser.getUid()); GroupChannel.createChannelWithUserIds(userList, true, new GroupChannel.GroupChannelCreateHandler() { @Override public void onResult(GroupChannel groupChannel, SendBirdException e) { if (e != null) { // Error! Log.d("errrr", e.getMessage()); Crashlytics.logException(e); return; } Fragment fragment = GroupChatFragment.newInstance(groupChannel.getUrl()); FragmentManager manager = getSupportFragmentManager(); manager.beginTransaction() .replace(R.id.container_group_channel, fragment) .addToBackStack(null) .commit(); } }); } } }); } public interface onBackPressedListener { boolean onBack(); } private onBackPressedListener mOnBackPressedListener; public void setOnBackPressedListener(onBackPressedListener listener) { mOnBackPressedListener = listener; } @Override public void onBackPressed() { if (mOnBackPressedListener != null && mOnBackPressedListener.onBack()) { return; } boolean userInfoYn = getIntent().getBooleanExtra("userInfoYn", false); if(!userInfoYn) { MainActivity.tabIndex = 2; startActivity(new Intent(this, MainActivity.class)); } finish(); super.onBackPressed(); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { onBackPressed(); return true; } return super.onOptionsItemSelected(item); } public void setActionBarTitle(String title) { if (getSupportActionBar() != null) { getSupportActionBar().setTitle(title); } } /*private GroupChannel groupChannel; private FirebaseAuth mAuth; private FirebaseUser fUser; private ChatView chatView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.chat_room); this.mAuth = FirebaseAuth.getInstance(); this.fUser = mAuth.getCurrentUser(); ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayShowCustomEnabled(true); //true설정을 해주셔야 합니다. actionBar.setDisplayHomeAsUpEnabled(false); //액션바 아이콘을 업 네비게이션 형태로 표시합니다. actionBar.setDisplayShowTitleEnabled(false); //액션바에 표시되는 제목의 표시유무를 설정합니다. actionBar.setDisplayShowHomeEnabled(false); //홈 아이콘을 숨김처리합니다. View view = getLayoutInflater().inflate(R.layout.custom_action, null); actionBar.setCustomView(view); Button backBtn = (Button) view.findViewById(R.id.backBtn); TextView textView = (TextView) view.findViewById(R.id.actionBarTitle); backBtn.setOnClickListener(view1 -> { finish(); }); this.chatView = (ChatView) findViewById(R.id.chat_view); this.chatView.setOnSentMessageListener(chatMessage -> { // perform actual message sending if(this.groupChannel != null) { this.groupChannel.sendUserMessage(chatMessage.getMessage(), (userMessage, e) -> { if (e != null) { // Error. Crashlytics.logException(e); return; } }); } return true; }); Intent intent = getIntent(); String channelUrl = intent.getStringExtra("channelUrl"); String userName = intent.getStringExtra("userName"); String profileUrl = intent.getStringExtra("profileUrl"); String uid = intent.getStringExtra("uid"); textView.setText(userName); SendBird.connect(this.fUser.getUid(), (user, e) -> { if (e != null) { // Error. Crashlytics.logException(e); return; } if(channelUrl == null || channelUrl.isEmpty()) { List<String> userList = new ArrayList<>(); userList.add(this.fUser.getUid()); userList.add(uid); GroupChannel.createChannelWithUserIds(userList, true, (GroupChannel.GroupChannelCreateHandler) (gc, e1) -> { this.groupChannel = gc; if (e1 != null) { // Error. Crashlytics.logException(e1); return; } loadChatMessages(); }); } else { GroupChannel.getChannel(channelUrl, (groupChannel, e1) -> { // public void onResult(GroupChannel groupChannel, SendBirdException e) { if (e1 != null) { // Error! Crashlytics.logException(e1); return; } this.groupChannel = groupChannel; groupChannel.markAsRead(); List<Member> memberList = groupChannel.getMembers(); for(Member member : memberList) { if(member.getUserId().equals(this.fUser.getUid())) { textView.setText(member.getNickname()); } } loadChatMessages(); }); } }); SendBird.addChannelHandler(Constant.CHANNEL_HANDLER_ID, new SendBird.ChannelHandler() { @Override public void onMessageReceived(BaseChannel baseChannel, BaseMessage baseMessage) { groupChannel.markAsRead(); if (baseMessage instanceof UserMessage) { // message is a UserMessage UserMessage userMessage = (UserMessage)baseMessage; ChatMessage chatMessage = new ChatMessage(userMessage.getMessage(), userMessage.getCreatedAt(), ChatMessage.Type.RECEIVED); chatView.addMessage(chatMessage); } else if (baseMessage instanceof FileMessage) { // message is a FileMessage } else if (baseMessage instanceof AdminMessage) { // message is an AdminMessage } } }); } private void loadChatMessages() { PreviousMessageListQuery prevMessageListQuery = this.groupChannel.createPreviousMessageListQuery(); prevMessageListQuery.load(30, false, (messages, e1) -> { if (e1 != null) { // Error. Crashlytics.logException(e1); return; } for(BaseMessage message : messages) { if (message instanceof UserMessage) { // message is a UserMessage UserMessage userMessage = (UserMessage)message; ChatMessage.Type type; if(this.fUser.getUid().equals(userMessage.getSender().getUserId())) { type = ChatMessage.Type.SENT; } else { type = ChatMessage.Type.RECEIVED; } ChatMessage chatMessage = new ChatMessage(userMessage.getMessage(), userMessage.getCreatedAt(), type); this.chatView.addMessage(chatMessage); } else if (message instanceof FileMessage) { // message is a FileMessage } else if (message instanceof AdminMessage) { // message is an AdminMessage } } }); }*/ }
37.696237
143
0.562291
2cd7ee9ad4f7462a29c8fe512182c788758a9e66
1,888
/** * The contents of this file are subject to the Mozilla Public License * Version 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is: this file * * The Initial Developer of the Original Code is Oliver Becker. * * Portions created by Philip Helger * are Copyright (C) 2016-2017 Philip Helger * All Rights Reserved. */ package net.sf.joost.grammar.tree; import org.xml.sax.SAXException; import net.sf.joost.grammar.AbstractTree; import net.sf.joost.stx.Context; import net.sf.joost.stx.Value; /** * Objects of ListTree represent nodes that are items in a parameter list of a * function call in the syntax tree of a pattern or an STXPath expression. * * @version $Revision: 1.1 $ $Date: 2004/09/29 05:59:51 $ * @author Oliver Becker */ public final class ListTree extends AbstractTree { public ListTree () { super (LIST); } public ListTree (final AbstractTree left, final AbstractTree right) { super (LIST, left, right); } @Override public Value evaluate (final Context context, final int top) throws SAXException { // this won't happen context.m_aErrorHandler.fatalError ("'evaluate()' called for a LIST node", context.currentInstruction.m_sPublicID, context.currentInstruction.m_sSystemID, context.currentInstruction.lineNo, context.currentInstruction.colNo); return Value.VAL_EMPTY; } }
32
82
0.673199
f9ca071819a49dafb0fbb57d5675982ad20e6758
613
package lightsearch.server.entity; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; @Component("datasourcePasswordProperty") @Scope("prototype") public class DatasourcePasswordPropertyImpl implements Property<String> { private final String name; private final String value; public DatasourcePasswordPropertyImpl(String value) { this.name = "datasource.password"; this.value = value; } @Override public String name() { return name; } @Override public String as() { return value; } }
21.892857
73
0.704731
b6adaaabe48b188ec5732da8cac5813acd829d58
4,685
package edu.gemini.spModel.gemini.obscomp; import edu.gemini.pot.sp.ISPObsComponent; import edu.gemini.spModel.config.AbstractObsComponentCB; import edu.gemini.spModel.data.config.*; import java.util.List; import java.util.Map; public class SPSiteQualityCB extends AbstractObsComponentCB { private static final String SYSTEM_NAME = "ocs"; private static final String MIN_HOUR_ANGLE = "MinHourAngle"; private static final String MAX_HOUR_ANGLE = "MaxHourAngle"; private static final String MIN_AIRMASS = "MinAirmass"; private static final String MAX_AIRMASS = "MaxAirmass"; private static final String TIMING_WINDOW_START = "TimingWindowStart"; private static final String TIMING_WINDOW_DURATION = "TimingWindowDuration"; private static final String TIMING_WINDOW_REPEAT = "TimingWindowRepeat"; private static final String TIMING_WINDOW_PERIOD = "TimingWindowPeriod"; private SPSiteQuality _dataObj; public SPSiteQualityCB(ISPObsComponent obsComp) { super(obsComp); } public Object clone() { SPSiteQualityCB result = (SPSiteQualityCB) super.clone(); result._dataObj = null; return result; } @Override protected void thisReset(Map<String, Object> options) { _dataObj = (SPSiteQuality) getDataObject(); } protected boolean thisHasConfiguration() { return _dataObj != null; } protected void thisApplyNext(IConfig config, IConfig prevFull) { if (_dataObj == null) return; IConfigParameter obsConds = DefaultConfigParameter.getInstance("obsConditions"); config.putParameter(SYSTEM_NAME, obsConds); ISysConfig sysConfig = (ISysConfig) obsConds.getValue(); IParameter ip; ip = StringParameter.getInstance( SPSiteQuality.SKY_BACKGROUND_PROP.getName(), _dataObj.getSkyBackground().sequenceValue()); sysConfig.putParameter(ip); ip = StringParameter.getInstance( SPSiteQuality.CLOUD_COVER_PROP.getName(), _dataObj.getCloudCover().sequenceValue()); sysConfig.putParameter(ip); ip = StringParameter.getInstance( SPSiteQuality.IMAGE_QUALITY_PROP.getName(), _dataObj.getImageQuality().sequenceValue()); sysConfig.putParameter(ip); ip = StringParameter.getInstance( SPSiteQuality.WATER_VAPOR_PROP.getName(), _dataObj.getWaterVapor().sequenceValue()); sysConfig.putParameter(ip); SPSiteQuality.ElevationConstraintType elType =_dataObj.getElevationConstraintType(); if (elType == SPSiteQuality.ElevationConstraintType.HOUR_ANGLE) { ip = StringParameter.getInstance( MIN_HOUR_ANGLE, String.valueOf(_dataObj.getElevationConstraintMin())); sysConfig.putParameter(ip); ip = StringParameter.getInstance( MAX_HOUR_ANGLE, String.valueOf(_dataObj.getElevationConstraintMax())); sysConfig.putParameter(ip); } else if (elType == SPSiteQuality.ElevationConstraintType.AIRMASS) { ip = StringParameter.getInstance( MIN_AIRMASS, String.valueOf(_dataObj.getElevationConstraintMin())); sysConfig.putParameter(ip); ip = StringParameter.getInstance( MAX_AIRMASS, String.valueOf(_dataObj.getElevationConstraintMax())); sysConfig.putParameter(ip); } List<SPSiteQuality.TimingWindow> timingWindows = _dataObj.getTimingWindows(); if (timingWindows.size() != 0) { int i = -1; for(SPSiteQuality.TimingWindow timingWindow : timingWindows) { i++; ip = StringParameter.getInstance( TIMING_WINDOW_START+i, String.valueOf(timingWindow.getStart())); sysConfig.putParameter(ip); ip = StringParameter.getInstance( TIMING_WINDOW_DURATION+i, String.valueOf(timingWindow.getDuration())); sysConfig.putParameter(ip); ip = StringParameter.getInstance( TIMING_WINDOW_REPEAT+i, String.valueOf(timingWindow.getRepeat())); sysConfig.putParameter(ip); ip = StringParameter.getInstance( TIMING_WINDOW_PERIOD+i, String.valueOf(timingWindow.getPeriod())); sysConfig.putParameter(ip); } } _dataObj = null; } }
35.763359
92
0.635005
7ecf0024cc82e98f87b138221174a8757d3f01a4
2,808
/** * */ package com.telecominfraproject.wlan.equipmentgateway.models; import java.util.Objects; import com.telecominfraproject.wlan.core.model.equipment.RadioType; /** * A Request for resetting a radio. * * @author ekeddy * */ public class CEGWRadioResetRequest extends EquipmentCommand { /** * */ private static final long serialVersionUID = -7415410522452755178L; private RadioType radio; private RadioResetMethod resetMethod; protected CEGWRadioResetRequest() { super(CEGWCommandType.RadioReset, null, 0); } public CEGWRadioResetRequest(String qrCode, long equipmentId, RadioType radio, RadioResetMethod resetMethod) { super(CEGWCommandType.RadioReset, qrCode, equipmentId); this.radio = radio; this.resetMethod = resetMethod; } public RadioType getRadio() { return radio; } public void setRadio(RadioType radio) { this.radio = radio; } public RadioResetMethod getResetMethod() { return resetMethod; } public void setResetMethod(RadioResetMethod resetMethod) { this.resetMethod = resetMethod; } /** * Construct a reset request for an init reset. * * @param qrCode * @param equipmentId * @param radio * @return */ public static CEGWRadioResetRequest init(String qrCode, long equipmentId, RadioType radio) { return new CEGWRadioResetRequest(qrCode, equipmentId, radio, RadioResetMethod.init); } /** * Construct a reset request for a reload reset. * * @param qrCode * @param equipmentId * @param radio * @return */ public static CEGWRadioResetRequest reload(String qrCode, long equipmentId, RadioType radio) { return new CEGWRadioResetRequest(qrCode, equipmentId, radio, RadioResetMethod.reload); } @Override public boolean hasUnsupportedValue() { if (super.hasUnsupportedValue()) { return true; } if (RadioResetMethod.isUnsupported(resetMethod) || RadioType.isUnsupported(radio)) { return true; } return false; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + Objects.hash(radio, resetMethod); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (!(obj instanceof CEGWRadioResetRequest)) { return false; } CEGWRadioResetRequest other = (CEGWRadioResetRequest) obj; return this.radio == other.radio && this.resetMethod == other.resetMethod; } }
25.527273
114
0.633903
7e02d5921ee7af661ce9572f82e1416a3417a3cb
3,179
package eu.f3rog.blade.compiler.util; import java.io.IOException; import java.util.Set; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.Filer; import javax.annotation.processing.Messager; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.tools.Diagnostic; public abstract class BaseProcessor extends AbstractProcessor { private static final boolean DEBUG = false; private ProcessingEnvironment mProcessingEnvironment; private Messager mMessager; private Filer mFiler; private boolean mProcessingStarted; /**BladePluginSpecification.groovy:77 * Called only once when annotation processing starts. */ protected abstract void prepare(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) throws ProcessorError, IOException; /** * Can be called multiple times during annotation processing. */ protected abstract void exec(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) throws ProcessorError, IOException; /** * Called only once when annotation processing ends. */ protected abstract void finish(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) throws ProcessorError, IOException; @Override public synchronized void init(ProcessingEnvironment processingEnv) { super.init(processingEnv); mMessager = processingEnv.getMessager(); mFiler = processingEnv.getFiler(); mProcessingEnvironment = processingEnv; mProcessingStarted = false; } @Override public SourceVersion getSupportedSourceVersion() { return SourceVersion.latestSupported(); } @Override public final boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { try { if (!mProcessingStarted) { prepare(annotations, roundEnv); mProcessingStarted = true; } else { return false; // end in 1 round } exec(annotations, roundEnv); finish(annotations, roundEnv); } catch (ProcessorError pe) { error(pe); } catch (IOException e) { throw new RuntimeException(e); } return false; } private void error(ProcessorError error) { mMessager.printMessage(Diagnostic.Kind.ERROR, error.getMessage(), error.getElement()); } private void error(Element e, String msg, Object... args) { mMessager.printMessage(Diagnostic.Kind.ERROR, String.format(msg, args), e); } protected void log(String msg, Object... args) { if (DEBUG) { System.out.println(String.format(msg, args)); } } public ProcessingEnvironment getProcessingEnvironment() { return mProcessingEnvironment; } public Filer getFiler() { return mFiler; } public Messager getMessager() { return mMessager; } }
30.567308
138
0.689525
dfc865a318fbccaf2457cc98261c366535b451a6
2,875
package city.market; import gui.trace.AlertTag; import java.util.*; import java.util.concurrent.Semaphore; import city.PersonAgent; import city.Place; import city.market.MarketCashierRole.*; import city.market.gui.*; import city.market.interfaces.MarketEmployee; import agent.Role; public class MarketEmployeeRole extends Role implements MarketEmployee{ public MarketEmployeeGui gui; public Market market; public List<CustomerOrder> pickUpOrders = new ArrayList<CustomerOrder>(); public List<RestaurantOrder> deliverOrders = new ArrayList<RestaurantOrder>(); enum RoleState{WantToLeave,none} RoleState role_state = RoleState.none; private Semaphore atDestination = new Semaphore(0,true); public MarketEmployeeRole(PersonAgent p, Market m){ super(p); this.market = m; } public void setGui(MarketEmployeeGui g) { gui = g; } public void msgAnimationFinished() { //from animation atDestination.release(); stateChanged(); } public void cmdFinishAndLeave() { role_state = RoleState.WantToLeave; stateChanged(); } public void msgPickOrder(CustomerOrder mc){ print(AlertTag.MARKET, "employee received customer order"); pickUpOrders.add(mc); stateChanged(); } public void msgPickOrder(RestaurantOrder rc){ print(AlertTag.MARKET, "employee received restaurant order"); deliverOrders.add(rc); stateChanged(); } public boolean pickAndExecuteAnAction(){ if(pickUpOrders.size()!=0){ pickUpOrders(pickUpOrders.get(0)); pickUpOrders.remove(0); return true; } if(deliverOrders.size()!=0){ deliverFood(deliverOrders.get(0)); deliverOrders.remove(0); return true; } if (pickUpOrders.size() == 0 && deliverOrders.size() == 0 && role_state == RoleState.WantToLeave && market.getNumberOfCustomers() == 0){ role_state = RoleState.none; active = false; return true; } DoGoHome(); return false; } public void pickUpOrders(CustomerOrder mc){ for (Item item : mc.orderFulfillment) DoPickUp(item.name); DoGoToCashier(); market.MarketCashier.msgHereAreGoods(mc); } public void deliverFood(RestaurantOrder mc){ for (Item item : mc.orderFulfillment){ DoPickUp(item.name); } DoGoToTruck(); market.truck.msgDeliverToCook(mc.orderFulfillment, mc.r); } public void DoPickUp(String item){ gui.PickUp(item); try{ atDestination.acquire(); } catch (InterruptedException e) { e.printStackTrace(); } } public void DoGoToCashier(){ gui.GoToCashier(); try{ atDestination.acquire(); } catch (InterruptedException e) { e.printStackTrace(); } } public void DoGoToTruck(){ gui.GoToTruck(); try{ atDestination.acquire(); } catch (InterruptedException e) { e.printStackTrace(); } } public void DoGoHome(){ gui.GoHome(); } @Override public Place place() { // TODO Auto-generated method stub return market; } }
21.946565
138
0.715826
9957ba5efa8e0ab0b168d1249822c83248c6bb0c
3,309
package org.basex.query.value.seq; import java.util.*; import org.basex.query.*; import org.basex.query.expr.*; import org.basex.query.value.*; import org.basex.query.value.item.*; import org.basex.query.value.type.*; /** * Sequence of items of type {@link Int xs:integer}, containing at least two of them. * * @author BaseX Team 2005-12, BSD License * @author Leo Woerteler */ public final class IntSeq extends NativeSeq { /** Values. */ private final long[] values; /** * Constructor. * @param vals values * @param t type */ private IntSeq(final long[] vals, final Type t) { super(vals.length, t); values = vals; } @Override public Int itemAt(final long pos) { return Int.get(values[(int) pos], type); } @Override public boolean sameAs(final Expr cmp) { if(!(cmp instanceof IntSeq)) return false; final IntSeq is = (IntSeq) cmp; return type == is.type && Arrays.equals(values, is.values); } @Override public Object toJava() throws QueryException { switch((AtomType) type) { case BYT: final byte[] t1 = new byte[(int) size]; for(int s = 0; s < size; s++) t1[s] = (byte) values[s]; return t1; case SHR: case UBY: final short[] t2 = new short[(int) size]; for(int s = 0; s < size; s++) t2[s] = (short) values[s]; return t2; case INT: case USH: final short[] t3 = new short[(int) size]; for(int s = 0; s < size; s++) t3[s] = (short) values[s]; return t3; default: return values; } } @Override public Value sub(final long start, final long length) { final int l = (int) length; final long[] tmp = new long[l]; System.arraycopy(values, (int) start, tmp, 0, l); return get(tmp, type); } @Override public Value reverse() { final int s = values.length; final long[] tmp = new long[s]; for(int l = 0, r = s - 1; l < s; l++, r--) tmp[l] = values[r]; return get(tmp, type); } // STATIC METHODS ===================================================================== /** * Creates a sequence with the specified items. * @param items items * @param type type * @return value */ public static Value get(final long[] items, final Type type) { return items.length == 0 ? Empty.SEQ : items.length == 1 ? Int.get(items[0], type) : new IntSeq(items, type); } /** * Creates a sequence with the items in the specified expressions. * @param vals values * @param size size of resulting sequence * @param type data type * @return value * @throws QueryException query exception */ public static Value get(final Value[] vals, final int size, final Type type) throws QueryException { final long[] tmp = new long[size]; int t = 0; for(final Value val : vals) { // speed up construction, depending on input final int vs = (int) val.size(); if(val instanceof Item) { tmp[t++] = ((Item) val).itr(null); } else if(val instanceof IntSeq) { final IntSeq sq = (IntSeq) val; System.arraycopy(sq.values, 0, tmp, t, vs); t += vs; } else { for(int v = 0; v < vs; v++) tmp[t++] = val.itemAt(v).itr(null); } } return get(tmp, type); } }
26.902439
89
0.578725
849a4727119f9bb9558b1106ea37c755cd2ac2d4
6,749
package Engine; import Data.BackendReader.ReadXML_Die; import Data.BackendReader.ReadXML_luckCard; import Data.BackendReader.ReadXML_player; import Data.BackendReader.ReadXML_tiles; import Engine.BuyableCards.BuyableCardsInterface; import Engine.BuyableCards.PropertyCard; import Engine.Dice.DicePortfolio; import Engine.LuckCards.LuckCardQueue; import Engine.Notifications.Notification; import Engine.Player.PlayerInterface; import Engine.Tile.TileInterface; import Engine.Tile.TilePortfolio; import java.util.ArrayList; import java.util.List; /** * Implements the methods on the Engine Interface. * Mainly responsible for the rules and engine interactions of the game. * @Author: Cemal Yagcioglu */ public class EngineMain implements EngineInterface{ private int currentPlayerIndex = 0; private ArrayList<PlayerInterface> playersList = new ArrayList<PlayerInterface>(); private PlayerInterface currentPlayer; private TilePortfolio allTiles; private DicePortfolio dicePortfolio; private LuckCardQueue luckCardQueue; private TileInterface currentActiveTile; private boolean canRoll = true; private boolean gameIsOver = false; private final int JAIL_FINE = 50; public void initiate(String gameTilesPath, String playersPath,String dicePath, String luckCardsPath, int numberOfPlayers){ playersList = ReadXML_player.ReadXML(numberOfPlayers,playersPath); dicePortfolio = ReadXML_Die.ReadXML(dicePath); luckCardQueue = ReadXML_luckCard.ReadXML(luckCardsPath); allTiles = ReadXML_tiles.ReadXML(gameTilesPath); currentPlayer = playersList.get(0); currentActiveTile = allTiles.getTile(0); } @Override public void rollDice() { if(canRoll) { dicePortfolio.roll(currentPlayer); Notification.rolled(getDiceValue(),currentPlayer.getID()); landOnTheNewPosition(); currentActiveTile = allTiles.getTile(currentPlayer.getCurrentPositionIndex()); if (!dicePortfolio.throwAgain()) { canRoll = false; } } } private void landOnTheNewPosition() { TileInterface landedOnTile = allTiles.getTile(currentPlayer.getCurrentPositionIndex()); BuyableCardsInterface landedOnBuyableCard = landedOnTile.getTheBuyableCard(); if(landedOnBuyableCard!=null){ landedOnBuyableCard.landOn(currentPlayer); } landedOnTile.actThePremise(currentPlayer); checkIfPlayerLost(); } @Override public void buy() { if(!canRoll || dicePortfolio.throwAgain()) { BuyableCardsInterface buyableCard = allTiles.getTile(currentPlayer.getCurrentPositionIndex()).getTheBuyableCard(); if(buyableCard!=null) { buyableCard.buy(currentPlayer); } } } @Override public void sell(PlayerInterface buyer, int priceNegotiated, BuyableCardsInterface cardToBeSold) { cardToBeSold.sellToAnotherPlayer(buyer,priceNegotiated); } @Override public void buyHouse() { if(canRoll && ownerIsTheActiveCurrentPlayer() && isCurrentTilePropertyCard()) { PropertyCard currentPropertyCard = (PropertyCard) currentActiveTile.getTheBuyableCard(); currentPropertyCard.buyHouse(); } } @Override public void sellHouse() { if(ownerIsTheActiveCurrentPlayer() && isCurrentTilePropertyCard()) { PropertyCard currentPropertyCard = (PropertyCard) currentActiveTile.getTheBuyableCard(); currentPropertyCard.sellHouse(); } } @Override public void buyHotel() { if(canRoll && ownerIsTheActiveCurrentPlayer() && isCurrentTilePropertyCard()) { PropertyCard currentPropertyCard = (PropertyCard) currentActiveTile.getTheBuyableCard(); currentPropertyCard.buyHotel(); } } @Override public void sellHotel() { if(ownerIsTheActiveCurrentPlayer() && isCurrentTilePropertyCard()) { PropertyCard currentPropertyCard = (PropertyCard) currentActiveTile.getTheBuyableCard(); currentPropertyCard.sellHotel(); } } @Override public void mortgagePut() { if(ownerIsTheActiveCurrentPlayer()) { BuyableCardsInterface currentBuyableCard = currentActiveTile.getTheBuyableCard(); currentBuyableCard.mortgagePut(); } } @Override public void mortgageLift() { if(canRoll && ownerIsTheActiveCurrentPlayer()) { BuyableCardsInterface currentBuyableCard = currentActiveTile.getTheBuyableCard(); currentBuyableCard.mortgageLift(); } } public boolean isCurrentTileBuyable(){ return currentActiveTile.getTheBuyableCard()!=null; } public void setTurnToNextPlayer(){ if(!canRoll && currentPlayer.getCurrentMoney()>=0) { int totalNumberOfPlayers = playersList.size(); currentPlayerIndex = (currentPlayerIndex + 1) % totalNumberOfPlayers; currentPlayer = playersList.get(currentPlayerIndex); canRoll = true; } } public void clickedOnTheTile(int tileClickedIndex){ int currentClickedTileIndex = tileClickedIndex; currentActiveTile = allTiles.getTile(currentClickedTileIndex); } public PlayerInterface getCurrentPlayer(){ return currentPlayer; } public int getCurrentPlayerId(){ return currentPlayerIndex+1; } public ArrayList<PlayerInterface> getPlayersList() { return playersList; } public TileInterface getCurrentTile(){ return currentActiveTile; } public boolean getCanRoll() { return canRoll;} public List<Integer> getDiceValue(){ return dicePortfolio.getLastDiceValues();} public TileInterface getTileWithIndex(int index){ return allTiles.getTile(index); } private boolean ownerIsTheActiveCurrentPlayer() { if (currentActiveTile.getTheBuyableCard() != null) { return currentPlayer == currentActiveTile.getTheBuyableCard().getOwner(); } return false; } private void checkIfPlayerLost(){ if(currentPlayer.getNetworth()<0){ Notification.playerLost(currentPlayer.getID()); currentPlayer.playerHasLost(); playersList.remove(currentPlayer); if(playersList.size()<=1){ gameIsOver=true; } currentPlayerIndex = (currentPlayerIndex+1)%playersList.size(); currentPlayer = playersList.get(currentPlayerIndex); } } public boolean isGameOver(){ return gameIsOver; } public int getActiveTileIndex(){ for(int i=0; i<allTiles.getSize();i++){ if(allTiles.getTile(i) == currentActiveTile){ return i; } } return -1; } public void payJailFine(){ if(currentPlayer.getJailTerm()!=0) { currentPlayer.setJailTerm(0); currentPlayer.deductMoney(JAIL_FINE); } } private boolean isCurrentTilePropertyCard() { if(currentActiveTile.getTheBuyableCard()!=null) { return currentActiveTile.getTheBuyableCard().getBuyableType() == 1; } return false; } }
30.129464
124
0.734776
99e0c473f9f62d9be5799fee9fa9171a26d96d80
863
package jp.vmi.selenium.selenese.subcommand; import org.openqa.selenium.Alert; import org.openqa.selenium.NoAlertPresentException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jp.vmi.selenium.selenese.Context; /** * "getNativeAlert". */ public class GetNativeAlert extends AbstractSubCommand<String> { private static final Logger log = LoggerFactory.getLogger(GetNativeAlert.class); @Override public String execute(Context context, String... args) { try { Alert alert = context.getWrappedDriver().switchTo().alert(); String result = alert.getText(); context.getNextNativeAlertActionListener().actionPerformed(alert); return result; } catch (NoAlertPresentException e) { log.warn("No alert dialog present."); return ""; } } }
28.766667
84
0.681344
53af15229a97726637abfd4527fe2c6afb0dcbca
2,691
/* * The MIT License (MIT) * * FXGL - JavaFX Game Library * * Copyright (c) 2015-2017 AlmasB (almaslvl@gmail.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.almasb.fxgl.asset; import com.almasb.fxgl.app.FXGL; import com.almasb.fxgl.audio.Sound; import com.almasb.fxgl.scene.CSS; import com.almasb.fxgl.ui.FontFactory; import javafx.scene.image.Image; /** * Stores internal assets, i.e. provided by FXGL. * These can be overridden by "system.properties" file under "/assets/properties/". * * @author Almas Baimagambetov (AlmasB) (almaslvl@gmail.com) */ public final class FXGLAssets { public static final Sound SOUND_NOTIFICATION; public static final Sound SOUND_MENU_SELECT; public static final Sound SOUND_MENU_BACK; public static final Sound SOUND_MENU_PRESS; public static final FontFactory UI_FONT; public static final CSS UI_CSS; public static final String UI_ICON_NAME; public static final Image UI_ICON; private static String getName(String assetKey) { return FXGL.getString(assetKey); } static { AssetLoader loader = FXGL.getAssetLoader(); SOUND_NOTIFICATION = loader.loadSound(getName("sound.notification")); SOUND_MENU_SELECT = loader.loadSound(getName("sound.menu.select")); SOUND_MENU_BACK = loader.loadSound(getName("sound.menu.back")); SOUND_MENU_PRESS = loader.loadSound(getName("sound.menu.press")); UI_FONT = loader.loadFont(getName("ui.font")); UI_CSS = loader.loadCSS(getName("ui.css")); UI_ICON_NAME = getName("ui.icon.name"); UI_ICON = loader.loadAppIcon(UI_ICON_NAME); } }
37.375
83
0.73207
fb3307d32b92e5d96650f4f79191ce2f46b2900c
607
package listeners; import interfaceCalc.CalculatorUI; import logicCalc.MathOperations; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /** * Created by алла on 03.08.15. */ public class CommaActionListener implements ActionListener { public static JTextArea inputOutputText2 = CalculatorUI.inputOutputText2; @Override public void actionPerformed(ActionEvent e) { String text = inputOutputText2.getText(); if (MathOperations.isIntegerNumber(text)) { inputOutputText2.append(e.getActionCommand()); } } }
25.291667
77
0.733114
bb21f913ee0968997a155eb21b03497d43e78742
1,883
/* * Company * Copyright (C) 2014-2020 All Rights Reserved. */ package com.cwenao.leetcode.algs.first; /** * TODO : Statement the class description * * @author cwenao * @version $Id MaxProfitIII.java, v1.0.0 2020-12-15 06:57 cwenao Exp $$ */ public class MaxProfitIII { public int maxProfit(int[] prices) { return maxProfitByDP(prices); } private int maxProfitByDP(int[] prices) { //define: dp[i][K][0] / dp[i][K][1] //i:第N天 //K:最大允许交易次数,这里K最大可以为2 //0,1: 未持有/持有 //base case: -1表示未开始 // dp[i][0][0] = dp[-1][K][0] = 0 // dp[i][0][1] = dp[-1][K][1] = Integer.MIN_VALUE; //======>dp[0][0][0] 表示未开始 //=====> dp[-1][K][0] --------> dp[0][K][0] //=====> dp[-1][K][1] --------> dp[0][K][1] //状态转移方程 //dp[i][K][0] = Math.max(dp[i-1][K][0],dp[i-1][K][1] + price[i]) //dp[i][K][1] = Math.max(dp[i-1][K][1],dp[i-1][K-1][0] - price[i]) //=========> 需要遍历K的状态 int n = prices.length + 1; int maxK = 2; int dp[][][] = new int[n][maxK + 1][2]; for (int i = 0; i < n; i++) { for (int k = maxK; k >= 1; k--) { if (i == 0) { dp[i][0][0] = dp[i][k][0] = 0; dp[i][0][1] = dp[i][k][1] = Integer.MIN_VALUE; continue; } dp[i][k][0] = Math.max(dp[i - 1][k][0], dp[i - 1][k][1] + prices[i-1]); dp[i][k][1] = Math.max(dp[i - 1][k][1], dp[i - 1][k - 1][0] - prices[i-1]); } } return dp[n - 1][maxK][0]; } public static void main(String[] args) { int[] prices = {3, 3, 5, 0, 0, 3, 1, 4}; // int[] prices = {1,2,3,4,5}; MaxProfitIII maxProfitIII = new MaxProfitIII(); System.out.println(maxProfitIII.maxProfit(prices)); } }
29.421875
91
0.433882
521769bf9e4c6fa3c347b93b5d67d93ec311eb87
7,944
/* * Copyright (c) 2008-2017, 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.internal.serialization.impl; import com.hazelcast.internal.serialization.DataSerializerHook; import com.hazelcast.logging.Logger; import com.hazelcast.nio.ClassLoaderUtil; import com.hazelcast.nio.ObjectDataInput; import com.hazelcast.nio.ObjectDataOutput; import com.hazelcast.nio.serialization.DataSerializable; import com.hazelcast.nio.serialization.DataSerializableFactory; import com.hazelcast.nio.serialization.HazelcastSerializationException; import com.hazelcast.nio.serialization.IdentifiedDataSerializable; import com.hazelcast.nio.serialization.StreamSerializer; import com.hazelcast.nio.serialization.TypedDataSerializable; import com.hazelcast.nio.serialization.TypedStreamDeserializer; import com.hazelcast.util.ExceptionUtil; import com.hazelcast.util.ServiceLoader; import com.hazelcast.util.collection.Int2ObjectHashMap; import java.io.IOException; import java.util.Iterator; import java.util.Map; import static com.hazelcast.internal.serialization.impl.SerializationConstants.CONSTANT_TYPE_DATA_SERIALIZABLE; /** * The {@link StreamSerializer} that handles: * <ol> * <li>{@link DataSerializable}</li> * <li>{@link IdentifiedDataSerializable}</li> * </ol> */ @SuppressWarnings("checkstyle:npathcomplexity") final class DataSerializableSerializer implements StreamSerializer<DataSerializable>, TypedStreamDeserializer<DataSerializable> { public static final byte IDS_FLAG = 1 << 0; public static final byte EE_FLAG = 1 << 1; private static final String FACTORY_ID = "com.hazelcast.DataSerializerHook"; private final Int2ObjectHashMap<DataSerializableFactory> factories = new Int2ObjectHashMap<DataSerializableFactory>(); DataSerializableSerializer(Map<Integer, ? extends DataSerializableFactory> dataSerializableFactories, ClassLoader classLoader) { try { final Iterator<DataSerializerHook> hooks = ServiceLoader.iterator(DataSerializerHook.class, FACTORY_ID, classLoader); while (hooks.hasNext()) { DataSerializerHook hook = hooks.next(); final DataSerializableFactory factory = hook.createFactory(); if (factory != null) { register(hook.getFactoryId(), factory); } } } catch (Exception e) { throw ExceptionUtil.rethrow(e); } if (dataSerializableFactories != null) { for (Map.Entry<Integer, ? extends DataSerializableFactory> entry : dataSerializableFactories.entrySet()) { register(entry.getKey(), entry.getValue()); } } } private void register(int factoryId, DataSerializableFactory factory) { final DataSerializableFactory current = factories.get(factoryId); if (current != null) { if (current.equals(factory)) { Logger.getLogger(getClass()).warning("DataSerializableFactory[" + factoryId + "] is already registered! Skipping " + factory); } else { throw new IllegalArgumentException("DataSerializableFactory[" + factoryId + "] is already registered! " + current + " -> " + factory); } } else { factories.put(factoryId, factory); } } @Override public int getTypeId() { return CONSTANT_TYPE_DATA_SERIALIZABLE; } @Override public DataSerializable read(ObjectDataInput in) throws IOException { return readInternal(in, null); } @Override public DataSerializable read(ObjectDataInput in, Class aClass) throws IOException { return readInternal(in, aClass); } private DataSerializable readInternal(ObjectDataInput in, Class aClass) throws IOException { DataSerializable ds = null; if (null != aClass) { try { ds = (DataSerializable) aClass.newInstance(); } catch (Exception e) { throw new HazelcastSerializationException("Requested class " + aClass + " could not be instantiated.", e); } } final byte header = in.readByte(); int id = 0; int factoryId = 0; String className = null; try { // If you ever change the way this is serialized think about to change // BasicOperationService::extractOperationCallId if (isFlagSet(header, IDS_FLAG)) { factoryId = in.readInt(); final DataSerializableFactory dsf = factories.get(factoryId); if (dsf == null) { throw new HazelcastSerializationException("No DataSerializerFactory registered for namespace: " + factoryId); } id = in.readInt(); if (null == aClass) { ds = dsf.create(id); if (ds == null) { throw new HazelcastSerializationException(dsf + " is not be able to create an instance for id: " + id + " on factoryId: " + factoryId); } } } else { className = in.readUTF(); if (null == aClass) { ds = ClassLoaderUtil.newInstance(in.getClassLoader(), className); } } if (isFlagSet(header, EE_FLAG)) { in.readByte(); in.readByte(); } ds.readData(in); return ds; } catch (Exception e) { throw rethrowReadException(id, factoryId, className, e); } } public static boolean isFlagSet(byte value, byte flag) { return (value & flag) != 0; } private IOException rethrowReadException(int id, int factoryId, String className, Exception e) throws IOException { if (e instanceof IOException) { throw (IOException) e; } if (e instanceof HazelcastSerializationException) { throw (HazelcastSerializationException) e; } throw new HazelcastSerializationException("Problem while reading DataSerializable, namespace: " + factoryId + ", id: " + id + ", class: '" + className + "'" + ", exception: " + e.getMessage(), e); } @Override public void write(ObjectDataOutput out, DataSerializable obj) throws IOException { // If you ever change the way this is serialized think about to change // BasicOperationService::extractOperationCallId final boolean identified = obj instanceof IdentifiedDataSerializable; out.writeBoolean(identified); if (identified) { final IdentifiedDataSerializable ds = (IdentifiedDataSerializable) obj; out.writeInt(ds.getFactoryId()); out.writeInt(ds.getId()); } else { if (obj instanceof TypedDataSerializable) { out.writeUTF(((TypedDataSerializable) obj).getClassType().getName()); } else { out.writeUTF(obj.getClass().getName()); } } obj.writeData(out); } @Override public void destroy() { factories.clear(); } }
38.75122
130
0.628273
9b0ffc21dac11e52dbd3e1833c5973e56ba63e31
190
import greenfoot.*; import java.util.*; public class House extends HouseBase implements HouseStrategy { public void getHouseImage(){ this.setImage("houseVisited.png"); } }
21.111111
63
0.705263
b8d957948acbaeb3135f5311eb3b65f411c75305
2,021
import java.util.Scanner; /** * Created by mvieck on 12/26/16. */ public class Validator { public Validator(){ } private void validate(String password) { boolean uppercase = hasUpperCase(password); boolean lowercase = hasLowerCase(password); boolean numbers = hasNumbers(password); boolean special = hasSpecialCharacter(password); boolean spaces = hasBlankSpaces(password); if (uppercase && lowercase && numbers && special && !spaces) { System.out.println("Password valid!"); } else { System.out.println("Password not valid."); } } private boolean hasUpperCase(String password) { return Character.isUpperCase(password.charAt(0)); } private boolean hasLowerCase(String password) { for (int i = 0; i < password.length(); i++) { if (Character.isLowerCase(password.charAt(i))) { return true; } } return false; } private boolean hasNumbers(String password) { for (int i = 0; i < password.length(); i++) { if (Character.isDigit(password.charAt(i))) { return true; } } return false; } private boolean hasSpecialCharacter(String password) { for (int i = 0; i < password.length(); i++) { if (!Character.isAlphabetic(password.charAt(i)) && !Character.isDigit(password.charAt(i))) { return true; } } return false; } private boolean hasBlankSpaces(String password) { return password.contains(" "); } public static void main(String[] args) { System.out.printf("Enter in your password that starts with an uppercase letter & contains one lowercase, one number, one special character, and no blankspaces\n"); Scanner scanner = new Scanner(System.in); Validator validator = new Validator(); validator.validate(scanner.nextLine()); } }
30.621212
171
0.591291
ffd9817366c9fb36e80b709061736442d6cdf86a
2,064
package io.recom.howabout.category.music.fragment; import io.recom.howabout.RoboSherlockFlurryAdlibSpiceFragmentActivity; import io.recom.howabout.category.music.activity.TrackListActivity; import io.recom.howabout.category.music.adapter.TrackListAdapter; import io.recom.howabout.category.music.model.TrackList; import io.recom.howabout.category.music.net.SearchedTracksRequest; import android.os.Bundle; import android.view.View; import android.widget.Toast; import com.octo.android.robospice.persistence.exception.SpiceException; import com.octo.android.robospice.request.listener.RequestListener; public class SearchedTrackListFragment extends TrackListFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle bundle = getArguments(); String searchKeyword = bundle.getString("searchKeyword"); this.tracksRequest = new SearchedTracksRequest(searchKeyword); performRequest(new SearchedTracksRequestListener()); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } private class SearchedTracksRequestListener implements RequestListener<TrackList> { @Override public void onRequestFailure(SpiceException e) { Toast.makeText(getActivity(), "Error during request: " + e.getMessage(), Toast.LENGTH_LONG).show(); progressBar.setVisibility(View.GONE); } @Override public void onRequestSuccess(TrackList trackList) { if (trackList == null) { return; } SearchedTrackListFragment.this.trackList = trackList; trackListAdapter = new TrackListAdapter( (RoboSherlockFlurryAdlibSpiceFragmentActivity) getActivity(), trackList); imagesGridView.setAdapter(trackListAdapter); trackListAdapter.notifyDataSetChanged(); progressBar.setVisibility(View.GONE); } } @Override protected void performRequest(RequestListener<TrackList> requestListener) { ((TrackListActivity) getActivity()).getContentManager().execute( tracksRequest, requestListener); } }
29.485714
76
0.794089
339c321d8948dd9b57d97f19a1d0b0407a02a62c
436
package com.lilithsthrone.world.population; /** * @since 0.3.7.7 * @version 0.3.7.7 * @author Innoxia */ public abstract class AbstractPopulationType { private String name; private String namePlural; public AbstractPopulationType(String name, String namePlural) { this.name = name; this.namePlural = namePlural; } public String getName() { return name; } public String getNamePlural() { return namePlural; } }
16.769231
64
0.715596
95fb93ddc33bd39592ce5ef0d0f88ea572e4bb01
1,310
/* * Copyright 2020 Marco Lombardo * * 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.github.mar9000.graphloader.test.data; import com.github.mar9000.graphloader.batch.AsyncMappedBatchLoader; import com.github.mar9000.graphloader.batch.MappedBatchLoaderContext; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; public class UserAsyncMappedBatchLoader implements AsyncMappedBatchLoader<Long, User> { @Override public CompletableFuture<Map<Long, User>> load(Set<Long> keys, MappedBatchLoaderContext context) { return UserRepository.getAsync(keys) .thenApplyAsync(list -> list.stream() .collect(Collectors.toMap(user -> user.id, user -> user))); } }
38.529412
102
0.745038
2683f81914e87e7367db4c26b5b008c02ea7c5d7
1,401
package org.hl7.davinci.ehrserver.authproxy; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; public class TokenRequest { private String grant_type; private String code; private String redirect_uri; private String client_id; public String getGrant_type() { return grant_type; } public void setGrant_type(String grant_type) { this.grant_type = grant_type; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getRedirect_uri() { return redirect_uri; } public void setRedirect_uri(String redirect_uri) { this.redirect_uri = redirect_uri; } public String getClient_id() { return client_id; } public void setClient_id(String client_id) { this.client_id = client_id; } public MultiValueMap<String, String> urlEncode() { MultiValueMap<String, String> map = new LinkedMultiValueMap<>(); map.add("grant_type", this.grant_type); map.add("code", this.code); map.add("redirect_uri", this.redirect_uri); if (this.client_id != null) { map.add("client_id", this.client_id); } return map; } @Override public String toString() { return "grantType: " + this.grant_type + "\ncode: " + this.code + "\nredirect_uri: " + this.redirect_uri + "\nclient_id: " + this.client_id; } }
22.967213
144
0.69379
e82c7b5e1a8be4dbaa528573ccc442e1f4ab96c3
2,921
/* * Copyright 2015-2015 Hippo B.V. (http://www.onehippo.com) * * 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.onehippo.forge.content.pojo.binder; import java.io.Serializable; import org.onehippo.forge.content.pojo.common.ContentValueConverter; import org.onehippo.forge.content.pojo.model.ContentItem; import org.onehippo.forge.content.pojo.model.ContentNode; import org.onehippo.forge.content.pojo.model.ContentProperty; /** * Content Node Binder interface, binding from a {@link ContentNode} to a physical data node. * * @param <D> physical data node (e.g, {@link javax.jcr.Node}) to which the {@link ContentNode} should bind. * @param <I> content item (e.g, {@link ContentItem}) used when filtering a content item (e.g, {@link ContentItem}). * @param <V> content value used when converting a value of {@link ContentProperty}. */ public interface ContentNodeBinder<D, I, V> extends Serializable { /** * Binds the {@code source} to the {@code dataNode}. * @param dataNode physical data node to bind to. * @param source {@link ContentNode} source to bind from. * @throws ContentNodeBindingException if content node binding exception occurs */ public void bind(D dataNode, ContentNode source) throws ContentNodeBindingException; /** * Binds the {@code source} to the {@code dataNode} with the given {@code itemFilter}. * @param dataNode physical data node to bind to. * @param source {@link ContentNode} source to bind from. * @param itemFilter content item filter * @throws ContentNodeBindingException if content node binding exception occurs */ public void bind(D dataNode, ContentNode source, ContentNodeBindingItemFilter<I> itemFilter) throws ContentNodeBindingException; /** * Binds the {@code source} to the {@code dataNode} with the given {@code itemFilter} and {@code valueConverter}. * @param dataNode physical data node to bind to. * @param source {@link ContentNode} source to bind from. * @param itemFilter content item filter * @param valueConverter value converter * @throws ContentNodeBindingException if content node binding exception occurs */ public void bind(D dataNode, ContentNode source, ContentNodeBindingItemFilter<I> itemFilter, ContentValueConverter<V> valueConverter) throws ContentNodeBindingException; }
45.640625
117
0.727833
5c29fe77acf54aca8229154f0a60485a20c87c88
279
package jjcard.text.game.shop; import jjcard.text.game.IItem; import jjcard.text.game.IMob; import jjcard.text.game.util.Experimental; /** * */ @Experimental public interface Buyer { void buy(IMob seller, IItem item); void buy(IMob seller, IItem item, int amount); }
15.5
47
0.727599
55cc5182f2df130915241017ca330033eff4fa86
563
package cresla.entities.containers.modules; abstract class EnergyModuleImpl extends Modules implements cresla.interfaces.EnergyModule { private int energyOutput; EnergyModuleImpl(int id, int energyOutput) { super(id); this.energyOutput = energyOutput; } @Override public int getEnergyOutput() { return this.energyOutput; } @Override public String toString() { return super.toString() + String.format("Energy Output: %d",this.getEnergyOutput()); } }
25.590909
95
0.634103
68c3df20c9bbe3aeda95bc15b024d9c034022c6e
317
package ftn.ktsnvt.culturalofferings.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import ftn.ktsnvt.culturalofferings.model.Location; @Repository public interface LocationRepository extends JpaRepository<Location, Long>{ }
26.416667
75
0.823344
47d50c11bc1032af1670456e11bd87fe50c01d5a
2,507
package com.albertlardizabal.packoverflow.models; import android.os.Parcel; import android.os.Parcelable; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; /** * Created by albertlardizabal on 2/25/17. */ public class PackingListItem implements Parcelable { @SerializedName("uid") @Expose private String uid; @SerializedName("is_checked") @Expose private boolean isChecked; @SerializedName("title") @Expose private String title; @SerializedName("subtitle") @Expose private String subtitle; @SerializedName("bag_type") @Expose private String bagType; @SerializedName("quantity") @Expose private String quantity; /** * @return The uid */ public String getUid() { return uid; } /** * @param uid The uid */ public void setUid(String uid) { this.uid = uid; } /** * @return The is item checked flag */ public boolean getIsChecked() { return isChecked; } /** * @param isChecked The is item checked flag */ public void setIsChecked(boolean isChecked) { this.isChecked = isChecked; } /** * @return The title */ public String getTitle() { return title; } /** * @param title The title */ public void setTitle(String title) { this.title = title; } /** * @return The subtitle */ public String getSubtitle() { return subtitle; } /** * @param subtitle The subtitle */ public void setSubtitle(String subtitle) { this.subtitle = subtitle; } /** * @return The bagType */ public String getBagType() { return bagType; } /** * @param bagType The bagType */ public void setBagType(String bagType) { this.bagType = bagType; } /** * @return The quantity */ public String getQuantity() { return quantity; } /** * @param quantity The quantity */ public void setQuantity(String quantity) { this.quantity = quantity; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(uid); dest.writeByte((byte) (isChecked ? 1 : 0)); dest.writeString(title); dest.writeString(subtitle); dest.writeString(bagType); dest.writeString(quantity); } public static final Parcelable.Creator<PackingListItem> CREATOR = new Parcelable.Creator<PackingListItem>() { @Override public PackingListItem createFromParcel(Parcel source) { return null; } @Override public PackingListItem[] newArray(int size) { return new PackingListItem[size]; } }; }
17.171233
110
0.688472
ba5f9876b15e7d7ad6c1070f2c217a98cfebe523
11,208
/* * 07/29/2009 * * FocusableTip.java - A focusable tool tip, like those in Eclipse. * * This library is distributed under a modified BSD license. See the included * RSyntaxTextArea.License.txt file for details. */ package org.fife.ui.rsyntaxtextarea.focusabletip; import java.awt.Component; import java.awt.ComponentOrientation; import java.awt.Dimension; import java.awt.Point; import java.awt.Rectangle; import java.awt.Window; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.net.URL; import java.util.ResourceBundle; import javax.swing.JTextArea; import javax.swing.SwingUtilities; import javax.swing.ToolTipManager; import javax.swing.event.CaretEvent; import javax.swing.event.CaretListener; import javax.swing.event.HyperlinkListener; import javax.swing.event.MouseInputAdapter; import org.fife.ui.rsyntaxtextarea.PopupWindowDecorator; /** * A focusable tool tip, similar to those found in Eclipse. The user can click * in the tip and it becomes a "real," resizable window. * * @author Robert Futrell * @version 1.0 */ public class FocusableTip { /** * Listens for events in a text area. */ private class TextAreaListener extends MouseInputAdapter implements CaretListener, ComponentListener, FocusListener, KeyListener { @Override public void caretUpdate(final CaretEvent e) { final Object source = e.getSource(); if (source == FocusableTip.this.textArea) FocusableTip.this.possiblyDisposeOfTipWindow(); } @Override public void componentHidden(final ComponentEvent e) { this.handleComponentEvent(e); } @Override public void componentMoved(final ComponentEvent e) { this.handleComponentEvent(e); } @Override public void componentResized(final ComponentEvent e) { this.handleComponentEvent(e); } @Override public void componentShown(final ComponentEvent e) { this.handleComponentEvent(e); } @Override public void focusGained(final FocusEvent e) { } @Override public void focusLost(final FocusEvent e) { // Only dispose of tip if it wasn't the TipWindow that was clicked // "c" can be null, at least on OS X, so we must check that before // calling SwingUtilities.getWindowAncestor() to guard against an // NPE. final Component c = e.getOppositeComponent(); final boolean tipClicked = c instanceof TipWindow || c != null && SwingUtilities.getWindowAncestor(c) instanceof TipWindow; if (!tipClicked) FocusableTip.this.possiblyDisposeOfTipWindow(); } private void handleComponentEvent(final ComponentEvent e) { FocusableTip.this.possiblyDisposeOfTipWindow(); } public void install(final JTextArea textArea) { textArea.addCaretListener(this); textArea.addComponentListener(this); textArea.addFocusListener(this); textArea.addKeyListener(this); textArea.addMouseListener(this); textArea.addMouseMotionListener(this); } @Override public void keyPressed(final KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ESCAPE) FocusableTip.this.possiblyDisposeOfTipWindow(); else if (e.getKeyCode() == KeyEvent.VK_F2) if (FocusableTip.this.tipWindow != null && !FocusableTip.this.tipWindow.getFocusableWindowState()) { FocusableTip.this.tipWindow.actionPerformed(null); e.consume(); // Don't do bookmarking stuff } } @Override public void keyReleased(final KeyEvent e) { } @Override public void keyTyped(final KeyEvent e) { } @Override public void mouseExited(final MouseEvent e) { // possiblyDisposeOfTipWindow(); } @Override public void mouseMoved(final MouseEvent e) { if (FocusableTip.this.tipVisibleBounds == null || !FocusableTip.this.tipVisibleBounds.contains(e.getPoint())) FocusableTip.this.possiblyDisposeOfTipWindow(); } public void uninstall() { FocusableTip.this.textArea.removeCaretListener(this); FocusableTip.this.textArea.removeComponentListener(this); FocusableTip.this.textArea.removeFocusListener(this); FocusableTip.this.textArea.removeKeyListener(this); FocusableTip.this.textArea.removeMouseListener(this); FocusableTip.this.textArea.removeMouseMotionListener(this); } } private static final ResourceBundle MSG = ResourceBundle .getBundle("org.fife.ui.rsyntaxtextarea.focusabletip.FocusableTip"); /** * Margin from mouse cursor at which to draw focusable tip. */ private static final int X_MARGIN = 18; /** * Margin from mouse cursor at which to draw focusable tip. */ private static final int Y_MARGIN = 12; /** * Returns localized text for the given key. * * @param key * The key into the resource bundle. * @return The localized text. */ static String getString(final String key) { return FocusableTip.MSG.getString(key); } private final HyperlinkListener hyperlinkListener; private URL imageBase; private String lastText; private Dimension maxSize; // null to automatic. private JTextArea textArea; private final TextAreaListener textAreaListener; /** * The screen bounds in which the mouse has to stay for the currently displayed * tip to stay visible. */ private final Rectangle tipVisibleBounds; private TipWindow tipWindow; public FocusableTip(final JTextArea textArea, final HyperlinkListener listener) { this.setTextArea(textArea); this.hyperlinkListener = listener; this.textAreaListener = new TextAreaListener(); this.tipVisibleBounds = new Rectangle(); } /** * Compute the bounds in which the user can move the mouse without the tip * window disappearing. */ private void computeTipVisibleBounds() { // Compute area that the mouse can move in without hiding the // tip window. Note that Java 1.4 can only detect mouse events // in Java windows, not globally. final Rectangle r = this.tipWindow.getBounds(); final Point p = r.getLocation(); SwingUtilities.convertPointFromScreen(p, this.textArea); r.setLocation(p); this.tipVisibleBounds.setBounds(r.x, r.y - 15, r.width, r.height + 15 * 2); } private void createAndShowTipWindow(final MouseEvent e, final String text) { final Window owner = SwingUtilities.getWindowAncestor(this.textArea); this.tipWindow = new TipWindow(owner, this, text); this.tipWindow.setHyperlinkListener(this.hyperlinkListener); // Give apps a chance to decorate us with drop shadows, etc. final PopupWindowDecorator decorator = PopupWindowDecorator.get(); if (decorator != null) decorator.decorate(this.tipWindow); // TODO: Position tip window better (handle RTL, edges of screen, etc.). // Wrap in an invokeLater() to work around a JEditorPane issue where it // doesn't return its proper preferred size until after it is displayed. // See http://forums.sun.com/thread.jspa?forumID=57&threadID=574810 // for a discussion. SwingUtilities.invokeLater(new Runnable() { @Override public void run() { // If a new FocusableTip is requested while another one is // *focused* and visible, the focused tip (i.e. "tipWindow") // will be disposed of. If this Runnable is run after the // dispose(), tipWindow will be null. All of this is done on // the EDT so no synchronization should be necessary. if (FocusableTip.this.tipWindow == null) return; FocusableTip.this.tipWindow.fixSize(); final ComponentOrientation o = FocusableTip.this.textArea.getComponentOrientation(); final Point p = e.getPoint(); SwingUtilities.convertPointToScreen(p, FocusableTip.this.textArea); // Ensure tool tip is in the window bounds. // Multi-monitor support - make sure the completion window (and // description window, if applicable) both fit in the same // window in a multi-monitor environment. To do this, we decide // which monitor the rectangle "p" is in, and use that one. final Rectangle sb = TipUtil.getScreenBoundsForPoint(p.x, p.y); // Dimension ss = tipWindow.getToolkit().getScreenSize(); // Try putting our stuff "below" the mouse first. int y = p.y + FocusableTip.Y_MARGIN; if (y + FocusableTip.this.tipWindow.getHeight() >= sb.y + sb.height) y = p.y - FocusableTip.Y_MARGIN - FocusableTip.this.tipWindow.getHeight(); // Get x-coordinate of completions. Try to align left edge // with the mouse first (with a slight margin). int x = p.x - FocusableTip.X_MARGIN; // ltr if (!o.isLeftToRight()) x = p.x - FocusableTip.this.tipWindow.getWidth() + FocusableTip.X_MARGIN; if (x < sb.x) x = sb.x; else if (x + FocusableTip.this.tipWindow.getWidth() > sb.x + sb.width) x = sb.x + sb.width - FocusableTip.this.tipWindow.getWidth(); FocusableTip.this.tipWindow.setLocation(x, y); FocusableTip.this.tipWindow.setVisible(true); FocusableTip.this.computeTipVisibleBounds(); // Do after tip is visible FocusableTip.this.textAreaListener.install(FocusableTip.this.textArea); FocusableTip.this.lastText = text; } }); } /** * Returns the base URL to use when loading images in this focusable tip. * * @return The base URL to use. * @see #setImageBase(URL) */ public URL getImageBase() { return this.imageBase; } /** * The maximum size for unfocused tool tips. * * @return The maximum size for unfocused tool tips. A value of * <code>null</code> will use a default size. * @see #setMaxSize(Dimension) */ public Dimension getMaxSize() { return this.maxSize; } /** * Disposes of the focusable tip currently displayed, if any. */ public void possiblyDisposeOfTipWindow() { if (this.tipWindow != null) { this.tipWindow.dispose(); this.tipWindow = null; this.textAreaListener.uninstall(); this.tipVisibleBounds.setBounds(-1, -1, 0, 0); this.lastText = null; this.textArea.requestFocus(); } } void removeListeners() { // System.out.println("DEBUG: Removing text area listeners"); this.textAreaListener.uninstall(); } /** * Sets the base URL to use when loading images in this focusable tip. * * @param url * The base URL to use. * @see #getImageBase() */ public void setImageBase(final URL url) { this.imageBase = url; } /** * Sets the maximum size for unfocused tool tips. * * @param maxSize * The new maximum size. A value of <code>null</code> will cause a * default size to be used. * @see #getMaxSize() */ public void setMaxSize(final Dimension maxSize) { this.maxSize = maxSize; } private void setTextArea(final JTextArea textArea) { this.textArea = textArea; // Is okay to do multiple times. ToolTipManager.sharedInstance().registerComponent(textArea); } public void toolTipRequested(final MouseEvent e, final String text) { if (text == null || text.length() == 0) { this.possiblyDisposeOfTipWindow(); this.lastText = text; return; } if (this.lastText == null || text.length() != this.lastText.length() || !text.equals(this.lastText)) { this.possiblyDisposeOfTipWindow(); this.createAndShowTipWindow(e, text); } } }
30.456522
104
0.721271
bdc7bf96756dfffc31c83fc8b935721f5d37f2d7
246
package de.mwvb.blockpuzzle.logic.spielstein; /** Long John */ public class Spielstein5 extends Spielstein { public Spielstein5() { fill(0, 2); fill(1, 2); fill(2, 2); fill(3, 2); fill(4, 2); } }
17.571429
45
0.54065
f7c8acebfadbd292bb76ba4febaa03d8b2725782
1,129
package com.squadb.workassistantapi.web.config.auth; import javax.servlet.http.HttpSession; import org.springframework.core.MethodParameter; import org.springframework.stereotype.Component; import org.springframework.web.bind.support.WebDataBinderFactory; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.method.support.ModelAndViewContainer; import lombok.RequiredArgsConstructor; @RequiredArgsConstructor @Component public class CurrentLoginMemberArgumentResolver implements HandlerMethodArgumentResolver { private final HttpSession httpSession; @Override public boolean supportsParameter(MethodParameter parameter) { return parameter.getParameterAnnotation(CurrentLoginMember.class) != null; } @Override public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) { return httpSession.getAttribute("LOGIN_MEMBER"); } }
36.419355
100
0.807795