Friday, November 15, 2024

JavaScript - The Definitive Guide 7th Edition

 JavaScript - The Definitive Guide 7th Edition

1. ES6 was released in 2015 and added major new features - including class and module syntax. Since ES6, the EMCAScript has moved to a yearly release ES2016, ES2017 ...

2. Install Node and run node snippet.js

    Console.log("Hello World");

or hello.html <script src="hello.js"></script>

3. let book = {

    topic: "JavaScript",

    edition: 7

};

book.topic

book["edition"] //another way to access property values

book.author="Flanagan";//create new properties

book.contents?.ch01?.set //conditionally access (ES2020)

4. In ES6 and laster, arrow function

    const plus1 = x=>x+1;

5. Semicolons are optional

6. In ES6 and later, string literals can be delimited with backticks:

let name = "Bill";

let greeting = `Hello ${name}`;

7. In ES6 and later use let and const

8. a??b->(A!==null&&a!==undefined)?a:b

9. let a = [1,2,3]

 let b = [0,...a,4];

10. let data = [1,2,3,4,5], sum  = 0;

data.forEach(value=>{sum+=value;});

data.forEach(function(v,i,a){a[i]=v+1;}); //data=[2,3,4,5,6]

11. let a = [1,2,3];

a.map(x=>x*x) //[1,4,9]

12. let a = [1,2,3,4,5];

a.reduce( (x,y)=>x+y,0) //15, sum

a.reduce( (x,y)=>X*y,1) //120, product

the second argument is optional, init value to the funciton

13.

[1,[2,3]].flat() // [1,2,3]

[1,[2,[3]].flat() //[1,2,[3]]

14. a.flatMap(f)=>a.map(f).flat()

let phrases = ["Hello world","The Guide"];

let words = phrases.flatMap( phrases=>phrases.split(" ")); //["Hello","world","The","Guide"]

15. let a = [1,2,3];

a.join(" ") //"1 2 3"

16. f.call(o);

      f.apply(o);

To invoke a function f as a method of the object o. apply() is like call, except that the arguments to be passed to the function are specified as an array: f.apply(0,[1,2]);

17. In Node, each file is an independent module with a private namespace.

Node modules import other modules with the require() function.

const fs = require("fs");

18. ES6 Exports

export const PI = Math.PI;

export function degreesToRadias(d){return d*PI/180;}

ES6 Imports

import BitSet from './bitset.js';

19. Promise (from ES6)

getJSON("/api/user/profile").then(displayUserProfile,handleProfileError);

if getJSON runs normally, it pases its result to displayUserProfile

if there is an error, then it passes an Error object to handleProfileError

getJSON("/api/user/profile").then(displayUserProfile).catch(handleProfileError);

any error in getJSON or in displayUserProfile, get passed to handleProfileError

queryDatabase().catch(e=>wait(500).then(queryDatabase))

                       .then(displayTable)

                        .catch(displayDatabaseError);

20.

let [value1,value2]=await Promise.all(getJSON(url1),getJSON(url2)];

21.

If you don't want your node program to completely crash.

    process.setUncaughtExceptionCaptureCallback( error=>{

  appLogger.error("Uncaught Exception: ",error);
});

process.on("unhandledRejection",(reason,promise)=>{
  appLogger.error("unhandledRejection: ",reason);
});

Thursday, November 7, 2024

store up for yourselves treasures in heaven

Do not store up for yourselves treasures on earth, where moths and vermin destroy, and where thieves break in and steal. 20 But store up for yourselves treasures in heaven, where moths and vermin do not destroy, and where thieves do not break in and steal. 21 For where your treasure is, there your heart will be also

Sunday, November 3, 2024

react default warning DeprecationWarning: 'onAfterSetupMiddleware' option is deprecated. Please use the 'setupMiddlewares' option

 After run command npx create-react-app aggridqs, got the warning 'onAfterSetupMiddleware' option is deprecated. Please use the 'setupMiddlewares' option.

C:\git\aggridqs>npm start


> aggridqs@0.1.0 start

> react-scripts start


(node:6264) [DEP_WEBPACK_DEV_SERVER_ON_AFTER_SETUP_MIDDLEWARE] DeprecationWarning: 'onAfterSetupMiddleware' option is deprecated. Please use the 'setupMiddlewares' option.

(Use `node --trace-deprecation ...` to show where the warning was created)

(node:6264) [DEP_WEBPACK_DEV_SERVER_ON_BEFORE_SETUP_MIDDLEWARE] DeprecationWarning: 'onBeforeSetupMiddleware' option is deprecated. Please use the 'setupMiddlewares' option.

Starting the development server...


DeprecationWarning Solution:


DEP_WEBPACK_DEV_SERVER_ON_AFTER_SETUP_MIDDLEWARE] 

DeprecationWarning: 'onAfterSetupMiddleware' option is deprecated.

In file: node_modules/react-scripts/config/webpackDevServer.config.js


like this


onBeforeSetupMiddleware(devServer) {

    // Keep `evalSourceMapMiddleware`

    // middlewares before `redirectServedPath` otherwise will not have any effect

    // This lets us fetch source contents from webpack for the error overlay

    devServer.app.use(evalSourceMapMiddleware(devServer));


    if (fs.existsSync(paths.proxySetup)) {

    // This registers user provided middleware for proxy reasons

    require(paths.proxySetup)(devServer.app);

    }

},

onAfterSetupMiddleware(devServer) {

    // Redirect to `PUBLIC_URL` or `homepage` from `package.json` if url not match

    devServer.app.use(redirectServedPath(paths.publicUrlOrPath));


    // This service worker file is effectively a 'no-op' that will reset any

    // previous service worker registered for the same host:port combination.

    // We do this in development to avoid hitting the production cache if

    // it used the same host and port.

    // https://github.com/facebook/create-react-app/issues/2272#issuecomment-302832432

    devServer.app.use(noopServiceWorkerMiddleware(paths.publicUrlOrPath));

},


Change to this: 


setupMiddlewares: (middlewares, devServer) => {

    if (!devServer) {

        throw new Error('webpack-dev-server is not defined')

    }


    if (fs.existsSync(paths.proxySetup)) {

        require(paths.proxySetup)(devServer.app)

    }


    middlewares.push(

        evalSourceMapMiddleware(devServer),

        redirectServedPath(paths.publicUrlOrPath),

        noopServiceWorkerMiddleware(paths.publicUrlOrPath)

    )


    return middlewares;

},

After the fix, it also starts up faster

ReactAllProjects/reactwithspring/public/MiddlewareDeprecationSolution.txt at main · DrVipinKumar/ReactAllProjects · GitHub


nodejs note

 

1. change package.json scripts to:

"start": "nodemon index.js"

so that when you run npm start, it can use nodemon to start it. Otherwise, you can use node directly use "node index.js".

2. serve static contents

create a directory 'static' and put a file page.html

app.use(express.static('static'))

now you can access http://localhost:3000/page.html

3. Express middleware functions. take three parameters, req, res, next

//log every requst to the terminal

app.use((req, res, next) => {

    console.log(req.url);

    next();

});

4.

app.use(compression());

app.disable('x-powered-by');

5.

CommonJS is the default (or set "type":"commonjs" in package.json)

setting "type":"module" in package.json parses the entry script as ESM (ES2015 modules)

ESM:

import {hello} from './two.mjs';

CommonJS:

const ehllo = require('.two.cjs');


Azure auto start virtual machine

 

Azure Automation Account with a Runbook

Azure Automation allows you to create Runbooks to start and stop VMs based on a schedule. Here’s how:

  • Go to Azure Portal and create an Automation Account if you don’t have one.

  • In the Automation Account, go to Runbooks and create a new Runbook.

  • Choose the PowerShell or Python option, then add the following code to start your VM:

    powershell
    # PowerShell example $subscriptionId = '8f3bc3a8-26f0-437c-b384-5388fc90d75d' $resourceGroupName = '<Your Resource Group Name>' $vmName = '<Your VM Name>' # Login and set the subscription Connect-AzAccount -Identity # if using managed identity Set-AzContext -SubscriptionId $subscriptionId # Start the VM Start-AzVM -ResourceGroupName $resourceGroupName -Name $vmName
  • Save and publish the Runbook.

  • Go to Schedules in the Runbook settings and set up a schedule to start the VM at your desired time.

This approach is powerful, flexible, and fully managed by Azure.


Azure disable auto shutdown from Nov 5, 1:20 PM 2024

Credits remaining

CA$271.20

Friday, November 1, 2024

申请一个域名国内国外差别太大了

 

腾讯云域名服务需要主体备案、上传身份证和视频核验、腾讯云初审、电话联系、管局审核、短信核验、ICP备案、公安备案等步骤。

而godaddy申请一个域名,只需要填写一下姓名住址电话等基本信息,没有任何查验、视频、身份证明,半小时之后域名就可以用了。

Tuesday, October 22, 2024

Eckhart Tolle

 Eckhart Tolle frequently reminds us, "The primary cause of unhappiness is never the situation, but your thoughts about it."