Push notification to web browser

 https://viblo.asia/p/push-notification-to-web-browser-MLzkOLZlvpq

Push notification là gì ?

Push notification là những tin nhắn do server đẩy xuống client thông qua một cổng cloud message nào đó rồi từ cổng này sẽ thông báo xuống máy chúng ta là có thông báo mới và hiển thị chúng. Chính vì vậy nên phải có internet thì mới push notification được.

Browser push notification

Tương tự như push notification, browser push notification sẽ gửi request xuống browser thông qua một cổng cloud message nào đó (gọi là endpoint) để hiển thị thông báo. Trong bài viết này chúng ta sẽ tìm hiểu cách gửi push notification thông qua Google Cloud Message xuống trình duyệt Chrome nhé.

main-qimg-e36ce150ca28f78d434fa4f2d5a9380a.png

1. Đăng ký Firebase Project

Đầu tiên chúng ta cần đăng ký một project tại https://console.firebase.google.com/

Sau khi đăng ký thành công chúng ta vào Project settings >> Cloud Messaging.

firebase project 2.png

Hoặc có thể truy cập trực tiếp vào liên kết sau https://console.firebase.google.com/project/<Your-Project-ID>/settings/cloudmessaging

firebase project.png

Trang này chứa Server key để push message mà chúng ta sẽ sử dụng sau này và và sender ID mà chúng ta cần phải đặt trong file manifest.json phần tiếp theo.

2. Tạo file Web App Manifest (manifest.json)

Chúng ta tạo một file manifest.json có chưa sender ID mà bạn vừa tạo ở bước trên với nội dung như sau:

{
  "name": "Push notification",
  "gcm_sender_id": "<Your Sender ID>"
}

Trên thực tế bạn có thể cho thêm nhiều thông tin khác như short_name, icon, start_url, display… nhưng mình chỉ để như vậy thôi là đủ rồi =))

Tiếp theo chúng ta phải include file này vào website:

<link rel="manifest" href="manifest.json">

3. Đăng ký service worker

Push notification có thể được gửi đến browser bất kỳ lúc nào kể cả khi bạn không mở website đó. Ví dụ khi bạn đăng ký nhận notification trên Facebook thì kể cả bạn không mở Facebook ra nhưng bạn vẫn có thể nhận notification của facebook khi có tin nhắn hay thông báo mới trên facebook. Để làm được như vậy là do service worker nó sẽ chạy ngầm trong background và được gọi ra bất cứ khi nào cần.

Đoạn code sau đây dùng để đăng ký 1 service worker vào browser:

var isPushEnabled = false;
window.addEventListener('load', function() {
    var pushButton = document.querySelector('.js-push-button');
    pushButton.addEventListener('click', function() {
        if (isPushEnabled) {
            unsubscribe();
        } else {
            subscribe();
        }
    });

    // Check that service workers are supported, if so, progressively
    // enhance and add push messaging support, otherwise continue without it.
    if ('serviceWorker' in navigator) {
        navigator.serviceWorker.register('/service-worker.js')
        .then(initialiseState);
    } else {
        console.warn('Service workers aren\'t supported in this browser.');
    }
});

Ở đây chúng ta sẽ để 1 button cho phép người dùng bật/tắt push notification nếu muốn.

<button class="js-push-button" disabled>
  Enable Push Messages
</button>

Chúng ta sẽ kiểm tra trạng thái hiện tại cho button này là bật hay tắt trong hàm initialiseState sau đây.

// Once the service worker is registered set the initial state
function initialiseState() {
  // Are Notifications supported in the service worker?
  if (!('showNotification' in ServiceWorkerRegistration.prototype)) {
    console.warn('Notifications aren\'t supported.');

    return;
  }

  // Check the current Notification permission.
  // If its denied, it's a permanent block until the
  // user changes the permission
  if (Notification.permission === 'denied') {
    console.warn('The user has blocked notifications.');

    return;
  }

  // Check if push messaging is supported
  if (!('PushManager' in window)) {
    console.warn('Push messaging isn\'t supported.');

    return;
  }

  // We need the service worker registration to check for a subscription
  navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) {
    // Do we already have a push message subscription?
    serviceWorkerRegistration.pushManager.getSubscription()
      .then(function(subscription) {
        // Enable any UI which subscribes / unsubscribes from
        // push messages.
        var pushButton = document.querySelector('.js-push-button');
        pushButton.disabled = false;

        if (!subscription) {
          // We aren't subscribed to push, so set UI
          // to allow the user to enable push
          return;
        }

        // Keep your server in sync with the latest subscriptionId
        sendSubscriptionToServer(subscription);

        // Set your UI to show they have subscribed for
        // push messages
        pushButton.textContent = 'Disable Push Messages';
        isPushEnabled = true;
      })
      .catch(function(err) {
        console.warn('Error during getSubscription()', err);
      });
  });
}

Sau khi đăng ký service worker thành công chúng ta sẽ có 1 đối tượng serviceWorkerRegistration cho phép ta subscribe push message. Điều này sẽ yêu cầu người dùng cho phép browser quyền gửi thông báo, nếu thành công sẽ trả lại một đối tượng PushSubscription sẽ chứa một thiết bị đầu cuối (endpoint). Endpoint này chúng ta cần phải lưu lưu lại trên server cho mỗi người dùng để sau này có thể xác định được endpoint này là của user nào để notification sao cho hợp lý.

function subscribe() {
  // Disable the button so it can't be changed while
  // we process the permission request
  var pushButton = document.querySelector('.js-push-button');
  pushButton.disabled = true;

  navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) {
    serviceWorkerRegistration.pushManager.subscribe()
      .then(function(subscription) {
        // The subscription was successful
        isPushEnabled = true;
        pushButton.textContent = 'Disable Push Messages';
        pushButton.disabled = false;
        // TODO: Send the subscription.endpoint to your server
        // and save it to send a push message at a later date
        return sendSubscriptionToServer(subscription);
      })
      .catch(function(e) {
        if (Notification.permission === 'denied') {
          // The user denied the notification permission which
          // means we failed to subscribe and the user will need
          // to manually change the notification permission to
          // subscribe to push messages
          console.warn('Permission for Notifications was denied');
          pushButton.disabled = true;
        } else {
          // A problem occurred with the subscription; common reasons
          // include network errors, and lacking gcm_sender_id and/or
          // gcm_user_visible_only in the manifest.
          console.error('Unable to subscribe to push.', e);
          pushButton.disabled = false;
          pushButton.textContent = 'Enable Push Messages';
        }
      });
  });
}

function sendSubscriptionToServer(subscription) {
    //save enpoint
}

Kết quả là bạn sẽ có một endpoint kiểu như sau gửi lên server:

https://android.googleapis.com/gcm/send/7vsNIgzF28KGspVmLUpMgYLAPA91bHPffi8zclbIBDcToXN_LEpT6iA87pgR-OfwWiyVdKh__rEt15W9n2o6cZ8nxrPoiiydjAJW6Fa9mE3Ts-ukL1KV8exGOnuJ-MuuVVycM0SmptG-rXdCPKTM5pvKiHk2rOAKdbvH9jcvg8h2gSi-zZJyT_Bd1rxaVh-L4NDzD7HyTkhF

Sau khi đã có endpoint thì bạn sẽ tạo một POST request đến endpoint đó để gửi push notification. Ở đây chúng ta sẽ sử dụng curl cho nó đơn giản nhé.

curl --header "Authorization: key=<YOUR_API_KEY>" --header
"Content-Type: application/json" https://android.googleapis.com/gcm/send -d
"{\"registration_ids\":[\"<YOUR_REGISTRATION_ID>\"]}"

Với <YOUR_API_KEY> là Server key của firebase project chúng ta đã tạo ở phần đầu tiên và <YOUR_REGISTRATION_ID> là phần cuối của URL endpoint, ví dụ như endpoint ở trên thì <YOUR_REGISTRATION_ID> sẽ là:

7vsNIgzF28KGspVmLUpMgYLAPA91bHPffi8zclbIBDcToXN_LEpT6iA87pgR-OfwWiyVdKh__rEt15W9n2o6cZ8nxrPoiiydjAJW6Fa9mE3Ts-ukL1KV8exGOnuJ-MuuVVycM0SmptG-rXdCPKTM5pvKiHk2rOAKdbvH9jcvg8h2gSi-zZJyT_Bd1rxaVh-L4NDzD7HyTkhF

4. Xử lý sự kiện khi nhận được push notification

Nếu để ý thì chúng ta sẽ thấy là mình không gửi bất kỳ một thông tin gì xuống client ví dụ như title, nội dung notification. Thay vì thế bạn sẽ phải dùng 1 request nữa để lấy ra message cần hiển thị. Và dĩ nhiên chúng ta sẽ phải gửi kèm endpoint lên để phân biệt là message đó của user nào. Request trả về json bao gồm có message, title, icon, url để khi bấm vào thông báo sẽ mở ra trang web nào đó. Dưới đây chúng ta sẽ xử lý sự kiện và dùng dùng request browser_push_notification?endpoint=xxx trả về json gần các thông tin cần thiết cho nofification.

self.addEventListener('push', function(event) {
  var apiPath = 'browser_push_notification?endpoint=';

  event.waitUntil(
    registration.pushManager.getSubscription()
    .then(function(subscription) {
      if (!subscription || !subscription.endpoint) {
        throw new Error();
      }

      apiPath = apiPath + encodeURI(subscription.endpoint);

      return fetch(apiPath)
      .then(function(response) {
        if (response.status !== 200){
          console.log("Problem Occurred:"+response.status);
          throw new Error();
        }

        return response.json();
      })
      .then(function(data) {
        if (data.status == 0) {
          console.error('The API returned an error.', data.error.message);
          throw new Error();
        }
        var data = data.data;
        var title = data.notification.title;
        var message = data.notification.message;
        var icon = data.notification.icon;
        var data = {
          url: data.notification.url
        };

        return self.registration.showNotification(title, {
          body: message,
          icon: icon,
          data: data
        });
      })
      .catch(function(err) {
        return self.registration.showNotification('Notification', {
          body: 'Có một sự kiện sắp diễn ra',
          icon: 'image/pn_logo.png',
          data: {
            url: "/"
          }
        });
      });
    })
  );
});

5. Xử lý sự kiện khi user click vào thông báo

self.addEventListener('notificationclick', function(event) {
    event.notification.close();
    var url = event.notification.data.url;
    event.waitUntil(
        clients.matchAll({
                type: 'window'
            })
            .then(function(windowClients) {
                for (var i = 0; i < windowClients.length; i++) {
                    var client = windowClients[i];
                    if (client.url === url && 'focus' in client) {
                        return client.focus();
                    }
                }
                if (clients.openWindow) {
                    return clients.openWindow(url);
                }
            })
    );
});

Đoạn code trên giúp cho việc click vào thông báo sẽ mở ra trang web tương ứng. Nếu như nó đã được mở rồi thì focus vào tab đó nếu chưa thì mở tab mới.

6. Unsubscribe push notification

Khi người dùng không muốn nhận thông báo nữa thì có thể unsubscribe, đoạn code dưới đây để xử lý việc này.

function unsubscribe() {
  var pushButton = document.querySelector('.js-push-button');
  pushButton.disabled = true;

  navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) {
    // To unsubscribe from push messaging, you need get the
    // subscription object, which you can call unsubscribe() on.
    serviceWorkerRegistration.pushManager.getSubscription().then(
      function(pushSubscription) {
        // Check we have a subscription to unsubscribe
        if (!pushSubscription) {
          // No subscription object, so set the state
          // to allow the user to subscribe to push
          isPushEnabled = false;
          pushButton.disabled = false;
          pushButton.textContent = 'Enable Push Messages';

          return;
        }

        var subscriptionId = pushSubscription.subscriptionId;
        // TODO: Make a request to your server to remove
        // the subscriptionId from your data store so you
        // don\'t attempt to send them push messages anymore

        // We have a subscription, so call unsubscribe on it
        pushSubscription.unsubscribe().then(function(successful) {
          pushButton.disabled = false;
          pushButton.textContent = 'Enable Push Messages';
          isPushEnabled = false;
        }).catch(function(e) {
          // We failed to unsubscribe, this can lead to
          // an unusual state, so may be best to remove
          // the users data from your data store and
          // inform the user that you have done so

          console.log('Unsubscription error: ', e);
          pushButton.disabled = false;
          pushButton.textContent = 'Enable Push Messages';
        });
      }).catch(function(e) {
        console.error('Error thrown while unsubscribing from push messaging.', e);
      });
  });
}

Ok vậy là chúng ta hoàn thành xong việc push notification trên trình duyệt Chrome/Cốc Cốc. Sau đây là demo ứng dụng dùng push notification.

https://browser-push-notification.herokuapp.com/

Bài viết hoàn toàn dựa trên việc tìm hiểu cá nhân nên có thể sai sót có gì mọi người cứ comment nhiệt tình ak =)).

Tham khảo:

Jquery click outside

 $(document).mouseup(function (e)

{

    var container = new Array();

    container.push($('#item_1'));

    container.push($('#item_2'));

    

    $.each(container, function(key, value) {

        if (!$(value).is(e.target) // if the target of the click isn't the container...

            && $(value).has(e.target).length === 0) // ... nor a descendant of the container

        {

            $(value).hide();

        }

    });

});

CKEditor support style attributes

 https://ckeditor.com/docs/ckeditor4/latest/guide/dev_allowed_content_rules.html

extraAllowedContent: '*[*]{*}(*)',

elements [attributes]{styles}(classes)
// A rule accepting <p> and <h1> elements, but without any property.
p h1

// A rule accepting <p> and <h1> elements with optional "left" and "right" classes.
// Note: Both elements may contain these classes, not only <h1>.
p h1(left,right)

// A rule accepting <p> and <h1> elements with all their attributes.
p h1[*]

// A rule accepting <p> and <h1> elements with all their attributes
// starting from 'data-'.
p h1[data-*]

// A rule accepting <a> only if it contains the "href" attribute.
a[!href]

// A rule accepting <img> with a required "src" attribute and an optional
// "alt" attribute plus optional "width" and "height" styles.
img[alt,!src]{width,height}

// The same as above, because the order of properties and their lists is irrelevant and white-spaces are ignored.
img { height, width } [ !src, alt ]
// Rules allowing:
// * <p> and <h1> elements with an optional "text-align" style,
// * <a> with a required "href" attribute,
// * <strong> and <em> elements,
// * <p> with an optional "tip" class (so <p> element may contain
//	a "text-align" style and a "tip" class at the same time).
p h1{text-align}; a[!href]; strong em; p(tip)

// Rules allowing:
// * <p> and <h1> elements with an optional "id" attribute,
// * <a> with a required "href" attribute and an optional "id" attribute.
p h1; a[!href]; *[id]

"AppendChild" same element multiple times in js

 https://dev.to/kiumad/can-you-appendchild-same-element-multiple-times-in-js-probably-not-4j

We can use cloneNode() , but I use another way
I want to use a function
like this :

//main function
function appendChildMultiple(parent) {
  //check function argument is an element
  if (parent.nodeType !== undefined) {
    const pTag = document.createElement("p");
    pTag.innerText = "This is the appended element";
    //finally append child to parent
    parent.appendChild(pTag);
  }
}

and use it :

const d1 = document.createElement("div");
const d2 = document.createElement("div");
appendChildMultiple(d1);
appendChildMultiple(d2);

How to validate start date and end date in bootstrap datepicker

 https://w3codegenerator.com/code-snippets/bootstrap/how-to-validate-start-date-and-end-date-in-bootstrap-datepicker

How to validate start date and end date in bootstrap datepicker

Through many examples, we will learn how to resolve the "How to validate start date and end date in bootstrap datepicker".

You can validate the start date and end date in the bootstrap datepicker. The end date must be after the date selected in the start date.
  • Start date and end date validation in bootstrap datepicker

    Bootstrap date picker CDN

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css" integrity="sha512-mSYUmp1HYZDFaVKK//63EcZq4iFWFjxSL+Z3T/aCt4IO9Cejm03q3NKKYN6pFQzY0SBOr8h+eCIAZHPXcpZaNw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js" integrity="sha512-T/tUfKSV1bihCnd+MxKD0Hm1uBBroVYBOYSk1knyvQ9VyZJpc/ALb4P0r6ubwVPSGB2GvjeoMAJJImBG12TiaQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    

    HTML (Input date)

    <div class="form-group">
        <label for="startDate">Start Date *</label>
        <input type="text" class="form-control" name="start_date" id="startDate" value="" />
    </div>
    
    <div class="form-group">
        <label for="endDate">End Date *</label>
        <input type="text" class="form-control" name="end_date" id="endDate" value="">
    </div>
    

    javascript

    
    <script>
    //Start date and end date
    var start = new Date();
    // set end date to max one year period:
    var end = new Date(new Date().setYear(start.getFullYear()+1));
    
    $('#startDate, #endDate').datepicker('setDate', start );
    $('#startDate').datepicker({
        startDate : start,
        format: "yyyy-mm-dd",
        todayHighlight: true,
        autoclose: true,
        endDate   : end
    // update "toDate" defaults whenever "fromDate" changes
    }).on('changeDate', function(){
        // set the "toDate" start to not be later than "fromDate" ends:
        $('#endDate').val("").datepicker("update");
        $('#endDate').datepicker('setStartDate', new Date($(this).val()));
    }); 
    
    $('#endDate').datepicker({
        startDate : start,
        format: "yyyy-mm-dd",
        todayHighlight: true,
        endDate   : end
    }); 
    </script>
    
  • How can I set start and end dates for a Datepicker?

    var start_date = new Date().increment('week', 1);

    var end_date = new Date().increment('week', 5);

  • How to validate start date and end date in jQuery?

    You can do on two different dates for alert like this. $('#end_date').on('change', function(){ var startDate = $('#start_date').val(); var endDate = $('#end_date') }).

  • How can set current date in bootstrap Datepicker?

    Set current date in bootstrap datepicker.

    var date = new Date();
    var today = new Date(date. getFullYear(), date. getMonth(), date. getDate());
    var optSimple = {
    	format: 'mm-dd-yyyy',
    	todayHighlight: true,
    	orientation: 'bottom right',
    	autoclose: true,
    
  • How do I know if my Datepicker is loaded?

    You can check to see if the datepicker script has loaded using below script.

    if ($.fn.datepicker) { $('.datepicker').datepicker(); }

  • What is date parse in Javascript?

    The Date.parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31).

  • What is Autoclose in Datepicker?

    autoclose. Whether or not to close the datepicker immediately when a date is selected.

  • Does bootstrap have a time picker?

    Bootstrap time picker is a jQuery plugin which allows the user to select a time in the Bootstrap form without the necessity of using custom JavaScript code.

  • Is there a bootstrap Datepicker?

    Bootstrap date picker is a plugin that adds the function of selecting time without the necessity of using custom JavaScript code. This documentation may contain syntax introduced in the MDB 4.17.

  • How do I close Datetimepicker after selecting date?

    On change date function you can close the datepicker.

    $(document).ready(function () {
        $('#example1').datepicker({
            format: "dd/mm/yyyy",
            autoclose: true
        });
    
        //Alternativ way
        $('#example2').datepicker({
          format: "dd/mm/yyyy"
        }).on('change', function(){
            $('.datepicker').hide();
        });
    });

How To Get Last Record In Each Group In MySQL

 https://ubiq.co/database-blog/get-last-record-group-mysql/

Sometimes you may need to select most recent record or get latest record for each date,user, id or any other group. Here’s the SQL query to get last record in each group in MySQL, since there is no built-in function for it. You can also use it to select last row for each group in PostgreSQL, SQL Server & Oracle.

 

How To Get Last Record In Each Group In MySQL

Here are the steps to get last record in each group in MySQL.

Let’s say you have a table product_sales(product, order_date,sale) that contains sales data for multiple products.

mysql> create table product_sales(product varchar(255),order_date date, sale int);

mysql> insert into product_sales(product,order_date, sale)
     values('A','2020-05-01',250),
     ('B','2020-05-01',350),
     ('C','2020-05-01',1250),
     ('A','2020-05-02',450),
     ('B','2020-05-02',650),
     ('C','2020-05-02',1050),
     ('A','2020-05-03',150),
     ('B','2020-05-03',250),
     ('C','2020-05-03',1850);

mysql> select * from product_sales;
+---------+------------+------+
| product | order_date | sale |
+---------+------------+------+
| A       | 2020-05-01 |  250 |
| B       | 2020-05-01 |  350 |
| C       | 2020-05-01 | 1250 |
| A       | 2020-05-02 |  450 |
| B       | 2020-05-02 |  650 |
| C       | 2020-05-02 | 1050 |
| A       | 2020-05-03 |  150 |
| B       | 2020-05-03 |  250 |
| C       | 2020-05-03 | 1850 |
+---------+------------+------+

Bonus Read : How to Get Record with Max Value in MySQL

 

Let’s say you want to get last record in each group, that is, for each product. First we use GROUP BY to get most recent date for each group.

mysql> select product,max(order_date) from product_sales group by product;
+---------+-----------------+
| product | max(order_date) |
+---------+-----------------+
| A       | 2020-05-03      |
| B       | 2020-05-03      |
| C       | 2020-05-03      |
+---------+-----------------+

Now that we know the most recent date for each group, we join this result with our original table to get latest record by date group.

mysql> select product_sales.* from product_sales,
           (select product,max(order_date) as order_date
                from product_sales
                group by product) max_sales
             where product_sales.product=max_sales.product
             and product_sales.order_date=max_sales.order_date;
+---------+------------+------+
| product | order_date | sale |
+---------+------------+------+
| A       | 2020-05-03 |  150 |
| B       | 2020-05-03 |  250 |
| C       | 2020-05-03 | 1850 |
+---------+------------+------+

Bonus Read : How to Create View in MySQL

 

How to Select Most Recent Record for Each User

Similarly, you can select most recent record for each user or get latest record for each id. Let’s say you have the following table user_data(user_id,transaction_date,sale) with user transaction data

mysql> create table user_data(user_id int, transaction_date date, sale int);

mysql> insert into user_data(user_id,transaction_date, sale)
          values('1','2020-05-01',25),
          ('2','2020-05-01',35),
          ('3','2020-05-01',125),
          ('1','2020-05-02',40),
          ('2','2020-05-02',50),
          ('3','2020-05-02',50),
          ('1','2020-05-03',15),
          ('2','2020-05-03',25),
          ('3','2020-05-03',50);


mysql> select * from user_data;
+---------+------------------+------+
| user_id | transaction_date | sale |
+---------+------------------+------+
|       1 | 2020-05-01       |   25 |
|       2 | 2020-05-01       |   35 |
|       3 | 2020-05-01       |  125 |
|       1 | 2020-05-02       |   40 |
|       2 | 2020-05-02       |   50 |
|       3 | 2020-05-02       |   50 |
|       1 | 2020-05-03       |   15 |
|       2 | 2020-05-03       |   25 |
|       3 | 2020-05-03       |   50 |
+---------+------------------+------+

Bonus Read : How to Get New Users Per Day in MySQL

 

First, we get the latest date for each user id using GROUP BY.

mysql> select user_id,max(transaction_date) from user_data group by user_id;
+---------+-----------------------+
| user_id | max(transaction_date) |
+---------+-----------------------+
|       1 | 2020-05-03            |
|       2 | 2020-05-03            |
|       3 | 2020-05-03            |
+---------+-----------------------+

Now that we know the most recent date for each user id, we join this result with our original table to get the latest record by user group.

mysql> select user_data.* from user_data,
                (select user_id,max(transaction_date) as transaction_date
                     from user_data
                     group by user_id) max_user
                  where user_data.user_id=max_user.user_id
                  and user_data.transaction_date=max_user.transaction_date;
+---------+------------------+------+
| user_id | transaction_date | sale |
+---------+------------------+------+
|       1 | 2020-05-03       |   15 |
|       2 | 2020-05-03       |   25 |
|       3 | 2020-05-03       |   50 |
+---------+------------------+------+

Hopefully, you can get last record in each group in MySQL

How to set default font and font size in CKEditor 4

 https://stackoverflow.com/questions/50887220/how-to-set-default-font-and-font-size-in-ckeditor-4

CKEDITOR.addCss(".cke_editable{cursor:text; font-size: 14px; font-family: Arial, sans-serif;}");

Git refusing to merge unrelated histories

 https://stackoverflow.com/questions/37937984/git-refusing-to-merge-unrelated-histories-on-rebase

In my case, the error was just fatal: refusing to merge unrelated histories on every try, especially the first pull request after remotely adding a Git repository.

Using the --allow-unrelated-histories flag worked with a pull request in this way:

git pull origin branchname --allow-unrelated-histories

As per 2.9.0 release notes - git pull has been taught to pass the --allow-unrelated-histories option to underlying git merge


Host Is Not Allowed to Connect to This MySQL Server

 

This error occurs due to the default configuration the MySQL database is currently using. This configuration allows connections only from the ‘root’ user when coming from ‘localhost’ and not other IP address ranges.

Resolution

Create a new administrator user or modify the root user to allow connections from ‘vScopeServerIP’.

To create a new administrator user, run the following queries in a mysql prompt:

> CREATE USER 'vScopeUserName'@'localhost' IDENTIFIED BY 'password';
> GRANT ALL PRIVILEGES ON *.* TO 'vScopeUserName'@'localhost' WITH GRANT OPTION;
> CREATE USER 'vScopeUserName'@'vScopeServerIP' IDENTIFIED BY 'password';
> GRANT ALL PRIVILEGES ON *.* TO 'vScopeUserName'@'vScopeServerIP' WITH GRANT OPTION;
> FLUSH PRIVILEGES;

To modify the root user (not recommended), run the following queries in a mysql prompt:

> GRANT ALL ON *.* to root@'vScopeServerIP' IDENTIFIED BY 'password';
> FLUSH PRIVILEGES;

utf8_general_ci and utf8_unicode_ci

 Update in 2019-10-29

As mentions by @Manuel Jordan in comments, utf8mb4_0900_ai_ci is the new default in MySQL 8.0, so the following is now again a better practice:

CREATE DATABASE mydatabase CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;

Answer before 2019-10-29
Note: The following is now considered a better practice (see bikeman868's answer):

CREATE DATABASE mydatabase CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;



MySQL is currently transitioning away from an older, flawed UTF-8 implementation. For now, you need to use utf8mb4 instead of utf8 for the character encoding part, to ensure you are getting the fixed version. The flawed version remains for backward compatibility, though it is being deprecated.

Key differences

  • utf8mb4_unicode_ci is based on the official Unicode rules for universal sorting and comparison, which sorts accurately in a wide range of languages.

  • utf8mb4_general_ci is a simplified set of sorting rules which aims to do as well as it can while taking many short-cuts designed to improve speed. It does not follow the Unicode rules and will result in undesirable sorting or comparison in some situations, such as when using particular languages or characters.

    On modern servers, this performance boost will be all but negligible. It was devised in a time when servers had a tiny fraction of the CPU performance of today's computers.

Benefits of utf8mb4_unicode_ci over utf8mb4_general_ci

utf8mb4_unicode_ci, which uses the Unicode rules for sorting and comparison, employs a fairly complex algorithm for correct sorting in a wide range of languages and when using a wide range of special characters. These rules need to take into account language-specific conventions; not everybody sorts their characters in what we would call 'alphabetical order'.

As far as Latin (ie "European") languages go, there is not much difference between the Unicode sorting and the simplified utf8mb4_general_ci sorting in MySQL, but there are still a few differences:

  • For examples, the Unicode collation sorts "ß" like "ss", and "Œ" like "OE" as people using those characters would normally want, whereas utf8mb4_general_ci sorts them as single characters (presumably like "s" and "e" respectively).

  • Some Unicode characters are defined as ignorable, which means they shouldn't count toward the sort order and the comparison should move on to the next character instead. utf8mb4_unicode_ci handles these properly.

In non-latin languages, such as Asian languages or languages with different alphabets, there may be a lot more differences between Unicode sorting and the simplified utf8mb4_general_ci sorting. The suitability of utf8mb4_general_ci will depend heavily on the language used. For some languages, it'll be quite inadequate.

What should you use?

There is almost certainly no reason to use utf8mb4_general_ci anymore, as we have left behind the point where CPU speed is low enough that the performance difference would be important. Your database will almost certainly be limited by other bottlenecks than this.

In the past, some people recommended to use utf8mb4_general_ci except when accurate sorting was going to be important enough to justify the performance cost. Today, that performance cost has all but disappeared, and developers are treating internationalization more seriously.

There's an argument to be made that if speed is more important to you than accuracy, you may as well not do any sorting at all. It's trivial to make an algorithm faster if you do not need it to be accurate. So, utf8mb4_general_ci is a compromise that's probably not needed for speed reasons and probably also not suitable for accuracy reasons.

One other thing I'll add is that even if you know your application only supports the English language, it may still need to deal with people's names, which can often contain characters used in other languages in which it is just as important to sort correctly. Using the Unicode rules for everything helps add peace of mind that the very smart Unicode people have worked very hard to make sorting work properly.

anti-pattern là gì

  Trong công nghệ và lập trình, Anti-pattern (mẫu phản diện) là những giải pháp bề ngoài có vẻ hiệu quả để giải quyết một vấn đề phổ biến, ...