Merge branch 'master' of github.com:eugenp/tutorials into feature/BAEL-2774-Run-Java-main-method-using-Gradle
This commit is contained in:
commit
d8b0c63f87
@ -1,5 +1,5 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>algorithms-miscellaneous-3</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
@ -18,17 +18,28 @@
|
||||
<version>${org.assertj.core.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>${commons-collections4.version}</version>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>${commons-collections4.version}</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.squareup.retrofit2</groupId>
|
||||
<artifactId>retrofit</artifactId>
|
||||
<version>${retrofit.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.squareup.retrofit2</groupId>
|
||||
<artifactId>converter-jackson</artifactId>
|
||||
<version>${retrofit.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
@ -61,5 +72,6 @@
|
||||
<org.assertj.core.version>3.9.0</org.assertj.core.version>
|
||||
<commons-collections4.version>4.3</commons-collections4.version>
|
||||
<guava.version>28.0-jre</guava.version>
|
||||
<retrofit.version>2.6.0</retrofit.version>
|
||||
</properties>
|
||||
</project>
|
@ -0,0 +1,35 @@
|
||||
package com.baeldung.algorithms.interpolationsearch;
|
||||
|
||||
public class InterpolationSearch {
|
||||
|
||||
public static int interpolationSearch(int[] data, int item) {
|
||||
|
||||
int highEnd = (data.length - 1);
|
||||
int lowEnd = 0;
|
||||
|
||||
while (item >= data[lowEnd] && item <= data[highEnd] && lowEnd <= highEnd) {
|
||||
|
||||
int probe = lowEnd + (highEnd - lowEnd) * (item - data[lowEnd]) / (data[highEnd] - data[lowEnd]);
|
||||
|
||||
if (highEnd == lowEnd) {
|
||||
if (data[lowEnd] == item) {
|
||||
return lowEnd;
|
||||
} else {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
if (data[probe] == item) {
|
||||
return probe;
|
||||
}
|
||||
|
||||
if (data[probe] < item) {
|
||||
lowEnd = probe + 1;
|
||||
} else {
|
||||
highEnd = probe - 1;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,45 @@
|
||||
package com.baeldung.algorithms.kmeans;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Encapsulates all coordinates for a particular cluster centroid.
|
||||
*/
|
||||
public class Centroid {
|
||||
|
||||
/**
|
||||
* The centroid coordinates.
|
||||
*/
|
||||
private final Map<String, Double> coordinates;
|
||||
|
||||
public Centroid(Map<String, Double> coordinates) {
|
||||
this.coordinates = coordinates;
|
||||
}
|
||||
|
||||
public Map<String, Double> getCoordinates() {
|
||||
return coordinates;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
Centroid centroid = (Centroid) o;
|
||||
return Objects.equals(getCoordinates(), centroid.getCoordinates());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(getCoordinates());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Centroid " + coordinates;
|
||||
}
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
package com.baeldung.algorithms.kmeans;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Defines a contract to calculate distance between two feature vectors. The less the
|
||||
* calculated distance, the more two items are similar to each other.
|
||||
*/
|
||||
public interface Distance {
|
||||
|
||||
/**
|
||||
* Calculates the distance between two feature vectors.
|
||||
*
|
||||
* @param f1 The first set of features.
|
||||
* @param f2 The second set of features.
|
||||
* @return Calculated distance.
|
||||
* @throws IllegalArgumentException If the given feature vectors are invalid.
|
||||
*/
|
||||
double calculate(Map<String, Double> f1, Map<String, Double> f2);
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
package com.baeldung.algorithms.kmeans;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Encapsulates methods to calculates errors between centroid and the cluster members.
|
||||
*/
|
||||
public class Errors {
|
||||
|
||||
public static double sse(Map<Centroid, List<Record>> clustered, Distance distance) {
|
||||
double sum = 0;
|
||||
for (Map.Entry<Centroid, List<Record>> entry : clustered.entrySet()) {
|
||||
Centroid centroid = entry.getKey();
|
||||
for (Record record : entry.getValue()) {
|
||||
double d = distance.calculate(centroid.getCoordinates(), record.getFeatures());
|
||||
sum += Math.pow(d, 2);
|
||||
}
|
||||
}
|
||||
|
||||
return sum;
|
||||
}
|
||||
}
|
@ -0,0 +1,26 @@
|
||||
package com.baeldung.algorithms.kmeans;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Calculates the distance between two items using the Euclidean formula.
|
||||
*/
|
||||
public class EuclideanDistance implements Distance {
|
||||
|
||||
@Override
|
||||
public double calculate(Map<String, Double> f1, Map<String, Double> f2) {
|
||||
if (f1 == null || f2 == null) {
|
||||
throw new IllegalArgumentException("Feature vectors can't be null");
|
||||
}
|
||||
|
||||
double sum = 0;
|
||||
for (String key : f1.keySet()) {
|
||||
Double v1 = f1.get(key);
|
||||
Double v2 = f2.get(key);
|
||||
|
||||
if (v1 != null && v2 != null) sum += Math.pow(v1 - v2, 2);
|
||||
}
|
||||
|
||||
return Math.sqrt(sum);
|
||||
}
|
||||
}
|
@ -0,0 +1,236 @@
|
||||
package com.baeldung.algorithms.kmeans;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Random;
|
||||
import java.util.Set;
|
||||
|
||||
import static java.util.stream.Collectors.toList;
|
||||
import static java.util.stream.Collectors.toSet;
|
||||
|
||||
/**
|
||||
* Encapsulates an implementation of KMeans clustering algorithm.
|
||||
*
|
||||
* @author Ali Dehghani
|
||||
*/
|
||||
public class KMeans {
|
||||
|
||||
private KMeans() {
|
||||
throw new IllegalAccessError("You shouldn't call this constructor");
|
||||
}
|
||||
|
||||
/**
|
||||
* Will be used to generate random numbers.
|
||||
*/
|
||||
private static final Random random = new Random();
|
||||
|
||||
/**
|
||||
* Performs the K-Means clustering algorithm on the given dataset.
|
||||
*
|
||||
* @param records The dataset.
|
||||
* @param k Number of Clusters.
|
||||
* @param distance To calculate the distance between two items.
|
||||
* @param maxIterations Upper bound for the number of iterations.
|
||||
* @return K clusters along with their features.
|
||||
*/
|
||||
public static Map<Centroid, List<Record>> fit(List<Record> records, int k, Distance distance, int maxIterations) {
|
||||
applyPreconditions(records, k, distance, maxIterations);
|
||||
|
||||
List<Centroid> centroids = randomCentroids(records, k);
|
||||
Map<Centroid, List<Record>> clusters = new HashMap<>();
|
||||
Map<Centroid, List<Record>> lastState = new HashMap<>();
|
||||
|
||||
// iterate for a pre-defined number of times
|
||||
for (int i = 0; i < maxIterations; i++) {
|
||||
boolean isLastIteration = i == maxIterations - 1;
|
||||
|
||||
// in each iteration we should find the nearest centroid for each record
|
||||
for (Record record : records) {
|
||||
Centroid centroid = nearestCentroid(record, centroids, distance);
|
||||
assignToCluster(clusters, record, centroid);
|
||||
}
|
||||
|
||||
// if the assignment does not change, then the algorithm terminates
|
||||
boolean shouldTerminate = isLastIteration || clusters.equals(lastState);
|
||||
lastState = clusters;
|
||||
if (shouldTerminate) {
|
||||
break;
|
||||
}
|
||||
|
||||
// at the end of each iteration we should relocate the centroids
|
||||
centroids = relocateCentroids(clusters);
|
||||
clusters = new HashMap<>();
|
||||
}
|
||||
|
||||
return lastState;
|
||||
}
|
||||
|
||||
/**
|
||||
* Move all cluster centroids to the average of all assigned features.
|
||||
*
|
||||
* @param clusters The current cluster configuration.
|
||||
* @return Collection of new and relocated centroids.
|
||||
*/
|
||||
private static List<Centroid> relocateCentroids(Map<Centroid, List<Record>> clusters) {
|
||||
return clusters
|
||||
.entrySet()
|
||||
.stream()
|
||||
.map(e -> average(e.getKey(), e.getValue()))
|
||||
.collect(toList());
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves the given centroid to the average position of all assigned features. If
|
||||
* the centroid has no feature in its cluster, then there would be no need for a
|
||||
* relocation. Otherwise, for each entry we calculate the average of all records
|
||||
* first by summing all the entries and then dividing the final summation value by
|
||||
* the number of records.
|
||||
*
|
||||
* @param centroid The centroid to move.
|
||||
* @param records The assigned features.
|
||||
* @return The moved centroid.
|
||||
*/
|
||||
private static Centroid average(Centroid centroid, List<Record> records) {
|
||||
// if this cluster is empty, then we shouldn't move the centroid
|
||||
if (records == null || records.isEmpty()) {
|
||||
return centroid;
|
||||
}
|
||||
|
||||
// Since some records don't have all possible attributes, we initialize
|
||||
// average coordinates equal to current centroid coordinates
|
||||
Map<String, Double> average = centroid.getCoordinates();
|
||||
|
||||
// The average function works correctly if we clear all coordinates corresponding
|
||||
// to present record attributes
|
||||
records
|
||||
.stream()
|
||||
.flatMap(e -> e
|
||||
.getFeatures()
|
||||
.keySet()
|
||||
.stream())
|
||||
.forEach(k -> average.put(k, 0.0));
|
||||
|
||||
for (Record record : records) {
|
||||
record
|
||||
.getFeatures()
|
||||
.forEach((k, v) -> average.compute(k, (k1, currentValue) -> v + currentValue));
|
||||
}
|
||||
|
||||
average.forEach((k, v) -> average.put(k, v / records.size()));
|
||||
|
||||
return new Centroid(average);
|
||||
}
|
||||
|
||||
/**
|
||||
* Assigns a feature vector to the given centroid. If this is the first assignment for this centroid,
|
||||
* first we should create the list.
|
||||
*
|
||||
* @param clusters The current cluster configuration.
|
||||
* @param record The feature vector.
|
||||
* @param centroid The centroid.
|
||||
*/
|
||||
private static void assignToCluster(Map<Centroid, List<Record>> clusters, Record record, Centroid centroid) {
|
||||
clusters.compute(centroid, (key, list) -> {
|
||||
if (list == null) {
|
||||
list = new ArrayList<>();
|
||||
}
|
||||
|
||||
list.add(record);
|
||||
return list;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* With the help of the given distance calculator, iterates through centroids and finds the
|
||||
* nearest one to the given record.
|
||||
*
|
||||
* @param record The feature vector to find a centroid for.
|
||||
* @param centroids Collection of all centroids.
|
||||
* @param distance To calculate the distance between two items.
|
||||
* @return The nearest centroid to the given feature vector.
|
||||
*/
|
||||
private static Centroid nearestCentroid(Record record, List<Centroid> centroids, Distance distance) {
|
||||
double minimumDistance = Double.MAX_VALUE;
|
||||
Centroid nearest = null;
|
||||
|
||||
for (Centroid centroid : centroids) {
|
||||
double currentDistance = distance.calculate(record.getFeatures(), centroid.getCoordinates());
|
||||
|
||||
if (currentDistance < minimumDistance) {
|
||||
minimumDistance = currentDistance;
|
||||
nearest = centroid;
|
||||
}
|
||||
}
|
||||
|
||||
return nearest;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates k random centroids. Before kicking-off the centroid generation process,
|
||||
* first we calculate the possible value range for each attribute. Then when
|
||||
* we're going to generate the centroids, we generate random coordinates in
|
||||
* the [min, max] range for each attribute.
|
||||
*
|
||||
* @param records The dataset which helps to calculate the [min, max] range for
|
||||
* each attribute.
|
||||
* @param k Number of clusters.
|
||||
* @return Collections of randomly generated centroids.
|
||||
*/
|
||||
private static List<Centroid> randomCentroids(List<Record> records, int k) {
|
||||
List<Centroid> centroids = new ArrayList<>();
|
||||
Map<String, Double> maxs = new HashMap<>();
|
||||
Map<String, Double> mins = new HashMap<>();
|
||||
|
||||
for (Record record : records) {
|
||||
record
|
||||
.getFeatures()
|
||||
.forEach((key, value) -> {
|
||||
// compares the value with the current max and choose the bigger value between them
|
||||
maxs.compute(key, (k1, max) -> max == null || value > max ? value : max);
|
||||
|
||||
// compare the value with the current min and choose the smaller value between them
|
||||
mins.compute(key, (k1, min) -> min == null || value < min ? value : min);
|
||||
});
|
||||
}
|
||||
|
||||
Set<String> attributes = records
|
||||
.stream()
|
||||
.flatMap(e -> e
|
||||
.getFeatures()
|
||||
.keySet()
|
||||
.stream())
|
||||
.collect(toSet());
|
||||
for (int i = 0; i < k; i++) {
|
||||
Map<String, Double> coordinates = new HashMap<>();
|
||||
for (String attribute : attributes) {
|
||||
double max = maxs.get(attribute);
|
||||
double min = mins.get(attribute);
|
||||
coordinates.put(attribute, random.nextDouble() * (max - min) + min);
|
||||
}
|
||||
|
||||
centroids.add(new Centroid(coordinates));
|
||||
}
|
||||
|
||||
return centroids;
|
||||
}
|
||||
|
||||
private static void applyPreconditions(List<Record> records, int k, Distance distance, int maxIterations) {
|
||||
if (records == null || records.isEmpty()) {
|
||||
throw new IllegalArgumentException("The dataset can't be empty");
|
||||
}
|
||||
|
||||
if (k <= 1) {
|
||||
throw new IllegalArgumentException("It doesn't make sense to have less than or equal to 1 cluster");
|
||||
}
|
||||
|
||||
if (distance == null) {
|
||||
throw new IllegalArgumentException("The distance calculator is required");
|
||||
}
|
||||
|
||||
if (maxIterations <= 0) {
|
||||
throw new IllegalArgumentException("Max iterations should be a positive number");
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,144 @@
|
||||
package com.baeldung.algorithms.kmeans;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import okhttp3.OkHttpClient;
|
||||
import retrofit2.Retrofit;
|
||||
import retrofit2.converter.jackson.JacksonConverterFactory;
|
||||
|
||||
import static java.util.stream.Collectors.toSet;
|
||||
|
||||
public class LastFm {
|
||||
|
||||
private static OkHttpClient okHttp = new OkHttpClient.Builder()
|
||||
.addInterceptor(new LastFmService.Authenticator("put your API key here"))
|
||||
.build();
|
||||
|
||||
private static Retrofit retrofit = new Retrofit.Builder()
|
||||
.client(okHttp)
|
||||
.addConverterFactory(JacksonConverterFactory.create())
|
||||
.baseUrl("http://ws.audioscrobbler.com/")
|
||||
.build();
|
||||
|
||||
private static LastFmService lastFm = retrofit.create(LastFmService.class);
|
||||
|
||||
private static ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
List<String> artists = getTop100Artists();
|
||||
Set<String> tags = getTop100Tags();
|
||||
List<Record> records = datasetWithTaggedArtists(artists, tags);
|
||||
|
||||
Map<Centroid, List<Record>> clusters = KMeans.fit(records, 7, new EuclideanDistance(), 1000);
|
||||
// Print the cluster configuration
|
||||
clusters.forEach((key, value) -> {
|
||||
System.out.println("------------------------------ CLUSTER -----------------------------------");
|
||||
|
||||
System.out.println(sortedCentroid(key));
|
||||
String members = String.join(", ", value
|
||||
.stream()
|
||||
.map(Record::getDescription)
|
||||
.collect(toSet()));
|
||||
System.out.print(members);
|
||||
|
||||
System.out.println();
|
||||
System.out.println();
|
||||
});
|
||||
|
||||
Map<String, Object> json = convertToD3CompatibleMap(clusters);
|
||||
System.out.println(mapper.writeValueAsString(json));
|
||||
}
|
||||
|
||||
private static Map<String, Object> convertToD3CompatibleMap(Map<Centroid, List<Record>> clusters) {
|
||||
Map<String, Object> json = new HashMap<>();
|
||||
json.put("name", "Musicians");
|
||||
List<Map<String, Object>> children = new ArrayList<>();
|
||||
clusters.forEach((key, value) -> {
|
||||
Map<String, Object> child = new HashMap<>();
|
||||
child.put("name", dominantGenre(sortedCentroid(key)));
|
||||
List<Map<String, String>> nested = new ArrayList<>();
|
||||
for (Record record : value) {
|
||||
nested.add(Collections.singletonMap("name", record.getDescription()));
|
||||
}
|
||||
child.put("children", nested);
|
||||
|
||||
children.add(child);
|
||||
});
|
||||
json.put("children", children);
|
||||
return json;
|
||||
}
|
||||
|
||||
private static String dominantGenre(Centroid centroid) {
|
||||
return centroid
|
||||
.getCoordinates()
|
||||
.keySet()
|
||||
.stream()
|
||||
.limit(2)
|
||||
.collect(Collectors.joining(", "));
|
||||
}
|
||||
|
||||
private static Centroid sortedCentroid(Centroid key) {
|
||||
List<Map.Entry<String, Double>> entries = new ArrayList<>(key
|
||||
.getCoordinates()
|
||||
.entrySet());
|
||||
entries.sort((e1, e2) -> e2
|
||||
.getValue()
|
||||
.compareTo(e1.getValue()));
|
||||
|
||||
Map<String, Double> sorted = new LinkedHashMap<>();
|
||||
for (Map.Entry<String, Double> entry : entries) {
|
||||
sorted.put(entry.getKey(), entry.getValue());
|
||||
}
|
||||
|
||||
return new Centroid(sorted);
|
||||
}
|
||||
|
||||
private static List<Record> datasetWithTaggedArtists(List<String> artists, Set<String> topTags) throws IOException {
|
||||
List<Record> records = new ArrayList<>();
|
||||
for (String artist : artists) {
|
||||
Map<String, Double> tags = lastFm
|
||||
.topTagsFor(artist)
|
||||
.execute()
|
||||
.body()
|
||||
.all();
|
||||
|
||||
// Only keep popular tags.
|
||||
tags
|
||||
.entrySet()
|
||||
.removeIf(e -> !topTags.contains(e.getKey()));
|
||||
|
||||
records.add(new Record(artist, tags));
|
||||
}
|
||||
return records;
|
||||
}
|
||||
|
||||
private static Set<String> getTop100Tags() throws IOException {
|
||||
return lastFm
|
||||
.topTags()
|
||||
.execute()
|
||||
.body()
|
||||
.all();
|
||||
}
|
||||
|
||||
private static List<String> getTop100Artists() throws IOException {
|
||||
List<String> artists = new ArrayList<>();
|
||||
for (int i = 1; i <= 2; i++) {
|
||||
artists.addAll(lastFm
|
||||
.topArtists(i)
|
||||
.execute()
|
||||
.body()
|
||||
.all());
|
||||
}
|
||||
|
||||
return artists;
|
||||
}
|
||||
}
|
@ -0,0 +1,118 @@
|
||||
package com.baeldung.algorithms.kmeans;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonAutoDetect;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import okhttp3.HttpUrl;
|
||||
import okhttp3.Interceptor;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.Response;
|
||||
import retrofit2.Call;
|
||||
import retrofit2.http.GET;
|
||||
import retrofit2.http.Query;
|
||||
|
||||
import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.ANY;
|
||||
import static java.util.stream.Collectors.toList;
|
||||
|
||||
public interface LastFmService {
|
||||
|
||||
@GET("/2.0/?method=chart.gettopartists&format=json&limit=50")
|
||||
Call<Artists> topArtists(@Query("page") int page);
|
||||
|
||||
@GET("/2.0/?method=artist.gettoptags&format=json&limit=20&autocorrect=1")
|
||||
Call<Tags> topTagsFor(@Query("artist") String artist);
|
||||
|
||||
@GET("/2.0/?method=chart.gettoptags&format=json&limit=100")
|
||||
Call<TopTags> topTags();
|
||||
|
||||
/**
|
||||
* HTTP interceptor to intercept all HTTP requests and add the API key to them.
|
||||
*/
|
||||
class Authenticator implements Interceptor {
|
||||
|
||||
private final String apiKey;
|
||||
|
||||
Authenticator(String apiKey) {
|
||||
this.apiKey = apiKey;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Response intercept(Chain chain) throws IOException {
|
||||
HttpUrl url = chain
|
||||
.request()
|
||||
.url()
|
||||
.newBuilder()
|
||||
.addQueryParameter("api_key", apiKey)
|
||||
.build();
|
||||
Request request = chain
|
||||
.request()
|
||||
.newBuilder()
|
||||
.url(url)
|
||||
.build();
|
||||
|
||||
return chain.proceed(request);
|
||||
}
|
||||
}
|
||||
|
||||
@JsonAutoDetect(fieldVisibility = ANY)
|
||||
class TopTags {
|
||||
|
||||
private Map<String, Object> tags;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public Set<String> all() {
|
||||
List<Map<String, Object>> topTags = (List<Map<String, Object>>) tags.get("tag");
|
||||
return topTags
|
||||
.stream()
|
||||
.map(e -> ((String) e.get("name")))
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
}
|
||||
|
||||
@JsonAutoDetect(fieldVisibility = ANY)
|
||||
class Tags {
|
||||
|
||||
@JsonProperty("toptags") private Map<String, Object> topTags;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public Map<String, Double> all() {
|
||||
try {
|
||||
Map<String, Double> all = new HashMap<>();
|
||||
List<Map<String, Object>> tags = (List<Map<String, Object>>) topTags.get("tag");
|
||||
for (Map<String, Object> tag : tags) {
|
||||
all.put(((String) tag.get("name")), ((Integer) tag.get("count")).doubleValue());
|
||||
}
|
||||
|
||||
return all;
|
||||
} catch (Exception e) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@JsonAutoDetect(fieldVisibility = ANY)
|
||||
class Artists {
|
||||
|
||||
private Map<String, Object> artists;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public List<String> all() {
|
||||
try {
|
||||
List<Map<String, Object>> artists = (List<Map<String, Object>>) this.artists.get("artist");
|
||||
return artists
|
||||
.stream()
|
||||
.map(e -> ((String) e.get("name")))
|
||||
.collect(toList());
|
||||
} catch (Exception e) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,65 @@
|
||||
package com.baeldung.algorithms.kmeans;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Encapsulates all feature values for a few attributes. Optionally each record
|
||||
* can be described with the {@link #description} field.
|
||||
*/
|
||||
public class Record {
|
||||
|
||||
/**
|
||||
* The record description. For example, this can be the artist name for the famous musician
|
||||
* example.
|
||||
*/
|
||||
private final String description;
|
||||
|
||||
/**
|
||||
* Encapsulates all attributes and their corresponding values, i.e. features.
|
||||
*/
|
||||
private final Map<String, Double> features;
|
||||
|
||||
public Record(String description, Map<String, Double> features) {
|
||||
this.description = description;
|
||||
this.features = features;
|
||||
}
|
||||
|
||||
public Record(Map<String, Double> features) {
|
||||
this("", features);
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public Map<String, Double> getFeatures() {
|
||||
return features;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
String prefix = description == null || description
|
||||
.trim()
|
||||
.isEmpty() ? "Record" : description;
|
||||
|
||||
return prefix + ": " + features;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
Record record = (Record) o;
|
||||
return Objects.equals(getDescription(), record.getDescription()) && Objects.equals(getFeatures(), record.getFeatures());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(getDescription(), getFeatures());
|
||||
}
|
||||
}
|
@ -4,7 +4,7 @@ import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
public class PrintTriangleExamples {
|
||||
|
||||
public static String printARightAngledTriangle(int N) {
|
||||
public static String printARightTriangle(int N) {
|
||||
StringBuilder result = new StringBuilder();
|
||||
for (int r = 1; r <= N; r++) {
|
||||
for (int j = 1; j <= r; j++) {
|
||||
@ -29,6 +29,17 @@ public class PrintTriangleExamples {
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
public static String printAnIsoscelesTriangleUsingStringUtils(int N) {
|
||||
StringBuilder result = new StringBuilder();
|
||||
|
||||
for (int r = 1; r <= N; r++) {
|
||||
result.append(StringUtils.repeat(' ', N - r));
|
||||
result.append(StringUtils.repeat('*', 2 * r - 1));
|
||||
result.append(System.lineSeparator());
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
public static String printAnIsoscelesTriangleUsingSubstring(int N) {
|
||||
StringBuilder result = new StringBuilder();
|
||||
String helperString = StringUtils.repeat(' ', N - 1) + StringUtils.repeat('*', N * 2 - 1);
|
||||
@ -41,8 +52,9 @@ public class PrintTriangleExamples {
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.out.println(printARightAngledTriangle(5));
|
||||
System.out.println(printARightTriangle(5));
|
||||
System.out.println(printAnIsoscelesTriangle(5));
|
||||
System.out.println(printAnIsoscelesTriangleUsingStringUtils(5));
|
||||
System.out.println(printAnIsoscelesTriangleUsingSubstring(5));
|
||||
}
|
||||
|
||||
|
3384
algorithms-miscellaneous-3/src/main/resources/kmeans/artists.json
Normal file
3384
algorithms-miscellaneous-3/src/main/resources/kmeans/artists.json
Normal file
File diff suppressed because it is too large
Load Diff
490
algorithms-miscellaneous-3/src/main/resources/kmeans/lastfm.json
Normal file
490
algorithms-miscellaneous-3/src/main/resources/kmeans/lastfm.json
Normal file
@ -0,0 +1,490 @@
|
||||
{
|
||||
"children": [
|
||||
{
|
||||
"children": [
|
||||
{
|
||||
"name": "Radiohead"
|
||||
},
|
||||
{
|
||||
"name": "Red Hot Chili Peppers"
|
||||
},
|
||||
{
|
||||
"name": "Coldplay"
|
||||
},
|
||||
{
|
||||
"name": "Nirvana"
|
||||
},
|
||||
{
|
||||
"name": "Panic! at the Disco"
|
||||
},
|
||||
{
|
||||
"name": "The Cure"
|
||||
},
|
||||
{
|
||||
"name": "Linkin Park"
|
||||
},
|
||||
{
|
||||
"name": "Radiohead"
|
||||
},
|
||||
{
|
||||
"name": "Red Hot Chili Peppers"
|
||||
},
|
||||
{
|
||||
"name": "Coldplay"
|
||||
},
|
||||
{
|
||||
"name": "Nirvana"
|
||||
},
|
||||
{
|
||||
"name": "Panic! at the Disco"
|
||||
},
|
||||
{
|
||||
"name": "The Cure"
|
||||
},
|
||||
{
|
||||
"name": "Linkin Park"
|
||||
},
|
||||
{
|
||||
"name": "Muse"
|
||||
},
|
||||
{
|
||||
"name": "Maroon 5"
|
||||
},
|
||||
{
|
||||
"name": "Foo Fighters"
|
||||
},
|
||||
{
|
||||
"name": "Paramore"
|
||||
},
|
||||
{
|
||||
"name": "Oasis"
|
||||
},
|
||||
{
|
||||
"name": "Fall Out Boy"
|
||||
},
|
||||
{
|
||||
"name": "OneRepublic"
|
||||
},
|
||||
{
|
||||
"name": "Weezer"
|
||||
},
|
||||
{
|
||||
"name": "System of a Down"
|
||||
},
|
||||
{
|
||||
"name": "The White Stripes"
|
||||
}
|
||||
],
|
||||
"name": "rock, alternative"
|
||||
},
|
||||
{
|
||||
"children": [
|
||||
{
|
||||
"name": "Lil Nas X"
|
||||
},
|
||||
{
|
||||
"name": "Post Malone"
|
||||
},
|
||||
{
|
||||
"name": "Drake"
|
||||
},
|
||||
{
|
||||
"name": "Kanye West"
|
||||
},
|
||||
{
|
||||
"name": "Kendrick Lamar"
|
||||
},
|
||||
{
|
||||
"name": "Tyler, the Creator"
|
||||
},
|
||||
{
|
||||
"name": "Eminem"
|
||||
},
|
||||
{
|
||||
"name": "Childish Gambino"
|
||||
},
|
||||
{
|
||||
"name": "Frank Ocean"
|
||||
},
|
||||
{
|
||||
"name": "Lil Nas X"
|
||||
},
|
||||
{
|
||||
"name": "Post Malone"
|
||||
},
|
||||
{
|
||||
"name": "Drake"
|
||||
},
|
||||
{
|
||||
"name": "Kanye West"
|
||||
},
|
||||
{
|
||||
"name": "Kendrick Lamar"
|
||||
},
|
||||
{
|
||||
"name": "Tyler, the Creator"
|
||||
},
|
||||
{
|
||||
"name": "Eminem"
|
||||
},
|
||||
{
|
||||
"name": "Childish Gambino"
|
||||
},
|
||||
{
|
||||
"name": "Frank Ocean"
|
||||
},
|
||||
{
|
||||
"name": "Lizzo"
|
||||
},
|
||||
{
|
||||
"name": "Travi$ Scott"
|
||||
},
|
||||
{
|
||||
"name": "A$AP Rocky"
|
||||
},
|
||||
{
|
||||
"name": "Nicki Minaj"
|
||||
},
|
||||
{
|
||||
"name": "xxxtentacion"
|
||||
}
|
||||
],
|
||||
"name": "Hip-Hop, rap"
|
||||
},
|
||||
{
|
||||
"children": [
|
||||
{
|
||||
"name": "Arctic Monkeys"
|
||||
},
|
||||
{
|
||||
"name": "Imagine Dragons"
|
||||
},
|
||||
{
|
||||
"name": "The Killers"
|
||||
},
|
||||
{
|
||||
"name": "Gorillaz"
|
||||
},
|
||||
{
|
||||
"name": "The Black Keys"
|
||||
},
|
||||
{
|
||||
"name": "Arctic Monkeys"
|
||||
},
|
||||
{
|
||||
"name": "Imagine Dragons"
|
||||
},
|
||||
{
|
||||
"name": "The Killers"
|
||||
},
|
||||
{
|
||||
"name": "Gorillaz"
|
||||
},
|
||||
{
|
||||
"name": "The Black Keys"
|
||||
},
|
||||
{
|
||||
"name": "Twenty One Pilots"
|
||||
},
|
||||
{
|
||||
"name": "Ellie Goulding"
|
||||
},
|
||||
{
|
||||
"name": "Florence + the Machine"
|
||||
},
|
||||
{
|
||||
"name": "Vampire Weekend"
|
||||
},
|
||||
{
|
||||
"name": "The Smiths"
|
||||
},
|
||||
{
|
||||
"name": "The Strokes"
|
||||
},
|
||||
{
|
||||
"name": "MGMT"
|
||||
},
|
||||
{
|
||||
"name": "Foster the People"
|
||||
},
|
||||
{
|
||||
"name": "Two Door Cinema Club"
|
||||
},
|
||||
{
|
||||
"name": "Cage the Elephant"
|
||||
},
|
||||
{
|
||||
"name": "Arcade Fire"
|
||||
},
|
||||
{
|
||||
"name": "The 1975"
|
||||
}
|
||||
],
|
||||
"name": "indie, alternative"
|
||||
},
|
||||
{
|
||||
"children": [
|
||||
{
|
||||
"name": "Ed Sheeran"
|
||||
},
|
||||
{
|
||||
"name": "Tame Impala"
|
||||
},
|
||||
{
|
||||
"name": "Ed Sheeran"
|
||||
},
|
||||
{
|
||||
"name": "Tame Impala"
|
||||
},
|
||||
{
|
||||
"name": "Green Day"
|
||||
},
|
||||
{
|
||||
"name": "Metallica"
|
||||
},
|
||||
{
|
||||
"name": "blink-182"
|
||||
},
|
||||
{
|
||||
"name": "Bon Iver"
|
||||
},
|
||||
{
|
||||
"name": "The Clash"
|
||||
}
|
||||
],
|
||||
"name": "rock, punk rock"
|
||||
},
|
||||
{
|
||||
"children": [
|
||||
{
|
||||
"name": "Calvin Harris"
|
||||
},
|
||||
{
|
||||
"name": "The Weeknd"
|
||||
},
|
||||
{
|
||||
"name": "The Chainsmokers"
|
||||
},
|
||||
{
|
||||
"name": "Daft Punk"
|
||||
},
|
||||
{
|
||||
"name": "Marshmello"
|
||||
},
|
||||
{
|
||||
"name": "David Guetta"
|
||||
},
|
||||
{
|
||||
"name": "Calvin Harris"
|
||||
},
|
||||
{
|
||||
"name": "The Weeknd"
|
||||
},
|
||||
{
|
||||
"name": "The Chainsmokers"
|
||||
},
|
||||
{
|
||||
"name": "Daft Punk"
|
||||
},
|
||||
{
|
||||
"name": "Marshmello"
|
||||
},
|
||||
{
|
||||
"name": "David Guetta"
|
||||
},
|
||||
{
|
||||
"name": "Avicii"
|
||||
},
|
||||
{
|
||||
"name": "Kygo"
|
||||
},
|
||||
{
|
||||
"name": "Martin Garrix"
|
||||
},
|
||||
{
|
||||
"name": "Major Lazer"
|
||||
},
|
||||
{
|
||||
"name": "Depeche Mode"
|
||||
}
|
||||
],
|
||||
"name": "electronic, dance"
|
||||
},
|
||||
{
|
||||
"children": [
|
||||
{
|
||||
"name": "Queen"
|
||||
},
|
||||
{
|
||||
"name": "The Beatles"
|
||||
},
|
||||
{
|
||||
"name": "David Bowie"
|
||||
},
|
||||
{
|
||||
"name": "Fleetwood Mac"
|
||||
},
|
||||
{
|
||||
"name": "Pink Floyd"
|
||||
},
|
||||
{
|
||||
"name": "The Rolling Stones"
|
||||
},
|
||||
{
|
||||
"name": "Led Zeppelin"
|
||||
},
|
||||
{
|
||||
"name": "Queen"
|
||||
},
|
||||
{
|
||||
"name": "The Beatles"
|
||||
},
|
||||
{
|
||||
"name": "David Bowie"
|
||||
},
|
||||
{
|
||||
"name": "Fleetwood Mac"
|
||||
},
|
||||
{
|
||||
"name": "Pink Floyd"
|
||||
},
|
||||
{
|
||||
"name": "The Rolling Stones"
|
||||
},
|
||||
{
|
||||
"name": "Led Zeppelin"
|
||||
},
|
||||
{
|
||||
"name": "Elton John"
|
||||
}
|
||||
],
|
||||
"name": "classic rock, rock"
|
||||
},
|
||||
{
|
||||
"children": [
|
||||
{
|
||||
"name": "Billie Eilish"
|
||||
},
|
||||
{
|
||||
"name": "Ariana Grande"
|
||||
},
|
||||
{
|
||||
"name": "Taylor Swift"
|
||||
},
|
||||
{
|
||||
"name": "Beyoncé"
|
||||
},
|
||||
{
|
||||
"name": "Shawn Mendes"
|
||||
},
|
||||
{
|
||||
"name": "Rihanna"
|
||||
},
|
||||
{
|
||||
"name": "Lana Del Rey"
|
||||
},
|
||||
{
|
||||
"name": "Katy Perry"
|
||||
},
|
||||
{
|
||||
"name": "Lady Gaga"
|
||||
},
|
||||
{
|
||||
"name": "Miley Cyrus"
|
||||
},
|
||||
{
|
||||
"name": "Mark Ronson"
|
||||
},
|
||||
{
|
||||
"name": "Madonna"
|
||||
},
|
||||
{
|
||||
"name": "Lorde"
|
||||
},
|
||||
{
|
||||
"name": "Khalid"
|
||||
},
|
||||
{
|
||||
"name": "Billie Eilish"
|
||||
},
|
||||
{
|
||||
"name": "Ariana Grande"
|
||||
},
|
||||
{
|
||||
"name": "Taylor Swift"
|
||||
},
|
||||
{
|
||||
"name": "Beyoncé"
|
||||
},
|
||||
{
|
||||
"name": "Shawn Mendes"
|
||||
},
|
||||
{
|
||||
"name": "Rihanna"
|
||||
},
|
||||
{
|
||||
"name": "Lana Del Rey"
|
||||
},
|
||||
{
|
||||
"name": "Katy Perry"
|
||||
},
|
||||
{
|
||||
"name": "Lady Gaga"
|
||||
},
|
||||
{
|
||||
"name": "Miley Cyrus"
|
||||
},
|
||||
{
|
||||
"name": "Mark Ronson"
|
||||
},
|
||||
{
|
||||
"name": "Madonna"
|
||||
},
|
||||
{
|
||||
"name": "Lorde"
|
||||
},
|
||||
{
|
||||
"name": "Khalid"
|
||||
},
|
||||
{
|
||||
"name": "Sia"
|
||||
},
|
||||
{
|
||||
"name": "Sam Smith"
|
||||
},
|
||||
{
|
||||
"name": "Halsey"
|
||||
},
|
||||
{
|
||||
"name": "Michael Jackson"
|
||||
},
|
||||
{
|
||||
"name": "Charli XCX"
|
||||
},
|
||||
{
|
||||
"name": "Britney Spears"
|
||||
},
|
||||
{
|
||||
"name": "Dua Lipa"
|
||||
},
|
||||
{
|
||||
"name": "Jonas Brothers"
|
||||
},
|
||||
{
|
||||
"name": "Bruno Mars"
|
||||
},
|
||||
{
|
||||
"name": "Carly Rae Jepsen"
|
||||
},
|
||||
{
|
||||
"name": "P!nk"
|
||||
},
|
||||
{
|
||||
"name": "Adele"
|
||||
}
|
||||
],
|
||||
"name": "pop, female vocalists"
|
||||
}
|
||||
],
|
||||
"name": "Musicians"
|
||||
}
|
@ -0,0 +1,68 @@
|
||||
<!DOCTYPE html>
|
||||
<meta charset="utf-8">
|
||||
<style>
|
||||
.node circle {
|
||||
fill: #fff;
|
||||
stroke: steelblue;
|
||||
stroke-width: 1.5px;
|
||||
}
|
||||
|
||||
.node {
|
||||
font: 10px sans-serif;
|
||||
}
|
||||
|
||||
.link {
|
||||
fill: none;
|
||||
stroke: #ccc;
|
||||
stroke-width: 1.5px;
|
||||
}
|
||||
</style>
|
||||
<body>
|
||||
<script src="http://d3js.org/d3.v3.min.js"></script>
|
||||
<script>
|
||||
var diameter = 1100;
|
||||
var tree = d3.layout.tree()
|
||||
.size([360, diameter / 2 - 300])
|
||||
.separation(function (a, b) {
|
||||
return (a.parent == b.parent ? 1 : 2) / a.depth;
|
||||
});
|
||||
var diagonal = d3.svg.diagonal.radial()
|
||||
.projection(function (d) {
|
||||
return [d.y, d.x / 180 * Math.PI];
|
||||
});
|
||||
var svg = d3.select("body").append("svg")
|
||||
.attr("width", diameter)
|
||||
.attr("height", diameter - 150)
|
||||
.append("g")
|
||||
.attr("transform", "translate(" + diameter / 2 + "," + diameter / 2 + ")");
|
||||
d3.json("lastfm.json", function (error, root) {
|
||||
var nodes = tree.nodes(root),
|
||||
links = tree.links(nodes);
|
||||
var link = svg.selectAll(".link")
|
||||
.data(links)
|
||||
.enter().append("path")
|
||||
.attr("class", "link")
|
||||
.attr("d", diagonal);
|
||||
var node = svg.selectAll(".node")
|
||||
.data(nodes)
|
||||
.enter().append("g")
|
||||
.attr("class", "node")
|
||||
.attr("transform", function (d) {
|
||||
return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")";
|
||||
})
|
||||
node.append("circle")
|
||||
.attr("r", 4.5);
|
||||
node.append("text")
|
||||
.attr("dy", ".31em")
|
||||
.attr("text-anchor", function (d) {
|
||||
return d.x < 180 ? "start" : "end";
|
||||
})
|
||||
.attr("transform", function (d) {
|
||||
return d.x < 180 ? "translate(8)" : "rotate(180)translate(-8)";
|
||||
})
|
||||
.text(function (d) {
|
||||
return d.name;
|
||||
});
|
||||
});
|
||||
d3.select(self.frameElement).style("height", diameter - 150 + "px");
|
||||
</script>
|
@ -0,0 +1,29 @@
|
||||
package com.baeldung.algorithms.interpolationsearch;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class InterpolationSearchUnitTest {
|
||||
|
||||
private int[] myData;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
myData = new int[]{13,21,34,55,69,73,84,101};
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSortedArray_whenLookingFor84_thenReturn6() {
|
||||
int pos = InterpolationSearch.interpolationSearch(myData, 84);
|
||||
assertEquals(6, pos);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSortedArray_whenLookingFor19_thenReturnMinusOne() {
|
||||
int pos = InterpolationSearch.interpolationSearch(myData, 19);
|
||||
assertEquals(-1, pos);
|
||||
}
|
||||
|
||||
}
|
@ -9,9 +9,9 @@ import static org.junit.Assert.assertEquals;
|
||||
|
||||
@RunWith(JUnitParamsRunner.class)
|
||||
public class PrintTriangleExamplesUnitTest {
|
||||
|
||||
private static Object[][] rightAngledTriangles() {
|
||||
String expected0 = "";
|
||||
|
||||
private static Object[][] rightTriangles() {
|
||||
String expected0 = "";
|
||||
|
||||
String expected2 = "*" + System.lineSeparator()
|
||||
+ "**" + System.lineSeparator();
|
||||
@ -39,9 +39,9 @@ public class PrintTriangleExamplesUnitTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@Parameters(method = "rightAngledTriangles")
|
||||
public void whenPrintARightAngledTriangleIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) {
|
||||
String actual = PrintTriangleExamples.printARightAngledTriangle(nrOfRows);
|
||||
@Parameters(method = "rightTriangles")
|
||||
public void whenPrintARightTriangleIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) {
|
||||
String actual = PrintTriangleExamples.printARightTriangle(nrOfRows);
|
||||
|
||||
assertEquals(expected, actual);
|
||||
}
|
||||
@ -81,6 +81,14 @@ public class PrintTriangleExamplesUnitTest {
|
||||
|
||||
assertEquals(expected, actual);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Parameters(method = "isoscelesTriangles")
|
||||
public void whenPrintAnIsoscelesTriangleUsingStringUtilsIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) {
|
||||
String actual = PrintTriangleExamples.printAnIsoscelesTriangleUsingStringUtils(nrOfRows);
|
||||
|
||||
assertEquals(expected, actual);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Parameters(method = "isoscelesTriangles")
|
||||
|
@ -5,3 +5,4 @@
|
||||
- [Quicksort Algorithm Implementation in Java](https://www.baeldung.com/java-quicksort)
|
||||
- [Insertion Sort in Java](https://www.baeldung.com/java-insertion-sort)
|
||||
- [Heap Sort in Java](https://www.baeldung.com/java-heap-sort)
|
||||
- [Shell Sort in Java](https://www.baeldung.com/java-shell-sort)
|
||||
|
@ -8,3 +8,4 @@
|
||||
- [Pattern Matching in Strings in Groovy](https://www.baeldung.com/groovy-pattern-matching)
|
||||
- [Working with XML in Groovy](https://www.baeldung.com/groovy-xml)
|
||||
- [Integrating Groovy into Java Applications](https://www.baeldung.com/groovy-java-applications)
|
||||
- [Concatenate Strings with Groovy](https://www.baeldung.com/groovy-concatenate-strings)
|
||||
|
@ -1,3 +1,5 @@
|
||||
## Relevant Articles
|
||||
|
||||
- [Extending an Array’s Length](https://www.baeldung.com/java-array-add-element-at-the-end)
|
||||
- [Checking If an Array Is Sorted in Java](https://www.baeldung.com/java-check-sorted-array)
|
||||
- [Looping Diagonally Through a 2d Java Array](https://www.baeldung.com/java-loop-diagonal-array)
|
||||
|
@ -0,0 +1,11 @@
|
||||
package com.baeldung.concurrent.mutex;
|
||||
|
||||
public class SequenceGenerator {
|
||||
private int currentValue = 0;
|
||||
|
||||
public int getNextSequence() throws InterruptedException {
|
||||
currentValue = currentValue + 1;
|
||||
Thread.sleep(500);
|
||||
return currentValue;
|
||||
}
|
||||
}
|
@ -0,0 +1,18 @@
|
||||
package com.baeldung.concurrent.mutex;
|
||||
|
||||
import com.google.common.util.concurrent.Monitor;
|
||||
|
||||
public class SequenceGeneratorUsingMonitor extends SequenceGenerator {
|
||||
|
||||
private Monitor monitor = new Monitor();
|
||||
|
||||
@Override
|
||||
public int getNextSequence() throws InterruptedException {
|
||||
monitor.enter();
|
||||
try {
|
||||
return super.getNextSequence();
|
||||
} finally {
|
||||
monitor.leave();
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,18 @@
|
||||
package com.baeldung.concurrent.mutex;
|
||||
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
public class SequenceGeneratorUsingReentrantLock extends SequenceGenerator {
|
||||
|
||||
private ReentrantLock mutex = new ReentrantLock();
|
||||
|
||||
@Override
|
||||
public int getNextSequence() throws InterruptedException {
|
||||
try {
|
||||
mutex.lock();
|
||||
return super.getNextSequence();
|
||||
} finally {
|
||||
mutex.unlock();
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,18 @@
|
||||
package com.baeldung.concurrent.mutex;
|
||||
|
||||
import java.util.concurrent.Semaphore;
|
||||
|
||||
public class SequenceGeneratorUsingSemaphore extends SequenceGenerator {
|
||||
|
||||
private Semaphore mutex = new Semaphore(1);
|
||||
|
||||
@Override
|
||||
public int getNextSequence() throws InterruptedException {
|
||||
try {
|
||||
mutex.acquire();
|
||||
return super.getNextSequence();
|
||||
} finally {
|
||||
mutex.release();
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,12 @@
|
||||
package com.baeldung.concurrent.mutex;
|
||||
|
||||
public class SequenceGeneratorUsingSynchronizedBlock extends SequenceGenerator {
|
||||
|
||||
@Override
|
||||
public int getNextSequence() throws InterruptedException {
|
||||
synchronized (this) {
|
||||
return super.getNextSequence();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,10 @@
|
||||
package com.baeldung.concurrent.mutex;
|
||||
|
||||
public class SequenceGeneratorUsingSynchronizedMethod extends SequenceGenerator {
|
||||
|
||||
@Override
|
||||
public synchronized int getNextSequence() throws InterruptedException {
|
||||
return super.getNextSequence();
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,81 @@
|
||||
package com.baeldung.concurrent.mutex;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.concurrent.mutex.SequenceGenerator;
|
||||
import com.baeldung.concurrent.mutex.SequenceGeneratorUsingMonitor;
|
||||
import com.baeldung.concurrent.mutex.SequenceGeneratorUsingReentrantLock;
|
||||
import com.baeldung.concurrent.mutex.SequenceGeneratorUsingSemaphore;
|
||||
import com.baeldung.concurrent.mutex.SequenceGeneratorUsingSynchronizedBlock;
|
||||
import com.baeldung.concurrent.mutex.SequenceGeneratorUsingSynchronizedMethod;
|
||||
|
||||
public class MutexUnitTest {
|
||||
|
||||
private final int RANGE = 30;
|
||||
|
||||
@Test
|
||||
public void givenUnsafeSequenceGenerator_whenRaceCondition_thenUnexpectedBehavior() throws Exception {
|
||||
Set<Integer> uniqueSequences = getASetOFUniqueSequences(new SequenceGenerator());
|
||||
Assert.assertNotEquals(RANGE, uniqueSequences.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSequenceGeneratorUsingSynchronizedMethod_whenRaceCondition_thenSuccess() throws Exception {
|
||||
Set<Integer> uniqueSequences = getASetOFUniqueSequences(new SequenceGeneratorUsingSynchronizedMethod());
|
||||
Assert.assertEquals(RANGE, uniqueSequences.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSequenceGeneratorUsingSynchronizedBlock_whenRaceCondition_thenSuccess() throws Exception {
|
||||
Set<Integer> uniqueSequences = getASetOFUniqueSequences(new SequenceGeneratorUsingSynchronizedBlock());
|
||||
Assert.assertEquals(RANGE, uniqueSequences.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSequenceGeneratorUsingReentrantLock_whenRaceCondition_thenSuccess() throws Exception {
|
||||
Set<Integer> uniqueSequences = getASetOFUniqueSequences(new SequenceGeneratorUsingReentrantLock());
|
||||
Assert.assertEquals(RANGE, uniqueSequences.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSequenceGeneratorUsingSemaphore_whenRaceCondition_thenSuccess() throws Exception {
|
||||
Set<Integer> uniqueSequences = getASetOFUniqueSequences(new SequenceGeneratorUsingSemaphore());
|
||||
Assert.assertEquals(RANGE, uniqueSequences.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSequenceGeneratorUsingMonitor_whenRaceCondition_thenSuccess() throws Exception {
|
||||
Set<Integer> uniqueSequences = getASetOFUniqueSequences(new SequenceGeneratorUsingMonitor());
|
||||
Assert.assertEquals(RANGE, uniqueSequences.size());
|
||||
}
|
||||
|
||||
private Set<Integer> getASetOFUniqueSequences(SequenceGenerator generator) throws Exception {
|
||||
ExecutorService executor = Executors.newFixedThreadPool(3);
|
||||
Set<Integer> uniqueSequences = new HashSet<>();
|
||||
List<Future<Integer>> futures = new ArrayList<>();
|
||||
|
||||
for (int i = 0; i < RANGE; i++) {
|
||||
futures.add(executor.submit(generator::getNextSequence));
|
||||
}
|
||||
|
||||
for (Future<Integer> future : futures) {
|
||||
uniqueSequences.add(future.get());
|
||||
}
|
||||
|
||||
executor.awaitTermination(15, TimeUnit.SECONDS);
|
||||
executor.shutdown();
|
||||
|
||||
return uniqueSequences;
|
||||
}
|
||||
|
||||
}
|
65
core-java-modules/core-java-jndi/pom.xml
Normal file
65
core-java-modules/core-java-jndi/pom.xml
Normal file
@ -0,0 +1,65 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.baeldung.jndi</groupId>
|
||||
<artifactId>core-java-jndi</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>5.5.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-core</artifactId>
|
||||
<version>5.0.9.RELEASE</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
<version>5.0.9.RELEASE</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-jdbc</artifactId>
|
||||
<version>5.0.9.RELEASE</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
<version>5.0.9.RELEASE</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>1.4.199</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
@ -0,0 +1,60 @@
|
||||
package com.baeldung.jndi;
|
||||
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.jdbc.datasource.DriverManagerDataSource;
|
||||
import org.springframework.jndi.JndiTemplate;
|
||||
import org.springframework.mock.jndi.SimpleNamingContextBuilder;
|
||||
|
||||
import javax.naming.*;
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import java.util.Enumeration;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class JndiUnitTest {
|
||||
|
||||
private static InitialContext ctx;
|
||||
private static DriverManagerDataSource ds;
|
||||
|
||||
@BeforeAll
|
||||
static void setUp() throws Exception {
|
||||
SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
|
||||
ds = new DriverManagerDataSource("jdbc:h2:mem:mydb");
|
||||
builder.activate();
|
||||
|
||||
JndiTemplate jndiTemplate = new JndiTemplate();
|
||||
ctx = (InitialContext) jndiTemplate.getContext();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenACompositeName_whenAddingAnElement_thenNameIncludesIt() throws Exception {
|
||||
Name objectName = new CompositeName("java:comp/env/jdbc");
|
||||
|
||||
Enumeration<String> elements = objectName.getAll();
|
||||
while(elements.hasMoreElements()) {
|
||||
System.out.println(elements.nextElement());
|
||||
}
|
||||
|
||||
objectName.add("example");
|
||||
|
||||
assertEquals("env", objectName.get(1));
|
||||
assertEquals("example", objectName.get(objectName.size() - 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenADataSource_whenAddingDriver_thenBind() throws Exception {
|
||||
ds.setDriverClassName("org.h2.Driver");
|
||||
ctx.bind("java:comp/env/jdbc/datasource", ds);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenContext_whenLookupByName_thenValidDataSource() throws Exception {
|
||||
DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/datasource");
|
||||
|
||||
assertNotNull(ds);
|
||||
assertNotNull(ds.getConnection());
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,42 @@
|
||||
package com.baeldung.jndi.exceptions;
|
||||
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
import org.springframework.jndi.JndiTemplate;
|
||||
import org.springframework.mock.jndi.SimpleNamingContextBuilder;
|
||||
|
||||
import javax.naming.InitialContext;
|
||||
import javax.naming.NameNotFoundException;
|
||||
import javax.naming.NoInitialContextException;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
public class JndiExceptionsUnitTest {
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void givenNoContext_whenLookupObject_thenThrowNoInitialContext() {
|
||||
assertThrows(NoInitialContextException.class, () -> {
|
||||
JndiTemplate jndiTemplate = new JndiTemplate();
|
||||
InitialContext ctx = (InitialContext) jndiTemplate.getContext();
|
||||
ctx.lookup("java:comp/env/jdbc/datasource");
|
||||
}).printStackTrace();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void givenEmptyContext_whenLookupNotBounds_thenThrowNameNotFound() {
|
||||
assertThrows(NameNotFoundException.class, () -> {
|
||||
SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
|
||||
builder.activate();
|
||||
|
||||
JndiTemplate jndiTemplate = new JndiTemplate();
|
||||
InitialContext ctx = (InitialContext) jndiTemplate.getContext();
|
||||
ctx.lookup("badJndiName");
|
||||
}).printStackTrace();
|
||||
}
|
||||
|
||||
}
|
3
core-java-modules/core-java-networking-2/README.md
Normal file
3
core-java-modules/core-java-networking-2/README.md
Normal file
@ -0,0 +1,3 @@
|
||||
### Relevant Articles
|
||||
|
||||
- [Checking if a URL Exists in Java](https://www.baeldung.com/java-check-url-exists)
|
@ -7,4 +7,4 @@ This module uses Java 9, so make sure to have the JDK 9 installed to run it.
|
||||
- [Java 9 Process API Improvements](http://www.baeldung.com/java-9-process-api)
|
||||
- [Guide to java.lang.Process API](https://www.baeldung.com/java-process-api)
|
||||
- [Guide to java.lang.ProcessBuilder API](https://www.baeldung.com/java-lang-processbuilder-api)
|
||||
|
||||
- [Get the Current Working Directory in Java](https://www.baeldung.com/java-current-directory)
|
||||
|
@ -0,0 +1,23 @@
|
||||
package com.baeldung.matrices;
|
||||
|
||||
public class HomemadeMatrix {
|
||||
public static double[][] multiplyMatrices(double[][] firstMatrix, double[][] secondMatrix) {
|
||||
double[][] result = new double[firstMatrix.length][secondMatrix[0].length];
|
||||
|
||||
for (int row = 0; row < result.length; row++) {
|
||||
for (int col = 0; col < result[row].length; col++) {
|
||||
result[row][col] = multiplyMatricesCell(firstMatrix, secondMatrix, row, col);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static double multiplyMatricesCell(double[][] firstMatrix, double[][] secondMatrix, int row, int col) {
|
||||
double cell = 0;
|
||||
for (int i = 0; i < secondMatrix.length; i++) {
|
||||
cell += firstMatrix[row][i] * secondMatrix[i][col];
|
||||
}
|
||||
return cell;
|
||||
}
|
||||
}
|
@ -0,0 +1,31 @@
|
||||
package com.baeldung.algorithms.logarithm;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class LogarithmUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenLog10_shouldReturnValidResults() {
|
||||
assertEquals(Math.log10(100), 2);
|
||||
assertEquals(Math.log10(1000), 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLogE_shouldReturnValidResults() {
|
||||
assertEquals(Math.log(Math.E), 1);
|
||||
assertEquals(Math.log(10), 2.30258, 0.00001);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCustomLog_shouldReturnValidResults() {
|
||||
assertEquals(customLog(2, 256), 8);
|
||||
assertEquals(customLog(10, 100), 2);
|
||||
}
|
||||
|
||||
private static double customLog(double base, double logNumber) {
|
||||
return Math.log(logNumber) / Math.log(base);
|
||||
}
|
||||
|
||||
}
|
@ -1,9 +1,84 @@
|
||||
package com.baeldung.matrices;
|
||||
|
||||
import cern.colt.matrix.DoubleFactory2D;
|
||||
import cern.colt.matrix.DoubleMatrix2D;
|
||||
import cern.colt.matrix.linalg.Algebra;
|
||||
import org.apache.commons.math3.linear.Array2DRowRealMatrix;
|
||||
import org.apache.commons.math3.linear.RealMatrix;
|
||||
import org.ejml.simple.SimpleMatrix;
|
||||
import org.la4j.Matrix;
|
||||
import org.la4j.matrix.dense.Basic2DMatrix;
|
||||
import org.nd4j.linalg.api.ndarray.INDArray;
|
||||
import org.nd4j.linalg.factory.Nd4j;
|
||||
import org.openjdk.jmh.annotations.Benchmark;
|
||||
import org.openjdk.jmh.annotations.Mode;
|
||||
import org.openjdk.jmh.runner.Runner;
|
||||
import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class MatrixMultiplicationBenchmarking {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
org.openjdk.jmh.Main.main(args);
|
||||
Options opt = new OptionsBuilder()
|
||||
.include(MatrixMultiplicationBenchmarking.class.getSimpleName())
|
||||
.mode(Mode.AverageTime)
|
||||
.forks(2)
|
||||
.warmupIterations(5)
|
||||
.measurementIterations(10)
|
||||
.timeUnit(TimeUnit.MICROSECONDS)
|
||||
.build();
|
||||
|
||||
new Runner(opt).run();
|
||||
}
|
||||
|
||||
}
|
||||
@Benchmark
|
||||
public Object homemadeMatrixMultiplication(MatrixProvider matrixProvider) {
|
||||
return HomemadeMatrix.multiplyMatrices(matrixProvider.getFirstMatrix(), matrixProvider.getSecondMatrix());
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public Object ejmlMatrixMultiplication(MatrixProvider matrixProvider) {
|
||||
SimpleMatrix firstMatrix = new SimpleMatrix(matrixProvider.getFirstMatrix());
|
||||
SimpleMatrix secondMatrix = new SimpleMatrix(matrixProvider.getSecondMatrix());
|
||||
|
||||
return firstMatrix.mult(secondMatrix);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public Object apacheCommonsMatrixMultiplication(MatrixProvider matrixProvider) {
|
||||
RealMatrix firstMatrix = new Array2DRowRealMatrix(matrixProvider.getFirstMatrix());
|
||||
RealMatrix secondMatrix = new Array2DRowRealMatrix(matrixProvider.getSecondMatrix());
|
||||
|
||||
return firstMatrix.multiply(secondMatrix);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public Object la4jMatrixMultiplication(MatrixProvider matrixProvider) {
|
||||
Matrix firstMatrix = new Basic2DMatrix(matrixProvider.getFirstMatrix());
|
||||
Matrix secondMatrix = new Basic2DMatrix(matrixProvider.getSecondMatrix());
|
||||
|
||||
return firstMatrix.multiply(secondMatrix);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public Object nd4jMatrixMultiplication(MatrixProvider matrixProvider) {
|
||||
INDArray firstMatrix = Nd4j.create(matrixProvider.getFirstMatrix());
|
||||
INDArray secondMatrix = Nd4j.create(matrixProvider.getSecondMatrix());
|
||||
|
||||
return firstMatrix.mmul(secondMatrix);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public Object coltMatrixMultiplication(MatrixProvider matrixProvider) {
|
||||
DoubleFactory2D doubleFactory2D = DoubleFactory2D.dense;
|
||||
|
||||
DoubleMatrix2D firstMatrix = doubleFactory2D.make(matrixProvider.getFirstMatrix());
|
||||
DoubleMatrix2D secondMatrix = doubleFactory2D.make(matrixProvider.getSecondMatrix());
|
||||
|
||||
Algebra algebra = new Algebra();
|
||||
return algebra.mult(firstMatrix, secondMatrix);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,33 @@
|
||||
package com.baeldung.matrices;
|
||||
|
||||
import org.openjdk.jmh.annotations.Scope;
|
||||
import org.openjdk.jmh.annotations.State;
|
||||
|
||||
@State(Scope.Benchmark)
|
||||
public class MatrixProvider {
|
||||
private double[][] firstMatrix;
|
||||
private double[][] secondMatrix;
|
||||
|
||||
public MatrixProvider() {
|
||||
firstMatrix =
|
||||
new double[][] {
|
||||
new double[] {1d, 5d},
|
||||
new double[] {2d, 3d},
|
||||
new double[] {1d ,7d}
|
||||
};
|
||||
|
||||
secondMatrix =
|
||||
new double[][] {
|
||||
new double[] {1d, 2d, 3d, 7d},
|
||||
new double[] {5d, 2d, 8d, 1d}
|
||||
};
|
||||
}
|
||||
|
||||
public double[][] getFirstMatrix() {
|
||||
return firstMatrix;
|
||||
}
|
||||
|
||||
public double[][] getSecondMatrix() {
|
||||
return secondMatrix;
|
||||
}
|
||||
}
|
@ -7,15 +7,10 @@ import org.openjdk.jmh.annotations.*;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@Fork(value = 2)
|
||||
@Warmup(iterations = 5)
|
||||
@Measurement(iterations = 10)
|
||||
public class RealMatrixUnitTest {
|
||||
class RealMatrixUnitTest {
|
||||
|
||||
@Test
|
||||
@Benchmark
|
||||
public void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() {
|
||||
void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() {
|
||||
RealMatrix firstMatrix = new Array2DRowRealMatrix(
|
||||
new double[][] {
|
||||
new double[] {1d, 5d},
|
||||
@ -43,5 +38,4 @@ public class RealMatrixUnitTest {
|
||||
|
||||
assertThat(actual).isEqualTo(expected);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -8,15 +8,10 @@ import org.openjdk.jmh.annotations.*;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@Fork(value = 2)
|
||||
@Warmup(iterations = 5)
|
||||
@Measurement(iterations = 10)
|
||||
public class DoubleMatrix2DUnitTest {
|
||||
class DoubleMatrix2DUnitTest {
|
||||
|
||||
@Test
|
||||
@Benchmark
|
||||
public void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() {
|
||||
void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() {
|
||||
DoubleFactory2D doubleFactory2D = DoubleFactory2D.dense;
|
||||
|
||||
DoubleMatrix2D firstMatrix = doubleFactory2D.make(
|
||||
@ -48,4 +43,4 @@ public class DoubleMatrix2DUnitTest {
|
||||
assertThat(actual).isEqualTo(expected);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
@ -6,15 +6,10 @@ import org.openjdk.jmh.annotations.*;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@Fork(value = 2)
|
||||
@Warmup(iterations = 5)
|
||||
@Measurement(iterations = 10)
|
||||
public class SimpleMatrixUnitTest {
|
||||
class SimpleMatrixUnitTest {
|
||||
|
||||
@Test
|
||||
@Benchmark
|
||||
public void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() {
|
||||
void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() {
|
||||
SimpleMatrix firstMatrix = new SimpleMatrix(
|
||||
new double[][] {
|
||||
new double[] {1d, 5d},
|
||||
@ -43,4 +38,4 @@ public class SimpleMatrixUnitTest {
|
||||
assertThat(actual).matches(m -> m.isIdentical(expected, 0d));
|
||||
}
|
||||
|
||||
}
|
||||
}
|
@ -5,15 +5,10 @@ import org.openjdk.jmh.annotations.*;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@Fork(value = 2)
|
||||
@Warmup(iterations = 5)
|
||||
@Measurement(iterations = 10)
|
||||
public class HomemadeMatrixUnitTest {
|
||||
class HomemadeMatrixUnitTest {
|
||||
|
||||
@Test
|
||||
@Benchmark
|
||||
public void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() {
|
||||
void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() {
|
||||
double[][] firstMatrix = {
|
||||
new double[]{1d, 5d},
|
||||
new double[]{2d, 3d},
|
||||
@ -55,4 +50,5 @@ public class HomemadeMatrixUnitTest {
|
||||
}
|
||||
return cell;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -7,15 +7,10 @@ import org.openjdk.jmh.annotations.*;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@Fork(value = 2)
|
||||
@Warmup(iterations = 5)
|
||||
@Measurement(iterations = 10)
|
||||
public class Basic2DMatrixUnitTest {
|
||||
class Basic2DMatrixUnitTest {
|
||||
|
||||
@Test
|
||||
@Benchmark
|
||||
public void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() {
|
||||
void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() {
|
||||
Matrix firstMatrix = new Basic2DMatrix(
|
||||
new double[][]{
|
||||
new double[]{1d, 5d},
|
||||
@ -44,4 +39,4 @@ public class Basic2DMatrixUnitTest {
|
||||
assertThat(actual).isEqualTo(expected);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
@ -7,14 +7,10 @@ import org.openjdk.jmh.annotations.*;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@Fork(value = 2)
|
||||
@Warmup(iterations = 5)
|
||||
@Measurement(iterations = 10)
|
||||
public class INDArrayUnitTest {
|
||||
class INDArrayUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() {
|
||||
void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() {
|
||||
INDArray firstMatrix = Nd4j.create(
|
||||
new double[][]{
|
||||
new double[]{1d, 5d},
|
||||
@ -43,4 +39,4 @@ public class INDArrayUnitTest {
|
||||
assertThat(actual).isEqualTo(expected);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
2
java-numbers-2/README.md
Normal file
2
java-numbers-2/README.md
Normal file
@ -0,0 +1,2 @@
|
||||
## Relevant Articles
|
||||
- [Lossy Conversion in Java](https://www.baeldung.com/java-lossy-conversion)
|
@ -23,3 +23,4 @@
|
||||
- [Java Multi-line String](https://www.baeldung.com/java-multiline-string)
|
||||
- [Checking If a String Is a Repeated Substring](https://www.baeldung.com/java-repeated-substring)
|
||||
- [How to Reverse a String in Java](https://www.baeldung.com/java-reverse-string)
|
||||
- [String toLowerCase and toUpperCase Methods in Java](https://www.baeldung.com/java-string-convert-case)
|
||||
|
@ -1 +1,2 @@
|
||||
### Relevant Articles:
|
||||
- [Java EE Application with Kotlin](https://www.baeldung.com/java-ee-kotlin-app)
|
||||
|
@ -1,3 +1,4 @@
|
||||
### Relevant Articles
|
||||
|
||||
- [Introduction to Quasar in Kotlin](https://www.baeldung.com/kotlin-quasar)
|
||||
- [Advanced Quasar Usage for Kotlin](https://www.baeldung.com/kotlin-quasar-advanced)
|
||||
|
5
libraries-data-3/README.md
Normal file
5
libraries-data-3/README.md
Normal file
@ -0,0 +1,5 @@
|
||||
### Relevant articles
|
||||
- [Parsing YAML with SnakeYAML](http://www.baeldung.com/java-snake-yaml)
|
||||
- [Guide to JMapper](https://www.baeldung.com/jmapper)
|
||||
- [An Introduction to SuanShu](https://www.baeldung.com/suanshu)
|
||||
- [Intro to Derive4J](https://www.baeldung.com/derive4j)
|
1
libraries-data-3/log4j.properties
Normal file
1
libraries-data-3/log4j.properties
Normal file
@ -0,0 +1 @@
|
||||
log4j.rootLogger=INFO, stdout
|
55
libraries-data-3/pom.xml
Normal file
55
libraries-data-3/pom.xml
Normal file
@ -0,0 +1,55 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>libraries-data-3</artifactId>
|
||||
<name>libraries-data-3</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.yaml</groupId>
|
||||
<artifactId>snakeyaml</artifactId>
|
||||
<version>${snakeyaml.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.googlecode.jmapper-framework</groupId>
|
||||
<artifactId>jmapper-core</artifactId>
|
||||
<version>${jmapper.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.numericalmethod</groupId>
|
||||
<artifactId>suanshu</artifactId>
|
||||
<version>${suanshu.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.derive4j</groupId>
|
||||
<artifactId>derive4j</artifactId>
|
||||
<version>${derive4j.version}</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>nm-repo</id>
|
||||
<name>Numerical Method's Maven Repository</name>
|
||||
<url>http://repo.numericalmethod.com/maven/</url>
|
||||
<layout>default</layout>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
<properties>
|
||||
<snakeyaml.version>1.21</snakeyaml.version>
|
||||
<jmapper.version>1.6.0.1</jmapper.version>
|
||||
<suanshu.version>4.0.0</suanshu.version>
|
||||
<derive4j.version>1.1.0</derive4j.version>
|
||||
</properties>
|
||||
</project>
|
10
libraries-data-3/src/main/resources/user_jmapper.xml
Normal file
10
libraries-data-3/src/main/resources/user_jmapper.xml
Normal file
@ -0,0 +1,10 @@
|
||||
<jmapper>
|
||||
<class name="com.baeldung.jmapper.UserDto">
|
||||
<attribute name="id">
|
||||
<value name="id"/>
|
||||
</attribute>
|
||||
<attribute name="username">
|
||||
<value name="email"/>
|
||||
</attribute>
|
||||
</class>
|
||||
</jmapper>
|
5
libraries-data-3/src/main/resources/user_jmapper1.xml
Normal file
5
libraries-data-3/src/main/resources/user_jmapper1.xml
Normal file
@ -0,0 +1,5 @@
|
||||
<jmapper>
|
||||
<class name="com.baeldung.jmapper.UserDto1">
|
||||
<global/>
|
||||
</class>
|
||||
</jmapper>
|
21
libraries-data-3/src/main/resources/user_jmapper2.xml
Normal file
21
libraries-data-3/src/main/resources/user_jmapper2.xml
Normal file
@ -0,0 +1,21 @@
|
||||
<jmapper>
|
||||
<class name="com.baeldung.jmapper.relational.User">
|
||||
<attribute name="id">
|
||||
<value name="id"/>
|
||||
<classes>
|
||||
<class name="com.baeldung.jmapper.relational.UserDto1"/>
|
||||
<class name="com.baeldung.jmapper.relational.UserDto2"/>
|
||||
</classes>
|
||||
</attribute>
|
||||
<attribute name="email">
|
||||
<attributes>
|
||||
<attribute name="username"/>
|
||||
<attribute name="email"/>
|
||||
</attributes>
|
||||
<classes>
|
||||
<class name="com.baeldung.jmapper.relational.UserDto1"/>
|
||||
<class name="com.baeldung.jmapper.relational.UserDto2"/>
|
||||
</classes>
|
||||
</attribute>
|
||||
</class>
|
||||
</jmapper>
|
3
libraries-data-3/src/test/resources/yaml/customer.yaml
Normal file
3
libraries-data-3/src/test/resources/yaml/customer.yaml
Normal file
@ -0,0 +1,3 @@
|
||||
firstName: "John"
|
||||
lastName: "Doe"
|
||||
age: 20
|
@ -0,0 +1,7 @@
|
||||
firstName: "John"
|
||||
lastName: "Doe"
|
||||
age: 31
|
||||
contactDetails:
|
||||
- { type: "mobile", number: 123456789}
|
||||
- { type: "landline", number: 456786868}
|
||||
|
@ -0,0 +1,13 @@
|
||||
firstName: "John"
|
||||
lastName: "Doe"
|
||||
age: 31
|
||||
contactDetails:
|
||||
- type: "mobile"
|
||||
number: 123456789
|
||||
- type: "landline"
|
||||
number: 456786868
|
||||
homeAddress:
|
||||
line: "Xyz, DEF Street"
|
||||
city: "City Y"
|
||||
state: "State Y"
|
||||
zip: 345657
|
@ -0,0 +1,6 @@
|
||||
firstName: "John"
|
||||
lastName: "Doe"
|
||||
age: 31
|
||||
contactDetails:
|
||||
- !contact { type: "mobile", number: 123456789}
|
||||
- !contact { type: "landline", number: 456786868}
|
@ -0,0 +1,4 @@
|
||||
!!com.baeldung.snakeyaml.Customer
|
||||
firstName: "John"
|
||||
lastName: "Doe"
|
||||
age: 20
|
8
libraries-data-3/src/test/resources/yaml/customers.yaml
Normal file
8
libraries-data-3/src/test/resources/yaml/customers.yaml
Normal file
@ -0,0 +1,8 @@
|
||||
---
|
||||
firstName: "John"
|
||||
lastName: "Doe"
|
||||
age: 20
|
||||
---
|
||||
firstName: "Jack"
|
||||
lastName: "Jones"
|
||||
age: 25
|
@ -9,7 +9,6 @@
|
||||
- [Introduction to JCache](http://www.baeldung.com/jcache)
|
||||
- [A Guide to Apache Ignite](http://www.baeldung.com/apache-ignite)
|
||||
- [Apache Ignite with Spring Data](http://www.baeldung.com/apache-ignite-spring-data)
|
||||
- [Guide to JMapper](https://www.baeldung.com/jmapper)
|
||||
- [A Guide to Apache Crunch](https://www.baeldung.com/apache-crunch)
|
||||
- [Intro to Apache Storm](https://www.baeldung.com/apache-storm)
|
||||
- [Guide to Ebean ORM](https://www.baeldung.com/ebean-orm)
|
||||
|
@ -141,12 +141,7 @@
|
||||
<artifactId>hazelcast</artifactId>
|
||||
<version>${hazelcast.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.googlecode.jmapper-framework</groupId>
|
||||
<artifactId>jmapper-core</artifactId>
|
||||
<version>${jmapper.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- crunch project -->
|
||||
<dependency>
|
||||
<groupId>org.apache.crunch</groupId>
|
||||
@ -460,7 +455,6 @@
|
||||
<datanucleus-maven-plugin.version>5.0.2</datanucleus-maven-plugin.version>
|
||||
<datanucleus-xml.version>5.0.0-release</datanucleus-xml.version>
|
||||
<datanucleus-jdo-query.version>5.0.4</datanucleus-jdo-query.version>
|
||||
<jmapper.version>1.6.0.1</jmapper.version>
|
||||
<org.apache.crunch.crunch-core.version>0.15.0</org.apache.crunch.crunch-core.version>
|
||||
<org.apache.hadoop.hadoop-client>2.2.0</org.apache.hadoop.hadoop-client>
|
||||
<ebean.version>11.22.4</ebean.version>
|
||||
|
@ -5,3 +5,7 @@
|
||||
- [A Guide to Google-Http-Client](http://www.baeldung.com/google-http-client)
|
||||
- [Asynchronous HTTP with async-http-client in Java](http://www.baeldung.com/async-http-client)
|
||||
- [WebSockets with AsyncHttpClient](http://www.baeldung.com/async-http-client-websockets)
|
||||
- [Integrating Retrofit with RxJava](http://www.baeldung.com/retrofit-rxjava)
|
||||
- [Introduction to Retrofit](http://www.baeldung.com/retrofit)
|
||||
- [A Guide to Unirest](http://www.baeldung.com/unirest)
|
||||
- [Creating REST Microservices with Javalin](http://www.baeldung.com/javalin-rest-microservices)
|
@ -44,6 +44,23 @@
|
||||
<version>${googleclient.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Retrofit -->
|
||||
<dependency>
|
||||
<groupId>com.squareup.retrofit2</groupId>
|
||||
<artifactId>retrofit</artifactId>
|
||||
<version>${retrofit.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.squareup.retrofit2</groupId>
|
||||
<artifactId>converter-gson</artifactId>
|
||||
<version>${retrofit.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.squareup.retrofit2</groupId>
|
||||
<artifactId>adapter-rxjava</artifactId>
|
||||
<version>${retrofit.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- https://mvnrepository.com/artifact/org.asynchttpclient/async-http-client -->
|
||||
<dependency>
|
||||
<groupId>org.asynchttpclient</groupId>
|
||||
@ -69,13 +86,52 @@
|
||||
<version>${com.squareup.okhttp3.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.mashape.unirest</groupId>
|
||||
<artifactId>unirest-java</artifactId>
|
||||
<version>${unirest.version}</version>
|
||||
</dependency>
|
||||
<!-- javalin -->
|
||||
<dependency>
|
||||
<groupId>io.javalin</groupId>
|
||||
<artifactId>javalin</artifactId>
|
||||
<version>${javalin.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.squareup.okhttp3</groupId>
|
||||
<artifactId>logging-interceptor</artifactId>
|
||||
<version>${logging-interceptor.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpclient</artifactId>
|
||||
<version>${httpclient.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
<groupId>commons-logging</groupId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<httpclient.version>4.5.3</httpclient.version>
|
||||
<jackson.version>2.9.8</jackson.version>
|
||||
<assertj.version>3.6.2</assertj.version>
|
||||
<com.squareup.okhttp3.version>3.14.2</com.squareup.okhttp3.version>
|
||||
<googleclient.version>1.23.0</googleclient.version>
|
||||
<async.http.client.version>2.2.0</async.http.client.version>
|
||||
<retrofit.version>2.3.0</retrofit.version>
|
||||
<unirest.version>1.4.9</unirest.version>
|
||||
<javalin.version>1.6.0</javalin.version>
|
||||
<logging-interceptor.version>3.9.0</logging-interceptor.version>
|
||||
</properties>
|
||||
</project>
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user