sabato 4 maggio 2019

My cyberdeck

This is my version of Cyberdeck from the dystropian future of William Gibson.
It is raspberry pi2 + arduino micro + 50W audio amply and double LCD display.
Portable.


Design Pattern : Flyweight Pattern

Flyweight Pattern is user to reduce the amount or memory when you have many objects with a common part. So you separate the common part from the specialized part of the object and you reuse the common parte for all object.
For example you can create a cache class that stores a list of objects, these objects are common and you don't need to instantiate a new object if it is already instantiated previously. The Classic example is a Word processore that uses characters. The characters have a common part: font,size,color, and a specificare part, the characters itself : 'a', 'b', etc and when you use the characters 'a' you don't have to recreate the object again when you use it a second time.

class Character
{
    int size;
    string font;
    Color color;

    public void Character()
    {
         size = 8;
         font = "Verdana";
         color = Color.Red;
    }
}

public class CharacterA : Character
{
    char character;
   
    public void CharacterA()
    {
         character = 'A';
    }
}

public class CharacterB : Character
{
    char character;
   
    public void CharacterB()
    {
         character = 'B';
    }
}

...

public class CharacterFactory
{
    private Dictionary<char,Character> characterMap;
    ...
    public Character GetCharacter(char character)
   {
        Character characterToReturn;
        if (characterMap.ContainsKey(character))
        {
             characterToReturn = characterMap[character];
        }
        else
       {
             switch(character)
             {
                   case 'A':
                       characterToReturn = new CharacterA();
                   case 'B':
                        characterToReturn = new CharacterB();
                   ...
             }
             characterMap[character] = characterToReturn;
       }

       return characterToReturn;
   }
}

domenica 28 aprile 2019

Design Patterns : State Pattern

State pattern defines a way to manage a state machine, if you don't use design patterns, in traditional programming, you will use a switch statement to move throw the states.
You have to create an interface with a method for the action to do in a specific state, then you have to create concreate classes for each state and implement the method to implement the state, then you need a context to switch the states. The client will use the context to change the states.

public interface IStatus
{
     void ApplyStatus();
}

public class StateInit : Status
{
     void ApplyStatus()
     {
           InitializeMachine();
     }
}

public class StateRunning : Status
{
     public void ApplyStatus()
     {
           RunMachine();
     }
}

public class StateStop : Status
{
     public void ApplyStatus()
     {
           StopMachine();
     }
}

public class Context
{
      private Status state,

      public void SetStatus(Status status)
      {
            state = status;
      }

      public ChangeStatus()
     {
           state.ApplyStatus();
     }
}

Usage:
Contex contex;
context.SetStatus(new StateInit());
context.ChangeStatus();
context.SetStatus(new StateRunning());
context.ChangeStatus();
context.SetStatus(new StateStop());
context.ChangeStatus();

sabato 27 aprile 2019

Design Patterns : Factory Pattern


Factory pattern is a pattern to create objects from a factory, when 2 objects are similar, to avoid casting.
You have to create an abstract base class with some methods and one or more concrete classes that inherit the base class, then you have to create a factory class that has a method that return a base class, the class returned is based on the parameters of the method.

abstract class Vehicle
{
       public abstract Run();
}

class Car : Vehichle
{
      public override Run()
      {
          // implement run for a car
      }
}

class Motorcycle : Vehichle
{
      public override Run()
      {
          // implement run for a motorcycle
      }
}

class NullMobile : Vehichle
{
      public override Run()
      {
          // do nothing
      }
}


public static class Factory
{
       public Vehicle GetVehicle(string type)
      {
            if (type.Equals("car"))
                   return new Car();
            else if (type.Equals("motorcycle"))
                   return new Motorcycle();
            else
                   return new NullMobile();
      }
}

Usage:
var newCar = Factory.GetVehicle("car);
 newCar.Run();

Design Patterns : Singleton

Singleton is very easy design pattern, it is used to instantiate an object only 1 time in the application.
It's like a static member.
You have to create a class and add a private member of the same class (the instance of the class), then you have to set private the constructor and add a method to get the instance that creates a new instance if not already created, otherwise it returns the private member.

static class Singleton
{
       private static Singleton instance;
   
       pubic static GetInstance()
       {
              if (instance == null)
                    instance = new Singleton();
              return instance;
       }
}

Usage:

var mySingleton1 = Singleton.GetInstance();
var mySingleton2 = Singleton.GetInstance(); // in another module
and the result is mySingleton1 = mySingleton2

Design Patterns: Composite Patter

Composite patter essentially implements a tree of objects and you can use it everytime you need a tree data structure.
At first you define a class for a node with private information for the node and the list of child node. In the constructor you pass the information to create the node, also you need a method to add a child node that add the child node in the private list of child nodes and also a method to get all the child nodes. You also need an class for the root node to create the tree. the root node class has a private node that is the root node. you need a method to get this root node, then you call rootnode.add to add child nodes to root node and build the tree. A classic use of composite pattern is associated to the filesystem that is a tree data structure.

public class Node
{
      private NodeInfo nodeInfo;
      private List<Node> childNodes;
      public void Node(NodeInfo info)
     {
           nodeInfo = info;
           childNodes = new List<Node>();
     }

     public NodeInfo GetInfo()
    {
           return nodeInfo;
    }

     public void Add(Node node)
     {
            childNodes.Add(node);
     }

     public IEnumerable<Node> GetChildNodes()
    {
            foreach(var node in childNodes)
                   yield return node;
    }

}

pubic class Root
{
      private Node root;

      public Root(Node node)
      {
             root = node;
      }

      public Node getRoot()
      {
             return root;
      }
}

Usage:
var rootNode = new Node(nodeInfo);
var firstChild = new Node(nodeInfo1);
var secondChild = new Node(nodeInfo2);
var tree = new Root(rootNode);
var node = tree.getRoot(),
node.Add(firstChild);
node.Add(secondChild);
foreach(n in node.GetChildNodes())
     Console.WriteNode(n);

Design Patterns: Strategy Pattern

In the latest years design pattern programming seems a must if you want to work in a development team, especially java and C#. What I think is that a good programmer only need common sense.

This is very simplified explanation of strategy pattern:
Strategy pattern is when you want use different strategy or algorithms to process data. For example you want to use different types of sort: quick sort, bubble sort,etc, in this case the strategy is the sort algorithm. You have to create an abstract class Strategy with a method to apply the strategy, then you have to implement the strategies classes inherit from Strategy class that overload the same method with their strategy.
At the end you have to create a context class that has a private Strategy member, in the constructor you pass the strategy class (Ex: quick sort) and a method to implement the strategy that will call the strategy.strategy method.

public abstract class Strategy
{
public abstract double applyAlgorithm(int a,int b),
}

public class FirstAlghorithm extends Strategy
{
@Override
         public double ApplyAlgorithm(int a,int b)
         {
// do calculation
}
}

public class SecondAlghorithm extends Strategy
{
@Override
         public double ApplyAlgorithm(int a,int b)
         {
// do calculation
}
}

public class Context
{
         private Strategy strategy,
   
         public Context(Strategy strategy)
         {
                this.strategy = strategy;
         } 

         public double applyAlgorithm(int a,int b)
         {
return strategy.ApplyAlgorithm(a,b);
}
}

Usage:

Context ctx = new Context( new FirstStrategy());

double result = ctx.ApplyAlgorithm( 4, 2);


In case of sorting strategies the previous example  become:

public abstract class StrategySort
{
public abstract void Sort(int[] array),
}

public class MergeSort extends StrategySort
{
@Override
        public void Sort(int[] array)         
        {
// do merge sort in array
}
}

public class QuickSort extends StrategySort
{
@Override
        public void Sort(int[] array)         
        {
// do quicksort in array
}
}

public class Context
{
         private StrategySort strategy,
   
         public Context(StrategySort strategy)
         {
                this.strategy = strategy;
         } 

        public void Sort(int[] array)         
        {
strategy.Sort(array);
}
}

Usage:

Context ctx = new Context( new QuickSort());

double result = ctx.Sort(array);





mercoledì 27 marzo 2019

ESP32 AND C#

I installed nanoframework in Visual Studio 2017 and I can program ESP32 using C#.
The API for ESP32 is quite limited and with Arduino IDE you can do much more, but C# is high level programming language,  it's highly OOP oriented and it's a good solution  for complex applications. ESP32 has a lot of memory and double core CPU. If you use it with LUA or javascipt you are limited  by the language.
Also, if you have a ESP32 board with JTAG, you can  use the step by step debugger of Visual Studio.
You have to download a specific firmware on ESP32 to make it  work with nanoframework, the firmware is in nanoframework git repository.

domenica 27 gennaio 2019

SPARKFUN MICRO PRO


Dear friends,
I was  googling about how  to  use esp32 like  a usb  keyboard, but it doesn't seem feasible and youncan't use  the  arduino keyboard  library.
It seems only certain arduinos can use keyboard  library: Leonardo, micro, arduino 2, mkr serie.
I opted for sparkfun micro pro, because I found it in  the electronic  shop behind the corner.
At first glance I was very surprised for the size,  it's incredible  small, apart  that, keyboard libraries  works  perfectly on it.
You will wonder why am I interested  in such a device?
The reason is because I red of a device  called bash bunny.
That'an interesting concept,  because the idea of simply connect to the computer an usb keyboard and automagically control  it is the fantasy of my childhood and it  is used  in many Hollywood movies.
In past  I thought to simulate a cdrom with  an  arduino, because  it you pur certain  files  on a cdrom  the  old versions  of windows  executed it when you3 inserted the  cdrom  without asking, but  the latest  versions of windows  asks.
Basically  as usb  key  emulator you can do anything on the computer. You  can login, activate the command prompt or the  powershell  prompt  and write your  program and execute  it. Top can have the total control  of the system.
For example it you want to start  the command  prompt, voi nave to use this code:
include "Keyboard.h"
...
Keyboard.begin();
Keyboard.press(KEY_LEFT_GUI);
Keyboard.press('r');
Keyboard.releaseAll();
delay(2000);
Keyboard.press(KEY_RETURN);
Keyboard.releaseAll();
delay(2000);
Now you can write your commands
...
It you want to type many characters, you need an  sd reader to  connect to  the micro pro. Usually sd card  readers requires 5volt.  You  can  use  the  usb  to  obtain this Voltage. I bought the 3.3 volts  version  of the micro  pro because I wanted to connect  it to the esp32, but there is also  a 5v version.

sabato 19 gennaio 2019

FACE EDITOR

Hey guys,
I found a program that uses unsupervised learning neural network to generate random faces.
https://github.com/HackerPoet/FaceEditor
These faces are not faces of real people, these are faces of unexisting people. You click a button and it generates a random face,then you can change this face using many switches.
These are some faces I generated:

What happens if someone put a unexisting face in a fake facebook profile?


sabato 29 dicembre 2018

NEURONA


This is an ESP32 board with OLED display. It's cool.
I was trying to program this board by Zerynth Studio, but the display on this board uses I2C, while the libraries for Zerynth Studio works only with SPI interface. In order to avoid to manage the I2C protocol from the base class, I had to move to Arduino IDE and forget Python.
Has been a long time since I used Arduino Ide and I discovered an interesting neural network implementation, it is distributed as Arduino library: Neurona.
This library implements a supervised neural network for Arduino boards and also it works for ESP32, my crush board. The usage of the library is quite simple, you initialize it with the number of inputs, the number of hidden layers and the number of outputs. You have to provide the trained weights, it does not train on Arduino, you have to use an external software to train the network and obtains the weight, then you pass the weight to the library.

sabato 15 dicembre 2018

EVOLUTION FOR ANDROID

I found this app on  Google Play:
You can build a creature by adding joints,  bones and muscles.
The game uses neural network to evolve your creature to walk,  jump  and avoid obstacles.
It's very funny and additive.

lunedì 5 novembre 2018

NEMATODE BRAIN

A nematode has 302 neurons.
Can we replicate the brain of a nematode by an artificial neural network? 
I think we can't. The question is: the soul of the nematode is in those 302 neurons? Or not?
Is the nematode self conscious? If the nematode is not self conscious, it is only a machine.
If a nematode is not self conscious, a cat is self conscious? Why are we self conscious and a nematode not? Because we have more neurons?
Are we sure we are self conscious or we are only executing a complex alghorithm? 
How can a neuro contains part of a soul?
The model of an artificial neuron make sums, the signal of a single neuron is multiplied by a weight and summed with the other neurons on the same layer and at the result is applied a function, usually a sigmoid, probably a real neuron is more complicated, but not so complicated.
We believe, we hope to have a soul, we hope to be more than a machine, but we are only machines.
We are machine. We are not, until we act with humanity.
If you don't act with humanity, you are only a machine.

sabato 3 novembre 2018

WINDOWS MEMORY BUFFER EXECUTION

Executing a buffer of memory doesn't make sense on Windows, but you could face to this problem.
For example, if you play with Kali Linux, in this distribution you can find a tool called msfvenom, Basically it generaters payloads for metasploit framework and usually these payloads are backdoors.
A great payload is meterpreter, a backdoor that gives you total control of a remote host, you can also take pics from the webcam. 
Msfvenom has several encoders and you can use these encoders to crypt the payload. Now you are happy, you encrypt you payload, you create it for windows and when you put your windows executable in your windows machine, instantly your antivirus remove the file.
What's happening? You put you file on the disk, and zap! the antivirus removes it.
Nowaday antivirus recognize msfvenom even if you encrypt the payload, they recognize any msfvenom signature. What you can do is put your encrypted payload in a data file, Antiviruses usually don't scan data files, they scan only executables.
Once you have your meterpreter on a data file, you need  to load it from file and execute it.
On Windows you cannot execute directly from stack or from heap memory.
You can't do something that looks like:

unsigned char *code=malloc(...);
((void(*)())code)();

You have to use VirtualAlloc to be able to execute the code. VirtualAlloc is a low level API that permits to allocate memory for execution. 

char *code; 
code = (char *)VirtualAlloc( 
NULL, l, MEM_COMMIT,
PAGE_EXECUTE_READWRITE //Set the memory to be writable and executable
);
memcpy(code, payload, l); //Copy our payload into the executable section of memory
((void(*)())code)(); //execute the payload

That works, use gcc to compile.

venerdì 2 novembre 2018

MARKOV CHAINS AGAIN

Basically Markov chains can predict a sequence of states, if we have a matrix where columns are the states and row are the same states, for each state there is a row of the probability that the next state is that column, and the sum of the elements for each row is 1.
For example, if you consider a man that lives  in a big city, he can have only 4 states: sleep, eat, walking in the park and playing cards.
Markov chains can be used to predict the next state, for example, if the current state is sleeping, what is the probability that the next state is walking?

state/state sleep eat walking play cards
sleep0.20.40.30.1
eat0.10.20.60.1
walking0.20.20.30.2
play cards0.10.40.20.3

if the man sleep, probably the next state is eat (because is the more probable next event (0.4)),
if the man eat, probably the next state is walking, and so on.
This procedure can learn, because if the next state is not the state predicted, we can change the probabilities in the matrix and next time the predicted state will be different.
I know Markov chains was used in some chatter bots, in that case the states are one or more words, and the
sequence was a sequence of words. Training the chain with common phrases, the system was able
to produce phrases that made sense. Obviously the machine have no idea of the meaning of the phrase it is generating.
I'm still new in Markov Chains and I still have to assimilate the concept, but I'm sure it's powerful. I'm thinking about Markov chain these days to find some interesting application.
I started with neural networks, but they are heavy to use in python on a device like esp32, training requires too much cpu calculation.
I think Markov chains can be a simple alternative to neural networks, but they have to be used in the right way for the right application.

martedì 30 ottobre 2018

MARKOV CHAIN

The defining characteristic of a Markov chain is that no matter how the process arrived at its present state, the possible future states are fixed

The future depends on the present