Hiển thị các bài đăng có nhãn programming. Hiển thị tất cả bài đăng
Hiển thị các bài đăng có nhãn programming. Hiển thị tất cả bài đăng

Chủ Nhật, 24 tháng 1, 2021

Git và những thứ hay ho cần nhớ [Bài viết của dân không chuyên IT]

Git và những thứ hay ho

  1. Git là gì
  2. Github là gì?
  3. Cài đặt Git
  4. Các câu lệnh cơ bản trong git
  5. bla bla

GIT là gì?

Git là một hệ thống quản lý phân tán. Thay vì lưu file kiểu Project1, Project1_V1, Project1_Final, Project1_Final_Last.... bla bla. Thì Git giúp bạn không cần lưu kiểu củ chuối này, nhưng bằng cách nào thì cần theo dõi đến cuối.

Github là gì?

GitHub là một dịch vụ lưu trữ trên web của thằng Git. Github nó chả phải là con cái của thằng Git như trước giờ lầm tưởng. Một số dịch vụ thay thế tương tự Github có thể kể đến như BitBucket, GitLab, SourceForge, .... Việc bắt buộc để sử dụng được git là tạo một tài khoản vào một trong các dịch vụ này. Mà mọi người thì thường dùng Github.com

Cài đặt git

Lên trang dưới  https://git-scm.com/downloads và download tương thích với hệ điều hành của bạn. Việc cài thì chỉ bấm next ...đến hết.

Các câu lệnh cơ bản trong git

Git nó quản lý theo các Repository. Mỗi Repository bao gồm các branch, mà trong mỗi branch là một cụm code  hoặc cụm các file tùy thích. Một Repository có thể có một hoặc nhiều branch(es). Git nó ở 2 nơi, một là trên server gọi là remote, một là trên máy bạn gọi là local. Bạn cần phải khởi tạo git ở trên local, rồi sau đó mới đẩy lên remote. Có thể bỏ qua branch, nếu chỉ project chỉ làm 1 mình, và chắc chắn nó luôn đúng. haha

Các bước cơ bản để có thể gọi là dùng được: Tạo repository => Khởi tạo bằng lênh Init =>  lệnh Commit =>Tạo Branch => Tạo đường dẫn kết nối với remote => Push 

Để tạo Repository, bạn vào trang chủ Github, và nhấn vào góc phải như hình để tạo mới. 


Nhập tên và bấm Creat repository


Sau khi có repository, bạn tạo 1 folder trên máy tính của bạn. Truy cập vào thư mục, và chuột phải chuột chọn Git Bash Here
Ví dụ tui có một thư mục NewFolder và có 1 file Hello.txt. Sau khi chọn Git bash Here thì màn hình đen hiện ra:


Giải thích về các lệnh dưới đây:
git init   //Khởi tạo git
git add *   //thêm tất cả cacsc file vào git local, tức là trên máy tính bạn
git commit -m "first commit"  //commit, kiểu như make sure thao tác vừa làm
git branch -M main             //tạo một branch mới
git remote add origin https://github.com/lesonglam/newRepository.git  
                            //khởi tạo cho remote 
git push -u origin main  //đẩy lên remote
git branch -a //kiểm tra tất cả các branch đang làm việc(cả local và remote)

git clean -fX //xóa lỗi với vẩnclear hoặcctrl+l //xóa màn hình

git checkout master  //Để  di chuyển đến branch master.

git merge developBranch // để merge từ một branch có tên là develop branch

//sang branch có tên master

Link tham khảo: 
Link 1: https://forum.freecodecamp.org/t/push-a-new-local-branch-to-a-remote-git-repository-and-track-it-too/13222
Link 2: https://backlog.com/git-tutorial/vn/stepup/stepup2_4.html















Read more... »

Thứ Tư, 6 tháng 5, 2020

Đọc file Matlab .mat vào C#

Để đọc file .mat được xuất ra từ Matlab, cần dùng thư viện MatFileHandle từ Github, bằng đường dẫn sau: https://github.com/mahalex/MatFileHandler.git
Trong đoạn code dưới, ex3weights.mat là tên file. For....each hiển thị 10 hàng đầu tiên của mỗi cột data

  static void Main(string[] args)
        {
            IMatFile matFile;
            using (var fileStream = new System.IO.FileStream("ex3weights.mat", System.IO.FileMode.Open))
            {
                var reader = new MatFileReader(fileStream);
                matFile = reader.Read();
               double[] vars = new double[matFile.Variables.Length];
               foreach (IVariable variable in matFile.Variables)
                {
                    var a = variable.Value.ConvertToDoubleArray();
                    Console.WriteLine(a.Length.ToString());
                    //a.Length
                    for (int i = 0; i <=10 ; i=i + 1)
                    {
                        Console.WriteLine(a[i].ToString());
                    }
                }
Read more... »

Thứ Tư, 15 tháng 4, 2020

Eigenvalue Eigenvectors

Hôm nay mình học PCA, gặp cái eigen  value và eigen vector mà chưa hiểu rõ meaning nó lắm. Google rồi ra mấy kết quả này này. Đem lưu lại đây để sau này lỡ quên còn đọc

In mathematics, eigenvalue, eigenvector, and eigenspace are related concepts in the field of linear algebra. Linear algebra studies linear transformations, which are represented by matrices acting on vectors. Eigenvalues, eigenvectors and eigenspaces are properties of a matrix. They are computed using various matrix methods, give important information about the matrix, and can be used in matrix factorization. They have applications in areas of applied mathematics as diverse as finance and quantum mechanics.
In general, a matrix acts on a vector by changing both its magnitude and its direction. However, a matrix may act on certain vectors by changing only their magnitude, and leaving their direction unchanged (or, possibly, reversing it). These vectors are the eigenvectors of the matrix. A matrix acts on an eigenvector by multiplying its magnitude by a factor, which is positive if its direction is unchanged and negative if its direction is reversed. This factor is the eigenvalue associated with that eigenvector. An eigenspace is the set of all eigenvectors that have the same eigenvalue. The concepts cannot be formally defined without prerequisites, including an understanding of matrices, vectors, and linear transformations.
In quantum mechanics, and in particular in atomic and molecular physics, within the Hartree-Fock theory, the atomic and molecular orbitals can be defined by the eigenvectors of the Fock operator. The corresponding eigenvalues are interpreted as ionization potentials via Koopmans' theorem. In this case, the term eigenvector is used in a somewhat more general meaning, since the Fock operator is explicitly dependent on the orbitals and their eigenvalues.
In geology, especially in the study of glacial till, eigenvectors and eigenvalues are used as a method by which a mass of information of a clast fabric's constituents' orientation and dip can be summarized in a 3-D space by six numbers. In the field, a geologist may collect such data for hundreds or thousands of clasts in a soil sample, which can only be compared graphically such as in a Tri-Plot (Sneed and Folk) diagram, or as a Stereonet on a Wulff Net. The output for the orientation tensor is in the three orthogonal (perpendicular) axes of space.
In mechanics, the eigenvectors of the inertia tensor define the principal axes of a rigid body. The tensor of inertia is a key quantity required in order to determine the rotation of a rigid body around its center of mass.
Eigenvalue problems occur naturally in the vibration analysis of mechanical structures with many degrees of freedom. The eigenvalues are used to determine the natural frequencies of vibration, and the eigenvectors determine the shapes of these vibrational modes. The orthogonality properties of the eigenvectors allows decoupling of the differential equations so that the system can be represented as linear summation of the eigenvectors. The eigenvalue problem of complex structures is often solved using finite element analysis.
Nguồn: Nguồn
Read more... »

Thứ Năm, 5 tháng 3, 2020

Tính CRC - Modbus RTU

Tính CRC Modbus

int[] intSend = new int[8];
intSend[0] = 0x01; // ID of slave device
intSend[1] = 0x03; // code of the command
intSend[2] = 0x1D; // Register address 0x1D63
intSend[3] = 0x63; // Register address 0x1D63
intSend[4] = 0x00; // First 8 bits of the data
intSend[5] = 0x02; // Second 8 bits of the data

int int_crc = 0xFFFF;
int int_lsb;
int int_crc_byte_a, int_crc_byte_b;

for (int int_i = 0; int_i < intSend.Length - 2; int_i++)
{
int_crc = int_crc ^ intSend[int_i];
for (int int_j = 0; int_j < 8; int_j++)
{
int_lsb = int_crc & 0x0001; // Mask of LSB
int_crc = int_crc >> 1;
int_crc = int_crc & 0x7FFF;
if (int_lsb == 1) int_crc = int_crc ^ 0xA001;
}
}


Mình sẽ cho các bạn 1 đoạn mã để thử như sau :
"01 03 00 01 00 04" có mã CRC = 15 C9
----------------------------------------

Hoặc có hàm tính CRC này thấy dễ xem hơn .
Khi sử dụng, thì hãy truyền vào 1 mảng, kiểu dữ liệu là byte và "len" là số byte của chuỗi truyền.
Ví dụ: Với chuỗi "01 03 00 01 00 04". Ta khai báo 1 mảng byte mang[];
Hãy gán giá trị cho mảng như sau: mang[0] = Convert.ToByte("01",16) ....và tiếp tục với
các giá trị còn lại còn lại.
chuỗi truyền có 6 byte nên "len = 6";
Khi sử dụng thì hãy gọi hàm ModRTU_CRC(mang,len);


UInt16 ModRTU_CRC(byte[] buf, int len)
{
UInt16 crc = 0xFFFF;

for (int pos = 0; pos < len; pos++) {
crc ^= (UInt16)buf[pos]; // XOR byte into least sig. byte of crc

for (int i = 8; i != 0; i--) { // Loop over each bit
if ((crc & 0x0001) != 0) { // If the LSB is set
crc >>= 1; // Shift right and XOR 0xA001
crc ^= 0xA001;
}
else // Else LSB is not set
crc >>= 1; // Just shift right
}
}
// Note, this number has low and high bytes swapped, so use it accordingly (or swap bytes)
return crc;
}




Và đây là 1 video tui từng làm 

https://www.youtube.com/watch?v=eKS4dYHkMls
Read more... »

Thứ Năm, 13 tháng 6, 2019

Làm quen với ESP8266 cho người mới - TCP Server, STA mode ...etc

Chả là hôm nay rảnh hơi, đi mua cái module 4 relay ESP8266 về làm chơi. Mà làm mãi dựa trên cái SmartConfig của mấy bạn tàu mà không được, hỏi cũng chả ai nói sao, thật là khó hiểu,,,,hay là tại tui....chậm tiêu. Anyway, kệ nó vậy, viết bài Tut cho sau này lỡ quên thì còn có chỗ mà coi.

Q1. Nên mua board mà có tích hợp sẵn của mấy ông LCTECH không?
A1: Nope, đừng có mua, mé nó cứ làm lằng nhằng bỏ mịa, việc gì cứ phải đâm đầu ngồi nhớ A1 00, với A1 01 làm gì.
Q2. Nên mua board nào? Mua thêm phụ kiện gì?
A2. Nên mua loại board tích hợp về thử trước, mấy board Node MCU, có ra chừng chục I/O, tha hồ chơi, nó cũng cho code thoải mãi trên IDE của Arduino. Giá mấy con này loại chíp chuyển là CH340 cg chỉ chừng 70k. Sau đó mua thêm một cái module 4 relays chừng 30k nữa là về đóng mở điện bá cháy. Mua thêm vài cái Jump đực-cái, với cái sợi Usb micro của mấy đt  Android.
Chốt lại, cần những thứ sau để bắt đầu chơi:

  1. Board ESP8266 Node mcu, loại chíp CH340 hoặc tương đương
  2. Module 4 relays loại kích cao(thấp)
  3. 10 sợi bus đưc, 10 sợi cái
  4. Dây micro usb
Nào cùng bắt đầu nhé....tèn tén ten

Sơ đồ chân của em ESP8266 Node MCU


Ví dụ 01: Thay đổi trạng thái cho ngõ ra D1


#define LED_PIN D3   // Lưu ý khi khai báo chân cho ESP, nhìn vào mặt trên để khai báo,
                                      // đừng mất công đi khai báo theo chân GPIO

void setup() 
{
  pinMode(LED_PIN, OUTPUT); 
}
int delay_temp=0;
bool stt=0;
void loop() {

     digitalWrite(LED_PIN, stt);
     stt^=1;   //đảo trạng thái bằng lệnh XOR
    delay(500);
    
}


Đấy, giờ nạp được rồi đấy.


Bài 2: Tạo TCP Server trên ESP,  STA network mode

Code sườn được lấy từ Tech Tutorial's website , so  Credite to Tech tutorial 



#include "ESP8266WiFi.h" #define LED D3 const char* ssid = "Lam de thuong"; const char* password = "Lam dep trai"; WiFiServer wifiServer(80); void setup() { pinMode(LED, OUTPUT); Serial.begin(115200); delay(1000); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Connecting.."); } Serial.print("Connected to WiFi. IP:"); Serial.println(WiFi.localIP()); wifiServer.begin(); } void loop() { WiFiClient client = wifiServer.available(); if (client) { while (client.connected()) { while (client.available()>0) { char c = client.read(); if (c=='H' ) { digitalWrite(LED, HIGH); Serial.println("LED-HIGH"); } if (c=='L' ) { digitalWrite(LED, LOW); Serial.println("LED-LOW"); } delay(10); } } client.stop(); Serial.println("Client disconnected"); } }


Bây giờ làm sao để test code này nhỉ?

Bạn cần down load 1 phần mềm TCP Client bất kỳ và thử connect nhé. Ví dụ nếu tui dùng Hercules để thử chẳng hạn. 


Thứ tự cần làm là: Mở terminal COM trên IDE arduino =>> Mở Hercules =>> Chọn TCP Client =>> Điền IP và port tương ứng với mạng nhà bạn, của tui là xx.xx.1.13 port là 80 =>> Nhập chữ L và H như góc trái dưới =>> Bấm Send.,,,,yeah
Read more... »

Thứ Sáu, 19 tháng 5, 2017

How to download journal for free?

For some reason, maybe student can not access to the journal source libraries. I would suggest the following these steps: 
  1. Go to http://sci-hub.cc/ website home page
  2. Copy and paste the journal link or URL you want to download for free
  3. Click on “Open” on sci-hub to continue to the next page.
  4. A download page will be appeared
  5. Then, you will be able download the journal.
Lets try ! That's all.
Làm sao để tải báo khoa học miễn phí. Khi mà các trường học ở VN chưa mua các tài nguyên báo từ các trang IEEE, sciencedirect,... thì các bạn sinh viên rất khó khăn để mua cái bài báo đó vì giá của chúng cũng không hề thấp so vs mức sống ở sv VN.
Đây là cách đơn giản cho các bạn có thể có thêm tài liệu để nghiên cứu. Chúc các bạn học tốt !


Read more... »

Thứ Ba, 4 tháng 4, 2017

OPC Kepware and C#

Recently, I have received many question about How to connect OPC to C# .
These are a good instruction for you. Following step by step, you can easily finish your project. 
Good luck !!!!!!!!


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using OPCAutomation;




namespace OPC2
{
    public partial class Form1 : Form
    {
        public OPCAutomation.OPCServer AnOPCServer;
        public OPCAutomation.OPCServer ConnectedOPCServer;
        public OPCAutomation.OPCGroups ConnectedServerGroup;
        public OPCAutomation.OPCGroup ConnectedGroup;
        public string Groupname;

        int ItemCount;
        Array OPCItemIDs = Array.CreateInstance(typeof(string), 10);
        Array ItemServerHandles = Array.CreateInstance(typeof(Int32), 10);
        Array ItemServerErrors = Array.CreateInstance(typeof(Int32), 10);
        Array ClientHandles = Array.CreateInstance(typeof(Int32), 10);
        Array RequestedDataTypes = Array.CreateInstance(typeof(Int16), 10);
        Array AccessPaths = Array.CreateInstance(typeof(string), 10);
        Array WriteItems = Array.CreateInstance(typeof(string), 10);
        
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            try
            {
                string IOServer = "Kepware.KEPServerEX.V5";
                string IOGroup = "OPCGroup1";

                ConnectedOPCServer = new OPCAutomation.OPCServer();
                ConnectedOPCServer.Connect(IOServer, "");
                ConnectedGroup = ConnectedOPCServer.OPCGroups.Add(IOGroup);
                ConnectedGroup.DataChange += new DIOPCGroupEvent_DataChangeEventHandler(ObjOPCGroup_DataChange);
                ConnectedGroup.UpdateRate = 1000;
                ConnectedGroup.IsSubscribed = ConnectedGroup.IsActive;


                ItemCount = 2;
                OPCItemIDs.SetValue("Channel2.Device1.R1", 1);
                ClientHandles.SetValue(1, 1);
                OPCItemIDs.SetValue("Channel2.Device1.R2", 2);
                ClientHandles.SetValue(2, 2);

                ConnectedGroup.OPCItems.DefaultIsActive = true;
                ConnectedGroup.OPCItems.AddItems(ItemCount, ref OPCItemIDs, ref ClientHandles, out ItemServerHandles, out ItemServerErrors, RequestedDataTypes, AccessPaths);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

        }

        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            ConnectedOPCServer.Disconnect();
        }

        private void ObjOPCGroup_DataChange(int TransactionID, int NumItems, ref Array ClientHandles, ref Array ItemValues, ref Array Qualities, ref Array TimeStamps)
        {
            try
            {
                for (int i = 1; i <= NumItems; i++)
                {
                    if ((Convert.ToInt32(ClientHandles.GetValue(i)) == 1))
                    {
                        textBox1.Text = ItemValues.GetValue(i).ToString();
                    }
                    if ((Convert.ToInt32(ClientHandles.GetValue(i)) == 2))
                    {
                        textBox2.Text = ItemValues.GetValue(i).ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            
        }

        private void btnWrite1_Click(object sender, EventArgs e)
        {
            try
            {
                WriteItems.SetValue(textBox4.Text, 1);
                ConnectedGroup.SyncWrite(ItemCount, ref ItemServerHandles, ref WriteItems, out ItemServerErrors);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

        }

    }
}


Watch more about communication between
 PLC and C#, without OPC:  
https://youtu.be/PruLwQsBX_M

P/s: Nếu bạn gặp lỗi khi add dll thì theo code project
 The files myOPC.dll and Interop.OPCAutomation.dll both should 
be referenced by your client file and their properties "Copy Local" set to true. 

and more My project - Youtube
Read more... »