Saturday, December 28, 2013

The Usefullness of Linux

     One thing every Linux user should familiarize themselves with at some point in time is the terminal. Bash scripting is not too different from any other scripting language in my opinion. Once you get familiar with bash, all of a sudden you may indeed realize the power and flexibility behind Linux. Note: if you try this in Windows' command line, it is possible... but... good luck figuring it out - it's a mess!
     Here I wish to share the commands I find useful, and may periodically update this post as I discover new commands... Any combination of commands can be saved in a bash file (your_file.sh); Remember to include #! /bin/bash at the beginning of the file.

  • Install an app or library: sudo apt-get install app-name-here
  • Uninstall an app or library: sudo apt-get remove app-name-here
  • Update all apps and libraries: sudo apt-get update
  • Wireless Fix:
    rfkill unblock all
    rfkill list all
  • Operating System Version: cat /etc/lsb-release
  • VirtualBox Shared Folders: (Note: 'shared_folder_name' is created by clicking on 'Shared folders' in the VirtualBox Manager and then by clicking add folder icon)
    cd ~
    cd /media
    sudo mkdir
    folder_name_here
    sudo mount -t vboxsf shared_folder_name /media/folder_name_here
  • List items in folder: ls
  • Navigate directories:
    # navigate forward
    cd /folder/path
    # navigate backwords
    cd ../..
  • Kill process: sudo killall program_name_here
  • Current username: whoami
  • IP and Network information: ifconfig
  • Network Ports: iwconfig and ip addr show
  • Port-scan a computer/address (requires nmap): nmap -sS -O computer_ip_address
  • Edit file: gksudo gedit /path/to/file.txt OR sudo nano /path/to/file.txt
  • Get list of installed applications: dpkg --get-selections
  • Start app (server-side SSH - WARNING: See below!): DISPLAY=:0.0 application_name
  • Send virtual file input to app upon execution:
    app_name << EOF
    your file content here
    EOF
  • Evaluate a console command incompatible to bash syntax:
    # wmctrl is a non-native bash command and sublime is an active text editor
    # see programming bellow for more bash syntax
    function func{
         eval
    "wmctrl -a sublime"
    }
  • Gain root-level access: sudo su root
  • Get running time: uptime
  • Take a screenshot (prt sc - requires gnome-screenshot):
    gnome-screenshot -f /home/user/Desktop/pic.png
  • Copy file: cp /path/to/file.txt /path/to/newfile.txt
  • Move file: mv /path/to/file.txt /new/path/to/file.txt
  • Open port in firewall: sudo ufw allow 1500
  • Close port in firewall: sudo ufw deny 1500
  • Mount device to folder: sudo mount /path/to/source /path/to/folder
  • List connected USB devices: lsusb
  • Port Forwarding:
    echo 1 > /proc/sys/net/ipv4/ip_forward
    sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
    sudo iptables -A FORWARD -i eth0 -o eth1 -m state --state RELATED,ESTABLISHED -j ACCEPT
    sudo iptables -A FORWARD -i eth1 -o eth0 -j ACCEPT
  • Run app or process in background: google-chrome "http://www.blogger.com/" &
  • Search path for a program file: which $program_name
  • Hibernation or Sleep: sudo pm-suspend
  • Manual for a command: man command
  • View and Manage Ethernet Media:
    man ethtool
    man mii-tool
  • System processes and monitoring top # htop
  • Send messages to users on remote server: w; write 'user' |pts\$n|;
  • Set static IP:
    nano /etc/network/interfaces
    # enter the following
    auto eth0 # set on startup
    iface eth0 inet static # dhcp for temporary IP
    address 10.0.0.25 # the static IP
    netmask 255.255.255.0
    network 10.0.0.0 # IP for 10.0.0.X networks
    broadcast 10.0.0.255
    gateway 10.0.0.1 # default IP of device - similar to the IP used to access router config
  • Set temporary IP (good for tapping into a routerless network; aka: a network where IPs are not assigned by any DNS or other address manager):
    ifconfig eth0 down
    ifconfig eth0 X.X.X.X up # replace 'X' with custom IP


Setup SSH (Linux to Linux):
  1. sudo apt-get install ssh  # on both systems
  2. sudo apt-get install openssh-client  # on the accessing system
  3. gksudo gedit /etc/ssh/sshd-config  # on the accessed system
  4. Type a port number of choice. For example: Port 1500 or Port 4321. Save.
  5. Make sure only one ssh process is running to avoid a mess. Check with ps -e | grep ssh If more than one are running, kill the process (sudo killall sshd) or if none are running, start one up with sudo /etc/init.d/ssh start. (For some installations, first type eval "sudo $(which sshd)" because sshd may be located in another directory such as /usr/sbin/sshd .)
  6. From the accessing computer's terminal, establish a connection with ssh -p port username@ipaddress for example: ssh -p 1500 admin@128.0.4.12
  7. For added security, install and run Firestarter on the accessed computer. Under 'Policy,' add a rule to allowed services. Include ssh port number and IP of accessing computer.
  8. To exit the session, press Ctrl+D.
  9. Copy a file from server to client:
    SCP -P 1500 admin@128.0.4.12:/path/to/file.txt /path/copied/to
  10. Copy a file from client to server:
    SCP -P 1500 /path/to/file.txt admin@128.0.4.12:/path/copied/to
  11. Copy folder & files from server:
    SCP -P 1500 -r admin@128.0.4.12:/server/folder /path/copied/to
  12. Copy folder & files to server:
    SCP -P 1500 -r /client/folder admin@128.0.4.12:/path/copied/to 

Running Applications Server-Side:
If an app were to run from the console, console access will not be returned until the app closes. So, if an app were run through an SSH terminal, either another SSH connection will need to be made to close the program or someone server-side would need to close the app. However, there is a work-around: start a new console server-side and from that console, start the application. Here is a demo (Mint to Kubuntu tested - requires xdotool):
DISPLAY=:0.0 konsole
DISPLAY=:0.0 xdotool type "google-chrome-stable"
# enter: KP_Enter; space: space; backspace: BackSpace
# Run application:
DISPLAY=:0.0 xdotool key KP_Enter


Bash User Interface:
Sometimes it can be convenient to add a user interface for a user's comfort and to reduce confusion. Zenity does just this. But of course, one can take Zenity another step forward with YAD - as the developers know it as: "Zenity on Steroids." All the features of Zenity and then some. Here is a demo (requires YAD):
frmdata=$(yad --title "Test Form" --form --field "Address" --field "name")
frmaddr=$(echo $frmdata | awk 'BEGIN {FS="|"} { print $1 }')
frmname=$(echo $frmdata | awk 'BEGIN {FS="|"} { print $2 }')
echo $frmaddr
echo $frmname



Basic Bash Programming:
# variables
str="hello world"
var=2

# write to a file

echo "hello" > file.txt

# read from a file
while IFS= read -r line;
do
     echo $line
done < file.txt

# create a folder
mkdir folder_name

# write to console
echo "hello world"

# read from console

read var


# conditioning
if ["true" = "true"]; then
     echo "this is true"
elif ["a" == "b"]; then
     echo "maybe not"
else
     echo "No!"
fi





# comment line

# foreach loop
for i in $( ls ); do
     echo item: $i
done

# for loop

for i in `seq 1 10`; do
     echo $i
done
for ((i=0; i<10; i++)); do
     echo yes
done

# while loop

CTR=0
while [  $CTR -lt 10 ]; do
    echo The counter is $CTR
    let CTR=CTR+1 
done

# until loop

CTR=0
while [  $CTR -lt 10 ]; do
     echo The counter is $CTR
     let CTR=CTR+1
done




# functions
function func {
     # echo params
     echo $1 $2 $3
}
func hello world !

# menu prompt

OPTIONS="Hello Qt"
select opt in $OPTIONS; do
     if ["$opt" = "Qt"];
     then
          echo done
          exit
     fi
done

# a static class could

# be seen as a bash file

# regex ( ~ )

[[ "Hello World" =~ "Hello"$ ]] && 
echo matched

# evaluation
eval "expression"

# delete file or directory
rm -r /path/to/file.txt





[My Simple Back Story]

     It has been close to two years now of getting use to the ways of Linux - a free and secure operating system. Depending on the title and version of Linux, one may face varying levels of difficulty. Linux does have a stereotype of being 'challenging' and 'only used by computer experts.' How do I know this? Because I was once one of those to hear them; even further, I saw one of the first Linux operating systems in action and immediately agreed about it's difficulty (even though I never even touched it once). 

     I gave it a try one day just to see - perhaps about four years ago this was. Kubuntu, my first choice, simply because it was blue. I realized that, although a little different from Windows and OSX, it actually had a very familiar feel to it. A 'start' button in the lower left, the time, network, and other tasks in the lower right, windows showed up in the task bar and have the usual minimize/maximize/close buttons at the top... Browsing the internet is just as easy. With Sublime Text, I have an advanced version of notepad. With OpenOffice or LibreOffice, I have free and compatible version of MSOffice. With Wine (a windows emulator) I can run windows-based applications such as windows notepad.
     Later, my roommate in college, introduced me to Linux Mint. Just like Kubuntu, Mint is a child branch of the Ubuntu based systems. Linux Mint is probably the easiest title out there to date. I've been using it for the past three days and all I can say is 'Wow, where have you been all my life?!'
     Here is a little something interesting I thought of: if you can master Linux Mint, you will be able to handle both Windows and Mac. Also, as a result of persuading some friends to convert from Mac to Linux, I learned of a project called Macbuntu which is OSX functionality with Linux as the underlying engine.
     All this is some pretty cool stuff. I was convinced the moment I learned of the simplicity. This operating system is for the naive all the way to the expert. And remember, you've already had a taste of Linux if you've ever surfed the web!

Wednesday, November 20, 2013

Writing a File to Computer with Arduino

As far as I found, there is no native support for this in the Arduino libraries. Nevertheless, it can be done and with any language of choice! For my demonstration I will use C#. Now so I don't confuse my audience already, writing requires two separate applications, one for the Arduino board and one for the computer - the app for Arduino is in C/C++ while the app for the computer is in C# (or any supported language of your choosing really).

To get started, lets look at the code for the Arduino:

int led = 13;
bool flag = true;

void setup()
{
    pinMode(9, OUTPUT);
}

void loop()
{
    Serial.begin(9600);
    Serial.println("Hello World!");
    Serial.end();
    Toggle();
    delay(500);
}

void Toggle(){
     if(flag) digitalWrite(led, HIGH);
     else digitalWrite(led, LOW);
     flag = !flag;
}


For every 500 milliseconds, the board will send the message "Hello World!" via USB to the computer. Any program listening on that port, will hear the message. (I added a little extra code that toggles an on-board LED on and off after every consecutive message sent - just to signify it itself is functioning properly.)

Serial.begin() primes the USB for data transfer and the (9600) portion is the baud rate (pulses per second - the ancestor of bits per second).
Serial.end() ends the transmission and releases control of the port.
Serial.println() writes ASCII data to the port.
A list of Serial functions can be found on Arduino.cc under References: http://arduino.cc/en/Reference/Serial




Now on to the computer side of things:

using System;
using System.IO.Ports;
using System.Threading;

namespace Arduino_SerialReader
{
    class Program
    {
        static SerialPort port;
        static void Main(string[] args)
        {
            port = new SerialPort("COM", 9600, Parity.None);
            Thread reader = new Thread(Read);

            port.ReadTimeout = 500;

            port.Open();
            reader.Start();
        }

        static void Read()
        {
            bool flag = true;
            while (flag)
            {
                try
                {
                    string message = port.ReadLine();
                    Console.WriteLine(message);
                }
                catch { }
            }
        }
    }
}


First, create a SerialPort object and give it a name: 'COM', the same baud rate set for the Arduino board (9600), and finally, no parity checking. (A parity bit is a simple way of error checking data received; more on parity checking can be found here) Purposefully, I set the timeout to be the same as my first app so to be almost perfectly synchronous.

Open the port and start the Read thread. The read thread is a separate thread that will indefinitely listen for any and all incoming messages on the port and then print them to the console.

So where is the code to write a file? Well, by now you would know enough to take it from here, but if you really need to know how to write a file in C#, here is a simple one-liner hack:

File.WriteAllText("filename.txt", "your string here");

More file handling example can be found here: microsoft OR stackoverflow
Feel free to ask questions!


Friday, October 4, 2013

How to Become a Millionaire

For those who want to know the secret(s) to how to become a millionaire, you must be willing to accept what is required of you, and do it in faith that these secrets are tried and true and will not fail you.

START EARLY
PAY YOURSELF FIRST
&
MAKE IT AUTOMATIC

Now, is that really such a challenge? Well, for many it is, because they lack faith in the system. Only when they are shown the underlying logic that makes this system work, are they more willing to try it - yet, even then, after witnessing hard core evidence, they may still shy away simply because of a lack of trust (perhaps not as much but nonetheless). If you are one of those who need to see how this really works before you put your money on the line, and to make sure I am not just pulling your leg, or you simply just want to know more about this in general, then I recommend a book for you called, 

"The Automatic Millionaire: A Powerful One-Step Plan To Live And Finish Rich" 

by David Back



     All of about $7 to $10 for a new copy (or as low as $4 used). I purchased a used copy my self for a University Family Finance class I recently had taken. It was an EZ-A class that would satisfy a general education graduation requirement. I figured "why not?", it would be more fun than a second history or humanities class and guess what, I do fancy some business and number-crunching from time to time.
     I graduated highschool one year after they started requiring students to take a financial literacy class. I learned quite a bit in that time and it really motivated me to take action and build up my wealth - again, not a very challenging class. I even desired to dive into stock exchange after hearing the many success stories from older generations, then, around my age. 
     My first goal with taking a similar class was just to slap another beautiful 'A' on my transcript. Then, as the week drew closer to this class, I started thinking about how this class would benefit me beyond an A-grade. The thoughts that ran through my mind got me even more excited and I couldn't wait for class to begin, like the night before Christmas.
     One of the books that where required on my list was the book 'Automatic Millionaire.' Those words sounded like the book was going to be an entertaining read - and I am not one who likes to read just any book that is required of me. Anyways, the week came when we needed to read the entirety of the book and write a summary about it. I must say, the introduction really builds on one's curiosity to 'know this answer' of which they so highly esteem. David shares a simple proof of concept through a story of how he came to learn about this secret. Following his story, David dedicates the remaining chapters to a deeper understanding of how things work and what one needs to do to become a success. (He also includes a checklist at the end of each chapter because 'there is just something about righting it down that motivates one to act upon it')

Buy the book, read it, live it, and love it!

Just a Little Note: This book (The Automatic Millionaire) is NOT about becoming an instant millionaire, but rather about how to retire as a millionaire without all the hullabaloo one could think of. Some of these techniques mentioned in the book also work outside the bounds of retirement as well.



Tuesday, September 3, 2013

Recursively Calculate All Possible Pairs in CSharp

A friend of mine challenged me with an algorithm that could find all possible computational pairs within a given list consecutively printing them out. Of course, the challenge was to do this using only one method and all recursion. It took me about 30 minutes before I finally got the code working and though it may not print in 'alphabetically order,' it does just the what I need! I was surprised that this algorithm from for-loops could become such a challenge when attempted with recursion - but that may just be me... trying to wrap my brain around it.


Here is the code:
(It takes a list of any length and prints all possible computational pairs recursively)

static void Function(List<String> list, int z = -1, int x = -1)
{
    if (x == -2 || z == -2) { x = list.Count; z = 0; }

    x--;
    if (x >= z) Function(list, z, x);
    else
    {
        z++;
        x = list.Count - 1;
        if (z < list.Count-1) Function(list, z, x);
    }
         
    Console.Write("{0}-:-{1}, ", list[z], list[x]);
}



And here would be the output for a list of strings { "A", "B", "C", "D"}:

D-:-D, C-:-D, C-:-C, B-:-D, B-:-C, B-:-B, A-:-D, A-:-C, A-:-B, A-:-A

Monday, July 29, 2013

Understanding Electromagnetic 'EM' Waves

Through many strait hours of research I think I am starting to understand the characteristics behind electromagnetic waves - without having taken a class in physics, optics, or electrodynamics! Here I will share my understanding and useful finds . . .

  • There are two common types of waves: Longitudinal and Transverse; Plane was another interesting wave I came across on my voyage. EM waves are a combination of two 2D transverse waves perpendicularly intersecting each other.
  • This is what an electromagnetic wave looks like graphed in 3D space: An E-Field and an M-Field.
    [Figure 1]
  • ...and this is the same graph, except representing elliptical polarization. (If Z were a magnetic field line, a charged particle would whirl around Z over an extended time period.)
    [Figure 2]

  • >> The above graph does not represent a motion or oscillation of a substance but the forces felt by observers. (An EM wave has no electric charge! "Wait, wait,..WHAT?! But what about the 'Electro' in electromagnetism?" There is a difference between an Electric Charge and an Electric Field - don't get them mixed up!)
    A demonstration:

    "Think of the Earth as a giant electron, and you are a proton. Since you are oppositely charged, you are attracted to the Earth, and vice versa. The electric force is similar to gravity in this manner.
    Now think of how your distance from the Earth affects your weight. You know that the farther you are from Earth, the less you weigh, and so the less force you feel. This is similar to the electric field.

    Check out these two equations:
    Weight -> F_weight = mass * gravity
    E-Field -> F_electr = charge * E-field

    A particle's charge is like mass.
    The E-field is like gravity. The stronger gravity, the more force you feel (due to your weight). The stronger the E-field, the more force a charged particle feels." by 
    zee_prime on Yahoo Answers
  • An Electrical Field is the force experienced by a motionless electrically charged particle at any point in space. For example: a Proton has an electrical field of +1, a Neutron: 0, and an Electron: -1 (these values are an ideal state, also commonly and simply known as +, -, and N). The strength of the field is proportional to the number of added charged particles. So E+E+E=-3, P+P+N+E=1, and N+N=0. An E-Field is measured in Newtons-per-Coulomb (N/C) or Volts-per-Meter (V/M).
  • A Magnetic Field is the product of a particle with an electrical field moving through space or spinning. The strength of the field is proportional to the charge of the particle cluster and the velocity of it's travel or speed of it's spin. An M-Field is measured in Teslas or Gauss's (G) for smaller fields (1T = 10,000G). Water can be levitated in an M-Field of approximately 10T!
  • There are two electrical field models, one for each charge: (neutral has no charge or it's charge is 0 so it is discarded here) [Figures 3 & 4]
  • There are two models of fields (electrical and magnetic respectively): [Figures 5 & 6]


    An H-FieldA B-Field
  • The M-Field is crossed with the velocity vector (or in other words is at a right angle to the path the particle is traveling) and the force it exerts is crossed with the M-Field and Velocity. This can simply be seen as an XYZ axes in space where X is the magnetic field, Z is the influencing force, and Y is the  distance/time. As a demonstration:
    - You in a standing position will represent the forward vector - the direction of movement, from your feet to your head.
    - With your left hand, point in front of you. Your left arm represents the direction of the magnetic field.
    - Now, with your right hand, raise it to a T so that you are now pointing it to your right. Your right arm represents the direction of force acting on the particle's surroundings.
Here is a fun fact I learned on the way that boggled my mind. 
It seemed surreal at first but is quite logical now:
  • Electromagnetism is one of the four forces of nature - of course. This force has two parts: an Electrical-Field and a Magnetic-Field.
  • M-Fields do not slow or speed up surrounding particles. WHAT?! Nope! In fact, a magnetic field doesn't do any work at all except change the direction of the particle's travel. When a magnetic field collapses, it is converted into it's respective electrical value until the energy equalizes (aka: potential energy).
  • Permanent Magnets: are they emitting a magnetic field? Yes they are. While there is no distinct current flowing within them, on the quantum level the charged particles are spinning as well as the almost unnoticeable whirl of electrons about their nuclei.
  • Note the B-Field above (Figure 6). If you sever the loop and straighten the path of travel for charged particles, you can get a better view of how a B-Field works. Demonstration:
    [Figure 7]
    As negative electrons move up, a magnetic field emits outward (perpendicular to the electrical field) and rotates counterclockwise looking down (clockwise looking up). Again, an electrically charged particle would spin around a magnetic path just like a magnetic field about an electrical path.

Images from StackExchange and Wikipedia

Thursday, July 25, 2013

Regular Expressions in C# (RegEx)

While working with several code-cleanup regular expressions, I had a thought of putting together a collection of nifty and useful patterns that I could use latter when the time came so I and anyone else wouldn't need to rebuild or re-research them.

The list is small for now, but I will try to add to it in time... If you have useful expression not listed here, do share!



  • {([^{]*?)}
    • This expression matches the objects contents from left curly bracket to the right and returns the body within the brackets $1.
    • If implemented properly in a source code bottom-up decomposer, this expression will be able to help break a string into a tree of objects (TreeNode)
  • \{((?>[^{}]+|\{(?<DEPTH>)|\}(?<-DEPTH>))*(?(DEPTH)(?!)))\} by Tim Pietzcker on StackOverflow
    • This does the same as the above except that it also includes embedded objects.
    • If implemented properly in a source code top-down decomposer, this expression will be able to help break a string into a tree of objects (TreeNode)

  • ^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$
    • This expression matches valid emails.

  • (?<=<body([^<]*?)>)[\s\S]*(?=</body>)
    • Extract HTML body using Look-ahead and Look-behind.
  • (<script([^<]*?)>[\s\S]*?</script>)
    • Select SCRIPT block within body of HTML.

  • [\n]+
    • Remove multiple newline characters: '\n\n\n' => '\n' (replace '\n' with any other character to do the same: [ab]+ => 'aaabbb' => 'ab')

  • "[^\\"]*(?:(?:\\\\)*(?:\\"[^\\"]*)?)*" Hatchi on StackOverflow
    • Capture a string with an embedded string - used for parsing source code. (This one took me some time to find!)
  • \"([^\"]+)\"
    • Capture every other matching string.
      Example: "my"string"has"quotes"!" → { my, has, ! } and not { string, quotes }.

  • (?<=^)
    • Match patterns at the beginning of a string using the 'look-behind' expression combined with the carrot character delimiter.

    I wrote a simple WinForms App to test my expressions on so I would know if they would work the way I intended them to. This editor was also built to apply the expression on the given text, a file, or a tree of files of a given file extension. There is the option to Replace, Capitalize, Lowercase, and Invert-Case.
    The code in this picture is partially parsed java code. Though I am capable of manually parsing Java code to CSharp, it becomes a tedious chore that consomes too much time when there are over 1.2 thousand files to port (and a simple String.Replace will not do the trick - too many variables to consider)!

Tuesday, June 18, 2013

Performing Operations on Byte Arrays ( CSharp Solutions - C# )

When working with digital electronics, this can be easily accomplished with a few flip-flops and logic operators. To program something like this is just as easy - when one can rap their mind around it! I successfully wrote addition and subtraction methods that would perform these respective operations on raw byte arrays, many months ago. I lost the sources and had to really think how to replicate my results. Today I have not only successfully rewritten the source code but also composed them to add more than just one byte to an array of bytes.




Addition

public static byte[] Add(this byte[] A, byte[] B)
{
    List<byte> array = new List<byte>(A);
    for (int i = 0; i < B.Length; i++)

        array = _add_(array, B[i], i);

    return array.ToArray();
}
private static List<byte> _add_(List<byte> A, byte b, int idx = 0, byte rem = 0)
{
    short sample = 0;
    if (idx < A.Count)
    {
        sample = (short)((short)A[idx] + (short)b);
        A[idx] = (byte)(sample % 256);
        rem = (byte)((sample - A[idx]) % 255);
        if (rem > 0)
            return _add_(A, (byte)rem, idx + 1);
    }
    else A.Add(b);

    return A;
}


Subtraction

public static byte[] Subtract(this byte[] A, byte[] B)
{
    // find which array has a greater value for accurate
    // operation if one knows a better way to find which 
    // array is greater in value, do let me know. 
    // (MyArray.Length is not a good option here because
    // an array {255} - {100 000 000} will not yield a
    // correct answer.)
    int x = A.Length-1, y = B.Length-1;
    while (A[x] == 0 && x > -1) { x--; }
    while (B[y] == 0 && y > -1) { y--; }
    bool flag;
    if (x == y) flag = (A[x] > B[y]);
    else flag = (x > y);

    // using this flag, we can determine order of operations
    // (this flag can also be used to return whether
    // the array is negative)
    List<byte> array = new List<byte>(flag?A:B);
    int len = flag ? B.Length : A.Length;
    for (int i = 0; i < len; i++)
        array = _sub_(array, flag ? B[i] : A[i], i);

    return array.ToArray();
}
private static List<byte> _sub_(List<byte> A, byte b, int idx, byte rem = 0)
{
    short sample = 0;
    if (idx < A.Count)
    {
        sample = (short)((short)A[idx] - (short)b);
        A[idx] = (byte)(sample % 256);
        rem = (byte)(Math.Abs((sample - A[idx])) % 255);
        if (rem > 0)
            return _sub_(A, (byte)rem, idx + 1);
    }
    else A.Add(b);

    return A;
}


Multiplication

public static byte[] Multiply(this byte[] A, byte[] B)
{
    List<byte> ans = new List<byte>();

    
byte ov, res;
    int idx = 0;
    for (int i = 0; i < A.Length; i++)
    {
        ov = 0;
        for (int j = 0; j < B.Length; j++)
        {
            short result = (short)(A[i] * B[j] + ov);

            // get overflow (high order byte)
            ov = (byte)(result >> 8);
            res = (byte)result;
            idx = i + j;

            // apply result to answer array
            if (idx < (ans.Count))
                ans = _add_(ans, res, idx); else ans.Add(res);

        }
        // apply remainder, if any
        if(ov > 0) 
            if (idx+1 < (ans.Count)) 
                ans = _add_(ans, ov, idx+1); 
            else ans.Add(ov);
    }

    return ans.ToArray();
}

Division

- on the way -


Modulus

n = n - ( mod * ⌊ n / mod ⌋ )





To be used as follows: (Addition)
byte[] A = new byte[] { 0xFF };
byte[] B = BitConverter.GetBytes(235192);

byte[] C = A.Add(B);


Sunday, June 9, 2013

Ruby on Rails: Working between Ruby and JavaScript Methods

In an attempt to help a friend with a Ruby project, I needed to become familiar with the Rails' way of doing things. Never thought I'd touch the stuff till about two days ago. I must say, that was quite the new experience for me - as I have never programmed before between three different scripting languages under the same project. (Ruby, JavaScript, and HTML5, if that counts)

Anyhow, I ran into a nerve-wrecking conflict in this development voyage: "calling a Ruby method from JavaScript!"

I had probably spent at least 15 hours strait trying to find the answer to this, at the same time as attempting to understand what lines of script did and why I continuously received errors or broken functions - even though my code looked identical to that which I tried from online forums (including the 'read-on' bug-fixes down the forums). FINALLY, today, I believe I stumbled upon a bit o' luck as things were starting to fall into place and just work the way I wanted it to!




  • First things first that I found often in my digging: 'know where an action should be implemented.' Ruby is to Server-Side as JavaScript is to Client-Side. All data on the client-side's page should be gathered and assembled into a 'packet' sent to the server-side method(s).
  • Ajax makes things easier (in my view).

In this example, I will show you how I successfully called a Ruby method from JavaScript.

My Environment:
Hardware: HP Z1 | Xeon | Quadro 500 | 4DDR3
OS/Version: Windows 7 Professional 64-bit
Ruby Version1.9.3p392
Rails Version3.2.13
Browser/VersionChrome 27.0.1453.110 m

  1. In your console, type: rails new your_project_name followed by cd your_project_name
  2. In your console, type: rails generate controller home index
  3. Navigate to app > views > home and open index.html.erb in Notepad (or preferred editor)
  4. Navigate to config and open routes.rb in Sublime Text 2 (or preferred editor)
  5. Navigate to app > controllers and open home_controller.rb in Sublime Text 2 (or preferred editor)
  6. In index.html.erb, add the following lines:

  7. <script type="text/javascript">
    function func()
    {
        // get user input from text field
        nm = $('input[id=numeric]').val();
        // call ruby method and send input as a 'data' parameter
        // {data:nm} is the equivalent to :data => nm
        // and can also be written as {value:nm} or {myinput:nm}
        $.post("fetchInput", {data:nm}, function(data)
        {
            alert(data);
        });
    }
    </script>
    
    <%= text_field_tag("numeric", "0", :size => 1) %>
    <!-- This button invokes a JavaScript method instead of a Ruby method as a means of easy and clean code implementation -->
    <%= link_to "<button>Submit</button>".html_safe, 'javascript:void(0);', :onclick => "func()", :id => "button_id", :class => "button_class" %>
  8. In routs.rb, add the following lines:

    your_projectname::Application.routes.draw do
        root :to => "home#index"
    
        # as of Rails 4, match has become deprecated
        # the alternative would be to use key-words 
        # appropriate for the task in this case:
        # post '/fetchInput' => 'home#fetchInput'
        match '/fetchInput' => 'home#fetchInput', :as => 'fetchInput'
    end
  9. In home_controller.rb, add the following lines:

    class HomeController < ApplicationController
    
        def index
            # code executes here on page-loading     end     def fetchInput
            # get variable information passed to this method         # again, :data can also be written as :value or :myinput         # respective to how you passed it in through ajax         # ie: :data from {data:nm}          tokens = params[:data]
            # this line returns the method result as a text object         render :text => tokens     end
    end
  10. In your console, type: rails server
  11. Enter a value into the text field and then click the button to see what happens. If all goes well, a popup window will appear containing the text information you entered.

Monday, February 4, 2013

How Do You Identify Get Rich Quick Ads & Other Online Scams

There is one thing you should note before continuing on: If you remain a complete skeptic of almost anything not proven and set on concrete, you could miss out of many life changing events that may first require a leap of faith.

I bold the key phrases bellow for those who wish to read strait to the point; if you want to learn more about that specific topic, then read on - Google, Bing, Yahoo, and Wikipedia are also friendly companions.


  1. The first typical feature well known to many is the 'Too Good To Be True' statement. If it sounds (or looks) too good to be true, then it probably is. Almost all ads appeal to viewers' envy and desires and usually the scam-type ads will include hooks or hangers to get you as the viewer to 'click' and learn more - even to get 'involved'. A few familiar examples would be:
    • "Language Professors HATE Him!"
    • "One easy workout trick that will make you ripped in one week!"
    • "Dad quit his job: He makes $4000 online playing video games!" - When it comes to money ads, check for over exaggeration, do your research. Large numbers are always a sure sign of something suspicious. (Note: large amounts of money isn't going to leave the hands of any smart investor with out first assurance that s/he will benefit - money is wither worked for or won through means of gambling - the world is rough and money is hard to come by [w/o work] so don't expect anyone online to simple 'hand you money for free')
  2. If you decide that it's worth a shot to investigate, then by all means, click the link! (I must warn that some sites or ad-redirecting links may bring you to a site with malicious, fraudulent, or in other words, explicit content, so do be prepared for the worst!) The next obvious details you will see to dictate immediately if something is a scam, is the style of the website
    • Unusually large scaled fonts
    • Fonts have a 'handwritten' theme instead of a professional Arial, Times New Roman, or Tahoma
    • Key features are enlarged and are highlighted, typically in red and yellow colors
    • Graphical arrows directing your focus and actions
    • Stock photos - scams tend to use images that are usually used to promote or sell something instead of stating somethings' existence (not provoking impulse); business-like photos are a sign that there is something that requires a purchase, though, not all the time does that mean the item(s) or business is part of a scam or gimmick - it is important to do research on these topics, maybe someone else already walked in your footsteps, but don't trust it until you feel your self that what they're saying may be legit.
  3. Investment required first - The only times I have ever seen a need to invest money in order to make money was when I either A. needed to start and maintain a website, B. purchase the necessary equipment, software, and supplies, or C. buy and sell stock in the stock market. Some have also asked the question, "Well, if I'll be making money, why can't you (as the promoter) admit me and I just pay you back?" - this is one way how the scammers make their money. Watch out, some of their stories are pretty convincing!
  4. Insufficient or no contact information readily available. It is understandable when an owner hides his or her contact information to avoid spam, but professional businesses - especially when dealing with money - always have a valid email and phone number available for customer support (usually located next to the website's copyright info or in the site navigational directory).
  5. Excessive amount of information required for registration. What better info to use to solicit ads than through a phone number or home address? If you think a site is asking for more info than it needs [as a requirement] to register, then I think something is up. Take extra caution when a new site requires card or bank information - look for a 'secure' symbol in the upper left of your URL address bar. For most browsers, it will appear as a green lock. DON'T enter any information regarding if you don't see the 'OK' symbol first!
  6. URLs can be sneaky! Check your URL and make sure the correct address appears. This is a sneaky phishing filter trick, where you take a well know URL and mutate it a little to fool the viewer at first glance: www.facebook.com -> www.fakebook.com OR google.com -> www.goog.le.com
  7. It's an interesting thing, because the scammers don't want you to leave their site, especially when they're so close to picking your pocket book. The popup windows that get your attention with lots of symbols such as *** and --- and "Don't Leave!" - which pop up either when you first arrive or, most commonly, when you leave.
  8. Try to avoid most, if not all, money ad or survey related links; they are benefiting from you, however, you are not benefiting from them.

If you want to make money online and not risk scams and solicitations, the best things to look into:
For cosmetics or other products:
  • Read as many reviews as needed from trusted sources. (I would suggest Amazon.com)
  • Watch uploaded videos of progress or products in action. (YouTube seems to do the job pretty well)