file_id
int64
1
180k
content
stringlengths
13
357k
repo
stringlengths
6
109
path
stringlengths
6
1.15k
101
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * 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.iluwatar.memento; import lombok.Getter; import lombok.Setter; /** * Star uses "mementos" to store and restore state. */ public class Star { private StarType type; private int ageYears; private int massTons; /** * Constructor. */ public Star(StarType startType, int startAge, int startMass) { this.type = startType; this.ageYears = startAge; this.massTons = startMass; } /** * Makes time pass for the star. */ public void timePasses() { ageYears *= 2; massTons *= 8; switch (type) { case RED_GIANT -> type = StarType.WHITE_DWARF; case SUN -> type = StarType.RED_GIANT; case SUPERNOVA -> type = StarType.DEAD; case WHITE_DWARF -> type = StarType.SUPERNOVA; case DEAD -> { ageYears *= 2; massTons = 0; } default -> { } } } StarMemento getMemento() { var state = new StarMementoInternal(); state.setAgeYears(ageYears); state.setMassTons(massTons); state.setType(type); return state; } void setMemento(StarMemento memento) { var state = (StarMementoInternal) memento; this.type = state.getType(); this.ageYears = state.getAgeYears(); this.massTons = state.getMassTons(); } @Override public String toString() { return String.format("%s age: %d years mass: %d tons", type.toString(), ageYears, massTons); } /** * StarMemento implementation. */ @Getter @Setter private static class StarMementoInternal implements StarMemento { private StarType type; private int ageYears; private int massTons; } }
iluwatar/java-design-patterns
memento/src/main/java/com/iluwatar/memento/Star.java
102
/* * Copyright (C) 2014 The Guava 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 com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.NullnessCasts.uncheckedCastNullableTToT; import com.google.common.annotations.GwtCompatible; import com.google.common.math.IntMath; import java.math.RoundingMode; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.stream.Stream; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * An accumulator that selects the "top" {@code k} elements added to it, relative to a provided * comparator. "Top" can mean the greatest or the lowest elements, specified in the factory used to * create the {@code TopKSelector} instance. * * <p>If your input data is available as a {@link Stream}, prefer passing {@link * Comparators#least(int)} to {@link Stream#collect(java.util.stream.Collector)}. If it is available * as an {@link Iterable} or {@link Iterator}, prefer {@link Ordering#leastOf(Iterable, int)}. * * <p>This uses the same efficient implementation as {@link Ordering#leastOf(Iterable, int)}, * offering expected O(n + k log k) performance (worst case O(n log k)) for n calls to {@link * #offer} and a call to {@link #topK}, with O(k) memory. In comparison, quickselect has the same * asymptotics but requires O(n) memory, and a {@code PriorityQueue} implementation takes O(n log * k). In benchmarks, this implementation performs at least as well as either implementation, and * degrades more gracefully for worst-case input. * * <p>The implementation does not necessarily use a <i>stable</i> sorting algorithm; when multiple * equivalent elements are added to it, it is undefined which will come first in the output. * * @author Louis Wasserman */ @GwtCompatible @ElementTypesAreNonnullByDefault final class TopKSelector< T extends @Nullable Object> { /** * Returns a {@code TopKSelector} that collects the lowest {@code k} elements added to it, * relative to the natural ordering of the elements, and returns them via {@link #topK} in * ascending order. * * @throws IllegalArgumentException if {@code k < 0} or {@code k > Integer.MAX_VALUE / 2} */ public static <T extends Comparable<? super T>> TopKSelector<T> least(int k) { return least(k, Ordering.natural()); } /** * Returns a {@code TopKSelector} that collects the lowest {@code k} elements added to it, * relative to the specified comparator, and returns them via {@link #topK} in ascending order. * * @throws IllegalArgumentException if {@code k < 0} or {@code k > Integer.MAX_VALUE / 2} */ public static <T extends @Nullable Object> TopKSelector<T> least( int k, Comparator<? super T> comparator) { return new TopKSelector<>(comparator, k); } /** * Returns a {@code TopKSelector} that collects the greatest {@code k} elements added to it, * relative to the natural ordering of the elements, and returns them via {@link #topK} in * descending order. * * @throws IllegalArgumentException if {@code k < 0} or {@code k > Integer.MAX_VALUE / 2} */ public static <T extends Comparable<? super T>> TopKSelector<T> greatest(int k) { return greatest(k, Ordering.natural()); } /** * Returns a {@code TopKSelector} that collects the greatest {@code k} elements added to it, * relative to the specified comparator, and returns them via {@link #topK} in descending order. * * @throws IllegalArgumentException if {@code k < 0} or {@code k > Integer.MAX_VALUE / 2} */ public static <T extends @Nullable Object> TopKSelector<T> greatest( int k, Comparator<? super T> comparator) { return new TopKSelector<>(Ordering.from(comparator).reverse(), k); } private final int k; private final Comparator<? super T> comparator; /* * We are currently considering the elements in buffer in the range [0, bufferSize) as candidates * for the top k elements. Whenever the buffer is filled, we quickselect the top k elements to the * range [0, k) and ignore the remaining elements. */ private final @Nullable T[] buffer; private int bufferSize; /** * The largest of the lowest k elements we've seen so far relative to this comparator. If * bufferSize ≥ k, then we can ignore any elements greater than this value. */ @CheckForNull private T threshold; @SuppressWarnings("unchecked") // TODO(cpovirk): Consider storing Object[] instead of T[]. private TopKSelector(Comparator<? super T> comparator, int k) { this.comparator = checkNotNull(comparator, "comparator"); this.k = k; checkArgument(k >= 0, "k (%s) must be >= 0", k); checkArgument(k <= Integer.MAX_VALUE / 2, "k (%s) must be <= Integer.MAX_VALUE / 2", k); this.buffer = (T[]) new Object[IntMath.checkedMultiply(k, 2)]; this.bufferSize = 0; this.threshold = null; } /** * Adds {@code elem} as a candidate for the top {@code k} elements. This operation takes amortized * O(1) time. */ public void offer(@ParametricNullness T elem) { if (k == 0) { return; } else if (bufferSize == 0) { buffer[0] = elem; threshold = elem; bufferSize = 1; } else if (bufferSize < k) { buffer[bufferSize++] = elem; // uncheckedCastNullableTToT is safe because bufferSize > 0. if (comparator.compare(elem, uncheckedCastNullableTToT(threshold)) > 0) { threshold = elem; } // uncheckedCastNullableTToT is safe because bufferSize > 0. } else if (comparator.compare(elem, uncheckedCastNullableTToT(threshold)) < 0) { // Otherwise, we can ignore elem; we've seen k better elements. buffer[bufferSize++] = elem; if (bufferSize == 2 * k) { trim(); } } } /** * Quickselects the top k elements from the 2k elements in the buffer. O(k) expected time, O(k log * k) worst case. */ @SuppressWarnings("nullness") // TODO: b/316358623 - Remove after checker fix. private void trim() { int left = 0; int right = 2 * k - 1; int minThresholdPosition = 0; // The leftmost position at which the greatest of the k lower elements // -- the new value of threshold -- might be found. int iterations = 0; int maxIterations = IntMath.log2(right - left, RoundingMode.CEILING) * 3; while (left < right) { int pivotIndex = (left + right + 1) >>> 1; int pivotNewIndex = partition(left, right, pivotIndex); if (pivotNewIndex > k) { right = pivotNewIndex - 1; } else if (pivotNewIndex < k) { left = Math.max(pivotNewIndex, left + 1); minThresholdPosition = pivotNewIndex; } else { break; } iterations++; if (iterations >= maxIterations) { @SuppressWarnings("nullness") // safe because we pass sort() a range that contains real Ts T[] castBuffer = (T[]) buffer; // We've already taken O(k log k), let's make sure we don't take longer than O(k log k). Arrays.sort(castBuffer, left, right + 1, comparator); break; } } bufferSize = k; threshold = uncheckedCastNullableTToT(buffer[minThresholdPosition]); for (int i = minThresholdPosition + 1; i < k; i++) { if (comparator.compare( uncheckedCastNullableTToT(buffer[i]), uncheckedCastNullableTToT(threshold)) > 0) { threshold = buffer[i]; } } } /** * Partitions the contents of buffer in the range [left, right] around the pivot element * previously stored in buffer[pivotValue]. Returns the new index of the pivot element, * pivotNewIndex, so that everything in [left, pivotNewIndex] is ≤ pivotValue and everything in * (pivotNewIndex, right] is greater than pivotValue. */ private int partition(int left, int right, int pivotIndex) { T pivotValue = uncheckedCastNullableTToT(buffer[pivotIndex]); buffer[pivotIndex] = buffer[right]; int pivotNewIndex = left; for (int i = left; i < right; i++) { if (comparator.compare(uncheckedCastNullableTToT(buffer[i]), pivotValue) < 0) { swap(pivotNewIndex, i); pivotNewIndex++; } } buffer[right] = buffer[pivotNewIndex]; buffer[pivotNewIndex] = pivotValue; return pivotNewIndex; } private void swap(int i, int j) { T tmp = buffer[i]; buffer[i] = buffer[j]; buffer[j] = tmp; } TopKSelector<T> combine(TopKSelector<T> other) { for (int i = 0; i < other.bufferSize; i++) { this.offer(uncheckedCastNullableTToT(other.buffer[i])); } return this; } /** * Adds each member of {@code elements} as a candidate for the top {@code k} elements. This * operation takes amortized linear time in the length of {@code elements}. * * <p>If all input data to this {@code TopKSelector} is in a single {@code Iterable}, prefer * {@link Ordering#leastOf(Iterable, int)}, which provides a simpler API for that use case. */ public void offerAll(Iterable<? extends T> elements) { offerAll(elements.iterator()); } /** * Adds each member of {@code elements} as a candidate for the top {@code k} elements. This * operation takes amortized linear time in the length of {@code elements}. The iterator is * consumed after this operation completes. * * <p>If all input data to this {@code TopKSelector} is in a single {@code Iterator}, prefer * {@link Ordering#leastOf(Iterator, int)}, which provides a simpler API for that use case. */ public void offerAll(Iterator<? extends T> elements) { while (elements.hasNext()) { offer(elements.next()); } } /** * Returns the top {@code k} elements offered to this {@code TopKSelector}, or all elements if * fewer than {@code k} have been offered, in the order specified by the factory used to create * this {@code TopKSelector}. * * <p>The returned list is an unmodifiable copy and will not be affected by further changes to * this {@code TopKSelector}. This method returns in O(k log k) time. */ @SuppressWarnings("nullness") // TODO: b/316358623 - Remove after checker fix. public List<T> topK() { @SuppressWarnings("nullness") // safe because we pass sort() a range that contains real Ts T[] castBuffer = (T[]) buffer; Arrays.sort(castBuffer, 0, bufferSize, comparator); if (bufferSize > k) { Arrays.fill(buffer, k, buffer.length, null); bufferSize = k; threshold = buffer[k - 1]; } // Up to bufferSize, all elements of buffer are real Ts (not null unless T includes null) T[] topK = Arrays.copyOf(castBuffer, bufferSize); // we have to support null elements, so no ImmutableList for us return Collections.unmodifiableList(Arrays.asList(topK)); } }
google/guava
guava/src/com/google/common/collect/TopKSelector.java
103
package com.thealgorithms.others; import java.util.Scanner; final class TowerOfHanoi { private TowerOfHanoi() { } public static void shift(int n, String startPole, String intermediatePole, String endPole) { // if n becomes zero the program returns thus ending the loop. if (n != 0) { // Shift function is called in recursion for swapping the n-1 disc from the startPole to // the intermediatePole shift(n - 1, startPole, endPole, intermediatePole); System.out.format("Move %d from %s to %s%n", n, startPole, endPole); // Result Printing // Shift function is called in recursion for swapping the n-1 disc from the // intermediatePole to the endPole shift(n - 1, intermediatePole, startPole, endPole); } } public static void main(String[] args) { System.out.print("Enter number of discs on Pole 1: "); Scanner scanner = new Scanner(System.in); int numberOfDiscs = scanner.nextInt(); // input of number of discs on pole 1 shift(numberOfDiscs, "Pole1", "Pole2", "Pole3"); // Shift function called scanner.close(); } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/others/TowerOfHanoi.java
104
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.tasks; import org.elasticsearch.action.ActionResponse; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.common.io.stream.NamedWriteable; import org.elasticsearch.telemetry.tracing.Traceable; import org.elasticsearch.xcontent.ToXContent; import org.elasticsearch.xcontent.ToXContentObject; import java.io.IOException; import java.util.Map; import java.util.Set; /** * Current task information */ public class Task implements Traceable { /** * The request header to mark tasks with specific ids */ public static final String X_OPAQUE_ID_HTTP_HEADER = "X-Opaque-Id"; /** * The request header which is contained in HTTP request. We parse trace.id from it and store it in thread context. * TRACE_PARENT once parsed in RestController.tryAllHandler is not preserved * has to be declared as a header copied over from http request. * May also be used internally when APM is enabled. */ public static final String TRACE_PARENT_HTTP_HEADER = "traceparent"; /** * A request header that indicates the origin of the request from Elastic stack. The value will stored in ThreadContext * and emitted to ES logs */ public static final String X_ELASTIC_PRODUCT_ORIGIN_HTTP_HEADER = "X-elastic-product-origin"; public static final String TRACE_STATE = "tracestate"; /** * Used internally to pass the apm trace context between the nodes */ public static final String APM_TRACE_CONTEXT = "apm.local.context"; /** * Parsed part of traceparent. It is stored in thread context and emitted in logs. * Has to be declared as a header copied over for tasks. */ public static final String TRACE_ID = "trace.id"; public static final String TRACE_START_TIME = "trace.starttime"; public static final String TRACE_PARENT = "traceparent"; public static final Set<String> HEADERS_TO_COPY = Set.of( X_OPAQUE_ID_HTTP_HEADER, TRACE_PARENT_HTTP_HEADER, TRACE_ID, X_ELASTIC_PRODUCT_ORIGIN_HTTP_HEADER ); private final long id; private final String type; private final String action; private final String description; private final TaskId parentTask; private final Map<String, String> headers; /** * The task's start time as a wall clock time since epoch ({@link System#currentTimeMillis()} style). */ private final long startTime; /** * The task's start time as a relative time ({@link System#nanoTime()} style). */ private final long startTimeNanos; public Task(long id, String type, String action, String description, TaskId parentTask, Map<String, String> headers) { this(id, type, action, description, parentTask, System.currentTimeMillis(), System.nanoTime(), headers); } public Task( long id, String type, String action, String description, TaskId parentTask, long startTime, long startTimeNanos, Map<String, String> headers ) { this.id = id; this.type = type; this.action = action; this.description = description; this.parentTask = parentTask; this.startTime = startTime; this.startTimeNanos = startTimeNanos; this.headers = headers; } /** * Build a version of the task status you can throw over the wire and back * to the user. * * @param localNodeId * the id of the node this task is running on * @param detailed * should the information include detailed, potentially slow to * generate data? */ public final TaskInfo taskInfo(String localNodeId, boolean detailed) { String description = null; Task.Status status = null; if (detailed) { description = getDescription(); status = getStatus(); } return taskInfo(localNodeId, description, status); } /** * Build a proper {@link TaskInfo} for this task. */ protected final TaskInfo taskInfo(String localNodeId, String description, Status status) { return new TaskInfo( new TaskId(localNodeId, getId()), getType(), localNodeId, getAction(), description, status, startTime, System.nanoTime() - startTimeNanos, this instanceof CancellableTask, this instanceof CancellableTask && ((CancellableTask) this).isCancelled(), parentTask, headers ); } /** * Returns task id */ public long getId() { return id; } /** * Returns task channel type (netty, transport, direct) */ public String getType() { return type; } /** * Returns task action */ public String getAction() { return action; } /** * Generates task description */ public String getDescription() { return description; } /** * Returns the task's start time as a wall clock time since epoch ({@link System#currentTimeMillis()} style). */ public long getStartTime() { return startTime; } /** * Returns the task's start time in nanoseconds ({@link System#nanoTime()} style). */ public long getStartTimeNanos() { return startTimeNanos; } /** * Returns id of the parent task or NO_PARENT_ID if the task doesn't have any parent tasks */ public TaskId getParentTaskId() { return parentTask; } /** * Build a status for this task or null if this task doesn't have status. * Since most tasks don't have status this defaults to returning null. While * this can never perform IO it might be a costly operation, requiring * collating lists of results, etc. So only use it if you need the value. */ public Status getStatus() { return null; } @Override public String toString() { return "Task{id=" + id + ", type='" + type + "', action='" + action + "', description='" + description + "', parentTask=" + parentTask + ", startTime=" + startTime + ", startTimeNanos=" + startTimeNanos + '}'; } /** * Report of the internal status of a task. These can vary wildly from task * to task because each task is implemented differently but we should try * to keep each task consistent from version to version where possible. * That means each implementation of {@linkplain Task.Status#toXContent} * should avoid making backwards incompatible changes to the rendered * result. But if we change the way a request is implemented it might not * be possible to preserve backwards compatibility. In that case, we * <b>can</b> change this on version upgrade but we should be careful * because some statuses (reindex) have become defacto standardized because * they are used by systems like Kibana. */ public interface Status extends ToXContentObject, NamedWriteable {} /** * Returns stored task header associated with the task */ public String getHeader(String header) { return headers.get(header); } public Map<String, String> headers() { return headers; } public TaskResult result(DiscoveryNode node, Exception error) throws IOException { return new TaskResult(taskInfo(node.getId(), true), error); } public TaskResult result(DiscoveryNode node, ActionResponse response) throws IOException { if (response instanceof ToXContent) { return new TaskResult(taskInfo(node.getId(), true), (ToXContent) response); } else { throw new IllegalStateException("response has to implement ToXContent to be able to store the results"); } } @Override public String getSpanId() { return "task-" + getId(); } }
elastic/elasticsearch
server/src/main/java/org/elasticsearch/tasks/Task.java
105
import java.io.*; import java.util.*; /************************************************************************************************************************************** * Class Example *****/ class Example implements Debuggable { int domain_id; double current_boosting_weight; // loss = @TemperedLoss => tempered weight // loss = @LogLoss => unnormalized boosting weight Vector typed_features; // features with type, excluding class double initial_class; double unnormalized_class; double normalized_class; double noisy_normalized_class; // class, only for training and in the context of LS model public void affiche() { System.out.println(this); } public String toString() { String v = ""; int i; v += domain_id + " typed features : "; for (i = 0; i < typed_features.size(); i++) v += typed_features.elementAt(i) + " "; v += " -> " + normalized_class + "(" + noisy_normalized_class + "), w = " + current_boosting_weight; return v; } static Vector TO_TYPED_FEATURES(Vector ev, int index_class, Vector fv) { Vector vv = new Vector(); int i; Feature f; for (i = 0; i < fv.size(); i++) { if (i != index_class) { f = (Feature) fv.elementAt(i); if (f.type.equals(Feature.CONTINUOUS)) vv.addElement(new Double(Double.parseDouble((String) ev.elementAt(i)))); else if (f.type.equals(Feature.NOMINAL)) vv.addElement(new String((String) ev.elementAt(i))); } } return vv; } static double VAL_CLASS(Vector ev, int index_class) { return Double.parseDouble(((String) ev.elementAt(index_class))); } Example(int id, Vector v, int index_class, Vector fv) { domain_id = id; typed_features = Example.TO_TYPED_FEATURES(v, index_class, fv); initial_class = Example.VAL_CLASS(v, index_class); unnormalized_class = initial_class; current_boosting_weight = -1.0; } public int checkFeatures(Vector fv, int index_class) { // check that the example has features in the domain, otherwise errs int i, index = 0, vret = 0; Feature f; String fn; double fd; for (i = 0; i < fv.size(); i++) { if (i != index_class) { f = (Feature) fv.elementAt(i); if (f.type.equals(Feature.NOMINAL)) { fn = (String) typed_features.elementAt(index); if (!f.has_in_range(fn)) { Dataset.warning( "Example.class :: nominal attribute value " + fn + " not in range " + f.range() + " for feature " + f.name); vret++; } } index++; } } return vret; } public void complete_normalized_class( double translate_v, double min_v, double max_v, double eta) { // TO Expand for more choices if (max_v != min_v) { if ((Dataset.DEFAULT_INDEX_FIT_CLASS != 0) && (Dataset.DEFAULT_INDEX_FIT_CLASS != 3) && (Dataset.DEFAULT_INDEX_FIT_CLASS != 4)) Dataset.perror( "Example.class :: Choice " + Dataset.DEFAULT_INDEX_FIT_CLASS + " not implemented to fit the class"); normalized_class = Dataset.TRANSLATE_SHRINK( unnormalized_class, translate_v, min_v, max_v, Feature.MAX_CLASS_MAGNITUDE); if (Dataset.DEFAULT_INDEX_FIT_CLASS == 4) normalized_class = Math.signum(normalized_class); unnormalized_class = 0.0; } else normalized_class = max_v; noisy_normalized_class = normalized_class; if (Utils.R.nextDouble() < eta) noisy_normalized_class = -noisy_normalized_class; } public boolean is_positive_noisy() { if (noisy_normalized_class == 0.0) Dataset.perror("Example.class :: normalized class is zero"); if (noisy_normalized_class < 0.0) return false; return true; } }
google-research/google-research
tempered_boosting/Example.java
106
/* Copyright 2016 The TensorFlow Authors. 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 org.tensorflow; import java.util.Iterator; /** * A data flow graph representing a TensorFlow computation. * * <p>Instances of a Graph are thread-safe. * * <p><b>WARNING:</b> Resources consumed by the Graph object must be explicitly freed by invoking * the {@link #close()} method then the Graph object is no longer needed. */ public final class Graph implements ExecutionEnvironment, AutoCloseable { /** Create an empty Graph. */ public Graph() { nativeHandle = allocate(); } /** Create a Graph from an existing handle (takes ownership). */ Graph(long nativeHandle) { this.nativeHandle = nativeHandle; } /** * Release resources associated with the Graph. * * <p>Blocks until there are no active {@link Session} instances referring to this Graph. A Graph * is not usable after close returns. */ @Override public void close() { synchronized (nativeHandleLock) { if (nativeHandle == 0) { return; } while (refcount > 0) { try { nativeHandleLock.wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // Possible leak of the graph in this case? return; } } delete(nativeHandle); nativeHandle = 0; } } /** * Returns the operation (node in the Graph) with the provided name. * * <p>Or {@code null} if no such operation exists in the Graph. */ public GraphOperation operation(String name) { synchronized (nativeHandleLock) { long oph = operation(nativeHandle, name); if (oph == 0) { return null; } return new GraphOperation(this, oph); } } /** * Iterator over all the {@link Operation}s in the graph. * * <p>The order of iteration is unspecified. Consumers of the iterator will receive no * notification should the underlying graph change during iteration. */ public Iterator<Operation> operations() { return new OperationIterator(this); } /** * Returns a builder to add {@link Operation}s to the Graph. * * @param type of the Operation (i.e., identifies the computation to be performed) * @param name to refer to the created Operation in the graph. * @return an {@link OperationBuilder}, which will add the Operation to the graph when {@link * OperationBuilder#build()} is invoked. If {@link OperationBuilder#build()} is not invoked, * then some resources may leak. */ @Override public GraphOperationBuilder opBuilder(String type, String name) { return new GraphOperationBuilder(this, type, name); } /** * Import a serialized representation of a TensorFlow graph. * * <p>The serialized representation of the graph, often referred to as a <i>GraphDef</i>, can be * generated by {@link #toGraphDef()} and equivalents in other language APIs. * * @throws IllegalArgumentException if graphDef is not a recognized serialization of a graph. * @see #importGraphDef(byte[], String) */ public void importGraphDef(byte[] graphDef) throws IllegalArgumentException { importGraphDef(graphDef, ""); } /** * Import a serialized representation of a TensorFlow graph. * * @param graphDef the serialized representation of a TensorFlow graph. * @param prefix a prefix that will be prepended to names in graphDef * @throws IllegalArgumentException if graphDef is not a recognized serialization of a graph. * @see #importGraphDef(byte[]) */ public void importGraphDef(byte[] graphDef, String prefix) throws IllegalArgumentException { if (graphDef == null || prefix == null) { throw new IllegalArgumentException("graphDef and prefix cannot be null"); } synchronized (nativeHandleLock) { importGraphDef(nativeHandle, graphDef, prefix); } } /** * Generate a serialized representation of the Graph. * * @see #importGraphDef(byte[]) * @see #importGraphDef(byte[], String) */ public byte[] toGraphDef() { synchronized (nativeHandleLock) { return toGraphDef(nativeHandle); } } /** * Adds operations to compute the partial derivatives of sum of {@code y}s w.r.t {@code x}s, i.e., * {@code d(y_1 + y_2 + ...)/dx_1, d(y_1 + y_2 + ...)/dx_2...} * * <p>{@code dx} are used as initial gradients (which represent the symbolic partial derivatives * of some loss function {@code L} w.r.t. {@code y}). {@code dx} must be null or have size of * {@code y}. * * <p>If {@code dx} is null, the implementation will use dx of {@link * org.tensorflow.op.core.OnesLike OnesLike} for all shapes in {@code y}. * * <p>{@code prefix} is used as the name prefix applied to all nodes added to the graph to compute * gradients. It must be unique within the provided graph or the operation will fail. * * <p>If {@code prefix} is null, then one will be chosen automatically. * * @param prefix unique string prefix applied before the names of nodes added to the graph to * compute gradients. If null, a default one will be chosen. * @param y output of the function to derive * @param x inputs of the function for which partial derivatives are computed * @param dx if not null, the partial derivatives of some loss function {@code L} w.r.t. {@code y} * @return the partial derivatives {@code dy} with the size of {@code x} */ public Output<?>[] addGradients(String prefix, Output<?>[] y, Output<?>[] x, Output<?>[] dx) { Output<?>[] dy = new Output<?>[x.length]; final long[] yHandles = new long[y.length]; final int[] yIndices = new int[y.length]; final long[] xHandles = new long[x.length]; final int[] xIndices = new int[x.length]; long[] dxHandles = null; int[] dxIndices = null; try (Reference ref = ref()) { for (int i = 0; i < y.length; ++i) { yHandles[i] = y[i].getUnsafeNativeHandle(); yIndices[i] = y[i].index(); } for (int i = 0; i < x.length; ++i) { xHandles[i] = x[i].getUnsafeNativeHandle(); xIndices[i] = x[i].index(); } if (dx != null && dx.length > 0) { dxHandles = new long[dx.length]; dxIndices = new int[dx.length]; for (int i = 0; i < dx.length; ++i) { dxHandles[i] = dx[i].getUnsafeNativeHandle(); dxIndices[i] = dx[i].index(); } } // Gradient outputs are returned in two continuous arrays concatenated into one. The first // holds the native handles of the gradient operations while the second holds the index of // their output e.g. given // xHandles = [x0Handle, x1Handle, ...] and xIndices = [x0Index, x1Index, ..], we obtain // dy = [dy0Handle, dy1Handle, ..., dy0Index, dy1Index, ...] long[] dyHandlesAndIndices = addGradients( ref.nativeHandle(), prefix, yHandles, yIndices, xHandles, xIndices, dxHandles, dxIndices); int ndy = dyHandlesAndIndices.length >> 1; if (ndy != dy.length) { throw new IllegalStateException(String.valueOf(ndy) + " gradients were added to the graph when " + dy.length + " were expected"); } for (int i = 0, j = ndy; i < ndy; ++i, ++j) { GraphOperation op = new GraphOperation(this, dyHandlesAndIndices[i]); dy[i] = new Output<>(op, (int) dyHandlesAndIndices[j]); } } return dy; } /** * Adds operations to compute the partial derivatives of sum of {@code y}s w.r.t {@code x}s, * i.e., {@code dy/dx_1, dy/dx_2...} * <p> * This is a simplified version of {@link #addGradients(String, Output[], Output[], Output[])} * where {@code y} is a single output, {@code dx} is null and {@code prefix} is null. * * @param y output of the function to derive * @param x inputs of the function for which partial derivatives are computed * @return the partial derivatives {@code dy} with the size of {@code x} */ public Output<?>[] addGradients(Output<?> y, Output<?>[] x) { return addGradients(null, new Output<?>[] {y}, x, null); } /** * Used to instantiate an abstract class which overrides the buildSubgraph method to build a * conditional or body subgraph for a while loop. After Java 8, this can alternatively be used to * create a lambda for the same purpose. * * <p>To be used when calling {@link #whileLoop(Output[], * org.tensorflow.Graph.WhileSubgraphBuilder, org.tensorflow.Graph.WhileSubgraphBuilder, String)} * * <p>Example usage (prior to Java 8): * * <p>{@code WhileSubgraphBuilder bodyGraphBuilder = new WhileSubgraphBuilder() { @Override public * void buildSubgraph(Graph bodyGraph, Output<?>[] bodyInputs, Output<?>[] bodyOutputs) { // build * body subgraph } }; } * * <p>Example usage (after Java 8): * * <p>{@code WhileSubgraphBuilder bodyGraphBuilder = (bodyGraph, bodyInputs, bodyOutputs) -> { // * build body subgraph };} */ public interface WhileSubgraphBuilder { /** * To be overridden by user with code to build conditional or body subgraph for a while loop * * @param g the subgraph * @param inputs subgraph inputs * @param outputs subgraph outputs */ public void buildSubgraph(Graph g, Output<?>[] inputs, Output<?>[] outputs); } // called by while loop code in graph_jni.cc to construct conditional/body subgraphs private static long[] buildSubgraph( WhileSubgraphBuilder subgraphBuilder, long subgraphHandle, long[] inputHandles, int[] inputIndices, long[] outputHandles, int[] outputIndices) { Graph subgraph = new Graph(subgraphHandle); int ninputs = inputHandles.length; int noutputs = outputHandles.length; Output<?>[] inputs = new Output<?>[ninputs]; Output<?>[] outputs = new Output<?>[noutputs]; long[] outputHandlesAndIndices = new long[noutputs * 2]; synchronized (subgraph.nativeHandleLock) { try (Reference ref = subgraph.ref()) { for (int i = 0; i < ninputs; i++) { Operation op = new GraphOperation(subgraph, inputHandles[i]); inputs[i] = op.output(inputIndices[i]); } for (int i = 0; i < noutputs; i++) { Operation op = new GraphOperation(subgraph, outputHandles[i]); outputs[i] = op.output(outputIndices[i]); } subgraphBuilder.buildSubgraph(subgraph, inputs, outputs); for (int i = 0, j = noutputs; i < noutputs; i++, j++) { outputHandlesAndIndices[i] = outputs[i].getUnsafeNativeHandle(); outputHandlesAndIndices[j] = (long) outputs[i].index(); } } return outputHandlesAndIndices; } } /** * Builds a while loop. * * @param inputs the loop inputs * @param cgBuilder WhileSubgraphBuilder to build the conditional subgraph * @param bgBuilder WhileSubgraphBuilder to build the body subgraph * @param name name for the loop * @return list of loop outputs, of the same length as {@code inputs} */ public Output<?>[] whileLoop( Output<?>[] inputs, WhileSubgraphBuilder cgBuilder, WhileSubgraphBuilder bgBuilder, String name) { int ninputs = inputs.length; long[] inputHandles = new long[ninputs]; int[] inputIndices = new int[ninputs]; Output<?>[] outputs = new Output<?>[ninputs]; synchronized (nativeHandleLock) { try (Reference ref = ref()) { for (int i = 0; i < ninputs; i++) { inputHandles[i] = inputs[i].getUnsafeNativeHandle(); inputIndices[i] = inputs[i].index(); } long[] outputHandlesAndIndices = whileLoop(nativeHandle, inputHandles, inputIndices, name, cgBuilder, bgBuilder); for (int i = 0, j = ninputs; i < ninputs; ++i, ++j) { Operation op = new GraphOperation(this, outputHandlesAndIndices[i]); outputs[i] = op.output((int) outputHandlesAndIndices[j]); } } return outputs; } } private final Object nativeHandleLock = new Object(); private long nativeHandle; private int refcount = 0; // Related native objects (such as the TF_Operation object backing an Operation instance) // have a validity tied to that of the Graph. The handles to those native objects are not // valid after Graph.close() has been invoked. // // Instances of the Reference class should be used to ensure the Graph has not been closed // while dependent handles are in use. class Reference implements AutoCloseable { private Reference() { synchronized (Graph.this.nativeHandleLock) { active = Graph.this.nativeHandle != 0; if (!active) { throw new IllegalStateException("close() has been called on the Graph"); } active = true; Graph.this.refcount++; } } @Override public void close() { synchronized (Graph.this.nativeHandleLock) { if (!active) { return; } active = false; if (--Graph.this.refcount == 0) { Graph.this.nativeHandleLock.notifyAll(); } } } public long nativeHandle() { synchronized (Graph.this.nativeHandleLock) { return active ? Graph.this.nativeHandle : 0; } } private boolean active; } Reference ref() { return new Reference(); } private static final class OperationIterator implements Iterator<Operation> { OperationIterator(Graph g) { this.graph = g; this.operation = null; this.position = 0; this.advance(); } private final void advance() { Graph.Reference reference = this.graph.ref(); this.operation = null; try { long[] nativeReturn = nextOperation(reference.nativeHandle(), this.position); if ((nativeReturn != null) && (nativeReturn[0] != 0)) { this.operation = new GraphOperation(this.graph, nativeReturn[0]); this.position = (int) nativeReturn[1]; } } finally { reference.close(); } } @Override public boolean hasNext() { return (this.operation != null); } @Override public Operation next() { Operation rhett = this.operation; this.advance(); return rhett; } @Override public void remove() { throw new UnsupportedOperationException("remove() is unsupported."); } private final Graph graph; private Operation operation; private int position; } private static native long allocate(); private static native void delete(long handle); private static native long operation(long handle, String name); // This method returns the Operation native handle at index 0 and the new value for pos at index 1 // (see TF_GraphNextOperation) private static native long[] nextOperation(long handle, int position); private static native void importGraphDef(long handle, byte[] graphDef, String prefix) throws IllegalArgumentException; private static native byte[] toGraphDef(long handle); private static native long[] addGradients( long handle, String prefix, long[] inputHandles, int[] inputIndices, long[] outputHandles, int[] outputIndices, long[] gradInputHandles, int[] gradInputIndices); private static native long[] whileLoop( long handle, long[] inputHandles, int[] inputIndices, String name, WhileSubgraphBuilder condGraphBuilder, WhileSubgraphBuilder bodyGraphBuilder); static { TensorFlow.init(); } }
tensorflow/tensorflow
tensorflow/java/src/main/java/org/tensorflow/Graph.java
107
package org.opencv.highgui; import org.opencv.core.Mat; import javax.swing.*; import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.image.BufferedImage; import java.awt.image.DataBufferByte; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /** * This class was designed for use in Java applications * to recreate the OpenCV HighGui functionalities. */ public final class HighGui { // Constants for namedWindow public final static int WINDOW_NORMAL = ImageWindow.WINDOW_NORMAL; public final static int WINDOW_AUTOSIZE = ImageWindow.WINDOW_AUTOSIZE; // Control Variables public static int n_closed_windows = 0; public static int pressedKey = -1; public static CountDownLatch latch = new CountDownLatch(1); // Windows Map public static Map<String, ImageWindow> windows = new HashMap<String, ImageWindow>(); public static void namedWindow(String winname) { namedWindow(winname, HighGui.WINDOW_AUTOSIZE); } public static void namedWindow(String winname, int flag) { ImageWindow newWin = new ImageWindow(winname, flag); if (windows.get(winname) == null) windows.put(winname, newWin); } public static void imshow(String winname, Mat img) { if (img.empty()) { System.err.println("Error: Empty image in imshow"); System.exit(-1); } else { ImageWindow tmpWindow = windows.get(winname); if (tmpWindow == null) { ImageWindow newWin = new ImageWindow(winname, img); windows.put(winname, newWin); } else { tmpWindow.setMat(img); } } } public static Image toBufferedImage(Mat m) { int type = BufferedImage.TYPE_BYTE_GRAY; if (m.channels() > 1) { type = BufferedImage.TYPE_3BYTE_BGR; } BufferedImage image = new BufferedImage(m.cols(), m.rows(), type); final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData(); m.get(0, 0, targetPixels); return image; } public static JFrame createJFrame(String title, int flag) { JFrame frame = new JFrame(title); frame.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent windowEvent) { n_closed_windows++; if (n_closed_windows == windows.size()) latch.countDown(); } }); frame.addKeyListener(new KeyListener() { @Override public void keyTyped(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { pressedKey = e.getKeyCode(); latch.countDown(); } }); if (flag == WINDOW_AUTOSIZE) frame.setResizable(false); return frame; } public static void waitKey(){ waitKey(0); } public static int waitKey(int delay) { // Reset control values latch = new CountDownLatch(1); n_closed_windows = 0; pressedKey = -1; // If there are no windows to be shown return if (windows.isEmpty()) { System.err.println("Error: waitKey must be used after an imshow"); System.exit(-1); } // Remove the unused windows Iterator<Map.Entry<String, ImageWindow>> iter = windows.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, ImageWindow> entry = iter.next(); ImageWindow win = entry.getValue(); if (win.alreadyUsed) { iter.remove(); win.frame.dispose(); } } // (if) Create (else) Update frame for (ImageWindow win : windows.values()) { if (win.img != null) { ImageIcon icon = new ImageIcon(toBufferedImage(win.img)); if (win.lbl == null) { JFrame frame = createJFrame(win.name, win.flag); JLabel lbl = new JLabel(icon); win.setFrameLabelVisible(frame, lbl); } else { win.lbl.setIcon(icon); } } else { System.err.println("Error: no imshow associated with" + " namedWindow: \"" + win.name + "\""); System.exit(-1); } } try { if (delay == 0) { latch.await(); } else { latch.await(delay, TimeUnit.MILLISECONDS); } } catch (InterruptedException e) { e.printStackTrace(); } // Set all windows as already used for (ImageWindow win : windows.values()) win.alreadyUsed = true; return pressedKey; } public static void destroyWindow(String winname) { ImageWindow tmpWin = windows.get(winname); if (tmpWin != null) windows.remove(winname); } public static void destroyAllWindows() { windows.clear(); } public static void resizeWindow(String winname, int width, int height) { ImageWindow tmpWin = windows.get(winname); if (tmpWin != null) tmpWin.setNewDimension(width, height); } public static void moveWindow(String winname, int x, int y) { ImageWindow tmpWin = windows.get(winname); if (tmpWin != null) tmpWin.setNewPosition(x, y); } }
opencv/opencv
modules/highgui/misc/java/src/java/highgui+HighGui.java
108
import com.twilio.sdk.TwilioRestClient; import com.twilio.sdk.TwilioRestException; import com.twilio.sdk.resource.factory.MessageFactory; import com.twilio.sdk.resource.instance.Message; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import java.util.ArrayList; import java.util.List; import java.util.Random; public class Hangover { public static final String ACCOUNT_SID = System.getenv("TWILIO_ACCOUNT_SID"); public static final String AUTH_TOKEN = System.getenv("TWILIO_AUTH_TOKEN"); public static final String YOUR_NUMBER = "1231231231"; public static final String BOSS_NUMBER = "3213213213"; public static void main(String[] args) throws TwilioRestException { TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN); String[] randomMessages = { "Locked out", "Pipes broke", "Food poisoning", "Not feeling well" }; int randomIndex = new Random().nextInt(randomMessages.length); String finalMessage = (randomMessages[randomIndex]); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("Body", "Gonna work from home. " + finalMessage)); params.add(new BasicNameValuePair("From", YOUR_NUMBER)); params.add(new BasicNameValuePair("To", BOSS_NUMBER)); MessageFactory messageFactory = client.getAccount().getMessageFactory(); Message message = messageFactory.create(params); System.out.println(message.getSid()); } }
NARKOZ/hacker-scripts
java/Hangover.java
109
// ASM: a very small and fast Java bytecode manipulation framework // Copyright (c) 2000-2011 INRIA, France Telecom // All rights reserved. // // 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 holders 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 OWNER 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.springframework.asm; /** * The input and output stack map frames of a basic block. * * <p>Stack map frames are computed in two steps: * * <ul> * <li>During the visit of each instruction in MethodWriter, the state of the frame at the end of * the current basic block is updated by simulating the action of the instruction on the * previous state of this so called "output frame". * <li>After all instructions have been visited, a fix point algorithm is used in MethodWriter to * compute the "input frame" of each basic block (i.e. the stack map frame at the beginning of * the basic block). See {@link MethodWriter#computeAllFrames}. * </ul> * * <p>Output stack map frames are computed relatively to the input frame of the basic block, which * is not yet known when output frames are computed. It is therefore necessary to be able to * represent abstract types such as "the type at position x in the input frame locals" or "the type * at position x from the top of the input frame stack" or even "the type at position x in the input * frame, with y more (or less) array dimensions". This explains the rather complicated type format * used in this class, explained below. * * <p>The local variables and the operand stack of input and output frames contain values called * "abstract types" hereafter. An abstract type is represented with 4 fields named DIM, KIND, FLAGS * and VALUE, packed in a single int value for better performance and memory efficiency: * * <pre> * ===================================== * |...DIM|KIND|.F|...............VALUE| * ===================================== * </pre> * * <ul> * <li>the DIM field, stored in the 6 most significant bits, is a signed number of array * dimensions (from -32 to 31, included). It can be retrieved with {@link #DIM_MASK} and a * right shift of {@link #DIM_SHIFT}. * <li>the KIND field, stored in 4 bits, indicates the kind of VALUE used. These 4 bits can be * retrieved with {@link #KIND_MASK} and, without any shift, must be equal to {@link * #CONSTANT_KIND}, {@link #REFERENCE_KIND}, {@link #UNINITIALIZED_KIND}, {@link * #FORWARD_UNINITIALIZED_KIND},{@link #LOCAL_KIND} or {@link #STACK_KIND}. * <li>the FLAGS field, stored in 2 bits, contains up to 2 boolean flags. Currently only one flag * is defined, namely {@link #TOP_IF_LONG_OR_DOUBLE_FLAG}. * <li>the VALUE field, stored in the remaining 20 bits, contains either * <ul> * <li>one of the constants {@link #ITEM_TOP}, {@link #ITEM_ASM_BOOLEAN}, {@link * #ITEM_ASM_BYTE}, {@link #ITEM_ASM_CHAR} or {@link #ITEM_ASM_SHORT}, {@link * #ITEM_INTEGER}, {@link #ITEM_FLOAT}, {@link #ITEM_LONG}, {@link #ITEM_DOUBLE}, {@link * #ITEM_NULL} or {@link #ITEM_UNINITIALIZED_THIS}, if KIND is equal to {@link * #CONSTANT_KIND}. * <li>the index of a {@link Symbol#TYPE_TAG} {@link Symbol} in the type table of a {@link * SymbolTable}, if KIND is equal to {@link #REFERENCE_KIND}. * <li>the index of an {@link Symbol#UNINITIALIZED_TYPE_TAG} {@link Symbol} in the type * table of a {@link SymbolTable}, if KIND is equal to {@link #UNINITIALIZED_KIND}. * <li>the index of a {@link Symbol#FORWARD_UNINITIALIZED_TYPE_TAG} {@link Symbol} in the * type table of a {@link SymbolTable}, if KIND is equal to {@link * #FORWARD_UNINITIALIZED_KIND}. * <li>the index of a local variable in the input stack frame, if KIND is equal to {@link * #LOCAL_KIND}. * <li>a position relatively to the top of the stack of the input stack frame, if KIND is * equal to {@link #STACK_KIND}, * </ul> * </ul> * * <p>Output frames can contain abstract types of any kind and with a positive or negative array * dimension (and even unassigned types, represented by 0 - which does not correspond to any valid * abstract type value). Input frames can only contain CONSTANT_KIND, REFERENCE_KIND, * UNINITIALIZED_KIND or FORWARD_UNINITIALIZED_KIND abstract types of positive or {@literal null} * array dimension. In all cases the type table contains only internal type names (array type * descriptors are forbidden - array dimensions must be represented through the DIM field). * * <p>The LONG and DOUBLE types are always represented by using two slots (LONG + TOP or DOUBLE + * TOP), for local variables as well as in the operand stack. This is necessary to be able to * simulate DUPx_y instructions, whose effect would be dependent on the concrete types represented * by the abstract types in the stack (which are not always known). * * @author Eric Bruneton */ class Frame { // Constants used in the StackMapTable attribute. // See https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.4. static final int SAME_FRAME = 0; static final int SAME_LOCALS_1_STACK_ITEM_FRAME = 64; static final int RESERVED = 128; static final int SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED = 247; static final int CHOP_FRAME = 248; static final int SAME_FRAME_EXTENDED = 251; static final int APPEND_FRAME = 252; static final int FULL_FRAME = 255; static final int ITEM_TOP = 0; static final int ITEM_INTEGER = 1; static final int ITEM_FLOAT = 2; static final int ITEM_DOUBLE = 3; static final int ITEM_LONG = 4; static final int ITEM_NULL = 5; static final int ITEM_UNINITIALIZED_THIS = 6; static final int ITEM_OBJECT = 7; static final int ITEM_UNINITIALIZED = 8; // Additional, ASM specific constants used in abstract types below. private static final int ITEM_ASM_BOOLEAN = 9; private static final int ITEM_ASM_BYTE = 10; private static final int ITEM_ASM_CHAR = 11; private static final int ITEM_ASM_SHORT = 12; // The size and offset in bits of each field of an abstract type. private static final int DIM_SIZE = 6; private static final int KIND_SIZE = 4; private static final int FLAGS_SIZE = 2; private static final int VALUE_SIZE = 32 - DIM_SIZE - KIND_SIZE - FLAGS_SIZE; private static final int DIM_SHIFT = KIND_SIZE + FLAGS_SIZE + VALUE_SIZE; private static final int KIND_SHIFT = FLAGS_SIZE + VALUE_SIZE; private static final int FLAGS_SHIFT = VALUE_SIZE; // Bitmasks to get each field of an abstract type. private static final int DIM_MASK = ((1 << DIM_SIZE) - 1) << DIM_SHIFT; private static final int KIND_MASK = ((1 << KIND_SIZE) - 1) << KIND_SHIFT; private static final int VALUE_MASK = (1 << VALUE_SIZE) - 1; // Constants to manipulate the DIM field of an abstract type. /** The constant to be added to an abstract type to get one with one more array dimension. */ private static final int ARRAY_OF = +1 << DIM_SHIFT; /** The constant to be added to an abstract type to get one with one less array dimension. */ private static final int ELEMENT_OF = -1 << DIM_SHIFT; // Possible values for the KIND field of an abstract type. private static final int CONSTANT_KIND = 1 << KIND_SHIFT; private static final int REFERENCE_KIND = 2 << KIND_SHIFT; private static final int UNINITIALIZED_KIND = 3 << KIND_SHIFT; private static final int FORWARD_UNINITIALIZED_KIND = 4 << KIND_SHIFT; private static final int LOCAL_KIND = 5 << KIND_SHIFT; private static final int STACK_KIND = 6 << KIND_SHIFT; // Possible flags for the FLAGS field of an abstract type. /** * A flag used for LOCAL_KIND and STACK_KIND abstract types, indicating that if the resolved, * concrete type is LONG or DOUBLE, TOP should be used instead (because the value has been * partially overridden with an xSTORE instruction). */ private static final int TOP_IF_LONG_OR_DOUBLE_FLAG = 1 << FLAGS_SHIFT; // Useful predefined abstract types (all the possible CONSTANT_KIND types). private static final int TOP = CONSTANT_KIND | ITEM_TOP; private static final int BOOLEAN = CONSTANT_KIND | ITEM_ASM_BOOLEAN; private static final int BYTE = CONSTANT_KIND | ITEM_ASM_BYTE; private static final int CHAR = CONSTANT_KIND | ITEM_ASM_CHAR; private static final int SHORT = CONSTANT_KIND | ITEM_ASM_SHORT; private static final int INTEGER = CONSTANT_KIND | ITEM_INTEGER; private static final int FLOAT = CONSTANT_KIND | ITEM_FLOAT; private static final int LONG = CONSTANT_KIND | ITEM_LONG; private static final int DOUBLE = CONSTANT_KIND | ITEM_DOUBLE; private static final int NULL = CONSTANT_KIND | ITEM_NULL; private static final int UNINITIALIZED_THIS = CONSTANT_KIND | ITEM_UNINITIALIZED_THIS; // ----------------------------------------------------------------------------------------------- // Instance fields // ----------------------------------------------------------------------------------------------- /** The basic block to which these input and output stack map frames correspond. */ Label owner; /** The input stack map frame locals. This is an array of abstract types. */ private int[] inputLocals; /** The input stack map frame stack. This is an array of abstract types. */ private int[] inputStack; /** The output stack map frame locals. This is an array of abstract types. */ private int[] outputLocals; /** The output stack map frame stack. This is an array of abstract types. */ private int[] outputStack; /** * The start of the output stack, relatively to the input stack. This offset is always negative or * null. A null offset means that the output stack must be appended to the input stack. A -n * offset means that the first n output stack elements must replace the top n input stack * elements, and that the other elements must be appended to the input stack. */ private short outputStackStart; /** The index of the top stack element in {@link #outputStack}. */ private short outputStackTop; /** The number of types that are initialized in the basic block. See {@link #initializations}. */ private int initializationCount; /** * The abstract types that are initialized in the basic block. A constructor invocation on an * UNINITIALIZED, FORWARD_UNINITIALIZED or UNINITIALIZED_THIS abstract type must replace <i>every * occurrence</i> of this type in the local variables and in the operand stack. This cannot be * done during the first step of the algorithm since, during this step, the local variables and * the operand stack types are still abstract. It is therefore necessary to store the abstract * types of the constructors which are invoked in the basic block, in order to do this replacement * during the second step of the algorithm, where the frames are fully computed. Note that this * array can contain abstract types that are relative to the input locals or to the input stack. */ private int[] initializations; // ----------------------------------------------------------------------------------------------- // Constructor // ----------------------------------------------------------------------------------------------- /** * Constructs a new Frame. * * @param owner the basic block to which these input and output stack map frames correspond. */ Frame(final Label owner) { this.owner = owner; } /** * Sets this frame to the value of the given frame. * * <p>WARNING: after this method is called the two frames share the same data structures. It is * recommended to discard the given frame to avoid unexpected side effects. * * @param frame The new frame value. */ final void copyFrom(final Frame frame) { inputLocals = frame.inputLocals; inputStack = frame.inputStack; outputStackStart = 0; outputLocals = frame.outputLocals; outputStack = frame.outputStack; outputStackTop = frame.outputStackTop; initializationCount = frame.initializationCount; initializations = frame.initializations; } // ----------------------------------------------------------------------------------------------- // Static methods to get abstract types from other type formats // ----------------------------------------------------------------------------------------------- /** * Returns the abstract type corresponding to the given public API frame element type. * * @param symbolTable the type table to use to lookup and store type {@link Symbol}. * @param type a frame element type described using the same format as in {@link * MethodVisitor#visitFrame}, i.e. either {@link Opcodes#TOP}, {@link Opcodes#INTEGER}, {@link * Opcodes#FLOAT}, {@link Opcodes#LONG}, {@link Opcodes#DOUBLE}, {@link Opcodes#NULL}, or * {@link Opcodes#UNINITIALIZED_THIS}, or the internal name of a class, or a Label designating * a NEW instruction (for uninitialized types). * @return the abstract type corresponding to the given frame element type. */ static int getAbstractTypeFromApiFormat(final SymbolTable symbolTable, final Object type) { if (type instanceof Integer) { return CONSTANT_KIND | ((Integer) type).intValue(); } else if (type instanceof String) { String descriptor = Type.getObjectType((String) type).getDescriptor(); return getAbstractTypeFromDescriptor(symbolTable, descriptor, 0); } else { Label label = (Label) type; if ((label.flags & Label.FLAG_RESOLVED) != 0) { return UNINITIALIZED_KIND | symbolTable.addUninitializedType("", label.bytecodeOffset); } else { return FORWARD_UNINITIALIZED_KIND | symbolTable.addForwardUninitializedType("", label); } } } /** * Returns the abstract type corresponding to the internal name of a class. * * @param symbolTable the type table to use to lookup and store type {@link Symbol}. * @param internalName the internal name of a class. This must <i>not</i> be an array type * descriptor. * @return the abstract type value corresponding to the given internal name. */ static int getAbstractTypeFromInternalName( final SymbolTable symbolTable, final String internalName) { return REFERENCE_KIND | symbolTable.addType(internalName); } /** * Returns the abstract type corresponding to the given type descriptor. * * @param symbolTable the type table to use to lookup and store type {@link Symbol}. * @param buffer a string ending with a type descriptor. * @param offset the start offset of the type descriptor in buffer. * @return the abstract type corresponding to the given type descriptor. */ private static int getAbstractTypeFromDescriptor( final SymbolTable symbolTable, final String buffer, final int offset) { String internalName; switch (buffer.charAt(offset)) { case 'V': return 0; case 'Z': case 'C': case 'B': case 'S': case 'I': return INTEGER; case 'F': return FLOAT; case 'J': return LONG; case 'D': return DOUBLE; case 'L': internalName = buffer.substring(offset + 1, buffer.length() - 1); return REFERENCE_KIND | symbolTable.addType(internalName); case '[': int elementDescriptorOffset = offset + 1; while (buffer.charAt(elementDescriptorOffset) == '[') { ++elementDescriptorOffset; } int typeValue; switch (buffer.charAt(elementDescriptorOffset)) { case 'Z': typeValue = BOOLEAN; break; case 'C': typeValue = CHAR; break; case 'B': typeValue = BYTE; break; case 'S': typeValue = SHORT; break; case 'I': typeValue = INTEGER; break; case 'F': typeValue = FLOAT; break; case 'J': typeValue = LONG; break; case 'D': typeValue = DOUBLE; break; case 'L': internalName = buffer.substring(elementDescriptorOffset + 1, buffer.length() - 1); typeValue = REFERENCE_KIND | symbolTable.addType(internalName); break; default: throw new IllegalArgumentException( "Invalid descriptor fragment: " + buffer.substring(elementDescriptorOffset)); } return ((elementDescriptorOffset - offset) << DIM_SHIFT) | typeValue; default: throw new IllegalArgumentException("Invalid descriptor: " + buffer.substring(offset)); } } // ----------------------------------------------------------------------------------------------- // Methods related to the input frame // ----------------------------------------------------------------------------------------------- /** * Sets the input frame from the given method description. This method is used to initialize the * first frame of a method, which is implicit (i.e. not stored explicitly in the StackMapTable * attribute). * * @param symbolTable the type table to use to lookup and store type {@link Symbol}. * @param access the method's access flags. * @param descriptor the method descriptor. * @param maxLocals the maximum number of local variables of the method. */ final void setInputFrameFromDescriptor( final SymbolTable symbolTable, final int access, final String descriptor, final int maxLocals) { inputLocals = new int[maxLocals]; inputStack = new int[0]; int inputLocalIndex = 0; if ((access & Opcodes.ACC_STATIC) == 0) { if ((access & Constants.ACC_CONSTRUCTOR) == 0) { inputLocals[inputLocalIndex++] = REFERENCE_KIND | symbolTable.addType(symbolTable.getClassName()); } else { inputLocals[inputLocalIndex++] = UNINITIALIZED_THIS; } } for (Type argumentType : Type.getArgumentTypes(descriptor)) { int abstractType = getAbstractTypeFromDescriptor(symbolTable, argumentType.getDescriptor(), 0); inputLocals[inputLocalIndex++] = abstractType; if (abstractType == LONG || abstractType == DOUBLE) { inputLocals[inputLocalIndex++] = TOP; } } while (inputLocalIndex < maxLocals) { inputLocals[inputLocalIndex++] = TOP; } } /** * Sets the input frame from the given public API frame description. * * @param symbolTable the type table to use to lookup and store type {@link Symbol}. * @param numLocal the number of local variables. * @param local the local variable types, described using the same format as in {@link * MethodVisitor#visitFrame}. * @param numStack the number of operand stack elements. * @param stack the operand stack types, described using the same format as in {@link * MethodVisitor#visitFrame}. */ final void setInputFrameFromApiFormat( final SymbolTable symbolTable, final int numLocal, final Object[] local, final int numStack, final Object[] stack) { int inputLocalIndex = 0; for (int i = 0; i < numLocal; ++i) { inputLocals[inputLocalIndex++] = getAbstractTypeFromApiFormat(symbolTable, local[i]); if (local[i] == Opcodes.LONG || local[i] == Opcodes.DOUBLE) { inputLocals[inputLocalIndex++] = TOP; } } while (inputLocalIndex < inputLocals.length) { inputLocals[inputLocalIndex++] = TOP; } int numStackTop = 0; for (int i = 0; i < numStack; ++i) { if (stack[i] == Opcodes.LONG || stack[i] == Opcodes.DOUBLE) { ++numStackTop; } } inputStack = new int[numStack + numStackTop]; int inputStackIndex = 0; for (int i = 0; i < numStack; ++i) { inputStack[inputStackIndex++] = getAbstractTypeFromApiFormat(symbolTable, stack[i]); if (stack[i] == Opcodes.LONG || stack[i] == Opcodes.DOUBLE) { inputStack[inputStackIndex++] = TOP; } } outputStackTop = 0; initializationCount = 0; } final int getInputStackSize() { return inputStack.length; } // ----------------------------------------------------------------------------------------------- // Methods related to the output frame // ----------------------------------------------------------------------------------------------- /** * Returns the abstract type stored at the given local variable index in the output frame. * * @param localIndex the index of the local variable whose value must be returned. * @return the abstract type stored at the given local variable index in the output frame. */ private int getLocal(final int localIndex) { if (outputLocals == null || localIndex >= outputLocals.length) { // If this local has never been assigned in this basic block, it is still equal to its value // in the input frame. return LOCAL_KIND | localIndex; } else { int abstractType = outputLocals[localIndex]; if (abstractType == 0) { // If this local has never been assigned in this basic block, so it is still equal to its // value in the input frame. abstractType = outputLocals[localIndex] = LOCAL_KIND | localIndex; } return abstractType; } } /** * Replaces the abstract type stored at the given local variable index in the output frame. * * @param localIndex the index of the output frame local variable that must be set. * @param abstractType the value that must be set. */ private void setLocal(final int localIndex, final int abstractType) { // Create and/or resize the output local variables array if necessary. if (outputLocals == null) { outputLocals = new int[10]; } int outputLocalsLength = outputLocals.length; if (localIndex >= outputLocalsLength) { int[] newOutputLocals = new int[Math.max(localIndex + 1, 2 * outputLocalsLength)]; System.arraycopy(outputLocals, 0, newOutputLocals, 0, outputLocalsLength); outputLocals = newOutputLocals; } // Set the local variable. outputLocals[localIndex] = abstractType; } /** * Pushes the given abstract type on the output frame stack. * * @param abstractType an abstract type. */ private void push(final int abstractType) { // Create and/or resize the output stack array if necessary. if (outputStack == null) { outputStack = new int[10]; } int outputStackLength = outputStack.length; if (outputStackTop >= outputStackLength) { int[] newOutputStack = new int[Math.max(outputStackTop + 1, 2 * outputStackLength)]; System.arraycopy(outputStack, 0, newOutputStack, 0, outputStackLength); outputStack = newOutputStack; } // Pushes the abstract type on the output stack. outputStack[outputStackTop++] = abstractType; // Updates the maximum size reached by the output stack, if needed (note that this size is // relative to the input stack size, which is not known yet). short outputStackSize = (short) (outputStackStart + outputStackTop); if (outputStackSize > owner.outputStackMax) { owner.outputStackMax = outputStackSize; } } /** * Pushes the abstract type corresponding to the given descriptor on the output frame stack. * * @param symbolTable the type table to use to lookup and store type {@link Symbol}. * @param descriptor a type or method descriptor (in which case its return type is pushed). */ private void push(final SymbolTable symbolTable, final String descriptor) { int typeDescriptorOffset = descriptor.charAt(0) == '(' ? Type.getReturnTypeOffset(descriptor) : 0; int abstractType = getAbstractTypeFromDescriptor(symbolTable, descriptor, typeDescriptorOffset); if (abstractType != 0) { push(abstractType); if (abstractType == LONG || abstractType == DOUBLE) { push(TOP); } } } /** * Pops an abstract type from the output frame stack and returns its value. * * @return the abstract type that has been popped from the output frame stack. */ private int pop() { if (outputStackTop > 0) { return outputStack[--outputStackTop]; } else { // If the output frame stack is empty, pop from the input stack. return STACK_KIND | -(--outputStackStart); } } /** * Pops the given number of abstract types from the output frame stack. * * @param elements the number of abstract types that must be popped. */ private void pop(final int elements) { if (outputStackTop >= elements) { outputStackTop -= elements; } else { // If the number of elements to be popped is greater than the number of elements in the output // stack, clear it, and pop the remaining elements from the input stack. outputStackStart -= elements - outputStackTop; outputStackTop = 0; } } /** * Pops as many abstract types from the output frame stack as described by the given descriptor. * * @param descriptor a type or method descriptor (in which case its argument types are popped). */ private void pop(final String descriptor) { char firstDescriptorChar = descriptor.charAt(0); if (firstDescriptorChar == '(') { pop((Type.getArgumentsAndReturnSizes(descriptor) >> 2) - 1); } else if (firstDescriptorChar == 'J' || firstDescriptorChar == 'D') { pop(2); } else { pop(1); } } // ----------------------------------------------------------------------------------------------- // Methods to handle uninitialized types // ----------------------------------------------------------------------------------------------- /** * Adds an abstract type to the list of types on which a constructor is invoked in the basic * block. * * @param abstractType an abstract type on a which a constructor is invoked. */ private void addInitializedType(final int abstractType) { // Create and/or resize the initializations array if necessary. if (initializations == null) { initializations = new int[2]; } int initializationsLength = initializations.length; if (initializationCount >= initializationsLength) { int[] newInitializations = new int[Math.max(initializationCount + 1, 2 * initializationsLength)]; System.arraycopy(initializations, 0, newInitializations, 0, initializationsLength); initializations = newInitializations; } // Store the abstract type. initializations[initializationCount++] = abstractType; } /** * Returns the "initialized" abstract type corresponding to the given abstract type. * * @param symbolTable the type table to use to lookup and store type {@link Symbol}. * @param abstractType an abstract type. * @return the REFERENCE_KIND abstract type corresponding to abstractType if it is * UNINITIALIZED_THIS or an UNINITIALIZED_KIND or FORWARD_UNINITIALIZED_KIND abstract type for * one of the types on which a constructor is invoked in the basic block. Otherwise returns * abstractType. */ private int getInitializedType(final SymbolTable symbolTable, final int abstractType) { if (abstractType == UNINITIALIZED_THIS || (abstractType & (DIM_MASK | KIND_MASK)) == UNINITIALIZED_KIND || (abstractType & (DIM_MASK | KIND_MASK)) == FORWARD_UNINITIALIZED_KIND) { for (int i = 0; i < initializationCount; ++i) { int initializedType = initializations[i]; int dim = initializedType & DIM_MASK; int kind = initializedType & KIND_MASK; int value = initializedType & VALUE_MASK; if (kind == LOCAL_KIND) { initializedType = dim + inputLocals[value]; } else if (kind == STACK_KIND) { initializedType = dim + inputStack[inputStack.length - value]; } if (abstractType == initializedType) { if (abstractType == UNINITIALIZED_THIS) { return REFERENCE_KIND | symbolTable.addType(symbolTable.getClassName()); } else { return REFERENCE_KIND | symbolTable.addType(symbolTable.getType(abstractType & VALUE_MASK).value); } } } } return abstractType; } // ----------------------------------------------------------------------------------------------- // Main method, to simulate the execution of each instruction on the output frame // ----------------------------------------------------------------------------------------------- /** * Simulates the action of the given instruction on the output stack frame. * * @param opcode the opcode of the instruction. * @param arg the numeric operand of the instruction, if any. * @param argSymbol the Symbol operand of the instruction, if any. * @param symbolTable the type table to use to lookup and store type {@link Symbol}. */ void execute( final int opcode, final int arg, final Symbol argSymbol, final SymbolTable symbolTable) { // Abstract types popped from the stack or read from local variables. int abstractType1; int abstractType2; int abstractType3; int abstractType4; switch (opcode) { case Opcodes.NOP: case Opcodes.INEG: case Opcodes.LNEG: case Opcodes.FNEG: case Opcodes.DNEG: case Opcodes.I2B: case Opcodes.I2C: case Opcodes.I2S: case Opcodes.GOTO: case Opcodes.RETURN: break; case Opcodes.ACONST_NULL: push(NULL); break; case Opcodes.ICONST_M1: case Opcodes.ICONST_0: case Opcodes.ICONST_1: case Opcodes.ICONST_2: case Opcodes.ICONST_3: case Opcodes.ICONST_4: case Opcodes.ICONST_5: case Opcodes.BIPUSH: case Opcodes.SIPUSH: case Opcodes.ILOAD: push(INTEGER); break; case Opcodes.LCONST_0: case Opcodes.LCONST_1: case Opcodes.LLOAD: push(LONG); push(TOP); break; case Opcodes.FCONST_0: case Opcodes.FCONST_1: case Opcodes.FCONST_2: case Opcodes.FLOAD: push(FLOAT); break; case Opcodes.DCONST_0: case Opcodes.DCONST_1: case Opcodes.DLOAD: push(DOUBLE); push(TOP); break; case Opcodes.LDC: switch (argSymbol.tag) { case Symbol.CONSTANT_INTEGER_TAG: push(INTEGER); break; case Symbol.CONSTANT_LONG_TAG: push(LONG); push(TOP); break; case Symbol.CONSTANT_FLOAT_TAG: push(FLOAT); break; case Symbol.CONSTANT_DOUBLE_TAG: push(DOUBLE); push(TOP); break; case Symbol.CONSTANT_CLASS_TAG: push(REFERENCE_KIND | symbolTable.addType("java/lang/Class")); break; case Symbol.CONSTANT_STRING_TAG: push(REFERENCE_KIND | symbolTable.addType("java/lang/String")); break; case Symbol.CONSTANT_METHOD_TYPE_TAG: push(REFERENCE_KIND | symbolTable.addType("java/lang/invoke/MethodType")); break; case Symbol.CONSTANT_METHOD_HANDLE_TAG: push(REFERENCE_KIND | symbolTable.addType("java/lang/invoke/MethodHandle")); break; case Symbol.CONSTANT_DYNAMIC_TAG: push(symbolTable, argSymbol.value); break; default: throw new AssertionError(); } break; case Opcodes.ALOAD: push(getLocal(arg)); break; case Opcodes.LALOAD: case Opcodes.D2L: pop(2); push(LONG); push(TOP); break; case Opcodes.DALOAD: case Opcodes.L2D: pop(2); push(DOUBLE); push(TOP); break; case Opcodes.AALOAD: pop(1); abstractType1 = pop(); push(abstractType1 == NULL ? abstractType1 : ELEMENT_OF + abstractType1); break; case Opcodes.ISTORE: case Opcodes.FSTORE: case Opcodes.ASTORE: abstractType1 = pop(); setLocal(arg, abstractType1); if (arg > 0) { int previousLocalType = getLocal(arg - 1); if (previousLocalType == LONG || previousLocalType == DOUBLE) { setLocal(arg - 1, TOP); } else if ((previousLocalType & KIND_MASK) == LOCAL_KIND || (previousLocalType & KIND_MASK) == STACK_KIND) { // The type of the previous local variable is not known yet, but if it later appears // to be LONG or DOUBLE, we should then use TOP instead. setLocal(arg - 1, previousLocalType | TOP_IF_LONG_OR_DOUBLE_FLAG); } } break; case Opcodes.LSTORE: case Opcodes.DSTORE: pop(1); abstractType1 = pop(); setLocal(arg, abstractType1); setLocal(arg + 1, TOP); if (arg > 0) { int previousLocalType = getLocal(arg - 1); if (previousLocalType == LONG || previousLocalType == DOUBLE) { setLocal(arg - 1, TOP); } else if ((previousLocalType & KIND_MASK) == LOCAL_KIND || (previousLocalType & KIND_MASK) == STACK_KIND) { // The type of the previous local variable is not known yet, but if it later appears // to be LONG or DOUBLE, we should then use TOP instead. setLocal(arg - 1, previousLocalType | TOP_IF_LONG_OR_DOUBLE_FLAG); } } break; case Opcodes.IASTORE: case Opcodes.BASTORE: case Opcodes.CASTORE: case Opcodes.SASTORE: case Opcodes.FASTORE: case Opcodes.AASTORE: pop(3); break; case Opcodes.LASTORE: case Opcodes.DASTORE: pop(4); break; case Opcodes.POP: case Opcodes.IFEQ: case Opcodes.IFNE: case Opcodes.IFLT: case Opcodes.IFGE: case Opcodes.IFGT: case Opcodes.IFLE: case Opcodes.IRETURN: case Opcodes.FRETURN: case Opcodes.ARETURN: case Opcodes.TABLESWITCH: case Opcodes.LOOKUPSWITCH: case Opcodes.ATHROW: case Opcodes.MONITORENTER: case Opcodes.MONITOREXIT: case Opcodes.IFNULL: case Opcodes.IFNONNULL: pop(1); break; case Opcodes.POP2: case Opcodes.IF_ICMPEQ: case Opcodes.IF_ICMPNE: case Opcodes.IF_ICMPLT: case Opcodes.IF_ICMPGE: case Opcodes.IF_ICMPGT: case Opcodes.IF_ICMPLE: case Opcodes.IF_ACMPEQ: case Opcodes.IF_ACMPNE: case Opcodes.LRETURN: case Opcodes.DRETURN: pop(2); break; case Opcodes.DUP: abstractType1 = pop(); push(abstractType1); push(abstractType1); break; case Opcodes.DUP_X1: abstractType1 = pop(); abstractType2 = pop(); push(abstractType1); push(abstractType2); push(abstractType1); break; case Opcodes.DUP_X2: abstractType1 = pop(); abstractType2 = pop(); abstractType3 = pop(); push(abstractType1); push(abstractType3); push(abstractType2); push(abstractType1); break; case Opcodes.DUP2: abstractType1 = pop(); abstractType2 = pop(); push(abstractType2); push(abstractType1); push(abstractType2); push(abstractType1); break; case Opcodes.DUP2_X1: abstractType1 = pop(); abstractType2 = pop(); abstractType3 = pop(); push(abstractType2); push(abstractType1); push(abstractType3); push(abstractType2); push(abstractType1); break; case Opcodes.DUP2_X2: abstractType1 = pop(); abstractType2 = pop(); abstractType3 = pop(); abstractType4 = pop(); push(abstractType2); push(abstractType1); push(abstractType4); push(abstractType3); push(abstractType2); push(abstractType1); break; case Opcodes.SWAP: abstractType1 = pop(); abstractType2 = pop(); push(abstractType1); push(abstractType2); break; case Opcodes.IALOAD: case Opcodes.BALOAD: case Opcodes.CALOAD: case Opcodes.SALOAD: case Opcodes.IADD: case Opcodes.ISUB: case Opcodes.IMUL: case Opcodes.IDIV: case Opcodes.IREM: case Opcodes.IAND: case Opcodes.IOR: case Opcodes.IXOR: case Opcodes.ISHL: case Opcodes.ISHR: case Opcodes.IUSHR: case Opcodes.L2I: case Opcodes.D2I: case Opcodes.FCMPL: case Opcodes.FCMPG: pop(2); push(INTEGER); break; case Opcodes.LADD: case Opcodes.LSUB: case Opcodes.LMUL: case Opcodes.LDIV: case Opcodes.LREM: case Opcodes.LAND: case Opcodes.LOR: case Opcodes.LXOR: pop(4); push(LONG); push(TOP); break; case Opcodes.FALOAD: case Opcodes.FADD: case Opcodes.FSUB: case Opcodes.FMUL: case Opcodes.FDIV: case Opcodes.FREM: case Opcodes.L2F: case Opcodes.D2F: pop(2); push(FLOAT); break; case Opcodes.DADD: case Opcodes.DSUB: case Opcodes.DMUL: case Opcodes.DDIV: case Opcodes.DREM: pop(4); push(DOUBLE); push(TOP); break; case Opcodes.LSHL: case Opcodes.LSHR: case Opcodes.LUSHR: pop(3); push(LONG); push(TOP); break; case Opcodes.IINC: setLocal(arg, INTEGER); break; case Opcodes.I2L: case Opcodes.F2L: pop(1); push(LONG); push(TOP); break; case Opcodes.I2F: pop(1); push(FLOAT); break; case Opcodes.I2D: case Opcodes.F2D: pop(1); push(DOUBLE); push(TOP); break; case Opcodes.F2I: case Opcodes.ARRAYLENGTH: case Opcodes.INSTANCEOF: pop(1); push(INTEGER); break; case Opcodes.LCMP: case Opcodes.DCMPL: case Opcodes.DCMPG: pop(4); push(INTEGER); break; case Opcodes.JSR: case Opcodes.RET: throw new IllegalArgumentException("JSR/RET are not supported with computeFrames option"); case Opcodes.GETSTATIC: push(symbolTable, argSymbol.value); break; case Opcodes.PUTSTATIC: pop(argSymbol.value); break; case Opcodes.GETFIELD: pop(1); push(symbolTable, argSymbol.value); break; case Opcodes.PUTFIELD: pop(argSymbol.value); pop(); break; case Opcodes.INVOKEVIRTUAL: case Opcodes.INVOKESPECIAL: case Opcodes.INVOKESTATIC: case Opcodes.INVOKEINTERFACE: pop(argSymbol.value); if (opcode != Opcodes.INVOKESTATIC) { abstractType1 = pop(); if (opcode == Opcodes.INVOKESPECIAL && argSymbol.name.charAt(0) == '<') { addInitializedType(abstractType1); } } push(symbolTable, argSymbol.value); break; case Opcodes.INVOKEDYNAMIC: pop(argSymbol.value); push(symbolTable, argSymbol.value); break; case Opcodes.NEW: push(UNINITIALIZED_KIND | symbolTable.addUninitializedType(argSymbol.value, arg)); break; case Opcodes.NEWARRAY: pop(); switch (arg) { case Opcodes.T_BOOLEAN: push(ARRAY_OF | BOOLEAN); break; case Opcodes.T_CHAR: push(ARRAY_OF | CHAR); break; case Opcodes.T_BYTE: push(ARRAY_OF | BYTE); break; case Opcodes.T_SHORT: push(ARRAY_OF | SHORT); break; case Opcodes.T_INT: push(ARRAY_OF | INTEGER); break; case Opcodes.T_FLOAT: push(ARRAY_OF | FLOAT); break; case Opcodes.T_DOUBLE: push(ARRAY_OF | DOUBLE); break; case Opcodes.T_LONG: push(ARRAY_OF | LONG); break; default: throw new IllegalArgumentException(); } break; case Opcodes.ANEWARRAY: String arrayElementType = argSymbol.value; pop(); if (arrayElementType.charAt(0) == '[') { push(symbolTable, '[' + arrayElementType); } else { push(ARRAY_OF | REFERENCE_KIND | symbolTable.addType(arrayElementType)); } break; case Opcodes.CHECKCAST: String castType = argSymbol.value; pop(); if (castType.charAt(0) == '[') { push(symbolTable, castType); } else { push(REFERENCE_KIND | symbolTable.addType(castType)); } break; case Opcodes.MULTIANEWARRAY: pop(arg); push(symbolTable, argSymbol.value); break; default: throw new IllegalArgumentException(); } } // ----------------------------------------------------------------------------------------------- // Frame merging methods, used in the second step of the stack map frame computation algorithm // ----------------------------------------------------------------------------------------------- /** * Computes the concrete output type corresponding to a given abstract output type. * * @param abstractOutputType an abstract output type. * @param numStack the size of the input stack, used to resolve abstract output types of * STACK_KIND kind. * @return the concrete output type corresponding to 'abstractOutputType'. */ private int getConcreteOutputType(final int abstractOutputType, final int numStack) { int dim = abstractOutputType & DIM_MASK; int kind = abstractOutputType & KIND_MASK; if (kind == LOCAL_KIND) { // By definition, a LOCAL_KIND type designates the concrete type of a local variable at // the beginning of the basic block corresponding to this frame (which is known when // this method is called, but was not when the abstract type was computed). int concreteOutputType = dim + inputLocals[abstractOutputType & VALUE_MASK]; if ((abstractOutputType & TOP_IF_LONG_OR_DOUBLE_FLAG) != 0 && (concreteOutputType == LONG || concreteOutputType == DOUBLE)) { concreteOutputType = TOP; } return concreteOutputType; } else if (kind == STACK_KIND) { // By definition, a STACK_KIND type designates the concrete type of a local variable at // the beginning of the basic block corresponding to this frame (which is known when // this method is called, but was not when the abstract type was computed). int concreteOutputType = dim + inputStack[numStack - (abstractOutputType & VALUE_MASK)]; if ((abstractOutputType & TOP_IF_LONG_OR_DOUBLE_FLAG) != 0 && (concreteOutputType == LONG || concreteOutputType == DOUBLE)) { concreteOutputType = TOP; } return concreteOutputType; } else { return abstractOutputType; } } /** * Merges the input frame of the given {@link Frame} with the input and output frames of this * {@link Frame}. Returns {@literal true} if the given frame has been changed by this operation * (the input and output frames of this {@link Frame} are never changed). * * @param symbolTable the type table to use to lookup and store type {@link Symbol}. * @param dstFrame the {@link Frame} whose input frame must be updated. This should be the frame * of a successor, in the control flow graph, of the basic block corresponding to this frame. * @param catchTypeIndex if 'frame' corresponds to an exception handler basic block, the type * table index of the caught exception type, otherwise 0. * @return {@literal true} if the input frame of 'frame' has been changed by this operation. */ final boolean merge( final SymbolTable symbolTable, final Frame dstFrame, final int catchTypeIndex) { boolean frameChanged = false; // Compute the concrete types of the local variables at the end of the basic block corresponding // to this frame, by resolving its abstract output types, and merge these concrete types with // those of the local variables in the input frame of dstFrame. int numLocal = inputLocals.length; int numStack = inputStack.length; if (dstFrame.inputLocals == null) { dstFrame.inputLocals = new int[numLocal]; frameChanged = true; } for (int i = 0; i < numLocal; ++i) { int concreteOutputType; if (outputLocals != null && i < outputLocals.length) { int abstractOutputType = outputLocals[i]; if (abstractOutputType == 0) { // If the local variable has never been assigned in this basic block, it is equal to its // value at the beginning of the block. concreteOutputType = inputLocals[i]; } else { concreteOutputType = getConcreteOutputType(abstractOutputType, numStack); } } else { // If the local variable has never been assigned in this basic block, it is equal to its // value at the beginning of the block. concreteOutputType = inputLocals[i]; } // concreteOutputType might be an uninitialized type from the input locals or from the input // stack. However, if a constructor has been called for this class type in the basic block, // then this type is no longer uninitialized at the end of basic block. if (initializations != null) { concreteOutputType = getInitializedType(symbolTable, concreteOutputType); } frameChanged |= merge(symbolTable, concreteOutputType, dstFrame.inputLocals, i); } // If dstFrame is an exception handler block, it can be reached from any instruction of the // basic block corresponding to this frame, in particular from the first one. Therefore, the // input locals of dstFrame should be compatible (i.e. merged) with the input locals of this // frame (and the input stack of dstFrame should be compatible, i.e. merged, with a one // element stack containing the caught exception type). if (catchTypeIndex > 0) { for (int i = 0; i < numLocal; ++i) { frameChanged |= merge(symbolTable, inputLocals[i], dstFrame.inputLocals, i); } if (dstFrame.inputStack == null) { dstFrame.inputStack = new int[1]; frameChanged = true; } frameChanged |= merge(symbolTable, catchTypeIndex, dstFrame.inputStack, 0); return frameChanged; } // Compute the concrete types of the stack operands at the end of the basic block corresponding // to this frame, by resolving its abstract output types, and merge these concrete types with // those of the stack operands in the input frame of dstFrame. int numInputStack = inputStack.length + outputStackStart; if (dstFrame.inputStack == null) { dstFrame.inputStack = new int[numInputStack + outputStackTop]; frameChanged = true; } // First, do this for the stack operands that have not been popped in the basic block // corresponding to this frame, and which are therefore equal to their value in the input // frame (except for uninitialized types, which may have been initialized). for (int i = 0; i < numInputStack; ++i) { int concreteOutputType = inputStack[i]; if (initializations != null) { concreteOutputType = getInitializedType(symbolTable, concreteOutputType); } frameChanged |= merge(symbolTable, concreteOutputType, dstFrame.inputStack, i); } // Then, do this for the stack operands that have pushed in the basic block (this code is the // same as the one above for local variables). for (int i = 0; i < outputStackTop; ++i) { int abstractOutputType = outputStack[i]; int concreteOutputType = getConcreteOutputType(abstractOutputType, numStack); if (initializations != null) { concreteOutputType = getInitializedType(symbolTable, concreteOutputType); } frameChanged |= merge(symbolTable, concreteOutputType, dstFrame.inputStack, numInputStack + i); } return frameChanged; } /** * Merges the type at the given index in the given abstract type array with the given type. * Returns {@literal true} if the type array has been modified by this operation. * * @param symbolTable the type table to use to lookup and store type {@link Symbol}. * @param sourceType the abstract type with which the abstract type array element must be merged. * This type should be of {@link #CONSTANT_KIND}, {@link #REFERENCE_KIND}, {@link * #UNINITIALIZED_KIND} or {@link #FORWARD_UNINITIALIZED_KIND} kind, with positive or * {@literal null} array dimensions. * @param dstTypes an array of abstract types. These types should be of {@link #CONSTANT_KIND}, * {@link #REFERENCE_KIND}, {@link #UNINITIALIZED_KIND} or {@link #FORWARD_UNINITIALIZED_KIND} * kind, with positive or {@literal null} array dimensions. * @param dstIndex the index of the type that must be merged in dstTypes. * @return {@literal true} if the type array has been modified by this operation. */ private static boolean merge( final SymbolTable symbolTable, final int sourceType, final int[] dstTypes, final int dstIndex) { int dstType = dstTypes[dstIndex]; if (dstType == sourceType) { // If the types are equal, merge(sourceType, dstType) = dstType, so there is no change. return false; } int srcType = sourceType; if ((sourceType & ~DIM_MASK) == NULL) { if (dstType == NULL) { return false; } srcType = NULL; } if (dstType == 0) { // If dstTypes[dstIndex] has never been assigned, merge(srcType, dstType) = srcType. dstTypes[dstIndex] = srcType; return true; } int mergedType; if ((dstType & DIM_MASK) != 0 || (dstType & KIND_MASK) == REFERENCE_KIND) { // If dstType is a reference type of any array dimension. if (srcType == NULL) { // If srcType is the NULL type, merge(srcType, dstType) = dstType, so there is no change. return false; } else if ((srcType & (DIM_MASK | KIND_MASK)) == (dstType & (DIM_MASK | KIND_MASK))) { // If srcType has the same array dimension and the same kind as dstType. if ((dstType & KIND_MASK) == REFERENCE_KIND) { // If srcType and dstType are reference types with the same array dimension, // merge(srcType, dstType) = dim(srcType) | common super class of srcType and dstType. mergedType = (srcType & DIM_MASK) | REFERENCE_KIND | symbolTable.addMergedType(srcType & VALUE_MASK, dstType & VALUE_MASK); } else { // If srcType and dstType are array types of equal dimension but different element types, // merge(srcType, dstType) = dim(srcType) - 1 | java/lang/Object. int mergedDim = ELEMENT_OF + (srcType & DIM_MASK); mergedType = mergedDim | REFERENCE_KIND | symbolTable.addType("java/lang/Object"); } } else if ((srcType & DIM_MASK) != 0 || (srcType & KIND_MASK) == REFERENCE_KIND) { // If srcType is any other reference or array type, // merge(srcType, dstType) = min(srcDdim, dstDim) | java/lang/Object // where srcDim is the array dimension of srcType, minus 1 if srcType is an array type // with a non reference element type (and similarly for dstDim). int srcDim = srcType & DIM_MASK; if (srcDim != 0 && (srcType & KIND_MASK) != REFERENCE_KIND) { srcDim = ELEMENT_OF + srcDim; } int dstDim = dstType & DIM_MASK; if (dstDim != 0 && (dstType & KIND_MASK) != REFERENCE_KIND) { dstDim = ELEMENT_OF + dstDim; } mergedType = Math.min(srcDim, dstDim) | REFERENCE_KIND | symbolTable.addType("java/lang/Object"); } else { // If srcType is any other type, merge(srcType, dstType) = TOP. mergedType = TOP; } } else if (dstType == NULL) { // If dstType is the NULL type, merge(srcType, dstType) = srcType, or TOP if srcType is not a // an array type or a reference type. mergedType = (srcType & DIM_MASK) != 0 || (srcType & KIND_MASK) == REFERENCE_KIND ? srcType : TOP; } else { // If dstType is any other type, merge(srcType, dstType) = TOP whatever srcType. mergedType = TOP; } if (mergedType != dstType) { dstTypes[dstIndex] = mergedType; return true; } return false; } // ----------------------------------------------------------------------------------------------- // Frame output methods, to generate StackMapFrame attributes // ----------------------------------------------------------------------------------------------- /** * Makes the given {@link MethodWriter} visit the input frame of this {@link Frame}. The visit is * done with the {@link MethodWriter#visitFrameStart}, {@link MethodWriter#visitAbstractType} and * {@link MethodWriter#visitFrameEnd} methods. * * @param methodWriter the {@link MethodWriter} that should visit the input frame of this {@link * Frame}. */ final void accept(final MethodWriter methodWriter) { // Compute the number of locals, ignoring TOP types that are just after a LONG or a DOUBLE, and // all trailing TOP types. int[] localTypes = inputLocals; int numLocal = 0; int numTrailingTop = 0; int i = 0; while (i < localTypes.length) { int localType = localTypes[i]; i += (localType == LONG || localType == DOUBLE) ? 2 : 1; if (localType == TOP) { numTrailingTop++; } else { numLocal += numTrailingTop + 1; numTrailingTop = 0; } } // Compute the stack size, ignoring TOP types that are just after a LONG or a DOUBLE. int[] stackTypes = inputStack; int numStack = 0; i = 0; while (i < stackTypes.length) { int stackType = stackTypes[i]; i += (stackType == LONG || stackType == DOUBLE) ? 2 : 1; numStack++; } // Visit the frame and its content. int frameIndex = methodWriter.visitFrameStart(owner.bytecodeOffset, numLocal, numStack); i = 0; while (numLocal-- > 0) { int localType = localTypes[i]; i += (localType == LONG || localType == DOUBLE) ? 2 : 1; methodWriter.visitAbstractType(frameIndex++, localType); } i = 0; while (numStack-- > 0) { int stackType = stackTypes[i]; i += (stackType == LONG || stackType == DOUBLE) ? 2 : 1; methodWriter.visitAbstractType(frameIndex++, stackType); } methodWriter.visitFrameEnd(); } /** * Put the given abstract type in the given ByteVector, using the JVMS verification_type_info * format used in StackMapTable attributes. * * @param symbolTable the type table to use to lookup and store type {@link Symbol}. * @param abstractType an abstract type, restricted to {@link Frame#CONSTANT_KIND}, {@link * Frame#REFERENCE_KIND}, {@link Frame#UNINITIALIZED_KIND} or {@link * Frame#FORWARD_UNINITIALIZED_KIND} types. * @param output where the abstract type must be put. * @see <a href="https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.4">JVMS * 4.7.4</a> */ static void putAbstractType( final SymbolTable symbolTable, final int abstractType, final ByteVector output) { int arrayDimensions = (abstractType & Frame.DIM_MASK) >> DIM_SHIFT; if (arrayDimensions == 0) { int typeValue = abstractType & VALUE_MASK; switch (abstractType & KIND_MASK) { case CONSTANT_KIND: output.putByte(typeValue); break; case REFERENCE_KIND: output .putByte(ITEM_OBJECT) .putShort(symbolTable.addConstantClass(symbolTable.getType(typeValue).value).index); break; case UNINITIALIZED_KIND: output.putByte(ITEM_UNINITIALIZED).putShort((int) symbolTable.getType(typeValue).data); break; case FORWARD_UNINITIALIZED_KIND: output.putByte(ITEM_UNINITIALIZED); symbolTable.getForwardUninitializedLabel(typeValue).put(output); break; default: throw new AssertionError(); } } else { // Case of an array type, we need to build its descriptor first. StringBuilder typeDescriptor = new StringBuilder(32); // SPRING PATCH: larger initial size while (arrayDimensions-- > 0) { typeDescriptor.append('['); } if ((abstractType & KIND_MASK) == REFERENCE_KIND) { typeDescriptor .append('L') .append(symbolTable.getType(abstractType & VALUE_MASK).value) .append(';'); } else { switch (abstractType & VALUE_MASK) { case Frame.ITEM_ASM_BOOLEAN: typeDescriptor.append('Z'); break; case Frame.ITEM_ASM_BYTE: typeDescriptor.append('B'); break; case Frame.ITEM_ASM_CHAR: typeDescriptor.append('C'); break; case Frame.ITEM_ASM_SHORT: typeDescriptor.append('S'); break; case Frame.ITEM_INTEGER: typeDescriptor.append('I'); break; case Frame.ITEM_FLOAT: typeDescriptor.append('F'); break; case Frame.ITEM_LONG: typeDescriptor.append('J'); break; case Frame.ITEM_DOUBLE: typeDescriptor.append('D'); break; default: throw new AssertionError(); } } output .putByte(ITEM_OBJECT) .putShort(symbolTable.addConstantClass(typeDescriptor.toString()).index); } } }
spring-projects/spring-framework
spring-core/src/main/java/org/springframework/asm/Frame.java
110
// Given two 1d vectors, implement an iterator to return their elements alternately. // For example, given two 1d vectors: // v1 = [1, 2] // v2 = [3, 4, 5, 6] // By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1, 3, 2, 4, 5, 6]. // Follow up: What if you are given k 1d vectors? How well can your code be extended to such cases? /** * Your ZigzagIterator object will be instantiated and called as such: * ZigzagIterator i = new ZigzagIterator(v1, v2); * while (i.hasNext()) v[f()] = i.next(); */ public class ZigZagIterator { private Iterator<Integer> i; private Iterator<Integer> j; private Iterator<Integer> temp; public ZigzagIterator(List<Integer> v1, List<Integer> v2) { i = v1.iterator(); j = v2.iterator(); } public int next() { if(i.hasNext()) { temp = i; i = j; j = temp; } return j.next(); } public boolean hasNext() { return i.hasNext() || j.hasNext(); } }
kdn251/interviews
company/google/ZigZagIterator.java
111
package com.genymobile.scrcpy; import java.io.File; import java.io.IOException; import java.io.OutputStream; /** * Handle the cleanup of scrcpy, even if the main process is killed. * <p> * This is useful to restore some state when scrcpy is closed, even on device disconnection (which kills the scrcpy process). */ public final class CleanUp { private static final int MSG_TYPE_MASK = 0b11; private static final int MSG_TYPE_RESTORE_STAY_ON = 0; private static final int MSG_TYPE_DISABLE_SHOW_TOUCHES = 1; private static final int MSG_TYPE_RESTORE_NORMAL_POWER_MODE = 2; private static final int MSG_TYPE_POWER_OFF_SCREEN = 3; private static final int MSG_PARAM_SHIFT = 2; private final OutputStream out; public CleanUp(OutputStream out) { this.out = out; } public static CleanUp configure(int displayId) throws IOException { String[] cmd = {"app_process", "/", CleanUp.class.getName(), String.valueOf(displayId)}; ProcessBuilder builder = new ProcessBuilder(cmd); builder.environment().put("CLASSPATH", Server.SERVER_PATH); Process process = builder.start(); return new CleanUp(process.getOutputStream()); } private boolean sendMessage(int type, int param) { assert (type & ~MSG_TYPE_MASK) == 0; int msg = type | param << MSG_PARAM_SHIFT; try { out.write(msg); out.flush(); return true; } catch (IOException e) { Ln.w("Could not configure cleanup (type=" + type + ", param=" + param + ")", e); return false; } } public boolean setRestoreStayOn(int restoreValue) { // Restore the value (between 0 and 7), -1 to not restore // <https://developer.android.com/reference/android/provider/Settings.Global#STAY_ON_WHILE_PLUGGED_IN> assert restoreValue >= -1 && restoreValue <= 7; return sendMessage(MSG_TYPE_RESTORE_STAY_ON, restoreValue & 0b1111); } public boolean setDisableShowTouches(boolean disableOnExit) { return sendMessage(MSG_TYPE_DISABLE_SHOW_TOUCHES, disableOnExit ? 1 : 0); } public boolean setRestoreNormalPowerMode(boolean restoreOnExit) { return sendMessage(MSG_TYPE_RESTORE_NORMAL_POWER_MODE, restoreOnExit ? 1 : 0); } public boolean setPowerOffScreen(boolean powerOffScreenOnExit) { return sendMessage(MSG_TYPE_POWER_OFF_SCREEN, powerOffScreenOnExit ? 1 : 0); } public static void unlinkSelf() { try { new File(Server.SERVER_PATH).delete(); } catch (Exception e) { Ln.e("Could not unlink server", e); } } public static void main(String... args) { unlinkSelf(); int displayId = Integer.parseInt(args[0]); int restoreStayOn = -1; boolean disableShowTouches = false; boolean restoreNormalPowerMode = false; boolean powerOffScreen = false; try { // Wait for the server to die int msg; while ((msg = System.in.read()) != -1) { int type = msg & MSG_TYPE_MASK; int param = msg >> MSG_PARAM_SHIFT; switch (type) { case MSG_TYPE_RESTORE_STAY_ON: restoreStayOn = param > 7 ? -1 : param; break; case MSG_TYPE_DISABLE_SHOW_TOUCHES: disableShowTouches = param != 0; break; case MSG_TYPE_RESTORE_NORMAL_POWER_MODE: restoreNormalPowerMode = param != 0; break; case MSG_TYPE_POWER_OFF_SCREEN: powerOffScreen = param != 0; break; default: Ln.w("Unexpected msg type: " + type); break; } } } catch (IOException e) { // Expected when the server is dead } Ln.i("Cleaning up"); if (disableShowTouches) { Ln.i("Disabling \"show touches\""); try { Settings.putValue(Settings.TABLE_SYSTEM, "show_touches", "0"); } catch (SettingsException e) { Ln.e("Could not restore \"show_touches\"", e); } } if (restoreStayOn != -1) { Ln.i("Restoring \"stay awake\""); try { Settings.putValue(Settings.TABLE_GLOBAL, "stay_on_while_plugged_in", String.valueOf(restoreStayOn)); } catch (SettingsException e) { Ln.e("Could not restore \"stay_on_while_plugged_in\"", e); } } if (Device.isScreenOn()) { if (powerOffScreen) { Ln.i("Power off screen"); Device.powerOffScreen(displayId); } else if (restoreNormalPowerMode) { Ln.i("Restoring normal power mode"); Device.setScreenPowerMode(Device.POWER_MODE_NORMAL); } } System.exit(0); } }
Genymobile/scrcpy
server/src/main/java/com/genymobile/scrcpy/CleanUp.java
112
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC 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.openqa.selenium; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.regex.Pattern; import org.openqa.selenium.internal.Require; /** * Mechanism used to locate elements within a document. In order to create your own locating * mechanisms, it is possible to subclass this class and override the protected methods as required, * though it is expected that all subclasses rely on the basic finding mechanisms provided through * static methods of this class: * * <pre><code> * public WebElement findElement(WebDriver driver) { * WebElement element = driver.findElement(By.id(getSelector())); * if (element == null) * element = driver.findElement(By.name(getSelector()); * return element; * } * </code></pre> */ public abstract class By { /** * @param id The value of the "id" attribute to search for. * @return A By which locates elements by the value of the "id" attribute. */ public static By id(String id) { return new ById(id); } /** * @param linkText The exact text to match against. * @return A By which locates A elements by the exact text it displays. */ public static By linkText(String linkText) { return new ByLinkText(linkText); } /** * @param partialLinkText The partial text to match against * @return a By which locates elements that contain the given link text. */ public static By partialLinkText(String partialLinkText) { return new ByPartialLinkText(partialLinkText); } /** * @param name The value of the "name" attribute to search for. * @return A By which locates elements by the value of the "name" attribute. */ public static By name(String name) { return new ByName(name); } /** * @param tagName The element's tag name. * @return A By which locates elements by their tag name. */ public static By tagName(String tagName) { return new ByTagName(tagName); } /** * @param xpathExpression The XPath to use. * @return A By which locates elements via XPath. */ public static By xpath(String xpathExpression) { return new ByXPath(xpathExpression); } /** * Find elements based on the value of the "class" attribute. Only one class name should be used. * If an element has multiple classes, please use {@link By#cssSelector(String)}. * * @param className The value of the "class" attribute to search for. * @return A By which locates elements by the value of the "class" attribute. */ public static By className(String className) { return new ByClassName(className); } /** * Find elements via the driver's underlying W3C Selector engine. If the browser does not * implement the Selector API, the best effort is made to emulate the API. In this case, we strive * for at least CSS2 support, but offer no guarantees. * * @param cssSelector CSS expression. * @return A By which locates elements by CSS. */ public static By cssSelector(String cssSelector) { return new ByCssSelector(cssSelector); } /** * Find a single element. Override this method if necessary. * * @param context A context to use to find the element. * @return The WebElement that matches the selector. */ public WebElement findElement(SearchContext context) { List<WebElement> allElements = findElements(context); if (allElements == null || allElements.isEmpty()) { throw new NoSuchElementException("Cannot locate an element using " + toString()); } return allElements.get(0); } /** * Find many elements. * * @param context A context to use to find the elements. * @return A list of WebElements matching the selector. */ public abstract List<WebElement> findElements(SearchContext context); protected WebDriver getWebDriver(SearchContext context) { if (context instanceof WebDriver) { return (WebDriver) context; } if (!(context instanceof WrapsDriver)) { throw new IllegalArgumentException("Context does not wrap a webdriver: " + context); } return ((WrapsDriver) context).getWrappedDriver(); } protected JavascriptExecutor getJavascriptExecutor(SearchContext context) { WebDriver driver = getWebDriver(context); if (!(context instanceof JavascriptExecutor)) { throw new IllegalArgumentException( "Context does not provide a mechanism to execute JS: " + context); } return (JavascriptExecutor) driver; } @Override public boolean equals(Object o) { if (!(o instanceof By)) { return false; } By that = (By) o; return this.toString().equals(that.toString()); } @Override public int hashCode() { return toString().hashCode(); } @Override public String toString() { // A stub to prevent endless recursion in hashCode() return "[unknown locator]"; } public static class ById extends PreW3CLocator { private final String id; public ById(String id) { super( "id", Require.argument("Id", id).nonNull("Cannot find elements when id is null."), "#%s"); this.id = id; } @Override public String toString() { return "By.id: " + id; } } public static class ByLinkText extends BaseW3CLocator { private final String linkText; public ByLinkText(String linkText) { super( "link text", Require.argument("Link text", linkText) .nonNull("Cannot find elements when the link text is null.")); this.linkText = linkText; } @Override public String toString() { return "By.linkText: " + linkText; } } public static class ByPartialLinkText extends BaseW3CLocator { private final String partialLinkText; public ByPartialLinkText(String partialLinkText) { super( "partial link text", Require.argument("Partial link text", partialLinkText) .nonNull("Cannot find elements when the link text is null.")); this.partialLinkText = partialLinkText; } @Override public String toString() { return "By.partialLinkText: " + partialLinkText; } } public static class ByName extends PreW3CLocator { private final String name; public ByName(String name) { super( "name", Require.argument("Name", name).nonNull("Cannot find elements when name text is null."), String.format("*[name='%s']", name.replace("'", "\\'"))); this.name = name; } @Override public String toString() { return "By.name: " + name; } } public static class ByTagName extends BaseW3CLocator { private final String tagName; public ByTagName(String tagName) { super( "tag name", Require.argument("Tag name", tagName) .nonNull("Cannot find elements when the tag name is null.")); if (tagName.isEmpty()) { throw new InvalidSelectorException("Tag name must not be blank"); } this.tagName = tagName; } @Override public String toString() { return "By.tagName: " + tagName; } } public static class ByXPath extends BaseW3CLocator { private final String xpathExpression; public ByXPath(String xpathExpression) { super( "xpath", Require.argument("XPath", xpathExpression) .nonNull("Cannot find elements when the XPath is null.")); this.xpathExpression = xpathExpression; } @Override public String toString() { return "By.xpath: " + xpathExpression; } } public static class ByClassName extends PreW3CLocator { private final String className; public ByClassName(String className) { super( "class name", Require.argument("Class name", className) .nonNull("Cannot find elements when the class name expression is null."), ".%s"); if (className.matches(".*\\s.*")) { throw new InvalidSelectorException("Compound class names not permitted"); } this.className = className; } @Override public String toString() { return "By.className: " + className; } } public static class ByCssSelector extends BaseW3CLocator { private final String cssSelector; public ByCssSelector(String cssSelector) { super( "css selector", Require.argument("CSS selector", cssSelector) .nonNull("Cannot find elements when the selector is null")); this.cssSelector = cssSelector; } @Override public String toString() { return "By.cssSelector: " + cssSelector; } } public interface Remotable { Parameters getRemoteParameters(); class Parameters { private final String using; private final Object value; public Parameters(String using, Object value) { this.using = Require.nonNull("Search mechanism", using); // There may be subclasses where the value is optional. Allow for this. this.value = value; } public String using() { return using; } public Object value() { return value; } @Override public String toString() { return "[" + using + ": " + value + "]"; } @Override public boolean equals(Object o) { if (!(o instanceof Parameters)) { return false; } Parameters that = (Parameters) o; return using.equals(that.using) && Objects.equals(value, that.value); } @Override public int hashCode() { return Objects.hash(using, value); } private Map<String, Object> toJson() { Map<String, Object> params = new HashMap<>(); params.put("using", using); params.put("value", value); return Collections.unmodifiableMap(params); } } } private abstract static class BaseW3CLocator extends By implements Remotable { private final Parameters params; protected BaseW3CLocator(String using, String value) { this.params = new Parameters(using, value); } @Override public WebElement findElement(SearchContext context) { Require.nonNull("Search Context", context); return context.findElement(this); } @Override public List<WebElement> findElements(SearchContext context) { Require.nonNull("Search Context", context); return context.findElements(this); } @Override public final Parameters getRemoteParameters() { return params; } protected final Map<String, Object> toJson() { return getRemoteParameters().toJson(); } } private abstract static class PreW3CLocator extends By implements Remotable { private static final Pattern CSS_ESCAPE = Pattern.compile("([\\s'\"\\\\#.:;,!?+<>=~*^$|%&@`{}\\-\\/\\[\\]\\(\\)])"); private final Parameters remoteParams; private final ByCssSelector fallback; private PreW3CLocator(String using, String value, String formatString) { this.remoteParams = new Remotable.Parameters(using, value); this.fallback = new ByCssSelector(String.format(formatString, cssEscape(value))); } @Override public WebElement findElement(SearchContext context) { return context.findElement(fallback); } @Override public List<WebElement> findElements(SearchContext context) { return context.findElements(fallback); } @Override public final Parameters getRemoteParameters() { return remoteParams; } protected final Map<String, Object> toJson() { return fallback.toJson(); } private String cssEscape(String using) { using = CSS_ESCAPE.matcher(using).replaceAll("\\\\$1"); if (!using.isEmpty() && Character.isDigit(using.charAt(0))) { using = "\\" + (30 + Integer.parseInt(using.substring(0, 1))) + " " + using.substring(1); } return using; } } }
SeleniumHQ/selenium
java/src/org/openqa/selenium/By.java
113
/** * File: TreeNode.java * Created Time: 2022-11-25 * Author: krahets (krahets@163.com) */ package utils; import java.util.*; /* Binary tree node class */ public class TreeNode { public int val; // Node value public int height; // Node height public TreeNode left; // Reference to the left child node public TreeNode right; // Reference to the right child node /* Constructor */ public TreeNode(int x) { val = x; } // For serialization encoding rules, refer to: // https://www.hello-algo.com/chapter_tree/array_representation_of_tree/ // Array representation of the binary tree: // [1, 2, 3, 4, None, 6, 7, 8, 9, None, None, 12, None, None, 15] // Linked list representation of the binary tree: // /——— 15 // /——— 7 // /——— 3 // | \——— 6 // | \——— 12 // ——— 1 // \——— 2 // | /——— 9 // \——— 4 // \——— 8 /* Deserialize a list into a binary tree: Recursively */ private static TreeNode listToTreeDFS(List<Integer> arr, int i) { if (i < 0 || i >= arr.size() || arr.get(i) == null) { return null; } TreeNode root = new TreeNode(arr.get(i)); root.left = listToTreeDFS(arr, 2 * i + 1); root.right = listToTreeDFS(arr, 2 * i + 2); return root; } /* Deserialize a list into a binary tree */ public static TreeNode listToTree(List<Integer> arr) { return listToTreeDFS(arr, 0); } /* Serialize a binary tree into a list: Recursively */ private static void treeToListDFS(TreeNode root, int i, List<Integer> res) { if (root == null) return; while (i >= res.size()) { res.add(null); } res.set(i, root.val); treeToListDFS(root.left, 2 * i + 1, res); treeToListDFS(root.right, 2 * i + 2, res); } /* Serialize a binary tree into a list */ public static List<Integer> treeToList(TreeNode root) { List<Integer> res = new ArrayList<>(); treeToListDFS(root, 0, res); return res; } }
krahets/hello-algo
en/codes/java/utils/TreeNode.java
114
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd package com.google.protobuf.osgi; import aQute.bnd.osgi.Analyzer; import aQute.bnd.osgi.Jar; import java.io.File; import java.util.Arrays; import java.util.concurrent.Callable; import java.util.jar.Manifest; import java.util.stream.Collectors; import picocli.CommandLine; import picocli.CommandLine.Command; import picocli.CommandLine.Option; /** Java binary that runs bndlib to analyze a jar file to generate OSGi bundle manifest. */ @Command(name = "osgi_wrapper") public final class OsgiWrapper implements Callable<Integer> { private static final String REMOVEHEADERS = Arrays.stream( new String[] { "Embed-Dependency", "Embed-Transitive", "Built-By", // "Tool", "Created-By", // "Build-Jdk", "Originally-Created-By", "Archiver-Version", "Include-Resource", "Private-Package", "Ignore-Package", // "Bnd-LastModified", "Target-Label" }) .collect(Collectors.joining(",")); @Option( names = {"--input_jar"}, description = "The jar file to wrap with OSGi metadata") private File inputJar; @Option( names = {"--output_jar"}, description = "Output path to the wrapped jar") private File outputJar; @Option( names = {"--classpath"}, description = "The classpath that contains dependencies of the input jar, separated with :") private String classpath; @Option( names = {"--automatic_module_name"}, description = "The automatic module name of the bundle") private String automaticModuleName; @Option( names = {"--bundle_copyright"}, description = "Copyright string for the bundle") private String bundleCopyright; @Option( names = {"--bundle_description"}, description = "Description of the bundle") private String bundleDescription; @Option( names = {"--bundle_doc_url"}, description = "Documentation URL for the bundle") private String bundleDocUrl; @Option( names = {"--bundle_license"}, description = "URL for the license of the bundle") private String bundleLicense; @Option( names = {"--bundle_name"}, description = "The name of the bundle") private String bundleName; @Option( names = {"--bundle_symbolic_name"}, description = "The symbolic name of the bundle") private String bundleSymbolicName; @Option( names = {"--bundle_version"}, description = "The version of the bundle") private String bundleVersion; @Option( names = {"--export_package"}, description = "The exported packages from this bundle") private String exportPackage; @Option( names = {"--import_package"}, description = "The imported packages from this bundle") private String importPackage; @Override public Integer call() throws Exception { Jar bin = new Jar(inputJar); Analyzer analyzer = new Analyzer(); analyzer.setJar(bin); analyzer.setProperty(Analyzer.AUTOMATIC_MODULE_NAME, automaticModuleName); analyzer.setProperty(Analyzer.BUNDLE_NAME, bundleName); analyzer.setProperty(Analyzer.BUNDLE_SYMBOLICNAME, bundleSymbolicName); analyzer.setProperty(Analyzer.BUNDLE_VERSION, bundleVersion); analyzer.setProperty(Analyzer.IMPORT_PACKAGE, importPackage); analyzer.setProperty(Analyzer.EXPORT_PACKAGE, exportPackage); analyzer.setProperty(Analyzer.BUNDLE_DESCRIPTION, bundleDescription); analyzer.setProperty(Analyzer.BUNDLE_COPYRIGHT, bundleCopyright); analyzer.setProperty(Analyzer.BUNDLE_DOCURL, bundleDocUrl); analyzer.setProperty(Analyzer.BUNDLE_LICENSE, bundleLicense); analyzer.setProperty(Analyzer.REMOVEHEADERS, REMOVEHEADERS); if (classpath != null) { for (String dep : Arrays.asList(classpath.split(":"))) { analyzer.addClasspath(new File(dep)); } } analyzer.analyze(); Manifest manifest = analyzer.calcManifest(); if (analyzer.isOk()) { analyzer.getJar().setManifest(manifest); if (analyzer.save(outputJar, true)) { return 0; } } return 1; } public static void main(String[] args) { int exitCode = new CommandLine(new OsgiWrapper()).execute(args); System.exit(exitCode); } }
protocolbuffers/protobuf
java/osgi/OsgiWrapper.java
115
class Solution { public int numJewelsInStones(String J, String S) { Set<Character> Jset = new HashSet(); for (char j: J.toCharArray()) Jset.add(j); int ans = 0; for (char s: S.toCharArray()) if (Jset.contains(s)) ans++; return ans; } }
MisterBooo/LeetCodeAnimation
0771-Jewels-Stones/Code/1.java
116
import java.io.*; import java.lang.Integer.*; import java.util.*; import java.util.stream.*; import java.lang.StringBuilder; import java.util.concurrent.CountDownLatch; //////////////////////////////// Solve Sudoku Puzzles //////////////////////////////// //////////////////////////////// See http://norvig.com/CQ //////////////////////////////// //////////////////////////////// @author Peter Norvig //////////////////////////////// /** There are two representations of puzzles that we will use: ** 1. A gridstring is 81 chars, with characters '0' or '.' for blank and '1' to '9' for digits. ** 2. A puzzle grid is an int[81] with a digit d (1-9) represented by the integer (1 << (d - 1)); ** that is, a bit pattern that has a single 1 bit representing the digit. ** A blank is represented by the OR of all the digits 1-9, meaning that any digit is possible. ** While solving the puzzle, some of these digits are eliminated, leaving fewer possibilities. ** The puzzle is solved when every square has only a single possibility. ** ** Search for a solution with `search`: ** - Fill an empty square with a guessed digit and do constraint propagation. ** - If the guess is consistent, search deeper; if not, try a different guess for the square. ** - If all guesses fail, back up to the previous level. ** - In selecting an empty square, we pick one that has the minimum number of possible digits. ** - To be able to back up, we need to keep the grid from the previous recursive level. ** But we only need to keep one grid for each level, so to save garbage collection, ** we pre-allocate one grid per level (there are 81 levels) in a `gridpool`. ** Do constraint propagation with `arcConsistent`, `dualConsistent`, and `nakedPairs`. **/ public class Sudoku { //////////////////////////////// main; command line options ////////////////////////////// static final String usage = String.join("\n", "usage: java Sudoku -help | -(no)[fptgadnsrv] | -[RT]<number> | <filename> ...", "E.g., -v turns verify flag on, -nov turns it off. -R and -T require a number. The args are:\n", " -h(elp) Print this usage message", " -f(ile) Print summary stats for each file (default on)", " -p(uzzle) Print summary stats for each puzzle (default off)", " -t(hread) Print summary stats for each thread (default off)", " -g(rid) Print each puzzle grid and solution grid (default off)", " -a(rc) Run arc consistency (default on)", " -d(ual) Run dual consistency (default on)", " -n(aked) Run naked pairs (default on)", " -s(earch) Run search (default on, but some puzzles can be solved with CSP methods alone)", " -r(everse) Solve the reverse of each puzzle as well as each puzzle itself (default off)", " -v(erify) Verify each solution is valid (default off)", " -T<number> Concurrently run <number> threads (default 26)", " -R<number> Repeat each puzzle <number> times (default 1)", " <filename> Solve all puzzles in filename, which has one puzzle per line"); boolean printFileStats = true; // -f boolean printPuzzleStats = false; // -p boolean printThreadStats = false; // -t boolean printGrid = false; // -g boolean runArcCons = true; // -a boolean runDualCons = true; // -d boolean runNakedPairs = true; // -n boolean runSearch = true; // -s boolean reversePuzzle = false; // -r boolean verifySolution = false; // -v int nThreads = 26; // -T int repeat = 1; // -R /** Parse command line args and solve puzzles in files. **/ public static void main(String[] args) throws IOException { Sudoku s = new Sudoku(); for (String arg: args) { if (!arg.startsWith("-")) { s.solveFile(arg); } else { boolean value = !arg.startsWith("-no"); switch(arg.charAt(value ? 1 : 3)) { case 'h': if (value) { System.out.println(usage); } break; case 'f': s.printFileStats = value; break; case 'p': s.printPuzzleStats = value; break; case 't': s.printThreadStats = value; break; case 'a': s.runArcCons = value; break; case 'g': s.printGrid = value; break; case 'd': s.runDualCons = value; break; case 's': s.runSearch = value; break; case 'n': s.runNakedPairs = value; break; case 'r': s.reversePuzzle = value; break; case 'v': s.verifySolution = value; break; case 'T': s.nThreads = Integer.parseInt(arg.substring(2)); break; case 'R': s.repeat = Integer.parseInt(arg.substring(2)); break; default: System.out.println("Unrecognized option: " + arg + "\n" + usage); } } } } //////////////////////////////// Handling Lists of Puzzles //////////////////////////////// /** Solve all the puzzles in a file. Report timing statistics. **/ void solveFile(String filename) throws IOException { List<int[]> grids = readFile(filename); long startTime = System.nanoTime(); switch(nThreads) { case 1: solveList(grids); break; default: solveListThreaded(grids, nThreads); break; } if (printFileStats) printStats(grids.size() * repeat, startTime, filename); } /** Solve a list of puzzles in a single thread. ** repeat -R<number> times; print each puzzle's stats if -p; print grid if -g; verify if -v. **/ void solveList(List<int[]> grids) { int[] puzzle = new int[N * N]; // Used to save a copy of the original grid int[][] gridpool = new int[N * N][N * N]; // Reuse grids during the search for (int g=0; g<grids.size(); ++g) { int grid[] = grids.get(g); System.arraycopy(grid, 0, puzzle, 0, grid.length); for (int i = 0; i < repeat; ++i) { long startTime = printPuzzleStats ? System.nanoTime() : 0; int[] solution = initialize(grid); // All the real work is if (runSearch) search(solution, gridpool, 0); // on these 2 lines. if (printPuzzleStats) { printStats(1, startTime, "Puzzle " + (g + 1)); } if (i == 0 && (printGrid || (verifySolution && !isSolution(solution, puzzle)))) { printGrids("Puzzle " + (g + 1), grid, solution); } } } } /** Break a list of puzzles into nThreads sublists and solve each sublist in a separate thread. **/ void solveListThreaded(List<int[]> grids, int nThreads) { try { final long startTime = System.nanoTime(); int nGrids = grids.size(); final CountDownLatch latch = new CountDownLatch(nThreads); int size = nGrids / nThreads; for (int c = 0; c < nThreads; ++c) { final List<int[]> sublist = grids.subList(c * size, c == nThreads - 1 ? nGrids : (c + 1) * size); new Thread() { public void run() { solveList(sublist); latch.countDown(); if (printThreadStats) { printStats(repeat * sublist.size(), startTime, "Thread"); } } }.start(); } latch.await(); // Wait for all threads to finish } catch (InterruptedException e) { System.err.println("And you may ask yourself, 'Well, how did I get here?'"); } } //////////////////////////////// Utility functions //////////////////////////////// /** Return an array of ints {0, 1, ..., n-1} **/ int[] range(int n) { int[] result = new int[n]; for (int i = 0; i<n; ++i) { result[i] = i; } return result; } /** Return an array of all squares in the intersection of these rows and cols **/ int[] cross(int[] rows, int[] cols) { int[] result = new int[rows.length * cols.length]; int i = 0; for (int r: rows) { for (int c: cols) { result[i++] = N * r + c; } } return result; } /** Return true iff item is an element of array, or array[0:end]. **/ boolean member(int item, int[] array) { return member(item, array, array.length); } boolean member(int item, int[] array, int end) { for (int i = 0; i<end; ++i) { if (array[i] == item) { return true; } } return false; } //////////////////////////////// Constants //////////////////////////////// final int N = 9; // Number of cells on a side of grid. final int[] DIGITS = {1<< 0, 1<< 1, 1<< 2, 1<< 3, 1<< 4, 1<< 5, 1<< 6, 1<< 7, 1<< 8}; final int ALL_DIGITS = Integer.parseInt("111111111", 2); final int[] ROWS = range(N); final int[] COLS = ROWS; final int[] SQUARES = range(N * N); final int[][] BLOCKS = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}}; final int[][] ALL_UNITS = new int[3 * N][]; final int[][][] UNITS = new int[N * N][3][N]; final int[][] PEERS = new int[N * N][20]; final int[] NUM_DIGITS = new int[ALL_DIGITS + 1]; final int[] HIGHEST_DIGIT = new int[ALL_DIGITS + 1]; { // Initialize ALL_UNITS to be an array of the 27 units: rows, columns, and blocks int i = 0; for (int r: ROWS) {ALL_UNITS[i++] = cross(new int[] {r}, COLS); } for (int c: COLS) {ALL_UNITS[i++] = cross(ROWS, new int[] {c}); } for (int[] rb: BLOCKS) {for (int[] cb: BLOCKS) {ALL_UNITS[i++] = cross(rb, cb); } } // Initialize each UNITS[s] to be an array of the 3 units for square s. for (int s: SQUARES) { i = 0; for (int[] u: ALL_UNITS) { if (member(s, u)) UNITS[s][i++] = u; } } // Initialize each PEERS[s] to be an array of the 20 squares that are peers of square s. for (int s: SQUARES) { i = 0; for (int[] u: UNITS[s]) { for (int s2: u) { if (s2 != s && !member(s2, PEERS[s], i)) { PEERS[s][i++] = s2; } } } } // Initialize NUM_DIGITS[val] to be the number of 1 bits in the bitset val // and HIGHEST_DIGIT[val] to the highest bit set in the bitset val for (int val = 0; val <= ALL_DIGITS; val++) { NUM_DIGITS[val] = Integer.bitCount(val); HIGHEST_DIGIT[val] = Integer.highestOneBit(val); } } //////////////////////////////// Search algorithm //////////////////////////////// /** Search for a solution to grid. If there is an unfilled square, select one ** and try--that is, search recursively--every possible digit for the square. **/ int[] search(int[] grid, int[][] gridpool, int level) { if (grid == null) { return null; } int s = select_square(grid); if (s == -1) { return grid; // No squares to select means we are done! } for (int d: DIGITS) { // For each possible digit d that could fill square s, try it if ((d & grid[s]) > 0) { // Copy grid's contents into the gridpool to be used at the next level System.arraycopy(grid, 0, gridpool[level], 0, grid.length); int[] result = search(assign(gridpool[level], s, d), gridpool, level + 1); if (result != null) { return result; } } } return null; } /** Check if grid is a solution to the puzzle. **/ boolean isSolution(int[] grid, int[] puzzle) { if (grid == null) { return false; } // Check that all squares have a single digit, and // no filled square in the puzzle was changed in the solution. for (int s: SQUARES) { if (NUM_DIGITS[grid[s]] != 1 || (NUM_DIGITS[puzzle[s]] == 1 && grid[s] != puzzle[s])) return false; } // Check that each unit is a permutation of digits for (int[] u: ALL_UNITS) { if (IntStream.of(u).sum() != ALL_DIGITS) return false; } return true; } /** Choose an unfilled square with the minimum number of possible values. ** If all squares are filled, return -1 (which means the puzzle is complete). **/ int select_square(int[] grid) { int square = -1; int min = N + 1; for (int s: SQUARES) { int c = NUM_DIGITS[grid[s]]; if (c == 2) { return s; // Can't get fewer than 2 possible digits } else if (c > 1 && c < min) { square = s; min = c; } } return square; } /** Assign grid[s] = d. If this leads to contradiction, return null. **/ int[] assign(int[] grid, int s, int d) { if ((grid == null) || ((grid[s] & d) == 0)) { return null; } // d not possible for grid[s] grid[s] = d; for (int p: PEERS[s]) { if (!eliminate(grid, p, d)) { // If we can't eliminate d from all peers of s, then fail return null; } } return grid; } /** Remove digit d from possibilities for grid[s]. ** Run the 3 constraint propagation routines (unless a command line flag says not to). ** If constraint propagation detects a contradiction return false. **/ boolean eliminate(int[] grid, int s, int d) { if ((grid[s] & d) == 0) { return true; } // d already eliminated from grid[s] grid[s] -= d; return ((!runArcCons || arc_consistent(grid, s)) && (!runDualCons || dual_consistent(grid, s, d)) && (!runNakedPairs || naked_pairs(grid, s))); } //////////////////////////////// Constraint Propagation //////////////////////////////// /** Check if square s is ok: that is, it has multiple possible values, or it has ** one possible value which we can consistently assign. **/ boolean arc_consistent(int[] grid, int s) { int c = NUM_DIGITS[grid[s]]; return c >= 2 || (c == 1 && (assign(grid, s, grid[s]) != null)); } /** After we eliminate d from possibilities for grid[s], check each unit of s ** and make sure there is some position in the unit where d can go. ** If there is only one possible place for d, assign it. **/ boolean dual_consistent(int[] grid, int s, int d) { for (int[] u: UNITS[s]) { int dPlaces = 0; // The number of possible places for d within unit u int dplace = -1; // Try to find a place in the unit where d can go for (int s2: u) { if ((grid[s2] & d) > 0) { // s2 is a possible place for d dPlaces++; if (dPlaces > 1) break; dplace = s2; } } if (dPlaces == 0 || (dPlaces == 1 && (assign(grid, dplace, d) == null))) { return false; } } return true; } /** Look for two squares in a unit with the same two possible values, and no other values. ** For example, if s and s2 both have the possible values 8|9, then we know that 8 and 9 ** must go in those two squares. We don't know which is which, but we can eliminate ** 8 and 9 from any other square s3 that is in the unit. **/ boolean naked_pairs(int[] grid, int s) { int val = grid[s]; if (NUM_DIGITS[val] != 2) { return true; } // Doesn't apply for (int s2: PEERS[s]) { if (grid[s2] == val) { // s and s2 are a naked pair; find what unit(s) they share for (int[] u: UNITS[s]) { if (member(s2, u)) { for (int s3: u) { // s3 can't have either of the values in val (e.g. 8|9) if (s3 != s && s3 != s2) { int d = HIGHEST_DIGIT[val]; int d2 = val - d; if (!eliminate(grid, s3, d) || !eliminate(grid, s3, d2)) { return false; } } } } } } } return true; } //////////////////////////////// Input //////////////////////////////// /** The method `readFile` reads one puzzle per file line and returns a List of puzzle grids. **/ List<int[]> readFile(String filename) throws IOException { BufferedReader in = new BufferedReader(new FileReader(filename)); List<int[]> grids = new ArrayList<int[]>(260000); String gridstring; while ((gridstring = in.readLine()) != null) { grids.add(parseGrid(gridstring)); if (reversePuzzle) { grids.add(parseGrid(new StringBuilder(gridstring).reverse().toString())); } } return grids; } /** Parse a gridstring into a puzzle grid: an int[] with values 0-9. **/ int[] parseGrid(String gridstring) { int[] grid = new int[N * N]; int s = 0; for (int i = 0; i<gridstring.length(); ++i) { char c = gridstring.charAt(i); if ('1' <= c && c <= '9') { grid[s++] = DIGITS[c - '1']; // A single-bit set to represent a digit } else if (c == '0' || c == '.') { grid[s++] = ALL_DIGITS; // Any digit is possible } } assert s == N * N; return grid; } /** Initialize a grid from a puzzle. ** First initialize every square in the new grid to ALL_DIGITS, meaning any value is possible. ** Then, call `assign` on the puzzle's filled squares to initiate constraint propagation. **/ int[] initialize(int[] puzzle) { int[] grid = new int[N * N]; for (int s: SQUARES) { grid[s] = ALL_DIGITS; } for (int s: SQUARES) { if (puzzle[s] != ALL_DIGITS) { assign(grid, s, puzzle[s]); } } return grid; } //////////////////////////////// Output //////////////////////////////// boolean headerPrinted = false; /** Print stats on puzzles solved, average time, frequency, threads used, and name. **/ void printStats(int nGrids, long startTime, String name) { double usecs = (System.nanoTime() - startTime) / 1000.; String line = String.format("%7d %8.1f %7.3f %7d %s", nGrids, usecs / nGrids, 1000 * nGrids / usecs, nThreads, name); synchronized (this) { // So that printing from different threads doesn't get garbled if (!headerPrinted) { System.out.println("Puzzles Avg μsec KHz Threads Name\n" + "======= ======== ======= ======= ===="); headerPrinted = true; } System.out.println(line); } } /** Print the original puzzle grid and the solution grid. **/ void printGrids(String name, int[] puzzle, int[] solution) { String bar = "------+-------+------"; String gap = " "; // Space between the puzzle grid and solution grid if (solution == null) solution = new int[N * N]; synchronized (this) { // So that printing from different threads doesn't get garbled System.out.format("\n%-22s%s%s\n", name + ":", gap, (isSolution(solution, puzzle) ? "Solution:" : "FAILED:")); for (int r = 0; r < N; ++r) { System.out.println(rowString(puzzle, r) + gap + rowString(solution, r)); if (r == 2 || r == 5) System.out.println(bar + gap + bar); } } } /** Return a String representing a row of this puzzle. **/ String rowString(int[] grid, int r) { String row = ""; for (int s = r * 9; s < (r + 1) * 9; ++s) { row += (char) ((NUM_DIGITS[grid[s]] != 1) ? '.' : ('1' + Integer.numberOfTrailingZeros(grid[s]))); row += (s % 9 == 2 || s % 9 == 5 ? " | " : " "); } return row; } }
norvig/pytudes
py/Sudoku.java
117
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch; import org.elasticsearch.core.Assertions; import org.elasticsearch.core.UpdateForV9; import java.lang.reflect.Field; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.NavigableMap; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import java.util.function.IntFunction; /** * <p>Transport version is used to coordinate compatible wire protocol communication between nodes, at a fine-grained level. This replaces * and supersedes the old Version constants.</p> * * <p>Before adding a new version constant, please read the block comment at the end of the list of constants.</p> */ public class TransportVersions { /* * NOTE: IntelliJ lies! * This map is used during class construction, referenced by the registerTransportVersion method. * When all the transport version constants have been registered, the map is cleared & never touched again. */ static TreeSet<Integer> IDS = new TreeSet<>(); static TransportVersion def(int id) { if (IDS == null) throw new IllegalStateException("The IDS map needs to be present to call this method"); if (IDS.add(id) == false) { throw new IllegalArgumentException("Version id " + id + " defined twice"); } if (id < IDS.last()) { throw new IllegalArgumentException("Version id " + id + " is not defined in the right location. Keep constants sorted"); } return new TransportVersion(id); } @UpdateForV9 // remove the transport versions with which v9 will not need to interact public static final TransportVersion ZERO = def(0); public static final TransportVersion V_7_0_0 = def(7_00_00_99); public static final TransportVersion V_7_0_1 = def(7_00_01_99); public static final TransportVersion V_7_1_0 = def(7_01_00_99); public static final TransportVersion V_7_2_0 = def(7_02_00_99); public static final TransportVersion V_7_2_1 = def(7_02_01_99); public static final TransportVersion V_7_3_0 = def(7_03_00_99); public static final TransportVersion V_7_3_2 = def(7_03_02_99); public static final TransportVersion V_7_4_0 = def(7_04_00_99); public static final TransportVersion V_7_5_0 = def(7_05_00_99); public static final TransportVersion V_7_6_0 = def(7_06_00_99); public static final TransportVersion V_7_7_0 = def(7_07_00_99); public static final TransportVersion V_7_8_0 = def(7_08_00_99); public static final TransportVersion V_7_8_1 = def(7_08_01_99); public static final TransportVersion V_7_9_0 = def(7_09_00_99); public static final TransportVersion V_7_10_0 = def(7_10_00_99); public static final TransportVersion V_7_10_1 = def(7_10_01_99); public static final TransportVersion V_7_11_0 = def(7_11_00_99); public static final TransportVersion V_7_12_0 = def(7_12_00_99); public static final TransportVersion V_7_13_0 = def(7_13_00_99); public static final TransportVersion V_7_14_0 = def(7_14_00_99); public static final TransportVersion V_7_15_0 = def(7_15_00_99); public static final TransportVersion V_7_15_1 = def(7_15_01_99); public static final TransportVersion V_7_16_0 = def(7_16_00_99); public static final TransportVersion V_7_17_0 = def(7_17_00_99); public static final TransportVersion V_7_17_1 = def(7_17_01_99); public static final TransportVersion V_7_17_8 = def(7_17_08_99); public static final TransportVersion V_8_0_0 = def(8_00_00_99); public static final TransportVersion V_8_1_0 = def(8_01_00_99); public static final TransportVersion V_8_2_0 = def(8_02_00_99); public static final TransportVersion V_8_3_0 = def(8_03_00_99); public static final TransportVersion V_8_4_0 = def(8_04_00_99); public static final TransportVersion V_8_5_0 = def(8_05_00_99); public static final TransportVersion V_8_6_0 = def(8_06_00_99); public static final TransportVersion V_8_6_1 = def(8_06_01_99); public static final TransportVersion V_8_7_0 = def(8_07_00_99); public static final TransportVersion V_8_7_1 = def(8_07_01_99); public static final TransportVersion V_8_8_0 = def(8_08_00_99); public static final TransportVersion V_8_8_1 = def(8_08_01_99); /* * READ THE COMMENT BELOW THIS BLOCK OF DECLARATIONS BEFORE ADDING NEW TRANSPORT VERSIONS * Detached transport versions added below here. */ public static final TransportVersion V_8_9_X = def(8_500_020); public static final TransportVersion V_8_10_X = def(8_500_061); public static final TransportVersion V_8_11_X = def(8_512_00_1); public static final TransportVersion V_8_12_0 = def(8_560_00_0); public static final TransportVersion V_8_12_1 = def(8_560_00_1); public static final TransportVersion V_8_13_0 = def(8_595_00_0); public static final TransportVersion V_8_13_4 = def(8_595_00_1); // 8.14.0+ public static final TransportVersion RANDOM_AGG_SHARD_SEED = def(8_596_00_0); public static final TransportVersion ESQL_TIMINGS = def(8_597_00_0); public static final TransportVersion DATA_STREAM_AUTO_SHARDING_EVENT = def(8_598_00_0); public static final TransportVersion ADD_FAILURE_STORE_INDICES_OPTIONS = def(8_599_00_0); public static final TransportVersion ESQL_ENRICH_OPERATOR_STATUS = def(8_600_00_0); public static final TransportVersion ESQL_SERIALIZE_ARRAY_VECTOR = def(8_601_00_0); public static final TransportVersion ESQL_SERIALIZE_ARRAY_BLOCK = def(8_602_00_0); public static final TransportVersion ADD_DATA_STREAM_GLOBAL_RETENTION = def(8_603_00_0); public static final TransportVersion ALLOCATION_STATS = def(8_604_00_0); public static final TransportVersion ESQL_EXTENDED_ENRICH_TYPES = def(8_605_00_0); public static final TransportVersion KNN_EXPLICIT_BYTE_QUERY_VECTOR_PARSING = def(8_606_00_0); public static final TransportVersion ESQL_EXTENDED_ENRICH_INPUT_TYPE = def(8_607_00_0); public static final TransportVersion ESQL_SERIALIZE_BIG_VECTOR = def(8_608_00_0); public static final TransportVersion AGGS_EXCLUDED_DELETED_DOCS = def(8_609_00_0); public static final TransportVersion ESQL_SERIALIZE_BIG_ARRAY = def(8_610_00_0); public static final TransportVersion AUTO_SHARDING_ROLLOVER_CONDITION = def(8_611_00_0); public static final TransportVersion KNN_QUERY_VECTOR_BUILDER = def(8_612_00_0); public static final TransportVersion USE_DATA_STREAM_GLOBAL_RETENTION = def(8_613_00_0); public static final TransportVersion ML_COMPLETION_INFERENCE_SERVICE_ADDED = def(8_614_00_0); public static final TransportVersion ML_INFERENCE_EMBEDDING_BYTE_ADDED = def(8_615_00_0); public static final TransportVersion ML_INFERENCE_L2_NORM_SIMILARITY_ADDED = def(8_616_00_0); public static final TransportVersion SEARCH_NODE_LOAD_AUTOSCALING = def(8_617_00_0); public static final TransportVersion ESQL_ES_SOURCE_OPTIONS = def(8_618_00_0); public static final TransportVersion ADD_PERSISTENT_TASK_EXCEPTIONS = def(8_619_00_0); public static final TransportVersion ESQL_REDUCER_NODE_FRAGMENT = def(8_620_00_0); public static final TransportVersion FAILURE_STORE_ROLLOVER = def(8_621_00_0); public static final TransportVersion CCR_STATS_API_TIMEOUT_PARAM = def(8_622_00_0); public static final TransportVersion ESQL_ORDINAL_BLOCK = def(8_623_00_0); public static final TransportVersion ML_INFERENCE_COHERE_RERANK = def(8_624_00_0); public static final TransportVersion INDEXING_PRESSURE_DOCUMENT_REJECTIONS_COUNT = def(8_625_00_0); public static final TransportVersion ALIAS_ACTION_RESULTS = def(8_626_00_0); public static final TransportVersion HISTOGRAM_AGGS_KEY_SORTED = def(8_627_00_0); public static final TransportVersion INFERENCE_FIELDS_METADATA = def(8_628_00_0); public static final TransportVersion ML_INFERENCE_TIMEOUT_ADDED = def(8_629_00_0); public static final TransportVersion MODIFY_DATA_STREAM_FAILURE_STORES = def(8_630_00_0); public static final TransportVersion ML_INFERENCE_RERANK_NEW_RESPONSE_FORMAT = def(8_631_00_0); public static final TransportVersion HIGHLIGHTERS_TAGS_ON_FIELD_LEVEL = def(8_632_00_0); public static final TransportVersion TRACK_FLUSH_TIME_EXCLUDING_WAITING_ON_LOCKS = def(8_633_00_0); public static final TransportVersion ML_INFERENCE_AZURE_OPENAI_EMBEDDINGS = def(8_634_00_0); public static final TransportVersion ILM_SHRINK_ENABLE_WRITE = def(8_635_00_0); public static final TransportVersion GEOIP_CACHE_STATS = def(8_636_00_0); public static final TransportVersion SHUTDOWN_REQUEST_TIMEOUTS_FIX_8_14 = def(8_636_00_1); public static final TransportVersion WATERMARK_THRESHOLDS_STATS = def(8_637_00_0); public static final TransportVersion ENRICH_CACHE_ADDITIONAL_STATS = def(8_638_00_0); public static final TransportVersion ML_INFERENCE_RATE_LIMIT_SETTINGS_ADDED = def(8_639_00_0); public static final TransportVersion ML_TRAINED_MODEL_CACHE_METADATA_ADDED = def(8_640_00_0); public static final TransportVersion TOP_LEVEL_KNN_SUPPORT_QUERY_NAME = def(8_641_00_0); public static final TransportVersion INDEX_SEGMENTS_VECTOR_FORMATS = def(8_642_00_0); public static final TransportVersion ADD_RESOURCE_ALREADY_UPLOADED_EXCEPTION = def(8_643_00_0); public static final TransportVersion ESQL_MV_ORDERING_SORTED_ASCENDING = def(8_644_00_0); public static final TransportVersion ESQL_PAGE_MAPPING_TO_ITERATOR = def(8_645_00_0); public static final TransportVersion BINARY_PIT_ID = def(8_646_00_0); public static final TransportVersion SECURITY_ROLE_MAPPINGS_IN_CLUSTER_STATE = def(8_647_00_0); public static final TransportVersion ESQL_REQUEST_TABLES = def(8_648_00_0); public static final TransportVersion ROLE_REMOTE_CLUSTER_PRIVS = def(8_649_00_0); public static final TransportVersion NO_GLOBAL_RETENTION_FOR_SYSTEM_DATA_STREAMS = def(8_650_00_0); public static final TransportVersion SHUTDOWN_REQUEST_TIMEOUTS_FIX = def(8_651_00_0); public static final TransportVersion INDEXING_PRESSURE_REQUEST_REJECTIONS_COUNT = def(8_652_00_0); public static final TransportVersion ROLLUP_USAGE = def(8_653_00_0); public static final TransportVersion SECURITY_ROLE_DESCRIPTION = def(8_654_00_0); public static final TransportVersion ML_INFERENCE_AZURE_OPENAI_COMPLETIONS = def(8_655_00_0); public static final TransportVersion JOIN_STATUS_AGE_SERIALIZATION = def(8_656_00_0); public static final TransportVersion ML_RERANK_DOC_OPTIONAL = def(8_657_00_0); public static final TransportVersion FAILURE_STORE_FIELD_PARITY = def(8_658_00_0); public static final TransportVersion ML_INFERENCE_AZURE_AI_STUDIO = def(8_659_00_0); public static final TransportVersion ML_INFERENCE_COHERE_COMPLETION_ADDED = def(8_660_00_0); public static final TransportVersion ESQL_REMOVE_ES_SOURCE_OPTIONS = def(8_661_00_0); public static final TransportVersion NODE_STATS_INGEST_BYTES = def(8_662_00_0); /* * STOP! READ THIS FIRST! No, really, * ____ _____ ___ ____ _ ____ _____ _ ____ _____ _ _ ___ ____ _____ ___ ____ ____ _____ _ * / ___|_ _/ _ \| _ \| | | _ \| ____| / \ | _ \ |_ _| | | |_ _/ ___| | ___|_ _| _ \/ ___|_ _| | * \___ \ | || | | | |_) | | | |_) | _| / _ \ | | | | | | | |_| || |\___ \ | |_ | || |_) \___ \ | | | | * ___) || || |_| | __/|_| | _ <| |___ / ___ \| |_| | | | | _ || | ___) | | _| | || _ < ___) || | |_| * |____/ |_| \___/|_| (_) |_| \_\_____/_/ \_\____/ |_| |_| |_|___|____/ |_| |___|_| \_\____/ |_| (_) * * A new transport version should be added EVERY TIME a change is made to the serialization protocol of one or more classes. Each * transport version should only be used in a single merged commit (apart from the BwC versions copied from o.e.Version, ≤V_8_8_1). * * ADDING A TRANSPORT VERSION * To add a new transport version, add a new constant at the bottom of the list, above this comment. Don't add other lines, * comments, etc. The version id has the following layout: * * M_NNN_SS_P * * M - The major version of Elasticsearch * NNN - The server version part * SS - The serverless version part. It should always be 00 here, it is used by serverless only. * P - The patch version part * * To determine the id of the next TransportVersion constant, do the following: * - Use the same major version, unless bumping majors * - Bump the server version part by 1, unless creating a patch version * - Leave the serverless part as 00 * - Bump the patch part if creating a patch version * * If a patch version is created, it should be placed sorted among the other existing constants. * * REVERTING A TRANSPORT VERSION * * If you revert a commit with a transport version change, you MUST ensure there is a NEW transport version representing the reverted * change. DO NOT let the transport version go backwards, it must ALWAYS be incremented. * * DETERMINING TRANSPORT VERSIONS FROM GIT HISTORY * * If your git checkout has the expected minor-version-numbered branches and the expected release-version tags then you can find the * transport versions known by a particular release ... * * git show v8.11.0:server/src/main/java/org/elasticsearch/TransportVersions.java | grep '= def' * * ... or by a particular branch ... * * git show 8.11:server/src/main/java/org/elasticsearch/TransportVersions.java | grep '= def' * * ... and you can see which versions were added in between two versions too ... * * git diff v8.11.0..main -- server/src/main/java/org/elasticsearch/TransportVersions.java * * In branches 8.7-8.10 see server/src/main/java/org/elasticsearch/TransportVersion.java for the equivalent definitions. */ /** * Reference to the earliest compatible transport version to this version of the codebase. * This should be the transport version used by the highest minor version of the previous major. */ public static final TransportVersion MINIMUM_COMPATIBLE = V_7_17_0; /** * Reference to the minimum transport version that can be used with CCS. * This should be the transport version used by the previous minor release. */ public static final TransportVersion MINIMUM_CCS_VERSION = V_8_13_0; static final NavigableMap<Integer, TransportVersion> VERSION_IDS = getAllVersionIds(TransportVersions.class); // the highest transport version constant defined in this file, used as a fallback for TransportVersion.current() static final TransportVersion LATEST_DEFINED; static { LATEST_DEFINED = VERSION_IDS.lastEntry().getValue(); // see comment on IDS field // now we're registered all the transport versions, we can clear the map IDS = null; } public static NavigableMap<Integer, TransportVersion> getAllVersionIds(Class<?> cls) { Map<Integer, String> versionIdFields = new HashMap<>(); NavigableMap<Integer, TransportVersion> builder = new TreeMap<>(); Set<String> ignore = Set.of("ZERO", "CURRENT", "MINIMUM_COMPATIBLE", "MINIMUM_CCS_VERSION"); for (Field declaredField : cls.getFields()) { if (declaredField.getType().equals(TransportVersion.class)) { String fieldName = declaredField.getName(); if (ignore.contains(fieldName)) { continue; } TransportVersion version; try { version = (TransportVersion) declaredField.get(null); } catch (IllegalAccessException e) { throw new AssertionError(e); } builder.put(version.id(), version); if (Assertions.ENABLED) { // check the version number is unique var sameVersionNumber = versionIdFields.put(version.id(), fieldName); assert sameVersionNumber == null : "Versions [" + sameVersionNumber + "] and [" + fieldName + "] have the same version number [" + version.id() + "]. Each TransportVersion should have a different version number"; } } } return Collections.unmodifiableNavigableMap(builder); } static Collection<TransportVersion> getAllVersions() { return VERSION_IDS.values(); } static final IntFunction<String> VERSION_LOOKUP = ReleaseVersions.generateVersionsLookup(TransportVersions.class); // no instance private TransportVersions() {} }
elastic/elasticsearch
server/src/main/java/org/elasticsearch/TransportVersions.java
118
///usr/bin/env jbang "$0" "$@" ; exit $? // Update the Quarkus version to what you want here or run jbang with // `-Dquarkus.version=<version>` to override it. //DEPS io.quarkus:quarkus-bom:${quarkus.version:2.4.0.Final}@pom //DEPS io.quarkus:quarkus-resteasy //JAVAC_OPTIONS -parameters //FILES META-INF/resources/index.html=index.html import javax.enterprise.context.ApplicationScoped; import javax.ws.rs.GET; import javax.ws.rs.Path; @Path("/hello") @ApplicationScoped public class jbangquarkus { @GET public String sayHello() { return "Hello from Quarkus with jbang.dev"; } }
eugenp/tutorials
jbang/jbangquarkus.java
119
/* * Copyright (c) 2016-present, RxJava Contributors. * * 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. */ module io.reactivex.rxjava3 { exports io.reactivex.rxjava3.annotations; exports io.reactivex.rxjava3.core; exports io.reactivex.rxjava3.disposables; exports io.reactivex.rxjava3.exceptions; exports io.reactivex.rxjava3.flowables; exports io.reactivex.rxjava3.functions; exports io.reactivex.rxjava3.observables; exports io.reactivex.rxjava3.observers; exports io.reactivex.rxjava3.operators; exports io.reactivex.rxjava3.parallel; exports io.reactivex.rxjava3.plugins; exports io.reactivex.rxjava3.processors; exports io.reactivex.rxjava3.schedulers; exports io.reactivex.rxjava3.subjects; exports io.reactivex.rxjava3.subscribers; requires transitive org.reactivestreams; }
ReactiveX/RxJava
src/main/module/module-info.java
120
/* * Copyright (C) 2011 The Guava 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 com.google.common.collect; import com.google.common.annotations.GwtIncompatible; import com.google.errorprone.annotations.DoNotMock; import java.util.NoSuchElementException; import java.util.Set; import javax.annotation.CheckForNull; /** * A set comprising zero or more {@linkplain Range#isEmpty nonempty}, {@linkplain * Range#isConnected(Range) disconnected} ranges of type {@code C}. * * <p>Implementations that choose to support the {@link #add(Range)} operation are required to * ignore empty ranges and coalesce connected ranges. For example: * * <pre>{@code * RangeSet<Integer> rangeSet = TreeRangeSet.create(); * rangeSet.add(Range.closed(1, 10)); // {[1, 10]} * rangeSet.add(Range.closedOpen(11, 15)); // disconnected range; {[1, 10], [11, 15)} * rangeSet.add(Range.closedOpen(15, 20)); // connected range; {[1, 10], [11, 20)} * rangeSet.add(Range.openClosed(0, 0)); // empty range; {[1, 10], [11, 20)} * rangeSet.remove(Range.open(5, 10)); // splits [1, 10]; {[1, 5], [10, 10], [11, 20)} * }</pre> * * <p>Note that the behavior of {@link Range#isEmpty()} and {@link Range#isConnected(Range)} may not * be as expected on discrete ranges. See the Javadoc of those methods for details. * * <p>For a {@link Set} whose contents are specified by a {@link Range}, see {@link ContiguousSet}. * * <p>See the Guava User Guide article on <a href= * "https://github.com/google/guava/wiki/NewCollectionTypesExplained#rangeset">RangeSets</a>. * * @author Kevin Bourrillion * @author Louis Wasserman * @since 14.0 */ @SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989 @DoNotMock("Use ImmutableRangeSet or TreeRangeSet") @GwtIncompatible @ElementTypesAreNonnullByDefault public interface RangeSet<C extends Comparable> { // TODO(lowasser): consider adding default implementations of some of these methods // Query methods /** Determines whether any of this range set's member ranges contains {@code value}. */ boolean contains(C value); /** * Returns the unique range from this range set that {@linkplain Range#contains contains} {@code * value}, or {@code null} if this range set does not contain {@code value}. */ @CheckForNull Range<C> rangeContaining(C value); /** * Returns {@code true} if there exists a non-empty range enclosed by both a member range in this * range set and the specified range. This is equivalent to calling {@code * subRangeSet(otherRange)} and testing whether the resulting range set is non-empty. * * @since 20.0 */ boolean intersects(Range<C> otherRange); /** * Returns {@code true} if there exists a member range in this range set which {@linkplain * Range#encloses encloses} the specified range. */ boolean encloses(Range<C> otherRange); /** * Returns {@code true} if for each member range in {@code other} there exists a member range in * this range set which {@linkplain Range#encloses encloses} it. It follows that {@code * this.contains(value)} whenever {@code other.contains(value)}. Returns {@code true} if {@code * other} is empty. * * <p>This is equivalent to checking if this range set {@link #encloses} each of the ranges in * {@code other}. */ boolean enclosesAll(RangeSet<C> other); /** * Returns {@code true} if for each range in {@code other} there exists a member range in this * range set which {@linkplain Range#encloses encloses} it. Returns {@code true} if {@code other} * is empty. * * <p>This is equivalent to checking if this range set {@link #encloses} each range in {@code * other}. * * @since 21.0 */ default boolean enclosesAll(Iterable<Range<C>> other) { for (Range<C> range : other) { if (!encloses(range)) { return false; } } return true; } /** Returns {@code true} if this range set contains no ranges. */ boolean isEmpty(); /** * Returns the minimal range which {@linkplain Range#encloses(Range) encloses} all ranges in this * range set. * * @throws NoSuchElementException if this range set is {@linkplain #isEmpty() empty} */ Range<C> span(); // Views /** * Returns a view of the {@linkplain Range#isConnected disconnected} ranges that make up this * range set. The returned set may be empty. The iterators returned by its {@link * Iterable#iterator} method return the ranges in increasing order of lower bound (equivalently, * of upper bound). */ Set<Range<C>> asRanges(); /** * Returns a descending view of the {@linkplain Range#isConnected disconnected} ranges that make * up this range set. The returned set may be empty. The iterators returned by its {@link * Iterable#iterator} method return the ranges in decreasing order of lower bound (equivalently, * of upper bound). * * @since 19.0 */ Set<Range<C>> asDescendingSetOfRanges(); /** * Returns a view of the complement of this {@code RangeSet}. * * <p>The returned view supports the {@link #add} operation if this {@code RangeSet} supports * {@link #remove}, and vice versa. */ RangeSet<C> complement(); /** * Returns a view of the intersection of this {@code RangeSet} with the specified range. * * <p>The returned view supports all optional operations supported by this {@code RangeSet}, with * the caveat that an {@link IllegalArgumentException} is thrown on an attempt to {@linkplain * #add(Range) add} any range not {@linkplain Range#encloses(Range) enclosed} by {@code view}. */ RangeSet<C> subRangeSet(Range<C> view); // Modification /** * Adds the specified range to this {@code RangeSet} (optional operation). That is, for equal * range sets a and b, the result of {@code a.add(range)} is that {@code a} will be the minimal * range set for which both {@code a.enclosesAll(b)} and {@code a.encloses(range)}. * * <p>Note that {@code range} will be {@linkplain Range#span(Range) coalesced} with any ranges in * the range set that are {@linkplain Range#isConnected(Range) connected} with it. Moreover, if * {@code range} is empty, this is a no-op. * * @throws UnsupportedOperationException if this range set does not support the {@code add} * operation */ void add(Range<C> range); /** * Removes the specified range from this {@code RangeSet} (optional operation). After this * operation, if {@code range.contains(c)}, {@code this.contains(c)} will return {@code false}. * * <p>If {@code range} is empty, this is a no-op. * * @throws UnsupportedOperationException if this range set does not support the {@code remove} * operation */ void remove(Range<C> range); /** * Removes all ranges from this {@code RangeSet} (optional operation). After this operation, * {@code this.contains(c)} will return false for all {@code c}. * * <p>This is equivalent to {@code remove(Range.all())}. * * @throws UnsupportedOperationException if this range set does not support the {@code clear} * operation */ void clear(); /** * Adds all of the ranges from the specified range set to this range set (optional operation). * After this operation, this range set is the minimal range set that {@linkplain * #enclosesAll(RangeSet) encloses} both the original range set and {@code other}. * * <p>This is equivalent to calling {@link #add} on each of the ranges in {@code other} in turn. * * @throws UnsupportedOperationException if this range set does not support the {@code addAll} * operation */ void addAll(RangeSet<C> other); /** * Adds all of the specified ranges to this range set (optional operation). After this operation, * this range set is the minimal range set that {@linkplain #enclosesAll(RangeSet) encloses} both * the original range set and each range in {@code other}. * * <p>This is equivalent to calling {@link #add} on each of the ranges in {@code other} in turn. * * @throws UnsupportedOperationException if this range set does not support the {@code addAll} * operation * @since 21.0 */ default void addAll(Iterable<Range<C>> ranges) { for (Range<C> range : ranges) { add(range); } } /** * Removes all of the ranges from the specified range set from this range set (optional * operation). After this operation, if {@code other.contains(c)}, {@code this.contains(c)} will * return {@code false}. * * <p>This is equivalent to calling {@link #remove} on each of the ranges in {@code other} in * turn. * * @throws UnsupportedOperationException if this range set does not support the {@code removeAll} * operation */ void removeAll(RangeSet<C> other); /** * Removes all of the specified ranges from this range set (optional operation). * * <p>This is equivalent to calling {@link #remove} on each of the ranges in {@code other} in * turn. * * @throws UnsupportedOperationException if this range set does not support the {@code removeAll} * operation * @since 21.0 */ default void removeAll(Iterable<Range<C>> ranges) { for (Range<C> range : ranges) { remove(range); } } // Object methods /** * Returns {@code true} if {@code obj} is another {@code RangeSet} that contains the same ranges * according to {@link Range#equals(Object)}. */ @Override boolean equals(@CheckForNull Object obj); /** Returns {@code asRanges().hashCode()}. */ @Override int hashCode(); /** * Returns a readable string representation of this range set. For example, if this {@code * RangeSet} consisted of {@code Range.closed(1, 3)} and {@code Range.greaterThan(4)}, this might * return {@code " [1..3](4..+∞)}"}. */ @Override String toString(); }
google/guava
guava/src/com/google/common/collect/RangeSet.java
121
/* * Copyright (C) 2013 Square, 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 retrofit2.http; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Annotation; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import java.lang.reflect.Type; import retrofit2.Retrofit; /** * Named replacement in a URL path segment. Values are converted to strings using {@link * Retrofit#stringConverter(Type, Annotation[])} (or {@link Object#toString()}, if no matching * string converter is installed) and then URL encoded. * * <p>Simple example: * * <pre><code> * &#64;GET("/image/{id}") * Call&lt;ResponseBody&gt; example(@Path("id") int id); * </code></pre> * * Calling with {@code foo.example(1)} yields {@code /image/1}. * * <p>Values are URL encoded by default. Disable with {@code encoded=true}. * * <pre><code> * &#64;GET("/user/{name}") * Call&lt;ResponseBody&gt; encoded(@Path("name") String name); * * &#64;GET("/user/{name}") * Call&lt;ResponseBody&gt; notEncoded(@Path(value="name", encoded=true) String name); * </code></pre> * * Calling {@code foo.encoded("John%Doe")} yields {@code /user/John%25Doe} whereas {@code * foo.notEncoded("John%Doe")} yields {@code /user/John%Doe}. * * <p>Path parameters may not be {@code null}. */ @Documented @Retention(RUNTIME) @Target(PARAMETER) public @interface Path { String value(); /** * Specifies whether the argument value to the annotated method parameter is already URL encoded. */ boolean encoded() default false; }
square/retrofit
retrofit/src/main/java/retrofit2/http/Path.java
122
/* * Copyright (C) 2015 Square, 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 retrofit2; import static retrofit2.Utils.throwIfFatal; import java.io.IOException; import java.util.Objects; import javax.annotation.Nullable; import javax.annotation.concurrent.GuardedBy; import okhttp3.MediaType; import okhttp3.Request; import okhttp3.ResponseBody; import okio.Buffer; import okio.BufferedSource; import okio.ForwardingSource; import okio.Okio; import okio.Timeout; final class OkHttpCall<T> implements Call<T> { private final RequestFactory requestFactory; private final Object instance; private final Object[] args; private final okhttp3.Call.Factory callFactory; private final Converter<ResponseBody, T> responseConverter; private volatile boolean canceled; @GuardedBy("this") private @Nullable okhttp3.Call rawCall; @GuardedBy("this") // Either a RuntimeException, non-fatal Error, or IOException. private @Nullable Throwable creationFailure; @GuardedBy("this") private boolean executed; OkHttpCall( RequestFactory requestFactory, Object instance, Object[] args, okhttp3.Call.Factory callFactory, Converter<ResponseBody, T> responseConverter) { this.requestFactory = requestFactory; this.instance = instance; this.args = args; this.callFactory = callFactory; this.responseConverter = responseConverter; } @SuppressWarnings("CloneDoesntCallSuperClone") // We are a final type & this saves clearing state. @Override public OkHttpCall<T> clone() { return new OkHttpCall<>(requestFactory, instance, args, callFactory, responseConverter); } @Override public synchronized Request request() { try { return getRawCall().request(); } catch (IOException e) { throw new RuntimeException("Unable to create request.", e); } } @Override public synchronized Timeout timeout() { try { return getRawCall().timeout(); } catch (IOException e) { throw new RuntimeException("Unable to create call.", e); } } /** * Returns the raw call, initializing it if necessary. Throws if initializing the raw call throws, * or has thrown in previous attempts to create it. */ @GuardedBy("this") private okhttp3.Call getRawCall() throws IOException { okhttp3.Call call = rawCall; if (call != null) return call; // Re-throw previous failures if this isn't the first attempt. if (creationFailure != null) { if (creationFailure instanceof IOException) { throw (IOException) creationFailure; } else if (creationFailure instanceof RuntimeException) { throw (RuntimeException) creationFailure; } else { throw (Error) creationFailure; } } // Create and remember either the success or the failure. try { return rawCall = createRawCall(); } catch (RuntimeException | Error | IOException e) { throwIfFatal(e); // Do not assign a fatal error to creationFailure. creationFailure = e; throw e; } } @Override public void enqueue(final Callback<T> callback) { Objects.requireNonNull(callback, "callback == null"); okhttp3.Call call; Throwable failure; synchronized (this) { if (executed) throw new IllegalStateException("Already executed."); executed = true; call = rawCall; failure = creationFailure; if (call == null && failure == null) { try { call = rawCall = createRawCall(); } catch (Throwable t) { throwIfFatal(t); failure = creationFailure = t; } } } if (failure != null) { callback.onFailure(this, failure); return; } if (canceled) { call.cancel(); } call.enqueue( new okhttp3.Callback() { @Override public void onResponse(okhttp3.Call call, okhttp3.Response rawResponse) { Response<T> response; try { response = parseResponse(rawResponse); } catch (Throwable e) { throwIfFatal(e); callFailure(e); return; } try { callback.onResponse(OkHttpCall.this, response); } catch (Throwable t) { throwIfFatal(t); t.printStackTrace(); // TODO this is not great } } @Override public void onFailure(okhttp3.Call call, IOException e) { callFailure(e); } private void callFailure(Throwable e) { try { callback.onFailure(OkHttpCall.this, e); } catch (Throwable t) { throwIfFatal(t); t.printStackTrace(); // TODO this is not great } } }); } @Override public synchronized boolean isExecuted() { return executed; } @Override public Response<T> execute() throws IOException { okhttp3.Call call; synchronized (this) { if (executed) throw new IllegalStateException("Already executed."); executed = true; call = getRawCall(); } if (canceled) { call.cancel(); } return parseResponse(call.execute()); } private okhttp3.Call createRawCall() throws IOException { okhttp3.Call call = callFactory.newCall(requestFactory.create(instance, args)); if (call == null) { throw new NullPointerException("Call.Factory returned null."); } return call; } Response<T> parseResponse(okhttp3.Response rawResponse) throws IOException { ResponseBody rawBody = rawResponse.body(); // Remove the body's source (the only stateful object) so we can pass the response along. rawResponse = rawResponse .newBuilder() .body(new NoContentResponseBody(rawBody.contentType(), rawBody.contentLength())) .build(); int code = rawResponse.code(); if (code < 200 || code >= 300) { try { // Buffer the entire body to avoid future I/O. ResponseBody bufferedBody = Utils.buffer(rawBody); return Response.error(bufferedBody, rawResponse); } finally { rawBody.close(); } } if (code == 204 || code == 205) { rawBody.close(); return Response.success(null, rawResponse); } ExceptionCatchingResponseBody catchingBody = new ExceptionCatchingResponseBody(rawBody); try { T body = responseConverter.convert(catchingBody); return Response.success(body, rawResponse); } catch (RuntimeException e) { // If the underlying source threw an exception, propagate that rather than indicating it was // a runtime exception. catchingBody.throwIfCaught(); throw e; } } @Override public void cancel() { canceled = true; okhttp3.Call call; synchronized (this) { call = rawCall; } if (call != null) { call.cancel(); } } @Override public boolean isCanceled() { if (canceled) { return true; } synchronized (this) { return rawCall != null && rawCall.isCanceled(); } } static final class NoContentResponseBody extends ResponseBody { private final @Nullable MediaType contentType; private final long contentLength; NoContentResponseBody(@Nullable MediaType contentType, long contentLength) { this.contentType = contentType; this.contentLength = contentLength; } @Override public MediaType contentType() { return contentType; } @Override public long contentLength() { return contentLength; } @Override public BufferedSource source() { throw new IllegalStateException("Cannot read raw response body of a converted body."); } } static final class ExceptionCatchingResponseBody extends ResponseBody { private final ResponseBody delegate; private final BufferedSource delegateSource; @Nullable IOException thrownException; ExceptionCatchingResponseBody(ResponseBody delegate) { this.delegate = delegate; this.delegateSource = Okio.buffer( new ForwardingSource(delegate.source()) { @Override public long read(Buffer sink, long byteCount) throws IOException { try { return super.read(sink, byteCount); } catch (IOException e) { thrownException = e; throw e; } } }); } @Override public MediaType contentType() { return delegate.contentType(); } @Override public long contentLength() { return delegate.contentLength(); } @Override public BufferedSource source() { return delegateSource; } @Override public void close() { delegate.close(); } void throwIfCaught() throws IOException { if (thrownException != null) { throw thrownException; } } } }
square/retrofit
retrofit/src/main/java/retrofit2/OkHttpCall.java
123
package com.thealgorithms.conversions; import java.util.Scanner; // given a source number , source base, destination base, this code can give you the destination // number. // sn ,sb,db ---> ()dn . this is what we have to do . public final class AnytoAny { private AnytoAny() { } public static void main(String[] args) { Scanner scn = new Scanner(System.in); int sn = scn.nextInt(); int sb = scn.nextInt(); int db = scn.nextInt(); int m = 1, dec = 0, dn = 0; while (sn != 0) { dec = dec + (sn % 10) * m; m *= sb; sn /= 10; } m = 1; while (dec != 0) { dn = dn + (dec % db) * m; m *= 10; dec /= db; } System.out.println(dn); scn.close(); } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/conversions/AnytoAny.java
124
import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.zip.Deflater; import java.util.Base64; public class Xml2Js { /** * */ protected static final int IO_BUFFER_SIZE = 4 * 1024; /** * */ public static String CHARSET_FOR_URL_ENCODING = "UTF-8"; /** * * @param path * @return */ public List<String> walk(File base, File root) throws IOException { if (root == null) { root = base; } List<String> result = new LinkedList<String>(); String basePath = base.getCanonicalPath(); File[] list = root.listFiles(); if (list != null) { for (File f : list) { if (f.isDirectory()) { result.addAll(walk(base, f)); } else if (f.getCanonicalPath().toLowerCase().endsWith(".xml")) { String name = f.getCanonicalPath() .substring(basePath.length() + 1); result.add( "f['" + name + "'] = '" + processFile(f) + "';\n"); } } } return result; } /** * * @param file * @return * @throws IOException */ public static String processFile(File file) throws IOException { Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION, true); byte[] inBytes = readInputStream(new FileInputStream(file)).getBytes("UTF-8"); deflater.setInput(inBytes); ByteArrayOutputStream outputStream = new ByteArrayOutputStream( inBytes.length); deflater.finish(); byte[] buffer = new byte[IO_BUFFER_SIZE]; while (!deflater.finished()) { int count = deflater.deflate(buffer); // returns the generated code... index outputStream.write(buffer, 0, count); } outputStream.close(); return Base64.getEncoder().encodeToString(outputStream.toByteArray()); } /** * * @param stream * @return * @throws IOException */ public static String readInputStream(InputStream stream) throws IOException { BufferedReader reader = new BufferedReader( new InputStreamReader(stream)); StringBuffer result = new StringBuffer(); String tmp = reader.readLine(); while (tmp != null) { result.append(tmp.trim()); tmp = reader.readLine(); } reader.close(); return result.toString(); } public static String encodeURIComponent(String s, String charset) { if (s == null) { return null; } else { String result; try { result = URLEncoder.encode(s, charset).replaceAll("\\+", "%20") .replaceAll("\\%21", "!").replaceAll("\\%27", "'") .replaceAll("\\%28", "(").replaceAll("\\%29", ")") .replaceAll("\\%7E", "~"); } catch (UnsupportedEncodingException e) { // This exception should never occur result = s; } return result; } } private static final char[] CA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" .toCharArray(); private static final int[] IA = new int[256]; static { Arrays.fill(IA, -1); for (int i = 0, iS = CA.length; i < iS; i++) IA[CA[i]] = i; IA['='] = 0; } /** * Main */ public static void main(String[] args) { if (args.length < 2) { System.out.println("Usage: xml2js path file"); } else { try { Xml2Js fw = new Xml2Js(); // Generates result StringBuffer result = new StringBuffer(); result.append("(function() {\nvar f = {};\n"); List<String> files = fw .walk(new File(new File(".").getCanonicalPath() + File.separator + args[0]), null); Iterator<String> it = files.iterator(); while (it.hasNext()) { result.append(it.next()); } result.append("\n"); result.append("var l = mxStencilRegistry.loadStencil;\n\n"); result.append( "mxStencilRegistry.loadStencil = function(filename, fn)\n{\n"); result.append(" var t = f[filename.substring(STENCIL_PATH.length + 1)];\n"); result.append(" var s = null;\n"); result.append(" if (t != null) {\n"); result.append(" s = pako.inflateRaw(Uint8Array.from(atob(t), function (c) {\n"); result.append(" return c.charCodeAt(0);\n"); result.append(" }), {to: 'string'});\n"); result.append(" }\n"); result.append(" if (fn != null && s != null) {\n"); result.append( " window.setTimeout(function(){fn(mxUtils.parseXml(s))}, 0);\n"); result.append(" } else {\n"); result.append( " return (s != null) ? mxUtils.parseXml(s) : l.apply(this, arguments)\n"); result.append(" }\n"); result.append("};\n"); result.append("})();\n"); FileWriter writer = new FileWriter( new File(new File(".").getCanonicalPath() + File.separator + args[1])); writer.write(result.toString()); writer.flush(); writer.close(); } catch (IOException ex) { ex.printStackTrace(); } } } }
jgraph/drawio
etc/build/Xml2Js.java
125
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * 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.iluwatar; import java.time.LocalDate; import lombok.Getter; import lombok.Setter; /** * Data transfer object which stores information about the worker. This is carried between * objects and layers to reduce the number of method calls made. */ @Getter @Setter public class RegisterWorkerDto extends DataTransferObject { private String name; private String occupation; private LocalDate dateOfBirth; /** * Error for when name field is blank or missing. */ public static final NotificationError MISSING_NAME = new NotificationError(1, "Name is missing"); /** * Error for when occupation field is blank or missing. */ public static final NotificationError MISSING_OCCUPATION = new NotificationError(2, "Occupation is missing"); /** * Error for when date of birth field is blank or missing. */ public static final NotificationError MISSING_DOB = new NotificationError(3, "Date of birth is missing"); /** * Error for when date of birth is less than 18 years ago. */ public static final NotificationError DOB_TOO_SOON = new NotificationError(4, "Worker registered must be over 18"); protected RegisterWorkerDto() { super(); } /** * Simple set up function for capturing our worker information. * * @param name Name of the worker * @param occupation occupation of the worker * @param dateOfBirth Date of Birth of the worker */ public void setupWorkerDto(String name, String occupation, LocalDate dateOfBirth) { this.name = name; this.occupation = occupation; this.dateOfBirth = dateOfBirth; } }
rajprins/java-design-patterns
notification/src/main/java/com/iluwatar/RegisterWorkerDto.java
126
/* Copyright 2017 The TensorFlow Authors. 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 org.tensorflow.lite; import java.io.File; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Map; import org.checkerframework.checker.nullness.qual.NonNull; /** * Driver class to drive model inference with TensorFlow Lite. * * <p>Note: If you don't need access to any of the "experimental" API features below, prefer to use * InterpreterApi and InterpreterFactory rather than using Interpreter directly. * * <p>A {@code Interpreter} encapsulates a pre-trained TensorFlow Lite model, in which operations * are executed for model inference. * * <p>For example, if a model takes only one input and returns only one output: * * <pre>{@code * try (Interpreter interpreter = new Interpreter(file_of_a_tensorflowlite_model)) { * interpreter.run(input, output); * } * }</pre> * * <p>If a model takes multiple inputs or outputs: * * <pre>{@code * Object[] inputs = {input0, input1, ...}; * Map<Integer, Object> map_of_indices_to_outputs = new HashMap<>(); * FloatBuffer ith_output = FloatBuffer.allocateDirect(3 * 2 * 4); // Float tensor, shape 3x2x4. * ith_output.order(ByteOrder.nativeOrder()); * map_of_indices_to_outputs.put(i, ith_output); * try (Interpreter interpreter = new Interpreter(file_of_a_tensorflowlite_model)) { * interpreter.runForMultipleInputsOutputs(inputs, map_of_indices_to_outputs); * } * }</pre> * * <p>If a model takes or produces string tensors: * * <pre>{@code * String[] input = {"foo", "bar"}; // Input tensor shape is [2]. * String[][] output = new String[3][2]; // Output tensor shape is [3, 2]. * try (Interpreter interpreter = new Interpreter(file_of_a_tensorflowlite_model)) { * interpreter.runForMultipleInputsOutputs(input, output); * } * }</pre> * * <p>Note that there's a distinction between shape [] and shape[1]. For scalar string tensor * outputs: * * <pre>{@code * String[] input = {"foo"}; // Input tensor shape is [1]. * ByteBuffer outputBuffer = ByteBuffer.allocate(OUTPUT_BYTES_SIZE); // Output tensor shape is []. * try (Interpreter interpreter = new Interpreter(file_of_a_tensorflowlite_model)) { * interpreter.runForMultipleInputsOutputs(input, outputBuffer); * } * byte[] outputBytes = new byte[outputBuffer.remaining()]; * outputBuffer.get(outputBytes); * // Below, the `charset` can be StandardCharsets.UTF_8. * String output = new String(outputBytes, charset); * }</pre> * * <p>Orders of inputs and outputs are determined when converting TensorFlow model to TensorFlowLite * model with Toco, as are the default shapes of the inputs. * * <p>When inputs are provided as (multi-dimensional) arrays, the corresponding input tensor(s) will * be implicitly resized according to that array's shape. When inputs are provided as {@code Buffer} * types, no implicit resizing is done; the caller must ensure that the {@code Buffer} byte size * either matches that of the corresponding tensor, or that they first resize the tensor via {@link * #resizeInput(int, int[])}. Tensor shape and type information can be obtained via the {@link * Tensor} class, available via {@link #getInputTensor(int)} and {@link #getOutputTensor(int)}. * * <p><b>WARNING:</b>{@code Interpreter} instances are <b>not</b> thread-safe. A {@code Interpreter} * owns resources that <b>must</b> be explicitly freed by invoking {@link #close()} * * <p>The TFLite library is built against NDK API 19. It may work for Android API levels below 19, * but is not guaranteed. */ public final class Interpreter extends InterpreterImpl implements InterpreterApi { /** An options class for controlling runtime interpreter behavior. */ public static class Options extends InterpreterImpl.Options { public Options() {} public Options(InterpreterApi.Options options) { super(options); } Options(InterpreterImpl.Options options) { super(options); } @Override public Options setUseXNNPACK(boolean useXNNPACK) { super.setUseXNNPACK(useXNNPACK); return this; } @Override public Options setNumThreads(int numThreads) { super.setNumThreads(numThreads); return this; } @Override public Options setUseNNAPI(boolean useNNAPI) { super.setUseNNAPI(useNNAPI); return this; } /** * Sets whether to allow float16 precision for FP32 calculation when possible. Defaults to false * (disallow). * * @deprecated Prefer using <a * href="https://github.com/tensorflow/tensorflow/blob/5dc7f6981fdaf74c8c5be41f393df705841fb7c5/tensorflow/lite/delegates/nnapi/java/src/main/java/org/tensorflow/lite/nnapi/NnApiDelegate.java#L127">NnApiDelegate.Options#setAllowFp16(boolean * enable)</a>. */ @Deprecated public Options setAllowFp16PrecisionForFp32(boolean allow) { this.allowFp16PrecisionForFp32 = allow; return this; } @Override public Options addDelegate(Delegate delegate) { super.addDelegate(delegate); return this; } @Override public Options addDelegateFactory(DelegateFactory delegateFactory) { super.addDelegateFactory(delegateFactory); return this; } /** * Advanced: Set if buffer handle output is allowed. * * <p>When a {@link Delegate} supports hardware acceleration, the interpreter will make the data * of output tensors available in the CPU-allocated tensor buffers by default. If the client can * consume the buffer handle directly (e.g. reading output from OpenGL texture), it can set this * flag to false, avoiding the copy of data to the CPU buffer. The delegate documentation should * indicate whether this is supported and how it can be used. * * <p>WARNING: This is an experimental interface that is subject to change. */ public Options setAllowBufferHandleOutput(boolean allow) { this.allowBufferHandleOutput = allow; return this; } @Override public Options setCancellable(boolean allow) { super.setCancellable(allow); return this; } @Override public Options setRuntime(InterpreterApi.Options.TfLiteRuntime runtime) { super.setRuntime(runtime); return this; } } /** * Initializes an {@code Interpreter}. * * @param modelFile a File of a pre-trained TF Lite model. * @throws IllegalArgumentException if {@code modelFile} does not encode a valid TensorFlow Lite * model. */ public Interpreter(@NonNull File modelFile) { this(modelFile, /*options = */ null); } /** * Initializes an {@code Interpreter} and specifies options for customizing interpreter behavior. * * @param modelFile a file of a pre-trained TF Lite model * @param options a set of options for customizing interpreter behavior * @throws IllegalArgumentException if {@code modelFile} does not encode a valid TensorFlow Lite * model. */ public Interpreter(@NonNull File modelFile, Options options) { this(new NativeInterpreterWrapperExperimental(modelFile.getAbsolutePath(), options)); } /** * Initializes an {@code Interpreter} with a {@code ByteBuffer} of a model file. * * <p>The ByteBuffer should not be modified after the construction of a {@code Interpreter}. The * {@code ByteBuffer} can be either a {@code MappedByteBuffer} that memory-maps a model file, or a * direct {@code ByteBuffer} of nativeOrder() that contains the bytes content of a model. * * @throws IllegalArgumentException if {@code byteBuffer} is not a {@code MappedByteBuffer} nor a * direct {@code ByteBuffer} of nativeOrder. */ public Interpreter(@NonNull ByteBuffer byteBuffer) { this(byteBuffer, /* options= */ null); } /** * Initializes an {@code Interpreter} with a {@code ByteBuffer} of a model file and a set of * custom {@link Interpreter.Options}. * * <p>The {@code ByteBuffer} should not be modified after the construction of an {@code * Interpreter}. The {@code ByteBuffer} can be either a {@code MappedByteBuffer} that memory-maps * a model file, or a direct {@code ByteBuffer} of nativeOrder() that contains the bytes content * of a model. * * @throws IllegalArgumentException if {@code byteBuffer} is not a {@code MappedByteBuffer} nor a * direct {@code ByteBuffer} of nativeOrder. */ public Interpreter(@NonNull ByteBuffer byteBuffer, Options options) { this(new NativeInterpreterWrapperExperimental(byteBuffer, options)); } private Interpreter(NativeInterpreterWrapperExperimental wrapper) { super(wrapper); wrapperExperimental = wrapper; signatureKeyList = getSignatureKeys(); } /** * Runs model inference based on SignatureDef provided through {@code signatureKey}. * * <p>See {@link Interpreter#run(Object, Object)} for more details on the allowed input and output * data types. * * <p>WARNING: This is an experimental API and subject to change. * * @param inputs A map from input name in the SignatureDef to an input object. * @param outputs A map from output name in SignatureDef to output data. This may be empty if the * caller wishes to query the {@link Tensor} data directly after inference (e.g., if the * output shape is dynamic, or output buffer handles are used). * @param signatureKey Signature key identifying the SignatureDef. * @throws IllegalArgumentException if {@code inputs} is null or empty, if {@code outputs} or * {@code signatureKey} is null, or if an error occurs when running inference. */ public void runSignature( @NonNull Map<String, Object> inputs, @NonNull Map<String, Object> outputs, String signatureKey) { checkNotClosed(); if (signatureKey == null && signatureKeyList.length == 1) { signatureKey = signatureKeyList[0]; } if (signatureKey == null) { throw new IllegalArgumentException( "Input error: SignatureDef signatureKey should not be null. null is only allowed if the" + " model has a single Signature. Available Signatures: " + Arrays.toString(signatureKeyList)); } wrapper.runSignature(inputs, outputs, signatureKey); } /** * Same as {@link #runSignature(Map, Map, String)} but doesn't require passing a signatureKey, * assuming the model has one SignatureDef. If the model has more than one SignatureDef it will * throw an exception. * * <p>WARNING: This is an experimental API and subject to change. */ public void runSignature( @NonNull Map<String, Object> inputs, @NonNull Map<String, Object> outputs) { checkNotClosed(); runSignature(inputs, outputs, null); } /** * Gets the Tensor associated with the provided input name and signature method name. * * <p>WARNING: This is an experimental API and subject to change. * * @param inputName Input name in the signature. * @param signatureKey Signature key identifying the SignatureDef, can be null if the model has * one signature. * @throws IllegalArgumentException if {@code inputName} or {@code signatureKey} is null or empty, * or invalid name provided. */ public Tensor getInputTensorFromSignature(String inputName, String signatureKey) { checkNotClosed(); if (signatureKey == null && signatureKeyList.length == 1) { signatureKey = signatureKeyList[0]; } if (signatureKey == null) { throw new IllegalArgumentException( "Input error: SignatureDef signatureKey should not be null. null is only allowed if the" + " model has a single Signature. Available Signatures: " + Arrays.toString(signatureKeyList)); } return wrapper.getInputTensor(inputName, signatureKey); } /** * Gets the list of SignatureDef exported method names available in the model. * * <p>WARNING: This is an experimental API and subject to change. */ public String[] getSignatureKeys() { checkNotClosed(); return wrapper.getSignatureKeys(); } /** * Gets the list of SignatureDefs inputs for method {@code signatureKey}. * * <p>WARNING: This is an experimental API and subject to change. */ public String[] getSignatureInputs(String signatureKey) { checkNotClosed(); return wrapper.getSignatureInputs(signatureKey); } /** * Gets the list of SignatureDefs outputs for method {@code signatureKey}. * * <p>WARNING: This is an experimental API and subject to change. */ public String[] getSignatureOutputs(String signatureKey) { checkNotClosed(); return wrapper.getSignatureOutputs(signatureKey); } /** * Gets the Tensor associated with the provided output name in specific signature method. * * <p>Note: Output tensor details (e.g., shape) may not be fully populated until after inference * is executed. If you need updated details *before* running inference (e.g., after resizing an * input tensor, which may invalidate output tensor shapes), use {@link #allocateTensors()} to * explicitly trigger allocation and shape propagation. Note that, for graphs with output shapes * that are dependent on input *values*, the output shape may not be fully determined until * running inference. * * <p>WARNING: This is an experimental API and subject to change. * * @param outputName Output name in the signature. * @param signatureKey Signature key identifying the SignatureDef, can be null if the model has * one signature. * @throws IllegalArgumentException if {@code outputName} or {@code signatureKey} is null or * empty, or invalid name provided. */ public Tensor getOutputTensorFromSignature(String outputName, String signatureKey) { checkNotClosed(); if (signatureKey == null && signatureKeyList.length == 1) { signatureKey = signatureKeyList[0]; } if (signatureKey == null) { throw new IllegalArgumentException( "Input error: SignatureDef signatureKey should not be null. null is only allowed if the" + " model has a single Signature. Available Signatures: " + Arrays.toString(signatureKeyList)); } return wrapper.getOutputTensor(outputName, signatureKey); } /** * Advanced: Resets all variable tensors to the default value. * * <p>If a variable tensor doesn't have an associated buffer, it will be reset to zero. * * <p>WARNING: This is an experimental API and subject to change. */ public void resetVariableTensors() { checkNotClosed(); wrapperExperimental.resetVariableTensors(); } /** * Advanced: Interrupts inference in the middle of a call to {@link Interpreter#run}. * * <p>A cancellation flag will be set to true when this function gets called. The interpreter will * check the flag between Op invocations, and if it's {@code true}, the interpreter will stop * execution. The interpreter will remain a cancelled state until explicitly "uncancelled" by * {@code setCancelled(false)}. * * <p>WARNING: This is an experimental API and subject to change. * * @param cancelled {@code true} to cancel inference in a best-effort way; {@code false} to * resume. * @throws IllegalStateException if the interpreter is not initialized with the cancellable * option, which is by default off. * @see Interpreter.Options#setCancellable(boolean). */ public void setCancelled(boolean cancelled) { wrapper.setCancelled(cancelled); } private final NativeInterpreterWrapperExperimental wrapperExperimental; private final String[] signatureKeyList; }
tensorflow/tensorflow
tensorflow/lite/java/src/main/java/org/tensorflow/lite/Interpreter.java
127
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * 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 dto; import java.util.List; import java.util.Optional; /** * DTO for cakes. */ public class CakeInfo { public final Optional<Long> id; public final CakeToppingInfo cakeToppingInfo; public final List<CakeLayerInfo> cakeLayerInfos; /** * Constructor. */ public CakeInfo(Long id, CakeToppingInfo cakeToppingInfo, List<CakeLayerInfo> cakeLayerInfos) { this.id = Optional.of(id); this.cakeToppingInfo = cakeToppingInfo; this.cakeLayerInfos = cakeLayerInfos; } /** * Constructor. */ public CakeInfo(CakeToppingInfo cakeToppingInfo, List<CakeLayerInfo> cakeLayerInfos) { this.id = Optional.empty(); this.cakeToppingInfo = cakeToppingInfo; this.cakeLayerInfos = cakeLayerInfos; } /** * Calculate calories. */ public int calculateTotalCalories() { var total = cakeToppingInfo != null ? cakeToppingInfo.calories : 0; total += cakeLayerInfos.stream().mapToInt(c -> c.calories).sum(); return total; } @Override public String toString() { return String.format("CakeInfo id=%d topping=%s layers=%s totalCalories=%d", id.orElse(-1L), cakeToppingInfo, cakeLayerInfos, calculateTotalCalories()); } }
rajprins/java-design-patterns
layers/src/main/java/dto/CakeInfo.java
128
/** * We define the parity of an integer n as the sum of the bits in binary representation computed modulo * two. As an example, the number 21 = 101012 has three 1s in its binary representation so it has parity * 3(mod2), or 1. * In this problem you have to calculate the parity of an integer 1 ≤ I ≤ 2147483647. * Input * Each line of the input has an integer I and the end of the input is indicated by a line where I = 0 that * should not be processed. * Output * For each integer I in the inputt you should print a line ‘The parity of B is P (mod 2).’, where B * is the binary representation of I. * Sample Input * 1 * 2 * 10 * 21 * 0 * Sample Output * The parity of 1 is 1 (mod 2). * The parity of 10 is 1 (mod 2). * The parity of 1010 is 2 (mod 2). * The parity of 10101 is 3 (mod 2). */ //https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1872 import java.util.Scanner; public class Parity { public static void main(String[] args) { while (true) { Scanner input = new Scanner(System.in); int number = input.nextInt(); if (number == 0) { break; } String binaryInString = convertToBinary(number); int count = 0; for (int i = 0; i < binaryInString.length(); i++) { if ("1".equals(binaryInString.charAt(i) + "")) { count++; } } System.out.println("The parity of " + binaryInString + " is " + count + " (mod 2)."); } } private static String convertToBinary(int number) { StringBuilder s = new StringBuilder(""); while (number != 0) { s = s.append(number % 2); number = number / 2; } return s.reverse().toString(); } }
kdn251/interviews
uva/Parity.java
129
/** * In these days you can more and more often happen to see programs which perform some useful calculations * being executed rather then trivial screen savers. Some of them check the system message queue * and in case of finding it empty (for examples somebody is editing a file and stays idle for some time) * execute its own algorithm. * As an examples we can give programs which calculate primary numbers. * One can also imagine a program which calculates a factorial of given numbers. In this case it is not * the time complexity of order O(n) which makes troubles, but the memory requirements. Considering * the fact that 500! gives 1135-digit number. No standard, neither integer nor floating, data type is * applicable here. * Your task is to write a programs which calculates a factorial of a given number. * Input * Any number of lines, each containing value n for which you should provide value of n! * Output * 2 lines for each input case. First should contain value n followed by character ‘!’. The second should * contain calculated value n!. * Assumptions: * • Value of a number n which factorial should be calculated of does not exceed 1000 (although 500! * is the name of the problem, 500 is a small limit). * • Mind that visually big number of case 4 is broken after 80 characters, but this is not the case in * the real output file. * Sample Input * 10 * 30 * 50 * 100 * Sample Output * 10! * 3628800 * 30! * 265252859812191058636308480000000 * 50! * 30414093201713378043612608166064768844377641568960512000000000000 * 100! * 93326215443944152681699238856266700490715968264381621468592963895217599993229915 * 608941463976156518286253697920827223758251185210916864000000000000000000000000 */ //https://uva.onlinejudge.org/index.php?option=onlinejudge&Itemid=99999999&page=show_problem&category=&problem=564 import java.math.BigInteger; import java.util.Scanner; public class FiveHundredFactorial { public static void main(String[] args) { Scanner input = new Scanner(System.in); while (input.hasNext()) { int number = input.nextInt(); BigInteger product = BigInteger.ONE; for (int i = 2; i < number + 1; i++) { product = product.multiply(BigInteger.valueOf(i)); } System.out.println(number + "!\n" + product); } } }
kdn251/interviews
uva/FiveHundredFactorial.java
130
/** * There is man named ”mabu” for switching on-off light in our University. He switches on-off the lights * in a corridor. Every bulb has its own toggle switch. That is, if it is pressed then the bulb turns on. * Another press will turn it off. To save power consumption (or may be he is mad or something else) * he does a peculiar thing. If in a corridor there is n bulbs, he walks along the corridor back and forth * n times and in i-th walk he toggles only the switches whose serial is divisable by i. He does not press * any switch when coming back to his initial position. A i-th walk is defined as going down the corridor * (while doing the peculiar thing) and coming back again. Now you have to determine what is the final * condition of the last bulb. Is it on or off? * Input * The input will be an integer indicating the n’th bulb in a corridor. Which is less then or equals 232 −1. * A zero indicates the end of input. You should not process this input. * Output * Output ‘yes’ if the light is on otherwise ‘no’, in a single line. * Sample Input * 3 * 6241 * 8191 * 0 * Sample Output * no * yes * no */ //https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&category=&problem=1051 import java.util.Scanner; public class LightMoreLight { public static void main(String[] args) { Scanner input = new Scanner(System.in); long number = input.nextLong(); while (number != 0) { if (isAPerfectSquare(number)) { System.out.println("yes"); } else { System.out.println("no"); } number = input.nextLong(); } } private static boolean isAPerfectSquare(long number) { long squareRoot = (long) Math.sqrt(number); return squareRoot * squareRoot == number; } }
kdn251/interviews
uva/LightMoreLight.java
131
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * 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 entity; import jakarta.persistence.CascadeType; import jakarta.persistence.Entity; import jakarta.persistence.FetchType; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; import jakarta.persistence.OneToMany; import jakarta.persistence.OneToOne; import java.util.HashSet; import java.util.Set; import lombok.Getter; import lombok.Setter; /** * Cake entity. */ @Entity @Getter @Setter public class Cake { @Id @GeneratedValue private Long id; @OneToOne(cascade = CascadeType.REMOVE) private CakeTopping topping; @OneToMany(cascade = CascadeType.REMOVE, fetch = FetchType.EAGER) private Set<CakeLayer> layers; public Cake() { setLayers(new HashSet<>()); } public void addLayer(CakeLayer layer) { this.layers.add(layer); } @Override public String toString() { return String.format("id=%s topping=%s layers=%s", id, topping, layers.toString()); } }
iluwatar/java-design-patterns
layers/src/main/java/entity/Cake.java
132
package com.thealgorithms.strings; public final class Upper { private Upper() { } /** * Driver Code */ public static void main(String[] args) { String[] strings = {"ABC", "ABC123", "abcABC", "abc123ABC"}; for (String s : strings) { assert toUpperCase(s).equals(s.toUpperCase()); } } /** * Converts all of the characters in this {@code String} to upper case * * @param s the string to convert * @return the {@code String}, converted to uppercase. */ public static String toUpperCase(String s) { if (s == null || "".equals(s)) { return s; } char[] values = s.toCharArray(); for (int i = 0; i < values.length; ++i) { if (Character.isLetter(values[i]) && Character.isLowerCase(values[i])) { values[i] = Character.toUpperCase(values[i]); } } return new String(values); } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/strings/Upper.java
133
/** * Your MinStack object will be instantiated and called as such: * MinStack obj = new MinStack(); * obj.push(x); * obj.pop(); * int param_3 = obj.top(); * int param_4 = obj.getMin(); */ class MinStack { class Node { int data; int min; Node next; public Node(int data, int min) { this.data = data; this.min = min; this.next = null; } } Node head; /** initialize your data structure here. */ public MinStack() { } public void push(int x) { if(head == null) { head = new Node(x, x); } else { Node newNode = new Node(x, Math.min(x, head.min)); newNode.next = head; head = newNode; } } public void pop() { head = head.next; } public int top() { return head.data; } public int getMin() { return head.min; } }
kdn251/interviews
company/facebook/MinStack.java
134
package com.thealgorithms.strings; public final class Lower { private Lower() { } /** * Driver Code */ public static void main(String[] args) { String[] strings = {"ABC", "ABC123", "abcABC", "abc123ABC"}; for (String s : strings) { assert toLowerCase(s).equals(s.toLowerCase()); } } /** * Converts all of the characters in this {@code String} to lower case * * @param s the string to convert * @return the {@code String}, converted to lowercase. */ public static String toLowerCase(String s) { char[] values = s.toCharArray(); for (int i = 0; i < values.length; ++i) { if (Character.isLetter(values[i]) && Character.isUpperCase(values[i])) { values[i] = Character.toLowerCase(values[i]); } } return new String(values); } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/strings/Lower.java
135
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * 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 dto; import java.util.Optional; /** * DTO for cake toppings. */ public class CakeToppingInfo { public final Optional<Long> id; public final String name; public final int calories; /** * Constructor. */ public CakeToppingInfo(Long id, String name, int calories) { this.id = Optional.of(id); this.name = name; this.calories = calories; } /** * Constructor. */ public CakeToppingInfo(String name, int calories) { this.id = Optional.empty(); this.name = name; this.calories = calories; } @Override public String toString() { return String.format("CakeToppingInfo id=%d name=%s calories=%d", id.orElse(-1L), name, calories); } }
rajprins/java-design-patterns
layers/src/main/java/dto/CakeToppingInfo.java
136
/* Copyright 2016 The TensorFlow Authors. 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. ==============================================================================*/ /** * Defines classes to build, save, load and execute TensorFlow models. * *<aside class="warning"> * <b>Warning:</b> This API is deprecated and will be removed in a future * version of TensorFlow after <a href="https://tensorflow.org/java">the replacement</a> * is stable. *</aside> * * <p>To get started, see the <a href="https://tensorflow.org/install/lang_java_legacy"> * installation instructions.</a></p> * * <p>The <a * href="https://www.tensorflow.org/code/tensorflow/java/src/main/java/org/tensorflow/examples/LabelImage.java">LabelImage</a> * example demonstrates use of this API to classify images using a pre-trained <a * href="http://arxiv.org/abs/1512.00567">Inception</a> architecture convolutional neural network. * It demonstrates: * * <ul> * <li>Graph construction: using the OperationBuilder class to construct a graph to decode, resize * and normalize a JPEG image. * <li>Model loading: Using Graph.importGraphDef() to load a pre-trained Inception model. * <li>Graph execution: Using a Session to execute the graphs and find the best label for an * image. * </ul> * * <p>Additional examples can be found in the <a * href="https://github.com/tensorflow/java">tensorflow/java</a> GitHub repository. */ package org.tensorflow;
tensorflow/tensorflow
tensorflow/java/src/main/java/org/tensorflow/package-info.java
137
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * 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.iluwatar.memento; import java.util.Stack; import lombok.extern.slf4j.Slf4j; /** * The Memento pattern is a software design pattern that provides the ability to restore an object * to its previous state (undo via rollback). * * <p>The Memento pattern is implemented with three objects: the originator, a caretaker and a * memento. The originator is some object that has an internal state. The caretaker is going to do * something to the originator, but wants to be able to undo the change. The caretaker first asks * the originator for a memento object. Then it does whatever operation (or sequence of operations) * it was going to do. To roll back to the state before the operations, it returns the memento * object to the originator. The memento object itself is an opaque object (one which the caretaker * cannot, or should not, change). When using this pattern, care should be taken if the originator * may change other objects or resources - the memento pattern operates on a single object. * * <p>In this example the object ({@link Star}) gives out a "memento" ({@link StarMemento}) that * contains the state of the object. Later on the memento can be set back to the object restoring * the state. */ @Slf4j public class App { /** * Program entry point. */ public static void main(String[] args) { var states = new Stack<StarMemento>(); var star = new Star(StarType.SUN, 10000000, 500000); LOGGER.info(star.toString()); states.add(star.getMemento()); star.timePasses(); LOGGER.info(star.toString()); states.add(star.getMemento()); star.timePasses(); LOGGER.info(star.toString()); states.add(star.getMemento()); star.timePasses(); LOGGER.info(star.toString()); states.add(star.getMemento()); star.timePasses(); LOGGER.info(star.toString()); while (!states.isEmpty()) { star.setMemento(states.pop()); LOGGER.info(star.toString()); } } }
iluwatar/java-design-patterns
memento/src/main/java/com/iluwatar/memento/App.java
138
/* Copyright 2017 The TensorFlow Authors. 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 org.tensorflow.lite; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Logger; import org.tensorflow.lite.InterpreterApi.Options.TfLiteRuntime; /** Static utility methods for loading the TensorFlowLite runtime and native code. */ public final class TensorFlowLite { // We use Java logging here (java.util.logging), rather than Android logging (android.util.Log), // to avoid unnecessary platform dependencies. This also makes unit testing simpler and faster, // since we can use plain Java tests rather than needing to use Robolectric (android_local_test). // // WARNING: some care is required when using Java logging on Android. In particular, avoid // logging with severity levels lower than "INFO", since the default Java log handler on Android // will discard those, and avoid logging messages with parameters (call String.format instead), // since the default Java log handler on Android only logs the raw message string and doesn't // apply the parameters. private static final Logger logger = Logger.getLogger(TensorFlowLite.class.getName()); private static final String[][] TFLITE_RUNTIME_LIBNAMES = new String[][] { // We load the first library that we find in each group. new String[] { // Regular TF Lite. "tensorflowlite_jni", // Full library, including experimental features. "tensorflowlite_jni_stable", // Subset excluding experimental features. }, new String[] { // TF Lite from system. "tensorflowlite_jni_gms_client" } }; private static final Throwable LOAD_LIBRARY_EXCEPTION; private static volatile boolean isInit = false; static { // Attempt to load the TF Lite runtime's JNI library, trying each alternative name in turn. // If unavailable, catch and save the exception(s); the client may choose to link the native // deps into their own custom native library, so it's not an error if the default library names // can't be loaded. Throwable loadLibraryException = null; for (String[] group : TFLITE_RUNTIME_LIBNAMES) { for (String libName : group) { try { System.loadLibrary(libName); logger.info("Loaded native library: " + libName); break; } catch (UnsatisfiedLinkError e) { logger.info("Didn't load native library: " + libName); if (loadLibraryException == null) { loadLibraryException = e; } else { loadLibraryException.addSuppressed(e); } } } } LOAD_LIBRARY_EXCEPTION = loadLibraryException; } private TensorFlowLite() {} /** * Returns the version of the underlying TensorFlowLite model schema. * * @deprecated Prefer using {@link #runtimeVersion() or #schemaVersion()}. */ @Deprecated public static String version() { return schemaVersion(); } /** Returns the version of the specified TensorFlowLite runtime. */ public static String runtimeVersion(TfLiteRuntime runtime) { return getFactory(runtime, "org.tensorflow.lite.TensorFlowLite", "runtimeVersion") .runtimeVersion(); } /** Returns the version of the default TensorFlowLite runtime. */ public static String runtimeVersion() { return runtimeVersion(null); } /** * Returns the version of the TensorFlowLite model schema that is supported by the specified * TensorFlowLite runtime. */ public static String schemaVersion(TfLiteRuntime runtime) { return getFactory(runtime, "org.tensorflow.lite.TensorFlowLite", "schemaVersion") .schemaVersion(); } /** * Returns the version of the TensorFlowLite model schema that is supported by the default * TensorFlowLite runtime. */ public static String schemaVersion() { return schemaVersion(null); } /** * Ensure the TensorFlowLite native library has been loaded. * * <p>If unsuccessful, throws an UnsatisfiedLinkError with the appropriate error message. */ public static void init() { if (isInit) { return; } try { // Try to invoke a native method (which itself does nothing) to ensure that native libs are // available. nativeDoNothing(); isInit = true; } catch (UnsatisfiedLinkError e) { // Prefer logging the original library loading exception if native methods are unavailable. Throwable exceptionToLog = LOAD_LIBRARY_EXCEPTION != null ? LOAD_LIBRARY_EXCEPTION : e; UnsatisfiedLinkError exceptionToThrow = new UnsatisfiedLinkError( "Failed to load native TensorFlow Lite methods. Check that the correct native" + " libraries are present, and, if using a custom native library, have been" + " properly loaded via System.loadLibrary():\n" + " " + exceptionToLog); exceptionToThrow.initCause(e); throw exceptionToThrow; } } private static native void nativeDoNothing(); /** Encapsulates the use of reflection to find an available TF Lite runtime. */ private static class PossiblyAvailableRuntime { private final InterpreterFactoryApi factory; private final Exception exception; /** * @param namespace: "org.tensorflow.lite" or "com.google.android.gms.tflite". * @param category: "application" or "system". */ PossiblyAvailableRuntime(String namespace, String category) { InterpreterFactoryApi factory = null; Exception exception = null; try { Class<?> clazz = Class.forName(namespace + ".InterpreterFactoryImpl"); Constructor<?> factoryConstructor = clazz.getDeclaredConstructor(); factoryConstructor.setAccessible(true); factory = (InterpreterFactoryApi) factoryConstructor.newInstance(); if (factory != null) { logger.info(String.format("Found %s TF Lite runtime client in %s", category, namespace)); } else { logger.warning( String.format("Failed to construct TF Lite runtime client from %s", namespace)); } } catch (ClassNotFoundException | IllegalAccessException | IllegalArgumentException | InstantiationException | InvocationTargetException | NoSuchMethodException | SecurityException e) { logger.info( String.format("Didn't find %s TF Lite runtime client in %s", category, namespace)); exception = e; } this.exception = exception; this.factory = factory; } /** * @return the InterpreterFactoryApi for this runtime, or null if this runtime wasn't found. */ public InterpreterFactoryApi getFactory() { return factory; } /** * @return The exception that occurred when trying to find this runtime, if any, or null. */ public Exception getException() { return exception; } } // We use static members here for caching, to ensure that we only do the reflective lookups once // and then afterwards re-use the previously computed results. // // We put these static members in nested static classes to ensure that Java will // delay the initialization of these static members until their respective first use; // that's needed to ensure that we only log messages about TF Lite runtime not found // for TF Lite runtimes that the application actually tries to use. private static class RuntimeFromSystem { static final PossiblyAvailableRuntime TFLITE = new PossiblyAvailableRuntime("com.google.android.gms.tflite", "system"); } private static class RuntimeFromApplication { static final PossiblyAvailableRuntime TFLITE = new PossiblyAvailableRuntime("org.tensorflow.lite", "application"); } // We log at most once for each different options.runtime value. private static final AtomicBoolean[] haveLogged = new AtomicBoolean[TfLiteRuntime.values().length]; static { for (int i = 0; i < TfLiteRuntime.values().length; i++) { haveLogged[i] = new AtomicBoolean(); } } static InterpreterFactoryApi getFactory(TfLiteRuntime runtime) { return getFactory(runtime, "org.tensorflow.lite.InterpreterApi.Options", "setRuntime"); } /** * Internal method for finding the TF Lite runtime implementation. * * @param className Class name for method to mention in exception messages. * @param methodName Method name for method to mention in exception messages. */ private static InterpreterFactoryApi getFactory( TfLiteRuntime runtime, String className, String methodName) { Exception exception = null; if (runtime == null) { runtime = TfLiteRuntime.FROM_APPLICATION_ONLY; } if (runtime == TfLiteRuntime.PREFER_SYSTEM_OVER_APPLICATION || runtime == TfLiteRuntime.FROM_SYSTEM_ONLY) { if (RuntimeFromSystem.TFLITE.getFactory() != null) { if (!haveLogged[runtime.ordinal()].getAndSet(true)) { logger.info( String.format( "TfLiteRuntime.%s: " + "Using system TF Lite runtime client from com.google.android.gms", runtime.name())); } return RuntimeFromSystem.TFLITE.getFactory(); } else { exception = RuntimeFromSystem.TFLITE.getException(); } } if (runtime == TfLiteRuntime.PREFER_SYSTEM_OVER_APPLICATION || runtime == TfLiteRuntime.FROM_APPLICATION_ONLY) { if (RuntimeFromApplication.TFLITE.getFactory() != null) { if (!haveLogged[runtime.ordinal()].getAndSet(true)) { logger.info( String.format( "TfLiteRuntime.%s: " + "Using application TF Lite runtime client from org.tensorflow.lite", runtime.name())); } return RuntimeFromApplication.TFLITE.getFactory(); } else { if (exception == null) { exception = RuntimeFromApplication.TFLITE.getException(); } else if (exception.getSuppressed().length == 0) { exception.addSuppressed(RuntimeFromApplication.TFLITE.getException()); } } } String message; switch (runtime) { case FROM_APPLICATION_ONLY: message = String.format( "You should declare a build dependency on org.tensorflow.lite:tensorflow-lite," + " or call .%s with a value other than TfLiteRuntime.FROM_APPLICATION_ONLY" + " (see docs for %s#%s(TfLiteRuntime)).", methodName, className, methodName); break; case FROM_SYSTEM_ONLY: message = String.format( "You should declare a build dependency on" + " com.google.android.gms:play-services-tflite-java," + " or call .%s with a value other than TfLiteRuntime.FROM_SYSTEM_ONLY " + " (see docs for %s#%s).", methodName, className, methodName); break; default: message = "You should declare a build dependency on" + " org.tensorflow.lite:tensorflow-lite or" + " com.google.android.gms:play-services-tflite-java"; break; } throw new IllegalStateException( "Couldn't find TensorFlow Lite runtime's InterpreterFactoryImpl class --" + " make sure your app links in the right TensorFlow Lite runtime. " + message, exception); } }
tensorflow/tensorflow
tensorflow/lite/java/src/main/java/org/tensorflow/lite/TensorFlowLite.java
139
/** * Adam’s parents put up a sign that says “CONGRATULATIONS”. The sign is so big that exactly one * letter fits on each panel. Some of Adam’s younger cousins got bored during the reception and decided * to rearrange the panels. How many unique ways can the panels be arranged (counting the original * arrangement)? * Input * The first line of input is a single non-negative integer. It indicates the number of data sets to follow. * Its value will be less than 30001. * Each data set consists of a single word, in all capital letters. * Each word will have at most 20 letters. There will be no spaces or other punctuation. * The number of arrangements will always be able to fit into an unsigned long int. Note that 12! * is the largest factorial that can fit into an unsigned long int. * Output * For each word, output the number of unique ways that the letters can be rearranged (counting the * original arrangement). Use the format shown in Sample Output, below. * Sample Input * 3 * HAPPY * WEDDING * ADAM * Sample Output * Data set 1: 60 * Data set 2: 2520 * Data set 3: 12 */ //https://uva.onlinejudge.org/index.php?option=onlinejudge&Itemid=99999999&page=show_problem&category=&problem=1279 import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class MischievousChildren { public static void main(String[] args) { Scanner input = new Scanner(System.in); int numberOfCases = input.nextInt(); int currentCase = 1; while (numberOfCases != 0) { String line = input.next(); int numberOfLetters = line.length(); Map<Character, Integer> letterCounter = new HashMap<Character, Integer>(); for (int i = 0; i < numberOfLetters; i++) { char c = line.charAt(i); if (letterCounter.containsKey(c)) { int previousOccurrences = letterCounter.get(c); letterCounter.replace(c, previousOccurrences + 1); } else { letterCounter.put(c, 1); } } String lineWithoutDuplicates = ""; for (int i = 0; i < numberOfLetters; i++) { char c = line.charAt(i); if (!lineWithoutDuplicates.contains(c + "")) { lineWithoutDuplicates = lineWithoutDuplicates + c; } } long nFactorial = computeFactorial(numberOfLetters); for (int i = 0; i < letterCounter.size(); i++) { char c = lineWithoutDuplicates.charAt(i); int numberOfOccurrences = letterCounter.get(c); if (numberOfOccurrences != 1) { long currentProduct = computeFactorial(numberOfOccurrences); nFactorial = nFactorial / currentProduct; } } System.out.println("Data set " + currentCase + ": " + nFactorial); currentCase++; numberOfCases--; } } private static long computeFactorial(int number) { long product = 1; for (int i = 2; i < number + 1; i++) { product = product * i; } return product; } }
kdn251/interviews
uva/MischievousChildren.java
140
//Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. //push(x) -- Push element x onto stack. //pop() -- Removes the element on top of the stack. //top() -- Get the top element. //getMin() -- Retrieve the minimum element in the stack. /** * Your MinStack object will be instantiated and called as such: * MinStack obj = new MinStack(); * obj.push(x); * obj.pop(); * int param_3 = obj.top(); * int param_4 = obj.getMin(); */ class MinStack { class Node { int data; int min; Node next; public Node(int data, int min) { this.data = data; this.min = min; this.next = null; } } Node head; /** initialize your data structure here. */ public MinStack() { } public void push(int x) { if(head == null) { head = new Node(x, x); } else { Node newNode = new Node(x, Math.min(x, head.min)); newNode.next = head; head = newNode; } } public void pop() { head = head.next; } public int top() { return head.data; } public int getMin() { return head.min; } }
kdn251/interviews
leetcode/stack/MinStack.java
141
/** * Hashmat is a brave warrior who with his group of young soldiers moves from one place to another to * fight against his opponents. Before Fighting he just calculates one thing, the difference between his * soldier number and the opponent’s soldier number. From this difference he decides whether to fight or * not. Hashmat’s soldier number is never greater than his opponent. * Input * The input contains two numbers in every line. These two numbers in each line denotes the number * soldiers in Hashmat’s army and his opponent’s army or vice versa. The input numbers are not greater * than 232. Input is terminated by ‘End of File’. * Output * For each line of input, print the difference of number of soldiers between Hashmat’s army and his * opponent’s army. Each output should be in seperate line. * Sample Input * 10 12 * 10 14 * 100 200 * Sample Output * 2 * 4 * 100 */ //https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=996 import java.util.Scanner; public class HashmatWarriors { public static void main(String[] args) { Scanner input = new Scanner(System.in); String nextLine = input.nextLine(); while (!"".equals(nextLine)) { String[] nums = nextLine.split(" "); long firstNum = Long.valueOf(nums[0]); long secondNum = Long.valueOf(nums[1]); System.out.println(Math.abs(secondNum - firstNum)); nextLine = input.nextLine(); } } }
kdn251/interviews
uva/HashmatWarriors.java
142
/** * The short story titled Coconuts, by Ben Ames Williams, appeared in the Saturday Evening Post on * October 9, 1926. The story tells about five men and a monkey who were shipwrecked on an island. * They spent the first night gathering coconuts. During the night, one man woke up and decided to take * his share of the coconuts. He divided them into five piles. One coconut was left over so he gave it to * the monkey, then hid his share and went back to sleep. * Soon a second man woke up and did the same thing. After dividing the coconuts into five piles, * one coconut was left over which he gave to the monkey. He then hid his share and went back to bed. * The third, fourth, and fifth man followed exactly the same procedure. The next morning, after they * all woke up, they divided the remaining coconuts into five equal shares. This time no coconuts were * left over. * An obvious question is “how many coconuts did they originally gather?” There are an infinite * number of answers, but the lowest of these is 3,121. But that’s not our problem here. * Suppose we turn the problem around. If we know the number of coconuts that were gathered, what * is the maximum number of persons (and one monkey) that could have been shipwrecked if the same * procedure could occur? * Input * The input will consist of a sequence of integers, each representing the number of coconuts gathered by * a group of persons (and a monkey) that were shipwrecked. The sequence will be followed by a negative * number. * Output * For each number of coconuts, determine the largest number of persons who could have participated in * the procedure described above. Display the results similar to the manner shown below, in the Sample * Output. There may be no solution for some of the input cases; if so, state that observation. * Sample Input * 25 * 30 * 3121 * -1 * Sample Output * 25 coconuts, 3 people and 1 monkey * 30 coconuts, no solution * 3121 coconuts, 5 people and 1 monkey */ //https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=557 import java.util.Scanner; public class CoconutsRevisited { public static void main(String[] args) { Scanner input = new Scanner(System.in); int i, rez, j; boolean isValid; while (true) { isValid = false; int num = input.nextInt(); if (num == -1) { break; } for (i = (int) (Math.sqrt(num) + 1); i > 1; i--) { rez = num; for (j = 0; j < i && rez % i == 1; j++) { rez = rez - rez / i - 1; } if (rez % i == 0 && i == j) { isValid = true; break; } } if (isValid) { System.out.println(num + " coconuts, " + i + " people and 1 monkey"); } else { System.out.println(num + " coconuts, no solution"); } } } }
kdn251/interviews
uva/CoconutsRevisited.java
143
// At an open-source fair held at a major university, // leaders of open-source projects put sign-up // sheets on the wall, with the project name at the // top in capital letters for identification. // Students then signed up for projects using // their userids. A userid is a string of lower-case // letters and numbers starting with a letter. // The organizer then took all the sheets off the // wall and typed in the information. // Your job is to summarize the number of // students who have signed up for each project. // Some students were overly enthusiastic and put // their name down several times for the same // project. That’s okay, but they should only count // once. Students were asked to commit to a single // project, so any student who has signed up for more // than one project should not count for any project. // There are at most 10,000 students at the university, // and at most 100 projects were advertised. // Input // The input contains several test cases, each one ending with a line that starts with the digit 1. The last // test case is followed by a line starting with the digit 0. // Each test case consists of one or more project sheets. A project sheet consists of a line containing // the project name in capital letters, followed by the userids of students, one per line. // Output // For each test case, output a summary of each project sheet. The summary is one line with the name // of the project followed by the number of students who signed up. These lines should be printed in // decreasing order of number of signups. If two or more projects have the same number of signups, they // should be listed in alphabetical order. // Sample Input // UBQTS TXT // tthumb // LIVESPACE BLOGJAM // philton // aeinstein // YOUBOOK // j97lee // sswxyzy // j97lee // aeinstein // SKINUX // 1 // 0 // Sample Output // YOUBOOK 2 // LIVESPACE BLOGJAM 1 // UBQTS TXT 1 // SKINUX 0 import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.*; import static java.lang.Character.isUpperCase; /** * Created by kdn251 on 3/7/17. */ public class OpenSource { public static void main(String args[]) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line; while(!(line = br.readLine()).equals("0")) { HashMap<String, Integer> projects = new HashMap<String, Integer>(); HashMap<String, String> students = new HashMap<String, String>(); String project = line; projects.put(project, 0); while(!(line = br.readLine()).equals("1")) { if(isUpperCase(line.charAt(0))) { project = line; projects.put(project, 0); } else { if(students.containsKey(line)) { if(students.get(line).equals("")) { continue; } else { if(!students.get(line).equals(project)) { projects.put(students.get(line), projects.get(students.get(line)) - 1); students.put(line, ""); } } } else { projects.put(project, projects.get(project) + 1); students.put(line, project); } } } List<Pair> pairs = new ArrayList<Pair>(); int count = 0; for(String s : projects.keySet()) { pairs.add(new Pair(s, projects.get(s))); } Collections.sort(pairs,new Comparator<Pair>() { public int compare(Pair o1, Pair o2) { if(-Integer.compare(o1.total, o2.total) == 0) { return o1.name.compareTo(o2.name); } return -Integer.compare(o1.total, o2.total); } }); for(Pair p : pairs) { System.out.println(p.name + " " + p.total); } } } } class Pair { String name; int total; Pair(String name, int total) { this.name = name; this.total = total; } }
kdn251/interviews
uva/OpenSource.java
144
/** * In an attempt to bolster her sagging palm-reading business, Madam Phoenix has decided to offer * several numerological treats to her customers. She has been able to convince them that the frequency * of occurrence of the digits in the decimal representation of factorials bear witness to their futures. * Unlike palm-reading, however, she can’t just conjure up these frequencies, so she has employed you to * determine these values. * (Recall that the definition of n! (that is, n factorial) is just 1 × 2 × 3 × · · · × n. As she expects to use * either the day of the week, the day of the month, or the day of the year as the value of n, you must be * able to determine the number of occurrences of each decimal digit in numbers as large as 366 factorial * (366!), which has 781 digits. * Madam Phoenix will be forever (or longer) in your debt; she might even give you a trip if you do * your job well! * Input * The input data for the program is simply a list of integers for which the digit counts are desired. All * of these input values will be less than or equal to 366 and greater than 0, except for the last integer, * which will be zero. Don’t bother to process this zero value; just stop your program at that point. * Output * The output format isn’t too critical, but you should make your program produce results that look * similar to those shown below. * Sample Input * 3 * 8 * 100 * 0 * Sample Output * 3! -- * (0) 0 (1) 0 (2) 0 (3) 0 (4) 0 * (5) 0 (6) 1 (7) 0 (8) 0 (9) 0 * 8! -- * (0) 2 (1) 0 (2) 1 (3) 1 (4) 1 * (5) 0 (6) 0 (7) 0 (8) 0 (9) 0 * 100! -- * (0) 30 (1) 15 (2) 19 (3) 10 (4) 10 * (5) 14 (6) 19 (7) 7 (8) 14 (9) 20 */ //https://uva.onlinejudge.org/index.php?option=onlinejudge&Itemid=99999999&page=show_problem&category=&problem=260 import java.math.BigInteger; import java.util.Scanner; public class FactorialFrequenices { public static void main(String[] args) { Scanner input = new Scanner(System.in); int number = input.nextInt(); while (number != 0) { BigInteger product = BigInteger.ONE; for (int i = 2; i < number + 1; i++) { product = product.multiply(BigInteger.valueOf(i)); } int[] digitCounter = new int[10]; BigInteger productValue = product; while (!productValue.equals(BigInteger.ZERO)) { digitCounter[Integer.valueOf(productValue.mod(BigInteger.TEN) .toString())]++; productValue = productValue.divide(BigInteger.TEN); } formatOutput(number, digitCounter); number = input.nextInt(); } } private static void formatOutput(int number, int[] digits) { System.out.println(number + "! --"); for (int i = 0; i < 10; i++) { if (i != 0 || i != 9 || i != 4) System.out.printf(" "); System.out.printf("(%d)%5d", i, digits[i]); if (i == 4 || i == 9) System.out.printf("\n"); } } }
kdn251/interviews
uva/FactorialFrequenices.java
145
import java.io.*; import java.util.*; /************************************************************************************************************************************** * Class Feature *****/ class Feature implements Debuggable { public static String NOMINAL = "NOMINAL", CONTINUOUS = "CONTINUOUS", CLASS = "CLASS"; public static String TYPE[] = {Feature.NOMINAL, Feature.CONTINUOUS, Feature.CLASS}; public static boolean MODALITIES[] = {true, false, false}; public static int CLASS_INDEX = 2; public static double MODALITY_PRESENT = 1.0, MODALITY_ABSENT = 0.0; public static double MINV = -1.0, MAXV = 1.0; // values used for normalization in [MINV, MAXV] public static double MAX_CLASS_MAGNITUDE = 1.0; String name; String type; double minn, maxx; Vector modalities; // applies to nominal feature Vector tests; // set of test values as returned by TEST_LIST public static Vector TEST_LIST(Feature f) { // generates a vector of a list of tests -- does not depend on training data for privacy // purposes // if continuous, list of evenly spaces ties // if nominal, list of partial non-empty subsets of the whole set Vector v = new Vector(); if (IS_CONTINUOUS(f.type)) { v = null; } else if (HAS_MODALITIES(f.type)) { v = Utils.ALL_NON_TRIVIAL_SUBSETS(f.modalities); } return v; } public void update_tests(double[] all_vals) { if ((all_vals == null) || (all_vals.length <= 1)) Dataset.perror("Feature.class :: <= 1 observed values for continuous feature"); Vector v = new Vector(); int i; minn = all_vals[0]; maxx = all_vals[all_vals.length - 1]; for (i = 0; i < all_vals.length - 1; i++) { if (all_vals[i] == all_vals[i + 1]) Dataset.perror("Feature.class :: repeated feature values"); v.addElement(new Double((all_vals[i] + all_vals[i + 1]) / 2.0)); } tests = v; } public String tests() { int i, j; String v = "{"; Vector dv; for (i = 0; i < tests.size(); i++) { if (Feature.IS_CONTINUOUS(type)) v += DF6.format(((Double) tests.elementAt(i)).doubleValue()); else if (Feature.HAS_MODALITIES(type)) { dv = ((Vector) tests.elementAt(i)); for (j = 0; j < dv.size(); j++) v += ((String) dv.elementAt(j)); } if (i < tests.size() - 1) v += ", "; } v += "}"; return v; } public static boolean IS_CONTINUOUS(String t) { return (t.equals(Feature.CONTINUOUS)); } public static boolean IS_CLASS(String t) { return (t.equals(Feature.CLASS)); } static int INDEX(String t) { int i = 0; do { if (t.equals(TYPE[i])) return i; i++; } while (i < TYPE.length); Dataset.perror("No type found for " + t); return -1; } static boolean HAS_MODALITIES(String t) { // synonym of is nominal return MODALITIES[Feature.INDEX(t)]; } Feature(String n, String t, Vector m) { name = n; type = t; modalities = null; if (Feature.HAS_MODALITIES(t)) modalities = m; tests = Feature.TEST_LIST(this); } public boolean has_in_range(String s) { if (Feature.IS_CONTINUOUS(type)) Dataset.perror( "Feature.class :: Continuous feature " + this + " queried for nominal value " + s); if (!Feature.HAS_MODALITIES(type)) Dataset.perror("Feature.class :: feature type " + type + " unregistered "); int i; String ss; for (i = 0; i < modalities.size(); i++) { ss = (String) modalities.elementAt(i); if (ss.equals(s)) return true; } return false; } public String range() { String v = ""; int i; if (Feature.HAS_MODALITIES(type)) { v += "{"; for (i = 0; i < modalities.size(); i++) { v += "" + modalities.elementAt(i); if (i < modalities.size() - 1) v += ", "; } v += "}"; } else if (Feature.IS_CONTINUOUS(type)) { v += "[" + minn + ", " + maxx + "]"; } return v; } public boolean example_goes_left(Example e, int index_feature_in_e, int index_test) { // continuous values : <= is left, > is right // nominal values : in the set is left, otherwise is right double cv, tv; String nv; Vector ssv; int i; if (Feature.IS_CONTINUOUS(type)) { if (e.typed_features.elementAt(index_feature_in_e).getClass().getName().equals("String")) Dataset.perror( "Feature.class :: wrong class match : " + e.typed_features.elementAt(index_feature_in_e) + " not a Double"); cv = ((Double) e.typed_features.elementAt(index_feature_in_e)).doubleValue(); tv = ((Double) tests.elementAt(index_test)).doubleValue(); if (cv <= tv) return true; return false; } else if (Feature.HAS_MODALITIES(type)) { if (e.typed_features.elementAt(index_feature_in_e).getClass().getName().equals("Double")) Dataset.perror( "Feature.class :: wrong class match : " + e.typed_features.elementAt(index_feature_in_e) + " not a String"); nv = ((String) e.typed_features.elementAt(index_feature_in_e)); ssv = (Vector) tests.elementAt(index_test); for (i = 0; i < ssv.size(); i++) { if (nv.equals((String) ssv.elementAt(i))) return true; } return false; } else Dataset.perror("Feature.class :: no type available for feature " + this); return false; } public String display_test(int index_test) { String v = name; int i; Vector ssv; if (Feature.IS_CONTINUOUS(type)) v += " <= " + DF.format(((Double) tests.elementAt(index_test)).doubleValue()); else if (Feature.HAS_MODALITIES(type)) { v += " in {"; ssv = (Vector) tests.elementAt(index_test); for (i = 0; i < ssv.size(); i++) { v += (String) ssv.elementAt(i); if (i < ssv.size() - 1) v += ", "; } v += "}"; } else Dataset.perror("Feature.class :: no type available for feature " + this); return v; } public String toString() { String v = ""; int i; v += name + " -- " + type + " in " + range() + " -- tests : " + tests(); return v; } }
google-research/google-research
tempered_boosting/Feature.java
146
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * 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.iluwatar.memento; /** * External interface to memento. */ public interface StarMemento { }
smedals/java-design-patterns
memento/src/main/java/com/iluwatar/memento/StarMemento.java
147
/** * The most relevant definition for this problem is 2a: An integer g > 1 is said to be prime if and only * if its only positive divisors are itself and one (otherwise it is said to be composite). For example, the * number 21 is composite; the number 23 is prime. Note that the decompositon of a positive number g * into its prime factors, i.e., * g = f1 × f2 × · · · × fn * is unique if we assert that fi > 1 for all i and fi ≤ fj for i < j. * One interesting class of prime numbers are the so-called Mersenne primes which are of the form * 2 * p − 1. Euler proved that 2 * 31 − 1 is prime in 1772 — all without the aid of a computer. * Input * The input will consist of a sequence of numbers. Each line of input will contain one number g in the * range −2 * 31 < g < 2 * 31, but different of -1 and 1. The end of input will be indicated by an input line * having a value of zero. * Output * For each line of input, your program should print a line of output consisting of the input number and * its prime factors. For an input number g > 0, g = f1 × f2 × · · · × fn, where each fi * is a prime number * greater than unity (with fi ≤ fj for i < j), the format of the output line should be * g = f1 x f2 x . . . x fn * When g < 0, if | g |= f1 × f2 × · · · × fn, the format of the output line should be * g = -1 x f1 x f2 x . . . x fn * Sample Input * -190 * -191 * -192 * -193 * -194 * 195 * 196 * 197 * 198 * 199 * 200 * 0 * Sample Output * -190 = -1 x 2 x 5 x 19 * -191 = -1 x 191 * -192 = -1 x 2 x 2 x 2 x 2 x 2 x 2 x 3 * -193 = -1 x 193 * -194 = -1 x 2 x 97 * 195 = 3 x 5 x 13 * 196 = 2 x 2 x 7 x 7 * 197 = 197 * 198 = 2 x 3 x 3 x 11 * 199 = 199 * 200 = 2 x 2 x 2 x 5 x 5 */ //https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=524 import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; public class PrimeFactors { public static void main(String[] args) { Scanner input = new Scanner(System.in); int number = input.nextInt(); boolean[] isPrime = generatePrimeNumbers(); while (number != 0) { boolean isNegative = false; if (number < 0) { isNegative = true; number = Math.abs(number); } int originalNumber = number; formatOutput(originalNumber, sieveOfEratosthenes(isPrime, originalNumber), isNegative); number = input.nextInt(); } } public static List<Integer> sieveOfEratosthenes(boolean[] isPrime, int number) { List<Integer> primeFactors = new ArrayList<Integer>(); int squareRootOfOriginalNumber = (int) Math.sqrt(number); for (int i = 2; i <= squareRootOfOriginalNumber; i++) { if (isPrime[i]) { while (number % i == 0) { primeFactors.add(i); number = number / i; } } } if (number != 1) { primeFactors.add(number); } return primeFactors; } static void formatOutput(int number, List<Integer> primeFactors, boolean isNegative) { if (isNegative) { number *= -1; } StringBuilder output = new StringBuilder(number + " = "); int numberOfPrimeFactors = primeFactors.size(); if (numberOfPrimeFactors == 1) { if (isNegative) { output.append("-1 x " + (number * (-1))); } else { output.append(number); } } else { Collections.sort(primeFactors); if (isNegative) { output.append("-1 x "); } for (int i = 0; i < numberOfPrimeFactors - 1; i++) { output.append(primeFactors.get(i) + " x "); } output.append(primeFactors.get(numberOfPrimeFactors - 1)); } System.out.println(output); } static boolean[] generatePrimeNumbers() { int number = (int) Math.sqrt(Integer.MAX_VALUE); boolean[] isPrime = new boolean[number + 1]; for (int i = 2; i < number + 1; i++) { isPrime[i] = true; } for (int factor = 2; factor * factor < number + 1; factor++) { if (isPrime[factor]) { for (int j = factor; j * factor < number + 1; j++) { isPrime[j * factor] = false; } } } return isPrime; } }
kdn251/interviews
uva/PrimeFactors.java
148
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * 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.iluwatar.currying; import java.time.LocalDate; import java.util.Objects; import java.util.function.Function; import lombok.AllArgsConstructor; /** * Book class. */ @AllArgsConstructor public class Book { private final Genre genre; private final String author; private final String title; private final LocalDate publicationDate; @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Book book = (Book) o; return Objects.equals(author, book.author) && Objects.equals(genre, book.genre) && Objects.equals(title, book.title) && Objects.equals(publicationDate, book.publicationDate); } @Override public int hashCode() { return Objects.hash(author, genre, title, publicationDate); } @Override public String toString() { return "Book{" + "genre=" + genre + ", author='" + author + '\'' + ", title='" + title + '\'' + ", publicationDate=" + publicationDate + '}'; } /** * Curried book builder/creator function. */ static Function<Genre, Function<String, Function<String, Function<LocalDate, Book>>>> book_creator = bookGenre -> bookAuthor -> bookTitle -> bookPublicationDate -> new Book(bookGenre, bookAuthor, bookTitle, bookPublicationDate); /** * Implements the builder pattern using functional interfaces to create a more readable book * creator function. This function is equivalent to the BOOK_CREATOR function. */ public static AddGenre builder() { return genre -> author -> title -> publicationDate -> new Book(genre, author, title, publicationDate); } /** * Functional interface which adds the genre to a book. */ public interface AddGenre { Book.AddAuthor withGenre(Genre genre); } /** * Functional interface which adds the author to a book. */ public interface AddAuthor { Book.AddTitle withAuthor(String author); } /** * Functional interface which adds the title to a book. */ public interface AddTitle { Book.AddPublicationDate withTitle(String title); } /** * Functional interface which adds the publication date to a book. */ public interface AddPublicationDate { Book withPublicationDate(LocalDate publicationDate); } }
Skarlso/java-design-patterns
currying/src/main/java/com/iluwatar/currying/Book.java
149
package com.thealgorithms.maths; import java.util.ArrayList; import java.util.Collections; /** * Class for calculating the Fast Fourier Transform (FFT) of a discrete signal * using the Cooley-Tukey algorithm. * * @author Ioannis Karavitsis * @version 1.0 */ public final class FFT { private FFT() { } /** * This class represents a complex number and has methods for basic * operations. * * <p> * More info: * https://introcs.cs.princeton.edu/java/32class/Complex.java.html */ static class Complex { private double real, img; /** * Default Constructor. Creates the complex number 0. */ Complex() { real = 0; img = 0; } /** * Constructor. Creates a complex number. * * @param r The real part of the number. * @param i The imaginary part of the number. */ Complex(double r, double i) { real = r; img = i; } /** * Returns the real part of the complex number. * * @return The real part of the complex number. */ public double getReal() { return real; } /** * Returns the imaginary part of the complex number. * * @return The imaginary part of the complex number. */ public double getImaginary() { return img; } /** * Adds this complex number to another. * * @param z The number to be added. * @return The sum. */ public Complex add(Complex z) { Complex temp = new Complex(); temp.real = this.real + z.real; temp.img = this.img + z.img; return temp; } /** * Subtracts a number from this complex number. * * @param z The number to be subtracted. * @return The difference. */ public Complex subtract(Complex z) { Complex temp = new Complex(); temp.real = this.real - z.real; temp.img = this.img - z.img; return temp; } /** * Multiplies this complex number by another. * * @param z The number to be multiplied. * @return The product. */ public Complex multiply(Complex z) { Complex temp = new Complex(); temp.real = this.real * z.real - this.img * z.img; temp.img = this.real * z.img + this.img * z.real; return temp; } /** * Multiplies this complex number by a scalar. * * @param n The real number to be multiplied. * @return The product. */ public Complex multiply(double n) { Complex temp = new Complex(); temp.real = this.real * n; temp.img = this.img * n; return temp; } /** * Finds the conjugate of this complex number. * * @return The conjugate. */ public Complex conjugate() { Complex temp = new Complex(); temp.real = this.real; temp.img = -this.img; return temp; } /** * Finds the magnitude of the complex number. * * @return The magnitude. */ public double abs() { return Math.hypot(this.real, this.img); } /** * Divides this complex number by another. * * @param z The divisor. * @return The quotient. */ public Complex divide(Complex z) { Complex temp = new Complex(); double d = z.abs() * z.abs(); d = (double) Math.round(d * 1000000000d) / 1000000000d; temp.real = (this.real * z.real + this.img * z.img) / (d); temp.img = (this.img * z.real - this.real * z.img) / (d); return temp; } /** * Divides this complex number by a scalar. * * @param n The divisor which is a real number. * @return The quotient. */ public Complex divide(double n) { Complex temp = new Complex(); temp.real = this.real / n; temp.img = this.img / n; return temp; } } /** * Iterative In-Place Radix-2 Cooley-Tukey Fast Fourier Transform Algorithm * with Bit-Reversal. The size of the input signal must be a power of 2. If * it isn't then it is padded with zeros and the output FFT will be bigger * than the input signal. * * <p> * More info: * https://www.algorithm-archive.org/contents/cooley_tukey/cooley_tukey.html * https://www.geeksforgeeks.org/iterative-fast-fourier-transformation-polynomial-multiplication/ * https://en.wikipedia.org/wiki/Cooley%E2%80%93Tukey_FFT_algorithm * https://cp-algorithms.com/algebra/fft.html * @param x The discrete signal which is then converted to the FFT or the * IFFT of signal x. * @param inverse True if you want to find the inverse FFT. * @return */ public static ArrayList<Complex> fft(ArrayList<Complex> x, boolean inverse) { /* Pad the signal with zeros if necessary */ paddingPowerOfTwo(x); int N = x.size(); int log2N = findLog2(N); x = fftBitReversal(N, log2N, x); int direction = inverse ? -1 : 1; /* Main loop of the algorithm */ for (int len = 2; len <= N; len *= 2) { double angle = -2 * Math.PI / len * direction; Complex wlen = new Complex(Math.cos(angle), Math.sin(angle)); for (int i = 0; i < N; i += len) { Complex w = new Complex(1, 0); for (int j = 0; j < len / 2; j++) { Complex u = x.get(i + j); Complex v = w.multiply(x.get(i + j + len / 2)); x.set(i + j, u.add(v)); x.set(i + j + len / 2, u.subtract(v)); w = w.multiply(wlen); } } } x = inverseFFT(N, inverse, x); return x; } /* Find the log2(N) */ public static int findLog2(int N) { int log2N = 0; while ((1 << log2N) < N) { log2N++; } return log2N; } /* Swap the values of the signal with bit-reversal method */ public static ArrayList<Complex> fftBitReversal(int N, int log2N, ArrayList<Complex> x) { int reverse; for (int i = 0; i < N; i++) { reverse = reverseBits(i, log2N); if (i < reverse) { Collections.swap(x, i, reverse); } } return x; } /* Divide by N if we want the inverse FFT */ public static ArrayList<Complex> inverseFFT(int N, boolean inverse, ArrayList<Complex> x) { if (inverse) { for (int i = 0; i < x.size(); i++) { Complex z = x.get(i); x.set(i, z.divide(N)); } } return x; } /** * This function reverses the bits of a number. It is used in Cooley-Tukey * FFT algorithm. * * <p> * E.g. num = 13 = 00001101 in binary log2N = 8 Then reversed = 176 = * 10110000 in binary * * <p> * More info: https://cp-algorithms.com/algebra/fft.html * https://www.geeksforgeeks.org/write-an-efficient-c-program-to-reverse-bits-of-a-number/ * * @param num The integer you want to reverse its bits. * @param log2N The number of bits you want to reverse. * @return The reversed number */ private static int reverseBits(int num, int log2N) { int reversed = 0; for (int i = 0; i < log2N; i++) { if ((num & (1 << i)) != 0) { reversed |= 1 << (log2N - 1 - i); } } return reversed; } /** * This method pads an ArrayList with zeros in order to have a size equal to * the next power of two of the previous size. * * @param x The ArrayList to be padded. */ private static void paddingPowerOfTwo(ArrayList<Complex> x) { int n = 1; int oldSize = x.size(); while (n < oldSize) { n *= 2; } for (int i = 0; i < n - oldSize; i++) { x.add(new Complex()); } } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/maths/FFT.java
150
package com.thealgorithms.others; import java.util.Comparator; import java.util.PriorityQueue; import java.util.Scanner; // node class is the basic structure // of each node present in the Huffman - tree. class HuffmanNode { int data; char c; HuffmanNode left; HuffmanNode right; } // comparator class helps to compare the node // on the basis of one of its attribute. // Here we will be compared // on the basis of data values of the nodes. class MyComparator implements Comparator<HuffmanNode> { public int compare(HuffmanNode x, HuffmanNode y) { return x.data - y.data; } } public final class Huffman { private Huffman() { } // recursive function to print the // huffman-code through the tree traversal. // Here s is the huffman - code generated. public static void printCode(HuffmanNode root, String s) { // base case; if the left and right are null // then its a leaf node and we print // the code s generated by traversing the tree. if (root.left == null && root.right == null && Character.isLetter(root.c)) { // c is the character in the node System.out.println(root.c + ":" + s); return; } // if we go to left then add "0" to the code. // if we go to the right add"1" to the code. // recursive calls for left and // right sub-tree of the generated tree. printCode(root.left, s + "0"); printCode(root.right, s + "1"); } // main function public static void main(String[] args) { Scanner s = new Scanner(System.in); // number of characters. int n = 6; char[] charArray = {'a', 'b', 'c', 'd', 'e', 'f'}; int[] charfreq = {5, 9, 12, 13, 16, 45}; // creating a priority queue q. // makes a min-priority queue(min-heap). PriorityQueue<HuffmanNode> q = new PriorityQueue<HuffmanNode>(n, new MyComparator()); for (int i = 0; i < n; i++) { // creating a Huffman node object // and add it to the priority queue. HuffmanNode hn = new HuffmanNode(); hn.c = charArray[i]; hn.data = charfreq[i]; hn.left = null; hn.right = null; // add functions adds // the huffman node to the queue. q.add(hn); } // create a root node HuffmanNode root = null; // Here we will extract the two minimum value // from the heap each time until // its size reduces to 1, extract until // all the nodes are extracted. while (q.size() > 1) { // first min extract. HuffmanNode x = q.peek(); q.poll(); // second min extarct. HuffmanNode y = q.peek(); q.poll(); // new node f which is equal HuffmanNode f = new HuffmanNode(); // to the sum of the frequency of the two nodes // assigning values to the f node. f.data = x.data + y.data; f.c = '-'; // first extracted node as left child. f.left = x; // second extracted node as the right child. f.right = y; // marking the f node as the root node. root = f; // add this node to the priority-queue. q.add(f); } // print the codes by traversing the tree printCode(root, ""); s.close(); } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/others/Huffman.java
151
// Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target. // Example: // nums = [1, 2, 3] // target = 4 // The possible combination ways are: // (1, 1, 1, 1) // (1, 1, 2) // (1, 2, 1) // (1, 3) // (2, 1, 1) // (2, 2) // (3, 1) // Note that different sequences are counted as different combinations. // Therefore the output is 7. // Follow up: // What if negative numbers are allowed in the given array? // How does it change the problem? // What limitation we need to add to the question to allow negative numbers? public class Solution { public int combinationSum4(int[] nums, int target) { int[] dp = new int[target + 1]; dp[0] = 1; for(int i = 1; i < dp.length; i++) { for(int j = 0; j < nums.length; j++) { if(i - nums[j] >= 0) { dp[i] += dp[i - nums[j]]; } } } return dp[target]; } }
kdn251/interviews
company/facebook/CombinationSumIV.java
152
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * 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.iluwatar.slob.lob; import static com.iluwatar.slob.lob.Animal.iterateXmlForAnimalAndPlants; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; /** * Creates an object Forest which contains animals and plants as its constituents. Animals may eat * plants or other animals in the forest. */ @Data @NoArgsConstructor @AllArgsConstructor public class Forest implements Serializable { private String name; private Set<Animal> animals = new HashSet<>(); private Set<Plant> plants = new HashSet<>(); /** * Provides the representation of Forest in XML form. * * @return XML Element */ public Element toXmlElement() throws ParserConfigurationException { Document xmlDoc = getXmlDoc(); Element forestXml = xmlDoc.createElement("Forest"); forestXml.setAttribute("name", name); Element animalsXml = xmlDoc.createElement("Animals"); for (Animal animal : animals) { Element animalXml = animal.toXmlElement(xmlDoc); animalsXml.appendChild(animalXml); } forestXml.appendChild(animalsXml); Element plantsXml = xmlDoc.createElement("Plants"); for (Plant plant : plants) { Element plantXml = plant.toXmlElement(xmlDoc); plantsXml.appendChild(plantXml); } forestXml.appendChild(plantsXml); return forestXml; } /** * Returns XMLDoc to use for XML creation. * * @return XML DOC Object * @throws ParserConfigurationException {@inheritDoc} */ private Document getXmlDoc() throws ParserConfigurationException { return DocumentBuilderFactory.newDefaultInstance().newDocumentBuilder().newDocument(); } /** * Parses the Forest Object from the input XML Document. * * @param document the XML document from which the Forest is to be parsed */ public void createObjectFromXml(Document document) { name = document.getDocumentElement().getAttribute("name"); NodeList nodeList = document.getElementsByTagName("*"); iterateXmlForAnimalAndPlants(nodeList, animals, plants); } @Override public String toString() { StringBuilder sb = new StringBuilder("\n"); sb.append("Forest Name = ").append(name).append("\n"); sb.append("Animals found in the ").append(name).append(" Forest: \n"); for (Animal animal : animals) { sb.append("\n--------------------------\n"); sb.append(animal.toString()); sb.append("\n--------------------------\n"); } sb.append("\n"); sb.append("Plants in the ").append(name).append(" Forest: \n"); for (Plant plant : plants) { sb.append("\n--------------------------\n"); sb.append(plant.toString()); sb.append("\n--------------------------\n"); } return sb.toString(); } }
rajprins/java-design-patterns
slob/src/main/java/com/iluwatar/slob/lob/Forest.java
153
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * 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.iluwatar.memento; /** * StarType enumeration. */ public enum StarType { SUN("sun"), RED_GIANT("red giant"), WHITE_DWARF("white dwarf"), SUPERNOVA("supernova"), DEAD("dead star"); private final String title; StarType(String title) { this.title = title; } @Override public String toString() { return title; } }
smedals/java-design-patterns
memento/src/main/java/com/iluwatar/memento/StarType.java
154
package com.thealgorithms.others; /** * Dijkstra's algorithm,is a graph search algorithm that solves the * single-source shortest path problem for a graph with nonnegative edge path * costs, producing a shortest path tree. * * <p> * NOTE: The inputs to Dijkstra's algorithm are a directed and weighted graph * consisting of 2 or more nodes, generally represented by an adjacency matrix * or list, and a start node. * * <p> * Original source of code: * https://rosettacode.org/wiki/Dijkstra%27s_algorithm#Java Also most of the * comments are from RosettaCode. */ import java.util.HashMap; import java.util.Map; import java.util.NavigableSet; import java.util.TreeSet; public final class Dijkstra { private Dijkstra() { } private static final Graph.Edge[] GRAPH = { // Distance from node "a" to node "b" is 7. // In the current Graph there is no way to move the other way (e,g, from "b" to "a"), // a new edge would be needed for that new Graph.Edge("a", "b", 7), new Graph.Edge("a", "c", 9), new Graph.Edge("a", "f", 14), new Graph.Edge("b", "c", 10), new Graph.Edge("b", "d", 15), new Graph.Edge("c", "d", 11), new Graph.Edge("c", "f", 2), new Graph.Edge("d", "e", 6), new Graph.Edge("e", "f", 9), }; private static final String START = "a"; private static final String END = "e"; /** * main function Will run the code with "GRAPH" that was defined above. */ public static void main(String[] args) { Graph g = new Graph(GRAPH); g.dijkstra(START); g.printPath(END); // g.printAllPaths(); } } class Graph { // mapping of vertex names to Vertex objects, built from a set of Edges private final Map<String, Vertex> graph; /** * One edge of the graph (only used by Graph constructor) */ public static class Edge { public final String v1, v2; public final int dist; Edge(String v1, String v2, int dist) { this.v1 = v1; this.v2 = v2; this.dist = dist; } } /** * One vertex of the graph, complete with mappings to neighbouring vertices */ public static class Vertex implements Comparable<Vertex> { public final String name; // MAX_VALUE assumed to be infinity public int dist = Integer.MAX_VALUE; public Vertex previous = null; public final Map<Vertex, Integer> neighbours = new HashMap<>(); Vertex(String name) { this.name = name; } private void printPath() { if (this == this.previous) { System.out.printf("%s", this.name); } else if (this.previous == null) { System.out.printf("%s(unreached)", this.name); } else { this.previous.printPath(); System.out.printf(" -> %s(%d)", this.name, this.dist); } } public int compareTo(Vertex other) { if (dist == other.dist) { return name.compareTo(other.name); } return Integer.compare(dist, other.dist); } @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null || getClass() != object.getClass()) { return false; } if (!super.equals(object)) { return false; } Vertex vertex = (Vertex) object; if (dist != vertex.dist) { return false; } if (name != null ? !name.equals(vertex.name) : vertex.name != null) { return false; } if (previous != null ? !previous.equals(vertex.previous) : vertex.previous != null) { return false; } return neighbours != null ? neighbours.equals(vertex.neighbours) : vertex.neighbours == null; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + dist; result = 31 * result + (previous != null ? previous.hashCode() : 0); result = 31 * result + (neighbours != null ? neighbours.hashCode() : 0); return result; } @Override public String toString() { return "(" + name + ", " + dist + ")"; } } /** * Builds a graph from a set of edges */ Graph(Edge[] edges) { graph = new HashMap<>(edges.length); // one pass to find all vertices for (Edge e : edges) { if (!graph.containsKey(e.v1)) { graph.put(e.v1, new Vertex(e.v1)); } if (!graph.containsKey(e.v2)) { graph.put(e.v2, new Vertex(e.v2)); } } // another pass to set neighbouring vertices for (Edge e : edges) { graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist); // graph.get(e.v2).neighbours.put(graph.get(e.v1), e.dist); // also do this for an // undirected graph } } /** * Runs dijkstra using a specified source vertex */ public void dijkstra(String startName) { if (!graph.containsKey(startName)) { System.err.printf("Graph doesn't contain start vertex \"%s\"%n", startName); return; } final Vertex source = graph.get(startName); NavigableSet<Vertex> q = new TreeSet<>(); // set-up vertices for (Vertex v : graph.values()) { v.previous = v == source ? source : null; v.dist = v == source ? 0 : Integer.MAX_VALUE; q.add(v); } dijkstra(q); } /** * Implementation of dijkstra's algorithm using a binary heap. */ private void dijkstra(final NavigableSet<Vertex> q) { Vertex u, v; while (!q.isEmpty()) { // vertex with shortest distance (first iteration will return source) u = q.pollFirst(); if (u.dist == Integer.MAX_VALUE) { break; // we can ignore u (and any other remaining vertices) since they are // unreachable } // look at distances to each neighbour for (Map.Entry<Vertex, Integer> a : u.neighbours.entrySet()) { v = a.getKey(); // the neighbour in this iteration final int alternateDist = u.dist + a.getValue(); if (alternateDist < v.dist) { // shorter path to neighbour found q.remove(v); v.dist = alternateDist; v.previous = u; q.add(v); } } } } /** * Prints a path from the source to the specified vertex */ public void printPath(String endName) { if (!graph.containsKey(endName)) { System.err.printf("Graph doesn't contain end vertex \"%s\"%n", endName); return; } graph.get(endName).printPath(); System.out.println(); } /** * Prints the path from the source to every vertex (output order is not * guaranteed) */ public void printAllPaths() { for (Vertex v : graph.values()) { v.printPath(); System.out.println(); } } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/others/Dijkstra.java
155
//There are 1000 buckets, one and only one of them contains poison, the rest are filled with water. //They all look the same. If a pig drinks that poison it will die within 15 minutes. What is the //minimum amount of pigs you need to figure out which bucket contains the poison within one hour. //Answer this question, and write an algorithm for the follow-up general case. //Follow-up: //If there are n buckets and a pig drinking poison will die within m minutes, how many pigs (x) //you need to figure out the "poison" bucket within p minutes? There is exact one bucket with poison. class PoorPigs { public int poorPigs(int buckets, int minutesToDie, int minutesToTest) { int numPigs = 0; while (Math.pow(minutesToTest / minutesToDie + 1, numPigs) < buckets) { numPigs++; } return numPigs; } }
kdn251/interviews
leetcode/math/PoorPigs.java
156
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * 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 concreteextensions; import abstractextensions.SoldierExtension; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import units.SoldierUnit; /** * Class defining Soldier. */ @Slf4j public record Soldier(SoldierUnit unit) implements SoldierExtension { @Override public void soldierReady() { LOGGER.info("[Soldier] " + unit.getName() + " is ready!"); } }
iluwatar/java-design-patterns
extension-objects/src/main/java/concreteextensions/Soldier.java
157
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * 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.iluwatar.virtual.proxy; /** * The main application class that sets up and runs the Virtual Proxy pattern demo. */ public class App { /** * The entry point of the application. * * @param args the command line arguments */ public static void main(String[] args) { ExpensiveObject videoObject = new VideoObjectProxy(); videoObject.process(); // The first call creates and plays the video videoObject.process(); // Subsequent call uses the already created object } }
iluwatar/java-design-patterns
virtual-proxy/src/main/java/com/iluwatar/virtual/proxy/App.java
158
// There is a fence with n posts, each post can be painted with one of the k colors. // You have to paint all the posts such that no more than two adjacent fence posts have the same color. // Return the total number of ways you can paint the fence. // Note: // n and k are non-negative integers. public class PaintFence { public int numWays(int n, int k) { if(n <= 0) { return 0; } int sameColorCounts = 0; int differentColorCounts = k; for(int i = 2; i <= n; i++) { int temp = differentColorCounts; differentColorCounts = (sameColorCounts + differentColorCounts) * (k - 1); sameColorCounts = temp; } return sameColorCounts + differentColorCounts; } }
kdn251/interviews
company/google/PaintFence.java
159
/** * Your girlfriend Marry has some problems with programming task teacher gave her. Since you have * the great programming skills it won’t be a problem for you to help her. And certainly you don’t want * Marry to have her time spent on this task because you were planning to go to the cinema with her this * weekend. If you accomplish this task Marry will be very grateful and will definitely go with you to the * cinema and maybe even more. So it’s up to you now * That’s the task she was given: * Number 0 ≤ M ≤ 101000 is given, and a set S of different numbers from the interval [1;12]. All * numbers in this set are integers. Number M is said to be wonderful if it is divisible by all numbers in * set S. Find out whether or not number M is wonderful. * Input * First line of input data contains number N (0 < N ≤ 2000). Then N tests follow each described on * two lines. First line of each test case contains number M. Second line contains the number of elements * in a set S followed by a space and the numbers in the set. Numbers of this set are separated by a space * character. * Output * Output one line for each test case: ‘M - Wonderful.’, if the number is wonderful or ‘M - Simple.’ * if it is not. Replace M character with the corresponding number. Refer output data for details. * Sample Input * 4 * 0 * 12 1 2 3 4 5 6 7 8 9 10 11 12 * 379749833583241 * 1 11 * 3909821048582988049 * 1 7 * 10 * 3 1 2 9 * Sample Output * 0 - Wonderful. * 379749833583241 - Wonderful. * 3909821048582988049 - Wonderful. * 10 - Simple. */ //https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2319 import java.math.BigInteger; import java.util.Scanner; public class TheHugeOne { public static void main(String[] args) { Scanner input = new Scanner(System.in); int numberOfTestCases = input.nextInt(); while (numberOfTestCases != 0) { BigInteger M = input.nextBigInteger(); input.nextLine(); String[] elementsLine = input.nextLine().split(" "); boolean found = false; for (int i = 1; i < elementsLine.length; i++) { BigInteger number = new BigInteger(elementsLine[i]); if (!M.mod(number).equals(BigInteger.ZERO)) { System.out.println(M + " - Simple."); found = true; break; } } if (!found) { System.out.println(M + " - Wonderful."); } numberOfTestCases--; } } }
kdn251/interviews
uva/TheHugeOne.java
160
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * 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.iluwatar.strategy; import lombok.extern.slf4j.Slf4j; /** * Lambda implementation for enum strategy pattern. */ @Slf4j public class LambdaStrategy { /** * Enum to demonstrate strategy pattern. */ public enum Strategy implements DragonSlayingStrategy { MELEE_STRATEGY(() -> LOGGER.info( "With your Excalibur you severe the dragon's head!")), PROJECTILE_STRATEGY(() -> LOGGER.info( "You shoot the dragon with the magical crossbow and it falls dead on the ground!")), SPELL_STRATEGY(() -> LOGGER.info( "You cast the spell of disintegration and the dragon vaporizes in a pile of dust!")); private final DragonSlayingStrategy dragonSlayingStrategy; Strategy(DragonSlayingStrategy dragonSlayingStrategy) { this.dragonSlayingStrategy = dragonSlayingStrategy; } @Override public void execute() { dragonSlayingStrategy.execute(); } } }
iluwatar/java-design-patterns
strategy/src/main/java/com/iluwatar/strategy/LambdaStrategy.java
161
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * 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.iluwatar.metamapping; import com.iluwatar.metamapping.model.User; import com.iluwatar.metamapping.service.UserService; import com.iluwatar.metamapping.utils.DatabaseUtil; import java.util.List; import lombok.extern.slf4j.Slf4j; import org.hibernate.service.ServiceRegistry; /** * Metadata Mapping specifies the mapping * between classes and tables so that * we could treat a table of any database like a Java class. * * <p>With hibernate, we achieve list/create/update/delete/get operations: * 1)Create the H2 Database in {@link DatabaseUtil}. * 2)Hibernate resolve hibernate.cfg.xml and generate service like save/list/get/delete. * For learning metadata mapping pattern, we go deeper into Hibernate here: * a)read properties from hibernate.cfg.xml and mapping from *.hbm.xml * b)create session factory to generate session interacting with database * c)generate session with factory pattern * d)create query object or use basic api with session, * hibernate will convert all query to database query according to metadata * 3)We encapsulate hibernate service in {@link UserService} for our use. * @see org.hibernate.cfg.Configuration#configure(String) * @see org.hibernate.cfg.Configuration#buildSessionFactory(ServiceRegistry) * @see org.hibernate.internal.SessionFactoryImpl#openSession() */ @Slf4j public class App { /** * Program entry point. * * @param args command line args. */ public static void main(String[] args) { // get service var userService = new UserService(); // use create service to add users for (var user : generateSampleUsers()) { var id = userService.createUser(user); LOGGER.info("Add user" + user + "at" + id + "."); } // use list service to get users var users = userService.listUser(); LOGGER.info(String.valueOf(users)); // use get service to get a user var user = userService.getUser(1); LOGGER.info(String.valueOf(user)); // change password of user 1 user.setPassword("new123"); // use update service to update user 1 userService.updateUser(1, user); // use delete service to delete user 2 userService.deleteUser(2); // close service userService.close(); } /** * Generate users. * * @return list of users. */ public static List<User> generateSampleUsers() { final var user1 = new User("ZhangSan", "zhs123"); final var user2 = new User("LiSi", "ls123"); final var user3 = new User("WangWu", "ww123"); return List.of(user1, user2, user3); } }
iluwatar/java-design-patterns
metadata-mapping/src/main/java/com/iluwatar/metamapping/App.java
162
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * 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.iluwatar.dirtyflag; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.List; import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; /** * A mock database manager -- Fetches data from a raw file. * * @author swaisuan */ @Slf4j public class DataFetcher { private static final String FILENAME = "world.txt"; private long lastFetched; public DataFetcher() { this.lastFetched = -1; } private boolean isDirty(long fileLastModified) { if (lastFetched != fileLastModified) { lastFetched = fileLastModified; return true; } return false; } /** * Fetches data/content from raw file. * * @return List of strings */ public List<String> fetch() { var classLoader = getClass().getClassLoader(); var file = new File(classLoader.getResource(FILENAME).getFile()); if (isDirty(file.lastModified())) { LOGGER.info(FILENAME + " is dirty! Re-fetching file content..."); try (var br = new BufferedReader(new FileReader(file))) { return br.lines().collect(Collectors.collectingAndThen(Collectors.toList(), List::copyOf)); } catch (IOException e) { LOGGER.error("An error occurred: ", e); } } return List.of(); } }
iluwatar/java-design-patterns
dirty-flag/src/main/java/com/iluwatar/dirtyflag/DataFetcher.java
163
package com.thealgorithms.maths; /** * Calculate average of a list of numbers */ public final class Average { private Average() { } /** * Calculate average of a list of numbers * * @param numbers array to store numbers * @return mean of given numbers */ public static double average(double[] numbers) { if (numbers == null || numbers.length == 0) { throw new IllegalArgumentException("Numbers array cannot be empty or null"); } double sum = 0; for (double number : numbers) { sum += number; } return sum / numbers.length; } /** * find average value of an int array * * @param numbers the array contains element and the sum does not excess long * value limit * @return average value */ public static int average(int[] numbers) { if (numbers == null || numbers.length == 0) { throw new IllegalArgumentException("Numbers array cannot be empty or null"); } long sum = 0; for (int number : numbers) { sum += number; } return (int) (sum / numbers.length); } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/maths/Average.java
164
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * 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.iluwatar.execute.around; import java.io.File; import java.io.IOException; import java.util.Scanner; import lombok.extern.slf4j.Slf4j; /** * The Execute Around idiom specifies executable code before and after a method. Typically, * the idiom is used when the API has methods to be executed in pairs, such as resource * allocation/deallocation or lock acquisition/release. * * <p>In this example, we have {@link SimpleFileWriter} class that opens and closes the file for * the user. The user specifies only what to do with the file by providing the {@link * FileWriterAction} implementation. */ @Slf4j public class App { /** * Program entry point. */ public static void main(String[] args) throws IOException { // create the file writer and execute the custom action FileWriterAction writeHello = writer -> writer.write("Gandalf was here"); new SimpleFileWriter("testfile.txt", writeHello); // print the file contents try (var scanner = new Scanner(new File("testfile.txt"))) { while (scanner.hasNextLine()) { LOGGER.info(scanner.nextLine()); } } } }
iluwatar/java-design-patterns
execute-around/src/main/java/com/iluwatar/execute/around/App.java
165
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * 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.iluwatar.mediator; import lombok.Getter; /** * Action enumeration. */ public enum Action { HUNT("hunted a rabbit", "arrives for dinner"), TALE("tells a tale", "comes to listen"), GOLD("found gold", "takes his share of the gold"), ENEMY("spotted enemies", "runs for cover"), NONE("", ""); private final String title; @Getter private final String description; Action(String title, String description) { this.title = title; this.description = description; } public String toString() { return title; } }
iluwatar/java-design-patterns
mediator/src/main/java/com/iluwatar/mediator/Action.java
166
package com.thealgorithms.sorts; /** * Comb Sort algorithm implementation * * <p> * Best-case performance O(n * log(n)) Worst-case performance O(n ^ 2) * Worst-case space complexity O(1) * * <p> * Comb sort improves on bubble sort. * * @author Sandeep Roy (https://github.com/sandeeproy99) * @author Podshivalov Nikita (https://github.com/nikitap492) * @see BubbleSort * @see SortAlgorithm */ class CombSort implements SortAlgorithm { // To find gap between elements private int nextGap(int gap) { // Shrink gap by Shrink factor gap = (gap * 10) / 13; return Math.max(gap, 1); } /** * Function to sort arr[] using Comb * * @param arr - an array should be sorted * @return sorted array */ @Override public <T extends Comparable<T>> T[] sort(T[] arr) { int size = arr.length; // initialize gap int gap = size; // Initialize swapped as true to make sure that loop runs boolean swapped = true; // Keep running while gap is more than 1 and last iteration caused a swap while (gap != 1 || swapped) { // Find next gap gap = nextGap(gap); // Initialize swapped as false so that we can check if swap happened or not swapped = false; // Compare all elements with current gap for (int i = 0; i < size - gap; i++) { if (SortUtils.less(arr[i + gap], arr[i])) { // Swap arr[i] and arr[i+gap] SortUtils.swap(arr, i, i + gap); swapped = true; } } } return arr; } // Driver method public static void main(String[] args) { CombSort ob = new CombSort(); Integer[] arr = { 8, 4, 1, 56, 3, -44, -1, 0, 36, 34, 8, 12, -66, -78, 23, -6, 28, 0, }; ob.sort(arr); System.out.println("sorted array"); SortUtils.print(arr); } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/sorts/CombSort.java
167
import java.text.DecimalFormat; import java.util.Random; interface Debuggable { static DecimalFormat DF6 = new DecimalFormat("#0.000000"); static DecimalFormat DF8 = new DecimalFormat("#0.00000000"); static DecimalFormat DF = new DecimalFormat("#0.0000"); static DecimalFormat DF0 = new DecimalFormat("#0.00"); static DecimalFormat DF1 = new DecimalFormat("#0.0"); static boolean Debug = false; // variables used to optimize a bit space + time static boolean SAVE_MEMORY = true; static double EPS = 1E-4; static double EPS2 = 1E-5; static double EPS3 = 1E-10; public static int NUMBER_STRATIFIED_CV = 10; public static double TOO_BIG_RATIO = 100.0; public static double INITIAL_FAN_ANGLE = Math.PI; public static double GRANDCHILD_FAN_RATIO = 0.8; public static boolean SAVE_PARAMETERS_DURING_TRAINING = true; public static boolean SAVE_CLASSIFIERS = true; }
google-research/google-research
tempered_boosting/Misc.java
168
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * 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.iluwatar.promise; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.function.Consumer; import java.util.function.Function; /** * A Promise represents a proxy for a value not necessarily known when the promise is created. It * allows you to associate dependent promises to an asynchronous action's eventual success value or * failure reason. This lets asynchronous methods return values like synchronous methods: instead of * the final value, the asynchronous method returns a promise of having a value at some point in the * future. * * @param <T> type of result. */ public class Promise<T> extends PromiseSupport<T> { private Runnable fulfillmentAction; private Consumer<? super Throwable> exceptionHandler; /** * Creates a promise that will be fulfilled in the future. */ public Promise() { // Empty constructor } /** * Fulfills the promise with the provided value. * * @param value the fulfilled value that can be accessed using {@link #get()}. */ @Override public void fulfill(T value) { super.fulfill(value); postFulfillment(); } /** * Fulfills the promise with exception due to error in execution. * * @param exception the exception will be wrapped in {@link ExecutionException} when accessing the * value using {@link #get()}. */ @Override public void fulfillExceptionally(Exception exception) { super.fulfillExceptionally(exception); handleException(exception); postFulfillment(); } private void handleException(Exception exception) { if (exceptionHandler == null) { return; } exceptionHandler.accept(exception); } private void postFulfillment() { if (fulfillmentAction == null) { return; } fulfillmentAction.run(); } /** * Executes the task using the executor in other thread and fulfills the promise returned once the * task completes either successfully or with an exception. * * @param task the task that will provide the value to fulfill the promise. * @param executor the executor in which the task should be run. * @return a promise that represents the result of running the task provided. */ public Promise<T> fulfillInAsync(final Callable<T> task, Executor executor) { executor.execute(() -> { try { fulfill(task.call()); } catch (Exception ex) { fulfillExceptionally(ex); } }); return this; } /** * Returns a new promise that, when this promise is fulfilled normally, is fulfilled with result * of this promise as argument to the action provided. * * @param action action to be executed. * @return a new promise. */ public Promise<Void> thenAccept(Consumer<? super T> action) { var dest = new Promise<Void>(); fulfillmentAction = new ConsumeAction(this, dest, action); return dest; } /** * Set the exception handler on this promise. * * @param exceptionHandler a consumer that will handle the exception occurred while fulfilling the * promise. * @return this */ public Promise<T> onError(Consumer<? super Throwable> exceptionHandler) { this.exceptionHandler = exceptionHandler; return this; } /** * Returns a new promise that, when this promise is fulfilled normally, is fulfilled with result * of this promise as argument to the function provided. * * @param func function to be executed. * @return a new promise. */ public <V> Promise<V> thenApply(Function<? super T, V> func) { Promise<V> dest = new Promise<>(); fulfillmentAction = new TransformAction<>(this, dest, func); return dest; } /** * Accesses the value from source promise and calls the consumer, then fulfills the destination * promise. */ private class ConsumeAction implements Runnable { private final Promise<T> src; private final Promise<Void> dest; private final Consumer<? super T> action; private ConsumeAction(Promise<T> src, Promise<Void> dest, Consumer<? super T> action) { this.src = src; this.dest = dest; this.action = action; } @Override public void run() { try { action.accept(src.get()); dest.fulfill(null); } catch (Throwable throwable) { dest.fulfillExceptionally((Exception) throwable.getCause()); } } } /** * Accesses the value from source promise, then fulfills the destination promise using the * transformed value. The source value is transformed using the transformation function. */ private class TransformAction<V> implements Runnable { private final Promise<T> src; private final Promise<V> dest; private final Function<? super T, V> func; private TransformAction(Promise<T> src, Promise<V> dest, Function<? super T, V> func) { this.src = src; this.dest = dest; this.func = func; } @Override public void run() { try { dest.fulfill(func.apply(src.get())); } catch (Throwable throwable) { dest.fulfillExceptionally((Exception) throwable.getCause()); } } } }
iluwatar/java-design-patterns
promise/src/main/java/com/iluwatar/promise/Promise.java
169
package com.thealgorithms.others; import java.util.Scanner; class PageRank { public static void main(String[] args) { int nodes, i, j; Scanner in = new Scanner(System.in); System.out.print("Enter the Number of WebPages: "); nodes = in.nextInt(); PageRank p = new PageRank(); System.out.println("Enter the Adjacency Matrix with 1->PATH & 0->NO PATH Between two WebPages: "); for (i = 1; i <= nodes; i++) { for (j = 1; j <= nodes; j++) { p.path[i][j] = in.nextInt(); if (j == i) { p.path[i][j] = 0; } } } p.calc(nodes); } public int[][] path = new int[10][10]; public double[] pagerank = new double[10]; public void calc(double totalNodes) { double InitialPageRank; double OutgoingLinks = 0; double DampingFactor = 0.85; double[] TempPageRank = new double[10]; int ExternalNodeNumber; int InternalNodeNumber; int k = 1; // For Traversing int ITERATION_STEP = 1; InitialPageRank = 1 / totalNodes; System.out.printf(" Total Number of Nodes :" + totalNodes + "\t Initial PageRank of All Nodes :" + InitialPageRank + "\n"); // 0th ITERATION _ OR _ INITIALIZATION PHASE // for (k = 1; k <= totalNodes; k++) { this.pagerank[k] = InitialPageRank; } System.out.print("\n Initial PageRank Values , 0th Step \n"); for (k = 1; k <= totalNodes; k++) { System.out.printf(" Page Rank of " + k + " is :\t" + this.pagerank[k] + "\n"); } while (ITERATION_STEP <= 2) { // Iterations // Store the PageRank for All Nodes in Temporary Array for (k = 1; k <= totalNodes; k++) { TempPageRank[k] = this.pagerank[k]; this.pagerank[k] = 0; } for (InternalNodeNumber = 1; InternalNodeNumber <= totalNodes; InternalNodeNumber++) { for (ExternalNodeNumber = 1; ExternalNodeNumber <= totalNodes; ExternalNodeNumber++) { if (this.path[ExternalNodeNumber][InternalNodeNumber] == 1) { k = 1; OutgoingLinks = 0; // Count the Number of Outgoing Links for each ExternalNodeNumber while (k <= totalNodes) { if (this.path[ExternalNodeNumber][k] == 1) { OutgoingLinks = OutgoingLinks + 1; // Counter for Outgoing Links } k = k + 1; } // Calculate PageRank this.pagerank[InternalNodeNumber] += TempPageRank[ExternalNodeNumber] * (1 / OutgoingLinks); } } System.out.printf("\n After " + ITERATION_STEP + "th Step \n"); for (k = 1; k <= totalNodes; k++) { System.out.printf(" Page Rank of " + k + " is :\t" + this.pagerank[k] + "\n"); } ITERATION_STEP = ITERATION_STEP + 1; } // Add the Damping Factor to PageRank for (k = 1; k <= totalNodes; k++) { this.pagerank[k] = (1 - DampingFactor) + DampingFactor * this.pagerank[k]; } // Display PageRank System.out.print("\n Final Page Rank : \n"); for (k = 1; k <= totalNodes; k++) { System.out.printf(" Page Rank of " + k + " is :\t" + this.pagerank[k] + "\n"); } } } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/others/PageRank.java
170
package com.thealgorithms.strings; import java.util.HashSet; /** * Wikipedia: https://en.wikipedia.org/wiki/Pangram */ public final class Pangram { private Pangram() { } /** * Test code */ public static void main(String[] args) { assert isPangram("The quick brown fox jumps over the lazy dog"); assert !isPangram("The quick brown fox jumps over the azy dog"); // L is missing assert !isPangram("+-1234 This string is not alphabetical"); assert !isPangram("\u0000/\\"); } /** * Checks if a String is considered a Pangram * * @param s The String to check * @return {@code true} if s is a Pangram, otherwise {@code false} */ // alternative approach using Java Collection Framework public static boolean isPangramUsingSet(String s) { HashSet<Character> alpha = new HashSet<>(); s = s.trim().toLowerCase(); for (int i = 0; i < s.length(); i++) if (s.charAt(i) != ' ') alpha.add(s.charAt(i)); return alpha.size() == 26; } /** * Checks if a String is considered a Pangram * * @param s The String to check * @return {@code true} if s is a Pangram, otherwise {@code false} */ public static boolean isPangram(String s) { boolean[] lettersExisting = new boolean[26]; for (char c : s.toCharArray()) { int letterIndex = c - (Character.isUpperCase(c) ? 'A' : 'a'); if (letterIndex >= 0 && letterIndex < lettersExisting.length) { lettersExisting[letterIndex] = true; } } for (boolean letterFlag : lettersExisting) { if (!letterFlag) { return false; } } return true; } /** * Checks if a String is Pangram or not by checking if each alhpabet is present or not * * @param s The String to check * @return {@code true} if s is a Pangram, otherwise {@code false} */ public static boolean isPangram2(String s) { if (s.length() < 26) { return false; } s = s.toLowerCase(); // Converting s to Lower-Case for (char i = 'a'; i <= 'z'; i++) { if (s.indexOf(i) == -1) { return false; // if any alphabet is not present, return false } } return true; } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/strings/Pangram.java
171
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * 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.iluwatar.commander.queue; import com.iluwatar.commander.Order; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.Setter; /** * QueueTask object is the object enqueued in queue. */ @RequiredArgsConstructor public class QueueTask { /** * TaskType is the type of task to be done. */ public enum TaskType { MESSAGING, PAYMENT, EMPLOYEE_DB } public final Order order; public final TaskType taskType; public final int messageType; //0-fail, 1-error, 2-success /*we could have varargs Object instead to pass in any parameter instead of just message type but keeping it simple here*/ @Getter @Setter private long firstAttemptTime = -1L; //when first time attempt made to do task /** * getType method. * * @return String representing type of task */ public String getType() { if (!this.taskType.equals(TaskType.MESSAGING)) { return this.taskType.toString(); } else { if (this.messageType == 0) { return "Payment Failure Message"; } else if (this.messageType == 1) { return "Payment Error Message"; } else { return "Payment Success Message"; } } } public boolean isFirstAttempt() { return this.firstAttemptTime == -1L; } }
iluwatar/java-design-patterns
commander/src/main/java/com/iluwatar/commander/queue/QueueTask.java
172
//A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). // //The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). // //How many possible unique paths are there? class UniquePaths { public int uniquePaths(int m, int n) { Integer[][] map = new Integer[m][n]; //only 1 way to get to ith row, 0th column (move down) for(int i = 0; i < m; i++){ map[i][0] = 1; } //only 1 way to get to ith column, 0th row (move right) for(int j= 0; j < n; j++){ map[0][j]=1; } //x ways to get to ith row, jth column (# of ways to get to //ith - 1 row, jth column + # of ways to get to jth - 1 column //ith column for(int i = 1;i < m; i++){ for(int j = 1; j < n; j++){ map[i][j] = map[i - 1][j] + map[i][j - 1]; } } return map[m - 1][n - 1]; } }
kdn251/interviews
leetcode/array/UniquePaths.java
173
/* Copyright 2021 The TensorFlow Authors. 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 org.tensorflow.lite; import java.lang.reflect.Array; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.LongBuffer; import java.nio.ShortBuffer; import java.util.Arrays; import org.checkerframework.checker.nullness.qual.NonNull; /** Implementation of {@link Tensor}. */ // TODO(b/153882978): Add scalar getters similar to TF's Java API. final class TensorImpl implements Tensor { /** * Creates a Tensor wrapper from the provided interpreter instance and tensor index. * * <p>The caller is responsible for closing the created wrapper, and ensuring the provided native * interpreter is valid until the tensor is closed. */ static TensorImpl fromIndex(long nativeInterpreterHandle, int tensorIndex) { return new TensorImpl(create(nativeInterpreterHandle, tensorIndex, /*subgraphIndex=*/ 0)); } /** * Creates a Tensor wrapper for a Signature input. * * <p>The caller is responsible for closing the created wrapper, and ensuring the provided native * SignatureRunner is valid until the tensor is closed. */ static TensorImpl fromSignatureInput(long signatureRunnerHandle, String inputName) { long tensorHandle = createSignatureInputTensor(signatureRunnerHandle, inputName); if (tensorHandle == -1) { throw new IllegalArgumentException("Input error: input " + inputName + " not found."); } else { return new TensorImpl(tensorHandle); } } /** * Creates a Tensor wrapper for a Signature output. * * <p>The caller is responsible for closing the created wrapper, and ensuring the provided native * SignatureRunner is valid until the tensor is closed. */ static TensorImpl fromSignatureOutput(long signatureRunnerHandle, String outputName) { long tensorHandle = createSignatureOutputTensor(signatureRunnerHandle, outputName); if (tensorHandle == -1) { throw new IllegalArgumentException("Input error: output " + outputName + " not found."); } else { return new TensorImpl(tensorHandle); } } /** Disposes of any resources used by the Tensor wrapper. */ void close() { delete(nativeHandle); nativeHandle = 0; } @Override public DataType dataType() { return dtype; } @Override public int numDimensions() { return shapeCopy.length; } @Override public int numBytes() { return numBytes(nativeHandle); } @Override public int numElements() { return computeNumElements(shapeCopy); } @Override public int[] shape() { return shapeCopy; } @Override public int[] shapeSignature() { return shapeSignatureCopy; } @Override public int index() { return index(nativeHandle); } @Override public String name() { return name(nativeHandle); } @Override public QuantizationParams quantizationParams() { return quantizationParamsCopy; } @Override public ByteBuffer asReadOnlyBuffer() { // Note that the ByteBuffer order is not preserved when duplicated or marked read only, so // we have to repeat the call. return buffer().asReadOnlyBuffer().order(ByteOrder.nativeOrder()); } /** * Copies the contents of the provided {@code src} object to the Tensor. * * <p>The {@code src} should either be a (multi-dimensional) array with a shape matching that of * this tensor, a {@link ByteBuffer} of compatible primitive type with a matching flat size, or * {@code null} iff the tensor has an underlying delegate buffer handle. * * @throws IllegalArgumentException if the tensor is a scalar or if {@code src} is not compatible * with the tensor (for example, mismatched data types or shapes). */ void setTo(Object src) { if (src == null) { if (hasDelegateBufferHandle(nativeHandle)) { return; } throw new IllegalArgumentException( "Null inputs are allowed only if the Tensor is bound to a buffer handle."); } throwIfTypeIsIncompatible(src); throwIfSrcShapeIsIncompatible(src); if (isBuffer(src)) { setTo((Buffer) src); } else if (dtype == DataType.STRING && shapeCopy.length == 0) { // Update scalar string input with 1-d byte array. writeScalar(nativeHandle, src); } else if (src.getClass().isArray()) { writeMultiDimensionalArray(nativeHandle, src); } else { writeScalar(nativeHandle, src); } } private void setTo(Buffer src) { // Note that we attempt to use a direct memcpy optimization for direct, native-ordered buffers. // There are no base Buffer#order() or Buffer#put() methods, so again we have to ugly cast. if (src instanceof ByteBuffer) { ByteBuffer srcBuffer = (ByteBuffer) src; if (srcBuffer.isDirect() && srcBuffer.order() == ByteOrder.nativeOrder()) { writeDirectBuffer(nativeHandle, src); } else { buffer().put(srcBuffer); } } else if (src instanceof LongBuffer) { LongBuffer srcBuffer = (LongBuffer) src; if (srcBuffer.isDirect() && srcBuffer.order() == ByteOrder.nativeOrder()) { writeDirectBuffer(nativeHandle, src); } else { buffer().asLongBuffer().put(srcBuffer); } } else if (src instanceof FloatBuffer) { FloatBuffer srcBuffer = (FloatBuffer) src; if (srcBuffer.isDirect() && srcBuffer.order() == ByteOrder.nativeOrder()) { writeDirectBuffer(nativeHandle, src); } else { buffer().asFloatBuffer().put(srcBuffer); } } else if (src instanceof IntBuffer) { IntBuffer srcBuffer = (IntBuffer) src; if (srcBuffer.isDirect() && srcBuffer.order() == ByteOrder.nativeOrder()) { writeDirectBuffer(nativeHandle, src); } else { buffer().asIntBuffer().put(srcBuffer); } } else if (src instanceof ShortBuffer) { ShortBuffer srcBuffer = (ShortBuffer) src; if (srcBuffer.isDirect() && srcBuffer.order() == ByteOrder.nativeOrder()) { writeDirectBuffer(nativeHandle, src); } else { buffer().asShortBuffer().put(srcBuffer); } } else { throw new IllegalArgumentException("Unexpected input buffer type: " + src); } } /** * Copies the contents of the tensor to {@code dst}. * * @param dst the destination buffer, either an explicitly-typed array, a compatible {@link * Buffer} or {@code null} iff the tensor has an underlying delegate buffer handle. If * providing a (multi-dimensional) array, its shape must match the tensor shape *exactly*. If * providing a {@link Buffer}, its capacity must be at least as large as the source tensor's * capacity. * @throws IllegalArgumentException if {@code dst} is not compatible with the tensor (for example, * mismatched data types or shapes). */ void copyTo(Object dst) { if (dst == null) { if (hasDelegateBufferHandle(nativeHandle)) { return; } throw new IllegalArgumentException( "Null outputs are allowed only if the Tensor is bound to a buffer handle."); } throwIfTypeIsIncompatible(dst); throwIfDstShapeIsIncompatible(dst); if (isBuffer(dst)) { copyTo((Buffer) dst); } else { readMultiDimensionalArray(nativeHandle, dst); } } private void copyTo(Buffer dst) { // There is no base Buffer#put() method, so we have to ugly cast. if (dst instanceof ByteBuffer) { ((ByteBuffer) dst).put(buffer()); } else if (dst instanceof FloatBuffer) { ((FloatBuffer) dst).put(buffer().asFloatBuffer()); } else if (dst instanceof LongBuffer) { ((LongBuffer) dst).put(buffer().asLongBuffer()); } else if (dst instanceof IntBuffer) { ((IntBuffer) dst).put(buffer().asIntBuffer()); } else if (dst instanceof ShortBuffer) { ((ShortBuffer) dst).put(buffer().asShortBuffer()); } else { throw new IllegalArgumentException("Unexpected output buffer type: " + dst); } } /** Returns the provided buffer's shape if specified and different from this Tensor's shape. */ // TODO(b/80431971): Remove this method after deprecating multi-dimensional array inputs. int[] getInputShapeIfDifferent(Object input) { if (input == null) { return null; } // Implicit resizes based on ByteBuffer capacity isn't supported, so short-circuit that path. // The Buffer's size will be validated against this Tensor's size in {@link #setTo(Object)}. if (isBuffer(input)) { return null; } throwIfTypeIsIncompatible(input); int[] inputShape = computeShapeOf(input); if (Arrays.equals(shapeCopy, inputShape)) { return null; } return inputShape; } /** * Forces a refresh of the tensor's cached shape. * * <p>This is useful if the tensor is resized or has a dynamic shape. */ void refreshShape() { this.shapeCopy = shape(nativeHandle); } /** Returns the type of the data. */ DataType dataTypeOf(@NonNull Object o) { Class<?> c = o.getClass(); // For arrays, the data elements must be a *primitive* type, e.g., an // array of floats is fine, but not an array of Floats. if (c.isArray()) { while (c.isArray()) { c = c.getComponentType(); } if (float.class.equals(c)) { return DataType.FLOAT32; } else if (int.class.equals(c)) { return DataType.INT32; } else if (short.class.equals(c)) { return DataType.INT16; } else if (byte.class.equals(c)) { // Byte array can be used for storing string tensors, especially for ParseExample op. if (dtype == DataType.STRING) { return DataType.STRING; } return DataType.UINT8; } else if (long.class.equals(c)) { return DataType.INT64; } else if (boolean.class.equals(c)) { return DataType.BOOL; } else if (String.class.equals(c)) { return DataType.STRING; } } else { // For scalars, the type will be boxed. if (Float.class.equals(c) || o instanceof FloatBuffer) { return DataType.FLOAT32; } else if (Integer.class.equals(c) || o instanceof IntBuffer) { return DataType.INT32; } else if (Short.class.equals(c) || o instanceof ShortBuffer) { return DataType.INT16; } else if (Byte.class.equals(c)) { // Note that we don't check for ByteBuffer here; ByteBuffer payloads // are allowed to map to any type, and should be handled earlier // in the input/output processing pipeline. return DataType.UINT8; } else if (Long.class.equals(c) || o instanceof LongBuffer) { return DataType.INT64; } else if (Boolean.class.equals(c)) { return DataType.BOOL; } else if (String.class.equals(c)) { return DataType.STRING; } } throw new IllegalArgumentException( "DataType error: cannot resolve DataType of " + o.getClass().getName()); } /** Returns the shape of an object as an int array. */ private int[] computeShapeOf(Object o) { int size = computeNumDimensions(o); if (dtype == DataType.STRING) { Class<?> c = o.getClass(); if (c.isArray()) { while (c.isArray()) { c = c.getComponentType(); } // If the given string data is stored in byte streams, the last array dimension should be // treated as a value. if (byte.class.equals(c)) { --size; } } } int[] dimensions = new int[size]; fillShape(o, 0, dimensions); return dimensions; } /** Returns the number of elements in a flattened (1-D) view of the tensor's shape. */ static int computeNumElements(int[] shape) { int n = 1; for (int j : shape) { n *= j; } return n; } /** Returns the number of dimensions of a multi-dimensional array, otherwise 0. */ static int computeNumDimensions(Object o) { if (o == null || !o.getClass().isArray()) { return 0; } if (Array.getLength(o) == 0) { throw new IllegalArgumentException("Array lengths cannot be 0."); } return 1 + computeNumDimensions(Array.get(o, 0)); } /** Recursively populates the shape dimensions for a given (multi-dimensional) array. */ static void fillShape(Object o, int dim, int[] shape) { if (shape == null || dim == shape.length) { return; } final int len = Array.getLength(o); if (shape[dim] == 0) { shape[dim] = len; } else if (shape[dim] != len) { throw new IllegalArgumentException( String.format("Mismatched lengths (%d and %d) in dimension %d", shape[dim], len, dim)); } final int nextDim = dim + 1; // Short-circuit the innermost dimension to avoid unnecessary Array.get() reflection overhead. if (nextDim == shape.length) { return; } for (int i = 0; i < len; ++i) { fillShape(Array.get(o, i), nextDim, shape); } } private void throwIfTypeIsIncompatible(@NonNull Object o) { // ByteBuffer payloads can map to any type, so exempt it from the check. if (isByteBuffer(o)) { return; } DataType oType = dataTypeOf(o); if (oType != dtype) { // INT8 and UINT8 have the same string name, "byte" if (DataTypeUtils.toStringName(oType).equals(DataTypeUtils.toStringName(dtype))) { return; } throw new IllegalArgumentException( String.format( "Cannot convert between a TensorFlowLite tensor with type %s and a Java " + "object of type %s (which is compatible with the TensorFlowLite type %s).", dtype, o.getClass().getName(), oType)); } } private void throwIfSrcShapeIsIncompatible(Object src) { if (isBuffer(src)) { Buffer srcBuffer = (Buffer) src; int bytes = numBytes(); // Note that we allow the client to provide a ByteBuffer even for non-byte Tensors. // In such cases, we only care that the raw byte capacity matches the tensor byte capacity. int srcBytes = isByteBuffer(src) ? srcBuffer.capacity() : srcBuffer.capacity() * dtype.byteSize(); if (bytes != srcBytes) { throw new IllegalArgumentException( String.format( "Cannot copy to a TensorFlowLite tensor (%s) with %d bytes from a " + "Java Buffer with %d bytes.", name(), bytes, srcBytes)); } return; } int[] srcShape = computeShapeOf(src); if (!Arrays.equals(srcShape, shapeCopy)) { throw new IllegalArgumentException( String.format( "Cannot copy to a TensorFlowLite tensor (%s) with shape %s from a Java object " + "with shape %s.", name(), Arrays.toString(shapeCopy), Arrays.toString(srcShape))); } } private void throwIfDstShapeIsIncompatible(Object dst) { if (isBuffer(dst)) { Buffer dstBuffer = (Buffer) dst; int bytes = numBytes(); // Note that we allow the client to provide a ByteBuffer even for non-byte Tensors. // In such cases, we only care that the raw byte capacity fits the tensor byte capacity. // This is subtly different than Buffer *inputs*, where the size should be exact. int dstBytes = isByteBuffer(dst) ? dstBuffer.capacity() : dstBuffer.capacity() * dtype.byteSize(); if (bytes > dstBytes) { throw new IllegalArgumentException( String.format( "Cannot copy from a TensorFlowLite tensor (%s) with %d bytes to a " + "Java Buffer with %d bytes.", name(), bytes, dstBytes)); } return; } int[] dstShape = computeShapeOf(dst); if (!Arrays.equals(dstShape, shapeCopy)) { throw new IllegalArgumentException( String.format( "Cannot copy from a TensorFlowLite tensor (%s) with shape %s to a Java object " + "with shape %s.", name(), Arrays.toString(shapeCopy), Arrays.toString(dstShape))); } } private static boolean isBuffer(Object o) { return o instanceof Buffer; } private static boolean isByteBuffer(Object o) { return o instanceof ByteBuffer; } private long nativeHandle; private final DataType dtype; private int[] shapeCopy; private final int[] shapeSignatureCopy; private final QuantizationParams quantizationParamsCopy; private TensorImpl(long nativeHandle) { this.nativeHandle = nativeHandle; this.dtype = DataTypeUtils.fromC(dtype(nativeHandle)); this.shapeCopy = shape(nativeHandle); this.shapeSignatureCopy = shapeSignature(nativeHandle); this.quantizationParamsCopy = new QuantizationParams( quantizationScale(nativeHandle), quantizationZeroPoint(nativeHandle)); } private ByteBuffer buffer() { return buffer(nativeHandle).order(ByteOrder.nativeOrder()); } private static native long create(long interpreterHandle, int tensorIndex, int subgraphIndex); private static native long createSignatureInputTensor( long signatureRunnerHandle, String inputName); private static native long createSignatureOutputTensor( long signatureRunnerHandle, String outputName); private static native void delete(long handle); private static native ByteBuffer buffer(long handle); private static native void writeDirectBuffer(long handle, Buffer src); private static native int dtype(long handle); private static native int[] shape(long handle); private static native int[] shapeSignature(long handle); private static native int numBytes(long handle); private static native boolean hasDelegateBufferHandle(long handle); private static native void readMultiDimensionalArray(long handle, Object dst); private static native void writeMultiDimensionalArray(long handle, Object src); private static native void writeScalar(long handle, Object src); private static native int index(long handle); private static native String name(long handle); private static native float quantizationScale(long handle); private static native int quantizationZeroPoint(long handle); }
tensorflow/tensorflow
tensorflow/lite/java/src/main/java/org/tensorflow/lite/TensorImpl.java
174
// You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night. // Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police. public class HouseRobber { public int rob(int[] nums) { if(nums.length == 0) { return 0; } if(nums.length == 1) { return nums[0]; } int[] dp = new int[nums.length]; dp[0] = nums[0]; dp[1] = nums[0] > nums[1] ? nums[0] : nums[1]; for(int i = 2; i < nums.length; i++) { dp[i] = Math.max(dp[i - 2] + nums[i], dp[i - 1]); } return dp[dp.length - 1]; } }
kdn251/interviews
company/linkedin/HouseRobber.java
175
// ASM: a very small and fast Java bytecode manipulation framework // Copyright (c) 2000-2011 INRIA, France Telecom // All rights reserved. // // 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 holders 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 OWNER 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.springframework.asm; /** * A position in the bytecode of a method. Labels are used for jump, goto, and switch instructions, * and for try catch blocks. A label designates the <i>instruction</i> that is just after. Note * however that there can be other elements between a label and the instruction it designates (such * as other labels, stack map frames, line numbers, etc.). * * @author Eric Bruneton */ public class Label { /** * A flag indicating that a label is only used for debug attributes. Such a label is not the start * of a basic block, the target of a jump instruction, or an exception handler. It can be safely * ignored in control flow graph analysis algorithms (for optimization purposes). */ static final int FLAG_DEBUG_ONLY = 1; /** * A flag indicating that a label is the target of a jump instruction, or the start of an * exception handler. */ static final int FLAG_JUMP_TARGET = 2; /** A flag indicating that the bytecode offset of a label is known. */ static final int FLAG_RESOLVED = 4; /** A flag indicating that a label corresponds to a reachable basic block. */ static final int FLAG_REACHABLE = 8; /** * A flag indicating that the basic block corresponding to a label ends with a subroutine call. By * construction in {@link MethodWriter#visitJumpInsn}, labels with this flag set have at least two * outgoing edges: * * <ul> * <li>the first one corresponds to the instruction that follows the jsr instruction in the * bytecode, i.e. where execution continues when it returns from the jsr call. This is a * virtual control flow edge, since execution never goes directly from the jsr to the next * instruction. Instead, it goes to the subroutine and eventually returns to the instruction * following the jsr. This virtual edge is used to compute the real outgoing edges of the * basic blocks ending with a ret instruction, in {@link #addSubroutineRetSuccessors}. * <li>the second one corresponds to the target of the jsr instruction, * </ul> */ static final int FLAG_SUBROUTINE_CALLER = 16; /** * A flag indicating that the basic block corresponding to a label is the start of a subroutine. */ static final int FLAG_SUBROUTINE_START = 32; /** A flag indicating that the basic block corresponding to a label is the end of a subroutine. */ static final int FLAG_SUBROUTINE_END = 64; /** A flag indicating that this label has at least one associated line number. */ static final int FLAG_LINE_NUMBER = 128; /** * The number of elements to add to the {@link #otherLineNumbers} array when it needs to be * resized to store a new source line number. */ static final int LINE_NUMBERS_CAPACITY_INCREMENT = 4; /** * The number of elements to add to the {@link #forwardReferences} array when it needs to be * resized to store a new forward reference. */ static final int FORWARD_REFERENCES_CAPACITY_INCREMENT = 6; /** * The bit mask to extract the type of a forward reference to this label. The extracted type is * either {@link #FORWARD_REFERENCE_TYPE_SHORT} or {@link #FORWARD_REFERENCE_TYPE_WIDE}. * * @see #forwardReferences */ static final int FORWARD_REFERENCE_TYPE_MASK = 0xF0000000; /** * The type of forward references stored with two bytes in the bytecode. This is the case, for * instance, of a forward reference from an ifnull instruction. */ static final int FORWARD_REFERENCE_TYPE_SHORT = 0x10000000; /** * The type of forward references stored in four bytes in the bytecode. This is the case, for * instance, of a forward reference from a lookupswitch instruction. */ static final int FORWARD_REFERENCE_TYPE_WIDE = 0x20000000; /** * The type of forward references stored in two bytes in the <i>stack map table</i>. This is the * case of the labels of {@link Frame#ITEM_UNINITIALIZED} stack map frame elements, when the NEW * instruction is after the &lt;init&gt; constructor call (in bytecode offset order). */ static final int FORWARD_REFERENCE_TYPE_STACK_MAP = 0x30000000; /** * The bit mask to extract the 'handle' of a forward reference to this label. The extracted handle * is the bytecode offset where the forward reference value is stored (using either 2 or 4 bytes, * as indicated by the {@link #FORWARD_REFERENCE_TYPE_MASK}). * * @see #forwardReferences */ static final int FORWARD_REFERENCE_HANDLE_MASK = 0x0FFFFFFF; /** * A sentinel element used to indicate the end of a list of labels. * * @see #nextListElement */ static final Label EMPTY_LIST = new Label(); /** * A user managed state associated with this label. Warning: this field is used by the ASM tree * package. In order to use it with the ASM tree package you must override the getLabelNode method * in MethodNode. */ public Object info; /** * The type and status of this label or its corresponding basic block. Must be zero or more of * {@link #FLAG_DEBUG_ONLY}, {@link #FLAG_JUMP_TARGET}, {@link #FLAG_RESOLVED}, {@link * #FLAG_REACHABLE}, {@link #FLAG_SUBROUTINE_CALLER}, {@link #FLAG_SUBROUTINE_START}, {@link * #FLAG_SUBROUTINE_END}. */ short flags; /** * The source line number corresponding to this label, if {@link #FLAG_LINE_NUMBER} is set. If * there are several source line numbers corresponding to this label, the first one is stored in * this field, and the remaining ones are stored in {@link #otherLineNumbers}. */ private short lineNumber; /** * The source line numbers corresponding to this label, in addition to {@link #lineNumber}, or * null. The first element of this array is the number n of source line numbers it contains, which * are stored between indices 1 and n (inclusive). */ private int[] otherLineNumbers; /** * The offset of this label in the bytecode of its method, in bytes. This value is set if and only * if the {@link #FLAG_RESOLVED} flag is set. */ int bytecodeOffset; /** * The forward references to this label. The first element is the number of forward references, * times 2 (this corresponds to the index of the last element actually used in this array). Then, * each forward reference is described with two consecutive integers noted * 'sourceInsnBytecodeOffset' and 'reference': * * <ul> * <li>'sourceInsnBytecodeOffset' is the bytecode offset of the instruction that contains the * forward reference, * <li>'reference' contains the type and the offset in the bytecode where the forward reference * value must be stored, which can be extracted with {@link #FORWARD_REFERENCE_TYPE_MASK} * and {@link #FORWARD_REFERENCE_HANDLE_MASK}. * </ul> * * <p>For instance, for an ifnull instruction at bytecode offset x, 'sourceInsnBytecodeOffset' is * equal to x, and 'reference' is of type {@link #FORWARD_REFERENCE_TYPE_SHORT} with value x + 1 * (because the ifnull instruction uses a 2 bytes bytecode offset operand stored one byte after * the start of the instruction itself). For the default case of a lookupswitch instruction at * bytecode offset x, 'sourceInsnBytecodeOffset' is equal to x, and 'reference' is of type {@link * #FORWARD_REFERENCE_TYPE_WIDE} with value between x + 1 and x + 4 (because the lookupswitch * instruction uses a 4 bytes bytecode offset operand stored one to four bytes after the start of * the instruction itself). */ private int[] forwardReferences; // ----------------------------------------------------------------------------------------------- // Fields for the control flow and data flow graph analysis algorithms (used to compute the // maximum stack size or the stack map frames). A control flow graph contains one node per "basic // block", and one edge per "jump" from one basic block to another. Each node (i.e., each basic // block) is represented with the Label object that corresponds to the first instruction of this // basic block. Each node also stores the list of its successors in the graph, as a linked list of // Edge objects. // // The control flow analysis algorithms used to compute the maximum stack size or the stack map // frames are similar and use two steps. The first step, during the visit of each instruction, // builds information about the state of the local variables and the operand stack at the end of // each basic block, called the "output frame", <i>relatively</i> to the frame state at the // beginning of the basic block, which is called the "input frame", and which is <i>unknown</i> // during this step. The second step, in {@link MethodWriter#computeAllFrames} and {@link // MethodWriter#computeMaxStackAndLocal}, is a fix point algorithm // that computes information about the input frame of each basic block, from the input state of // the first basic block (known from the method signature), and by the using the previously // computed relative output frames. // // The algorithm used to compute the maximum stack size only computes the relative output and // absolute input stack heights, while the algorithm used to compute stack map frames computes // relative output frames and absolute input frames. /** * The number of elements in the input stack of the basic block corresponding to this label. This * field is computed in {@link MethodWriter#computeMaxStackAndLocal}. */ short inputStackSize; /** * The number of elements in the output stack, at the end of the basic block corresponding to this * label. This field is only computed for basic blocks that end with a RET instruction. */ short outputStackSize; /** * The maximum height reached by the output stack, relatively to the top of the input stack, in * the basic block corresponding to this label. This maximum is always positive or {@literal * null}. */ short outputStackMax; /** * The id of the subroutine to which this basic block belongs, or 0. If the basic block belongs to * several subroutines, this is the id of the "oldest" subroutine that contains it (with the * convention that a subroutine calling another one is "older" than the callee). This field is * computed in {@link MethodWriter#computeMaxStackAndLocal}, if the method contains JSR * instructions. */ short subroutineId; /** * The input and output stack map frames of the basic block corresponding to this label. This * field is only used when the {@link MethodWriter#COMPUTE_ALL_FRAMES} or {@link * MethodWriter#COMPUTE_INSERTED_FRAMES} option is used. */ Frame frame; /** * The successor of this label, in the order they are visited in {@link MethodVisitor#visitLabel}. * This linked list does not include labels used for debug info only. If the {@link * MethodWriter#COMPUTE_ALL_FRAMES} or {@link MethodWriter#COMPUTE_INSERTED_FRAMES} option is used * then it does not contain either successive labels that denote the same bytecode offset (in this * case only the first label appears in this list). */ Label nextBasicBlock; /** * The outgoing edges of the basic block corresponding to this label, in the control flow graph of * its method. These edges are stored in a linked list of {@link Edge} objects, linked to each * other by their {@link Edge#nextEdge} field. */ Edge outgoingEdges; /** * The next element in the list of labels to which this label belongs, or {@literal null} if it * does not belong to any list. All lists of labels must end with the {@link #EMPTY_LIST} * sentinel, in order to ensure that this field is null if and only if this label does not belong * to a list of labels. Note that there can be several lists of labels at the same time, but that * a label can belong to at most one list at a time (unless some lists share a common tail, but * this is not used in practice). * * <p>List of labels are used in {@link MethodWriter#computeAllFrames} and {@link * MethodWriter#computeMaxStackAndLocal} to compute stack map frames and the maximum stack size, * respectively, as well as in {@link #markSubroutine} and {@link #addSubroutineRetSuccessors} to * compute the basic blocks belonging to subroutines and their outgoing edges. Outside of these * methods, this field should be null (this property is a precondition and a postcondition of * these methods). */ Label nextListElement; // ----------------------------------------------------------------------------------------------- // Constructor and accessors // ----------------------------------------------------------------------------------------------- /** Constructs a new label. */ public Label() { // Nothing to do. } /** * Returns the bytecode offset corresponding to this label. This offset is computed from the start * of the method's bytecode. <i>This method is intended for {@link Attribute} sub classes, and is * normally not needed by class generators or adapters.</i> * * @return the bytecode offset corresponding to this label. * @throws IllegalStateException if this label is not resolved yet. */ public int getOffset() { if ((flags & FLAG_RESOLVED) == 0) { throw new IllegalStateException("Label offset position has not been resolved yet"); } return bytecodeOffset; } /** * Returns the "canonical" {@link Label} instance corresponding to this label's bytecode offset, * if known, otherwise the label itself. The canonical instance is the first label (in the order * of their visit by {@link MethodVisitor#visitLabel}) corresponding to this bytecode offset. It * cannot be known for labels which have not been visited yet. * * <p><i>This method should only be used when the {@link MethodWriter#COMPUTE_ALL_FRAMES} option * is used.</i> * * @return the label itself if {@link #frame} is null, otherwise the Label's frame owner. This * corresponds to the "canonical" label instance described above thanks to the way the label * frame is set in {@link MethodWriter#visitLabel}. */ final Label getCanonicalInstance() { return frame == null ? this : frame.owner; } // ----------------------------------------------------------------------------------------------- // Methods to manage line numbers // ----------------------------------------------------------------------------------------------- /** * Adds a source line number corresponding to this label. * * @param lineNumber a source line number (which should be strictly positive). */ final void addLineNumber(final int lineNumber) { if ((flags & FLAG_LINE_NUMBER) == 0) { flags |= FLAG_LINE_NUMBER; this.lineNumber = (short) lineNumber; } else { if (otherLineNumbers == null) { otherLineNumbers = new int[LINE_NUMBERS_CAPACITY_INCREMENT]; } int otherLineNumberIndex = ++otherLineNumbers[0]; if (otherLineNumberIndex >= otherLineNumbers.length) { int[] newLineNumbers = new int[otherLineNumbers.length + LINE_NUMBERS_CAPACITY_INCREMENT]; System.arraycopy(otherLineNumbers, 0, newLineNumbers, 0, otherLineNumbers.length); otherLineNumbers = newLineNumbers; } otherLineNumbers[otherLineNumberIndex] = lineNumber; } } /** * Makes the given visitor visit this label and its source line numbers, if applicable. * * @param methodVisitor a method visitor. * @param visitLineNumbers whether to visit of the label's source line numbers, if any. */ final void accept(final MethodVisitor methodVisitor, final boolean visitLineNumbers) { methodVisitor.visitLabel(this); if (visitLineNumbers && (flags & FLAG_LINE_NUMBER) != 0) { methodVisitor.visitLineNumber(lineNumber & 0xFFFF, this); if (otherLineNumbers != null) { for (int i = 1; i <= otherLineNumbers[0]; ++i) { methodVisitor.visitLineNumber(otherLineNumbers[i], this); } } } } // ----------------------------------------------------------------------------------------------- // Methods to compute offsets and to manage forward references // ----------------------------------------------------------------------------------------------- /** * Puts a reference to this label in the bytecode of a method. If the bytecode offset of the label * is known, the relative bytecode offset between the label and the instruction referencing it is * computed and written directly. Otherwise, a null relative offset is written and a new forward * reference is declared for this label. * * @param code the bytecode of the method. This is where the reference is appended. * @param sourceInsnBytecodeOffset the bytecode offset of the instruction that contains the * reference to be appended. * @param wideReference whether the reference must be stored in 4 bytes (instead of 2 bytes). */ final void put( final ByteVector code, final int sourceInsnBytecodeOffset, final boolean wideReference) { if ((flags & FLAG_RESOLVED) == 0) { if (wideReference) { addForwardReference(sourceInsnBytecodeOffset, FORWARD_REFERENCE_TYPE_WIDE, code.length); code.putInt(-1); } else { addForwardReference(sourceInsnBytecodeOffset, FORWARD_REFERENCE_TYPE_SHORT, code.length); code.putShort(-1); } } else { if (wideReference) { code.putInt(bytecodeOffset - sourceInsnBytecodeOffset); } else { code.putShort(bytecodeOffset - sourceInsnBytecodeOffset); } } } /** * Puts a reference to this label in the <i>stack map table</i> of a method. If the bytecode * offset of the label is known, it is written directly. Otherwise, a null relative offset is * written and a new forward reference is declared for this label. * * @param stackMapTableEntries the stack map table where the label offset must be added. */ final void put(final ByteVector stackMapTableEntries) { if ((flags & FLAG_RESOLVED) == 0) { addForwardReference(0, FORWARD_REFERENCE_TYPE_STACK_MAP, stackMapTableEntries.length); } stackMapTableEntries.putShort(bytecodeOffset); } /** * Adds a forward reference to this label. This method must be called only for a true forward * reference, i.e. only if this label is not resolved yet. For backward references, the relative * bytecode offset of the reference can be, and must be, computed and stored directly. * * @param sourceInsnBytecodeOffset the bytecode offset of the instruction that contains the * reference stored at referenceHandle. * @param referenceType either {@link #FORWARD_REFERENCE_TYPE_SHORT} or {@link * #FORWARD_REFERENCE_TYPE_WIDE}. * @param referenceHandle the offset in the bytecode where the forward reference value must be * stored. */ private void addForwardReference( final int sourceInsnBytecodeOffset, final int referenceType, final int referenceHandle) { if (forwardReferences == null) { forwardReferences = new int[FORWARD_REFERENCES_CAPACITY_INCREMENT]; } int lastElementIndex = forwardReferences[0]; if (lastElementIndex + 2 >= forwardReferences.length) { int[] newValues = new int[forwardReferences.length + FORWARD_REFERENCES_CAPACITY_INCREMENT]; System.arraycopy(forwardReferences, 0, newValues, 0, forwardReferences.length); forwardReferences = newValues; } forwardReferences[++lastElementIndex] = sourceInsnBytecodeOffset; forwardReferences[++lastElementIndex] = referenceType | referenceHandle; forwardReferences[0] = lastElementIndex; } /** * Sets the bytecode offset of this label to the given value and resolves the forward references * to this label, if any. This method must be called when this label is added to the bytecode of * the method, i.e. when its bytecode offset becomes known. This method fills in the blanks that * where left in the bytecode (and optionally in the stack map table) by each forward reference * previously added to this label. * * @param code the bytecode of the method. * @param stackMapTableEntries the 'entries' array of the StackMapTable code attribute of the * method. Maybe {@literal null}. * @param bytecodeOffset the bytecode offset of this label. * @return {@literal true} if a blank that was left for this label was too small to store the * offset. In such a case the corresponding jump instruction is replaced with an equivalent * ASM specific instruction using an unsigned two bytes offset. These ASM specific * instructions are later replaced with standard bytecode instructions with wider offsets (4 * bytes instead of 2), in ClassReader. */ final boolean resolve( final byte[] code, final ByteVector stackMapTableEntries, final int bytecodeOffset) { this.flags |= FLAG_RESOLVED; this.bytecodeOffset = bytecodeOffset; if (forwardReferences == null) { return false; } boolean hasAsmInstructions = false; for (int i = forwardReferences[0]; i > 0; i -= 2) { final int sourceInsnBytecodeOffset = forwardReferences[i - 1]; final int reference = forwardReferences[i]; final int relativeOffset = bytecodeOffset - sourceInsnBytecodeOffset; int handle = reference & FORWARD_REFERENCE_HANDLE_MASK; if ((reference & FORWARD_REFERENCE_TYPE_MASK) == FORWARD_REFERENCE_TYPE_SHORT) { if (relativeOffset < Short.MIN_VALUE || relativeOffset > Short.MAX_VALUE) { // Change the opcode of the jump instruction, in order to be able to find it later in // ClassReader. These ASM specific opcodes are similar to jump instruction opcodes, except // that the 2 bytes offset is unsigned (and can therefore represent values from 0 to // 65535, which is sufficient since the size of a method is limited to 65535 bytes). int opcode = code[sourceInsnBytecodeOffset] & 0xFF; if (opcode < Opcodes.IFNULL) { // Change IFEQ ... JSR to ASM_IFEQ ... ASM_JSR. code[sourceInsnBytecodeOffset] = (byte) (opcode + Constants.ASM_OPCODE_DELTA); } else { // Change IFNULL and IFNONNULL to ASM_IFNULL and ASM_IFNONNULL. code[sourceInsnBytecodeOffset] = (byte) (opcode + Constants.ASM_IFNULL_OPCODE_DELTA); } hasAsmInstructions = true; } code[handle++] = (byte) (relativeOffset >>> 8); code[handle] = (byte) relativeOffset; } else if ((reference & FORWARD_REFERENCE_TYPE_MASK) == FORWARD_REFERENCE_TYPE_WIDE) { code[handle++] = (byte) (relativeOffset >>> 24); code[handle++] = (byte) (relativeOffset >>> 16); code[handle++] = (byte) (relativeOffset >>> 8); code[handle] = (byte) relativeOffset; } else { stackMapTableEntries.data[handle++] = (byte) (bytecodeOffset >>> 8); stackMapTableEntries.data[handle] = (byte) bytecodeOffset; } } return hasAsmInstructions; } // ----------------------------------------------------------------------------------------------- // Methods related to subroutines // ----------------------------------------------------------------------------------------------- /** * Finds the basic blocks that belong to the subroutine starting with the basic block * corresponding to this label, and marks these blocks as belonging to this subroutine. This * method follows the control flow graph to find all the blocks that are reachable from the * current basic block WITHOUT following any jsr target. * * <p>Note: a precondition and postcondition of this method is that all labels must have a null * {@link #nextListElement}. * * @param subroutineId the id of the subroutine starting with the basic block corresponding to * this label. */ final void markSubroutine(final short subroutineId) { // Data flow algorithm: put this basic block in a list of blocks to process (which are blocks // belonging to subroutine subroutineId) and, while there are blocks to process, remove one from // the list, mark it as belonging to the subroutine, and add its successor basic blocks in the // control flow graph to the list of blocks to process (if not already done). Label listOfBlocksToProcess = this; listOfBlocksToProcess.nextListElement = EMPTY_LIST; while (listOfBlocksToProcess != EMPTY_LIST) { // Remove a basic block from the list of blocks to process. Label basicBlock = listOfBlocksToProcess; listOfBlocksToProcess = listOfBlocksToProcess.nextListElement; basicBlock.nextListElement = null; // If it is not already marked as belonging to a subroutine, mark it as belonging to // subroutineId and add its successors to the list of blocks to process (unless already done). if (basicBlock.subroutineId == 0) { basicBlock.subroutineId = subroutineId; listOfBlocksToProcess = basicBlock.pushSuccessors(listOfBlocksToProcess); } } } /** * Finds the basic blocks that end a subroutine starting with the basic block corresponding to * this label and, for each one of them, adds an outgoing edge to the basic block following the * given subroutine call. In other words, completes the control flow graph by adding the edges * corresponding to the return from this subroutine, when called from the given caller basic * block. * * <p>Note: a precondition and postcondition of this method is that all labels must have a null * {@link #nextListElement}. * * @param subroutineCaller a basic block that ends with a jsr to the basic block corresponding to * this label. This label is supposed to correspond to the start of a subroutine. */ final void addSubroutineRetSuccessors(final Label subroutineCaller) { // Data flow algorithm: put this basic block in a list blocks to process (which are blocks // belonging to a subroutine starting with this label) and, while there are blocks to process, // remove one from the list, put it in a list of blocks that have been processed, add a return // edge to the successor of subroutineCaller if applicable, and add its successor basic blocks // in the control flow graph to the list of blocks to process (if not already done). Label listOfProcessedBlocks = EMPTY_LIST; Label listOfBlocksToProcess = this; listOfBlocksToProcess.nextListElement = EMPTY_LIST; while (listOfBlocksToProcess != EMPTY_LIST) { // Move a basic block from the list of blocks to process to the list of processed blocks. Label basicBlock = listOfBlocksToProcess; listOfBlocksToProcess = basicBlock.nextListElement; basicBlock.nextListElement = listOfProcessedBlocks; listOfProcessedBlocks = basicBlock; // Add an edge from this block to the successor of the caller basic block, if this block is // the end of a subroutine and if this block and subroutineCaller do not belong to the same // subroutine. if ((basicBlock.flags & FLAG_SUBROUTINE_END) != 0 && basicBlock.subroutineId != subroutineCaller.subroutineId) { basicBlock.outgoingEdges = new Edge( basicBlock.outputStackSize, // By construction, the first outgoing edge of a basic block that ends with a jsr // instruction leads to the jsr continuation block, i.e. where execution continues // when ret is called (see {@link #FLAG_SUBROUTINE_CALLER}). subroutineCaller.outgoingEdges.successor, basicBlock.outgoingEdges); } // Add its successors to the list of blocks to process. Note that {@link #pushSuccessors} does // not push basic blocks which are already in a list. Here this means either in the list of // blocks to process, or in the list of already processed blocks. This second list is // important to make sure we don't reprocess an already processed block. listOfBlocksToProcess = basicBlock.pushSuccessors(listOfBlocksToProcess); } // Reset the {@link #nextListElement} of all the basic blocks that have been processed to null, // so that this method can be called again with a different subroutine or subroutine caller. while (listOfProcessedBlocks != EMPTY_LIST) { Label newListOfProcessedBlocks = listOfProcessedBlocks.nextListElement; listOfProcessedBlocks.nextListElement = null; listOfProcessedBlocks = newListOfProcessedBlocks; } } /** * Adds the successors of this label in the method's control flow graph (except those * corresponding to a jsr target, and those already in a list of labels) to the given list of * blocks to process, and returns the new list. * * @param listOfLabelsToProcess a list of basic blocks to process, linked together with their * {@link #nextListElement} field. * @return the new list of blocks to process. */ private Label pushSuccessors(final Label listOfLabelsToProcess) { Label newListOfLabelsToProcess = listOfLabelsToProcess; Edge outgoingEdge = outgoingEdges; while (outgoingEdge != null) { // By construction, the second outgoing edge of a basic block that ends with a jsr instruction // leads to the jsr target (see {@link #FLAG_SUBROUTINE_CALLER}). boolean isJsrTarget = (flags & Label.FLAG_SUBROUTINE_CALLER) != 0 && outgoingEdge == outgoingEdges.nextEdge; if (!isJsrTarget && outgoingEdge.successor.nextListElement == null) { // Add this successor to the list of blocks to process, if it does not already belong to a // list of labels. outgoingEdge.successor.nextListElement = newListOfLabelsToProcess; newListOfLabelsToProcess = outgoingEdge.successor; } outgoingEdge = outgoingEdge.nextEdge; } return newListOfLabelsToProcess; } // ----------------------------------------------------------------------------------------------- // Overridden Object methods // ----------------------------------------------------------------------------------------------- /** * Returns a string representation of this label. * * @return a string representation of this label. */ @Override public String toString() { return "L" + System.identityHashCode(this); } }
spring-projects/spring-framework
spring-core/src/main/java/org/springframework/asm/Label.java
176
/** * One of the first users of BIT’s new supercomputer was Chip Diller. He extended his exploration of * powers of 3 to go from 0 to 333 and he explored taking various sums of those numbers. * “This supercomputer is great,” remarked Chip. “I only wish Timothy were here to see these results.” * (Chip moved to a new apartment, once one became available on the third floor of the Lemon Sky * apartments on Third Street.) * Input * The input will consist of at most 100 lines of text, each of which contains a single VeryLongInteger. * Each VeryLongInteger will be 100 or fewer characters in length, and will only contain digits (no * VeryLongInteger will be negative). * The final input line will contain a single zero on a line by itself. * Output * Your program should output the sum of the VeryLongIntegers given in the input. * Sample Input * 123456789012345678901234567890 * 123456789012345678901234567890 * 123456789012345678901234567890 * 0 * Sample Output * 370370367037037036703703703670 */ //https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&category=&problem=365 import java.math.BigInteger; import java.util.Scanner; public class IntegerInquiry { public static void main(String[] args) { Scanner input = new Scanner(System.in); BigInteger sum = BigInteger.ZERO; while (true) { BigInteger number = input.nextBigInteger(); if (number.equals(BigInteger.ZERO)) { break; } sum = sum.add(number); } System.out.println(sum); } }
kdn251/interviews
uva/IntegerInquiry.java
177
package com.thealgorithms.maths; import java.util.ArrayList; public final class Gaussian { private Gaussian() { } public static ArrayList<Double> gaussian(int mat_size, ArrayList<Double> matrix) { ArrayList<Double> answerArray = new ArrayList<Double>(); int i, j = 0; double[][] mat = new double[mat_size + 1][mat_size + 1]; double[][] x = new double[mat_size][mat_size + 1]; // Values from arraylist to matrix for (i = 0; i < mat_size; i++) { for (j = 0; j <= mat_size; j++) { mat[i][j] = matrix.get(i); } } mat = gaussianElimination(mat_size, i, mat); answerArray = valueOfGaussian(mat_size, x, mat); return answerArray; } // Perform Gaussian elimination public static double[][] gaussianElimination(int mat_size, int i, double[][] mat) { int step = 0; for (step = 0; step < mat_size - 1; step++) { for (i = step; i < mat_size - 1; i++) { double a = (mat[i + 1][step] / mat[step][step]); for (int j = step; j <= mat_size; j++) { mat[i + 1][j] = mat[i + 1][j] - (a * mat[step][j]); } } } return mat; } // calculate the x_1, x_2, ... values of the gaussian and save it in an arraylist. public static ArrayList<Double> valueOfGaussian(int mat_size, double[][] x, double[][] mat) { ArrayList<Double> answerArray = new ArrayList<Double>(); int i, j; for (i = 0; i < mat_size; i++) { for (j = 0; j <= mat_size; j++) { x[i][j] = mat[i][j]; } } for (i = mat_size - 1; i >= 0; i--) { double sum = 0; for (j = mat_size - 1; j > i; j--) { x[i][j] = x[j][j] * x[i][j]; sum = x[i][j] + sum; } if (x[i][i] == 0) { x[i][i] = 0; } else { x[i][i] = (x[i][mat_size] - sum) / (x[i][i]); } answerArray.add(x[i][j]); } return answerArray; } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/maths/Gaussian.java
178
package com.thealgorithms.sorts; import java.util.Random; // https://en.wikipedia.org/wiki/Odd%E2%80%93even_sort public final class OddEvenSort { private OddEvenSort() { } public static void main(String[] args) { int[] arr = new int[100]; Random random = new Random(); // Print out unsorted elements for (int i = 0; i < arr.length; ++i) { arr[i] = random.nextInt(100) - 50; System.out.println(arr[i]); } System.out.println("--------------"); oddEvenSort(arr); // Print Sorted elements for (int i = 0; i < arr.length - 1; ++i) { System.out.println(arr[i]); assert arr[i] <= arr[i + 1]; } } /** * Odd Even Sort algorithms implements * * @param arr the array contains elements */ public static void oddEvenSort(int[] arr) { boolean sorted = false; while (!sorted) { sorted = true; for (int i = 1; i < arr.length - 1; i += 2) { if (arr[i] > arr[i + 1]) { swap(arr, i, i + 1); sorted = false; } } for (int i = 0; i < arr.length - 1; i += 2) { if (arr[i] > arr[i + 1]) { swap(arr, i, i + 1); sorted = false; } } } } /** * Helper function to swap two array values. * * @param arr the array contains elements * @param i the first index to be swapped * @param j the second index to be swapped */ private static void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/sorts/OddEvenSort.java
179
package com.thealgorithms.maths; import java.util.Scanner; /*A magic square of order n is an arrangement of distinct n^2 integers,in a square, such that the n numbers in all rows, all columns, and both diagonals sum to the same constant. A magic square contains the integers from 1 to n^2.*/ public final class MagicSquare { private MagicSquare() { } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Input a number: "); int num = sc.nextInt(); if ((num % 2 == 0) || (num <= 0)) { System.out.print("Input number must be odd and >0"); System.exit(0); } int[][] magic_square = new int[num][num]; int row_num = num / 2; int col_num = num - 1; magic_square[row_num][col_num] = 1; for (int i = 2; i <= num * num; i++) { if (magic_square[(row_num - 1 + num) % num][(col_num + 1) % num] == 0) { row_num = (row_num - 1 + num) % num; col_num = (col_num + 1) % num; } else { col_num = (col_num - 1 + num) % num; } magic_square[row_num][col_num] = i; } // print the square for (int i = 0; i < num; i++) { for (int j = 0; j < num; j++) { if (magic_square[i][j] < 10) { System.out.print(" "); } if (magic_square[i][j] < 100) { System.out.print(" "); } System.out.print(magic_square[i][j] + " "); } System.out.println(); } sc.close(); } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/maths/MagicSquare.java
180
package com.thealgorithms.others; import java.awt.Color; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; /** * The Mandelbrot set is the set of complex numbers "c" for which the series * "z_(n+1) = z_n * z_n + c" does not diverge, i.e. remains bounded. Thus, a * complex number "c" is a member of the Mandelbrot set if, when starting with * "z_0 = 0" and applying the iteration repeatedly, the absolute value of "z_n" * remains bounded for all "n > 0". Complex numbers can be written as "a + b*i": * "a" is the real component, usually drawn on the x-axis, and "b*i" is the * imaginary component, usually drawn on the y-axis. Most visualizations of the * Mandelbrot set use a color-coding to indicate after how many steps in the * series the numbers outside the set cross the divergence threshold. Images of * the Mandelbrot set exhibit an elaborate and infinitely complicated boundary * that reveals progressively ever-finer recursive detail at increasing * magnifications, making the boundary of the Mandelbrot set a fractal curve. * (description adapted from https://en.wikipedia.org/wiki/Mandelbrot_set ) (see * also https://en.wikipedia.org/wiki/Plotting_algorithms_for_the_Mandelbrot_set * ) */ public final class Mandelbrot { private Mandelbrot() { } public static void main(String[] args) { // Test black and white BufferedImage blackAndWhiteImage = getImage(800, 600, -0.6, 0, 3.2, 50, false); // Pixel outside the Mandelbrot set should be white. assert blackAndWhiteImage.getRGB(0, 0) == new Color(255, 255, 255).getRGB(); // Pixel inside the Mandelbrot set should be black. assert blackAndWhiteImage.getRGB(400, 300) == new Color(0, 0, 0).getRGB(); // Test color-coding BufferedImage coloredImage = getImage(800, 600, -0.6, 0, 3.2, 50, true); // Pixel distant to the Mandelbrot set should be red. assert coloredImage.getRGB(0, 0) == new Color(255, 0, 0).getRGB(); // Pixel inside the Mandelbrot set should be black. assert coloredImage.getRGB(400, 300) == new Color(0, 0, 0).getRGB(); // Save image try { ImageIO.write(coloredImage, "png", new File("Mandelbrot.png")); } catch (IOException e) { e.printStackTrace(); } } /** * Method to generate the image of the Mandelbrot set. Two types of * coordinates are used: image-coordinates that refer to the pixels and * figure-coordinates that refer to the complex numbers inside and outside * the Mandelbrot set. The figure-coordinates in the arguments of this * method determine which section of the Mandelbrot set is viewed. The main * area of the Mandelbrot set is roughly between "-1.5 < x < 0.5" and "-1 < * y < 1" in the figure-coordinates. * * @param imageWidth The width of the rendered image. * @param imageHeight The height of the rendered image. * @param figureCenterX The x-coordinate of the center of the figure. * @param figureCenterY The y-coordinate of the center of the figure. * @param figureWidth The width of the figure. * @param maxStep Maximum number of steps to check for divergent behavior. * @param useDistanceColorCoding Render in color or black and white. * @return The image of the rendered Mandelbrot set. */ public static BufferedImage getImage(int imageWidth, int imageHeight, double figureCenterX, double figureCenterY, double figureWidth, int maxStep, boolean useDistanceColorCoding) { if (imageWidth <= 0) { throw new IllegalArgumentException("imageWidth should be greater than zero"); } if (imageHeight <= 0) { throw new IllegalArgumentException("imageHeight should be greater than zero"); } if (maxStep <= 0) { throw new IllegalArgumentException("maxStep should be greater than zero"); } BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB); double figureHeight = figureWidth / imageWidth * imageHeight; // loop through the image-coordinates for (int imageX = 0; imageX < imageWidth; imageX++) { for (int imageY = 0; imageY < imageHeight; imageY++) { // determine the figure-coordinates based on the image-coordinates double figureX = figureCenterX + ((double) imageX / imageWidth - 0.5) * figureWidth; double figureY = figureCenterY + ((double) imageY / imageHeight - 0.5) * figureHeight; double distance = getDistance(figureX, figureY, maxStep); // color the corresponding pixel based on the selected coloring-function image.setRGB(imageX, imageY, useDistanceColorCoding ? colorCodedColorMap(distance).getRGB() : blackAndWhiteColorMap(distance).getRGB()); } } return image; } /** * Black and white color-coding that ignores the relative distance. The * Mandelbrot set is black, everything else is white. * * @param distance Distance until divergence threshold * @return The color corresponding to the distance. */ private static Color blackAndWhiteColorMap(double distance) { return distance >= 1 ? new Color(0, 0, 0) : new Color(255, 255, 255); } /** * Color-coding taking the relative distance into account. The Mandelbrot * set is black. * * @param distance Distance until divergence threshold. * @return The color corresponding to the distance. */ private static Color colorCodedColorMap(double distance) { if (distance >= 1) { return new Color(0, 0, 0); } else { // simplified transformation of HSV to RGB // distance determines hue double hue = 360 * distance; double saturation = 1; double val = 255; int hi = (int) (Math.floor(hue / 60)) % 6; double f = hue / 60 - Math.floor(hue / 60); int v = (int) val; int p = 0; int q = (int) (val * (1 - f * saturation)); int t = (int) (val * (1 - (1 - f) * saturation)); switch (hi) { case 0: return new Color(v, t, p); case 1: return new Color(q, v, p); case 2: return new Color(p, v, t); case 3: return new Color(p, q, v); case 4: return new Color(t, p, v); default: return new Color(v, p, q); } } } /** * Return the relative distance (ratio of steps taken to maxStep) after * which the complex number constituted by this x-y-pair diverges. Members * of the Mandelbrot set do not diverge so their distance is 1. * * @param figureX The x-coordinate within the figure. * @param figureX The y-coordinate within the figure. * @param maxStep Maximum number of steps to check for divergent behavior. * @return The relative distance as the ratio of steps taken to maxStep. */ private static double getDistance(double figureX, double figureY, int maxStep) { double a = figureX; double b = figureY; int currentStep = 0; for (int step = 0; step < maxStep; step++) { currentStep = step; double aNew = a * a - b * b + figureX; b = 2 * a * b + figureY; a = aNew; // divergence happens for all complex number with an absolute value // greater than 4 (= divergence threshold) if (a * a + b * b > 4) { break; } } return (double) currentStep / (maxStep - 1); } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/others/Mandelbrot.java
181
package com.thealgorithms.maths; /** * Class for linear convolution of two discrete signals * * @author Ioannis Karavitsis * @version 1.0 */ public final class Convolution { private Convolution() { } /** * Discrete linear convolution function. Both input signals and the output * signal must start from 0. If you have a signal that has values before 0 * then shift it to start from 0. * * @param A The first discrete signal * @param B The second discrete signal * @return The convolved signal */ public static double[] convolution(double[] A, double[] B) { double[] convolved = new double[A.length + B.length - 1]; /* The discrete convolution of two signals A and B is defined as: A.length C[i] = Σ (A[k]*B[i-k]) k=0 It's obvious that: 0 <= k <= A.length , 0 <= i <= A.length + B.length - 2 and 0 <= i-k <= B.length - 1 From the last inequality we get that: i - B.length + 1 <= k <= i and thus we get the conditions below. */ for (int i = 0; i < convolved.length; i++) { convolved[i] = 0; int k = Math.max(i - B.length + 1, 0); while (k < i + 1 && k < A.length) { convolved[i] += A[k] * B[i - k]; k++; } } return convolved; } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/maths/Convolution.java
182
package com.macro.mall; import org.mybatis.generator.api.MyBatisGenerator; import org.mybatis.generator.config.Configuration; import org.mybatis.generator.config.xml.ConfigurationParser; import org.mybatis.generator.internal.DefaultShellCallback; import java.io.InputStream; import java.util.ArrayList; import java.util.List; /** * MBG代码生成工具 * Created by macro on 2018/4/26. */ public class Generator { public static void main(String[] args) throws Exception { //MBG 执行过程中的警告信息 List<String> warnings = new ArrayList<String>(); //当生成的代码重复时,覆盖原代码 boolean overwrite = true; //读取我们的 MBG 配置文件 InputStream is = Generator.class.getResourceAsStream("/generatorConfig.xml"); ConfigurationParser cp = new ConfigurationParser(warnings); Configuration config = cp.parseConfiguration(is); is.close(); DefaultShellCallback callback = new DefaultShellCallback(overwrite); //创建 MBG MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings); //执行生成代码 myBatisGenerator.generate(null); //输出警告信息 for (String warning : warnings) { System.out.println(warning); } } }
macrozheng/mall
mall-mbg/src/main/java/com/macro/mall/Generator.java
183
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * 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.iluwatar.property; import java.util.HashMap; import java.util.Map; /** * Represents Character in game and his abilities (base stats). */ public class Character implements Prototype { /** * Enumeration of Character types. */ public enum Type { WARRIOR, MAGE, ROGUE } private final Prototype prototype; private final Map<Stats, Integer> properties = new HashMap<>(); private String name; private Type type; /** * Constructor. */ public Character() { this.prototype = new Prototype() { // Null-value object @Override public Integer get(Stats stat) { return null; } @Override public boolean has(Stats stat) { return false; } @Override public void set(Stats stat, Integer val) { // Does Nothing } @Override public void remove(Stats stat) { // Does Nothing. } }; } public Character(Type type, Prototype prototype) { this.type = type; this.prototype = prototype; } /** * Constructor. */ public Character(String name, Character prototype) { this.name = name; this.type = prototype.type; this.prototype = prototype; } public String name() { return name; } public Type type() { return type; } @Override public Integer get(Stats stat) { var containsValue = properties.containsKey(stat); if (containsValue) { return properties.get(stat); } else { return prototype.get(stat); } } @Override public boolean has(Stats stat) { return get(stat) != null; } @Override public void set(Stats stat, Integer val) { properties.put(stat, val); } @Override public void remove(Stats stat) { properties.put(stat, null); } @Override public String toString() { var builder = new StringBuilder(); if (name != null) { builder.append("Player: ").append(name).append('\n'); } if (type != null) { builder.append("Character type: ").append(type.name()).append('\n'); } builder.append("Stats:\n"); for (var stat : Stats.values()) { var value = this.get(stat); if (value == null) { continue; } builder.append(" - ").append(stat.name()).append(':').append(value).append('\n'); } return builder.toString(); } }
smedals/java-design-patterns
property/src/main/java/com/iluwatar/property/Character.java
184
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * 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.iluwatar.iterator.bst; import lombok.Getter; import lombok.Setter; /** * TreeNode Class, representing one node in a Binary Search Tree. Allows for a generically typed * value. * * @param <T> generically typed to accept various data types for the val property */ public class TreeNode<T extends Comparable<T>> { private final T val; @Getter @Setter private TreeNode<T> left; @Getter @Setter private TreeNode<T> right; /** * Creates a TreeNode with a given value, and null children. * * @param val The value of the given node */ public TreeNode(T val) { this.val = val; this.left = null; this.right = null; } public T getVal() { return val; } /** * Inserts new TreeNode based on a given value into the subtree represented by self. * * @param valToInsert The value to insert as a new TreeNode */ public void insert(T valToInsert) { var parent = getParentNodeOfValueToBeInserted(valToInsert); parent.insertNewChild(valToInsert); } /** * Fetch the Parent TreeNode for a given value to insert into the BST. * * @param valToInsert Value of the new TreeNode to be inserted * @return Parent TreeNode of `valToInsert` */ private TreeNode<T> getParentNodeOfValueToBeInserted(T valToInsert) { TreeNode<T> parent = null; var curr = this; while (curr != null) { parent = curr; curr = curr.traverseOneLevelDown(valToInsert); } return parent; } /** * Returns left or right child of self based on a value that would be inserted; maintaining the * integrity of the BST. * * @param value The value of the TreeNode that would be inserted beneath self * @return The child TreeNode of self which represents the subtree where `value` would be inserted */ private TreeNode<T> traverseOneLevelDown(T value) { if (this.isGreaterThan(value)) { return this.left; } return this.right; } /** * Add a new Child TreeNode of given value to self. WARNING: This method is destructive (will * overwrite existing tree structure, if any), and should be called only by this class's insert() * method. * * @param valToInsert Value of the new TreeNode to be inserted */ private void insertNewChild(T valToInsert) { if (this.isLessThanOrEqualTo(valToInsert)) { this.setRight(new TreeNode<>(valToInsert)); } else { this.setLeft(new TreeNode<>(valToInsert)); } } private boolean isGreaterThan(T val) { return this.val.compareTo(val) > 0; } private boolean isLessThanOrEqualTo(T val) { return this.val.compareTo(val) < 1; } @Override public String toString() { return val.toString(); } }
iluwatar/java-design-patterns
iterator/src/main/java/com/iluwatar/iterator/bst/TreeNode.java
185
// A palindrome is a sequence of one or more characters that reads the same from the left as it does from // the right. For example, Z, TOT and MADAM are palindromes, but ADAM is not. // Your job, should you choose to accept it, is to write a program that reads a sequence of strings and // for each string determines the number of UNIQUE palindromes that are substrings. // Input // The input file consists of a number of strings (one per line), of at most 80 characters each, starting in // column 1. // Output // For each non-empty input line, the output consists of one line containing the message: // The string 'input string' contains nnnn palindromes. // where input string is replaced by the actual input string and nnnn is replaced by the number of // UNIQUE palindromes that are substrings. // Note: // See below the explanation of the sample below // • The 3 unique palindromes in ‘boy’ are ‘b’, ‘o’ and ‘y’. // • The 4 unique palindromes in ‘adam’ are ‘a’, ‘d’, ‘m’, and ‘ada’. // • The 5 unique palindromes in ‘madam’ are ‘m’, ‘a’, ‘d’, ‘ada’, and ‘madam’. // • The 3 unique palindromes in ‘tot’ are ‘t’, ‘o’ and ‘tot’. // Sample input // boy // adam // madam // tot // Sample output // The string 'boy' contains 3 palindromes. // The string 'adam' contains 4 palindromes. // The string 'madam' contains 5 palindromes. // The string 'tot' contains 3 palindromes. import java.util.*; public class PeskyPalindromes { public static void main(String args[]) { int x; Scanner sc = new Scanner(System.in); while(sc.hasNext()) { String currentString = sc.next(); List<String> allSubstrings = generateSubstrings(currentString); int uniquePalindromes = findUniquePalindromes(allSubstrings); System.out.println("The string " + "'" + currentString + "'" + " contains " + uniquePalindromes + " palindromes."); } } public static List<String> generateSubstrings(String s) { List<String> allSubstrings = new ArrayList<String>(); for(int i = 0; i < s.length(); i++) { for(int j = i + 1; j <= s.length(); j++) { String currentSubstring = s.substring(i, j); if(!allSubstrings.contains(currentSubstring)) { allSubstrings.add(currentSubstring); } } } return allSubstrings; } public static int findUniquePalindromes(List<String> allSubstrings) { int totalUniquePalindromes = 0; for(String s : allSubstrings) { int left = 0; int right = s.length() - 1; boolean isPalindrome = true; while(left < right) { if(s.charAt(left) != s.charAt(right)) { isPalindrome = false; break; } left++; right--; } if(isPalindrome) { totalUniquePalindromes++; } } return totalUniquePalindromes; } }
kdn251/interviews
uva/PeskyPalindromes.java
186
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * 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.iluwatar.slob.lob; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * Creates an object Animal with a list of animals and/or plants it consumes. */ @Data @AllArgsConstructor @NoArgsConstructor public class Animal implements Serializable { private String name; private Set<Plant> plantsEaten = new HashSet<>(); private Set<Animal> animalsEaten = new HashSet<>(); /** * Iterates over the input nodes recursively and adds new plants to {@link Animal#plantsEaten} or * animals to {@link Animal#animalsEaten} found to input sets respectively. * * @param childNodes contains the XML Node containing the Forest * @param animalsEaten set of Animals eaten * @param plantsEaten set of Plants eaten */ protected static void iterateXmlForAnimalAndPlants(NodeList childNodes, Set<Animal> animalsEaten, Set<Plant> plantsEaten) { for (int i = 0; i < childNodes.getLength(); i++) { Node child = childNodes.item(i); if (child.getNodeType() == Node.ELEMENT_NODE) { if (child.getNodeName().equals(Animal.class.getSimpleName())) { Animal animalEaten = new Animal(); animalEaten.createObjectFromXml(child); animalsEaten.add(animalEaten); } else if (child.getNodeName().equals(Plant.class.getSimpleName())) { Plant plant = new Plant(); plant.createObjectFromXml(child); plantsEaten.add(plant); } } } } /** * Provides XML Representation of the Animal. * * @param xmlDoc object to which the XML representation is to be written to * @return XML Element contain the Animal representation */ public Element toXmlElement(Document xmlDoc) { Element root = xmlDoc.createElement(Animal.class.getSimpleName()); root.setAttribute("name", name); for (Plant plant : plantsEaten) { Element xmlElement = plant.toXmlElement(xmlDoc); if (xmlElement != null) { root.appendChild(xmlElement); } } for (Animal animal : animalsEaten) { Element xmlElement = animal.toXmlElement(xmlDoc); if (xmlElement != null) { root.appendChild(xmlElement); } } xmlDoc.appendChild(root); return (Element) xmlDoc.getFirstChild(); } /** * Parses the Animal Object from the input XML Node. * * @param node the XML Node from which the Animal Object is to be parsed */ public void createObjectFromXml(Node node) { name = node.getAttributes().getNamedItem("name").getNodeValue(); NodeList childNodes = node.getChildNodes(); iterateXmlForAnimalAndPlants(childNodes, animalsEaten, plantsEaten); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("\nAnimal Name = ").append(name); if (!animalsEaten.isEmpty()) { sb.append("\n\tAnimals Eaten by ").append(name).append(": "); } for (Animal animal : animalsEaten) { sb.append("\n\t\t").append(animal); } sb.append("\n"); if (!plantsEaten.isEmpty()) { sb.append("\n\tPlants Eaten by ").append(name).append(": "); } for (Plant plant : plantsEaten) { sb.append("\n\t\t").append(plant); } return sb.toString(); } }
rajprins/java-design-patterns
slob/src/main/java/com/iluwatar/slob/lob/Animal.java
187
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * 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.iluwatar.converter; /** * Example implementation of the simple User converter. */ public class UserConverter extends Converter<UserDto, User> { public UserConverter() { super(UserConverter::convertToEntity, UserConverter::convertToDto); } private static UserDto convertToDto(User user) { return new UserDto(user.firstName(), user.lastName(), user.active(), user.userId()); } private static User convertToEntity(UserDto dto) { return new User(dto.firstName(), dto.lastName(), dto.active(), dto.email()); } }
rajprins/java-design-patterns
converter/src/main/java/com/iluwatar/converter/UserConverter.java
189
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * 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 entity; import jakarta.persistence.CascadeType; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; import jakarta.persistence.OneToOne; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; /** * CakeTopping entity. */ @Entity @Getter @Setter @NoArgsConstructor @AllArgsConstructor @Builder @EqualsAndHashCode public class CakeTopping { @Id @GeneratedValue private Long id; private String name; private int calories; @OneToOne(cascade = CascadeType.ALL) private Cake cake; public CakeTopping(String name, int calories) { this.setName(name); this.setCalories(calories); } @Override public String toString() { return String.format("id=%s name=%s calories=%d", id, name, calories); } }
rajprins/java-design-patterns
layers/src/main/java/entity/CakeTopping.java
190
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * 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.iluwatar.identitymap; import java.io.Serial; import java.io.Serializable; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; /** * Person definition. */ @EqualsAndHashCode(onlyExplicitlyIncluded = true) @Getter @Setter @AllArgsConstructor public final class Person implements Serializable { @Serial private static final long serialVersionUID = 1L; @EqualsAndHashCode.Include private int personNationalId; private String name; private long phoneNum; @Override public String toString() { return "Person ID is : " + personNationalId + " ; Person Name is : " + name + " ; Phone Number is :" + phoneNum; } }
iluwatar/java-design-patterns
identity-map/src/main/java/com/iluwatar/identitymap/Person.java
191
/** * In positional notation we know the position of a digit indicates the weight of that digit toward the * value of a number. For example, in the base 10 number 362 we know that 2 has the weight 100 * , 6 * has the weight 101 * , and 3 has the weight 102 * , yielding the value 3 × 102 + 6 × 101 + 2 × 100 * , or just * 300 + 60 + 2. The same mechanism is used for numbers expressed in other bases. While most people * assume the numbers they encounter everyday are expressed using base 10, we know that other bases * are possible. In particular, the number 362 in base 9 or base 14 represents a totally different value than * 362 in base 10. * For this problem your program will presented with a sequence of pairs of integers. Let’s call the * members of a pair X and Y . What your program is to do is determine the smallest base for X and the * smallest base for Y (likely different from that for X) so that X and Y represent the same value. * Consider, for example, the integers 12 and 5. Certainly these are not equal if base 10 is used for * each. But suppose 12 was a base 3 number and 5 was a base 6 number? 12 base 3 = 1 × 3 * 1 + 2 × 3 * 0 * , * or 5 base 10, and certainly 5 in any base is equal to 5 base 10. So 12 and 5 can be equal, if you select * the right bases for each of them! * Input * On each line of the input data there will be a pair of integers, X and Y , separated by one or more blanks; * leading and trailing blanks may also appear on each line, are are to be ignored. The bases associated * with X and Y will be between 1 and 36 (inclusive), and as noted above, need not be the same for X and * Y . In representing these numbers the digits 0 through 9 have their usual decimal interpretations. The * uppercase alphabetic characters A through Z represent digits with values 10 through 35, respectively. * Output * For each pair of integers in the input display a message similar to those shown in the examples shown * below. Of course if the two integers cannot be equal regardless of the assumed base for each, then print * an appropriate message; a suitable illustration is given in the examples. * Sample Input * 12 5 * 10 A * 12 34 * 123 456 * 1 2 * 10 2 * Sample Output * 12 (base 3) = 5 (base 6) * 10 (base 10) = A (base 11) * 12 (base 17) = 34 (base 5) * 123 is not equal to 456 in any base 2..36 * 1 is not equal to 2 in any base 2..36 * 10 (base 2) = 2 (base 3) */ //https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&category=&problem=279 import java.math.BigInteger; import java.util.Scanner; public class WhatBaseIsThis { public static void main(String[] args) { Scanner input = new Scanner(System.in); while (input.hasNext()) { String x = input.next(); String y = input.next(); boolean found = false; for (int i = 2; i < 37 && !found; i++) { BigInteger xConvertedToBase; try { xConvertedToBase = new BigInteger(x, i); } catch (Exception e) { continue; } for (int j = 2; j < 37; j++) { BigInteger yConvertedToBase; try { yConvertedToBase = new BigInteger(y, j); } catch (Exception e) { continue; } if (xConvertedToBase.equals(yConvertedToBase)) { System.out.println(x + " (base " + i + ") = " + y + " (base " + j + ")"); found = true; break; } } } if (!found) { System.out.println(x + " is not equal to " + y + " in any base 2..36"); } } } }
kdn251/interviews
uva/WhatBaseIsThis.java
192
// Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. // Example 1: // 11110 // 11010 // 11000 // 00000 // Answer: 1 // Example 2: // 11000 // 11000 // 00100 // 00011 // Answer: 3 public class NumberOfIslands { char[][] gridCopy; public int numIslands(char[][] grid) { //set grid copy to the current grid gridCopy = grid; //initialize number of islands to zero int numberOfIslands = 0; //iterate through every index of the grid for(int i = 0; i < grid.length; i++) { for(int j = 0; j < grid[0].length; j++) { //attempt to "sink" the current index of the grid numberOfIslands += sink(gridCopy, i, j); } } //return the total number of islands return numberOfIslands; } int sink(char[][] grid, int i, int j) { //check the bounds of i and j and if the current index is an island or not (1 or 0) if(i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] == '0') { return 0; } //set current index to 0 grid[i][j] = '0'; // sink all neighbors of current index sink(grid, i + 1, j); sink(grid, i - 1, j); sink(grid, i, j + 1); sink(grid, i, j - 1); //increment number of islands return 1; } }
kdn251/interviews
company/amazon/NumberOfIslands.java
193
/** * Fermat’s theorem states that for any * prime number p and for any integer a > 1, * a * p == a (mod p). That is, if we raise a to * the pth power and divide by p, the remainder * is a. Some (but not very many) nonprime * values of p, known as base-a pseudoprimes, * have this property for some a. * (And some, known as Carmichael Numbers, * are base-a pseudoprimes for all a.) * Given 2 < p ≤ 1, 000, 000, 000 and 1 < * a < p, determine whether or not p is a * base-a pseudoprime. * Input * Input contains several test cases followed by a line containing ‘0 0’. Each test case consists of a line * containing p and a. * Output * For each test case, output ‘yes’ if p is a base-a pseudoprime; otherwise output ‘no’. * Sample Input * 3 2 * 10 3 * 341 2 * 341 3 * 1105 2 * 1105 3 * 0 0 * Sample Output * no * no * yes * no * yes * yes */ //https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=2262 import java.math.BigInteger; import java.util.Scanner; public class PseudoPrimeNumbers { public static void main(String[] args) { Scanner input = new Scanner(System.in); while (true) { int p = input.nextInt(); int a = input.nextInt(); if (a == 0 && p == 0) { break; } BigInteger pAsBigInteger = new BigInteger(p + ""); BigInteger aAsBigInteger = new BigInteger(a + ""); String answer = ""; if (!pAsBigInteger.isProbablePrime(10)) { BigInteger result = aAsBigInteger.modPow(pAsBigInteger, pAsBigInteger); if (result.equals(aAsBigInteger)) { answer = "yes"; } else { answer = "no"; } } else { answer = "no"; } System.out.println(answer); } } }
kdn251/interviews
uva/PseudoPrimeNumbers.java
194
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * 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.iluwatar.reactor.framework; import java.io.IOException; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import lombok.extern.slf4j.Slf4j; /** * This class acts as Synchronous Event De-multiplexer and Initiation Dispatcher of Reactor pattern. * Multiple handles i.e. {@link AbstractNioChannel}s can be registered to the reactor, and it blocks * for events from all these handles. Whenever an event occurs on any of the registered handles, it * synchronously de-multiplexes the event which can be any of read, write or accept, and dispatches * the event to the appropriate {@link ChannelHandler} using the {@link Dispatcher}. * * <p>Implementation: A NIO reactor runs in its own thread when it is started using {@link * #start()} method. {@link NioReactor} uses {@link Selector} for realizing Synchronous Event * De-multiplexing. * * <p>NOTE: This is one of the ways to implement NIO reactor, and it does not take care of all * possible edge cases which are required in a real application. This implementation is meant to * demonstrate the fundamental concepts that lie behind Reactor pattern. */ @Slf4j public class NioReactor { private final Selector selector; private final Dispatcher dispatcher; /** * All the work of altering the SelectionKey operations and Selector operations are performed in * the context of main event loop of reactor. So when any channel needs to change its readability * or writability, a new command is added in the command queue and then the event loop picks up * the command and executes it in next iteration. */ private final Queue<Runnable> pendingCommands = new ConcurrentLinkedQueue<>(); private final ExecutorService reactorMain = Executors.newSingleThreadExecutor(); /** * Creates a reactor which will use provided {@code dispatcher} to dispatch events. The * application can provide various implementations of dispatcher which suits its needs. * * @param dispatcher a non-null dispatcher used to dispatch events on registered channels. * @throws IOException if any I/O error occurs. */ public NioReactor(Dispatcher dispatcher) throws IOException { this.dispatcher = dispatcher; this.selector = Selector.open(); } /** * Starts the reactor event loop in a new thread. */ public void start() { reactorMain.execute(() -> { try { LOGGER.info("Reactor started, waiting for events..."); eventLoop(); } catch (IOException e) { LOGGER.error("exception in event loop", e); } }); } /** * Stops the reactor and related resources such as dispatcher. * * @throws InterruptedException if interrupted while stopping the reactor. * @throws IOException if any I/O error occurs. */ public void stop() throws InterruptedException, IOException { reactorMain.shutdown(); selector.wakeup(); if (!reactorMain.awaitTermination(4, TimeUnit.SECONDS)) { reactorMain.shutdownNow(); } selector.close(); LOGGER.info("Reactor stopped"); } /** * Registers a new channel (handle) with this reactor. Reactor will start waiting for events on * this channel and notify of any events. While registering the channel the reactor uses {@link * AbstractNioChannel#getInterestedOps()} to know about the interested operation of this channel. * * @param channel a new channel on which reactor will wait for events. The channel must be bound * prior to being registered. * @return this * @throws IOException if any I/O error occurs. */ public NioReactor registerChannel(AbstractNioChannel channel) throws IOException { var key = channel.getJavaChannel().register(selector, channel.getInterestedOps()); key.attach(channel); channel.setReactor(this); return this; } private void eventLoop() throws IOException { // honor interrupt request while (!Thread.interrupted()) { // honor any pending commands first processPendingCommands(); /* * Synchronous event de-multiplexing happens here, this is blocking call which returns when it * is possible to initiate non-blocking operation on any of the registered channels. */ selector.select(); /* * Represents the events that have occurred on registered handles. */ var keys = selector.selectedKeys(); var iterator = keys.iterator(); while (iterator.hasNext()) { var key = iterator.next(); if (!key.isValid()) { iterator.remove(); continue; } processKey(key); } keys.clear(); } } private void processPendingCommands() { var iterator = pendingCommands.iterator(); while (iterator.hasNext()) { var command = iterator.next(); command.run(); iterator.remove(); } } /* * Initiation dispatcher logic, it checks the type of event and notifier application specific * event handler to handle the event. */ private void processKey(SelectionKey key) throws IOException { if (key.isAcceptable()) { onChannelAcceptable(key); } else if (key.isReadable()) { onChannelReadable(key); } else if (key.isWritable()) { onChannelWritable(key); } } private static void onChannelWritable(SelectionKey key) throws IOException { var channel = (AbstractNioChannel) key.attachment(); channel.flush(key); } private void onChannelReadable(SelectionKey key) { try { // reads the incoming data in context of reactor main loop. Can this be improved? var readObject = ((AbstractNioChannel) key.attachment()).read(key); dispatchReadEvent(key, readObject); } catch (IOException e) { try { key.channel().close(); } catch (IOException e1) { LOGGER.error("error closing channel", e1); } } } /* * Uses the application provided dispatcher to dispatch events to application handler. */ private void dispatchReadEvent(SelectionKey key, Object readObject) { dispatcher.onChannelReadEvent((AbstractNioChannel) key.attachment(), readObject, key); } private void onChannelAcceptable(SelectionKey key) throws IOException { var serverSocketChannel = (ServerSocketChannel) key.channel(); var socketChannel = serverSocketChannel.accept(); socketChannel.configureBlocking(false); var readKey = socketChannel.register(selector, SelectionKey.OP_READ); readKey.attach(key.attachment()); } /** * Queues the change of operations request of a channel, which will change the interested * operations of the channel sometime in the future. * * <p>This is a non-blocking method and does not guarantee that the operations have changed when * this method returns. * * @param key the key for which operations have to be changed. * @param interestedOps the new interest operations. */ public void changeOps(SelectionKey key, int interestedOps) { pendingCommands.add(new ChangeKeyOpsCommand(key, interestedOps)); selector.wakeup(); } /** * A command that changes the interested operations of the key provided. */ static class ChangeKeyOpsCommand implements Runnable { private final SelectionKey key; private final int interestedOps; public ChangeKeyOpsCommand(SelectionKey key, int interestedOps) { this.key = key; this.interestedOps = interestedOps; } public void run() { key.interestOps(interestedOps); } @Override public String toString() { return "Change of ops to: " + interestedOps; } } }
rajprins/java-design-patterns
reactor/src/main/java/com/iluwatar/reactor/framework/NioReactor.java
195
/** * Calculate * R := B * P mod M * for large values of B, P, and M using an efficient algorithm. (That’s right, this problem has a time * dependency !!!.) * Input * The input will contain several test cases, each of them as described below. Consecutive test cases are * separated by a single blank line. * Three integer values (in the order B, P, M) will be read one number per line. B and P are integers * in the range 0 to 2147483647 inclusive. M is an integer in the range 1 to 46340 inclusive. * Output * For each test, the result of the computation. A single integer on a line by itself. * Sample Input * 3 * 18132 * 17 * 17 * 1765 * 3 * 2374859 * 3029382 * 36123 * Sample Output * 13 * 2 * 13195 */ //https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=727&page=show_problem&problem=310 import java.math.BigInteger; import java.util.Scanner; public class BigMod { public static void main(String[] args) { Scanner input = new Scanner(System.in); while (input.hasNext()) { BigInteger b = input.nextBigInteger(); BigInteger p = input.nextBigInteger(); BigInteger m = input.nextBigInteger(); System.out.println(b.modPow(p, m)); } } }
kdn251/interviews
uva/BigMod.java
196
// Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue. // Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. // Note: // You are not suppose to use the library's sort function for this problem. public class SortColors { public void sortColors(int[] nums) { int wall = 0; for(int i = 0; i < nums.length; i++) { if(nums[i] < 1) { int temp = nums[i]; nums[i] = nums[wall]; nums[wall] = temp; wall++; } } for(int i = 0; i < nums.length; i++) { if(nums[i] == 1) { int temp = nums[i]; nums[i] = nums[wall]; nums[wall] = temp; wall++; } } } }
kdn251/interviews
leetcode/two-pointers/SortColors.java
197
/** * An integer greater than 1 is called a prime number if its only positive divisors (factors) are 1 and itself. * Prime numbers have been studied over the years by a lot of mathematicians. Applications of prime * numbers arise in Cryptography and Coding Theory among others. * Have you tried reversing a prime? For most primes, you get a composite (43 becomes 34). An * Emirp (Prime spelt backwards) is a Prime that gives you a different Prime when its digits are reversed. * For example, 17 is Emirp because 17 as well as 71 are Prime. * In this problem, you have to decide whether a number N is Non-prime or Prime or Emirp. Assume * that 1 < N < 1000000. * Interestingly, Emirps are not new to NTU students. We have been boarding 199 and 179 buses for * quite a long time! * Input * Input consists of several lines specifying values for N. * Output * For each N given in the input, output should contain one of the following: * 1. ‘N is not prime.’, if N is not a Prime number. * 2. ‘N is prime.’, if N is Prime and N is not Emirp. * 3. ‘N is emirp.’, if N is Emirp. * Sample Input * 17 * 18 * 19 * 179 * 199 * Sample Output * 17 is emirp. * 18 is not prime. * 19 is prime. * 179 is emirp. * 199 is emirp. */ //https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1176 import java.math.BigInteger; import java.util.Scanner; public class SimplyEmirp { public static void main(String[] args) { Scanner input = new Scanner(System.in); while (input.hasNext()) { String inputGiven = input.next(); BigInteger number = new BigInteger(inputGiven); if (!number.isProbablePrime(10)) { System.out.println(number + " is not prime."); } else { String numberReversedAsString = new StringBuilder( number.toString()).reverse().toString(); BigInteger numberReversed = new BigInteger( numberReversedAsString); if (numberReversed.isProbablePrime(10) && numberReversed.compareTo(number) != 0) { System.out.println(number + " is emirp."); } else { System.out.println(number + " is prime."); } } } } }
kdn251/interviews
uva/SimplyEmirp.java
198
// Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2. // Note: // The length of both num1 and num2 is < 110. // Both num1 and num2 contains only digits 0-9. // Both num1 and num2 does not contain any leading zero. // You must not use any built-in BigInteger library or convert the inputs to integer directly. public class MultiplyStrings { public String multiply(String num1, String num2) { int m = num1.length(); int n = num2.length(); int[] pos = new int[m + n]; for(int i = m - 1; i >= 0; i--) { for(int j = n - 1; j >= 0; j--) { int mul = (num1.charAt(i) - '0') * (num2.charAt(j) - '0'); int p1 = i + j; int p2 = i + j + 1; int sum = mul + pos[p2]; pos[p1] += sum / 10; pos[p2] = (sum) % 10; } } StringBuilder sb = new StringBuilder(); for(int p : pos) { if(!(sb.length() == 0 && p == 0)) { sb.append(p); } } return sb.length() == 0 ? "0" : sb.toString(); } }
kdn251/interviews
company/twitter/MultiplyStrings.java
199
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * 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.iluwatar.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Optional; import java.util.Spliterator; import java.util.Spliterators; import java.util.function.Consumer; import java.util.stream.Stream; import java.util.stream.StreamSupport; import javax.sql.DataSource; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; /** * An implementation of {@link CustomerDao} that persists customers in RDBMS. */ @Slf4j @RequiredArgsConstructor public class DbCustomerDao implements CustomerDao { private final DataSource dataSource; /** * Get all customers as Java Stream. * * @return a lazily populated stream of customers. Note the stream returned must be closed to free * all the acquired resources. The stream keeps an open connection to the database till it is * complete or is closed manually. */ @Override public Stream<Customer> getAll() throws Exception { try { var connection = getConnection(); var statement = connection.prepareStatement("SELECT * FROM CUSTOMERS"); // NOSONAR var resultSet = statement.executeQuery(); // NOSONAR return StreamSupport.stream(new Spliterators.AbstractSpliterator<Customer>(Long.MAX_VALUE, Spliterator.ORDERED) { @Override public boolean tryAdvance(Consumer<? super Customer> action) { try { if (!resultSet.next()) { return false; } action.accept(createCustomer(resultSet)); return true; } catch (SQLException e) { throw new RuntimeException(e); // NOSONAR } } }, false).onClose(() -> mutedClose(connection, statement, resultSet)); } catch (SQLException e) { throw new CustomException(e.getMessage(), e); } } private Connection getConnection() throws SQLException { return dataSource.getConnection(); } private void mutedClose(Connection connection, PreparedStatement statement, ResultSet resultSet) { try { resultSet.close(); statement.close(); connection.close(); } catch (SQLException e) { LOGGER.info("Exception thrown " + e.getMessage()); } } private Customer createCustomer(ResultSet resultSet) throws SQLException { return new Customer(resultSet.getInt("ID"), resultSet.getString("FNAME"), resultSet.getString("LNAME")); } /** * {@inheritDoc} */ @Override public Optional<Customer> getById(int id) throws Exception { ResultSet resultSet = null; try (var connection = getConnection(); var statement = connection.prepareStatement("SELECT * FROM CUSTOMERS WHERE ID = ?")) { statement.setInt(1, id); resultSet = statement.executeQuery(); if (resultSet.next()) { return Optional.of(createCustomer(resultSet)); } else { return Optional.empty(); } } catch (SQLException ex) { throw new CustomException(ex.getMessage(), ex); } finally { if (resultSet != null) { resultSet.close(); } } } /** * {@inheritDoc} */ @Override public boolean add(Customer customer) throws Exception { if (getById(customer.getId()).isPresent()) { return false; } try (var connection = getConnection(); var statement = connection.prepareStatement("INSERT INTO CUSTOMERS VALUES (?,?,?)")) { statement.setInt(1, customer.getId()); statement.setString(2, customer.getFirstName()); statement.setString(3, customer.getLastName()); statement.execute(); return true; } catch (SQLException ex) { throw new CustomException(ex.getMessage(), ex); } } /** * {@inheritDoc} */ @Override public boolean update(Customer customer) throws Exception { try (var connection = getConnection(); var statement = connection .prepareStatement("UPDATE CUSTOMERS SET FNAME = ?, LNAME = ? WHERE ID = ?")) { statement.setString(1, customer.getFirstName()); statement.setString(2, customer.getLastName()); statement.setInt(3, customer.getId()); return statement.executeUpdate() > 0; } catch (SQLException ex) { throw new CustomException(ex.getMessage(), ex); } } /** * {@inheritDoc} */ @Override public boolean delete(Customer customer) throws Exception { try (var connection = getConnection(); var statement = connection.prepareStatement("DELETE FROM CUSTOMERS WHERE ID = ?")) { statement.setInt(1, customer.getId()); return statement.executeUpdate() > 0; } catch (SQLException ex) { throw new CustomException(ex.getMessage(), ex); } } }
smedals/java-design-patterns
dao/src/main/java/com/iluwatar/dao/DbCustomerDao.java
200
package com.thealgorithms.maths; /** * This is Euclid's algorithm, used to find the greatest common * denominator Override function name gcd * * @author Oskar Enmalm 3/10/17 */ public final class GCD { private GCD() { } /** * get the greatest common divisor * * @param num1 the first number * @param num2 the second number * @return gcd */ public static int gcd(int num1, int num2) { if (num1 < 0 || num2 < 0) { throw new ArithmeticException(); } if (num1 == 0 || num2 == 0) { return Math.abs(num1 - num2); } while (num1 % num2 != 0) { int remainder = num1 % num2; num1 = num2; num2 = remainder; } return num2; } /** * @brief computes gcd of an array of numbers * * @param numbers the input array * @return gcd of all of the numbers in the input array */ public static int gcd(int[] numbers) { int result = 0; for (final var number : numbers) { result = gcd(result, number); } return result; } public static void main(String[] args) { int[] myIntArray = {4, 16, 32}; // call gcd function (input array) System.out.println(gcd(myIntArray)); // => 4 System.out.printf("gcd(40,24)=%d gcd(24,40)=%d%n", gcd(40, 24), gcd(24, 40)); // => 8 } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/maths/GCD.java
201
/* Automatically generated by GNU msgfmt. Do not modify! */ package org.postgresql.translation; public class messages_pl extends java.util.ResourceBundle { private static final java.lang.String[] table; static { java.lang.String[] t = new java.lang.String[346]; t[0] = ""; t[1] = "Project-Id-Version: head-pl\nReport-Msgid-Bugs-To: \nPO-Revision-Date: 2005-05-22 03:01+0200\nLast-Translator: Jarosław Jan Pyszny <jarek@pyszny.net>\nLanguage-Team: <pl@li.org>\nLanguage: \nMIME-Version: 1.0\nContent-Type: text/plain; charset=UTF-8\nContent-Transfer-Encoding: 8bit\nX-Generator: KBabel 1.10\nPlural-Forms: nplurals=3; plural=(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);\n"; t[2] = "The driver currently does not support COPY operations."; t[3] = "Sterownik nie obsługuje aktualnie operacji COPY."; t[4] = "Internal Query: {0}"; t[5] = "Wewnętrzne Zapytanie: {0}"; t[6] = "There are no rows in this ResultSet."; t[7] = "Nie ma żadnych wierszy w tym ResultSet."; t[8] = "Invalid character data was found. This is most likely caused by stored data containing characters that are invalid for the character set the database was created in. The most common example of this is storing 8bit data in a SQL_ASCII database."; t[9] = "Znaleziono nieprawidłowy znak. Najprawdopodobniej jest to spowodowane przechowywaniem w bazie znaków, które nie pasują do zestawu znaków wybranego podczas tworzenia bazy danych. Najczęstszy przykład to przechowywanie 8-bitowych znaków w bazie o kodowaniu SQL_ASCII."; t[12] = "Fastpath call {0} - No result was returned and we expected an integer."; t[13] = "Wywołanie fastpath {0} - Nie otrzymano żadnego wyniku, a oczekiwano liczby całkowitej."; t[14] = "An error occurred while setting up the SSL connection."; t[15] = "Wystąpił błąd podczas ustanawiania połączenia SSL."; t[20] = "A CallableStatement was declared, but no call to registerOutParameter(1, <some type>) was made."; t[21] = "Funkcja CallableStatement została zadeklarowana, ale nie wywołano registerOutParameter (1, <jakiś typ>)."; t[24] = "Unexpected command status: {0}."; t[25] = "Nieoczekiwany status komendy: {0}."; t[32] = "A connection could not be made using the requested protocol {0}."; t[33] = "Nie można było nawiązać połączenia stosując żądany protokołu {0}."; t[38] = "Bad value for type {0} : {1}"; t[39] = "Zła wartość dla typu {0}: {1}"; t[40] = "Not on the insert row."; t[41] = "Nie na wstawianym rekordzie."; t[42] = "Premature end of input stream, expected {0} bytes, but only read {1}."; t[43] = "Przedwczesny koniec strumienia wejściowego, oczekiwano {0} bajtów, odczytano tylko {1}."; t[48] = "Unknown type {0}."; t[49] = "Nieznany typ {0}."; t[52] = "The server does not support SSL."; t[53] = "Serwer nie obsługuje SSL."; t[60] = "Cannot call updateRow() when on the insert row."; t[61] = "Nie można wywołać updateRow() na wstawianym rekordzie."; t[62] = "Where: {0}"; t[63] = "Gdzie: {0}"; t[72] = "Cannot call cancelRowUpdates() when on the insert row."; t[73] = "Nie można wywołać cancelRowUpdates() na wstawianym rekordzie."; t[82] = "Server SQLState: {0}"; t[83] = "Serwer SQLState: {0}"; t[92] = "ResultSet is not updateable. The query that generated this result set must select only one table, and must select all primary keys from that table. See the JDBC 2.1 API Specification, section 5.6 for more details."; t[93] = "ResultSet nie jest modyfikowalny (not updateable). Zapytanie, które zwróciło ten wynik musi dotyczyć tylko jednej tabeli oraz musi pobierać wszystkie klucze główne tej tabeli. Zobacz Specyfikację JDBC 2.1 API, rozdział 5.6, by uzyskać więcej szczegółów."; t[102] = "Cannot tell if path is open or closed: {0}."; t[103] = "Nie można stwierdzić, czy ścieżka jest otwarta czy zamknięta: {0}."; t[108] = "The parameter index is out of range: {0}, number of parameters: {1}."; t[109] = "Indeks parametru jest poza zakresem: {0}, liczba parametrów: {1}."; t[110] = "Unsupported Types value: {0}"; t[111] = "Nieznana wartość Types: {0}"; t[112] = "Currently positioned after the end of the ResultSet. You cannot call deleteRow() here."; t[113] = "Aktualna pozycja za końcem ResultSet. Nie można wywołać deleteRow()."; t[114] = "This ResultSet is closed."; t[115] = "Ten ResultSet jest zamknięty."; t[120] = "Conversion of interval failed"; t[121] = "Konwersja typu interval nie powiodła się"; t[122] = "Unable to load the class {0} responsible for the datatype {1}"; t[123] = "Nie jest możliwe załadowanie klasy {0} odpowiedzialnej za typ danych {1}"; t[138] = "Error loading default settings from driverconfig.properties"; t[139] = "Błąd podczas wczytywania ustawień domyślnych z driverconfig.properties"; t[142] = "The array index is out of range: {0}"; t[143] = "Indeks tablicy jest poza zakresem: {0}"; t[146] = "Unknown Types value."; t[147] = "Nieznana wartość Types."; t[154] = "The maximum field size must be a value greater than or equal to 0."; t[155] = "Maksymalny rozmiar pola musi być wartością dodatnią lub 0."; t[168] = "Detail: {0}"; t[169] = "Szczegóły: {0}"; t[170] = "Unknown Response Type {0}."; t[171] = "Nieznany typ odpowiedzi {0}."; t[172] = "Maximum number of rows must be a value grater than or equal to 0."; t[173] = "Maksymalna liczba rekordów musi być wartością dodatnią lub 0."; t[184] = "Query timeout must be a value greater than or equals to 0."; t[185] = "Timeout zapytania musi być wartością dodatnią lub 0."; t[186] = "Too many update results were returned."; t[187] = "Zapytanie nie zwróciło żadnych wyników."; t[190] = "The connection attempt failed."; t[191] = "Próba nawiązania połączenia nie powiodła się."; t[198] = "Connection has been closed automatically because a new connection was opened for the same PooledConnection or the PooledConnection has been closed."; t[199] = "Połączenie zostało zamknięte automatycznie, ponieważ nowe połączenie zostało otwarte dla tego samego PooledConnection lub PooledConnection zostało zamknięte."; t[204] = "Protocol error. Session setup failed."; t[205] = "Błąd protokołu. Nie udało się utworzyć sesji."; t[206] = "This PooledConnection has already been closed."; t[207] = "To PooledConnection zostało już zamknięte."; t[208] = "DataSource has been closed."; t[209] = "DataSource zostało zamknięte."; t[212] = "Method {0} is not yet implemented."; t[213] = "Metoda {0}nie jest jeszcze obsługiwana."; t[216] = "Hint: {0}"; t[217] = "Wskazówka: {0}"; t[218] = "No value specified for parameter {0}."; t[219] = "Nie podano wartości dla parametru {0}."; t[222] = "Position: {0}"; t[223] = "Pozycja: {0}"; t[226] = "Cannot call deleteRow() when on the insert row."; t[227] = "Nie można wywołać deleteRow() na wstawianym rekordzie."; t[240] = "Conversion of money failed."; t[241] = "Konwersja typu money nie powiodła się."; t[244] = "Internal Position: {0}"; t[245] = "Wewnętrzna Pozycja: {0}"; t[248] = "Connection has been closed."; t[249] = "Połączenie zostało zamknięte."; t[254] = "Currently positioned before the start of the ResultSet. You cannot call deleteRow() here."; t[255] = "Aktualna pozycja przed początkiem ResultSet. Nie można wywołać deleteRow()."; t[258] = "Failed to create object for: {0}."; t[259] = "Nie powiodło się utworzenie obiektu dla: {0}."; t[262] = "Fetch size must be a value greater to or equal to 0."; t[263] = "Rozmiar pobierania musi być wartością dodatnią lub 0."; t[270] = "No results were returned by the query."; t[271] = "Zapytanie nie zwróciło żadnych wyników."; t[276] = "The authentication type {0} is not supported. Check that you have configured the pg_hba.conf file to include the client''s IP address or subnet, and that it is using an authentication scheme supported by the driver."; t[277] = "Uwierzytelnienie typu {0} nie jest obsługiwane. Upewnij się, że skonfigurowałeś plik pg_hba.conf tak, że zawiera on adres IP lub podsieć klienta oraz że użyta metoda uwierzytelnienia jest wspierana przez ten sterownik."; t[280] = "Conversion to type {0} failed: {1}."; t[281] = "Konwersja do typu {0} nie powiodła się: {1}."; t[282] = "A result was returned when none was expected."; t[283] = "Zwrócono wynik zapytania, choć nie był on oczekiwany."; t[292] = "Transaction isolation level {0} not supported."; t[293] = "Poziom izolacji transakcji {0} nie jest obsługiwany."; t[306] = "ResultSet not positioned properly, perhaps you need to call next."; t[307] = "Zła pozycja w ResultSet, może musisz wywołać next."; t[308] = "Location: File: {0}, Routine: {1}, Line: {2}"; t[309] = "Lokalizacja: Plik: {0}, Procedura: {1}, Linia: {2}"; t[314] = "An unexpected result was returned by a query."; t[315] = "Zapytanie zwróciło nieoczekiwany wynik."; t[316] = "The column index is out of range: {0}, number of columns: {1}."; t[317] = "Indeks kolumny jest poza zakresem: {0}, liczba kolumn: {1}."; t[318] = "Expected command status BEGIN, got {0}."; t[319] = "Spodziewano się statusu komendy BEGIN, otrzymano {0}."; t[320] = "The fastpath function {0} is unknown."; t[321] = "Funkcja fastpath {0} jest nieznana."; t[324] = "The server requested password-based authentication, but no password was provided."; t[325] = "Serwer zażądał uwierzytelnienia opartego na haśle, ale żadne hasło nie zostało dostarczone."; t[332] = "The array index is out of range: {0}, number of elements: {1}."; t[333] = "Indeks tablicy jest poza zakresem: {0}, liczba elementów: {1}."; t[338] = "Something unusual has occurred to cause the driver to fail. Please report this exception."; t[339] = "Coś niezwykłego spowodowało pad sterownika. Proszę, zgłoś ten wyjątek."; t[342] = "Zero bytes may not occur in string parameters."; t[343] = "Zerowe bajty nie mogą pojawiać się w parametrach typu łańcuch znakowy."; table = t; } public java.lang.Object handleGetObject (java.lang.String msgid) throws java.util.MissingResourceException { int hash_val = msgid.hashCode() & 0x7fffffff; int idx = (hash_val % 173) << 1; { java.lang.Object found = table[idx]; if (found == null) return null; if (msgid.equals(found)) return table[idx + 1]; } int incr = ((hash_val % 171) + 1) << 1; for (;;) { idx += incr; if (idx >= 346) idx -= 346; java.lang.Object found = table[idx]; if (found == null) return null; if (msgid.equals(found)) return table[idx + 1]; } } public java.util.Enumeration getKeys () { return new java.util.Enumeration() { private int idx = 0; { while (idx < 346 && table[idx] == null) idx += 2; } public boolean hasMoreElements () { return (idx < 346); } public java.lang.Object nextElement () { java.lang.Object key = table[idx]; do idx += 2; while (idx < 346 && table[idx] == null); return key; } }; } public java.util.ResourceBundle getParent () { return parent; } }
pgjdbc/pgjdbc
pgjdbc/src/main/java/org/postgresql/translation/messages_pl.java