Tag Archive for c

Class Dependency Graphs for C++

echo "digraph G {"> diagram.dot
sed -n -e "s/class [ ]*([a-zA-Z0-9_]*)[ ]*:[ ]*public [ ]*([a-zA-Z0-9_]*)[ ]*[{][ ]*/1 -> 2 ;/p" *.h >> diagram.dot
echo "}" >> diagram.dot

source

Fast Scientific Computation in Mex Functions Using Armadillo

#include "mex.h"
#include "math.h"
#include<armadillo>

using namespace arma;

void matlab2arma(mat& A, const mxArray *mxdata){
// delete [] A.mem; // don't do this!
access::rw(A.mem)=mxGetPr(mxdata);
access::rw(A.n_rows)=mxGetM(mxdata); // transposed!
access::rw(A.n_cols)=mxGetN(mxdata);
access::rw(A.n_elem)=A.n_rows*A.n_cols;
};

void freeVar(mat& A, const double *ptr){
access::rw(A.mem)=ptr;
access::rw(A.n_rows)=1; // transposed!
access::rw(A.n_cols)=1;
access::rw(A.n_elem)=1;
};

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
if (nrhs != 2)
mexErrMsgTxt("Incorrect number of input arguments");
if (nlhs != 1)
mexErrMsgTxt("Incorrect number of output arguments");

mat D1(1,1);
const double* D1mem=access::rw(D1.mem);
matlab2arma(D1,prhs[0]); // First create the matrix, then change it to point to the matlab data.

mat D2(1,1);
const double* D2mem=access::rw(D2.mem);
matlab2arma(D2,prhs[1]);

// check if the input corresponds to what you are expecting
if( D1.n_rows != D2.n_rows )
mexErrMsgTxt("Columns of D1 and D2 must be of equal length!");

if( D1.n_cols != D2.n_cols )
mexErrMsgTxt("Rows of D1 and D2 must be of equal length!");

plhs[0] = mxCreateDoubleMatrix(D1.n_rows, D1.n_cols, mxREAL);
mat output(1,1);
const double* outputmem=access::rw(output.mem);
matlab2arma(output,plhs[0]);

output=D1+D2;
// output.print();

freeVar(D1,D1mem); // Change back the pointers!!
freeVar(D2,D2mem);
freeVar(output,outputmem);
return;
}

source

Using XSLT to Transform XML Using C# ASP.NET

using System.Xml;
using System.Xml.Xsl;
using System.Xml.XPath;
using System.IO;

private string ApplyXSLTransformation()
{
string strHtml;

string strXstFile = Server.MapPath("my-xsl.xslt");
XslCompiledTransform x = new XslCompiledTransform();

// Load the XML
XPathDocument doc = new XPathDocument(Server.MapPath("my-xml.xml"));

// Load the style sheet.
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load(strXstFile);
MemoryStream ms = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(ms, Encoding.ASCII);
StreamReader rd = new StreamReader(ms);
xslt.Transform(doc, writer);
ms.Position = 0;
strHtml = rd.ReadToEnd();
rd.Close();
ms.Close();
return strHtml;
}

source

Represent int as hex with leading zeros

Console.WriteLine("|0123456789|
|{0,10}|", 47.ToString("X4"));
// produces the output
// |0123456789|
// |      002F|

source

C# proxy for JavaScript applications

<%@ WebHandler Language="C#" Class="proxy" %>
/*
This proxy page does not have any security checks. It is highly recommended
that a user deploying this proxy page on their web server, add appropriate
security checks, for example checking request path, username/password, target
url, etc.
*/
using System;
using System.Web;

public class proxy : IHttpHandler {

public void ProcessRequest (HttpContext context) {

string uri = context.Request.QueryString[0];
System.Net.WebRequest req = System.Net.WebRequest.Create(new Uri(uri));
req.Method = context.Request.HttpMethod;

byte[] bytes = new byte[context.Request.InputStream.Length];
context.Request.InputStream.Read(bytes,0,(int)context.Request.InputStream.Length);
req.ContentLength = bytes.Length;
req.ContentType = "application/x-www-form-urlencoded";
System.IO.Stream outputStream = req.GetRequestStream();
outputStream.Write(bytes, 0, bytes.Length);
outputStream.Close();

System.Net.WebResponse res = req.GetResponse();
context.Response.ContentType = res.ContentType;

System.IO.StreamReader sr = new System.IO.StreamReader(res.GetResponseStream());
string strResponse = sr.ReadToEnd();
context.Response.Write(strResponse);
context.Response.End();
}

public bool IsReusable {
get {
return false;
}
}

}

source

Clean up braces in many languages

/([s	]*[
]+[s	]*{)/ {/gi

source

PropertyGrid values in hex/hexadecimal using class derived from TypeConverter

// Included...
// [1] Define TypeConverter class for hex.
// [2] use it when defining a member of a data class using attribute TypeConverter.
// [3] Connect the data class to a PropertyGrid.


// [1] define UInt32HexTypeConverter is-a TypeConverter
public class UInt32HexTypeConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
{
return true;
}
else
{
return base.CanConvertFrom(context, sourceType);
}
}

public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(string))
{
return true;
}
else
{
return base.CanConvertTo(context, destinationType);
}
}

public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string) && value.GetType() == typeof(UInt32))
{
return string.Format("0x{0:X8}", value);
}
else
{
return base.ConvertTo(context, culture, value, destinationType);
}
}

public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
if (value.GetType() == typeof(string))
{
string input = (string)value;

if (input.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
{
input = input.Substring(2);
}

return UInt32.Parse(input, System.Globalization.NumberStyles.HexNumber, culture);
}
else
{
return base.ConvertFrom(context, culture, value);
}
}
} // UInt32HexTypeConverter used by grid to display hex.


// [2] define a class for data to be associated with the PropertyGrid.
[DefaultPropertyAttribute("Name")]
public class Data
.
.
.
public UInt32 stat;
[CategoryAttribute("Main Scanner"), DescriptionAttribute("Status"), TypeConverter(typeof(UInt32HexTypeConverter))]
public UInt32 Status
{
get { return stat; }
}
.
.
.
// [3] reference data for propertyGrid. (here, myData is a Data).
propertyGrid1.SelectedObject = myData ;

source

Break nsstring into array

Found this at <a href="http://borkware.com/quickies/one?topic=NSString" >http://borkware.com/quickies/one?topic=NSString</a> (useful link):

NSString *string = @"oop:ack:bork:greeble:ponies";
NSArray *chunks = [string componentsSeparatedByString: @":"];

Hope this helps!

Adam

source

Minimalist XSLT Transform Using Two Strings

public string TransformXML(string xml, string xslt)
{
string output = string.Empty;

XPathDocument xpd = new XPathDocument(new StringReader(xml));

XslCompiledTransform transform = new XslCompiledTransform(true);
transform.Load(new XmlTextReader(xslt, XmlNodeType.Document, null));

StringWriter sr = new StringWriter();
transform.Transform(xpd.CreateNavigator(), null, sr);
output = sr.ToString();

return output;
}


//Note that the XSL needs namespace prefixes to make .Net happy:

xsl = @"<xsl:stylesheet version='1.0'
xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>
<xsl:output method='text'/>
<xsl:template match='msg'>Found it!</xsl:template>
</xsl:stylesheet>";


xml = @"<msg/>";

source

Singleton

/**
* file Singleton.h
* rief The Singleton design pattern using templates.
* author Justin Chouinard <justin@chouinardconsulting.com>
*
***********************************************************************
* MyClass.h:
***********************************************************************
*
* class MyClass : public Singleton<MyClass>
* {
* ..
* }
*
***********************************************************************
* MyClass.cc
***********************************************************************
*
* MyClass *Singleton<MyClass>::inst = 0;
*
***********************************************************************
* Others
***********************************************************************
* Other files may access the instance by calling MyClass::getInstance().
*
**/


#ifndef __SINGLETON_H__
#define __SINGLETON_H__

template <class Type>
class Singleton
{
public:
static Type *getInstance(void);
private:
static Type *inst;
};	// end of class Singleton

template <class Type>
Type *Singleton<Type>::getInstance(void)
{
if (inst == 0)
inst = new Type;

return inst;
}

template <class Type>
Type *Singleton<Type>::inst = 0;

#endif // __SINGLETON_H__

source