Algorithm

February LeetCoding Challenge 2021

Number of 1 Bits

Example 1:
Input: n = 00000000000000000000000000001011
Outpu**t: 3
Explanation: The input binary string 00000000000000000000000000001011** has a total of three ‘1’ bits.

  1. /**
  2. * @param {number} n - a positive integer
  3. * @return {number}
  4. */
  5. var hammingWeight = function(n) {
  6. var arrayOfBits = Array.from(String(n.toString(2))); //Change bits integer into bits array
  7. var count=0;
  8. for (let i = 0; i < arrayOfBits.length; i++){ //Go through each element in array
  9. if(arrayOfBits[i]==='1'){ //Judge if each element equals 1
  10. count++; //Then record into ccount
  11. }
  12. }
  13. return count;
  14. };

image.png

Review

What Are Blockchain Apps and How to Develop One

  • Step 1: Clarify your idea
  • Step 2: Do competitor research
  • Step 3: Analyze your options
  • Step 4: Choose a platform
  • Step 5: Start the development process

1. Business analysis – At this point, a business analyst extracts requirements, expectations, and business goals during an interview and creates a technical specification. This document describes every detail of the development process, from the people responsible for development and communication to frameworks, libraries, and operating systems.
2. Design – Depending on its complexity, design can take from 8% to 20% of the total development budget.
3. Preparation stage – This consists of setting up the development environment, APIs, backend, and architecture.
4. Development + quality assurance – These steps happen simultaneously as one continuous process. Before deployment, a QA engineer runs a full regression test to check that everything works correctly.
5. Deployment – To be successful, an app must comply with all rules and conditions of the App Store and/or Google Play Store. After deployment, it’s crucial to analyze both performance data and user analytics.
6. Maintenance and support – This includes updates to libraries, frameworks, and operating systems, as well as implementing new features and making changes to the app according to your current business needs.

  • Step 6: Deploy and maintain your DApp

Blockchain and the future of accountancy

  • The parts of accounting concerned with transactional assurance and carrying out transfer of property rights will be transformed by blockchain and smart contract approaches.
  • Many current-day accounting department processes can be optimised through blockchain and other modern technologies, such as data analytics or machine learning; this will increase the efficiency and value of the accounting function.

    15 DevOps Trends to Watch for in 2021

  • Migrating from monolithic to microservice and containerized architecture will be a must for all the company for their Digital Transformation journey. It’s not going to be a choice or option anymore. This is where the adoption of Kubernetes will be on rise and when organizations will adopt multi-cloud, Terraform will be the ultimate choice to automate Infrastructure.

  • Now, it is high time for DevOps to step up and use available data and metrics to generate valuable insights, learn and apply machine learning models to predict incidents or outages, develop automation which learns itself from the data and forecast capacity to improve budget planning. Many have already started calling MLOps/AIOps to this part.

    How To Use Array Methods in JavaScript: Iteration Methods

    Site Reliability Engineering (SRE)

    Debugging

    image.png

    Tip

    Advanced Objects

    ```javascript //‘this’ in objects, but cannot used in arrow function const goat = { dietType: ‘herbivore’, makeSound() { console.log(‘baaa’); }, diet() { console.log(this.dietType); //this’ call dietType in goat } };

goat.diet(); // Output: herbivore

//privacy in objects

/Getter methods return the value of internal properties. They cannot be called with parentheses, looking like accessing a property/ const robot = { _model: ‘1E78V2’, _energyLevel: 100, get energyLevel(){ if(typeof this._energyLevel===’number’){ return My current energy level is ${this._energyLevel} }else{ return System malfunction: cannot retrieve energy level }; } }; console.log(robot.energyLevel);

/Setter methods safely reassign property values. They cannot be called with parentheses, looking like reassigning the value of a property/ const robot = { _model: ‘1E78V2’, _energyLevel: 100, _numOfSensors: 15, get numOfSensors(){ if(typeof this._numOfSensors === ‘number’){ return this._numOfSensors; } else { return ‘Sensors are currently down.’ } }, set numOfSensors(num){ if(typeof num===’number’ && num>=0){ this._numOfSensors=num;
}else{ console.log(Pass in a number that is greater than or equal to 0); } } };

robot.numOfSensors=100; console.log(robot.numOfSensors);

//factory functions, creating many object instances quickly const monsterFactory = (name, age, energySource, catchPhrase) => { return { name: name, age: age, energySource: energySource, scare() { console.log(catchPhrase); } } }; const ghost = monsterFactory(‘Ghouly’, 251, ‘ectoplasm’, ‘BOO!’); ghost.scare(); // ‘BOO!’

//property value shorthand, a destructuring technique, saving keystrokes const monsterFactory = (name, age) => { return { name, age } };

//destructured assignment, a destructuring technique, saving keystrokes const vampire = { name: ‘Dracula’, residence: ‘Transylvania’, preferences: { day: ‘stay inside’, night: ‘satisfy appetite’ } }; const residence = vampire.residence; //regular method const { residence } = vampire; //use destructured assignment console.log(residence); // Prints ‘Transylvania’ const { day } = vampire.preferences; console.log(day); // Prints ‘stay inside’

//create a meal-maker object const menu={ _courses:{ appetizers:[], mains:[], desserts:[] }, get appetizers(){ return this._courses.appetizers; }, get mains(){ return this._courses.mains; }, get desserts(){ return this._courses.mains; }, set appetizers(appetizers){ this._courses.appetizers=appetizers }, set mains(main){ this._courses.appetizers=main }, set desserts(dessert){ this._courses.desserts=dessert }, get courses(){ return{ appetizers:this.appetizers, mains:this.mains, desserts:this.desserts }; }, addDishToCourse(courseName,dishName,dishPrice){ const dish={ name:dishName, price:dishPrice, }; this._courses[courseName].push(dish); }, getRandomDishFromCourse: function(courseName){ const dishes=this._courses[courseName]; const randomIndex=Math.floor(Math.random()*dishes.length); return dishes[randomIndex]; }, generateRandomMeal:function(){ const appetizer=this.getRandomDishFromCourse(‘appetizers’); const main=this.getRandomDishFromCourse(‘mains’); const dessert=this.getRandomDishFromCourse(‘desserts’); const totalPrice=appetizer.price+main.price+dessert.price; return Your meal is ${appetizer.name}, ${main.name}, ${dessert.name}. The price is $${totalPrice}.; } };

menu.addDishToCourse(‘appetizers’,’Caesar Salad’, 4.5); menu.addDishToCourse(‘mains’,’Salmon’, 7.7); menu.addDishToCourse(‘desserts’,’Cake’, 3.25); let meal=menu.generateRandomMeal(); console.log(meal);//output:Your meal is Caesar Salad, Salmon, Cake. The price is $15.45.

//create and extract information about sports team const team={ _players:[ { firstName: ‘Pablo’, lastName: ‘Sanchez’, age: 11 } ], _games:[ { opponent: ‘Broncos’, teamPoints: 42, opponentPoints: 27 } ], get players(){ return this._players; }, get games(){ return this._games; }, addPlayer(firstName,lastName,age){ let player ={ firstName:firstName, lastName:lastName, age:age }; this.players.push(player); }, _games:[ { opponent:’Knicks’, teamPoints:120, opponentPoints: 60 } ], addGame(opp, myPts, oppPts){ const game ={ opponent:opp, teamPoints:myPts, opponentPoints:oppPts }; this.games.push(game); } };

team.addPlayer(‘Steph’,’Curry’,28); team.addPlayer(‘Lisa’,’Leslie’,44); team.addPlayer(‘Bugs’,’Bunny’,76); console.log(team.players); team.addGame(‘Titans’, 100, 98); team.addGame(‘Match’, 56, 89); team.addGame(‘Sight’, 49, 12); console.log(team.games);

  1. <a name="79GlU"></a>
  2. ### [Built-in Object Methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#Methods)
  3. - [Object.keys(object_A)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys)output an array
  4. - [Object.entries(](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries)[object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys)_A[)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries)output an array in `[key, value]` pairs
  5. - [Object.assign(](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)[object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys)_A, [object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys)_B[)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)combine & update object_B properties into object_A
  6. - [**More object built-in methods**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
  7. - [Function.name](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name)
  8. <a name="0rnKv"></a>
  9. ## Iterators
  10. ```javascript
  11. //rename function in easier words
  12. const checkThatTwoPlusTwoEqualsFourAMillionTimes = () => {
  13. .........
  14. }
  15. const is2p2= checkThatTwoPlusTwoEqualsFourAMillionTimes;
  16. is2p2();
  17. console.log(is2p2.name); //output checkThatTwoPlusTwoEqualsFourAMillionTimes
  18. //higher-order function either accepts functions as parameters, returns a function, or both
  19. const timeFuncRuntime = funcParameter => {
  20. let t1 = Date.now();
  21. funcParameter();
  22. let t2 = Date.now();
  23. return t2 - t1;
  24. }
  25. const addOneToOne = () => 1 + 1;
  26. timeFuncRuntime(addOneToOne);
  27. //Anonymous function can also be arguments
  28. timeFuncRuntime(() => {
  29. for (let i = 10; i>0; i--){
  30. console.log(i);
  31. }
  32. });
  33. //Iterators are methods called on arrays to manipulate elements and return values.
  34. //.forEach() Method
  35. const fruits = ['mango', 'papaya', 'pineapple', 'apple'];
  36. fruits.forEach(fruits => console.log(`I want to eat a ${fruits}.`));// Iterate over fruits
  37. //.map() Method
  38. const numbers = [1, 2, 3, 4, 5];
  39. const bigNumbers = numbers.map(number => {
  40. return number * 10;
  41. }); //print [10, 20, 30, 40, 50];
  42. //.filter() Method
  43. const words = ['chair', 'music', 'pillow', 'brick', 'pen', 'door'];
  44. const shortWords = words.filter(word => {
  45. return word.length < 4;
  46. });
  47. //.findIndex() Method
  48. const animals = ['hippo', 'tiger', 'lion', 'seal', 'cheetah', 'monkey', 'salamander', 'elephant'];
  49. const foundAnimal=animals.findIndex(animals=>{
  50. return animals==='elephant';
  51. }); //output 7
  52. const startsWithS=animals.findIndex(animals=>{
  53. return animals[0]==='s';
  54. }); //output 3
  55. //.reduce() Method
  56. const summedNums = numbers.reduce((accumulator, currentValue) => {
  57. return accumulator + currentValue
  58. })
  59. console.log(summedNums) // Output: 17
  60. // improve the quality of a paragraph and gather some information about that paragraph
  61. let story = 'Last weekend, I took literally the most beautiful bike ride of my life. The route is called "The 9W to Nyack" and it actually stretches all the way from Riverside Park in Manhattan to South Nyack, New Jersey. It\'s really an adventure from beginning to end! It is a 48 mile loop and it basically took me an entire day. I stopped at Riverbank State Park to take some extremely artsy photos. It was a short stop, though, because I had a really long way left to go. After a quick photo op at the very popular Little Red Lighthouse, I began my trek across the George Washington Bridge into New Jersey. The GW is actually very long - 4,760 feet! I was already very tired by the time I got to the other side. An hour later, I reached Greenbrook Nature Sanctuary, an extremely beautiful park along the coast of the Hudson. Something that was very surprising to me was that near the end of the route you actually cross back into New York! At this point, you are very close to the end.';
  62. let overusedWords = ['really', 'very', 'basically'];
  63. let unnecessaryWords = ['extremely', 'literally', 'actually' ];
  64. const storyWords=story.split(' ');
  65. console.log(storyWords.length);
  66. const betterWords=storyWords.filter(word => {
  67. return !unnecessaryWords.includes(word)});
  68. console.log(betterWords);
  69. let Times=0;
  70. betterWords.forEach(word => {
  71. if(overusedWords.includes(word)){
  72. Times++;
  73. }});
  74. console.log(Times);
  75. let sentences=0;
  76. betterWords.forEach(word => {
  77. if(word.includes('.')||word.includes('!')){
  78. sentences++;
  79. }
  80. });
  81. console.log(sentences);
  82. console.log('Word count: '+storyWords.length);
  83. console.log('Sentence count: '+sentences);
  84. console.log('Times count: '+Times);

Built-in Iterator Methods

  • .every(), tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.
  • .forEach() , execute the same code on every element in an array but does not change the array and returns undefined.
  • .map(), executes the same code on every element in an array and returns a new array with the updated elements.
  • .filter(), checks every element in an array to see if it meets certain criteria and returns a new array with the elements that return truthy for the criteria.
  • .findIndex(), returns the index of the first element of an array which satisfies a condition in the callback function. It returns -1 if none of the elements satisfies the condition.
  • .reduce(), iterates through an array and takes the values of the elements and returns a single value.

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

  • .some(),at least one element is true or false

    JavaScript Array class

    Share

    Docker: Complete Guide to Docker For Beginners and Intermediates_

    image.png

    Section 1: Docker Platform And Architecture

    Just summarize where I think is helpful and insightful

  • ‘As technology grows, virtual machines, development tools that were once instrumental有帮助的, are becoming redundant, in part because of the complexity of using Virtual Machines, but mainly because of the technological changes precipitated沉淀的 by the process of reducing hardware emulation仿真. Containers are taking over the territory once owned by Virtual Machines.’

  • Docker’s platform and kernel features

image.png

  • Namespaces, a technology used by docker to provide the isolated workspace. When you run a container, Docker creates a set of namespaces for that container. These namespaces provide a layer of isolation. Each aspect of a container runs in a separate namespace and its access is limited to that namespace. Docker Engine uses namespaces such as the following on Linux:
  • The pid namespace: Process isolation (PID: Process ID).
  • The net namespace: Managing network interfaces (NET: Networking).
  • The ipc namespace: Managing access to IPC resources (IPC: InterProcess Communication).
  • The mnt namespace: Managing filesystem mount points (MNT: Mount).
  • The uts namespace: Isolating kernel and version identifiers. (UTS: Unix Timesharing System).
  • Win10 Home do not support to install Docker, only professional and enterprise edition supports. But you can successfully install it by following those online tips.
  1. Windows10家庭版安装Docker Desktop(非Docker Toolbox)
  2. Docker for Windows error: “Hardware assisted virtualization and data execution protection must be enabled in the BIOS”

image.png

Docker Labs

  • about how to get started with Docker

    DevOps Job Introduction

    image.png

image.png
image.png
image.png
image.png
image.png
image.png