Github review
git issue comments
Git conflict syntax was not removed after before in docs/handling-events file #242 / fr.react.dev closed
✍️ 3 comments

How can i contribute to fix this ?

@blade-sensei You can fix this with a pull request if you want, but it's a bug with a commit from the bot and many pages have to be fixed. ;)

edit : a pull request to fix handling-event page is already on review but you can fix another page if you want

when using childnodes the first element [0] of array has 'content' object #23 / learning closed
#problem
✍️ 1 comments

This happens when there is a space after the opened div. We should remove the be sure that any space or breakline is after <div class="table-row">

Can we share a file module in server side and to client side ? #24 / learning closed
#wiki
✍️ 1 comments
(function(test){     
     shared = {
          hello() {
               console.log('hello');
          },
     }
      test = Object.assign(test, shared);
  }(typeof module === 'undefined' ? this['utilsModule'] = {} : module.exports));

Server side file

const utils = require('../path/to/file/shared.js');
utils.hello();

Client side file

<script src="shared.js"></script>
<script src="/js/index.js"></script>

Now in index.js client side you can call use

utilsModule.hello();

Another way is this https://medium.com/@ShamreshKhan/how-to-share-client-side-and-server-side-js-code-cc04c3422497

But as you use exports.functionName if we have many function we should always use something like this

 exports.someSharedMethod = function(){
          // code here will be shared
     };

     exports.function = function() {
          
     }

I prefer to write all functions 'normally' then export it in a whole module.exports

is it different to create module file with functions and exports ? AS create a class then export ? #25 / learning closed
#wiki
✍️ 1 comments

It's the same. Class are objects When we export as module.exports qui export a object which contains functions, Class exports function to and a class is an objects.

The only difference is that if in our Module Class we don't use new Class() and let the user of the module do it after import, user can create many module in the same file.

Whereas if we use module.exports the module is ready once when it's imported. Sure user can use again import twice but it should be weird ..

How to get information of a rejected Promise in Promise.all() #27 / learning closed
#wiki
✍️ 1 comments

2 scenarios. If we need only 1 function we be repeated. We can wrap the function in way to do'nt throw we a request fails but to resolve anyway

Or if we don't want to change behaviour or the throw on the function Or if we have many differents functions to run. we shoud use a for loop and insert in each array

If we have an a async function X that IN calls a async function with await then return a value. IF we use X function do we need to call it with an await TOO ? #26 / learning closed
#wiki
✍️ 1 comments

Yes we do, cause ASYNC is considered as a Promise so when we write async function under() this function returns a Promise. so if over function use it without await the results of under will we Promise pending...

The rest of code after the await (line) instruction is considered as the handle/callback like a then(callback).

async function under() {
  await fakePromise(true)
  console.log('after first fakePromise');
  return 'hello under'
}

async function over() {
  const underData = await under();
  const changed = underData + ' changed';
  console.log(changed);
  return changed;
}

await over();
group and filter repo in blog #29 / learning open
#project
✍️ 0 comments
visualizer of algorithms #30 / learning open
#project
✍️ 0 comments
game of life #28 / learning open
#project
✍️ 0 comments
array recap #18 / learning closed
#road
✍️ 0 comments
Write about ubuntu #6 / learning closed
#blog
#wiki
✍️ 1 comments

Ubuntu means 'I am because we are', or 'humanity to others' , is this a philosophy or concept that cames from South Africa, basically it means that we need to be aware of each other.

There is a nice story about this concept.

One day a an anthropologist propose to an African tribu. He put some fruits in a basket, and said the first person who touch this basket will gain all the fruits. He fire the start.. but none of the kids move, they look at each other and held their hands and start to move forwards together and at the end they touch the basket at the sametime. The man asked them why they do that They responded 'Ubuntu', how could one of us be happy if remains are sad..'

Is the code under and await instruction pending even if in the code under we don't use the value returner by await ? #31 / learning closed
#wiki
✍️ 1 comments

We want to know if the the code under await SO here

console.log('i don't use users');
return 'loading..';

will we executed immediatly ? and in this case console.log('i don't use users') should be displayed before ('waiting..');

OR if this code will we executed pending.

async function load() {
 const users = fakeRequestUserAsync();
 console.log('i don't use users');
return 'loading..';
}

load();
console.log('waiting...');

The response here that the code under await is considered as the callback/then anyway so it's 'pending code' here the output will be

waiting..
i don' use users
setTimeout(callback, 0) is not exectued immediatly. This helps to undertands why Promise with asynchronous code run after, main loop. #39 / learning closed
✍️ 2 comments
console.log('after callback');
setTimeout(() => console.log('timeout'), 0);
process.nextTick(() => console.log('tick'))
for (let i = 0; i < 100; i++) {
  console.log('test');
}

If we have this code. Main loop (JS thread) First after callback will be executed then seTimeout --> We go out and create another thread

Thread alternatives (timers, async etc)

Explanation

With this fact, and everything else, it all makes sense.

When f1() is encountered in the path of execution, the function is called and in it a setTimeout is called which has a callback which would be queued up for execution after 0 seconds has expired. Which should translate to immediate, but since the actual minimum is 4 milliseconds, the callback function is queued for execution after 4 milliseconds.

In this period, since JavaScript is non blocking, and in this particular case, this is not a I/O operation but a timeout, the preceding line, f2() gets executed. And this is why the output of f2() appears before f1():

source

First i thought that setime out was excuted after because the thread create by nodeJS or the browser is exectued un parallel or just after that setTimeout was executed so it lets the time to the JS main loop to take the next instruction and fill the call stack. THAT means the QUEUE job will be filled after that.. that means we will need to wait the end of the call stack.

BUT there is also another point, is that setTIme 0 has a REAL delay of 4ms (browser) or 1ms (node) depends on the env. and the case explained above is used.

The question now is if the REAL delay were 0ms.. is the callback be executed immediatly ? because the call stack of main JS thread will not have time to be filled ? OR maybe it depends of the time execution of each thread ( if the JS main thead is faster than the thread created for the async/or the env) it will be executed after.

So. I did some mistakes. JS and event loops are running in the same thread. Just for few cases we run in another threads. setimeout schedule this but in the future. but immediatly we fill the stack.

how await manage the callback (then) #37 / learning closed
#wiki
✍️ 1 comments

Then implentation (grossly explanation)

Then will return a new Promise In this promise the constructor will be wraped by a setTimeOut to respect asynchronous. Donc on va essayer de jouer les 2 callbacks passés dans se setTimeOut (DO). Mais seulement l'un des 2 callbacks va être joués, selon l'état de la promeses.

la 1er callback si on lui a passé un handle/then elle va retourner le resolve avec en paramètre la callback then + valeur si c'est pas une fonction alors on va resolve en passant directement le result de notre promise. // this if make to just play one the handlers and return the same result if the promises was already resolved and played handlers.

Second callback will do the same but for the handle error. (catch)

source implentation

this.then = function (onFulfilled, onRejected) {
  var self = this;
  return new Promise(function (resolve, reject) {
    return self.done(function (result) {
      if (typeof onFulfilled === 'function') {
        try {
          return resolve(onFulfilled(result));
        } catch (ex) {
          return reject(ex);
        }
      } else {
        return resolve(result);
      }
    }, function (error) {
      if (typeof onRejected === 'function') {
        try {
          return resolve(onRejected(error));
        } catch (ex) {
          return reject(ex);
        }
      } else {
        return reject(error);
      }
    });
  });
}

function resolve(result) {
    try {
      var then = getThen(result);
      if (then) {
        doResolve(then.bind(result), resolve, reject)
        return
      }
      fulfill(result);
    } catch (e) {
      reject(e);
    }
  }
blog: if some pages redirect to blank page with a message index.php not found #41 / learning closed
#bug
#wiki
✍️ 2 comments

maybe htacess redirects to index.html and not your base url name like myblog/index.php or wordpress/index.php

Go to htaccess file and change base and rule lines. an example

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /wordpress
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /wordpress/index.php [L]
</IfModule>

# END WordPress
wordpress if admin dashboard doesnt redirect to the board #40 / learning closed
#bug
#wiki
#wordpress
✍️ 1 comments

use another user or create one in database.

how to create a sticky footer #33 / learning closed
#wiki
✍️ 4 comments

implementing or blog website deploy to server

html {
    position: relative;
    min-height: 100%;
}
body {
    margin: 0 0 100px; /* bottom = footer height */
}
#bottom-footer {
    position: absolute;
    left: 0;
    bottom: 0;
    height: 100px;
    width: 100%;
}

Solution

we can also use

html {
height: 100vh
}

to adapt all the body/html content to fit in the viewport

difference. height on pourcent and vh

pourcent. adapts to the parent height/width vh adapts to the viewport

https://www.sitepoint.com/css-viewport-units-quick-start/

why parrot imitate humains voice #42 / learning closed
#mixed
#nature
✍️ 1 comments

There is a research with Australian birds/parakeet, similar to parrots . This researches shows that these birds when they choose a partner couple, after years, they will try to get the same squawk for both.. an uniq couple squawk in some ways.

So when a parrot has more affection to his master they will try to copy the same language/voice than his masters.

This could be one of the reasons of why parrot imitate humains voice

source french

jsdoc describe props of object (param) description text #44 / learning closed
#problem
#wiki
✍️ 2 comments
  /**
     * Build html layouts with data for each layer
     * 
     * Returns Promise of HTML String of all the combined/builded layers
     * @param {Object} layers one or many layers to build the layout
     * @param {string} layers.name name, path/name to the view
     * @param {{}} [layers.data] data passed to the view. [require]: prop names should be the same used in the view.
     * 
     * Options:
     *

this doesnt work it only shows properties of layers

This is a good option:

 /**
     * Build one or many html `layers` with optional data for each layer
     * 
     * Returns Promise of HTML String of all the combined/builded layers
     * 
     * `layers`:
     *
     *  - `layers.name` name, path/name to the view
     *  - `layers.data?` [require]: properties must be named as in the view.
     * 
     * 
     * @param {Object} layers
     * @param {string} layers.name 
     * @param {{}} [layers.data] 
     * 
     */
publish package to github package #45 / learning closed
✍️ 1 comments

The package are not public, only private package, means that if you need to publish public package this is not the best solution. 1 solution is to create script to publish hybrid to npm and github. see: https://dev.to/jgierer12/how-to-publish-packages-to-the-github-package-repository-4bai

But the package name will have a scope anycase. In my case i don't want that. So i will use npm registry

Create a layout with mustache template #32 / learning closed
#project
#wiki
✍️ 4 comments
  • install server and nodemon

  • install mustche and set in server.js

app.engine('html', mustacheExpress());
 app.set('view engine', 'html');
app.set('views', __dirname + '/views');

How to pass data to extends layouts

  • Utils without class
  • Inject function to response express object, cannont get doc description of the function
  • create function and add app to this function to use render function, singleton
run command of package installed as dev but without create script in package json -> solution npx [packageCLI] #46 / learning closed
#problem
#wiki
✍️ 1 comments

npx allows you to run dev cli as if they were installed in global local

test #47 / learning open
✍️ 0 comments
create tree of nodes - toggle #36 / learning closed
#project
✍️ 2 comments

nextSibling - previousSibiling (next element in the parent scope)

css -< content with ::after ::before to insert HEXA encoded code 'use \'

keyboard keypress react push event before the #49 / learning closed
#problem
#react
✍️ 1 comments

We need to use callback to set the next step AFTER set key string

handleKeyUp(e) {
    console.log(e.key);
    this.setState({ value: e.key.toString() }, () => {
      this.onButtonClick()
    });
  }
naming variables: entry vs input ? #50 / learning closed
#topic
✍️ 1 comments

https://wikidiff.com/input/entry We should use input, Entry is used a ACCESS POINT meaning

naming: float vs decimal #52 / learning closed
#topic
#wiki
✍️ 1 comments

float for programming : floating number point and decimal is the name for REAL maths

https://fr.wikipedia.org/wiki/Virgule_flottante

naming: add vs append vs create #51 / learning closed
#topic
#wiki
✍️ 2 comments

append is used to agregate to string or file .. ciontinious add is more for creating or ADD INTO

append

attach, insert and element at the end of generally a list or string (string is considered as a list or chars)

Examples:

DOM: element.appendChild() add element to list child In the element (parent)
Python: list.append(item)

add

add has the same function that append, so it can be the same thing in different langages/tools/libs etc.

combination of other things so as to increase the original unit in numbers, size, amount

Examples:

JS: Set.add() add: add and element to set object

Insert

Insert is also used to add but in a specific place or Index (arrays)

Examples:

python: list.insert(index, element)

create

Builds/create and object but it's not attached to anything.

Examples

DOM: document.createElement("BUTTON"); create / not added anywhere
slice vs substr vs substring #57 / learning closed
#topic
#javascript
✍️ 2 comments
  • substring arguments -> all indexes start and ? end, end is excluded, negatives are used as 0. Can switch arguments when > superior
  • substr arguments are start and ? length of elements we need to take. if length is not set that means we take all element from start to the end. Support negatives
  • slice: argument - start and ? end. Enables negative CONTRARY than substring
border vs outline #53 / learning closed
#topic
#css
✍️ 3 comments

#60

SO Outline as it is created around/on top or BOrder and doesnt take place To modify height or width or element. i will add "border" that can be override the margin.

Border will change the height/width so it's fixed than not change If we change dynamically border it's a problem cause it can change position on your HTML

So a solution is to put a outline

outline = doesnt change element position border = changes element position

test #61 / learning open
✍️ 0 comments
box model css #60 / learning closed
#topic
#css
✍️ 4 comments

The height and width sets the PADDING Then the margin will add On top OF padding if Border is added will be Added on TOP of padding THEN Margin will be build on top or BORDER so they are ADDED.

SO Outline as it is created around/on top or BOrder and doesnt take place To modify height or width or element. i will add "border" that can be override the margin.

Border will change the height/width so it's fixed than not change If we change dynamically border it's a problem cause it can change position on your HTML

So a solution is to put a outline

It’s not a part of the box model, so it won’t effect the position of the element or adjacent elements

misake: dont preserve CONTENT. It tries if there is espace. But if there is not espace content will me small each time. The only thing we preserve if the postion xy

vertical align testing css #56 / learning closed
#topic
#css
✍️ 2 comments
.parent {
    height: 200px;
    width: 200px;
    background-color: aqua;
    display: table-cell;
    vertical-align: middle;
}

.child {
    height: 60px;
    width: 60px;
    background-color: rgb(115, 255, 0);
    display: block;
    margin: 0 auto;
}

Vertical align the green square: add: table-cell + vertical-algin to the PARENT. If you need center. Add 0 auto margin to the child BUT if the child is inline-block it doesnt work if child is inline-block add text-algin: center to the PARENT.

linear gradient for background #54 / learning closed
#topic
#css
✍️ 1 comments

3 kind of gradient in css

linear

This will take a point and expand the colors/gradualy to another color, in a linear way.

  • you can change the direction of the linear with 54deg for example. 0 points to the TOP. 90 points to the right. OR with words like "to left right" "to bottom top" etc.
  • You can also change point of median change colors with a pourcent
  background: linear-gradient(to top, black, 20%, cyan);
argument is after colors
  • You can also define the breakpoint of a color, just pout the pourcent near the color linear-gradient(red 40%, yellow 30%, blue 65%);

radial gradient

Expands the colors transition AROUNT a point.

conic gradient

Expands the colors transition following the clockwise.

French source: https://developer.mozilla.org/fr/docs/Web/CSS/Utilisation_de_d%C3%A9grad%C3%A9s_CSS

react: pass params to parent comp #59 / learning closed
#react
✍️ 1 comments

use handle the key is first use the input user in the component that needs to display but if other components need this value, pass to the parent that wraps all the others, the parent should be the state controller.

👍

Il ne doit y avoir qu’une seule « source de vérité » pour toute donnée qui change dans une application React. En général, l’état est d’abord ajouté au composant qui en a besoin pour s’afficher. Ensuite, si d’autres composants en ont également besoin, vous pouvez faire remonter l’état dans l’ancêtre commun le plus proche. Au lieu d’essayer de synchroniser les états de différents composants, vous devriez vous baser sur des données qui se propagent du haut vers le bas.

react: controlled components #62 / learning closed
#react
✍️ 1 comments

bassically it means that the FIRSt value to the UI/Html is passed by the state of controler. It means controller has the SOURCE information. If we only set handle event HTML its stills remain the source. we need both: handle event + pass component state

check this:

https://www.robinwieruch.de/react-controlled-components

git: history graph #63 / learning closed
#git
✍️ 1 comments

use : git --graph --all (branches)

other options useful

--date=relative --oneline --decorate

git log --graph --oneline --decorate --all

react: deal with class names dynamic #55 / learning closed
#topic
#react
✍️ 2 comments

1th Option

using component state and generate class with a getClassName function

getClassName () {
    let className = this.state.type;
    if (this.isZeroButton()) {
      className = `${className} zero`
    } else if (this.state.value === '/') {
      className = `${className} divide`;
    }
    return className;
  }
}

Using like this

render() {
    const className = this.getClassName();

    return (
    <button onClick={ this.onButtonClick }  className={ className }> { this.state.value } </button>
    )
  }

Or there is also this lib: https://www.npmjs.com/package/classnames It works with TRUE FALSE flags to setup a list of classnames.

var btnClass = classNames('btn', this.props.className, {
  'btn-pressed': this.state.isPressed,
  'btn-over': !this.state.isPressed && this.state.isHovered
});
how audit chrome works #35 / learning open
#topic
#javascript
✍️ 0 comments
Learn about currying function #8 / learning open
#topic
#javascript
✍️ 0 comments
how to unit test services in MVC Server #38 / learning open
#topic
#javascript
✍️ 0 comments
math - sum from a to n #19 / learning open
#blog
#math
✍️ 0 comments
How CD rom works/read #11 / learning open
#topic
#ed: tech
✍️ 0 comments
How geoloc works #12 / learning open
#topic
#ed: tech
✍️ 0 comments
XSS cross site check #22 / learning open
#topic
#sys:security
✍️ 0 comments
difference between thread and process #16 / learning open
#topic
#cs: ops
✍️ 0 comments
how promises works #67 / learning open
#topic
#javascript
✍️ 1 comments

Promises callback of executed in the JOB Queue The rest of IO Asynchronous callbacks are placed in Task/Queue callback

Async fonctions are executed after the principal stack

Javascript doesnot provide async function - SetTimeout or Request are included by Browser API and NodeJS Packages

Promises Works

Les promeses sont des objets avec un Etats et des evenements à executer selon l'état

On les appeles des promses car elles donnent la promese que la valeur sera immutable

L'un des avantage des promeses par rapport au Callbacks sont les chaines avec then().then()

  • Execution d'une fonction qui retourne une promeses
  • Ajout des evenements avec then()
  • L'object Promise va être crée avec les étapes à suivre pour optenir la valeur de retour RESOLVE, mais cette étaape peut prendre du temps si c'est un appel asynchrone

Il peut avoir 2 cas ICI. Soit l'instruction prend du temps dans ce cas c'est le THEN qui sera executé Avant le RESOLVE ou REJECT

Soit l'instruction est rapide et le resolve ou reject s'executent avant le THEN.

  1. le then va ajouter le handle/callback dans la liste de la promese et va executer un doResolve pour vérifier l'état de la promeses Si elle est à l'état FILLED et va executer les handlers qu'elle vient de mettre en liste de même pour reject. Si elle est en Pending est va juste l'ajouter à la liste.. Après un certain temps notre fonction asynchrone est terminé et va effectuer soit un Resolve ou Reject, le doResolve va être executé et on va mettre en JOB Queu le handle. Ce qui signifie que l'event loop va la prendre lorsque la stack principal aura terminé les execution.

La promise possède une seule valeur qui ne peut être changé.

Quand on chaine avec d'autre the net des callbacks on récupère l'état de objet promese prcédédante avec la valeur immutable

Resolve ou Reject va changer l'état de notre Promese vont faire un doResolve doResolve vérifie l'état de la promese et éxecute les handlers

create comparator file like git #48 / learning open
#project
#javascript
✍️ 3 comments

Questions

  • How to detect that a file is different than other : we can compare file size/bigger or smallest
  • How to detect which line was added
  • How to detect that a specific line has changed - add new information (delete)
  • How to detect that a s specific line was complety deleted (not a change)
    • even if this line was replaced by the above line
    • deleted line can be now empty if there was a text already OR can be fill but by a text that was already in the file (line under or above)
  • with offset a line can be now move next another line - it will be considered as delete and added change

test

  • test with compare text with same lines

Display

  • File LEFT will adapt lines (delete or add lines) to compare line in the same order

idea: it seems that git hash each line or file (called blom object) to differentiate/to get uniq words/lines.. first clue

today/tomorrow 5/04 #64 / learning closed
#daily
✍️ 1 comments

ToDay

  • plan for next small project
  • leetcode challenge
  • reorganize learning folders
  • how to learn effeciently, techniques, training, memorize start a repo
    • vulgar
    • set protocol/rules to track problems to remember

Summary

  • Leetcode: done 2 ex. is Happy 1 and Single Number.
  • Git find some problems when comparing files to see which line was added, which word added or deleted
  • Reorganize project into sandbox, algo

Tomorrow

  • how to learn effeciently, techniques, training, memorize start a repo
    • vulgar
    • set protocol/rules to track problems to remember
  • leetcode challenge 3 more
  • review yesterday
  • define april calendar review. Tuesday( 3 ) Saturday (week) Last saturday (month)

Summary

Finish 3 more leetcode challange to read https://medium.com/@pawan_rawal/demystifying-git-internals-a004f0425a70 git

algo: Kadane algorithm to resolve subarray max sum #69 / learning closed
#topic
#cs: algo
✍️ 3 comments

Depends on the specific conditions be have 2 GLOBAL ways to resolve tihs.

  • If the problem ask to handle NON empty array
  • we should ask what to return if subarray is empty. 0 ? -Infinty
  • If the problem doesnt ask to handle empty array, There is many ways of approch the problem.

First approch

Consideres that for each iteration we compute the MAX_SUM unti index i.

[ 2,  3]  --> index 1 (3) 
|--|
|------| = 
|--| + |3| (i)

First To do that we need to SUM of the contiguous subarrayi, We should not forget that i is also a subarray (of only 1 element). So we compute the the maximal the current_sum and the current element i (line 1 below). Now we know which if the subarray_sum is max (current_sum or i. But we still don't compare with previous_sum (subarrayi -1) that can be greater than the current_sum. So compute this globalMax = Math.max(globalMax, currentMax); if this is first element or array of single element. the previousGlobalmax will be -infinity, to return the single element but in case it's negative it will works. Now this result is returned, globalMax will also be used for the next subarray+1, +2..

Important ❌

In summary ech iteration will have 3 the options of MAX_SUM at this index

  • keep subarrayi+1 ?
  • keep i ? currentMax = Math.max(currentMax + number, nuber);
  • keep the subarrayi-1 ? globalMax = Math.max(globalMax, currentMax);
//The expression: 
SUM_CURRENT = max_current_subarray[i-1] + [i]
max_current_subarray[i] = Max(SUM_CURRENT, [i])
//final code first approch

var maxSubArray = function(nums) {
  let currentMax = 0;
  let globalMax = -Infinity
  
  for (let number of nums) {
    currentMax = Math.max(currentMax + number, number);
    globalMax = Math.max(globalMax, currentMax);
  }
  return globalMax
};

Second approch

We considere that if we get negatives as sum if a subarray. the next contigious subarrays are not neccessary anymore to be calculated. Cause this negative subarray will decrease the max_sum. So we dont need to keep this subarray. Another sum subarray will be greater, so to start another sum we reset the sum_max to 0, this way, next iteration will set sum_max = sum_max + i, it means that we start another sum from i.

var maxSubArray = function(nums) {
  let currentMax = 0;
  let globalMax = -Infinity
  
  for (let number of nums) {
    currentMax = currentMax + number;
    globalMax = Math.max(globalMax, currentMax);
    currentMax = Math.max(currentMax, 0);
  }
  return globalMax
};

Summary

Kadane Algorithm is used to get the maximal sum of contiguous subarray.

Basically we need to compare EACH sum of subarrays.

What is a a contigious subarray respects these criterias

  • is a part of array that compose the MAIN/Principal array
  • must be composed by subarrays/elements that are next each other
  • subarray can also contain a single element like 10.

. Example:

principal array --> [-2, 10, 2, -12]

> one of contiguous subarray is [2, -12]
 - is its part of the principal array
 - is it composed by [2] [-12] that are next each other

> [10, -12] is a non contiguous subarray: don't respect second criteria

Understand the idea

Core idea (see dynamic programming)

The main idea behind Kadane algorithm is to resolve smallest problem by one one. So the idea:

  • to iterate the array from start (index 0) to the last index to resolve the main problem
  • each iteration acts like it was the main problem, we store the result and other necessary state for the next index.
  • the next iteration will access to the previous value to compute his own problem.

Implement the idea with Kadane/ Which states we save

  • We need to store an accumulated sum for the current level of subarray (levels will we explained further in a example).
  • And also the global_max_sum computed by compare sum levels.

Here for each iteration

  • the current subarray (index) uses the previous subarray (just behind -> it's important to create contiguous) to create a new subarray.
  • this current subarray will used to check which of the
    • recently subarraycurrent
    • and the subarray sum of previous level (or in other words the previous global_track_sum stored) is greater (MAX), the result is save in a global_track_sum.

as a subarray can also be composed by one element like 10 an index = subarrayindex

/**
 * if [-2, 10, 2, -12] 
 *      >
* In a classic brute force we change device the contiguous subarray this way:
* 1 -> [-2] [-2,10] [-2,10, 2] [-2,10,2,-12]
*2 -> [10]  [10,2]    [10,2,-12] 
*3 -> [2]   [2,-12]
*4 -> [-12]
* 
**/

 We can use the same structure for Kadane algorith we considered that we have 4 POTENTIALY max sum of each LEVEL. 
algorithm: in-place / two pointer #70 / learning closed
#topic
#cs: algo
✍️ 2 comments

Definition

In-place algorithm updates input sequence only through replacement or swapping of elements

Example

Move Zeroes is a problem based on this https://leetcode.com/problems/move-zeroes/solution/

Two Pointer solution

First is to move all the no zeros to the left then add zeros.

var moveZeroes = function(nums) {
  let pointer = 0;

  console.log(nums);
  for (let num of nums) {
    if (num !== 0) {
      nums[pointer] = num;
      pointer++;
    }
  }

  for (let i = pointer; i < nums.length; i++) {
    nums[i] = 0;
  }
  

return nums;
};
test #71 / learning open
✍️ 0 comments
Happy Number: #72 / learning open
#topic
#cs: algo
✍️ 2 comments

Brute force but really bad perform

var isHappy = function(n) {
  const alreadyFind = [];
  if (n <= 0) return false;
    let numberToCheck = n;
    while (numberToCheck !== 1) {
      let numberString = numberToCheck.toString();
      numberString = numberString.split('');
      numberString = numberString.map((number) => {
        return Math.pow(Number(number), 2);
      });
      numberToCheck = numberString.reduce((p, c) => p + c);
      if (alreadyFind.includes(numberToCheck)) {
        return false;
      } else {
        alreadyFind.push(numberToCheck);
      }
      console.log(numberToCheck, alreadyFind)

    }
    return true;
};

☝️ Here we need to return false when we see that this will we a infinite loop. thats we need to chech isAlreadyfind

007 Skyfall #74 / learning closed
#general knowledge
✍️ 1 comments
  • 🚆 💣 -🔥 🏠 ☁️
  • 🛥️ - 🎨
today/tomorrow 6/04 #68 / learning closed
#daily
✍️ 1 comments
  • how to learn effeciently, techniques, training, memorize start a repo
    • vulgar
    • set protocol/rules to track problems to remember
  • leetcode challenge 3 more
  • review yesterday
  • define april calendar review. Tuesday( 3 ) Saturday (week) Last saturday (month)

Summary

Finish 3 more leetcode challange to read https://medium.com/@pawan_rawal/demystifying-git-internals-a004f0425a70 git

calculator #9 / learning closed
#project
#react
✍️ 4 comments

problems during dev: #53 #58 #57 #55

Shoud we set userInput state and THEN handle it with callback OR should be first handle it and THEN at the end of the focus setState the userInput

We need to test the FIRST.

So State Will be:

'expression' = '0' then user inputs a button '3' type number or 'x' type operator 'now we get expression = '0' and input = { '3', type } THEN after input setState we should handle input to create a new expression or NOT. ??

fetch comments of issues from github #1 / rtn-review open
#good first issue
✍️ 1 comments
react map undefined will render useState #81 / learning closed
#problem
#react
✍️ 1 comments

set initial state const [issues, setIssues] = useState([])

Could not find "client" in the context of Apollo(MyComponent). Wrap the root component in an <ApolloProvider> Gatsby #80 / learning closed
#problem
#gatsby
#graphql
✍️ 3 comments

Solution

  • Instead of wrapping components to get the Apollo Client, i create a Global Context (REACT) then i pass the client though all component

See this code

//gatsby-browser.js

import React from "react"
import GlobalContextProvider from "./src/context/GlobalContextProvider"

export const wrapRootElement = ({ element }) => {
  return <GlobalContextProvider>{element}</GlobalContextProvider>
}

//GlobalContextProvider.js

import React, { useState } from "react"
import  ApolloClient  from 'apollo-boost';
export const GlobalStateContext = React.createContext()
export const GlobalDispatchContext = React.createContext()

const token = 'df0ad05d2d05bb3f3790d060860499fd017c2b21';
const client = new ApolloClient({
  uri: 'https://api.github.com/graphql',
  request: (operation) => {
    operation.setContext({
      headers: {
        authorization: `Bearer ${token}`
      }
    })
  }
});


const initialState = {
  client
}

function reducer(state) {
  return state;
}

const GlobalContextProvider = ({ children }) => {
  const [state, dispatch] = React.useReducer(reducer, initialState)
  return (
    <GlobalStateContext.Provider value={state}>
      <GlobalDispatchContext.Provider value={dispatch}>
        {children}
      </GlobalDispatchContext.Provider>
    </GlobalStateContext.Provider>
  )
}

export default GlobalContextProvider

//review.js ( a component that use Client Apollo)

import React, { useState, useEffect, useContext } from "react"
import Layout from "../components/layout"
import Issues from "../components/issues"
import { gql } from "apollo-boost";

import {
  GlobalDispatchContext,
  GlobalStateContext,
} from "../context/GlobalContextProvider"

const Review = () => {
  
  const dispatch = useContext(GlobalDispatchContext)
  const state = useContext(GlobalStateContext)
 
  const [userName, setUserName] = useState(0)
  useEffect(() => {

    console.log(dispatch)
    state.client.query({
      query: gql`
        {
          viewer {
            name
          }
        }
      `
    })
    .then(result => {
      console.log(result)
      setUserName(result.data.viewer.name);
    });

    // get data from GitHub api
  }, [])
  const handleClick = () => {
    setUserName('test');
  }
  console.log(state);

  return (
    <Layout>
      {`test: ${userName}`}
      <button onClick={ handleClick }> change </button>
      <Issues git={userName} />
    </Layout>
  )
}

export default Review
Fix the Infinite Loop Inside “useEffect” #82 / learning closed
#problem
#react
✍️ 1 comments

We need to set a check variable change We only run useEffect is this variable has changed explain link https://medium.com/@andrewmyint/infinite-loop-inside-useeffect-react-hooks-6748de62871

get date in format 'yyyy-mm-dd' #83 / learning closed
#javascript
✍️ 2 comments

first

One solution is to use date.toISOString() then slice only 10 first chars. but you will have a ISO date (universal) not current zone date.

second

toLocaleDateString return a local zone 👍 but in format dd/mm/yyyy we can split on array and inverse the array then join.

third

we can use build the date buy ourself date.getFullYear + date.getMonth but getMonth returns an index, for January it returns 0 because this is the index in a month array.. so it's annoying to handle month .. we need to add 0 in case month < 10 .. and add + 1

Summary

I think the best solution here is the second, even if we need to split + join .. i dont like use array function to much for perfs .. but here is ok maybe.

let formattedDate = currentDate.toLocaleDateString();
formattedDate = formattedDate.split('/').reverse().join('-');
algo: get number left and side in calcul expression STRING (operators) #58 / learning closed
#cs: algo
✍️ 1 comments

Setps

First need to get the operator prioprity like * or / To execute first then search for the left and right side operands

left right side

etRightOperand(expression, index) {
    let rightLimit = expression.length;
    let leftLimit = index + 1;
    for (let endIndex = leftLimit; endIndex < expression.length; endIndex++) {
      const term = expression[endIndex];
      if (this.isOperator(term)) {
        rightLimit  = endIndex;
        break;
      }
    }
    let number = expression.slice(leftLimit, rightLimit);
    number = number.join('');
    number = Number(number);
    return [number, rightLimit - 1]
  }

  getLeftOperand(expression, index) {
    let leftLimit = 0;
    for (let endIndex = index - 1; endIndex >= 0; endIndex--) {
      const term = expression[endIndex];
      if (this.isOperator(term)) {
        leftLimit  = endIndex + 1;
        break;
      }
    }
    let number = expression.slice(leftLimit, index);
    number = number.join('');
    number = Number(number);
    return [number, leftLimit]
  }

priority sign index

 let firstOperatorFound = false;
    let indexPriorityOperator;
    let operands = [];

    for (let [index, term] of expression.entries()) {
      if (this.isOperator(term)) {
        if (this.isPriorityOperator(term)) {
          indexPriorityOperator = index;
          break;
        } if (!firstOperatorFound) {
          indexPriorityOperator = index;
          firstOperatorFound = true;
        }
      }
    }
roadtoninja web site: create activity page. Better visibility on github activity #65 / learning closed
#project
✍️ 11 comments

draft sketch

notes about architecture pros cons

need to start mockups

I was thinking about, what i really need and how. I need a overview of a progress in a day OR days. So i need to see clearly what are the comments of all REPOS/Projects in a same page (github doesnt prive a global overview dashboard).. Github provides an activity page "in profil" but there no details and you need to open PAGES and PAGES to see specific issus or comment... I need a page where i can see ALL. Groupy by projects and comments.

To allow a review and see a progress during x1 time to x20. I need that this page allows me to set a period time.

So: a repo while get a board. in this board we put issues. That we will comment.

Activity will fetch all the COMMENTS. ISSUES for each REPO. GRoup by repo of a specific TIME (today) or (from 2March to 2 April) example. !!!

I iwll create comments in a issue called "daily". This will allow me to organize my "tomorrow" todo list in a "reminder app" samsung.

query {
  
  viewer {
  issues(
    first: 5
    orderBy: { field: UPDATED_AT, direction: ASC},
    filterBy: { since: "2020-04-18T00:00:00Z"}
  ) {
      edges {
        node {
          repository {
            name
          }
          labels(first: 4) {
            edges {
              node {
                name
              }
            }
          }
          title,
          createdAt,
          updatedAt
          state
          comments(first:10) {
            edges {
              node {
                body
                createdAt,
                updatedAt
              }
            }
          }
        }
      }
    }
  }
}
 const client = new HttpLink({
  uri: 'https://api.github.com/graphql',
  request: (operation) => {
    operation.setContext({
      headers: {
        authorization: `Bearer ${token}`
      }
    })
  }
});
`
``

using apollo to get graphql data -> error wrap root element i tried to wrap the root with ApolloProvier but i didn't work.. i found another solution in this repo:

https://github.com/codebushi/gatsby-global-state

Create a global state to pass a client apollo instance.

  • P It seems that i cant get issue name in a single GET request issues/comments
  • i need to do a request to each issues url...

  • S: If we theory i only need comments for a specific ONE day.

  • that means there will not be more than 30 comments per day. So it equals to do 30 request for issues information The solution maybe will be to: fetch /issues for only 1 repo (learning) for 1 day. then get all comments for 1 day of each issues

  • P: since parameter returns only updated comments... bad for me.

  • S: The solution would be to fetch all issues. Filter only issues that match with specific day/date, when create requests to get comments of issues.

  • P: With Github RestAPI i can get issues of user ( i didnt tried but it seems you can) i can also get issues from specific repository.

  • But in any case the response doesnt provide comments arrays. One solution could be to fetch comments directly with "issues/comments" route BUT the response doesnt provide "issue" information, so in both cases i need to do more requests for issues or comments.

  • S: Github also provides GraphQL API i did some test this query works for me

  • This query allow me to get issues of specific date. I will pick first 5 issues WHY ? As we cant request issues for 1 ONLY DAY, i can only get AFTER DATE issues. Solution: As the response is ASC the first objects are the closest to the date i don't need the latest objects. This is to match and only get the issues of the DAY.

Then i can get issues information like labels/name/number/state (without need extra request as like using rest API)

I can access comments directly, i assume that i will not comment more than 10 times an issue. so i set limit to first 10 comments per issue.

20/04 I can call GraphQL API Github with Apollo I pass client apollo instance. Works in browser

Now i need to refactor components

  • Issue to display issue name, number, tags name, state (open/close)
  • Comment display title, date, content.
  • Issuing function components (not class)

Next: Primary

  • toggle issues first DONE
  • toggle comment DONE
  • filter comment for specific date DONE
  • graphql add parameter for date DONE

  • Date picker doesnt work when we change it (no update), i think it beacause we set the state and after we call graphql but as setState is async grpaql has not the current date changed DONE Second

  • Format dates done
  • change size images done
  • add icon to open/close done
  • label colors done

  • change style for code markdown https://medium.com/young-developer/react-markdown-code-and-syntax-highlighting-632d2f9b4ada done

  • Now free style ...

  • toggle only hidde content cards comment
  • add comment url
  • text when issues are empty
  • icon for open/close
  • add image url
  • push to firebase or netlify (maybe both to test)

Next steps

  • Remove triangle toggle for comments and allow to close/open by clicking in title comment section
  • Adapte to mobile (remove overlap space right side when comment has large text (width) ( i don't know how for the moment) DONE ✅

Samsung internet (browser) doesnt handle input type date very well

input date type android support #89 / learning open
#problem
✍️ 1 comments

It seems that event is not fired. I tried to set onBlur but desnt work for me. https://stackoverflow.com/questions/40762549/html5-input-type-date-onchange-event

Next: maybe i should try to put a normal input date without passing state prop and see if it changes. Then add another change event for another state prop string and see what happens..

why text sometimes overflow the div (outside) why word-wrap is a solution word-wrap vs word-break #87 / learning closed
#problem
#css
✍️ 2 comments
word-wrap    : break-word;
overflow-wrap: break-word; 

word-wrap is must supported

It happens cause text is not break so it continues to fill the content

pourcent vs vh css #85 / learning closed
#topic
#css
✍️ 1 comments

Good explanation about height 100% and vh https://la-cascade.io/pourquoi-height-100-ne-marche-pas/ (french)

Summary

vh is used only for height prop, the viewport is nutshell the screen size (for mobile it's different) but pourcent refers the POURCENT relative to the parent. while 100vh is relative to the screen/viewport

grids cards css html #90 / learning closed
#problem
#css
✍️ 1 comments

1 solution

display: grid;
grid-template-columns: repeat(3,1fr);
grid-gap: 20px;
learn box-shadow #88 / learning closed
#css
✍️ 1 comments

Summary

box-shadow properties doesnt ADD something to bottom left or anything It SHIFT (moves the shadow) to left-right (x) or top-bottom (y) the third is the blurry radious (like gradient) the 4th is like make bigger the surface (like border) ..

10px 5px 5px red;
box-shadow: 12px 12px 2px 30px rgba(0, 0, 255, .2);

grapql basics #79 / learning closed
#topic
#graphql
✍️ 3 comments

Params

Alias

To rename responses,without conflicts

Fragments

to reuse a small par of queries

types

query, mutation, or subscription like get/post-update/hooks

Directives

Conditional fetch props @include(if: $withFriends)

Call API GraphQL

//from browser 

https://graphql.org/graphql-js/graphql-clients/

var dice = 3;
var sides = 6;
var query = `query RollDice($dice: Int!, $sides: Int) {
  rollDice(numDice: $dice, numSides: $sides)
}`;

fetch('/graphql', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
  },
  body: JSON.stringify({
    query,
    variables: { dice, sides },
  })
})
  .then(r => r.json())
  .then(data => console.log('data returned:', data));

Apollo with React/Gatsby

import React from "react"
import ApolloClient  from 'apollo-boost';
import githubToken from '../secrets'
import fetch from 'isomorphic-fetch';

const token = githubToken;
const client = new ApolloClient({
  uri: 'https://api.github.com/graphql',
  request: (operation) => {
    operation.setContext({
      headers: {
        authorization: `Bearer ${token}`
      }
    })
  },
  fetch,
});

A better example for integration with Gatsby The particularity with Gatsby is to Wrap the root component with Apollo Provider but here we can use a global context to pass the client apollo instance to use it in components https://github.com/blade-sensei/rtn-review/blob/master/src/context/GlobalContextProvider.js

memory - learning techniques #73 / learning closed
#topic
✍️ 2 comments

Memory

  • repeat space
  • Assiciate semantic/group/Families
  • Learn also contraries
  • Create mental space to store (house/rooms)
  • Question the content / how should i do, is it right ?

Programming

  • Use paper
  • Basic concepts / think first on concepts likes then one day comeback to really study details underhood

Reading

  • Avoid thinking voice with speed, brain should not be annoy
  • Jump word/use global vision
  • Summary and think while starting on the 3 important points to remain
  • Change rythm fast/slow

Study

  • Pomodoro (not for all people)
  • breath for the brain
  • Concentrate on objectif like basketball/golf dont think on mouvement o other small things

Focus

  • Meditation
android browser has different toLocalDateString date as Desktop browser #91 / learning closed
✍️ 2 comments

toLocalDateString returns mm/dd/yyyy in android browser mobile but in desktop browser it return yyyy/mm/dd

Solution

let currentDate = new Date();
let formattedDate = currentDate;
    formattedDate.setMinutes(
      currentDate.getMinutes() + (currentDate.getTimezoneOffset() * -1)
    ); 
    
    formattedDate = formattedDate.toJSON();
    formattedDate = formattedDate.slice(0, 10);
array javascript time complexity #94 / learning open
#javascript
✍️ 2 comments
  • Access - O(1)
  • Appending - Amortized O(1) (sometimes resizing the hashtable is required; usually only insertion is required)
  • Prepending - O(n) via unshift, since it requires reassigning all the indexes
  • Insertion - Amortized O(1) if the value does not exist. O(n) if you want to shift existing values (Eg, using splice).
  • Deletion - Amortized O(1) to remove a value, O(n) if you want to reassign indices via splice.
  • Swapping - O(1)
trends tech #96 / learning closed
#ed: tech
✍️ 16 comments

react redux

create progessive web app

testing tools integration 2e2 teting serverless kubernetes docker swarn ML participate open source repo material ui wepack jest next js graphq ql apollo service worker BEM css

how to open web link to native app like spotify for example how it works

postgress redis all about cache ngnix authentication app (basics passwords etc) jenkins github actions CI Infrastructure terraforme config management Ansible vs Puppet Node GO

css grid flexbox float

Write a class and protptype

IIFE (Immediately Invoked Function Expression) is a

react redirections routing #100 / learning closed
#react
✍️ 1 comments

redirection by using parameters in url (query params) https://stackoverflow.com/questions/44121069/how-to-pass-params-with-history-push-link-redirect-in-react-router-v4

using redirection with push history also is explained here. this.props.location.state // it is equal to yourData

shorts cut code Javascript #101 / learning closed
#javascript
✍️ 3 comments

Math.pow Short Hand

var val =123console.log(Math.floor(val)) // Long version
console.log(~~val) // Short Version

Converting String To Number

const num1 = parseInt(100);
// In Short
console.log(+"100")
console.log(+"100.2")
HOC react #95 / learning closed
#react
✍️ 2 comments
import React from 'react';
export function WrappedAdd(WrappedComponent, {a, b}) {
   return class extends React.Component {
      constructor(props) {
      super(props);
    }
      render() {
         this.props.a = this.props.a++;
         this.props.b = this.props.b++;
       
         return <WrappedComponent a={this.props.a} b={this.props.b} />
      }
   }
}
hero on big size screen #1 / portfolio open
#enhancement
✍️ 0 comments
dotnetcore 3.0 Serialize Enums auto convert json for AP responses #105 / learning closed
#dotnet
✍️ 1 comments

Should add in Startup.cs

  services.AddMvc()
    .AddJsonOptions(options => {
        options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
        options.JsonSerializerOptions.IgnoreNullValues = true;
    });

And in the model

        [EnumMember(Value = "Venue")]