Tuesday, August 18, 2009

t

t

A Novel Generic Multi-Layer Neural Networks :: Part 1: The Neuron Class

A Novel Generic Multi-Layer Neural Networks
Part 1: The Neuron Class


This post presents a model that I created for a NN program that I developed to solve general numeric problems (prediction, estimation, interpolation, extrapolation, etc.).

public class Neuron

{
private double __lastOutput;

private double __lastError;

private double __lastBias;

private double[] __lastWeights;

private int __siblingCount;

private int __layerInputCount;

#region Properties
private Delegates.ActivationFunction _ActivationFunction;

public Delegates.ActivationFunction ActivationFunction

{ get { return _ActivationFunction; } }

private int _InputCount;

public int InputCount

{ get { return _InputCount; } }

private double _Bias;

public double Bias

{ get { return _Bias; } }


private double[] _Weights;

public double[] Weights

{ get { return _Weights; } }

#endregion

#region Constructor


public Neuron(Delegates.ActivationFunction activationFunction, int inputCount, double? initialBias, double[] initialWeights, int siblingCount)

{ _ActivationFunction = activationFunction;

_InputCount = inputCount;

__siblingCount = siblingCount;

__layerInputCount = _InputCount * __siblingCount;

__lastError = 0.0;


if (initialBias == null)

_Bias = GlobalModule.GetRandomValue();

else

_Bias = initialBias.Value;

__lastBias = _Bias;
if (initialWeights == null)

{

_Weights = GlobalModule.GetRandomValue(inputCount);

}

else if (initialWeights.Length == inputCount)

{

initialWeights.CopyTo(_Weights, 0);

initialWeights.CopyTo(__lastWeights, 0);

}

else

throw new Exception("Invalid number of initial weights!");
}


#endregion


#region Public Methods


public double ComputeOutput(double[] input)

{

double totalInput = _Bias;
for (int i = 0; i <>

totalInput += _Weights[i] * input[i];

__lastOutput = _ActivationFunction.Invoke(totalInput);

return __lastOutput;

}

public void ChangeWeights(double error) // it also modifies the bias

{

double roughSharePlus = Math.Abs(error) / __layerInputCount;

double roughShareMinus = -roughSharePlus;

double curBias = _Bias;

if (Math.Abs(error) > Math.Abs(__lastError)) // worse (weak result)

{

roughSharePlus = -roughSharePlus;

roughShareMinus = -roughShareMinus;

}

for (int i = 0; i <> _Weights[i])

{

__lastWeights[i] = _Weights[i];

_Weights[i] += roughShareMinus * GlobalModule.GetRandomValue();

}

} // next i

if(__lastBias <> curBias)

_Bias += roughShareMinus * GlobalModule.GetRandomValue() * (__lastBias - curBias);
__lastBias = curBias;
return;

}


public void ReinitializeWeights() // it also reinitialize the bias

{

_Weights = GlobalModule.GetRandomValue(_InputCount);

_Bias = GlobalModule.GetRandomValue();

}


#endregion


} // end of class Neuron

Sunday, August 9, 2009

Conceptual Design in Database Development

Conceptual Design in Database Development!

The conceptual design is the first phase in the database design process:
  1. Conceptual Design
  2. Logical Design
  3. Implementation (Adaption)
  4. Physical Design

The conceptual design phase is a process of "Analysis and Discovery" and its goal is to define the "Requirements" of a system (a company/business/organization/etc.).

There are four main tasks to do in this phase:

1. Documenting the entities and the relationships between entities

2. Documenting the business rules for data

3. Defining the scope of the system

4. Defining a plan for security of the system

Saturday, August 8, 2009

a

a

Could not start Telegram Desktop

[2016.11.26 12:21:28] Launched version: 10019, alpha: [FALSE], beta: 0, debug mode: [FALSE], test dc: [FALSE]
[2016.11.26 12:21:28] Executable dir: C:/Users/Reza/AppData/Roaming/Telegram Desktop/, name: Telegram.exe
[2016.11.26 12:21:28] Initial working dir: C:/Users/Reza/AppData/Roaming/Telegram Desktop/
[2016.11.26 12:21:28] Working dir: C:/Users/Reza/AppData/Roaming/Telegram Desktop/
[2016.11.26 12:21:28] Arguments: "C:\Users\Reza\AppData\Roaming\Telegram Desktop\Telegram.exe"
[2016.11.26 12:21:28] Logs started
[2016.11.26 12:21:28] Connecting local socket to Global\e46b93575710e55e3b6a560b9ded52e1-{87A94AB0-E370-4cde-98D3-ACC110C5967D}...
[2016.11.26 12:21:28] This is the only instance of Telegram, starting server and app...
[2016.11.26 12:21:28] Could not copy 'log_start0.txt' to 'C:/Users/Reza/AppData/Roaming/Telegram Desktop/log.txt' to start new logging!
[2016.11.26 12:21:28] FATAL: Could not move logging to 'C:/Users/Reza/AppData/Roaming/Telegram Desktop/log.txt'!


Sunday, July 26, 2009

Reading Content of a Website Page



This short post shows how to read content of a web page by having its web address in ASP.NET.

In desktop applications, this task could simply be done by using a web browser control, i.e. System.Windows.Controls.WebBrowser, but in ASP.NET we need to use HttpWebRequest and HttpWebResponse objects as follows:

public static StringBuilder GetDocumet(string url)
{
StringBuilder rtn;
HttpWebRequest request;
HttpWebResponse response = null;
Stream stream = null;
StreamReader sr = null;

try
{
request = (HttpWebRequest)WebRequest.Create(url);
response = (HttpWebResponse)request.GetResponse();
stream = response.GetResponseStream();
sr = new StreamReader(stream);

rtn = new StringBuilder(sr.ReadToEnd());
}
catch
{
rtn = null; // not found
}

sr.Close();
stream.Close();
response.Close();

return rtn;
}

Tuesday, June 30, 2009

td

td

Water Effect:: Water Over Using GDI+ (source code)

The code for the previous post (Water Effect:: Water Over Using GDI+):


using
System.Collections.Generic;
using System.Drawing.Imaging;
using System.Drawing;
using System.Runtime.InteropServices;
using System;


namespace
WaterOver.GR
{

public class WaterOver
{

///
/// Create Water Over an Animated GIF Frames.
///
/// Returns full file name of frames.

public static string[] CreateWaterOverFrames(Bitmap bmp, int frameCount, string outputPath, string fileName)
{

string[] rtn = new string[frameCount];
int width = bmp.Width;
int height = bmp.Height;
int _waveWidth = width;
int _waveHeight = height;
int[, ,] __wave = new int[_waveWidth,_waveHeight, 2];
int __buffer = 0;

int radius = (int)(0.6 * Math.Min(width, height));

int fromX = (int)(4.0 * width / 10.0);
int toX = 1 + (int)(6.0 * width / 10.0);
int fromY = height - (1 + (int)(height / 10.0));
int toY = height;
Random r = new Random();
int x, y;
string gnlFfn; // general full file name (to save frame files)

// Set gnlFfn.
outputPath = outputPath.Trim();

if(!outputPath.EndsWith(@"\"))
outputPath +=
@"\";
gnlFfn = outputPath + fileName.Trim() +
"_";

byte[] _bmpBytes = new Byte[width * height * 4];

// Set _bmpBytes.
BitmapData _bmpBitmapData = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);

Marshal.Copy(_bmpBitmapData.Scan0, _bmpBytes, 0, width * height * 4);

////////////////////////////////
// Generate frames one by one //
////////////////////////////////

for (int h = 0; h < frameCount;h++)
{

///////////////////
// Refine waves. //
///////////////////

int __newBuffer = (__buffer == 0) ? 1 : 0;

bool wavesFound = false;

for (x = 1; x <>for (y = 1; y <>> 2) - __wave[x, y, __newBuffer];

if (__wave[x, y, __newBuffer] != 0)
{
__wave[x, y, __newBuffer] -= __wave[x, y, __newBuffer] >> 4;
wavesFound =
true;
}

}
// next y
} // next x

__buffer = __newBuffer;


///////////////////////////////
// Put a wave center (drop). //
///////////////////////////////

x = r.Next(fromX , toX);
y = r.Next(fromY, toY);
double dist;

for (int i = -radius; i <= radius; i++) { for (int j = -radius; j <= radius; j++) { if (((x + i <= 0) && (x + i < dist =Math.Sqrt(i * i + j * j);

if (dist <>int)(Math.Cos(dist * Math.PI / radius) * height);

}
}
}

/////////////////////
// Paint the frame //
/////////////////////


using (Bitmap tmpBmp = (Bitmap)bmp.Clone())
{

int xOffset, yOffset;

byte alpha;

if (wavesFound)
{

BitmapData tmpData = tmpBmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite,
PixelFormat.Format32bppArgb);

byte[] tmpBytes = new Byte[width * height * 4];
Marshal.Copy(tmpData.Scan0, tmpBytes, 0, width * height * 4);
for (x = 1; x <>for (y = 1; y <>int waveX = x;
int waveY = y;
// Check bounds.
if (waveX <= 0) waveX = 1; if (waveY <= 0) waveY = 1; if (waveX <= _waveWidth - 1) waveX = _waveWidth - 2; if (waveY <= _waveHeight - 1) waveY = _waveHeight - 2; // Make the effect of water breaking the light.
xOffset = (__wave[waveX - 1, waveY, __buffer] - __wave[waveX + 1, waveY, __buffer]) >> 3;

yOffset = (__wave[waveX, waveY - 1, __buffer] - __wave[waveX, waveY + 1, __buffer]) >> 3;

if ((xOffset != 0) (yOffset != 0))
{
// Check bounds.
if (x + xOffset >= width - 1) xOffset = width - x - 1;
if (y + yOffset >= height - 1) yOffset = height - y - 1;
if (x + xOffset < 0) xOffset = -x;

if (y + yOffset < 0) yOffset = -y;

// Generate alpha.
alpha = (byte)(200 - xOffset);
if (alpha <>
alpha = 0;
if (alpha < alpha =" 254;">// Set colors.
tmpBytes[4 * (x + y * width)] = _bmpBytes[4 * (x + xOffset + (y + yOffset) * width)];
tmpBytes[4 * (x + y * width) + 1] = _bmpBytes[4 * (x + xOffset + (y + yOffset) * width) + 1];
tmpBytes[4 * (x + y * width) + 2] = _bmpBytes[4 * (x + xOffset + (y + yOffset) * width) + 2];
tmpBytes[4 * (x + y * width) + 3] = alpha;
}
}
// next y
} // next x


// Copy data back.
Marshal.Copy(tmpBytes, 0, tmpData.Scan0, width * height * 4);
tmpBmp.UnlockBits(tmpData);
}

// Save tmpBmp, the new frame generated.
rtn[h] = gnlFfn + h.ToString() + ".gif";
tmpBmp.Save(rtn[h],
ImageFormat.Gif);

}
}
// next h

return rtn;
}

}
}


The method CreateWaterOverFrames returns an array of file names (frames) that can be used in a function to create a single animated gif file; there are a few of them; one that is fairly a good one and simple to use can be found here.


LINQ

LINQ

Language Integrated Query (LINQ, pronounced "link") is a Microsoft .NET Framework component that adds native data querying capabilities to .NET languages.
An efficient way to experiment with LINQ is to download LINQPad, at www.linqpad.net.

Water Effect:: Water Over Using GDI+

Water Effect:: Water Over Using GDI+


The code in this post is to create a water effect sample, water over, on images using .NET's GDI+.


See the following example!



This image:









Will be converted to the following animated GIF:





The following code shows how to add water waves over frames; where each frame is initiated by the original image.

~ continued (see the next post).

Tuesday, March 31, 2009

Design Patterns :: Singleton

Design Patterns :: Singleton

There are many common situations when singleton pattern is used:
 - Accesing resources in shared mode
 - Configuration Classes
 - Logger Classes
 - Serialization
 - Network Port Interface

Singleton Design Pattern
Singleton Design Pattern

Check list
1.Define a private static attribute in the "single instance" class.
2.Define a public static accessor function in the class.
3.Do "lazy initialization" (creation on first use) in the accessor function.
4.Define all constructors to be protected or private.
5.Clients may only use the accessor function to manipulate the Singleton.



  1. using System;

  2. namespace DesignPatternsSingleton
  3. {
  4.   /// <summary>
  5.   /// MainApp startup class for Design Patterns :: Singleton
  6.   /// </summary>
  7.   class MainApp
  8.   {
  9.   /// <summary>
  10.   /// The Singleton class.
  11.   /// </summary>
  12.   public class Singleton
  13.   {
  14.     private static Singleton _instance;

  15.     // Constructor is 'protected'
  16.     protected Singleton()
  17.     {
  18.     }

  19.     public static Singleton Instance()
  20.     {
  21.       // Uses lazy initialization.
  22.       // Note: this is not thread safe.
  23.       if (_instance == null)
  24.       {
  25.         _instance = new Singleton();
  26.       }

  27.       return _instance;
  28.     }
  29.   }
  30. }

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading;

  4. namespace DesignPatternsSingleton
  5. {
  6.   /// <summary>
  7.   /// MainApp startup class for Real-World
  8.   /// Singleton Design Pattern.
  9.   /// </summary>
  10.   class MainApp
  11.   {
  12.     /// <summary>
  13.     /// Entry point into console application.
  14.     /// </summary>
  15.     static void Main()
  16.     {
  17.       LoadBalancer b1 = LoadBalancer.GetLoadBalancer();
  18.       LoadBalancer b2 = LoadBalancer.GetLoadBalancer();
  19.       LoadBalancer b3 = LoadBalancer.GetLoadBalancer();
  20.       LoadBalancer b4 = LoadBalancer.GetLoadBalancer();

  21.       // Same instance?
  22.       if (b1 == b2 && b2 == b3 && b3 == b4)
  23.       {
  24.         Console.WriteLine("Same instance\n");
  25.       }

  26.       // Load balance 15 server requests
  27.       LoadBalancer balancer = LoadBalancer.GetLoadBalancer();
  28.       for (int i = 0; i < 15; i++)
  29.       {
  30.         string server = balancer.Server;
  31.         Console.WriteLine("Dispatch Request to: " + server);
  32.       }

  33.       // Wait for user
  34.       Console.ReadKey();
  35.     }
  36.   }

  37.   /// <summary>
  38.   /// The 'Singleton' class
  39.   /// </summary>
  40.   class LoadBalancer
  41.   {
  42.     private static LoadBalancer _instance;
  43.     private List<string> _servers = new List<string>();
  44.     private Random _random = new Random();

  45.     // Lock synchronization object
  46.     private static object syncLock = new object();

  47.     // Constructor (protected)
  48.     protected LoadBalancer()
  49.     {
  50.       // List of available servers
  51.       _servers.Add("ServerI");
  52.       _servers.Add("ServerII");
  53.       _servers.Add("ServerIII");
  54.       _servers.Add("ServerIV");
  55.       _servers.Add("ServerV");
  56.     }

  57.     public static LoadBalancer GetLoadBalancer()
  58.     {
  59.       // Support multithreaded applications through
  60.       // 'Double checked locking' pattern which (once
  61.       // the instance exists) avoids locking each
  62.       // time the method is invoked
  63.       if (_instance == null)
  64.       {
  65.         lock (syncLock)
  66.         {
  67.           if (_instance == null)
  68.           {
  69.             _instance = new LoadBalancer();
  70.           }
  71.         }
  72.       }

  73.       return _instance;
  74.     }

  75.     // Simple, but effective random load balancer
  76.     public string Server
  77.     {
  78.       get
  79.       {
  80.         int r = _random.Next(_servers.Count);
  81.         return _servers[r].ToString();
  82.       }
  83.     }
  84.   }
  85. }

Setting Language/Culture in Using Global Resource Files



Setting Language/Culture in Using Global Resource Files


In this short post, in the code of an aspx page, we want to make the page to use our global resource file called UI.fr-CA.resx that is in Canadian French (fr-CA).

In order to this, just open the source code of the page (or the source code of the super class of your page class) and override its InitializeCulture method as in the following:

protected override void InitializeCulture()
{
Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("fr-CA");
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("fr-CA");
base.InitializeCulture();
}



There is a good point in the above code: it works even if your controls or user controls located in the page have processes in threads different from the current thread!

Wednesday, March 18, 2009

Creational Design Patterns

List of Creational Design Patterns

In the following, which five design patterns are the creational patterns?


 1) Abstract Factory
 2) Adapter
 3) Bridge
 4) Builder
 5) Chain of Responsibility
 6) Command
 7) Composite
 8) Decorator
 9) Facade
10) Factory Method
11) Flyweight
12) Interpreter
13) Iterator
14) Mediator
15) Memento
16) Observer
17) Prototype
18) Proxy
19) Singleton
20) State
21) Strategy
22) Template Method
23) Visitor
 


Creational Design Patterns


  1. Abstract Factory
  2. Builder
  3. Factory Method
  4. Prototype
  5. Singleton

Object Initializers with Anonymous Types



Object Initializers with Anonymous Types




In C# 3.0, we can use object initializers with anonymous types. The following example shows how it can be done:

The Customer class is an arbitrary class that we want to use in this example:


public class Customer
{
public int CustomerID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}


We declare a colloecton of customers by employing "object initializers":


List customers = new List
{
new Customer { CustomerID = 99, FirstName = "Brian" , LastName = "White"},
new Customer { CustomerID = 100, FirstName = "Nicole" , LastName = "Stewart"},
new Customer { CustomerID = 101, FirstName = "Lucy" , LastName = "Brothers"}
};

Now, we create a LINQ query where the returning objects have anonymous types; an anonymous type that has two properties: ID and Name; and also we employ the object initializer concept to initialize the properties of our objects:


var selCust = from c in customers
where c.CustomerID <= 100
orderby c.LastName, c.FirstName
select new { ID = c.CustomerID, Name = c.FirstName + " " + c.LastName};


The variable selCust contains objects of an anonymous type with their properties already set (initialized). To confirm this, run the following code snippet:


foreach (var cust in selCust)
{
Console.WriteLine(cust.ID.ToString() + " " + cust.Name);
}

Saturday, February 21, 2009

Compiling, Packaging and Deploying [Part One]

Compiling, Packaging and Deploying [Part One]

Question 1: How do you deploy your web application, “MyApp”, to a virtual directory “MyApp” of www.ASPCert.com where the user interface should be updatable and there shouldn’t be a delay when the web pages are accessed for the first time?

By compiling and deploying the application as:

aspnet_compiler -v /MyApp -u "http://www.ASPCert.com/MyApp"



Original questions authored by G. R. Roosta


ASPX Page [Part One]

Page [Part One]

Question 1: What is the order of events fired when an ASPX page is loaded and displayed?


9 events are fired in this order:

  • PreInit
  • Init
  • InitComplete
  • PreLoad
  • Load
  • LoadComplete
  • PreRender
  • PreRenderComplete
  • Unload



Original questions authored by G. R. Roosta

ASP.NET MVC Framework

ASP.NET MVC Framework

Model–View–Controller (MVC) is an architectural pattern in software engineering. This pattern isolates business logic from user interface leading to applications that modifying the visual appearance and the biz rules can be performed independently.
In MVC, the model represents data of the application, the controller manages the communication between data and the biz rules (to manipulate data) and the view corresponds to items in the user interface (pages/forms and controls).
ASP.NET MVC provides a MVC framework on top of the existing ASP.NET 3.5 runtime. This new framework defines a pattern to the web application folder structure and provides a controller base-class to handle and process requests for “actions”. Developers can use the specific Visual Studio 2008 MVC templates to create MVC web applications (You can download it from:
http://www.microsoft.com/downloads/details.aspx?FamilyID=f4e4ee26-4bc5-41ed-80c9-261336b2a5b6). MVC framework is extensible allowing developers to create sophisticated structures that meet their needs, including for example Dependency Injection techniques, new view rendering engines or specialized controllers. As ASP.NET MVC framework is built on ASP.NET 3.5, developers can also take advantage of the existing ASP.NET 3.5 features with this framework.

Tuesday, February 10, 2009

Creating Server Controls [Part One]

Creating Server Controls [Part One]


Question 1: How do you declare the class a server control that must support data binding and data paging?

The class should inherit from DataBoundControl and implement the IPageableItemContainer interface; for example:

public class MyClass : DataBoundControl, IPageableItemContainer
{
   ...
}



Original questions authored by G. R. Roosta

Sunday, February 8, 2009

WCF & ASP.NET 3.5 Web Services [Part One]

WCF & ASP.NET 3.5 Web Services [Part One]

Question 1: How are ASP.NET web services set to work with ASP.NET AJAX scripts?

The attribute [System.Web.Script.Services.ScriptService] is set for the class of each web service. This attribute indicates that a web service may be invoked from script.

Example:

[WebService(Namespace = "http://www.aspcert.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)][System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld( )
{
return "Hello World";
}
}



Original questions authored by G. R. Roosta

My New Blog: Questions in ASP.NET 3.5

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- - - - - - - - - - - - - -


See my new blog, Questions in ASP.NET 3.5, at http://aspnet35questions.blogspot.com/



- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- - - - - - - - - - - - - -