using System;
using System.Collections.Generic;
using System.Linq;
namespace bio2
{
public class PartialDigest
{
int width; List<int> X = new List<int>();
List<int> L = new List<int> { 2, 2, 3, 3, 4, 5, 6, 7, 8, 10 };
public void Main()
{
width = L.Max();
L.Remove(L.Single(x => x == width));
X.Add(0);
X.Add(width);
DisplayStatus();
Place();
}
public void DisplayStatus()
{
Console.Write("L:");
Utility.print(L);
Console.Write("X:");
Utility.print(X);
}
public void Place()
{
if (L.Count() == 0)
{
Console.WriteLine("Solution found");
Console.WriteLine("****************");
Utility.print(X);
Console.WriteLine("****************");
return;
}
int y1 = L.Max();
List<int> DX1 = (from v in X select Math.Abs(y1 - v)).ToList();
if (Utility.IsAInB(DX1, L))
{
X.Add(y1);
Utility.RemoveAFromB(DX1, L);
DisplayStatus();
Place();
}
int y2 = width - y1;
List<int> DX2 = (from v in X select Math.Abs(y2 - v)).ToList();
if (Utility.IsAInB(DX2, L))
{
X.Add(y2);
Utility.RemoveAFromB(DX2, L);
DisplayStatus();
Place();
}
}
}
}
04 February 2023
Practical Restriction Mapping Algorithm in C#
https://github.com/leocfong/bio2
11 July 2022
Partial Digest C++ implementation
https://github.com/leocfong/bio/blob/main/bio/digest.cpp
The rest of the code is in GitHub
The rest of the code is in GitHub
#include "digest.h"
#include <iostream>
#include <vector>
#include "Util.h"
using namespace std;
vector<int> FindDigest(vector<int>& X)
{
vector<int> v;
size_t n = X.size();
for (int i = 0; i < n; i++)
{
for (int j = 0; j < i; j++)
{
int g = abs(X[i] - X[j]);
v.push_back(g);
}
}
return v;
}
void Place(vector<int>& L, vector<int>& X, const int width, std::vector<int>& Answer)
{
if (L.size() == 0)
{
Answer = X;
cout << endl << "*****************" << endl;
cout << "Answer:" << endl;
Render(Answer);
cout << endl<< "*****************" << endl;
return;
}
int y = FindMax(L);
vector<int> r1 = DeltaToVector(X, y);
if (IsSubsetOf(r1, L))
{
X.push_back(y);
RemoveSubset(L, r1);
cout << "A-X:"; Render(X); cout << " L:"; Render(L); cout << " r1:"; Render(r1); cout << endl;
Place(L, X, width, Answer);
cout << "B-X:"; Render(X); cout << " L:"; Render(L); cout << " r1:"; Render(r1); cout << endl;
RemoveFromVector(X, y);
Add(L, r1);
}
int wy = width - y;
vector<int> r2 = DeltaToVector(X, wy);
if (IsSubsetOf(r2, L))
{
X.push_back(wy);
RemoveSubset(L, r2);
cout << "A-X:"; Render(X); cout << " L:"; Render(L); cout << " r2:"; Render(r2); cout << endl;
Place(L, X, width, Answer);
cout << "B-X:"; Render(X); cout << " L:"; Render(L); cout << " r2:"; Render(r2); cout << endl;
RemoveFromVector(X, wy);
Add(L, r2);
}
return;
}
void PartialDigest(vector<int>& L, vector<int>& X, std::vector<int>& Answer)
{
int width = FindMax(L);
RemoveFromVector(L, width);
X.push_back(0); X.push_back(width);
cout << "X:";Render(X);cout << " L:";Render(L); cout << endl;
Place(L, X, width, Answer);
}
05 March 2022
Enumerating k-mers Lexicographically solution for ROSALIND - https://rosalind.info/problems/lexf/
f = open("out.txt", "w")
input_file = open("rosalind_lexf.txt", "r")
lines = input_file.readlines()
char_array = lines[0].replace('\n', '').split(' ')
seq_len = int(lines[1])
char_array.sort()
char_array_len = len(char_array)
rep_len = []
rep_inc_counter = []
rep_char_index = []
rep_len_i = 1
for i in range(seq_len):
rep_inc_counter.append(0)
rep_char_index.append(0)
rep_len.append(rep_len_i)
rep_len_i = rep_len_i * char_array_len
num_combination = char_array_len ** seq_len
C = []
for i in range(num_combination):
s = ""
for l in range(seq_len):
s = char_array[rep_char_index[l]] + s
rep_inc_counter[l] = rep_inc_counter[l] + 1
if rep_inc_counter[l] == rep_len[l]:
rep_char_index[l] = rep_char_index[l] + 1
rep_inc_counter[l] = 0
if rep_char_index[l]==char_array_len:
rep_char_index[l] = 0
C.append(s)
for s in C:
print(s)
f.write(s+'\n')
f.close()
27 February 2022
ROSALIND RNA Splicing solution - https://rosalind.info/problems/splc/
import re
from asyncio.windows_events import NULL
f = open("out.txt", "w")
condon_len = 3
test= "TCTCGAGAGGCATATGGTCACATGATCGGTCGAGCGTGTTTCAAAGTTTGCGCCTAG"
dna_map = {
"TTT":"F", "TCT":"S", "TAT":"Y", "TGT":"C",
"TTC":"F", "TCC":"S", "TAC":"Y", "TGC":"C",
"TTA":"L", "TCA":"S", "TAA":"STOP", "TGA":"STOP",
"TTG":"L", "TCG":"S", "TAG":"STOP", "TGG":"W",
"CTT":"L", "CCT":"P", "CAT":"H", "CGT":"R",
"CTC":"L", "CCC":"P", "CAC":"H", "CGC":"R",
"CTA":"L", "CCA":"P", "CAA":"Q", "CGA":"R",
"CTG":"L", "CCG":"P", "CAG":"Q", "CGG":"R",
"ATT":"I", "ACT":"T", "AAT":"N", "AGT":"S",
"ATC":"I", "ACC":"T", "AAC":"N", "AGC":"S",
"ATA":"I", "ACA":"T", "AAA":"K", "AGA":"R",
"ATG":"M", "ACG":"T", "AAG":"K", "AGG":"R",
"GTT":"V", "GCT":"A", "GAT":"D", "GGT":"G",
"GTC":"V", "GCC":"A", "GAC":"D", "GGC":"G",
"GTA":"V", "GCA":"A", "GAA":"E", "GGA":"G",
"GTG":"V", "GCG":"A", "GAG":"E", "GGG":"G"
}
def GetAA(condon):
return dna_map[condon]
class Sequence:
def __init__(self, name, seq):
self.name = name
self.seq = seq
self.found = []
def p(self):
print("seq name:" + self.name + "len:" + str(len(self.seq)))
print("seq:" + self.seq)
for s in self.found:
print(s)
def pAA(self):
print (self.found[0])
f.write(self.found[0])
def Translate(self):
seq_len = len(self.seq)
aa_seq=""
start_pos = 0
end_pos = condon_len
while end_pos <= seq_len:
condon = self.seq[start_pos:end_pos]
AA = GetAA(condon)
if AA=="STOP":
break
aa_seq = aa_seq + AA
start_pos = start_pos + condon_len
end_pos = end_pos + condon_len
self.found.append(aa_seq)
input_file = open("rosalind_splc.txt", "r")
lines = input_file.readlines()
list = []
s = NULL
for l in lines:
if (l[0]==">"):
if s != NULL:
list.append(s)
s = Sequence(l.replace('\n', ''), '')
else:
s.seq = s.seq + l.replace('\n', '')
list.append(s)
list_len = len(list)
for i in range(1, list_len):
list[0].seq = list[0].seq.replace(list[i].seq, '')
list[0].Translate()
list[0].pAA()
f.close()
26 February 2022
ROSALIND - Locating Restriction Sites solution to https://rosalind.info/problems/revp/
c_map = {
"A":"T",
"G":"C",
"C":"G",
"T":"A"
}
def GetComplement(seq):
r = ''.join([c_map[x] for x in seq])
return r
def GetRevComplement(seq):
c = GetComplement(seq)
return c[::-1]
f = open("out.txt", "w")
input_file = open("rosalind_revp.txt", "r")
seq = ""
lines = input_file.readlines()
for l in lines:
if (l[0]!=">"):
seq = seq + l.replace("\n", "").replace("\r","")
seq_len = len(seq)
start_len = 2
end_len = 6
found_list = {}
for i in range(start_len, end_len+1):
for j in range(0, seq_len-(i*2)+1):
first_half = seq[j:j+i]
second_half =seq[j+i:j+i*2]
rc_second_half = GetRevComplement(second_half)
if (first_half == rc_second_half):
#print(first_half + " " + second_half + " " + rc_second_half + " " + str(j+1) + " " +str(i*2))
found_list[j+1]=i*2
sorted_found_list = sorted(found_list.items(), key=lambda item: item[0])
for key, value in sorted_found_list:
print(str(key) + " " + str(value))
f.write(str(key) + " " + str(value) + '\n')
f.close()
25 February 2022
Enumerating Gene Orders - https://rosalind.info/problems/perm/
from itertools import permutations
import math
f = open("out.txt", "w")
num=5
s=1
e=s+num
p=math.factorial(num)
print(p)
f.write(str(p) + '\n')
l = list(permutations(range(s, e)))
for i in range(p):
for j in range(num):
print(l[i][j], end=' ')
f.write(str(l[i][j]) + ' ')
print('')
f.write('\n')
f.close()
Calculating Protein Mass - https://rosalind.info/problems/prtm/
mmt = {
"A":71.03711,
"C":103.00919,
"D":115.02694,
"E":129.04259,
"F":147.06841,
"G":57.02146,
"H":137.05891,
"I":113.08406,
"K":128.09496,
"L":113.08406,
"M":131.04049,
"N":114.04293,
"P":97.05276,
"Q":128.05858,
"R":156.10111,
"S":87.03203,
"T":101.04768,
"V":99.06841,
"W":186.07931,
"Y":163.06333 }
input_file = open("rosalind_prtm.txt", "r")
AA = input_file.read().replace('\n','')
print(sum([mmt[x] for x in AA]))
Answer for ROSALIND Open Reading Frames https://rosalind.info/problems/orf/
import re
condon_len = 3
c_map = {
"A":"T",
"G":"C",
"C":"G",
"T":"A"
}
dna_map = {
"TTT":"F", "TCT":"S", "TAT":"Y", "TGT":"C",
"TTC":"F", "TCC":"S", "TAC":"Y", "TGC":"C",
"TTA":"L", "TCA":"S", "TAA":"STOP", "TGA":"STOP",
"TTG":"L", "TCG":"S", "TAG":"STOP", "TGG":"W",
"CTT":"L", "CCT":"P", "CAT":"H", "CGT":"R",
"CTC":"L", "CCC":"P", "CAC":"H", "CGC":"R",
"CTA":"L", "CCA":"P", "CAA":"Q", "CGA":"R",
"CTG":"L", "CCG":"P", "CAG":"Q", "CGG":"R",
"ATT":"I", "ACT":"T", "AAT":"N", "AGT":"S",
"ATC":"I", "ACC":"T", "AAC":"N", "AGC":"S",
"ATA":"I", "ACA":"T", "AAA":"K", "AGA":"R",
"ATG":"M", "ACG":"T", "AAG":"K", "AGG":"R",
"GTT":"V", "GCT":"A", "GAT":"D", "GGT":"G",
"GTC":"V", "GCC":"A", "GAC":"D", "GGC":"G",
"GTA":"V", "GCA":"A", "GAA":"E", "GGA":"G",
"GTG":"V", "GCG":"A", "GAG":"E", "GGG":"G"
}
found = []
input_file = open("rosalind_orf.txt", "r")
def GetComplement(seq):
r = ''.join([c_map[x] for x in seq])
return r
def GetAA(condon):
return dna_map[condon]
def GetAASeq(dna_seq, pos):
dna_seq_len = len(dna_seq)
seq=""
start_pos = pos
end_pos = pos + condon_len
condon = dna_seq[start_pos:end_pos]
AA = GetAA(condon)
while AA != "STOP":
seq = seq + AA
start_pos = start_pos + condon_len
end_pos = end_pos + condon_len
if (end_pos> (dna_seq_len-1)):
return "" #end of seq reached without finding stop condon
condon = dna_seq[start_pos:end_pos]
AA = GetAA(condon)
found.append(seq)
return seq
dna_seq = ""
lines = input_file.readlines()
for l in lines:
if (l[0]!=">"):
dna_seq = dna_seq + l.replace("\n", "").replace("\r","")
r_dna_seq = GetComplement(dna_seq[::-1])
seq_regex="ATG"
p = re.compile(seq_regex)
for m in p.finditer(dna_seq):
GetAASeq(dna_seq, m.start())
for m in p.finditer(r_dna_seq):
GetAASeq(r_dna_seq, m.start())
for s in list(set(found)):
print(s)
17 February 2022
ROSALIND - Inferring mRNA from Protein
Answer to https://rosalind.info/problems/mrna/
def GetMRna(AA):
l_aa = {key for key, value in aa_map.items() if value == AA}
return l_aa
input_file = open("rosalind_mrna.txt", "r")
aa_seq = input_file.read().replace("\n", "")
print(aa_seq)
aa_map = {
"UUU":"F", "UCU":"S", "UAU":"Y", "UGU":"C",
"UUC":"F", "UCC":"S", "UAC":"Y", "UGC":"C",
"UUA":"L", "UCA":"S", "UAA":"STOP", "UGA":"STOP",
"UUG":"L", "UCG":"S", "UAG":"STOP", "UGG":"W",
"CUU":"L", "CCU":"P", "CAU":"H", "CGU":"R",
"CUC":"L", "CCC":"P", "CAC":"H", "CGC":"R",
"CUA":"L", "CCA":"P", "CAA":"Q", "CGA":"R",
"CUG":"L", "CCG":"P", "CAG":"Q", "CGG":"R",
"AUU":"I", "ACU":"T", "AAU":"N", "AGU":"S",
"AUC":"I", "ACC":"T", "AAC":"N", "AGC":"S",
"AUA":"I", "ACA":"T", "AAA":"K", "AGA":"R",
"AUG":"M", "ACG":"T", "AAG":"K", "AGG":"R",
"GUU":"V", "GCU":"A", "GAU":"D", "GGU":"G",
"GUC":"V", "GCC":"A", "GAC":"D", "GGC":"G",
"GUA":"V", "GCA":"A", "GAA":"E", "GGA":"G",
"GUG":"V", "GCG":"A", "GAG":"E", "GGG":"G",
}
condon_len = []
stop_condons_len = 3
aa_seq_len = len(aa_seq)
for i in range(aa_seq_len):
condons = GetMRna(aa_seq[i])
condons_len = len(condons)
stop_condons_len = stop_condons_len * condons_len
print("Answer:" + str(stop_condons_len % 1000000) )
06 February 2022
Rosalind - Answer to Finding a Protein Motif
Answer to Finding a Protein Motif https://rosalind.info/problems/mprt/
import urllib.request
import re
from numpy import mat
#N-glycosylation motif
MotifRegex = "N[^P][ST][^P]"
file_out = open("output.txt", "w")
#Class to process protein sequence
class Sequence:
def __init__(self, name, seq):
self.name = name
self.seq = seq
def FindReg(self, reg):
match_string = ""
for match in re.finditer('(?={0})'.format(MotifRegex), self.seq):
index = match.start()+1
if len(match_string) == 0:
match_string = str(index)
else:
match_string = match_string + " " + str(index)
return match_string
def PrintOutcome(self):
match_string = self.FindReg(MotifRegex)
if len(match_string)>0:
print(self.name)
print(match_string)
file_out.write(self.name + '\n')
file_out.write(match_string + '\n')
#Get protein sequence from https://www.uniprot.org/uniprot/
def GetProtein(name):
url_base = "https://www.uniprot.org/uniprot/"
url_prefix = ".fasta"
url = url_base + name + url_prefix
with urllib.request.urlopen(url) as response:
html = response.read()
lines = html.decode().split("\n")
for line in lines:
if len(line)>1 and line[0] == ">":
protein = Sequence(name, "")
else:
protein.seq = protein.seq+line
return protein
ProteinList = []
input_file = open("rosalind_mprt.txt", "r")
#input_file = open("input.txt", "r")
lines = input_file.readlines()
for line in lines:
Protein = GetProtein(line.replace("\n", ""))
ProteinList.append(Protein)
for Protein in ProteinList:
Protein.PrintOutcome()
file_out.close()
04 January 2022
Found a really useful rapidxml example
#include <string.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <vector>
#include "rapidxml.hpp"
using namespace rapidxml;
using namespace std;
int main()
{
cout << "Parsing my beer journal..." << endl;
xml_document<> doc;
xml_node<>* root_node;
// Read the xml file into a vector
ifstream theFile("C:\\Work3\\ReadXml\\beerJournal.xml");
vector<char> buffer((istreambuf_iterator<char>(theFile)), istreambuf_iterator<char>());
buffer.push_back('\0');
// Parse the buffer using the xml file parsing library into doc
doc.parse<0>(&buffer[0]);
// Find our root node
root_node = doc.first_node("MyBeerJournal");
// Iterate over the brewerys
for (xml_node<>* brewery_node = root_node->first_node("Brewery"); brewery_node; brewery_node = brewery_node->next_sibling())
{
printf("I have visited %s in %s. ",
brewery_node->first_attribute("name")->value(),
brewery_node->first_attribute("location")->value());
// Interate over the beers
for (xml_node<>* beer_node = brewery_node->first_node("Beer"); beer_node; beer_node = beer_node->next_sibling())
{
printf("On %s, I tried their %s which is a %s. ",
beer_node->first_attribute("dateSampled")->value(),
beer_node->first_attribute("name")->value(),
beer_node->first_attribute("description")->value());
printf("I gave it the following review: %s", beer_node->value());
}
cout << endl;
}
}
<?xml version="1.0" encoding="utf-8"?>
<MyBeerJournal>
<Brewery name="Founders Brewing Company" location="Grand Rapids, MI">
<Beer name="Centennial" description="IPA" rating="A+" dateSampled="01/02/2011">
"What an excellent IPA. This is the most delicious beer I have ever tasted!"
</Beer>
</Brewery>
<Brewery name="Brewery Vivant" location="Grand Rapids, MI">
<Beer name="Farmhouse Ale" description="Belgian Ale" rating="B" dateSampled="02/07/2015">
This beer is not so good... but I am not that big of a fan of english style ales.
</Beer>
</Brewery>
<Brewery name="Bells Brewery" location="Kalamazoo, MI">
<Beer name="Two Hearted Ale" description="IPA" rating="A" dateSampled="03/15/2012">
Another execllent brew. Two Hearted gives Founders Centennial a run for it's money.
</Beer>
</Brewery>
</MyBeerJournal>
26 December 2021
Simple MFC UDP example
// SimpleUDPDlg.cpp : implementation file
//
#include "stdafx.h"
#include "SimpleUDP.h"
#include "SimpleUDPDlg.h"
#include "afxsock.h"
#include "ClientSend.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#define ECHOMAX 1024
/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About
HANDLE thr;
unsigned long id1;
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// Dialog Data
//{{AFX_DATA(CAboutDlg)
enum { IDD = IDD_ABOUTBOX };
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CAboutDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
//{{AFX_MSG(CAboutDlg)
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
//{{AFX_DATA_INIT(CAboutDlg)
//}}AFX_DATA_INIT
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAboutDlg)
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
//{{AFX_MSG_MAP(CAboutDlg)
// No message handlers
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CSimpleUDPDlg dialog
CSimpleUDPDlg::CSimpleUDPDlg(CWnd* pParent /*=NULL*/)
: CDialog(CSimpleUDPDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CSimpleUDPDlg)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CSimpleUDPDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CSimpleUDPDlg)
DDX_Control(pDX, IDC_EDIT1, m_edit);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CSimpleUDPDlg, CDialog)
//{{AFX_MSG_MAP(CSimpleUDPDlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_BUTTON1, OnStart)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CSimpleUDPDlg message handlers
UINT ReceiveData(LPVOID pParam)
{
CSimpleUDPDlg *dlg=(CSimpleUDPDlg*)pParam;
AfxSocketInit(NULL);
CSocket echoServer;
// Create socket for sending/receiving datagrams
if (echoServer.Create(514, SOCK_DGRAM, NULL)== 0) {
AfxMessageBox("Create() failed");
}
for(;;) { // Run forever
// Client address
SOCKADDR_IN echoClntAddr;
// Set the size of the in-out parameter
int clntAddrLen = sizeof(echoClntAddr);
// Buffer for echo string
char echoBuffer[ECHOMAX];
// Block until receive message from a client
int recvMsgSize = echoServer.ReceiveFrom(echoBuffer,
ECHOMAX, (SOCKADDR*)&echoClntAddr, &clntAddrLen, 0);
if (recvMsgSize < 0) {
AfxMessageBox("RecvFrom() failed");
}
echoBuffer[recvMsgSize]='\0';
dlg->m_edit.ReplaceSel(echoBuffer);
dlg->m_edit.ReplaceSel("\r\n");
}
}
BOOL CSimpleUDPDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
thr=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)ReceiveData,this,NULL,&id1);
// TODO: Add extra initialization here
return TRUE; // return TRUE unless you set the focus to a control
}
void CSimpleUDPDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CSimpleUDPDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
// The system calls this to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CSimpleUDPDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}
void CSimpleUDPDlg::OnStart()
{
// TODO: Add your control notification handler code here
CClientSend send;
send.DoModal();
}
01 October 2020
Create Bitmap example
#include <stdio.h>
const int BYTES_PER_PIXEL = 3; /// red, green, & blue
const int FILE_HEADER_SIZE = 14;
const int INFO_HEADER_SIZE = 40;
void generateBitmapImage(unsigned char* image, int height, int width, char* imageFileName);
unsigned char* createBitmapFileHeader(int height, int stride);
unsigned char* createBitmapInfoHeader(int height, int width);
int main()
{
int height = 361;
int width = 867;
unsigned char image[361][867][BYTES_PER_PIXEL];
char* imageFileName = (char*)"c:\\Work\\bitmapImage.bmp";
int i, j;
for (i = 0; i < height; i++) {
for (j = 0; j < width; j++) {
image[i][j][2] = (unsigned char)(i * 255 / height); ///red
image[i][j][1] = (unsigned char)(j * 255 / width); ///green
image[i][j][0] = (unsigned char)((i + j) * 255 / (height + width)); ///blue
}
}
generateBitmapImage((unsigned char*)image, height, width, imageFileName);
printf("Image generated!!");
}
void generateBitmapImage(unsigned char* image, int height, int width, char* imageFileName)
{
int widthInBytes = width * BYTES_PER_PIXEL;
unsigned char padding[3] = { 0, 0, 0 };
int paddingSize = (4 - (widthInBytes) % 4) % 4;
int stride = (widthInBytes)+paddingSize;
FILE* imageFile = fopen(imageFileName, "wb");
unsigned char* fileHeader = createBitmapFileHeader(height, stride);
fwrite(fileHeader, 1, FILE_HEADER_SIZE, imageFile);
unsigned char* infoHeader = createBitmapInfoHeader(height, width);
fwrite(infoHeader, 1, INFO_HEADER_SIZE, imageFile);
int i;
for (i = 0; i < height; i++) {
fwrite(image + (i * widthInBytes), BYTES_PER_PIXEL, width, imageFile);
fwrite(padding, 1, paddingSize, imageFile);
}
fclose(imageFile);
}
unsigned char* createBitmapFileHeader(int height, int stride)
{
int fileSize = FILE_HEADER_SIZE + INFO_HEADER_SIZE + (stride * height);
static unsigned char fileHeader[] = {
0,0, /// signature
0,0,0,0, /// image file size in bytes
0,0,0,0, /// reserved
0,0,0,0, /// start of pixel array
};
fileHeader[0] = (unsigned char)('B');
fileHeader[1] = (unsigned char)('M');
fileHeader[2] = (unsigned char)(fileSize);
fileHeader[3] = (unsigned char)(fileSize >> 8);
fileHeader[4] = (unsigned char)(fileSize >> 16);
fileHeader[5] = (unsigned char)(fileSize >> 24);
fileHeader[10] = (unsigned char)(FILE_HEADER_SIZE + INFO_HEADER_SIZE);
return fileHeader;
}
unsigned char* createBitmapInfoHeader(int height, int width)
{
static unsigned char infoHeader[] = {
0,0,0,0, /// header size
0,0,0,0, /// image width
0,0,0,0, /// image height
0,0, /// number of color planes
0,0, /// bits per pixel
0,0,0,0, /// compression
0,0,0,0, /// image size
0,0,0,0, /// horizontal resolution
0,0,0,0, /// vertical resolution
0,0,0,0, /// colors in color table
0,0,0,0, /// important color count
};
infoHeader[0] = (unsigned char)(INFO_HEADER_SIZE);
infoHeader[4] = (unsigned char)(width);
infoHeader[5] = (unsigned char)(width >> 8);
infoHeader[6] = (unsigned char)(width >> 16);
infoHeader[7] = (unsigned char)(width >> 24);
infoHeader[8] = (unsigned char)(height);
infoHeader[9] = (unsigned char)(height >> 8);
infoHeader[10] = (unsigned char)(height >> 16);
infoHeader[11] = (unsigned char)(height >> 24);
infoHeader[12] = (unsigned char)(1);
infoHeader[14] = (unsigned char)(BYTES_PER_PIXEL * 8);
return infoHeader;
}
03 June 2020
Easy way of finding centriod using octave
Octave code:
A=[10 11; 20 21; 30 31; 40 41; 50 51; 60 61; 70 71]
PB = [1 1 3 3 2 2 2]
C = A (PB==3,:)
D = mean(C)
SD = size(C,1)
Results:
A =
10 11
20 21
30 31
40 41
50 51
60 61
70 71
PB =
1 1 3 3 2 2 2
C =
30 31
40 41
D =
35 36
SD = 2
Simplified code:
for i=1:K
centroids(i,:) = mean( X(idx==i,:) );
endfor
A=[10 11; 20 21; 30 31; 40 41; 50 51; 60 61; 70 71]
PB = [1 1 3 3 2 2 2]
C = A (PB==3,:)
D = mean(C)
SD = size(C,1)
Results:
A =
10 11
20 21
30 31
40 41
50 51
60 61
70 71
PB =
1 1 3 3 2 2 2
C =
30 31
40 41
D =
35 36
SD = 2
Simplified code:
for i=1:K
centroids(i,:) = mean( X(idx==i,:) );
endfor
02 June 2020
Array indexing in Octave
A=[10 11; 20 21; 30 31; 40 41; 60 61; 60 61; 70 71]
PB = [1 3 5]
B = [1 2 3 4 7]
C = A (B(PB),:)
D = mean(C)
A =
10 11
20 21
30 31
40 41
60 61
60 61
70 71
PB =
1 3 5
B =
1 2 3 4 7
C =
10 11
30 31
70 71
D =
36.667 37.667
PB = [1 3 5]
B = [1 2 3 4 7]
C = A (B(PB),:)
D = mean(C)
A =
10 11
20 21
30 31
40 41
60 61
60 61
70 71
PB =
1 3 5
B =
1 2 3 4 7
C =
10 11
30 31
70 71
D =
36.667 37.667
25 April 2020
WPF update user interface in multithreading mode
public partial class Window1 : Window
{
public Class1 c;
public Window1()
{
InitializeComponent();
c = new Class1();
c.Class1Event += C_Class1Event;
}
private void C_Class1Event(object sender, Class1EventArgs e)
{//Triggered from a different thread
this.Dispatcher.Invoke((Action)(() =>
{//this refer to form in WPF application
imgShirt.Source = new BitmapImage(new Uri(System.AppDomain.CurrentDomain.BaseDirectory + @"\images2.jpg", UriKind.RelativeOrAbsolute));
}));
}
private void Change_Click(object sender, RoutedEventArgs e)
{
c.Start();
}
private void Change2_Click(object sender, RoutedEventArgs e)
{//Called from the same thread
Uri fileUri = new Uri(System.AppDomain.CurrentDomain.BaseDirectory + @"\images.jpg", UriKind.RelativeOrAbsolute);
imgShirt.Source = new BitmapImage(fileUri);
}
}
public class Class1
{
public event EventHandler<Class1EventArgs> Class1Event;
public Class1()
{
}
public void Start()
{
Task.Run(() => {
Class1EventArgs e = new Class1EventArgs();
Class1Event(this, e);
});
}
}
public class Class1EventArgs : EventArgs
{
}
31 January 2020
How to deserialize Xml with different namespaces / prefixes
Specify the namespace in the child element
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.8.3928.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace= "http://search.yahoo.com/mrss/", IsNullable=false)]
public partial class group {
private groupContent[] contentField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("content")]
public groupContent[] content {
get {
return this.contentField;
}
set {
this.contentField = value;
}
}
}
Use the XmlElement tag and specify the namespace in the parent node
/// <remarks/>
public string pubDate {
get {
return this.pubDateField;
}
set {
this.pubDateField = value;
}
}
[XmlElement("group", Namespace = "http://search.yahoo.com/mrss/")]
public group group
{
get
{
return this.groupField;
}
set
{
this.groupField = value;
}
}
}
Note: If you want to use the Visual Studio xsd.exe to generate the C# class, you need to strip off the elements with different namespace for xsd.exe to work. You can add the separate elements manually after.
14 April 2019
C++ Use Boost property_tree to manipulate xml files
#include "pch.h"
#include <iostream>
#include <string>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
using namespace std;
int main()
{
string path = "C:\\Work\\Students.xml";
string path2 = "C:\\Work\\Students2.xml";
try
{
std::cout << "Using property tree to manipulate XML files\n";
//how to load an xml file
boost::property_tree::ptree pt;
read_xml(path, pt);
boost::property_tree::ptree& Students = pt.get_child("Students");
//how to remove a node using Id
for (auto it = Students.begin(); it != Students.end();)
{
int id = it->second.get(".Id");
if (id == 1)
{
it = Students.erase(it);
}
else
{
++it;
}
}
//how to add nodes
for (auto data : { 3, 4, 5 })
{
boost::property_tree::ptree& Student = Students.add("Student", "");
Student.add(".Id", data);
Student.add("LastName", "McDonalds");
Student.add("FirstName", "Robert");
}
//how to save
write_xml(path2, pt, std::locale(), boost::property_tree::xml_writer_make_settings('\t', 1));
}
catch (exception e)
{
string s = e.what();
std::cout << s;
}
}
08 April 2019
SWIG, pass C++ array of classes back to C# example
Step 1 Create a C++ Windows DLL Project StudentDll
Step 2 Add Student.h file
#pragma once
#include
#include
class Student
{
public:
std::string FirstName;
std::string LastName;
Student(std::string _FirstName, std::string _LastName);
Student();
};
std::vector GetStudents();
Fill in the default Program.cs file as follow
using System.Text;
using System.Threading.Tasks;
namespace StudentConsumer
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World");
var s = StudentDllPINVOKE.GetStudents();
StudentVector sv = new StudentVector(s, true);
var sv0 = sv[0];
var sv00 = SWIGTYPE_p_Student.getCPtr(sv0);
var sv01 = new Student(sv00);
Console.WriteLine(sv01.FirstName + ", " + sv01.LastName);
Console.ReadKey();
}
}
}
public class Student : global::System.IDisposable {
private global::System.Runtime.InteropServices.HandleRef swigCPtr;
protected bool swigCMemOwn;
public Student(global::System.Runtime.InteropServices.HandleRef _swigCPtr)
{
swigCPtr = _swigCPtr;
}
Step 8 Set the StartUp project as StudentConsumer and Run it
swig is a good tool for converting interpolating code between C++ and other languages
http://www.swig.org/
Step 2 Add Student.h file
#pragma once
#include
#include
class Student
{
public:
std::string FirstName;
std::string LastName;
Student(std::string _FirstName, std::string _LastName);
Student();
};
std::vector
Step 3 Add Student.cpp file
#include "stdafx.h"
#include "Student.h"
Student::Student(std::string _FirstName, std::string _LastName)
{
FirstName = _FirstName;
LastName = _LastName;
}
Student::Student()
{
}
std::vector GetStudents()
{
std::vector sv;
sv.push_back(Student("John", "Smith"));
sv.push_back(Student("Mary", "Boyle"));
return sv;
}
Step 4 Add Student.i file
%module StudentDll
%include "std_string.i"
%apply const std::string& {std::string* FirstName};
%apply const std::string& {std::string* LastName};
%{
#include "student.h"
%}
%include
%include "student.h"
Step 4a
Select Student.i, Properties, General, Item Type as Custom Build Tool.
Select Apply to create the Custom Build Tool property group.
In Custom Build Tool, General, Command Line enter:
swig -csharp -c++ -outdir Student.i
In Outputs, enter Student_wrap.cxx, and click OK to close the dialog.
Right-click Student.i and Compile. This should create four files: three in the C# Generated folder and one in the C++ project.
Create a Generated Files filter in the C++ project and add Student_wrap.cxx to it.
Step 5 Add StudentVector.i file
%module StudentVectorDll
%include std_vector.i
%include std_string.i
/* allow partial c# classes */
%typemap(csclassmodifiers) SWIGTYPE "public partial class"
/* generate template around vector */
%template(StudentVector) std::vector;
Step 5a
Select Student.i, Properties, General, Item Type as Custom Build Tool.
Select Apply to create the Custom Build Tool property group.
In Custom Build Tool, General, Command Line enter:
swig -csharp -c++ -outdir GeneratedFolderPath StudentVector.i
In Outputs, enter StudentVector_wrap.cxx, and click OK to close the dialog.
Right-click StudentVector.i and Compile. This should create four files: three in the C# Generated folder and one in the C++ project.
Create a Generated Files filter in the C++ project and add StudentVector_wrap.cxx to it.
Step 6 Create a C# .Net Framework project StudentConsumer
Step 4 Add Student.i file
%module StudentDll
%include "std_string.i"
%apply const std::string& {std::string* FirstName};
%apply const std::string& {std::string* LastName};
%{
#include "student.h"
%}
%include
%include "student.h"
Step 4a
swig -csharp -c++ -outdir Student.i
Step 5 Add StudentVector.i file
%module StudentVectorDll
%include std_vector.i
%include std_string.i
/* allow partial c# classes */
%typemap(csclassmodifiers) SWIGTYPE "public partial class"
/* generate template around vector
%template(StudentVector) std::vector
Step 5a
swig -csharp -c++ -outdir GeneratedFolderPath StudentVector.i
Step 6 Create a C# .Net Framework project StudentConsumer
Fill in the default Program.cs file as follow
using System.Text;
using System.Threading.Tasks;
namespace StudentConsumer
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World");
var s = StudentDllPINVOKE.GetStudents();
StudentVector sv = new StudentVector(s, true);
var sv0 = sv[0];
var sv00 = SWIGTYPE_p_Student.getCPtr(sv0);
var sv01 = new Student(sv00);
Console.WriteLine(sv01.FirstName + ", " + sv01.LastName);
Console.ReadKey();
}
}
}
Step 7 Add Generated folder in the C# Student Consumer project
Step 7a Add the content of GeneratedFolderPath folder from C++ StudentDll project to the Generated folder
Step 7b Add an extra Constructor in the Student.cspublic class Student : global::System.IDisposable {
private global::System.Runtime.InteropServices.HandleRef swigCPtr;
protected bool swigCMemOwn;
public Student(global::System.Runtime.InteropServices.HandleRef _swigCPtr)
{
swigCPtr = _swigCPtr;
}
Step 8 Set the StartUp project as StudentConsumer and Run it
swig is a good tool for converting interpolating code between C++ and other languages
http://www.swig.org/
22 January 2019
C++ how using reserve method in vector reduces the number of times copy constructor is called
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <queue>
#include <ctime>
#include <chrono>
#include <type_traits>
#include <string>
#include <fstream>
using namespace std;
using namespace std::chrono;
class Point
{
public:
int x; int y;
Point(int _x, int _y)
{
x = _x;
y = _y;
cout << "constructor " << x << ", " << y << endl;
}
~Point()
{
cout << "destructor " << x << ", " << y <<endl;
}
Point(const Point& p)
{
x = p.x;
y = p.y;
cout << "!!! copy constructor " << x << ", " << y << endl;
}
friend std::ostream& operator<< (std::ostream& stream, const Point& p) {
return stream << "(" << p.x << ", " << p.y << ")";
}
};
Point CreatePoint()
{
Point p(100, 101);
return p;
}
int main()
{
vector<Point> p;
p.push_back(Point(1, 2));
p.push_back(Point(3, 4));
p.push_back(Point(5, 6));
vector<Point> p2;
p2.reserve(3);
p2.push_back(Point(10, 20));
p2.push_back(Point(30, 40));
p2.push_back(Point(50, 60));
Point cp = CreatePoint();
cout << "tesing completed." << endl;
getchar();
return 0;
}
Outputconstructor 1, 2
!!! copy constructor 1, 2
destructor 1, 2
constructor 3, 4
!!! copy constructor 3, 4
!!! copy constructor 1, 2
destructor 1, 2
destructor 3, 4
constructor 5, 6
!!! copy constructor 5, 6
!!! copy constructor 1, 2
!!! copy constructor 3, 4
destructor 1, 2
destructor 3, 4
destructor 5, 6
constructor 10, 20
!!! copy constructor 10, 20
destructor 10, 20
constructor 30, 40
!!! copy constructor 30, 40
destructor 30, 40
constructor 50, 60
!!! copy constructor 50, 60
destructor 50, 60
constructor 100, 101
tesing completed.
destructor 100, 101
destructor 10, 20
destructor 30, 40
destructor 50, 60
destructor 1, 2
destructor 3, 4
destructor 5, 6
Subscribe to:
Posts (Atom)




