copy paste json pretty print

in terminal
pbpaste | json_pp | pbcopy

Raspberry pi Docker Portainer

apt update -y && apt upgrade -y
apt install git

create downloads folder get: https://github.com/novaspirit/pi-hosted

install docker

installdocker.sh

#!/bin/bash

function error {
  echo -e "\\e[91m$1\\e[39m"
  exit 1
}

function check_internet() {
  printf "Checking if you are online..."
  wget -q --spider http://github.com
  if [ $? -eq 0 ]; then
    echo "Online. Continuing."
  else
    error "Offline. Go connect to the internet then run the script again."
  fi
}

check_internet

curl -sSL https://get.docker.com | sh || error "Failed to install Docker."
sudo usermod -aG docker $USER || error "Failed to add user to the Docker usergroup."
echo "Remember to logoff/reboot for the changes to take effect."

check if docker in groups.

groups

apt install docker

install portainer

#!/bin/bash

function error {
  echo -e "\\e[91m$1\\e[39m"
  exit 1
}

function check_internet() {
  printf "Checking if you are online..."
  wget -q --spider http://github.com
  if [ $? -eq 0 ]; then
    echo "Online. Continuing."
  else
    error "Offline. Go connect to the internet then run the script again."
  fi
}

check_internet

sudo docker pull portainer/portainer-ce:latest || error "Failed to pull latest Portainer docker image!"
sudo docker run -d -p 9000:9000 -p 9443:9443 --name=portainer --restart=always -v /var/run/docker.sock:/var/run/docker.sock -v portainer_data:/data portainer/portainer-ce:latest || error "Failed to run Portainer docker image!"

check in browser if portainer is working.

list templates for portainer:

templates
https://raw.githubusercontent.com/SelfhostedPro/selfhosted_templates/master/Template/portainer-v2.json

default:
https://raw.githubusercontent.com/portainer/templates/master/templates-2.0.json

nog 1:
https://raw.githubusercontent.com/dnburgess/self-hosted-template/master/template.json

redditpost:
https://raw.githubusercontent.com/dnburgess/self-hosted-template/master/template.json

https://raw.githubusercontent.com/Qballjos/portainer_templates/master/Template/template.json

https://raw.githubusercontent.com/SelfhostedPro/selfhosted_templates/portainer-2.0/Template/template.json

https://raw.githubusercontent.com/technorabilia/portainer-templates/main/lsio/templates/templates-2.0.json

https://raw.githubusercontent.com/mikestraney/portainer-templates/master/templates.json

https://raw.githubusercontent.com/mycroftwilde/portainer_templates/master/Template/template.json

speedtest cli

curl -s https://raw.githubusercontent.com/sivel/speedtest-cli/master/speedtest.py | python -

Dynamic UIFont

example by demo

UIFont

.largeTitle, .title1, .title2, .title3, .headline, .subheadline, .body, .footnote, .caption1, .caption2, .callout

Large (Default)

| Style | Weight | Size (points)
| ---------- | :------: | --------------: |
Large Title | Regular | 34
Title 1 | Regular | 28
Title 2 | Regular | 22
Title 3 | Regular | 20
Headline | Semi-Bold | 17
Body |Regular | 17
Callout | Regular | 16
Subhead | Regular |15
Footnote | Regular | 13
Caption 1 | Regular | 12
Caption 2 | Regular | 11

let label = UILabel()
label.font = UIFont.preferredFont(forTextStyle: .body)
label.adjustsFontForContentSizeCategory = true 

apple doc
article with examples

Tags: 

Typescript enum to array

// enum with string values
enum Lines {
    Line1 = 'text1',
    Line2 = 'text2',
    Line3 = 'text3'
}
// enum
enum State {
    Start,
    Running,
    Stop
}

function ToArray(lines: any) {
    return Object.keys(lines)
        .filter(l => typeof l === "string")
        .map(l => lines[l]);
}

const arr = ToArray(Lines);

console.log(ToArray(arr)); //  ["text1", "text2", "text3"]

const arr2 = ToArray(State);

console.log(ToArray(arr2)); // ["Start", "Running", "Stop", 0, 1, 2]  ??? 0, 1, 2 are no strings???

Cli with java commons

pom.xml

<?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>org.example</groupId>
    <artifactId>testffCli</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>commons-cli</groupId>
            <artifactId>commons-cli</artifactId>
            <version>1.4</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>Cli</finalName>
    </build>
</project>

Cli.java

import org.apache.commons.cli.*;
import java.io.PrintWriter;

public class Cli {
    private static final Option ARG_ADD = new Option("a", "addition", false, "Add numbers together.");
    private static final Option ARG_SUBTRACT = new Option("s", "subtract", false, "Subtracts numbers together.");
    private static final Option ARG_MULTIPLY = new Option("m", "multiply", false, "Multiply numbers together.");
    private static final Option ARG_DIVIDE = new Option("d", "divide", false, "Divide numbers together.");

    public static void printHelp(Options options) {
        HelpFormatter hf = new HelpFormatter();
        PrintWriter pw = new PrintWriter(System.out);
        pw.println("Math App " + Cli.class.getPackage().getImplementationVersion());
        pw.println();
        hf.printUsage(pw, 100, "java -jar Cli.jar [OPTIONS] Number Number");
        hf.printOptions(pw, 100, options, 2, 5);
        pw.close();
    }

    public static void main(String[] args) {

        CommandLineParser clp = new DefaultParser();
        Options options = new Options();
        options.addOption(ARG_ADD);
        options.addOption(ARG_SUBTRACT);
        options.addOption(ARG_MULTIPLY);
        options.addOption(ARG_DIVIDE);

        try {
            CommandLine cl = clp.parse(options, args);

            if (cl.getArgList().size() < 2) {
                printHelp(options);
                System.exit(-1);
            }

            var a = Integer.parseInt(cl.getArgList().get(0));
            var b = Integer.parseInt(cl.getArgList().get(1));

            if (cl.hasOption(ARG_ADD.getLongOpt())) {
                System.out.println(String.format("%1$d + %2$d = %3$d", a, b, (a + b)));
            } else if (cl.hasOption(ARG_SUBTRACT.getLongOpt())) {
                System.out.println(String.format("%1$d - %2$d = %3$d", a, b, (a - b)));
            } else if (cl.hasOption(ARG_MULTIPLY.getLongOpt())) {
                System.out.println(String.format("%1$d * %2$d = %3$d", a, b, (a * b)));
            } else if (cl.hasOption(ARG_DIVIDE.getLongOpt())) {
                System.out.println(String.format("%1$d / %2$d = %3$d", a, b, (a / b)));
            } else {
                printHelp(options);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
Tags: 

Remove all node_module folders

find . -name "node_modules" -type d -prune | xargs du -chs
find . -name "node_modules" -type d -prune -exec rm -rf '{}' +

Spring + Angular in one jar

based on:
Webapp with Create React App

  • create spring app
  • prevent cors
@Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedOrigins("http://localhost:4200")
                        .allowedHeaders("application/json", "text/plain", "*/*",
                                "Access-Control-Allow-Headers",
                                "Access-Control-Allow-Origin",
                                "Origin", "Accept", "X-Requested-With, Content-Type",
                                "Access-Control-Request-Method",
                                "Access-Control-Request-Headers")
                        .allowedMethods("GET", "PUT", "POST", "PATCH", "DELETE", "OPTIONS")
                        .maxAge(3600)
                ;
            }
        };

  • in root create new ng app
  • create proxy.conf.json in root frontend app
{
  "/api/*": {
    "target": "http://localhost:8080",
    "secure": false,
    "logLevel": "debug",
    "changeOrigin": true
  }
}
  • change angular.json:
            "development": {
              "browserTarget": "frontend:build:development",
              "proxyConfig": "proxy.conf.json"
            }
  • add plugin for building the frontend:
    note: version!!!
    note: npmVersion!!!
    note: nodeVersion!!!
<plugin>
                <groupId>com.github.eirslett</groupId>
                <artifactId>frontend-maven-plugin</artifactId>
                <version>1.9.1</version>
                <configuration>
                    <workingDirectory>frontend</workingDirectory>
                    <installDirectory>target</installDirectory>
                </configuration>
                <executions>
                    <execution>
                        <id>install node and npm</id>
                        <goals>
                            <goal>install-node-and-npm</goal>
                        </goals>
                        <configuration>
                            <nodeVersion>v14.15.4</nodeVersion>
                            <npmVersion>7.17.0</npmVersion>
                        </configuration>
                    </execution>
                    <execution>
                        <id>npm install</id>
                        <goals>
                            <goal>npm</goal>
                        </goals>
                        <configuration>
                            <arguments>install</arguments>
                        </configuration>
                    </execution>
                    <execution>
                        <id>npm run build</id>
                        <goals>
                            <goal>npm</goal>
                        </goals>
                        <configuration>
                            <arguments>run build</arguments>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

  • copy the dist version to target:
    note double check location where the build is located
    note mvn clean package
<plugin>
                <artifactId>maven-antrun-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>generate-resources</phase>
                        <configuration>
                            <target>
                                <copy todir="${project.build.directory}/classes/public">
                                    <fileset dir="${project.basedir}/frontend/dist"/>
                                </copy>
                            </target>
                        </configuration>
                        <goals>
                            <goal>run</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

Grafana

with local data

  docker run -d -p 3000:3000 --name grafana --volume "$PWD/data:/var/lib/grafana" grafana/grafana  
  docker container ls -a  
  docker container stop <tagname>  
  docker container rm <tagname> 

hub.docker.com

docker run -d -p 3000:3000 --name grafana --user 472 --volume "$PWD/data:/var/lib/grafana" -e "GF_INSTALL_PLUGINS=grafana-clock-panel,grafana-simple-json-datasource" grafana/grafana

docker stop grafana
docker commit grafana
docker tag grafana yoyohu/grafana-tuinhok
docker push yoyohu/grafana-tuinhok:latest

Query time correction

SELECT
  UNIX_TIMESTAMP(created) AS "time",
  temperature
FROM temperatures
WHERE
  $__timeFilter(created)
ORDER BY created

Kubernetes

Kubernetes on Digital Ocean with Ingress

  • Create Kubernetes with Create-Button
  • Install One-click app Ingress
  • Make sure DNS is routed to the ip address of the kubernetes-stack
  • Add pods, create from form and choose INTERNAL service.
  • When removing pod double check you have removed all the services and routes etc etc.

Add Ingres yaml

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: web
  namespace: default
spec:
  rules:
  - host: nginx01-test.webaddress.com
    http:
      paths:
      - backend:
          serviceName: nginx01
          servicePort: 80
  - host: nginx02-test.yourwebaddress.com
    http:
      paths:
      - backend:
          serviceName: nginx02
          servicePort: 80

Openshift Podman K8s

containerized applications shares host os, hardware, trad os, isolates resources, network, libs namespace
advantage not vulnerable or need to be stopped for updates base system, lower hardware footprint, env iso, quick deploy, multiple env deploy, reusability
OCI open container initiative (specs)
Rocket Drawbridge Docker Podman

containers: namespaces, controlgroups cgroups, Seccomp, SELinux

k8s
is helmsman/orchestrator => simplyfy deployment, managment, scaling containers
service discovery and load balancing
horizontal scaling
self healing
automated rollout
secrets and config management
operators

openshift is set of modular components and services on top of kubernetes

openshift
integrates dev workflow (ci/cd pipelines, s2i)
routes
metrics & logging
unified ui

https://registry.redhat.io
https://quay.io

registries
redhat container images
trusted source
original deps
vulnerability-free
runtime protection
red hat enterprise linux
red hat support

configuring in podman

/etc/containers/registries.conf
[registries.search]
registries = ["registry.access.redhat.com", "quay.io"]

to support insecure connections:

[registries.insecure]
registries = ['localhost:5000']

PODMAN

sudo podman search rhel
sudo podman pull [OPTIONS] [REGISTRY[:PORT]/]NAME[:TAG]
sudo podman push [OPTIONS] IMAGE [DESTINATION]
sudo podman commit [OPTIONS] CONTAINER \ > [REPOSITORY[:PORT]/]IMAGE_NAME[:TAG]
sudo podman diff mysql-basic
sudo podman save [-o FILE_NAME] IMAGE_NAME[:TAG]
sudo podman tag [OPTIONS] IMAGE[:TAG] \ > [REGISTRYHOST/][USERNAME/]NAME[:TAG]
sudo podman images
sudo podman ps
sudo podman ps -a
sudo podman run REPO/IMG CMD
sudo podman run ubi7/ubi7:7 echo ‘hello’
sudo podman run -it ubi7/ubi:7.7 /bin/bash
sudo podman run -e GREET=Hello -e NAME=RedHat \ > rhel7:7.5 printenv GREET NAME # env vars!
sudo podman run --name mysql-custom -e MYSQL_USER=redhat -e MYSQL_PASSWORD=r3dh4t -d rhmap47/mysql:5.5
sudo podman exec -it mysql-basic /bin/bash  # run bash in running container
sudo podman inspect -l -f "{{.NetworkSettings.IPAddress}}"
sudo podman inspect \
> -f "{{range .Mounts}}{{println .Destination}}{{end}}" CONTAINER_NAME/ID
sudo podman ps --format "{{.ID}} {{.Image}} {{.Names}}"
sudo podman ps --format="{{.ID}} {{.Names}} {{.Status}}"
sudo podman ps -a
sudo podman stop containername/ID
sudo podman kill container
sudo podman kill -s SIGKKILL container
sudo podman restart container
sudo podman rm container
sudo podman rm -f container
sudo podman rmi [OPTIONS] IMAGE [IMAGE...]
sudo podman rmi -a
sudo podman rmi container

login with quay or docker:
sudo podman login -u username \ > -p password registry.access.redhat.com


persistant storage:
sudo mkdir /var/dbfiles
sudo chown -R 27:27 /var/dbfiles
sudo semanage fcontext -a -t container_file_t '/var/dbfiles(/.*)?'
sudo restorecon -Rv /var/dbfiles
sudo podman run -v /var/dbfiles:/var/lib/mysql rhmap47/mysql

===
sudo podman run --name mysqldb-port -d -v /var/local/mysql:/var/lib/mysql/data -p 13306:3306 -e MYSQL_USER=user1 -e MYSQL_PASSWORD=mypa55 -e MYSQL_DATABASE=items -e MYSQL_ROOT_PASSWORD=r00tpa55  rhscl/mysql-57-rhel7
sudo podman ps --format="{{.ID}} {{.Names}} {{.Ports}}"
mysql -uuser1 -h 127.0.0.1 -pmypa55 -P13306 items < /home/student/DO180/labs/manage-networking/db.sql
sudo podman exec -it mysqldb-port  /opt/rh/rh-mysql57/root/usr/bin/mysql -uroot items -e "SELECT * FROM Item"

===
sudo mkdir -pv /var/local/mysql
sudo semanage fcontext -a \ > -t container_file_t '/var/local/mysql(/.*)?'
sudo restorecon -R /var/local/mysql
sudo chown -Rv 27:27 /var/local/mysql
sudo podman run --name mysql-1 \
> -d -v /var/local/mysql:/var/lib/mysql/data \
> -e MYSQL_USER=user1 -e MYSQL_PASSWORD=mypa55 \
> -e MYSQL_DATABASE=items -e MYSQL_ROOT_PASSWORD=r00tpa55 \ > rhscl/mysql-57-rhel7
sudo podman ps --format="{{.ID}} {{.Names}}"
sudo podman inspect \ > -f '{{ .NetworkSettings.IPAddress }}' mysql-1
mysql -uuser1 -h CONTAINER_IP \
> -pmypa55 items < /home/student/DO180/labs/manage-review/db.sql
mysql -uuser1 -h CONTAINER_IP -pmypa55 items \ > -e "SELECT * FROM Item"
sudo podman stop mysql-1

Isolate folder containerize manually

in linux env

mkdir jail  
sudo cp /bin/bash ./jail/  
tree jail  
ldd /bin/bash # see the dep of bash program  
mkdir /jail/lib64  
sudo cp /lib64/lininfo.so.6 jail/lib64 // etc 5c  
tree jail  
chroot /root/jail/ ./bash // !!!  

Minikube

Minikube

run an Angular app in local kubernetes Minikube env with image from Docker.io

create angular app
in angular.ts custom output path: ... "options": { "outputPath": "dist/pw", ...

create nginx file:

events{}
http {
    include /etc/nginx/mime.types;
    server {
        listen 80;
        server_name localhost;
        root /usr/share/nginx/html;
        index index.html;
        location / {
            try_files $uri $uri/ /index.html;
        }
    }
}

create Dockerfile

Dockerfile

FROM nginx
COPY nginx.conf /etc/nginx/nginx.conf
COPY ./dist/pw /usr/share/nginx/html 

Minikube

On mac: install via brew minikube and hyperkit.
brew install hyperkit
brew install minikube
brew install kubectl

minikube start --vm-driver=hyperkit

in other terminal window

minikube dashboard

back to the first window:
(after a ng build --prod)

docker build -t DOCKER_ACCOUNTNAME/pw-app:latest .

docker push docker.io/DOCKER_ACCOUNTNAME/pw-app:latest

kubectl create deployment pw-app --image=docker.io/DOCKER_ACCOUNTNAME/pw-app:latest

kubectl expose deployment pw-app --type=NodePort --port=80
minikube service pw-app

remove node_modules from mac cli

find

find -d .  -name node_modules -prune 

find & size

Development % find . -type d -name node_modules -prune | tr '\n' '\0' |  xargs -0 du -sch  

find & remove

find . -name "node_modules" -type d -prune -exec rm -rf '{}' +  

Styling console.log()

Styling in console.log()
console.log("%c%s", "color: white; background-color: orange; font-style: italic;","my message")

%c - format styling
%s - format string
%o - dom object
%O - Javascript object
%i %f %d - numbers

MySQL Recap, Stored Procedures

SQL

Structured query language

show databases;

use dbname;

show tables;

desc users;
-- use a db
use testdb;

-- use a delimter
delimiter $$

create procedure HelloWorld()
begin
select "Hello WOlrd!";
end$$

delimiter ;

drop procedure HelloWorld;

call HelloWorld();

Openshift

Developer perspective

GUI

add shortcuts in menu for:
deployments services
routes
image streams
pods
replica sets

terminal oc project demoapp

oc config get-contexts

alles oc api-resources oc get pods oc get pods,deploy,svc oc get pods,rs,deploy

oc get all

(refresh at every 2 sec) watch oc get pods,deploy,svc

oc scale deploy demoapp-name --replicas=7

oc delete pod devops-demo-app-git-c8c68f8-8pfcs

Spring SLF4J: Class path contains multiple SLF4J bindings.

adding SLF4J and get rid of the error

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>

results in error after building

SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/Users/hjhubeek/.m2/repository/ch/qos/logback/logback-classic/1.2.3/logback-classic-1.2.3.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/Users/hjhubeek/.m2/repository/org/apache/logging/log4j/log4j-slf4j-impl/2.13.3/log4j-slf4j-impl-2.13.3.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [ch.qos.logback.classic.util.ContextSelectorStaticBinder]

something doubled up according to: Class path contains multiple SLF4J bindings.

mvn dependency:tree

or

the IntelliJ maven tab

will show

[INFO] +- org.springframework.boot:spring-boot-starter-log4j2:jar:2.4.1:compile
[INFO] |  +- org.apache.logging.log4j:log4j-slf4j-impl:jar:2.13.3:compile
[INFO] |  |  +- org.slf4j:slf4j-api:jar:1.7.30:compile
[INFO] |  |  \- org.apache.logging.log4j:log4j-api:jar:2.13.3:compile
[INFO] |  +- org.apache.logging.log4j:log4j-core:jar:2.13.3:compile
[INFO] |  +- org.apache.logging.log4j:log4j-jul:jar:2.13.3:compile
[INFO] |  \- org.slf4j:jul-to-slf4j:jar:1.7.30:compile

in the error message you find the hint for the solution.

SLF4J: Found binding in [jar:file:/Users/hjhubeek/.m2/repository/org/apache/logging/log4j/log4j-slf4j-impl/2.13.3/log4j-slf4j-impl-2.13.3.jar!/org/slf4j/impl/StaticLoggerBinder.class]

the groupId will be in there /org/apache/logging/log4j -> org.apache.logging.log4j

and artefact log4j-slf4j-impl -> log4j-slf4j-impl

will be solved:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-log4j2</artifactId>
    <exclusions>
      <exclusion>
        <groupId>org.apache.logging.log4j</groupId>
          <artifactId>log4j-slf4j-impl</artifactId>
      </exclusion>
    </exclusions>
 </dependency>

Java collections

list.forEach(System.out::print);

Array

int[] a = new int[5];

a[0] = 1;
a[1] = 2;
a[2] = 4;
a[3] = 8;
a[4] = 16;

String => array with .split() & .join()

ArrayList

ordered, index based, dyn sizing, non sync, duplicates allowed

//Non-generic arraylist - NOT RECOMMENDED !!
ArrayList list = new ArrayList();

//Generic Arraylist with default capacity(=16)
List<Integer> numbers = new ArrayList<>(); 

//Generic Arraylist with the given capacity
List<Integer> numbers = new ArrayList<>(6); 

//Generic Arraylist initialized with another collection
List<Integer> numbers = new ArrayList<>( Arrays.asList(1,2,3,4,5) ); 
List<Integer> numbers = new ArrayList<>(6); 
numbers.add(1);

ArrayList<String> charList = new ArrayList<>(Arrays.asList(("A", "B", "C"));
String aChar = alphabetsList.get(0);

ArrayList<Integer> digits = new ArrayList<>(Arrays.asList(1,2,3,4,5,6));

Iterator<Integer> iterator = digits.iterator();

while(iterator.hasNext()) 
{
    System.out.println(iterator.next());
}
for(int i = 0; i < digits.size(); i++) 
{
    System.out.print(digits.get(i));
}
for(Integer d : digits) 
{
    System.out.print(d);
}

sorting

public class AgeSorter implements Comparator<Employee> 
{
    @Override
    public int compare(Employee e1, Employee e2) {
        //comparison logic
    }
}

link: https://howtodoinjava.com/java-collections/

build jar with namen in maven

<build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>3.2.0</version>
                <configuration>
                    <finalName>scraper</finalName>
                </configuration>
            </plugin>
        </plugins>
    </build>

Spring Mysql One to Many....

pom.xml
- lombok
- spring-boot-starter-data-jpa
- mysql-connector-java

application.properties

# MySQL connection properties
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=username
spring.datasource.password=password
spring.datasource.url=jdbc:mysql://localhost:3306/testspring

# Log JPA queries
# Comment this in production
spring.jpa.show-sql=true

# Drop and create new tables (create, create-drop, validate, update)
# Only for testing purpose - comment this in production
spring.jpa.hibernate.ddl-auto=create-drop

# Hibernate SQL dialect
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect

ResApplication.java

public class RestApplication {

    public static void main(String[] args) {
        SpringApplication.run(RestApplication.class, args);
    }

    @Bean
    public CommandLineRunner mappingDemo(BookRepository bookRepository,
                                         PageRepository pageRepository) {
        return args -> {

            // create a new book
            Book book = new Book("Java 101", "John Doe", "123456");

            // save the book
            bookRepository.save(book);
            pageRepository.save(new Page(65, "Java 8 contents", "Java 8", book));
            pageRepository.save(new Page(95, "Concurrency contents", "Concurrency", book));
        };
    }
}

Book.java


@Entity @Table(name = "books") @Getter @Setter public class Book implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String title; private String author; @Column(unique = true) private String isbn; ```**```@JsonManagedReference```**``` @OneToMany(mappedBy = "book", fetch = FetchType.LAZY, cascade = CascadeType.ALL) private List<Page> pages = new ArrayList<Page>(); public Book() { } public Book(String title, String author, String isbn) { this.title = title; this.author = author; this.isbn = isbn; } // getters and setters, equals(), toString() .... (omitted for brevity) @Override public String toString() { return "Book{" + "id=" + id + ", title='" + title + '\'' + ", author='" + author + '\'' + ", isbn='" + isbn + '\'' + ", number of pages=" + pages.size() + '}'; } }

Pages.java


@Entity @Table(name = "pages") @Setter @Getter public class Page implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private int number; private String content; private String chapter; @JsonBackReference @ManyToOne(fetch = FetchType.LAZY, optional = false) @JoinColumn(name = "book_id", nullable = false) private Book book; public Page() { } public Page(int number, String content, String chapter, Book book) { this.number = number; this.content = content; this.chapter = chapter; this.book = book; } // getters and setters, equals(), toString() .... (omitted for brevity) @Override public String toString() { return "Page{" + "id=" + id + ", number=" + number + ", content='" + content + '\'' + ", chapter='" + chapter + '\'' + ", book=" + book.toString() + '}'; } }

BookRepository.java

public interface BookRepository extends CrudRepository<Book, Long> {

    Book findByIsbn(String isbn);
}

PageRepository.java

public interface PageRepository extends CrudRepository<Page, Long> {

    List<Page> findByBook(Book book, Sort sort);
}

BooksController.java


@RestController @RequestMapping(value = "/books", produces = MediaType.APPLICATION_JSON_VALUE) public class BooksController { private final BookRepository bookRepository; private final PageRepository pageRepository; public BooksController(BookRepository bookRepository, PageRepository pageRepository) { this.bookRepository = bookRepository; this.pageRepository = pageRepository; } @GetMapping(value = "/pages", produces = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.OK) public List<Page> pages(){ List<Page> result = (List<Page>) pageRepository.findAll(); System.out.println(result); System.out.println(result.get(0)); return result; } @GetMapping("/") public List<Book> books(){ return (List<Book>)bookRepository.findAll(); } }

http://localhost:8080/books/

[
{
"id": 1,
"title": "Java 101",
"author": "John Doe",
"isbn": "123456",
"pages": [
{
"id": 1,
"number": 1,
"content": "Introduction contents",
"chapter": "Introduction"
},
{
"id": 2,
"number": 65,
"content": "Java 8 contents",
"chapter": "Java 8"
},
{
"id": 3,
"number": 95,
"content": "Concurrency contents",
"chapter": "Concurrency"
}
]
}
]

http://localhost:8080/books/pages

[
{
"id": 1,
"number": 1,
"content": "Introduction contents",
"chapter": "Introduction"
},
{
"id": 2,
"number": 65,
"content": "Java 8 contents",
"chapter": "Java 8"
},
{
"id": 3,
"number": 95,
"content": "Concurrency contents",
"chapter": "Concurrency"
}
]

youtube dl

install youtube-dl

sudo curl -L https://yt-dl.org/downloads/latest/youtube-dl -o /usr/local/bin/youtube-dl
sudo chmod a+rx /usr/local/bin/youtube-dl

youtube-dl is replaced by yt-dlp

yt-dlp -x --audio-format mp3 --audio-quality 0 "$1" | awk '{gsub(/\[[^]]*\]/,""); print}'
alias yt='function _yt() { yt-dlp -x --audio-format mp3 --audio-quality 0 "$1" | awk "{gsub(/\\[[^\\]]*\\]/,\"\"); print}"; }; _yt'

mp3

youtube-dl --extract-audio --audio-format mp3 URL-vid

playlist

youtube-dl --extract-audio --audio-format mp3 -o "%(title)s.%(ext)s" URL-playlist
youtube-dl -cit --extract-audio --audio-format mp3 URL-playlist
Tags: 

Javafx

Download the appropriate JavaFX SDK for your operating system and unzip it to a desired location, for instance /Users/your-user/Downloads/javafx-sdk-11.

Create a JavaFX project

Create a JavaFX project Provide a name to the project, like HelloFX, and a location. When the project opens, the JavaFX classes are not recognized. enter image description here

Set JDK 11

Go to File -> Project Structure -> Project, and set the project SDK to 11. You can also set the language level to 11. Set JDK 11 enter image description here

Create a library

Go to File -> Project Structure -> Libraries and add the JavaFX 11 SDK as a library to the project. Point to the lib folder of the JavaFX SDK. enter image description here

Once the library is applied, the JavaFX classes will be recognized by the IDE. enter image description here

Warning: If you run now the project it will compile but you will get this error:

Error: JavaFX runtime components are missing, and are required to run this application

This error is shown since the Java 11 launcher checks if the main class extends javafx.application.Application. If that is the case, it is required to have the javafx.graphics module on the module-path.

Add VM options

To solve the issue, click on Run -> Edit Configurations... and add these VM options:

--module-path %PATH_TO_FX% --add-modules=javafx.controls,javafx.fxml

Note that the default project created by IntelliJ uses FXML, so javafx.fxml is required along with javafx.controls. If your project uses other modules, you will need to add them as well. enter image description here Click apply and close the dialog.

Run the project

Click Run -> Run... to run the project, now it should work fine.

maven start

<properties>
      <maven.compiler.source>1.14</maven.compiler.source>
      <maven.compiler.target>1.14</maven.compiler.target>
   </properties>

Tags: 

Add new remote on github from cli

curl -u 'USER' https://api.github.com/user/repos -d '{"name":"PROJNAME"}'

Windows cli check for running at port 1234

netstat -ano | findstr :<PORT>
tskill typeyourPIDhere 
or taskkill /PID 14328 /F

Arrays

Declare Array
let products = [];
let todos = new Array();
The recommended way is to use [] notation to create arrays.

Merge Two Arrays by concat() method
let array1 = [1,2,3];
let array2 = [4,5,6];
let merged = array1.concat(array2);
console.log(merged);
// expected output: Array [1,2,3,4,5,6]
The concat() method is used to merge two or more arrays. This method returns a new array instead to changing the existing arrays.

ES6 Ways to merge two array
let array1 = [1,2,3];
let array2 = [4,5,6];
let merged = [...array1, ...array2];
console.log(merged);
// expected output: Array [1,2,3,4,5,6]
Get the length of Array
To get the length of array or count of elements in the array we can use the length property.

let product = [1,2,3];
product.length // returns 3
Adding items to the end of an array
Let us add some items to the end of an array. We use the push() method to do so.

let product = ['apple', 'mango'];
product.push('banana');
console.log(projects);
// ['apple', 'mango', 'banana']
Adding items to the beginning of an array
let product = ['apple', 'mango'];
product.unshift('banana');
console.log(projects);
// ['banana', 'apple', 'mango']
Adding items to the beginning of an array in ES6
let product = ['apple', 'mango'];
product = ['banana', ...product];
console.log(projects);
// ['banana', 'apple', 'mango']
Adding items to the end of an array ES6
let product = ['apple', 'mango'];
product = [...product, 'banana'];
console.log(projects);
// ['apple', 'mango', 'banana']
Remove first item from the array
The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array. It returns undefined if the array is empty.

let product = ['apple', 'mango', 'banana'];
let firstValue= product.shift();
console.log(firstValue); // ['mango', 'banana'];
console.log(firstValue); // apple
Remove portion of an array
JavaScript give us slice method to cut the array from any position. The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.

arr.slice([begin[, end]])
Example
var elements = ['Task 1', 'Task 2', 'Task 3', 'Task 4', 'Task 5'];

elements.slice(2) //["Task 3", "Task 4", "Task 5"]
elements.slice(2,4) // ["Task 3", "Task 4"]
elements.slice(1,5) // ["Task 2", "Task 3", "Task 4", "Task 5"]
Remove /adding portion of an array -> splice() method
The splice() method changes the contents of an array by removing existing elements and/or adding new elements. Be careful, splice() method mutates the array.

A detailed reference here at MDN splice method.

array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
Parameters
startIndex at which to start changing the array (with origin 0).

deleteCount (Optional)An integer indicating the number of old array elements to remove.

item1, item2, ... (Optional)The elements to add to the array, beginning at the start index. If you don’t specify any elements, splice() will only remove elements from the array.

Return value
An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.

var months = ['Jan', 'March', 'April', 'June'];months.splice(1, 0, 'Feb');
// inserts at 1st index positionconsole.log(months);
// expected output: Array ['Jan', 'Feb', 'March', 'April', 'June']months.splice(4, 1, 'May');
// replaces 1 element at 4th indexconsole.log(months);
// expected output: Array ['Jan', 'Feb', 'March', 'April', 'May']
Remove last item from the array -> pop() method
The pop() method removes the last element from an array and returns that element. This method changes the length of the array.

var elements = ['Task 1', 'Task 2', 'Task 3'];
elements.pop() // 'Task 3'
console.log(elements) // ['Task 1', 'Task 2'];
Joining arrays -> Join () method
The join() method joins all elements of an array (or an array-like object) into a string and returns this string. This is a very useful method.

var elements = ['Task 1', 'Task 2', 'Task 3'];console.log(elements.join());
// expected output: Task 1,Task 2,Task 3console.log(elements.join(''));
// expected output: Task 1Task 2Task3console.log(elements.join('-'));
// expected output: Task 1-Task 2-Task 3
Looping through array
There are various ways to loop through an array. Let’s see the simple example first.

Looping through array — forEach Loop
The forEach loop takes a function, a normal or arrow and gives access to the individual element as a parameter to the function. It takes two parameters, the first is the array element and the second is the index.

let products = ['apple', 'mango'];
products.forEach((e) => {
console.log(e);
});
// Output
// apple
// mango
let products = ['apple', 'mango'];
products.forEach(function (e) {
console.log(e);
});
// Output
// apple
// mango
Let’s see how we can access the index in forEach. Below I am using the arrow function notation, but will work for es5 function type as well.

products .forEach((e, index) => {
console.log(e, index);
});

// Output
// apple 0
// mango 1
Finding Elements in an array — find method
The find() method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.

The syntax is given below.

callback — Function to execute on each value in the array, taking three arguments
***** element — The current element being processed in the array
***** index (optional) — The index of the current element
***** array (optional) — The array find was called upon.
thisArg (optional) — Object to use as this when executing callback.
Return value
A value in the array if any element passes the test; otherwise, undefined.

arr.find(callback[, thisArg])var data = [51, 12, 8, 130, 44];var found = data.find(function(element) {
return element > 10;
});console.log(found); // expected output: 51
Looping through an array — for in Loop
A for...in loop only iterates over enumerable properties and since arrays are enumerable it works with arrays.

The loop will iterate over all enumerable properties of the object itself and those the object inherits from its constructor’s prototype (properties closer to the object in the prototype chain override prototypes’ properties).

More reading at MDN for in loop

let products = ['apple', 'mango'];
for(let index in products) {
console.log(projects[index]);
}

// Output
// apple
// mango
Note in the above code, a new index variable is created every time in the loop.

Looping through array — map function ()
The map() function allows us to transform the array into a new object and returns a new array based on the provided function.

It is a very powerful method in the hands of the JavaScript developer.

NOTE: Map always returns the same number of output, but it can modify the type of output. For example, if the array contains 5 element map will always return 5 transformed element as the output.

let num = [1,2,3,4,5];
let squared = num.map((value, index, origArr) => {
return value * value;
});
The function passed to map can take three parameters.

squared — the new array that is returned
num — the array to run the map function on
value — the current value being processed
index — the current index of the value being processed
origArr — the original array
Map () — Example 1 — Simple
let num = [1,2,3,4,5];let squared = num.map((e) => {
return e * e;
});
console.log(squared); // [1, 4, 9, 16, 25]
In the above code, we loop through all elements in the array and create a new array with the square of the original element in the array.

A quick peek into the output.

Map () — Example 2— Simple Transformation
Let us take an input object literal and transform it into key-value pair.

For example, let’s take the below array

let projects = ['Learn Spanish', 'Learn Go', 'Code more'];
and transform into key-value pair as shown below.

{
0: "Learn Spanish",
1: "Learn Go",
2: "Code more"
}
Here is the code for the above transformation with the output.

let newProjects = projects.map((project, index) => {
return {
[index]: project
}
});
console.log(newProjects); // [{0: "apple"}, {1: "mango"},]
Map () — Example 3 — Return a subset of data
Lets take the below input

let tasks = [
{ "name": "Learn Angular",
"votes": [3,4,5,3]
},
{ "name": "Learn React",
"votes": [4,4,5,3]
},
];
The output that we need is just the name of the tasks. Let’s look at the implementation

let taskTitles = tasks.map((task, index, origArray) => {
return {
name: task.name
}
});

console.log(taskTitles); //
Looping through an array — filter function ()
Filter returns a subset of an array. It is useful for scenarios where you need to find records in a collection of records. The callback function to filter must return true or false. Return true includes the record in the new array and returning false excludes the record from the new array.

It gives a new array back.

Let’s consider the below array as an input.

let tasks = [
{ "name": "Learn Angular",
"rating": 3
},
{ "name": "Learn React",
"rating": 5
},
{ "name": "Learn Erlang",
"rating": 3
},
{ "name": "Learn Go",
"rating": 5
},];
Now lets use the filter function to find all tasks with a rating of 5.

Let’s peek into the code and the result.

let products = [
{
"name" : "product 1",
"rating" : 5
},
{
"name" : "product 2",
"rating" : 4
},
{
"name" : "product 3",
"rating" : 5
},
{
"name" : "product 4",
"rating" : 2
}
];
let filteredProducts = products.filter((product) => {
return product.rating === 5;
});
console.log( filteredProducts );
// [{"name" : "product 1","rating" : 5},{"name" : "product 3", "rating" : 5}]
Since we are only using one statement in the filter function we can shorten the above function as shown below.

tasks.filter(task => task.rating === 5);
NOTE: Filter function cannot transform the output into a new array.

Looping through an array — reduce function ()
Reduce function loops through array and can result a reduced set. It is a very powerful function, I guess, more powerful than any other array methods (though every method has its role).

From MDN, The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

Reduce — Simple Example — 1
const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer)); // expected output: 10// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15
Note: The first time the callback is called, accumulator and currentValue can be one of two values. If initialValue is provided in the call to reduce(),

then accumulator will be equal to initialValue, and currentValue will be equal to the first value in the array. If no initialValue is provided, then accumulator will be equal to the first value in the array, and currentValue will be equal to the second.

The reason reduce is very powerful is because just with reduce() we can implement our own, map(), find() and filter() methods.

Using reduce to categorize data
Assume you have the below data structure which you would like to categorize into male and female dataset.

let data = [
{name: "Raphel", gender: "male"},
{name: "Tom", gender: "male"},
{name: "Jerry", gender: "male"},
{name: "Dorry", gender: "female"},
{name: "Suzie", gender: "female"},
{name: "Dianna", gender: "female"},
{name: "Prem", gender: "male"},
];
And we would like the output to be as below

{"female" : [
{name: "Dorry", gender:"female"},
{name: "Suzie", gender: "female"},
{name: "Dianna", gender: "female"},
],
"male" : [
{name: "Raphel", gender:"male"},
{name: "Tom", gender:"male"},
{name: "Jerry", gender:"male"},
{name: "Prem", gender:"male"},
]
}
So, lets get to the code and understand how to achieve the above categorization.

let genderwise = data.reduce((acc,item, index) => {
acc[item.gender].push(item);
return acc;
}, {male: [], female:[]});console.log(genderwise);
The important point above is the reduce function can be initialized with any type of starting accumulator, in the above case an object literal containing

{ male: [], female: []}
I hope this is sufficient to demonstrate the power of reduce method.

Using reduce to implement custom map() function
function map(arr, fn) {
return arr.reduce((acc, item) => [...acc, fn(item)], []);
}
The above is the implementation of custom map function. In the above function we are passing empty array [] as the initial value for the accumulator and the reduce function is returning a new array with the values from the accumulator spread out and appending the result of invoking the callback function with the current item.

Using reduce to implement custom filter() function
Let’s implement the filter() method using reduce().

function filter (arr, fn) {
return arr.reduce(function (acc, item, index) {
if (fn(item, index)) {
acc.push(item);
}
return acc;
},[]);
}
Let’s see the usage and the output below. I could have overwritten the original Array.prototype.filter, but am doing so to avoid manipulating built-in methods.

Using reduce to implement custom forEach function
Let us know implement our own forEach function.

function forEach(arr, fn) {
arr.reduce((acc, item, index) => {
item = fn(item, index);
}, []);
}
The implementation is very simple compared to other methods. We just grab the passed in array and invoke the reduce, and return the current item as a result of invoking the callback with the current item and index.

Using reduce to implement custom pipe() function
A pipe function sequentially executes a chain of functions from left to right. The output of one function serves as the input to the next function in the chain.

Implementation of pipe function

function pipe(...fns) {
// This parameters to inner functions
return function (...x) {
return fns.reduce((v, f) => {
let result = f(v);
return Array.isArray(result) ? result: [result];
},x)
}
}
Usage
const print = (msg) => {
console.log(msg);
return msg;
}
const squareAll = (args) => {
let result = args.map((a) => {
return a * a;
});
return result;
}
const cubeAll = (args) => {
let result = args.map((a) => {
return a * a * a;
});
return result;
}
pipe(squareAll,cubeAll, print)(1,2,3); // outputs => [1, 64, 729]

Holes in arrays
Holes in arrays means there are empty elements within the array. This may be because of couples of operations like delete or other operations that left these holes accidentally.

Now having ‘holes’ in an array is not good from a performance perspective. Let us take an example below.

let num = [1,2,3,4,5]; // No holes or gapsdelete num[2]; // Creates holesconsole.log (num); [1, 2, empty, 4, 5]
So, do not use delete method on array, unless you know what you are doing. delete method doesn’t alter the length of the array.

You can avoid holes in an array by using the array methods splice(), pop() or shift() as applicable.

Changing array length and holes
You can quickly change the length of the array as below.

let num = [1,2,3,4,5]; // length = 5;
num.length = 3; // change length to 3//The below logs outputs
// [1,2,3] -> The last two elements are deleted
console.log(num);
Now, increasing the length this way creates holes.

let num = [1,2,3,4,5];num.length = 10; // increase the length to 10
console.log(num); // [1, 2, 3, empty × 10]
Quickly Fill Arrays
Let’s take a look at how to quickly fill or initialize an array.

The Array.prototype.fill() method
The fill method (modifies) all the elements of an array from a start index (default zero) to an end index (default array length) with a static value. It returns the modified array.

Description
The fill method takes up to three arguments value, start and end. The start and endarguments are optional with default values of 0 and the length of the this object.

If start is negative, it is treated as length+start where length is the length of the array. If end is negative, it is treated as length+end.

fill is intentionally generic, it does not require that its this value be an Array object.

fill is a mutable method, it will change this object itself, and return it, not just return a copy of it.

When fill gets passed an object, it will copy the reference and fill the array with references to that object.

Example 1 — Simple fill
new Array(5).fill(“hi”)
//Output => (5) [“hi”, “hi”, “hi”, “hi”, “hi”]
Example 2 — Fill with object
new Array(5).fill({'message':'good morning'})
// Output
// [{message: "good morning"}, {message: "good morning"} , {message: "good morning"} , {message: "good morning"} , {message: "good morning"}]
Example 3 — Generate sequence
Array(5).fill().map((v,i)=>i);
The output will be

[0,1,2,3,4,5]
Example 4— More examples
[1, 2, 3].fill(4); // [4, 4, 4]
[1, 2, 3].fill(4, 1); // [1, 4, 4]
[1, 2, 3].fill(4, 1, 2); // [1, 4, 3]
[1, 2, 3].fill(4, 1, 1); // [1, 2, 3]
[1, 2, 3].fill(4, 3, 3); // [1, 2, 3]
[1, 2, 3].fill(4, -3, -2); // [4, 2, 3]
[1, 2, 3].fill(4, NaN, NaN); // [1, 2, 3]
[1, 2, 3].fill(4, 3, 5); // [1, 2, 3]
Array(3).fill(4); // [4, 4, 4]
The Array.from method (static method)
The Array.from() function is an inbuilt function in JavaScript which creates a new array instance from a given array. In case of a string, every alphabet of the string is converted to an element of the new array instance and in case of integer values, new array instance simple take the elements of the given array.

Syntax

Array.from(object, mapFunction, thisValue)
Example 1 — Simple example
console.log(Array.from('foo'));
The output will be

["f", "o", "o"]
Example 2 — Object length
Array.from({ length: 5 });
The output will be

[undefined, undefined, undefined, undefined, undefined]

Tags: 

Spotlight

problems with indexing , not indexing, stopped indexing.

1)

  • Enable Indexing – sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.metadata.mds.plist
  • Disable Indexing – sudo launchctl unload -w /System/Library/LaunchDaemons/com.apple.metadata.mds.plist

2)
Open Terminal
Type - not copy! - the following but wait a few second between them:

sudo mdutil -i off /
sudo mdutil -i on /
sudo mdutil -E /

If, after a few minutes, Spotlight is still not indexing, try running this command, followed by the three commands above:
sudo rm -rf /.Spotlight-V100

Cleanup simulators

xcrun simctl shutdown all  
xcrun simctl erase all  
xcrun simctl delete unavailable  
Tags: 

Swift App from Terminal

ObjC article by chris eidhof

// Run any SwiftUI view as a Mac app.

import Cocoa
import SwiftUI

NSApplication.shared.run {
    VStack {
        Text("Hello, World")
            .padding()
            .background(Capsule().fill(Color.blue))
            .padding()
    }
    .frame(maxWidth: .infinity, maxHeight: .infinity)

}

extension NSApplication {
    public func run<V: View>(@ViewBuilder view: () -> V) {
        let appDelegate = AppDelegate(view())
        NSApp.setActivationPolicy(.regular)
        mainMenu = customMenu
        delegate = appDelegate
        run()
    }
}

// Inspired by https://www.cocoawithlove.com/2010/09/minimalist-cocoa-programming.html

extension NSApplication {
    var customMenu: NSMenu {
        let appMenu = NSMenuItem()
        appMenu.submenu = NSMenu()
        let appName = ProcessInfo.processInfo.processName
        appMenu.submenu?.addItem(NSMenuItem(title: "About \(appName)", action: #selector(NSApplication.orderFrontStandardAboutPanel(_:)), keyEquivalent: ""))
        appMenu.submenu?.addItem(NSMenuItem.separator())
        let services = NSMenuItem(title: "Services", action: nil, keyEquivalent: "")
        self.servicesMenu = NSMenu()
        services.submenu = self.servicesMenu
        appMenu.submenu?.addItem(services)
        appMenu.submenu?.addItem(NSMenuItem.separator())
        appMenu.submenu?.addItem(NSMenuItem(title: "Hide \(appName)", action: #selector(NSApplication.hide(_:)), keyEquivalent: "h"))
        let hideOthers = NSMenuItem(title: "Hide Others", action: #selector(NSApplication.hideOtherApplications(_:)), keyEquivalent: "h")
        hideOthers.keyEquivalentModifierMask = [.command, .option]
        appMenu.submenu?.addItem(hideOthers)
        appMenu.submenu?.addItem(NSMenuItem(title: "Show All", action: #selector(NSApplication.unhideAllApplications(_:)), keyEquivalent: ""))
        appMenu.submenu?.addItem(NSMenuItem.separator())
        appMenu.submenu?.addItem(NSMenuItem(title: "Quit \(appName)", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q"))

        let windowMenu = NSMenuItem()
        windowMenu.submenu = NSMenu(title: "Window")
        windowMenu.submenu?.addItem(NSMenuItem(title: "Minmize", action: #selector(NSWindow.miniaturize(_:)), keyEquivalent: "m"))
        windowMenu.submenu?.addItem(NSMenuItem(title: "Zoom", action: #selector(NSWindow.performZoom(_:)), keyEquivalent: ""))
        windowMenu.submenu?.addItem(NSMenuItem.separator())
        windowMenu.submenu?.addItem(NSMenuItem(title: "Show All", action: #selector(NSApplication.arrangeInFront(_:)), keyEquivalent: "m"))

        let mainMenu = NSMenu(title: "Main Menu")
        mainMenu.addItem(appMenu)
        mainMenu.addItem(windowMenu)
        return mainMenu
    }
}

class AppDelegate<V: View>: NSObject, NSApplicationDelegate, NSWindowDelegate {
    init(_ contentView: V) {
        self.contentView = contentView

    }
    var window: NSWindow!
    var hostingView: NSView?
    var contentView: V

    func applicationDidFinishLaunching(_ notification: Notification) {
        window = NSWindow(
            contentRect: NSRect(x: 0, y: 0, width: 480, height: 300),
            styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
            backing: .buffered, defer: false)
        window.center()
        window.setFrameAutosaveName("Main Window")
        hostingView = NSHostingView(rootView: contentView)
        window.contentView = hostingView
        window.makeKeyAndOrderFront(nil)
        window.delegate = self
        NSApp.activate(ignoringOtherApps: true)
    }
}

Pages

Subscribe to hjsnips RSS