วันเสาร์ที่ 23 กุมภาพันธ์ พ.ศ. 2562

C# Auto update program


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace UpdateVersion
{
    public partial class Form1 : Form
    {
        List<string> listFiles = new List<string>();
        double countFiles = 0.0;
        public Form1()
        {
            InitializeComponent();
        }   
        private void Form1_Load(object sender, EventArgs e)
        {         
            backgroundWorker1.RunWorkerAsync();
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            listFiles = CopyFolder("D:\\Datas", "D:\\Backup");
            countFiles = 100.0 / listFiles.Count;

            for(int i=1;i<=listFiles.Count;i++)
            {           
                backgroundWorker1.ReportProgress(i);
                if (i == listFiles.Count)
                    Thread.Sleep(500);
                Thread.Sleep(50);
            }
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBarValue.Value = (int)(countFiles * e.ProgressPercentage);
            this.label1.Text = "Update to "+ listFiles[e.ProgressPercentage-1].ToString();       
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.label1.Text = "Update completed!!!!";
            Thread.Sleep(1000);
          //  Process.Start("D:\\Backup\\UpdateVersion.exe");
            Application.Exit();

        }
        static public List<string> CopyFolder(string sourceFolder, string destFolder)
        {
            List<string> listfile = new List<string>();
            if (!Directory.Exists(destFolder))
                Directory.CreateDirectory(destFolder);
            string[] files = Directory.GetFiles(sourceFolder);
            foreach (string file in files)
            {
                string name = Path.GetFileName(file);
                string dest = Path.Combine(destFolder, name);

                File.Copy(file, dest,true);
                listfile.Add(dest);
            }
            string[] folders = Directory.GetDirectories(sourceFolder);
            foreach (string folder in folders)
            {
                string name = Path.GetFileName(folder);
                string dest = Path.Combine(destFolder, name);
                CopyFolder(folder, dest);
                listfile.Add(dest);
            }
            return listfile;
        }     
    }
}

วันเสาร์ที่ 12 มกราคม พ.ศ. 2562

C# Create Button By programmatically



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

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        List<string> listRoom;
        List<Index> index;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            listRoom = new List<string>();
            index = new List<Index>();

            for(char c='A';c<='Z';c++)
            {
                listRoom.Add(c.ToString());
            }

            List<Button> buttons = new List<Button>();
            int y = 5;
            int x = 5;
            for (int i = 1; i <= listRoom.Count; i++)
            {
                Button newButton = new Button();
                if (i % 3 != 0)
                {
                    newButton.Location = new Point(2 * x, 2 * y);
                    x += 42;
                 
                }
                else
                {
                    newButton.Location = new Point(2 * x, 2 * y);
                    y += 30;
                    x = 5;
                 
                }
                newButton.Text = listRoom[i-1].ToString();
                newButton.Size = new Size(80, 50);
                newButton.MouseEnter += (s, ee) => newButton.Cursor = Cursors.Hand;
                newButton.MouseLeave += (s, ee) => newButton.Cursor = Cursors.Arrow;
                newButton.BackColor = Color.Green;
                buttons.Add(newButton);
             
                this.Controls.Add(newButton);
                Index ind = new Index();
                ind.index = newButton.TabIndex;
                ind.Room = listRoom[i - 1].ToString();
                index.Add(ind);
                newButton.Click += NewButton_Click;
             
            }
        }
        private void NewButton_Click(object sender, EventArgs e)
        {
            Button b = (Button)sender;
            if (b.BackColor != Color.Red)
            {
                b.Text =  b.Text + " [Disable]";
                b.BackColor = Color.Red;
            }
            else
            {
                foreach (var v in index)
                {
                    if (b.TabIndex == v.index)
                    {
                        b.Text = v.Room;
                        b.BackColor = Color.Green;
                        break;
                    }
                }
            }
        }     
    }
    public class Index
    {
        public int index { get; set; }
        public string Room { get; set; }
    }
}



วันศุกร์ที่ 21 ธันวาคม พ.ศ. 2561

C# Select Data by Lambda (Sql Server)



using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            Data.GetDataUser("Kriangkrai.R");         
            Console.WriteLine($"Manager       = {Data.getNameManager()}");
            Console.WriteLine($"Director      = {Data.getNameDirector()}");
            Console.WriteLine($"Administrator = {Data.getNameAdmin()}");

            Console.ReadKey();
        }
    }
    public class Data
    {
        public string Name;
        public string Location;
        public string Department;
        public string Permission;
        public string Groups;
        public static string Manager;
        public static string Director;
        public static string Admin;

        public Data(string Name,string Location, string Department, string Permission,string Groups)
        {
            this.Name = Name;
            this.Location = Location;
            this.Department = Department;
            this.Permission = Permission;
            this.Groups = Groups;
        }

        public static void GetDataUser(string Name)
        {
            List<Data> listData = new List<Data>();
            SqlConnection con = new SqlConnection("Data Source=DESKTOP-BMFLGER\\SA;Initial Catalog=DataUser;User ID = sa; Password = 123456;");
            con.Open();
            SqlCommand cmd = new SqlCommand("SELECT * FROM [User]", con);
            SqlDataReader dr = cmd.ExecuteReader();

            if (dr.HasRows)
            {
                while (dr.Read())
                {
                    Data d = new Data(dr["Name"].ToString(), dr["LOcation"].ToString(), dr["Department"].ToString(), dr["Permission"].ToString(), dr["Groups"].ToString());
                    listData.Add(d);
                }
                dr.Close();
            }
            con.Close();

            string department = "";
            string Location = "";
            foreach (var v in listData)
            {
                if(Name == v.Name)
                {
                    department = v.Department;
                    Location = v.Location;
                    break;
                }
            }

            //Get Name Manager
            var NameManager = listData.Where(x => x.Department == department && x.Permission == "M").Select(x => x.Name).ToList();
            foreach(var v in NameManager)
            {
                Manager += v.ToString() + ",";
            }
            Manager = Manager.Remove(Manager.Length - 1);



            //Get Name Director
            if (Location == "Bangkok" || Location == "Konkaen")
            {
                var NameDirector = listData.Where(x => x.Permission == "D" && (x.Location == "Bangkok")).Select(x => new DataDirector { Name = x.Name, Location = x.Location }).ToList();
                foreach (var v in NameDirector)
                {
                    Director = v.Name + ",";
                }
                Director = Director.Remove(Director.Length - 1);
            }
            else if(Location == "Rayong")
            {
                var NameDirector = listData.Where(x => x.Permission == "D" && (x.Location == "Rayong")).Select(x => new DataDirector { Name = x.Name, Location = x.Location }).ToList();
                foreach (var v in NameDirector)
                {
                    Director = v.Name + ",";
                }
                Director = Director.Remove(Director.Length - 1);
            }

            //Get Name Admin
            var NameAdmin = listData.Where(x => x.Permission == "Admin").Select(x => x.Name).ToList();
            foreach(var v in NameAdmin)
            {
                Admin += v.ToString() + ",";
            }
            Admin = Admin.Remove(Admin.Length - 1);
        }
        
        public static string getNameManager()
        {
            return Manager;
        }
        public static string getNameDirector()
        {
            return Director;
        }
        public static string getNameAdmin()
        {
            return Admin;
        }
    }

   class DataDirector
    {
        public string Name { get; set; }
        public string Location { get; set; }       
    }
    
}




วันพุธที่ 18 เมษายน พ.ศ. 2561

Random Lot

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> ReadFile = File.ReadAllLines(@"D:\Data.txt").ToList();
            List<string> random = new List<string>();
            Random rnd = new Random();

            Console.Write("Do you want to Number of value : ");
            string number = Console.ReadLine();
            int want = 100- ReadFile.Count -(Int32.Parse(number))-1;
            for (int j = 0; j <100; j++)
            {
                random.Add(j.ToString());
       
            }
            for (int i = 0; i < ReadFile.Count; i++)
            {
                random.Remove(ReadFile[i]);
            }

            for (int j = 0; j < want; j++)
            {
                for (int i = 0; i < 1; i++)
                {
                    int k = rnd.Next(0, random.Count);
                    random.Remove(random[k]);

                }
                int count = 0;
                int row=20;
                foreach (string ii in random)
                {
                    if (Int32.Parse(count.ToString()) % row != 0)
                    {
                        if (Int32.Parse(ii) == Int32.Parse(random.Last()))
                        {
                            if (Int32.Parse(ii) < 10)
                            {
                                Console.Write("0" + ii.ToString());
                            }
                            else
                            {
                                Console.Write(ii.ToString());
                            }
                        }
                        else
                        {
                            if (Int32.Parse(ii) < 10)
                            {
                                Console.Write("0" + ii.ToString() + ",");
                            }
                            else
                            {
                                Console.Write(ii.ToString() + ",");
                            }
                        }                       
                    }
                    else
                    {
                        Console.WriteLine();
                    }
                    count++;
                    Thread.Sleep(10);
                }
                Console.WriteLine("\n");
            }
        }
    }
}

วันศุกร์ที่ 15 ธันวาคม พ.ศ. 2560

C# Search , Add , Delete DataGridView

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

namespace WindowsFormsApp2
{
    public partial class Form1 : Form
    {
        DataTable table;
        DataTable table1;
        public Form1()
        {
            InitializeComponent();
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            var item = dataGridView1.Rows[e.RowIndex].Cells[1].Value;
            table1.Rows.Add(item.ToString());
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            table = new DataTable();
            table.Columns.Add("Id", typeof(int));
            table.Columns.Add("Name", typeof(string));
            table.Rows.Add(1,"Mee");
            table.Rows.Add(2, "Yha");
            dataGridView1.DataSource = table;

            table1 = new DataTable();
            table1.Columns.Add("Name", typeof(string));
            dataGridView2.DataSource = table1;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int rowIndex = dataGridView2.CurrentCell.RowIndex;
                dataGridView2.Rows.RemoveAt(rowIndex);
        }

        private void dataGridView2_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyData == Keys.Delete)
            {
                int rowIndex = dataGridView2.CurrentCell.RowIndex;
                    dataGridView2.Rows.RemoveAt(rowIndex);
            }
        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if(e.KeyChar == (char)13)
            {
                DataView dv = table.DefaultView;
                dv.RowFilter = string.Format("Name like '%{0}%'" , textBox1.Text);
                dataGridView1.DataSource = dv.ToTable();
            }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            DataView dv = table.DefaultView;
            dv.RowFilter = string.Format("Name like '%{0}%'", textBox1.Text);
            dataGridView1.DataSource = dv.ToTable();
        }
    }
}

วันศุกร์ที่ 24 พฤศจิกายน พ.ศ. 2560

C# Binary Search

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Linkedlist
{
    class Program
    {
        static public int[] numsort(int[] x)
        {
            int[] a = x;

            for (int i = 0; i < a.Length; i++)
            {
                for (int j = 0; j < a.Length - 1; j++)
                {
                    if (a[j] > a[j + 1])
                    {
                        int temp;
                        temp = a[j];
                        a[j] = a[j + 1];
                        a[j + 1] = temp;
                    }
                }
            }
            return a;
        }
        static public int binarySerach(int[] x,int find)
        {
            int left = 0;
            int right = x.Length-1;
            int mid;
            while(left <= right)
            {
                mid = (left + right) / 2;
                if (find == x[mid])
                    return mid;
                else if (find < x[mid])
                {
                    right = mid - 1;
                }
                else
                    left = mid + 1;
            }
            return -1;
        }
        static public void output(int[] x)
        {
            for(int i=0;i<x.Length;i++)
            {
                Console.Write(x[i]+" ");
            }
            Console.WriteLine();
        }
        static void Main(string[] args)
        {
            Random r = new Random();
            int find = 5;
            int[] x = new int[10];
            for(int i=0;i<10;i++)
            {
                x[i] = r.Next(10) + 1;
            }
            numsort(x);
            output(x);
            int c = binarySerach(x, find);
            Console.WriteLine("Find : " + find + " Index : " + (c+1));
         

            Console.ReadLine();
        }   
    }

}

วันศุกร์ที่ 3 พฤศจิกายน พ.ศ. 2560

C# sequential Search

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

namespace LinkedList
{
    public partial class Form1 : Form
    {
        int n = 100;
        int[] a;
        public Form1()
        {
            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)
        {
            a = new int[n];
            Random x = new Random();
            textBox1.Text = "";
            for(int i=0;i<n;i++)
            {
                a[i] = x.Next(100) + 1;
                textBox1.Text = textBox1.Text + "[" +i.ToString() + "]"+a[i].ToString() + " , ";
            }
        }

        private int sequentialsearch(int k)
        {
            int i=0;
            while(i<n && a[i] !=k)
            {
                i++;
            }
            if (i < n)
                return i;
            else
                return -1;             
        }
        private void button2_Click(object sender, EventArgs e)
        {
            int k = Convert.ToInt32(textBox2.Text);
            textBox3.Text = sequentialsearch(k).ToString();
        }


    }

}

C# LinkedList

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

namespace LinkedList
{
    public partial class Form1 : Form
    {
        singlrLinkedList sll;
        public Form1()
        {
            InitializeComponent();
            startup();
        }
        public void startup()
        {
            sll = new LinkedList.singlrLinkedList();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            sll.addLinkedList(textBox1.Text, Int32.Parse(textBox2.Text.ToString()));
         
            textBox1.Clear();
            textBox2.Clear();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            textBox3.Text = sll.showall();
   
        }

        private void button3_Click(object sender, EventArgs e)
        {
            sll.deletepos(Convert.ToInt32(textBox4.Text));
            textBox3.Text = sll.showall();
        }
    }
    public class node
    {
        public string name;
        public int age;
        public node next;

        public node()
        {
            next = null;
        }
    }
    public class singlrLinkedList
    {
        public node header;
        public node cur;
        public node newnode;
        public singlrLinkedList()
        {
            header = null;
            cur = null;
        }
        public void addLinkedList(string name ,int age)
        {
            newnode = new LinkedList.node();
            newnode.name = name;
            newnode.age = age;
           
            if (header == null)
            {
                header = newnode;
                cur = header;
            }
            else
            {
                cur.next = newnode;
                cur = cur.next;
            }
        }
        public void deletepos(int i)
        {
            node delx;
            cur = header;
            if(i==1)
            {
                header = cur.next;
                cur = header;
            }
            else
            {
                for(int j=1;j<i-1;j++)
                {
                    cur = cur.next;
                }
                delx = cur.next;
                if(delx != null)
                {
                    cur.next = delx.next;
                }
            }
        }
        public string showall()
        {
            int i = 1;
            string str = "";
            cur = header;
            while(cur !=null)
            {
                str = str + i.ToString() + " : " + cur.name + "," + cur.age.ToString()+Environment.NewLine;
                i++;
                cur = cur.next;
            }         
            return str;
        }
    }
}

วันอาทิตย์ที่ 29 ตุลาคม พ.ศ. 2560

C++ Stack

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <thread>
typedef struct node
{
int data;
struct node* link;
}STACK_NODE;

typedef struct
{
int count;
STACK_NODE *top;

}STACK;

void insertData(STACK* pStack);
void print(STACK* pStack);
bool push(STACK* pList, int dataIn);
bool pop(STACK* pList, int *dataOut);


int main()
{
STACK *pStack;
pStack = new STACK;
printf("=============STACK=============\n\n");
pStack->top = NULL;
pStack->count = 0;
insertData(pStack);
print(pStack);

return 0;
}

void insertData(STACK* pStack)
{
int numIn;
bool success;
srand(time(NULL));
printf("Create Number : ");
for (int nodeCount = 0; nodeCount < 10; nodeCount++)
{
numIn = rand() % 999;
printf("%4d", numIn);
success = push(pStack, numIn);
if (!success)
{
printf("Error out of memory\n");
exit(101);
}
}
printf("\n\n");
return;
}
void print(STACK* pStack)
{
int printData;
printf("Stack contained : \n");
printf("\t\t +--------+\n");
while (!pop(pStack, &printData))
{
printf("\t\t |  %4d  |\n", printData);
}
printf("\t\t +--------+\n");
return;
}
bool push(STACK* pList, int dataIn)
{
STACK_NODE* pNew;
bool success;
pNew = (STACK_NODE*)malloc(sizeof(STACK_NODE));
if (!pNew)
{
success = false;
}
else
{
pNew->data = dataIn;
pNew->link = pList->top;
pList->top = pNew;
pList->count++;
success = true;
}
return success;
}
bool pop(STACK* pList, int *dataOut)
{
STACK_NODE* pDlt;
bool success;

if (pList->top)
{
success = false;
*dataOut = pList->top->data;
pDlt = pList->top;
pList->top = (pList->top)->link;
pList->count--;
free(pDlt);
}
else
{
success = true;
}
return success;
}


วันเสาร์ที่ 14 ตุลาคม พ.ศ. 2560

C++ partial Sum


#include <vector>
#include <iostream>
using namespace std;

double sum(int n)
{
double partialSum = 0.0;
for (int k = 2; k <= n; k++)
{
partialSum += sqrt(k / (k + 1.)) -sqrt((k - 1.) / k);
}
return partialSum;
}
int main(int argc,char*argv)
{
cout << sum(1000) << endl;
return 0;
}





วันเสาร์ที่ 7 ตุลาคม พ.ศ. 2560

C++ opencv edit pixel

#include<opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>

#include<iostream>
#include<conio.h>         

using namespace std;
using namespace cv;

void procFrame(cv::Mat &frame);
int main(int argc,char** argv)
{
VideoCapture cap(0);
if (!cap.isOpened())
{
cout << "Could not open camera" << endl;
return -1;
}
cap.set(CV_CAP_PROP_FRAME_WIDTH, 640);
cap.set(CV_CAP_PROP_FRAME_HEIGHT, 480);

namedWindow("Exam", WINDOW_AUTOSIZE);
while (true)
{
Mat frame;
if (cap.read(frame))
{
procFrame(frame);
imshow("Exam", frame);
}
if (waitKey(30) == 27)
{
break;
}
}
return 0;
}

void procFrame(cv::Mat & frame)
{
static float alpha = 1.0f;
for (unsigned int z = 0; z<frame.rows; z++)
{
for (unsigned int i = 0; i < frame.cols; i++)
{
Vec3b &cur_pixel = frame.at<Vec3b>(z, i);
cur_pixel[0] *= (-alpha);
cur_pixel[1] *= (-alpha);
cur_pixel[2] *= alpha;
}
}
alpha += 0.1f;
}


C++ opencv drawing Box

#include<opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>

#include<iostream>
#include<conio.h>       

using namespace std;
using namespace cv;

void my_mouse_calback(int event, int x, int y, int flags, void*data);

Rect Box;
Mat drawing;

bool drawing_box = false;

void draw_box(Mat& img, Rect box)
{
rectangle(img, box.tl(), box.br(), Scalar(255, 0, 0));
}

int main(int argc,char** argv)
{
int Bright = 1, Cont = 47;
Mat drawing, drawing2;
drawing = imread("D:\\3.jpg"); drawing.copyTo(drawing2);
Box = Rect(-1, -1, 0, 0);

namedWindow("Exam", CV_WINDOW_AUTOSIZE);


setMouseCallback("Exam", my_mouse_calback, (void*)&drawing);
while(1)
{
drawing.copyTo(drawing2);
if (drawing_box)draw_box(drawing2, Box);
imshow("Exam", drawing2);
if (waitKey(30) == 27)
break;
}
return 0;
}

void my_mouse_calback(int event, int x, int y, int flags, void*data)
{
Mat& drawing = *(Mat*)data;
int w, h, r;
if (event == EVENT_MOUSEMOVE)
{
if (drawing_box)
{
Box.width = x - Box.x;
Box.height = y - Box.y;
}
}

if (event == EVENT_LBUTTONDOWN)
{
drawing_box = true;
Box = Rect(x, y, 0, 0);
}
if (event == EVENT_LBUTTONUP)
{
drawing_box = false;

if (Box.width < 0)
{
Box.x += Box.width;
Box.width *= -1;
}
if (Box.height < 0)
{
Box.x = Box.height;
Box.width *= -1;
}
draw_box(drawing, Box);
}
}


วันอาทิตย์ที่ 11 มิถุนายน พ.ศ. 2560

C++ queue

#include <iostream>
using namespace std;
#define N 11
int queuedata[N];
int front = 0;
int rear = 0;

int add(int data)
{
if (rear < N - 1)
{
rear++;
queuedata[rear] = data;
if (!front)
return -1;
return 1;
}
return -1;
}
int get()
{
int temp;
if (front)
{
temp = queuedata[front];
if (front > rear)
{
front = 0;
rear = 0;
return -1;
}
else
front++;
}
else
return -1;

return temp;
}
void show()
{
for (int i = front+1; i < rear + 1; i++)
{
cout << queuedata[i] << " ";
}
cout << endl;
}

int main(int argc, char** argv)
{
add(5);
add(8);
get();
show();
return 0;
}

C++ stack

#include <iostream>
using namespace std;
#define N 10
int stackdata[N];
int top = -1;

int push(int n)
{
if (top < N - 1)
{
top++;
stackdata[top] = n;
return 1;
}
return -1;
}
int pop()
{
int r;
if (top > -1)
{
r = stackdata[top];
stackdata[top] = 0;
top--;
return r;
}
return -1;
}
int main(int argc, char** argv)
{
push(1);
push(3);
pop();
push(9);
push(9);
push(3);

for (int i = 0; i <= top; i++)
{
cout << stackdata[i] << " ";
}
cout << endl;
return 0;
}

วันเสาร์ที่ 10 มิถุนายน พ.ศ. 2560

C++ การเรียงกลับหลังใน Array

#include <iostream>
using namespace std;
#define N 5
int main(int argc, char** argv)
{
int data[N] = { 1,2,3,4,5 };
int i;

for (i = 0; i < N / 2; i++)
{
int temp;
temp = data[i];
data[i] = data[N - 1 - i];
data[N - 1 - i] = temp;
}

for (int i = 0; i < N; i++)
cout << data[i] << " ";

cout << endl;
return 0;
}

C++ การลบข้อมูลใน Array

#include <iostream>
using namespace std;
#define N 5
int main(int argc, char** argv)
{
int data[N] = { 1,2,3,4,5 };
int position = 3;
int i;

for (i = position; i < N; i++)
data[i - 1] = data[i];
data[i - 1] = -1;

for (int i = 0; i < N; i++)
cout << data[i] << " ";

cout << endl;
return 0;
}

C++ การแทรกข้อมูลใน Array

#include <iostream>
using namespace std;
#define N 5
int main(int argc, char** argv)
{
int data[N] = { 1,2,3,4,5 };
int newdata = 6;
int position = 3;
int i;
for (i = N - 1; i >= position; i--)
data[i] = data[i - 1];
data[i] = newdata;

for (int i = 0; i < N; i++)
{
cout << data[i] << " ";
}
cout << endl;
return 0;
}

C++ ค้นหาข้อมูลใน Array

#include <iostream>
using namespace std;

int main(int argc, char** argv)
{
int data[5] = { 1,2,3,4,5 };
int count = 0;
bool h = false;
int search = 5;
while (count < 5)
{
if (data[count] == search)
{
cout << "Have data at position " << count+1 << endl;
h = true;
break;
}
count++;
}
if (h == false)
cout << "Have not data in array" << endl;
return 0;
}

วันพฤหัสบดีที่ 23 มีนาคม พ.ศ. 2560

C++ opencv Thresholds

#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <stdlib.h>
#include <stdio.h>

using namespace cv;

/// Global variables

int threshold_value = 0;
int threshold_type = 3;;
int const max_value = 255;
int const max_type = 4;
int const max_BINARY_value = 255;

Mat frame, src_gray, dst;
char* window_name = "Threshold Demo";

char* trackbar_type = "Type: \n 0: Binary \n 1: Binary Inverted \n 2: Truncate \n 3: To Zero \n 4: To Zero Inverted";
char* trackbar_value = "Value";

/// Function headers
void Threshold_Demo(int, void*);

int main(int argc, char** argv)
{
VideoCapture cap(0);
while (1)
{

cap >> frame;
/// Convert the image to Gray
cvtColor(frame, src_gray, CV_BGR2GRAY);

/// Create a window to display results
namedWindow(window_name, CV_WINDOW_AUTOSIZE);

/// Create Trackbar to choose type of Threshold
createTrackbar(trackbar_type,
window_name, &threshold_type,
max_type, Threshold_Demo);

createTrackbar(trackbar_value,
window_name, &threshold_value,
max_value, Threshold_Demo);

/// Call the function to initialize
Threshold_Demo(0, 0);
if (waitKey(30) == 27)
break;

}
return 0;
}

void Threshold_Demo(int, void*)
{
/* 0: Binary
1: Binary Inverted
2: Threshold Truncated
3: Threshold to Zero
4: Threshold to Zero Inverted
*/
threshold(src_gray, dst, threshold_value, max_BINARY_value, threshold_type);
imshow(window_name, dst);
}

C++ opencv Threshold

#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>

using namespace cv;
using namespace std;

Mat src; Mat src_gray;
int thresh = 100;
int max_thresh = 255;

/// Function header
void thresh_callback(int, void*);

/** @function main */
int main(int argc, char** argv)
{
VideoCapture cap(0);
while (1)
{
cap >> src;
/// Convert image to gray and blur it
cvtColor(src, src_gray, CV_BGR2GRAY);
blur(src_gray, src_gray, Size(3, 3));

/// Create Window
char* source_window = "Source";
namedWindow(source_window, CV_WINDOW_AUTOSIZE);
imshow(source_window, src);

createTrackbar(" Canny thresh:", "Source", &thresh, max_thresh, thresh_callback);
thresh_callback(0, 0);
if (waitKey(30) == 27)
break;
}
return(0);
}

/** @function thresh_callback */
void thresh_callback(int, void*)
{
Mat canny_output;
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;

/// Detect edges using canny
Canny(src_gray, canny_output, thresh, thresh * 2, 3);
/// Find contours
findContours(canny_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));

/// Draw contours
Mat drawing = Mat::zeros(canny_output.size(), CV_8UC3);
for (int i = 0; i< contours.size(); i++)
{
drawContours(drawing, contours, i, Scalar(255,255,255), 1, 8, hierarchy, 0, Point());
}

/// Show in a window
namedWindow("Contours", CV_WINDOW_AUTOSIZE);
imshow("Contours", drawing);
}