Thứ Sáu, 22 tháng 11, 2019

Thủ thuật Delay trong javascript

Cách 1:

 var runF = async (x) => {
    return new Promise(resolve => {
        setTimeout(() => {
            console.log('ket qua ', x);
            resolve();
        }, 3000);
    });
}

var lst = [1, 2, 3];

lst.reduce(async (pr, val) => {
    await pr;
    console.log('bat dau ', val);
    // ĐẶT HÀM Ở ĐÂY....
    await runF(val);

    console.log('ket thuc ', val);
}, Promise.resolve());

CÁCH 2:
function trickDelay() {

    console.log('BAT DAU');

    var index = 0;
    var length = lst.length;



    while (index < length) {
        setTimeout(function() {
            console.log('WAIT...');
            var viTriHienTai = index - length;

            //...CALL FUNCTION HERERE

            //
            index++;
        }, index * 2000);

        index++;

    }
}

Thứ Hai, 4 tháng 11, 2019

64 app cần cài khi cài lại máy Android

AceStream
AlReader
AnyBooks
aPhim
AutomaTag
Blokada
Box
Brave
Camscanner
Chiasenhac
ClipTV
ColorNote
Cram
Diaro
Drive
Dropbox
Facebook
Foody
FoxitPDF
Fpt play
Fx File
GoogleMap
Grab
HabitHub
HereMap
Laban Key
LichViet
LivetvLinks
Memrise
Messenger Lite
MoboPlayer
Mocha
Mocha
Momo
Moon Reader
Mx player
Nhaccuatui
OALD
Outlook
Phonograph
Photos
QuickPic
Shazam
Shopee
Skype
Slack
Snapseed
Sofascore
SoloLearn
SoptoHttp
Spotify
Telegram
TFlat
Tiki
Todoist
Translate
UnitConverter
ViettelPay
WPS Office
Xiami
Youtube
Zalo
ZingMp3
ZingTV

Thứ Sáu, 1 tháng 11, 2019

Chặn quảng cáo in-app ios/android

https://tinhte.vn/threads/huong-dan-chan-quang-cao-trong-ung-dung-bang-surge-adguard-pro-quantumult-va-adblock.2844988/
https://github.com/bigdargon/hostsVN/wiki/Opt-out
https://github.com/bigdargon/hostsVN/wiki/Adguard-Pro

Link file Host: https://app.box.com/s/5xebu3doftu21mtbjkqmpd0ywdt7wark

Opt out

BigDargon edited this page on 29 Jun · 7 revisions

Opt-out là gì?

  • Bạn vô tình click vào một quảng cáo trên một trang web nào đó có thể khiến bạn mệt mỏi khi liên tục bị “bám đuôi” theo bất kì trang web nào? Thậm chí nhiều lúc quảng cáo đó chẳng liên quan gì đến thói quen hay nhu cầu lướt web của bạn? Cảm thấy phiền phức và muốn cắt đuôi với quảng cáo?
  • Opt-Out là khái niệm cho các nhà quảng cáo biết rằng "tôi không muốn cá nhân hóa quảng cáo đối với tôi".
Hãy thực hiện theo các bước dưới đây tùy vào hệ điều hành bạn đang sử dụng.
  1. iOS
  2. PC
  3. Android

iOS

Bước 1: Vào Settings (Cài đặt) của thiết bị > Chọn Privacy (Quyền riêng tư) > Chọn Advertising (Quảng cáo) > Bật Limit Ad Tracking (Giới hạn theo dõi quảng cáo)

Bật đúng như hình là đã thành công

Bước 2: Nhấn vào dòng Reset Advertising Identifier... (Đặt lại mã định danh quảng cáo...)

Bước 3: Nhấn Reset Identifier (Đặt lại mã định danh) > Sau đó lặp lại Bước 2Bước 3 khoảng 2-3 lần, điều này nhằm chắc chắn hệ thống đã thực hiện reset

Bước 4: Trở về mục Privacy (Riêng tư) > Chọn Location Services (Dịch vụ định vị) > Chọn tiếp System Services (Dịch vụ hệ thống) > Tắt dòng Location-Based Apple Ads (Apple Ads dựa trên vị trí)

Bước 5: Bước này nhằm kiểm tra lại bạn đã reset thành công, tải apps đính kèm bên dưới để thực hiện kiểm tra
Tải ứng dụng: https://itunes.apple.com/app/my-tune-device/id1100377074?mt=8
  • Nếu ứng dụng xuất hiện dòng Ad-Tracking Limit là bạn đã thực hiện thành công

  • Nếu ứng dụng xuất hiện dãy ID như hình là bạn đã thực hiện không thành công là phải thực hiện lại từ Bước 1 đến Bước 3

Tiếp tục đến các bài hướng dẫn cài đặt

PC

Bước 1: Truy cập vào myaccount.google.com > Đăng nhập tài khoản Google của mình. Hoặc nhấn trái chuột vào góc vuông trên bên phải màn hình, chọn My Account (Tài khoản của tôi) và tiến hành đăng nhập tài khoản Google.

Bước 2: Nhấn chọn Ad Settings (Cài đặt quảng cáo) ở vùng Personal info and Privacy (Thông tin cá nhân và bảo mật) trong giao diện quản lý tài khoản của Google > Nhấn Manage ads settings (Quản lý cài đặt quảng cáo) > Trượt thanh kích hoạt của tùy chọn Ads Personalization (Cá nhân hóa quảng cáo) > Nhấn Turn Off (Tắt) để hoàn tất vô hiệu hóa quảng cáo cá nhân.


Android

Chỉ cần vào Google Settings (Cài đặt Google) > Ads (Quảng cáo) > Trượt thanh kích hoạt của tùy chọn Opt out of Ads Personalization (Tắt cá nhân hóa quảng cáo) là hoàn tất. Từ bây giờ, một số khu vực trên trang web sẽ được để trống hoặc chuyển sang hiển thị những nội dung quảng cáo khác với tần suất ít hơn thay vì hiển thị hàng loạt như trước kia.

Regex tìm link trong string javascript

var pattern = /(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/[^ );]*)?/gm;

CODE DEMO:

function addTagLink(contentAnswerItem) {
        //pattern url
        var pattern = /(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/[^ );]*)?/gm;

        //xử lý add tag <a> link
        var listMatch = contentAnswerItem.match(pattern);
        if (listMatch != null && listMatch.length > 0) {
            $.each(listMatch, function (index, value) {
                contentAnswerItem = contentAnswerItem.replace(value, '<a class="msg-link" target="_blank" href="' + value + '">' + value + '</a> ');

            });
        }
        //insert message tag
        $('.msg-insert').append("<div class='msg-receive'>" + contentAnswerItem + "</div>");
    }

Thứ Hai, 28 tháng 10, 2019

Checkbox check only one without ListItem

<span class="group1"><input id="CheckBox1" type="checkbox" name="CheckBox1" /></span>
<span class="group1"><input id="CheckBox2" type="checkbox" name="CheckBox2" /></span>
<span class="group1"><input id="CheckBox3" type="checkbox" name="CheckBox3" /></span>

$('[type=checkbox]').each(function() {
    var clienClassName = $(this).parent().attr('class');

    $(this).click(function(e) {

        // ensure proper event
        //if (!e) e = window.event;
        //var sender = e.target || e.srcElement;
        //if (sender.nodeName != 'INPUT') return;

        var clientId = $(this).attr('id');
        var isChecked = $(this).is(":checked");

        //không cho thay đổi item đã click
        if (isChecked == false)
            $(this).prop('checked', true);

        $('.' + clienClassName).each(function() {
            //this là thẻ span
            var checkId = $(this).children().first().attr('id');

            if (checkId != clientId) {
                $('#' + checkId).prop('checked', false);
            }
        });
    });
});

Checkbox group check only one item C#

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CheckboxDemo.aspx.cs" Inherits="WebApplicationApiUpload.CheckboxDemo" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>

<body>
    <form id="form1" runat="server">
        <div>

            <asp:CheckBoxList data-toggle="radio" runat="server" RepeatDirection="Horizontal">
                <asp:ListItem Value="TGJU"> TG </asp:ListItem>
                <asp:ListItem Value="GOLDOZ"> Gold </asp:ListItem>
                <asp:ListItem Value="SILVEROZ"> Silver </asp:ListItem>
            </asp:CheckBoxList>
        </div>

        <div>

            <asp:CheckBoxList data-toggle="radio" runat="server" RepeatDirection="Horizontal">
                <asp:ListItem Value="TGJU"> TG </asp:ListItem>
                <asp:ListItem Value="GOLDOZ"> Gold </asp:ListItem>
                <asp:ListItem Value="SILVEROZ"> Silver </asp:ListItem>
            </asp:CheckBoxList>
        </div>

    </form>
    <script src="js/jquery-3.2.1.min.js"></script>
    <script>
        $(document).ready(function () {
            // turn all CheckBoxLists labeled for 'radio' to be single-select
            $('[data-toggle=radio]').each(function () {
                var clientId = $(this).attr('id');
                $(this).find('input').each(function () {
                    // set parent's id
                    $(this).attr('data-parent', clientId);

                    // add an onclick to each input
                    $(this).click(function (e) {
                        // ensure proper event
                        if (!e) e = window.event;
                        var sender = e.target || e.srcElement;
                        if (sender.nodeName != 'INPUT') return;


                        // toggle off siblings
                        var id = $(this).attr('id');
                        var parent = $(this).attr('data-parent');
                        $('input[data-parent=' + parent + ']').not('#' + id).prop('checked', false);
                    });
                });
            });
        });
    </script>
</body>
</html>


Thứ Hai, 14 tháng 10, 2019

ffmpeg tạo thumb Video

ffmpeg -i b.mp4 -ss 00:00:00 -codec copy -t 120 output1.mp4 && ffmpeg -i output1.mp4 -vf "setpts=0.2*PTS" -r 6 -an output2.mp4


ffmpeg -i b.mp4 -ss 00:00:00 -codec copy -t 120 output1.mp4
ffmpeg -i output1.mp4 -vf "setpts=0.2*PTS" -r 6 -an output2.mp4

Get Youtube title from video ID

http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=' . $ref . '&format=json

Ví dụ

https://www.youtube.com/watch?v=DZDYZ9nRHfU

Ta có link:
http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=DZDYZ9nRHfU&format=json

Thứ Tư, 9 tháng 10, 2019

regex javascript dd/MM/yyyy

+ 31 day months
(0[13578]|1[02])[\/.](0[1-9]|[12][0-9]|3[01])[\/.](18|19|20)[0-9]{2}
(0[1-9]|[12][0-9]|3[01])[\/.](0[13578]|1[02])[\/.](18|19|20)[0-9]{2}

+ 30 day months
(0[469]|11)[\/.](0[1-9]|[12][0-9]|30)[\/.](18|19|20)[0-9]{2}
(0[1-9]|[12][0-9]|30)[\/.](0[469]|11)[\/.](18|19|20)[0-9]{2}

+ February 1-28 always valid
(02)[\/.](0[1-9]|1[0-9]|2[0-8])[\/.](18|19|20)[0-9]{2}
(0[1-9]|1[0-9]|2[0-8])[\/.](02)[\/.](18|19|20)[0-9]{2}

+ February 29 also valid on leap years
(02)[\/.]29[\/.](((18|19|20)(04|08|[2468][048]|[13579][26]))|2000)
29[\/.](02)[\/.](((18|19|20)(04|08|[2468][048]|[13579][26]))|2000)

==> which means it would be this if you put it all together:

Năm nhuận:
a) dd/MM/yyyy
((0[1-9]|[12][0-9]|3[01])[\/.](0[13578]|1[02])[\/.](18|19|20)[0-9]{2})|((0[1-9]|[12][0-9]|30)[\/.](0[469]|11)[\/.](18|19|20)[0-9]{2})|((0[1-9]|1[0-9]|2[0-8])[\/.](02)[\/.](18|19|20)[0-9]{2})|(29[\/.](02)[\/.](((18|19|20)(04|08|[2468][048]|[13579][26]))|2000))

b) dd/MM/yyyy cho phép số 0 có hoặc không ở ngày/tháng


((0?[1-9]|[12][0-9]|3[01])[\/.](0?[13578]|1[02])[\/.](18|19|20)[0-9]{2})|((0?[1-9]|[12][0-9]|30)[\/.](0?[469]|11)[\/.](18|19|20)[0-9]{2})|((0?[1-9]|1[0-9]|2[0-8])[\/.](0?2)[\/.](18|19|20)[0-9]{2})|(29[\/.](0?2)[\/.](((18|19|20)(04|08|[2468][048]|[13579][26]))|2000))

Chuẩn hơn cho dấu - và / :
((0?[1-9]|[12][0-9]|3[01])[\/](0?[13578]|1[02])[\/](18|19|20)[0-9]{2})|((0?[1-9]|[12][0-9]|30)[\/](0?[469]|11)[\/](18|19|20)[0-9]{2})|((0?[1-9]|1[0-9]|2[0-8])[\/](0?2)[\/](18|19|20)[0-9]{2})|(29[\/](0?2)[\/](((18|19|20)(04|08|[2468][048]|[13579][26]))|2000))|((0?[1-9]|[12][0-9]|3[01])[\-](0?[13578]|1[02])[\-](18|19|20)[0-9]{2})|((0?[1-9]|[12][0-9]|30)[\-](0?[469]|11)[\-](18|19|20)[0-9]{2})|((0?[1-9]|1[0-9]|2[0-8])[\-](0?2)[\-](18|19|20)[0-9]{2})|(29[\-](0?2)[\-](((18|19|20)(04|08|[2468][048]|[13579][26]))|2000))

c) MM/dd/yyyy
((0[13578]|1[02])[\/.](0[1-9]|[12][0-9]|3[01])[\/.](18|19|20)[0-9]{2})|((0[469]|11)[\/.](0[1-9]|[12][0-9]|30)[\/.](18|19|20)[0-9]{2})|((02)[\/.](0[1-9]|1[0-9]|2[0-8])[\/.](18|19|20)[0-9]{2})|((02)[\/.]29[\/.](((18|19|20)(04|08|[2468][048]|[13579][26]))|2000))

Thứ Hai, 7 tháng 10, 2019

Kiểm tra ngày tháng dd/MM/yyyy là hợp lệ trong Js

function isValidDmy(dateDmy) {
    var seperated = '/';
   
    var arr = dateDmy.split(seperated);

    var day =  Number(arr[0]);
    var month = Number(arr[1]);
    var year = Number(arr[2]);

    if(isNaN(day)||isNaN(month)||isNaN(year))
        return false;
    else{

        var dateMdy = month+seperated+day+seperated+year;
        console.log(dateMdy);
        return validateMdy(dateMdy);
    }
}

//input is M/d/yyyy or MM/dd/yyyy
function validateMdy(input) {
    var date = new Date(input);
    input = input.split( '/' );  
    return date.getMonth() + 1 === +input[0] &&
           date.getDate() === +input[1] &&
           date.getFullYear() === +input[2];
}

console.log(isValidDmy('29/22/2000'));

Javascript Print format

// print format
//-- print("Hello, {0}! The answer is {1}.", "World", 42);
function format(fmt, ...args) {
    if (!fmt.match(/^(?:(?:(?:[^{}]|(?:\{\{)|(?:\}\}))+)|(?:\{[0-9]+\}))+$/)) {
        throw new Error('invalid format string.');
    }
    return fmt.replace(/((?:[^{}]|(?:\{\{)|(?:\}\}))+)|(?:\{([0-9]+)\})/g, (m, str, index) => {
        if (str) {
            return str.replace(/(?:{{)|(?:}})/g, m => m[0]);
        } else {
            if (index >= args.length) {
                throw new Error('argument index is out of range in format');
            }
            return args[index];
        }
    });
}

Thứ Sáu, 4 tháng 10, 2019

Check hợp lệ form sử dụng Jquery

Với ý tưởng ban đầu là tạo các regEx để check hợp lệ và nạp lỗi vào các thẻ HTML đã định sẵn.

Code HTML:
<!DOCTYPE html>
<html>

<head>
    <title>Validate Lib Demo</title>

    <style type="text/css">
        .message {
            color: red;
        }
    </style>

    <script type="text/javascript" src="jquery-3.2.1.min.js"></script>
    <script type="text/javascript" src="jquery.validate-1.9.1.min.js"></script>
    <script type="text/javascript" src="my-simple-validate.js"></script>
</head>

<body>
    <form method="get" accept-charset="utf-8" style="width:600px;margin: 0px auto;" id="formDemo">
        <fieldset>
            <legend>Demo jQuery Validation</legend>
            <div>
                <label>Số</label>
                <input id="txtNumber" name="ho" type="text" placeholder="Vui lòng nhập số">
            </div>
            <p id="txtNumber_message" class="message"></p>

            <div>
                <label>Địa chỉ mail</label>
                <input id="txtDiaChi" name="diachi" type="text" placeholder="Vui lòng nhập địa chỉ" />
            </div>

            <div>
                <label>Ten</label>
                <input id="txtTen" type="text" placeholder="Vui lòng nhập tên" />
                <p id="txtTen_message" class="message"></p>
            </div>

            <div>
                <label>Email mới</label>
                <input id="txtEmailMoi" class="validator" type="text" placeholder="Vui lòng nhập tên" onkeyup="Validator(this,'required len(6,8) email','',null)" />
                <p id="txtEmailMoi_message" class="message"></p>
            </div>

            <div>
                <label>Mật khẩu</label>
                <input id="txtPass" name="pass" type="text" placeholder="Nhập mật khẩu" />
            </div>

            <div>
                <label>Mật khẩu</label>
                <input id="txtRePass" class="validator" onkeyup="Validator(this,'required cfpass(txtPass)','',null)" name="repass" type="text" placeholder="Nhập lại mật khẩu" />
                <p id="txtRePass_message" class="message"></p>
            </div>
            <div>
                <select id="car" class="validator" name="cars" onblur="Validator(this,'required','',null)">
                    <option value></option>
                    <option value="volvo">Volvo</option>
                    <option value="saab">Saab</option>
                    <option value="fiat">Fiat</option>
                    <option value="audi">Audi</option>
                </select>
                <p id="car_message" class="message"></p>
            </div>

            <div>
                <label>Ngày tháng</label>
                <input id="txtdate" class="validator" onkeyup="Validator(this,'required date','',null)" name="date" type="text" placeholder="Nhập ngày tháng" />
                <p id="txtdate_message" class="message"></p>
            </div>
            <br/>
            <button type="button" id="btnSubmit" onclick="return SubmitForm()">Submit event</button>
        </fieldset>
    </form>
</body>

</html>
Code JS:
//--regEx----------------------------------------------------------------------------------------//
var regNumber = /^\d+$/;
var regEmail = /^(?:[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i;
var regText = /[a-zA-Z0-9_]+$/;
var regVietnamese = /[a-zA-Z ÀÁÂÃÈÉÊÌÍÒÓÔÕÙÚĂĐĨŨƠàáâãèéêìíòóôõùúăđĩũơƯĂẠẢẤẦẨẪẬẮẰẲẴẶẸẺẼỀỀỂưăạảấầẩẫậắằẳẵặẹẻẽềềểỄỆỈỊỌỎỐỒỔỖỘỚỜỞỠỢỤỦỨỪễệỉịọỏốồổỗộớờởỡợụủứừỬỮỰỲỴÝỶỸửữựỳỵỷỹ]+$/;

//--errMessage-----------------------------------------------------------------------------------//
var error = "";
var REQUIRED_DF = "Trường bắt buộc";
var INVALID_DF = "Giá trị không hợp lệ";
var NUMBER_DF = "Giá trị nhập vào phải là số";
var EMAIL_DF = "Email không hợp lệ";
var TEXT_DF = "Giá trị nhập vào phải là chữ cái, chữ số hoặc ký tự gạch dưới";
var VIETNAMESE_DF = "Giá trị nhập vào phải là chữ cái tiếng Việt hoặc khoảng trắng";

var LEN_MINMAX_DF = "Giá trị nhập vào trong khoảng {0} - {1} ký tự";
var LEN_MIN_DF = "Giá trị nhập vào ít nhất {0} ký tự";
var LEN_MAX_DF = "Giá trị nhập vào không quá {0} ký tự";

var PASSWORD_NOT_MATCH_DF = "Mật khẩu không khớp";
var DATE_NOT_VALID_DF = "Ngày tháng không hợp lệ";

//---custom

var REQUIRED = " là trường bắt buộc";
var INVALID = " không hợp lệ";
var NUMBER = " nhập vào phải là số";
var EMAIL = " không hợp lệ";

var TEXT = " nhập vào phải là chữ cái, chữ số hoặc ký tự gạch dưới";
var VIETNAMESE = " nhập vào phải là chữ cái tiếng Việt hoặc khoảng trắng";

var LEN_MINMAX = " nhập vào trong khoảng {0} - {1} ký tự";
var LEN_MIN = " nhập vào ít nhất {0} ký tự";
var LEN_MAX = " nhập vào không quá {0} ký tự";

var PASSWORD_NOT_MATCH = " không khớp";

var DATE_NOT_VALID = "Ngày tháng không hợp lệ";


//--typeCheck------------------------------------------------------------------------------------//
//typeCheck 'required number email text vi len(6,x) cfpass(id_pass) date'
function Validator(item, typeCheck, description, customMessage) {

    //khởi gán lỗi
    error = "";

    //mô tả trường
    if (description == null)
        description = "";


    // lấy id
    var itemId = $(item).attr('id');
    //console.log(itemId);

    //kiểm tra thuộc tính: required
    //console.log(!regNumber.test($(item).val()));

    //var attr = $(item).attr('required');
    // if (typeof attr !== typeof undefined && attr !== false && !$.trim($(item).val()).length) {
    //     error = REQUIRED;
    // } else {

    var subTypeCheck = typeCheck.split(' ');

    for (var i = 0; i < subTypeCheck.length; i++) {
        //alert(subTypeCheck.length)
        //console.log(subTypeCheck);
        // console.log('+'+subTypeCheck[i]+'+');
        // console.log('++'+$(item).val()+'+');

        var check = subTypeCheck[i];

        // variables
        var minVal = 0;
        var maxVal = 0;
        var lenCheck = 0;

        var prePass = "";
        var reEnterPass = "";

        //--- len check:



        if (check.includes('len')) {
            check = 'len';

            var arrNum = subTypeCheck[i].replace('len(', '').replace(')', '').split(',');
            if (!isNaN(arrNum[0]) && !isNaN(arrNum[1])) {
                minVal = Number(arrNum[0]);
                maxVal = Number(arrNum[1]);
                lenCheck = 0;
            } else if (!isNaN(arrNum[0])) {
                minVal = Number(arrNum[0]);
                lenCheck = 1;
            } else if (!isNaN(arrNum[1])) {
                maxVal = Number(arrNum[1]);
                lenCheck = 2;
            }

        }

        //--- re-enter password check

        if (check.includes('cfpass')) {
            check = 'cfpass';

            var idItemPass = '#' + subTypeCheck[i].replace('cfpass(', '').replace(')', '');

            prePass = $(idItemPass).val();
            reEnterPass = $(item).val();
        }


        //--------------------------------------CHECK----------------------
        switch (check) {
            case 'required':
                if (!$.trim($(item).val()).length) {
                    error = REQUIRED;
                }
                break;

            case 'len':
                var lenValue = $.trim($(item).val()).length;
                switch (lenCheck) {
                    case 0:
                        console.log('minmaxx');
                        if (lenValue < minVal || lenValue > maxVal)
                            error = format(LEN_MINMAX, minVal, maxVal);
                        break;
                    case 1:
                        console.log('minx');
                        if (lenValue < minVal)
                            error = format(LEN_MIN, minVal);
                        break;
                    case 2:
                        console.log('maxx');
                        if (lenValue > maxVal)
                            error = format(LEN_MAX, maxVal);
                        break;
                }

                break;

            case 'text':
                if (!regText.test($(item).val())) {
                    error = TEXT;
                }
                break;

            case 'number':
                if (!regNumber.test($(item).val())) {
                    error = NUMBER;
                }
                break;

            case 'email':
                if (!regEmail.test($(item).val())) {

                    error = EMAIL;
                }
                break;

            case 'vi':
                if (!regVietnamese.test($(item).val())) {
                    error = VIETNAMESE;
                }
                break;

            case 'cfpass':
                if (prePass != reEnterPass)
                    error = PASSWORD_NOT_MATCH;
                break;

            case 'date':
                if (!isValidVietnamDate($.trim($(item).val())))
                    error = DATE_NOT_VALID;
                break;
        }

        console.log(error);
        if (error != "")
            break;
    }

    //------------------------------------------END CHECK ------------------------- //

    //------------ SHOW error ---

    if (error != "") {

        //console.log(customMessage);

        if (customMessage == null)
            $('#' + itemId + '_message').html(description + error);
        else
            $('#' + itemId + '_message').html(customMessage);
    } else {
        //console.log("YES");
        $('#' + itemId + '_message').empty();

    }
}

//---------------- SUBMIT FORM

function SubmitForm() {

    var total = "";

    $(".validator").each(function() {
        var lstAtrr = getAttributes($(this)); // lấy tất cả thuộc tính
        console.log(lstAtrr["id"]); // lấy giá trị từng thuộc tính
        console.log(Object.keys(lstAtrr)); // lấy tất cả key thành mảng

        lstAllKey = Object.keys(lstAtrr);

        if (lstAllKey.includes('onblur'))
            $(this).blur();

        if (lstAllKey.includes('onclick'))
            $(this).click();

        if (lstAllKey.includes('onkeyup'))
            $(this).keyup();

        if (lstAllKey.includes('onkeydown'))
            $(this).keydown();

        if (lstAllKey.includes('onkeypress'))
            $(this).keypress();

        if (lstAllKey.includes('onfocus'))
            $(this).focus();

        if (lstAllKey.includes('onchange'))
            $(this).change();

        //


        // kiểm tra còn lỗi hay không??
        var messId = '#' + lstAtrr["id"] + '_message';
        console.log($(messId).html());

        // if($(messId).html()!='')
        //     return false;
        // return true;

        total = total + $(messId).html();
        // console.log('TOTAL=');
        // console.log(total);

    });

    if (total == "") {
        console.log("FORM is true");

        return true;
    } else {
        console.log("FORM is false");
        return false;
    }
}


//--------------- Các hàm phụ trợ-------------------------.......
// lấy tất cả các thuộc tính element
function getAttributes($node) {
    var attrs = {};
    $.each($node[0].attributes, function(index, attribute) {
        attrs[attribute.name] = attribute.value;
    });
    return attrs;
}

// print format
//-- print("Hello, {0}! The answer is {1}.", "World", 42);
function format(fmt, ...args) {
    if (!fmt.match(/^(?:(?:(?:[^{}]|(?:\{\{)|(?:\}\}))+)|(?:\{[0-9]+\}))+$/)) {
        throw new Error('invalid format string.');
    }
    return fmt.replace(/((?:[^{}]|(?:\{\{)|(?:\}\}))+)|(?:\{([0-9]+)\})/g, (m, str, index) => {
        if (str) {
            return str.replace(/(?:{{)|(?:}})/g, m => m[0]);
        } else {
            if (index >= args.length) {
                throw new Error('argument index is out of range in format');
            }
            return args[index];
        }
    });
}

//-------------------
function isValidVietnamDate(dateDmy) {
    if (dateDmy.includes('/'))
        return isValidDmyWithSeparated(dateDmy, '/');
    else
        return isValidDmyWithSeparated(dateDmy, '-');
}

//Hàm chính kiểm tra ngày tháng separated = / or -
function isValidDmyWithSeparated(dateDmy, separated) {

    var arr = dateDmy.split(separated);

    console.log(arr.length);

    if (arr.length != 3)
        return false;


    var day = Number(arr[0]);
    var month = Number(arr[1]);
    var year = Number(arr[2]);

    if (isNaN(day) || isNaN(month) || isNaN(year) || year < 1000)
        return false;
    else {
        var dateMdy = month + separated + day + separated + year;
        return validateMdy(dateMdy, separated);
    }
}

//input is M/d/yyyy or MM/dd/yyyy
function validateMdy(input, separated) {
    var date = new Date(input);
    input = input.split(separated);
    return date.getMonth() + 1 === +input[0] &&
        date.getDate() === +input[1] &&
        date.getFullYear() === +input[2];
}

Check and Convert Video .mp4 From H265 to H264 C#

Trên Android chỉ chạy được mp4 với codec_name là H264, vì vậy cần hàm chuyển đổi video trên Server rồi trả api kết quả.

Code:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class ConvertVideoH264 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ConvertVideoH265toH264();
    }

    string exeFfmpegPath = @"F:\OTL\ffmpeg\ffmpeg\bin\ffmpeg.exe";
    string exeFfprobePath = @"F:\OTL\ffmpeg\ffmpeg\bin\ffprobe.exe";
    string fileInputPath = @"F:\OTL\ffmpeg\ffmpeg\bin\input.mp4";
    protected void ConvertVideoH265toH264()
    {
        string output = @"F:\OTL\ffmpeg\ffmpeg\bin\output.mp4";

        string cmdConvertH265toH264 = String.Format("-i {0} -c:v libx264 -crf 23 -vf format=yuv420p -c:a copy {1}", fileInputPath, output);

        string codecName = GetCodecName();
        //chuyen doi H255->H264
        if (codecName != "h264")
        {
            Task<string> callTask = Task.Run(() => RunFFTask(exeFfmpegPath, fileInputPath, cmdConvertH265toH264));
            callTask.Wait();
        }
    }

    protected string GetCodecName()
    {
        string cmdGetCodec = String.Format("-v error -select_streams v:0 -show_entries stream=codec_name -of default=noprint_wrappers=1:nokey=1 {0}", fileInputPath);

        Task<string> callTask = Task.Run(() => RunFFTask(exeFfprobePath, fileInputPath, cmdGetCodec));
        callTask.Wait();
        // does NOT deadlock - shouldn't call await Task.Result on main
        string codec = callTask.Result;
        return codec;
    }

    protected Task<string> RunFFTask(string exeFilePath, string fileInputPath, string cmd)
    {
        var tcs = new TaskCompletionSource<string>();

        // Use ProcessStartInfo class
        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.CreateNoWindow = false;
        startInfo.UseShellExecute = false;
        startInfo.FileName = exeFilePath;
        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
        startInfo.Arguments = String.Format("{0}", cmd);
        startInfo.RedirectStandardOutput = true; // add to receive output

        var process = new Process
        {
            StartInfo = startInfo,
            EnableRaisingEvents = true,
        };

        process.Exited += (sender, args) =>
        {
            tcs.SetResult(process.StandardOutput.ReadLine());

            process.Dispose();
        };

        process.Start();

        return tcs.Task;
    }
}

Thứ Tư, 2 tháng 10, 2019

Linq trong C#

static void LinqDemo()
        {
            string sentence = "the quick brown fox jumps over the lazy dog";
            string[] list = sentence.Split(' ');

            //------------- Sorting data-----------------------------
            //Sắp xếp tăng dần với cả 2 điều kiện lọc:
            List<string> queryTangDan = list.OrderBy(o => o.Length).ThenBy(o => o.Substring(0, 1)).Select(o => o.ToUpper()).ToList();
            //Sắp xếp giảm dần với cả 2 điều kiện lọc, sử dụng đảo ngược Reverse():
            List<string> queryGiamDanBangDaoNguoc = list.OrderBy(o => o.Length).ThenBy(o => o.Substring(0, 1)).Select(o => o.ToUpper()).Reverse().ToList();

            //Sắp xếp giảm dần với cả 2 điều kiện lọc:
            List<string> queryGiamDan = list.OrderByDescending(o => o.Length).ThenByDescending(o => o.Substring(0, 1)).Select(o => o.ToUpper()).ToList();

            //------------- Set data-----------------------------
            //Loại bỏ phần tử trùng
            List<string> queryLoaiBoTrung = list.Distinct().ToList();

            //Hiệu của 2 tập hợp: phần tử A không có trong B
            List<string> lstB = new List<string>() { "quick", "brown", "dog", "cat" };
            List<string> queryHieu = list.Except(lstB).ToList();

            //Giao của 2 tập hợp: có cả trong A và B
            List<string> queryGiao = list.Intersect(lstB).ToList();

            //Hợp của 2 tập hợp: có trong A hoặc B
            List<string> queryHop = list.Union(lstB).ToList();

            //------------- Filtering Data-----------------------------
            //Lọc theo điều kiện: độ dài chuỗi bằng 4
            List<string> queryFilter = list.Where(o => o.Length == 4).ToList();

            //Lọc theo kiểu dữ liệu
            object[] objs = new object[] { "12345", 12 };
            List<string> queryFilterType = objs.OfType<string>().ToList(); //return { "12345" }


            //------------- Quantifier Operations-----------------------------
            List<Student> students = new List<Student>();
            students.Add(new Student { ID = 1, Name = "Asutosh", Age = 19 });
            students.Add(new Student { ID = 2, Name = "Kapil", Age = 20 });
            students.Add(new Student { ID = 3, Name = "Sumit", Age = 21 });

            Student newStudent = new Student { ID = 3, Name = "Anil", Age = 22 };
            students.Add(newStudent);

            //Điều kiện Tất cả SV đều lớn hơn 20 tuổi
            bool isAllOver20 = students.All(student => student.Age > 20);

            //Điều kiện tồn tại SV lớn hơn 20 tuổi
            bool isAnyOver20 = students.Any(student => student.Age > 20);

            //Điều kiện chứa SV - cùng 1 đối tượng
            bool isContain = students.Contains(newStudent);


            Console.WriteLine(isContain);

            foreach (string str in queryFilterType)
                Console.WriteLine(str);

        }

Trộn 2 file có cùng số dòng trong C#

Vd: file a.txt là
A
B
C
Và file b.txt là
1
2
3
=> Khi trộn sẽ ra
A
1
B
2
C
3

Code:
static void TronFile()
        {
            // 2 files
            const string file1 = @"F:\OTL\Test Tron File\a.txt";
            const string file2 = @"F:\OTL\Test Tron File\b.txt";


            // Read a text file line by line. 
            string[] lines1 = File.ReadAllLines(file1);
            string[] lines2 = File.ReadAllLines(file2);

            //Ghi file
            String filepath = @"F:\OTL\Test Tron File\out.txt";// đường dẫn của file muốn tạo
            FileStream fs = new FileStream(filepath, FileMode.Create);//Tạo file mới tên là test.txt           
            StreamWriter sWriter = new StreamWriter(fs, Encoding.UTF8);//fs là 1 FileStream
            for (int i = 0; i < lines1.Length; i++)
            {
                sWriter.WriteLine(lines1[i]);
                sWriter.WriteLine(lines2[i]);
            }
            // Ghi và đóng file
            sWriter.Flush();
            fs.Close();

        }

Chủ Nhật, 29 tháng 9, 2019

Enum trong C#

A. Lớp tập hợp các Enum:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
 
namespace KieuEnum
{
    class EnumCollection
    {
        public enum WeekDay
        {
            MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
        }
 
        //[Flags]
        public enum WeekDayDescription
        {
            [Description("Thứ hai")]
            MONDAY,
            [Description("Thứ ba")]
            TUESDAY,
            [Description("Thứ tư")]
            WEDNESDAY,
            [Description("Thứ năm")]
            THURSDAY,
 
            [Description("Thứ sáu")]
            FRIDAY,
            [Description("Thứ bảy")]
            SATURDAY,
            [Description("Chủ nhật")]
            SUNDAY,
 
        }
        public enum GioiTinh
        {
            [Description("Nam")]
            NAM = 1,
            [Description("Nữ")]
            NU = 0
        }
 
        //Hint: Change the method signature and input paramter to use the type parameter T
        public static string GetEnumDescription(Enum GenericEnum) 
        {
            Type genericEnumType = GenericEnum.GetType();
            MemberInfo[] memberInfo = genericEnumType.GetMember(GenericEnum.ToString());
            if ((memberInfo != null && memberInfo.Length > 0))
            {
                var _Attribs = memberInfo[0].GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
                if ((_Attribs != null && _Attribs.Count() > 0))
                {
                    return ((System.ComponentModel.DescriptionAttribute)_Attribs.ElementAt(0)).Description;
                }
            }
            return GenericEnum.ToString();
        }
 
        public static bool IsGioiTinhNam(GioiTinh gt)
        {
            return Convert.ToBoolean(gt);
        }
    }
}

B. Hàm main:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
 
namespace KieuEnum
{
    class Program
    {
        //public static List<T> GetFlagEnumAttributes<T>(this Enum flagEnum) where T : Attribute
        //{
        //    var type = flagEnum.GetType();
        //    return Enum.GetValues(type)
        //       .Cast<Enum>()
        //       .Where(flagEnum.HasFlag)
        //       .Select(e => type.GetMember(e.ToString()).First())
        //       .Select(info => info.GetCustomAttribute<T>())
        //       .Where(attribute => attribute != null)
        //       .ToList();
        //}
        static int Compare<T>(T first, T second)
        {
            if (first.Equals(second))
            {
                return 0;
            }
 
            return 1;
        }
        static void Main(string[] args)
        {
 
 
            Console.OutputEncoding = Encoding.UTF8;
 
 
            Console.WriteLine(getJob(EnumCollection.WeekDay.MONDAY));
 
 
            int result1 = Compare(2, 2);
            int result2 = Compare("abc""def");
 
            Console.WriteLine(result1);
            Console.WriteLine(result2);
 
            string description = EnumCollection.GetEnumDescription(EnumCollection.WeekDayDescription.THURSDAY);
            Console.WriteLine(description + ":" + EnumCollection.WeekDayDescription.THURSDAY + ":" + (int)EnumCollection.WeekDayDescription.THURSDAY);
 
            EnumCollection.GioiTinh nu = EnumCollection.GioiTinh.NU;
            Console.WriteLine(EnumCollection.GetEnumDescription(nu) + ":" + nu + ":" + (int)nu);
 
 
            Console.WriteLine(EnumCollection.IsGioiTinhNam(nu) ? "Nam" : "Nu");
 
 
            Console.ReadKey();
        }
 
        public static String getJob(EnumCollection.WeekDay weekDay)
        {
            if (weekDay == EnumCollection.WeekDay.SATURDAY || weekDay == EnumCollection.WeekDay.SUNDAY)
            {
                return "Nothing";
            }
            return "Coding for " + weekDay.ToString();
        }
    }
}