Java code examples

import java.util.HashMap;

import java.util.Map;

public class PeopleAddressList { private Map<String, String> addressList; public PeopleAddressList() { addressList = new HashMap<>(); }

public void addPerson(String name, String address) { addressList.put(name, address); }

public String getAddress(String name) { return addressList.get(name); }

public void removePerson(String name) { addressList.remove(name); }

public int size() { return addressList.size(); }

public void clear() { addressList.clear(); }

public void printAddressList() { for (String name : addressList.keySet()) { System.out.println(name + ” : ” + addressList.get(name)); } }

public static void main(String[] args) { PeopleAddressList list = new PeopleAddressList(); list.addPerson(“John Doe”, “123 Main Street”);

list.addPerson(“Jane Doe”, “456 Elm Street”); list.printAddressList(); }}

//Main class as below

import java.util.HashMap;

import java.util.Map;

public class AddressSummary {

private PeopleAddressList addressList; public void setAddressList(PeopleAddressList addressList) { this.addressList = addressList; }

public String toString() { StringBuilder sb = new StringBuilder(); for (String name : addressList.keySet()) { sb.append(name + ” : ” + addressList.get(name) + “\n”); } return sb.toString(); }

public static void main(String[] args) { AddressGeneration generation = new AddressGeneration(); PeopleAddressList list = generation.getPeopleAddressList(); AddressSummary summary = new AddressSummary(); summary.setAddressList(list); System.out.println(summary); }}

public class AddressGeneration {

public PeopleAddressList getPeopleAddressList() { PeopleAddressList list = new PeopleAddressList(); list.addPerson(“John Doe”, “123 Main Street”);

list.addPerson(“Jane Doe”, “456 Elm Street”);

return list; }}

//Facade Design pattern

import java.util.HashMap;
import java.util.Map;

public class AddressSummaryFacade {

private AddressGeneration generation;
private AddressSummary summary;

public AddressSummaryFacade() {
    generation = new AddressGeneration();
    summary = new AddressSummary();
}

public String getAddressSummary() {
    summary.setAddressList(generation.getPeopleAddressList());
    return summary.toString();
}

}

public class Main {

public static void main(String[] args) {
    AddressSummaryFacade facade = new AddressSummaryFacade();
    System.out.println(facade.getAddressSummary());
}

}

tablesaw vs apachepoi

import org.apache.poi.ss.usermodel.*;import org.apache.poi.xssf.usermodel.XSSFWorkbook;import tech.tablesaw.api.Table;import org.openjdk.jmh.annotations.*;import java.io.File;import java.io.FileInputStream;import java.io.IOException;@BenchmarkMode(Mode.Throughput)@Warmup(iterations = 3, time = 1)@Measurement(iterations = 5, time = 1)@State(Scope.Benchmark)public class ExcelReadBenchmark { private File excelFile; private Table tablesawTable; @Setup public void setup() { // Initialize your Excel file and Tablesaw table here excelFile = new File(“your-excel-file.xlsx”); // Replace with your Excel file path tablesawTable = Table.read().csv(“your-csv-file.csv”); // Replace with your CSV file path } @Benchmark public void readAndPrintWithTablesaw() { // Perform reading and printing using Tablesaw String column1 = tablesawTable.column(“Column1”).toString(); // Print or process column1 here } @Benchmark public void readAndPrintWithApachePOI() throws IOException { // Perform reading and printing using Apache POI FileInputStream inputStream = new FileInputStream(excelFile); Workbook workbook = new XSSFWorkbook(inputStream); Sheet sheet = workbook.getSheetAt(0); // Assuming the data is in the first sheet for (Row row : sheet) { Cell cell = row.getCell(0); // Access the first cell (column 1) if (cell != null) { String cellValue = cell.toString(); // Print or process cellValue here } } workbook.close(); inputStream.close(); } public static void main(String[] args) throws Exception { org.openjdk.jmh.Main.main(args); }}

read from 100 to 200

import tech.tablesaw.api.*;
import tech.tablesaw.io.csv.CsvReadOptions;

public class ReadCSVWithTablesaw {

public static void main(String[] args) {
    // Define the path to your CSV file
    String csvFilePath = "path/to/your/file.csv"; // Replace with your CSV file path

    // Define the range of rows you want to read (100 to 200)
    int startRow = 100;
    int endRow = 200;

    try {
        // Define read options
        CsvReadOptions options = CsvReadOptions.builder(csvFilePath)
                .header(true) // Assuming the CSV file has a header row
                .build();

        // Read the CSV file into a Table
        Table table = Table.read().csv(options);

        // Extract the desired rows (100 to 200) from column 1
        Column<String> column1 = table.column(1).subList(startRow, endRow + 1).asStringColumn();

        // Print or process the values in column1
        for (String value : column1) {
            System.out.println(value);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

// SpringBoot

//YourService

import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

@Service
public class YourService {

public Mono<Address> fetchAddress(String branch, String filename) {
    return WebClient.create()
            .get()
            .uri("https://bitbucket.org/{filename}?branch={branch}")
            .retrieve()
            .bodyToMono(String.class)
            .map(json -> parseAddressFromJson(json)); // Custom parsing logic
}

private Address parseAddressFromJson(String json) {
    // Implement your JSON parsing logic to convert JSON string to Address object
    // For example, using Jackson ObjectMapper:
    ObjectMapper objectMapper = new ObjectMapper();
    try {
        return objectMapper.readValue(json, Address.class);
    } catch (JsonProcessingException e) {
        // Handle parsing exception
        throw new RuntimeException("Error parsing JSON", e);
    }
}

}

//Controller

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

@RestController
@RequestMapping(“/api/addresses”)
public class AddressController {

private final YourService yourService;

@Autowired
public AddressController(YourService yourService) {
    this.yourService = yourService;
}

@GetMapping("/{branch}/{filename}")
public Mono<ResponseEntity<Address>> getAddress(
        @PathVariable String branch,
        @PathVariable String filename) {
    return yourService.fetchAddress(branch, filename)
            .map(ResponseEntity::ok)
            .defaultIfEmpty(ResponseEntity.notFound().build());
}

}

// Detailed implementation

//AddressService

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.io.IOException;

@Service
public class AddressService {

private final WebClient webClient;
private final String repositoryUrl;
private final String branch;

public AddressService(WebClient.Builder webClientBuilder,
                      @Value("${bitbucket.repositoryUrl}") String repositoryUrl,
                      @Value("${bitbucket.branch}") String branch) {
    this.webClient = webClientBuilder.build();
    this.repositoryUrl = repositoryUrl;
    this.branch = branch;
}

public Mono<Address> getAddressFromBitbucket(String filename) {
    // Construct the URL to the JSON file in the Bitbucket repository
    String url = String.format("%s/%s/%s/%s", repositoryUrl, branch, filename);

    // Make a GET request using WebClient
    return webClient.get()
            .uri(url)
            .retrieve()
            .bodyToMono(String.class)
            .flatMap(this::parseAddressFromJson);
}

private Mono<Address> parseAddressFromJson(String jsonResponse) {
    ObjectMapper mapper = new ObjectMapper();
    try {
        JsonNode jsonNode = mapper.readTree(jsonResponse);

        // Extract address data from the JSON node
        Address address = new Address();
        address.setStreet(jsonNode.get("street").asText());
        address.setCity(jsonNode.get("city").asText());
        address.setState(jsonNode.get("state").asText());
        address.setCountry(jsonNode.get("country").asText());
        address.setPostalCode(jsonNode.get("postalCode").asText());

        return Mono.just(address);
    } catch (IOException e) {
        return Mono.error(e);
    }
}

}

// app prop / yaml

bitbucket.repositoryUrl=https://api.bitbucket.org/2.0/repositories/{username}/{repo_slug}/src
bitbucket.branch=master

// your service

@Service
public class YourService {

private final AddressService addressService;

public YourService(AddressService addressService) {
    this.addressService = addressService;
}

public Mono<Address> getAddress(String filename) {
    return addressService.getAddressFromBitbucket(filename);
}

}

// controller

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

@RestController
@RequestMapping(“/api”)
public class AddressController {

private final YourService yourService;

@Autowired
public AddressController(YourService yourService) {
    this.yourService = yourService;
}

@GetMapping("/address/{filename}")
public Mono<ResponseEntity<Address>> getAddress(@PathVariable String filename) {
    return yourService.getAddress(filename)
            .map(ResponseEntity::ok)
            .defaultIfEmpty(ResponseEntity.notFound().build());
}

}

Addl java examples

@Service
public class BitbucketService {
private final WebClient webClient;

public BitbucketService() {
    webClient = WebClient.builder()
            .baseUrl("https://api.bitbucket.org/2.0/")
            .build();
}

public String getJsonFile() {
    String repoOwner = "your-repo-owner";
    String repoName = "your-repo-name";
    String filePath = "path/to/your/json/file.json";

    String url = String.format("repos/%s/%s/contents/%s", repoOwner, repoName, filePath);
    return webClient.get().uri(url).retrieve().bodyToMono(String.class).block();
}

}

@RestController
public class JsonController {
private final BitbucketService bitbucketService;

public JsonController(BitbucketService bitbucketService) {
    this.bitbucketService = bitbucketService;
}

@GetMapping("/json")
public String getJson() {
    return bitbucketService.getJsonFile();
}

}

some python examples

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

corpus = [
“The first document is about space exploration.”,
“The second document is about machine learning.”,
“The third is about gardening.”
]

vectorizer = TfidfVectorizer(stop_words=’english’)
tfidf_matrix = vectorizer.fit_transform(corpus)

def answer_question(query):
query_vector = vectorizer.transform([query])
similarities = cosine_similarity(query_vector, tfidf_matrix)[0]
most_similar_doc_idx = similarities.argmax()
print(“Most relevant document:”, corpus[most_similar_doc_idx])

question = “What is machine learning?”
answer_question(question)