Thursday, December 22, 2022

RxJS mergeMap

 flatMap is deprecated and replaced by mergeMap

import { of, mergeMap, interval, map, take } from 'rxjs';

const letters = of('a', 'b', 'c');
const result = letters.pipe(
mergeMap((x) =>
interval(1000).pipe(
take(4),
map((i) => x + i)
)
)
);

result.subscribe((x) => console.log(new Date().toISOString()x));

// Results in the following:
// a0
// b0
// c0
// a1
// b1
// c1

RxJS switchmap example

 RxJS switchmap example, easy to understand

https://stackblitz.com/edit/rxjs-switchmap-example-1-vslesu?file=index.ts

import { interval } from 'rxjs';
import { take, switchMap, map, flatmap } from 'rxjs/operators';

let outer$ = interval(5000).pipe(take(2));

let combined$ = outer$.pipe(
switchMap((x) => {
return interval(2000).pipe(
take(3),
map((y) => `outer ${x}: inner ${y}`)
);
})
);

/*
5 seconds: the inner observable is started
7 seconds: 0 0
9 seconds: 0 1
10 seconds (now the second outer$ comes, the inner observable is unsubscribed)
12 seconds: 1 0
14 seconds: 1 1
16 seconds: 1 2
*/

console.log(new Date().toISOString());
combined$.subscribe((result) =>
console.log(new Date().toISOString() + ' ' + `${result}`)
);


Wednesday, December 14, 2022

rxjs note - Angular - The Complete Guide

 

1. 

  1. In order to follow along smoothly with the course examples, make sure you install RxJS v6 by running

    In addition, also install the rxjs-compat package:

  2. To get discount on Max's courses, go to https://academind.com/courses
  3. 3.
  4. https://www.learnrxjs.io/
  5. 4.
  6. Use Subject instead of EventEmitter, emit->subject.next
  7. 5.

typescript

 Type script:

//union type
let course: string | number = 'Complete guide';
course = 1234;

//type alias
type Person = {
name: string,
age: number;
}
let person: Person;

//generics
function insertAtBeginning(origArray: any[],value: any){
const newArray = [value,...origArray];
return newArray;
}

const demoArray = [1,2,3];
const upadtedArray = insertAtBeginning(demoArray,-1);
upadtedArray[0].split('');

//to
function insertAtBeginning2<T>(origArray: T[],value: T){
const newArray = [value,...origArray];
return newArray;
}

const demoArray2 = [1,2,3];
const upadtedArray2 = insertAtBeginning2(demoArray,-1);
upadtedArray2[0].split(''); //error detected


let idStr: string = "2";
const id = +idStr;
console.log(id*8);

this.isAuthenticated = !user : false : true;
equals
this.isAuthenticated = !!user;

Monday, December 12, 2022

bootstrap

 1. bootstrap grid

https://mdbootstrap.com/learn/mdb-foundations/bootstrap/grid-system/

for the grid to work properly, you should always place columns in rows, and rows in containers.

Bootstrap grid allows you to add up to 12 columns in one line. If you add more than 12, the excess column will jump to the next line.

Breakpoints are the triggers in Bootstrap for how your layout responsive changes across device or viewport sizes.

<div class="container">

  <div class="row">

    <div class="col-md-4">First column</div>

    <div class="col-md-8">Second column</div>

  </div>

</div>

All we have to do is add a breakpoint -md (meaning "medium screen size") to the col class, so that the Bootstrap grid knows that we want 4/8 columns ratio only on screens bigger than medium size, and on other screens (medium and small size) the columns should be stretched to full width.

To sum up - by using class col-md-4, we tell grid the following command:

  1. On screens smaller than 768px, I want this column to stretch to full width
  2. On screens larger than 768px, I want this column to be 4 units wide
2. Forms
https://mdbootstrap.com/learn/mdb-foundations/bootstrap/forms/
Login forms

3.
could be interview question
how to control how many instances when service is injected? Say component constructor injected one log service, another component injected the log service? How to make them share the same instance?
providers, injectable

Angular - The Complete Guide Section 5 note

 @Input('srvElement') element : {type: string, name: string, content: string};

<app-server-element *ngFor="let serverElement of serverElements"

[srvElement]="serverElement"></app-server-element>


Go the error "ERR_OSSL_EVP_UNSUPPORTED"

  opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],

  library: 'digital envelope routines',

  reason: 'unsupported',

  code: 'ERR_OSSL_EVP_UNSUPPORTED'

when run "ng serve"

The fix is:

export NODE_OPTIONS=--openssl-legacy-provider
https://stackoverflow.com/questions/69394632/webpack-build-failing-with-err-ossl-evp-unsupported

Sunday, December 11, 2022

Angular - The complete Guide Section 1 and 2 note

 package.json: the project dependencies


<input type="text" [(ngModel)]="name">
<p>{{ name }}</p>

npm install --save bootstrap
"styles": [
"node_modules/bootstrap/dist/css/bootstrap.min.css",
"src/styles.css"
],
dev tool->sources->styles.css: Bootstrap v5.2.3

<div>
<button class="btn btn-primary" (click)="onToggleDisplay()">Display Details</button>
<p *ngIf="showSecret">Secret Password = tuna</p>
<div *ngFor="let logItem of log;let idx=index"
[ngStyle]="{backgroundColor:(idx+1)>5?'green':'transparent'}"
[ngClass]="{'white-text':(idx+1)>5}"> {{logItem}} </div>
</div>

export class AppComponent {
showSecret: boolean = false;
log = [];

onToggleDisplay(){
this.showSecret = !this.showSecret;
this.log.push(new Date());
}
}

Sunday, November 13, 2022

mac os ventura

Updated to mac os ventura today, for the photos app (remove duplicate), and iphone can be used as mac webcam.

Before the upgrade, checked the parallel desktip website that PD17 also supports Ventura.

After the upgrade, found some issues:

0. The OS startup becomes slower so the user has chance to close the auto lock script. I need to auto login and then lock the OS to run some backgroud tasks.

1. Cannot set the scheduled start time/shutdown time from energy center. Although it seems it can set through command line and my previous setting is still available.


2. To enter recovery mode, Command+R doesn't work any more. Can trigger it by keep pressing the power button (for mac mini m1). The option is better but it's even better to keep the previous way.

3. Time machine cannot restore to the previous OS any more. It's a big downgrade.

4. After upgrade to Ventura, I verified PD17.1.4 worked well and then upgraded PD to PD17.1.5. The auto login cannot work as expected after the upgrade. Luckily I have the PD17.1.4 time machine backup. After revert to PD17.1.4, the auto login works well.




5. Also, my Ventura cannot show the bluetooth battery level, from the control center or the bluebooth settings.


As a pro developer, the lession is that the users should not upgrade unless they have no option. The product is added a lot of functions because a lot of reason, the root cause maybe not for the user, but for the product manager, the developer and the company.

Friday, October 28, 2022

A bad design example - change apple id country/region

I tried to change my apple id country/region, but got a prompt to say I need to cancel my apple music subsciption.

The apple music subscription (free) is already cancelled, but it only expires next month. 

From the google search, can only request apple support to do it.

https://discussions.apple.com/thread/7634200 

The normal cancellation does not take effect until the auto-renewal is due. To request an immediate cancellation, contact iTunes Customer Service:

Contact - Official Apple Support


I contacted the apple support and got it done immediately. The support actually has no idea she can cancel it immediately unless I shared the related information.


It's a bad design example, gives the user bad experience and waste a lot of apple resource. It should have an option to warn the user and let the user proceed. Or the better way is no need to cancel the subscription, when the user change the country/region back, the subscription can come back.







Tuesday, September 20, 2022

The complete book on angular 11 - Chapter 5 Built-in Directives

 The complete book on angular 11 - Chapter 5 Built-in Directives

1.

A FormControl represents a single input field - it is the smallest unit of an Angular

form.

FormControls encapsulate the field’s value, and states such as being valid, dirty

(changed), or has errors.

2.

the FormsModule gives us template driven directives such as:

• ngModel and

• NgForm

Whereas ReactiveFormsModule gives us reactive driven directives like

formControl and

• ngFormGroup

3.

<form #f="ngForm" (ngSubmit)="onSubmit(f.value)">

The #v="thing" syntax says that we want to create a

local variable for this view.

4.

Validaor

<div class="field"

[class.error]="!sku.valid && sku.touched">

 <label for="skuInput">SKU</label>

 <input type="text"

 id="skuInput"

 placeholder="SKU"

 [formControl]="sku">

 <div *ngIf="!sku.valid"

 class="ui error message">SKU is invalid</div>

 <div *ngIf="sku.hasError('required')"

 class="ui error message">SKU is required</div>

 </div>

Thursday, September 15, 2022

The complete book on angular 11 - Chapter 4 Built-in Directives

 The complete book on angular 11 - Chapter 4 Built-in Directives

1. ngSwitch

<div class="container" [ngSwitch]="myVar">

<div *ngSwitchCase="'A'">Var is A</div>

<div *ngSwitchCase="'B'">Var is B</div>

<div *ngSwitchDefault>Var is something else</div>

</div>

2. NgStyle

<div [style.background-color]="'yellow'">

Uses fixed yellow background

</div>

<div [ngStyle]="{color: 'white', 'background-color': 'blue'}">

Uses fixed white text on blue background

</div>

3. ngClass

<div [ngClass]="{bordered: false}">This is never bordered</div>

4. ngNonBindable

<div class='ngNonBindableDemo'>

<span class="bordered">{{ content }}</span>

<span class="pre" ngNonBindable>

&larr; This is what {{ content }} rendered

</span>

</div>

TODO Forms in Angular

Wednesday, September 14, 2022

The complete book on angular 11 - Chapter 3 How Angular Works

 Chapter 3 How Angular Works

1.

We’ve provided the entire, completed application in the code download folder under

how-angular-works/inventory-app.

2.

The @Component is called a decorator.

The Component controller is defined by a class.

<h1>{{ product.name }}</h1> //Using the {{…}} syntax is called template binding.

What’s neat about template binding is that the code inside the brackets is an

expression. That means you can do things like this:

• {{ count + 1 }}

• {{ myFunction(myArguments) }}

3.

When we use products-list we’re using a key feature of Angular components:

inputs and outputs:

<products-list

[productList]="products" <!-- input -->

(onProductSelected)="productWasSelected($event)"> <!-- output -->

</products-list>

The [squareBrackets] pass inputs and the (parentheses) handle outputs.

Data flows in to your component via input bindings and events flow out of your

component through output bindings.

(onProductSelected)="productWasSelected($event)": We’re saying that we want to listen to the onProductSelected output from the

ProductsList component.

import {

Component,

EventEmitter,

Input,

Output

} from '@angular/core';

import { Product } from '../product.model';

/**

* @ProductsList: A component for rendering all ProductRows and

* storing the currently selected Product

*/

@Component({

selector: 'products-list',

templateUrl: './products-list.component.html'

})

export class ProductsListComponent {

/**

* @input productList - the Product[] passed to us

*/

@Input() productList: Product[];

/**

* @output onProductSelected - outputs the current

* Product whenever a new Product is selected

*/

@Output() onProductSelected: EventEmitter<Product>;

we can listen to an event by using the (output)="action" syntax.

4.

<my-component [shortName]="myName" [oldAge]="myAge"></my-component>

@Input("shortName") name: string;

@Input("oldAge") age: number;

5.

To create a custom output event we do three things

1. Specify outputs in the @Component configuration

2. Attach an EventEmitter to the output property

3. Emit an event from the EventEmitter, at the right time

An EventEmitter is an object that helps you implement the Observer

Pattern. That is, it’s an object that will:

1. maintain a list of subscribers and

2. publish events to them.

Here’s a short and sweet example of how you can use EventEmitter

let ee = new EventEmitter(); 

ee.subscribe((name: string) => console.log(Hello ${name})); 

ee.emit(“Nate”);

// -> “Hello Nate”

6.

The line [class.selected]="isSelected(myProduct)" is a fun one: Angular allows

us to set classes conditionally on an element using this syntax. This syntax says

“add the CSS class selected if isSelected(myProduct) returns true.”

7.

@HostBinding('attr.class') cssClass = 'item';

we’re saying that we want to attach the CSS class item to the host element.

TODO Built-in Directives

The complete book on angular 11 - Chapter 2 TypeScript

 Chapter 2 TypeScript

1. 

npm install -g typescript

npm install -g tsun (TypeScript Upgraded Node)

tsun

> var fullName: string = 'Nate Murray'

> console.log(fullName)

var jobs: Array<string> = ['IBM', 'Microsoft', 'Google']; equals with the below

var jobs: string[] = ['Apple', 'Dell', 'HP'];

enum Role {Employee, Manager, Admin};

var role: Role = Role.Employee;

console.log('Roles: ', Role[0], ',', Role[1], 'and', Role[2]);

any is the default type if we omit typing for a given variable. Having a variable of

type any allows it to receive any kind of value.

var something: any = 'as string';

something = 1;

something = [1, 2, 3];

2. 

//ES5-like example

var data = ['Alice Green', 'Paul Pfifer', 'Louis Blakenship'];

data.forEach(function(line) { console.log(line); });

However with the fat arrow => syntax we can instead rewrite it like so:

// Typescript example

var data: string[] = ['Alice Green', 'Paul Pfifer', 'Louis Blakenship'];

data.forEach( (line) => console.log(line) );

Parentheses are optional when there’s only one parameter.

data.forEach( line => console.log(line) );

3.

var firstName = "Nate";

var lastName = "Murray";

// interpolate a string (enclose your string in backticks)

var greeting = `Hello ${firstName} ${lastName}`;

console.log(greeting);

TODO: page 121

Sunday, September 11, 2022

The complete book on angular 11 - Chapter 1 Writing Your First Angular Web Application

Chapter 1: Writing Your First Angular Web Application


1. To get help, go to community chat room:

https://newline.co/discord/ng-book

https://github.com/srdeleon/angular-reddit ?

2.

To get started with Angular, you’ll need to have Node.js installed.

The Node Package Manager (npm for short) is installed as a part of Node.js.

To check, run

npm -v

Once you have Node.js setup, the next step is to install TypeScript.

npm install -g typescript

tsc -v

Install Angular CLI:

npm install -g @angular/cli

Once it’s installed you’ll be able to run it from the command line using the ng

command.

ng help

3.

ng new angular-hello-world

ng serve/ng serve --port 9001

ng will look at the file angular.json to find the entry point to our app.

angular.json specifies a "main" file, which in this case is main.ts

main.ts is the entry-point for our app and it bootstraps our application

We use the AppModule to bootstrap the app. AppModule is specified in src/app/app.module.ts

AppModule specifies which component to use as the top-level component. In this case it is AppComponent

4.

ng generate component hello-world

Using backticks `` for multiline strings makes it easy to put templates inside your code files.

5.

<ul>

    <li *ngFor="let name of names">Hello {{ name }}</li>

</ul>

6.

@Input() name: string | undefined;


<ul>

    <li *ngFor="let individualUserName of names">

        <app-user-item [name]="individualUserName"></app-user-item>

    </li>

</ul>

7.

ng new angular-reddit

Notice that in the input tags we used the # (hash) to tell Angular to assign those tags

to a local variable. By adding the #newtitle and #newlink to the appropriate <input/> elements, we can pass 

them as variables into the addArticle() function on the button!

console.log(`Adding article title: ${title.value} and link: ${link.value}`);

8.

@HostBinding('attr.class') cssClass = 'row';

9.

JavaScript, by default, propagates the click event to all the parent components.

Because the click event is propagated to parents, our browser is trying to follow the

empty link, which tells the browser to reload.

To fix that, we need to make the click event handler to return false

10.

The votes parameter is optional (denoted by

the ? at the end of the name) and defaults to zero.

    constructor(title: string,link: string, votes?: number){

        this.title = title;

        this.link = link;

        this.votes = votes || 0;

    }

11.

ng build --prod -> deprecated and removed

ng build --configuration production

Thursday, September 8, 2022

RxJS and NgRx

1. RxJS

2. NgRx

Each reducer function is a listener of actions.
 


Tuesday, August 2, 2022

会攻打台湾吗?

https://www.zhihu.com/question/546647347

有很大可能借此收复台湾。平时调兵遣将容易引起注意和怀疑,此时可以随意调动和部署军队。把台湾团团围住,都不会有人在意。信息如此透明公开,都能做到出其不意。

  1. 1. 反正也主要靠内循环了,不怕制裁。
  2. 2 可以和俄罗斯抱团。
  3. 3. 有利于树立威信、巩固政权。
  4. 4. 美军刚走,敌人紧张了几天,最松懈的时候。

  5. 要是不准备采取有效行动,应该不会舆论宣传做这么足,而且放任各平台讨论。很难有比这更好的机会了。股市关注航天发展、长城军工,回调可以买入。




Wednesday, June 22, 2022

interview

 

1. How to log all the requests and responses for all restful APIs?

2. How to log all the requests and responses for the SOAP web services?

3. How to disable the log in PRD?

Spring cloud config

context-path for JBoss/Spring boot

what's the advantage/disadvantage of Spring boot?

what's CORS, how would you in Spring boot?

Exception Spring boot

Spring Session + Redis 来实现 session 共享 micro services

RestTemplate/Apache http client/webclient (spring 5)

How and why you can get a POJO object instead of a String?

Say you developed a new endpoint, how do you test it? If there's unexpected issue, how would you debug/fix?


Friday, June 10, 2022

Send gmail using OAuth2 - Java

 1.

Login to https://console.cloud.google.com/ to create the project and the client_id, oauth consent screen...

2.

Run the oauth2.py to get the refresh token.

I updated the file to support python 3.

3.

From Java,

call the below to exchange back the access token:

public static String getNewToken(String refreshToken, String clientId, String clientSecret) throws IOException {

List<String> scopes = new ArrayList<>();

TokenResponse tokenResponse = new GoogleRefreshTokenRequest(new NetHttpTransport(), new JacksonFactory(),

refreshToken, clientId, clientSecret).setScopes(scopes).setGrantType("refresh_token").execute();

return tokenResponse.getAccessToken();

}

4. With the access token, call the below to send email:

SMTPTransport transport = new SMTPTransport(session, null);

transport.connect(SMTP_SERVER_HOST, FROM_USER_EMAIL, null);

transport.issueCommand(

"AUTH XOAUTH2 " + new String(BASE64EncoderStream.encode(

String.format("user=%s\1auth=Bearer %s\1\1", FROM_USER_EMAIL, newAccessToken).getBytes())),

235);

transport.sendMessage(msg, msg.getAllRecipients());

Refer:

https://hellokoding.com/sending-email-through-gmail-smtp-server-with-java-mail-api-and-oauth-2-authorization/

https://www.youtube.com/watch?v=-rcRf7yswfM

Saturday, April 9, 2022

Netflix Human pulse Climbing

When I'm at the top, I feel a sense of relief for sure, a sense of complishment. 

Climbing is a form of therapy for me because I can just escape.



Thursday, March 31, 2022

mac auto login and lock

auto lock mac after auto login 

cat autolock.sh 

#!/bin/bash

/System/Library/CoreServices/Menu\ Extras/User.menu/Contents/Resources/CGSession -suspend

exit 0


For BigSur and monterey, CGSession is not available any more.

#!/bin/zsh

osascript -e 'tell app "System Events" to key code 12 using {control down, command down}'

https://apple.stackexchange.com/questions/406616/replacement-for-cgsession-suspend 



Tuesday, March 22, 2022

Use MKVToolNix to edit audio track

 My son loves watching Naruto Shippuden. However, Netflix only has the first 10 seasons, while Hulu only accepts US IP (and payment). The resouce on the website are mostly Japanese audio or Chinese audio (with Chinese subtitle). The target is to get the English audio (with or without English subtitle).

1. Download and MKVToolNix install https://mkvtoolnix.download/downloads.html#macosx

2. Download Naruto Shippuden mp4 (with English audio) from

https://animedao.to/anime/naruto-shippuden-dubbed/

3. Extract mka audio file from the mp4 (using MKVToolNix)

4. Add the English Audio into the Japanese MKV (see the screenshot)

MKVToolNix conversion is pretty fast, however, it's hard to batch download Naruto Shippuden mp4 as it has some protection. The online play is annoying as it has inappropriate ads, also the video quality is not as good as the MKV (89M vs 200M)



Sunday, March 6, 2022

Windows 11 time issue

 I installed Windows 11 VM from Parallel Desktop, everything is OK but sometimes the time is not accurate, and it causes the scheduled tasks can't run at the specified time. My Mac is on Toronto timezone while the VM has to be on Beijing Timezone.

Parallel Desktop technically support suggests to disable time sync from PD (Time: Do not sync), but I still see the issue.

The workaround:

Update HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\Config

MinPollInterval and MinPollInterval.

I updated both to 8, (2 power of 8 = 256 seconds), and run "w32tm /config /update" to update.

(Windows Time service needs to auto start)

Now I can see the time is sync at 12:14:07,12:18:23,12:22:39...

NtpClient SpecialPollInterval setting doesn't work for me, maybe need some other flag settings to make it work.

https://docs.microsoft.com/en-us/troubleshoot/windows-server/identity/specialpollinterval-polling-interval-time-service-not-correct

https://docs.microsoft.com/en-us/troubleshoot/windows-server/identity/w32time-sync-specialpollinterval-ignored



Tuesday, February 22, 2022

JBoss EAP7.3 udemy note

 1. The linux command

netstat -an|more: list the active internet connections

nslookup ip/dn: convert ip to dn or dn to ip

2. JBoss server log:





Compile and Run C++ program on mac (m1)

 Compile and Run C++ program on mac (m1):

#include <iostream>

using namespace std;

int main() {
    cout << "Hello, World!" << endl;
    return 0;
}

g++ -o hello hello.cpp

./hello

Thursday, February 17, 2022

algorithms

 1. Find the common number between different int array.

2. Find the same String between different String array. How about if the arrays are super fast, say the duplicate name between US and Canada? two big files

3. Query a LOL player's statistics

4. Display photos

    Display photos with username/password

    Display photos with username/password (no hack/partly)


boolean/int

+-*/ ++ --

== != > < >= <=

&& ||

if/else

swtich(expression){

case c1:

..break;

default:

}

array

For loop

recursion

constructor

static

Math.sqrt(x*x+y*y)

calculate what day after 100 days

read file/write file

Swing


Monday, February 7, 2022

Enterprise OAuth2 and Open ID Connect note (Udemy)

 Enterprise OAuth2 and Open ID Connect

1. Federated user

a single user identity used by all the applications

2. SAML flow


3. What is OAuth2


4. Opaque token
     need verify access token with authorization server every time


5. JWT token
   
   The resource server can verify the signed JWT token by itself, with the public signer



6. Grant type - auth code

Auth code is on the front channal but it expires a few mins, access token is on the back channel

7. Grant type - Implicit

Return the access token from the front channel directly - could be stolen, deprecated

8. Grant type - Client credentials

    Pretty simple, no resource owner/browser agent.

9. Grant Type - ROPC

    Resource Owner Password Credential - deprecated, need the client application and the resource server are the same organization (client application is third party) as the password is exposed to the client application. For example, shutterfly cannot use this grant type.


10. OpenID