Giter Club home page Giter Club logo

findings's People

Contributors

cjmling avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar

findings's Issues

Using angular after jquery append or insert

So you inserted some element or html using jQuery, and now you want to able to use ng-click (or any other stuff) on those newly inserted element?

Answer: You need to compile that newly inserted html/element into the $scope

How/Example:

Anywhere using jquery

$(".chandu").append('<div id="bandu"><span>etc etc etc</span></div>');

in Angular Controller

$scope.compileScope = function(){ //whatever function name doesn't matter
 var myHtml = angular.element(document.querySelector('#bandu'));
 $compile(myHtml)($scope);
}

Finally call this compileScope function whenever new element get added from jquery. ( its could be a bit tricky in your scenario)

In my case I was adding new element on a button click which was inside ng-controller so I just added ng-click="compileScope()" to that button so this function get called too.

Running node from php

exec("cd directoryPath && node myScript.js 2>&1", $out, $err);

  1. You need to cd into that directory of node script. What to put at directoryPath? use php function getcwd() to know your current directory then build your directoryPath on your need

  2. 2>&1 not sure what it is but we need it. $err will = 0 if no error, otherwise other integer value.

เริ่มใช้ socket io โดย ไม่ต้องสร้าง http ก่อน และไม่ต้องใช้ express

( ถ้าเราเริ่มต้นโดยยังไม่มี nodejs โปรเจ็คหรือ ยังไม่ได้สร้าง ก็ทำตามนี้ก่อน #10 เสร็จแล้วก็ค่อยมาทำตามด้านล่าง )

เริ่มด้วยการ install socket.io กัน โดยใช้ command

npm install socket.io --save

npm ก็จะเริ่ม download .. ซึ่งเบื้องหลัง npm ก็จะสร้างโฟลเดอร์ npm_modules ขึ้นมาถ้าไม่มีอยู่แล้ว แล้วก็โหลด module socket มาเก็บไว้ในนั้น และนอกจากแค่ socket มันก็จะโหลด module ไรอีกไม่รู้เยอะๆมาเก็บไว้ในนั้นอีกเพียบ

ตอนนี้เราก็จะมีโฟลเดอร์เป็นประมาณนี้

node-test
  - package.json
  - node_modules ( เป็นโฟลเดอร์และก็จะมี module socket io และอื่นๆอีกเยอะแยะ )
  - app.js

ใน app.js ก็จะมี

var Socket = require('socket.io');

var io = new Socket(9000); //ระบุพอร์ตเพื่อสื่อสารผ่าน socket และ บรรทัดนี้เหมือนว่ามันจะสร้าง http server ให้เราด้วยบนพอร์ต 9000

io.on('connection', function (socket) {

    console.log('Someone connected');

    socket.emit('news', { hello: 'world' }); //ส่งข้อความไปหา ห้อง news 

    socket.on('private_message', function (from, msg) {  //เมื่อมีคนตอบกลับมาบน ห้อง private_message
        console.log('I received a private message by ', from, ' saying ', msg);
    });

    socket.on('disconnect', function () {  // เมื่อมีคนหลุด
        console.log('user disconnected');
    });
});

และเราก็สร้าง index.html ขึ้นมา มีโค๊ดอันนี้

//include script client side ของ socket.io  เราจะ link include จาก node_modules ก็ได้หรือจะใช้จาก cdn ก็ได้
// ดู version อื่นๆ https://cdnjs.com/libraries/socket.io
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
<script>
    var socket = io('http://localhost:9000'); //subscribe ไปยังพอร์ตที่เราเพิ่งสร้าง
    
    socket.on('news', function (data) { // ฟังว่ามีคนส่งข้อความเข้า ห้อง news ไหม
        console.log(data);
        socket.emit('news', 'cjmling' , 'good afternoon'); // ตอบกลับห้อง news 
  });
</script>

คราวนี้ก็ถึงเวลา run socketio server หล่ะโดยใช้คำสั่ง

node app.js

แล้ว double click เปิดไฟล์ index.html ใน browser ดูแล้วดูใน tab console ของ developer tools จะเห็นข้อความการโต้ตอบ ส่งข้ความไปมา

node socket project , how to use socket in node , node create socket

Windows home path in powershell

%HOME%

try echo in powershell

echo %HOME%

as a result in normal case should output something like this

C:\Users\YOUR_USERNAME

** BUT ** Sometime its $HOME , so you may try echo $HOME

Not sure what is the difference and why its different on windows. ( at home %HOME% work , at work $HOME work )

Regex Examples

^chandu => match chandu only those which start with chandu
chandu$ => match chandu only those which end with chandu
chandu => match chandu anywhere in start or ending or middle
chandu|name => match chandu or name string
[a-zA-Z0-9] => match all a-z , A-Z , 0-9 in a string
[^a-zA-Z0-9] => match all other than a-z , A-Z , 0-9 in a string for example space , underscore or any others

Passport js authenticate bad request

If you are trying to authenticate using passport and only getting bad request error but no more useful error message then look into Custom Callback section of http://www.passportjs.org/docs/authenticate/
So try to log those param and you will get more clue.

app.get('/login', function(req, res, next) {
  passport.authenticate('local', function(err, user, info) {
    if (err) { return next(err); }
    if (!user) { return res.redirect('/login'); }
    req.logIn(user, function(err) {
      if (err) { return next(err); }
      return res.redirect('/users/' + user.username);
    });
  })(req, res, next);
});

React router doesn't render component

Had codes something like this.

<BrowserRouter>
                <div>
                    <ul>
                        <li>
                        <Link to='/'>Home</Link>
                        </li>
                        <li>
                        <Link to='/about'>About</Link>
                        </li>
                        <li>
                        <Link to='/topic/'>Topic</Link>
                        </li>
                        <li>
                        <Link to='/search'>Search</Link>
                        </li>
                    </ul>

                    <hr />
                    <Switch>
                        <Route path='/' component={Home} />
                        <Route path='/about' component={About} />
                        <Route path='/topic' component={Topic} /> 
                        <Route component={NoMatch} />                    
                    </Switch>
                </div>
            </BrowserRouter>
class NoMatch extends Component{
    render(){
        console.log('no match');
        return (<h2>No Match</h2>);
    };
}

class Search extends Component{
    render(){
        console.log('topic');
        return (<h2>Search</h2>);
    };
}

class Home  extends Component{
    constructor(props){
        super(props);
        console.log(props);
        console.log('home constructor');
    }
    render(){
        console.log('home');
        return (<h2>Home</h2>);
    };
}

Router wasn't working as it always match the home page no matter what route i click/visit.

The problem seems to be at home route route='/' where I need exact for this one. It makes sense to match this route everytime because all the route have / too. So it need to be exact.

<Route exact path='/' component={Home} />

Firestore Error: No document to update when trying to update

Had this error because i was confused about the id being used in when update()
You need to give the documentId, not any other id value you might have in that document.

screen shot 2561-04-02 at 11 52 21 pm

I was confused with the MySql as there they don't have document id , and most likely you will have auto increment id as primary key and used as reference when try to update

Firebase authentication basics theory

We don't authenticate user using username/password from "server/backend" side like we used to do normally. https://firebase.google.com/docs/auth/web/start

We do login in client side using firebase client library/module import firebase from 'firebase/app'; import 'firebase/auth'; and firebase client key. This client key we get from firebase console in authentication menu. (Its not same as service account key)

Before able to login in client side we have to create user with firebase auth first which is by calling this method firebase.auth().createUserWithEmailAndPassword(email, password)

Once user is created, we will see this user in authentication menu in firebase console.

Now we can login the user firebase.auth().signInWithEmailAndPassword(email, password). With this you will get user info as return value. The user info will contain email , uid and access token.

We send this access token to server.

In the server side , we use firebase admin library/module and service account credentials (need to download from google) to verify this access token with firebase. If it is correct then it will return user info which will have email, uid etc. informatin. Now we know that which user it is and proceed further.

NOTE:

  1. There is two different module , client side and server side (aka admin sdk)
  2. There is two different set of credentials , client have its own , for servicer side have it own

SEO : firebase authentication auth

เริ่มสร้าง project สำหรับ node js

สิ่งที่ต้องใช้คือ npm กับ node.js เช็คก่อนว่ามีลงไว้ไหม โดยพิมพ์ node -v กับ npm -v เพื่อเช็ค ถ้ามีลงไว้มันก็จะตอบกลับมาเป็นตัวเลขซึ่งก็คือ version ที่เราลงไว้นั่นเอง

ถ้ามีแล้วก็เริ่มกันเลย

เริ่มแรกก็ต้องมี Folder สำหรับเก็บไฟล์ project ของเรา ก็ทำการสร้าง folder ขึ้นมา

mkdir node-test

แล้วก็เข้าไปใน folder นั้น

cd node-test

หลังอยู่ใน folder project แล้วก็พิมพ์

npm init

ซึ่งจะเป็นการเริ่มสร้าง project นั่นเอง โดยมันจะสร้าง package.json ให้เรา .. มันจะถามหารายละเอียดอื่นๆสำหรับโปรเจคนั้น เราสามารถกด enter รัวๆไปได้เกือบหมดทุกอัน ให้มันสร้างค่า default หรือ เว้นว่างให้ ยกเว้น entry point ซึ่งก็คือการระบุไฟล์หลัก ถ้าเรากด enter ข้ามไปด้วย มันก็จะ default เป็น index.js ซึ่งก็ไม่มีปัญหาอะไร แต่ไม่รู้ทำไม เห็นตัวอย่างที่ใหนก็มักจะเปลี่ยนเป็น app.js กัน ก็เอาตามเขาแล้วกัน 555 ก็ตามนี้ถ้ามันถามให้เลือกก็เปลี่ยนเป็น app.js

พอเสร็จก็จะมี package.json ให้อีกไฟล์นึง สรุปตอนนี้ในโฟล์เดอร์ socket-test ก็จะมีแค่ไฟล์เดียว package.json น่ะครับ ยังไม่มี index.js หรือ app.js

node-test
  - package.json

เสร็จเราก็มาสร้างไฟล์ app.js หรือ index.js ว่างๆอันนึงเข้าไป ( จะสร้างผ่าน command line หรือ คลิ๊กขวาแล้วสร้างก็แล้วแต่ )

ตอนนี้ก็จะเป็น

node-test
  - package.json
  - app.js

นี่คือจุดเริ่มต้นของการเริ่มสร้าง project ด้วย nodejs ซึ่งน่ะตอนนี้มันยังใช้ทำไรไม่ได้ ไม่สามารถทดสอบไรได้ เดี๋ยวไว้เขียนวิธีเอาไปใช้ทำอย่างอื่นๆเช่นทำ http server หรือ ทำ socket ใน issue ต่อไป

node create project , npm , node new project

Pushing laravel job from Node.js or anywhere

So you want to add a job for laravel to process but not from laravel it self ? may be from nodejs?

You can do it by just creating a records in jobs table with payload equal to

{"job":"FootyRoom\\Jobs\\AnyJobClassName@handle", "data":{"key":value1,"key2":value2,.... and so on}}

you see, its just plain json object. having job and data

Now then you need to process this job, so create a job class in Jobs folder.

Most likely will look like this

<?php

namespace FootyRoom\Jobs;

use Illuminate\Queue\Jobs\DatabaseJob;  //As we are using DatabaseJob for storing our job

class AnyJobClassNameextends Job
{
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
    }

    /**
     * Execute the job.
     *
     * @param \Illuminate\Queue\Jobs\DatabaseJob;
     * @param  array  $data
     * @return void
     */
    public function handle(DatabaseJob $job, array $data)
    {
        $job variable will have details about the job
        $data variable will have details about the data passed

      // Do whatever you want to do with this job here

       // So obviously once you processed the job successfully you need to delete that job record
        if (!$job->isDeletedOrReleased()) {
            $job->delete();
        }
    }
}

Image VS Container

  • Image : contain the necessary software and configuration for applications. Comparing it to programming language it is like class with some predefined properties and behavior. .
  • Container : is like instance of that image. So to create container you need image.. You can create multiple container from a single image.

React create component

Mainly you can create in 2 ways

First Way: Functional Component aka dumb component

search-bar.js

import React from 'react';

const SearchBar = (props) => {
    return <input />;
};

export default SearchBar;

Second Way: Class based component aka smarts component

import React from 'react';

class SearchBar extends React.Component {
    render() {
        return <input />;
    }
}

export default SearchBar;

SourceTree Git : รวม commit หรือ squash commits และแก้ commit message

บางครั้งเราทำการ commit เล็กๆไปหลายอันแล้วอยากจะรวมมันไว้ใน commit เดียวกัน หรือ บางครั้งแค่อยากจะแก้คำ commit message เราก็ทำได้ตามนี้

  1. คลิ๊กขวาบน commit ( เลือกย้อนหลังไป 1 commit ) ในหน้า commit history แล้วเลือก rebase xxx yyy interactively..
    ยกตัวอย่าง ถ้าเรามี history เป็น
- a
- b
- c
- d

แล้วเราต้องการ squash b กับ c ก็กดที่ d
ถ้าเราต้องการ squash ระหว่าง a กับ c ก็กดที่ d แล้ว ในหน้าต่างถัดไปกดเลื่อน commit a ลงไปให้อยู่ติดกับ c แล้วค่อยทำขั้นตอนต่อไป แต่ต้องแน่ใจว่าตรงกลาง (ใน b) ไม่มีการแก้ไขไฟล์เดียวกัน

  1. ก็จะเปิดหน้า windows ใหม่ขึ้นมา

  2. กดเลือก commit message ( ไม่ใช่ติ๊กถูกใน Amend Commit น่ะ !!! ) เลือกให้เป็นแถบสีฟ้าพอ

  3. กดเลือกด้านล่าง Squash with previous แล้วก็ทำการแก้รวมคำ commit message ด้วย

หรือ ถ้าไม่ได้ต้องการ squash ก็เลือก edit message แทนเพื่อแก้ commit message

Docker compose คืออะไร คร่าวๆ ?

TLDR : Docker compose เป็นคล้ายๆ script คำสั่งเพื่อ สร้าง container หลายๆอันขึ้นมาพร้อมกัน โดยใช้คำสั่งเดียว

ปกติเราสร้าง container จาก image ใช่ไหมครับ ซึ่งยกตัวอย่างถ้าจะทดสอบ wordpress ก็คงต้อง สร้าง container mysql , container httpd หรือ container nginx หรือ มากกว่านั้นในกรณีที่เป็นโปรเจคอื่นที่ใช้ technology/service เยอะๆ และมันเชื่อมต่อกัน

ปัญหา : คือเราก็ต้องมาสร้าง container ทีหล่ะอัน config ทีหล่ะอัน ซึ่งมันเสียเวลาใช่ไหมครับ

Solution : และเพราะปัญหาด้านบนเลยเกิด docker compose ขึ้นมา คือเราสามารถกำหนดไว้ในไฟล์ docker-compose.yml เลย ว่าใช้ services ไรมั่ง ตั้งค่าไรมั่ง แล้วกด run command แค่ docker-compose up คำสั่งเดียว มันก็จะสร้าง container ทุกๆอันให้เราอัตโนมัติ ตามค่า config ที่เราตั้งไว้

Create ES6 module

// lib/counter.js
export let counter = 1;

export function increment() {
  counter++;
}

export function decrement() {
  counter--;
}


// src/main.js
import * as counter from '../../counter';

console.log(counter.counter); // 1
counter.increment();
console.log(counter.counter); // 2

Create custom emmet in vscode

  1. Create a folder (whatever name and where ever ) where you want to store your custom snippet and create a file snippets.js in it.

  2. So lets say if you created folder and file in user root directory that is at ~ for Mac then add this in user settings of VSCODE (no need to mention file name), vscode will automatically look for snippets.js in that folder

{
    "emmet.extensionsPath": "~/FolderName/"
}
  1. Create some snippets in snippets.js you just created . Some example snippets are here https://code.visualstudio.com/docs/editor/emmet#_using-custom-emmet-snippets

  2. Restart vscode ( quite and open ) or easier way to restart is press CMD + SHIFT + P to open command pallet and choose Reload Window

Php Mongo : Query date compare example

use MongoDate;
.
.
.
.
$query['datetime'] = [ '$lt' => new MongoDate(strtotime("2017-10-19")) ];

$cursor = $this->mongo->matches->find($query);

foreach ($cursor as $match) {
    // get each record details here in $match['key']
}

SEO: php query mongo by date, php mongodb date query

SourceTree Git : rebase เพื่ออยู่บน branch อื่น

ในกรณีที่อยากจะ rebase คือเอาโค๊ดที่เราแก้อยู่บน branch ของเรา ไปเขียนทับบนโค๊ดของ branch อื่น เราก็จะทำการ rebase นั่นเอง ซึ่งแน่นอนว่าอาจจะมีการ conflict เราก็ต้องแก้

  1. คลิ๊กขวาบน branch อื่น เลือก rebase

  2. ก็จะเกิด conflict เพราะบางไฟล์ เราแก้ใน branch เราด้วย ถูกแก้ใน branch อื่นด้วย ก็ทำการ fix conflict ก่อน
    2.1 Incoming Change : My Work , Current Change : Not my work

  3. หลังจากแก้ conflict แล้วก็ทำการ stage file ให้ครบ

  4. Action > Continue Rebase

  5. คราวนี้ก็ทำการ push ได้ แต่ต้อง force push ( อาจจะต้องตั้งค่า เปิดการใช้งาน force push ก่อน ไม่งั้นจะไม่เห็นช่องให้ติ๊ก force push)

  6. ดูให้ดีว่าเราเลือก branch ถูกต้องแล้วกดดำเนินการซะ :D

Create .bash_profile in user home directory

In case you want to add new path to your environment then its simpler to add it to a file .bash_profile in your home directory.

Go to home directory and check if you have already created .bash_profile file

cd ~
ls -al

If correct then you can just edit it and add the path you want to .

It may content something like this

export PATH=/usr/local/php5/bin:$PATH

Path are separated by :

The above line mean new PATH = /usr/local/php5/bin + other existing $PATH , which basically are defined/set other places. There are many way to set up path.

You can echo $PATH in terminal to see what are all the path.

IMPORTANT:
You need to restart the terminal before it recognize the new command.

Node path.join example

If i have directory structure like this

node_modules
log
- app.js
logs
- cron.log

I want to access cron.log from app.js I have to path.join like this

path.join(__dirname, '../logs', 'cron.log')

don't forget to require path in app.js

var path = require('path');

SourceTree Git : ย้อนกลับไป 1 commit , WIP

แบบสมมุติเราทำ WIP commit จากที่ทำงานแล้ว กลับมาบ้าน แน่นนอนว่าเราก็ต้องทำการ fetch all แล้ว ทำการ pull แล้วเลือก rebase ลงเครื่องเราก่อน

คราวนี้เราอยากจะไปอยู่ในสถานะย้อนหลัง 1 commit เสมือนว่า WIP commit นั่นไม่ได้เกิดขึ้น อยากเอาพวก changes ที่เรา commit ไปใน WIP นั่นลงมาในเครื่องเรา เพื่อที่เราจะได้แก้ต่อแล้วค่อย commit ใหม่ ใส่ message ดีๆ แล้วค่อย push

เราสามารถทำได้โดยคลิ๊กขวาที่ commit ย้อนหลัง 1 commit แล้วเลือก reset current branch to this commit แล้วเลือก soft/mixed/hard ก็ว่าไป

ทำความเข้าใจ ตัวอย่าง Compose ไฟล์ของ wordpress นิดนึง

https://docs.docker.com/compose/wordpress/#define-the-project

คือมันดึง official image ของ wordpress จาก https://hub.docker.com/_/wordpress/ ซึ่งมี docker file เป็นอันนี้
https://github.com/docker-library/wordpress/blob/666c5c06d7bc9d02c71fd48a74911248be6f5a5b/php5.6/apache/Dockerfile

หลังจากเรา compose wordpress ไปแล้ว เราก็จะเปิดหน้าเว็บ localhost:8000 ได้ ซึ่งไฟล์ที่เห็นหรือหน้าที่แสดงพวก config อะไรต่างๆของ wordpress มันดึงมาจาก /var/www/html เพราะมัน define ไว้เพื่อสร้าง volume ใน dockerfile ของ wordpress ( แต่จริงๆดูเหมือน wordpress ไม่ได้เป็นคนกำหนดว่า เข้า localhost:8000 แล้วให้วิ่งไป var/www/html น่ะ น่าจะเป็น apache กำหนดมากกว่า ดูเม้นล่าง )

แต่ปัญหาคือพวกไฟล์ wordpress ที่มันโหลดมามันเข้าไปอยู่ในนั้น ( var/www/html ) ได้ไง เพราะถ้าเราดู dockerfile นั่นดีๆ ก็จะเห็น script ว่ามันโหลด wordpress มาแล้วเก็บไว้ใน /usr/src/ ... แล้วมันไปอยู่ใน var/www/html ได้ไงหว่า

คำตอบคือ มันมี script เพิ่มเติมที่ทำการย้าย ซึ่งก็คือในบรรทัด ENTRYPOINT ซึ่ง run docker-entrypoint.sh แล้วในไฟล์ entrypoint เนี่ยะมันมีคำสั่งทำการ copy/ย้ายไฟล์ไปไว้ใน var/www/html นั่นเอง

UFS : Union File System คืออะไร

อธิบายไว้ที่นี่ดีมาก http://container-solutions.com/understanding-volumes-docker/

In order to understand what a Docker volume is, we first need to be clear about how the filesystem normally works in Docker. Docker images are stored as series of read-only layers. When we start a container, Docker takes the read-only image and adds a read-write layer on top. If the running container modifies an existing file, the file is copied out of the underlying read-only layer and into the top-most read-write layer where the changes are applied. The version in the read-write layer hides the underlying file, but does not destroy it — it still exists in the underlying layer. When a Docker container is deleted, relaunching the image will start a fresh container without any of the changes made in the previously running container — those changes are lost. Docker calls this combination of read-only layers with a read-write layer on top a Union File System.

Webpack not loading css or unexpected code or syntax error on css

May be not just on css or other js file. Spend an hour or two solving this but very silly mistake.

So i already had webpack running with webpack --watch. I was just only compiling js file at that time.

Then I wanted to add css into webpack. Downloaded those required style or css loaded and added the config in webpack. Imported the css into the js file. Boom webpack say those error.

It looked like webpack could not load its loader , of course it won't because we needed to restart webpack.

solution: quit webpack and restart to watch for changes again.

dammit

Set passportjs , passport-local , passport-local-mongoose to use email+password instead of username+password

So you want to use email+password to authenticate instead of "default" ( default of passport-local ) to use username+password?

So setup follows those tutorial , example : https://www.djamware.com/post/58bd823080aca7585c808ebf/nodejs-expressjs-mongoosejs-and-passportjs-authentication

Then you got to edit/change/set these

  1. passport.use(new LocalStrategy(User.authenticate())); => passport.use(User.createStrategy());
    Note: no more new LocalStrategy

  2. UserSchema.plugin(passportLocalMongoose); => UserSchema.plugin(passportLocalMongoose, {usernameField: 'email'});

Thats it. Now when you post form from front end make sure you post email and password field. As passportjs look into req object of nodejs to find them and do the authentication. At first i thougth we will have to give value to passport js to authenticate , but no they will pull value by themself from the req

React use lodash debounce on input change example

class SearchBar extends Component {

    constructor(props){
        super(props);
        this.state = {term: ''};
        this.onInputChange = this.onInputChange.bind(this);
        this._debouncedSearch = _.debounce((term) => this.videoSearch(term),1000);
    }

    render() {
        return (
            <div>
                <input  
                    value={this.state.term}
                    onChange={ this.onInputChange }/>
                    {this.state.term}
            </div>
        )
    }

    onInputChange(event){
        this.setState({term: event.target.value});
        this._debouncedSearch(event.target.value);
    }

    videoSearch(term){
       console.log('debounced', term);
    }
}

Docker Interactive Mode อธิบายหน่อย

หลายคนพูดถึง Interactive Mode แต่คืออออ .. google แล้วไม่เจอเหมือนกันว่าคำว่า interactive mode นี่มันหมายความว่ายังไง สามารถอธิบายเป็นประโยคยังไง ..

แต่เท่าที่เข้าใจคือ ตอนเราสร้าง container ให้เราเข้าไปในตัว container แล้วสามารถ run คำสั่งอื่นๆในตัว container ได้เช่น

ดูตัวอย่างวีดีโอนี้ https://youtu.be/pOGVngLsaX4?t=5m24s

ตัวอย่างคำสั่งเพิ่มเติม https://gist.github.com/mitchwongho/11266726

หรืออ่านอันนี้ ( อันนี้เหมือนว่าตอน สร้าง container แล้วไม่ได้ใช้ -it แล้วเราจะเข้าไปในตัว container ได้ยังไง ) https://askubuntu.com/questions/505506/how-to-get-bash-or-ssh-into-a-running-container-in-background-mode

เพิ่มเติม https://www.jacobtomlinson.co.uk/linux/2016/03/31/interactive-docker-containers/

Nodejs create module and export

IMPORTANT: We can't seems able to use import and export like we use in react or any other frontend javascript library.

"export and import have not been implemented in the V8 that node uses."

Therefore we do it by module.exports and require

You can do something like: https://stackoverflow.com/a/16631079/507203

module.exports = {
    method: function() {},
    otherMethod: function() {}
}

Or even just:

exports.method = function() {};
exports.otherMethod = function() {};

Then in the calling program:

var MyMethods = require('./myModule.js');
var method = MyMethods.method;
var otherMethod = MyMethods.otherMethod;

How to set up React, Webpack, Babel and MobX with decorators

Follow this tutorial for setting up How to set up React, Webpack 3, and Babel
https://www.valentinog.com/blog/react-webpack-babel/

Note: We are using webpack to load babel through babel-loader. We still need .babelrc and config the presets and plugins in the .babelrc itself.

Now we need to add MobX and use the decorators feature. We need to add two babel plugin

  1. https://github.com/loganfsmyth/babel-plugin-transform-decorators-legacy
    install by : npm install --save-dev babel-plugin-transform-decorators-legacy

  2. https://www.npmjs.com/package/babel-plugin-transform-class-properties
    install by : npm install --save-dev babel-plugin-transform-class-properties

So now our .babelrc looks like

{
    "presets": ["env","react"],
    "plugins": ["transform-decorators-legacy","transform-class-properties"]
}

Note : Seems orders of plugin, providing that transform-decorators-legacy plugin before the transform-class-properties is necessary for some reason

and the webpack.config.js module part looks like

module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                }
            }
        ]
    },

Docker Container lifecycle มันไม่ยืนยาว แล้วพวก data หรือ ฐานข้อมูลหล่ะ และ Docker Volumes คืออะไร ?

ปกติ container เราสร้างขึ้นมา เราสามารถลบ หรือ หยุด มันได้ใช่ไหมครับ ซึ่งเวลา dev กันจริงๆก็คงได้หยุดหรือลบ หรือ สร้างใหม่บ่อยๆ ตราวนี้ก็จะเห็นปัญหาว่าแล้ว พวกฐานข้อมูลหล่ะ จะทำไง บางทีเราก็ไม่อยากลบฐานข้อมูลเพราะฐานช้อมูลอาจจะใหญ่ ขี้เกียจรอ seed ขึ้นไปใหม่

เพราะเหตุนี้ docker ก็มีทางออกให้คือเก็บพวก data นี้ที่อื่น ซึ่งทำได้ 2 วิธี

  1. Data Volumes ( docker มีอันนี้หลัง bind mounts และแนะนำให้ใช้วิธีนี้ )
  2. Bind Mounts ( ดูวีดีโอดีๆตัวนี้ https://www.youtube.com/watch?v=pOGVngLsaX4 )

ตวามแตกต่างของ 2 อันนี้เท่าที่เข้าใจตอนนี้คือ
Data Volumes : เราสั่งให้ docker สร้างพื้นที่เพื่อเก็บข้อมูลให้เรา ซึ่งมันก็จะสร้างและเก็บไว้ในที่ๆของมันประมาณว่า relative path กับมัน มันจะรู้ว่าเก็บไว้ใหน ... พอเราสร้าง container ตัวนี้ในเครื่องคอมพ์ที่ใหนก็ตามมันก็สร้างที่เก็บข้อมูลตำแหน่งเดิมเมื่อเทียบกับตัวมัน ก็จะสามารถเข้าถึงได้โดยไม่มีปัญหา

ส่วน

Bind Mounts : คือเราสร้างพื้นที่เก็บข้อมูลในคอมพ์เราก่อน เป็น folder ไรก็ตาม แล้วสั่ง docker ว่านายเก็บข้อมูลที่จะต้องเก็บไว้ในตรงนี้น่ะ
ปัญหา: ที่จะเกิดขึ้นคือคราวนี้พอเราจะไป run เพื่อสร้าง container หรือ ทดสอบบนเครื่องอื่นๆ เช่นเครื่องที่เป็น windows บ้างหรือ Mac บ้าง คราวนี้ตำแหน่ง location ของ folder ที่เราระบุไว้มันก็ไม่เหมือนกันชะ เพราะ windows ใช้ path คนหล่ะแบบกับ Mac มันก็อาจจจะสร้างปัญหาได้... ตัวอย่างเราอาจจะเก็บไว้ใน C://folder/folder แต่ใน Mac ดันไม่มีไดร C: คราวนี้ก็เกิดปัญหาได้

น่าจะประมาณนี้น่ะ ไว้ค่อยมาอัปเดต

อันนี้ก๊อปมาจาก Docs .. ข้อดีของ volume เหนืออื่นจาก bind mounts (https://docs.docker.com/compose/compose-file/#volumes)
Volumes have several advantages over bind mounts:

  • Volumes are easier to back up or migrate than bind mounts.
  • You can manage volumes using Docker CLI commands or the Docker API.
  • Volumes work on both Linux and Windows containers.
  • Volumes can be more safely shared among multiple containers.
  • Volume drivers allow you to store volumes on remote hosts or cloud providers, to encrypt the contents of volumes, or to add other functionality.
  • A new volume’s contents can be pre-populated by a container.

Firestore get documentId after get data

return db.collection('xxxx').get()
    .then((snapshot) => { 
        snapshot.forEach((doc) => {
            // Actual document data = doc.data();
            // Actual document Id = doc.id;
        });
    })

Javascript Promises with mongoose

  1. First one should be done using Promise.resolve or return new Promise then laters one can be just put in then

Examples:

function getDatasss() {
    return getData()

    .then(function(matches) {
        getData2()
    });
}

function getData() {
    return Promise.resolve(
        Match.find({}).lean().exec()
    );
}

function getData2(){
   return Match.find({}).lean().exec();
}

Typescript getter and setter

class Point{
    private x;

    getX(){
       return this.x;
    }
    
    setX(value){
       this.x = value;
    }
}

let point = new Point;
let x = point.getX();
point.setX(10);

a may be a better? more beautiful? or equivalent method

class Point{
    private x;

    get X(){
       return this.x;
    }
    
    set X(value){
       this.x = value;
    }
}

let point = new Point;
let x = point.X;
point.X = 10;

But now it might break the camelCase notation which we might be following. So normally in javascript they prefix private variables with _ underscore. So it can be written as

class Point{
    private _x;

    get x(){
       return this._x;
    }
    
    set x(value){
       this._x = value;
    }
}

let point = new Point;
let x = point.x;
point.x = 10;

https://youtu.be/NjN00cM18Z4?t=41m16s

Express js get query parameter

Example

test?q=chandu

app.get('/test', (request, response) => {
   // to access chandu  , its there in request.query.q
});

nodejs execute mongodb results in sequence sync

use stream()

Example codes

var stream = Vote.find({............})
        .lean()
        .stream();

        stream.on('data', function (vote) {

           // once got a data pause it 
            stream.pause();
    
            // Do some async shit here
            return new Jobs(newJob).save()
            
            .then(function () {
                //Once that async shit done, then resume getting next data
                stream.resume();
            })

            .catch(function (err) {
                stream.destroy(err);
            });
        });

        stream.on('error', reject);

        //Once all the datas fetched from database, mean stream got close , resolve it. So you can chain further some async shit
        stream.on('close', resolve);
    });

Php Mongo : insert/upsert example

$result = $this->mongo->selectCollection('COLLECTION_NAME')->update(
            ['userId' => $xxxx, 'matchId' => $yyyy, 'predictorId' => $zzzz ],
            ['$set' => [
                'userId' => $xxx,
                'predictorId' => $yyy,
                'matchId' => $zzz,
                'vote' => $aaa,
            ]],
            ['upsert' => true]
        );

SEO: php mongo upsert, insert ,

Docker Commands

References

  1. semaphoreci.com : Dockerizing a PHP Application

VM

  • docker-machine ls => after installing Docker on our host, run this command to see the list of available VMs. A default VM is created by default.
$ docker-machine ls
NAME        ACTIVE   DRIVER       STATE     URL                         SWARM
default     *        virtualbox   Running   tcp://192.168.99.100:2376
dev                  virtualbox   Stopped
  • docker-mahine start|stop|restart|status <VM name> => we can manage our VMs using the start, stop, restart and status options.
$ docker-machine start default
Starting VM...
Started machines may have new IP addresses. You may need to re-run the `docker-machine env` command.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.